mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 17:16:04 +09:00
Compare commits
No files matched your search
@@ -0,0 +1,109 @@
|
||||
# Plan: Admin Feedback Visibility
|
||||
|
||||
**Created:** 2026-03-23
|
||||
**Branch:** feat/sess-20260323-1454-feedback-email-debug
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
User feedback submissions are stored in Firestore (`user_feedback` collection) but are completely invisible to the admin. The admin panel only shows a boolean "Feedback Submitted: Yes/No" badge per user. This plan adds:
|
||||
|
||||
1. **Admin UI page** to browse and review all submitted feedback
|
||||
2. **Email notification** to admin@nomadkaraoke.com on each new submission
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Admin page at `/admin/feedback` listing all feedback with ratings, text, timestamps, and user info
|
||||
- [ ] Sortable by date (newest first by default) and filterable by search (email)
|
||||
- [ ] Star ratings rendered visually (not just numbers)
|
||||
- [ ] Email sent to admin@nomadkaraoke.com immediately when feedback is submitted
|
||||
- [ ] Email includes all feedback content (ratings, text fields, user email)
|
||||
- [ ] Test data filtering works (exclude_test toggle)
|
||||
- [ ] Sidebar navigation includes new "Feedback" item
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Admin API Endpoint
|
||||
Add `GET /api/admin/feedback` to `backend/api/routes/admin.py`. Follows the standard admin endpoint pattern: `require_admin` dependency, pagination with `limit`/`offset`/`search`/`exclude_test`, returns Pydantic response model. Queries `user_feedback` Firestore collection.
|
||||
|
||||
### Admin UI Page
|
||||
New page at `frontend/app/admin/feedback/page.tsx`. Follows existing admin page patterns (Card, Table, Badge, pagination, search input, loading states). Uses `adminApi.listFeedback()` to fetch data.
|
||||
|
||||
### Email Notification
|
||||
Add a new method to `EmailService` (or call `send_email` directly) from the `submit_user_feedback` endpoint in `users.py`. Uses the existing SendGrid infrastructure — no new template service templates needed since this is an internal admin notification (simple HTML table with the feedback data).
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Backend — Admin feedback list endpoint
|
||||
|
||||
1. [ ] Add `AdminFeedbackItem` and `AdminFeedbackListResponse` Pydantic models to `admin.py`
|
||||
2. [ ] Add `GET /api/admin/feedback` endpoint with:
|
||||
- Pagination: `limit=50`, `offset=0`
|
||||
- Search by user email
|
||||
- `exclude_test` filter (reuse `is_test_email`)
|
||||
- Sort by `created_at` descending
|
||||
- Return: items, total, offset, limit, has_more
|
||||
3. [ ] Add aggregate stats in response: average ratings, total count
|
||||
|
||||
### Step 2: Backend — Email notification on submission
|
||||
|
||||
4. [ ] Add `send_feedback_notification` method to `EmailService` that sends an HTML email to `admin@nomadkaraoke.com` containing:
|
||||
- User email
|
||||
- All 4 star ratings
|
||||
- All text fields
|
||||
- Would recommend / would use again
|
||||
- Submitted timestamp
|
||||
- Link to admin feedback page
|
||||
5. [ ] Call `send_feedback_notification` from `submit_user_feedback` in `users.py` (fire-and-forget, don't block the user response on email success)
|
||||
|
||||
### Step 3: Frontend — Admin API client
|
||||
|
||||
6. [ ] Add `listFeedback` method to `adminApi` in `frontend/lib/api.ts`
|
||||
7. [ ] Add TypeScript types for `AdminFeedbackItem` and `AdminFeedbackListResponse`
|
||||
|
||||
### Step 4: Frontend — Admin feedback page
|
||||
|
||||
8. [ ] Create `frontend/app/admin/feedback/page.tsx` with:
|
||||
- Table: user email, date, overall rating (stars), ease of use, lyrics accuracy, correction experience, would recommend, would use again
|
||||
- Expandable rows or click-to-detail for text fields (what went well, what could improve, additional comments)
|
||||
- Search by email
|
||||
- Pagination (50 per page)
|
||||
- Refresh button
|
||||
- Test data toggle (via `useAdminSettings`)
|
||||
9. [ ] Add "Feedback" item to admin sidebar in `frontend/components/admin/admin-sidebar.tsx` with `MessageSquare` icon
|
||||
|
||||
### Step 5: Testing
|
||||
|
||||
10. [ ] Backend unit test for `GET /api/admin/feedback` endpoint (pagination, search, exclude_test)
|
||||
11. [ ] Backend unit test for `send_feedback_notification` email method
|
||||
12. [ ] Frontend component test for feedback page (render, empty state)
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/admin.py` | Modify | Add feedback list endpoint + response models |
|
||||
| `backend/api/routes/users.py` | Modify | Add email notification call in `submit_user_feedback` |
|
||||
| `backend/services/email_service.py` | Modify | Add `send_feedback_notification` method |
|
||||
| `frontend/lib/api.ts` | Modify | Add `adminApi.listFeedback()` method + types |
|
||||
| `frontend/app/admin/feedback/page.tsx` | Create | Admin feedback review page |
|
||||
| `frontend/components/admin/admin-sidebar.tsx` | Modify | Add "Feedback" nav item |
|
||||
| `backend/tests/test_admin_feedback.py` | Create | Tests for admin feedback endpoint |
|
||||
| `backend/tests/test_feedback_email.py` | Create | Tests for feedback email notification |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Admin endpoint (pagination, filtering, sorting), email method (content formatting, send call)
|
||||
- **Integration**: Submit feedback → verify email service called
|
||||
- **Manual verification**: Check email arrives in admin@nomadkaraoke.com inbox after submission
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should the admin page show feedback from the old `beta_feedback` collection too, or just `user_feedback`? (Recommendation: just `user_feedback` — the beta collection is legacy)
|
||||
- [ ] Should there be any spam/quality detection flagging? (Some submissions appear to game the system for credits)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Backend: Remove endpoint from admin.py, revert email call in users.py
|
||||
- Frontend: Delete feedback page, remove sidebar item
|
||||
- No data migration needed — Firestore collection unchanged
|
||||
@@ -0,0 +1,151 @@
|
||||
# Plan: AI-Powered Credit Gating
|
||||
|
||||
**Created:** 2026-03-23
|
||||
**Branch:** feat/sess-20260323-1716-ai-credit-gating
|
||||
**Status:** Implemented
|
||||
|
||||
## Overview
|
||||
|
||||
Replace the automatic welcome/feedback credit grants with an AI-powered evaluation step. When a user triggers a credit grant (email verification or feedback submission), instead of immediately granting credits, we collect abuse signals and ask Gemini to make a grant/deny decision. Suspected abusers get a friendly rejection email (CC'd to Andrew) instead of free credits.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Welcome credit grants go through AI evaluation before granting
|
||||
- [ ] Feedback credit grants go through AI evaluation before granting
|
||||
- [ ] AI evaluates: fingerprint correlations, IP correlations, IP geo info, user agent, signup recency patterns
|
||||
- [ ] Approved users get credits as before (seamless experience)
|
||||
- [ ] Rejected users get a friendly-but-firm email explaining the situation, CC'd to andrew@beveridge.uk
|
||||
- [ ] Rejection email invites them to reply if it's a mistake
|
||||
- [ ] Decision is logged to Firestore for audit trail
|
||||
- [ ] Fail-open: if AI evaluation fails, grant credits (don't punish users for our errors)
|
||||
- [ ] Admin can override decisions via existing admin credit grant endpoint
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Architecture
|
||||
|
||||
```
|
||||
User verifies email / submits feedback
|
||||
↓
|
||||
Collect abuse signals (sync, fast):
|
||||
- User's fingerprint + IP
|
||||
- Other accounts with same fingerprint (from correlations)
|
||||
- Other accounts with same IP
|
||||
- IP geolocation info
|
||||
- Recent signup count from same IP/fingerprint (last 24h)
|
||||
- User agent string
|
||||
- For feedback: the feedback content itself
|
||||
↓
|
||||
Call Gemini (vertexai/gemini-2.5-pro-preview) with structured prompt:
|
||||
- Present all signals
|
||||
- Ask for JSON response: {decision: "grant" | "deny", reasoning: string, confidence: number}
|
||||
↓
|
||||
If "grant": grant credits normally, log decision
|
||||
If "deny": skip credit grant, send rejection email, log decision
|
||||
If AI call fails: grant credits (fail-open), log error
|
||||
```
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
1. **Two-phase verification**: The magic link verify endpoint returns immediately with session + a `credit_status: "evaluating"` field. The frontend shows a "preparing your account" loading screen, then polls/waits for the evaluation result via a new lightweight endpoint. This keeps the auth flow snappy while the AI evaluation runs in the background of the same request or via a short follow-up call. The frontend then shows either a celebratory "2 free credits!" interstitial or a "sorry, couldn't grant credits" interstitial before navigating to the dashboard.
|
||||
|
||||
2. **Fail-open**: If Gemini is down or returns an error, we grant credits. Better to let an occasional abuser through than block legitimate users.
|
||||
|
||||
3. **Use google-genai directly**: The project already has `langchain-google-genai` installed. We can use the simpler `google.generativeai` library directly for a focused prompt/response, or use the existing LangChain setup. We'll use `google.generativeai` for simplicity since this is a single-turn evaluation, not an agentic workflow.
|
||||
|
||||
4. **Structured JSON output**: Ask Gemini for structured output with decision, reasoning, and confidence to make decisions parseable and auditable.
|
||||
|
||||
5. **Log all decisions**: Store every evaluation in a `credit_evaluations` Firestore collection for audit trail and to tune the prompt over time.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Add google-generativeai dependency
|
||||
- Add `google-generativeai` to pyproject.toml (lightweight, direct Gemini access)
|
||||
- Verify it works with Vertex AI auth in the nomadkaraoke project
|
||||
|
||||
### Step 2: Create credit evaluation service
|
||||
- New file: `backend/services/credit_evaluation_service.py`
|
||||
- `CreditEvaluationService` class with:
|
||||
- `evaluate_credit_grant(email, grant_type, feedback_content=None) -> CreditEvaluation`
|
||||
- Collects all abuse signals by calling existing services (user_service, ip_geolocation_service)
|
||||
- Builds prompt with signals
|
||||
- Calls Gemini for decision
|
||||
- Logs decision to Firestore
|
||||
- Returns structured result
|
||||
|
||||
### Step 3: Build the Gemini prompt
|
||||
- System prompt explaining the role: "You are an anti-abuse evaluator for a karaoke video service..."
|
||||
- Present all signals in a structured format
|
||||
- Request JSON response: `{decision: "grant"|"deny", reasoning: "...", confidence: 0.0-1.0}`
|
||||
- Include clear guidelines: same fingerprint across accounts = very suspicious, same IP = somewhat suspicious, etc.
|
||||
|
||||
### Step 4: Create rejection email template
|
||||
- Add `send_credit_denied_email(email, reasoning)` to EmailService
|
||||
- Friendly-but-firm tone
|
||||
- CC andrew@beveridge.uk
|
||||
- Invite reply if it's a mistake
|
||||
- Use existing email template infrastructure (branding, styling)
|
||||
|
||||
### Step 5: Integrate into welcome credit flow
|
||||
- Modify `grant_welcome_credits_if_eligible()` in user_service.py
|
||||
- Before granting: call `CreditEvaluationService.evaluate_credit_grant(email, "welcome")`
|
||||
- If denied: send rejection email, return False
|
||||
- If error: log warning, grant anyway (fail-open)
|
||||
|
||||
### Step 6: Integrate into feedback credit flow
|
||||
- Modify feedback endpoint in users.py
|
||||
- Before granting credits: evaluate with feedback content included
|
||||
- If denied: return different response message, send rejection email
|
||||
- If error: grant anyway
|
||||
|
||||
### Step 7: Add Firestore collection for audit trail
|
||||
- Collection: `credit_evaluations`
|
||||
- Document fields: email, grant_type, decision, reasoning, confidence, signals_snapshot, model_used, evaluated_at
|
||||
- TTL: keep indefinitely (small volume, high audit value)
|
||||
|
||||
### Step 8: Tests
|
||||
- Unit tests for signal collection
|
||||
- Unit tests for prompt building
|
||||
- Unit tests for decision parsing (grant/deny/error cases)
|
||||
- Integration test for the evaluation service with mocked Gemini
|
||||
- Integration test for welcome credit flow with evaluation
|
||||
- Integration test for feedback credit flow with evaluation
|
||||
- Test fail-open behavior
|
||||
|
||||
### Step 9: Configuration
|
||||
- Add env vars: `CREDIT_EVAL_MODEL` (default: "gemini-2.5-pro-preview"), `CREDIT_EVAL_ENABLED` (default: true)
|
||||
- Add to config.py
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `pyproject.toml` | Modify | Add google-generativeai dependency |
|
||||
| `backend/config.py` | Modify | Add credit evaluation config vars |
|
||||
| `backend/services/credit_evaluation_service.py` | Create | New service: collect signals, call Gemini, log decision |
|
||||
| `backend/services/user_service.py` | Modify | Integrate evaluation into welcome credit grant |
|
||||
| `backend/api/routes/users.py` | Modify | Integrate evaluation into feedback credit grant |
|
||||
| `backend/services/email_service.py` | Modify | Add credit denied email template |
|
||||
| `backend/tests/test_credit_evaluation.py` | Create | Tests for evaluation service |
|
||||
| `backend/tests/test_anti_abuse.py` | Modify | Update welcome credit tests for evaluation |
|
||||
| `frontend/app/auth/verify/page.tsx` | Modify | Add "preparing account" loading + credit result interstitial |
|
||||
| `frontend/lib/api.ts` | Modify | Add credit evaluation status endpoint |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Signal collection, prompt building, response parsing, fail-open behavior
|
||||
- **Integration tests**: Full evaluation flow with mocked Gemini responses
|
||||
- **E2E tests**: Manual verification in production with test accounts
|
||||
- **Edge cases**: Gemini timeout, malformed response, missing signals, first-ever user (no correlations)
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **Gemini model**: Using `gemini-3.1-pro-preview` as specified — already available in the nomadkaraoke GCP project.
|
||||
|
||||
2. **Latency UX**: Frontend shows a friendly "preparing your account" loading screen while evaluation runs. Then transitions to either a celebratory "2 free credits!" message (with gentle reminder not to abuse) or a "sorry, couldn't grant free credits" message with a buy credits CTA. User clicks through to dashboard from either.
|
||||
|
||||
3. **Should we also gate the existing rate limiter?** Currently `is_signup_rate_limited()` silently blocks at 2 accounts per IP/fingerprint per 24h. The AI evaluation is complementary — rate limiter blocks obvious rapid abuse, AI evaluation catches more subtle patterns.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run env vars → immediate rollback to auto-grant behavior. No data model changes needed. The evaluation service is purely additive.
|
||||
+345
-116
@@ -959,6 +959,11 @@ jobs:
|
||||
REPOSITORY: karaoke-repo
|
||||
BASE_IMAGE_NAME: karaoke-backend-base
|
||||
APP_IMAGE_NAME: karaoke-backend
|
||||
# GPU image for audio worker (L4 in us-east4)
|
||||
GPU_REGISTRY: us-east4-docker.pkg.dev
|
||||
GPU_REPOSITORY: karaoke-backend-gpu
|
||||
GPU_BASE_IMAGE_NAME: karaoke-backend-gpu-base
|
||||
GPU_APP_IMAGE_NAME: karaoke-backend
|
||||
steps:
|
||||
- name: Check disk space (aggressive for Docker builds)
|
||||
run: |
|
||||
@@ -1016,14 +1021,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 +1040,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 +1053,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,132 +1066,267 @@ 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)."
|
||||
fi
|
||||
|
||||
- name: Restart GCE Encoding Worker
|
||||
- name: Wait for service health
|
||||
id: health
|
||||
continue-on-error: true
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
HEALTH_URL="http://${SECONDARY_IP}:8080/health"
|
||||
|
||||
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"
|
||||
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
|
||||
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
|
||||
|
||||
# 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::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
|
||||
|
||||
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
|
||||
elif [ "$JOB_STATUS" = "failed" ]; then
|
||||
echo "::error::Encode test failed"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
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
|
||||
run: |
|
||||
gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
|
||||
|
||||
# ============================================
|
||||
# Docker Build with BuildKit + Registry Cache
|
||||
@@ -1304,6 +1445,86 @@ jobs:
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
# ============================================
|
||||
# GPU Image Build (for audio worker with L4 GPU)
|
||||
# Same pattern as base image: hash check → rebuild if needed
|
||||
# GPU image lives in us-east4 (co-located with GPU instances)
|
||||
# ============================================
|
||||
|
||||
- name: Calculate GPU base image hash
|
||||
id: gpu-base-hash
|
||||
run: |
|
||||
# Hash Dockerfile.gpu-base + pyproject.toml (deps that affect GPU image)
|
||||
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base pyproject.toml | sha256sum | cut -d' ' -f1)
|
||||
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "📋 GPU base content hash: $CURRENT_HASH"
|
||||
|
||||
- name: Check if GPU base image exists and is current
|
||||
id: check-gpu-base
|
||||
run: |
|
||||
GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
EXISTING_HASH=""
|
||||
|
||||
MANIFEST=$(docker manifest inspect $GPU_BASE_IMAGE 2>/dev/null || echo "")
|
||||
CONFIG_DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
|
||||
|
||||
if [ -n "$CONFIG_DIGEST" ] && [ "$CONFIG_DIGEST" != "null" ] && [ "$CONFIG_DIGEST" != "" ]; then
|
||||
echo "📋 Found GPU manifest, config digest: $CONFIG_DIGEST"
|
||||
TOKEN=$(gcloud auth print-access-token)
|
||||
CONFIG_JSON=$(curl -sL -H "Authorization: Bearer $TOKEN" \
|
||||
"https://${{ env.GPU_REGISTRY }}/v2/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}/blobs/$CONFIG_DIGEST" 2>/dev/null)
|
||||
EXISTING_HASH=$(echo "$CONFIG_JSON" | jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
|
||||
echo "📋 Registry GPU base image hash: $EXISTING_HASH"
|
||||
else
|
||||
echo "⚠️ No existing GPU base image found in registry - will build"
|
||||
fi
|
||||
|
||||
if [ "${{ steps.gpu-base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
|
||||
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or pyproject.toml changed)"
|
||||
echo " Current: ${{ steps.gpu-base-hash.outputs.hash }}"
|
||||
echo " Registry: $EXISTING_HASH"
|
||||
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "✅ GPU base image is up to date"
|
||||
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Build and push GPU base image (if needed)
|
||||
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
|
||||
timeout-minutes: 45
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile.gpu-base
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
build-args: |
|
||||
BUILD_DATE=${{ github.run_id }}
|
||||
BUILD_ID=${{ github.sha }}
|
||||
BASE_CONTENT_HASH=${{ steps.gpu-base-hash.outputs.hash }}
|
||||
provenance: false
|
||||
|
||||
- name: Build and push GPU app image
|
||||
timeout-minutes: 10
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
build-args: |
|
||||
BASE_IMAGE=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
@@ -1333,22 +1554,30 @@ jobs:
|
||||
--min-instances 4 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true" \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
run: |
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
|
||||
echo "📦 Updating Cloud Run Jobs to image: $IMAGE"
|
||||
echo "📦 Updating Cloud Run Jobs..."
|
||||
|
||||
# Video encoding job - runs video worker to completion, immune to service deployments
|
||||
# Video encoding job (CPU, us-central1)
|
||||
gcloud run jobs update video-encoding-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
# Audio separation job (GPU, us-east4) — uses GPU image
|
||||
gcloud run jobs update audio-separation-job \
|
||||
--image "$GPU_IMAGE" \
|
||||
--region us-east4 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
echo "✅ Cloud Run Jobs updated"
|
||||
|
||||
- name: Verify deployment and version
|
||||
|
||||
+9
-1
@@ -26,7 +26,15 @@ COPY backend /app/backend
|
||||
# Note: lyrics_transcriber is now a subpackage of karaoke_gen
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
RUN pip install --no-cache-dir -e .
|
||||
# GPU images (MODEL_DIR set in base): use --no-deps to preserve pinned torch cu126
|
||||
# and audio-separator[gpu]. Without this, pip upgrades torch to cu130 (breaks CUDA
|
||||
# on Cloud Run L4 drivers) and reinstalls audio-separator[cpu] (breaks GPU ONNX).
|
||||
# CPU images: normal install resolves all deps from pyproject.toml.
|
||||
RUN if [ -n "$MODEL_DIR" ]; then \
|
||||
pip install --no-cache-dir --no-deps -e .; \
|
||||
else \
|
||||
pip install --no-cache-dir -e .; \
|
||||
fi
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models
|
||||
# This image is rebuilt only when deps or models change (infrequently).
|
||||
#
|
||||
# Build with: gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
|
||||
# Or manually: docker build -f backend/Dockerfile.gpu-base -t karaoke-backend-gpu-base .
|
||||
#
|
||||
# Layer caching strategy:
|
||||
# 1. System deps + fonts + ffmpeg (rarely change, always cached)
|
||||
# 2. CUDA library path configuration
|
||||
# 3. pyproject.toml + package stubs (changes with dep updates)
|
||||
# 4. pip install karaoke-gen deps + audio-separator[gpu] (slow, cached unless pyproject.toml changes)
|
||||
# 5. Source code copy (changes every rebuild, but AFTER deps are installed)
|
||||
# 6. spaCy model download (cached unless pip install layer changes)
|
||||
# 7. Pre-downloaded ensemble preset models (~1-1.5 GB, cached unless pip layer changes)
|
||||
|
||||
FROM nvidia/cuda:12.6.3-runtime-ubuntu22.04
|
||||
|
||||
# Prevent interactive prompts during package installation
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Install Python 3.11 from deadsnakes PPA and system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
software-properties-common \
|
||||
&& add-apt-repository -y ppa:deadsnakes/ppa \
|
||||
&& apt-get update && apt-get install -y --no-install-recommends \
|
||||
# Python 3.11
|
||||
python3.11 \
|
||||
python3.11-dev \
|
||||
python3.11-venv \
|
||||
# Audio libraries
|
||||
libsndfile1 \
|
||||
libsox-dev \
|
||||
sox \
|
||||
# Build tools
|
||||
build-essential \
|
||||
# Utilities
|
||||
curl \
|
||||
xz-utils \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& python3.11 --version
|
||||
|
||||
# Install comprehensive font support for international lyrics and symbols
|
||||
# Noto fonts provide full Unicode coverage including:
|
||||
# - Latin, Greek, Cyrillic (core)
|
||||
# - CJK: Chinese, Japanese, Korean (~150MB)
|
||||
# - Arabic, Hebrew, Thai, Hindi, and other scripts (extra)
|
||||
# - Color emoji (limited support in libass, but available)
|
||||
# - Musical symbols (♪ ♫ etc.)
|
||||
# Note: This adds ~200-300MB to the image but ensures all languages render correctly
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fonts-noto-extra \
|
||||
fonts-noto-color-emoji \
|
||||
fontconfig \
|
||||
&& fc-cache -f \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install FFmpeg from Ubuntu package
|
||||
# The audio worker only uses FFmpeg for format conversion and padding, not
|
||||
# encoding-intensive tasks, so the Debian package is sufficient. The static
|
||||
# build from johnvansickle.com is used for the encoding worker instead.
|
||||
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set Python 3.11 as default and install pip
|
||||
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1 \
|
||||
&& update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 \
|
||||
&& curl -sS https://bootstrap.pypa.io/get-pip.py | python3.11 \
|
||||
&& python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel
|
||||
|
||||
# Set up CUDA library paths so GPU-accelerated packages can find CUDA libs at runtime
|
||||
RUN echo '/usr/local/cuda/lib64' >> /etc/ld.so.conf.d/cuda.conf && ldconfig
|
||||
|
||||
# Environment configuration for CUDA and Python
|
||||
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH \
|
||||
PATH=/usr/local/cuda/bin:$PATH \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
MODEL_DIR=/models
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy ONLY dependency specification files first (changes less often than source code)
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
|
||||
# Create minimal package stubs so pip can resolve the editable install
|
||||
# pip install -e . needs package directories to exist but doesn't validate content
|
||||
RUN mkdir -p /app/karaoke_gen /app/lyrics_transcriber_temp /app/backend && \
|
||||
touch /app/karaoke_gen/__init__.py /app/lyrics_transcriber_temp/__init__.py /app/backend/__init__.py
|
||||
|
||||
# Install all karaoke-gen Python dependencies (the slow part)
|
||||
# BuildKit cache mount preserves downloaded wheels across builds
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install --upgrade pip && \
|
||||
pip install -e .
|
||||
|
||||
# Install audio-separator with GPU support (PyTorch + CUDA + onnxruntime-gpu)
|
||||
# This is separate from pip install -e . to keep layer caching granular
|
||||
#
|
||||
# IMPORTANT: Install PyTorch cu126 FIRST, then audio-separator[gpu].
|
||||
# The default audio-separator[gpu] pulls PyTorch cu130, but Cloud Run L4 GPUs
|
||||
# have NVIDIA driver 570 which only supports up to CUDA 12.8. PyTorch cu130
|
||||
# fails with "NVIDIA driver is too old". PyTorch cu126 works with 12.8 drivers.
|
||||
# Installing torch first means audio-separator[gpu] sees it as already satisfied.
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install torch==2.6.0+cu126 torchvision==0.21.0+cu126 --index-url https://download.pytorch.org/whl/cu126 && \
|
||||
pip install "audio-separator[gpu]"
|
||||
|
||||
# Now copy actual source code (AFTER deps installed, so code changes don't
|
||||
# invalidate the expensive pip install layer in registry cache)
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
|
||||
COPY backend /app/backend
|
||||
|
||||
# Download spaCy language model for lyrics transcription
|
||||
# Must be done at build time, not runtime (Cloud Run network restrictions)
|
||||
RUN python -m spacy download en_core_web_sm
|
||||
|
||||
# Create models directory and pre-download ensemble preset models
|
||||
# Baking models into the image eliminates cold-start model download latency.
|
||||
# Total model size: ~1-1.5 GB for instrumental_clean + karaoke presets.
|
||||
RUN mkdir -p /models
|
||||
COPY backend/scripts/download_models.py /tmp/download_models.py
|
||||
RUN python /tmp/download_models.py /models && \
|
||||
rm /tmp/download_models.py && \
|
||||
ls -lh /models/
|
||||
|
||||
# Label with build info
|
||||
ARG BUILD_DATE
|
||||
ARG BUILD_ID
|
||||
ARG BASE_CONTENT_HASH
|
||||
LABEL org.opencontainers.image.created="${BUILD_DATE}"
|
||||
LABEL org.opencontainers.image.revision="${BUILD_ID}"
|
||||
LABEL org.opencontainers.image.title="karaoke-backend-gpu-base"
|
||||
LABEL org.opencontainers.image.description="GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models for karaoke-backend audio worker"
|
||||
LABEL base.content.hash="${BASE_CONTENT_HASH}"
|
||||
@@ -3586,6 +3586,56 @@ async def find_related_accounts(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/abuse/correlations")
|
||||
async def find_account_correlations(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Find clusters of accounts sharing the same device fingerprint or signup IP.
|
||||
|
||||
Returns fingerprint clusters (RED flag - near-certain multi-accounting) and
|
||||
IP clusters (ORANGE flag - suspicious but could be shared network), sorted
|
||||
by group size. Includes user agent data for additional correlation signal.
|
||||
"""
|
||||
result = user_service.find_account_correlations()
|
||||
user_agents = result.get("user_agents", {})
|
||||
|
||||
def serialize_cluster_user(u, include_user_agent=True):
|
||||
data = {
|
||||
"email": u.email,
|
||||
"signup_ip": u.signup_ip,
|
||||
"device_fingerprint": u.device_fingerprint,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_jobs_completed": u.total_jobs_completed,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
if include_user_agent:
|
||||
data["user_agent"] = user_agents.get(u.email)
|
||||
return data
|
||||
|
||||
return {
|
||||
"fingerprint_clusters": [
|
||||
{
|
||||
"fingerprint": cluster["fingerprint"],
|
||||
"count": len(cluster["users"]),
|
||||
"users": [serialize_cluster_user(u) for u in cluster["users"]],
|
||||
}
|
||||
for cluster in result["fingerprint_clusters"]
|
||||
],
|
||||
"ip_clusters": [
|
||||
{
|
||||
"ip": cluster["ip"],
|
||||
"count": len(cluster["users"]),
|
||||
"users": [serialize_cluster_user(u) for u in cluster["users"]],
|
||||
}
|
||||
for cluster in result["ip_clusters"]
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/abuse/suspicious")
|
||||
async def find_suspicious_accounts(
|
||||
min_jobs: int = 2,
|
||||
@@ -3794,3 +3844,109 @@ async def get_ip_info_batch(
|
||||
raise HTTPException(status_code=400, detail="Maximum 100 IPs per batch request")
|
||||
geo_service = get_ip_geolocation_service()
|
||||
return geo_service.lookup_ips_batch(request.ips)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# User Feedback
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class AdminFeedbackItem(BaseModel):
|
||||
"""Single feedback submission for admin view."""
|
||||
id: str
|
||||
user_email: str
|
||||
created_at: Optional[str] = None
|
||||
overall_rating: int
|
||||
ease_of_use_rating: int
|
||||
lyrics_accuracy_rating: int
|
||||
correction_experience_rating: int
|
||||
what_went_well: Optional[str] = None
|
||||
what_could_improve: Optional[str] = None
|
||||
additional_comments: Optional[str] = None
|
||||
would_recommend: bool = True
|
||||
would_use_again: bool = True
|
||||
|
||||
|
||||
class AdminFeedbackListResponse(BaseModel):
|
||||
"""Paginated list of feedback submissions."""
|
||||
items: List[AdminFeedbackItem]
|
||||
total: int
|
||||
offset: int
|
||||
limit: int
|
||||
has_more: bool
|
||||
avg_overall_rating: Optional[float] = None
|
||||
avg_ease_of_use_rating: Optional[float] = None
|
||||
avg_lyrics_accuracy_rating: Optional[float] = None
|
||||
avg_correction_experience_rating: Optional[float] = None
|
||||
|
||||
|
||||
@router.get("/feedback", response_model=AdminFeedbackListResponse)
|
||||
def list_user_feedback(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
search: Optional[str] = None,
|
||||
exclude_test: bool = False,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""List all user feedback submissions with pagination and search."""
|
||||
limit = max(1, min(limit, 200))
|
||||
offset = max(0, offset)
|
||||
|
||||
user_service = get_user_service()
|
||||
db = user_service.db
|
||||
|
||||
items = []
|
||||
for doc in db.collection("user_feedback").stream():
|
||||
data = doc.to_dict()
|
||||
email = data.get("user_email", "")
|
||||
|
||||
if exclude_test and is_test_email(email):
|
||||
continue
|
||||
|
||||
if search and search.lower() not in email.lower():
|
||||
continue
|
||||
|
||||
created_at = data.get("created_at")
|
||||
if created_at is not None and hasattr(created_at, "isoformat"):
|
||||
created_at = created_at.isoformat()
|
||||
elif created_at is not None:
|
||||
created_at = str(created_at)
|
||||
|
||||
items.append(AdminFeedbackItem(
|
||||
id=data.get("id", doc.id),
|
||||
user_email=email,
|
||||
created_at=created_at,
|
||||
overall_rating=data.get("overall_rating", 0),
|
||||
ease_of_use_rating=data.get("ease_of_use_rating", 0),
|
||||
lyrics_accuracy_rating=data.get("lyrics_accuracy_rating", 0),
|
||||
correction_experience_rating=data.get("correction_experience_rating", 0),
|
||||
what_went_well=data.get("what_went_well"),
|
||||
what_could_improve=data.get("what_could_improve"),
|
||||
additional_comments=data.get("additional_comments"),
|
||||
would_recommend=data.get("would_recommend", True),
|
||||
would_use_again=data.get("would_use_again", True),
|
||||
))
|
||||
|
||||
# Sort by newest first
|
||||
items.sort(key=lambda x: x.created_at or "", reverse=True)
|
||||
|
||||
# Compute aggregate stats
|
||||
total = len(items)
|
||||
avg_overall = sum(i.overall_rating for i in items) / total if total else None
|
||||
avg_ease = sum(i.ease_of_use_rating for i in items) / total if total else None
|
||||
avg_lyrics = sum(i.lyrics_accuracy_rating for i in items) / total if total else None
|
||||
avg_correction = sum(i.correction_experience_rating for i in items) / total if total else None
|
||||
|
||||
paginated = items[offset:offset + limit]
|
||||
|
||||
return AdminFeedbackListResponse(
|
||||
items=paginated,
|
||||
total=total,
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
has_more=(offset + limit) < total,
|
||||
avg_overall_rating=round(avg_overall, 2) if avg_overall is not None else None,
|
||||
avg_ease_of_use_rating=round(avg_ease, 2) if avg_ease is not None else None,
|
||||
avg_lyrics_accuracy_rating=round(avg_lyrics, 2) if avg_lyrics is not None else None,
|
||||
avg_correction_experience_rating=round(avg_correction, 2) if avg_correction is not None else None,
|
||||
)
|
||||
@@ -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)}
|
||||
@@ -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
|
||||
|
||||
@@ -1693,11 +1693,14 @@ async def retry_job(
|
||||
"retry_stage": "video_generation"
|
||||
}
|
||||
|
||||
# If we have corrections and screens but no video, retry render
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections and screens, retrying from render stage")
|
||||
# If we have corrections, screens, AND review was completed, retry render
|
||||
# Review completion is proven by instrumental_selection in state_data
|
||||
# (set only when user submits the review endpoint)
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title') and
|
||||
state_data.get('instrumental_selection')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
|
||||
|
||||
# Clear error state and reset worker progress for idempotency
|
||||
job_manager.update_job(job_id, {
|
||||
@@ -1717,16 +1720,48 @@ async def retry_job(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
|
||||
# Trigger render video worker
|
||||
background_tasks.add_task(worker_service.trigger_render_video_worker, job_id)
|
||||
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "review_complete",
|
||||
"message": "Job retry started from render stage",
|
||||
"retry_stage": "render_video"
|
||||
}
|
||||
|
||||
# If we have corrections and screens but review was NOT completed,
|
||||
# return to awaiting_review so the user can review lyrics
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
|
||||
|
||||
# Clear error state
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
'error_details': None,
|
||||
})
|
||||
|
||||
# Transition to AWAITING_REVIEW so user can review lyrics
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message=f"Ready for review. Please review lyrics and select your instrumental."
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "awaiting_review",
|
||||
"message": "Job retry: returning to lyrics review (review was not completed before failure)",
|
||||
"retry_stage": "awaiting_review"
|
||||
}
|
||||
|
||||
# If we have stems and corrections, retry from screens generation
|
||||
elif (file_urls.get('stems', {}).get('instrumental_clean') and
|
||||
|
||||
+130
-6
@@ -10,6 +10,7 @@ Handles:
|
||||
"""
|
||||
import hashlib
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
|
||||
@@ -132,6 +133,32 @@ class LogoutResponse(BaseModel):
|
||||
# Magic Link Authentication
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def _precompute_credit_eval(token: str, email: str) -> None:
|
||||
"""Run credit evaluation in background and store result on magic link doc.
|
||||
|
||||
Called in a background thread after sending a magic link for new users.
|
||||
If the user clicks the link before this finishes, verify_magic_link falls
|
||||
back to inline evaluation (same as before this optimization).
|
||||
"""
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import get_credit_evaluation_service
|
||||
from backend.services.user_service import get_user_service, MAGIC_LINKS_COLLECTION
|
||||
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
|
||||
user_service = get_user_service()
|
||||
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
|
||||
"credit_eval_decision": evaluation.decision,
|
||||
"credit_eval_reasoning": evaluation.reasoning,
|
||||
"credit_eval_error": evaluation.error,
|
||||
})
|
||||
logger.info(f"Pre-computed credit eval for {_mask_email(email)}: {evaluation.decision}")
|
||||
except Exception:
|
||||
logger.exception(f"Background credit eval failed for {_mask_email(email)} — verify will compute inline")
|
||||
|
||||
|
||||
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
|
||||
async def send_magic_link(
|
||||
request: SendMagicLinkRequest,
|
||||
@@ -250,6 +277,17 @@ async def send_magic_link(
|
||||
# Don't reveal failure to prevent email enumeration
|
||||
# Still return success
|
||||
|
||||
# Pre-compute credit evaluation in background for new users.
|
||||
# By the time they check their email and click the link, the decision
|
||||
# will be ready and verification will be instant.
|
||||
if existing_user is None:
|
||||
thread = threading.Thread(
|
||||
target=_precompute_credit_eval,
|
||||
args=(magic_link.token, email),
|
||||
daemon=True,
|
||||
)
|
||||
thread.start()
|
||||
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
@@ -297,13 +335,28 @@ async def verify_magic_link(
|
||||
if not success or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
# Grant welcome credits on first verification (not at account creation)
|
||||
# Grant welcome credits on first verification (with AI abuse evaluation)
|
||||
# Use pre-computed evaluation from magic link if available (computed at send time)
|
||||
precomputed_eval = None
|
||||
if magic_link_doc.exists:
|
||||
precomputed_eval = {
|
||||
k: magic_link_data.get(k)
|
||||
for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error")
|
||||
if magic_link_data.get(k) is not None
|
||||
} or None
|
||||
|
||||
credits_granted = 0
|
||||
if user_service.grant_welcome_credits_if_eligible(user.email):
|
||||
credit_status = "not_applicable" # returning user, not first login
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
|
||||
user.email, precomputed_eval=precomputed_eval,
|
||||
)
|
||||
if granted:
|
||||
credits_granted = user_service.NEW_USER_FREE_CREDITS
|
||||
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
|
||||
# Refresh user to get updated credit balance
|
||||
user = user_service.get_user(user.email)
|
||||
elif credit_status == "denied":
|
||||
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
|
||||
|
||||
# Create session with tenant context and device fingerprint from the magic link
|
||||
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
|
||||
@@ -346,6 +399,7 @@ async def verify_magic_link(
|
||||
message="Successfully signed in",
|
||||
tenant_subdomain=tenant_subdomain,
|
||||
credits_granted=credits_granted,
|
||||
credit_status=credit_status,
|
||||
)
|
||||
|
||||
|
||||
@@ -1121,7 +1175,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,
|
||||
)
|
||||
|
||||
|
||||
@@ -1132,7 +1186,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
|
||||
@@ -1210,8 +1264,59 @@ async def submit_user_feedback(
|
||||
has_submitted_feedback=True,
|
||||
)
|
||||
|
||||
# Grant 2 credits
|
||||
credits_granted = 2
|
||||
# AI evaluation before granting feedback credits
|
||||
credits_granted = 0
|
||||
feedback_content = {
|
||||
"overall_rating": request.overall_rating,
|
||||
"what_went_well": request.what_went_well,
|
||||
"what_could_improve": request.what_could_improve,
|
||||
"additional_comments": request.additional_comments,
|
||||
}
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import get_credit_evaluation_service
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(user.email, "feedback", feedback_content)
|
||||
|
||||
if evaluation.decision == "deny":
|
||||
logger.info(f"Feedback credits denied for {_mask_email(user.email)}: {evaluation.reasoning}")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_denied_email(user.email, "feedback")
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send credit denied email to {_mask_email(user.email)}")
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message="Thank you for your feedback! We appreciate your input.",
|
||||
credits_granted=0,
|
||||
)
|
||||
|
||||
if evaluation.decision == "pending_review":
|
||||
logger.info(f"Feedback credits pending review for {_mask_email(user.email)}: {evaluation.reasoning}")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_review_needed_email(user.email, "feedback", evaluation.reasoning)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send review needed email for {_mask_email(user.email)}")
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message="Thank you for your feedback! Our team will review your account shortly.",
|
||||
credits_granted=0,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Credit evaluation failed for {_mask_email(user.email)} — pending review (fail-closed)")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_review_needed_email(user.email, "feedback", "Evaluation error")
|
||||
except Exception:
|
||||
pass
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message="Thank you for your feedback! Our team will review your account shortly.",
|
||||
credits_granted=0,
|
||||
)
|
||||
|
||||
# Grant 1 credit (passed evaluation)
|
||||
credits_granted = 1
|
||||
user_service.add_credits(
|
||||
email=user.email,
|
||||
amount=credits_granted,
|
||||
@@ -1223,6 +1328,25 @@ async def submit_user_feedback(
|
||||
f"credits granted: {credits_granted}"
|
||||
)
|
||||
|
||||
# Send admin notification email (fire-and-forget)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
email_service.send_feedback_notification(
|
||||
user_email=user.email,
|
||||
overall_rating=request.overall_rating,
|
||||
ease_of_use_rating=request.ease_of_use_rating,
|
||||
lyrics_accuracy_rating=request.lyrics_accuracy_rating,
|
||||
correction_experience_rating=request.correction_experience_rating,
|
||||
what_went_well=request.what_went_well,
|
||||
what_could_improve=request.what_could_improve,
|
||||
additional_comments=request.additional_comments,
|
||||
would_recommend=request.would_recommend,
|
||||
would_use_again=request.would_use_again,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to send feedback notification email: {e}")
|
||||
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message=f"Thank you for your feedback! You earned {credits_granted} free credits.",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Cloud Build config for GPU base image
|
||||
#
|
||||
# Builds the CUDA + PyTorch + models base image used by the audio worker.
|
||||
# This image is large (~10GB) so builds take 15-30 minutes.
|
||||
#
|
||||
# Trigger manually:
|
||||
# gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
|
||||
#
|
||||
# The app-layer Dockerfile uses this as its BASE_IMAGE for audio worker deploys.
|
||||
|
||||
steps:
|
||||
- name: 'gcr.io/cloud-builders/docker'
|
||||
args:
|
||||
- 'build'
|
||||
- '-f'
|
||||
- 'backend/Dockerfile.gpu-base'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- '--build-arg'
|
||||
- 'BUILD_DATE=$_BUILD_DATE'
|
||||
- '--build-arg'
|
||||
- 'BUILD_ID=$BUILD_ID'
|
||||
- '.'
|
||||
|
||||
images:
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
|
||||
timeout: '3600s'
|
||||
|
||||
options:
|
||||
machineType: 'E2_HIGHCPU_32'
|
||||
diskSizeGb: 100
|
||||
@@ -57,6 +57,12 @@ class Settings(BaseSettings):
|
||||
# use uncorrected transcription - human review will fix any issues.
|
||||
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
|
||||
|
||||
# AI Credit Evaluation (anti-abuse gating for free credits)
|
||||
# When enabled, welcome and feedback credit grants are evaluated by Gemini
|
||||
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
|
||||
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
|
||||
|
||||
# Cloud Tasks (for scalable worker coordination)
|
||||
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
|
||||
# When disabled (default), workers are triggered via direct HTTP (for development)
|
||||
|
||||
+2
-1
@@ -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)
|
||||
|
||||
@@ -129,6 +129,11 @@ class MagicLinkToken(BaseModel):
|
||||
# Multi-tenant support (None = default Nomad Karaoke)
|
||||
tenant_id: Optional[str] = None
|
||||
|
||||
# Pre-computed credit evaluation (set asynchronously after magic link is sent)
|
||||
credit_eval_decision: Optional[str] = None # "grant", "deny", "pending_review"
|
||||
credit_eval_reasoning: Optional[str] = None
|
||||
credit_eval_error: Optional[str] = None
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
"""
|
||||
@@ -180,6 +185,7 @@ class VerifyMagicLinkResponse(BaseModel):
|
||||
message: str
|
||||
tenant_subdomain: Optional[str] = None
|
||||
credits_granted: int = 0
|
||||
credit_status: str = "not_applicable" # "granted", "denied", "pending_review", "already_granted", "not_applicable"
|
||||
|
||||
|
||||
class UserPublic(BaseModel):
|
||||
@@ -228,7 +234,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
|
||||
@@ -283,4 +289,4 @@ class FeedbackEligibilityResponse(BaseModel):
|
||||
eligible: bool
|
||||
has_submitted: bool
|
||||
jobs_completed: int
|
||||
credits_reward: int = 2
|
||||
credits_reward: int = 1
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Download ensemble preset models at Docker build time.
|
||||
|
||||
Bakes models into the image so they're available immediately at runtime,
|
||||
avoiding cold-start model download latency in Cloud Run Jobs.
|
||||
|
||||
Usage: python backend/scripts/download_models.py /models
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import logging
|
||||
import importlib.resources as resources
|
||||
from audio_separator.separator import Separator
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Presets to bake into the GPU image
|
||||
PRESETS_TO_DOWNLOAD = ["instrumental_clean", "karaoke"]
|
||||
|
||||
|
||||
def download_preset_models(model_dir: str) -> None:
|
||||
"""Download all models for the configured presets individually.
|
||||
|
||||
Ensemble presets resolve to multiple model filenames. We must download
|
||||
each model individually via load_model(model_filename) — calling
|
||||
load_model() with no args on an ensemble preset doesn't trigger downloads.
|
||||
"""
|
||||
with resources.open_text("audio_separator", "ensemble_presets.json") as f:
|
||||
presets = json.load(f)["presets"]
|
||||
|
||||
models_to_download = set()
|
||||
for preset_name in PRESETS_TO_DOWNLOAD:
|
||||
models_to_download.update(presets[preset_name]["models"])
|
||||
|
||||
logger.info(f"Downloading {len(models_to_download)} models for presets: {PRESETS_TO_DOWNLOAD}")
|
||||
for model in sorted(models_to_download):
|
||||
logger.info(f" Downloading: {model}")
|
||||
sep = Separator(model_file_dir=model_dir)
|
||||
sep.load_model(model)
|
||||
logger.info(f" Done: {model}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
model_dir = sys.argv[1] if len(sys.argv) > 1 else "/models"
|
||||
download_preset_models(model_dir)
|
||||
logger.info(f"All preset models downloaded to {model_dir}")
|
||||
@@ -0,0 +1,441 @@
|
||||
"""
|
||||
AI-powered credit evaluation service.
|
||||
|
||||
Evaluates whether to grant free credits (welcome or feedback) by collecting
|
||||
abuse signals and asking Gemini for a grant/deny decision. Fail-open: if
|
||||
the AI call fails for any reason, credits are granted.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CREDIT_EVALUATIONS_COLLECTION = "credit_evaluations"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CreditEvaluation:
|
||||
"""Result of an AI credit evaluation."""
|
||||
decision: str # "grant" or "deny"
|
||||
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 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.
|
||||
|
||||
## Decision Guidelines
|
||||
|
||||
**DENY if any of these are true:**
|
||||
- The user's device fingerprint matches other accounts (strong signal of multi-accounting)
|
||||
- The user's signup IP matches other accounts AND those accounts also have suspicious patterns (e.g., no spend, same user agent)
|
||||
- There's a clear pattern of account creation from the same device/network to farm free credits
|
||||
|
||||
**GRANT if:**
|
||||
- This appears to be a genuine new user with no suspicious correlations
|
||||
- The IP match is explainable (e.g., different fingerprints suggest different actual users on a shared network like a school or office)
|
||||
- There's insufficient evidence to confidently flag abuse
|
||||
|
||||
**When in doubt, GRANT.** False positives (blocking real users) are worse than false negatives (letting an occasional abuser through). We'd rather lose a few dollars than alienate a real customer.
|
||||
|
||||
## Response Format
|
||||
|
||||
Respond with ONLY a JSON object, no other text:
|
||||
{"decision": "grant" or "deny", "reasoning": "Brief explanation", "confidence": 0.0 to 1.0}
|
||||
"""
|
||||
|
||||
|
||||
def _build_user_prompt(
|
||||
email: str,
|
||||
grant_type: str,
|
||||
user_data: dict,
|
||||
fingerprint_matches: list,
|
||||
ip_matches: list,
|
||||
ip_geo: Optional[dict],
|
||||
recent_signups_ip: int,
|
||||
recent_signups_fp: int,
|
||||
user_agent: Optional[str],
|
||||
feedback_content: Optional[dict] = None,
|
||||
) -> str:
|
||||
"""Build the user prompt with all abuse signals."""
|
||||
lines = [
|
||||
f"## Credit Grant Request",
|
||||
f"- **Email:** {email}",
|
||||
f"- **Grant type:** {grant_type} credits",
|
||||
f"- **User's device fingerprint:** {user_data.get('device_fingerprint', 'unknown')}",
|
||||
f"- **User's signup IP:** {user_data.get('signup_ip', 'unknown')}",
|
||||
f"- **User agent:** {user_agent or 'unknown'}",
|
||||
f"- **Account created:** {user_data.get('created_at', 'unknown')}",
|
||||
f"- **Jobs created:** {user_data.get('total_jobs_created', 0)}",
|
||||
f"- **Jobs completed:** {user_data.get('total_jobs_completed', 0)}",
|
||||
f"- **Total spent (real money):** ${user_data.get('total_spent', 0) / 100:.2f}",
|
||||
f"- **Current credits:** {user_data.get('credits', 0)}",
|
||||
"",
|
||||
]
|
||||
|
||||
# IP geolocation
|
||||
if ip_geo and ip_geo.get("status") == "success":
|
||||
lines.extend([
|
||||
f"## IP Geolocation",
|
||||
f"- **Country:** {ip_geo.get('country', 'unknown')} ({ip_geo.get('country_code', '')})",
|
||||
f"- **City/Region:** {ip_geo.get('city', '')}, {ip_geo.get('region', '')}",
|
||||
f"- **ISP:** {ip_geo.get('isp', 'unknown')}",
|
||||
f"- **Organization:** {ip_geo.get('org', 'unknown')}",
|
||||
f"- **ASN:** {ip_geo.get('as_number', '')} {ip_geo.get('as_name', '')}",
|
||||
"",
|
||||
])
|
||||
|
||||
# Recent signup patterns
|
||||
lines.extend([
|
||||
f"## Recent Signup Patterns (last 24 hours)",
|
||||
f"- **New accounts from same IP:** {recent_signups_ip}",
|
||||
f"- **New accounts from same fingerprint:** {recent_signups_fp}",
|
||||
"",
|
||||
])
|
||||
|
||||
# Fingerprint correlations
|
||||
if fingerprint_matches:
|
||||
lines.append("## Other Accounts with Same Device Fingerprint (RED FLAG)")
|
||||
for match in fingerprint_matches:
|
||||
lines.append(
|
||||
f"- {match.get('email', '?')} | "
|
||||
f"Jobs: {match.get('total_jobs_created', 0)} | "
|
||||
f"Spent: ${match.get('total_spent', 0) / 100:.2f} | "
|
||||
f"Created: {match.get('created_at', '?')}"
|
||||
)
|
||||
lines.append("")
|
||||
else:
|
||||
lines.extend(["## Other Accounts with Same Device Fingerprint", "None found.", ""])
|
||||
|
||||
# IP correlations
|
||||
if ip_matches:
|
||||
lines.append("## Other Accounts from Same Signup IP")
|
||||
for match in ip_matches:
|
||||
lines.append(
|
||||
f"- {match.get('email', '?')} | "
|
||||
f"Fingerprint: {match.get('device_fingerprint', 'unknown')} | "
|
||||
f"Jobs: {match.get('total_jobs_created', 0)} | "
|
||||
f"Spent: ${match.get('total_spent', 0) / 100:.2f} | "
|
||||
f"Created: {match.get('created_at', '?')}"
|
||||
)
|
||||
lines.append("")
|
||||
else:
|
||||
lines.extend(["## Other Accounts from Same Signup IP", "None found.", ""])
|
||||
|
||||
# Feedback content (if applicable)
|
||||
if feedback_content:
|
||||
lines.extend([
|
||||
"## Feedback Submitted",
|
||||
f"- **Overall rating:** {feedback_content.get('overall_rating', '?')}/5",
|
||||
f"- **What went well:** {feedback_content.get('what_went_well', 'N/A')[:200]}",
|
||||
f"- **What could improve:** {feedback_content.get('what_could_improve', 'N/A')[:200]}",
|
||||
f"- **Additional comments:** {feedback_content.get('additional_comments', 'N/A')[:200]}",
|
||||
"",
|
||||
])
|
||||
|
||||
lines.append("Based on these signals, should we GRANT or DENY free credits to this user?")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _parse_gemini_response(response_text: str) -> CreditEvaluation:
|
||||
"""Parse Gemini's JSON response into a CreditEvaluation."""
|
||||
try:
|
||||
# Strip markdown code fences if present
|
||||
text = response_text.strip()
|
||||
if text.startswith("```"):
|
||||
text = text.split("\n", 1)[1] if "\n" in text else text[3:]
|
||||
if text.endswith("```"):
|
||||
text = text.rsplit("```", 1)[0]
|
||||
text = text.strip()
|
||||
if text.startswith("json"):
|
||||
text = text[4:].strip()
|
||||
|
||||
data = json.loads(text)
|
||||
decision = data.get("decision", "").lower()
|
||||
if decision not in ("grant", "deny"):
|
||||
decision = "pending_review" # fail-closed: unknown decision → manual review
|
||||
|
||||
return CreditEvaluation(
|
||||
decision=decision,
|
||||
reasoning=str(data.get("reasoning", "No reasoning provided")),
|
||||
confidence=float(data.get("confidence", 0.5)),
|
||||
)
|
||||
except (json.JSONDecodeError, ValueError, TypeError) as e:
|
||||
logger.warning(f"Failed to parse Gemini response: {e}. Response: {response_text[:200]}")
|
||||
return CreditEvaluation(
|
||||
decision="pending_review",
|
||||
reasoning="Failed to parse AI response — pending manual review",
|
||||
confidence=0.0,
|
||||
error=f"Parse error: {e}",
|
||||
)
|
||||
|
||||
|
||||
class CreditEvaluationService:
|
||||
"""Evaluates credit grant requests using Gemini AI."""
|
||||
|
||||
def __init__(self):
|
||||
self.settings = get_settings()
|
||||
|
||||
def _collect_signals(self, email: str) -> dict:
|
||||
"""Collect all abuse signals for evaluation."""
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.ip_geolocation_service import get_ip_geolocation_service
|
||||
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(email)
|
||||
|
||||
if not user:
|
||||
return {
|
||||
"user_data": {},
|
||||
"fingerprint_matches": [],
|
||||
"ip_matches": [],
|
||||
"ip_geo": None,
|
||||
"recent_signups_ip": 0,
|
||||
"recent_signups_fp": 0,
|
||||
"user_agent": None,
|
||||
}
|
||||
|
||||
user_data = {
|
||||
"email": user.email,
|
||||
"device_fingerprint": user.device_fingerprint,
|
||||
"signup_ip": user.signup_ip,
|
||||
"credits": user.credits,
|
||||
"total_jobs_created": user.total_jobs_created,
|
||||
"total_jobs_completed": user.total_jobs_completed,
|
||||
"total_spent": user.total_spent,
|
||||
"created_at": str(user.created_at),
|
||||
}
|
||||
|
||||
# Find other accounts with same fingerprint
|
||||
fingerprint_matches = []
|
||||
if user.device_fingerprint:
|
||||
fp_users = user_service.find_users_by_fingerprint(user.device_fingerprint)
|
||||
fingerprint_matches = [
|
||||
{
|
||||
"email": u.email,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in fp_users if u.email != email
|
||||
]
|
||||
|
||||
# Find other accounts from same IP
|
||||
ip_matches = []
|
||||
if user.signup_ip:
|
||||
ip_users = user_service.find_users_by_signup_ip(user.signup_ip)
|
||||
ip_matches = [
|
||||
{
|
||||
"email": u.email,
|
||||
"device_fingerprint": u.device_fingerprint,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in ip_users if u.email != email
|
||||
]
|
||||
|
||||
# IP geolocation
|
||||
ip_geo = None
|
||||
if user.signup_ip:
|
||||
try:
|
||||
geo_service = get_ip_geolocation_service()
|
||||
ip_geo = geo_service.lookup_ip(user.signup_ip)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Recent signup counts
|
||||
recent_signups_ip = 0
|
||||
recent_signups_fp = 0
|
||||
if user.signup_ip:
|
||||
recent_signups_ip = user_service.count_recent_signups_from_ip(user.signup_ip)
|
||||
if user.device_fingerprint:
|
||||
recent_signups_fp = user_service.count_recent_signups_from_fingerprint(user.device_fingerprint)
|
||||
|
||||
# User agent from latest session
|
||||
user_agent = None
|
||||
try:
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from google.cloud import firestore as fs
|
||||
sessions = (
|
||||
user_service.db.collection("sessions")
|
||||
.where(filter=FieldFilter("user_email", "==", email))
|
||||
.order_by("created_at", direction=fs.Query.DESCENDING)
|
||||
.limit(1)
|
||||
.stream()
|
||||
)
|
||||
for session_doc in sessions:
|
||||
user_agent = session_doc.to_dict().get("user_agent")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"user_data": user_data,
|
||||
"fingerprint_matches": fingerprint_matches,
|
||||
"ip_matches": ip_matches,
|
||||
"ip_geo": ip_geo,
|
||||
"recent_signups_ip": recent_signups_ip,
|
||||
"recent_signups_fp": recent_signups_fp,
|
||||
"user_agent": user_agent,
|
||||
}
|
||||
|
||||
def _call_gemini(self, prompt: str) -> str:
|
||||
"""Call Gemini and return the response text."""
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.credit_eval_model,
|
||||
contents=prompt,
|
||||
config=genai.types.GenerateContentConfig(
|
||||
system_instruction=SYSTEM_PROMPT,
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
|
||||
def _log_evaluation(
|
||||
self,
|
||||
email: str,
|
||||
grant_type: str,
|
||||
evaluation: CreditEvaluation,
|
||||
signals: dict,
|
||||
):
|
||||
"""Log the evaluation decision to Firestore for audit trail."""
|
||||
try:
|
||||
from google.cloud import firestore as fs
|
||||
db = fs.Client(project=self.settings.google_cloud_project)
|
||||
doc_id = str(uuid.uuid4())
|
||||
db.collection(CREDIT_EVALUATIONS_COLLECTION).document(doc_id).set({
|
||||
"id": doc_id,
|
||||
"email": email,
|
||||
"grant_type": grant_type,
|
||||
"decision": evaluation.decision,
|
||||
"reasoning": evaluation.reasoning,
|
||||
"confidence": evaluation.confidence,
|
||||
"error": evaluation.error,
|
||||
"model": self.settings.credit_eval_model,
|
||||
"signals_snapshot": {
|
||||
"fingerprint_match_count": len(signals.get("fingerprint_matches", [])),
|
||||
"ip_match_count": len(signals.get("ip_matches", [])),
|
||||
"recent_signups_ip": signals.get("recent_signups_ip", 0),
|
||||
"recent_signups_fp": signals.get("recent_signups_fp", 0),
|
||||
"user_ip": signals.get("user_data", {}).get("signup_ip"),
|
||||
"user_fingerprint": signals.get("user_data", {}).get("device_fingerprint"),
|
||||
},
|
||||
"evaluated_at": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
except Exception:
|
||||
logger.exception(f"Failed to log credit evaluation for {email}")
|
||||
|
||||
def evaluate(
|
||||
self,
|
||||
email: str,
|
||||
grant_type: str,
|
||||
feedback_content: Optional[dict] = None,
|
||||
) -> CreditEvaluation:
|
||||
"""
|
||||
Evaluate whether to grant free credits.
|
||||
|
||||
Args:
|
||||
email: User's email
|
||||
grant_type: "welcome" or "feedback"
|
||||
feedback_content: Feedback form data (for feedback grants only)
|
||||
|
||||
Returns:
|
||||
CreditEvaluation with decision, reasoning, confidence.
|
||||
Fail-closed: returns "pending_review" on any error (admin notified).
|
||||
"""
|
||||
if not self.settings.credit_eval_enabled:
|
||||
return CreditEvaluation(
|
||||
decision="grant",
|
||||
reasoning="Credit evaluation disabled — auto-granting",
|
||||
confidence=1.0,
|
||||
)
|
||||
|
||||
try:
|
||||
# Collect signals
|
||||
signals = self._collect_signals(email)
|
||||
|
||||
# Quick-grant: if no correlations found at all, skip AI call
|
||||
if (
|
||||
not signals["fingerprint_matches"]
|
||||
and not signals["ip_matches"]
|
||||
and signals["recent_signups_ip"] <= 1
|
||||
and signals["recent_signups_fp"] <= 1
|
||||
):
|
||||
evaluation = CreditEvaluation(
|
||||
decision="grant",
|
||||
reasoning="No suspicious correlations found — clean user",
|
||||
confidence=1.0,
|
||||
signals=signals,
|
||||
)
|
||||
self._log_evaluation(email, grant_type, evaluation, signals)
|
||||
return evaluation
|
||||
|
||||
# Build prompt and call Gemini
|
||||
prompt = _build_user_prompt(
|
||||
email=email,
|
||||
grant_type=grant_type,
|
||||
user_data=signals["user_data"],
|
||||
fingerprint_matches=signals["fingerprint_matches"],
|
||||
ip_matches=signals["ip_matches"],
|
||||
ip_geo=signals["ip_geo"],
|
||||
recent_signups_ip=signals["recent_signups_ip"],
|
||||
recent_signups_fp=signals["recent_signups_fp"],
|
||||
user_agent=signals["user_agent"],
|
||||
feedback_content=feedback_content,
|
||||
)
|
||||
|
||||
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(
|
||||
f"Credit evaluation for {email} ({grant_type}): "
|
||||
f"{evaluation.decision} (confidence={evaluation.confidence:.2f})"
|
||||
)
|
||||
return evaluation
|
||||
|
||||
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, collected_signals or {})
|
||||
except Exception:
|
||||
pass
|
||||
return evaluation
|
||||
|
||||
|
||||
_service_instance: Optional[CreditEvaluationService] = None
|
||||
|
||||
|
||||
def get_credit_evaluation_service() -> CreditEvaluationService:
|
||||
"""Get or create the singleton credit evaluation service."""
|
||||
global _service_instance
|
||||
if _service_instance is None:
|
||||
_service_instance = CreditEvaluationService()
|
||||
return _service_instance
|
||||
@@ -1416,6 +1416,315 @@ Open Job: {app_url}
|
||||
)
|
||||
|
||||
|
||||
def send_feedback_notification(
|
||||
self,
|
||||
user_email: str,
|
||||
overall_rating: int,
|
||||
ease_of_use_rating: int,
|
||||
lyrics_accuracy_rating: int,
|
||||
correction_experience_rating: int,
|
||||
what_went_well: Optional[str] = None,
|
||||
what_could_improve: Optional[str] = None,
|
||||
additional_comments: Optional[str] = None,
|
||||
would_recommend: bool = True,
|
||||
would_use_again: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
Send admin notification when a user submits product feedback.
|
||||
|
||||
Args:
|
||||
user_email: Email of the user who submitted feedback
|
||||
overall_rating: 1-5 star rating
|
||||
ease_of_use_rating: 1-5 star rating
|
||||
lyrics_accuracy_rating: 1-5 star rating
|
||||
correction_experience_rating: 1-5 star rating
|
||||
what_went_well: Optional text feedback
|
||||
what_could_improve: Optional text feedback
|
||||
additional_comments: Optional text feedback
|
||||
would_recommend: Whether user would recommend
|
||||
would_use_again: Whether user would use again
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
admin_email = os.getenv("ADMIN_NOTIFICATION_EMAIL", "admin@nomadkaraoke.com")
|
||||
subject = f"New Feedback from {user_email} — {overall_rating}/5 overall"
|
||||
|
||||
def stars(rating: int) -> str:
|
||||
return "★" * rating + "☆" * (5 - rating)
|
||||
|
||||
def text_block(label: str, value: Optional[str]) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
escaped = html.escape(value).replace("\n", "<br>")
|
||||
return f"""
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold; vertical-align: top; white-space: nowrap;">{label}</td>
|
||||
<td style="padding: 8px 12px;">{escaped}</td>
|
||||
</tr>"""
|
||||
|
||||
recommend_badge = "Yes ✓" if would_recommend else "No ✗"
|
||||
use_again_badge = "Yes ✓" if would_use_again else "No ✗"
|
||||
|
||||
admin_url = f"{self.frontend_url}/admin/feedback"
|
||||
|
||||
extra_styles = """
|
||||
.feedback-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.feedback-table td {
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
.stars {
|
||||
color: #eab308;
|
||||
font-size: 18px;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>New product feedback submitted by <strong>{html.escape(user_email)}</strong>:</p>
|
||||
|
||||
<table class="feedback-table">
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Overall</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(overall_rating)}</span> ({overall_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Ease of Use</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(ease_of_use_rating)}</span> ({ease_of_use_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Lyrics Accuracy</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(lyrics_accuracy_rating)}</span> ({lyrics_accuracy_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Correction Experience</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(correction_experience_rating)}</span> ({correction_experience_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Would Recommend</td>
|
||||
<td style="padding: 8px 12px;">{recommend_badge}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Would Use Again</td>
|
||||
<td style="padding: 8px 12px;">{use_again_badge}</td>
|
||||
</tr>
|
||||
{text_block("What went well", what_went_well)}
|
||||
{text_block("What could improve", what_could_improve)}
|
||||
{text_block("Additional comments", additional_comments)}
|
||||
</table>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{admin_url}" class="button">View All Feedback</a>
|
||||
</p>
|
||||
"""
|
||||
|
||||
text_content = f"""New Feedback from {user_email}
|
||||
|
||||
Overall: {overall_rating}/5
|
||||
Ease of Use: {ease_of_use_rating}/5
|
||||
Lyrics Accuracy: {lyrics_accuracy_rating}/5
|
||||
Correction Experience: {correction_experience_rating}/5
|
||||
Would Recommend: {recommend_badge}
|
||||
Would Use Again: {use_again_badge}
|
||||
|
||||
What went well: {what_went_well or '(empty)'}
|
||||
What could improve: {what_could_improve or '(empty)'}
|
||||
Additional comments: {additional_comments or '(empty)'}
|
||||
|
||||
View all feedback: {admin_url}
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=admin_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
|
||||
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 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>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{admin_user_url}" class="button">Review User</a>
|
||||
</p>
|
||||
|
||||
<p style="color: #999; font-size: 14px;">
|
||||
If the user looks legitimate, grant them credits from their admin page.
|
||||
If not, no action needed — they already have 0 credits.
|
||||
</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.
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email="andrew@beveridge.uk",
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_credit_denied_email(self, email: str, grant_type: str = "welcome") -> bool:
|
||||
"""
|
||||
Send a friendly-but-firm email when free credits are denied due to abuse signals.
|
||||
|
||||
CC'd to andrew@beveridge.uk so he can intervene if it's a false positive.
|
||||
The tone invites the user to reply if it's a mistake.
|
||||
"""
|
||||
subject = "About your Nomad Karaoke free credits"
|
||||
|
||||
credit_type = "welcome credits" if grant_type == "welcome" else "feedback bonus credits"
|
||||
|
||||
content = f"""
|
||||
<p>Hi there,</p>
|
||||
|
||||
<p>Thanks for signing up for Nomad Karaoke!</p>
|
||||
|
||||
<p>Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected
|
||||
patterns that suggest this may not be your first account with us, and each karaoke generation job
|
||||
costs us real money in cloud computing and API fees.</p>
|
||||
|
||||
<p>We totally understand if this is a mistake! If you're a genuine new user, please just
|
||||
<strong>reply to this email</strong> and let Andrew (the founder) know. He built this service and is
|
||||
happy to grant you some free credits to try it out — he just asks that you provide honest feedback
|
||||
on the experience in return.</p>
|
||||
|
||||
<p>If you'd like to get started right away, you can also purchase credits:</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.buy_url}" class="button">Buy Credits</a>
|
||||
</p>
|
||||
|
||||
<p style="color: #999; font-size: 14px;">We keep costs low so we can offer the service affordably,
|
||||
which means we need to be careful about free credit abuse. Thanks for understanding!</p>
|
||||
|
||||
{self._get_email_signature()}
|
||||
"""
|
||||
|
||||
text_content = f"""Hi there,
|
||||
|
||||
Thanks for signing up for Nomad Karaoke!
|
||||
|
||||
Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected patterns that suggest this may not be your first account with us, and each karaoke generation job costs us real money in cloud computing and API fees.
|
||||
|
||||
We totally understand if this is a mistake! If you're a genuine new user, please just reply to this email and let Andrew (the founder) know. He built this service and is happy to grant you some free credits to try it out - he just asks that you provide honest feedback on the experience in return.
|
||||
|
||||
If you'd like to get started right away, you can also purchase credits:
|
||||
{self.buy_url}
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
cc_emails=["andrew@beveridge.uk"],
|
||||
)
|
||||
|
||||
|
||||
# Global instance
|
||||
_email_service = None
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
@@ -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."""
|
||||
@@ -370,31 +370,104 @@ class UserService:
|
||||
logger.exception("Error verifying magic link")
|
||||
return False, None, "An error occurred during verification"
|
||||
|
||||
def grant_welcome_credits_if_eligible(self, email: str) -> bool:
|
||||
def grant_welcome_credits_if_eligible(
|
||||
self,
|
||||
email: str,
|
||||
precomputed_eval: Optional[dict] = None,
|
||||
) -> Tuple[bool, str]:
|
||||
"""
|
||||
Grant welcome credits on first magic link verification.
|
||||
|
||||
Uses AI evaluation to check for abuse before granting. Fail-open:
|
||||
if evaluation fails, credits are granted anyway.
|
||||
|
||||
Uses a dedicated welcome_credits_granted flag as primary idempotency
|
||||
check (survives credit_transactions list trimming). Falls back to
|
||||
checking for welcome_credit transaction as secondary defense.
|
||||
|
||||
Args:
|
||||
email: User's email address.
|
||||
precomputed_eval: Optional pre-computed evaluation from magic link doc.
|
||||
Keys: credit_eval_decision, credit_eval_reasoning, credit_eval_error.
|
||||
If provided and has a decision, skips the AI call.
|
||||
|
||||
Returns:
|
||||
True if credits were granted, False if already received or user not found.
|
||||
Tuple of (credits_granted: bool, status: str).
|
||||
status is one of: "granted", "denied", "already_granted", "not_found", "error"
|
||||
"""
|
||||
try:
|
||||
email = email.lower()
|
||||
user = self.get_user(email)
|
||||
if not user:
|
||||
return False
|
||||
return False, "not_found"
|
||||
|
||||
# Primary check: dedicated flag (survives transaction list trimming)
|
||||
if user.welcome_credits_granted:
|
||||
return False
|
||||
return False, "already_granted"
|
||||
|
||||
# Secondary check: look for existing welcome_credit transaction
|
||||
for txn in user.credit_transactions:
|
||||
if txn.reason == "welcome_credit":
|
||||
return False # Already received
|
||||
return False, "already_granted"
|
||||
|
||||
# AI evaluation: check for abuse signals before granting
|
||||
# Use pre-computed result from magic link if available
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import (
|
||||
get_credit_evaluation_service,
|
||||
CreditEvaluation,
|
||||
)
|
||||
precomputed_decision = (precomputed_eval or {}).get("credit_eval_decision")
|
||||
if precomputed_decision:
|
||||
logger.info(f"Using pre-computed credit eval for {email}: {precomputed_decision}")
|
||||
evaluation = CreditEvaluation(
|
||||
decision=precomputed_decision,
|
||||
reasoning=(precomputed_eval or {}).get("credit_eval_reasoning", ""),
|
||||
confidence=1.0,
|
||||
error=(precomputed_eval or {}).get("credit_eval_error"),
|
||||
)
|
||||
else:
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
|
||||
if evaluation.decision == "deny":
|
||||
# Mark as evaluated but not granted so we don't re-evaluate
|
||||
self.update_user(email, welcome_credits_granted=True)
|
||||
logger.info(
|
||||
f"Denied welcome credits to {email}: {evaluation.reasoning}"
|
||||
)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_denied_email(email, "welcome")
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send credit denied email to {email}")
|
||||
return False, "denied"
|
||||
|
||||
if evaluation.decision == "pending_review":
|
||||
# Don't mark welcome_credits_granted — allow retry after manual review
|
||||
logger.info(
|
||||
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
|
||||
)
|
||||
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, signals=evaluation.signals,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send review needed email for {email}")
|
||||
return False, "pending_review"
|
||||
except Exception:
|
||||
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
|
||||
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}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, "pending_review"
|
||||
|
||||
# Grant welcome credits
|
||||
welcome_credit = self.NEW_USER_FREE_CREDITS
|
||||
@@ -416,11 +489,11 @@ class UserService:
|
||||
)
|
||||
|
||||
logger.info(f"Granted {welcome_credit} welcome credits to {email}")
|
||||
return True
|
||||
return True, "granted"
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error granting welcome credits to {email}")
|
||||
return False
|
||||
return False, "error"
|
||||
|
||||
# =========================================================================
|
||||
# Anti-Abuse Rate Limiting
|
||||
@@ -556,6 +629,8 @@ class UserService:
|
||||
min_jobs: Minimum total_jobs_created to flag (default: 2)
|
||||
max_spend: Maximum total_spent in cents to include (default: 0 = free only)
|
||||
"""
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
@@ -566,7 +641,7 @@ class UserService:
|
||||
users = []
|
||||
for doc in query.stream():
|
||||
user = User(**doc.to_dict())
|
||||
if user.total_spent <= max_spend:
|
||||
if user.total_spent <= max_spend and not is_internal_or_test_email(user.email):
|
||||
users.append(user)
|
||||
return users
|
||||
except Exception:
|
||||
@@ -602,6 +677,93 @@ class UserService:
|
||||
"by_fingerprint": by_fingerprint,
|
||||
}
|
||||
|
||||
def find_account_correlations(self) -> dict:
|
||||
"""
|
||||
Find clusters of accounts sharing the same fingerprint or signup IP.
|
||||
|
||||
Returns groups of 2+ accounts that share the same identifier,
|
||||
sorted by group size (largest first). Excludes internal/test accounts.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
|
||||
# Known bad IPs (load balancer, metadata, placeholder) that don't represent real client IPs
|
||||
BAD_IPS = {"169.254.169.126", "unknown", ""}
|
||||
|
||||
try:
|
||||
all_users = []
|
||||
for doc in self.db.collection(USERS_COLLECTION).stream():
|
||||
user = User(**doc.to_dict())
|
||||
if not is_internal_or_test_email(user.email):
|
||||
all_users.append(user)
|
||||
|
||||
# Group by fingerprint
|
||||
fp_groups: dict[str, list[User]] = defaultdict(list)
|
||||
for user in all_users:
|
||||
if user.device_fingerprint:
|
||||
fp_groups[user.device_fingerprint].append(user)
|
||||
|
||||
# Group by IP (exclude known bad IPs)
|
||||
ip_groups: dict[str, list[User]] = defaultdict(list)
|
||||
for user in all_users:
|
||||
if user.signup_ip and user.signup_ip not in BAD_IPS:
|
||||
ip_groups[user.signup_ip].append(user)
|
||||
|
||||
# Collect user agents from latest sessions for users in clusters
|
||||
cluster_emails = set()
|
||||
for fp, users in fp_groups.items():
|
||||
if len(users) >= 2:
|
||||
cluster_emails.update(u.email for u in users)
|
||||
for ip, users in ip_groups.items():
|
||||
if len(users) >= 2:
|
||||
cluster_emails.update(u.email for u in users)
|
||||
|
||||
user_agents: dict[str, str] = {}
|
||||
for email in cluster_emails:
|
||||
try:
|
||||
sessions = (
|
||||
self.db.collection(SESSIONS_COLLECTION)
|
||||
.where(filter=FieldFilter("user_email", "==", email))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(1)
|
||||
.stream()
|
||||
)
|
||||
for session_doc in sessions:
|
||||
session_data = session_doc.to_dict()
|
||||
ua = session_data.get("user_agent")
|
||||
if ua:
|
||||
user_agents[email] = ua
|
||||
except Exception:
|
||||
pass # Skip if session lookup fails
|
||||
|
||||
# Build response - only clusters with 2+ users
|
||||
fingerprint_clusters = []
|
||||
for fp, users in fp_groups.items():
|
||||
if len(users) >= 2:
|
||||
fingerprint_clusters.append({
|
||||
"fingerprint": fp,
|
||||
"users": sorted(users, key=lambda u: u.created_at or "", reverse=True),
|
||||
})
|
||||
fingerprint_clusters.sort(key=lambda c: len(c["users"]), reverse=True)
|
||||
|
||||
ip_clusters = []
|
||||
for ip, users in ip_groups.items():
|
||||
if len(users) >= 2:
|
||||
ip_clusters.append({
|
||||
"ip": ip,
|
||||
"users": sorted(users, key=lambda u: u.created_at or "", reverse=True),
|
||||
})
|
||||
ip_clusters.sort(key=lambda c: len(c["users"]), reverse=True)
|
||||
|
||||
return {
|
||||
"fingerprint_clusters": fingerprint_clusters,
|
||||
"ip_clusters": ip_clusters,
|
||||
"user_agents": user_agents,
|
||||
}
|
||||
except Exception:
|
||||
logger.exception("Error finding account correlations")
|
||||
return {"fingerprint_clusters": [], "ip_clusters": [], "user_agents": {}}
|
||||
|
||||
# =========================================================================
|
||||
# Session Management
|
||||
# =========================================================================
|
||||
|
||||
@@ -383,14 +383,13 @@ class WorkerService:
|
||||
"""
|
||||
Trigger audio separation worker.
|
||||
|
||||
Always uses Cloud Run Jobs to avoid instance termination during long-running
|
||||
Modal API calls. The BackgroundTasks approach caused Cloud Run to terminate
|
||||
instances mid-processing when no HTTP requests were active.
|
||||
Uses Cloud Run Jobs with L4 GPU in us-east4 for direct audio separation.
|
||||
"""
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="audio-separation-job",
|
||||
worker_module="audio_worker",
|
||||
location="us-east4", # GPU job runs in us-east4 (L4 quota)
|
||||
)
|
||||
|
||||
async def trigger_lyrics_worker(self, job_id: str) -> bool:
|
||||
@@ -448,6 +447,7 @@ class WorkerService:
|
||||
job_id: str,
|
||||
cloud_run_job_name: str,
|
||||
worker_module: str,
|
||||
location: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Trigger a worker as a Cloud Run Job.
|
||||
@@ -460,6 +460,7 @@ class WorkerService:
|
||||
job_id: Job ID to process
|
||||
cloud_run_job_name: Name of the Cloud Run Job (e.g., "lyrics-transcription-job")
|
||||
worker_module: Worker module name (e.g., "lyrics_worker")
|
||||
location: GCP region for the job (defaults to settings.gcp_region)
|
||||
|
||||
Returns:
|
||||
True if job was triggered successfully, False otherwise
|
||||
@@ -472,7 +473,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger Cloud Run Job")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
location = location or self.settings.gcp_region
|
||||
job_name = f"projects/{project}/locations/{location}/jobs/{cloud_run_job_name}"
|
||||
|
||||
# Create Cloud Run Jobs client
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
"""
|
||||
Unit tests for admin feedback endpoint and feedback email notification.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from datetime import datetime
|
||||
|
||||
from backend.services.email_service import EmailService
|
||||
|
||||
|
||||
class TestAdminFeedbackEndpoint:
|
||||
"""Tests for GET /api/admin/feedback endpoint."""
|
||||
|
||||
def _make_feedback_doc(self, email="user@example.com", overall=4, **kwargs):
|
||||
"""Create a mock Firestore feedback document."""
|
||||
doc = Mock()
|
||||
doc.id = kwargs.get("id", "test-id-1")
|
||||
data = {
|
||||
"id": doc.id,
|
||||
"user_email": email,
|
||||
"created_at": kwargs.get("created_at", datetime(2026, 3, 1, 12, 0, 0)),
|
||||
"overall_rating": overall,
|
||||
"ease_of_use_rating": kwargs.get("ease_of_use", 4),
|
||||
"lyrics_accuracy_rating": kwargs.get("lyrics_accuracy", 3),
|
||||
"correction_experience_rating": kwargs.get("correction_experience", 4),
|
||||
"what_went_well": kwargs.get("what_went_well", "Great app"),
|
||||
"what_could_improve": kwargs.get("what_could_improve", "More songs"),
|
||||
"additional_comments": kwargs.get("additional_comments", None),
|
||||
"would_recommend": kwargs.get("would_recommend", True),
|
||||
"would_use_again": kwargs.get("would_use_again", True),
|
||||
}
|
||||
doc.to_dict.return_value = data
|
||||
return doc
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_returns_items(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that feedback items are returned correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 2
|
||||
assert len(result.items) == 2
|
||||
assert result.has_more is False
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_search_filter(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that search filters by email."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search="alice", exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].user_email == "alice@example.com"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_exclude_test(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that test emails are excluded when exclude_test=True."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("test@inbox.testmail.app", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
# Make is_test_email return True for the test email
|
||||
mock_is_test.side_effect = lambda e: "testmail" in e
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=True,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].user_email == "alice@example.com"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_pagination(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test pagination with offset and limit."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
docs = [
|
||||
self._make_feedback_doc(f"user{i}@example.com", 4, id=f"id-{i}")
|
||||
for i in range(5)
|
||||
]
|
||||
mock_db.collection.return_value.stream.return_value = docs
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=2, offset=2, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 5
|
||||
assert len(result.items) == 2
|
||||
assert result.has_more is True
|
||||
assert result.offset == 2
|
||||
assert result.limit == 2
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_aggregate_stats(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that aggregate rating averages are computed correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("a@x.com", 5, id="id-1", ease_of_use=4, lyrics_accuracy=3, correction_experience=2)
|
||||
doc2 = self._make_feedback_doc("b@x.com", 3, id="id-2", ease_of_use=2, lyrics_accuracy=5, correction_experience=4)
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.avg_overall_rating == 4.0
|
||||
assert result.avg_ease_of_use_rating == 3.0
|
||||
assert result.avg_lyrics_accuracy_rating == 4.0
|
||||
assert result.avg_correction_experience_rating == 3.0
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_empty(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test empty results."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
|
||||
mock_db.collection.return_value.stream.return_value = []
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 0
|
||||
assert len(result.items) == 0
|
||||
assert result.avg_overall_rating is None
|
||||
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_handles_string_created_at(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that string timestamps (not datetime objects) are handled correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at="2026-03-01T12:00:00")
|
||||
mock_db.collection.return_value.stream.return_value = [doc]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.items[0].created_at == "2026-03-01T12:00:00"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_handles_none_created_at(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that None created_at is handled correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at=None)
|
||||
mock_db.collection.return_value.stream.return_value = [doc]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.items[0].created_at is None
|
||||
|
||||
|
||||
class TestSubmitFeedbackEmailIntegration:
|
||||
"""Test that submit_user_feedback correctly calls send_feedback_notification."""
|
||||
|
||||
@patch("backend.services.email_service.get_email_service")
|
||||
@patch("backend.services.auth_service.get_auth_service")
|
||||
def test_submit_feedback_sends_admin_notification(self, mock_get_auth, mock_get_email):
|
||||
"""Verify the caller (submit_user_feedback) passes correct args to email service."""
|
||||
import asyncio
|
||||
import uuid as uuid_mod
|
||||
from backend.api.routes.users import submit_user_feedback
|
||||
from backend.models.user import UserFeedbackRequest
|
||||
|
||||
# Mock auth
|
||||
mock_auth_svc = Mock()
|
||||
mock_auth_result = Mock()
|
||||
mock_auth_result.is_valid = True
|
||||
mock_auth_result.user_email = "alice@example.com"
|
||||
mock_auth_svc.validate_token_full.return_value = mock_auth_result
|
||||
mock_get_auth.return_value = mock_auth_svc
|
||||
|
||||
# Mock email service
|
||||
mock_email_svc = Mock()
|
||||
mock_email_svc.send_feedback_notification.return_value = True
|
||||
mock_get_email.return_value = mock_email_svc
|
||||
|
||||
# Mock user service with a db that has a collection mock
|
||||
mock_user_svc = Mock()
|
||||
mock_user = Mock()
|
||||
mock_user.email = "alice@example.com"
|
||||
mock_user.total_jobs_completed = 5
|
||||
mock_user.has_submitted_feedback = False
|
||||
mock_user_svc.get_or_create_user.return_value = mock_user
|
||||
mock_user_svc.update_user.return_value = None
|
||||
mock_user_svc.add_credits.return_value = None
|
||||
|
||||
went_well = "The lyrics synchronization was incredibly accurate and impressive overall"
|
||||
could_improve = "Speed could be faster for longer songs in the processing queue"
|
||||
|
||||
request = UserFeedbackRequest(
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=3,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=2,
|
||||
what_went_well=went_well,
|
||||
what_could_improve=could_improve,
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=False,
|
||||
)
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# Verify email notification was called with matching args
|
||||
mock_email_svc.send_feedback_notification.assert_called_once_with(
|
||||
user_email="alice@example.com",
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=3,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=2,
|
||||
what_went_well=went_well,
|
||||
what_could_improve=could_improve,
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=False,
|
||||
)
|
||||
|
||||
assert result.credits_granted == 1
|
||||
|
||||
@patch("backend.services.email_service.get_email_service")
|
||||
@patch("backend.services.auth_service.get_auth_service")
|
||||
def test_submit_feedback_continues_on_email_failure(self, mock_get_auth, mock_get_email):
|
||||
"""Verify feedback submission succeeds even if email notification fails."""
|
||||
import asyncio
|
||||
import uuid as uuid_mod
|
||||
from backend.api.routes.users import submit_user_feedback
|
||||
from backend.models.user import UserFeedbackRequest
|
||||
|
||||
mock_auth_svc = Mock()
|
||||
mock_auth_result = Mock()
|
||||
mock_auth_result.is_valid = True
|
||||
mock_auth_result.user_email = "bob@example.com"
|
||||
mock_auth_svc.validate_token_full.return_value = mock_auth_result
|
||||
mock_get_auth.return_value = mock_auth_svc
|
||||
|
||||
# Email service throws an exception
|
||||
mock_email_svc = Mock()
|
||||
mock_email_svc.send_feedback_notification.side_effect = Exception("SendGrid down")
|
||||
mock_get_email.return_value = mock_email_svc
|
||||
|
||||
mock_user_svc = Mock()
|
||||
mock_user = Mock()
|
||||
mock_user.email = "bob@example.com"
|
||||
mock_user.total_jobs_completed = 3
|
||||
mock_user.has_submitted_feedback = False
|
||||
mock_user_svc.get_or_create_user.return_value = mock_user
|
||||
|
||||
request = UserFeedbackRequest(
|
||||
overall_rating=5,
|
||||
ease_of_use_rating=5,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=5,
|
||||
what_went_well="Everything was perfect and I really enjoyed the experience a lot",
|
||||
)
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# User still gets credits even though email failed
|
||||
assert result.status == "success"
|
||||
assert result.credits_granted == 1
|
||||
|
||||
|
||||
class TestFeedbackEmailNotification:
|
||||
"""Tests for send_feedback_notification email method."""
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_calls_provider(self, mock_get_provider):
|
||||
"""Test that feedback notification sends email via provider."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
result = service.send_feedback_notification(
|
||||
user_email="alice@example.com",
|
||||
overall_rating=5,
|
||||
ease_of_use_rating=4,
|
||||
lyrics_accuracy_rating=3,
|
||||
correction_experience_rating=4,
|
||||
what_went_well="Great lyrics sync",
|
||||
what_could_improve="More song variety",
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=True,
|
||||
)
|
||||
|
||||
assert result is True
|
||||
mock_provider.send_email.assert_called_once()
|
||||
call_args = mock_provider.send_email.call_args
|
||||
|
||||
# Check email is sent to admin
|
||||
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
|
||||
assert to_email == "admin@nomadkaraoke.com"
|
||||
|
||||
# Check subject contains user email and rating
|
||||
subject = call_args.kwargs.get("subject") or call_args[0][1]
|
||||
assert "alice@example.com" in subject
|
||||
assert "5/5" in subject
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_content(self, mock_get_provider):
|
||||
"""Test that feedback notification email contains all feedback fields."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
service.send_feedback_notification(
|
||||
user_email="bob@example.com",
|
||||
overall_rating=3,
|
||||
ease_of_use_rating=2,
|
||||
lyrics_accuracy_rating=4,
|
||||
correction_experience_rating=5,
|
||||
what_went_well="Easy to use",
|
||||
what_could_improve="Better mobile support",
|
||||
additional_comments="Love it overall",
|
||||
would_recommend=False,
|
||||
would_use_again=True,
|
||||
)
|
||||
|
||||
call_args = mock_provider.send_email.call_args
|
||||
html_content = call_args.kwargs.get("html_content") or call_args[0][2]
|
||||
text_content = call_args.kwargs.get("text_content") or call_args[0][3]
|
||||
|
||||
# Check HTML contains feedback text
|
||||
assert "Easy to use" in html_content
|
||||
assert "Better mobile support" in html_content
|
||||
assert "Love it overall" in html_content
|
||||
assert "bob@example.com" in html_content
|
||||
|
||||
# Check plain text also contains feedback
|
||||
assert "Easy to use" in text_content
|
||||
assert "Better mobile support" in text_content
|
||||
assert "3/5" in text_content
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
@patch.dict("os.environ", {"ADMIN_NOTIFICATION_EMAIL": "custom@admin.com"})
|
||||
def test_send_feedback_notification_custom_admin_email(self, mock_get_provider):
|
||||
"""Test that admin email can be configured via env var."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
service.send_feedback_notification(
|
||||
user_email="test@example.com",
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=4,
|
||||
lyrics_accuracy_rating=4,
|
||||
correction_experience_rating=4,
|
||||
)
|
||||
|
||||
call_args = mock_provider.send_email.call_args
|
||||
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
|
||||
assert to_email == "custom@admin.com"
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_returns_false_on_failure(self, mock_get_provider):
|
||||
"""Test that failure is returned when provider fails."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = False
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
result = service.send_feedback_notification(
|
||||
user_email="test@example.com",
|
||||
overall_rating=1,
|
||||
ease_of_use_rating=1,
|
||||
lyrics_accuracy_rating=1,
|
||||
correction_experience_rating=1,
|
||||
)
|
||||
|
||||
assert result is False
|
||||
@@ -118,15 +118,48 @@ class TestGrantWelcomeCredits:
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.grant_welcome_credits_if_eligible("new@example.com")
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
|
||||
from backend.services.credit_evaluation_service import CreditEvaluation
|
||||
mock_eval.return_value.evaluate.return_value = CreditEvaluation(decision="grant", reasoning="OK", confidence=1.0)
|
||||
granted, status = service.grant_welcome_credits_if_eligible("new@example.com")
|
||||
|
||||
assert result is True
|
||||
assert granted is True
|
||||
# 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')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_uses_precomputed_eval_when_provided(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible uses pre-computed eval and skips AI call."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="new@example.com", credits=0, credit_transactions=[])
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
|
||||
granted, status = service.grant_welcome_credits_if_eligible(
|
||||
"new@example.com",
|
||||
precomputed_eval={
|
||||
"credit_eval_decision": "grant",
|
||||
"credit_eval_reasoning": "Pre-computed: clean user",
|
||||
},
|
||||
)
|
||||
# AI evaluation should NOT have been called
|
||||
mock_eval.return_value.evaluate.assert_not_called()
|
||||
|
||||
assert granted is True
|
||||
assert status == "granted"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_if_flag_already_set(self, mock_fs, mock_settings):
|
||||
@@ -148,9 +181,9 @@ class TestGrantWelcomeCredits:
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.grant_welcome_credits_if_eligible("existing@example.com")
|
||||
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
|
||||
|
||||
assert result is False
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
@@ -180,9 +213,9 @@ class TestGrantWelcomeCredits:
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.grant_welcome_credits_if_eligible("existing@example.com")
|
||||
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
|
||||
|
||||
assert result is False
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
@@ -199,9 +232,9 @@ class TestGrantWelcomeCredits:
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.grant_welcome_credits_if_eligible("ghost@example.com")
|
||||
granted, status = service.grant_welcome_credits_if_eligible("ghost@example.com")
|
||||
|
||||
assert result is False
|
||||
assert granted is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -376,7 +409,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
|
||||
|
||||
|
||||
@@ -524,10 +557,10 @@ class TestVerifyGrantsCredits:
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
mock_user_svc.verify_magic_link.return_value = (True, user, "Success")
|
||||
mock_user_svc.grant_welcome_credits_if_eligible.return_value = credits_eligible
|
||||
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()
|
||||
@@ -556,12 +589,55 @@ 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
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_passes_precomputed_eval(self, mock_user_svc):
|
||||
"""Verify endpoint passes pre-computed eval from magic link doc."""
|
||||
user = User(email="new@example.com", credits=2, email_verified=True)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
|
||||
|
||||
# Add pre-computed eval to the magic link doc
|
||||
mock_ml_doc = mock_user_svc.db.collection.return_value.document.return_value.get.return_value
|
||||
mock_ml_doc.to_dict.return_value = {
|
||||
'email': user.email,
|
||||
'tenant_id': None,
|
||||
'credit_eval_decision': 'grant',
|
||||
'credit_eval_reasoning': 'Clean user',
|
||||
}
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
# Verify precomputed_eval was passed through
|
||||
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
|
||||
assert call_kwargs[1]['precomputed_eval'] == {
|
||||
'credit_eval_decision': 'grant',
|
||||
'credit_eval_reasoning': 'Clean user',
|
||||
}
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_falls_back_without_precomputed_eval(self, mock_user_svc):
|
||||
"""Verify endpoint passes None when no pre-computed eval exists."""
|
||||
user = User(email="new@example.com", credits=2, email_verified=True)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
|
||||
assert call_kwargs[1]['precomputed_eval'] is None
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_returns_zero_credits_for_returning_user(self, mock_user_svc):
|
||||
"""Returning user gets credits_granted=0."""
|
||||
user = User(
|
||||
@@ -652,8 +728,8 @@ class TestErrorPaths:
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.grant_welcome_credits_if_eligible("test@example.com")
|
||||
assert result is False
|
||||
granted, status = service.grant_welcome_credits_if_eligible("test@example.com")
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
|
||||
@@ -65,6 +65,40 @@ class TestJobCreationIp:
|
||||
assert job.creation_ip is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Internal/Test Email Filtering
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestInternalOrTestEmail:
|
||||
"""Tests for is_internal_or_test_email utility."""
|
||||
|
||||
def test_nomadkaraoke_is_internal(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("admin@nomadkaraoke.com") is True
|
||||
|
||||
def test_beveridge_is_internal(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("vocalstar@beveridge.uk") is True
|
||||
|
||||
def test_testmail_is_test(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("test123@inbox.testmail.app") is True
|
||||
|
||||
def test_regular_email_is_not_internal(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("user@gmail.com") is False
|
||||
|
||||
def test_empty_email(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("") is False
|
||||
|
||||
def test_is_internal_email_only(self):
|
||||
from backend.utils.test_data import is_internal_email
|
||||
assert is_internal_email("andrew@beveridge.uk") is True
|
||||
assert is_internal_email("user@gmail.com") is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# UserService Investigation Methods
|
||||
# =============================================================================
|
||||
@@ -153,6 +187,33 @@ class TestFindSuspiciousAccounts:
|
||||
assert len(results) == 1
|
||||
assert results[0].email == "free@test.com"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_excludes_internal_and_test_accounts(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
real_user = User(email="abuser@gmail.com", total_jobs_created=5, total_spent=0).model_dump(mode='json')
|
||||
internal_user = User(email="admin@nomadkaraoke.com", total_jobs_created=10, total_spent=0).model_dump(mode='json')
|
||||
test_user = User(email="e2e@inbox.testmail.app", total_jobs_created=8, total_spent=0).model_dump(mode='json')
|
||||
personal_user = User(email="vocalstar@beveridge.uk", total_jobs_created=3, total_spent=0).model_dump(mode='json')
|
||||
|
||||
docs = []
|
||||
for data in [real_user, internal_user, test_user, personal_user]:
|
||||
doc = MagicMock()
|
||||
doc.to_dict.return_value = data
|
||||
docs.append(doc)
|
||||
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_suspicious_accounts(min_jobs=2, max_spend=0)
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].email == "abuser@gmail.com"
|
||||
|
||||
|
||||
class TestFindRelatedAccounts:
|
||||
|
||||
@@ -215,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
|
||||
|
||||
|
||||
@@ -293,3 +354,127 @@ class TestAdminAbuseEndpoints:
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/related/ghost@test.com")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_correlations_endpoint(self, admin_client, mock_user_svc):
|
||||
user_a = User(email="a@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=2)
|
||||
user_b = User(email="b@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3)
|
||||
|
||||
mock_user_svc.find_account_correlations.return_value = {
|
||||
"fingerprint_clusters": [
|
||||
{"fingerprint": "fp123", "users": [user_a, user_b]},
|
||||
],
|
||||
"ip_clusters": [
|
||||
{"ip": "1.2.3.4", "users": [user_a, user_b]},
|
||||
],
|
||||
"user_agents": {"a@test.com": "Mozilla/5.0", "b@test.com": "Mozilla/5.0"},
|
||||
}
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/correlations")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["fingerprint_clusters"]) == 1
|
||||
assert data["fingerprint_clusters"][0]["fingerprint"] == "fp123"
|
||||
assert data["fingerprint_clusters"][0]["count"] == 2
|
||||
assert data["fingerprint_clusters"][0]["users"][0]["user_agent"] == "Mozilla/5.0"
|
||||
assert len(data["ip_clusters"]) == 1
|
||||
assert data["ip_clusters"][0]["ip"] == "1.2.3.4"
|
||||
assert data["ip_clusters"][0]["count"] == 2
|
||||
|
||||
def test_correlations_endpoint_empty(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_account_correlations.return_value = {
|
||||
"fingerprint_clusters": [],
|
||||
"ip_clusters": [],
|
||||
"user_agents": {},
|
||||
}
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/correlations")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["fingerprint_clusters"] == []
|
||||
assert data["ip_clusters"] == []
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Correlations Service Method Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestFindAccountCorrelations:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_groups_by_fingerprint_and_ip(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user_a = User(email="a@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=2).model_dump(mode='json')
|
||||
user_b = User(email="b@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3).model_dump(mode='json')
|
||||
user_c = User(email="c@gmail.com", signup_ip="5.6.7.8", device_fingerprint="fp999", total_jobs_created=1).model_dump(mode='json')
|
||||
|
||||
docs = []
|
||||
for data in [user_a, user_b, user_c]:
|
||||
doc = MagicMock()
|
||||
doc.to_dict.return_value = data
|
||||
docs.append(doc)
|
||||
|
||||
# Mock the users collection stream
|
||||
mock_db.collection.return_value.stream.return_value = docs
|
||||
|
||||
# Mock session lookups (return empty for simplicity)
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.find_account_correlations()
|
||||
|
||||
# a and b share fp123 → 1 fingerprint cluster
|
||||
assert len(result["fingerprint_clusters"]) == 1
|
||||
assert result["fingerprint_clusters"][0]["fingerprint"] == "fp123"
|
||||
assert len(result["fingerprint_clusters"][0]["users"]) == 2
|
||||
|
||||
# a and b share IP 1.2.3.4 → 1 IP cluster
|
||||
assert len(result["ip_clusters"]) == 1
|
||||
assert result["ip_clusters"][0]["ip"] == "1.2.3.4"
|
||||
assert len(result["ip_clusters"][0]["users"]) == 2
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_excludes_internal_accounts(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
real_user = User(email="user@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123").model_dump(mode='json')
|
||||
internal_user = User(email="admin@nomadkaraoke.com", signup_ip="1.2.3.4", device_fingerprint="fp123").model_dump(mode='json')
|
||||
|
||||
docs = []
|
||||
for data in [real_user, internal_user]:
|
||||
doc = MagicMock()
|
||||
doc.to_dict.return_value = data
|
||||
docs.append(doc)
|
||||
|
||||
mock_db.collection.return_value.stream.return_value = docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.find_account_correlations()
|
||||
|
||||
# Only 1 non-internal user with fp123, so no cluster (need 2+)
|
||||
assert len(result["fingerprint_clusters"]) == 0
|
||||
assert len(result["ip_clusters"]) == 0
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_returns_empty_on_error(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
mock_db.collection.return_value.stream.side_effect = Exception("Firestore down")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.find_account_correlations()
|
||||
|
||||
assert result["fingerprint_clusters"] == []
|
||||
assert result["ip_clusters"] == []
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
"""
|
||||
Tests for AI-powered credit evaluation service.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch, PropertyMock
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
from backend.models.user import User
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Prompt Building Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestBuildUserPrompt:
|
||||
|
||||
def test_builds_prompt_with_all_signals(self):
|
||||
from backend.services.credit_evaluation_service import _build_user_prompt
|
||||
|
||||
prompt = _build_user_prompt(
|
||||
email="test@example.com",
|
||||
grant_type="welcome",
|
||||
user_data={
|
||||
"device_fingerprint": "fp123",
|
||||
"signup_ip": "1.2.3.4",
|
||||
"credits": 0,
|
||||
"total_jobs_created": 0,
|
||||
"total_jobs_completed": 0,
|
||||
"total_spent": 0,
|
||||
"created_at": "2026-03-23",
|
||||
},
|
||||
fingerprint_matches=[
|
||||
{"email": "other@test.com", "total_jobs_created": 5, "total_spent": 0, "created_at": "2026-03-20"},
|
||||
],
|
||||
ip_matches=[],
|
||||
ip_geo={"status": "success", "country": "US", "country_code": "US", "city": "Portland", "region": "OR", "isp": "Comcast", "org": "Comcast", "as_number": "AS7922", "as_name": "Comcast"},
|
||||
recent_signups_ip=1,
|
||||
recent_signups_fp=2,
|
||||
user_agent="Mozilla/5.0",
|
||||
)
|
||||
|
||||
assert "test@example.com" in prompt
|
||||
assert "fp123" in prompt
|
||||
assert "1.2.3.4" in prompt
|
||||
assert "other@test.com" in prompt
|
||||
assert "RED FLAG" in prompt
|
||||
assert "Portland" in prompt
|
||||
assert "Comcast" in prompt
|
||||
assert "Mozilla/5.0" in prompt
|
||||
|
||||
def test_builds_prompt_without_correlations(self):
|
||||
from backend.services.credit_evaluation_service import _build_user_prompt
|
||||
|
||||
prompt = _build_user_prompt(
|
||||
email="clean@user.com",
|
||||
grant_type="welcome",
|
||||
user_data={"device_fingerprint": "fp999", "signup_ip": "5.6.7.8"},
|
||||
fingerprint_matches=[],
|
||||
ip_matches=[],
|
||||
ip_geo=None,
|
||||
recent_signups_ip=1,
|
||||
recent_signups_fp=1,
|
||||
user_agent=None,
|
||||
)
|
||||
|
||||
assert "None found" in prompt
|
||||
assert "clean@user.com" in prompt
|
||||
|
||||
def test_includes_feedback_content(self):
|
||||
from backend.services.credit_evaluation_service import _build_user_prompt
|
||||
|
||||
prompt = _build_user_prompt(
|
||||
email="test@example.com",
|
||||
grant_type="feedback",
|
||||
user_data={},
|
||||
fingerprint_matches=[],
|
||||
ip_matches=[],
|
||||
ip_geo=None,
|
||||
recent_signups_ip=0,
|
||||
recent_signups_fp=0,
|
||||
user_agent=None,
|
||||
feedback_content={
|
||||
"overall_rating": 5,
|
||||
"what_went_well": "Great audio quality!",
|
||||
"what_could_improve": "Faster processing",
|
||||
"additional_comments": "Love it",
|
||||
},
|
||||
)
|
||||
|
||||
assert "Feedback Submitted" in prompt
|
||||
assert "Great audio quality!" in prompt
|
||||
assert "5" in prompt
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Response Parsing Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestParseGeminiResponse:
|
||||
|
||||
def test_parses_grant_decision(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response('{"decision": "grant", "reasoning": "Clean user", "confidence": 0.95}')
|
||||
assert result.decision == "grant"
|
||||
assert result.reasoning == "Clean user"
|
||||
assert result.confidence == 0.95
|
||||
assert result.error is None
|
||||
|
||||
def test_parses_deny_decision(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response('{"decision": "deny", "reasoning": "Same fingerprint as 3 other accounts", "confidence": 0.9}')
|
||||
assert result.decision == "deny"
|
||||
assert "fingerprint" in result.reasoning
|
||||
|
||||
def test_handles_markdown_code_fences(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response('```json\n{"decision": "grant", "reasoning": "OK", "confidence": 0.8}\n```')
|
||||
assert result.decision == "grant"
|
||||
|
||||
def test_fails_closed_on_invalid_json(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response("I think this user is fine")
|
||||
assert result.decision == "pending_review"
|
||||
assert result.error is not None
|
||||
|
||||
def test_fails_closed_on_unexpected_decision(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response('{"decision": "maybe", "reasoning": "Unsure", "confidence": 0.5}')
|
||||
assert result.decision == "pending_review" # fail-closed
|
||||
|
||||
def test_fails_closed_on_empty_response(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response("")
|
||||
assert result.decision == "pending_review"
|
||||
assert result.error is not None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Evaluation Service Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreditEvaluationService:
|
||||
|
||||
@patch('backend.services.credit_evaluation_service.get_settings')
|
||||
def test_returns_grant_when_disabled(self, mock_settings):
|
||||
mock_settings.return_value = MagicMock(credit_eval_enabled=False)
|
||||
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
service = CreditEvaluationService()
|
||||
result = service.evaluate("test@example.com", "welcome")
|
||||
|
||||
assert result.decision == "grant"
|
||||
assert "disabled" in result.reasoning
|
||||
|
||||
@patch('backend.services.credit_evaluation_service.get_settings')
|
||||
def test_quick_grants_clean_users(self, mock_settings):
|
||||
mock_settings.return_value = MagicMock(
|
||||
credit_eval_enabled=True,
|
||||
credit_eval_model="gemini-3.1-pro-preview",
|
||||
google_cloud_project="test",
|
||||
)
|
||||
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
service = CreditEvaluationService()
|
||||
|
||||
with patch.object(service, '_collect_signals', return_value={
|
||||
"user_data": {"email": "clean@user.com"},
|
||||
"fingerprint_matches": [],
|
||||
"ip_matches": [],
|
||||
"ip_geo": None,
|
||||
"recent_signups_ip": 1,
|
||||
"recent_signups_fp": 1,
|
||||
"user_agent": "Mozilla/5.0",
|
||||
}), patch.object(service, '_log_evaluation'):
|
||||
result = service.evaluate("clean@user.com", "welcome")
|
||||
|
||||
assert result.decision == "grant"
|
||||
assert "clean" in result.reasoning.lower()
|
||||
|
||||
@patch('backend.services.credit_evaluation_service.get_settings')
|
||||
def test_calls_gemini_when_correlations_found(self, mock_settings):
|
||||
mock_settings.return_value = MagicMock(
|
||||
credit_eval_enabled=True,
|
||||
credit_eval_model="gemini-3.1-pro-preview",
|
||||
google_cloud_project="test",
|
||||
)
|
||||
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
service = CreditEvaluationService()
|
||||
|
||||
with patch.object(service, '_collect_signals', return_value={
|
||||
"user_data": {"email": "sus@user.com", "device_fingerprint": "fp123", "signup_ip": "1.2.3.4"},
|
||||
"fingerprint_matches": [{"email": "other@test.com", "total_jobs_created": 5, "total_spent": 0, "created_at": "2026-03-20"}],
|
||||
"ip_matches": [],
|
||||
"ip_geo": None,
|
||||
"recent_signups_ip": 1,
|
||||
"recent_signups_fp": 2,
|
||||
"user_agent": None,
|
||||
}), patch.object(service, '_call_gemini', return_value='{"decision": "deny", "reasoning": "Same fingerprint", "confidence": 0.9}'), \
|
||||
patch.object(service, '_log_evaluation'):
|
||||
result = service.evaluate("sus@user.com", "welcome")
|
||||
|
||||
assert result.decision == "deny"
|
||||
|
||||
@patch('backend.services.credit_evaluation_service.get_settings')
|
||||
def test_fails_closed_on_gemini_error(self, mock_settings):
|
||||
mock_settings.return_value = MagicMock(
|
||||
credit_eval_enabled=True,
|
||||
credit_eval_model="gemini-3.1-pro-preview",
|
||||
google_cloud_project="test",
|
||||
)
|
||||
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
service = CreditEvaluationService()
|
||||
|
||||
with patch.object(service, '_collect_signals', side_effect=Exception("Firestore down")), \
|
||||
patch.object(service, '_log_evaluation'):
|
||||
result = service.evaluate("test@example.com", "welcome")
|
||||
|
||||
assert result.decision == "pending_review"
|
||||
assert result.error is not None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Welcome Credit Integration Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestWelcomeCreditsWithEvaluation:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_grants_credits_when_evaluation_approves(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="new@user.com", welcome_credits_granted=False)
|
||||
user_doc = MagicMock()
|
||||
user_doc.exists = True
|
||||
user_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
from backend.services.credit_evaluation_service import CreditEvaluation
|
||||
|
||||
service = UserService()
|
||||
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
|
||||
mock_eval.return_value.evaluate.return_value = CreditEvaluation(
|
||||
decision="grant", reasoning="Clean user", confidence=0.95
|
||||
)
|
||||
granted, status = service.grant_welcome_credits_if_eligible("new@user.com")
|
||||
|
||||
assert granted is True
|
||||
assert status == "granted"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_denies_credits_when_evaluation_rejects(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="abuser@test.com", welcome_credits_granted=False)
|
||||
user_doc = MagicMock()
|
||||
user_doc.exists = True
|
||||
user_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
from backend.services.credit_evaluation_service import CreditEvaluation
|
||||
|
||||
service = UserService()
|
||||
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval, \
|
||||
patch('backend.services.email_service.get_email_service') as mock_email:
|
||||
mock_eval.return_value.evaluate.return_value = CreditEvaluation(
|
||||
decision="deny", reasoning="Same fingerprint as 3 accounts", confidence=0.9
|
||||
)
|
||||
granted, status = service.grant_welcome_credits_if_eligible("abuser@test.com")
|
||||
|
||||
assert granted is False
|
||||
assert status == "denied"
|
||||
# Verify rejection email was sent
|
||||
mock_email.return_value.send_credit_denied_email.assert_called_once_with("abuser@test.com", "welcome")
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_pending_review_when_evaluation_fails(self, mock_fs, mock_settings):
|
||||
"""Fail-closed: if evaluation crashes, credits are NOT granted, admin notified."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="new@user.com", welcome_credits_granted=False)
|
||||
user_doc = MagicMock()
|
||||
user_doc.exists = True
|
||||
user_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
|
||||
service = UserService()
|
||||
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval, \
|
||||
patch('backend.services.email_service.get_email_service') as mock_email:
|
||||
mock_eval.return_value.evaluate.side_effect = Exception("Gemini is down")
|
||||
granted, status = service.grant_welcome_credits_if_eligible("new@user.com")
|
||||
|
||||
assert granted is False
|
||||
assert status == "pending_review"
|
||||
# Verify admin review email was sent
|
||||
mock_email.return_value.send_credit_review_needed_email.assert_called_once()
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_already_granted(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="existing@user.com", welcome_credits_granted=True)
|
||||
user_doc = MagicMock()
|
||||
user_doc.exists = True
|
||||
user_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("existing@user.com")
|
||||
|
||||
assert granted is False
|
||||
assert status == "already_granted"
|
||||
@@ -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"
|
||||
@@ -387,3 +387,128 @@ class TestScreensWorkerPrerequisites:
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True}, artist="", title="Test")
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
|
||||
# ==================== GCS URI Passthrough ====================
|
||||
|
||||
class TestGCSURIPassthrough:
|
||||
"""
|
||||
Test that Stage 1 uses gcs_uri when input_gcs_uri is set on the processor.
|
||||
Fixes 413 Request Entity Too Large for large FLAC files.
|
||||
"""
|
||||
|
||||
def test_stage1_uses_gcs_uri_when_set(self):
|
||||
"""When input_gcs_uri is set, Stage 1 passes gcs_uri instead of file_path."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None
|
||||
processor.job_id = "gcs-test-001"
|
||||
processor.input_gcs_uri = "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
for name in ["gcs-test-001_mixed_vocals.flac", "gcs-test-001_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "gcs-test-001_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "gcs-test-001_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "song.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify gcs_uri was passed instead of file_path
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert call_kwargs["gcs_uri"] == "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
|
||||
# Verify file_path was NOT passed as a positional arg
|
||||
call_args = mock_client.separate_audio_and_wait.call_args[0]
|
||||
assert len(call_args) == 0
|
||||
|
||||
def test_stage1_uses_file_upload_when_no_gcs_uri(self):
|
||||
"""When input_gcs_uri is not set, Stage 1 uses file upload as before."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None
|
||||
processor.job_id = "file-test-001"
|
||||
# No input_gcs_uri set
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
for name in ["file-test-001_mixed_vocals.flac", "file-test-001_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "file-test-001_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "file-test-001_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "song.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify file_path was passed as positional arg (old behavior)
|
||||
call_args = mock_client.separate_audio_and_wait.call_args[0]
|
||||
assert call_args[0] == input_file
|
||||
# Verify gcs_uri was NOT in kwargs
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert "gcs_uri" not in call_kwargs
|
||||
@@ -224,7 +224,38 @@ class TestRetryEndpoint:
|
||||
assert has_video and has_instrumental_selection
|
||||
|
||||
def test_retry_checkpoint_detection_render_stage(self):
|
||||
"""Test retry detects render stage checkpoint."""
|
||||
"""Test retry detects render stage checkpoint when review was completed."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
},
|
||||
state_data={
|
||||
'instrumental_selection': 'clean'
|
||||
}
|
||||
)
|
||||
|
||||
# This job has corrections, screens, AND completed review - should retry from render
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
has_review = (job.state_data or {}).get('instrumental_selection')
|
||||
assert has_corrections and has_screens and not has_video and has_review
|
||||
|
||||
def test_retry_checkpoint_returns_to_review_when_not_completed(self):
|
||||
"""Test retry returns to awaiting_review when corrections and screens exist
|
||||
but user never completed the review (no instrumental_selection).
|
||||
|
||||
Regression test: previously, retry would skip to REVIEW_COMPLETE based solely
|
||||
on corrections.json + title.mov existing, but these are auto-generated artifacts
|
||||
that exist BEFORE the user reviews anything.
|
||||
"""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
@@ -236,13 +267,15 @@ class TestRetryEndpoint:
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
}
|
||||
# No state_data.instrumental_selection — review was never completed
|
||||
)
|
||||
|
||||
# This job has corrections and screens - should retry from render
|
||||
# Has corrections and screens but NO review completion
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
assert has_corrections and has_screens and not has_video
|
||||
has_review = (job.state_data or {}).get('instrumental_selection')
|
||||
# Should match the "awaiting_review" checkpoint, NOT "render"
|
||||
assert has_corrections and has_screens and not has_review
|
||||
|
||||
def test_retry_checkpoint_detection_from_beginning(self):
|
||||
"""Test retry detects need to restart from beginning."""
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -179,48 +179,48 @@ class TestLyricsWorker:
|
||||
return storage
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_lyrics_results_requires_job(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results correctly fetches job for artist/title.
|
||||
|
||||
This test would have caught the UnboundLocalError bug where job was used
|
||||
before being defined.
|
||||
async def test_upload_lyrics_results_finds_corrections_by_scan(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results finds corrections JSON by scanning the directory.
|
||||
|
||||
The function scans for files ending in '(Lyrics Corrections).json' rather than
|
||||
reconstructing filenames from job.artist/title, since those may change mid-processing
|
||||
(e.g. admin updates artist name while lyrics worker is running).
|
||||
"""
|
||||
with patch('backend.workers.lyrics_worker.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.workers.lyrics_worker.StorageService', return_value=mock_storage):
|
||||
|
||||
|
||||
from backend.workers.lyrics_worker import upload_lyrics_results
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Create mock lyrics directory and files
|
||||
lyrics_dir = os.path.join(temp_dir, "lyrics")
|
||||
os.makedirs(lyrics_dir)
|
||||
|
||||
# Create test LRC file
|
||||
|
||||
lrc_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Karaoke).lrc")
|
||||
with open(lrc_path, 'w') as f:
|
||||
f.write("[00:00.00]Test lyrics\n")
|
||||
|
||||
# Create corrections JSON
|
||||
corrections_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Lyrics Corrections).json")
|
||||
|
||||
# Use a different artist than what's in the job to simulate mid-run rename
|
||||
corrections_path = os.path.join(lyrics_dir, "OldArtist - Waterloo (Lyrics Corrections).json")
|
||||
with open(corrections_path, 'w') as f:
|
||||
json.dump({"lines": [], "corrections": []}, f)
|
||||
|
||||
|
||||
transcription_result = {
|
||||
"lrc_filepath": lrc_path,
|
||||
"corrections_filepath": corrections_path
|
||||
}
|
||||
|
||||
# This should NOT raise UnboundLocalError
|
||||
|
||||
await upload_lyrics_results(
|
||||
"test123",
|
||||
temp_dir,
|
||||
transcription_result,
|
||||
mock_storage,
|
||||
"test123",
|
||||
temp_dir,
|
||||
transcription_result,
|
||||
mock_storage,
|
||||
mock_job_manager
|
||||
)
|
||||
|
||||
# Verify job was fetched
|
||||
mock_job_manager.get_job.assert_called_with("test123")
|
||||
|
||||
# Verify corrections file was found and uploaded as corrections.json
|
||||
upload_calls = mock_storage.upload_file.call_args_list
|
||||
corrections_uploads = [c for c in upload_calls if 'corrections.json' in str(c)]
|
||||
assert len(corrections_uploads) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_lyrics_results_uploads_lrc_file(self, mock_job_manager, mock_storage, mock_job):
|
||||
@@ -281,53 +281,68 @@ class TestLyricsWorker:
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_lyrics_results_uses_artist_title_from_job(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results correctly uses job.artist and job.title.
|
||||
|
||||
This test specifically validates the bug fix where job was not defined
|
||||
when accessing job.artist and job.title for reference file lookups.
|
||||
"""
|
||||
async def test_upload_lyrics_results_raises_when_no_corrections(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results raises when no corrections file exists at all."""
|
||||
from backend.workers.lyrics_worker import upload_lyrics_results
|
||||
import json
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
lyrics_dir = os.path.join(temp_dir, "lyrics")
|
||||
os.makedirs(lyrics_dir)
|
||||
|
||||
# Create LRC file
|
||||
|
||||
lrc_path = os.path.join(lyrics_dir, "test.lrc")
|
||||
with open(lrc_path, 'w') as f:
|
||||
f.write("[00:00.00]Test\n")
|
||||
|
||||
# Create required corrections.json file
|
||||
corrections_path = os.path.join(lyrics_dir, "corrections.json")
|
||||
|
||||
# No corrections file at all
|
||||
transcription_result = {"lrc_filepath": lrc_path}
|
||||
|
||||
with pytest.raises(Exception, match="No corrections JSON found"):
|
||||
await upload_lyrics_results(
|
||||
"test123", temp_dir, transcription_result,
|
||||
mock_storage, mock_job_manager
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_lyrics_results_finds_reference_and_uncorrected_by_scan(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results finds reference and uncorrected files by scanning.
|
||||
|
||||
Files are found by suffix pattern, not by reconstructing from job.artist/title,
|
||||
so mid-processing artist name changes don't break the upload.
|
||||
"""
|
||||
from backend.workers.lyrics_worker import upload_lyrics_results
|
||||
import json
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
lyrics_dir = os.path.join(temp_dir, "lyrics")
|
||||
os.makedirs(lyrics_dir)
|
||||
|
||||
lrc_path = os.path.join(lyrics_dir, "test.lrc")
|
||||
with open(lrc_path, 'w') as f:
|
||||
f.write("[00:00.00]Test\n")
|
||||
|
||||
corrections_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Corrections).json")
|
||||
with open(corrections_path, 'w') as f:
|
||||
json.dump({"corrected_segments": []}, f)
|
||||
|
||||
# Create a reference lyrics file using the job's artist/title
|
||||
ref_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Genius).txt")
|
||||
|
||||
# Reference and uncorrected files with arbitrary artist name
|
||||
ref_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Genius).txt")
|
||||
with open(ref_path, 'w') as f:
|
||||
f.write("Reference lyrics content\n")
|
||||
|
||||
# Create uncorrected transcription file using job's artist/title
|
||||
uncorrected_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Uncorrected).txt")
|
||||
|
||||
uncorrected_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Uncorrected).txt")
|
||||
with open(uncorrected_path, 'w') as f:
|
||||
f.write("Uncorrected transcription\n")
|
||||
|
||||
|
||||
transcription_result = {"lrc_filepath": lrc_path}
|
||||
|
||||
# This should NOT raise UnboundLocalError for 'job'
|
||||
|
||||
await upload_lyrics_results(
|
||||
"test123", temp_dir, transcription_result,
|
||||
mock_storage, mock_job_manager
|
||||
)
|
||||
|
||||
# Verify job was fetched to get artist/title
|
||||
mock_job_manager.get_job.assert_called_with("test123")
|
||||
|
||||
# Verify files were uploaded (the reference and uncorrected files exist)
|
||||
|
||||
# Verify files were uploaded: LRC + corrections + genius ref + uncorrected = 4
|
||||
upload_calls = mock_storage.upload_file.call_args_list
|
||||
assert len(upload_calls) >= 2 # LRC + at least one reference or uncorrected
|
||||
assert len(upload_calls) == 4
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_lyrics_transcription_marks_failed_on_error(self, mock_job_manager, mock_storage):
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
"""
|
||||
Utilities for identifying test data.
|
||||
Utilities for identifying test data and internal accounts.
|
||||
|
||||
Test data is generated by automated E2E tests and should be filterable
|
||||
in admin dashboards to show only real user data by default.
|
||||
|
||||
Internal accounts belong to team members and should be excluded from
|
||||
abuse investigation views.
|
||||
"""
|
||||
|
||||
# Email domains used by automated testing frameworks
|
||||
@@ -10,6 +13,12 @@ TEST_EMAIL_DOMAINS = [
|
||||
"inbox.testmail.app", # Used by E2E happy path tests
|
||||
]
|
||||
|
||||
# Email domains belonging to internal team members
|
||||
INTERNAL_EMAIL_DOMAINS = [
|
||||
"nomadkaraoke.com", # Team accounts
|
||||
"beveridge.uk", # Founder's personal domain
|
||||
]
|
||||
|
||||
|
||||
def is_test_email(email: str) -> bool:
|
||||
"""
|
||||
@@ -25,3 +34,16 @@ def is_test_email(email: str) -> bool:
|
||||
return False
|
||||
email_lower = email.lower()
|
||||
return any(email_lower.endswith(f"@{domain}") for domain in TEST_EMAIL_DOMAINS)
|
||||
|
||||
|
||||
def is_internal_email(email: str) -> bool:
|
||||
"""Check if an email address belongs to an internal team member."""
|
||||
if not email:
|
||||
return False
|
||||
email_lower = email.lower()
|
||||
return any(email_lower.endswith(f"@{domain}") for domain in INTERNAL_EMAIL_DOMAINS)
|
||||
|
||||
|
||||
def is_internal_or_test_email(email: str) -> bool:
|
||||
"""Check if an email is internal or automated test data."""
|
||||
return is_test_email(email) or is_internal_email(email)
|
||||
@@ -2,11 +2,13 @@
|
||||
Audio separation worker.
|
||||
|
||||
Handles the audio processing track of parallel processing:
|
||||
1. Stage 1: Clean instrumental separation (Modal API, 3-5 min)
|
||||
2. Stage 2: Backing vocals separation (Modal API, 2-3 min)
|
||||
1. Stage 1: Clean instrumental separation (GPU, 3-5 min)
|
||||
2. Stage 2: Backing vocals separation (GPU, 2-3 min)
|
||||
3. Post-processing: Combine instrumentals, normalize
|
||||
|
||||
Re-uses karaoke_gen.audio_processor.AudioProcessor for remote GPU separation.
|
||||
Supports two modes:
|
||||
- Local GPU: Runs Separator directly with L4 GPU (MODEL_DIR env var)
|
||||
- Remote API: Calls audio-separator Cloud Run Service (AUDIO_SEPARATOR_API_URL env var)
|
||||
|
||||
Observability:
|
||||
- All operations wrapped in tracing spans for Cloud Trace visibility
|
||||
@@ -200,6 +202,7 @@ async def download_from_url(url: str, temp_dir: str, artist: str, title: str, jo
|
||||
|
||||
def create_audio_processor(
|
||||
temp_dir: str,
|
||||
model_file_dir: Optional[str] = None,
|
||||
clean_instrumental_model: Optional[str] = None,
|
||||
backing_vocals_models: Optional[list] = None,
|
||||
other_stems_models: Optional[list] = None,
|
||||
@@ -207,15 +210,24 @@ def create_audio_processor(
|
||||
karaoke_preset: Optional[str] = None,
|
||||
) -> AudioProcessor:
|
||||
"""
|
||||
Create an AudioProcessor instance configured for remote API processing.
|
||||
Create an AudioProcessor instance configured for audio processing.
|
||||
|
||||
Supports two modes:
|
||||
- Local GPU mode: When model_file_dir is set, uses the local Separator class
|
||||
with GPU models loaded from that directory. No remote API calls.
|
||||
- Remote API mode (default): When model_file_dir is None, delegates separation
|
||||
to a remote audio-separator API server.
|
||||
|
||||
Within each mode, separation can be configured via:
|
||||
- Preset mode (default): Uses ensemble presets for higher quality separation.
|
||||
Presets are resolved by the audio-separator API server.
|
||||
Presets are resolved by the audio-separator API server (remote) or local
|
||||
preset definitions (local GPU).
|
||||
- Model mode (legacy): Uses explicit model filenames for per-job overrides.
|
||||
|
||||
Args:
|
||||
temp_dir: Temporary directory for processing
|
||||
model_file_dir: Directory containing local model files for GPU separation.
|
||||
When set, enables local GPU mode. When None (default), uses remote API.
|
||||
clean_instrumental_model: Model for clean instrumental (legacy, overrides preset)
|
||||
backing_vocals_models: Models for backing vocals (legacy, overrides preset)
|
||||
other_stems_models: Models for other stems (legacy, default empty)
|
||||
@@ -241,7 +253,7 @@ def create_audio_processor(
|
||||
logger=audio_logger,
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None, # No local models, using remote API
|
||||
model_file_dir=model_file_dir,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model=effective_clean_model,
|
||||
backing_vocals_models=effective_backing_models,
|
||||
@@ -249,7 +261,7 @@ def create_audio_processor(
|
||||
ffmpeg_base_command=ffmpeg_base_command,
|
||||
)
|
||||
|
||||
# Set preset configuration (used by _process_audio_separation_remote)
|
||||
# Set preset configuration (used by both remote and local paths)
|
||||
processor.instrumental_preset = instrumental_preset or DEFAULT_INSTRUMENTAL_PRESET
|
||||
processor.karaoke_preset = karaoke_preset or DEFAULT_KARAOKE_PRESET
|
||||
|
||||
@@ -265,8 +277,8 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
|
||||
Workflow:
|
||||
1. Download audio from GCS
|
||||
2. Stage 1: Separate with clean instrumental + other stems models (Modal API)
|
||||
3. Stage 2: Separate vocals for backing vocals (Modal API)
|
||||
2. Stage 1: Separate with clean instrumental + other stems models (GPU)
|
||||
3. Stage 2: Separate vocals for backing vocals (GPU)
|
||||
4. Post-process: Combine instrumentals, normalize audio
|
||||
5. Upload all stems to GCS
|
||||
6. Mark job as AUDIO_COMPLETE
|
||||
@@ -326,13 +338,22 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
job_log.info(f"Starting audio separation for {job.artist} - {job.title}")
|
||||
logger.info(f"[job:{job_id}] Starting audio separation for {job.artist} - {job.title}")
|
||||
|
||||
# Ensure AUDIO_SEPARATOR_API_URL is set
|
||||
# Determine separation mode: local GPU or remote API
|
||||
api_url = os.environ.get("AUDIO_SEPARATOR_API_URL")
|
||||
if not api_url:
|
||||
raise Exception("AUDIO_SEPARATOR_API_URL environment variable not set. "
|
||||
"Cannot perform audio separation without remote API access.")
|
||||
job_log.info(f"Audio separator API: {api_url}")
|
||||
add_span_attribute("audio_separator_api", api_url)
|
||||
model_dir = os.environ.get("MODEL_DIR")
|
||||
if api_url:
|
||||
job_log.info(f"Audio separator mode: remote API at {api_url}")
|
||||
add_span_attribute("audio_separator_mode", "remote")
|
||||
add_span_attribute("audio_separator_api", api_url)
|
||||
elif model_dir:
|
||||
job_log.info(f"Audio separator mode: local GPU (models at {model_dir})")
|
||||
add_span_attribute("audio_separator_mode", "local_gpu")
|
||||
add_span_attribute("model_dir", model_dir)
|
||||
else:
|
||||
raise Exception(
|
||||
"Audio separation not configured. Set either AUDIO_SEPARATOR_API_URL "
|
||||
"(remote API) or MODEL_DIR (local GPU with baked-in models)."
|
||||
)
|
||||
|
||||
# Download audio file from GCS or URL
|
||||
with job_span("download-audio", job_id) as download_span:
|
||||
@@ -371,9 +392,15 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
clean_instrumental_model=job.clean_instrumental_model,
|
||||
backing_vocals_models=job.backing_vocals_models,
|
||||
other_stems_models=job.other_stems_models,
|
||||
model_file_dir=model_dir,
|
||||
)
|
||||
audio_processor.job_id = job_id # Used as filename prefix (avoids artist/title encoding issues)
|
||||
|
||||
# Pass GCS URI so the separator can fetch directly from GCS (avoids 413 for large files)
|
||||
if job.input_media_gcs_path:
|
||||
audio_processor.input_gcs_uri = f"gs://{settings.gcs_bucket_name}/{job.input_media_gcs_path}"
|
||||
job_log.info(f" GCS URI for separator: {audio_processor.input_gcs_uri}")
|
||||
|
||||
# Store effective model names in state_data for video_worker to use in file naming
|
||||
# This ensures output filenames match local CLI behavior (e.g., "Instrumental model_bs_roformer_ep_317_sdr_12.9755.ckpt")
|
||||
effective_model_names = {
|
||||
@@ -392,22 +419,42 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
artist_title = f"{safe_artist} - {safe_title}"
|
||||
|
||||
# Run audio separation (calls Modal API internally)
|
||||
# Run audio separation (local GPU or remote API)
|
||||
# This returns a dict with paths to all separated stems
|
||||
with job_span("modal-separation", job_id) as sep_span:
|
||||
with job_span("audio-separation", job_id) as sep_span:
|
||||
sep_start = time.time()
|
||||
job_log.info("Starting audio separation (this may take 5-10 minutes)...")
|
||||
job_log.info(" Stage 1: Clean instrumental separation (MDX models)")
|
||||
job_log.info(" Stage 2: Backing vocals separation (Demucs model)")
|
||||
add_span_event("separation_started")
|
||||
logger.info(f"[job:{job_id}] Calling Modal API for audio separation")
|
||||
logger.info(f"[job:{job_id}] Starting audio separation")
|
||||
|
||||
with metrics.time_external_api("modal", job_id):
|
||||
separation_result = audio_processor.process_audio_separation(
|
||||
audio_file=audio_path,
|
||||
artist_title=artist_title,
|
||||
track_output_dir=temp_dir
|
||||
)
|
||||
# Retry with exponential backoff. The audio-separator GPU service
|
||||
# may be busy processing other jobs for 5-10+ minutes each, so we
|
||||
# need patience: 60s, 120s, 240s, 480s = ~15 min total wait.
|
||||
max_retries = 5
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
with metrics.time_external_api("audio_separation", job_id):
|
||||
separation_result = audio_processor.process_audio_separation(
|
||||
audio_file=audio_path,
|
||||
artist_title=artist_title,
|
||||
track_output_dir=temp_dir
|
||||
)
|
||||
break # Success
|
||||
except Exception as e:
|
||||
error_str = str(e)
|
||||
if attempt < max_retries:
|
||||
wait_time = 60 * (2 ** (attempt - 1)) # 60s, 120s, 240s, 480s
|
||||
job_log.warning(
|
||||
f"Audio separation attempt {attempt}/{max_retries} failed: {error_str}. "
|
||||
f"Retrying in {wait_time}s..."
|
||||
)
|
||||
logger.warning(f"[job:{job_id}] Separation attempt {attempt} failed: {error_str}")
|
||||
time.sleep(wait_time)
|
||||
else:
|
||||
job_log.error(f"Audio separation failed after {max_retries} attempts: {error_str}")
|
||||
raise
|
||||
|
||||
sep_duration = time.time() - sep_start
|
||||
sep_span.set_attribute("duration_seconds", sep_duration)
|
||||
@@ -435,7 +482,7 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
# Store processing metadata for separation provenance
|
||||
duration = time.time() - start_time
|
||||
job_manager.update_processing_metadata(job_id, "separation", {
|
||||
"provider": "modal",
|
||||
"provider": "local_gpu" if model_dir else "remote_api",
|
||||
"clean_model": effective_model_names['clean_instrumental_model'],
|
||||
"backing_models": effective_model_names['backing_vocals_models'],
|
||||
"other_models": effective_model_names['other_stems_models'],
|
||||
@@ -776,7 +823,7 @@ def main():
|
||||
Environment Variables:
|
||||
GOOGLE_CLOUD_PROJECT: GCP project ID (required)
|
||||
GCS_BUCKET_NAME: Storage bucket name (required)
|
||||
AUDIO_SEPARATOR_API_URL: Modal API URL (required)
|
||||
AUDIO_SEPARATOR_API_URL: Remote API URL (or MODEL_DIR for local GPU)
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
|
||||
@@ -29,7 +29,6 @@ from typing import Optional, Dict, Any
|
||||
from pathlib import Path
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
@@ -599,10 +598,7 @@ async def upload_lyrics_results(
|
||||
job_log: Optional JobLogger for remote debugging
|
||||
"""
|
||||
logger.info(f"Job {job_id}: Uploading lyrics results to GCS")
|
||||
|
||||
# Get job object for artist/title
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
|
||||
lyrics_dir = os.path.join(temp_dir, "lyrics")
|
||||
|
||||
# Upload LRC file (timed lyrics)
|
||||
@@ -614,17 +610,21 @@ async def upload_lyrics_results(
|
||||
|
||||
# Upload corrections JSON (for review interface)
|
||||
# LyricsProcessor saves it as "{artist} - {title} (Lyrics Corrections).json"
|
||||
# Sanitize artist/title to prevent path injection and match LyricsProcessor's sanitization
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
corrections_filename = f"{safe_artist} - {safe_title} (Lyrics Corrections).json"
|
||||
corrections_file = os.path.join(lyrics_dir, corrections_filename)
|
||||
# Scan the directory instead of reconstructing the filename, because the artist/title
|
||||
# in Firestore may have been updated (e.g. by admin) after LyricsProcessor generated the file.
|
||||
corrections_file = None
|
||||
if os.path.isdir(lyrics_dir):
|
||||
for fname in os.listdir(lyrics_dir):
|
||||
if fname.endswith("(Lyrics Corrections).json"):
|
||||
corrections_file = os.path.join(lyrics_dir, fname)
|
||||
break
|
||||
# Fallback: check for generic corrections.json
|
||||
if not corrections_file:
|
||||
fallback = os.path.join(lyrics_dir, "corrections.json")
|
||||
if os.path.exists(fallback):
|
||||
corrections_file = fallback
|
||||
|
||||
# Also check for generic corrections.json (fallback)
|
||||
if not os.path.exists(corrections_file):
|
||||
corrections_file = os.path.join(lyrics_dir, "corrections.json")
|
||||
|
||||
if os.path.exists(corrections_file):
|
||||
if corrections_file and os.path.exists(corrections_file):
|
||||
# Always upload as corrections.json for consistent access
|
||||
gcs_path = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
url = storage.upload_file(corrections_file, gcs_path)
|
||||
@@ -660,33 +660,29 @@ async def upload_lyrics_results(
|
||||
else:
|
||||
# CRITICAL: corrections.json is required for the review UI
|
||||
# If it's missing, the job cannot proceed to review
|
||||
error_msg = f"No corrections JSON found at {corrections_file}. Transcription may have produced no lyrics."
|
||||
error_msg = f"No corrections JSON found in {lyrics_dir}. Transcription may have produced no lyrics."
|
||||
logger.error(f"Job {job_id}: {error_msg}")
|
||||
raise Exception(error_msg)
|
||||
|
||||
# Upload ALL reference lyrics files (not just first) so they're available for distribution
|
||||
# Note: Source names use .title() so "lrclib" -> "Lrclib", "genius" -> "Genius"
|
||||
# Use sanitized artist/title to match LyricsProcessor's file naming
|
||||
reference_files = [
|
||||
(f"{safe_artist} - {safe_title} (Lyrics Genius).txt", "genius"),
|
||||
(f"{safe_artist} - {safe_title} (Lyrics Spotify).txt", "spotify"),
|
||||
(f"{safe_artist} - {safe_title} (Lyrics Musixmatch).txt", "musixmatch"),
|
||||
(f"{safe_artist} - {safe_title} (Lyrics Lrclib).txt", "lrclib"),
|
||||
]
|
||||
# Scan directory for reference files instead of reconstructing filenames,
|
||||
# since artist/title may have changed in Firestore after file generation.
|
||||
source_keys = {"Genius": "genius", "Spotify": "spotify", "Musixmatch": "musixmatch", "Lrclib": "lrclib"}
|
||||
|
||||
found_references = []
|
||||
for ref_filename, source_key in reference_files:
|
||||
ref_path = os.path.join(lyrics_dir, ref_filename)
|
||||
if os.path.exists(ref_path):
|
||||
# Upload with original filename to preserve proper naming
|
||||
gcs_path = f"jobs/{job_id}/lyrics/{ref_filename}"
|
||||
url = storage.upload_file(ref_path, gcs_path)
|
||||
# Track in job.files so video_worker can download for distribution
|
||||
job_manager.update_file_url(job_id, 'lyrics', f'reference_{source_key}', url)
|
||||
if job_log:
|
||||
job_log.info(f"Found reference lyrics from {source_key}")
|
||||
logger.info(f"Job {job_id}: Uploaded reference lyrics: {ref_filename}")
|
||||
found_references.append(source_key)
|
||||
if os.path.isdir(lyrics_dir):
|
||||
for fname in os.listdir(lyrics_dir):
|
||||
for source_label, source_key in source_keys.items():
|
||||
if fname.endswith(f"(Lyrics {source_label}).txt"):
|
||||
ref_path = os.path.join(lyrics_dir, fname)
|
||||
gcs_path = f"jobs/{job_id}/lyrics/{fname}"
|
||||
url = storage.upload_file(ref_path, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', f'reference_{source_key}', url)
|
||||
if job_log:
|
||||
job_log.info(f"Found reference lyrics from {source_key}")
|
||||
logger.info(f"Job {job_id}: Uploaded reference lyrics: {fname}")
|
||||
found_references.append(source_key)
|
||||
break
|
||||
|
||||
if not found_references:
|
||||
if job_log:
|
||||
@@ -695,14 +691,17 @@ async def upload_lyrics_results(
|
||||
else:
|
||||
logger.info(f"Job {job_id}: Found {len(found_references)} reference lyrics sources: {found_references}")
|
||||
|
||||
# Upload uncorrected transcription if available (preserve original filename for distribution)
|
||||
uncorrected_filename = f"{safe_artist} - {safe_title} (Lyrics Uncorrected).txt"
|
||||
uncorrected_file = os.path.join(lyrics_dir, uncorrected_filename)
|
||||
if os.path.exists(uncorrected_file):
|
||||
gcs_path = f"jobs/{job_id}/lyrics/{uncorrected_filename}"
|
||||
url = storage.upload_file(uncorrected_file, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'uncorrected', url)
|
||||
logger.info(f"Job {job_id}: Uploaded uncorrected transcription: {uncorrected_filename}")
|
||||
# Upload uncorrected transcription if available
|
||||
# Scan directory instead of reconstructing filename (artist/title may have changed)
|
||||
if os.path.isdir(lyrics_dir):
|
||||
for fname in os.listdir(lyrics_dir):
|
||||
if fname.endswith("(Lyrics Uncorrected).txt"):
|
||||
uncorrected_file = os.path.join(lyrics_dir, fname)
|
||||
gcs_path = f"jobs/{job_id}/lyrics/{fname}"
|
||||
url = storage.upload_file(uncorrected_file, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'uncorrected', url)
|
||||
logger.info(f"Job {job_id}: Uploaded uncorrected transcription: {fname}")
|
||||
break
|
||||
|
||||
logger.info(f"Job {job_id}: All lyrics results uploaded successfully")
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
# AI-Powered Credit Gating
|
||||
|
||||
## Overview
|
||||
|
||||
Free credit grants (welcome credits and feedback bonus credits) are evaluated by an AI model before being approved. This prevents multi-account abuse where users create multiple accounts to farm free karaoke generation credits.
|
||||
|
||||
The system is **fail-closed**: if anything goes wrong (AI error, unclear response, network issue), credits are NOT granted automatically. Instead, the admin is notified to review manually.
|
||||
|
||||
## How It Works
|
||||
|
||||
```
|
||||
User verifies email (or submits feedback)
|
||||
↓
|
||||
Collect abuse signals:
|
||||
• Device fingerprint correlations (other accounts with same fingerprint)
|
||||
• IP address correlations (other accounts from same IP)
|
||||
• IP geolocation (country, ISP, VPN detection)
|
||||
• Recent signup patterns (new accounts from same IP/fingerprint in last 24h)
|
||||
• User agent string
|
||||
• For feedback: the submitted feedback content
|
||||
↓
|
||||
Clean user? (no correlations, no recent signup spike)
|
||||
→ YES: Grant credits immediately (no AI call needed)
|
||||
→ NO: Call Gemini for evaluation
|
||||
↓
|
||||
Gemini decision:
|
||||
• "grant" → Grant credits, user sees celebratory welcome screen
|
||||
• "deny" → No credits, user gets rejection email (CC'd to Andrew)
|
||||
• Error/uncertain → No credits, user told "team will review shortly",
|
||||
Andrew gets review email with admin link
|
||||
```
|
||||
|
||||
## Decision Outcomes
|
||||
|
||||
| Scenario | Credits | User Experience | Admin Notification |
|
||||
|----------|---------|-----------------|-------------------|
|
||||
| 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 |
|
||||
| Evaluation disabled | Granted | Same as clean | None |
|
||||
|
||||
## Frontend Flow
|
||||
|
||||
The verify page (`/auth/verify`) shows these states in sequence:
|
||||
|
||||
1. **"Verifying your sign-in link..."** — Token validation
|
||||
2. **"Preparing your account..."** — AI evaluation running (2-5 seconds)
|
||||
3. One of:
|
||||
- **Credits granted** — Celebratory screen with credit count, gentle reminder not to abuse, "Start Creating Karaoke" button
|
||||
- **Credits denied** — "Couldn't grant free credits" with buy credits CTA and link to dashboard
|
||||
- **Credits pending review** — "Team will review shortly" with buy credits CTA and "Explore the App" button
|
||||
- **Success** (returning user) — "Welcome back!" with auto-redirect
|
||||
|
||||
## Emails
|
||||
|
||||
### To User: Credit Denied
|
||||
- Subject: "About your Nomad Karaoke free credits"
|
||||
- CC: andrew@beveridge.uk
|
||||
- Tone: Friendly but firm — explains costs, invites reply if mistake
|
||||
- Includes buy credits link
|
||||
|
||||
### To Admin: Review Needed
|
||||
- Subject: "Credit review needed: user@example.com (welcome)"
|
||||
- To: andrew@beveridge.uk
|
||||
- Includes direct link to user's admin page (`/admin/users/detail?email=...`)
|
||||
- Explains what to do: grant credits if legitimate, do nothing if not
|
||||
|
||||
## Configuration
|
||||
|
||||
| Environment Variable | Default | Description |
|
||||
|---------------------|---------|-------------|
|
||||
| `CREDIT_EVAL_ENABLED` | `true` | Set to `false` to disable AI evaluation and auto-grant all credits |
|
||||
| `CREDIT_EVAL_MODEL` | `gemini-3.1-pro-preview` | Gemini model to use for evaluation |
|
||||
|
||||
### Emergency Rollback
|
||||
|
||||
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run environment variables. This immediately reverts to the old behavior of auto-granting all credits without AI evaluation.
|
||||
|
||||
## Audit Trail
|
||||
|
||||
Every evaluation is logged to the `credit_evaluations` Firestore collection:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "uuid",
|
||||
"email": "user@example.com",
|
||||
"grant_type": "welcome",
|
||||
"decision": "grant",
|
||||
"reasoning": "No suspicious correlations found — clean user",
|
||||
"confidence": 1.0,
|
||||
"error": null,
|
||||
"model": "gemini-3.1-pro-preview",
|
||||
"signals_snapshot": {
|
||||
"fingerprint_match_count": 0,
|
||||
"ip_match_count": 0,
|
||||
"recent_signups_ip": 1,
|
||||
"recent_signups_fp": 1,
|
||||
"user_ip": "1.2.3.4",
|
||||
"user_fingerprint": "abc123..."
|
||||
},
|
||||
"evaluated_at": "2026-03-23T21:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
## Admin Workflow
|
||||
|
||||
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 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.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `backend/services/credit_evaluation_service.py` | Core service: signal collection, Gemini prompt, response parsing, audit logging |
|
||||
| `backend/config.py` | `CREDIT_EVAL_ENABLED`, `CREDIT_EVAL_MODEL` config |
|
||||
| `backend/services/user_service.py` | `grant_welcome_credits_if_eligible()` integration |
|
||||
| `backend/api/routes/users.py` | Feedback credit flow integration, verify response includes `credit_status` |
|
||||
| `backend/services/email_service.py` | `send_credit_denied_email()`, `send_credit_review_needed_email()` |
|
||||
| `backend/models/user.py` | `VerifyMagicLinkResponse.credit_status` field |
|
||||
| `frontend/app/auth/verify/page.tsx` | 5-state verify flow with interstitials |
|
||||
| `frontend/lib/types.ts` | `credit_status` type on verify response |
|
||||
|
||||
### Signal Collection
|
||||
|
||||
The evaluation service calls these existing methods to collect signals:
|
||||
|
||||
- `user_service.find_users_by_fingerprint()` — other accounts with same device fingerprint
|
||||
- `user_service.find_users_by_signup_ip()` — other accounts from same IP
|
||||
- `user_service.count_recent_signups_from_ip()` — new accounts from same IP in last 24h
|
||||
- `user_service.count_recent_signups_from_fingerprint()` — new accounts from same fingerprint in last 24h
|
||||
- `ip_geolocation_service.lookup_ip()` — country, ISP, org info
|
||||
- Session collection query — latest user agent
|
||||
|
||||
### Gemini Prompt
|
||||
|
||||
The prompt instructs Gemini to:
|
||||
- **DENY** if fingerprint matches other accounts (strong multi-accounting signal)
|
||||
- **DENY** if IP matches + other suspicious patterns (same UA, no spend)
|
||||
- **GRANT** if appears genuine or insufficient evidence
|
||||
- **When in doubt, GRANT** — false positives worse than false negatives
|
||||
|
||||
The response is structured JSON: `{"decision": "grant"|"deny", "reasoning": "...", "confidence": 0.0-1.0}`
|
||||
|
||||
### Quick-Grant Optimization
|
||||
|
||||
If no correlations are found at all (no fingerprint matches, no IP matches, recent signup counts ≤ 1), the system skips the AI call entirely and grants immediately. This means most legitimate users experience zero additional latency.
|
||||
+46
-4
@@ -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.
|
||||
|
||||
@@ -1699,6 +1699,48 @@ Called by Cloud Tasks 5 minutes after a job enters a blocking state (primarily `
|
||||
|
||||
**Note**: With the combined review flow, users complete both lyrics review and instrumental selection in one session. The `awaiting_instrumental_selection` state is only used for finalise-only jobs.
|
||||
|
||||
### Admin Feedback
|
||||
|
||||
```http
|
||||
GET /api/admin/feedback
|
||||
GET /api/admin/feedback?search=user@example.com&exclude_test=true&limit=50&offset=0
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Lists all user feedback submissions with pagination, search, and aggregate stats.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "uuid",
|
||||
"user_email": "user@example.com",
|
||||
"created_at": "2026-03-01T12:00:00",
|
||||
"overall_rating": 4,
|
||||
"ease_of_use_rating": 5,
|
||||
"lyrics_accuracy_rating": 3,
|
||||
"correction_experience_rating": 4,
|
||||
"what_went_well": "...",
|
||||
"what_could_improve": "...",
|
||||
"additional_comments": null,
|
||||
"would_recommend": true,
|
||||
"would_use_again": true
|
||||
}
|
||||
],
|
||||
"total": 2,
|
||||
"offset": 0,
|
||||
"limit": 50,
|
||||
"has_more": false,
|
||||
"avg_overall_rating": 4.0,
|
||||
"avg_ease_of_use_rating": 4.5,
|
||||
"avg_lyrics_accuracy_rating": 3.5,
|
||||
"avg_correction_experience_rating": 4.0
|
||||
}
|
||||
```
|
||||
|
||||
An email notification is also sent to `admin@nomadkaraoke.com` (configurable via `ADMIN_NOTIFICATION_EMAIL` env var) whenever a user submits new feedback.
|
||||
|
||||
## Rate Limits & Abuse Prevention
|
||||
|
||||
### Usage Control
|
||||
|
||||
+74
-2
@@ -161,7 +161,7 @@ LyricsTranscriber LyricsTranscriber
|
||||
|
||||
| Service | Purpose | Required |
|
||||
|---------|---------|----------|
|
||||
| Cloud Run GPU (L4) | Audio stem separation (us-east4) | Yes |
|
||||
| Cloud Run GPU Job (L4, us-east4) | Audio stem separation — `Separator` runs directly in the audio worker Job (no HTTP hop) | Yes |
|
||||
| AudioShake | Lyrics transcription | Yes |
|
||||
| Vertex AI | Agentic AI correction (Gemini 3 Flash) | Default off (SKIP_CORRECTION=false to enable) |
|
||||
| Genius | Reference lyrics | Yes |
|
||||
@@ -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).
|
||||
@@ -323,7 +369,7 @@ Audio and lyrics workers run as **Cloud Run Jobs** - standalone batch containers
|
||||
│ │
|
||||
│ audio-download-job - 30s-5 min (flacfetch/YouTube) │
|
||||
│ lyrics-transcription-job - 5-15 min (AudioShake + correction)│
|
||||
│ audio-separation-job - 10-20 min (Cloud Run GPU) │
|
||||
│ audio-separation-job - 10-20 min (L4 GPU, us-east4, direct) │
|
||||
│ video-encoding-job - up to 60 min (optional) │
|
||||
│ │
|
||||
│ Triggered via: google.cloud.run_v2.JobsClient.run_job() │
|
||||
@@ -360,6 +406,32 @@ Screens and render workers run via internal HTTP endpoints with BackgroundTasks,
|
||||
- If workers active, calls `wait_for_completion(timeout=600)` (10 min max)
|
||||
- Logs which workers are still running for debugging
|
||||
|
||||
## Audio Separation Architecture
|
||||
|
||||
Audio stem separation runs **directly inside the audio worker Cloud Run Job** — the `Separator` class from `audio-separator` is imported and called in-process. There is no separate GPU microservice.
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ audio-separation-job (Cloud Run Job, L4 GPU, us-east4) │
|
||||
│ │
|
||||
│ AudioWorker │
|
||||
│ ├── download audio from GCS │
|
||||
│ ├── create_audio_processor() ← Separator(model_file_dir=...) │
|
||||
│ ├── Stage 1: instrumental_clean preset │
|
||||
│ │ └── produces: vocals.flac, instrumental_clean.flac │
|
||||
│ ├── Stage 2: karaoke preset │
|
||||
│ │ └── produces: instrumental_with_backing.flac │
|
||||
│ └── upload stems to GCS │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Key decisions:**
|
||||
- **Direct GPU** — No HTTP hop to a separate service. Jobs can run up to 24h; no timeout concerns.
|
||||
- **Two-stage ensemble preset** — `instrumental_clean` (stage 1) + `karaoke` (stage 2).
|
||||
- **Model cache** — Models are downloaded to `model_file_dir` (GCS-backed or local) and reused across executions.
|
||||
|
||||
**Rollback**: The old audio-separator Cloud Run Service (HTTP endpoint) is kept for rollback but no longer receives traffic. It will be removed in a future phase.
|
||||
|
||||
## Multitenancy
|
||||
|
||||
The platform supports white-label B2B portals where business customers get their own branded karaoke generation experience.
|
||||
|
||||
+65
-1
@@ -170,7 +170,6 @@ The frontend's `detectTenantFromUrl()` checks for the `tenant` query param on lo
|
||||
# Required
|
||||
AUDIOSHAKE_API_TOKEN=...
|
||||
GENIUS_ACCESS_TOKEN=...
|
||||
AUDIO_SEPARATOR_API_URL=... # Modal API endpoint
|
||||
|
||||
# GCP (auto-configured in Cloud Run)
|
||||
GOOGLE_CLOUD_PROJECT=...
|
||||
@@ -208,6 +207,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
|
||||
|
||||
```
|
||||
|
||||
@@ -36,9 +36,51 @@ 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.
|
||||
|
||||
### Cloud Run GPU: Let the Platform Scale, Not Your Code (Mar 2026)
|
||||
|
||||
**Don't use fire-and-forget + semaphore on Cloud Run.** We tried making the `/separate` endpoint return immediately (fire-and-forget background thread) with a `threading.Semaphore(1)` to serialize GPU work. Cloud Run couldn't see background threads as "busy", so it routed ALL requests to one instance where they queued behind the semaphore — causing 30-minute timeouts in production.
|
||||
|
||||
**Fix: synchronous endpoint + `concurrency=1`.** Keep the HTTP request active during processing. Cloud Run sees the request as occupying the instance and scales to new GPU instances for concurrent jobs. This matches Modal's `.spawn()` pattern where each job gets its own container. The client POST timeout must match Cloud Run's request timeout (1800s).
|
||||
|
||||
**Rule of thumb**: If you need the platform's autoscaler to work for you, the request must stay active. Background threads are invisible to the platform.
|
||||
|
||||
### Direct GPU in Cloud Run Jobs > HTTP Microservice
|
||||
|
||||
When a Cloud Run Job needs GPU processing, attach the GPU directly to the Job instead of calling a separate GPU service over HTTP. Benefits:
|
||||
- No HTTP timeout concerns (Jobs can run up to 24h)
|
||||
- No connection management, retry logic, or polling
|
||||
- Simpler architecture (1 hop instead of 3)
|
||||
- Platform handles scaling naturally (each Job execution gets its own GPU)
|
||||
|
||||
The audio separator started as a separate Cloud Run Service called via HTTP from the audio worker Job. This required 1800s HTTP timeouts, complex retry logic, and caused a production outage when the fire-and-forget pattern interacted badly with Cloud Run's autoscaler. Moving the GPU work directly into the Job eliminated all of this complexity.
|
||||
|
||||
### GPU Docker Images: Pin CUDA-Specific Package Versions (Mar 2026)
|
||||
|
||||
**`pip install audio-separator[gpu]` pulls the latest PyTorch, which may require a newer CUDA than your runtime provides.** Cloud Run L4 GPUs have NVIDIA driver 570 (CUDA 12.8 max), but the default torch install gets `cu130` (requires CUDA 13.0), which fails silently — PyTorch reports "NVIDIA driver is too old" and falls back to CPU, then ONNX models fail to load.
|
||||
|
||||
**Fix:** Pin torch to a CUDA version your driver supports (`torch==2.6.0+cu126` from `--index-url https://download.pytorch.org/whl/cu126`), install it BEFORE `audio-separator[gpu]`, and protect it from being overwritten by later `pip install` commands (use `--no-deps` in the app layer).
|
||||
|
||||
**Validate with the actual Docker image, not just packages.** We proved the package combo worked interactively on a VM but missed that the app Dockerfile's `pip install -e .` (with `torch>=2.7` in pyproject.toml) upgraded torch back to cu130. The fastest debugging loop: spin up a GCE L4 VM (~$1/hr), build the Docker image locally, run separation inside the container with `--gpus all`, tear down.
|
||||
|
||||
### audio-separator Ensemble Presets Require Explicit load_model() (Mar 2026)
|
||||
|
||||
**Always call `separator.load_model()` before `separator.separate()`, even when using ensemble presets.** The Separator constructor with `ensemble_preset=` resolves the preset to model names but does NOT load them into memory. Calling `separate()` without `load_model()` fails with "Initialization failed or model not loaded."
|
||||
|
||||
Similarly, **baking models into Docker images requires downloading each model individually** — `Separator(ensemble_preset=...).load_model()` with no args doesn't trigger downloads. Use `sep.load_model(model_filename)` for each model file in the preset.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Decisions
|
||||
@@ -977,3 +1019,11 @@ For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_d
|
||||
|
||||
**Key insight:** For abuse prevention, static lists give you a floor but not a ceiling. Real-time API verification services maintain much larger and more current databases. The tiered approach (free service first, paid service only for edge cases) keeps costs minimal while dramatically improving detection. In our test of 60 recent signups, the free DeBounce API caught 6 disposable accounts and verifymail.io caught 4 more that DeBounce missed.
|
||||
|
||||
### Lyrics Upload Race Condition: Admin Edits During Processing (Mar 2026)
|
||||
|
||||
**Problem:** When an admin updated a job's artist name while the lyrics worker was running, `upload_lyrics_results` reconstructed filenames from the updated Firestore values (`job.artist`, `job.title`), which no longer matched the files on disk generated with the original values. This caused "No corrections JSON found" errors even though the files existed.
|
||||
|
||||
**Fix:** Scan the lyrics directory for files by suffix pattern (e.g., `*(Lyrics Corrections).json`, `*(Lyrics Genius).txt`) instead of reconstructing filenames from Firestore job metadata. This decouples the upload from the current state of mutable job fields.
|
||||
|
||||
**Key insight:** Long-running workers should avoid re-reading mutable metadata to reconstruct local file paths. If a file was created earlier in the same pipeline, find it by pattern rather than reconstructing its name from state that may have changed. This is a variant of TOCTOU — the "check" (reading artist/title) and "use" (looking for the file) happen at different times, and the underlying data can change between them.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -45,7 +45,7 @@ Input (audio + metadata)
|
||||
v v
|
||||
┌───────────────────┐ ┌───────────────────┐
|
||||
│ Audio Separation │ │ Lyrics Processing │
|
||||
│ (Modal GPU) │ │ (AudioShake API) │
|
||||
│ (Cloud Run GPU L4)│ │ (AudioShake API) │
|
||||
│ │ │ │
|
||||
│ • Clean vocal │ │ • Fetch reference │
|
||||
│ removal │ │ lyrics │
|
||||
@@ -98,7 +98,7 @@ All code is open source (MIT license) because:
|
||||
However, reliable fully-automated generation requires:
|
||||
- **AudioShake API**: ~$0.50-1.00 per track for high-quality transcription
|
||||
- **LLM tokens**: ~$0.50-1.00 for agentic correction workflow
|
||||
- **GPU compute**: ~$0.20-0.50 for audio separation on Modal
|
||||
- **GPU compute**: ~$0.10-0.30 for audio separation on Cloud Run GPU (L4)
|
||||
- **Infrastructure**: Cloud Run, Firestore, GCS, etc.
|
||||
|
||||
**Cost per track: ~$2-3** for fully-automated processing, making a paid service necessary to sustain development.
|
||||
@@ -130,7 +130,7 @@ Commercial producers pay for API access or custom integration to generate tracks
|
||||
## Current State (December 2025)
|
||||
|
||||
### What Works
|
||||
- Audio upload and separation (Modal API)
|
||||
- Audio upload and separation (Cloud Run GPU)
|
||||
- Lyrics transcription (AudioShake API)
|
||||
- Agentic AI correction (Gemini 3 Flash via Vertex AI)
|
||||
- Human lyrics review (React UI)
|
||||
@@ -188,7 +188,7 @@ Commercial producers pay for API access or custom integration to generate tracks
|
||||
- **Database**: Firestore
|
||||
- **Storage**: Google Cloud Storage
|
||||
- **Secrets**: Google Secret Manager
|
||||
- **Audio Separation**: Modal (GPU compute)
|
||||
- **Audio Separation**: Cloud Run GPU (L4, us-east4)
|
||||
- **Lyrics Transcription**: AudioShake API
|
||||
- **AI Correction**: Vertex AI (Gemini 3 Flash)
|
||||
- **Payments**: Stripe
|
||||
|
||||
+4
-4
@@ -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).
|
||||
|
||||
@@ -237,7 +237,7 @@
|
||||
```
|
||||
Upload Audio → Parallel Processing → Human Review → Video Generation → Download
|
||||
│ │
|
||||
(Modal + AudioShake) (LyricsTranscriber UI)
|
||||
(Cloud Run GPU + AudioShake) (LyricsTranscriber UI)
|
||||
```
|
||||
|
||||
## For AI Agents
|
||||
|
||||
@@ -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'))
|
||||
"
|
||||
```
|
||||
@@ -0,0 +1,70 @@
|
||||
# Audio Separator Cloud Run GPU Architecture
|
||||
|
||||
**Date:** 2026-03-25 (updated 2026-03-26)
|
||||
**Status:** Implemented and deployed
|
||||
**Repos:** python-audio-separator, karaoke-gen (infrastructure)
|
||||
|
||||
## Problem
|
||||
|
||||
The audio separator service had two issues:
|
||||
1. **Client timeout**: The POST timeout (300s) was too short for ensemble presets on large WAV files (>5 min processing)
|
||||
2. **No multi-instance scaling**: In-memory job status store and no concurrency protection prevented scaling
|
||||
|
||||
## Solution: Synchronous + Cloud Run Autoscaling (Modal Pattern)
|
||||
|
||||
The architecture mirrors how Modal handled this: **each separation request occupies one GPU instance** for its full duration, and the platform (Cloud Run) handles scaling to multiple instances for concurrent jobs.
|
||||
|
||||
### How it works
|
||||
|
||||
1. Client POSTs to `/separate` with `timeout=1800s`
|
||||
2. Server downloads audio (from GCS URI or upload), runs separation synchronously
|
||||
3. Server uploads output files to GCS, updates Firestore with status
|
||||
4. Server returns completed result to client
|
||||
5. Cloud Run sees the request as "active" for 3-5 minutes, so with `concurrency=1`, it scales to new instances for new requests
|
||||
6. Up to 5 GPU instances run in parallel (Cloud Run GPU limit)
|
||||
|
||||
### Key infrastructure
|
||||
|
||||
| Component | Detail |
|
||||
|-----------|--------|
|
||||
| **Cloud Run GPU** | L4, us-east4, concurrency=1, max_instances=5 |
|
||||
| **Firestore** | `audio_separation_jobs` collection — job status for observability |
|
||||
| **GCS** | `nomadkaraoke-audio-separator-outputs` bucket — output files (1-day lifecycle) |
|
||||
| **Client timeout** | 1800s POST timeout (matches Cloud Run request timeout) |
|
||||
|
||||
### Why synchronous, not fire-and-forget
|
||||
|
||||
We initially tried fire-and-forget (background threads + polling), but Cloud Run can't see background threads as "busy". With `concurrency=50` and fire-and-forget, all requests routed to one instance and queued behind a GPU semaphore — defeating the purpose of multi-instance scaling. Making the endpoint synchronous lets Cloud Run's autoscaler work naturally.
|
||||
|
||||
### Why no GPU semaphore
|
||||
|
||||
With `concurrency=1`, Cloud Run guarantees only one active request per instance. Each instance has its own GPU. No application-level serialization needed.
|
||||
|
||||
## Cross-repo changes
|
||||
|
||||
### python-audio-separator
|
||||
- `deploy_cloudrun.py` — synchronous endpoint, Firestore status, GCS output upload
|
||||
- `api_client.py` — 1800s POST timeout
|
||||
- `job_store.py` — Firestore-backed job status store
|
||||
- `output_store.py` — GCS output file management
|
||||
- `Dockerfile.cloudrun` — google-cloud-firestore dependency
|
||||
|
||||
### karaoke-gen (infrastructure)
|
||||
- `audio_separator_service.py` — concurrency=1, GCS bucket, Firestore IAM, env vars
|
||||
- `database.py` — Firestore composite index for cleanup queries
|
||||
|
||||
## Phase 2: Migrate to Cloud Run Jobs
|
||||
|
||||
The current synchronous-service approach works but is not the ideal architecture. Cloud Run Jobs would be a natural fit — karaoke-gen already uses them for the audio worker itself. Benefits:
|
||||
- No HTTP timeout concern (Jobs run up to 24h, no client connection needed)
|
||||
- Native scaling (each execution gets its own container/GPU)
|
||||
- Fire-and-forget + poll pattern (submit job, poll Firestore, download from GCS)
|
||||
- Eliminates the `concurrency=1` workaround for autoscaling
|
||||
|
||||
The Firestore job store and GCS output store built in this session are the right foundations — they'd be reused directly by the Jobs-based approach.
|
||||
|
||||
## Lessons learned
|
||||
|
||||
1. **Cloud Run can't track background threads** — fire-and-forget makes the instance look idle, so the autoscaler doesn't scale. If you need the platform to scale for you, keep the request active.
|
||||
2. **Match the platform's scaling model** — Modal's `.spawn()` gave each job its own container. Cloud Run's `concurrency=1` with synchronous processing achieves the same effect.
|
||||
3. **The GPU semaphore was the wrong abstraction** — it serialized work on one instance instead of distributing across instances. Let the platform handle concurrency.
|
||||
@@ -0,0 +1,123 @@
|
||||
# Plan: Fix 413 Audio Separation Error via GCS Path Passthrough
|
||||
|
||||
**Created:** 2026-03-25
|
||||
**Branch:** feat/sess-20260325-1130-fix-413-audio-sep
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Audio separation fails with `413 Request Entity Too Large` when FLAC files exceed Cloud Run's 32MB request body limit. The current architecture uploads the entire audio file as a multipart POST body to the separator API. Since the file is **already in GCS** by the time the audio worker runs, we should pass the GCS path and let the separator download directly from GCS.
|
||||
|
||||
**Root cause:** `api_client.py:77,136` sends the file as `files={"file": (filename, open(file_path, "rb"))}` in a POST to `/separate`. Cloud Run rejects bodies > 32MB.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Audio separation works for files of any size (no HTTP body limit)
|
||||
- [ ] Backward compatible — file upload still works for non-GCS callers (CLI, tests)
|
||||
- [ ] No data duplication — separator reads from the same GCS bucket, doesn't copy
|
||||
- [ ] Stage 2 (backing vocals) still works — uses Stage 1 output which is local on the separator
|
||||
|
||||
## Technical Approach
|
||||
|
||||
**Change:** Add a `gcs_uri` parameter to the `/separate` endpoint. When provided, the separator downloads from GCS instead of expecting a file upload. The API client gains a new parameter for this.
|
||||
|
||||
Both services are in the same GCP project (`nomadkaraoke`), so the separator's service account just needs `roles/storage.objectViewer` on the `karaoke-gen-storage` bucket.
|
||||
|
||||
### Flow: Before
|
||||
```
|
||||
audio_worker → download from GCS → local file → HTTP POST (file bytes) → separator
|
||||
```
|
||||
|
||||
### Flow: After
|
||||
```
|
||||
audio_worker → pass GCS path → separator downloads from GCS directly
|
||||
```
|
||||
|
||||
Stage 2 (backing vocals) still uploads the local mixed_vocals file since it's a Stage 1 output that only exists on the separator's local disk. But Stage 2 files are small (vocals only), so no 413 risk.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Repo 1: python-audio-separator (separate worktree)
|
||||
|
||||
1. [ ] **Server: Add `gcs_uri` parameter to `/separate` endpoint** (`audio_separator/remote/deploy_cloudrun.py`)
|
||||
- Add `gcs_uri: Optional[str] = Form(None)` parameter
|
||||
- When provided, download from GCS instead of reading `file` upload
|
||||
- Make `file` parameter optional (required only when `gcs_uri` not provided)
|
||||
- Validate: exactly one of `file` or `gcs_uri` must be provided
|
||||
|
||||
2. [ ] **Server: Add GCS download helper** (`audio_separator/remote/deploy_cloudrun.py`)
|
||||
- `download_from_gcs(gcs_uri: str, output_dir: str) -> tuple[bytes, str]`
|
||||
- Parse `gs://bucket/path` or just `bucket/path` format
|
||||
- Use `google-cloud-storage` (already a dependency for model download)
|
||||
- Return `(audio_bytes, filename)`
|
||||
|
||||
3. [ ] **Client: Add `gcs_uri` parameter** (`audio_separator/remote/api_client.py`)
|
||||
- Add `gcs_uri` param to `separate_audio()` and `separate_audio_and_wait()`
|
||||
- When `gcs_uri` is provided, send it as form data instead of file upload
|
||||
- When `gcs_uri` is provided, `file_path` becomes optional (not opened/sent)
|
||||
|
||||
4. [ ] **Tests: Add unit tests for GCS passthrough**
|
||||
- Test server accepts `gcs_uri` parameter
|
||||
- Test client sends `gcs_uri` instead of file when provided
|
||||
- Test validation (can't provide both `file` and `gcs_uri`, must provide one)
|
||||
|
||||
5. [ ] **Bump version, push, publish**
|
||||
|
||||
### Repo 2: karaoke-gen (this worktree)
|
||||
|
||||
6. [ ] **Infrastructure: Grant GCS read access to separator SA** (`infrastructure/modules/audio_separator_service.py`)
|
||||
- Add `roles/storage.objectViewer` on `karaoke-gen-storage` bucket to the `audio-separator` service account
|
||||
|
||||
7. [ ] **Audio worker: Pass GCS path to separator** (`karaoke_gen/audio_processor.py`)
|
||||
- In `_process_audio_separation_remote()`, pass `gcs_uri` for Stage 1
|
||||
- Construct URI: `gs://karaoke-gen-storage/{job.input_media_gcs_path}`
|
||||
- Stage 2 continues using local file upload (the mixed_vocals file is on separator's disk, not in GCS)
|
||||
|
||||
8. [ ] **Update audio-separator dependency** (`pyproject.toml`)
|
||||
- `poetry update audio-separator` after the new version is published
|
||||
|
||||
9. [ ] **Tests**
|
||||
- Update existing audio processor tests to verify `gcs_uri` is passed
|
||||
- Test that Stage 1 uses GCS path, Stage 2 uses file upload
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
### python-audio-separator
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `audio_separator/remote/deploy_cloudrun.py` | Modify | Add `gcs_uri` param to `/separate`, add GCS download helper |
|
||||
| `audio_separator/remote/api_client.py` | Modify | Add `gcs_uri` param to client methods |
|
||||
| `tests/unit/test_remote_api_client.py` | Modify | Add tests for GCS passthrough |
|
||||
| `pyproject.toml` | Modify | Bump version |
|
||||
|
||||
### karaoke-gen
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `infrastructure/modules/audio_separator_service.py` | Modify | Add GCS read permission |
|
||||
| `karaoke_gen/audio_processor.py` | Modify | Pass `gcs_uri` in Stage 1 |
|
||||
| `backend/workers/audio_worker.py` | Modify | Pass GCS path to audio processor |
|
||||
| `pyproject.toml` | Modify | Update audio-separator dependency |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests:** Mock GCS client in separator, verify download_from_gcs works
|
||||
- **Unit tests:** Verify API client sends gcs_uri param correctly
|
||||
- **Integration test:** Deploy separator locally, test with a real GCS file
|
||||
- **Production test:** Re-run failed job `45f9bbc0` after deployment
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should we also upload Stage 2 input (mixed_vocals) to GCS and use gcs_uri? Not needed now — vocals-only files are small — but would be more consistent.
|
||||
- [ ] Should the `gcs_uri` format be `gs://bucket/path` or just the blob path with a separate bucket param? Suggest `gs://` URI for clarity and flexibility.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Revert to file upload by not passing `gcs_uri` — the parameter is optional
|
||||
- The separator still accepts file uploads as before (backward compatible)
|
||||
- No infrastructure changes needed for rollback (extra IAM permission is harmless)
|
||||
|
||||
## Execution Order
|
||||
|
||||
1. Start with python-audio-separator (steps 1-5) — this is the dependency
|
||||
2. Apply infra change (step 6) — can be done in parallel
|
||||
3. Update karaoke-gen (steps 7-9) — depends on step 5
|
||||
@@ -0,0 +1,53 @@
|
||||
# Plan: Pre-compute Credit Evaluation at Magic Link Send Time
|
||||
|
||||
**Created:** 2026-03-25
|
||||
**Branch:** feat/sess-20260324-2308-welcome-credit-abuse
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Move the AI credit evaluation from verify-magic-link time to send-magic-link time. By the time the user clicks the link in their email (typically 10-20+ seconds later), the decision is already made and verification is instant. If they click very fast, fall back to computing inline (same experience as today).
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Run credit evaluation asynchronously after sending the magic link email
|
||||
- [ ] Store the evaluation result on the magic link document in Firestore
|
||||
- [ ] At verify time, read pre-computed result if available
|
||||
- [ ] Fall back to inline evaluation if result isn't ready yet (preserves "preparing" UX)
|
||||
- [ ] Only evaluate new users (existing users skip evaluation already)
|
||||
- [ ] No change to the user-facing experience — just faster
|
||||
|
||||
## Technical Approach
|
||||
|
||||
**Key insight:** `send_magic_link` already has all the signals needed (email, IP, fingerprint) and already creates the user via `get_or_create_user()`. We just need to run the evaluation after sending the email and store the result.
|
||||
|
||||
**Threading:** Use `threading.Thread` to run evaluation in background so the magic link response returns immediately. FastAPI's async doesn't help here since the evaluation is sync (Firestore + Gemini calls).
|
||||
|
||||
**Storage:** Add `credit_eval_decision`, `credit_eval_reasoning`, and `credit_eval_error` fields to the magic link Firestore document. The verify endpoint already reads this document.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] Add evaluation result fields to magic link document schema
|
||||
2. [ ] Create helper function that runs evaluation and writes result to magic link doc
|
||||
3. [ ] Call helper in background thread from `send_magic_link` (new users only)
|
||||
4. [ ] Update `verify_magic_link` to check for pre-computed result before calling evaluation
|
||||
5. [ ] Update tests
|
||||
6. [ ] Bump version
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/users.py` | Modify | Trigger background eval in send_magic_link; read pre-computed result in verify_magic_link |
|
||||
| `backend/services/user_service.py` | Modify | Add method to store eval result on magic link doc |
|
||||
| `backend/models/user.py` | Modify | Add optional eval fields to MagicLinkToken model |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Update existing anti-abuse tests to verify pre-computation flow
|
||||
- Test fallback path (no pre-computed result → inline evaluation)
|
||||
- Test that send_magic_link still returns quickly (doesn't block on eval)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
The fallback path IS the current behavior. If pre-computation breaks, verify just runs evaluation inline as before.
|
||||
@@ -0,0 +1,158 @@
|
||||
# Direct GPU Audio Separation in Audio Worker
|
||||
|
||||
**Date:** 2026-03-26
|
||||
**Status:** Approved, ready for implementation
|
||||
**Repos:** karaoke-gen (primary), python-audio-separator (read-only reference)
|
||||
**Branch:** feat/sess-20260326-1339-audio-sep-direct-gpu
|
||||
|
||||
## Problem
|
||||
|
||||
The audio worker Cloud Run Job calls a separate Cloud Run Service (audio-separator) over HTTP for GPU-accelerated stem separation. This architecture has proven fragile:
|
||||
|
||||
- 1800s HTTP timeout is the max Cloud Run allows; large files can exceed it
|
||||
- Holding connections open for 5-10 minutes wastes resources
|
||||
- `concurrency=1` forces a new $1/hr GPU instance per request
|
||||
- Cold start delays add to the client's wait time
|
||||
- A recent production outage (2026-03-25) was caused by the fire-and-forget/semaphore interaction with Cloud Run's autoscaler
|
||||
|
||||
## Solution
|
||||
|
||||
Run the `Separator` class directly inside the audio worker Cloud Run Job with an L4 GPU attached. This eliminates the HTTP hop entirely.
|
||||
|
||||
### Architecture Change
|
||||
|
||||
```
|
||||
Current (3 hops):
|
||||
karaoke-gen backend → Cloud Run Job (audio worker, CPU, us-central1)
|
||||
→ HTTP POST → Cloud Run Service (separator, GPU, us-east4)
|
||||
|
||||
New (1 hop):
|
||||
karaoke-gen backend → Cloud Run Job (audio worker, GPU, us-east4)
|
||||
→ Separator class runs locally
|
||||
```
|
||||
|
||||
## Decisions
|
||||
|
||||
| Decision | Choice | Rationale |
|
||||
|----------|--------|-----------|
|
||||
| Docker image | Separate `karaoke-backend-gpu` image | Keeps regular backend lean; audio worker gets exactly what it needs |
|
||||
| GPU region | us-east4 | L4 GPU quota already exists there; batch job tolerates cross-region latency |
|
||||
| Model loading | Bake into image | Faster cold starts; model set rarely changes |
|
||||
| Rollback strategy | Keep old service running | Phase 1 adds new path; old service removed in phase 2 |
|
||||
| Code path | Reuse existing local Separator path | Already works; minimizes code changes and risk |
|
||||
|
||||
## Components
|
||||
|
||||
### 1. New Docker image: `karaoke-backend-gpu`
|
||||
|
||||
A GPU-capable base image for the audio worker. Based on `nvidia/cuda:12.6.3-runtime-ubuntu22.04`, includes everything from `karaoke-backend-base` plus GPU-specific dependencies.
|
||||
|
||||
**GPU dependencies (from audio-separator's Dockerfile.cloudrun):**
|
||||
- PyTorch with CUDA support
|
||||
- ONNX Runtime GPU (`onnxruntime-gpu`)
|
||||
- `audio-separator[gpu]` package
|
||||
- CUDA runtime libraries (already in base NVIDIA image)
|
||||
|
||||
**Baked-in models (~1.5GB total):**
|
||||
- `instrumental_clean` preset models (Fv7z + Resurrection)
|
||||
- `karaoke` preset models (3 karaoke models)
|
||||
- Downloaded at build time via `scripts/download_preset_models.py` pattern from python-audio-separator
|
||||
|
||||
**Shared with karaoke-backend-base:**
|
||||
- Python 3.11 (note: audio-separator uses 3.12; need to verify compatibility or align)
|
||||
- FFmpeg (static build), sox, libsndfile
|
||||
- Noto fonts (CJK, emoji, etc.)
|
||||
- spaCy `en_core_web_sm` model
|
||||
- All pip dependencies from karaoke-gen's pyproject.toml
|
||||
|
||||
**New files:**
|
||||
- `backend/Dockerfile.gpu-base` — GPU base image definition
|
||||
- `backend/cloudbuild-gpu-base.yaml` — Cloud Build config
|
||||
- `backend/scripts/download_models.py` — Model download script for build time
|
||||
|
||||
**Artifact Registry:**
|
||||
- New repo `karaoke-backend-gpu` in `us-east4` (co-located with GPU instances)
|
||||
|
||||
### 2. Infrastructure changes
|
||||
|
||||
All in `infrastructure/modules/cloud_run.py`:
|
||||
|
||||
**Audio worker Cloud Run Job modifications:**
|
||||
- Move from `us-central1` to `us-east4` (GPU quota)
|
||||
- Add L4 GPU: `nvidia.com/gpu: "1"`
|
||||
- Increase resources: CPU 2→4, memory 4Gi→16Gi
|
||||
- Change image to `us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend:latest`
|
||||
- Remove `AUDIO_SEPARATOR_API_URL` env var (absence triggers local Separator path)
|
||||
- Add `MODEL_DIR=/models` env var (tells Separator where baked-in models live)
|
||||
|
||||
**New resources in `infrastructure/`:**
|
||||
- Artifact Registry repo for `karaoke-backend-gpu` in us-east4
|
||||
- IAM for the existing audio-separator service account to pull from the new repo
|
||||
|
||||
### 3. Code changes
|
||||
|
||||
**`backend/workers/audio_worker.py`:**
|
||||
- Remove the hard error when `AUDIO_SEPARATOR_API_URL` is not set (lines ~330-333)
|
||||
- When `AUDIO_SEPARATOR_API_URL` is absent, configure `create_audio_processor()` with `model_file_dir` pointing to the baked-in models directory
|
||||
|
||||
**`backend/workers/audio_worker.py` — `create_audio_processor()`:**
|
||||
- Accept optional `model_file_dir` parameter
|
||||
- Pass `instrumental_preset` and `karaoke_preset` through to the processor (currently only used in remote path; the local path needs to use them too)
|
||||
- When `model_file_dir` is set, the processor uses local `Separator`; when not set, it errors
|
||||
|
||||
**`karaoke_gen/audio_processor.py`:**
|
||||
- In the local code path (lines ~200+), support `ensemble_preset` on the `Separator` constructor instead of only using explicit model lists
|
||||
- The existing local path currently uses `self.clean_instrumental_model` / `self.backing_vocals_models` to call individual separation methods. With presets, we pass `ensemble_preset` to `Separator()` and call `separator.separate()` once — the preset handles model selection internally.
|
||||
- Keep the file-lock mechanism (harmless in Cloud Run Jobs; one container = no contention)
|
||||
|
||||
### 4. What stays unchanged (phase 1)
|
||||
|
||||
- Audio-separator Cloud Run Service (kept for rollback)
|
||||
- Firestore `audio_separation_jobs` collection and GCS output bucket
|
||||
- Remote API code path in `audio_processor.py` (`_process_audio_separation_remote`)
|
||||
- CI/CD for the existing `karaoke-backend` image
|
||||
- All other Cloud Run Jobs (lyrics, video workers)
|
||||
|
||||
### 5. CI/CD
|
||||
|
||||
- Add a Cloud Build trigger for the GPU base image (triggered by changes to `backend/Dockerfile.gpu-base` or `pyproject.toml`)
|
||||
- The existing app-layer build (`backend/Dockerfile`) works unchanged — just needs `BASE_IMAGE` build arg set to the GPU base for audio worker deploys
|
||||
- GitHub Actions workflow addition: build and push the GPU image on merge to main
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
**Unit tests:**
|
||||
- Verify `create_audio_processor()` configures correctly with and without `AUDIO_SEPARATOR_API_URL`
|
||||
- Verify `model_file_dir` is passed through when set
|
||||
- Verify preset parameters reach the `Separator` constructor
|
||||
|
||||
**Local integration:**
|
||||
- Build the GPU image locally (requires NVIDIA Docker runtime)
|
||||
- Run a test separation with a sample audio file
|
||||
|
||||
**Production verification:**
|
||||
- Submit a test job after deploy
|
||||
- Verify all stems are generated: clean instrumental, vocals, lead vocals, backing vocals, combined instrumentals
|
||||
- Compare output quality with a job processed through the old HTTP path
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
If issues arise after deployment:
|
||||
1. Add `AUDIO_SEPARATOR_API_URL` back to the audio worker job env vars
|
||||
2. The code falls through to the remote API path
|
||||
3. The old audio-separator service is still running (scale-to-zero, no cost)
|
||||
|
||||
No code changes needed for rollback — just an infra env var change via Pulumi.
|
||||
|
||||
## Phase 2 (follow-up PR)
|
||||
|
||||
After the direct GPU path is verified in production:
|
||||
- Remove the audio-separator Cloud Run Service infrastructure
|
||||
- Remove `AUDIO_SEPARATOR_API_URL` references from code
|
||||
- Remove `_process_audio_separation_remote()` method
|
||||
- Remove `AudioSeparatorAPIClient` import
|
||||
- Clean up Firestore job store / GCS output bucket if no longer needed for observability
|
||||
|
||||
## Python Version
|
||||
|
||||
The audio-separator package requires Python >= 3.10. The GPU base image will use Python 3.11 (same as the existing karaoke-gen base) for consistency. The audio-separator's Dockerfile.cloudrun uses 3.12, but that's not a requirement — it was just the version chosen for that image.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
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.
|
||||
@@ -6,6 +6,10 @@ import type {
|
||||
AbuseSuspiciousUser,
|
||||
AbuseRelatedResponse,
|
||||
AbuseRelatedUser,
|
||||
AbuseCorrelationsResponse,
|
||||
AbuseFingerprintCluster,
|
||||
AbuseIpCluster,
|
||||
AbuseClusterUser,
|
||||
} from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { IpInfo } from "@/components/admin/ip-info"
|
||||
@@ -296,6 +300,312 @@ function SuspiciousAccountsTab({
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Correlations Tab (primary view)
|
||||
// =============================================================================
|
||||
|
||||
function ClusterUserRow({
|
||||
user,
|
||||
highlightUa,
|
||||
onInvestigate,
|
||||
}: {
|
||||
user: AbuseClusterUser
|
||||
highlightUa: boolean
|
||||
onInvestigate: (email: string) => void
|
||||
}) {
|
||||
return (
|
||||
<TableRow>
|
||||
<TableCell className="font-mono text-xs max-w-[200px] truncate">
|
||||
<a
|
||||
href={`/admin/users/detail?email=${encodeURIComponent(user.email)}`}
|
||||
className="hover:underline text-blue-400"
|
||||
>
|
||||
{user.email}
|
||||
</a>
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium">
|
||||
{user.total_jobs_created}
|
||||
{user.total_jobs_completed > 0 && (
|
||||
<span className="text-muted-foreground text-xs ml-1">
|
||||
({user.total_jobs_completed} done)
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">{user.credits}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{user.total_spent === 0 ? (
|
||||
<Badge variant="destructive" className="text-xs">$0</Badge>
|
||||
) : (
|
||||
formatCents(user.total_spent)
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<IpInfo ip={user.signup_ip} compact />
|
||||
</TableCell>
|
||||
<TableCell className="text-xs max-w-[200px] truncate" title={user.user_agent || undefined}>
|
||||
{user.user_agent ? (
|
||||
<span className={highlightUa ? "bg-yellow-500/20 text-yellow-300 px-1 py-0.5 rounded" : ""}>
|
||||
{truncate(user.user_agent, 30)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground">
|
||||
{formatDate(user.created_at)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onInvestigate(user.email)}
|
||||
title="Investigate related accounts"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function hasMatchingUserAgents(users: AbuseClusterUser[]): boolean {
|
||||
const agents = users.map((u) => u.user_agent).filter(Boolean)
|
||||
if (agents.length < 2) return false
|
||||
return new Set(agents).size < agents.length
|
||||
}
|
||||
|
||||
function getMatchingUaSet(users: AbuseClusterUser[]): Set<string> {
|
||||
const counts: Record<string, number> = {}
|
||||
for (const u of users) {
|
||||
if (u.user_agent) {
|
||||
counts[u.user_agent] = (counts[u.user_agent] || 0) + 1
|
||||
}
|
||||
}
|
||||
return new Set(Object.keys(counts).filter((ua) => counts[ua] > 1))
|
||||
}
|
||||
|
||||
function FingerprintClusterCard({
|
||||
cluster,
|
||||
onInvestigate,
|
||||
}: {
|
||||
cluster: AbuseFingerprintCluster
|
||||
onInvestigate: (email: string) => void
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(true)
|
||||
const uaMatches = hasMatchingUserAgents(cluster.users)
|
||||
const matchingUas = getMatchingUaSet(cluster.users)
|
||||
|
||||
return (
|
||||
<Card className="border-red-500/30">
|
||||
<CardHeader className="pb-3 cursor-pointer" onClick={() => setExpanded(!expanded)}>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Fingerprint className="w-4 h-4 text-red-500" />
|
||||
<Badge variant="destructive" className="text-xs">{cluster.count} accounts</Badge>
|
||||
<code className="text-xs bg-muted px-1.5 py-0.5 rounded font-mono">{cluster.fingerprint}</code>
|
||||
{uaMatches && (
|
||||
<Badge className="text-xs bg-yellow-500/20 text-yellow-300 border-yellow-500/30">
|
||||
matching UA
|
||||
</Badge>
|
||||
)}
|
||||
<ChevronRight className={`w-4 h-4 ml-auto transition-transform ${expanded ? "rotate-90" : ""}`} />
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
{expanded && (
|
||||
<CardContent>
|
||||
<div className="border rounded-lg overflow-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead className="text-right">Jobs</TableHead>
|
||||
<TableHead className="text-right">Credits</TableHead>
|
||||
<TableHead className="text-right">Spent</TableHead>
|
||||
<TableHead>Signup IP</TableHead>
|
||||
<TableHead>User Agent</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{cluster.users.map((user) => (
|
||||
<ClusterUserRow
|
||||
key={user.email}
|
||||
user={user}
|
||||
highlightUa={!!user.user_agent && matchingUas.has(user.user_agent)}
|
||||
onInvestigate={onInvestigate}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function IpClusterCard({
|
||||
cluster,
|
||||
onInvestigate,
|
||||
}: {
|
||||
cluster: AbuseIpCluster
|
||||
onInvestigate: (email: string) => void
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(true)
|
||||
const uaMatches = hasMatchingUserAgents(cluster.users)
|
||||
const matchingUas = getMatchingUaSet(cluster.users)
|
||||
|
||||
return (
|
||||
<Card className="border-orange-500/30">
|
||||
<CardHeader className="pb-3 cursor-pointer" onClick={() => setExpanded(!expanded)}>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Globe className="w-4 h-4 text-orange-500" />
|
||||
<Badge className="text-xs bg-orange-500/20 text-orange-300 border-orange-500/30">
|
||||
{cluster.count} accounts
|
||||
</Badge>
|
||||
<IpInfo ip={cluster.ip} compact />
|
||||
{uaMatches && (
|
||||
<Badge className="text-xs bg-yellow-500/20 text-yellow-300 border-yellow-500/30">
|
||||
matching UA
|
||||
</Badge>
|
||||
)}
|
||||
<ChevronRight className={`w-4 h-4 ml-auto transition-transform ${expanded ? "rotate-90" : ""}`} />
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
{expanded && (
|
||||
<CardContent>
|
||||
<div className="border rounded-lg overflow-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead className="text-right">Jobs</TableHead>
|
||||
<TableHead className="text-right">Credits</TableHead>
|
||||
<TableHead className="text-right">Spent</TableHead>
|
||||
<TableHead>Signup IP</TableHead>
|
||||
<TableHead>User Agent</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{cluster.users.map((user) => (
|
||||
<ClusterUserRow
|
||||
key={user.email}
|
||||
user={user}
|
||||
highlightUa={!!user.user_agent && matchingUas.has(user.user_agent)}
|
||||
onInvestigate={onInvestigate}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function CorrelationsTab({
|
||||
onInvestigate,
|
||||
}: {
|
||||
onInvestigate: (email: string) => void
|
||||
}) {
|
||||
const { toast } = useToast()
|
||||
const [data, setData] = useState<AbuseCorrelationsResponse | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const result = await adminApi.getAbuseCorrelations()
|
||||
setData(result)
|
||||
} catch (err: any) {
|
||||
toast({ title: "Error", description: err.message, variant: "destructive" })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
load()
|
||||
}, [])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center py-12">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!data) return null
|
||||
|
||||
const totalFpAccounts = data.fingerprint_clusters.reduce((sum: number, c: AbuseFingerprintCluster) => sum + c.count, 0)
|
||||
const totalIpAccounts = data.ip_clusters.reduce((sum: number, c: AbuseIpCluster) => sum + c.count, 0)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Fingerprint clusters */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Fingerprint className="w-5 h-5 text-red-500" />
|
||||
<h3 className="text-lg font-semibold">Shared Fingerprints</h3>
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
{data.fingerprint_clusters.length} cluster{data.fingerprint_clusters.length !== 1 ? "s" : ""} ({totalFpAccounts} accounts)
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Multiple accounts sharing the same device fingerprint — strong indicator of multi-accounting.
|
||||
</p>
|
||||
{data.fingerprint_clusters.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-6 text-center text-muted-foreground">
|
||||
No shared fingerprint clusters found.
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
data.fingerprint_clusters.map((cluster) => (
|
||||
<FingerprintClusterCard
|
||||
key={cluster.fingerprint}
|
||||
cluster={cluster}
|
||||
onInvestigate={onInvestigate}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* IP clusters */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="w-5 h-5 text-orange-500" />
|
||||
<h3 className="text-lg font-semibold">Shared Signup IPs</h3>
|
||||
<Badge className="text-xs bg-orange-500/20 text-orange-300 border-orange-500/30">
|
||||
{data.ip_clusters.length} cluster{data.ip_clusters.length !== 1 ? "s" : ""} ({totalIpAccounts} accounts)
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Multiple accounts from the same IP address — suspicious but could be a shared network (school, office, VPN).
|
||||
</p>
|
||||
{data.ip_clusters.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-6 text-center text-muted-foreground">
|
||||
No shared IP clusters found.
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
data.ip_clusters.map((cluster) => (
|
||||
<IpClusterCard
|
||||
key={cluster.ip}
|
||||
cluster={cluster}
|
||||
onInvestigate={onInvestigate}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Related Accounts Detail View
|
||||
// =============================================================================
|
||||
@@ -391,7 +701,7 @@ function RelatedAccountsView({
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href={`/admin/users/${encodeURIComponent(email)}`}>
|
||||
<a href={`/admin/users/detail?email=${encodeURIComponent(email)}`}>
|
||||
<ExternalLink className="w-3 h-3 mr-1" />
|
||||
View full user profile
|
||||
</a>
|
||||
@@ -656,7 +966,7 @@ function LookupTab({
|
||||
// =============================================================================
|
||||
|
||||
export default function AbuseInvestigationPage() {
|
||||
const [activeTab, setActiveTab] = useState("suspicious")
|
||||
const [activeTab, setActiveTab] = useState("correlations")
|
||||
const [investigatingEmail, setInvestigatingEmail] = useState<string | null>(null)
|
||||
|
||||
const handleInvestigate = (email: string) => {
|
||||
@@ -689,6 +999,10 @@ export default function AbuseInvestigationPage() {
|
||||
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="correlations">
|
||||
<Users className="w-4 h-4 mr-1" />
|
||||
Correlations
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="suspicious">
|
||||
<AlertTriangle className="w-4 h-4 mr-1" />
|
||||
Suspicious
|
||||
@@ -699,6 +1013,10 @@ export default function AbuseInvestigationPage() {
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="correlations" className="space-y-6">
|
||||
<CorrelationsTab onInvestigate={handleInvestigate} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="suspicious" className="space-y-6">
|
||||
<SuspiciousAccountsTab onInvestigate={handleInvestigate} />
|
||||
</TabsContent>
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
"use client"
|
||||
|
||||
import { Fragment, useEffect, useState, useCallback } from "react"
|
||||
import { adminApi, AdminFeedbackItem, AdminFeedbackListResponse } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Search,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Star,
|
||||
ThumbsUp,
|
||||
ThumbsDown,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
function StarRating({ rating }: { rating: number }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-0.5" title={`${rating}/5`}>
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<Star
|
||||
key={i}
|
||||
className={`w-3.5 h-3.5 ${
|
||||
i <= rating
|
||||
? "fill-yellow-400 text-yellow-400"
|
||||
: "text-muted-foreground/30"
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string | null) {
|
||||
if (!dateStr) return "—"
|
||||
try {
|
||||
return new Date(dateStr).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})
|
||||
} catch {
|
||||
return dateStr
|
||||
}
|
||||
}
|
||||
|
||||
function ExpandableText({ label, text }: { label: string; text: string | null }) {
|
||||
if (!text) return null
|
||||
return (
|
||||
<div className="mb-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">{label}</span>
|
||||
<p className="text-sm whitespace-pre-wrap">{text}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function AdminFeedbackPage() {
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [data, setData] = useState<AdminFeedbackListResponse | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState("")
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null)
|
||||
|
||||
const fetchFeedback = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await adminApi.listFeedback({
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
search: search || undefined,
|
||||
exclude_test: !showTestData,
|
||||
})
|
||||
setData(result)
|
||||
} catch (err) {
|
||||
toast.error("Failed to load feedback")
|
||||
console.error(err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [offset, search, showTestData])
|
||||
|
||||
useEffect(() => {
|
||||
fetchFeedback()
|
||||
}, [fetchFeedback])
|
||||
|
||||
const handleSearch = () => {
|
||||
setOffset(0)
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") handleSearch()
|
||||
}
|
||||
|
||||
const toggleExpand = (id: string) => {
|
||||
setExpandedId(expandedId === id ? null : id)
|
||||
}
|
||||
|
||||
const hasTextContent = (item: AdminFeedbackItem) =>
|
||||
item.what_went_well || item.what_could_improve || item.additional_comments
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">User Feedback</h1>
|
||||
<Button variant="outline" size="sm" onClick={fetchFeedback} disabled={loading}>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Aggregate stats */}
|
||||
{data && data.total > 0 && (
|
||||
<div className="grid grid-cols-2 md:grid-cols-5 gap-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
Total Responses
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{data.total}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{[
|
||||
{ label: "Overall", value: data.avg_overall_rating },
|
||||
{ label: "Ease of Use", value: data.avg_ease_of_use_rating },
|
||||
{ label: "Lyrics Accuracy", value: data.avg_lyrics_accuracy_rating },
|
||||
{ label: "Correction Exp.", value: data.avg_correction_experience_rating },
|
||||
].map(({ label, value }) => (
|
||||
<Card key={label}>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
Avg {label}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-2xl font-bold">
|
||||
{value != null ? value.toFixed(1) : "—"}
|
||||
</p>
|
||||
<span className="text-muted-foreground text-sm">/ 5</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search */}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Search by email..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<Button variant="outline" onClick={handleSearch}>
|
||||
<Search className="w-4 h-4 mr-2" />
|
||||
Search
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : !data || data.items.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
No feedback submissions found.
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-8"></TableHead>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>Date</TableHead>
|
||||
<TableHead>Overall</TableHead>
|
||||
<TableHead>Ease of Use</TableHead>
|
||||
<TableHead>Lyrics</TableHead>
|
||||
<TableHead>Correction</TableHead>
|
||||
<TableHead>Recommend</TableHead>
|
||||
<TableHead>Use Again</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.items.map((item) => (
|
||||
<Fragment key={item.id}>
|
||||
<TableRow
|
||||
className={`cursor-pointer hover:bg-muted/50 ${
|
||||
expandedId === item.id ? "bg-muted/30" : ""
|
||||
}`}
|
||||
onClick={() => toggleExpand(item.id)}
|
||||
>
|
||||
<TableCell className="w-8">
|
||||
{hasTextContent(item) && (
|
||||
expandedId === item.id
|
||||
? <ChevronUp className="w-4 h-4 text-muted-foreground" />
|
||||
: <ChevronDown className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm">
|
||||
{item.user_email}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{formatDate(item.created_at)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StarRating rating={item.overall_rating} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StarRating rating={item.ease_of_use_rating} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StarRating rating={item.lyrics_accuracy_rating} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StarRating rating={item.correction_experience_rating} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{item.would_recommend ? (
|
||||
<Badge variant="secondary" className="bg-green-500/10 text-green-600">
|
||||
<ThumbsUp className="w-3 h-3 mr-1" />
|
||||
Yes
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="bg-red-500/10 text-red-600">
|
||||
<ThumbsDown className="w-3 h-3 mr-1" />
|
||||
No
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{item.would_use_again ? (
|
||||
<Badge variant="secondary" className="bg-green-500/10 text-green-600">
|
||||
<ThumbsUp className="w-3 h-3 mr-1" />
|
||||
Yes
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="bg-red-500/10 text-red-600">
|
||||
<ThumbsDown className="w-3 h-3 mr-1" />
|
||||
No
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{expandedId === item.id && hasTextContent(item) && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={9} className="bg-muted/20 px-8 py-4">
|
||||
<ExpandableText label="What went well" text={item.what_went_well} />
|
||||
<ExpandableText label="What could improve" text={item.what_could_improve} />
|
||||
<ExpandableText label="Additional comments" text={item.additional_comments} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Pagination */}
|
||||
{data && data.total > PAGE_SIZE && (
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, data.total)} of {data.total}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={offset === 0}
|
||||
onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4 mr-1" />
|
||||
Previous
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!data.has_more}
|
||||
onClick={() => setOffset(offset + PAGE_SIZE)}
|
||||
>
|
||||
Next
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -2,24 +2,24 @@
|
||||
|
||||
import { Suspense, useEffect, useState, useRef } from "react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { Loader2, CheckCircle, XCircle } from "lucide-react"
|
||||
import { Loader2, CheckCircle, XCircle, Gift, ShoppingCart } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
|
||||
type VerifyState = "loading" | "success" | "error"
|
||||
type VerifyState = "verifying" | "preparing" | "credits_granted" | "credits_denied" | "credits_pending" | "success" | "error"
|
||||
|
||||
function VerifyMagicLinkContent() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [state, setState] = useState<VerifyState>("loading")
|
||||
const [state, setState] = useState<VerifyState>("verifying")
|
||||
const [errorMessage, setErrorMessage] = useState("")
|
||||
const [creditsGranted, setCreditsGranted] = useState(0)
|
||||
const [creditStatus, setCreditStatus] = useState<string>("not_applicable")
|
||||
const hasVerified = useRef(false)
|
||||
|
||||
const { verifyMagicLink, user, error } = useAuth()
|
||||
|
||||
useEffect(() => {
|
||||
// Prevent duplicate verification attempts
|
||||
if (hasVerified.current) return
|
||||
hasVerified.current = true
|
||||
|
||||
@@ -31,36 +31,47 @@ function VerifyMagicLinkContent() {
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the token
|
||||
const verify = async () => {
|
||||
// Show "preparing your account" while the backend runs AI evaluation
|
||||
setState("preparing")
|
||||
|
||||
const success = await verifyMagicLink(token)
|
||||
if (success) {
|
||||
setState("success")
|
||||
// Check verify response for welcome credits and tenant redirect
|
||||
const lastVerifyResponse = (window as any).__LAST_VERIFY_RESPONSE__
|
||||
if (lastVerifyResponse?.credits_granted > 0) {
|
||||
setCreditsGranted(lastVerifyResponse.credits_granted)
|
||||
}
|
||||
// Check if the verify response included a tenant subdomain
|
||||
// If we're on the wrong domain, redirect to the correct tenant portal
|
||||
const credits = lastVerifyResponse?.credits_granted || 0
|
||||
const status = lastVerifyResponse?.credit_status || "not_applicable"
|
||||
setCreditsGranted(credits)
|
||||
setCreditStatus(status)
|
||||
|
||||
// Check for tenant subdomain redirect
|
||||
if (lastVerifyResponse?.tenant_subdomain) {
|
||||
const currentHost = window.location.hostname.toLowerCase()
|
||||
const tenantSubdomain = lastVerifyResponse.tenant_subdomain.toLowerCase()
|
||||
if (currentHost !== tenantSubdomain) {
|
||||
// We're on the wrong domain — redirect to the correct tenant portal
|
||||
setState("success")
|
||||
setTimeout(() => {
|
||||
window.location.href = `https://${tenantSubdomain}/app`
|
||||
}, 1500)
|
||||
return
|
||||
}
|
||||
}
|
||||
// Same domain or no tenant — redirect normally
|
||||
setTimeout(() => {
|
||||
router.push("/app")
|
||||
}, 2000)
|
||||
|
||||
// Show appropriate interstitial based on credit status
|
||||
if (status === "granted" && credits > 0) {
|
||||
setState("credits_granted")
|
||||
} else if (status === "denied") {
|
||||
setState("credits_denied")
|
||||
} else if (status === "pending_review") {
|
||||
setState("credits_pending")
|
||||
} else {
|
||||
// Returning user or not applicable — go straight to app
|
||||
setState("success")
|
||||
setTimeout(() => {
|
||||
router.push("/app")
|
||||
}, 1500)
|
||||
}
|
||||
} else {
|
||||
setState("error")
|
||||
// Get error from auth store at this point
|
||||
const authStore = useAuth.getState()
|
||||
setErrorMessage(authStore.error || "Invalid or expired link")
|
||||
}
|
||||
@@ -69,9 +80,13 @@ function VerifyMagicLinkContent() {
|
||||
verify()
|
||||
}, [searchParams, verifyMagicLink, router])
|
||||
|
||||
const goToApp = () => router.push("/app")
|
||||
const goToBuy = () => router.push("/app?buy=true")
|
||||
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
{state === "loading" && (
|
||||
{/* Verifying token */}
|
||||
{state === "verifying" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
@@ -83,6 +98,118 @@ function VerifyMagicLinkContent() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Preparing account (AI evaluation running) */}
|
||||
{state === "preparing" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Preparing your account...
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Just a moment while we set things up for you.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits granted - celebratory interstitial */}
|
||||
{state === "credits_granted" && (
|
||||
<>
|
||||
<div className="relative mx-auto mb-4 w-16 h-16">
|
||||
<Gift className="w-16 h-16 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-foreground mb-2">
|
||||
Welcome to Nomad Karaoke!
|
||||
</h1>
|
||||
<div className="bg-primary/10 border border-primary/20 rounded-lg p-4 mb-4">
|
||||
<p className="text-3xl font-bold text-primary">{creditsGranted}</p>
|
||||
<p className="text-sm font-medium text-primary/80">free credits to get started</p>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
Each credit creates one professional karaoke video.
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mb-6">
|
||||
These credits cost us real money to fulfil, so please use them wisely
|
||||
and let us know what you think!
|
||||
</p>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
Start Creating Karaoke
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits denied - friendly rejection interstitial */}
|
||||
{state === "credits_denied" && (
|
||||
<>
|
||||
<XCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Welcome to Nomad Karaoke
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
We weren't able to grant free credits this time.
|
||||
Karaoke generation costs us real money for every job,
|
||||
so we need to be careful about free credit distribution.
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
If you think this is a mistake, check your email — we've sent you
|
||||
details on how to reach out to get this resolved.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={goToBuy}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
<ShoppingCart className="w-4 h-4 mr-2" />
|
||||
Buy Credits
|
||||
</Button>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
>
|
||||
Go to Dashboard
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits pending review - friendly holding message */}
|
||||
{state === "credits_pending" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Welcome to Nomad Karaoke!
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
We weren't able to assign your free credits automatically this time.
|
||||
Our team will review your signup shortly and assign credits if we're able to.
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
You can still explore the app while you wait, or purchase credits
|
||||
to get started right away.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={goToBuy}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
<ShoppingCart className="w-4 h-4 mr-2" />
|
||||
Buy Credits
|
||||
</Button>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
>
|
||||
Explore the App
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Simple success (returning user) */}
|
||||
{state === "success" && (
|
||||
<>
|
||||
<CheckCircle className="w-12 h-12 text-success mx-auto mb-4" />
|
||||
@@ -90,19 +217,15 @@ function VerifyMagicLinkContent() {
|
||||
Successfully signed in!
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Welcome{user?.email ? `, ${user.email}` : ""}!
|
||||
Welcome back{user?.email ? `, ${user.email}` : ""}!
|
||||
</p>
|
||||
{creditsGranted > 0 && (
|
||||
<p className="text-sm font-medium text-primary mb-4">
|
||||
You received {creditsGranted} free credits to get started!
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Redirecting you to the app...
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{state === "error" && (
|
||||
<>
|
||||
<XCircle className="w-12 h-12 text-destructive mx-auto mb-4" />
|
||||
|
||||
@@ -67,6 +67,16 @@
|
||||
--input: var(--secondary);
|
||||
--ring: var(--primary);
|
||||
--radius: 0.5rem;
|
||||
|
||||
/* Sidebar colors (admin panel) */
|
||||
--sidebar: #1a1a1a;
|
||||
--sidebar-foreground: var(--text);
|
||||
--sidebar-primary: var(--primary);
|
||||
--sidebar-primary-foreground: #ffffff;
|
||||
--sidebar-accent: #252525;
|
||||
--sidebar-accent-foreground: var(--text);
|
||||
--sidebar-border: var(--card-border);
|
||||
--sidebar-ring: var(--primary);
|
||||
}
|
||||
|
||||
.light {
|
||||
@@ -98,6 +108,16 @@
|
||||
--muted-foreground: var(--text-muted);
|
||||
--border: var(--card-border);
|
||||
--input: var(--secondary);
|
||||
|
||||
/* Sidebar colors - light mode */
|
||||
--sidebar: #ffffff;
|
||||
--sidebar-foreground: var(--text);
|
||||
--sidebar-primary: var(--primary);
|
||||
--sidebar-primary-foreground: #ffffff;
|
||||
--sidebar-accent: #f1f5f9;
|
||||
--sidebar-accent-foreground: var(--text);
|
||||
--sidebar-border: var(--card-border);
|
||||
--sidebar-ring: var(--primary);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
@@ -126,6 +146,14 @@
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
BookOpenCheck,
|
||||
Scissors,
|
||||
Fingerprint,
|
||||
MessageSquare,
|
||||
} from "lucide-react"
|
||||
|
||||
import {
|
||||
@@ -71,6 +72,11 @@ const navItems = [
|
||||
href: "/admin/audio-edits",
|
||||
icon: Scissors,
|
||||
},
|
||||
{
|
||||
title: "Feedback",
|
||||
href: "/admin/feedback",
|
||||
icon: MessageSquare,
|
||||
},
|
||||
{
|
||||
title: "Abuse Investigation",
|
||||
href: "/admin/abuse",
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -2363,6 +2363,14 @@ export const adminApi = {
|
||||
},
|
||||
|
||||
// Anti-abuse investigation endpoints
|
||||
async getAbuseCorrelations(): Promise<AbuseCorrelationsResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/abuse/correlations`,
|
||||
{ headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getAbuseSuspicious(params?: { min_jobs?: number; max_spend?: number }): Promise<AbuseSuspiciousResponse> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.min_jobs) searchParams.set('min_jobs', String(params.min_jobs));
|
||||
@@ -2415,6 +2423,25 @@ export const adminApi = {
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async listFeedback(params?: {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
search?: string;
|
||||
exclude_test?: boolean;
|
||||
}): Promise<AdminFeedbackListResponse> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.limit) searchParams.set('limit', String(params.limit));
|
||||
if (params?.offset) searchParams.set('offset', String(params.offset));
|
||||
if (params?.search) searchParams.set('search', params.search);
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
|
||||
const url = `${API_BASE_URL}/api/admin/feedback${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
};
|
||||
|
||||
export interface EditReviewSummary {
|
||||
@@ -2980,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;
|
||||
@@ -3248,6 +3304,36 @@ export interface AbuseByFingerprintResponse {
|
||||
users: AbuseRelatedUser[];
|
||||
}
|
||||
|
||||
// Correlation cluster types
|
||||
export interface AbuseClusterUser {
|
||||
email: string;
|
||||
signup_ip: string | null;
|
||||
device_fingerprint: string | null;
|
||||
credits: number;
|
||||
total_jobs_created: number;
|
||||
total_jobs_completed: number;
|
||||
total_spent: number;
|
||||
created_at: string;
|
||||
user_agent?: string | null;
|
||||
}
|
||||
|
||||
export interface AbuseFingerprintCluster {
|
||||
fingerprint: string;
|
||||
count: number;
|
||||
users: AbuseClusterUser[];
|
||||
}
|
||||
|
||||
export interface AbuseIpCluster {
|
||||
ip: string;
|
||||
count: number;
|
||||
users: AbuseClusterUser[];
|
||||
}
|
||||
|
||||
export interface AbuseCorrelationsResponse {
|
||||
fingerprint_clusters: AbuseFingerprintCluster[];
|
||||
ip_clusters: AbuseIpCluster[];
|
||||
}
|
||||
|
||||
// IP geolocation types
|
||||
export interface IpGeoInfo {
|
||||
status: string;
|
||||
@@ -3264,5 +3350,33 @@ export interface IpGeoInfo {
|
||||
cached_at?: string;
|
||||
}
|
||||
|
||||
// Admin feedback types
|
||||
export interface AdminFeedbackItem {
|
||||
id: string;
|
||||
user_email: string;
|
||||
created_at: string | null;
|
||||
overall_rating: number;
|
||||
ease_of_use_rating: number;
|
||||
lyrics_accuracy_rating: number;
|
||||
correction_experience_rating: number;
|
||||
what_went_well: string | null;
|
||||
what_could_improve: string | null;
|
||||
additional_comments: string | null;
|
||||
would_recommend: boolean;
|
||||
would_use_again: boolean;
|
||||
}
|
||||
|
||||
export interface AdminFeedbackListResponse {
|
||||
items: AdminFeedbackItem[];
|
||||
total: number;
|
||||
offset: number;
|
||||
limit: number;
|
||||
has_more: boolean;
|
||||
avg_overall_rating: number | null;
|
||||
avg_ease_of_use_rating: number | null;
|
||||
avg_lyrics_accuracy_rating: number | null;
|
||||
avg_correction_experience_rating: number | null;
|
||||
}
|
||||
|
||||
export { ApiError };
|
||||
|
||||
@@ -81,6 +81,7 @@ export const useAuth = create<AuthStore>()(
|
||||
(window as any).__LAST_VERIFY_RESPONSE__ = {
|
||||
tenant_subdomain: response.tenant_subdomain,
|
||||
credits_granted: response.credits_granted || 0,
|
||||
credit_status: response.credit_status || "not_applicable",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ export interface VerifyMagicLinkResponse {
|
||||
message: string
|
||||
tenant_subdomain?: string | null
|
||||
credits_granted?: number
|
||||
credit_status?: string // "granted", "denied", "already_granted", "not_applicable"
|
||||
}
|
||||
|
||||
export interface UserProfileResponse {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "karaoke-gen-frontend",
|
||||
"version": "0.85.7",
|
||||
"version": "0.85.8",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "next build && node scripts/spa-redirect-404.js",
|
||||
|
||||
@@ -40,8 +40,10 @@ 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 gpu_artifact_registry
|
||||
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 ====================
|
||||
|
||||
@@ -54,6 +56,9 @@ bucket = storage_module.create_bucket()
|
||||
# Artifact Registry for Docker images
|
||||
artifact_repo = artifact_registry.create_repository()
|
||||
|
||||
# GPU Artifact Registry in us-east4 (for audio worker GPU images)
|
||||
gpu_artifact_repo = gpu_artifact_registry.create_gpu_artifact_repo()
|
||||
|
||||
# Secret Manager secrets
|
||||
all_secrets = secrets.create_secrets()
|
||||
|
||||
@@ -84,6 +89,15 @@ artifact_registry_iam = artifactregistry.RepositoryIamBinding(
|
||||
members=cloudbuild_service_accounts,
|
||||
)
|
||||
|
||||
# Grant Cloud Build access to GPU Artifact Registry (us-east4)
|
||||
gpu_artifact_registry_iam = artifactregistry.RepositoryIamBinding(
|
||||
"cloudbuild-gpu-artifact-registry-access",
|
||||
repository=gpu_artifact_repo.name,
|
||||
location=gpu_artifact_repo.location,
|
||||
role="roles/artifactregistry.writer",
|
||||
members=cloudbuild_service_accounts,
|
||||
)
|
||||
|
||||
# Grant Cloud Build compute service account logging permissions
|
||||
cloudbuild_logging_iam = gcp.projects.IAMMember(
|
||||
"cloudbuild-logging-access",
|
||||
@@ -392,19 +406,75 @@ 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()
|
||||
|
||||
# Grant audio separator read access to main storage bucket (for GCS URI passthrough)
|
||||
gcp.storage.BucketIAMMember(
|
||||
"audio-separator-storage-reader",
|
||||
bucket=bucket.name,
|
||||
role="roles/storage.objectViewer",
|
||||
member=audio_separator_resources["service_account"].email.apply(
|
||||
lambda email: f"serviceAccount:{email}"
|
||||
),
|
||||
)
|
||||
|
||||
# ==================== 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 +594,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 +626,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)
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
@@ -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 ==="
|
||||
@@ -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
|
||||
@@ -87,8 +87,12 @@ fi
|
||||
echo "Downloaded wheel as: ${WHEEL_NAME}"
|
||||
|
||||
# 4. Install the wheel
|
||||
# Use --no-deps because the encoding worker venv has runtime deps pre-installed.
|
||||
# The wheel only needs to update the karaoke-gen code itself.
|
||||
# Full dependency resolution on the complex dep graph (langchain, CUDA, etc.)
|
||||
# can hit pip's "resolution-too-deep" error and prevent the service from starting.
|
||||
echo "[4/5] Installing wheel..."
|
||||
"${VENV}/bin/pip" install --upgrade --quiet --force-reinstall "${WHEEL_PATH}"
|
||||
"${VENV}/bin/pip" install --upgrade --quiet --force-reinstall --no-deps "${WHEEL_PATH}"
|
||||
|
||||
# 5. Verify installed version
|
||||
echo "[5/5] Verifying installed version..."
|
||||
|
||||
@@ -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"
|
||||
@@ -311,7 +311,8 @@ def _get_instance_age_hours(instance: compute_v1.Instance) -> float:
|
||||
|
||||
def check_github_for_pending_jobs() -> bool:
|
||||
"""
|
||||
Check GitHub API for any pending/queued/in-progress workflow runs.
|
||||
Check GitHub API for any pending/queued/in-progress workflow runs
|
||||
across all org repos that use self-hosted runners.
|
||||
|
||||
Returns True if there are runs that might need our self-hosted runners.
|
||||
"""
|
||||
@@ -320,25 +321,29 @@ def check_github_for_pending_jobs() -> bool:
|
||||
pat = get_github_pat()
|
||||
org = "nomadkaraoke"
|
||||
|
||||
for status in ["queued", "in_progress"]:
|
||||
url = f"https://api.github.com/repos/{org}/karaoke-gen/actions/runs?status={status}"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {pat}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
)
|
||||
# All repos that have workflows using self-hosted runners
|
||||
repos = ["karaoke-gen", "python-audio-separator"]
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
if data.get("total_count", 0) > 0:
|
||||
print(f"Found {data['total_count']} {status} runs in karaoke-gen")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error checking GitHub API ({status}): {e}")
|
||||
for repo in repos:
|
||||
for status in ["queued", "in_progress"]:
|
||||
url = f"https://api.github.com/repos/{org}/{repo}/actions/runs?status={status}"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {pat}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
if data.get("total_count", 0) > 0:
|
||||
print(f"Found {data['total_count']} {status} runs in {repo}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error checking GitHub API ({repo}/{status}): {e}")
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@@ -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(
|
||||
@@ -56,6 +43,26 @@ def create_service_account() -> serviceaccount.Account:
|
||||
)
|
||||
|
||||
|
||||
def create_output_bucket() -> gcp.storage.Bucket:
|
||||
"""Create GCS bucket for separation output files with auto-cleanup."""
|
||||
bucket = gcp.storage.Bucket(
|
||||
"audio-separator-output-bucket",
|
||||
name="nomadkaraoke-audio-separator-outputs",
|
||||
location="US",
|
||||
force_destroy=True,
|
||||
uniform_bucket_level_access=True,
|
||||
lifecycle_rules=[
|
||||
gcp.storage.BucketLifecycleRuleArgs(
|
||||
action=gcp.storage.BucketLifecycleRuleActionArgs(type="Delete"),
|
||||
condition=gcp.storage.BucketLifecycleRuleConditionArgs(
|
||||
age=1, # Delete after 1 day (minimum GCS lifecycle granularity)
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
return bucket
|
||||
|
||||
|
||||
def grant_permissions(
|
||||
sa: serviceaccount.Account,
|
||||
) -> dict:
|
||||
@@ -86,6 +93,14 @@ def grant_permissions(
|
||||
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Read/write Firestore for async job status
|
||||
bindings["firestore"] = gcp.projects.IAMMember(
|
||||
"audio-separator-firestore-access",
|
||||
project=PROJECT_ID,
|
||||
role="roles/datastore.user",
|
||||
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
return bindings
|
||||
|
||||
|
||||
@@ -107,8 +122,9 @@ def create_service(
|
||||
template=cloudrunv2.ServiceTemplateArgs(
|
||||
scaling=cloudrunv2.ServiceTemplateScalingArgs(
|
||||
min_instance_count=0,
|
||||
max_instance_count=1, # GPU zonal redundancy requires quota for >1
|
||||
max_instance_count=5, # Cloud Run GPU services limited to 5 max instances
|
||||
),
|
||||
max_instance_request_concurrency=1, # One GPU job per instance; forces Cloud Run to scale to new instances for concurrent jobs
|
||||
gpu_zonal_redundancy_disabled=True, # Not needed for batch workloads
|
||||
# Keep instances warm for 600s (10 min) between Stage 1 → Stage 2
|
||||
session_affinity=True,
|
||||
@@ -140,6 +156,14 @@ def create_service(
|
||||
name="STORAGE_DIR",
|
||||
value="/tmp/storage",
|
||||
),
|
||||
cloudrunv2.ServiceTemplateContainerEnvArgs(
|
||||
name="OUTPUT_BUCKET",
|
||||
value="nomadkaraoke-audio-separator-outputs",
|
||||
),
|
||||
cloudrunv2.ServiceTemplateContainerEnvArgs(
|
||||
name="GCP_PROJECT",
|
||||
value=PROJECT_ID,
|
||||
),
|
||||
],
|
||||
startup_probe=cloudrunv2.ServiceTemplateContainerStartupProbeArgs(
|
||||
http_get=cloudrunv2.ServiceTemplateContainerStartupProbeHttpGetArgs(
|
||||
@@ -197,13 +221,24 @@ def create_all_resources() -> dict:
|
||||
"""
|
||||
artifact_repo = create_audio_separator_artifact_repo()
|
||||
sa = create_service_account()
|
||||
output_bucket = create_output_bucket()
|
||||
iam_bindings = grant_permissions(sa)
|
||||
|
||||
# Output bucket IAM (separate from grant_permissions since it needs the bucket)
|
||||
output_bucket_iam = gcp.storage.BucketIAMMember(
|
||||
"audio-separator-output-bucket-access",
|
||||
bucket=output_bucket.name,
|
||||
role="roles/storage.objectAdmin",
|
||||
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
service = create_service(sa, artifact_repo)
|
||||
unauthenticated_access = allow_unauthenticated_access(service)
|
||||
|
||||
return {
|
||||
"artifact_repo": artifact_repo,
|
||||
"service_account": sa,
|
||||
"output_bucket": output_bucket,
|
||||
"service": service,
|
||||
"iam_bindings": iam_bindings,
|
||||
}
|
||||
+201
-192
@@ -10,6 +10,8 @@ from pulumi_gcp import cloudrun, cloudrunv2
|
||||
|
||||
from config import PROJECT_ID, REGION
|
||||
|
||||
AUDIO_WORKER_GPU_REGION = "us-east4" # L4 GPU quota available here
|
||||
|
||||
|
||||
def create_domain_mapping() -> cloudrun.DomainMapping:
|
||||
"""
|
||||
@@ -70,22 +72,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 +92,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 +102,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",
|
||||
),
|
||||
),
|
||||
@@ -165,13 +167,14 @@ def create_audio_separation_job(
|
||||
service_account: gcp.serviceaccount.Account,
|
||||
) -> cloudrunv2.Job:
|
||||
"""
|
||||
Create the Cloud Run Job for audio separation.
|
||||
Create the Cloud Run Job for audio separation with L4 GPU.
|
||||
|
||||
Cloud Run Jobs run to completion without HTTP request lifecycle concerns,
|
||||
avoiding the instance termination issue where Cloud Run would shut down
|
||||
instances mid-processing when using BackgroundTasks.
|
||||
Runs the Separator class directly with GPU acceleration, eliminating
|
||||
the HTTP call to the separate audio-separator service.
|
||||
|
||||
Typical duration: 10-20 minutes (Modal API for GPU separation)
|
||||
Deployed in us-east4 where L4 GPU quota is available.
|
||||
|
||||
Typical duration: 5-10 minutes (local GPU separation)
|
||||
|
||||
Args:
|
||||
bucket: The GCS bucket for job artifacts.
|
||||
@@ -183,41 +186,36 @@ def create_audio_separation_job(
|
||||
audio_separation_job = cloudrunv2.Job(
|
||||
"audio-separation-job",
|
||||
name="audio-separation-job",
|
||||
location=REGION,
|
||||
location=AUDIO_WORKER_GPU_REGION,
|
||||
deletion_protection=False, # Allow Pulumi to replace (region change requires delete+create)
|
||||
template=cloudrunv2.JobTemplateArgs(
|
||||
template=cloudrunv2.JobTemplateTemplateArgs(
|
||||
containers=[
|
||||
cloudrunv2.JobTemplateTemplateContainerArgs(
|
||||
image=f"{REGION}-docker.pkg.dev/{PROJECT_ID}/karaoke-repo/karaoke-backend:latest",
|
||||
image=f"{AUDIO_WORKER_GPU_REGION}-docker.pkg.dev/{PROJECT_ID}/karaoke-backend-gpu/karaoke-backend:latest",
|
||||
args=["python", "-m", "backend.workers.audio_worker"],
|
||||
resources=cloudrunv2.JobTemplateTemplateContainerResourcesArgs(
|
||||
limits={
|
||||
"cpu": "2",
|
||||
"memory": "4Gi",
|
||||
"cpu": "4",
|
||||
"memory": "16Gi",
|
||||
"nvidia.com/gpu": "1",
|
||||
},
|
||||
),
|
||||
envs=[
|
||||
# Basic configuration
|
||||
# Admin token for Cloud Tasks auth header
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GOOGLE_CLOUD_PROJECT",
|
||||
value=PROJECT_ID,
|
||||
name="ADMIN_TOKENS",
|
||||
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
|
||||
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
|
||||
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
|
||||
version="latest",
|
||||
),
|
||||
),
|
||||
),
|
||||
# Model directory (baked into GPU image, triggers local GPU mode)
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GCS_BUCKET_NAME",
|
||||
value=bucket.name,
|
||||
),
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="ENVIRONMENT",
|
||||
value="production",
|
||||
),
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GCP_REGION",
|
||||
value=REGION,
|
||||
),
|
||||
# Audio separator API (Cloud Run GPU service in us-east4)
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="AUDIO_SEPARATOR_API_URL",
|
||||
value="https://audio-separator-718638054799.us-east4.run.app",
|
||||
name="MODEL_DIR",
|
||||
value="/models",
|
||||
),
|
||||
# Cloud Run service URL for Cloud Tasks targeting
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
@@ -229,21 +227,32 @@ 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=AUDIO_WORKER_GPU_REGION,
|
||||
),
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GCS_BUCKET_NAME",
|
||||
value=bucket.name,
|
||||
),
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GOOGLE_CLOUD_PROJECT",
|
||||
value=PROJECT_ID,
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
node_selector=cloudrunv2.JobTemplateTemplateNodeSelectorArgs(
|
||||
accelerator="nvidia-l4",
|
||||
),
|
||||
gpu_zonal_redundancy_disabled=True, # Required for GPU Jobs (capacity limitation)
|
||||
service_account=service_account.email,
|
||||
timeout="2400s", # 40 minutes max per task (Modal can be slow)
|
||||
timeout="1800s", # 30 minutes (local GPU is faster than remote API)
|
||||
max_retries=2,
|
||||
),
|
||||
),
|
||||
@@ -300,39 +309,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 +329,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 +419,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 +434,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 +519,10 @@ def create_video_encoding_job(
|
||||
),
|
||||
),
|
||||
),
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="USE_GCE_ENCODING",
|
||||
value="true",
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
|
||||
@@ -222,6 +222,19 @@ def create_database() -> dict:
|
||||
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
|
||||
)
|
||||
|
||||
# Audio separation jobs: query by status + updated_at (for cleanup of old jobs)
|
||||
resources["firestore_index_audio_separation_jobs_cleanup"] = firestore.Index(
|
||||
"firestore-index-audio-separation-jobs-cleanup",
|
||||
project=PROJECT_ID,
|
||||
database=firestore_db.name,
|
||||
collection="audio_separation_jobs",
|
||||
fields=[
|
||||
firestore.IndexFieldArgs(field_path="status", order="ASCENDING"),
|
||||
firestore.IndexFieldArgs(field_path="updated_at", order="ASCENDING"),
|
||||
],
|
||||
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
|
||||
)
|
||||
|
||||
# ==================== Firestore TTL Field Configuration ====================
|
||||
# TTL policies automatically delete documents after expiration.
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
Artifact Registry for GPU Docker images.
|
||||
|
||||
Located in us-east4 (co-located with L4 GPU instances).
|
||||
Stores the karaoke-backend-gpu base image used by the audio worker.
|
||||
"""
|
||||
|
||||
import pulumi_gcp as gcp
|
||||
from pulumi_gcp import artifactregistry
|
||||
|
||||
from config import PROJECT_ID
|
||||
|
||||
GPU_REGION = "us-east4"
|
||||
|
||||
|
||||
def create_gpu_artifact_repo() -> artifactregistry.Repository:
|
||||
"""Create Artifact Registry repo for GPU Docker images in us-east4."""
|
||||
return artifactregistry.Repository(
|
||||
"karaoke-backend-gpu-artifact-repo",
|
||||
repository_id="karaoke-backend-gpu",
|
||||
location=GPU_REGION,
|
||||
format="DOCKER",
|
||||
description="Docker repository for GPU-enabled karaoke-backend images (audio worker)",
|
||||
)
|
||||
@@ -185,6 +185,9 @@ def grant_github_actions_permissions(
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/karaoke-decide"
|
||||
),
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/python-audio-separator"
|
||||
),
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/beveradb/cryptotrader"
|
||||
),
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
+123
-34
@@ -20,6 +20,14 @@ except ImportError:
|
||||
REMOTE_API_AVAILABLE = False
|
||||
AudioSeparatorAPIClient = None
|
||||
|
||||
# Try to import the Separator for local GPU processing
|
||||
try:
|
||||
from audio_separator.separator import Separator
|
||||
SEPARATOR_AVAILABLE = True
|
||||
except ImportError:
|
||||
SEPARATOR_AVAILABLE = False
|
||||
Separator = None
|
||||
|
||||
|
||||
# Placeholder class or functions for audio processing
|
||||
class AudioProcessor:
|
||||
@@ -116,8 +124,6 @@ class AudioProcessor:
|
||||
f"instantiating Separator with model_file_dir: {self.model_file_dir}, model_filename: {model_name} output_format: {self.lossless_output_format}"
|
||||
)
|
||||
|
||||
from audio_separator.separator import Separator
|
||||
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
@@ -179,21 +185,29 @@ class AudioProcessor:
|
||||
return self._process_audio_separation_remote(audio_file, artist_title, track_output_dir, remote_api_url)
|
||||
except Exception as e:
|
||||
error_str = str(e)
|
||||
# Don't fall back for download failures - these indicate API issues that should be fixed
|
||||
if ("no files were downloaded" in error_str or
|
||||
"failed to produce essential" in error_str):
|
||||
self.logger.error(f"Remote API processing failed with download/file organization issue: {error_str}")
|
||||
self.logger.error("This indicates an audio-separator API issue that should be fixed. Not falling back to local processing.")
|
||||
raise e
|
||||
else:
|
||||
# Fall back for other types of errors (network issues, etc.)
|
||||
self.logger.error(f"Remote API processing failed: {error_str}")
|
||||
self.logger.info("Falling back to local audio separation")
|
||||
self.logger.error(f"Remote API processing failed: {error_str}")
|
||||
# Never fall back for API processing errors (download failures,
|
||||
# missing files, etc.) — retrying locally won't help.
|
||||
# Only fall back for transient network errors AND only when
|
||||
# local processing is possible (model_file_dir is configured).
|
||||
is_api_error = (
|
||||
"no files were downloaded" in error_str
|
||||
or "failed to produce essential" in error_str
|
||||
or "missing" in error_str.lower()
|
||||
)
|
||||
if is_api_error or not self.model_file_dir:
|
||||
if not self.model_file_dir:
|
||||
self.logger.error("No local model directory configured — cannot fall back to local processing.")
|
||||
raise
|
||||
self.logger.info("Falling back to local audio separation")
|
||||
else:
|
||||
self.logger.info("AUDIO_SEPARATOR_API_URL not set, using local audio separation. "
|
||||
"Set this environment variable to use remote GPU processing.")
|
||||
|
||||
from audio_separator.separator import Separator
|
||||
if not SEPARATOR_AVAILABLE:
|
||||
raise ImportError(
|
||||
"audio-separator package not installed. Install with: pip install audio-separator[gpu]"
|
||||
)
|
||||
|
||||
self.logger.info(f"Starting local audio separation process for {artist_title}")
|
||||
|
||||
@@ -266,29 +280,95 @@ class AudioProcessor:
|
||||
continue
|
||||
|
||||
try:
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.lossless_output_format,
|
||||
)
|
||||
|
||||
stems_dir = self._create_stems_directory(track_output_dir)
|
||||
result = {"clean_instrumental": {}, "other_stems": {}, "backing_vocals": {}, "combined_instrumentals": {}}
|
||||
|
||||
if os.environ.get("KARAOKE_GEN_SKIP_AUDIO_SEPARATION"):
|
||||
return result
|
||||
|
||||
result["clean_instrumental"] = self._separate_clean_instrumental(
|
||||
separator, audio_file, artist_title, track_output_dir, stems_dir
|
||||
)
|
||||
result["other_stems"] = self._separate_other_stems(separator, audio_file, artist_title, stems_dir)
|
||||
result["backing_vocals"] = self._separate_backing_vocals(
|
||||
separator, result["clean_instrumental"]["vocals"], artist_title, stems_dir
|
||||
)
|
||||
result["combined_instrumentals"] = self._generate_combined_instrumentals(
|
||||
result["clean_instrumental"]["instrumental"], result["backing_vocals"], artist_title, track_output_dir
|
||||
)
|
||||
# Check if we have ensemble presets configured
|
||||
instrumental_preset = getattr(self, 'instrumental_preset', None)
|
||||
karaoke_preset = getattr(self, 'karaoke_preset', None)
|
||||
|
||||
if instrumental_preset:
|
||||
# Stage 1: Ensemble preset mode — higher quality, uses multiple models
|
||||
self.logger.info(f"Stage 1: Using ensemble preset '{instrumental_preset}'")
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.lossless_output_format,
|
||||
output_dir=stems_dir,
|
||||
ensemble_preset=instrumental_preset,
|
||||
)
|
||||
separator.load_model()
|
||||
output_files = separator.separate(audio_file)
|
||||
self.logger.info(f"Stage 1 ensemble produced {len(output_files)} files: {output_files}")
|
||||
|
||||
# Find vocals and instrumental from ensemble output
|
||||
# Output filenames follow: {base}_(Vocals)_preset_{name}.flac
|
||||
# Check instrumental/no_vocal first to avoid substring false match
|
||||
for f in output_files:
|
||||
basename = os.path.basename(f).lower()
|
||||
if "no_vocal" in basename or "instrumental" in basename:
|
||||
# Move instrumental to track_output_dir per convention
|
||||
final_path = os.path.join(track_output_dir, os.path.basename(f))
|
||||
if f != final_path:
|
||||
shutil.move(f, final_path)
|
||||
result["clean_instrumental"]["instrumental"] = final_path
|
||||
elif "vocal" in basename:
|
||||
result["clean_instrumental"]["vocals"] = f
|
||||
else:
|
||||
# Legacy mode — individual model calls (existing code)
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.lossless_output_format,
|
||||
)
|
||||
result["clean_instrumental"] = self._separate_clean_instrumental(
|
||||
separator, audio_file, artist_title, track_output_dir, stems_dir
|
||||
)
|
||||
result["other_stems"] = self._separate_other_stems(separator, audio_file, artist_title, stems_dir)
|
||||
|
||||
# Stage 2: Backing vocals separation
|
||||
vocals_path = result["clean_instrumental"].get("vocals")
|
||||
has_backing_config = karaoke_preset or self.backing_vocals_models
|
||||
|
||||
if vocals_path and has_backing_config:
|
||||
if karaoke_preset:
|
||||
self.logger.info(f"Stage 2: Using ensemble preset '{karaoke_preset}'")
|
||||
bv_separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.lossless_output_format,
|
||||
output_dir=stems_dir,
|
||||
ensemble_preset=karaoke_preset,
|
||||
)
|
||||
bv_separator.load_model()
|
||||
bv_output_files = bv_separator.separate(vocals_path)
|
||||
self.logger.info(f"Stage 2 ensemble produced {len(bv_output_files)} files: {bv_output_files}")
|
||||
|
||||
bv_key = karaoke_preset
|
||||
result["backing_vocals"][bv_key] = {}
|
||||
for f in bv_output_files:
|
||||
basename = os.path.basename(f).lower()
|
||||
if "instrumental" in basename or "backing" in basename or "no_vocal" in basename:
|
||||
result["backing_vocals"][bv_key]["backing_vocals"] = f
|
||||
elif "vocal" in basename:
|
||||
result["backing_vocals"][bv_key]["lead_vocals"] = f
|
||||
else:
|
||||
# Legacy: individual model calls (existing code)
|
||||
result["backing_vocals"] = self._separate_backing_vocals(
|
||||
separator, vocals_path, artist_title, stems_dir
|
||||
)
|
||||
|
||||
# Combined instrumentals + normalization
|
||||
if result["clean_instrumental"].get("instrumental") and result["backing_vocals"]:
|
||||
result["combined_instrumentals"] = self._generate_combined_instrumentals(
|
||||
result["clean_instrumental"]["instrumental"], result["backing_vocals"], artist_title, track_output_dir
|
||||
)
|
||||
self._normalize_audio_files(result, artist_title, track_output_dir)
|
||||
|
||||
self.logger.info("Audio separation, combination, and normalization process completed")
|
||||
@@ -343,10 +423,19 @@ class AudioProcessor:
|
||||
self.logger.info(f"Stage 1: Using explicit models: {stage1_models}")
|
||||
stage1_kwargs["models"] = stage1_models
|
||||
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
audio_file,
|
||||
**stage1_kwargs,
|
||||
)
|
||||
# Use GCS URI for Stage 1 if available (avoids 413 for large files)
|
||||
input_gcs_uri = getattr(self, 'input_gcs_uri', None)
|
||||
if input_gcs_uri:
|
||||
self.logger.info(f"Stage 1: Using GCS URI: {input_gcs_uri}")
|
||||
stage1_kwargs["gcs_uri"] = input_gcs_uri
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
**stage1_kwargs,
|
||||
)
|
||||
else:
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
audio_file,
|
||||
**stage1_kwargs,
|
||||
)
|
||||
|
||||
if stage1_result["status"] != "completed":
|
||||
raise Exception(f"Stage 1 remote audio separation failed: {stage1_result.get('error', 'Unknown error')}")
|
||||
|
||||
@@ -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
+81
-84
@@ -350,14 +350,14 @@ files = [
|
||||
|
||||
[[package]]
|
||||
name = "audio-separator"
|
||||
version = "0.43.0"
|
||||
version = "0.44.1"
|
||||
description = "Easy to use audio stem separation, using various models from UVR trained primarily by @Anjok07"
|
||||
optional = false
|
||||
python-versions = ">=3.10"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "audio_separator-0.43.0-py3-none-any.whl", hash = "sha256:7315f26fd0715e5cb3ddd02532565f2b63f77f208391463ad6bccd7cf4583454"},
|
||||
{file = "audio_separator-0.43.0.tar.gz", hash = "sha256:4628c2f1c43fc2d17a93e5451921bd6f5f720791d2bbf4bb6b70bda7114ac633"},
|
||||
{file = "audio_separator-0.44.1-py3-none-any.whl", hash = "sha256:6d9d3f570dceba16dd49116cf72a9764225e5aebb48ab117796bb79c8e1be4cd"},
|
||||
{file = "audio_separator-0.44.1.tar.gz", hash = "sha256:505c78c205ce2e6af27a7e73c1b4a59b0cc7c834a2abdd93b3f5cdaf8f3cb26f"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
@@ -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]
|
||||
@@ -2946,20 +2957,20 @@ protobuf = ["grpcio-tools (>=1.76.0)"]
|
||||
|
||||
[[package]]
|
||||
name = "grpcio-status"
|
||||
version = "1.76.0"
|
||||
version = "1.71.2"
|
||||
description = "Status proto mapping for gRPC"
|
||||
optional = false
|
||||
python-versions = ">=3.9"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "grpcio_status-1.76.0-py3-none-any.whl", hash = "sha256:380568794055a8efbbd8871162df92012e0228a5f6dffaf57f2a00c534103b18"},
|
||||
{file = "grpcio_status-1.76.0.tar.gz", hash = "sha256:25fcbfec74c15d1a1cb5da3fab8ee9672852dc16a5a9eeb5baf7d7a9952943cd"},
|
||||
{file = "grpcio_status-1.71.2-py3-none-any.whl", hash = "sha256:803c98cb6a8b7dc6dbb785b1111aed739f241ab5e9da0bba96888aa74704cfd3"},
|
||||
{file = "grpcio_status-1.71.2.tar.gz", hash = "sha256:c7a97e176df71cdc2c179cd1847d7fc86cca5832ad12e9798d7fed6b7a1aab50"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
googleapis-common-protos = ">=1.5.5"
|
||||
grpcio = ">=1.76.0"
|
||||
protobuf = ">=6.31.1,<7.0.0"
|
||||
grpcio = ">=1.71.2"
|
||||
protobuf = ">=5.26.1,<6.0dev"
|
||||
|
||||
[[package]]
|
||||
name = "h11"
|
||||
@@ -6748,22 +6759,23 @@ testing = ["google-api-core (>=1.31.5)"]
|
||||
|
||||
[[package]]
|
||||
name = "protobuf"
|
||||
version = "6.33.2"
|
||||
version = "5.29.6"
|
||||
description = ""
|
||||
optional = false
|
||||
python-versions = ">=3.9"
|
||||
python-versions = ">=3.8"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "protobuf-6.33.2-cp310-abi3-win32.whl", hash = "sha256:87eb388bd2d0f78febd8f4c8779c79247b26a5befad525008e49a6955787ff3d"},
|
||||
{file = "protobuf-6.33.2-cp310-abi3-win_amd64.whl", hash = "sha256:fc2a0e8b05b180e5fc0dd1559fe8ebdae21a27e81ac77728fb6c42b12c7419b4"},
|
||||
{file = "protobuf-6.33.2-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:d9b19771ca75935b3a4422957bc518b0cecb978b31d1dd12037b088f6bcc0e43"},
|
||||
{file = "protobuf-6.33.2-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:b5d3b5625192214066d99b2b605f5783483575656784de223f00a8d00754fc0e"},
|
||||
{file = "protobuf-6.33.2-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:8cd7640aee0b7828b6d03ae518b5b4806fdfc1afe8de82f79c3454f8aef29872"},
|
||||
{file = "protobuf-6.33.2-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:1f8017c48c07ec5859106533b682260ba3d7c5567b1ca1f24297ce03384d1b4f"},
|
||||
{file = "protobuf-6.33.2-cp39-cp39-win32.whl", hash = "sha256:7109dcc38a680d033ffb8bf896727423528db9163be1b6a02d6a49606dcadbfe"},
|
||||
{file = "protobuf-6.33.2-cp39-cp39-win_amd64.whl", hash = "sha256:2981c58f582f44b6b13173e12bb8656711189c2a70250845f264b877f00b1913"},
|
||||
{file = "protobuf-6.33.2-py3-none-any.whl", hash = "sha256:7636aad9bb01768870266de5dc009de2d1b936771b38a793f73cbbf279c91c5c"},
|
||||
{file = "protobuf-6.33.2.tar.gz", hash = "sha256:56dc370c91fbb8ac85bc13582c9e373569668a290aa2e66a590c2a0d35ddb9e4"},
|
||||
{file = "protobuf-5.29.6-cp310-abi3-win32.whl", hash = "sha256:62e8a3114992c7c647bce37dcc93647575fc52d50e48de30c6fcb28a6a291eb1"},
|
||||
{file = "protobuf-5.29.6-cp310-abi3-win_amd64.whl", hash = "sha256:7e6ad413275be172f67fdee0f43484b6de5a904cc1c3ea9804cb6fe2ff366eda"},
|
||||
{file = "protobuf-5.29.6-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:b5a169e664b4057183a34bdc424540e86eea47560f3c123a0d64de4e137f9269"},
|
||||
{file = "protobuf-5.29.6-cp38-abi3-manylinux2014_aarch64.whl", hash = "sha256:a8866b2cff111f0f863c1b3b9e7572dc7eaea23a7fae27f6fc613304046483e6"},
|
||||
{file = "protobuf-5.29.6-cp38-abi3-manylinux2014_x86_64.whl", hash = "sha256:e3387f44798ac1106af0233c04fb8abf543772ff241169946f698b3a9a3d3ab9"},
|
||||
{file = "protobuf-5.29.6-cp38-cp38-win32.whl", hash = "sha256:36ade6ff88212e91aef4e687a971a11d7d24d6948a66751abc1b3238648f5d05"},
|
||||
{file = "protobuf-5.29.6-cp38-cp38-win_amd64.whl", hash = "sha256:831e2da16b6cc9d8f1654c041dd594eda43391affd3c03a91bea7f7f6da106d6"},
|
||||
{file = "protobuf-5.29.6-cp39-cp39-win32.whl", hash = "sha256:cb4c86de9cd8a7f3a256b9744220d87b847371c6b2f10bde87768918ef33ba49"},
|
||||
{file = "protobuf-5.29.6-cp39-cp39-win_amd64.whl", hash = "sha256:76e07e6567f8baf827137e8d5b8204b6c7b6488bbbff1bf0a72b383f77999c18"},
|
||||
{file = "protobuf-5.29.6-py3-none-any.whl", hash = "sha256:6b9edb641441b2da9fa8f428760fc136a49cf97a52076010cf22a2ff73438a86"},
|
||||
{file = "protobuf-5.29.6.tar.gz", hash = "sha256:da9ee6a5424b6b30fd5e45c5ea663aef540ca95f9ad99d1e887e819cdf9b8723"},
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7872,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"
|
||||
@@ -10705,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
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.148.3"
|
||||
version = "0.153.2"
|
||||
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
|
||||
|
||||
Executable
+69
@@ -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()
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import shutil
|
||||
import pytest
|
||||
import glob
|
||||
import json
|
||||
@@ -8,7 +9,6 @@ import datetime as dt # Use alias to avoid conflict
|
||||
import fcntl
|
||||
from pydub import AudioSegment
|
||||
from karaoke_gen.karaoke_gen import KaraokePrep
|
||||
from audio_separator.separator import Separator # Keep for patching target
|
||||
|
||||
class TestAudio:
|
||||
def test_separate_audio(self, basic_karaoke_gen, temp_dir):
|
||||
@@ -34,7 +34,7 @@ class TestAudio:
|
||||
]
|
||||
|
||||
# Mock dependencies
|
||||
with patch('audio_separator.separator.Separator', return_value=mock_separator), \
|
||||
with patch('karaoke_gen.audio_processor.Separator', return_value=mock_separator), \
|
||||
patch('os.rename') as mock_rename:
|
||||
|
||||
# Call the method
|
||||
@@ -130,7 +130,7 @@ class TestAudio:
|
||||
]
|
||||
|
||||
# Mock dependencies
|
||||
with patch('audio_separator.separator.Separator', return_value=mock_separator), \
|
||||
with patch('karaoke_gen.audio_processor.Separator', return_value=mock_separator), \
|
||||
patch('os.rename') as mock_rename, \
|
||||
patch('os.path.exists', return_value=True), \
|
||||
patch('os.getpid', return_value=12345), \
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import os
|
||||
import logging
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
|
||||
from backend.workers.audio_worker import create_audio_processor, process_audio_separation
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
|
||||
|
||||
class TestCreateAudioProcessorLocalGPU:
|
||||
"""Tests for create_audio_processor with local GPU (model_file_dir set)."""
|
||||
|
||||
def test_model_file_dir_passed_through(self):
|
||||
"""When model_file_dir is provided, AudioProcessor gets it for local separation."""
|
||||
processor = create_audio_processor(
|
||||
temp_dir="/tmp/test",
|
||||
model_file_dir="/models",
|
||||
)
|
||||
assert processor.model_file_dir == "/models"
|
||||
|
||||
def test_model_file_dir_none_by_default(self):
|
||||
"""When model_file_dir is not provided, AudioProcessor gets None (remote mode)."""
|
||||
processor = create_audio_processor(
|
||||
temp_dir="/tmp/test",
|
||||
)
|
||||
assert processor.model_file_dir is None
|
||||
|
||||
def test_presets_set_by_default(self):
|
||||
"""Ensemble presets are always set on the processor."""
|
||||
processor = create_audio_processor(
|
||||
temp_dir="/tmp/test",
|
||||
model_file_dir="/models",
|
||||
)
|
||||
assert processor.instrumental_preset == "instrumental_clean"
|
||||
assert processor.karaoke_preset == "karaoke"
|
||||
|
||||
def test_custom_presets_override_defaults(self):
|
||||
"""Custom presets override the defaults."""
|
||||
processor = create_audio_processor(
|
||||
temp_dir="/tmp/test",
|
||||
model_file_dir="/models",
|
||||
instrumental_preset="instrumental_full",
|
||||
karaoke_preset="vocal_clean",
|
||||
)
|
||||
assert processor.instrumental_preset == "instrumental_full"
|
||||
assert processor.karaoke_preset == "vocal_clean"
|
||||
|
||||
|
||||
class TestProcessAudioSeparationMode:
|
||||
"""Tests for separation mode selection (remote API vs local GPU)."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.worker_registry")
|
||||
@patch("backend.workers.audio_worker.setup_job_logging")
|
||||
@patch("backend.workers.audio_worker.create_job_logger")
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
@patch("backend.workers.audio_worker.StorageService")
|
||||
@patch("backend.workers.audio_worker.get_settings")
|
||||
@patch("backend.workers.audio_worker.validate_worker_can_run", return_value=None)
|
||||
@patch("backend.workers.audio_worker.download_audio")
|
||||
@patch("backend.workers.audio_worker._store_audio_source_metadata")
|
||||
@patch("backend.workers.audio_worker.create_audio_processor")
|
||||
@patch("backend.workers.audio_worker.upload_separation_results", new_callable=AsyncMock)
|
||||
async def test_model_dir_enables_local_gpu(
|
||||
self,
|
||||
mock_upload,
|
||||
mock_create_processor,
|
||||
mock_store_metadata,
|
||||
mock_download,
|
||||
mock_validate,
|
||||
mock_settings,
|
||||
mock_storage,
|
||||
mock_job_manager_cls,
|
||||
mock_create_logger,
|
||||
mock_setup_logging,
|
||||
mock_registry,
|
||||
):
|
||||
"""When MODEL_DIR is set and AUDIO_SEPARATOR_API_URL is not, uses local GPU."""
|
||||
# Make async methods on the registry work properly
|
||||
mock_registry.register = AsyncMock()
|
||||
mock_registry.unregister = AsyncMock()
|
||||
|
||||
# Set up environment
|
||||
env = {k: v for k, v in os.environ.items()}
|
||||
env.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
env["MODEL_DIR"] = "/models"
|
||||
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
# Set up mocks
|
||||
mock_job = MagicMock()
|
||||
mock_job.artist = "Test"
|
||||
mock_job.title = "Song"
|
||||
mock_job.url = None
|
||||
mock_job.input_media_gcs_path = "audio/test.wav"
|
||||
mock_job.clean_instrumental_model = None
|
||||
mock_job.backing_vocals_models = None
|
||||
mock_job.other_stems_models = None
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_job_manager_cls.return_value = mock_jm
|
||||
|
||||
mock_settings_obj = MagicMock()
|
||||
mock_settings_obj.gcs_bucket_name = "test-bucket"
|
||||
mock_settings.return_value = mock_settings_obj
|
||||
|
||||
mock_download.return_value = "/tmp/test.wav"
|
||||
mock_create_logger.return_value = MagicMock()
|
||||
|
||||
mock_processor = MagicMock()
|
||||
mock_processor.process_audio_separation.return_value = {
|
||||
"clean_instrumental": {"vocals": "/tmp/v.flac", "instrumental": "/tmp/i.flac"},
|
||||
"other_stems": {},
|
||||
"backing_vocals": {},
|
||||
"combined_instrumentals": {},
|
||||
}
|
||||
mock_create_processor.return_value = mock_processor
|
||||
|
||||
result = await process_audio_separation("test-job-id")
|
||||
|
||||
assert result is True
|
||||
# Verify model_file_dir="/models" was passed
|
||||
mock_create_processor.assert_called_once()
|
||||
call_kwargs = mock_create_processor.call_args[1]
|
||||
assert call_kwargs.get("model_file_dir") == "/models"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.worker_registry")
|
||||
@patch("backend.workers.audio_worker.setup_job_logging")
|
||||
@patch("backend.workers.audio_worker.create_job_logger")
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
@patch("backend.workers.audio_worker.StorageService")
|
||||
@patch("backend.workers.audio_worker.get_settings")
|
||||
@patch("backend.workers.audio_worker.validate_worker_can_run", return_value=None)
|
||||
async def test_no_api_url_no_model_dir_raises(
|
||||
self,
|
||||
mock_validate,
|
||||
mock_settings,
|
||||
mock_storage,
|
||||
mock_job_manager_cls,
|
||||
mock_create_logger,
|
||||
mock_setup_logging,
|
||||
mock_registry,
|
||||
):
|
||||
"""When neither AUDIO_SEPARATOR_API_URL nor MODEL_DIR is set, raises error."""
|
||||
# Make async methods on the registry work properly
|
||||
mock_registry.register = AsyncMock()
|
||||
mock_registry.unregister = AsyncMock()
|
||||
|
||||
env = {k: v for k, v in os.environ.items()}
|
||||
env.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
env.pop("MODEL_DIR", None)
|
||||
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
mock_job = MagicMock()
|
||||
mock_job.artist = "Test"
|
||||
mock_job.title = "Song"
|
||||
mock_job.url = None
|
||||
mock_job.input_media_gcs_path = "audio/test.wav"
|
||||
mock_job.clean_instrumental_model = None
|
||||
mock_job.backing_vocals_models = None
|
||||
mock_job.other_stems_models = None
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_job_manager_cls.return_value = mock_jm
|
||||
|
||||
mock_settings_obj = MagicMock()
|
||||
mock_settings_obj.gcs_bucket_name = "test-bucket"
|
||||
mock_settings.return_value = mock_settings_obj
|
||||
mock_create_logger.return_value = MagicMock()
|
||||
|
||||
# Should fail because no separation mode is configured
|
||||
result = await process_audio_separation("test-job-id")
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestLocalSeparationWithPresets:
|
||||
"""Tests for local audio separation using ensemble presets."""
|
||||
|
||||
def setup_method(self):
|
||||
self.processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.DEBUG,
|
||||
log_formatter=None,
|
||||
model_file_dir="/models",
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
|
||||
backing_vocals_models=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
self.processor.instrumental_preset = "instrumental_clean"
|
||||
self.processor.karaoke_preset = "karaoke"
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_local_separation_uses_ensemble_preset_for_stage1(self, mock_separator_cls, mock_shutil):
|
||||
"""Stage 1 uses instrumental_preset on the Separator constructor."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
|
||||
# Disable karaoke_preset so stage 2 is skipped, isolating stage 1
|
||||
self.processor.karaoke_preset = None
|
||||
self.processor.backing_vocals_models = []
|
||||
|
||||
mock_sep = MagicMock()
|
||||
mock_sep.separate.return_value = ["/tmp/stems/vocals.flac", "/tmp/stems/instrumental.flac"]
|
||||
mock_separator_cls.return_value = mock_sep
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value="/tmp/stems"):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Title", "/tmp/output"
|
||||
)
|
||||
|
||||
# Verify Separator was constructed with ensemble_preset="instrumental_clean"
|
||||
mock_separator_cls.assert_called_once()
|
||||
constructor_kwargs = mock_separator_cls.call_args[1]
|
||||
assert constructor_kwargs.get("ensemble_preset") == "instrumental_clean"
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_local_separation_uses_karaoke_preset_for_stage2(self, mock_separator_cls, mock_shutil):
|
||||
"""Stage 2 uses karaoke_preset on a fresh Separator for BV separation."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
|
||||
mock_sep = MagicMock()
|
||||
mock_sep.separate.return_value = ["/tmp/stems/vocals.flac", "/tmp/stems/instrumental.flac"]
|
||||
mock_separator_cls.return_value = mock_sep
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value="/tmp/stems"):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Title", "/tmp/output"
|
||||
)
|
||||
|
||||
# Separator should be instantiated twice: once for stage 1, once for stage 2
|
||||
assert mock_separator_cls.call_count == 2
|
||||
stage2_kwargs = mock_separator_cls.call_args_list[1][1]
|
||||
assert stage2_kwargs.get("ensemble_preset") == "karaoke"
|
||||
@@ -106,7 +106,7 @@ class TestRemoteAudioSeparation(unittest.TestCase):
|
||||
@patch.dict(os.environ, {}, clear=True) # Clear AUDIO_SEPARATOR_API_URL
|
||||
def test_local_fallback_when_no_env_var(self):
|
||||
"""Test that local processing is used when environment variable is not set."""
|
||||
with patch('audio_separator.separator.Separator') as mock_separator_class:
|
||||
with patch('karaoke_gen.audio_processor.Separator') as mock_separator_class:
|
||||
mock_separator = MagicMock()
|
||||
mock_separator_class.return_value = mock_separator
|
||||
mock_separator.separate.return_value = []
|
||||
@@ -139,7 +139,7 @@ class TestRemoteAudioSeparation(unittest.TestCase):
|
||||
@patch('karaoke_gen.audio_processor.REMOTE_API_AVAILABLE', False)
|
||||
def test_local_fallback_when_remote_unavailable(self):
|
||||
"""Test that local processing is used when remote API is unavailable."""
|
||||
with patch('audio_separator.separator.Separator') as mock_separator_class:
|
||||
with patch('karaoke_gen.audio_processor.Separator') as mock_separator_class:
|
||||
mock_separator = MagicMock()
|
||||
mock_separator_class.return_value = mock_separator
|
||||
mock_separator.separate.return_value = []
|
||||
@@ -179,7 +179,7 @@ class TestRemoteAudioSeparation(unittest.TestCase):
|
||||
# Mock API failure
|
||||
mock_client.separate_audio_and_wait.side_effect = Exception("API Error")
|
||||
|
||||
with patch('audio_separator.separator.Separator') as mock_separator_class:
|
||||
with patch('karaoke_gen.audio_processor.Separator') as mock_separator_class:
|
||||
mock_separator = MagicMock()
|
||||
mock_separator_class.return_value = mock_separator
|
||||
mock_separator.separate.return_value = []
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user