mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 09:58:08 +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.
|
||||
@@ -0,0 +1,150 @@
|
||||
# Plan: Block Disposable Email Registration
|
||||
|
||||
**Created:** 2026-03-19
|
||||
**Branch:** feat/sess-20260319-1332-disposable-email-abuse
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Users are signing up with disposable email addresses (yopmail.com, emailhook.site, etc.) to get unlimited free credits (2 per account). The `EmailValidationService` already exists with 160+ disposable domains but is **never called during signup**. We need to wire it into the magic link flow and show a friendly rejection message.
|
||||
|
||||
## Context
|
||||
|
||||
- The `EmailValidationService` (`backend/services/email_validation_service.py`) is fully implemented with disposable domain detection, email/IP blocklists, and admin management APIs
|
||||
- The admin blocklist management routes exist (`backend/api/routes/rate_limits.py`) and work
|
||||
- The magic link endpoint (`POST /api/users/auth/magic-link` in `backend/api/routes/users.py:133`) **never calls** the validation service
|
||||
- Currently 1 yopmail user and 1 emailhook.site user in `gen_users`
|
||||
- Each new account gets 2 free welcome credits automatically
|
||||
|
||||
## Requirements
|
||||
|
||||
- [x] Reject disposable email domains at the magic link endpoint (backend)
|
||||
- [x] Return a **specific, distinguishable error** so the frontend can show a friendly message (not the generic "email enumeration" response)
|
||||
- [x] Show a warm, friendly message in the AuthDialog explaining why and encouraging real email use
|
||||
- [x] Add `emailhook.site` to the default disposable domains list
|
||||
- [x] Add backend unit tests for the integration
|
||||
- [x] Add frontend test coverage for the new error state
|
||||
|
||||
## Design Decision: Explicit Rejection vs Silent Failure
|
||||
|
||||
The current magic link endpoint returns a generic success message to prevent email enumeration. For disposable emails, we will **explicitly reject** with a 422 status and a specific error message. This is the right trade-off because:
|
||||
|
||||
1. We *want* the user to know their disposable email won't work (so they can use a real one)
|
||||
2. Disposable domain detection is not sensitive information — the blocklist is public knowledge
|
||||
3. The friendly message serves our goal of converting them to real email users
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Backend — Add disposable email check to magic link endpoint
|
||||
|
||||
**File:** `backend/api/routes/users.py`
|
||||
|
||||
Add the `EmailValidationService` check **after** email lowercasing (line 158) and **before** tenant validation (line 164). Return a 422 with a friendly message.
|
||||
|
||||
```python
|
||||
# Check for disposable email domains
|
||||
email_validation = get_email_validation_service()
|
||||
if email_validation.is_disposable_domain(email):
|
||||
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="disposable_email_not_allowed"
|
||||
)
|
||||
```
|
||||
|
||||
Use a machine-readable error code (`disposable_email_not_allowed`) so the frontend can match on it and show the custom friendly message. This keeps the backend response lean and puts the UX copy in the frontend where it belongs.
|
||||
|
||||
### Step 2: Backend — Also check email and IP blocklists
|
||||
|
||||
In the same location, add checks for explicitly blocked emails and IPs:
|
||||
|
||||
```python
|
||||
if email_validation.is_email_blocked(email):
|
||||
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
|
||||
# Silent reject — return generic success to prevent enumeration
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
ip_address = http_request.client.host if http_request.client else None
|
||||
if ip_address and email_validation.is_ip_blocked(ip_address):
|
||||
logger.warning(f"Blocked IP signup attempt: {ip_address}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
```
|
||||
|
||||
Note: Blocked emails/IPs get silent rejection (anti-enumeration). Disposable domains get explicit rejection (we want the user to switch to a real email).
|
||||
|
||||
### Step 3: Backend — Add `emailhook.site` to default disposable domains
|
||||
|
||||
**File:** `backend/services/email_validation_service.py`
|
||||
|
||||
Add `emailhook.site` to `DEFAULT_DISPOSABLE_DOMAINS` set.
|
||||
|
||||
### Step 4: Frontend — Handle the disposable email error in AuthDialog
|
||||
|
||||
**File:** `frontend/components/auth/AuthDialog.tsx`
|
||||
|
||||
The `sendMagicLink` call in `auth.ts` already catches errors and sets `error` from the API response message. The `handleResponse` in `api.ts` throws an `ApiError` with the `detail` string for non-200 responses.
|
||||
|
||||
Update `handleSendMagicLink` to detect the `disposable_email_not_allowed` error code and show a friendly multi-line message instead of the terse error string:
|
||||
|
||||
```tsx
|
||||
const success = await sendMagicLink(email.trim().toLowerCase())
|
||||
if (success) {
|
||||
setStep("sent")
|
||||
}
|
||||
// If error contains our specific code, override with friendly message
|
||||
// (the error state is already set by the auth store)
|
||||
```
|
||||
|
||||
We need to detect the specific error. The cleanest approach: check the error string in the `displayError` rendering. If it matches `disposable_email_not_allowed`, render a custom friendly block instead of the red error text.
|
||||
|
||||
The friendly message:
|
||||
|
||||
> **We don't support disposable email addresses**
|
||||
>
|
||||
> We'd love to help you create karaoke videos! Please use your regular email address so we can send you a notification when your video is ready.
|
||||
>
|
||||
> We promise — no spam, no marketing emails, ever. We only email you about your karaoke videos.
|
||||
|
||||
### Step 5: Backend tests
|
||||
|
||||
**File:** `backend/tests/test_email_validation_integration.py` (new)
|
||||
|
||||
Test cases:
|
||||
1. Magic link with disposable email returns 422 with `disposable_email_not_allowed`
|
||||
2. Magic link with legitimate email proceeds normally
|
||||
3. Magic link with blocked email returns silent success (no actual email sent)
|
||||
4. Magic link with blocked IP returns silent success
|
||||
|
||||
### Step 6: Frontend tests
|
||||
|
||||
**File:** `frontend/components/__tests__/AuthDialog.test.tsx` (new or extend existing)
|
||||
|
||||
Test cases:
|
||||
1. Submitting a disposable email shows the friendly rejection message
|
||||
2. The friendly message contains the key copy (no spam promise, use real email)
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/users.py` | Modify | Add email validation checks to magic link endpoint |
|
||||
| `backend/services/email_validation_service.py` | Modify | Add `emailhook.site` to default domains |
|
||||
| `frontend/components/auth/AuthDialog.tsx` | Modify | Handle disposable email error with friendly message |
|
||||
| `backend/tests/test_email_validation_integration.py` | Create | Integration tests for the validation in signup flow |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests:** Validate `is_disposable_domain` catches yopmail, emailhook.site (already covered in existing tests)
|
||||
- **Integration tests:** New test file verifying the magic link endpoint rejects disposable emails with 422
|
||||
- **Frontend tests:** Verify the AuthDialog shows friendly message on disposable email error
|
||||
- **Manual verification:** Try signing up with `test@yopmail.com` on dev server to see the UX
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Remove the validation check from `send_magic_link()` in `users.py`. The `EmailValidationService` itself remains unchanged (it's already deployed and used by admin routes).
|
||||
+264
-113
@@ -628,7 +628,24 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
- name: Start Docker for GCS emulator
|
||||
- name: Wait for Docker to be available
|
||||
run: |
|
||||
# Self-hosted runners may still be initializing Docker on boot.
|
||||
# Wait up to 60s for the docker command and daemon to be ready.
|
||||
for i in $(seq 1 12); do
|
||||
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
|
||||
echo "Docker is ready"
|
||||
exit 0
|
||||
fi
|
||||
echo "Waiting for Docker... (attempt $i/12)"
|
||||
sleep 5
|
||||
done
|
||||
echo "ERROR: Docker not available after 60s"
|
||||
echo "PATH=$PATH"
|
||||
which docker 2>&1 || echo "docker binary not found"
|
||||
exit 1
|
||||
|
||||
- name: Pull GCS emulator image
|
||||
run: docker pull fsouza/fake-gcs-server:latest
|
||||
|
||||
- name: Run emulator integration tests
|
||||
@@ -999,14 +1016,15 @@ jobs:
|
||||
version: "latest"
|
||||
|
||||
# ============================================
|
||||
# Deploy to GCE Encoding Worker (Immutable Deployment Pattern)
|
||||
# Blue-Green Deploy to GCE Encoding Worker
|
||||
#
|
||||
# This pattern ensures version consistency:
|
||||
# 1. Upload wheel to FIXED path (no version sorting)
|
||||
# 2. Upload startup.sh (logic can change without image rebuild)
|
||||
# 3. Write version manifest for verification
|
||||
# 4. Restart service (triggers bootstrap.sh -> startup.sh)
|
||||
# 5. STRICTLY verify deployed version (fail CI on mismatch)
|
||||
# This pattern ensures zero-downtime deployments:
|
||||
# 1. Upload wheel + startup.sh + version manifest to GCS
|
||||
# 2. Read blue-green config from Firestore
|
||||
# 3. Start secondary VM, wait for health + version match
|
||||
# 4. Deep health check: submit a real encode test
|
||||
# 5. Swap primary/secondary in Firestore (atomic transaction)
|
||||
# 6. Drain and stop old primary
|
||||
#
|
||||
# See infrastructure/encoding-worker/README.md for details
|
||||
# ============================================
|
||||
@@ -1017,12 +1035,12 @@ jobs:
|
||||
name: package-dist
|
||||
path: dist/
|
||||
|
||||
- name: Deploy to GCE Encoding Worker
|
||||
- name: Deploy to GCS
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
BUCKET="gs://karaoke-gen-storage-${{ env.PROJECT_ID }}"
|
||||
|
||||
echo "🚀 Deploying encoding worker v${VERSION}..."
|
||||
echo "Deploying encoding worker v${VERSION}..."
|
||||
|
||||
# 1. Find the wheel file
|
||||
WHEEL_FILE=$(ls dist/*.whl | head -1)
|
||||
@@ -1030,11 +1048,11 @@ jobs:
|
||||
echo "::error::No wheel file found in dist/"
|
||||
exit 1
|
||||
fi
|
||||
echo "📦 Found wheel: $WHEEL_FILE"
|
||||
echo "Found wheel: $WHEEL_FILE"
|
||||
|
||||
# 2. Upload wheel to FIXED path (atomic via temp file)
|
||||
# This eliminates version sorting - always use karaoke_gen-current.whl
|
||||
echo "📤 Uploading wheel to fixed path..."
|
||||
echo "Uploading wheel to fixed path..."
|
||||
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/karaoke_gen-current.whl.tmp"
|
||||
gsutil mv "${BUCKET}/wheels/karaoke_gen-current.whl.tmp" \
|
||||
"${BUCKET}/wheels/karaoke_gen-current.whl"
|
||||
@@ -1043,130 +1061,263 @@ jobs:
|
||||
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/"
|
||||
|
||||
# 3. Upload startup.sh (allows logic changes without image rebuild)
|
||||
echo "📤 Uploading startup.sh..."
|
||||
echo "Uploading startup.sh..."
|
||||
gsutil cp infrastructure/encoding-worker/startup.sh \
|
||||
"${BUCKET}/encoding-worker/startup.sh"
|
||||
|
||||
# 4. Write version manifest for verification
|
||||
echo "📝 Writing version manifest..."
|
||||
echo "Writing version manifest..."
|
||||
echo "${VERSION}" | gsutil cp - "${BUCKET}/encoding-worker/version.txt"
|
||||
|
||||
echo "✅ GCS deployment complete"
|
||||
echo "GCS deployment complete"
|
||||
|
||||
- name: Drain active encoding jobs before restart
|
||||
- name: Install Firestore client
|
||||
run: pip install google-cloud-firestore
|
||||
|
||||
- name: Read Firestore config
|
||||
id: config
|
||||
run: |
|
||||
# Graceful drain: wait for any active encoding jobs to finish before
|
||||
# restarting the worker. This prevents killing in-flight FFmpeg encodes.
|
||||
#
|
||||
# The /health endpoint returns active_jobs count. We poll until it's 0
|
||||
# or until the drain timeout expires (10 minutes — well within the
|
||||
# longest encoding time of ~5 min for a full 4-format encode).
|
||||
python3 << 'PYEOF'
|
||||
import json, os
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
doc = db.collection("config").document("encoding-worker").get()
|
||||
if not doc.exists:
|
||||
print("::error::Encoding worker config not found in Firestore")
|
||||
raise SystemExit(1)
|
||||
data = doc.to_dict()
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
|
||||
for key in ["primary_vm", "primary_ip", "primary_version",
|
||||
"secondary_vm", "secondary_ip"]:
|
||||
f.write(f"{key}={data.get(key, '')}\n")
|
||||
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
|
||||
print(f"Config: primary={data['primary_vm']}, secondary={data['secondary_vm']}")
|
||||
PYEOF
|
||||
|
||||
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
|
||||
DRAIN_TIMEOUT=600 # 10 minutes
|
||||
POLL_INTERVAL=15
|
||||
ELAPSED=0
|
||||
- name: Wait for concurrent deploy
|
||||
if: steps.config.outputs.deploy_in_progress == 'true'
|
||||
run: |
|
||||
echo "Another deploy is in progress, waiting..."
|
||||
python3 << 'PYEOF'
|
||||
import time
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
for i in range(20):
|
||||
time.sleep(30)
|
||||
doc = db.collection("config").document("encoding-worker").get()
|
||||
if not doc.to_dict().get("deploy_in_progress", False):
|
||||
print("Concurrent deploy finished, proceeding")
|
||||
break
|
||||
else:
|
||||
print("::error::Timed out waiting for concurrent deploy (10 min)")
|
||||
raise SystemExit(1)
|
||||
PYEOF
|
||||
|
||||
echo "🔍 Checking for active encoding jobs before restart..."
|
||||
- name: Set deploy in progress
|
||||
run: |
|
||||
python3 << 'PYEOF'
|
||||
from datetime import datetime, timezone
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
db.collection("config").document("encoding-worker").update({
|
||||
"deploy_in_progress": True,
|
||||
"deploy_in_progress_since": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
print("Set deploy_in_progress=true")
|
||||
PYEOF
|
||||
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
HEALTH=$(curl -sf -H "X-API-Key: $WORKER_KEY" "$WORKER_URL/health" 2>/dev/null || echo '{"active_jobs": -1}')
|
||||
ACTIVE=$(echo "$HEALTH" | grep -o '"active_jobs":[0-9]*' | cut -d: -f2)
|
||||
- name: Start secondary VM
|
||||
run: |
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
echo "Starting secondary VM: $SECONDARY_VM"
|
||||
gcloud compute instances start "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
if [ -z "$ACTIVE" ] || [ "$ACTIVE" = "-1" ]; then
|
||||
echo "⚠️ Could not reach health endpoint (worker may already be down). Proceeding with restart."
|
||||
for i in $(seq 1 12); do
|
||||
STATUS=$(gcloud compute instances describe "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke \
|
||||
--format='value(status)')
|
||||
echo "VM status: $STATUS (attempt $i/12)"
|
||||
if [ "$STATUS" = "RUNNING" ]; then
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$ACTIVE" = "0" ]; then
|
||||
echo "✅ No active encoding jobs. Safe to restart."
|
||||
break
|
||||
fi
|
||||
|
||||
echo "⏳ $ACTIVE active encoding job(s) running. Waiting ${POLL_INTERVAL}s... (${ELAPSED}s/${DRAIN_TIMEOUT}s)"
|
||||
sleep $POLL_INTERVAL
|
||||
ELAPSED=$((ELAPSED + POLL_INTERVAL))
|
||||
sleep 10
|
||||
done
|
||||
|
||||
if [ $ELAPSED -ge $DRAIN_TIMEOUT ]; then
|
||||
echo "⚠️ Drain timeout reached (${DRAIN_TIMEOUT}s) with jobs still active. Proceeding with restart."
|
||||
echo " Active jobs will be recoverable via idempotent /encode endpoint (PR #413)."
|
||||
- name: Wait for service health
|
||||
id: health
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
HEALTH_URL="http://${SECONDARY_IP}:8080/health"
|
||||
|
||||
echo "Waiting for service at $HEALTH_URL..."
|
||||
for i in $(seq 1 18); do
|
||||
RESPONSE=$(curl -sf "$HEALTH_URL" 2>/dev/null || echo "")
|
||||
if [ -n "$RESPONSE" ]; then
|
||||
WHEEL_VERSION=$(echo "$RESPONSE" | jq -r '.wheel_version // empty')
|
||||
echo "Health: version=$WHEEL_VERSION"
|
||||
if [ "$WHEEL_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "Version matches! Service is healthy."
|
||||
echo "healthy=true" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
echo "Attempt $i/18 - waiting 10s..."
|
||||
sleep 10
|
||||
done
|
||||
|
||||
echo "::error::Service did not become healthy within 3 minutes"
|
||||
echo "healthy=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
|
||||
- name: Deep health check - real encode test
|
||||
if: steps.health.outputs.healthy == 'true'
|
||||
id: encode-test
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
echo "Uploading test assets to GCS..."
|
||||
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
|
||||
gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass
|
||||
|
||||
echo "Submitting test encode to $SECONDARY_IP..."
|
||||
RESPONSE=$(curl -sf -X POST "http://${SECONDARY_IP}:8080/encode-preview" \
|
||||
-H "X-API-Key: $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"job_id": "deploy-health-check",
|
||||
"ass_gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass",
|
||||
"duration_seconds": 10
|
||||
}')
|
||||
|
||||
echo "Encode response: $RESPONSE"
|
||||
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
|
||||
|
||||
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "completed" ]; then
|
||||
echo "::error::Encode test failed with status: $STATUS"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Restart GCE Encoding Worker
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
|
||||
echo "🔄 Restarting encoding worker..."
|
||||
|
||||
# Use IAP tunneling - works directly with service account credentials
|
||||
gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
|
||||
echo "⏳ Waiting for service to start (up to 60s)..."
|
||||
sleep 20
|
||||
|
||||
- name: Verify Encoding Worker Version
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
|
||||
echo "🔍 Verifying encoding worker version..."
|
||||
|
||||
# Retry loop - service may take time to fully start
|
||||
MAX_RETRIES=6
|
||||
RETRY_DELAY=10
|
||||
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Attempt $i/$MAX_RETRIES..."
|
||||
|
||||
NEW_VERSION=$(gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="curl -s http://localhost:8080/health 2>/dev/null | grep -o '\"wheel_version\":\"[^\"]*\"' | cut -d'\"' -f4" 2>/dev/null || echo "")
|
||||
|
||||
if [ "$NEW_VERSION" = "$VERSION" ]; then
|
||||
echo "✅ Encoding worker version verified: v$NEW_VERSION"
|
||||
for i in $(seq 1 12); do
|
||||
sleep 5
|
||||
JOB_STATUS=$(curl -sf \
|
||||
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
|
||||
-H "X-API-Key: $API_KEY" | jq -r '.status // "unknown"')
|
||||
echo "Encode status: $JOB_STATUS (attempt $i/12)"
|
||||
if [ "$JOB_STATUS" = "completed" ]; then
|
||||
echo "Encode test passed!"
|
||||
echo "passed=true" >> $GITHUB_OUTPUT
|
||||
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -n "$NEW_VERSION" ]; then
|
||||
echo "⚠️ Version: $NEW_VERSION (expected: $VERSION)"
|
||||
else
|
||||
echo "⚠️ Health endpoint not responding yet"
|
||||
fi
|
||||
|
||||
if [ $i -lt $MAX_RETRIES ]; then
|
||||
echo " Retrying in ${RETRY_DELAY}s..."
|
||||
sleep $RETRY_DELAY
|
||||
elif [ "$JOB_STATUS" = "failed" ]; then
|
||||
echo "::error::Encode test failed"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# STRICT VERIFICATION: Fail CI on version mismatch
|
||||
echo ""
|
||||
echo "=============================================="
|
||||
echo "❌ ENCODING WORKER DEPLOYMENT FAILED"
|
||||
echo "=============================================="
|
||||
echo "Expected version: $VERSION"
|
||||
echo "Deployed version: $NEW_VERSION"
|
||||
echo ""
|
||||
echo "Possible causes:"
|
||||
echo " - GCS upload failed (check 'Deploy to GCE' step)"
|
||||
echo " - startup.sh download failed (check VM logs)"
|
||||
echo " - Wheel installation failed (check VM logs)"
|
||||
echo ""
|
||||
echo "To debug, SSH to VM and check logs:"
|
||||
echo " gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke --tunnel-through-iap"
|
||||
echo " sudo journalctl -u encoding-worker -n 100"
|
||||
echo " cat /var/log/encoding-worker-startup.log"
|
||||
echo "=============================================="
|
||||
|
||||
echo "::error::Encode test timed out after 60s"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
|
||||
- name: Rollback on failure
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
|
||||
run: |
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
if [ -n "$SECONDARY_VM" ]; then
|
||||
echo "Stopping secondary VM $SECONDARY_VM due to failed deploy"
|
||||
gcloud compute instances stop "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
fi
|
||||
|
||||
python3 -c "
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project='nomadkaraoke')
|
||||
db.collection('config').document('encoding-worker').update({
|
||||
'deploy_in_progress': False,
|
||||
'deploy_in_progress_since': None,
|
||||
})
|
||||
print('Cleared deploy_in_progress flag')
|
||||
" || true
|
||||
|
||||
- name: Swap primary in Firestore
|
||||
if: steps.encode-test.outputs.passed == 'true'
|
||||
env:
|
||||
NEW_PRIMARY: ${{ steps.config.outputs.secondary_vm }}
|
||||
NEW_PRIMARY_IP: ${{ steps.config.outputs.secondary_ip }}
|
||||
NEW_VERSION: ${{ steps.version_check.outputs.version }}
|
||||
OLD_PRIMARY: ${{ steps.config.outputs.primary_vm }}
|
||||
OLD_PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
|
||||
OLD_VERSION: ${{ steps.config.outputs.primary_version }}
|
||||
run: |
|
||||
echo "Swapping: $OLD_PRIMARY -> secondary, $NEW_PRIMARY -> primary"
|
||||
python3 << 'PYEOF'
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from google.cloud import firestore
|
||||
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
doc_ref = db.collection("config").document("encoding-worker")
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
@firestore.transactional
|
||||
def swap(transaction):
|
||||
transaction.update(doc_ref, {
|
||||
"primary_vm": os.environ["NEW_PRIMARY"],
|
||||
"primary_ip": os.environ["NEW_PRIMARY_IP"],
|
||||
"primary_version": os.environ["NEW_VERSION"],
|
||||
"primary_deployed_at": now,
|
||||
"secondary_vm": os.environ["OLD_PRIMARY"],
|
||||
"secondary_ip": os.environ["OLD_PRIMARY_IP"],
|
||||
"secondary_version": os.environ["OLD_VERSION"],
|
||||
"secondary_deployed_at": now,
|
||||
"last_swap_at": now,
|
||||
"deploy_in_progress": False,
|
||||
"deploy_in_progress_since": None,
|
||||
})
|
||||
|
||||
transaction = db.transaction()
|
||||
swap(transaction)
|
||||
print(f"Swapped: {os.environ['NEW_PRIMARY']} is now primary")
|
||||
PYEOF
|
||||
|
||||
- name: Drain and stop old primary
|
||||
if: steps.encode-test.outputs.passed == 'true'
|
||||
run: |
|
||||
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
|
||||
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
|
||||
if [ "$ACTIVE_JOBS" -gt 0 ]; then
|
||||
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
|
||||
DRAIN_TIMEOUT=600
|
||||
ELAPSED=0
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
if [ "$ACTIVE_JOBS" -eq 0 ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
echo "Stopping old primary: $OLD_PRIMARY"
|
||||
gcloud compute instances stop "$OLD_PRIMARY" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
- name: Configure Docker for Artifact Registry
|
||||
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
|
||||
@@ -1316,7 +1467,7 @@ 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,AUDIO_SEPARATOR_API_URL=https://audio-separator-718638054799.us-east4.run.app,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
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
|
||||
- **Backend**: FastAPI on Cloud Run, Firestore, GCS, Secret Manager
|
||||
- **Frontend**: Next.js on Cloudflare Pages
|
||||
- **Processing**: Modal (GPU audio separation), AudioShake/Whisper (transcription)
|
||||
- **Processing**: Cloud Run GPU (L4 audio separation), AudioShake/Whisper (transcription)
|
||||
- **Infra**: Pulumi IaC, GitHub Actions CI/CD
|
||||
|
||||
## Essential Rules
|
||||
|
||||
@@ -13,7 +13,8 @@ help:
|
||||
@echo "Available commands:"
|
||||
@echo " make test - Run ALL tests (backend + frontend, installs deps automatically)"
|
||||
@echo " make test-backend - Run backend tests only (unit + emulator)"
|
||||
@echo " make test-frontend - Run frontend tests only (unit + E2E)"
|
||||
@echo " make test-frontend - Run frontend unit tests (Jest)"
|
||||
@echo " make test-frontend-e2e - Run frontend E2E tests (Playwright, requires dev server)"
|
||||
@echo " make test-unit - Run unit tests only (karaoke_gen package)"
|
||||
@echo " make test-e2e - Run emulator tests with auto-start/stop"
|
||||
@echo " make install - Install all dependencies (backend + frontend)"
|
||||
@@ -89,10 +90,15 @@ test-backend: test-unit test-backend-unit test-e2e
|
||||
@echo ""
|
||||
@echo "✅ Backend tests passed!"
|
||||
|
||||
# Run frontend tests (unit + E2E)
|
||||
# Run frontend unit tests (Jest only - E2E requires manual setup)
|
||||
test-frontend: install-frontend
|
||||
@echo "=== Running frontend tests ==="
|
||||
cd frontend && timeout $(TEST_TIMEOUT) npm run test:all
|
||||
@echo "=== Running frontend unit tests ==="
|
||||
cd frontend && timeout $(TEST_TIMEOUT) npm run test:unit
|
||||
|
||||
# Run frontend E2E tests (requires dev server - run manually, not in make test)
|
||||
test-frontend-e2e: install-frontend
|
||||
@echo "=== Running frontend E2E tests ==="
|
||||
cd frontend && timeout $(TEST_TIMEOUT) npm run test:e2e
|
||||
|
||||
# Run ALL tests (backend + frontend) - use this before committing!
|
||||
test: test-backend test-frontend
|
||||
|
||||
@@ -24,6 +24,7 @@ from backend.services.audio_search_service import get_audio_search_service, NoRe
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.firestore_service import log_to_job
|
||||
from backend.utils.test_data import is_test_email
|
||||
from backend.services.ip_geolocation_service import get_ip_geolocation_service
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
|
||||
@@ -3528,3 +3529,424 @@ async def get_audio_edit_review_detail(
|
||||
"original_audio_url": original_audio_url,
|
||||
"current_audio_url": current_audio_url,
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Anti-Abuse Investigation
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.get("/abuse/related/{email}")
|
||||
async def find_related_accounts(
|
||||
email: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Find accounts related to the given email by shared signup IP or device fingerprint.
|
||||
|
||||
Returns the target user plus lists of other accounts from the same IP and/or fingerprint.
|
||||
"""
|
||||
result = user_service.find_related_accounts(email)
|
||||
|
||||
if not result["user"]:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
user = result["user"]
|
||||
return {
|
||||
"user": {
|
||||
"email": user.email,
|
||||
"signup_ip": user.signup_ip,
|
||||
"device_fingerprint": user.device_fingerprint,
|
||||
"credits": user.credits,
|
||||
"total_jobs_created": user.total_jobs_created,
|
||||
"total_spent": user.total_spent,
|
||||
"created_at": str(user.created_at),
|
||||
},
|
||||
"related_by_ip": [
|
||||
{
|
||||
"email": u.email,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in result["by_ip"]
|
||||
],
|
||||
"related_by_fingerprint": [
|
||||
{
|
||||
"email": u.email,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in result["by_fingerprint"]
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@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,
|
||||
max_spend: int = 0,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Find accounts with many jobs but no (or low) spend.
|
||||
|
||||
Detects potential free-credit abusers: people creating multiple accounts
|
||||
to get welcome credits without ever paying.
|
||||
|
||||
Args:
|
||||
min_jobs: Minimum jobs created to flag (default: 2)
|
||||
max_spend: Maximum total_spent in cents (default: 0 = only free accounts)
|
||||
"""
|
||||
users = user_service.find_suspicious_accounts(min_jobs=min_jobs, max_spend=max_spend)
|
||||
|
||||
return {
|
||||
"count": len(users),
|
||||
"users": [
|
||||
{
|
||||
"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,
|
||||
"has_submitted_feedback": u.has_submitted_feedback,
|
||||
"created_at": str(u.created_at),
|
||||
"last_login_at": str(u.last_login_at) if u.last_login_at else None,
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/abuse/by-ip/{ip_address:path}")
|
||||
async def find_users_by_ip(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""Find all users who signed up from a specific IP address."""
|
||||
users = user_service.find_users_by_signup_ip(ip_address)
|
||||
return {
|
||||
"ip_address": ip_address,
|
||||
"count": len(users),
|
||||
"users": [
|
||||
{
|
||||
"email": u.email,
|
||||
"device_fingerprint": u.device_fingerprint,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/abuse/by-fingerprint/{fingerprint}")
|
||||
async def find_users_by_fingerprint(
|
||||
fingerprint: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""Find all users who signed up with a specific device fingerprint."""
|
||||
users = user_service.find_users_by_fingerprint(fingerprint)
|
||||
return {
|
||||
"device_fingerprint": fingerprint,
|
||||
"count": len(users),
|
||||
"users": [
|
||||
{
|
||||
"email": u.email,
|
||||
"signup_ip": u.signup_ip,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/abuse/backfill-ips")
|
||||
async def backfill_signup_ips(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Backfill signup_ip for existing users from their earliest session or magic link.
|
||||
|
||||
One-time operation to populate signup_ip for users created before the field was added.
|
||||
Only updates users who currently have signup_ip=None.
|
||||
"""
|
||||
from backend.services.user_service import SESSIONS_COLLECTION, MAGIC_LINKS_COLLECTION
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
db = user_service.db
|
||||
updated = 0
|
||||
skipped = 0
|
||||
no_ip_found = 0
|
||||
|
||||
# Known bad IPs (load balancer / proxy IPs that aren't real client IPs)
|
||||
BAD_IPS = {"169.254.169.126", "unknown", ""}
|
||||
|
||||
# Find all users without signup_ip or with a known-bad IP
|
||||
users_query = db.collection(USERS_COLLECTION).stream()
|
||||
|
||||
for user_doc in users_query:
|
||||
user_data = user_doc.to_dict()
|
||||
current_ip = user_data.get("signup_ip")
|
||||
if current_ip and current_ip not in BAD_IPS:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
email = user_data.get("email", "")
|
||||
if not email:
|
||||
continue
|
||||
|
||||
ip = None
|
||||
|
||||
# Try sessions first (most reliable — created at verification)
|
||||
# No order_by to avoid needing extra composite index; any IP is fine
|
||||
sessions = (
|
||||
db.collection(SESSIONS_COLLECTION)
|
||||
.where(filter=FieldFilter("user_email", "==", email))
|
||||
.limit(5)
|
||||
.stream()
|
||||
)
|
||||
for session_doc in sessions:
|
||||
session_data = session_doc.to_dict()
|
||||
candidate_ip = session_data.get("ip_address")
|
||||
if candidate_ip and candidate_ip not in BAD_IPS:
|
||||
ip = candidate_ip
|
||||
break
|
||||
|
||||
# Fallback: try magic links
|
||||
if not ip:
|
||||
links = (
|
||||
db.collection(MAGIC_LINKS_COLLECTION)
|
||||
.where(filter=FieldFilter("email", "==", email))
|
||||
.limit(5)
|
||||
.stream()
|
||||
)
|
||||
for link_doc in links:
|
||||
link_data = link_doc.to_dict()
|
||||
candidate_ip = link_data.get("ip_address")
|
||||
if candidate_ip:
|
||||
ip = candidate_ip
|
||||
break
|
||||
|
||||
if ip:
|
||||
user_doc.reference.update({"signup_ip": ip})
|
||||
updated += 1
|
||||
logger.info(f"Backfilled signup_ip for {email}: {ip}")
|
||||
else:
|
||||
# Clear bad IP if one was set (e.g., load balancer IP)
|
||||
if current_ip and current_ip in BAD_IPS:
|
||||
user_doc.reference.update({"signup_ip": None})
|
||||
updated += 1
|
||||
logger.info(f"Cleared bad signup_ip for {email}: {current_ip}")
|
||||
else:
|
||||
no_ip_found += 1
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"updated": updated,
|
||||
"skipped_already_set": skipped,
|
||||
"no_ip_found": no_ip_found,
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# IP Geolocation Lookup
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class IpBatchRequest(BaseModel):
|
||||
"""Request for batch IP geolocation lookup."""
|
||||
ips: list[str]
|
||||
|
||||
|
||||
@router.get("/abuse/ip-info/{ip_address:path}")
|
||||
async def get_ip_info(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Look up geolocation info for a single IP address."""
|
||||
geo_service = get_ip_geolocation_service()
|
||||
return geo_service.lookup_ip(ip_address)
|
||||
|
||||
|
||||
@router.post("/abuse/ip-info/batch")
|
||||
async def get_ip_info_batch(
|
||||
request: IpBatchRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Look up geolocation info for multiple IP addresses."""
|
||||
if len(request.ips) > 100:
|
||||
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
|
||||
|
||||
@@ -308,6 +308,39 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
Return the installed audio-separator package version.
|
||||
|
||||
Does NOT call the remote GPU service — that would cold-start an expensive
|
||||
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
|
||||
installed package version, which matches what the audio worker uses.
|
||||
|
||||
No authentication required.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/detailed")
|
||||
async def detailed_health_check() -> Dict[str, Any]:
|
||||
"""
|
||||
|
||||
@@ -25,7 +25,7 @@ from backend.workers.screens_worker import generate_screens
|
||||
from backend.workers.video_worker import generate_video
|
||||
from backend.workers.render_video_worker import process_render_video
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.tracing import (
|
||||
extract_trace_context,
|
||||
@@ -114,6 +114,31 @@ def _check_worker_idempotency(job_id: str, worker_name: str) -> Optional[WorkerR
|
||||
return None
|
||||
|
||||
|
||||
@router.post("/sync-disposable-domains", response_model=WorkerResponse)
|
||||
async def sync_disposable_domains_endpoint(
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Sync external disposable domain blocklist. Called by Cloud Scheduler daily."""
|
||||
import asyncio
|
||||
from backend.services.disposable_domain_sync_service import (
|
||||
fetch_external_blocklist, sync_disposable_domains
|
||||
)
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
|
||||
domains = await fetch_external_blocklist()
|
||||
db = get_firestore_client()
|
||||
result = await asyncio.to_thread(sync_disposable_domains, db, domains)
|
||||
EmailValidationService._blocklist_cache = None
|
||||
|
||||
return WorkerResponse(
|
||||
status="completed",
|
||||
job_id="sync-disposable-domains",
|
||||
message=f"Synced {result['external_count']} domains"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workers/audio", response_model=WorkerResponse)
|
||||
async def trigger_audio_worker(
|
||||
request: WorkerRequest,
|
||||
@@ -480,6 +505,44 @@ async def process_youtube_upload_queue(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/process-stale-reviews")
|
||||
async def process_stale_reviews_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Process stale review jobs — send reminders and expire old ones.
|
||||
|
||||
Called by Cloud Scheduler (hourly). Can also be triggered manually
|
||||
from the admin dashboard.
|
||||
|
||||
- Jobs in review for >= 24h get a reminder email
|
||||
- Jobs in review for >= 48h are auto-cancelled with credit refund
|
||||
"""
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info("STALE_REVIEW_PROCESS starting")
|
||||
add_span_attribute("operation", "stale_review_process")
|
||||
|
||||
async def _process():
|
||||
try:
|
||||
result = await process_stale_reviews()
|
||||
logger.info(f"STALE_REVIEW_PROCESS complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"STALE_REVIEW_PROCESS failed: {e}")
|
||||
|
||||
background_tasks.add_task(_process)
|
||||
|
||||
add_span_event("stale_review_processing_started")
|
||||
return {
|
||||
"status": "started",
|
||||
"message": "Stale review processing started in background"
|
||||
}
|
||||
|
||||
|
||||
@router.post("/trigger-gdrive-validation")
|
||||
async def trigger_gdrive_validation_endpoint(
|
||||
http_request: Request,
|
||||
|
||||
@@ -18,6 +18,7 @@ from typing import List, Optional, Dict, Any
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
|
||||
|
||||
from datetime import datetime
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
|
||||
from backend.models.requests import (
|
||||
URLSubmissionRequest,
|
||||
@@ -70,6 +71,7 @@ async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
@router.post("", response_model=JobResponse)
|
||||
async def create_job(
|
||||
request: URLSubmissionRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> JobResponse:
|
||||
@@ -132,6 +134,11 @@ async def create_job(
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
|
||||
# Store client IP on job for anti-abuse correlation
|
||||
creation_ip = get_client_ip(http_request)
|
||||
if creation_ip:
|
||||
FirestoreService().update_job(job.job_id, {"creation_ip": creation_ip})
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job.job_id)
|
||||
add_span_attribute("job.source", "url")
|
||||
@@ -1277,6 +1284,26 @@ async def complete_review(
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
)
|
||||
|
||||
# Check for 0-segment lyrics — fail early with user-friendly message
|
||||
# Only check when lyrics pipeline has run (lyrics_metadata exists in state_data)
|
||||
state_data = job.state_data or {}
|
||||
lyrics_metadata = state_data.get('lyrics_metadata')
|
||||
if lyrics_metadata is not None:
|
||||
segment_count = lyrics_metadata.get('segment_count', 0)
|
||||
corrected_lyrics = state_data.get('corrected_lyrics', {})
|
||||
corrected_segments = corrected_lyrics.get('corrected_segments', [])
|
||||
|
||||
if segment_count == 0 and len(corrected_segments) == 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Cannot complete review: no lyrics were detected in the audio. "
|
||||
"This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). "
|
||||
"You can go back and paste lyrics manually using 'Replace All', "
|
||||
"or cancel this job and try again with an audio file that contains vocals."
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
# Store instrumental selection if provided (combined review flow)
|
||||
instrumental_selection = body.instrumental_selection if body else None
|
||||
@@ -2235,6 +2262,11 @@ async def create_job_from_search(
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Store client IP on job for anti-abuse correlation
|
||||
creation_ip = get_client_ip(request)
|
||||
if creation_ip:
|
||||
FirestoreService().update_job(job_id, {"creation_ip": creation_ip})
|
||||
|
||||
logger.info(f"Created job {job_id} from search session {body.search_session_id}")
|
||||
|
||||
# Trace attributes for observability
|
||||
|
||||
@@ -49,12 +49,16 @@ class YouTubeQueueListResponse(BaseModel):
|
||||
|
||||
|
||||
class BlocklistsResponse(BaseModel):
|
||||
"""All blocklist data."""
|
||||
disposable_domains: List[str]
|
||||
"""All blocklist data with domain source separation."""
|
||||
external_domains: List[str]
|
||||
manual_domains: List[str]
|
||||
allowlisted_domains: List[str]
|
||||
blocked_emails: List[str]
|
||||
blocked_ips: List[str]
|
||||
updated_at: Optional[datetime]
|
||||
updated_by: Optional[str]
|
||||
last_sync_at: Optional[datetime] = None
|
||||
last_sync_count: Optional[int] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
updated_by: Optional[str] = None
|
||||
|
||||
|
||||
class DomainRequest(BaseModel):
|
||||
@@ -86,38 +90,10 @@ class SuccessResponse(BaseModel):
|
||||
async def get_blocklists(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Get all blocklist data.
|
||||
|
||||
Returns disposable domains, blocked emails, and blocked IPs.
|
||||
"""
|
||||
"""Get all blocklist data with domain source separation."""
|
||||
email_validation = get_email_validation_service()
|
||||
|
||||
# Force refresh to get latest data
|
||||
config = email_validation.get_blocklist_config(force_refresh=True)
|
||||
|
||||
# Get the raw document for metadata
|
||||
from google.cloud import firestore
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
from backend.services.email_validation_service import BLOCKLISTS_COLLECTION, BLOCKLIST_CONFIG_DOC
|
||||
|
||||
db = get_firestore_client()
|
||||
doc = db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC).get()
|
||||
|
||||
updated_at = None
|
||||
updated_by = None
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
updated_at = data.get("updated_at")
|
||||
updated_by = data.get("updated_by")
|
||||
|
||||
return BlocklistsResponse(
|
||||
disposable_domains=sorted(list(config["disposable_domains"])),
|
||||
blocked_emails=sorted(list(config["blocked_emails"])),
|
||||
blocked_ips=sorted(list(config["blocked_ips"])),
|
||||
updated_at=updated_at,
|
||||
updated_by=updated_by,
|
||||
)
|
||||
raw_data = email_validation.get_blocklist_raw_data()
|
||||
return BlocklistsResponse(**raw_data)
|
||||
|
||||
|
||||
@router.post("/blocklists/disposable-domains", response_model=SuccessResponse)
|
||||
@@ -158,6 +134,57 @@ async def remove_disposable_domain(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/blocklists/allowlisted-domains", response_model=SuccessResponse)
|
||||
async def add_allowlisted_domain(
|
||||
request: DomainRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Add a domain to the allowlist (overrides external blocklist)."""
|
||||
email_validation = get_email_validation_service()
|
||||
domain = request.domain.lower().strip()
|
||||
if not domain or "." not in domain:
|
||||
raise HTTPException(status_code=400, detail="Invalid domain format")
|
||||
email_validation.add_allowlisted_domain(domain, auth_result.user_email)
|
||||
return SuccessResponse(success=True, message=f"Domain '{domain}' added to allowlist")
|
||||
|
||||
|
||||
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
|
||||
async def remove_allowlisted_domain(
|
||||
domain: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Remove a domain from the allowlist."""
|
||||
email_validation = get_email_validation_service()
|
||||
domain = domain.lower().strip()
|
||||
if not email_validation.remove_allowlisted_domain(domain, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="Domain not found in allowlist")
|
||||
return SuccessResponse(success=True, message=f"Domain '{domain}' removed from allowlist")
|
||||
|
||||
|
||||
@router.post("/blocklists/sync", response_model=SuccessResponse)
|
||||
async def trigger_sync(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Manually trigger a sync of the external disposable domain blocklist."""
|
||||
import asyncio
|
||||
from backend.services.disposable_domain_sync_service import (
|
||||
fetch_external_blocklist, sync_disposable_domains
|
||||
)
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
|
||||
domains = await fetch_external_blocklist()
|
||||
db = get_firestore_client()
|
||||
result = await asyncio.to_thread(sync_disposable_domains, db, domains)
|
||||
|
||||
# Invalidate cache
|
||||
EmailValidationService._blocklist_cache = None
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Synced {result['external_count']} external domains ({result['added']} added, {result['removed']} removed)"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/blocklists/blocked-emails", response_model=SuccessResponse)
|
||||
async def add_blocked_email(
|
||||
request: EmailRequest,
|
||||
|
||||
+219
-15
@@ -10,6 +10,7 @@ Handles:
|
||||
"""
|
||||
import hashlib
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
|
||||
@@ -34,6 +35,7 @@ def _mask_email(email: str) -> str:
|
||||
from fastapi import APIRouter, HTTPException, Depends, Request, Header
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
from backend.services.email_validation_service import get_email_validation_service
|
||||
from backend.models.user import (
|
||||
UserRole,
|
||||
UserPublic,
|
||||
@@ -67,6 +69,7 @@ from backend.services.youtube_download_service import (
|
||||
)
|
||||
from backend.exceptions import InvalidStateTransitionError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -130,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,
|
||||
@@ -147,6 +176,50 @@ async def send_magic_link(
|
||||
"""
|
||||
from backend.middleware.tenant import get_tenant_from_request, get_tenant_config_from_request
|
||||
|
||||
email = request.email.lower()
|
||||
|
||||
# Check for disposable email domains, blocked emails, and blocked IPs
|
||||
# (done before email service check so we can reject without needing email config)
|
||||
email_validation = get_email_validation_service()
|
||||
|
||||
if email_validation.is_disposable_domain(email):
|
||||
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="disposable_email_not_allowed"
|
||||
)
|
||||
|
||||
if email_validation.is_email_blocked(email):
|
||||
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
ip_address = get_client_ip(http_request)
|
||||
if ip_address and email_validation.is_ip_blocked(ip_address):
|
||||
logger.warning(f"Blocked IP signup attempt: {ip_address}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
# Per-IP and per-fingerprint signup rate limit (only for new users)
|
||||
device_fingerprint = request.device_fingerprint
|
||||
existing_user = user_service.get_user(email)
|
||||
if existing_user is None:
|
||||
if user_service.is_signup_rate_limited(
|
||||
ip_address=ip_address, device_fingerprint=device_fingerprint
|
||||
):
|
||||
logger.warning(
|
||||
f"Signup rate limit hit: IP={ip_address} for {_mask_email(email)}"
|
||||
)
|
||||
# Silent reject (anti-enumeration)
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
# Check if email service is configured
|
||||
if not email_service.is_configured():
|
||||
logger.error("Email service not configured - cannot send magic links")
|
||||
@@ -155,8 +228,6 @@ async def send_magic_link(
|
||||
detail="Email service is not available. Please contact support."
|
||||
)
|
||||
|
||||
email = request.email.lower()
|
||||
|
||||
# Get tenant context from middleware
|
||||
tenant_id = get_tenant_from_request(http_request)
|
||||
tenant_config = get_tenant_config_from_request(http_request)
|
||||
@@ -171,16 +242,16 @@ async def send_magic_link(
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
# Get client info for security logging
|
||||
ip_address = http_request.client.host if http_request.client else None
|
||||
# Get client info for security logging (ip_address already extracted above for blocklist check)
|
||||
user_agent = http_request.headers.get("user-agent")
|
||||
|
||||
# Create magic link token with tenant context
|
||||
# Create magic link token with tenant context and fingerprint
|
||||
magic_link = user_service.create_magic_link(
|
||||
email,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Get tenant-specific email configuration
|
||||
@@ -206,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."
|
||||
@@ -230,7 +312,7 @@ async def verify_magic_link(
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
|
||||
# Get client info
|
||||
ip_address = http_request.client.host if http_request.client else None
|
||||
ip_address = get_client_ip(http_request)
|
||||
user_agent = http_request.headers.get("user-agent")
|
||||
|
||||
# Check if this is a first login BEFORE verification (which sets last_login_at)
|
||||
@@ -253,12 +335,37 @@ async def verify_magic_link(
|
||||
if not success or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
# Create session with tenant context from the magic link
|
||||
# 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
|
||||
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
|
||||
session = user_service.create_session(
|
||||
user.email,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=magic_link_tenant_id
|
||||
tenant_id=magic_link_tenant_id,
|
||||
device_fingerprint=magic_link_fingerprint,
|
||||
)
|
||||
|
||||
# Send welcome email to first-time users
|
||||
@@ -291,6 +398,8 @@ async def verify_magic_link(
|
||||
user=user_public,
|
||||
message="Successfully signed in",
|
||||
tenant_subdomain=tenant_subdomain,
|
||||
credits_granted=credits_granted,
|
||||
credit_status=credit_status,
|
||||
)
|
||||
|
||||
|
||||
@@ -1066,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,
|
||||
)
|
||||
|
||||
|
||||
@@ -1077,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
|
||||
@@ -1155,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,
|
||||
@@ -1168,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.",
|
||||
@@ -1201,9 +1380,17 @@ class UserDetailResponse(BaseModel):
|
||||
last_login_at: Optional[str] = None
|
||||
total_jobs_created: int = 0
|
||||
total_jobs_completed: int = 0
|
||||
total_spent: int = 0
|
||||
credit_transactions: list[dict] = []
|
||||
recent_jobs: list[dict] = []
|
||||
active_sessions_count: int = 0
|
||||
# Anti-abuse / identity info
|
||||
signup_ip: Optional[str] = None
|
||||
device_fingerprint: Optional[str] = None
|
||||
welcome_credits_granted: bool = False
|
||||
has_submitted_feedback: bool = False
|
||||
# Recent session details (IP, user agent, fingerprint)
|
||||
recent_sessions: list[dict] = []
|
||||
|
||||
|
||||
@router.get("/admin/users", response_model=UserListResponsePaginated)
|
||||
@@ -1348,13 +1535,24 @@ async def get_user_detail(
|
||||
"created_at": created_at_str,
|
||||
})
|
||||
|
||||
# Count active sessions
|
||||
# Get active sessions with details
|
||||
sessions_query = db.collection("sessions").where(
|
||||
filter=FieldFilter("user_email", "==", email)
|
||||
).where(
|
||||
filter=FieldFilter("is_active", "==", True)
|
||||
)
|
||||
active_sessions_count = sum(1 for _ in sessions_query.stream())
|
||||
active_sessions = []
|
||||
for session_doc in sessions_query.stream():
|
||||
sd = session_doc.to_dict()
|
||||
created = sd.get("created_at")
|
||||
active_sessions.append({
|
||||
"ip_address": sd.get("ip_address"),
|
||||
"user_agent": sd.get("user_agent"),
|
||||
"device_fingerprint": sd.get("device_fingerprint"),
|
||||
"created_at": created.isoformat() if hasattr(created, 'isoformat') else str(created) if created else None,
|
||||
"last_activity_at": str(sd.get("last_activity_at", "")),
|
||||
})
|
||||
active_sessions_count = len(active_sessions)
|
||||
|
||||
# Format credit transactions
|
||||
credit_transactions = []
|
||||
@@ -1376,9 +1574,15 @@ async def get_user_detail(
|
||||
last_login_at=user.last_login_at.isoformat() if user.last_login_at else None,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
total_spent=user.total_spent,
|
||||
credit_transactions=credit_transactions,
|
||||
recent_jobs=recent_jobs,
|
||||
active_sessions_count=active_sessions_count,
|
||||
signup_ip=user.signup_ip,
|
||||
device_fingerprint=user.device_fingerprint,
|
||||
welcome_credits_granted=user.welcome_credits_granted,
|
||||
has_submitted_feedback=user.has_submitted_feedback,
|
||||
recent_sessions=active_sessions,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -321,6 +321,9 @@ class Job(BaseModel):
|
||||
# Creation-time decision params (for observability — what did the user actually choose?)
|
||||
creation_params: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
# Anti-abuse: IP address at job creation time (for cross-account correlation)
|
||||
creation_ip: Optional[str] = None
|
||||
|
||||
# Output deletion tracking (for admin cleanup without deleting job)
|
||||
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
|
||||
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
|
||||
|
||||
+19
-2
@@ -98,6 +98,13 @@ class User(BaseModel):
|
||||
# Feedback-for-credits program
|
||||
has_submitted_feedback: bool = False
|
||||
|
||||
# Anti-abuse: IP address and device fingerprint used during signup
|
||||
signup_ip: Optional[str] = None
|
||||
device_fingerprint: Optional[str] = None
|
||||
|
||||
# Flag to prevent duplicate welcome credit grants (idempotency)
|
||||
welcome_credits_granted: bool = False
|
||||
|
||||
|
||||
class MagicLinkToken(BaseModel):
|
||||
"""
|
||||
@@ -117,10 +124,16 @@ class MagicLinkToken(BaseModel):
|
||||
used_at: Optional[datetime] = None
|
||||
ip_address: Optional[str] = None
|
||||
user_agent: Optional[str] = None
|
||||
device_fingerprint: Optional[str] = None
|
||||
|
||||
# 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):
|
||||
"""
|
||||
@@ -138,6 +151,7 @@ class Session(BaseModel):
|
||||
last_activity_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
ip_address: Optional[str] = None
|
||||
user_agent: Optional[str] = None
|
||||
device_fingerprint: Optional[str] = None
|
||||
is_active: bool = True
|
||||
|
||||
# Multi-tenant support (None = default Nomad Karaoke)
|
||||
@@ -149,6 +163,7 @@ class Session(BaseModel):
|
||||
class SendMagicLinkRequest(BaseModel):
|
||||
"""Request to send a magic link email."""
|
||||
email: str
|
||||
device_fingerprint: Optional[str] = None
|
||||
|
||||
|
||||
class SendMagicLinkResponse(BaseModel):
|
||||
@@ -169,6 +184,8 @@ class VerifyMagicLinkResponse(BaseModel):
|
||||
user: "UserPublic"
|
||||
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):
|
||||
@@ -217,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
|
||||
@@ -272,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,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
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
Disposable Domain Sync Service.
|
||||
|
||||
Fetches and syncs disposable email domain blocklists from external sources.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Set
|
||||
|
||||
import httpx
|
||||
|
||||
from backend.services.email_validation_service import (
|
||||
BLOCKLISTS_COLLECTION,
|
||||
BLOCKLIST_CONFIG_DOC,
|
||||
DEFAULT_DISPOSABLE_DOMAINS,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
EXTERNAL_BLOCKLIST_URL = (
|
||||
"https://raw.githubusercontent.com/disposable-email-domains/"
|
||||
"disposable-email-domains/refs/heads/main/disposable_email_blocklist.conf"
|
||||
)
|
||||
FETCH_TIMEOUT_SECONDS = 30
|
||||
MAX_RESPONSE_BYTES = 2 * 1024 * 1024 # 2 MB
|
||||
MAX_DOMAIN_COUNT = 50_000
|
||||
|
||||
|
||||
def parse_blocklist_text(text: str) -> Set[str]:
|
||||
"""Parse newline-delimited blocklist text into a set of lowercase domains."""
|
||||
domains = set()
|
||||
for line in text.splitlines():
|
||||
domain = line.strip().lower()
|
||||
if domain:
|
||||
domains.add(domain)
|
||||
return domains
|
||||
|
||||
|
||||
async def fetch_external_blocklist() -> Set[str]:
|
||||
"""Fetch the external disposable domain blocklist from GitHub.
|
||||
|
||||
Checks Content-Length header and response body size against safety limits.
|
||||
"""
|
||||
async with httpx.AsyncClient(timeout=FETCH_TIMEOUT_SECONDS) as client:
|
||||
response = await client.get(EXTERNAL_BLOCKLIST_URL)
|
||||
response.raise_for_status()
|
||||
|
||||
content_length = response.headers.get("content-length")
|
||||
if content_length and int(content_length) > MAX_RESPONSE_BYTES:
|
||||
raise ValueError(
|
||||
f"Response size {content_length} exceeds maximum {MAX_RESPONSE_BYTES}"
|
||||
)
|
||||
|
||||
text = response.text
|
||||
if len(text.encode()) > MAX_RESPONSE_BYTES:
|
||||
raise ValueError(
|
||||
f"Response body size exceeds maximum {MAX_RESPONSE_BYTES}"
|
||||
)
|
||||
|
||||
domains = parse_blocklist_text(text)
|
||||
|
||||
if len(domains) > MAX_DOMAIN_COUNT:
|
||||
raise ValueError(
|
||||
f"Domain count {len(domains)} exceeds maximum {MAX_DOMAIN_COUNT}"
|
||||
)
|
||||
|
||||
logger.info(f"Fetched {len(domains)} domains from external blocklist")
|
||||
return domains
|
||||
|
||||
|
||||
def sync_disposable_domains(db, external_domains: Set[str]) -> dict:
|
||||
"""
|
||||
Sync external domains into Firestore.
|
||||
|
||||
Handles first-run migration from old disposable_domains field,
|
||||
and cleans up redundant manual domains on subsequent runs.
|
||||
|
||||
Note: This is a synchronous function (Firestore SDK is sync).
|
||||
Call from async code with `await asyncio.to_thread(sync_disposable_domains, db, domains)`.
|
||||
|
||||
Returns a summary dict with counts.
|
||||
"""
|
||||
doc_ref = db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
doc = doc_ref.get()
|
||||
|
||||
data = doc.to_dict() if doc.exists else {}
|
||||
result = {"external_count": len(external_domains), "added": 0, "removed": 0, "migrated_to_manual": []}
|
||||
|
||||
is_migration = "external_domains" not in data
|
||||
|
||||
if is_migration:
|
||||
old_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
|
||||
manual_only = old_domains - external_domains
|
||||
result["migrated_to_manual"] = sorted(manual_only)
|
||||
|
||||
new_data = {
|
||||
**data, # preserve all existing fields
|
||||
"external_domains": sorted(external_domains),
|
||||
"manual_domains": sorted(manual_only),
|
||||
"allowlisted_domains": data.get("allowlisted_domains", []),
|
||||
"last_sync_at": datetime.now(timezone.utc),
|
||||
"last_sync_count": len(external_domains),
|
||||
}
|
||||
new_data.pop("disposable_domains", None) # remove legacy field
|
||||
doc_ref.set(new_data)
|
||||
else:
|
||||
old_external = set(data.get("external_domains", []))
|
||||
manual_domains = set(data.get("manual_domains", []))
|
||||
|
||||
result["added"] = len(external_domains - old_external)
|
||||
result["removed"] = len(old_external - external_domains)
|
||||
|
||||
cleaned_manual = manual_domains - external_domains
|
||||
|
||||
new_data = {
|
||||
**data,
|
||||
"external_domains": sorted(external_domains),
|
||||
"manual_domains": sorted(cleaned_manual),
|
||||
"last_sync_at": datetime.now(timezone.utc),
|
||||
"last_sync_count": len(external_domains),
|
||||
}
|
||||
doc_ref.set(new_data)
|
||||
|
||||
logger.info(
|
||||
f"Sync complete: {result['external_count']} external domains, "
|
||||
f"{result['added']} added, {result['removed']} removed"
|
||||
)
|
||||
return result
|
||||
@@ -981,6 +981,194 @@ Get started: {self.frontend_url}
|
||||
text_content=message_content,
|
||||
)
|
||||
|
||||
def send_review_reminder(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send 24h review reminder email with expiry warning.
|
||||
|
||||
Sent when a job has been awaiting review for 24 hours.
|
||||
Offers help and warns that the job will expire in another 24 hours.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
job_id: Job ID for constructing the review link
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
song_info = f" — {artist} - {title}" if artist and title else ""
|
||||
subject = f"Reminder: Your karaoke video is waiting for review{song_info}"
|
||||
|
||||
review_url = f"{self.frontend_url}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}/app"
|
||||
|
||||
extra_styles = """
|
||||
.alert {
|
||||
background-color: #fef3c7;
|
||||
border: 1px solid #fcd34d;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.expiry-warning {
|
||||
background-color: #fef2f2;
|
||||
border: 1px solid #fca5a5;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
color: #991b1b;
|
||||
}
|
||||
.review-btn {
|
||||
display: inline-block;
|
||||
background-color: #ff7acc;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
margin: 16px 0;
|
||||
}
|
||||
"""
|
||||
|
||||
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
|
||||
|
||||
content = f"""
|
||||
<div class="alert">
|
||||
⏰ Your karaoke video is waiting for you!
|
||||
</div>
|
||||
|
||||
<p>Hi there! Just a friendly reminder that your karaoke video{song_name} is ready for review.</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(review_url)}" class="review-btn">Review Your Video</a>
|
||||
</p>
|
||||
|
||||
<p>During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!</p>
|
||||
|
||||
<p>If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.</p>
|
||||
|
||||
<div class="expiry-warning">
|
||||
⚠️ Please note: if the review isn't completed within the next <strong>24 hours</strong>,
|
||||
the job will automatically expire and your credit will be refunded.
|
||||
</div>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
text_content = (
|
||||
f"Reminder: Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} is ready for review.\n\n"
|
||||
f"Review it here: {review_url}\n\n"
|
||||
"If you're having trouble with the review process, just reply to this email and I'll help you out.\n\n"
|
||||
"Please note: if the review isn't completed within the next 24 hours, "
|
||||
"the job will automatically expire and your credit will be refunded."
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_review_expired(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
credits_balance: int = 0,
|
||||
) -> bool:
|
||||
"""
|
||||
Send review expiry notification email.
|
||||
|
||||
Sent when a job is auto-cancelled after 48 hours in review.
|
||||
Informs the user their credit has been refunded.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
credits_balance: User's current credit balance after refund
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
song_info = f" — {artist} - {title}" if artist and title else ""
|
||||
subject = f"Your karaoke video has expired{song_info}"
|
||||
|
||||
extra_styles = """
|
||||
.info-box {
|
||||
background-color: #f0f9ff;
|
||||
border: 1px solid #93c5fd;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.credit-badge {
|
||||
display: inline-block;
|
||||
background-color: #22c55e;
|
||||
color: #ffffff;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.create-btn {
|
||||
display: inline-block;
|
||||
background-color: #ff7acc;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
margin: 16px 0;
|
||||
}
|
||||
"""
|
||||
|
||||
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
|
||||
|
||||
content = f"""
|
||||
<div class="info-box">
|
||||
Your karaoke video{song_name} has been automatically cancelled because the review
|
||||
wasn't completed within 48 hours.
|
||||
</div>
|
||||
|
||||
<p>Don't worry — your credit has been refunded! Your current balance is
|
||||
<span class="credit-badge">{credits_balance} credit{'s' if credits_balance != 1 else ''}</span>.</p>
|
||||
|
||||
<p>You can create a new karaoke video anytime using your credits:</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(self.frontend_url)}/app" class="create-btn">Create New Video</a>
|
||||
</p>
|
||||
|
||||
<p>If you had any trouble with the review process or need help, just reply to this email — I'd love to help!</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
text_content = (
|
||||
f"Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} has been "
|
||||
"automatically cancelled because the review wasn't completed within 48 hours.\n\n"
|
||||
f"Your credit has been refunded. Current balance: {credits_balance} credit{'s' if credits_balance != 1 else ''}.\n\n"
|
||||
f"Create a new video anytime: {self.frontend_url}/app\n\n"
|
||||
"If you had any trouble or need help, just reply to this email."
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_youtube_upload_complete(
|
||||
self,
|
||||
to_email: str,
|
||||
@@ -1228,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
|
||||
|
||||
|
||||
@@ -3,20 +3,42 @@ Email Validation Service.
|
||||
|
||||
Provides email validation, normalization, and blocklist checking
|
||||
to prevent abuse during enrollment and other flows.
|
||||
|
||||
Uses a tiered disposable domain detection strategy:
|
||||
1. Static blocklist (instant, from Firestore)
|
||||
2. Verified-clean domain cache (skip API calls for 7 days)
|
||||
3. DeBounce API (free, <50ms)
|
||||
4. verifymail.io API (paid, only if DeBounce says clean)
|
||||
|
||||
Auto-learns: flagged domains are persisted to manual_domains,
|
||||
clean domains are cached for 7 days in verified_clean_domains.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, Tuple, Set
|
||||
|
||||
import httpx
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Module-level HTTP client for connection pooling (external API checks)
|
||||
_http_client: Optional[httpx.Client] = None
|
||||
_HTTP_TIMEOUT = 2.0 # seconds per external API call
|
||||
|
||||
|
||||
def _get_http_client() -> httpx.Client:
|
||||
"""Get or create the module-level HTTP client."""
|
||||
global _http_client
|
||||
if _http_client is None or _http_client.is_closed:
|
||||
_http_client = httpx.Client(timeout=_HTTP_TIMEOUT)
|
||||
return _http_client
|
||||
|
||||
|
||||
def _mask_email(email: str) -> str:
|
||||
"""Mask an email address for privacy-safe logging."""
|
||||
@@ -34,164 +56,12 @@ def _mask_email(email: str) -> str:
|
||||
BLOCKLISTS_COLLECTION = "blocklists"
|
||||
BLOCKLIST_CONFIG_DOC = "config"
|
||||
|
||||
# Default disposable email domains (can be extended via admin UI)
|
||||
DEFAULT_DISPOSABLE_DOMAINS = {
|
||||
# Popular temporary email services
|
||||
"10minutemail.com",
|
||||
"10minutemail.net",
|
||||
"guerrillamail.com",
|
||||
"guerrillamail.org",
|
||||
"guerrillamail.net",
|
||||
"guerrillamail.biz",
|
||||
"guerrillamailblock.com",
|
||||
"tempmail.com",
|
||||
"tempmail.net",
|
||||
"temp-mail.org",
|
||||
"temp-mail.io",
|
||||
"throwawaymail.com",
|
||||
"mailinator.com",
|
||||
"mailinator.net",
|
||||
"mailinator.org",
|
||||
"mailinator.info",
|
||||
"maildrop.cc",
|
||||
"yopmail.com",
|
||||
"yopmail.fr",
|
||||
"yopmail.net",
|
||||
"fakeinbox.com",
|
||||
"fakemailgenerator.com",
|
||||
"dispostable.com",
|
||||
"getairmail.com",
|
||||
"getnada.com",
|
||||
"mohmal.com",
|
||||
"trashmail.com",
|
||||
"trashmail.net",
|
||||
"trashmail.org",
|
||||
"sharklasers.com",
|
||||
"grr.la",
|
||||
"guerrillamail.de",
|
||||
"pokemail.net",
|
||||
"spam4.me",
|
||||
"spamgourmet.com",
|
||||
"mytrashmail.com",
|
||||
"mailnesia.com",
|
||||
"mailcatch.com",
|
||||
"mintemail.com",
|
||||
"tempr.email",
|
||||
"tempail.com",
|
||||
"emailondeck.com",
|
||||
"incognitomail.com",
|
||||
"inboxalias.com",
|
||||
"33mail.com",
|
||||
"spamex.com",
|
||||
"spamfree24.org",
|
||||
"spamspot.com",
|
||||
"mailnull.com",
|
||||
"mailsac.com",
|
||||
"emailfake.com",
|
||||
"fakemail.fr",
|
||||
"tempinbox.com",
|
||||
"throwaway.email",
|
||||
"burnermail.io",
|
||||
"anonbox.net",
|
||||
"anonymbox.com",
|
||||
"discard.email",
|
||||
"discardmail.com",
|
||||
"discardmail.de",
|
||||
"mailexpire.com",
|
||||
"mailforspam.com",
|
||||
"meltmail.com",
|
||||
"mt2009.com",
|
||||
"mt2014.com",
|
||||
"nospam.ze.tc",
|
||||
"nospamfor.us",
|
||||
"nowmymail.com",
|
||||
"receiveee.com",
|
||||
"safe-mail.net",
|
||||
"spamavert.com",
|
||||
"spambob.com",
|
||||
"spambog.com",
|
||||
"spambox.us",
|
||||
"spamcannon.com",
|
||||
"spamcannon.net",
|
||||
"spamcon.org",
|
||||
"spamcorptastic.com",
|
||||
"spamday.com",
|
||||
"spamfree.eu",
|
||||
"spamherelots.com",
|
||||
"spamhereplease.com",
|
||||
"spamhole.com",
|
||||
"spamify.com",
|
||||
"spaminator.de",
|
||||
"spamkill.info",
|
||||
"spaml.com",
|
||||
"spaml.de",
|
||||
"spamoff.de",
|
||||
"spamobox.com",
|
||||
"spamslicer.com",
|
||||
"spamstack.net",
|
||||
"spamthis.co.uk",
|
||||
"spamthisplease.com",
|
||||
"supergreatmail.com",
|
||||
"suremail.info",
|
||||
"teleworm.us",
|
||||
"tempemail.co.za",
|
||||
"tempemail.net",
|
||||
"tempmailaddress.com",
|
||||
"tempmailo.com",
|
||||
"thankyou2010.com",
|
||||
"thisisnotmyrealemail.com",
|
||||
"tm.slsrs.ru",
|
||||
"tmpeml.info",
|
||||
"trash-mail.at",
|
||||
"trash-mail.de",
|
||||
"trash2009.com",
|
||||
"trashemail.de",
|
||||
"trashmail.at",
|
||||
"trashmailer.com",
|
||||
"wegwerfmail.de",
|
||||
"wegwerfmail.net",
|
||||
"wegwerfmail.org",
|
||||
"wh4f.org",
|
||||
"willhackforfood.biz",
|
||||
"willselfdestruct.com",
|
||||
"xmaily.com",
|
||||
"xyzfree.net",
|
||||
"yep.it",
|
||||
"yogamaven.com",
|
||||
"yuurok.com",
|
||||
"zehnminutenmail.de",
|
||||
"zippymail.info",
|
||||
# Additional common ones
|
||||
"mailnator.com",
|
||||
"bugmenot.com",
|
||||
"dodgeit.com",
|
||||
"dodgit.com",
|
||||
"e4ward.com",
|
||||
"emailsensei.com",
|
||||
"hushmail.com",
|
||||
"jetable.org",
|
||||
"kasmail.com",
|
||||
"mailblock.net",
|
||||
"mailcatch.com",
|
||||
"mymailoasis.com",
|
||||
"nervmich.net",
|
||||
"nervtmansen.de",
|
||||
"oneoffemail.com",
|
||||
"pookmail.com",
|
||||
"shortmail.net",
|
||||
"sneakemail.com",
|
||||
"sogetthis.com",
|
||||
"tempemailaddress.com",
|
||||
"tempomail.fr",
|
||||
"temporaryemail.net",
|
||||
"temporaryforwarding.com",
|
||||
"temporaryinbox.com",
|
||||
"thankyou2010.com",
|
||||
"tyldd.com",
|
||||
"uggsrock.com",
|
||||
"veryrealemail.com",
|
||||
"yourewronghereswhy.com",
|
||||
}
|
||||
# Legacy default set — kept as empty set for import compatibility.
|
||||
# The external sync (disposable_domain_sync_service) replaces this with ~4,800
|
||||
# domains from the community-curated disposable-email-domains repo.
|
||||
# The migration path in sync_disposable_domains() references this set to ensure
|
||||
# no domains are lost during the transition.
|
||||
DEFAULT_DISPOSABLE_DOMAINS: Set[str] = set()
|
||||
|
||||
# Gmail-like domains that support alias normalization
|
||||
GMAIL_LIKE_DOMAINS = {
|
||||
@@ -199,6 +69,47 @@ GMAIL_LIKE_DOMAINS = {
|
||||
"googlemail.com",
|
||||
}
|
||||
|
||||
# Well-known email providers that are never disposable.
|
||||
# These skip all external API checks for zero-latency validation.
|
||||
WELL_KNOWN_PROVIDERS = {
|
||||
"gmail.com",
|
||||
"googlemail.com",
|
||||
"yahoo.com",
|
||||
"yahoo.co.uk",
|
||||
"yahoo.co.jp",
|
||||
"yahoo.fr",
|
||||
"hotmail.com",
|
||||
"hotmail.co.uk",
|
||||
"outlook.com",
|
||||
"outlook.fr",
|
||||
"live.com",
|
||||
"live.co.uk",
|
||||
"msn.com",
|
||||
"icloud.com",
|
||||
"me.com",
|
||||
"mac.com",
|
||||
"aol.com",
|
||||
"protonmail.com",
|
||||
"proton.me",
|
||||
"zoho.com",
|
||||
"yandex.com",
|
||||
"yandex.ru",
|
||||
"mail.com",
|
||||
"gmx.com",
|
||||
"gmx.de",
|
||||
"fastmail.com",
|
||||
"hey.com",
|
||||
"tutanota.com",
|
||||
"tuta.io",
|
||||
}
|
||||
|
||||
# How long a verified-clean domain result is trusted before re-checking
|
||||
VERIFIED_CLEAN_TTL = timedelta(days=7)
|
||||
|
||||
# External API URLs
|
||||
DEBOUNCE_API_URL = "https://disposable.debounce.io/"
|
||||
VERIFYMAIL_API_URL = "https://verifymail.io/api"
|
||||
|
||||
|
||||
class EmailValidationService:
|
||||
"""
|
||||
@@ -293,17 +204,27 @@ class EmailValidationService:
|
||||
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
if "external_domains" in data:
|
||||
# New data model: effective = (external + manual) - allowlisted
|
||||
external = set(data.get("external_domains", []))
|
||||
manual = set(data.get("manual_domains", []))
|
||||
allowlisted = set(data.get("allowlisted_domains", []))
|
||||
effective_domains = (external | manual) - allowlisted
|
||||
else:
|
||||
# Old data model (pre-migration): use disposable_domains + defaults
|
||||
effective_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
|
||||
config = {
|
||||
"disposable_domains": set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS,
|
||||
"disposable_domains": effective_domains,
|
||||
"blocked_emails": set(data.get("blocked_emails", [])),
|
||||
"blocked_ips": set(data.get("blocked_ips", [])),
|
||||
"verified_clean_domains": data.get("verified_clean_domains", {}),
|
||||
}
|
||||
else:
|
||||
# Use defaults if no config exists
|
||||
config = {
|
||||
"disposable_domains": DEFAULT_DISPOSABLE_DOMAINS.copy(),
|
||||
"blocked_emails": set(),
|
||||
"blocked_ips": set(),
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
|
||||
# Update cache
|
||||
@@ -316,6 +237,16 @@ class EmailValidationService:
|
||||
"""
|
||||
Check if an email uses a disposable domain.
|
||||
|
||||
Uses a tiered checking strategy:
|
||||
0. Well-known providers (gmail, yahoo, etc.) → instant False
|
||||
1. Static blocklist from Firestore → instant
|
||||
2. Verified-clean cache (7-day TTL) → skip API calls
|
||||
3. DeBounce API (free) → fast external check
|
||||
4. verifymail.io API (paid) → only if DeBounce says clean
|
||||
|
||||
Flagged domains are auto-learned to manual_domains.
|
||||
Clean domains are cached for 7 days.
|
||||
|
||||
Args:
|
||||
email: Email address to check
|
||||
|
||||
@@ -326,8 +257,188 @@ class EmailValidationService:
|
||||
return False
|
||||
|
||||
domain = email.lower().split("@")[-1]
|
||||
|
||||
# Tier 0: Well-known providers — skip everything
|
||||
if domain in WELL_KNOWN_PROVIDERS:
|
||||
return False
|
||||
|
||||
# Tier 1: Static blocklist (instant, always available)
|
||||
config = self.get_blocklist_config()
|
||||
return domain in config["disposable_domains"]
|
||||
if domain in config["disposable_domains"]:
|
||||
return True
|
||||
|
||||
# Tier 2: Recently verified clean? Skip API calls
|
||||
if self._is_domain_verified_clean(domain, config):
|
||||
return False
|
||||
|
||||
# Tier 3: DeBounce API (free, fast)
|
||||
debounce_result = self._check_debounce(email)
|
||||
if debounce_result is True:
|
||||
self._auto_learn_domain(domain)
|
||||
return True
|
||||
|
||||
# Tier 4: verifymail.io (paid, only if DeBounce gave definitive clean)
|
||||
if debounce_result is False:
|
||||
verifymail_result = self._check_verifymail(email)
|
||||
if verifymail_result is True:
|
||||
self._auto_learn_domain(domain)
|
||||
return True
|
||||
|
||||
# Both APIs say clean (or errored) — cache clean result
|
||||
if debounce_result is False:
|
||||
self._mark_domain_clean(domain)
|
||||
|
||||
return False
|
||||
|
||||
def _check_debounce(self, email: str) -> Optional[bool]:
|
||||
"""
|
||||
Check email against DeBounce disposable email API.
|
||||
|
||||
Returns:
|
||||
True if disposable, False if clean, None if error/timeout.
|
||||
"""
|
||||
try:
|
||||
client = _get_http_client()
|
||||
response = client.get(DEBOUNCE_API_URL, params={"email": email})
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
result = str(data.get("disposable", "")).lower() == "true"
|
||||
logger.info(
|
||||
f"DeBounce check for {_mask_email(email)}: "
|
||||
f"disposable={result}"
|
||||
)
|
||||
return result
|
||||
except httpx.TimeoutException:
|
||||
logger.warning(f"DeBounce API timeout for {_mask_email(email)}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f"DeBounce API error for {_mask_email(email)}: {e}")
|
||||
return None
|
||||
|
||||
def _check_verifymail(self, email: str) -> Optional[bool]:
|
||||
"""
|
||||
Check email against verifymail.io API.
|
||||
|
||||
Only called when DeBounce says clean (to minimize paid API usage).
|
||||
|
||||
Returns:
|
||||
True if disposable/blocked, False if clean, None if error/timeout
|
||||
or API key not configured.
|
||||
"""
|
||||
api_key = settings.get_secret("verifymail-api-key")
|
||||
if not api_key:
|
||||
logger.debug("verifymail.io API key not configured, skipping")
|
||||
return None
|
||||
|
||||
try:
|
||||
client = _get_http_client()
|
||||
response = client.get(
|
||||
f"{VERIFYMAIL_API_URL}/{email}",
|
||||
params={"key": api_key},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
# verifymail.io returns both "disposable" and "block" flags
|
||||
is_disposable = data.get("disposable") is True
|
||||
is_blocked = data.get("block") is True
|
||||
result = is_disposable or is_blocked
|
||||
logger.info(
|
||||
f"verifymail.io check for {_mask_email(email)}: "
|
||||
f"disposable={is_disposable}, block={is_blocked}"
|
||||
)
|
||||
return result
|
||||
except httpx.TimeoutException:
|
||||
logger.warning(f"verifymail.io API timeout for {_mask_email(email)}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f"verifymail.io API error for {_mask_email(email)}: {e}")
|
||||
return None
|
||||
|
||||
def _is_domain_verified_clean(self, domain: str, config: dict) -> bool:
|
||||
"""Check if a domain was verified clean within the TTL period."""
|
||||
verified = config.get("verified_clean_domains", {})
|
||||
entry = verified.get(domain)
|
||||
if not entry:
|
||||
return False
|
||||
|
||||
checked_at = entry.get("checked_at")
|
||||
if not checked_at:
|
||||
return False
|
||||
|
||||
# Handle both datetime objects and ISO strings
|
||||
if isinstance(checked_at, str):
|
||||
try:
|
||||
checked_at = datetime.fromisoformat(checked_at)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
# Make timezone-aware if naive
|
||||
if checked_at.tzinfo is None:
|
||||
checked_at = checked_at.replace(tzinfo=timezone.utc)
|
||||
|
||||
return (datetime.now(timezone.utc) - checked_at) < VERIFIED_CLEAN_TTL
|
||||
|
||||
def _auto_learn_domain(self, domain: str) -> None:
|
||||
"""
|
||||
Add a domain flagged by external API to manual_domains in Firestore.
|
||||
|
||||
This persists the result so future checks don't need the API call.
|
||||
Fire-and-forget: errors are logged but don't affect the caller.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(
|
||||
BLOCKLIST_CONFIG_DOC
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
manual = set(data.get("manual_domains", []))
|
||||
else:
|
||||
manual = set()
|
||||
|
||||
if domain not in manual:
|
||||
manual.add(domain)
|
||||
doc_ref.set(
|
||||
{
|
||||
"manual_domains": list(manual),
|
||||
"updated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"updated_by": "auto-learn",
|
||||
},
|
||||
merge=True,
|
||||
)
|
||||
logger.info(f"Auto-learned disposable domain: {domain}")
|
||||
|
||||
# Invalidate cache so the domain is blocked immediately
|
||||
EmailValidationService._blocklist_cache = None
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to auto-learn domain {domain}: {e}")
|
||||
|
||||
def _mark_domain_clean(self, domain: str) -> None:
|
||||
"""
|
||||
Record that a domain was verified clean by external APIs.
|
||||
|
||||
Stored in verified_clean_domains dict keyed by domain.
|
||||
Future checks within VERIFIED_CLEAN_TTL will skip API calls.
|
||||
|
||||
Note: Uses read-modify-write instead of dot notation because
|
||||
domain names contain dots which Firestore interprets as nested paths.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(
|
||||
BLOCKLIST_CONFIG_DOC
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
verified = doc.to_dict().get("verified_clean_domains", {}) if doc.exists else {}
|
||||
verified[domain] = {
|
||||
"checked_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
doc_ref.set({"verified_clean_domains": verified}, merge=True)
|
||||
logger.debug(f"Marked domain as verified clean: {domain}")
|
||||
|
||||
# Invalidate cache so new data is picked up
|
||||
EmailValidationService._blocklist_cache = None
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to mark domain clean {domain}: {e}")
|
||||
|
||||
def is_email_blocked(self, email: str) -> bool:
|
||||
"""
|
||||
@@ -398,13 +509,13 @@ class EmailValidationService:
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
domains = set(data.get("disposable_domains", []))
|
||||
domains = set(data.get("manual_domains", []))
|
||||
else:
|
||||
data = {}
|
||||
domains = set()
|
||||
|
||||
domains.add(domain)
|
||||
data["disposable_domains"] = list(domains)
|
||||
data["manual_domains"] = list(domains)
|
||||
data["updated_at"] = datetime.now(timezone.utc)
|
||||
data["updated_by"] = admin_email
|
||||
transaction.set(doc_ref, data, merge=True)
|
||||
@@ -432,14 +543,22 @@ class EmailValidationService:
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
domains = set(data.get("disposable_domains", []))
|
||||
|
||||
if domain not in domains:
|
||||
manual = set(data.get("manual_domains", []))
|
||||
external = set(data.get("external_domains", []))
|
||||
|
||||
if domain in manual:
|
||||
result["found"] = True
|
||||
manual.discard(domain)
|
||||
data["manual_domains"] = list(manual)
|
||||
elif domain in external:
|
||||
result["found"] = True
|
||||
allowlisted = set(data.get("allowlisted_domains", []))
|
||||
allowlisted.add(domain)
|
||||
data["allowlisted_domains"] = list(allowlisted)
|
||||
else:
|
||||
return
|
||||
|
||||
result["found"] = True
|
||||
domains.discard(domain)
|
||||
data["disposable_domains"] = list(domains)
|
||||
data["updated_at"] = datetime.now(timezone.utc)
|
||||
data["updated_by"] = admin_email
|
||||
transaction.set(doc_ref, data, merge=True)
|
||||
@@ -598,14 +717,126 @@ class EmailValidationService:
|
||||
logger.info(f"Removed blocked IP: {ip_address} by {admin_email}")
|
||||
return True
|
||||
|
||||
def add_allowlisted_domain(self, domain: str, admin_email: str) -> bool:
|
||||
"""Add a domain to the allowlisted domains list."""
|
||||
domain = domain.lower().strip()
|
||||
if not domain:
|
||||
return False
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
domains = set(data.get("allowlisted_domains", []))
|
||||
else:
|
||||
data = {}
|
||||
domains = set()
|
||||
|
||||
domains.add(domain)
|
||||
data["allowlisted_domains"] = list(domains)
|
||||
data["updated_at"] = datetime.now(timezone.utc)
|
||||
data["updated_by"] = admin_email
|
||||
transaction.set(doc_ref, data, merge=True)
|
||||
|
||||
transaction = self.db.transaction()
|
||||
update_in_transaction(transaction, doc_ref)
|
||||
|
||||
# Invalidate cache
|
||||
EmailValidationService._blocklist_cache = None
|
||||
|
||||
logger.info(f"Added allowlisted domain: {domain} by {admin_email}")
|
||||
return True
|
||||
|
||||
def remove_allowlisted_domain(self, domain: str, admin_email: str) -> bool:
|
||||
"""Remove a domain from the allowlisted domains list."""
|
||||
domain = domain.lower().strip()
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
result = {"found": False}
|
||||
|
||||
@firestore.transactional
|
||||
def remove_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if not doc.exists:
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
domains = set(data.get("allowlisted_domains", []))
|
||||
|
||||
if domain not in domains:
|
||||
return
|
||||
|
||||
result["found"] = True
|
||||
domains.discard(domain)
|
||||
data["allowlisted_domains"] = list(domains)
|
||||
data["updated_at"] = datetime.now(timezone.utc)
|
||||
data["updated_by"] = admin_email
|
||||
transaction.set(doc_ref, data, merge=True)
|
||||
|
||||
transaction = self.db.transaction()
|
||||
remove_in_transaction(transaction, doc_ref)
|
||||
|
||||
if not result["found"]:
|
||||
return False
|
||||
|
||||
# Invalidate cache
|
||||
EmailValidationService._blocklist_cache = None
|
||||
|
||||
logger.info(f"Removed allowlisted domain: {domain} by {admin_email}")
|
||||
return True
|
||||
|
||||
def get_blocklist_raw_data(self) -> dict:
|
||||
"""Get raw blocklist data for admin display (not the effective set)."""
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return {
|
||||
"external_domains": [], "manual_domains": [], "allowlisted_domains": [],
|
||||
"blocked_emails": [], "blocked_ips": [],
|
||||
"last_sync_at": None, "last_sync_count": None,
|
||||
"updated_at": None, "updated_by": None,
|
||||
}
|
||||
data = doc.to_dict()
|
||||
return {
|
||||
"external_domains": sorted(data.get("external_domains", [])),
|
||||
"manual_domains": sorted(data.get("manual_domains", [])),
|
||||
"allowlisted_domains": sorted(data.get("allowlisted_domains", [])),
|
||||
"blocked_emails": sorted(data.get("blocked_emails", [])),
|
||||
"blocked_ips": sorted(data.get("blocked_ips", [])),
|
||||
"last_sync_at": data.get("last_sync_at"),
|
||||
"last_sync_count": data.get("last_sync_count"),
|
||||
"updated_at": data.get("updated_at"),
|
||||
"updated_by": data.get("updated_by"),
|
||||
}
|
||||
|
||||
def get_blocklist_stats(self) -> dict:
|
||||
"""Get statistics about current blocklists."""
|
||||
config = self.get_blocklist_config(force_refresh=True)
|
||||
|
||||
# Also get raw data for detailed counts
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
doc = doc_ref.get()
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
external_count = len(data.get("external_domains", []))
|
||||
manual_count = len(data.get("manual_domains", []))
|
||||
allowlisted_count = len(data.get("allowlisted_domains", []))
|
||||
else:
|
||||
external_count = 0
|
||||
manual_count = 0
|
||||
allowlisted_count = 0
|
||||
|
||||
return {
|
||||
"disposable_domains_count": len(config["disposable_domains"]),
|
||||
"blocked_emails_count": len(config["blocked_emails"]),
|
||||
"blocked_ips_count": len(config["blocked_ips"]),
|
||||
"default_disposable_domains_count": len(DEFAULT_DISPOSABLE_DOMAINS),
|
||||
"external_domains_count": external_count,
|
||||
"manual_domains_count": manual_count,
|
||||
"allowlisted_domains_count": allowlisted_count,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -383,6 +383,8 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
output_files["mp4_4k_lossy"] = path
|
||||
elif "720p" in filename_lower:
|
||||
output_files["mp4_720p"] = path
|
||||
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
|
||||
output_files["with_vocals_mp4"] = path
|
||||
self.logger.info(f"Converted output_files list to dict: {output_files}")
|
||||
else:
|
||||
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
|
||||
@@ -393,6 +395,7 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
lossy_4k_mp4_path=output_files.get("mp4_4k_lossy"),
|
||||
lossless_mkv_path=output_files.get("mkv_4k"),
|
||||
lossy_720p_mp4_path=output_files.get("mp4_720p"),
|
||||
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
|
||||
output_files=output_files,
|
||||
encoding_time_seconds=encoding_time,
|
||||
encoding_backend=self.name
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
@@ -871,12 +871,14 @@ class FirestoreService:
|
||||
|
||||
# Collection group query across all jobs
|
||||
sessions_ref = self.db.collection_group("review_sessions")
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
|
||||
docs = query.stream()
|
||||
results = [doc.to_dict() for doc in docs]
|
||||
|
||||
# Filter in Python for text search (Firestore doesn't support LIKE)
|
||||
if query_text:
|
||||
# Over-fetch since we filter in Python (Firestore doesn't support LIKE/contains)
|
||||
fetch_limit = max(limit * 25, 500)
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(fetch_limit)
|
||||
docs = query.stream()
|
||||
results = [doc.to_dict() for doc in docs]
|
||||
|
||||
q_lower = query_text.lower()
|
||||
results = [
|
||||
r for r in results
|
||||
@@ -884,8 +886,11 @@ class FirestoreService:
|
||||
or q_lower in (r.get("title") or "").lower()
|
||||
or q_lower in (r.get("job_id") or "").lower()
|
||||
]
|
||||
|
||||
return results
|
||||
return results[:limit]
|
||||
else:
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
|
||||
docs = query.stream()
|
||||
return [doc.to_dict() for doc in docs]
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error searching review sessions: {e}")
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"""
|
||||
IP geolocation service with Firestore caching.
|
||||
|
||||
Looks up IP addresses via ip-api.com (free, no key needed) and caches
|
||||
results in Firestore to avoid repeated lookups. Used by admin UI to
|
||||
enrich IP displays with country, city, ISP, and ASN info.
|
||||
"""
|
||||
import ipaddress
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, List
|
||||
|
||||
import httpx
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
IP_GEOLOCATION_COLLECTION = "ip_geolocation"
|
||||
CACHE_TTL_DAYS = 90 # Cache results for 90 days
|
||||
IP_API_URL = "http://ip-api.com/json"
|
||||
IP_API_BATCH_URL = "http://ip-api.com/batch"
|
||||
IP_API_FIELDS = "status,country,countryCode,regionName,city,isp,org,as,timezone,query"
|
||||
RATE_LIMIT_PER_MINUTE = 45
|
||||
|
||||
|
||||
def _is_private_ip(ip: str) -> bool:
|
||||
"""Check if an IP is private/reserved (not routable on the internet)."""
|
||||
try:
|
||||
addr = ipaddress.ip_address(ip)
|
||||
return addr.is_private or addr.is_reserved or addr.is_loopback or addr.is_link_local
|
||||
except ValueError:
|
||||
return True # Invalid IP
|
||||
|
||||
|
||||
def _parse_ip_api_response(data: dict) -> dict:
|
||||
"""Parse ip-api.com response into our standard format."""
|
||||
if data.get("status") != "success":
|
||||
return {
|
||||
"status": "fail",
|
||||
"ip": data.get("query", ""),
|
||||
"cached_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
|
||||
# Parse AS field: "AS14615 Comporium Inc" -> number + name
|
||||
as_field = data.get("as", "")
|
||||
as_number = ""
|
||||
as_name = ""
|
||||
if as_field:
|
||||
parts = as_field.split(" ", 1)
|
||||
as_number = parts[0] if parts else ""
|
||||
as_name = parts[1] if len(parts) > 1 else ""
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"ip": data.get("query", ""),
|
||||
"country": data.get("country", ""),
|
||||
"country_code": data.get("countryCode", ""),
|
||||
"region": data.get("regionName", ""),
|
||||
"city": data.get("city", ""),
|
||||
"isp": data.get("isp", ""),
|
||||
"org": data.get("org", ""),
|
||||
"as_number": as_number,
|
||||
"as_name": as_name,
|
||||
"timezone": data.get("timezone", ""),
|
||||
"cached_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
|
||||
|
||||
class IpGeolocationService:
|
||||
"""IP geolocation lookup with Firestore caching."""
|
||||
|
||||
def __init__(self):
|
||||
settings = get_settings()
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
self._last_request_times: List[float] = []
|
||||
|
||||
def _check_rate_limit(self):
|
||||
"""Simple rate limiter — sleep if approaching 45 req/min."""
|
||||
now = time.time()
|
||||
# Remove entries older than 60 seconds
|
||||
self._last_request_times = [
|
||||
t for t in self._last_request_times if now - t < 60
|
||||
]
|
||||
if len(self._last_request_times) >= RATE_LIMIT_PER_MINUTE - 5:
|
||||
# Getting close to limit, wait
|
||||
sleep_time = 60 - (now - self._last_request_times[0])
|
||||
if sleep_time > 0:
|
||||
logger.info(f"IP geolocation rate limit: sleeping {sleep_time:.1f}s")
|
||||
time.sleep(sleep_time)
|
||||
self._last_request_times.append(time.time())
|
||||
|
||||
def _get_cached(self, ip: str) -> Optional[dict]:
|
||||
"""Get cached geolocation data for an IP."""
|
||||
try:
|
||||
# Firestore doc IDs can't contain '/' so IPv6 with :: is fine,
|
||||
# but we need to sanitize for doc ID
|
||||
doc_id = ip.replace("/", "_")
|
||||
doc = self.db.collection(IP_GEOLOCATION_COLLECTION).document(doc_id).get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
|
||||
data = doc.to_dict()
|
||||
|
||||
# Check TTL
|
||||
cached_at = data.get("cached_at", "")
|
||||
if cached_at:
|
||||
try:
|
||||
cached_dt = datetime.fromisoformat(cached_at)
|
||||
if datetime.utcnow() - cached_dt > timedelta(days=CACHE_TTL_DAYS):
|
||||
return None # Expired
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
return data
|
||||
except Exception:
|
||||
logger.exception(f"Error reading IP geo cache for {ip}")
|
||||
return None
|
||||
|
||||
def _cache_result(self, ip: str, data: dict):
|
||||
"""Store geolocation result in Firestore cache."""
|
||||
try:
|
||||
doc_id = ip.replace("/", "_")
|
||||
self.db.collection(IP_GEOLOCATION_COLLECTION).document(doc_id).set(data)
|
||||
except Exception:
|
||||
logger.exception(f"Error caching IP geo for {ip}")
|
||||
|
||||
def lookup_ip(self, ip: str) -> dict:
|
||||
"""
|
||||
Look up geolocation for a single IP address.
|
||||
|
||||
Returns cached result if available, otherwise queries ip-api.com.
|
||||
"""
|
||||
if not ip or _is_private_ip(ip):
|
||||
return {"status": "private", "ip": ip or ""}
|
||||
|
||||
# Check cache
|
||||
cached = self._get_cached(ip)
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
# Query ip-api.com
|
||||
try:
|
||||
self._check_rate_limit()
|
||||
with httpx.Client(timeout=10) as client:
|
||||
response = client.get(
|
||||
f"{IP_API_URL}/{ip}",
|
||||
params={"fields": IP_API_FIELDS},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
result = _parse_ip_api_response(data)
|
||||
self._cache_result(ip, result)
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error looking up IP {ip}")
|
||||
return {"status": "error", "ip": ip}
|
||||
|
||||
def lookup_ips_batch(self, ips: List[str]) -> Dict[str, dict]:
|
||||
"""
|
||||
Look up geolocation for multiple IPs.
|
||||
|
||||
Returns dict of ip -> geo data. Uses cache for known IPs,
|
||||
batches uncached lookups to ip-api.com.
|
||||
"""
|
||||
results = {}
|
||||
uncached = []
|
||||
|
||||
for ip in set(ips): # Deduplicate
|
||||
if not ip or _is_private_ip(ip):
|
||||
results[ip] = {"status": "private", "ip": ip or ""}
|
||||
continue
|
||||
|
||||
cached = self._get_cached(ip)
|
||||
if cached:
|
||||
results[ip] = cached
|
||||
else:
|
||||
uncached.append(ip)
|
||||
|
||||
if not uncached:
|
||||
return results
|
||||
|
||||
# ip-api.com batch endpoint accepts up to 100 IPs per request
|
||||
for i in range(0, len(uncached), 100):
|
||||
batch = uncached[i:i + 100]
|
||||
try:
|
||||
self._check_rate_limit()
|
||||
# Batch endpoint takes a JSON array of IPs
|
||||
payload = [
|
||||
{"query": ip, "fields": IP_API_FIELDS}
|
||||
for ip in batch
|
||||
]
|
||||
with httpx.Client(timeout=15) as client:
|
||||
response = client.post(IP_API_BATCH_URL, json=payload)
|
||||
response.raise_for_status()
|
||||
batch_results = response.json()
|
||||
|
||||
for data in batch_results:
|
||||
result = _parse_ip_api_response(data)
|
||||
ip = result.get("ip", data.get("query", ""))
|
||||
if ip:
|
||||
results[ip] = result
|
||||
self._cache_result(ip, result)
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error in batch IP lookup ({len(batch)} IPs)")
|
||||
# Mark failed IPs
|
||||
for ip in batch:
|
||||
if ip not in results:
|
||||
results[ip] = {"status": "error", "ip": ip}
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# Global instance
|
||||
_service = None
|
||||
|
||||
|
||||
def get_ip_geolocation_service() -> IpGeolocationService:
|
||||
"""Get the global IP geolocation service instance."""
|
||||
global _service
|
||||
if _service is None:
|
||||
_service = IpGeolocationService()
|
||||
return _service
|
||||
@@ -931,22 +931,22 @@ class JobManager:
|
||||
|
||||
def check_parallel_processing_complete(self, job_id: str) -> bool:
|
||||
"""
|
||||
Check if both parallel tracks (audio + lyrics) are complete.
|
||||
|
||||
This is called after audio_complete or lyrics_complete to determine
|
||||
if we can proceed to screen generation.
|
||||
|
||||
Check if lyrics processing is complete (sufficient for screen generation).
|
||||
|
||||
Audio separation is decoupled from the critical path — users can start
|
||||
reviewing lyrics while separation continues in the background. The
|
||||
instrumental review page handles the case where separation isn't done yet.
|
||||
|
||||
Returns:
|
||||
True if both tracks complete, False otherwise
|
||||
True if lyrics are complete, False otherwise
|
||||
"""
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
return False
|
||||
|
||||
audio_complete = job.state_data.get('audio_complete', False)
|
||||
|
||||
lyrics_complete = job.state_data.get('lyrics_complete', False)
|
||||
|
||||
return audio_complete and lyrics_complete
|
||||
|
||||
return lyrics_complete
|
||||
|
||||
async def start_job_processing(
|
||||
self,
|
||||
@@ -1022,30 +1022,25 @@ class JobManager:
|
||||
|
||||
def mark_audio_complete(self, job_id: str) -> None:
|
||||
"""
|
||||
Mark audio processing as complete and check if can proceed.
|
||||
|
||||
If lyrics are also complete, automatically triggers screens worker.
|
||||
Mark audio processing as complete.
|
||||
|
||||
Audio completion is decoupled from the lyrics review path — it no longer
|
||||
triggers screens. The instrumental review page polls for this flag.
|
||||
"""
|
||||
self.update_state_data(job_id, 'audio_complete', True)
|
||||
|
||||
if self.check_parallel_processing_complete(job_id):
|
||||
logger.info(f"Job {job_id}: Both audio and lyrics complete, triggering screens worker")
|
||||
# Transition happens in screens worker
|
||||
# We just trigger it here
|
||||
self._trigger_screens_worker(job_id)
|
||||
|
||||
logger.info(f"Job {job_id}: Audio processing complete (separation finished)")
|
||||
|
||||
def mark_lyrics_complete(self, job_id: str) -> None:
|
||||
"""
|
||||
Mark lyrics processing as complete and check if can proceed.
|
||||
|
||||
If audio is also complete, automatically triggers screens worker.
|
||||
Mark lyrics processing as complete and trigger screens if ready.
|
||||
|
||||
Lyrics completion is the sole gate for screen generation and review.
|
||||
Audio separation runs independently in the background.
|
||||
"""
|
||||
self.update_state_data(job_id, 'lyrics_complete', True)
|
||||
|
||||
|
||||
if self.check_parallel_processing_complete(job_id):
|
||||
logger.info(f"Job {job_id}: Both audio and lyrics complete, triggering screens worker")
|
||||
# Transition happens in screens worker
|
||||
# We just trigger it here
|
||||
logger.info(f"Job {job_id}: Lyrics complete, triggering screens worker")
|
||||
self._trigger_screens_worker(job_id)
|
||||
|
||||
def _trigger_screens_worker(self, job_id: str) -> None:
|
||||
|
||||
@@ -545,7 +545,10 @@ class LocalEncodingService:
|
||||
)
|
||||
output_files["with_vocals_mp4"] = config.output_with_vocals_mp4
|
||||
else:
|
||||
self.logger.info("[Step 2/6] Skipped - video already MP4")
|
||||
self.logger.info("[Step 2/6] Skipped - video already MP4, copying as-is")
|
||||
import shutil
|
||||
shutil.copy2(config.karaoke_video, config.output_with_vocals_mp4)
|
||||
output_files["with_vocals_mp4"] = config.output_with_vocals_mp4
|
||||
|
||||
# Step 3: Encode lossless 4K MP4
|
||||
if config.output_lossless_4k_mp4:
|
||||
|
||||
@@ -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."""
|
||||
@@ -107,15 +107,23 @@ class UserService:
|
||||
logger.exception(f"Error getting user {email}")
|
||||
return None
|
||||
|
||||
def get_or_create_user(self, email: str, tenant_id: Optional[str] = None) -> User:
|
||||
def get_or_create_user(
|
||||
self,
|
||||
email: str,
|
||||
tenant_id: Optional[str] = None,
|
||||
signup_ip: Optional[str] = None,
|
||||
device_fingerprint: Optional[str] = None,
|
||||
) -> User:
|
||||
"""
|
||||
Get existing user or create a new one.
|
||||
|
||||
New users receive a welcome credit to try the service.
|
||||
Welcome credits are granted on first magic link verification, not here.
|
||||
|
||||
Args:
|
||||
email: User's email address
|
||||
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
|
||||
signup_ip: Client IP address at signup (for rate limiting)
|
||||
device_fingerprint: Browser fingerprint at signup (for rate limiting)
|
||||
|
||||
Note: If user exists but has a different tenant_id, the existing user is returned.
|
||||
Users are uniquely identified by email, not email+tenant.
|
||||
@@ -129,22 +137,17 @@ class UserService:
|
||||
# (though features may be restricted per-tenant)
|
||||
return user
|
||||
|
||||
# Create new user with welcome credit
|
||||
welcome_credit = self.NEW_USER_FREE_CREDITS
|
||||
welcome_transaction = CreditTransaction(
|
||||
id=str(uuid.uuid4()),
|
||||
amount=welcome_credit,
|
||||
reason="welcome_credit",
|
||||
)
|
||||
|
||||
# Create new user with zero credits (welcome credits granted on first verification)
|
||||
user = User(
|
||||
email=email,
|
||||
credits=welcome_credit,
|
||||
credit_transactions=[welcome_transaction],
|
||||
credits=0,
|
||||
credit_transactions=[],
|
||||
tenant_id=tenant_id, # Associate with tenant on creation
|
||||
signup_ip=signup_ip,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
self._save_user(user)
|
||||
logger.info(f"Created new user: {email} with {welcome_credit} welcome credit(s) (tenant: {tenant_id or 'default'})")
|
||||
logger.info(f"Created new user: {email} (tenant: {tenant_id or 'default'}) — credits pending verification")
|
||||
return user
|
||||
|
||||
def _save_user(self, user: User) -> None:
|
||||
@@ -213,7 +216,8 @@ class UserService:
|
||||
email: str,
|
||||
ip_address: Optional[str] = None,
|
||||
user_agent: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
tenant_id: Optional[str] = None,
|
||||
device_fingerprint: Optional[str] = None,
|
||||
) -> MagicLinkToken:
|
||||
"""
|
||||
Create a magic link token for email authentication.
|
||||
@@ -226,11 +230,17 @@ class UserService:
|
||||
ip_address: Client IP for auditing
|
||||
user_agent: Client user agent for auditing
|
||||
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
|
||||
device_fingerprint: Browser fingerprint for anti-abuse
|
||||
"""
|
||||
email = email.lower()
|
||||
|
||||
# Ensure user exists (with tenant association)
|
||||
self.get_or_create_user(email, tenant_id=tenant_id)
|
||||
# Ensure user exists (with tenant association, signup IP, and fingerprint)
|
||||
self.get_or_create_user(
|
||||
email,
|
||||
tenant_id=tenant_id,
|
||||
signup_ip=ip_address,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Generate secure token
|
||||
token = secrets.token_urlsafe(32)
|
||||
@@ -242,6 +252,7 @@ class UserService:
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Save to Firestore
|
||||
@@ -359,6 +370,400 @@ 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,
|
||||
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:
|
||||
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, "not_found"
|
||||
|
||||
# Primary check: dedicated flag (survives transaction list trimming)
|
||||
if user.welcome_credits_granted:
|
||||
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_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
|
||||
transaction = CreditTransaction(
|
||||
id=str(uuid.uuid4()),
|
||||
amount=welcome_credit,
|
||||
reason="welcome_credit",
|
||||
)
|
||||
|
||||
transactions = user.credit_transactions[-MAX_CREDIT_TRANSACTIONS + 1:]
|
||||
transactions.append(transaction)
|
||||
|
||||
new_balance = user.credits + welcome_credit
|
||||
self.update_user(
|
||||
email,
|
||||
credits=new_balance,
|
||||
credit_transactions=[t.model_dump(mode='json') for t in transactions],
|
||||
welcome_credits_granted=True,
|
||||
)
|
||||
|
||||
logger.info(f"Granted {welcome_credit} welcome credits to {email}")
|
||||
return True, "granted"
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error granting welcome credits to {email}")
|
||||
return False, "error"
|
||||
|
||||
# =========================================================================
|
||||
# Anti-Abuse Rate Limiting
|
||||
# =========================================================================
|
||||
|
||||
# Maximum new signups allowed per IP address in the rate limit window
|
||||
MAX_SIGNUPS_PER_IP = 2
|
||||
SIGNUP_RATE_LIMIT_HOURS = 24
|
||||
|
||||
def count_recent_signups_from_ip(self, ip_address: str, hours: int = 24) -> int:
|
||||
"""
|
||||
Count new user accounts created from this IP in the last N hours.
|
||||
|
||||
Queries gen_users where signup_ip matches and created_at is recent.
|
||||
Used to rate-limit new account creation per IP address.
|
||||
|
||||
Args:
|
||||
ip_address: Client IP to check
|
||||
hours: Lookback window in hours (default: 24)
|
||||
|
||||
Returns:
|
||||
Number of recent signups from this IP
|
||||
"""
|
||||
try:
|
||||
cutoff = datetime.utcnow() - timedelta(hours=hours)
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("signup_ip", "==", ip_address))
|
||||
.where(filter=FieldFilter("created_at", ">=", cutoff))
|
||||
)
|
||||
|
||||
count = 0
|
||||
for _ in query.stream():
|
||||
count += 1
|
||||
return count
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error counting signups from IP {ip_address}")
|
||||
# On error, don't block — return 0 to allow the request
|
||||
return 0
|
||||
|
||||
def count_recent_signups_from_fingerprint(
|
||||
self, device_fingerprint: str, hours: int = 24
|
||||
) -> int:
|
||||
"""
|
||||
Count new user accounts created with this device fingerprint in the last N hours.
|
||||
|
||||
Args:
|
||||
device_fingerprint: Browser fingerprint to check
|
||||
hours: Lookback window in hours (default: 24)
|
||||
|
||||
Returns:
|
||||
Number of recent signups from this fingerprint
|
||||
"""
|
||||
try:
|
||||
cutoff = datetime.utcnow() - timedelta(hours=hours)
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("device_fingerprint", "==", device_fingerprint))
|
||||
.where(filter=FieldFilter("created_at", ">=", cutoff))
|
||||
)
|
||||
|
||||
count = 0
|
||||
for _ in query.stream():
|
||||
count += 1
|
||||
return count
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error counting signups from fingerprint")
|
||||
return 0
|
||||
|
||||
def is_signup_rate_limited(
|
||||
self, ip_address: Optional[str] = None, device_fingerprint: Optional[str] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Check if a signup should be rate limited based on IP and/or fingerprint.
|
||||
|
||||
Either signal hitting the limit triggers a block.
|
||||
"""
|
||||
if ip_address:
|
||||
ip_count = self.count_recent_signups_from_ip(
|
||||
ip_address, hours=self.SIGNUP_RATE_LIMIT_HOURS
|
||||
)
|
||||
if ip_count >= self.MAX_SIGNUPS_PER_IP:
|
||||
return True
|
||||
|
||||
if device_fingerprint:
|
||||
fp_count = self.count_recent_signups_from_fingerprint(
|
||||
device_fingerprint, hours=self.SIGNUP_RATE_LIMIT_HOURS
|
||||
)
|
||||
if fp_count >= self.MAX_SIGNUPS_PER_IP:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
# =========================================================================
|
||||
# Anti-Abuse Investigation
|
||||
# =========================================================================
|
||||
|
||||
def find_users_by_signup_ip(self, ip_address: str) -> List[User]:
|
||||
"""Find all users who signed up from this IP address."""
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("signup_ip", "==", ip_address))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(50)
|
||||
)
|
||||
return [User(**doc.to_dict()) for doc in query.stream()]
|
||||
except Exception:
|
||||
logger.exception(f"Error finding users by IP {ip_address}")
|
||||
return []
|
||||
|
||||
def find_users_by_fingerprint(self, device_fingerprint: str) -> List[User]:
|
||||
"""Find all users who signed up with this device fingerprint."""
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("device_fingerprint", "==", device_fingerprint))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(50)
|
||||
)
|
||||
return [User(**doc.to_dict()) for doc in query.stream()]
|
||||
except Exception:
|
||||
logger.exception(f"Error finding users by fingerprint")
|
||||
return []
|
||||
|
||||
def find_suspicious_accounts(self, min_jobs: int = 2, max_spend: int = 0) -> List[User]:
|
||||
"""
|
||||
Find accounts with many jobs but no spend (potential free-credit abusers).
|
||||
|
||||
Args:
|
||||
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)
|
||||
.where(filter=FieldFilter("total_jobs_created", ">=", min_jobs))
|
||||
.order_by("total_jobs_created", direction=firestore.Query.DESCENDING)
|
||||
.limit(100)
|
||||
)
|
||||
users = []
|
||||
for doc in query.stream():
|
||||
user = User(**doc.to_dict())
|
||||
if user.total_spent <= max_spend and not is_internal_or_test_email(user.email):
|
||||
users.append(user)
|
||||
return users
|
||||
except Exception:
|
||||
logger.exception("Error finding suspicious accounts")
|
||||
return []
|
||||
|
||||
def find_related_accounts(self, email: str) -> dict:
|
||||
"""
|
||||
Given a user email, find all accounts that share the same signup IP
|
||||
or device fingerprint. Returns a dict with grouped results.
|
||||
"""
|
||||
user = self.get_user(email)
|
||||
if not user:
|
||||
return {"user": None, "by_ip": [], "by_fingerprint": []}
|
||||
|
||||
by_ip = []
|
||||
if user.signup_ip:
|
||||
by_ip = [
|
||||
u for u in self.find_users_by_signup_ip(user.signup_ip)
|
||||
if u.email != user.email
|
||||
]
|
||||
|
||||
by_fingerprint = []
|
||||
if user.device_fingerprint:
|
||||
by_fingerprint = [
|
||||
u for u in self.find_users_by_fingerprint(user.device_fingerprint)
|
||||
if u.email != user.email
|
||||
]
|
||||
|
||||
return {
|
||||
"user": user,
|
||||
"by_ip": by_ip,
|
||||
"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
|
||||
# =========================================================================
|
||||
@@ -368,7 +773,8 @@ class UserService:
|
||||
user_email: str,
|
||||
ip_address: Optional[str] = None,
|
||||
user_agent: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
tenant_id: Optional[str] = None,
|
||||
device_fingerprint: Optional[str] = None,
|
||||
) -> Session:
|
||||
"""
|
||||
Create a new session for an authenticated user.
|
||||
@@ -378,6 +784,7 @@ class UserService:
|
||||
ip_address: Client IP for auditing
|
||||
user_agent: Client user agent for auditing
|
||||
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
|
||||
device_fingerprint: Browser fingerprint for cross-account correlation
|
||||
"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
token_prefix = token[:12]
|
||||
@@ -389,6 +796,7 @@ class UserService:
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Serialize and write to Firestore
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,833 @@
|
||||
"""
|
||||
Tests for anti-abuse improvements: credits on verification, IP rate limiting,
|
||||
and device fingerprinting.
|
||||
|
||||
Covers:
|
||||
- Phase 1: Welcome credits granted on verification, not account creation
|
||||
- Phase 2: Per-IP signup rate limiting (2 new accounts per 24h)
|
||||
- Phase 3: Device fingerprint rate limiting
|
||||
"""
|
||||
import pytest
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import MagicMock, Mock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
# Mock Firestore before importing modules that use it
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
from backend.models.user import (
|
||||
User,
|
||||
MagicLinkToken,
|
||||
CreditTransaction,
|
||||
SendMagicLinkRequest,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Phase 1: Credits on Verification
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGetOrCreateUserNoCredits:
|
||||
"""New users should be created with 0 credits."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_new_user_created_with_zero_credits(self, mock_fs, mock_settings):
|
||||
"""get_or_create_user creates users with 0 credits."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# Simulate user not found
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
user = service.get_or_create_user("new@example.com")
|
||||
|
||||
assert user.credits == 0
|
||||
assert user.credit_transactions == []
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_new_user_stores_signup_ip(self, mock_fs, mock_settings):
|
||||
"""get_or_create_user stores the signup IP."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
user = service.get_or_create_user(
|
||||
"new@example.com", signup_ip="1.2.3.4"
|
||||
)
|
||||
|
||||
assert user.signup_ip == "1.2.3.4"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_new_user_stores_device_fingerprint(self, mock_fs, mock_settings):
|
||||
"""get_or_create_user stores the device fingerprint."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
user = service.get_or_create_user(
|
||||
"new@example.com", device_fingerprint="abc123"
|
||||
)
|
||||
|
||||
assert user.device_fingerprint == "abc123"
|
||||
|
||||
|
||||
class TestGrantWelcomeCredits:
|
||||
"""Welcome credits should be granted on first verification."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_grants_credits_to_new_user(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible grants credits to user without welcome_credit txn."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User exists with 0 credits and no transactions
|
||||
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:
|
||||
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 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'] == 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):
|
||||
"""grant_welcome_credits_if_eligible returns False if welcome_credits_granted flag is True."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User has the flag set (even if transactions were trimmed)
|
||||
user = User(
|
||||
email="existing@example.com",
|
||||
credits=2,
|
||||
welcome_credits_granted=True,
|
||||
)
|
||||
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()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
|
||||
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_if_transaction_exists(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible returns False if welcome_credit txn exists (secondary check)."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User has transaction but flag not set (legacy user)
|
||||
user = User(
|
||||
email="existing@example.com",
|
||||
credits=2,
|
||||
welcome_credits_granted=False,
|
||||
credit_transactions=[
|
||||
CreditTransaction(
|
||||
id=str(uuid.uuid4()),
|
||||
amount=2,
|
||||
reason="welcome_credit",
|
||||
)
|
||||
],
|
||||
)
|
||||
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()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
|
||||
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_returns_false_for_nonexistent_user(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible returns False for unknown user."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("ghost@example.com")
|
||||
|
||||
assert granted is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Phase 2: Per-IP Signup Rate Limiting
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestIPRateLimiting:
|
||||
"""Test IP-based signup rate limiting."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_count_recent_signups_from_ip(self, mock_fs, mock_settings):
|
||||
"""count_recent_signups_from_ip counts matching users."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# Simulate 2 matching users
|
||||
mock_docs = [MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
count = service.count_recent_signups_from_ip("1.2.3.4")
|
||||
|
||||
assert count == 2
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_is_signup_rate_limited_by_ip(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited returns True when IP count >= 2."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# 2 signups = rate limited
|
||||
mock_docs = [MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
assert service.is_signup_rate_limited(ip_address="1.2.3.4") is True
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_not_rate_limited_with_one_signup(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited returns False when IP count < 2."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_docs = [MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
assert service.is_signup_rate_limited(ip_address="1.2.3.4") is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_no_ip_not_rate_limited(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited returns False when no IP provided."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
assert service.is_signup_rate_limited(ip_address=None) is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Phase 3: Device Fingerprint Rate Limiting
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestFingerprintRateLimiting:
|
||||
"""Test fingerprint-based signup rate limiting."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_count_recent_signups_from_fingerprint(self, mock_fs, mock_settings):
|
||||
"""count_recent_signups_from_fingerprint counts matching users."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_docs = [MagicMock(), MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
count = service.count_recent_signups_from_fingerprint("fp123")
|
||||
|
||||
assert count == 3
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_is_signup_rate_limited_by_fingerprint(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited returns True when fingerprint count >= 2."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# IP returns 0, fingerprint returns 2
|
||||
def side_effect_stream():
|
||||
return iter([MagicMock(), MagicMock()])
|
||||
|
||||
# We need separate mock chains for IP and fingerprint queries
|
||||
# Since both use the same mock chain, we'll set up the calls differently
|
||||
call_count = [0]
|
||||
def stream_side_effect():
|
||||
call_count[0] += 1
|
||||
if call_count[0] == 1:
|
||||
return iter([]) # IP query: 0 results
|
||||
return iter([MagicMock(), MagicMock()]) # Fingerprint query: 2 results
|
||||
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream = stream_side_effect
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.is_signup_rate_limited(
|
||||
ip_address="1.2.3.4", device_fingerprint="fp123"
|
||||
)
|
||||
|
||||
assert result is True
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_no_fingerprint_not_rate_limited(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited doesn't check fingerprint when None."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# IP query returns 0
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.is_signup_rate_limited(
|
||||
ip_address="1.2.3.4", device_fingerprint=None
|
||||
)
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Integration: Magic Link Endpoint Rate Limiting
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_validation_svc():
|
||||
"""Create a mock EmailValidationService."""
|
||||
svc = MagicMock()
|
||||
svc.is_disposable_domain.return_value = False
|
||||
svc.is_email_blocked.return_value = False
|
||||
svc.is_ip_blocked.return_value = False
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_svc():
|
||||
"""Create a mock UserService."""
|
||||
svc = MagicMock()
|
||||
svc.get_user.return_value = None # New user by default
|
||||
svc.is_signup_rate_limited.return_value = False
|
||||
svc.create_magic_link.return_value = MagicLinkToken(
|
||||
token="test-token",
|
||||
email="test@example.com",
|
||||
expires_at=datetime.utcnow() + timedelta(minutes=15),
|
||||
)
|
||||
svc.NEW_USER_FREE_CREDITS = 1
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_email_svc():
|
||||
"""Create a mock EmailService."""
|
||||
svc = MagicMock()
|
||||
svc.is_configured.return_value = True
|
||||
svc.send_magic_link.return_value = True
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_validation_svc, mock_user_svc, mock_email_svc):
|
||||
"""Create TestClient with mocked services via FastAPI dependency overrides."""
|
||||
from backend.main import app
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
|
||||
app.dependency_overrides[get_email_service] = lambda: mock_email_svc
|
||||
|
||||
with patch(
|
||||
"backend.api.routes.users.get_email_validation_service",
|
||||
return_value=mock_validation_svc,
|
||||
):
|
||||
yield TestClient(app)
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestMagicLinkRateLimiting:
|
||||
"""Integration tests for rate limiting in the magic link endpoint."""
|
||||
|
||||
def test_new_signup_allowed_when_not_rate_limited(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""New signup succeeds when not rate limited."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = False
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "new@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_user_svc.create_magic_link.assert_called_once()
|
||||
|
||||
def test_new_signup_blocked_when_rate_limited(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""New signup is silently rejected when rate limited."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "abuser@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
# Magic link should NOT have been created
|
||||
mock_user_svc.create_magic_link.assert_not_called()
|
||||
|
||||
def test_existing_user_not_rate_limited(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""Returning user bypasses rate limiting."""
|
||||
mock_user_svc.get_user.return_value = User(
|
||||
email="existing@example.com", credits=5
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "existing@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Rate limit check should not be called for existing users
|
||||
mock_user_svc.is_signup_rate_limited.assert_not_called()
|
||||
mock_user_svc.create_magic_link.assert_called_once()
|
||||
|
||||
def test_fingerprint_passed_to_create_magic_link(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""Device fingerprint from request body is passed to create_magic_link."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = False
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "new@example.com", "device_fingerprint": "fp-abc123"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
create_call = mock_user_svc.create_magic_link.call_args
|
||||
assert create_call.kwargs.get('device_fingerprint') == "fp-abc123"
|
||||
|
||||
def test_fingerprint_passed_to_rate_limiter(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""Device fingerprint is included in rate limit check."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = False
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "new@example.com", "device_fingerprint": "fp-abc123"},
|
||||
)
|
||||
|
||||
rate_limit_call = mock_user_svc.is_signup_rate_limited.call_args
|
||||
assert rate_limit_call.kwargs.get('device_fingerprint') == "fp-abc123"
|
||||
|
||||
def test_missing_fingerprint_gracefully_handled(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""Missing fingerprint doesn't break the flow."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = False
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "new@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
rate_limit_call = mock_user_svc.is_signup_rate_limited.call_args
|
||||
assert rate_limit_call.kwargs.get('device_fingerprint') is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Integration: Verify Endpoint Grants Credits
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestVerifyGrantsCredits:
|
||||
"""Test that the verify endpoint grants welcome credits."""
|
||||
|
||||
def _make_verify_client(self, mock_user_svc, user, credits_eligible):
|
||||
"""Helper to create a TestClient for verify endpoint tests."""
|
||||
from backend.main import app
|
||||
from backend.services.user_service import get_user_service
|
||||
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, "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 = 1
|
||||
|
||||
# Mock magic link doc for first-login check
|
||||
mock_ml_doc = MagicMock()
|
||||
mock_ml_doc.exists = True
|
||||
mock_ml_doc.to_dict.return_value = {
|
||||
'email': user.email,
|
||||
'tenant_id': None,
|
||||
}
|
||||
mock_user_svc.db.collection.return_value.document.return_value.get.return_value = mock_ml_doc
|
||||
|
||||
mock_email_svc = MagicMock()
|
||||
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
|
||||
app.dependency_overrides[get_email_service] = lambda: mock_email_svc
|
||||
|
||||
client = TestClient(app)
|
||||
return client
|
||||
|
||||
def test_verify_returns_credits_granted(self, mock_user_svc):
|
||||
"""Verify endpoint returns credits_granted in response."""
|
||||
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
|
||||
data = response.json()
|
||||
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(
|
||||
email="existing@example.com",
|
||||
credits=5,
|
||||
email_verified=True,
|
||||
last_login_at=datetime.utcnow(),
|
||||
)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=False)
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["credits_granted"] == 0
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Model Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestModelFields:
|
||||
"""Test that new fields exist on models."""
|
||||
|
||||
def test_user_has_signup_ip(self):
|
||||
"""User model has signup_ip field."""
|
||||
user = User(email="test@example.com", signup_ip="1.2.3.4")
|
||||
assert user.signup_ip == "1.2.3.4"
|
||||
|
||||
def test_user_has_device_fingerprint(self):
|
||||
"""User model has device_fingerprint field."""
|
||||
user = User(email="test@example.com", device_fingerprint="fp123")
|
||||
assert user.device_fingerprint == "fp123"
|
||||
|
||||
def test_user_defaults_none(self):
|
||||
"""New fields default to None."""
|
||||
user = User(email="test@example.com")
|
||||
assert user.signup_ip is None
|
||||
assert user.device_fingerprint is None
|
||||
|
||||
def test_magic_link_has_device_fingerprint(self):
|
||||
"""MagicLinkToken model has device_fingerprint field."""
|
||||
ml = MagicLinkToken(
|
||||
token="tok",
|
||||
email="test@example.com",
|
||||
expires_at=datetime.utcnow(),
|
||||
device_fingerprint="fp123",
|
||||
)
|
||||
assert ml.device_fingerprint == "fp123"
|
||||
|
||||
def test_send_magic_link_request_has_fingerprint(self):
|
||||
"""SendMagicLinkRequest accepts device_fingerprint."""
|
||||
req = SendMagicLinkRequest(
|
||||
email="test@example.com",
|
||||
device_fingerprint="fp123",
|
||||
)
|
||||
assert req.device_fingerprint == "fp123"
|
||||
|
||||
def test_send_magic_link_request_fingerprint_optional(self):
|
||||
"""SendMagicLinkRequest works without device_fingerprint."""
|
||||
req = SendMagicLinkRequest(email="test@example.com")
|
||||
assert req.device_fingerprint is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Error Path Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestErrorPaths:
|
||||
"""Test graceful degradation on errors."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_grant_credits_handles_exception(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible returns False on exception."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User lookup raises exception
|
||||
mock_db.collection.return_value.document.return_value.get.side_effect = Exception("Firestore down")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
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')
|
||||
def test_count_signups_from_ip_handles_exception(self, mock_fs, mock_settings):
|
||||
"""count_recent_signups_from_ip returns 0 on Firestore error (fail-open)."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_db.collection.return_value.where.return_value.where.side_effect = Exception("Query error")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
count = service.count_recent_signups_from_ip("1.2.3.4")
|
||||
assert count == 0 # Fail-open: don't block on error
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_count_signups_from_fingerprint_handles_exception(self, mock_fs, mock_settings):
|
||||
"""count_recent_signups_from_fingerprint returns 0 on error (fail-open)."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_db.collection.return_value.where.return_value.where.side_effect = Exception("Query error")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
count = service.count_recent_signups_from_fingerprint("fp123")
|
||||
assert count == 0
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Caller-Callee Contract Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCallerCalleeContracts:
|
||||
"""Verify that callers pass the right data to callees."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_create_magic_link_passes_fingerprint_to_get_or_create(self, mock_fs, mock_settings):
|
||||
"""create_magic_link passes device_fingerprint through to get_or_create_user."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User already exists (to avoid save path)
|
||||
user = User(email="test@example.com", credits=0)
|
||||
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.object(service, 'get_or_create_user', wraps=service.get_or_create_user) as spy:
|
||||
service.create_magic_link(
|
||||
"test@example.com",
|
||||
ip_address="1.2.3.4",
|
||||
device_fingerprint="fp-xyz",
|
||||
)
|
||||
spy.assert_called_once_with(
|
||||
"test@example.com",
|
||||
tenant_id=None,
|
||||
signup_ip="1.2.3.4",
|
||||
device_fingerprint="fp-xyz",
|
||||
)
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_create_magic_link_stores_fingerprint_on_token(self, mock_fs, mock_settings):
|
||||
"""create_magic_link includes device_fingerprint in the MagicLinkToken."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="test@example.com", credits=0)
|
||||
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()
|
||||
|
||||
ml = service.create_magic_link(
|
||||
"test@example.com",
|
||||
ip_address="1.2.3.4",
|
||||
device_fingerprint="fp-xyz",
|
||||
)
|
||||
|
||||
assert ml.device_fingerprint == "fp-xyz"
|
||||
|
||||
# Also verify the data written to Firestore includes the fingerprint
|
||||
set_call = mock_db.collection.return_value.document.return_value.set
|
||||
set_call.assert_called()
|
||||
saved_data = set_call.call_args[0][0]
|
||||
assert saved_data["device_fingerprint"] == "fp-xyz"
|
||||
@@ -0,0 +1,480 @@
|
||||
"""
|
||||
Tests for anti-abuse investigation features: admin endpoints, session/job
|
||||
fingerprint tracking, and user lookup methods.
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import MagicMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
from backend.models.user import User, Session, MagicLinkToken
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Model Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestSessionFingerprint:
|
||||
"""Session model stores device_fingerprint."""
|
||||
|
||||
def test_session_has_device_fingerprint(self):
|
||||
session = Session(
|
||||
token="tok",
|
||||
user_email="test@example.com",
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
device_fingerprint="fp-abc",
|
||||
)
|
||||
assert session.device_fingerprint == "fp-abc"
|
||||
|
||||
def test_session_fingerprint_defaults_none(self):
|
||||
session = Session(
|
||||
token="tok",
|
||||
user_email="test@example.com",
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
)
|
||||
assert session.device_fingerprint is None
|
||||
|
||||
|
||||
class TestJobCreationIp:
|
||||
"""Job model stores creation_ip."""
|
||||
|
||||
def test_job_has_creation_ip(self):
|
||||
from backend.models.job import Job, JobStatus
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
creation_ip="1.2.3.4",
|
||||
)
|
||||
assert job.creation_ip == "1.2.3.4"
|
||||
|
||||
def test_job_creation_ip_defaults_none(self):
|
||||
from backend.models.job import Job, JobStatus
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
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
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestFindUsersBySignupIp:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_finds_matching_users(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user1 = User(email="a@test.com", signup_ip="1.2.3.4").model_dump(mode='json')
|
||||
user2 = User(email="b@test.com", signup_ip="1.2.3.4").model_dump(mode='json')
|
||||
mock_doc1 = MagicMock()
|
||||
mock_doc1.to_dict.return_value = user1
|
||||
mock_doc2 = MagicMock()
|
||||
mock_doc2.to_dict.return_value = user2
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1, mock_doc2]
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_users_by_signup_ip("1.2.3.4")
|
||||
|
||||
assert len(results) == 2
|
||||
assert results[0].email == "a@test.com"
|
||||
|
||||
@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.where.side_effect = Exception("Firestore down")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_users_by_signup_ip("1.2.3.4")
|
||||
assert results == []
|
||||
|
||||
|
||||
class TestFindUsersByFingerprint:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_finds_matching_users(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user1 = User(email="a@test.com", device_fingerprint="fp123").model_dump(mode='json')
|
||||
mock_doc1 = MagicMock()
|
||||
mock_doc1.to_dict.return_value = user1
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1]
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_users_by_fingerprint("fp123")
|
||||
|
||||
assert len(results) == 1
|
||||
|
||||
|
||||
class TestFindSuspiciousAccounts:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_finds_free_high_usage_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
|
||||
|
||||
free_abuser = User(email="free@test.com", total_jobs_created=5, total_spent=0).model_dump(mode='json')
|
||||
paying_user = User(email="paid@test.com", total_jobs_created=10, total_spent=500).model_dump(mode='json')
|
||||
mock_doc1 = MagicMock()
|
||||
mock_doc1.to_dict.return_value = free_abuser
|
||||
mock_doc2 = MagicMock()
|
||||
mock_doc2.to_dict.return_value = paying_user
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1, mock_doc2]
|
||||
|
||||
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 == "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:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_finds_related_by_ip_and_fingerprint(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
target = User(email="target@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
|
||||
with patch.object(service, 'get_user', return_value=target), \
|
||||
patch.object(service, 'find_users_by_signup_ip', return_value=[
|
||||
target,
|
||||
User(email="related@test.com", signup_ip="1.2.3.4"),
|
||||
]), \
|
||||
patch.object(service, 'find_users_by_fingerprint', return_value=[
|
||||
target,
|
||||
User(email="device-buddy@test.com", device_fingerprint="fp123"),
|
||||
]):
|
||||
result = service.find_related_accounts("target@test.com")
|
||||
|
||||
assert result["user"].email == "target@test.com"
|
||||
# Should exclude the target user from related lists
|
||||
assert len(result["by_ip"]) == 1
|
||||
assert result["by_ip"][0].email == "related@test.com"
|
||||
assert len(result["by_fingerprint"]) == 1
|
||||
assert result["by_fingerprint"][0].email == "device-buddy@test.com"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_returns_empty_for_unknown_user(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_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.find_related_accounts("ghost@test.com")
|
||||
|
||||
assert result["user"] is None
|
||||
assert result["by_ip"] == []
|
||||
assert result["by_fingerprint"] == []
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Endpoint Integration Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_svc():
|
||||
svc = MagicMock()
|
||||
svc.NEW_USER_FREE_CREDITS = 1
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_client(mock_user_svc):
|
||||
from backend.main import app
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
mock_auth = MagicMock()
|
||||
mock_auth.is_admin = True
|
||||
mock_auth.user_email = "admin@nomadkaraoke.com"
|
||||
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
|
||||
app.dependency_overrides[require_admin] = lambda: mock_auth
|
||||
|
||||
yield TestClient(app)
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestAdminAbuseEndpoints:
|
||||
|
||||
def test_suspicious_accounts_endpoint(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_suspicious_accounts.return_value = [
|
||||
User(email="free@test.com", total_jobs_created=5, total_spent=0),
|
||||
]
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/suspicious?min_jobs=2&max_spend=0")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["count"] == 1
|
||||
assert data["users"][0]["email"] == "free@test.com"
|
||||
|
||||
def test_by_ip_endpoint(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_users_by_signup_ip.return_value = [
|
||||
User(email="a@test.com", signup_ip="1.2.3.4"),
|
||||
User(email="b@test.com", signup_ip="1.2.3.4"),
|
||||
]
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/by-ip/1.2.3.4")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["count"] == 2
|
||||
|
||||
def test_by_fingerprint_endpoint(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_users_by_fingerprint.return_value = [
|
||||
User(email="a@test.com", device_fingerprint="fp123"),
|
||||
]
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/by-fingerprint/fp123")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["count"] == 1
|
||||
|
||||
def test_related_endpoint(self, admin_client, mock_user_svc):
|
||||
target = User(email="target@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3)
|
||||
mock_user_svc.find_related_accounts.return_value = {
|
||||
"user": target,
|
||||
"by_ip": [User(email="buddy@test.com", signup_ip="1.2.3.4")],
|
||||
"by_fingerprint": [],
|
||||
}
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/related/target@test.com")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["user"]["email"] == "target@test.com"
|
||||
assert len(data["related_by_ip"]) == 1
|
||||
assert len(data["related_by_fingerprint"]) == 0
|
||||
|
||||
def test_related_endpoint_user_not_found(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_related_accounts.return_value = {
|
||||
"user": None, "by_ip": [], "by_fingerprint": [],
|
||||
}
|
||||
|
||||
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"] == []
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Tests for audio processor robustness fixes.
|
||||
|
||||
Covers:
|
||||
- Stage 2 validation catches missing stems
|
||||
- _normalize_audio_files handles missing clean instrumental path
|
||||
- _generate_combined_instrumentals handles missing backing vocals path
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
|
||||
|
||||
def _make_processor():
|
||||
"""Create an AudioProcessor with mocked dependencies."""
|
||||
processor = AudioProcessor.__new__(AudioProcessor)
|
||||
processor.logger = MagicMock()
|
||||
processor.clean_instrumental_model = "model_bs_roformer"
|
||||
processor.backing_vocals_models = ["mel_band_roformer_karaoke"]
|
||||
processor.other_stems_models = []
|
||||
processor.lossless_output_format = "FLAC"
|
||||
processor.ffmpeg_base_command = "ffmpeg -y"
|
||||
return processor
|
||||
|
||||
|
||||
class TestNormalizeAudioFilesNullSafety:
|
||||
"""Tests for _normalize_audio_files defensive checks."""
|
||||
|
||||
def test_raises_on_missing_clean_instrumental(self):
|
||||
processor = _make_processor()
|
||||
separation_result = {
|
||||
"clean_instrumental": {}, # missing "instrumental" key
|
||||
"combined_instrumentals": {},
|
||||
}
|
||||
with pytest.raises(ValueError, match="clean instrumental path is missing"):
|
||||
processor._normalize_audio_files(separation_result, "Artist - Title", "/tmp/output")
|
||||
|
||||
def test_raises_on_none_clean_instrumental(self):
|
||||
processor = _make_processor()
|
||||
separation_result = {
|
||||
"clean_instrumental": {"instrumental": None},
|
||||
"combined_instrumentals": {},
|
||||
}
|
||||
with pytest.raises(ValueError, match="clean instrumental path is missing"):
|
||||
processor._normalize_audio_files(separation_result, "Artist - Title", "/tmp/output")
|
||||
|
||||
def test_works_with_valid_path(self, tmp_path):
|
||||
processor = _make_processor()
|
||||
# Create a real file so _file_exists returns True
|
||||
audio_file = tmp_path / "instrumental.flac"
|
||||
audio_file.write_bytes(b"fake audio data")
|
||||
|
||||
separation_result = {
|
||||
"clean_instrumental": {"instrumental": str(audio_file), "vocals": str(tmp_path / "vocals.flac")},
|
||||
"combined_instrumentals": {},
|
||||
"other_stems": {},
|
||||
"backing_vocals": {},
|
||||
}
|
||||
# Mock _normalize_audio to avoid actually running ffmpeg
|
||||
with patch.object(processor, "_normalize_audio"):
|
||||
processor._normalize_audio_files(separation_result, "Artist - Title", str(tmp_path))
|
||||
|
||||
# Should have logged success (no exception)
|
||||
assert processor.logger.info.called
|
||||
|
||||
def test_normalizes_combined_instrumentals(self, tmp_path):
|
||||
processor = _make_processor()
|
||||
instrumental = tmp_path / "instrumental.flac"
|
||||
instrumental.write_bytes(b"fake instrumental")
|
||||
combined = tmp_path / "combined.flac"
|
||||
combined.write_bytes(b"fake combined")
|
||||
|
||||
separation_result = {
|
||||
"clean_instrumental": {"instrumental": str(instrumental), "vocals": str(tmp_path / "v.flac")},
|
||||
"combined_instrumentals": {"mel_band_roformer_karaoke": str(combined)},
|
||||
}
|
||||
with patch.object(processor, "_normalize_audio") as mock_normalize:
|
||||
processor._normalize_audio_files(separation_result, "Artist - Title", str(tmp_path))
|
||||
|
||||
# Both clean instrumental and combined instrumental should be normalized
|
||||
assert mock_normalize.call_count == 2
|
||||
normalized_paths = [call.args[0] for call in mock_normalize.call_args_list]
|
||||
assert str(instrumental) in normalized_paths
|
||||
assert str(combined) in normalized_paths
|
||||
|
||||
|
||||
class TestGenerateCombinedInstrumentalsNullSafety:
|
||||
"""Tests for _generate_combined_instrumentals defensive checks."""
|
||||
|
||||
def test_skips_model_with_missing_backing_vocals(self, tmp_path):
|
||||
processor = _make_processor()
|
||||
instrumental_path = str(tmp_path / "instrumental.flac")
|
||||
|
||||
# Model has lead_vocals but not backing_vocals
|
||||
backing_vocals_result = {
|
||||
"mel_band_roformer_karaoke": {"lead_vocals": "/tmp/lead.flac"}
|
||||
# "backing_vocals" key is missing
|
||||
}
|
||||
result = processor._generate_combined_instrumentals(
|
||||
instrumental_path, backing_vocals_result, "Artist - Title", str(tmp_path)
|
||||
)
|
||||
assert result == {}
|
||||
processor.logger.error.assert_called_once()
|
||||
assert "backing_vocals path is missing" in processor.logger.error.call_args[0][0]
|
||||
|
||||
|
||||
class TestStage2Validation:
|
||||
"""Tests for stage 2 remote results validation in _process_audio_separation_remote."""
|
||||
|
||||
def test_organize_stage2_missing_backing_vocals_stem(self):
|
||||
"""Test that _organize_stage2_remote_results correctly handles partial results."""
|
||||
processor = _make_processor()
|
||||
|
||||
# Simulate only getting the Vocals file, not the Instrumental file
|
||||
# This is what happened in the production failure
|
||||
import tempfile, os
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
stems_dir = os.path.join(tmpdir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
# Create only the vocals file (missing the instrumental/backing vocals file)
|
||||
vocals_file = os.path.join(tmpdir, "audio_(Vocals)_mel_band_roformer_karaoke.flac")
|
||||
with open(vocals_file, "w") as f:
|
||||
f.write("fake")
|
||||
|
||||
result = processor._organize_stage2_remote_results(
|
||||
[vocals_file], "Artist - Title", stems_dir
|
||||
)
|
||||
|
||||
# Should have the model with only lead_vocals, no backing_vocals
|
||||
assert "mel_band_roformer_karaoke" in result
|
||||
assert "lead_vocals" in result["mel_band_roformer_karaoke"]
|
||||
assert "backing_vocals" not in result["mel_band_roformer_karaoke"]
|
||||
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
Tests for AudioShake API retry logic.
|
||||
|
||||
Covers:
|
||||
- Retry on 5xx server errors
|
||||
- Retry on 429 rate limit
|
||||
- Retry on connection errors
|
||||
- No retry on 4xx client errors (except 429)
|
||||
- Retry exhaustion raises the original error
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
import requests
|
||||
from tenacity import wait_none
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import (
|
||||
AudioShakeAPI,
|
||||
AudioShakeConfig,
|
||||
_is_retryable_error,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_retry_wait():
|
||||
"""Disable retry wait times in all tests to avoid sleeping."""
|
||||
# Temporarily replace the wait strategy with no-wait for both retry-decorated methods
|
||||
methods = [AudioShakeAPI._request_with_retry, AudioShakeAPI._upload_file_with_retry]
|
||||
original_waits = [m.retry.wait for m in methods]
|
||||
for m in methods:
|
||||
m.retry.wait = wait_none()
|
||||
yield
|
||||
for m, w in zip(methods, original_waits):
|
||||
m.retry.wait = w
|
||||
|
||||
|
||||
class TestIsRetryableError:
|
||||
"""Tests for the _is_retryable_error predicate."""
|
||||
|
||||
def test_connection_error_is_retryable(self):
|
||||
assert _is_retryable_error(requests.exceptions.ConnectionError()) is True
|
||||
|
||||
def test_timeout_is_retryable(self):
|
||||
assert _is_retryable_error(requests.exceptions.Timeout()) is True
|
||||
|
||||
def test_502_is_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 502
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is True
|
||||
|
||||
def test_503_is_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 503
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is True
|
||||
|
||||
def test_429_is_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 429
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is True
|
||||
|
||||
def test_400_is_not_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 400
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is False
|
||||
|
||||
def test_401_is_not_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 401
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is False
|
||||
|
||||
def test_404_is_not_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 404
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is False
|
||||
|
||||
def test_value_error_is_not_retryable(self):
|
||||
assert _is_retryable_error(ValueError("bad")) is False
|
||||
|
||||
|
||||
class TestAudioShakeAPIRetry:
|
||||
"""Tests for AudioShakeAPI._request_with_retry."""
|
||||
|
||||
def _make_api(self):
|
||||
config = AudioShakeConfig(api_token="test-token")
|
||||
logger = MagicMock()
|
||||
return AudioShakeAPI(config, logger)
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
|
||||
def test_succeeds_on_first_try(self, mock_request):
|
||||
api = self._make_api()
|
||||
mock_response = MagicMock()
|
||||
mock_response.raise_for_status = MagicMock()
|
||||
mock_request.return_value = mock_response
|
||||
|
||||
result = api._request_with_retry("GET", "https://api.example.com/test")
|
||||
assert result == mock_response
|
||||
mock_request.assert_called_once()
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
|
||||
def test_retries_on_502_then_succeeds(self, mock_request):
|
||||
api = self._make_api()
|
||||
|
||||
# First call: 502 error
|
||||
bad_response = MagicMock()
|
||||
bad_response.status_code = 502
|
||||
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
|
||||
|
||||
# Second call: success
|
||||
good_response = MagicMock()
|
||||
good_response.raise_for_status = MagicMock()
|
||||
|
||||
mock_request.side_effect = [bad_response, good_response]
|
||||
|
||||
result = api._request_with_retry("GET", "https://api.example.com/test")
|
||||
|
||||
assert result == good_response
|
||||
assert mock_request.call_count == 2
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
|
||||
def test_does_not_retry_on_400(self, mock_request):
|
||||
api = self._make_api()
|
||||
|
||||
bad_response = MagicMock()
|
||||
bad_response.status_code = 400
|
||||
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
|
||||
mock_request.return_value = bad_response
|
||||
|
||||
with pytest.raises(requests.exceptions.HTTPError):
|
||||
api._request_with_retry("GET", "https://api.example.com/test")
|
||||
|
||||
# Should NOT retry — only 1 call
|
||||
mock_request.assert_called_once()
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
|
||||
def test_retries_on_connection_error(self, mock_request):
|
||||
api = self._make_api()
|
||||
|
||||
good_response = MagicMock()
|
||||
good_response.raise_for_status = MagicMock()
|
||||
|
||||
mock_request.side_effect = [
|
||||
requests.exceptions.ConnectionError("Connection refused"),
|
||||
good_response,
|
||||
]
|
||||
|
||||
result = api._request_with_retry("GET", "https://api.example.com/test")
|
||||
|
||||
assert result == good_response
|
||||
assert mock_request.call_count == 2
|
||||
|
||||
|
||||
class TestAudioShakeUploadRetry:
|
||||
"""Tests for upload_file using retry."""
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.post")
|
||||
def test_upload_file_retries_on_502(self, mock_post, tmp_path):
|
||||
config = AudioShakeConfig(api_token="test-token")
|
||||
logger = MagicMock()
|
||||
api = AudioShakeAPI(config, logger)
|
||||
|
||||
# Create a test file with known content
|
||||
test_file = tmp_path / "test.flac"
|
||||
test_file.write_bytes(b"fake audio data")
|
||||
|
||||
# First call: 502
|
||||
bad_response = MagicMock()
|
||||
bad_response.status_code = 502
|
||||
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
|
||||
|
||||
# Second call: success
|
||||
good_response = MagicMock()
|
||||
good_response.raise_for_status = MagicMock()
|
||||
good_response.json.return_value = {"id": "asset-123"}
|
||||
good_response.status_code = 200
|
||||
good_response.text = '{"id": "asset-123"}'
|
||||
|
||||
mock_post.side_effect = [bad_response, good_response]
|
||||
|
||||
asset_id = api.upload_file(str(test_file))
|
||||
|
||||
assert asset_id == "asset-123"
|
||||
assert mock_post.call_count == 2
|
||||
|
||||
# Verify file was re-opened on each attempt (both calls got file data)
|
||||
for call_args in mock_post.call_args_list:
|
||||
files_arg = call_args[1].get("files") or call_args[0][1] if len(call_args[0]) > 1 else call_args[1].get("files")
|
||||
assert files_arg is not None, "Each retry should pass files"
|
||||
@@ -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"
|
||||
@@ -0,0 +1,173 @@
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import sys
|
||||
sys.modules['google.cloud.firestore'] = MagicMock()
|
||||
sys.modules['google.cloud.storage'] = MagicMock()
|
||||
|
||||
|
||||
class TestParseExternalBlocklist:
|
||||
def test_parse_newline_delimited_domains(self):
|
||||
from backend.services.disposable_domain_sync_service import parse_blocklist_text
|
||||
text = "tempmail.com\nmailinator.com\n\nguerrillamail.com\n"
|
||||
result = parse_blocklist_text(text)
|
||||
assert result == {"tempmail.com", "mailinator.com", "guerrillamail.com"}
|
||||
|
||||
def test_parse_strips_whitespace(self):
|
||||
from backend.services.disposable_domain_sync_service import parse_blocklist_text
|
||||
text = " tempmail.com \n mailinator.com\t\n"
|
||||
result = parse_blocklist_text(text)
|
||||
assert result == {"tempmail.com", "mailinator.com"}
|
||||
|
||||
def test_parse_lowercases_domains(self):
|
||||
from backend.services.disposable_domain_sync_service import parse_blocklist_text
|
||||
text = "TempMail.COM\nMailinator.com\n"
|
||||
result = parse_blocklist_text(text)
|
||||
assert result == {"tempmail.com", "mailinator.com"}
|
||||
|
||||
def test_parse_empty_text(self):
|
||||
from backend.services.disposable_domain_sync_service import parse_blocklist_text
|
||||
assert parse_blocklist_text("") == set()
|
||||
assert parse_blocklist_text(" \n\n ") == set()
|
||||
|
||||
|
||||
class TestFetchExternalBlocklist:
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_success(self):
|
||||
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = "tempmail.com\nmailinator.com\n"
|
||||
mock_response.headers = {"content-length": "30"}
|
||||
|
||||
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client.__aexit__ = AsyncMock(return_value=False)
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_cls.return_value = mock_client
|
||||
|
||||
domains = await fetch_external_blocklist()
|
||||
assert domains == {"tempmail.com", "mailinator.com"}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_rejects_too_many_domains(self):
|
||||
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
fake_text = "\n".join(f"domain{i}.com" for i in range(50_001))
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = fake_text
|
||||
mock_response.headers = {"content-length": str(len(fake_text))}
|
||||
|
||||
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client.__aexit__ = AsyncMock(return_value=False)
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_cls.return_value = mock_client
|
||||
|
||||
with pytest.raises(ValueError, match="exceeds maximum"):
|
||||
await fetch_external_blocklist()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_rejects_non_200(self):
|
||||
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 500
|
||||
mock_response.raise_for_status = MagicMock(side_effect=Exception("Server Error"))
|
||||
|
||||
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client.__aexit__ = AsyncMock(return_value=False)
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_cls.return_value = mock_client
|
||||
|
||||
with pytest.raises(Exception):
|
||||
await fetch_external_blocklist()
|
||||
|
||||
|
||||
class TestSyncDisposableDomains:
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
return mock
|
||||
|
||||
def test_sync_first_run_migration(self, mock_db):
|
||||
"""First sync: migrate old disposable_domains to manual_domains."""
|
||||
from unittest.mock import patch
|
||||
from backend.services.disposable_domain_sync_service import sync_disposable_domains
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"disposable_domains": ["tempmail.com", "custom-temp.com"],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
external_domains = {"tempmail.com", "mailinator.com"}
|
||||
|
||||
with patch("backend.services.disposable_domain_sync_service.DEFAULT_DISPOSABLE_DOMAINS", set()):
|
||||
result = sync_disposable_domains(mock_db, external_domains)
|
||||
|
||||
assert result["migrated_to_manual"] == ["custom-temp.com"]
|
||||
assert result["external_count"] == 2
|
||||
|
||||
mock_db.collection.return_value.document.return_value.set.assert_called_once()
|
||||
call_data = mock_db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert set(call_data["external_domains"]) == {"tempmail.com", "mailinator.com"}
|
||||
assert set(call_data["manual_domains"]) == {"custom-temp.com"}
|
||||
assert "disposable_domains" not in call_data
|
||||
|
||||
def test_sync_subsequent_run(self, mock_db):
|
||||
"""Subsequent sync: just replace external_domains."""
|
||||
from backend.services.disposable_domain_sync_service import sync_disposable_domains
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com"],
|
||||
"manual_domains": ["my-custom.com"],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
external_domains = {"tempmail.com", "mailinator.com", "newdomain.com"}
|
||||
|
||||
result = sync_disposable_domains(mock_db, external_domains)
|
||||
|
||||
assert result["external_count"] == 3
|
||||
assert result["added"] == 2
|
||||
assert result["removed"] == 0
|
||||
|
||||
def test_sync_cleans_redundant_manual_domains(self, mock_db):
|
||||
"""Sync removes manual domains that now appear in external list."""
|
||||
from backend.services.disposable_domain_sync_service import sync_disposable_domains
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com"],
|
||||
"manual_domains": ["mailinator.com", "my-custom.com"],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
external_domains = {"tempmail.com", "mailinator.com"}
|
||||
|
||||
result = sync_disposable_domains(mock_db, external_domains)
|
||||
|
||||
call_data = mock_db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert set(call_data["manual_domains"]) == {"my-custom.com"}
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
Unit tests for EmailService review reminder and expiry email methods.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
# Mock Google Cloud before imports
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
|
||||
class TestSendReviewReminder:
|
||||
"""Test send_review_reminder() email method."""
|
||||
|
||||
def _make_service(self):
|
||||
"""Create an EmailService with a mock provider."""
|
||||
with patch('backend.services.email_service.get_settings'):
|
||||
from backend.services.email_service import EmailService
|
||||
service = EmailService.__new__(EmailService)
|
||||
service.provider = Mock()
|
||||
service.provider.send_email.return_value = True
|
||||
service.frontend_url = "https://gen.nomadkaraoke.com"
|
||||
service.buy_url = "https://gen.nomadkaraoke.com"
|
||||
service.settings = Mock()
|
||||
return service
|
||||
|
||||
def test_subject_with_artist_and_title(self):
|
||||
"""Subject should include artist and title."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
artist="Adele",
|
||||
title="Hello",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "Adele - Hello" in call_args.kwargs["subject"]
|
||||
assert "Reminder" in call_args.kwargs["subject"]
|
||||
|
||||
def test_subject_without_artist_and_title(self):
|
||||
"""Subject should work without artist/title."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "Reminder: Your karaoke video is waiting for review" == call_args.kwargs["subject"]
|
||||
|
||||
def test_content_includes_review_link(self):
|
||||
"""HTML content should include the review URL."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
artist="Adele",
|
||||
title="Hello",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
|
||||
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
|
||||
|
||||
def test_content_includes_expiry_warning(self):
|
||||
"""Content should warn about 24h expiry."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "24 hours" in call_args.kwargs["html_content"]
|
||||
assert "expire" in call_args.kwargs["html_content"]
|
||||
|
||||
def test_content_includes_help_offer(self):
|
||||
"""Content should offer help via reply."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "reply to this email" in call_args.kwargs["html_content"]
|
||||
|
||||
|
||||
class TestSendReviewExpired:
|
||||
"""Test send_review_expired() email method."""
|
||||
|
||||
def _make_service(self):
|
||||
"""Create an EmailService with a mock provider."""
|
||||
with patch('backend.services.email_service.get_settings'):
|
||||
from backend.services.email_service import EmailService
|
||||
service = EmailService.__new__(EmailService)
|
||||
service.provider = Mock()
|
||||
service.provider.send_email.return_value = True
|
||||
service.frontend_url = "https://gen.nomadkaraoke.com"
|
||||
service.buy_url = "https://gen.nomadkaraoke.com"
|
||||
service.settings = Mock()
|
||||
return service
|
||||
|
||||
def test_subject_with_artist_and_title(self):
|
||||
"""Subject should include artist and title."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
artist="Adele",
|
||||
title="Hello",
|
||||
credits_balance=2,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "Adele - Hello" in call_args.kwargs["subject"]
|
||||
assert "expired" in call_args.kwargs["subject"]
|
||||
|
||||
def test_subject_without_artist_and_title(self):
|
||||
"""Subject should work without artist/title."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
credits_balance=1,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "Your karaoke video has expired" == call_args.kwargs["subject"]
|
||||
|
||||
def test_content_includes_refund_message(self):
|
||||
"""Content should confirm credit refund."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
credits_balance=3,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "refunded" in call_args.kwargs["html_content"]
|
||||
assert "3 credits" in call_args.kwargs["html_content"]
|
||||
|
||||
def test_content_shows_singular_credit(self):
|
||||
"""Should show 'credit' (singular) for balance of 1."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
credits_balance=1,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "1 credit" in call_args.kwargs["html_content"]
|
||||
# Should NOT say "1 credits"
|
||||
assert "1 credits" not in call_args.kwargs["html_content"]
|
||||
|
||||
def test_content_includes_create_link(self):
|
||||
"""Content should include a link to create a new video."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
credits_balance=2,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "gen.nomadkaraoke.com/app" in call_args.kwargs["html_content"]
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
Tests for disposable email blocking in the magic link signup flow.
|
||||
|
||||
Verifies that EmailValidationService is correctly wired into the
|
||||
POST /api/users/auth/magic-link endpoint.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_validation_svc():
|
||||
"""Create a mock EmailValidationService."""
|
||||
svc = MagicMock()
|
||||
svc.is_disposable_domain.return_value = False
|
||||
svc.is_email_blocked.return_value = False
|
||||
svc.is_ip_blocked.return_value = False
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_validation_svc):
|
||||
"""Create TestClient with mocked email validation service."""
|
||||
from backend.main import app
|
||||
|
||||
with patch(
|
||||
"backend.api.routes.users.get_email_validation_service",
|
||||
return_value=mock_validation_svc,
|
||||
):
|
||||
yield TestClient(app)
|
||||
|
||||
|
||||
class TestDisposableEmailBlocking:
|
||||
"""Tests for disposable email rejection in magic link flow."""
|
||||
|
||||
def test_disposable_email_returns_422(self, client, mock_validation_svc):
|
||||
"""Disposable email domains should be rejected with 422."""
|
||||
mock_validation_svc.is_disposable_domain.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "test@yopmail.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 422
|
||||
assert response.json()["detail"] == "disposable_email_not_allowed"
|
||||
|
||||
def test_disposable_email_does_not_send_email(self, client, mock_validation_svc):
|
||||
"""Disposable email should be rejected before any email is sent."""
|
||||
mock_validation_svc.is_disposable_domain.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "abuse@tempmail.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 422
|
||||
# Validation should have been called with lowercased email
|
||||
mock_validation_svc.is_disposable_domain.assert_called_with("abuse@tempmail.com")
|
||||
|
||||
def test_blocked_email_silent_reject(self, client, mock_validation_svc):
|
||||
"""Blocked email should return generic success (anti-enumeration)."""
|
||||
mock_validation_svc.is_email_blocked.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "blocked@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
|
||||
def test_blocked_ip_silent_reject(self, client, mock_validation_svc):
|
||||
"""Blocked IP should return generic success (anti-enumeration)."""
|
||||
mock_validation_svc.is_ip_blocked.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "innocent@gmail.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
|
||||
def test_email_is_lowercased_before_check(self, client, mock_validation_svc):
|
||||
"""Email should be lowercased before disposable domain check."""
|
||||
mock_validation_svc.is_disposable_domain.return_value = True
|
||||
|
||||
client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "Test@YOPMAIL.COM"},
|
||||
)
|
||||
|
||||
mock_validation_svc.is_disposable_domain.assert_called_with("test@yopmail.com")
|
||||
|
||||
|
||||
class TestDisposableDomainList:
|
||||
"""Verify DEFAULT_DISPOSABLE_DOMAINS is now empty (replaced by external sync)."""
|
||||
|
||||
def test_defaults_empty_after_migration(self):
|
||||
from backend.services.email_validation_service import DEFAULT_DISPOSABLE_DOMAINS
|
||||
assert len(DEFAULT_DISPOSABLE_DOMAINS) == 0
|
||||
|
||||
def test_gmail_not_in_defaults(self):
|
||||
from backend.services.email_validation_service import DEFAULT_DISPOSABLE_DOMAINS
|
||||
assert "gmail.com" not in DEFAULT_DISPOSABLE_DOMAINS
|
||||
@@ -1,12 +1,16 @@
|
||||
"""
|
||||
Unit tests for EmailValidationService.
|
||||
|
||||
Tests email normalization, disposable domain detection, and blocklist management.
|
||||
Tests email normalization, disposable domain detection, blocklist management,
|
||||
and external API-based disposable domain checking (DeBounce + verifymail.io).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
|
||||
# Mock Google Cloud before imports
|
||||
import sys
|
||||
sys.modules['google.cloud.firestore'] = MagicMock()
|
||||
@@ -107,14 +111,22 @@ class TestEmailNormalization:
|
||||
|
||||
|
||||
class TestDisposableDomainDetection:
|
||||
"""Test disposable domain detection."""
|
||||
"""Test disposable domain detection (static blocklist only — external APIs mocked)."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
"""Create a mock Firestore client."""
|
||||
"""Create a mock Firestore client with new data model."""
|
||||
mock = MagicMock()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com", "mailinator.com", "guerrillamail.com"],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@@ -128,9 +140,26 @@ class TestDisposableDomainDetection:
|
||||
service = EmailValidationService(db=mock_db)
|
||||
return service
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_external_apis(self):
|
||||
"""Mock external API calls — these tests focus on static blocklist logic."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
# DeBounce returns clean for everything
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
# No verifymail API key configured
|
||||
mock_settings.get_secret.return_value = None
|
||||
yield mock_client
|
||||
|
||||
def test_detect_known_disposable_domain(self, email_service):
|
||||
"""Test known disposable domains are detected."""
|
||||
# These are in DEFAULT_DISPOSABLE_DOMAINS
|
||||
assert email_service.is_disposable_domain("user@tempmail.com") is True
|
||||
assert email_service.is_disposable_domain("user@mailinator.com") is True
|
||||
assert email_service.is_disposable_domain("user@guerrillamail.com") is True
|
||||
@@ -165,6 +194,7 @@ class TestBlocklistManagement:
|
||||
"disposable_domains": ["custom-temp.com"],
|
||||
"blocked_emails": ["spammer@example.com"],
|
||||
"blocked_ips": ["192.168.1.100"],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
@@ -179,6 +209,22 @@ class TestBlocklistManagement:
|
||||
service = EmailValidationService(db=mock_db)
|
||||
return service
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_external_apis(self):
|
||||
"""Mock external API calls."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
yield
|
||||
|
||||
def test_is_email_blocked(self, email_service):
|
||||
"""Test blocked email detection."""
|
||||
assert email_service.is_email_blocked("spammer@example.com") is True
|
||||
@@ -199,16 +245,226 @@ class TestBlocklistManagement:
|
||||
assert email_service.is_disposable_domain("user@custom-temp.com") is True
|
||||
|
||||
def test_blocklist_caching(self, email_service, mock_db):
|
||||
"""Test blocklist is cached."""
|
||||
# First call
|
||||
email_service.is_disposable_domain("user@test.com")
|
||||
# Second call should use cache
|
||||
email_service.is_disposable_domain("user@test2.com")
|
||||
"""Test blocklist config is cached between calls."""
|
||||
# Use well-known providers to avoid external API calls and Firestore writes
|
||||
email_service.is_disposable_domain("user@gmail.com")
|
||||
email_service.is_disposable_domain("user@yahoo.com")
|
||||
|
||||
# Should only call Firestore once due to caching
|
||||
# Should only call Firestore once for the blocklist config (both hit WELL_KNOWN_PROVIDERS first,
|
||||
# but the first call loads the config, and the second call uses the cache)
|
||||
# Actually, well-known providers short-circuit before get_blocklist_config(), so use
|
||||
# a disposable domain instead to exercise the config loading path.
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
mock_db.collection.return_value.document.return_value.get.reset_mock()
|
||||
|
||||
email_service.is_disposable_domain("user@custom-temp.com") # hits static list
|
||||
email_service.is_disposable_domain("user@custom-temp.com") # should use cache
|
||||
|
||||
# Only 1 Firestore read for blocklist config (cached on second call)
|
||||
assert mock_db.collection.return_value.document.return_value.get.call_count == 1
|
||||
|
||||
|
||||
class TestEffectiveBlocklist:
|
||||
"""Test effective blocklist computation with new data model."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com", "mailinator.com", "allowed-one.com"],
|
||||
"manual_domains": ["my-custom.com"],
|
||||
"allowlisted_domains": ["allowed-one.com"],
|
||||
"blocked_emails": ["bad@example.com"],
|
||||
"blocked_ips": ["1.2.3.4"],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@pytest.fixture
|
||||
def email_service(self, mock_db):
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
return EmailValidationService(db=mock_db)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_external_apis(self):
|
||||
"""Mock external API calls."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
yield
|
||||
|
||||
def test_effective_set_excludes_allowlisted(self, email_service):
|
||||
config = email_service.get_blocklist_config()
|
||||
assert "tempmail.com" in config["disposable_domains"]
|
||||
assert "mailinator.com" in config["disposable_domains"]
|
||||
assert "my-custom.com" in config["disposable_domains"]
|
||||
assert "allowed-one.com" not in config["disposable_domains"]
|
||||
|
||||
def test_allowlisted_domain_not_blocked(self, email_service):
|
||||
assert email_service.is_disposable_domain("user@allowed-one.com") is False
|
||||
|
||||
def test_external_domain_blocked(self, email_service):
|
||||
assert email_service.is_disposable_domain("user@tempmail.com") is True
|
||||
|
||||
def test_manual_domain_blocked(self, email_service):
|
||||
assert email_service.is_disposable_domain("user@my-custom.com") is True
|
||||
|
||||
|
||||
class TestNewDataModelCRUD:
|
||||
"""Test CRUD operations with the new data model."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com", "mailinator.com"],
|
||||
"manual_domains": ["my-custom.com"],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@pytest.fixture
|
||||
def email_service(self, mock_db):
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
return EmailValidationService(db=mock_db)
|
||||
|
||||
def test_add_disposable_domain_writes_to_manual(self, email_service, mock_db):
|
||||
"""Test add_disposable_domain writes to manual_domains field."""
|
||||
email_service.add_disposable_domain("new-spam.com", "admin@test.com")
|
||||
# Get the transaction set call args
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "new-spam.com" in data["manual_domains"]
|
||||
assert "my-custom.com" in data["manual_domains"]
|
||||
|
||||
def test_remove_disposable_domain_manual(self, email_service, mock_db):
|
||||
"""Test removing a manual domain removes from manual_domains."""
|
||||
email_service.remove_disposable_domain("my-custom.com", "admin@test.com")
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "my-custom.com" not in data["manual_domains"]
|
||||
|
||||
def test_remove_disposable_domain_external_adds_to_allowlist(self, email_service, mock_db):
|
||||
"""Test removing an external domain adds it to allowlisted_domains."""
|
||||
email_service.remove_disposable_domain("tempmail.com", "admin@test.com")
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "tempmail.com" in data["allowlisted_domains"]
|
||||
# external_domains should still contain it (not removed, just allowlisted)
|
||||
assert "tempmail.com" in data["external_domains"]
|
||||
|
||||
def test_add_allowlisted_domain(self, email_service, mock_db):
|
||||
"""Test add_allowlisted_domain writes to allowlisted_domains field."""
|
||||
email_service.add_allowlisted_domain("legit.com", "admin@test.com")
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "legit.com" in data["allowlisted_domains"]
|
||||
|
||||
def test_remove_allowlisted_domain(self, email_service, mock_db):
|
||||
"""Test remove_allowlisted_domain removes from allowlisted_domains."""
|
||||
# Set up mock with an existing allowlisted domain
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com"],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": ["legit.com"],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = email_service.remove_allowlisted_domain("legit.com", "admin@test.com")
|
||||
assert result is True
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "legit.com" not in data["allowlisted_domains"]
|
||||
|
||||
def test_remove_allowlisted_domain_not_found(self, email_service, mock_db):
|
||||
"""Test remove_allowlisted_domain returns False when domain not found."""
|
||||
result = email_service.remove_allowlisted_domain("nonexistent.com", "admin@test.com")
|
||||
assert result is False
|
||||
|
||||
def test_get_blocklist_raw_data(self, email_service, mock_db):
|
||||
"""Test get_blocklist_raw_data returns all raw fields."""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
# Clear cache so it reads fresh
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
|
||||
raw = email_service.get_blocklist_raw_data()
|
||||
assert "external_domains" in raw
|
||||
assert "manual_domains" in raw
|
||||
assert "allowlisted_domains" in raw
|
||||
assert "blocked_emails" in raw
|
||||
assert "blocked_ips" in raw
|
||||
assert "last_sync_at" in raw
|
||||
assert "last_sync_count" in raw
|
||||
assert "updated_at" in raw
|
||||
assert "updated_by" in raw
|
||||
# Check sorted
|
||||
assert raw["external_domains"] == sorted(["tempmail.com", "mailinator.com"])
|
||||
assert raw["manual_domains"] == ["my-custom.com"]
|
||||
|
||||
def test_get_blocklist_raw_data_no_doc(self, email_service, mock_db):
|
||||
"""Test get_blocklist_raw_data returns defaults when doc doesn't exist."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
raw = email_service.get_blocklist_raw_data()
|
||||
assert raw["external_domains"] == []
|
||||
assert raw["manual_domains"] == []
|
||||
assert raw["allowlisted_domains"] == []
|
||||
assert raw["last_sync_at"] is None
|
||||
|
||||
def test_get_blocklist_stats_new_model(self, email_service, mock_db):
|
||||
"""Test get_blocklist_stats returns counts for new data model fields."""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
|
||||
stats = email_service.get_blocklist_stats()
|
||||
assert stats["external_domains_count"] == 2
|
||||
assert stats["manual_domains_count"] == 1
|
||||
assert stats["allowlisted_domains_count"] == 0
|
||||
assert stats["disposable_domains_count"] == 3 # 2 external + 1 manual - 0 allowlisted
|
||||
assert stats["blocked_emails_count"] == 0
|
||||
assert stats["blocked_ips_count"] == 0
|
||||
|
||||
|
||||
class TestIPHashing:
|
||||
"""Test IP address hashing."""
|
||||
|
||||
@@ -240,3 +496,375 @@ class TestIPHashing:
|
||||
hash_result = email_service.hash_ip("192.168.1.1")
|
||||
assert len(hash_result) == 64
|
||||
assert all(c in "0123456789abcdef" for c in hash_result)
|
||||
|
||||
|
||||
class TestExternalAPIChecks:
|
||||
"""Test external API-based disposable domain detection (DeBounce + verifymail.io)."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["yopmail.com"],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@pytest.fixture
|
||||
def email_service(self, mock_db):
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
return EmailValidationService(db=mock_db)
|
||||
|
||||
# =========================================================================
|
||||
# Well-known provider skip
|
||||
# =========================================================================
|
||||
|
||||
def test_well_known_providers_skip_all_checks(self, email_service):
|
||||
"""Well-known providers return False without any API calls."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client:
|
||||
assert email_service.is_disposable_domain("user@gmail.com") is False
|
||||
assert email_service.is_disposable_domain("user@yahoo.com") is False
|
||||
assert email_service.is_disposable_domain("user@hotmail.com") is False
|
||||
assert email_service.is_disposable_domain("user@outlook.com") is False
|
||||
assert email_service.is_disposable_domain("user@protonmail.com") is False
|
||||
assert email_service.is_disposable_domain("user@icloud.com") is False
|
||||
# No HTTP calls should have been made
|
||||
mock_client.return_value.get.assert_not_called()
|
||||
|
||||
# =========================================================================
|
||||
# DeBounce API
|
||||
# =========================================================================
|
||||
|
||||
def test_debounce_flags_disposable(self, email_service):
|
||||
"""DeBounce returning disposable=true should flag the domain."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "true"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
result = email_service.is_disposable_domain("user@sketchy-domain.xyz")
|
||||
assert result is True
|
||||
|
||||
def test_debounce_clean_and_no_verifymail_key(self, email_service):
|
||||
"""DeBounce clean + no verifymail key → domain is clean."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
result = email_service.is_disposable_domain("user@legit-company.com")
|
||||
assert result is False
|
||||
|
||||
def test_debounce_timeout_falls_through_to_verifymail(self, email_service):
|
||||
"""DeBounce timeout → should try verifymail.io."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
# DeBounce times out, verifymail says disposable
|
||||
mock_client.return_value.get.side_effect = [
|
||||
httpx.TimeoutException("timeout"), # DeBounce
|
||||
]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
# DeBounce returns None (error) so verifymail is NOT called
|
||||
# (tier 4 only runs if debounce_result is False, not None)
|
||||
result = email_service.is_disposable_domain("user@unknown.xyz")
|
||||
assert result is False
|
||||
|
||||
def test_debounce_error_does_not_block_users(self, email_service):
|
||||
"""If DeBounce errors, don't block the user."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_client.return_value.get.side_effect = Exception("network error")
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
result = email_service.is_disposable_domain("user@some-domain.com")
|
||||
assert result is False
|
||||
|
||||
# =========================================================================
|
||||
# verifymail.io API
|
||||
# =========================================================================
|
||||
|
||||
def test_verifymail_catches_what_debounce_misses(self, email_service):
|
||||
"""DeBounce clean + verifymail disposable → flagged."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
# DeBounce says clean, verifymail says disposable
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
|
||||
verifymail_resp = Mock()
|
||||
verifymail_resp.json.return_value = {"disposable": True, "block": True}
|
||||
verifymail_resp.raise_for_status = Mock()
|
||||
|
||||
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
result = email_service.is_disposable_domain("user@sneaky-disposable.io.vn")
|
||||
assert result is True
|
||||
|
||||
def test_verifymail_block_flag_also_triggers(self, email_service):
|
||||
"""verifymail.io block=True (even if disposable=False) → flagged."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
|
||||
verifymail_resp = Mock()
|
||||
verifymail_resp.json.return_value = {"disposable": False, "block": True}
|
||||
verifymail_resp.raise_for_status = Mock()
|
||||
|
||||
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
result = email_service.is_disposable_domain("user@blocked-domain.store")
|
||||
assert result is True
|
||||
|
||||
def test_both_apis_clean(self, email_service):
|
||||
"""Both APIs say clean → not disposable."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
|
||||
verifymail_resp = Mock()
|
||||
verifymail_resp.json.return_value = {"disposable": False, "block": False}
|
||||
verifymail_resp.raise_for_status = Mock()
|
||||
|
||||
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
result = email_service.is_disposable_domain("user@real-company.vn")
|
||||
assert result is False
|
||||
|
||||
def test_both_apis_timeout_falls_back_to_static(self, email_service):
|
||||
"""Both APIs timeout → fall back to static list (returns False for unknown domain)."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_client.return_value.get.side_effect = httpx.TimeoutException("timeout")
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
# Unknown domain not in static list → False (don't block real users)
|
||||
result = email_service.is_disposable_domain("user@unknown-domain.com")
|
||||
assert result is False
|
||||
|
||||
def test_verifymail_skipped_when_no_api_key(self, email_service):
|
||||
"""verifymail.io is skipped when API key is not configured."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = debounce_resp
|
||||
mock_settings.get_secret.return_value = None # No API key
|
||||
|
||||
result = email_service.is_disposable_domain("user@some-domain.com")
|
||||
assert result is False
|
||||
# Only one HTTP call (DeBounce), not two
|
||||
assert mock_client.return_value.get.call_count == 1
|
||||
|
||||
# =========================================================================
|
||||
# Auto-learn
|
||||
# =========================================================================
|
||||
|
||||
def test_auto_learn_adds_to_manual_domains(self, email_service, mock_db):
|
||||
"""When DeBounce flags a domain, it should be auto-learned to manual_domains."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "true"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
email_service.is_disposable_domain("user@new-disposable.xyz")
|
||||
|
||||
# Verify Firestore was written to with the domain in manual_domains
|
||||
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
|
||||
assert len(set_calls) > 0
|
||||
# Find the auto-learn write
|
||||
for call in set_calls:
|
||||
data = call[0][0]
|
||||
if "manual_domains" in data:
|
||||
assert "new-disposable.xyz" in data["manual_domains"]
|
||||
assert data.get("updated_by") == "auto-learn"
|
||||
break
|
||||
else:
|
||||
pytest.fail("Auto-learn did not write manual_domains")
|
||||
|
||||
def test_auto_learn_verifymail_also_persists(self, email_service, mock_db):
|
||||
"""When verifymail flags a domain DeBounce missed, it should also auto-learn."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
|
||||
verifymail_resp = Mock()
|
||||
verifymail_resp.json.return_value = {"disposable": True, "block": True}
|
||||
verifymail_resp.raise_for_status = Mock()
|
||||
|
||||
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
email_service.is_disposable_domain("user@tricky-disposable.store")
|
||||
|
||||
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
|
||||
found_auto_learn = False
|
||||
for call in set_calls:
|
||||
data = call[0][0]
|
||||
if "manual_domains" in data and "tricky-disposable.store" in data["manual_domains"]:
|
||||
found_auto_learn = True
|
||||
break
|
||||
assert found_auto_learn, "verifymail flagged domain was not auto-learned"
|
||||
|
||||
# =========================================================================
|
||||
# Verified-clean domain cache
|
||||
# =========================================================================
|
||||
|
||||
def test_verified_clean_domain_skips_api_calls(self, email_service, mock_db):
|
||||
"""Domain verified clean within 7 days should skip external API calls."""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
|
||||
# Set up blocklist with a verified clean domain
|
||||
recent = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": [],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {
|
||||
"recently-checked.com": {"checked_at": recent},
|
||||
},
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client:
|
||||
result = email_service.is_disposable_domain("user@recently-checked.com")
|
||||
assert result is False
|
||||
# No HTTP calls — skipped due to verified-clean cache
|
||||
mock_client.return_value.get.assert_not_called()
|
||||
|
||||
def test_expired_clean_domain_rechecks_api(self, email_service, mock_db):
|
||||
"""Domain verified clean >7 days ago should re-check external APIs."""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
|
||||
expired = (datetime.now(timezone.utc) - timedelta(days=8)).isoformat()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": [],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {
|
||||
"expired-check.com": {"checked_at": expired},
|
||||
},
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
result = email_service.is_disposable_domain("user@expired-check.com")
|
||||
assert result is False
|
||||
# Should have called DeBounce since cache expired
|
||||
assert mock_client.return_value.get.call_count >= 1
|
||||
|
||||
def test_clean_result_persisted_to_firestore(self, email_service, mock_db):
|
||||
"""When both APIs say clean, the domain should be persisted as verified clean."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
email_service.is_disposable_domain("user@new-legit-domain.com")
|
||||
|
||||
# Check that verified_clean_domains was written
|
||||
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
|
||||
found_clean = False
|
||||
for call in set_calls:
|
||||
data = call[0][0]
|
||||
if "verified_clean_domains" in data:
|
||||
verified = data["verified_clean_domains"]
|
||||
if "new-legit-domain.com" in verified:
|
||||
assert "checked_at" in verified["new-legit-domain.com"]
|
||||
found_clean = True
|
||||
break
|
||||
assert found_clean, "Clean domain was not persisted to verified_clean_domains"
|
||||
@@ -348,6 +348,53 @@ class TestGCEEncodingBackend:
|
||||
assert output.lossless_4k_mp4_path == "gs://bucket/output/lossless.mp4"
|
||||
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_maps_with_vocals_mp4_from_list(self, mock_get_service):
|
||||
"""Test GCE encoding maps 'With Vocals' MP4 from output_files list.
|
||||
|
||||
The GCE worker returns output_files as a list of blob paths.
|
||||
The mapper must recognize '(With Vocals).mp4' and set with_vocals_mp4_path.
|
||||
Regression test for: with_vocals_mp4 silently dropped from GCE results.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4",
|
||||
"jobs/test/finals/Artist - Title (With Vocals).mp4",
|
||||
"jobs/test/finals/Artist - Title (Karaoke).mp4",
|
||||
]
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
options={
|
||||
"job_id": "test-job",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
assert output.success is True
|
||||
assert output.with_vocals_mp4_path == "jobs/test/finals/Artist - Title (With Vocals).mp4"
|
||||
assert output.lossless_4k_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4"
|
||||
assert output.lossy_4k_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4"
|
||||
assert output.lossless_mkv_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv"
|
||||
assert output.lossy_720p_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4"
|
||||
|
||||
|
||||
class TestGetEncodingBackend:
|
||||
"""Test encoding backend factory function."""
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,243 @@
|
||||
"""
|
||||
Tests for IP geolocation service.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from datetime import datetime
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
|
||||
class TestIsPrivateIp:
|
||||
def test_private_ipv4(self):
|
||||
from backend.services.ip_geolocation_service import _is_private_ip
|
||||
assert _is_private_ip("10.0.0.1") is True
|
||||
assert _is_private_ip("192.168.1.1") is True
|
||||
assert _is_private_ip("172.16.0.1") is True
|
||||
assert _is_private_ip("169.254.169.126") is True
|
||||
assert _is_private_ip("127.0.0.1") is True
|
||||
|
||||
def test_public_ipv4(self):
|
||||
from backend.services.ip_geolocation_service import _is_private_ip
|
||||
assert _is_private_ip("8.8.8.8") is False
|
||||
assert _is_private_ip("1.2.3.4") is False
|
||||
|
||||
def test_invalid_ip(self):
|
||||
from backend.services.ip_geolocation_service import _is_private_ip
|
||||
assert _is_private_ip("not-an-ip") is True
|
||||
assert _is_private_ip("") is True
|
||||
|
||||
def test_ipv6(self):
|
||||
from backend.services.ip_geolocation_service import _is_private_ip
|
||||
assert _is_private_ip("::1") is True # loopback
|
||||
assert _is_private_ip("2001:db8::1") is True # documentation range
|
||||
assert _is_private_ip("2402:800:63ac::1") is False # public
|
||||
|
||||
|
||||
class TestParseIpApiResponse:
|
||||
def test_success_response(self):
|
||||
from backend.services.ip_geolocation_service import _parse_ip_api_response
|
||||
data = {
|
||||
"status": "success",
|
||||
"country": "United States",
|
||||
"countryCode": "US",
|
||||
"regionName": "South Carolina",
|
||||
"city": "Lancaster",
|
||||
"isp": "Comporium Inc",
|
||||
"org": "Comporium Inc",
|
||||
"as": "AS14615 Comporium Inc",
|
||||
"timezone": "America/New_York",
|
||||
"query": "8.8.8.8",
|
||||
}
|
||||
result = _parse_ip_api_response(data)
|
||||
assert result["status"] == "success"
|
||||
assert result["country_code"] == "US"
|
||||
assert result["city"] == "Lancaster"
|
||||
assert result["isp"] == "Comporium Inc"
|
||||
assert result["as_number"] == "AS14615"
|
||||
assert result["as_name"] == "Comporium Inc"
|
||||
|
||||
def test_fail_response(self):
|
||||
from backend.services.ip_geolocation_service import _parse_ip_api_response
|
||||
result = _parse_ip_api_response({"status": "fail", "query": "bad"})
|
||||
assert result["status"] == "fail"
|
||||
|
||||
|
||||
class TestLookupIp:
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_private_ip_returns_immediately(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_fs.Client.return_value = MagicMock()
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
result = service.lookup_ip("192.168.1.1")
|
||||
assert result["status"] == "private"
|
||||
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_cache_hit_returns_cached(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
cached_data = {
|
||||
"status": "success",
|
||||
"ip": "8.8.8.8",
|
||||
"country_code": "US",
|
||||
"cached_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = cached_data
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
result = service.lookup_ip("8.8.8.8")
|
||||
assert result["status"] == "success"
|
||||
assert result["country_code"] == "US"
|
||||
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
@patch('backend.services.ip_geolocation_service.httpx')
|
||||
def test_cache_miss_fetches_from_api(self, mock_httpx, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# Cache miss
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
# Mock httpx response
|
||||
mock_response = MagicMock()
|
||||
mock_response.json.return_value = {
|
||||
"status": "success",
|
||||
"country": "Vietnam",
|
||||
"countryCode": "VN",
|
||||
"regionName": "Ho Chi Minh",
|
||||
"city": "Ho Chi Minh City",
|
||||
"isp": "Viettel",
|
||||
"org": "Viettel Group",
|
||||
"as": "AS7552 Viettel Group",
|
||||
"timezone": "Asia/Ho_Chi_Minh",
|
||||
"query": "14.191.152.247",
|
||||
}
|
||||
mock_client = MagicMock()
|
||||
mock_client.__enter__ = MagicMock(return_value=mock_client)
|
||||
mock_client.__exit__ = MagicMock(return_value=False)
|
||||
mock_client.get.return_value = mock_response
|
||||
mock_httpx.Client.return_value = mock_client
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
result = service.lookup_ip("14.191.152.247")
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["country_code"] == "VN"
|
||||
assert result["isp"] == "Viettel"
|
||||
# Should have cached the result
|
||||
mock_db.collection.return_value.document.return_value.set.assert_called_once()
|
||||
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_null_ip_returns_private(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_fs.Client.return_value = MagicMock()
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
result = service.lookup_ip("")
|
||||
assert result["status"] == "private"
|
||||
result2 = service.lookup_ip(None)
|
||||
assert result2["status"] == "private"
|
||||
|
||||
|
||||
class TestLookupBatch:
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_all_cached(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
cached_data = {
|
||||
"status": "success",
|
||||
"ip": "8.8.8.8",
|
||||
"country_code": "US",
|
||||
"cached_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = cached_data
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
results = service.lookup_ips_batch(["8.8.8.8"])
|
||||
assert "8.8.8.8" in results
|
||||
assert results["8.8.8.8"]["status"] == "success"
|
||||
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_private_ips_in_batch(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_fs.Client.return_value = MagicMock()
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
results = service.lookup_ips_batch(["192.168.1.1", "10.0.0.1"])
|
||||
assert results["192.168.1.1"]["status"] == "private"
|
||||
assert results["10.0.0.1"]["status"] == "private"
|
||||
|
||||
|
||||
class TestAdminEndpoints:
|
||||
@pytest.fixture
|
||||
def admin_client(self):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_admin
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
mock_auth = MagicMock()
|
||||
mock_auth.is_admin = True
|
||||
app.dependency_overrides[require_admin] = lambda: mock_auth
|
||||
|
||||
yield TestClient(app)
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
@patch('backend.api.routes.admin.get_ip_geolocation_service')
|
||||
def test_single_ip_endpoint(self, mock_get_svc, admin_client):
|
||||
mock_svc = MagicMock()
|
||||
mock_svc.lookup_ip.return_value = {
|
||||
"status": "success",
|
||||
"ip": "8.8.8.8",
|
||||
"country_code": "US",
|
||||
}
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/ip-info/8.8.8.8")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["country_code"] == "US"
|
||||
|
||||
@patch('backend.api.routes.admin.get_ip_geolocation_service')
|
||||
def test_batch_endpoint(self, mock_get_svc, admin_client):
|
||||
mock_svc = MagicMock()
|
||||
mock_svc.lookup_ips_batch.return_value = {
|
||||
"8.8.8.8": {"status": "success", "country_code": "US"},
|
||||
"1.1.1.1": {"status": "success", "country_code": "AU"},
|
||||
}
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
response = admin_client.post(
|
||||
"/api/admin/abuse/ip-info/batch",
|
||||
json={"ips": ["8.8.8.8", "1.1.1.1"]},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["8.8.8.8"]["country_code"] == "US"
|
||||
assert data["1.1.1.1"]["country_code"] == "AU"
|
||||
@@ -0,0 +1,514 @@
|
||||
"""
|
||||
Tests for Modal → GCP audio separation migration.
|
||||
|
||||
Covers:
|
||||
- Pipeline decoupling: separation no longer gates lyrics review
|
||||
- Preset-based model configuration
|
||||
- Custom output filenames (job_id prefix)
|
||||
- Screens worker prerequisites relaxation
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
|
||||
# ==================== Fixtures ====================
|
||||
|
||||
@pytest.fixture
|
||||
def mock_firestore_service():
|
||||
with patch('backend.services.job_manager.FirestoreService') as mock:
|
||||
service = Mock()
|
||||
mock.return_value = service
|
||||
yield service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(mock_firestore_service):
|
||||
return JobManager()
|
||||
|
||||
|
||||
def _make_job(job_id="test-001", state_data=None, **kwargs):
|
||||
defaults = dict(
|
||||
job_id=job_id,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
theme_id="default",
|
||||
)
|
||||
defaults.update(kwargs)
|
||||
if state_data is not None:
|
||||
defaults["state_data"] = state_data
|
||||
return Job(**defaults)
|
||||
|
||||
|
||||
# ==================== P0: Pipeline Decoupling ====================
|
||||
|
||||
class TestPipelineDecoupling:
|
||||
"""
|
||||
Critical: verify separation is decoupled from lyrics review path.
|
||||
|
||||
New behavior:
|
||||
- check_parallel_processing_complete() only checks lyrics_complete
|
||||
- mark_audio_complete() sets flag but does NOT trigger screens
|
||||
- mark_lyrics_complete() triggers screens on its own (no audio gate)
|
||||
"""
|
||||
|
||||
def test_check_parallel_only_requires_lyrics(self, job_manager, mock_firestore_service):
|
||||
"""lyrics_complete=True is sufficient, even without audio_complete."""
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
|
||||
assert job_manager.check_parallel_processing_complete("test-001") is True
|
||||
|
||||
def test_check_parallel_fails_without_lyrics(self, job_manager, mock_firestore_service):
|
||||
"""lyrics_complete=False means not ready, even if audio_complete=True."""
|
||||
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
|
||||
assert job_manager.check_parallel_processing_complete("test-001") is False
|
||||
|
||||
def test_check_parallel_fails_with_empty_state(self, job_manager, mock_firestore_service):
|
||||
"""Empty state_data means not ready."""
|
||||
job = _make_job(state_data={})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
|
||||
assert job_manager.check_parallel_processing_complete("test-001") is False
|
||||
|
||||
def test_mark_audio_complete_does_not_trigger_screens(self, job_manager, mock_firestore_service):
|
||||
"""Critical: audio completion must NOT trigger screens worker."""
|
||||
job = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
|
||||
def test_mark_lyrics_complete_triggers_screens_without_audio(self, job_manager, mock_firestore_service):
|
||||
"""Critical: lyrics completion triggers screens even if audio isn't done."""
|
||||
# After update_state_data sets lyrics_complete, get_job returns updated state
|
||||
job_after_update = _make_job(state_data={"audio_complete": False, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_after_update
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once_with("test-001")
|
||||
|
||||
def test_mark_lyrics_complete_triggers_screens_with_audio(self, job_manager, mock_firestore_service):
|
||||
"""Lyrics completion triggers screens when audio is already done too."""
|
||||
job_after_update = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_after_update
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once_with("test-001")
|
||||
|
||||
def test_ordering_audio_first_then_lyrics(self, job_manager, mock_firestore_service):
|
||||
"""Typical flow: audio finishes first, then lyrics triggers screens."""
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
# Audio completes first — get_job returns state without lyrics_complete
|
||||
job_audio_only = _make_job(state_data={"audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_audio_only
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
|
||||
# Now lyrics completes — get_job returns state with both flags
|
||||
job_both = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_both
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once()
|
||||
|
||||
def test_ordering_lyrics_first_then_audio(self, job_manager, mock_firestore_service):
|
||||
"""Less common: lyrics finishes first, triggers screens immediately."""
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
# Lyrics completes first — get_job returns state with lyrics_complete
|
||||
job_lyrics_only = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_lyrics_only
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once()
|
||||
|
||||
# Audio completes later — should NOT trigger screens again
|
||||
job_both = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_both
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
|
||||
|
||||
# ==================== P0: Preset Configuration ====================
|
||||
|
||||
class TestPresetConfiguration:
|
||||
"""
|
||||
Test that preset parameters flow through create_audio_processor correctly.
|
||||
"""
|
||||
|
||||
def test_create_audio_processor_sets_presets(self):
|
||||
"""Presets are set as attributes on the processor."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
processor = create_audio_processor(
|
||||
temp_dir,
|
||||
instrumental_preset="instrumental_clean",
|
||||
karaoke_preset="karaoke",
|
||||
)
|
||||
|
||||
# Verify presets are set on the returned object
|
||||
assert processor.instrumental_preset == "instrumental_clean"
|
||||
assert processor.karaoke_preset == "karaoke"
|
||||
|
||||
def test_create_audio_processor_default_presets(self):
|
||||
"""Default presets are used when not explicitly provided."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
|
||||
from backend.workers.audio_worker import (
|
||||
create_audio_processor,
|
||||
DEFAULT_INSTRUMENTAL_PRESET,
|
||||
DEFAULT_KARAOKE_PRESET,
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
processor = create_audio_processor(temp_dir)
|
||||
|
||||
assert processor.instrumental_preset == DEFAULT_INSTRUMENTAL_PRESET
|
||||
assert processor.karaoke_preset == DEFAULT_KARAOKE_PRESET
|
||||
|
||||
def test_default_other_models_is_empty(self):
|
||||
"""Demucs 6-stem is dropped — DEFAULT_OTHER_MODELS should be empty."""
|
||||
from backend.workers.audio_worker import DEFAULT_OTHER_MODELS
|
||||
assert DEFAULT_OTHER_MODELS == []
|
||||
|
||||
def test_create_audio_processor_with_explicit_models(self):
|
||||
"""Explicit model names still work (legacy per-job override)."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
processor = create_audio_processor(
|
||||
temp_dir,
|
||||
clean_instrumental_model="custom_model.ckpt",
|
||||
backing_vocals_models=["custom_bv.ckpt"],
|
||||
)
|
||||
|
||||
call_kwargs = MockProcessor.call_args[1]
|
||||
assert call_kwargs["clean_instrumental_model"] == "custom_model.ckpt"
|
||||
assert call_kwargs["backing_vocals_models"] == ["custom_bv.ckpt"]
|
||||
|
||||
|
||||
# ==================== P0: Custom Output Names Contract ====================
|
||||
|
||||
class TestCustomOutputNames:
|
||||
"""
|
||||
Test that AudioProcessor uses job_id-based custom_output_names
|
||||
and organizes results by known filenames.
|
||||
"""
|
||||
|
||||
def test_job_id_used_as_file_prefix(self):
|
||||
"""When job_id is set, it's used as the filename prefix in custom_output_names."""
|
||||
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=[], # No stage 2
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None # No stage 2
|
||||
processor.job_id = "abc123"
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
# Create expected output files
|
||||
for name in ["abc123_mixed_vocals.flac", "abc123_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, "abc123_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "abc123_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "test.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):
|
||||
result = processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify custom_output_names used job_id prefix
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert call_kwargs["custom_output_names"]["Vocals"] == "abc123_mixed_vocals"
|
||||
assert call_kwargs["custom_output_names"]["Instrumental"] == "abc123_mixed_instrumental"
|
||||
|
||||
# Verify results found by known filenames
|
||||
assert result["clean_instrumental"]["vocals"].endswith("abc123_mixed_vocals.flac")
|
||||
assert "abc123_mixed_instrumental" in result["clean_instrumental"]["instrumental"]
|
||||
|
||||
def test_stage1_results_found_by_known_filenames(self):
|
||||
"""Stage 1 results are located by predictable filenames, not parsed from model names."""
|
||||
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 # No stage 2
|
||||
processor.job_id = "job42"
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
# Create the files the API would produce
|
||||
vocals_path = os.path.join(stems_dir, "job42_mixed_vocals.flac")
|
||||
instrumental_path = os.path.join(stems_dir, "job42_mixed_instrumental.flac")
|
||||
with open(vocals_path, "w") as f:
|
||||
f.write("fake vocals")
|
||||
with open(instrumental_path, "w") as f:
|
||||
f.write("fake instrumental")
|
||||
|
||||
mock_client = Mock()
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [vocals_path, instrumental_path],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
# Write a fake input file
|
||||
input_file = os.path.join(temp_dir, "input.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('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
result = processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Should find vocals and instrumental by known filenames
|
||||
assert result["clean_instrumental"]["vocals"] == vocals_path
|
||||
assert "mixed_instrumental" in result["clean_instrumental"]["instrumental"]
|
||||
|
||||
|
||||
# ==================== P1: Screens Worker Prerequisites ====================
|
||||
|
||||
class TestScreensWorkerPrerequisites:
|
||||
"""
|
||||
Test that screens worker no longer requires audio_complete.
|
||||
"""
|
||||
|
||||
def test_validate_prerequisites_passes_without_audio(self):
|
||||
"""Screens can generate with only lyrics_complete (audio still in progress)."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
|
||||
assert _validate_prerequisites(job) is True
|
||||
|
||||
def test_validate_prerequisites_passes_with_both(self):
|
||||
"""Normal case: both audio and lyrics complete."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
|
||||
assert _validate_prerequisites(job) is True
|
||||
|
||||
def test_validate_prerequisites_fails_without_lyrics(self):
|
||||
"""Missing lyrics_complete should fail."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
def test_validate_prerequisites_fails_with_empty_state(self):
|
||||
"""Empty state_data should fail."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={})
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
def test_validate_prerequisites_fails_without_theme(self):
|
||||
"""Missing theme_id should fail."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True}, theme_id=None)
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
def test_validate_prerequisites_fails_without_artist_title(self):
|
||||
"""Missing artist or title should fail."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
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
|
||||
@@ -6,6 +6,8 @@ Tests that require full backend imports are in the emulator integration tests.
|
||||
"""
|
||||
import pytest
|
||||
import json
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
|
||||
|
||||
class TestJobStatusTransitionsForReview:
|
||||
@@ -277,6 +279,93 @@ class TestReviewResubmissionClearsWorkerProgress:
|
||||
assert callable(getattr(jm, 'delete_state_data_keys'))
|
||||
|
||||
|
||||
class TestCompleteReviewZeroSegmentValidation:
|
||||
"""Tests for the 0-segment lyrics guard in complete_review endpoint.
|
||||
|
||||
These test the actual HTTP endpoint, not just the validation logic.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def _patched_client(self):
|
||||
"""Create TestClient with mocked services for complete_review."""
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.transition_to_state.return_value = True
|
||||
mock_worker_service = MagicMock()
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = "googleapis.com"
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager), \
|
||||
patch("backend.api.routes.jobs.worker_service", mock_worker_service), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
yield TestClient(app), mock_job_manager
|
||||
|
||||
def _make_job(self, state_data=None):
|
||||
from backend.models.job import Job, JobStatus
|
||||
return Job(
|
||||
job_id="job-zero-seg",
|
||||
status=JobStatus.AWAITING_REVIEW,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
state_data=state_data,
|
||||
)
|
||||
|
||||
def test_endpoint_rejects_zero_segment_lyrics(self, _patched_client):
|
||||
"""POST complete-review returns 400 when lyrics pipeline produced 0 segments."""
|
||||
client, mock_jm = _patched_client
|
||||
job = self._make_job(state_data={
|
||||
'lyrics_metadata': {'segment_count': 0, 'ready_for_review': True},
|
||||
'corrected_lyrics': {'corrected_segments': [], 'original_segments': []},
|
||||
})
|
||||
mock_jm.get_job.return_value = job
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/job-zero-seg/complete-review",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "no lyrics were detected" in response.json()["detail"]
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
def test_endpoint_allows_nonzero_segment_lyrics(self, _patched_client):
|
||||
"""POST complete-review succeeds when lyrics have segments."""
|
||||
client, mock_jm = _patched_client
|
||||
job = self._make_job(state_data={
|
||||
'lyrics_metadata': {'segment_count': 42},
|
||||
'corrected_lyrics': {'corrected_segments': [{'text': 'hello'}] * 42},
|
||||
})
|
||||
mock_jm.get_job.return_value = job
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/job-zero-seg/complete-review",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_jm.transition_to_state.assert_called_once()
|
||||
|
||||
def test_endpoint_allows_job_without_lyrics_metadata(self, _patched_client):
|
||||
"""POST complete-review succeeds for jobs without lyrics_metadata (e.g. finalise-only)."""
|
||||
client, mock_jm = _patched_client
|
||||
job = self._make_job(state_data={}) # No lyrics pipeline ran
|
||||
mock_jm.get_job.return_value = job
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/job-zero-seg/complete-review",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
class TestPreviewStyleLoading:
|
||||
"""Tests for the unified style loader used in preview video generation.
|
||||
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
"""
|
||||
Unit tests for stale review processor.
|
||||
|
||||
Tests the logic for detecting stale review jobs, sending reminder emails,
|
||||
and auto-expiring jobs that exceed the 48h threshold.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
# Mock Google Cloud before imports
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
|
||||
def _make_job(
|
||||
job_id="job-123",
|
||||
status=JobStatus.AWAITING_REVIEW,
|
||||
hours_ago=30,
|
||||
user_email="user@test.com",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
made_for_you=False,
|
||||
tenant_id="",
|
||||
expiry_reminder_sent=False,
|
||||
has_blocking_state=True,
|
||||
):
|
||||
"""Helper to create a mock job with configurable state_data."""
|
||||
job = Mock()
|
||||
job.job_id = job_id
|
||||
job.status = status
|
||||
job.user_email = user_email
|
||||
job.artist = artist
|
||||
job.title = title
|
||||
job.made_for_you = made_for_you
|
||||
job.tenant_id = tenant_id
|
||||
|
||||
if has_blocking_state:
|
||||
entered_at = (datetime.now(timezone.utc) - timedelta(hours=hours_ago)).isoformat()
|
||||
job.state_data = {
|
||||
'blocking_state_entered_at': entered_at,
|
||||
'blocking_action_type': 'lyrics',
|
||||
'reminder_sent': True, # Existing idle reminder (always True for real jobs)
|
||||
}
|
||||
if expiry_reminder_sent:
|
||||
job.state_data['expiry_reminder_sent'] = True
|
||||
else:
|
||||
job.state_data = {}
|
||||
|
||||
return job
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestProcessStaleReviews:
|
||||
"""Test the main stale review processing function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_firestore(self):
|
||||
service = Mock()
|
||||
service.list_jobs.return_value = []
|
||||
service.update_job = Mock()
|
||||
return service
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(self):
|
||||
manager = Mock()
|
||||
manager.cancel_job.return_value = True
|
||||
return manager
|
||||
|
||||
@pytest.fixture
|
||||
def mock_email_service(self):
|
||||
service = Mock()
|
||||
service.send_review_reminder.return_value = True
|
||||
service.send_review_expired.return_value = True
|
||||
return service
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_service(self):
|
||||
service = Mock()
|
||||
service.check_credits.return_value = 2
|
||||
return service
|
||||
|
||||
def _patch_all(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Return a context manager that patches all dependencies."""
|
||||
from contextlib import contextmanager
|
||||
|
||||
@contextmanager
|
||||
def patches():
|
||||
with patch('backend.workers.stale_review_processor.FirestoreService', return_value=mock_firestore), \
|
||||
patch('backend.workers.stale_review_processor.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.workers.stale_review_processor.get_email_service', return_value=mock_email_service), \
|
||||
patch('backend.services.user_service.get_user_service', return_value=mock_user_service):
|
||||
yield
|
||||
return patches()
|
||||
|
||||
async def test_no_stale_jobs(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should return zero counts when no jobs are in review."""
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["reminders_sent"] == 0
|
||||
assert result["jobs_expired"] == 0
|
||||
assert result["status"] == "completed"
|
||||
|
||||
async def test_expires_job_over_48h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should expire a job that's been in review for over 48 hours."""
|
||||
job = _make_job(hours_ago=50)
|
||||
mock_firestore.list_jobs.side_effect = [[job], []] # awaiting_review query, in_review query
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 1
|
||||
mock_job_manager.cancel_job.assert_called_once_with(
|
||||
"job-123", reason="Review not completed within 48 hours"
|
||||
)
|
||||
mock_email_service.send_review_expired.assert_called_once_with(
|
||||
to_email="user@test.com",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
credits_balance=2,
|
||||
)
|
||||
|
||||
async def test_expires_job_over_48h_with_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should expire job >48h even if reminder was already sent (no duplicate reminder)."""
|
||||
job = _make_job(hours_ago=50, expiry_reminder_sent=True)
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 1
|
||||
# Reminder should NOT be sent again
|
||||
mock_email_service.send_review_reminder.assert_not_called()
|
||||
# But expiry email should still be sent
|
||||
mock_email_service.send_review_expired.assert_called_once()
|
||||
|
||||
async def test_sends_reminder_24_to_48h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should send reminder for job in 24-48h range."""
|
||||
job = _make_job(hours_ago=30)
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["reminders_sent"] == 1
|
||||
assert result["jobs_expired"] == 0
|
||||
mock_email_service.send_review_reminder.assert_called_once_with(
|
||||
to_email="user@test.com",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
job_id="job-123",
|
||||
)
|
||||
# Should update state_data with expiry_reminder_sent flag
|
||||
mock_firestore.update_job.assert_called_once()
|
||||
call_args = mock_firestore.update_job.call_args
|
||||
assert call_args[0][0] == "job-123"
|
||||
assert call_args[0][1]['state_data.expiry_reminder_sent'] is True
|
||||
assert 'state_data.expiry_reminder_sent_at' in call_args[0][1]
|
||||
|
||||
async def test_skips_if_expiry_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should skip reminder if expiry_reminder_sent is already True."""
|
||||
job = _make_job(hours_ago=30, expiry_reminder_sent=True)
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["reminders_sent"] == 0
|
||||
assert result["jobs_expired"] == 0
|
||||
mock_email_service.send_review_reminder.assert_not_called()
|
||||
|
||||
async def test_idle_reminder_sent_does_not_block_expiry_reminder(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Existing idle reminder_sent=True should not prevent 24h expiry reminder."""
|
||||
job = _make_job(hours_ago=30)
|
||||
# reminder_sent is True (set by idle reminder system) but expiry_reminder_sent is not set
|
||||
assert job.state_data['reminder_sent'] is True
|
||||
assert 'expiry_reminder_sent' not in job.state_data
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["reminders_sent"] == 1
|
||||
mock_email_service.send_review_reminder.assert_called_once()
|
||||
|
||||
async def test_no_action_under_24h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should take no action for jobs under 24 hours old."""
|
||||
job = _make_job(hours_ago=12)
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["reminders_sent"] == 0
|
||||
assert result["jobs_expired"] == 0
|
||||
mock_email_service.send_review_reminder.assert_not_called()
|
||||
mock_job_manager.cancel_job.assert_not_called()
|
||||
|
||||
async def test_skips_made_for_you_jobs(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should skip made-for-you jobs regardless of age."""
|
||||
job = _make_job(hours_ago=100, made_for_you=True)
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 0
|
||||
assert result["reminders_sent"] == 0
|
||||
mock_job_manager.cancel_job.assert_not_called()
|
||||
|
||||
async def test_skips_tenant_jobs(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should skip tenant/white-label jobs regardless of age."""
|
||||
job = _make_job(hours_ago=100, tenant_id="vocalstar")
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 0
|
||||
assert result["reminders_sent"] == 0
|
||||
mock_job_manager.cancel_job.assert_not_called()
|
||||
|
||||
async def test_skips_job_without_blocking_state(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should skip jobs that have no blocking_state_entered_at."""
|
||||
job = _make_job(hours_ago=50, has_blocking_state=False)
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 0
|
||||
assert result["reminders_sent"] == 0
|
||||
|
||||
async def test_expires_job_without_email(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should still expire jobs with no user_email (just skip the email)."""
|
||||
job = _make_job(hours_ago=50, user_email=None)
|
||||
mock_firestore.list_jobs.side_effect = [[job], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 1
|
||||
mock_job_manager.cancel_job.assert_called_once()
|
||||
# No email sent because no user_email
|
||||
mock_email_service.send_review_expired.assert_not_called()
|
||||
|
||||
async def test_error_in_one_job_doesnt_block_others(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""An error processing one job should not prevent processing others."""
|
||||
job1 = _make_job(job_id="job-bad", hours_ago=50)
|
||||
job2 = _make_job(job_id="job-good", hours_ago=50)
|
||||
mock_firestore.list_jobs.side_effect = [[job1, job2], []]
|
||||
|
||||
# First cancel raises, second succeeds
|
||||
mock_job_manager.cancel_job.side_effect = [Exception("DB error"), True]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 1 # Only job-good counted
|
||||
assert len(result["errors"]) == 1
|
||||
assert "job-bad" in result["errors"][0]
|
||||
|
||||
async def test_return_counts_correct(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Return value should have correct counts for mixed batch."""
|
||||
job_expire = _make_job(job_id="expire-1", hours_ago=50)
|
||||
job_remind = _make_job(job_id="remind-1", hours_ago=30)
|
||||
job_fresh = _make_job(job_id="fresh-1", hours_ago=12)
|
||||
job_skip = _make_job(job_id="skip-1", hours_ago=50, made_for_you=True)
|
||||
mock_firestore.list_jobs.side_effect = [[job_expire, job_remind, job_fresh, job_skip], []]
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 1
|
||||
assert result["reminders_sent"] == 1
|
||||
assert len(result["errors"]) == 0
|
||||
|
||||
async def test_handles_in_review_status(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should process jobs in IN_REVIEW status (user opened but abandoned)."""
|
||||
job = _make_job(job_id="in-review-1", status=JobStatus.IN_REVIEW, hours_ago=50)
|
||||
mock_firestore.list_jobs.side_effect = [[], [job]] # Empty awaiting, one in_review
|
||||
|
||||
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
result = await process_stale_reviews()
|
||||
|
||||
assert result["jobs_expired"] == 1
|
||||
mock_job_manager.cancel_job.assert_called_once()
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -399,8 +399,8 @@ class TestPackagingValidation:
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdg_validation_fails_when_enabled_but_not_produced(self):
|
||||
"""Test that orchestrator raises when CDG enabled but not produced."""
|
||||
async def test_cdg_validation_fails_when_enabled_but_not_produced_and_lrc_has_content(self):
|
||||
"""Test that orchestrator raises when CDG enabled but not produced and LRC has lyrics."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
@@ -417,6 +417,7 @@ class TestPackagingValidation:
|
||||
pass # CDG generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_lrc_has_lyrics_content", return_value=True), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
@@ -426,8 +427,37 @@ class TestPackagingValidation:
|
||||
mock_encoding.assert_not_called() # Should not reach encoding
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_txt_validation_fails_when_enabled_but_not_produced(self):
|
||||
"""Test that orchestrator raises when TXT enabled but not produced."""
|
||||
async def test_cdg_skipped_gracefully_when_lrc_has_no_content(self):
|
||||
"""Test that CDG failure is a warning (not error) when LRC has no lyrics content."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging():
|
||||
pass # CDG generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_lrc_has_lyrics_content", return_value=False), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding, \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is True # Pipeline continues
|
||||
mock_encoding.assert_called_once() # Encoding still runs
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_txt_validation_fails_when_enabled_but_not_produced_and_lrc_has_content(self):
|
||||
"""Test that orchestrator raises when TXT enabled but not produced and LRC has lyrics."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
@@ -443,6 +473,7 @@ class TestPackagingValidation:
|
||||
pass # TXT generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_lrc_has_lyrics_content", return_value=True), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
@@ -506,7 +537,7 @@ class TestPackagingValidation:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_both_cdg_and_txt_validation_fail_together(self):
|
||||
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled."""
|
||||
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled and LRC has content."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
@@ -523,6 +554,7 @@ class TestPackagingValidation:
|
||||
pass # Both CDG and TXT "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_lrc_has_lyrics_content", return_value=True), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
@@ -1709,3 +1741,57 @@ class TestDistributionWarnings:
|
||||
|
||||
assert len(orchestrator.result.distribution_warnings) == 1
|
||||
assert "Dropbox upload failed" in orchestrator.result.distribution_warnings[0]
|
||||
|
||||
|
||||
class TestLrcHasLyricsContent:
|
||||
"""Tests for _lrc_has_lyrics_content helper."""
|
||||
|
||||
def _make_orchestrator(self, lrc_file_path=None):
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
lrc_file_path=lrc_file_path,
|
||||
)
|
||||
return VideoWorkerOrchestrator(config)
|
||||
|
||||
def test_returns_false_when_no_lrc_path(self):
|
||||
orchestrator = self._make_orchestrator(lrc_file_path=None)
|
||||
assert orchestrator._lrc_has_lyrics_content() is False
|
||||
|
||||
def test_returns_false_when_lrc_file_missing(self):
|
||||
orchestrator = self._make_orchestrator(lrc_file_path="/nonexistent/path.lrc")
|
||||
assert orchestrator._lrc_has_lyrics_content() is False
|
||||
|
||||
def test_returns_false_for_empty_lrc(self, tmp_path):
|
||||
lrc_file = tmp_path / "empty.lrc"
|
||||
lrc_file.write_text("[re:MidiCo]\n")
|
||||
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
|
||||
assert orchestrator._lrc_has_lyrics_content() is False
|
||||
|
||||
def test_returns_true_for_lrc_with_lyrics(self, tmp_path):
|
||||
lrc_file = tmp_path / "valid.lrc"
|
||||
lrc_file.write_text("[re:MidiCo]\n[00:12.345]Hello world\n[00:15.678]Second line\n")
|
||||
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
|
||||
assert orchestrator._lrc_has_lyrics_content() is True
|
||||
|
||||
def test_returns_true_for_centisecond_timestamps(self, tmp_path):
|
||||
lrc_file = tmp_path / "centisecond.lrc"
|
||||
lrc_file.write_text("[01:02.34]Lyric line\n")
|
||||
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
|
||||
assert orchestrator._lrc_has_lyrics_content() is True
|
||||
|
||||
def test_returns_true_for_no_decimal_timestamps(self, tmp_path):
|
||||
lrc_file = tmp_path / "nodecimal.lrc"
|
||||
lrc_file.write_text("[01:30]Lyric line\n")
|
||||
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
|
||||
assert orchestrator._lrc_has_lyrics_content() is True
|
||||
|
||||
def test_returns_false_for_metadata_only_lrc(self, tmp_path):
|
||||
lrc_file = tmp_path / "meta.lrc"
|
||||
lrc_file.write_text("[ti:Song Title]\n[ar:Artist Name]\n[re:MidiCo]\n")
|
||||
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
|
||||
assert orchestrator._lrc_has_lyrics_content() is False
|
||||
@@ -621,7 +621,7 @@ class TestAudioWorkerModelConfiguration:
|
||||
# Should use default models
|
||||
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
|
||||
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
|
||||
assert call_kwargs['other_stems_models'] == []
|
||||
|
||||
def test_create_audio_processor_with_custom_clean_model(self):
|
||||
"""Test creating AudioProcessor with custom clean instrumental model."""
|
||||
@@ -762,7 +762,7 @@ class TestAudioWorkerModelConfiguration:
|
||||
# Should fall back to defaults
|
||||
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
|
||||
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
|
||||
assert call_kwargs['other_stems_models'] == []
|
||||
|
||||
|
||||
class TestDownloadFromUrl:
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
Request utility helpers for extracting client information.
|
||||
"""
|
||||
from typing import Optional
|
||||
from fastapi import Request
|
||||
|
||||
|
||||
def get_client_ip(request: Request) -> Optional[str]:
|
||||
"""
|
||||
Extract real client IP address from a request.
|
||||
|
||||
Cloud Run and load balancers set X-Forwarded-For header with the
|
||||
original client IP as the first entry. Falls back to request.client.host
|
||||
for direct connections (local dev).
|
||||
|
||||
Returns None if no IP can be determined.
|
||||
"""
|
||||
forwarded = request.headers.get("x-forwarded-for", "")
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()
|
||||
if request.client:
|
||||
return request.client.host
|
||||
return None
|
||||
@@ -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)
|
||||
@@ -61,10 +61,15 @@ async def _trigger_lyrics_worker_after_url_download(job_id: str) -> None:
|
||||
logger.error(f"Job {job_id}: Failed to trigger lyrics worker: {e}")
|
||||
|
||||
|
||||
# Default model names - used by create_audio_processor and stored in state_data
|
||||
# Default ensemble presets — resolved by audio-separator package into models + algorithm.
|
||||
# To change models, update ensemble_presets.json in audio-separator and release a new version.
|
||||
DEFAULT_INSTRUMENTAL_PRESET = "instrumental_clean" # Fv7z + Resurrection, SDR ~17.5
|
||||
DEFAULT_KARAOKE_PRESET = "karaoke" # 3 karaoke models ensemble, SDR ~10.6
|
||||
|
||||
# Legacy model name constants — kept for backward compatibility with per-job overrides
|
||||
DEFAULT_CLEAN_MODEL = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
DEFAULT_BACKING_MODELS = ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
|
||||
DEFAULT_OTHER_MODELS = ["htdemucs_6s.yaml"]
|
||||
DEFAULT_OTHER_MODELS = [] # Demucs 6-stem dropped — no longer separating individual instruments
|
||||
|
||||
|
||||
# Loggers to capture for audio worker
|
||||
@@ -197,50 +202,59 @@ def create_audio_processor(
|
||||
temp_dir: str,
|
||||
clean_instrumental_model: Optional[str] = None,
|
||||
backing_vocals_models: Optional[list] = None,
|
||||
other_stems_models: Optional[list] = None
|
||||
other_stems_models: Optional[list] = None,
|
||||
instrumental_preset: Optional[str] = None,
|
||||
karaoke_preset: Optional[str] = None,
|
||||
) -> AudioProcessor:
|
||||
"""
|
||||
Create an AudioProcessor instance configured for remote API processing.
|
||||
|
||||
This reuses the karaoke_gen AudioProcessor with settings optimized for Cloud Run:
|
||||
- Uses remote Modal API (via AUDIO_SEPARATOR_API_URL env var)
|
||||
- No local models needed (model_file_dir=None)
|
||||
- FLAC output format for quality
|
||||
- Model configurations from job or CLI defaults
|
||||
|
||||
|
||||
Supports two modes:
|
||||
- Preset mode (default): Uses ensemble presets for higher quality separation.
|
||||
Presets are resolved by the audio-separator API server.
|
||||
- Model mode (legacy): Uses explicit model filenames for per-job overrides.
|
||||
|
||||
Args:
|
||||
temp_dir: Temporary directory for processing
|
||||
clean_instrumental_model: Model for clean instrumental separation (optional, uses default if not provided)
|
||||
backing_vocals_models: List of models for backing vocals separation (optional, uses default if not provided)
|
||||
other_stems_models: List of models for other stems separation (optional, uses default if not provided)
|
||||
|
||||
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)
|
||||
instrumental_preset: Ensemble preset for instrumental separation
|
||||
karaoke_preset: Ensemble preset for karaoke/BV separation
|
||||
|
||||
Returns:
|
||||
Configured AudioProcessor instance
|
||||
"""
|
||||
# Configure logger for AudioProcessor
|
||||
audio_logger = logging.getLogger("karaoke_gen.audio_processor")
|
||||
audio_logger.setLevel(logging.INFO)
|
||||
|
||||
# Model configurations - use provided values or defaults from module constants
|
||||
|
||||
# Determine effective configuration
|
||||
# If explicit models are provided, use them (legacy per-job override)
|
||||
# Otherwise use ensemble presets (default)
|
||||
effective_clean_model = clean_instrumental_model or DEFAULT_CLEAN_MODEL
|
||||
effective_backing_models = backing_vocals_models or DEFAULT_BACKING_MODELS
|
||||
effective_other_models = other_stems_models or DEFAULT_OTHER_MODELS # For 6-stem separation (bass, drums, etc.)
|
||||
|
||||
# FFmpeg command for combining audio files (must be a string, not a list)
|
||||
effective_other_models = other_stems_models or DEFAULT_OTHER_MODELS
|
||||
|
||||
ffmpeg_base_command = "ffmpeg -hide_banner -loglevel error -nostats -y"
|
||||
|
||||
return AudioProcessor(
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=audio_logger,
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None, # Not needed for our use case
|
||||
log_formatter=None,
|
||||
model_file_dir=None, # No local models, using remote API
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model=effective_clean_model,
|
||||
backing_vocals_models=effective_backing_models,
|
||||
other_stems_models=effective_other_models,
|
||||
ffmpeg_base_command=ffmpeg_base_command
|
||||
ffmpeg_base_command=ffmpeg_base_command,
|
||||
)
|
||||
|
||||
# Set preset configuration (used by _process_audio_separation_remote)
|
||||
processor.instrumental_preset = instrumental_preset or DEFAULT_INSTRUMENTAL_PRESET
|
||||
processor.karaoke_preset = karaoke_preset or DEFAULT_KARAOKE_PRESET
|
||||
|
||||
return processor
|
||||
|
||||
|
||||
async def process_audio_separation(job_id: str) -> bool:
|
||||
"""
|
||||
@@ -356,8 +370,14 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
temp_dir,
|
||||
clean_instrumental_model=job.clean_instrumental_model,
|
||||
backing_vocals_models=job.backing_vocals_models,
|
||||
other_stems_models=job.other_stems_models
|
||||
other_stems_models=job.other_stems_models,
|
||||
)
|
||||
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")
|
||||
@@ -387,12 +407,32 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
add_span_event("separation_started")
|
||||
logger.info(f"[job:{job_id}] Calling Modal API for 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("modal", 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)
|
||||
@@ -439,7 +479,7 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
|
||||
except Exception as e:
|
||||
duration = time.time() - start_time
|
||||
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}")
|
||||
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id,
|
||||
error_message=f"Audio separation failed: {str(e)}",
|
||||
|
||||
@@ -45,6 +45,7 @@ from backend.services.tracing import job_span, add_span_event, add_span_attribut
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
|
||||
# Import from the unified style loader
|
||||
@@ -161,30 +162,32 @@ async def process_render_video(job_id: str) -> bool:
|
||||
with open(original_corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
# 3. Check if there are updated corrections (from review UI)
|
||||
# The frontend sends only partial data: {corrections, corrected_segments}
|
||||
# 3. Load base CorrectionResult from original data
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# 4. Apply user corrections if available (from review UI)
|
||||
# Uses the same method as preview generation to ensure
|
||||
# identical CorrectionResult construction (DRY).
|
||||
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
|
||||
if storage.file_exists(updated_corrections_gcs):
|
||||
job_log.info("Found updated corrections from review, merging")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, merging")
|
||||
job_log.info("Found updated corrections from review, applying via shared method")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
|
||||
updated_path = os.path.join(temp_dir, "corrections_updated.json")
|
||||
storage.download_file(updated_corrections_gcs, updated_path)
|
||||
|
||||
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
|
||||
# Merge: update the original with the user's corrections
|
||||
if 'corrections' in updated_data:
|
||||
original_data['corrections'] = updated_data['corrections']
|
||||
if 'corrected_segments' in updated_data:
|
||||
original_data['corrected_segments'] = updated_data['corrected_segments']
|
||||
|
||||
job_log.info("Merged user corrections into original data")
|
||||
logger.info(f"Job {job_id}: Merged user corrections into original data")
|
||||
|
||||
# 4. Convert to CorrectionResult
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# Same construction path as preview — prevents divergence
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
job_log.info("Applied user corrections via CorrectionOperations")
|
||||
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
|
||||
|
||||
@@ -258,7 +258,7 @@ async def generate_screens(job_id: str) -> bool:
|
||||
|
||||
def _validate_prerequisites(job) -> bool:
|
||||
"""
|
||||
Validate that both audio and lyrics processing are complete.
|
||||
Validate that lyrics processing is complete (audio is no longer required).
|
||||
|
||||
Single Responsibility: Validation logic separated from main flow.
|
||||
|
||||
@@ -286,17 +286,19 @@ def _validate_prerequisites(job) -> bool:
|
||||
)
|
||||
return False
|
||||
|
||||
audio_complete = job.state_data.get('audio_complete', False)
|
||||
lyrics_complete = job.state_data.get('lyrics_complete', False)
|
||||
|
||||
if not audio_complete:
|
||||
logger.error(f"Job {job.job_id}: Audio processing not complete")
|
||||
return False
|
||||
audio_complete = job.state_data.get('audio_complete', False)
|
||||
|
||||
if not lyrics_complete:
|
||||
logger.error(f"Job {job.job_id}: Lyrics processing not complete")
|
||||
return False
|
||||
|
||||
# Audio separation is no longer a prerequisite for screens.
|
||||
# Users can start lyrics review while separation runs in the background.
|
||||
# The instrumental review page handles waiting for audio_complete.
|
||||
if not audio_complete:
|
||||
logger.info(f"Job {job.job_id}: Audio separation still in progress (not blocking screens)")
|
||||
|
||||
if not job.artist or not job.title:
|
||||
logger.error(f"Job {job.job_id}: Missing artist or title")
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Stale review processor.
|
||||
|
||||
Detects jobs stuck in review (awaiting_review / in_review) and takes action:
|
||||
- 24h: sends a gentle reminder email with expiry warning
|
||||
- 48h: auto-cancels the job and refunds the user's credit
|
||||
|
||||
Called by Cloud Scheduler via an internal endpoint (hourly).
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Configurable thresholds (hours since blocking_state_entered_at)
|
||||
REVIEW_REMINDER_HOURS = 24
|
||||
REVIEW_EXPIRY_HOURS = 48
|
||||
|
||||
|
||||
async def process_stale_reviews() -> Dict[str, Any]:
|
||||
"""
|
||||
Query for stale review jobs and take action.
|
||||
|
||||
- Jobs in review for >= 48h are auto-cancelled with credit refund
|
||||
- Jobs in review for >= 24h (but < 48h) get a reminder email
|
||||
|
||||
Excludes made-for-you and tenant jobs.
|
||||
|
||||
Returns:
|
||||
Summary dict with counts and any errors encountered.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
firestore = FirestoreService()
|
||||
email_service = get_email_service()
|
||||
|
||||
reminders_sent = 0
|
||||
jobs_expired = 0
|
||||
errors = []
|
||||
|
||||
# Query for jobs in both blocking review states
|
||||
stale_jobs = []
|
||||
for status in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
try:
|
||||
jobs = firestore.list_jobs(status=status, limit=500)
|
||||
stale_jobs.extend(jobs)
|
||||
except Exception as e:
|
||||
error_msg = f"Failed to query jobs with status {status.value}: {e}"
|
||||
logger.error(error_msg)
|
||||
errors.append(error_msg)
|
||||
|
||||
if not stale_jobs:
|
||||
logger.info("No stale review jobs found")
|
||||
return {
|
||||
"status": "completed",
|
||||
"reminders_sent": 0,
|
||||
"jobs_expired": 0,
|
||||
"errors": errors,
|
||||
}
|
||||
|
||||
logger.info(f"Found {len(stale_jobs)} jobs in review states, checking for stale ones")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
for job in stale_jobs:
|
||||
try:
|
||||
# Skip made-for-you jobs (admin-controlled)
|
||||
if getattr(job, 'made_for_you', False):
|
||||
continue
|
||||
|
||||
# Skip tenant/white-label jobs (B2B partners)
|
||||
if getattr(job, 'tenant_id', '') and job.tenant_id:
|
||||
continue
|
||||
|
||||
# Get blocking state entry time from state_data
|
||||
state_data = job.state_data or {}
|
||||
blocking_entered_at_str = state_data.get('blocking_state_entered_at')
|
||||
if not blocking_entered_at_str:
|
||||
continue
|
||||
|
||||
# Parse the naive UTC ISO string and make it timezone-aware
|
||||
try:
|
||||
blocking_entered_at = datetime.fromisoformat(blocking_entered_at_str)
|
||||
if blocking_entered_at.tzinfo is None:
|
||||
blocking_entered_at = blocking_entered_at.replace(tzinfo=timezone.utc)
|
||||
except (ValueError, TypeError):
|
||||
logger.warning(
|
||||
f"Job {job.job_id}: invalid blocking_state_entered_at: {blocking_entered_at_str}"
|
||||
)
|
||||
continue
|
||||
|
||||
hours_elapsed = (now - blocking_entered_at).total_seconds() / 3600
|
||||
|
||||
if hours_elapsed >= REVIEW_EXPIRY_HOURS:
|
||||
# Auto-expire: cancel job (which refunds credit)
|
||||
logger.info(
|
||||
f"Job {job.job_id}: review stale for {hours_elapsed:.1f}h (>={REVIEW_EXPIRY_HOURS}h), "
|
||||
f"auto-expiring"
|
||||
)
|
||||
cancelled = job_manager.cancel_job(
|
||||
job.job_id,
|
||||
reason="Review not completed within 48 hours"
|
||||
)
|
||||
if cancelled:
|
||||
jobs_expired += 1
|
||||
|
||||
# Send expiry notification email
|
||||
if job.user_email:
|
||||
try:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
credits_balance = user_service.check_credits(job.user_email)
|
||||
|
||||
email_service.send_review_expired(
|
||||
to_email=job.user_email,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
credits_balance=credits_balance,
|
||||
)
|
||||
except Exception as email_err:
|
||||
logger.error(
|
||||
f"Job {job.job_id}: failed to send expiry email: {email_err}"
|
||||
)
|
||||
else:
|
||||
logger.warning(f"Job {job.job_id}: cancel_job returned False")
|
||||
|
||||
elif hours_elapsed >= REVIEW_REMINDER_HOURS:
|
||||
# Check if expiry reminder was already sent
|
||||
if state_data.get('expiry_reminder_sent'):
|
||||
continue
|
||||
|
||||
logger.info(
|
||||
f"Job {job.job_id}: review stale for {hours_elapsed:.1f}h (>={REVIEW_REMINDER_HOURS}h), "
|
||||
f"sending reminder"
|
||||
)
|
||||
|
||||
# Send reminder email
|
||||
if job.user_email:
|
||||
try:
|
||||
email_service.send_review_reminder(
|
||||
to_email=job.user_email,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
job_id=job.job_id,
|
||||
)
|
||||
except Exception as email_err:
|
||||
logger.error(
|
||||
f"Job {job.job_id}: failed to send reminder email: {email_err}"
|
||||
)
|
||||
|
||||
# Update state_data to mark reminder as sent (even if email failed,
|
||||
# to avoid retrying every hour)
|
||||
try:
|
||||
firestore.update_job(job.job_id, {
|
||||
'state_data.expiry_reminder_sent': True,
|
||||
'state_data.expiry_reminder_sent_at': datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
except Exception as update_err:
|
||||
logger.error(
|
||||
f"Job {job.job_id}: failed to update expiry_reminder_sent: {update_err}"
|
||||
)
|
||||
|
||||
reminders_sent += 1
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Job {job.job_id}: unexpected error: {e}"
|
||||
logger.exception(error_msg)
|
||||
errors.append(error_msg)
|
||||
|
||||
logger.info(
|
||||
f"Stale review processing complete: "
|
||||
f"{reminders_sent} reminders sent, {jobs_expired} jobs expired, "
|
||||
f"{len(errors)} errors"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "completed",
|
||||
"reminders_sent": reminders_sent,
|
||||
"jobs_expired": jobs_expired,
|
||||
"errors": errors,
|
||||
}
|
||||
@@ -18,6 +18,7 @@ Pipeline stages:
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, Dict, Any, List
|
||||
@@ -234,16 +235,31 @@ class VideoWorkerOrchestrator:
|
||||
await self._run_packaging()
|
||||
|
||||
# Validate required packaging outputs before expensive encoding
|
||||
# If LRC has no lyrics content (e.g. input audio had no vocals),
|
||||
# skip CDG/TXT gracefully instead of failing the entire job
|
||||
lrc_has_content = self._lrc_has_lyrics_content()
|
||||
if self.config.enable_cdg and not self.result.final_karaoke_cdg_zip:
|
||||
raise RuntimeError(
|
||||
"CDG generation was enabled but failed. "
|
||||
"Check worker logs for CDG-related errors."
|
||||
)
|
||||
if lrc_has_content:
|
||||
raise RuntimeError(
|
||||
"CDG generation was enabled but failed. "
|
||||
"Check worker logs for CDG-related errors."
|
||||
)
|
||||
else:
|
||||
self.job_log.warning(
|
||||
"CDG generation skipped: LRC file has no lyrics content. "
|
||||
"Video will be generated without CDG package."
|
||||
)
|
||||
if self.config.enable_txt and not self.result.final_karaoke_txt_zip:
|
||||
raise RuntimeError(
|
||||
"TXT generation was enabled but failed. "
|
||||
"Check worker logs for TXT-related errors."
|
||||
)
|
||||
if lrc_has_content:
|
||||
raise RuntimeError(
|
||||
"TXT generation was enabled but failed. "
|
||||
"Check worker logs for TXT-related errors."
|
||||
)
|
||||
else:
|
||||
self.job_log.warning(
|
||||
"TXT generation skipped: LRC file has no lyrics content. "
|
||||
"Video will be generated without TXT package."
|
||||
)
|
||||
|
||||
# Stage 2: Encoding
|
||||
await self._run_encoding()
|
||||
@@ -276,6 +292,18 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
return self.result
|
||||
|
||||
def _lrc_has_lyrics_content(self) -> bool:
|
||||
"""Check if the LRC file has actual lyrics content (timestamp lines), not just metadata."""
|
||||
if not self.config.lrc_file_path or not os.path.isfile(self.config.lrc_file_path):
|
||||
return False
|
||||
try:
|
||||
with open(self.config.lrc_file_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
# Match LRC timestamp lines: [MM:SS.xx] or [MM:SS.xxx] or [M:SS.xx]
|
||||
return bool(re.search(r"\[\d{1,2}:\d{2}(?:\.\d{1,3})?\]", content))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def _run_packaging(self):
|
||||
"""Run the packaging stage (CDG/TXT generation)."""
|
||||
self.job_log.info("Starting packaging stage (CDG/TXT)")
|
||||
|
||||
@@ -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.
|
||||
+62
-7
@@ -842,16 +842,18 @@ Common status codes:
|
||||
POST /api/users/auth/magic-link
|
||||
Content-Type: application/json
|
||||
|
||||
{"email": "user@example.com"}
|
||||
{"email": "user@example.com", "device_fingerprint": "optional-fp-string"}
|
||||
```
|
||||
|
||||
The `device_fingerprint` field is optional. If provided, it's used alongside the client IP for signup rate limiting (max 2 new accounts per IP or fingerprint per 24 hours). Existing users are never rate limited. Rate-limited requests receive a silent 200 response (anti-enumeration).
|
||||
|
||||
### Verify Magic Link
|
||||
|
||||
```http
|
||||
GET /api/users/auth/verify?token=TOKEN
|
||||
```
|
||||
|
||||
Returns session token and user info.
|
||||
Returns session token, user info, and `credits_granted` (number of welcome credits granted on this verification, 0 for returning users). Welcome credits are granted on first verification, not at account creation.
|
||||
|
||||
**Admin Login Token**: The same endpoint supports admin login tokens embedded in notification emails. When a made-for-you order is received, the admin notification email includes a link with `?admin_token=TOKEN` that auto-logs the admin into the app. The frontend detects this parameter and calls the verify endpoint to authenticate. Admin tokens expire after 24 hours.
|
||||
|
||||
@@ -942,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
|
||||
|
||||
@@ -967,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
|
||||
|
||||
@@ -982,7 +984,7 @@ Response:
|
||||
"eligible": true,
|
||||
"has_submitted": false,
|
||||
"jobs_completed": 3,
|
||||
"credits_reward": 2
|
||||
"credits_reward": 1
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1011,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.
|
||||
|
||||
@@ -1697,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
|
||||
@@ -1713,12 +1757,16 @@ Job creation is controlled by credits (purchased or earned via feedback). There
|
||||
GET /api/admin/rate-limits/blocklists
|
||||
POST /api/admin/rate-limits/blocklists/disposable-domains
|
||||
DELETE /api/admin/rate-limits/blocklists/disposable-domains/{domain}
|
||||
POST /api/admin/rate-limits/blocklists/allowlisted-domains
|
||||
DELETE /api/admin/rate-limits/blocklists/allowlisted-domains/{domain}
|
||||
POST /api/admin/rate-limits/blocklists/sync
|
||||
POST /api/admin/rate-limits/blocklists/blocked-emails
|
||||
DELETE /api/admin/rate-limits/blocklists/blocked-emails/{email}
|
||||
POST /api/admin/rate-limits/blocklists/blocked-ips
|
||||
DELETE /api/admin/rate-limits/blocklists/blocked-ips/{ip}
|
||||
POST /api/internal/sync-disposable-domains
|
||||
```
|
||||
Manage blocklists for disposable email domains, blocked emails, and blocked IPs.
|
||||
Manage blocklists for disposable email domains, blocked emails, and blocked IPs. The disposable domain list auto-syncs daily from the [disposable-email-domains](https://github.com/disposable-email-domains/disposable-email-domains) repo (~4,800 domains). Admins can add manual domains, and allowlist false positives. The `GET` response includes `external_domains`, `manual_domains`, `allowlisted_domains`, `last_sync_at`, and `last_sync_count`.
|
||||
|
||||
### YouTube Upload Queue
|
||||
|
||||
@@ -1744,6 +1792,13 @@ POST /api/internal/youtube-queue/process
|
||||
```
|
||||
Called by Cloud Scheduler hourly. Processes queued uploads while quota is available. Returns summary of processed/failed/remaining uploads.
|
||||
|
||||
### Internal Stale Review Processing
|
||||
|
||||
```http
|
||||
POST /api/internal/process-stale-reviews
|
||||
```
|
||||
Called by Cloud Scheduler hourly. Queries for jobs in `awaiting_review` or `in_review` status, sends reminder emails at 24h, and auto-cancels with credit refund at 48h. Excludes made-for-you and tenant jobs. Returns `{status: "started", message: "..."}` immediately; processing runs in background.
|
||||
|
||||
## Webhooks
|
||||
|
||||
Stripe webhooks implemented at `/api/users/webhooks/stripe`.
|
||||
|
||||
+69
-5
@@ -16,7 +16,7 @@
|
||||
│ https://api.nomadkaraoke.com │
|
||||
│ │
|
||||
│ Workers: │
|
||||
│ • Audio Worker - Stem separation via Modal API │
|
||||
│ • Audio Worker - Stem separation via Cloud Run GPU (L4) │
|
||||
│ • Lyrics Worker - Transcription via AudioShake │
|
||||
│ • Screens Worker - Title/end screen generation │
|
||||
│ • Render Worker - Karaoke video with lyrics │
|
||||
@@ -48,7 +48,7 @@
|
||||
2. PARALLEL PROCESSING (with Worker Registry coordination)
|
||||
┌─────────────────┐ ┌─────────────────┐
|
||||
│ Audio Worker │ │ Lyrics Worker │
|
||||
│ Modal API │ │ AudioShake │
|
||||
│ Cloud Run GPU │ │ AudioShake │
|
||||
│ 2-stage sep │ │ Auto-correct │
|
||||
│ ↓ register() │ │ ↓ register() │
|
||||
│ ↓ unregister() │ │ ↓ unregister() │
|
||||
@@ -161,7 +161,7 @@ LyricsTranscriber LyricsTranscriber
|
||||
|
||||
| Service | Purpose | Required |
|
||||
|---------|---------|----------|
|
||||
| Modal | GPU audio separation | Yes |
|
||||
| Cloud Run GPU (L4) | Audio stem separation (us-east4) | Yes |
|
||||
| AudioShake | Lyrics transcription | Yes |
|
||||
| Vertex AI | Agentic AI correction (Gemini 3 Flash) | Default off (SKIP_CORRECTION=false to enable) |
|
||||
| Genius | Reference lyrics | Yes |
|
||||
@@ -176,6 +176,24 @@ LyricsTranscriber LyricsTranscriber
|
||||
|
||||
*Flacfetch runs on a dedicated GCE VM with YouTube cookies and tracker access. Without it, YouTube downloads will fail due to bot detection on Cloud Run IPs.
|
||||
|
||||
### Data Pipeline Cloud Functions
|
||||
|
||||
Three Cloud Functions manage the community karaoke data pipeline, running daily on automated schedules:
|
||||
|
||||
| Function | Schedule | Purpose |
|
||||
|----------|----------|---------|
|
||||
| `divebar-mirror` | Daily 2:00 AM ET | Indexes 48K+ files from [diveBar Karaoke Google Drive](https://drive.google.com/drive/folders/1zxnSZcE03gzy0YVGOdnTrEIi8It_3Wu8) into BigQuery `divebar_catalog` |
|
||||
| `kn-data-sync` | Daily 3:05 AM + 4:30 AM ET | Fetches KaraokeNerds catalog (281K songs) and community tracks (58K with YouTube URLs) to BigQuery + GCS |
|
||||
| `divebar-lookup` | Daily 6:00 AM ET + on-demand API | Public search/lookup API for KJ Controller; rebuilds KN↔Divebar cross-reference index |
|
||||
|
||||
**Infrastructure** (Pulumi-managed in `infrastructure/`):
|
||||
- Service accounts: `divebar-mirror@`, `kn-data-sync@`, `divebar-lookup@` (least-privilege IAM)
|
||||
- GCS: `nomadkaraoke-kn-data` (raw exports), 3 source buckets for function code
|
||||
- BigQuery tables: `divebar_catalog`, `karaokenerds_community`, `kn_divebar_xref` (in `karaoke_decide` dataset)
|
||||
- Secret: `karaokenerds-api-key` (KN API access)
|
||||
|
||||
**Source code:** `infrastructure/functions/{divebar_mirror,kn_data_sync,divebar_lookup}/`
|
||||
|
||||
## Firestore Collections
|
||||
|
||||
karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses separate Firestore collections:
|
||||
@@ -196,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).
|
||||
@@ -241,7 +305,7 @@ The Video Worker uses an orchestrator pattern to ensure all features work regard
|
||||
| `job_notification_service.py` | Email orchestration (completion, reminders) |
|
||||
| `audio_transcoding_service.py` | Transcode FLAC → OGG Opus for review UI playback |
|
||||
| `youtube_quota_service.py` | Track YouTube API quota (GCP Cloud Monitoring + Firestore pending buffer) |
|
||||
| `email_validation_service.py` | Email validation, disposable domain detection, blocklist management |
|
||||
| `email_validation_service.py` | Email validation, tiered disposable domain detection (static list + DeBounce + verifymail.io APIs), blocklist management |
|
||||
| `youtube_upload_queue_service.py` | Deferred YouTube upload queue management |
|
||||
| `catalog_proxy_service.py` | Proxy to karaoke-decide catalog API (artist/track search) |
|
||||
| `karaokenerds_service.py` | Scrape karaokenerds.com for community karaoke versions |
|
||||
@@ -305,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 (Modal API) │
|
||||
│ audio-separation-job - 10-20 min (Cloud Run GPU) │
|
||||
│ video-encoding-job - up to 60 min (optional) │
|
||||
│ │
|
||||
│ Triggered via: google.cloud.run_v2.JobsClient.run_job() │
|
||||
|
||||
@@ -208,6 +208,71 @@ TESTMAIL_NAMESPACE=... # testmail.app namespace
|
||||
| `./scripts/setup-singa-tenant.py` | Generate Singa tenant assets and upload to GCS |
|
||||
| `./scripts/setup-vocalstar-tenant.py` | Generate Vocal Star tenant assets and upload to GCS |
|
||||
|
||||
## Encoding Worker Operations
|
||||
|
||||
The encoding worker uses a blue-green deployment with two GCE VMs (`encoding-worker-a`, `encoding-worker-b`). See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-deployment) for the full design.
|
||||
|
||||
### Seed Firestore config (initial setup or reset)
|
||||
|
||||
```bash
|
||||
python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>
|
||||
```
|
||||
|
||||
### Check VM status
|
||||
|
||||
```bash
|
||||
gcloud compute instances describe encoding-worker-a \
|
||||
--zone=us-central1-c --project=nomadkaraoke \
|
||||
--format='value(status)'
|
||||
```
|
||||
|
||||
### Manually start / stop a VM
|
||||
|
||||
```bash
|
||||
# Start
|
||||
gcloud compute instances start encoding-worker-a \
|
||||
--zone=us-central1-c --project=nomadkaraoke
|
||||
|
||||
# Stop
|
||||
gcloud compute instances stop encoding-worker-a \
|
||||
--zone=us-central1-c --project=nomadkaraoke
|
||||
```
|
||||
|
||||
### Check worker health
|
||||
|
||||
```bash
|
||||
IP=$(gcloud compute instances describe encoding-worker-a \
|
||||
--zone=us-central1-c --project=nomadkaraoke \
|
||||
--format='value(networkInterfaces[0].accessConfigs[0].natIP)')
|
||||
curl http://$IP:8080/health
|
||||
```
|
||||
|
||||
### Manually trigger idle shutdown
|
||||
|
||||
Go to Cloud Scheduler in the GCP console and click "Force run" on the `encoding-worker-idle-shutdown` job, or:
|
||||
|
||||
```bash
|
||||
gcloud scheduler jobs run encoding-worker-idle-shutdown \
|
||||
--location=us-central1 --project=nomadkaraoke
|
||||
```
|
||||
|
||||
### Roll back a deploy
|
||||
|
||||
If a deploy went wrong, swap the Firestore config back to the old primary:
|
||||
|
||||
```bash
|
||||
python3 << 'EOF'
|
||||
import os
|
||||
os.environ['GOOGLE_CLOUD_PROJECT'] = 'nomadkaraoke'
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project='nomadkaraoke')
|
||||
db.collection('config').document('encoding-worker').update({'primary': 'a'}) # or 'b'
|
||||
print("Rolled back")
|
||||
EOF
|
||||
```
|
||||
|
||||
The backend's 30-second URL cache will pick up the change within 30 seconds.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
|
||||
@@ -24,18 +24,20 @@ Analyzed GCP billing data and identified $1,440+/month in immediate savings thro
|
||||
|
||||
### ✅ GitHub Actions Runners Auto-Scaling
|
||||
|
||||
**Status:** Deployed and operational (February 10, 2026)
|
||||
**Status:** Fixed and operational (March 17, 2026)
|
||||
|
||||
**Changes Made:**
|
||||
- Reduced from 20 VMs to 3 Spot/Preemptible instances
|
||||
- Reduced from 20 VMs to 3 general + 1 build + 3 GPU runners
|
||||
- Implemented auto-start on CI job queue (via GitHub webhook)
|
||||
- Implemented auto-stop after 1 hour idle (via Cloud Scheduler)
|
||||
- Removed external IPs (using Cloud NAT instead)
|
||||
|
||||
**March 2026 Fix:** The initial auto-scaling implementation had critical bugs that prevented idle shutdown — runners were running 24/7 despite the auto-stop mechanism. See `docs/SELF-HOSTED-RUNNERS.md` for full details. Bugs fixed: metadata writes not awaited, "set now and keep" infinite loop, pending jobs resetting all timestamps, missing IAM permission (`iam.serviceAccountUser`), no STOPPING state handling, sequential (slow) stops.
|
||||
|
||||
**Cost Impact:**
|
||||
- **Before:** 20 VMs × $72/month = $1,440/month
|
||||
- **After:** 3 Spot VMs × $25/month × ~20% utilization = $50-100/month
|
||||
- **Savings:** ~$1,340-1,390/month (93% reduction)
|
||||
- **Before:** 7 VMs running 24/7 = ~$1,648/month
|
||||
- **After (fixed):** ~$50-150/month (estimated, with proper idle shutdown)
|
||||
- **Savings:** ~$1,500/month
|
||||
|
||||
**Implementation:**
|
||||
- PRs: [#376](https://github.com/nomadkaraoke/karaoke-gen/pull/376), [#383](https://github.com/nomadkaraoke/karaoke-gen/pull/383), [#385](https://github.com/nomadkaraoke/karaoke-gen/pull/385)
|
||||
|
||||
@@ -20,6 +20,35 @@ Autocomplete on the artist/title input fields confused users — it wasn't clear
|
||||
### Fuzzy Search: Artist Tiebreaker for Title-Based Fallback (Mar 2026)
|
||||
When fuzzy-matching by title returns multiple artists with the same song name (e.g. "Bruises" by Lewis Capaldi vs Fox Stevenson), use the user's garbled artist input as a tiebreaker — `stringSimilarity(userInput, track.artist_name) * 0.2` as a bonus score. Also: Spotify's `q` parameter searches track names, not artist names, so `searchCatalogTracks(artist, artist, 20)` (artist as both query and filter) returns nothing. Use `searchCatalogTracks(artist, undefined, 20)` to get the artist's tracks via general search.
|
||||
|
||||
### Pipeline Robustness Patterns (Mar 2026)
|
||||
Three patterns from investigating production job failures where errors cascaded far from their root cause:
|
||||
1. **Validate every stage's outputs, not just some** — stage 1 of audio separation had validation for expected stems, stage 2 didn't. The missing validation let a transient Modal API failure propagate through 3 more functions before crashing with a confusing NoneType error.
|
||||
2. **Block impossible downstream work early** — AudioShake returning 0 lyrics segments was treated as "success", letting the user submit an empty review that only failed at CDG generation. Validate at the boundary: if transcription returns 0 segments, fail with a user-friendly error, not 4 steps later.
|
||||
3. **File handles in retry loops** — when wrapping HTTP calls with retry (e.g. tenacity), ensure file handles are re-opened on each attempt. A `with open()` wrapping a retried `requests.post(files=...)` exhausts the file handle on the first attempt; subsequent retries send empty data.
|
||||
|
||||
---
|
||||
|
||||
## Infrastructure
|
||||
|
||||
### GCE Metadata Writes Must Be Awaited (Mar 2026)
|
||||
`compute_v1.InstancesClient.set_metadata()` returns an Operation object. Without calling `.result()`, the write completes asynchronously and fingerprint conflicts from concurrent calls are swallowed silently. This caused the runner manager's `last-activity` metadata to never persist, preventing idle shutdown entirely. Always await metadata operations.
|
||||
|
||||
### "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.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Decisions
|
||||
@@ -39,6 +68,16 @@ Audio separation and lyrics transcription run in parallel. Both can fail indepen
|
||||
### GCE Instance Selection for FFmpeg
|
||||
AMD EPYC (C4D series) significantly outperforms Intel Xeon (C4 series) for CPU-bound FFmpeg encoding with libass. C4D-highcpu-32 is ~5x faster than C4-standard-8. C4D requires `hyperdisk-balanced` disk type.
|
||||
|
||||
### Data Types Must Enforce Their Own Invariants (Mar 2026)
|
||||
When a data type has constraints on its fields (e.g., "word text must not contain newlines"), enforce them in the type's constructor (`__post_init__`), not in callers. This bug was caused by `Word` objects being constructed via two different code paths — one that stripped newlines (preview) and one that didn't (final render). The preview accidentally worked while final renders had corrupted subtitles with silently dropped lyrics. The fix: `Word.__post_init__` strips whitespace so ALL construction paths are safe, plus a defensive strip at the ASS output boundary.
|
||||
|
||||
**Key principles:**
|
||||
- **Single source of truth for data invariants** — the type, not the caller, is responsible for field constraints
|
||||
- **Defensive output boundaries** — even with clean inputs, validate at system boundaries (ASS file writing) as a safety net
|
||||
- **Two code paths doing "the same thing" will diverge** — if preview and render both construct CorrectionResult, they must use the same method, not reimplementations
|
||||
|
||||
**Detection clue:** If `corrected.txt` shows correct lyrics but the video is missing words, check for embedded newlines in Word text corrupting ASS dialogue events.
|
||||
|
||||
### Large Documents: GCS + Firestore Metadata (Mar 2026)
|
||||
When a document's payload can exceed Firestore's 1MB limit (e.g., CorrectionData at 100KB+ per session), store the payload in GCS and keep only metadata in Firestore. Use SHA-256 hash deduplication to avoid re-uploading identical data. For cross-document queries (e.g., searching sessions across jobs), use Firestore collection group queries on the metadata subcollection with Python-side text filtering — Firestore doesn't support LIKE/substring queries natively.
|
||||
|
||||
@@ -940,3 +979,11 @@ For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_d
|
||||
|
||||
**Broader principle:** Non-fatal code paths (try/except that swallows errors) are especially dangerous. The metadata storage was designed to never fail jobs, which is correct — but it also meant the bug was completely silent. When testing non-fatal paths, assert on the *positive outcome* (metadata was stored), not just the absence of exceptions. A test that only checks "didn't crash" provides false confidence when the code is designed to never crash.
|
||||
|
||||
### Static Disposable Email Lists Are Insufficient (Mar 2026)
|
||||
|
||||
**Problem:** A community-curated blocklist of ~5,339 disposable domains (synced from GitHub) missed 40% of disposable signups in a 4-day period. Domains like `lxbeta.com`, `nghienplus.store`, and custom `.io.vn` vanity domains slipped through because they're too niche or new to be in any static list.
|
||||
|
||||
**Solution:** Tiered external API checking as a fallback after the static list: DeBounce (free, catches most) → verifymail.io ($25/mo, catches niche domains the free service misses). Auto-learn persists flagged domains to `manual_domains` so each domain only requires one API call ever. Clean domains are cached for 7 days.
|
||||
|
||||
**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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
+9
-4
@@ -24,9 +24,9 @@
|
||||
| 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, quota-aware YouTube uploads) |
|
||||
| Abuse prevention & YouTube quota | Working (blocklists, IP/fingerprint rate limiting, credits on verification, quota-aware YouTube uploads) |
|
||||
| CI/CD self-hosted runner | Working (GCP) |
|
||||
| E2E happy path test | Working (~20-25 min full pipeline) |
|
||||
| **White-label B2B portals** | Working (Vocal Star, Singa) |
|
||||
@@ -35,6 +35,7 @@
|
||||
| **Song suggestions & fuzzy correction** | Working (catalog lookup on Step 2 + "Did you mean?" typo correction) |
|
||||
| **Community version detection** | Working (via karaokenerds.com) |
|
||||
| **Review session backup/restore** | Working (auto-save + restore UI) |
|
||||
| **Review reminder & auto-expiry** | Working (24h reminder, 48h cancel + refund) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
@@ -46,6 +47,10 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Anti-Abuse: Credits on Verification + Rate Limiting** (2026-03-21): Three-layer defense against free credit abuse. (1) Welcome credits now granted on first magic link verification, not account creation — unverified accounts get 0 credits. (2) Per-IP signup rate limiting: max 2 new accounts per IP per 24 hours, silent reject. (3) Device fingerprinting (FingerprintJS open source): browser fingerprint sent with magic link request, combined with IP for rate limiting. Either signal hitting 2/day triggers block. Returning users are never rate limited. Graceful degradation if fingerprinting fails. Frontend verify page shows "You received N free credits" on first login. See [archive/2026-03-21-anti-abuse-credits.plan.md](archive/2026-03-21-anti-abuse-credits.plan.md).
|
||||
|
||||
- **Review Reminder & Auto-Expiry** (2026-03-19): Jobs stuck in review (`awaiting_review` / `in_review`) now get automatic cleanup. At 24 hours, a gentle reminder email is sent with a review link, help offer, and warning. At 48 hours, the job is auto-cancelled and the user's credit is refunded. Expiry notification email confirms the refund and current balance. Excludes made-for-you and tenant jobs. Powered by hourly Cloud Scheduler cron (`stale-review-hourly`). New endpoint: `POST /api/internal/process-stale-reviews`. Also fixed `make test` hanging on frontend Playwright E2E tests by splitting into `test-frontend` (Jest unit only) and `test-frontend-e2e` (Playwright, run manually). See [archive/2026-03-19-review-reminder-autoexpiry.plan.md](archive/2026-03-19-review-reminder-autoexpiry.plan.md).
|
||||
|
||||
- **Step 2 Song Suggestions & Fuzzy Correction** (2026-03-08): Replaced the Step 1 autocomplete with a simpler approach: plain text inputs on Step 1, then catalog lookup + community version check fire in parallel with the audio search on Step 2. Results appear as a "Song found in our database" panel (exact match) or correction suggestion panel while the user waits. Added fuzzy "Did you mean?" correction — when audio search returns poor results (Tier 3) and catalog has no exact title match, fetches the artist's discography and fuzzy-matches against the user's title using LCS similarity. Shows an amber banner with one-click correction + expandable alternatives list. Handles garbled artist fields via title-based fallback with artist tiebreaker. Visibility step reworked with action buttons at top for one-click select+continue. See [archive/2026-03-08-step2-song-suggestions.plan.md](archive/2026-03-08-step2-song-suggestions.plan.md) and [archive/2026-03-08-fuzzy-did-you-mean.plan.md](archive/2026-03-08-fuzzy-did-you-mean.plan.md).
|
||||
|
||||
- **Review Session Backup/Restore** (2026-03-08): Server-side auto-save of lyrics review sessions replaces fragile localStorage-only mechanism. Sessions auto-save every 60s (if dirty), on preview video generation, and on page unload. Deduplication via SHA-256 hash prevents redundant saves. Correction data stored in GCS (can exceed Firestore's 1MB doc limit); metadata in Firestore subcollection (`jobs/{jobId}/review_sessions/{sessionId}`). Restore UI shows split-pane session browser with edit diff preview. Cross-job session search allows reusing edits across different jobs (with duration mismatch warning). On load, automatically prompts to restore if saved sessions exist. See [archive/2026-03-07-lyrics-review-sessions-plan.md](archive/2026-03-07-lyrics-review-sessions-plan.md).
|
||||
@@ -69,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).
|
||||
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
# Self-Hosted GitHub Actions Runners
|
||||
|
||||
Single source of truth for how Nomad Karaoke CI/CD runners work — architecture, cost model, auto-scaling, and troubleshooting.
|
||||
|
||||
## Why Self-Hosted Runners?
|
||||
|
||||
GitHub-hosted runners work but are slower (2 vCPU, 7GB RAM) and costs scale linearly with CI minutes. Self-hosted runners on GCP give us:
|
||||
|
||||
- **Faster builds** — persistent Docker caches, more CPU/RAM
|
||||
- **GPU access** — T4 GPUs for audio separation model testing
|
||||
- **Scale-to-zero** — runners shut down automatically when idle, so we only pay for active CI time
|
||||
- **Dedicated build runner** — 8 vCPU for Docker image builds
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
|
||||
│ GitHub Webhook │────>│ Cloud Function │────>│ Start Runner │
|
||||
│ (workflow_job) │ │ (runner-manager) │ │ VMs │
|
||||
└─────────────────┘ └──────────────────┘ └─────────────────┘
|
||||
│
|
||||
v
|
||||
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
|
||||
│ Cloud Scheduler│────>│ Cloud Function │────>│ Stop Idle │
|
||||
│ (every 15 min) │ │ (runner-manager) │ │ Runner VMs │
|
||||
└─────────────────┘ └──────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
### Components
|
||||
|
||||
| Component | Spec | Purpose |
|
||||
|-----------|------|---------|
|
||||
| General runners | 3x `github-runner-{1..3}`, `e2-standard-4`, 200GB SSD | Execute CI jobs (lint, test, type check, build) |
|
||||
| Build runner | 1x `github-build-runner`, `e2-standard-8`, 200GB SSD | Docker image builds (needs more CPU/RAM) |
|
||||
| GPU runners | 3x `github-gpu-runner-{1..3}`, `n1-standard-4` + T4 GPU, 200GB SSD | Audio separation model testing |
|
||||
| Cloud Function | `github-runner-manager`, Gen2, Python 3.12, 5min timeout | Start/stop VMs based on webhooks and idle checks |
|
||||
| Cloud Scheduler | `runner-manager-idle-check`, every 15 min | Trigger idle runner checks |
|
||||
| Cloud NAT | `github-runners-nat` + `github-runners-router` | Outbound internet for VMs (no external IPs) |
|
||||
|
||||
All runner VMs are in `us-central1-a`.
|
||||
|
||||
### Service Accounts
|
||||
|
||||
| Account | Purpose | Key Permissions |
|
||||
|---------|---------|-----------------|
|
||||
| `github-runner` | Runner VMs | `artifactregistry.reader`, `secretmanager.secretAccessor` |
|
||||
| `runner-manager` | Cloud Function | `compute.instanceAdmin.v1`, `iam.serviceAccountUser` on `github-runner`, secret access |
|
||||
| `runner-manager-scheduler` | Cloud Scheduler | `cloudfunctions.invoker` on the function |
|
||||
|
||||
### Runner Labels
|
||||
|
||||
| Label Set | VMs | Used By |
|
||||
|-----------|-----|---------|
|
||||
| `[self-hosted, linux, x64, gcp, large-disk]` | general runners | Most CI jobs |
|
||||
| `[self-hosted, linux, x64, gcp, large-disk, docker-build]` | build runner | Docker image builds |
|
||||
| `[self-hosted, linux, x64, gcp, gpu]` | GPU runners | Audio separation tests |
|
||||
|
||||
## How Auto-Scaling Works
|
||||
|
||||
### Starting Runners (Webhook-Driven)
|
||||
|
||||
1. Developer pushes code or opens a PR
|
||||
2. GitHub Actions queues CI jobs with labels `[self-hosted, linux, gcp]`
|
||||
3. GitHub sends a `workflow_job.queued` webhook to the Cloud Function
|
||||
4. The function iterates over all runner VM names (from `RUNNER_NAMES` env var)
|
||||
5. Any TERMINATED VMs are started in parallel via `ThreadPoolExecutor`
|
||||
6. If VMs are in STOPPING state (from an overlapping idle shutdown), the function polls until they become TERMINATED (up to 90s), then starts them
|
||||
7. VMs boot in ~2-3 minutes, run the startup script, register with GitHub, and pick up queued jobs
|
||||
|
||||
### Tracking Activity (Metadata-Based)
|
||||
|
||||
When a job completes, GitHub sends a `workflow_job.completed` webhook. The function updates a `last-activity` metadata key on the **specific runner** that ran the job (identified by `runner_name` from the webhook payload). Only updating the specific runner avoids fingerprint conflicts from concurrent webhook calls.
|
||||
|
||||
### Stopping Idle Runners (Scheduler-Driven)
|
||||
|
||||
Every 15 minutes, Cloud Scheduler triggers the function with `?action=check_idle`:
|
||||
|
||||
1. **Check for pending work:** Query GitHub API for queued/in-progress runs. If anything is pending, keep all runners alive (but do NOT refresh timestamps — that would reset idle tracking).
|
||||
2. **Check each runner's idle time:** For each RUNNING VM, read `last-activity` metadata. If missing, fall back to `creationTimestamp` (the VM's creation date).
|
||||
3. **Stop idle runners:** Any runner idle for 1+ hour is queued for shutdown. All stops execute in parallel to minimize the race window.
|
||||
|
||||
### The Race Condition (and How We Handle It)
|
||||
|
||||
During active development, new work can arrive while the idle check is shutting down runners:
|
||||
|
||||
- **Idle check** fires all stop operations in parallel (~60s window)
|
||||
- **Webhook** arrives with new `workflow_job.queued` event
|
||||
- **start_runners** finds some VMs in `STOPPING` state
|
||||
|
||||
Solution: `start_runners()` detects STOPPING VMs and **polls them every 5 seconds** (up to 90s) until they become TERMINATED, then starts them immediately.
|
||||
|
||||
## Cost Model
|
||||
|
||||
### Monthly Estimates
|
||||
|
||||
| Scenario | Runner Uptime | Monthly Cost |
|
||||
|----------|---------------|--------------|
|
||||
| Active development (8h/day) | ~10-12h/day | ~$100-150 |
|
||||
| Light usage (solo dev) | ~3-5h/day | ~$50-80 |
|
||||
| No activity (all stopped) | 0h | ~$35 (NAT + scheduler only) |
|
||||
|
||||
### Fixed Costs
|
||||
|
||||
| Component | Monthly Cost |
|
||||
|-----------|-------------|
|
||||
| Cloud NAT | ~$30 |
|
||||
| Cloud Scheduler | <$1 |
|
||||
| Cloud Function | <$5 |
|
||||
| **Total fixed** | **~$35** |
|
||||
|
||||
### Variable Costs
|
||||
|
||||
| VM Type | Hourly Cost | 24/7 Monthly |
|
||||
|---------|-------------|--------------|
|
||||
| e2-standard-4 (general) × 3 | $0.402 | $289 |
|
||||
| e2-standard-8 (build) × 1 | $0.268 | $193 |
|
||||
| n1-standard-4 + T4 (GPU) × 3 | $1.62 | $1,166 |
|
||||
| **All 7 VMs** | **$2.29/hr** | **$1,648** |
|
||||
|
||||
This is why idle shutdown is critical — the difference between working and broken auto-scaling is ~$1,600/month.
|
||||
|
||||
## Historical Bugs and Fixes (March 2026)
|
||||
|
||||
The initial runner manager implementation had several bugs that prevented idle shutdown. Runners were running 24/7 for weeks, wasting ~$1,600/month of GCP credits.
|
||||
|
||||
### Bug 1: Metadata Writes Not Awaited
|
||||
|
||||
**Problem:** `client.set_metadata()` returns an Operation object. Without calling `.result()`, the write completes asynchronously and fingerprint conflicts from concurrent calls are swallowed silently. `last-activity` metadata never persisted.
|
||||
|
||||
**Fix:** Added `operation.result(timeout=60)` to all metadata writes.
|
||||
|
||||
### Bug 2: "Set Now and Keep" Infinite Loop
|
||||
|
||||
**Problem:** When `last-activity` was missing, the function set it to "now" and kept the runner. Since the metadata write failed silently (Bug 1), every 15-minute idle check repeated: "No last-activity metadata, setting now" → keeps running → forever.
|
||||
|
||||
**Fix:** Use `creationTimestamp` as fallback instead of "now". VMs without metadata are treated as having been idle since creation.
|
||||
|
||||
### Bug 3: Pending Jobs Reset All Timestamps
|
||||
|
||||
**Problem:** When any queued run existed, the function refreshed `last-activity` on ALL runners. This reset idle tracking so runners could never accumulate enough idle time to be stopped.
|
||||
|
||||
**Fix:** When jobs are pending, keep runners alive but do NOT refresh timestamps.
|
||||
|
||||
### Bug 4: Missing IAM Permission
|
||||
|
||||
**Problem:** The `runner-manager` SA needed `iam.serviceAccountUser` on the `github-runner` SA to set metadata on VMs running as that account. Without it, metadata writes failed with `SERVICE_ACCOUNT_ACCESS_DENIED`.
|
||||
|
||||
**Fix:** Added `roles/iam.serviceAccountUser` binding in Pulumi.
|
||||
|
||||
### Bug 5: No STOPPING State Handling
|
||||
|
||||
**Problem:** VMs in STOPPING state (from an overlapping idle check) were skipped by `start_runners()`, potentially leaving all runners unreachable.
|
||||
|
||||
**Fix:** Poll STOPPING VMs until they become TERMINATED (up to 90s), then start them.
|
||||
|
||||
### Bug 6: Sequential Stops
|
||||
|
||||
**Problem:** Stopping VMs one at a time created a wide race window where new webhooks could overlap.
|
||||
|
||||
**Fix:** Stop all idle VMs in parallel using `ThreadPoolExecutor`.
|
||||
|
||||
### Bug 7: All Runners Updated on Job Completion
|
||||
|
||||
**Problem:** `in_progress` and `completed` webhooks updated metadata on ALL running instances, causing fingerprint conflicts when multiple jobs completed simultaneously.
|
||||
|
||||
**Fix:** Only update the specific runner identified by `runner_name` in the webhook payload. Removed the `in_progress` handler entirely.
|
||||
|
||||
### Bug 8: Flaky "docker: command not found" (Exit Code 127)
|
||||
|
||||
**Problem:** Backend Emulator Integration Tests intermittently failed with `docker: command not found` (exit code 127). Re-running the job always succeeded. Root cause: When a stopped VM restarts, the GHA runner systemd service (installed via `svc.sh install` on a previous boot) auto-starts immediately, accepting CI jobs before the GCE startup script has finished setting up Docker and other dependencies.
|
||||
|
||||
**Fix (two-part):**
|
||||
1. **Startup script:** Stop the runner service at the very top of the script, before any package installations, preventing premature job acceptance.
|
||||
2. **CI workflow:** Added a Docker readiness check step with 60-second retry loop in `backend-emulator-tests`, providing defense-in-depth.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Runners Not Starting
|
||||
|
||||
```bash
|
||||
# 1. Check VM status
|
||||
gcloud compute instances list --filter="name~github-runner" --format="table(name,status)" --project=nomadkaraoke
|
||||
|
||||
# 2. Check GitHub registration
|
||||
gh api /orgs/nomadkaraoke/actions/runners --jq '.runners[] | {name, status, busy}'
|
||||
|
||||
# 3. Check Cloud Function logs
|
||||
gcloud functions logs read github-runner-manager --limit=20 --gen2 --region=us-central1 --project=nomadkaraoke
|
||||
|
||||
# 4. Manual start if needed
|
||||
gcloud compute instances start github-runner-{1..3} github-build-runner --zone=us-central1-a --project=nomadkaraoke
|
||||
```
|
||||
|
||||
### Runners Not Stopping
|
||||
|
||||
```bash
|
||||
# 1. Check last-activity metadata
|
||||
for i in 1 2 3; do
|
||||
echo -n "github-runner-$i: "
|
||||
gcloud compute instances describe "github-runner-$i" --zone=us-central1-a --project=nomadkaraoke \
|
||||
--format="json(metadata.items)" | python3 -c "
|
||||
import sys,json; items=json.load(sys.stdin).get('metadata',{}).get('items',[])
|
||||
[print(i['value']) for i in items if i['key']=='last-activity']" 2>/dev/null || echo "no metadata"
|
||||
done
|
||||
|
||||
# 2. Check for pending jobs
|
||||
gh run list --limit 5 --json status,name --repo nomadkaraoke/karaoke-gen
|
||||
|
||||
# 3. Check function logs for idle check results
|
||||
gcloud functions logs read github-runner-manager --limit=30 --gen2 --region=us-central1 --project=nomadkaraoke | grep -E "(Scheduler|idle|stop|pending)"
|
||||
```
|
||||
|
||||
**Common causes:**
|
||||
- `last-activity` metadata not being set (check for IAM errors in function logs)
|
||||
- Scheduled workflows sending `workflow_job.queued` events
|
||||
- Function timeout exceeded
|
||||
|
||||
### Webhook Not Triggering
|
||||
|
||||
1. Check https://github.com/organizations/nomadkaraoke/settings/hooks
|
||||
2. Look at "Recent Deliveries" for the Cloud Function webhook
|
||||
3. Common issues: secret mismatch, function URL changed after deploy
|
||||
|
||||
## Infrastructure Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `infrastructure/config.py` | `NUM_GITHUB_RUNNERS`, `NUM_GPU_RUNNERS`, `RunnerManagerConfig` |
|
||||
| `infrastructure/compute/github_runners.py` | VM instances, Cloud NAT |
|
||||
| `infrastructure/modules/runner_manager.py` | Cloud Function, Cloud Scheduler, IAM bindings |
|
||||
| `infrastructure/functions/runner_manager/main.py` | Cloud Function code (webhook handler, idle check) |
|
||||
| `infrastructure/compute/startup_scripts/github_runner.sh` | General runner VM bootstrap |
|
||||
| `infrastructure/compute/startup_scripts/github_runner_gpu.sh` | GPU runner VM bootstrap |
|
||||
|
||||
## Secrets
|
||||
|
||||
| Secret | Purpose | Rotation |
|
||||
|--------|---------|----------|
|
||||
| `github-runner-pat` | Runner registration (PAT with `admin:org` > `manage_runners:org`) | Create new PAT, update secret, reset VMs |
|
||||
| `github-webhook-secret` | Webhook signature verification | Generate new hex, update secret + GitHub webhook config |
|
||||
|
||||
## Manual Operations
|
||||
|
||||
### Starting / Stopping All Runners
|
||||
|
||||
```bash
|
||||
# Start all
|
||||
gcloud compute instances start github-runner-{1..3} github-build-runner github-gpu-runner-{1..3} --zone=us-central1-a --project=nomadkaraoke
|
||||
|
||||
# Stop all
|
||||
gcloud compute instances stop github-runner-{1..3} github-build-runner github-gpu-runner-{1..3} --zone=us-central1-a --project=nomadkaraoke
|
||||
```
|
||||
|
||||
### Verifying Auto-Stop Works
|
||||
|
||||
```bash
|
||||
# After last CI job completes, wait 1+ hour, then check:
|
||||
gcloud compute instances list --filter="name~github-runner OR name~github-build OR name~github-gpu" \
|
||||
--format="table(name,status)" --project=nomadkaraoke
|
||||
# Expected: all TERMINATED
|
||||
```
|
||||
@@ -136,3 +136,119 @@ python scripts/backfill_gdrive_uploads.py --all-missing
|
||||
# Specific jobs
|
||||
python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Job failed: "CDG generation was enabled but failed"
|
||||
|
||||
**Cause:** The LRC file has no lyrics content (just metadata like `[re:MidiCo]`). This happens when AudioShake returns 0 segments — typically because the input audio has no vocals (e.g. user uploaded a karaoke track).
|
||||
|
||||
**Fix (v0.135+):** The video orchestrator now skips CDG/TXT gracefully when the LRC has no content. The `complete_review` endpoint also blocks 0-segment submissions with a user-friendly error, and the frontend shows a warning with guidance.
|
||||
|
||||
**For older jobs:** Retry won't help unless the user provides different audio or pastes lyrics manually via "Replace All".
|
||||
|
||||
---
|
||||
|
||||
## Job failed: "Audio separation failed: expected str, bytes or os.PathLike object, not NoneType"
|
||||
|
||||
**Cause (historical):** Modal API intermittently returned fewer stems than expected from stage 2 (backing vocals) separation. Missing stems caused NoneType crashes in downstream processing. This was resolved by migrating to Cloud Run GPU (see `docs/archive/2026-03-22-modal-to-gcp-migration-plan.md`).
|
||||
|
||||
**Fix (v0.135+):** Stage 2 now validates that all expected stems are present. Defensive null checks prevent confusing TypeError messages. Full tracebacks are logged with `exc_info=True`.
|
||||
|
||||
**Recovery:** Retry the job. With the Cloud Run GPU deployment, transient API failures are much less frequent than they were with Modal.
|
||||
|
||||
---
|
||||
|
||||
## Job failed: "Lyrics transcription failed: 502 Server Error: Bad Gateway for url: https://api.audioshake.ai/tasks"
|
||||
|
||||
**Cause:** AudioShake API returned a transient 5xx error.
|
||||
|
||||
**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,207 @@
|
||||
# Review Reminder & Auto-Expiry for Stale Jobs
|
||||
|
||||
**Date:** 2026-03-19
|
||||
**Status:** Design approved, ready for implementation
|
||||
**Branch:** `feat/sess-20260319-1419-review-reminder-autoexpiry`
|
||||
|
||||
## Problem
|
||||
|
||||
Jobs that enter the review stage (`awaiting_review` / `in_review`) sometimes sit indefinitely because users never complete the lyrics review. Examples: jobs c03686b9, c7eb4e2a, 4dcdb8aa — all stuck for 8+ days. These incomplete jobs linger in the system with no mechanism to resolve them.
|
||||
|
||||
## Solution
|
||||
|
||||
Hourly Cloud Scheduler cron that queries for stale review jobs and takes two actions:
|
||||
|
||||
1. **24h reminder email** — gentle nudge with review link, offer of help, and warning about 48h expiry
|
||||
2. **48h auto-expiry** — cancel job, refund credit, send expiry notification email
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Approach: Cloud Scheduler cron** (vs Cloud Tasks or hybrid). Simplest, most robust, easy to monitor. Up to 1h variance on timing is acceptable. Follows the existing YouTube queue processor pattern.
|
||||
- **Clock starts at `blocking_state_entered_at`** — set when job enters `awaiting_review`, regardless of whether user briefly opens the review page (`in_review`).
|
||||
- **Excluded from auto-expiry:**
|
||||
- Made-for-you jobs (`made_for_you == True`) — admin-controlled, customer already paid via Stripe
|
||||
- Tenant/white-label jobs (`tenant_id` is non-empty) — B2B partners with different workflows
|
||||
- **Credits refunded regardless** of whether they were free (welcome) or purchased.
|
||||
- **No retroactive cleanup** — existing stale jobs will be handled manually. (Note: the processor will naturally clean up old stale jobs on first run if they exist — "no retroactive" means no separate migration script.)
|
||||
- **`AWAITING_AUDIO_EDIT` excluded** — intentionally out of scope. Audio edit is a rare state (user uploaded audio needing trimming) with a different workflow. Can be added later if needed.
|
||||
- **Separate flag from idle reminder** — the existing 5-minute idle reminder system already sets `state_data.reminder_sent = True` on every job. The 24h expiry warning uses a distinct flag `state_data.expiry_reminder_sent` to avoid collision.
|
||||
- **`blocking_state_entered_at` resets on re-visit** — if a user opens and closes the review page, `blocking_state_entered_at` may be reset by `_schedule_idle_reminder()`. This is desirable: the user was recently active, so the clock should restart.
|
||||
- **Configurable thresholds** — `REVIEW_REMINDER_HOURS = 24` and `REVIEW_EXPIRY_HOURS = 48` as module-level constants for easy tuning.
|
||||
|
||||
## Architecture
|
||||
|
||||
### New Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `backend/workers/stale_review_processor.py` | Core logic: query stale jobs, send reminders, expire |
|
||||
|
||||
### Modified Files
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `backend/api/routes/internal.py` | Add `POST /internal/process-stale-reviews` endpoint |
|
||||
| `backend/services/email_service.py` | Add `send_review_reminder()` and `send_review_expired()` methods |
|
||||
| `infrastructure/__main__.py` | Add Cloud Scheduler job |
|
||||
|
||||
### No Changes Needed
|
||||
|
||||
- No new Firestore collections or indexes
|
||||
- No new Cloud Tasks queues
|
||||
- No model changes — reuses existing `state_data.blocking_state_entered_at`; adds `expiry_reminder_sent` and `expiry_reminder_sent_at` to `state_data` (no schema change needed, state_data is a flexible dict)
|
||||
- No new env vars or feature flags
|
||||
|
||||
## Detailed Design
|
||||
|
||||
### 1. Stale Review Processor (`backend/workers/stale_review_processor.py`)
|
||||
|
||||
```python
|
||||
async def process_stale_reviews() -> dict:
|
||||
"""
|
||||
Query for stale review jobs and take action.
|
||||
|
||||
Returns:
|
||||
{reminders_sent: int, jobs_expired: int, errors: list[str]}
|
||||
"""
|
||||
# 1. Query Firestore for jobs with status in [AWAITING_REVIEW, IN_REVIEW]
|
||||
# 2. For each job:
|
||||
# a. Skip if made_for_you == True
|
||||
# b. Skip if tenant_id is non-empty
|
||||
# c. Skip if no blocking_state_entered_at in state_data
|
||||
# d. Parse blocking_state_entered_at (naive UTC ISO string) to datetime
|
||||
# e. Calculate hours_since_review = now_utc - blocking_state_entered_at
|
||||
# f. If hours_since_review >= REVIEW_EXPIRY_HOURS (48):
|
||||
# - cancel_job(job_id, reason="Review not completed within 48 hours")
|
||||
# - Send expiry notification email with refund confirmation
|
||||
# g. Elif hours_since_review >= REVIEW_REMINDER_HOURS (24) and not expiry_reminder_sent:
|
||||
# - Send reminder email with review link and help offer
|
||||
# - Update state_data: expiry_reminder_sent=True, expiry_reminder_sent_at=now
|
||||
# Note: blocking_state_entered_at is stored as naive UTC ISO string (datetime.utcnow().isoformat())
|
||||
# 3. Return summary
|
||||
```
|
||||
|
||||
**Key details:**
|
||||
- 48h check comes before 24h check — if a job somehow misses the reminder window (e.g., Cloud Run was down), it still gets expired correctly
|
||||
- Firestore query is by status only; `made_for_you`, `tenant_id`, and time filtering happen in Python (the number of jobs in review at any time is small)
|
||||
- Uses existing `JobManager.cancel_job()` which already handles state transition + credit refund
|
||||
- All operations are wrapped in try/except per job — one failure doesn't block processing other jobs
|
||||
|
||||
### 2. Internal Endpoint (`backend/api/routes/internal.py`)
|
||||
|
||||
```python
|
||||
@router.post("/process-stale-reviews")
|
||||
async def process_stale_reviews_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Process stale review jobs — send reminders and expire old ones.
|
||||
|
||||
Called by Cloud Scheduler (hourly). Can also be triggered manually.
|
||||
"""
|
||||
# Run in background (same pattern as youtube-queue/process)
|
||||
# Return immediately with {status: "started"}
|
||||
```
|
||||
|
||||
### 3. Reminder Email — 24h (`EmailService.send_review_reminder()`)
|
||||
|
||||
**Subject:** `Reminder: Your karaoke video is waiting for review — {artist} - {title}`
|
||||
|
||||
**Content:**
|
||||
- Friendly reminder that their video is ready for review
|
||||
- Direct link to review page: `https://gen.nomadkaraoke.com/app/jobs#{job_id}/review`
|
||||
- Offer of help: "If you're having trouble with the review process, just reply to this email"
|
||||
- Expiry warning: "If the review isn't completed within the next 24 hours, the job will automatically expire and your credit will be refunded"
|
||||
|
||||
**Styling:** Existing yellow alert box pattern from `send_action_reminder()`.
|
||||
|
||||
### 4. Expiry Notification Email — 48h (`EmailService.send_review_expired()`)
|
||||
|
||||
**Subject:** `Your karaoke video has expired — {artist} - {title}`
|
||||
|
||||
**Content:**
|
||||
- Job was automatically cancelled because review wasn't completed within 48 hours
|
||||
- Credit has been refunded — show current balance
|
||||
- They can create a new job anytime
|
||||
- Offer of help if they had trouble
|
||||
|
||||
**Styling:** Informational tone (not alarming — they got their credit back).
|
||||
|
||||
### 5. Cloud Scheduler (`infrastructure/__main__.py`)
|
||||
|
||||
```python
|
||||
stale_review_scheduler = cloudscheduler.Job(
|
||||
"stale-review-scheduler",
|
||||
name="stale-review-hourly",
|
||||
description="Send review reminders and expire stale review jobs",
|
||||
region=REGION,
|
||||
schedule="0 * * * *", # Every hour on the hour
|
||||
time_zone="America/Los_Angeles",
|
||||
http_target=cloudscheduler.JobHttpTargetArgs(
|
||||
uri="https://api.nomadkaraoke.com/api/internal/process-stale-reviews",
|
||||
http_method="POST",
|
||||
oidc_token=cloudscheduler.JobHttpTargetOidcTokenArgs(
|
||||
service_account_email=backend_service_account.email,
|
||||
),
|
||||
),
|
||||
retry_config=cloudscheduler.JobRetryConfigArgs(
|
||||
retry_count=1,
|
||||
min_backoff_duration="60s",
|
||||
max_backoff_duration="300s",
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (`backend/tests/test_stale_review_processor.py`)
|
||||
- Job >48h with no reminder → expires + refunds + sends expiry email
|
||||
- Job >48h with reminder already sent → expires (doesn't send duplicate reminder)
|
||||
- Job 24-48h with no reminder → sends reminder, sets expiry_reminder_sent=True
|
||||
- Job 24-48h with expiry_reminder already sent → skips (no duplicate)
|
||||
- Job 24-48h with idle reminder_sent=True but expiry_reminder_sent=False → still sends 24h reminder (flags are independent)
|
||||
- Job <24h → no action
|
||||
- Made-for-you job >48h → skipped
|
||||
- Tenant job >48h → skipped
|
||||
- Job with no blocking_state_entered_at → skipped
|
||||
- Job with no user_email → skipped (no email sent, but still expires)
|
||||
- Error in one job doesn't block others
|
||||
- Return value includes correct counts
|
||||
|
||||
### Unit Tests (`backend/tests/test_email_service.py`)
|
||||
- `send_review_reminder()` renders correct subject, content, review link
|
||||
- `send_review_expired()` renders correct subject, content, balance info
|
||||
|
||||
### Integration Test (endpoint)
|
||||
- `POST /internal/process-stale-reviews` requires admin auth
|
||||
- Returns started status, processes in background
|
||||
|
||||
## Sequence Diagram
|
||||
|
||||
```
|
||||
Cloud Scheduler (hourly)
|
||||
│
|
||||
▼
|
||||
POST /api/internal/process-stale-reviews
|
||||
│
|
||||
▼
|
||||
process_stale_reviews()
|
||||
│
|
||||
├─ Query: status in [awaiting_review, in_review]
|
||||
│
|
||||
├─ For each job:
|
||||
│ ├─ Skip if made_for_you or tenant
|
||||
│ ├─ Calculate age from blocking_state_entered_at
|
||||
│ │
|
||||
│ ├─ Age >= 48h:
|
||||
│ │ ├─ cancel_job() → sets CANCELLED + refunds credit
|
||||
│ │ └─ send_review_expired() email
|
||||
│ │
|
||||
│ └─ Age >= 24h (reminder not sent):
|
||||
│ ├─ send_review_reminder() email
|
||||
│ └─ Update state_data.expiry_reminder_sent = True
|
||||
│
|
||||
└─ Return {reminders_sent, jobs_expired, errors}
|
||||
```
|
||||
@@ -0,0 +1,207 @@
|
||||
# Plan: External Email Verification APIs (DeBounce + verifymail.io)
|
||||
|
||||
**Created:** 2026-03-20
|
||||
**Branch:** feat/sess-20260320-1114-investigate-user-abuse
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Replace the static disposable domain blocklist (community GitHub list of ~5,339 domains) with real-time API checks using two external services. Our investigation found that the static list misses many disposable domains — 4 out of 10 disposable signups in a 4-day period got through.
|
||||
|
||||
**Strategy: Tiered checking to minimize cost and latency.**
|
||||
|
||||
```
|
||||
Email submitted
|
||||
→ Step 0: Well-known provider? (gmail, yahoo, etc.) → skip all checks
|
||||
→ Step 1: Static blocklist check (existing, instant, free)
|
||||
→ Step 2: Verified clean in last 7 days? → skip API calls
|
||||
→ Step 3: DeBounce API check (free, <50ms)
|
||||
→ Step 4: verifymail.io API check (paid, only if DeBounce says clean)
|
||||
→ Any says disposable → auto-learn domain + reject with 422
|
||||
→ All say clean → persist clean result for 7 days
|
||||
```
|
||||
|
||||
This means verifymail.io is only called for emails that pass both the static list AND DeBounce — minimizing paid API usage to only the tricky edge cases where it adds value.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Add DeBounce API client (free, no auth, GET `https://disposable.debounce.io/?email={email}`)
|
||||
- [ ] Add verifymail.io API client (paid, GET `https://verifymail.io/api/{email}?key={key}`)
|
||||
- [ ] Store verifymail.io API key in GCP Secret Manager (secret name: `verifymail-api-key`)
|
||||
- [ ] Wire both checks into `is_disposable_domain()` as a fallback after the static list check
|
||||
- [ ] Handle API failures gracefully — if external APIs are down, fall back to static list only (don't block real users)
|
||||
- [ ] Add timeout protection (2s per API call max)
|
||||
- [ ] Auto-learn: when an external API flags a domain, add it to `manual_domains` so future checks don't need the API call
|
||||
- [ ] Log API results for monitoring
|
||||
- [ ] Unit tests with mocked HTTP calls
|
||||
- [ ] Integration test verifying the full magic link rejection flow
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Where to add the logic
|
||||
|
||||
The change is concentrated in `EmailValidationService.is_disposable_domain()` (line 171 of `email_validation_service.py`). Currently it only checks the static set. We'll add external API calls as a fallback.
|
||||
|
||||
### Tiered check flow in `is_disposable_domain()`
|
||||
|
||||
```python
|
||||
def is_disposable_domain(self, email: str) -> bool:
|
||||
domain = email.lower().split("@")[-1]
|
||||
|
||||
# Tier 0: Well-known providers (gmail, yahoo, etc.) — skip everything
|
||||
if domain in WELL_KNOWN_PROVIDERS:
|
||||
return False
|
||||
|
||||
# Tier 1: Static blocklist (instant, always available)
|
||||
if domain in config["disposable_domains"]:
|
||||
return True
|
||||
|
||||
# Tier 2: Recently verified clean? (skip API calls)
|
||||
if self._is_domain_verified_clean(domain):
|
||||
return False
|
||||
|
||||
# Tier 3: DeBounce API (free, fast)
|
||||
debounce_result = self._check_debounce(email)
|
||||
if debounce_result is True:
|
||||
self._auto_learn_domain(domain) # Persist to manual_domains
|
||||
return True
|
||||
|
||||
# Tier 4: verifymail.io (paid, only if DeBounce says clean)
|
||||
if debounce_result is False: # Only escalate if DeBounce gave a definitive "no"
|
||||
verifymail_result = self._check_verifymail(email)
|
||||
if verifymail_result is True:
|
||||
self._auto_learn_domain(domain)
|
||||
return True
|
||||
|
||||
# Both APIs say clean (or errored) — persist clean result
|
||||
if debounce_result is False:
|
||||
self._mark_domain_clean(domain)
|
||||
|
||||
return False
|
||||
```
|
||||
|
||||
### Auto-learn mechanism
|
||||
|
||||
When an external API flags a domain as disposable, we add it to `manual_domains` in Firestore. This means:
|
||||
- The domain is blocked immediately for all future requests via the static check
|
||||
- No further API calls needed for that domain
|
||||
- The allowlist still overrides if we get false positives
|
||||
|
||||
### Error handling
|
||||
|
||||
- API timeout (2s) or network error → treat as "unknown" (not disposable), log warning
|
||||
- DeBounce error → skip to verifymail.io
|
||||
- Both APIs error → fall back to static list only
|
||||
- Never block a real user because an external API is down
|
||||
|
||||
### Secret management
|
||||
|
||||
Follow existing pattern: `settings.get_secret("verifymail-api-key")`. For local dev, set `VERIFYMAIL_API_KEY` env var. For production, create the secret in GCP Secret Manager.
|
||||
|
||||
### Caching strategy
|
||||
|
||||
Two layers of caching to minimize API calls:
|
||||
|
||||
**Disposable domains (persistent):** Auto-learn adds flagged domains to `manual_domains` in Firestore. Once learned, that domain is blocked via the static list forever — no API call needed again. This handles the "block" case.
|
||||
|
||||
**Clean domains (persistent):** Store verified-clean domains in a `verified_clean_domains` dict in the blocklist Firestore doc, keyed by domain with a `checked_at` timestamp. Domains verified clean within the last 7 days skip external API calls. This gets loaded into the existing 5-minute blocklist cache, so adds zero extra Firestore reads. Periodic cleanup removes entries older than 7 days (during the daily sync job).
|
||||
|
||||
**In-memory (both):** The existing 5-minute `_blocklist_cache` TTL already covers this — both `manual_domains` and `verified_clean_domains` are loaded with the blocklist config.
|
||||
|
||||
**Net effect:** For a given unknown domain, external APIs are called at most once per 7 days. Well-known providers (gmail, yahoo, etc.) skip APIs entirely via the short-circuit set.
|
||||
|
||||
### Performance considerations
|
||||
|
||||
- Static list check is instant — most legitimate emails (gmail.com, yahoo.com, etc.) short-circuit here without any API call
|
||||
- DeBounce adds <50ms for unknown domains
|
||||
- verifymail.io adds ~200-500ms but is only called for domains that pass both static + DeBounce
|
||||
- In practice, the vast majority of signups will never hit an external API
|
||||
- `httpx` with connection pooling for efficient HTTP (already a project dependency)
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Create the verifymail.io secret in GCP Secret Manager
|
||||
|
||||
```bash
|
||||
echo -n "YOUR_VERIFYMAIL_API_KEY" | \
|
||||
gcloud secrets create verifymail-api-key \
|
||||
--project=nomadkaraoke \
|
||||
--data-file=-
|
||||
```
|
||||
|
||||
No Pulumi change needed — this is a runtime secret, not infrastructure. The Cloud Run service account already has Secret Manager access.
|
||||
|
||||
### Step 2: Add external API checking to `EmailValidationService`
|
||||
|
||||
**File:** `backend/services/email_validation_service.py`
|
||||
|
||||
Add three private methods and modify `is_disposable_domain()`:
|
||||
|
||||
- `_check_debounce(email: str) -> Optional[bool]` — calls DeBounce API, returns True/False/None (None = error)
|
||||
- `_check_verifymail(email: str) -> Optional[bool]` — calls verifymail.io API, returns True/False/None
|
||||
- `_auto_learn_domain(domain: str)` — adds domain to `manual_domains` in Firestore (fire-and-forget, non-blocking)
|
||||
- `_mark_domain_clean(domain: str)` — adds domain to `verified_clean_domains` in Firestore with `checked_at` timestamp
|
||||
- `_is_domain_verified_clean(domain: str) -> bool` — checks `verified_clean_domains` cache, returns True if verified within 7 days
|
||||
- Modify `is_disposable_domain()` to check verified-clean cache before API calls, and call external APIs as fallback
|
||||
- Modify `get_blocklist_config()` to load `verified_clean_domains` into the cache
|
||||
|
||||
Use `httpx` (already in dependencies) for HTTP calls with:
|
||||
- 2-second timeout per request
|
||||
- Connection pooling via module-level client
|
||||
- Structured logging of API calls and results
|
||||
|
||||
### Step 3: Add well-known provider skip list
|
||||
|
||||
Domains like `gmail.com`, `yahoo.com`, `hotmail.com`, `outlook.com`, etc. should never hit external APIs — they're obviously not disposable. Add a `WELL_KNOWN_PROVIDERS` set and short-circuit before API calls.
|
||||
|
||||
### Step 4: Unit tests
|
||||
|
||||
**File:** `backend/tests/test_email_validation_service.py`
|
||||
|
||||
Add tests for:
|
||||
- DeBounce returns disposable=true → domain auto-learned, returns True
|
||||
- DeBounce returns disposable=false, verifymail returns disposable=true → domain auto-learned, returns True
|
||||
- Both APIs return clean → returns False
|
||||
- DeBounce timeout → falls through to verifymail
|
||||
- Both APIs timeout → falls back to static list (returns False)
|
||||
- Well-known providers skip API calls entirely
|
||||
- Auto-learn adds domain to manual_domains in Firestore
|
||||
- verifymail.io API key missing → skip verifymail, only use DeBounce
|
||||
|
||||
### Step 5: Integration test for magic link rejection
|
||||
|
||||
**File:** `backend/tests/test_email_validation_integration.py`
|
||||
|
||||
Add test: email from domain not in static list but flagged by external API → magic link returns 422 with `disposable_email_not_allowed`.
|
||||
|
||||
### Step 6: Version bump
|
||||
|
||||
Bump `tool.poetry.version` in `pyproject.toml`.
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/services/email_validation_service.py` | Modify | Add `_check_debounce()`, `_check_verifymail()`, `_auto_learn_domain()`, modify `is_disposable_domain()` |
|
||||
| `backend/tests/test_email_validation_service.py` | Modify | Add unit tests for external API checks |
|
||||
| `backend/tests/test_email_validation_integration.py` | Modify | Add integration test for API-based rejection |
|
||||
| `pyproject.toml` | Modify | Version bump |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Mock `httpx` responses for both APIs. Test all branches: success, timeout, error, auto-learn.
|
||||
- **Integration tests**: Mock HTTP at the transport level, verify full magic link → 422 flow.
|
||||
- **Manual verification**: After deploy, attempt signup with a known-disposable domain not in the static list (e.g., `test@lxbeta.com`) and confirm rejection.
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [x] ~~Which service to use?~~ → Both, tiered (DeBounce free primary, verifymail.io paid secondary)
|
||||
- [x] ~~Cache API results?~~ → Yes. Blocked domains auto-learn to `manual_domains` (permanent). Clean domains persist to `verified_clean_domains` with 7-day TTL. Both loaded via existing 5-min blocklist cache.
|
||||
- [ ] Should we add monitoring/alerting for external API failures? **Recommendation: Log warnings for now, add alerting later if needed.**
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
The external API checks are additive — they only add domains to the block list, never remove them. To rollback:
|
||||
1. Revert the code change (external APIs stop being called)
|
||||
2. Static blocklist continues to work as before
|
||||
3. Any auto-learned domains remain in `manual_domains` (can be removed via admin API if false positives)
|
||||
@@ -0,0 +1,388 @@
|
||||
# Plan: Anti-Abuse Improvements for Free Credits System
|
||||
|
||||
**Created:** 2026-03-21
|
||||
**Branch:** feat/sess-20260321-0043-anti-abuse-credits
|
||||
**Status:** Implemented
|
||||
|
||||
## Overview
|
||||
|
||||
Three improvements to prevent abuse of the 2-free-credits-per-account system:
|
||||
|
||||
1. **Per-IP signup rate limiting** — max 2 new accounts per IP per 24 hours
|
||||
2. **Device fingerprinting** — detect same-browser multi-account abuse
|
||||
3. **Credits on verification, not creation** — move welcome credits from account creation to first magic link verification
|
||||
|
||||
These are ordered by implementation complexity (simplest first) and can be shipped independently.
|
||||
|
||||
## Background
|
||||
|
||||
Investigation of 60 recent signups (2026-03-20) found disposable email abuse and potential multi-account patterns. The disposable email detection (DeBounce + verifymail.io, shipped in v0.144.0) blocks throwaway email services, but doesn't prevent someone from creating multiple accounts with real emails from the same device/IP.
|
||||
|
||||
## Part 1: Per-IP Signup Rate Limiting
|
||||
|
||||
### Problem
|
||||
|
||||
No limit on how many accounts can be created from a single IP address. An abuser can create unlimited accounts from the same machine.
|
||||
|
||||
### Approach
|
||||
|
||||
Track IP addresses on magic link requests (signup trigger). Before creating a magic link, check how many **distinct new accounts** were created from that IP in the last 24 hours. If >= 2, silently reject (return 200 to prevent enumeration, same pattern as blocked email/IP).
|
||||
|
||||
**Why track at magic link request, not user creation?**
|
||||
- Magic link request is the user-facing action (they enter email, click "send")
|
||||
- User creation happens inside `get_or_create_user()` which is called during verification
|
||||
- Rate limiting at the entry point prevents even sending the email
|
||||
|
||||
### Data model
|
||||
|
||||
Use the existing `magic_links` collection — it already stores `ip_address` and `email`. Query: count distinct emails with magic links created from this IP in the last 24 hours where the email doesn't already exist as a user.
|
||||
|
||||
No new collection needed. Just a query at magic link request time.
|
||||
|
||||
### Implementation
|
||||
|
||||
**File: `backend/api/routes/users.py` — `send_magic_link()` endpoint**
|
||||
|
||||
After the disposable domain check and blocked email/IP checks (lines 157-175), add:
|
||||
|
||||
```python
|
||||
# Per-IP signup rate limit (only for new users)
|
||||
existing_user = user_service.get_user(email)
|
||||
if existing_user is None:
|
||||
# This is a new signup — check IP rate limit
|
||||
recent_signups = user_service.count_recent_signups_from_ip(
|
||||
ip_address, hours=24
|
||||
)
|
||||
if recent_signups >= 2:
|
||||
logger.warning(
|
||||
f"IP signup rate limit hit: {ip_address} "
|
||||
f"({recent_signups} signups in 24h)"
|
||||
)
|
||||
# Silent reject (anti-enumeration)
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a login link."
|
||||
)
|
||||
```
|
||||
|
||||
**File: `backend/services/user_service.py`**
|
||||
|
||||
Add method:
|
||||
|
||||
```python
|
||||
def count_recent_signups_from_ip(self, ip_address: str, hours: int = 24) -> int:
|
||||
"""Count distinct new-user magic link requests from this IP in the last N hours."""
|
||||
cutoff = datetime.utcnow() - timedelta(hours=hours)
|
||||
# Query magic_links where ip_address matches and created_at > cutoff
|
||||
links = (
|
||||
self.db.collection("magic_links")
|
||||
.where("ip_address", "==", ip_address)
|
||||
.where("created_at", ">=", cutoff.isoformat())
|
||||
.stream()
|
||||
)
|
||||
# Count distinct emails that are NOT existing users
|
||||
emails = set()
|
||||
for link in links:
|
||||
data = link.to_dict()
|
||||
email = data.get("email", "")
|
||||
# Only count if this email resulted in a new user creation
|
||||
user_doc = self.db.collection("gen_users").document(email).get()
|
||||
if user_doc.exists:
|
||||
user_data = user_doc.to_dict()
|
||||
created_at = user_data.get("created_at", "")
|
||||
if created_at >= cutoff.isoformat():
|
||||
emails.add(email)
|
||||
return len(emails)
|
||||
```
|
||||
|
||||
**Optimization note:** This approach queries Firestore for each magic link email. For production, a simpler approach would be to add a Firestore composite index on `magic_links(ip_address, created_at)` and count distinct emails in the result set. At our volume (~60 signups/day), the extra reads are negligible.
|
||||
|
||||
**Alternative simpler approach:** Instead of querying magic_links, track signups directly by adding `signup_ip` to the `gen_users` document at creation time. Then query `gen_users` where `signup_ip == ip AND created_at >= cutoff`. This is cleaner and avoids cross-collection queries.
|
||||
|
||||
**Recommended: Use the simpler approach.** Add `signup_ip` field to User model, set it in `get_or_create_user()`, and query it for rate limiting.
|
||||
|
||||
### Edge cases
|
||||
|
||||
- **Shared IPs (offices, universities, VPNs):** 2 per day is generous enough for legitimate use. If a real user is blocked, they can try again tomorrow or contact support.
|
||||
- **IPv6 addresses:** Rate limit on the full address. Don't try to normalize /64 subnets — too complex and most residential IPv6 users get a stable address.
|
||||
- **Existing users logging in:** Rate limit only applies to new signups, not returning users.
|
||||
- **`169.254.169.126` (load balancer IP):** This is the LB IP seen on sessions/magic_links — need to ensure we're using the real client IP from X-Forwarded-For. Check how `ip_address` is set in the magic link endpoint. (From investigation: it uses `http_request.client.host` which should be the real IP behind Cloud Run's proxy, but verify.)
|
||||
|
||||
### Tests
|
||||
|
||||
- Unit test: `count_recent_signups_from_ip` returns correct count
|
||||
- Unit test: rate limit triggered → silent 200 response
|
||||
- Unit test: existing user login not rate limited
|
||||
- Unit test: 1 signup from IP → allowed, 2nd → allowed, 3rd → blocked
|
||||
- Integration test: magic link endpoint returns 200 (silent reject) when IP limit hit
|
||||
|
||||
---
|
||||
|
||||
## Part 2: Device Fingerprinting
|
||||
|
||||
### Problem
|
||||
|
||||
A determined abuser can use multiple IPs (VPN, mobile data, etc.) to bypass IP rate limiting. Device fingerprinting catches same-browser multi-account abuse regardless of IP.
|
||||
|
||||
### Approach
|
||||
|
||||
Use [FingerprintJS](https://github.com/nicedayfor/fingerprintjs) (open source, free) to generate a browser fingerprint on the frontend. Send it with the magic link request. Store it on the user document. Check it during signup rate limiting alongside IP.
|
||||
|
||||
**Why FingerprintJS open source (not Pro)?**
|
||||
- Free, no API key needed
|
||||
- Runs entirely client-side
|
||||
- ~60-70% accuracy for identifying unique browsers (good enough as a signal, not sole blocker)
|
||||
- Pro version ($0/mo for 20k identifications) is more accurate but adds external dependency
|
||||
|
||||
### Data flow
|
||||
|
||||
```
|
||||
Frontend: Generate fingerprint → send with magic link request
|
||||
Backend: Store fingerprint on magic link → check at signup
|
||||
Store fingerprint on user document → cross-reference
|
||||
```
|
||||
|
||||
### Frontend implementation
|
||||
|
||||
**File: `frontend/lib/fingerprint.ts` (new)**
|
||||
|
||||
```typescript
|
||||
import FingerprintJS from "@nicedayfor/fingerprintjs";
|
||||
|
||||
let cachedFingerprint: string | null = null;
|
||||
|
||||
export async function getDeviceFingerprint(): Promise<string> {
|
||||
if (cachedFingerprint) return cachedFingerprint;
|
||||
const fp = await FingerprintJS.load();
|
||||
const result = await fp.get();
|
||||
cachedFingerprint = result.visitorId;
|
||||
return cachedFingerprint;
|
||||
}
|
||||
```
|
||||
|
||||
**File: `frontend/lib/auth.ts` — modify `requestMagicLink()`**
|
||||
|
||||
Add fingerprint to the magic link request body:
|
||||
|
||||
```typescript
|
||||
const fingerprint = await getDeviceFingerprint();
|
||||
const response = await fetch("/api/users/auth/magic-link", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email, device_fingerprint: fingerprint }),
|
||||
});
|
||||
```
|
||||
|
||||
### Backend implementation
|
||||
|
||||
**File: `backend/api/routes/users.py`**
|
||||
|
||||
Add `device_fingerprint: Optional[str] = None` to `SendMagicLinkRequest` model.
|
||||
|
||||
Pass it through to `create_magic_link()` and store on the magic link document.
|
||||
|
||||
**File: `backend/models/user.py`**
|
||||
|
||||
Add `device_fingerprint: Optional[str] = None` to both `MagicLinkToken` and `User` models.
|
||||
|
||||
**File: `backend/services/user_service.py`**
|
||||
|
||||
- In `create_magic_link()`: store `device_fingerprint` on the magic link doc
|
||||
- In `get_or_create_user()`: store `device_fingerprint` on the user doc (from the magic link that triggered creation)
|
||||
- Add `count_recent_signups_from_fingerprint()`: similar to IP rate limit but by fingerprint
|
||||
|
||||
### Rate limiting with fingerprint
|
||||
|
||||
Combine IP and fingerprint signals:
|
||||
|
||||
```python
|
||||
# In send_magic_link endpoint, for new users:
|
||||
ip_signups = user_service.count_recent_signups_from_ip(ip_address, hours=24)
|
||||
fp_signups = user_service.count_recent_signups_from_fingerprint(
|
||||
device_fingerprint, hours=24
|
||||
) if device_fingerprint else 0
|
||||
|
||||
if ip_signups >= 2 or fp_signups >= 2:
|
||||
# Silent reject
|
||||
...
|
||||
```
|
||||
|
||||
### Edge cases
|
||||
|
||||
- **No fingerprint sent (old clients, API users, bots):** Fall back to IP-only rate limiting. Don't require fingerprint — it's an additional signal, not a hard requirement.
|
||||
- **Fingerprint collision:** FingerprintJS open source has ~60-70% uniqueness. Two different people could get the same fingerprint. The 2-per-day limit is generous enough to handle occasional collisions.
|
||||
- **Incognito/private browsing:** FingerprintJS still works reasonably well in incognito (canvas, WebGL, fonts are still consistent). Accuracy drops slightly.
|
||||
- **Browser extensions that block fingerprinting:** Fall back to IP-only.
|
||||
|
||||
### Tests
|
||||
|
||||
- Frontend: Unit test for fingerprint generation and caching
|
||||
- Backend: Unit test for fingerprint storage on magic link and user
|
||||
- Backend: Unit test for fingerprint-based rate limiting
|
||||
- Backend: Integration test for combined IP + fingerprint rate limiting
|
||||
- Backend: Test that missing fingerprint gracefully degrades to IP-only
|
||||
|
||||
### Dependencies
|
||||
|
||||
```bash
|
||||
# Frontend
|
||||
npm install @nicedayfor/fingerprintjs
|
||||
```
|
||||
|
||||
No backend dependencies needed (fingerprint is just a string).
|
||||
|
||||
---
|
||||
|
||||
## Part 3: Credits on Verification, Not Creation
|
||||
|
||||
### Problem
|
||||
|
||||
Currently, 2 welcome credits are granted in `get_or_create_user()` — at account creation time, before the user has verified their email. This means:
|
||||
- Unverified accounts get credits (wasted if user never verifies)
|
||||
- The user creation can be triggered by requesting a magic link (no verification needed)
|
||||
- An attacker could create accounts and use credits without ever clicking a magic link
|
||||
|
||||
### Approach
|
||||
|
||||
Move welcome credit granting from `get_or_create_user()` to the magic link verification endpoint (`verify`). Credits are only granted after the user successfully clicks the magic link (proving email ownership).
|
||||
|
||||
### Implementation
|
||||
|
||||
**File: `backend/services/user_service.py` — `get_or_create_user()`**
|
||||
|
||||
Remove welcome credit granting:
|
||||
|
||||
```python
|
||||
# BEFORE (lines 125-142):
|
||||
user = User(email=email, credits=NEW_USER_FREE_CREDITS, ...)
|
||||
credit_transaction = CreditTransaction(
|
||||
amount=NEW_USER_FREE_CREDITS, reason="welcome_credit", ...
|
||||
)
|
||||
|
||||
# AFTER:
|
||||
user = User(email=email, credits=0, ...)
|
||||
# No credit transaction at creation
|
||||
```
|
||||
|
||||
**File: `backend/services/user_service.py` — new method**
|
||||
|
||||
```python
|
||||
def grant_welcome_credits_if_eligible(self, email: str) -> bool:
|
||||
"""Grant welcome credits on first verification, if not already granted."""
|
||||
user = self.get_user(email)
|
||||
if not user:
|
||||
return False
|
||||
|
||||
# Check if welcome credits were already granted
|
||||
for txn in user.credit_transactions:
|
||||
if txn.reason == "welcome_credit":
|
||||
return False # Already received
|
||||
|
||||
# Grant credits
|
||||
self.add_credits(
|
||||
email=email,
|
||||
amount=NEW_USER_FREE_CREDITS,
|
||||
reason="welcome_credit",
|
||||
)
|
||||
return True
|
||||
```
|
||||
|
||||
**File: `backend/api/routes/users.py` — `verify` endpoint**
|
||||
|
||||
After successful verification (line ~283), add:
|
||||
|
||||
```python
|
||||
# Grant welcome credits on first verification
|
||||
credits_granted = user_service.grant_welcome_credits_if_eligible(user.email)
|
||||
if credits_granted:
|
||||
logger.info(f"Granted {NEW_USER_FREE_CREDITS} welcome credits to {_mask_email(user.email)}")
|
||||
```
|
||||
|
||||
### Migration consideration
|
||||
|
||||
Existing users who signed up before this change already have their welcome credits. The `grant_welcome_credits_if_eligible()` method checks for existing `welcome_credit` transactions, so it won't double-grant.
|
||||
|
||||
**Edge case: Users who signed up but haven't verified yet.** These users have credits but haven't verified. After the change, they'll still have their credits (we don't revoke). When they eventually verify, the method sees the existing `welcome_credit` transaction and skips. No action needed.
|
||||
|
||||
### Frontend impact
|
||||
|
||||
The verify response already includes the user's credit balance. The frontend should show a "You received 2 free credits!" message on first verification. Check if this already exists in the welcome flow.
|
||||
|
||||
**File: `frontend/app/auth/verify/page.tsx`**
|
||||
|
||||
The verify page already handles first-login detection (line ~57 checks for `is_first_login` in the response). We may need to add `credits_granted` to the verify response so the frontend can show a celebratory message.
|
||||
|
||||
### Tests
|
||||
|
||||
- Unit test: `get_or_create_user()` creates user with 0 credits
|
||||
- Unit test: `grant_welcome_credits_if_eligible()` grants credits on first call
|
||||
- Unit test: `grant_welcome_credits_if_eligible()` skips if already granted
|
||||
- Integration test: full flow — create user (0 credits) → verify magic link (2 credits)
|
||||
- Integration test: verify twice → credits only granted once
|
||||
|
||||
---
|
||||
|
||||
## Implementation Steps (All 3 Parts)
|
||||
|
||||
### Phase 1: Credits on verification (Part 3) — lowest risk, highest impact
|
||||
1. [ ] Move credit granting from `get_or_create_user()` to new `grant_welcome_credits_if_eligible()`
|
||||
2. [ ] Call `grant_welcome_credits_if_eligible()` in verify endpoint
|
||||
3. [ ] Add `credits_granted` to verify response
|
||||
4. [ ] Update frontend verify page to show credit grant message
|
||||
5. [ ] Unit + integration tests
|
||||
6. [ ] Version bump, ship
|
||||
|
||||
### Phase 2: Per-IP signup rate limiting (Part 1) — simple, effective
|
||||
7. [ ] Add `signup_ip` field to User model
|
||||
8. [ ] Set `signup_ip` in `get_or_create_user()` (passed from magic link endpoint)
|
||||
9. [ ] Add `count_recent_signups_from_ip()` method
|
||||
10. [ ] Add rate limit check in `send_magic_link()` endpoint (before sending email)
|
||||
11. [ ] Unit + integration tests
|
||||
12. [ ] Version bump, ship
|
||||
|
||||
### Phase 3: Device fingerprinting (Part 2) — most complex
|
||||
13. [ ] Install FingerprintJS in frontend
|
||||
14. [ ] Create `frontend/lib/fingerprint.ts`
|
||||
15. [ ] Send fingerprint with magic link request
|
||||
16. [ ] Add `device_fingerprint` to MagicLinkToken and User models
|
||||
17. [ ] Store fingerprint in `create_magic_link()` and `get_or_create_user()`
|
||||
18. [ ] Add `count_recent_signups_from_fingerprint()` method
|
||||
19. [ ] Combine IP + fingerprint rate limiting in `send_magic_link()`
|
||||
20. [ ] Unit + integration tests (frontend + backend)
|
||||
21. [ ] Version bump, ship
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Part | Description |
|
||||
|------|--------|------|-------------|
|
||||
| `backend/services/user_service.py` | Modify | 1,2,3 | Rate limit methods, credit granting changes, fingerprint storage |
|
||||
| `backend/api/routes/users.py` | Modify | 1,2,3 | Rate limit check, credit grant on verify, fingerprint passthrough |
|
||||
| `backend/models/user.py` | Modify | 1,2 | Add `signup_ip`, `device_fingerprint` fields |
|
||||
| `backend/tests/test_user_service.py` | Modify | 1,2,3 | Tests for all new methods |
|
||||
| `backend/tests/test_email_validation_integration.py` | Modify | 1 | Rate limit integration test |
|
||||
| `frontend/lib/fingerprint.ts` | Create | 2 | FingerprintJS wrapper |
|
||||
| `frontend/lib/auth.ts` | Modify | 2 | Send fingerprint with magic link request |
|
||||
| `frontend/app/auth/verify/page.tsx` | Modify | 3 | Show credit grant message |
|
||||
| `pyproject.toml` | Modify | 1,2,3 | Version bumps |
|
||||
| `frontend/package.json` | Modify | 2 | Add FingerprintJS dependency |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Mock Firestore for rate limit counting, credit granting, fingerprint storage
|
||||
- **Integration tests**: TestClient for magic link → silent reject flow, verify → credit grant flow
|
||||
- **E2E test**: After deploy, attempt signup with disposable domain (blocked), then attempt 3 signups from same IP (3rd blocked)
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [x] Should we show a user-facing message when IP rate limited, or always silently reject? **Recommendation: silent reject (anti-enumeration), same as blocked email/IP.**
|
||||
- [x] Should fingerprint rate limiting be a hard block or just a signal for review? **Recommendation: hard block (same as IP), since the 2-per-day limit is generous.**
|
||||
- [x] Should we backfill `signup_ip` for existing users from their first magic link/session? **Recommendation: no, not worth the complexity. Only applies to new signups going forward.**
|
||||
- [x] Should the feedback-for-credits flow also require verification? **Recommendation: it already requires completed jobs, which implies verification. No change needed.**
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Each part can be rolled back independently:
|
||||
1. **Credits on verification:** Revert code → new users get credits at creation again. Existing verified users unaffected.
|
||||
2. **IP rate limiting:** Revert code → no rate limiting. `signup_ip` field remains on docs but unused.
|
||||
3. **Fingerprinting:** Revert code → fingerprint not sent/stored. FingerprintJS dependency can be removed.
|
||||
|
||||
No data migrations needed for any rollback.
|
||||
@@ -0,0 +1,182 @@
|
||||
# Plan: Phase 1 — Mirror Divebar Google Drive to GCS
|
||||
|
||||
**Created:** 2026-03-21
|
||||
**Branch:** feat/sess-20260320-0015-divebar-mirror-index
|
||||
**Status:** Draft
|
||||
**Depends on:** Nothing (foundation phase)
|
||||
**Blocks:** Phase 3 (cross-reference index), Phase 4 (KJ Controller UI)
|
||||
|
||||
## Overview
|
||||
|
||||
Mirror the entire [diveBar Karaoke Google Drive](https://drive.google.com/drive/folders/1zxnSZcE03gzy0YVGOdnTrEIi8It_3Wu8) (~84 brand folders, tens of thousands of karaoke tracks in CDG+MP3, MP4, and ZIP formats) to a GCS bucket in the `nomadkaraoke` GCP project. Build a searchable index of all tracks with parsed metadata (artist, title, brand, format, file size). Run daily to sync new content.
|
||||
|
||||
### Why
|
||||
|
||||
- **Backup:** Community karaoke content is fragile — Drive links break, creators delete folders, accounts get suspended. Having our own mirror ensures we never lose access to tracks we've come to depend on.
|
||||
- **Performance:** Downloading from GCS to the KJ miniPC will be faster and more reliable than Google Drive, especially for large files.
|
||||
- **Searchability:** By parsing filenames and building a structured index, we can search across all 84 brands uniformly despite their inconsistent naming conventions.
|
||||
- **Foundation:** Phases 3 and 4 depend on having a reliable, indexed copy of the Divebar catalog.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] GCS bucket `nomadkaraoke-divebar-mirror` with all files from the shared Drive
|
||||
- [ ] Cloud Function (Python 3.12, Gen2) that recursively lists and downloads files from the Drive folder
|
||||
- [ ] Cloud Scheduler job running daily (e.g., 2 AM ET) to trigger sync
|
||||
- [ ] Incremental sync — only download new/modified files, skip unchanged
|
||||
- [ ] Structured index in BigQuery table `karaoke_decide.divebar_catalog` with parsed metadata
|
||||
- [ ] Handle all file types: `.cdg`, `.mp3`, `.mp4`, `.mkv`, `.avi`, `.webm`, `.zip`
|
||||
- [ ] Handle Drive shortcuts (most brand folders are shortcuts to other shared folders)
|
||||
- [ ] Service account with minimal permissions (Drive API read, GCS write, BigQuery write)
|
||||
- [ ] Pulumi-managed infrastructure (follows existing karaoke-gen patterns)
|
||||
- [ ] Logging and error reporting for failed downloads
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Google Drive API Access
|
||||
|
||||
The folder is publicly shared ("anyone with the link can view"). We'll use the Google Drive API v3 with a service account — even though the folder is public, the API requires authentication for listing operations. The service account doesn't need the folder explicitly shared with it for public folders, but we may need to use an API key for unauthenticated listing.
|
||||
|
||||
**Decision:** Use a service account with Drive API enabled. If the folder requires explicit share, the user can share it with the SA email.
|
||||
|
||||
### File Organization in GCS
|
||||
|
||||
```
|
||||
gs://nomadkaraoke-divebar-mirror/
|
||||
files/
|
||||
{brand_folder_name}/
|
||||
{original_filename}
|
||||
index/
|
||||
divebar-index-latest.json.gz
|
||||
divebar-index-{YYYY-MM-DD}.json.gz
|
||||
```
|
||||
|
||||
Preserve the Drive folder structure (brand → files) in GCS. This keeps the mirror browsable and allows us to attribute files to brands.
|
||||
|
||||
### Filename Parsing
|
||||
|
||||
Three main patterns observed across 84 brands:
|
||||
|
||||
1. **`BRAND_CODE - Artist - Title.ext`** (e.g., `NOMAD-0001 - This Is Me Smiling - Prettier.mp4`)
|
||||
2. **`Artist - Title - (Brand Tag).ext`** (e.g., `Alice in Chains - Heaven Beside You - (WTF Karaoke).mp4`)
|
||||
3. **`Artist - Title.ext`** (implicit brand from folder name)
|
||||
|
||||
Parser splits on ` - ` delimiter, tries each pattern, falls back to using the full filename as title with brand inferred from parent folder.
|
||||
|
||||
### Incremental Sync Strategy
|
||||
|
||||
- Store a `sync_state.json` in GCS with `{drive_file_id: {md5, size, gcs_path, synced_at}}`
|
||||
- On each run, list all Drive files recursively, compare MD5/size with sync state
|
||||
- Only download files that are new or modified
|
||||
- Track deleted files (present in sync state but not in Drive listing) — mark as deleted in index but don't remove from GCS (soft delete)
|
||||
|
||||
### Scale Considerations
|
||||
|
||||
- ~84 brand folders, estimated 20K-50K files, ~500GB-1TB total
|
||||
- Initial sync will take hours — Cloud Function has 60-min timeout (Gen2)
|
||||
- **Solution:** Use Cloud Run Job instead of Cloud Function for initial sync (9-hour timeout). Daily incremental syncs use Cloud Function (fast, only new files).
|
||||
- Rate limit Drive API calls (10 QPS default for service accounts)
|
||||
- Use batch upload to GCS with resumable uploads for large files
|
||||
|
||||
### BigQuery Index Schema
|
||||
|
||||
```sql
|
||||
CREATE TABLE karaoke_decide.divebar_catalog (
|
||||
file_id STRING NOT NULL, -- Google Drive file ID
|
||||
brand STRING NOT NULL, -- Brand folder name (e.g., "WTF Karaoke Videos")
|
||||
brand_code STRING, -- Extracted brand code (e.g., "WTF", "CKK", "NOMAD")
|
||||
artist STRING, -- Parsed artist name
|
||||
title STRING, -- Parsed song title
|
||||
disc_id STRING, -- Disc/track ID if present
|
||||
filename STRING NOT NULL, -- Original filename
|
||||
format STRING NOT NULL, -- File format (cdg, mp3, mp4, zip, etc.)
|
||||
paired_format STRING, -- For CDG: "cdg+mp3"; for standalone: NULL
|
||||
file_size INT64, -- File size in bytes
|
||||
gcs_path STRING NOT NULL, -- Full GCS URI
|
||||
drive_path STRING NOT NULL, -- Original Drive path
|
||||
drive_md5 STRING, -- MD5 from Drive API
|
||||
synced_at TIMESTAMP NOT NULL, -- When this file was last synced
|
||||
deleted BOOL DEFAULT FALSE, -- Soft delete flag
|
||||
artist_normalized STRING, -- Lowercased, stripped for matching
|
||||
title_normalized STRING, -- Lowercased, stripped for matching
|
||||
)
|
||||
```
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] **Create Pulumi module** `modules/divebar_mirror.py`
|
||||
- GCS bucket `nomadkaraoke-divebar-mirror`
|
||||
- Service account `divebar-mirror` with roles: `storage.objectAdmin` (on bucket), `bigquery.dataEditor` (on dataset)
|
||||
- Enable Drive API on project
|
||||
- Cloud Scheduler job (daily 2 AM ET)
|
||||
|
||||
2. [ ] **Create Cloud Function** `infrastructure/functions/divebar_mirror/`
|
||||
- `main.py` — entry point, incremental sync logic
|
||||
- `drive_client.py` — Google Drive API wrapper (recursive listing, download, shortcut resolution)
|
||||
- `filename_parser.py` — Parse karaoke filenames into artist/title/brand/disc_id
|
||||
- `index_builder.py` — Build and upload BigQuery index
|
||||
- `requirements.txt` — google-api-python-client, google-cloud-storage, google-cloud-bigquery
|
||||
|
||||
3. [ ] **Implement recursive Drive listing**
|
||||
- Handle shortcuts (resolve to actual folder, recurse into them)
|
||||
- Handle pagination (Drive API returns max 1000 items per page)
|
||||
- Return flat list of `{file_id, name, size, md5, mime_type, parent_folder_name, full_path}`
|
||||
|
||||
4. [ ] **Implement filename parser**
|
||||
- Pattern matching for the 3 naming conventions
|
||||
- CDG+MP3 pair detection (same base name, different extensions)
|
||||
- Brand code extraction from disc IDs or folder names
|
||||
- Normalization (lowercase, strip diacritics, strip special chars) for matching
|
||||
|
||||
5. [ ] **Implement incremental sync**
|
||||
- Load sync state from GCS
|
||||
- Compare Drive listing with sync state
|
||||
- Download new/modified files to GCS (resumable uploads)
|
||||
- Update sync state
|
||||
- Build and upload BigQuery index
|
||||
|
||||
6. [ ] **Create Cloud Run Job for initial sync**
|
||||
- Same logic as Cloud Function but with longer timeout
|
||||
- Can be triggered manually for first full sync
|
||||
|
||||
7. [ ] **Add to Pulumi __main__.py**
|
||||
- Import and wire up the new module
|
||||
- Export bucket name and function URL
|
||||
|
||||
8. [ ] **Test with a subset**
|
||||
- Test with 2-3 brand folders first
|
||||
- Verify filename parsing accuracy
|
||||
- Verify incremental sync (run twice, second should be no-op)
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `infrastructure/modules/divebar_mirror.py` | Create | Pulumi module: bucket, SA, scheduler, function |
|
||||
| `infrastructure/functions/divebar_mirror/main.py` | Create | Cloud Function entry point |
|
||||
| `infrastructure/functions/divebar_mirror/drive_client.py` | Create | Drive API wrapper |
|
||||
| `infrastructure/functions/divebar_mirror/filename_parser.py` | Create | Karaoke filename parser |
|
||||
| `infrastructure/functions/divebar_mirror/index_builder.py` | Create | BigQuery index builder |
|
||||
| `infrastructure/functions/divebar_mirror/requirements.txt` | Create | Python dependencies |
|
||||
| `infrastructure/__main__.py` | Modify | Import and wire up divebar_mirror module |
|
||||
| `infrastructure/config.py` | Modify | Add DIVEBAR_DRIVE_FOLDER_ID constant |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests** for `filename_parser.py` — test all 3 naming patterns + edge cases
|
||||
- **Unit tests** for `drive_client.py` — mock Drive API responses, test shortcut resolution, pagination
|
||||
- **Integration test** — run against 2-3 real brand folders, verify GCS files and BigQuery rows
|
||||
- **Manual testing** — trigger Cloud Function, inspect GCS bucket and BigQuery table
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] How large is the full dataset? Need to estimate GCS storage costs (~$0.02/GB/month for Standard)
|
||||
- [ ] Should we store ZIP files as-is or extract them? (CDG+MP3 pairs inside ZIPs)
|
||||
- [ ] Do we need the actual file content in GCS for Phase 4, or just the index? (KJ Controller could download directly from Drive using the file ID)
|
||||
- [ ] Should we use Cloud Run Job (longer timeout) or just let the Cloud Function page through in multiple invocations?
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Delete the GCS bucket contents (files are copies, originals safe in Drive)
|
||||
- Remove BigQuery table rows
|
||||
- `pulumi destroy` the module resources
|
||||
- Revert Pulumi code changes
|
||||
@@ -0,0 +1,169 @@
|
||||
# Plan: Phase 2 — Migrate KaraokeNerds Data Pipeline to nomadkaraoke
|
||||
|
||||
**Created:** 2026-03-21
|
||||
**Branch:** feat/sess-20260320-0015-divebar-mirror-index
|
||||
**Status:** Draft
|
||||
**Depends on:** Nothing (can run in parallel with Phase 1)
|
||||
**Blocks:** Phase 3 (cross-reference index)
|
||||
|
||||
## Overview
|
||||
|
||||
Migrate the daily KaraokeNerds data export pipeline from the legacy `projectbread-karaokay` GCP project to the `nomadkaraoke` project. Currently, two Gen1 Cloud Functions in `projectbread-karaokay` fetch community and full catalog exports daily from the KN API and store them in `gs://projectbread-karaokay.appspot.com/karaokenerds-data/`. The `karaoke-decide` app already has a BigQuery table `karaokenerds_raw` (275K rows) but it's a one-off dump with no automated refresh.
|
||||
|
||||
### Why
|
||||
|
||||
- **Consolidation:** All nomadkaraoke infrastructure should be in the `nomadkaraoke` GCP project, Pulumi-managed
|
||||
- **Automated refresh:** The BigQuery table is stale — it needs daily refresh from the KN API to stay current
|
||||
- **Foundation:** Phase 3 needs up-to-date KN data to cross-reference with Divebar files
|
||||
- **Cost:** The `projectbread-karaokay` project is on Firebase free tier but still costs for GCS storage (~7GB cumulative). Better to consolidate billing.
|
||||
|
||||
## Current State
|
||||
|
||||
### In `projectbread-karaokay`:
|
||||
|
||||
| Component | Details |
|
||||
|-----------|---------|
|
||||
| **Function 1:** `fetchAndStoreCommunityJson` | Daily 3:05 AM ET, fetches `karaokenerds.com/Data/Community?key=...`, stores gzipped JSON to GCS |
|
||||
| **Function 2:** `fetchAndStoreFullJson` | Daily 4:30 AM ET, fetches `karaokenerds.com/Data/Songs?key=...`, stores gzipped JSON to GCS |
|
||||
| **Storage:** | `gs://projectbread-karaokay.appspot.com/karaokenerds-data/{community,full}/` |
|
||||
| **API Key:** | `27b45f98099645c786b2b23cc35a405a` (env var `KARAOKENERDS_KEY`) |
|
||||
| **Runtime:** | Node.js 18, Gen1, us-central1 |
|
||||
| **Data size:** | Community: ~1.9 MB/day, Full: ~7.5 MB/day (gzipped) |
|
||||
|
||||
### In `nomadkaraoke` (karaoke-decide):
|
||||
|
||||
| Component | Details |
|
||||
|-----------|---------|
|
||||
| **BigQuery table:** | `karaoke_decide.karaokenerds_raw` (275K rows, 4 columns: Id, Artist, Title, Brands) |
|
||||
| **API client:** | `karaoke_decide/services/karaokenerds.py` — `KaraokeNerdsClient.fetch_catalog()` (exists but unused for scheduled imports) |
|
||||
| **Status:** | One-off dump, no automated refresh, TODO noted in DATA-CATALOG.md |
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] New Cloud Function in `nomadkaraoke` that fetches KN full catalog daily
|
||||
- [ ] Store raw JSON exports in GCS (`gs://nomadkaraoke-kn-data/`)
|
||||
- [ ] Automated daily BigQuery refresh of `karaokenerds_raw` table
|
||||
- [ ] Store KN API key in Secret Manager (not env var)
|
||||
- [ ] Pulumi-managed infrastructure
|
||||
- [ ] Keep community export too (useful for Phase 3 — community tracks map to Divebar)
|
||||
- [ ] Verify karaoke-decide still works after table refresh
|
||||
- [ ] Plan for decommissioning `projectbread-karaokay` functions (after validation)
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Single Cloud Function, Two Modes
|
||||
|
||||
Rather than two separate functions, create one function `kn-data-sync` with a `mode` parameter:
|
||||
- `mode=community` — fetch community export
|
||||
- `mode=full` — fetch full catalog export + refresh BigQuery
|
||||
|
||||
Two Cloud Scheduler jobs trigger the same function with different payloads.
|
||||
|
||||
### BigQuery Refresh Strategy
|
||||
|
||||
The full catalog is ~275K rows and ~7.5MB gzipped. Small enough to do a full replace:
|
||||
|
||||
1. Fetch JSON from KN API
|
||||
2. Store raw gzipped JSON in GCS (date-stamped + latest pointer)
|
||||
3. Parse JSON into rows
|
||||
4. Load to BigQuery staging table via `WRITE_TRUNCATE` (atomic replace)
|
||||
5. Swap staging → production (or just use `WRITE_TRUNCATE` directly on the main table since it's atomic)
|
||||
|
||||
### Enhanced Schema
|
||||
|
||||
The current `karaokenerds_raw` schema is minimal (4 columns). The KN API likely returns more fields. We should capture everything available:
|
||||
|
||||
```sql
|
||||
-- Existing (keep for backwards compatibility)
|
||||
Id INTEGER,
|
||||
Artist STRING,
|
||||
Title STRING,
|
||||
Brands STRING,
|
||||
|
||||
-- New fields (from full API export, if available)
|
||||
youtube_urls STRING, -- JSON array of YouTube URLs per track
|
||||
community_tracks STRING, -- JSON array of community contributions
|
||||
brand_codes STRING, -- Comma-separated brand codes
|
||||
last_updated TIMESTAMP, -- When KN last updated this entry
|
||||
```
|
||||
|
||||
We'll inspect the actual API response to determine the full schema.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] **Inspect KN API response**
|
||||
- Fetch `https://karaokenerds.com/Data/Songs?key=...` (use existing key)
|
||||
- Document the full JSON schema
|
||||
- Determine which fields to capture in BigQuery
|
||||
|
||||
2. [ ] **Create Secret Manager secret**
|
||||
- Store KN API key as `karaokenerds-api-key` in Secret Manager
|
||||
- Grant access to the new service account
|
||||
|
||||
3. [ ] **Create Pulumi module** `modules/kn_data_sync.py`
|
||||
- GCS bucket `nomadkaraoke-kn-data`
|
||||
- Service account `kn-data-sync` with roles: `storage.objectAdmin` (on bucket), `bigquery.dataEditor` (on dataset), `secretmanager.secretAccessor`
|
||||
- Cloud Function v2 (Python 3.12)
|
||||
- Two Cloud Scheduler jobs (community at 3:05 AM ET, full at 4:30 AM ET)
|
||||
|
||||
4. [ ] **Create Cloud Function** `infrastructure/functions/kn_data_sync/`
|
||||
- `main.py` — entry point, mode dispatch
|
||||
- `fetcher.py` — HTTP fetch from KN API with streaming
|
||||
- `bigquery_loader.py` — Parse JSON, load to BigQuery
|
||||
- `requirements.txt`
|
||||
|
||||
5. [ ] **Update BigQuery table schema**
|
||||
- Add new columns (if any) to `karaokenerds_raw` in karaoke-decide Pulumi
|
||||
- Or create a new table `karaokenerds_full` with expanded schema alongside the existing one
|
||||
|
||||
6. [ ] **Test the pipeline**
|
||||
- Run function locally or via direct invocation
|
||||
- Verify GCS files created correctly
|
||||
- Verify BigQuery table refreshed
|
||||
- Verify karaoke-decide app still works (quiz, recommendations)
|
||||
|
||||
7. [ ] **Run in parallel with legacy**
|
||||
- Keep both karaokay and nomadkaraoke functions running for 1 week
|
||||
- Compare outputs to ensure parity
|
||||
|
||||
8. [ ] **Decommission legacy**
|
||||
- Disable Cloud Scheduler in karaokay (don't delete yet)
|
||||
- After 30 days, delete functions and scheduler
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `infrastructure/modules/kn_data_sync.py` | Create | Pulumi: bucket, SA, function, scheduler |
|
||||
| `infrastructure/functions/kn_data_sync/main.py` | Create | Cloud Function entry point |
|
||||
| `infrastructure/functions/kn_data_sync/fetcher.py` | Create | KN API HTTP client |
|
||||
| `infrastructure/functions/kn_data_sync/bigquery_loader.py` | Create | BigQuery load logic |
|
||||
| `infrastructure/functions/kn_data_sync/requirements.txt` | Create | Dependencies |
|
||||
| `infrastructure/__main__.py` | Modify | Wire up kn_data_sync module |
|
||||
| `infrastructure/modules/secrets.py` | Modify | Add karaokenerds-api-key secret |
|
||||
|
||||
### Cross-repo changes (karaoke-decide):
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `infrastructure/__main__.py` | Modify | Update BigQuery table schema if needed |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests** for JSON parsing and BigQuery row generation
|
||||
- **Integration test** — fetch from actual KN API, verify response shape
|
||||
- **Comparison test** — compare new pipeline output with legacy karaokay export
|
||||
- **Regression** — verify karaoke-decide quiz/recommendation queries still work after schema change
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] What is the full KN API response schema? Need to inspect before finalizing BigQuery schema.
|
||||
- [ ] Does the community export have YouTube URLs that map to Divebar content?
|
||||
- [ ] Should we keep historical exports (date-stamped) or just latest? Current karaokay keeps all (~1100 days).
|
||||
- [ ] Should the BigQuery table live in karaoke-gen's infra or karaoke-decide's infra? (Currently in karaoke-decide)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Disable new Cloud Scheduler jobs
|
||||
- Re-enable legacy karaokay functions (they're still there)
|
||||
- BigQuery table can be restored from any historical GCS export
|
||||
@@ -0,0 +1,170 @@
|
||||
# Plan: Phase 3 — Cross-Reference Index (KN ↔ Divebar)
|
||||
|
||||
**Created:** 2026-03-21
|
||||
**Branch:** feat/sess-20260320-0015-divebar-mirror-index
|
||||
**Status:** Draft
|
||||
**Depends on:** Phase 1 (Divebar mirror + index), Phase 2 (KN pipeline with fresh data)
|
||||
**Blocks:** Phase 4 (KJ Controller UI — cross-reference badges on KN results)
|
||||
|
||||
## Overview
|
||||
|
||||
Build an automated cross-reference that links KaraokeNerds catalog entries (~275K songs) to Divebar Google Drive files (~20K-50K tracks). This enables the KJ Controller to show "Available in Divebar" badges on KN search results, and powers the unified search in Phase 4.
|
||||
|
||||
### Why
|
||||
|
||||
- **User experience:** When a KJ searches KaraokeNerds for a song, they should immediately see if it's available as a free community track in the Divebar collection — and download it from there instead of YouTube.
|
||||
- **Data enrichment:** Divebar files have inconsistent metadata. Cross-referencing with KN (which has curated artist/title/brand data) enriches the Divebar catalog.
|
||||
- **Deduplication:** Multiple Divebar brands may have the same song. The cross-reference helps identify duplicates.
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Matching Strategy
|
||||
|
||||
The challenge: KN has structured data (`Artist`, `Title`, `Brands`) while Divebar has filenames parsed heuristically. We need fuzzy matching.
|
||||
|
||||
**Three-tier matching:**
|
||||
|
||||
1. **Exact normalized match** (highest confidence, ~0.95)
|
||||
- Normalize both sides: lowercase, strip diacritics, remove parentheticals like "(Karaoke Version)", strip "the " prefix
|
||||
- Match on `(artist_normalized, title_normalized)`
|
||||
- Expected to catch ~60-70% of matches
|
||||
|
||||
2. **Fuzzy match** (medium confidence, ~0.80)
|
||||
- Use trigram similarity or Levenshtein distance
|
||||
- Threshold: 85% similarity on combined artist+title string
|
||||
- Catches minor spelling differences, abbreviations, punctuation variations
|
||||
- Expected to catch ~15-20% more
|
||||
|
||||
3. **Brand-assisted match** (high confidence, ~0.90)
|
||||
- Some Divebar brands are also listed in KN's `Brands` field
|
||||
- Map Divebar folder names to KN brand codes (e.g., "Nomad Karaoke" → "NOMAD")
|
||||
- If a Divebar file's brand matches a KN track's brand list AND artist matches, high confidence
|
||||
- This is the most reliable for brands that publish to both platforms
|
||||
|
||||
### Where to Run Matching
|
||||
|
||||
**BigQuery SQL** — both datasets are already there (Phase 1 puts Divebar in BigQuery, Phase 2 refreshes KN).
|
||||
|
||||
```sql
|
||||
-- Exact match
|
||||
SELECT
|
||||
kn.Id AS kn_id,
|
||||
db.file_id AS divebar_file_id,
|
||||
'exact' AS match_type,
|
||||
0.95 AS confidence
|
||||
FROM karaoke_decide.karaokenerds_raw kn
|
||||
JOIN karaoke_decide.divebar_catalog db
|
||||
ON kn.artist_normalized = db.artist_normalized
|
||||
AND kn.title_normalized = db.title_normalized
|
||||
WHERE db.deleted = FALSE
|
||||
```
|
||||
|
||||
For fuzzy matching, BigQuery has `SOUNDEX()` and we can use UDFs. Or run fuzzy matching in a Cloud Function with Python's `rapidfuzz` library.
|
||||
|
||||
### Output Table
|
||||
|
||||
```sql
|
||||
CREATE TABLE karaoke_decide.kn_divebar_xref (
|
||||
kn_id INTEGER NOT NULL, -- KaraokeNerds song ID
|
||||
divebar_file_id STRING NOT NULL, -- Drive file ID
|
||||
match_type STRING NOT NULL, -- 'exact', 'fuzzy', 'brand_assisted'
|
||||
confidence FLOAT64 NOT NULL, -- 0.0 to 1.0
|
||||
divebar_brand STRING, -- Brand folder name
|
||||
divebar_format STRING, -- File format
|
||||
divebar_gcs_path STRING, -- GCS URI for download
|
||||
matched_at TIMESTAMP NOT NULL, -- When this match was created
|
||||
verified BOOL DEFAULT FALSE, -- Manual verification flag
|
||||
)
|
||||
```
|
||||
|
||||
### Refresh Cadence
|
||||
|
||||
- Run matching after each Divebar mirror sync (daily, triggered by Phase 1 completion)
|
||||
- Cloud Function or BigQuery scheduled query
|
||||
- Full rebuild each time (WRITE_TRUNCATE) — simpler than incremental for cross-reference
|
||||
|
||||
### API Endpoint
|
||||
|
||||
Create a lightweight API (Cloud Function or add to karaoke-gen API) that the KJ Controller can query:
|
||||
|
||||
```
|
||||
GET /api/divebar/lookup?kn_ids=123,456,789
|
||||
→ { "123": [{"file_id": "abc", "format": "mp4", "brand": "WTF Karaoke", "gcs_path": "gs://..."}], ... }
|
||||
|
||||
GET /api/divebar/search?q=bohemian+rhapsody
|
||||
→ [{"file_id": "abc", "brand": "...", "artist": "Queen", "title": "Bohemian Rhapsody", "format": "mp4", "gcs_path": "gs://...", "kn_id": 123}]
|
||||
```
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] **Build brand mapping table**
|
||||
- Map Divebar folder names → KN brand codes
|
||||
- Manual mapping for the 84 brands (many will be community-only, not in KN)
|
||||
- Store as a JSON config or BigQuery table
|
||||
|
||||
2. [ ] **Implement normalization functions**
|
||||
- BigQuery UDFs or Python functions
|
||||
- Lowercase, strip diacritics, remove "(Karaoke)", "(KJ Version)", etc.
|
||||
- Strip "the " prefix from artist names
|
||||
- Handle "feat." / "ft." / "featuring" variations
|
||||
|
||||
3. [ ] **Implement exact matching**
|
||||
- BigQuery scheduled query joining on normalized fields
|
||||
- Write results to `kn_divebar_xref`
|
||||
|
||||
4. [ ] **Implement fuzzy matching**
|
||||
- Cloud Function using `rapidfuzz` library
|
||||
- Read unmatched Divebar files from BigQuery
|
||||
- Match against KN catalog with 85% threshold
|
||||
- Append to `kn_divebar_xref` with lower confidence
|
||||
|
||||
5. [ ] **Implement brand-assisted matching**
|
||||
- For Divebar files from mapped brands
|
||||
- Cross-reference with KN tracks that list the same brand
|
||||
- Higher confidence than pure fuzzy match
|
||||
|
||||
6. [ ] **Create API endpoint**
|
||||
- Cloud Function `divebar-lookup` or add routes to karaoke-gen API
|
||||
- Two endpoints: bulk lookup by KN IDs, and search by query
|
||||
- Returns Divebar file info + GCS download URLs
|
||||
|
||||
7. [ ] **Create Pulumi module** `modules/divebar_xref.py`
|
||||
- BigQuery table and scheduled query
|
||||
- Cloud Function for fuzzy matching
|
||||
- API Cloud Function (or Cloud Run route)
|
||||
|
||||
8. [ ] **Add to Pulumi __main__.py**
|
||||
- Wire up module, set dependency on divebar_mirror and kn_data_sync
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `infrastructure/modules/divebar_xref.py` | Create | Pulumi: BigQuery table, scheduled queries, functions |
|
||||
| `infrastructure/functions/divebar_xref/main.py` | Create | Matching logic (exact + fuzzy) |
|
||||
| `infrastructure/functions/divebar_xref/normalizer.py` | Create | Text normalization for matching |
|
||||
| `infrastructure/functions/divebar_xref/brand_mapping.json` | Create | Divebar folder → KN brand code mapping |
|
||||
| `infrastructure/functions/divebar_lookup/main.py` | Create | API endpoint for KJ Controller |
|
||||
| `infrastructure/__main__.py` | Modify | Wire up divebar_xref module |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests** for normalization functions (diacritics, parentheticals, prefixes)
|
||||
- **Unit tests** for matching logic with known song pairs
|
||||
- **Accuracy assessment** — sample 100 matches, manually verify correctness
|
||||
- **Coverage report** — what % of Divebar files have KN matches?
|
||||
- **API tests** — test lookup and search endpoints
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] What confidence threshold should we use for showing "Available in Divebar" badges? (Suggest ≥0.80)
|
||||
- [ ] Should we show multiple Divebar versions of the same KN song? (e.g., MP4 from brand A and CDG from brand B)
|
||||
- [ ] How do we handle CDG+MP3 pairs in the cross-reference? (One match for the pair, or separate entries?)
|
||||
- [ ] Should the API endpoint be authenticated? (KJ Controller is local network only, but the API would be public Cloud Run)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Drop `kn_divebar_xref` BigQuery table
|
||||
- Remove Cloud Functions
|
||||
- `pulumi destroy` module resources
|
||||
- Phase 4 falls back to Divebar-only search without KN cross-reference
|
||||
@@ -0,0 +1,339 @@
|
||||
# Plan: Modal → GCP Audio Separation Migration
|
||||
|
||||
**Created:** 2026-03-22
|
||||
**Branch:** feat/sess-20260321-2314-modal-gcp-migration
|
||||
**Worktrees:** `karaoke-gen-modal-gcp-migration` (infra + backend), `python-audio-separator-modal-gcp-migration` (server)
|
||||
**Status:** Draft → Ready for implementation
|
||||
|
||||
## Overview
|
||||
|
||||
Migrate audio stem separation from Modal to a Cloud Run Service with L4 GPU on GCP. This eliminates the only third-party compute dependency, fixes intermittent Modal API failures ("no files were downloaded"), upgrades to latest ensemble models for better quality, and decouples separation from the lyrics review critical path so users can start reviewing lyrics faster.
|
||||
|
||||
### Architecture Decision: Cloud Run GPU Service
|
||||
|
||||
| Factor | Cloud Run GPU | GCE VM + auto-stop |
|
||||
|--------|--------------|-------------------|
|
||||
| Idle cost | $0 (scales to zero) | $0 (when stopped) |
|
||||
| Cold start | ~30-60s (model load from GCS) | ~60-120s (VM boot + model load) |
|
||||
| Ops overhead | None (serverless) | Moderate (start/stop scripts, health monitoring) |
|
||||
| GPU available | L4 (24GB VRAM) in us-central1 | T4/L4/A100 |
|
||||
| Scaling | Automatic | Manual orchestration |
|
||||
| Cost/job (~12 min GPU) | ~$0.13 | ~$0.07-0.10 (T4) |
|
||||
| Deployment | Docker image push | Packer image + GCS wheel + SSH restart |
|
||||
|
||||
Cloud Run GPU wins on simplicity. L4 is faster than T4, cold start is acceptable, and per-job cost well under $1.
|
||||
|
||||
### Model Upgrade: Ensemble Presets as Default
|
||||
|
||||
**Current models (single-model):**
|
||||
| Stage | Model | SDR | Notes |
|
||||
|-------|-------|-----|-------|
|
||||
| 1 (instrumental) | `model_bs_roformer_ep_317_sdr_12.9755.ckpt` | 12.97 | Older BS-Roformer |
|
||||
| 1 (other stems) | `htdemucs_6s.yaml` | — | Demucs 6-stem — **dropping** |
|
||||
| 2 (karaoke/BV) | `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt` | 10.20 | Single karaoke model |
|
||||
|
||||
**New defaults (ensemble presets):**
|
||||
| Stage | Preset | Models | SDR | Notes |
|
||||
|-------|--------|--------|-----|-------|
|
||||
| 1 | `instrumental_clean` | Fv7z + Resurrection | ~17.5 | +35% quality, bleedless |
|
||||
| 2 | `karaoke` | 3 karaoke models (aufr33+gabox_v2+becruily) | ~10.6 | +4% quality, 3-model ensemble |
|
||||
|
||||
**Key design: preset-name references, not model filenames.** karaoke-gen references preset names (`instrumental_clean`, `karaoke`). The audio-separator package resolves preset → models + ensemble algorithm. When better models come out, update presets in audio-separator and release a new version — no karaoke-gen changes needed.
|
||||
|
||||
### Pipeline Decoupling: Separation Off Critical Path
|
||||
|
||||
**Current flow (both gate review):**
|
||||
```
|
||||
Job created
|
||||
├── Audio worker (separation) ──→ audio_complete=True ─┐
|
||||
│ ├→ GENERATING_SCREENS → AWAITING_REVIEW
|
||||
└── Lyrics worker (transcription) → lyrics_complete=True┘
|
||||
```
|
||||
|
||||
**New flow (lyrics gates review, separation runs in background):**
|
||||
```
|
||||
Job created
|
||||
├── Audio worker (separation) ──→ audio_complete=True (background, not gating)
|
||||
│
|
||||
└── Lyrics worker (transcription) → lyrics_complete=True → GENERATING_SCREENS → AWAITING_REVIEW
|
||||
│
|
||||
User reviews lyrics
|
||||
│
|
||||
Instrumental review
|
||||
(waits for audio_complete
|
||||
if not ready yet)
|
||||
```
|
||||
|
||||
**Why this works:**
|
||||
- Lyrics review (`/app/jobs#/{jobId}/review`) only needs transcription output — no stems needed
|
||||
- Instrumental review (`/app/jobs#/{jobId}/instrumental`) needs stems — but user typically spends 5+ min on lyrics review, buying time for separation to finish
|
||||
- In the rare case separation isn't done when user reaches instrumental review, show a "Separation in progress..." waiting state
|
||||
- Screens worker only truly needs lyrics to generate title/end screens
|
||||
|
||||
### Estimated Timeline
|
||||
|
||||
| Scenario | Stage 1 | Stage 2 | Cold start | Total |
|
||||
|----------|---------|---------|------------|-------|
|
||||
| Current (Modal, single models) | 3-5 min | 2-3 min | 0 | 7-11 min |
|
||||
| New ensemble (Cloud Run L4) | ~4-6 min | ~3-5 min | ~30-60s | ~8-12 min |
|
||||
| **User-perceived wait** (new) | — | — | — | **0 min** (decoupled) |
|
||||
|
||||
Separation takes slightly longer with ensembles, but users never wait for it — they're reviewing lyrics while it runs.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Audio separation runs on GCP Cloud Run with L4 GPU
|
||||
- [ ] Same HTTP API contract as Modal deployment (endpoints, request/response format)
|
||||
- [ ] `audio-separator-remote` CLI and `AudioSeparatorAPIClient` work unchanged
|
||||
- [ ] Default models use ensemble presets (`instrumental_clean` + `karaoke`)
|
||||
- [ ] karaoke-gen references preset names, not model filenames
|
||||
- [ ] Demucs 6-stem separation dropped from pipeline
|
||||
- [ ] Scale-to-zero when not processing (no idle GPU cost)
|
||||
- [ ] Cold start < 60 seconds
|
||||
- [ ] Per-job cost < $1
|
||||
- [ ] Models stored in GCS, loaded on container startup
|
||||
- [ ] Publicly accessible endpoint with auth token (reuse `admin-tokens` secret)
|
||||
- [ ] Infrastructure managed via Pulumi in karaoke-gen
|
||||
- [ ] Separation decoupled from lyrics review critical path
|
||||
- [ ] Instrumental review page handles "separation still in progress" gracefully
|
||||
- [ ] Docker image CI lives in python-audio-separator repo, pushes to Artifact Registry
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Cloud Run GPU Server (python-audio-separator repo)
|
||||
|
||||
#### Step 1.1 — Create Cloud Run-compatible FastAPI server
|
||||
- [ ] Create `audio_separator/remote/deploy_cloudrun.py` adapted from `deploy_modal.py`
|
||||
- [ ] Replace Modal-specific code:
|
||||
- `modal.Dict` → in-memory `dict` (single instance handles one job at a time)
|
||||
- `modal.Volume` → local `/tmp` storage + GCS for model cache
|
||||
- `modal.Function.spawn()` → synchronous processing (no background tasks needed)
|
||||
- `modal.Image` → Dockerfile
|
||||
- `modal.App` → standard FastAPI + uvicorn
|
||||
- [ ] Keep all existing API endpoints identical:
|
||||
- `POST /separate` — submit separation job
|
||||
- `GET /status/{task_id}` — return job status
|
||||
- `GET /download/{task_id}/{file_hash}` — download result file
|
||||
- `GET /models-json`, `GET /models` — list models
|
||||
- `GET /health` — health check (with model readiness indicator)
|
||||
- `GET /` — root info
|
||||
- [ ] Add model download on startup from GCS bucket (`gs://nomadkaraoke-audio-separator-models/`)
|
||||
- [ ] Add ensemble preset support: accept `preset` parameter in `/separate` that resolves to model list + algorithm
|
||||
- [ ] Add startup probe endpoint for Cloud Run GPU readiness
|
||||
|
||||
**Design:** Make `/separate` effectively synchronous — process inline, store results in-memory dict + local filesystem. Cloud Run instance stays alive for scale-down timeout (600s), so Stage 2 hits the same warm instance. Async polling API contract preserved for client compatibility.
|
||||
|
||||
#### Step 1.2 — Create Dockerfile
|
||||
- [ ] Create `Dockerfile.cloudrun` in repo root
|
||||
- [ ] Base: `nvidia/cuda:12.6.3-runtime-ubuntu22.04` (matches Cloud Run L4 driver support)
|
||||
- [ ] Install: Python 3.13, FFmpeg, libsndfile, sox, system audio libs
|
||||
- [ ] Install: `audio-separator[gpu]` from current repo
|
||||
- [ ] Entrypoint: `python -m audio_separator.remote.deploy_cloudrun`
|
||||
- [ ] Expose port 8080
|
||||
- [ ] Set env: `MODEL_DIR=/models`, `STORAGE_DIR=/tmp/storage`
|
||||
|
||||
#### Step 1.3 — Upload models to GCS
|
||||
- [ ] Create GCS bucket `nomadkaraoke-audio-separator-models` (us-central1, standard storage)
|
||||
- [ ] Upload all models needed by default ensemble presets:
|
||||
- `mel_band_roformer_instrumental_fv7z_gabox.ckpt` (instrumental_clean preset)
|
||||
- `bs_roformer_instrumental_resurrection_unwa.ckpt` (instrumental_clean preset)
|
||||
- `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt` (karaoke preset)
|
||||
- `mel_band_roformer_karaoke_gabox_v2.ckpt` (karaoke preset)
|
||||
- `mel_band_roformer_karaoke_becruily.ckpt` (karaoke preset)
|
||||
- [ ] Total: ~1-1.5 GB of models
|
||||
|
||||
#### Step 1.4 — Local testing
|
||||
- [ ] Build Docker image locally
|
||||
- [ ] Test with `docker run --gpus all` (if local GPU available) or CPU mode
|
||||
- [ ] Verify API compatibility: submit job with `preset=instrumental_clean`, poll status, download files
|
||||
- [ ] Verify output filename format matches expected pattern: `filename_(StemType)_modelname.ext`
|
||||
- [ ] Verify ensemble output: ensembled stems have correct naming
|
||||
- [ ] Compare output quality with Modal (A/B test on reference songs)
|
||||
|
||||
#### Step 1.5 — CI/CD for Docker image
|
||||
- [ ] Create `.github/workflows/deploy-to-cloudrun.yml` in python-audio-separator repo
|
||||
- [ ] Triggers: PyPI release, changes to Dockerfile.cloudrun, manual dispatch
|
||||
- [ ] Steps: build Docker image → push to Artifact Registry (`us-central1-docker.pkg.dev/nomadkaraoke/audio-separator`)
|
||||
- [ ] Use Workload Identity Federation for GCP auth
|
||||
|
||||
### Phase 2: GCP Infrastructure (karaoke-gen repo)
|
||||
|
||||
#### Step 2.1 — Artifact Registry
|
||||
- [ ] Add Artifact Registry Docker repo to Pulumi
|
||||
- [ ] Repository: `audio-separator` in `us-central1`
|
||||
|
||||
#### Step 2.2 — GCS Model Bucket
|
||||
- [ ] Create `nomadkaraoke-audio-separator-models` bucket via Pulumi
|
||||
- [ ] Standard storage class, us-central1
|
||||
- [ ] Grant read access to Cloud Run service account
|
||||
|
||||
#### Step 2.3 — Cloud Run GPU Service
|
||||
- [ ] Create `infrastructure/modules/audio_separator_service.py`
|
||||
- [ ] Cloud Run Service configuration:
|
||||
- Image: from Artifact Registry
|
||||
- GPU: 1x NVIDIA L4
|
||||
- CPU: 4 vCPU (minimum required for L4)
|
||||
- Memory: 16 GiB
|
||||
- Min instances: 0 (scale to zero)
|
||||
- Max instances: 2 (handle concurrent jobs)
|
||||
- Request timeout: 1800s (30 min)
|
||||
- Scale-down delay: 600s (keep warm between Stage 1 → Stage 2)
|
||||
- Startup probe: HTTP GET /health, 120s initial delay, 10s period
|
||||
- Env vars:
|
||||
- `MODEL_BUCKET=nomadkaraoke-audio-separator-models`
|
||||
- `MODEL_DIR=/models`
|
||||
- `ADMIN_TOKEN` (from Secret Manager, reuse existing `admin-tokens`)
|
||||
- Region: us-central1
|
||||
- Ingress: all traffic (public endpoint with auth)
|
||||
|
||||
#### Step 2.4 — Service Account & IAM
|
||||
- [ ] Create `audio-separator` service account
|
||||
- [ ] Grant: `storage.objectViewer` on model bucket
|
||||
- [ ] Grant: `secretmanager.secretAccessor` for admin-tokens
|
||||
- [ ] Grant: `logging.logWriter`, `monitoring.metricWriter`
|
||||
|
||||
#### Step 2.5 — Wire into Pulumi
|
||||
- [ ] Add to `infrastructure/__main__.py`
|
||||
- [ ] Add config constants to `infrastructure/config.py`
|
||||
|
||||
### Phase 3: Pipeline Decoupling + Model Upgrade (karaoke-gen repo)
|
||||
|
||||
#### Step 3.1 — Decouple separation from lyrics review path
|
||||
- [ ] In `backend/services/job_manager.py`:
|
||||
- Change `check_parallel_processing_complete()` to only check `lyrics_complete` (not `audio_complete`)
|
||||
- `mark_lyrics_complete()` triggers screens worker on its own (no need to wait for audio)
|
||||
- `mark_audio_complete()` no longer triggers screens — just sets the flag
|
||||
- [ ] In `backend/workers/screens_worker.py`:
|
||||
- Remove validation that `audio_complete` must be True
|
||||
- Screens only needs lyrics data to generate title/end screens
|
||||
- Skip instrumental analysis step if audio isn't complete yet (or make it a no-op)
|
||||
- [ ] Verify: lyrics review page works without stems present
|
||||
|
||||
#### Step 3.2 — Add "waiting for separation" state to instrumental review
|
||||
- [ ] In frontend instrumental review page (`/app/jobs#/{jobId}/instrumental`):
|
||||
- Check `state_data.audio_complete` on page load
|
||||
- If false, show "Audio separation in progress..." with a spinner/progress indicator
|
||||
- Poll job status every 5-10 seconds until `audio_complete=True`
|
||||
- Once complete, load and display instrumental options as normal
|
||||
- [ ] Backend: ensure instrumental review API endpoint returns separation status
|
||||
|
||||
#### Step 3.3 — Switch to preset-based model configuration
|
||||
- [ ] In `backend/workers/audio_worker.py`:
|
||||
- Replace `DEFAULT_CLEAN_MODEL` with `DEFAULT_INSTRUMENTAL_PRESET = "instrumental_clean"`
|
||||
- Replace `DEFAULT_BACKING_MODELS` with `DEFAULT_KARAOKE_PRESET = "karaoke"`
|
||||
- Remove `DEFAULT_OTHER_MODELS` (Demucs dropped)
|
||||
- Pass `preset=` parameter to API client instead of `models=`
|
||||
- [ ] In `karaoke_gen/audio_processor.py`:
|
||||
- Update `_process_audio_separation_remote()` to pass presets
|
||||
- Stage 1: `api_client.separate_audio_and_wait(audio_file, preset="instrumental_clean", ...)`
|
||||
- Stage 2: `api_client.separate_audio_and_wait(vocals_file, preset="karaoke", ...)`
|
||||
- Remove `other_stems_models` parameter (or default to empty)
|
||||
- Update result organization for ensemble outputs (stem names may include ensemble info)
|
||||
- [ ] In `audio_separator/remote/api_client.py` (python-audio-separator repo):
|
||||
- Add `preset` parameter to `separate_audio()` and `separate_audio_and_wait()`
|
||||
- Client passes `preset` field in multipart form data to API
|
||||
- API server resolves preset → models + algorithm
|
||||
|
||||
#### Step 3.4 — Update tests
|
||||
- [ ] Update `tests/unit/test_audio_remote.py`:
|
||||
- Test preset-based separation calls
|
||||
- Remove Demucs 6-stem references
|
||||
- Test new default model/preset names
|
||||
- [ ] Add test for pipeline decoupling:
|
||||
- Verify `mark_lyrics_complete()` triggers screens without `audio_complete`
|
||||
- Verify `mark_audio_complete()` sets flag but doesn't trigger screens
|
||||
- [ ] Add frontend test for instrumental review waiting state
|
||||
|
||||
### Phase 4: Cutover & Cleanup
|
||||
|
||||
#### Step 4.1 — Deploy and test
|
||||
- [ ] Deploy Cloud Run GPU service via `pulumi up`
|
||||
- [ ] Run separation on 3-5 test songs with ensemble presets
|
||||
- [ ] Compare output quality to Modal (listen test)
|
||||
- [ ] Verify timing: ensemble separation completes within ~8-12 min
|
||||
- [ ] Test cold start scenario (wait for scale-down, then submit)
|
||||
- [ ] Test back-to-back jobs (Stage 1 → Stage 2 hits warm instance)
|
||||
- [ ] Test pipeline decoupling: verify lyrics review available before separation completes
|
||||
- [ ] Test instrumental review waiting state
|
||||
|
||||
#### Step 4.2 — Update Cloud Run audio worker config
|
||||
- [ ] Change `AUDIO_SEPARATOR_API_URL` in `infrastructure/modules/cloud_run.py` from Modal URL to Cloud Run URL
|
||||
- [ ] Deploy via `pulumi up`
|
||||
- [ ] Run 5-10 production jobs, monitor for errors
|
||||
|
||||
#### Step 4.3 — Monitor (1 week)
|
||||
- [ ] Watch Cloud Run logs for errors
|
||||
- [ ] Monitor separation timing in job state_data
|
||||
- [ ] Check Cloud Run billing (verify per-job cost < $1)
|
||||
- [ ] Verify scale-to-zero works (no idle GPU charges)
|
||||
- [ ] Watch for users hitting the "waiting for separation" state — measure frequency
|
||||
|
||||
#### Step 4.4 — Decommission Modal
|
||||
- [ ] Remove Modal deployment workflow from python-audio-separator repo
|
||||
- [ ] Delete Modal app
|
||||
- [ ] Close Modal account
|
||||
- [ ] Remove `modal` from python-audio-separator dependencies
|
||||
- [ ] Update `AUDIO_SEPARATOR_API_URL` env var in local `.envrc` files
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
### python-audio-separator repo (`python-audio-separator-modal-gcp-migration` worktree)
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `audio_separator/remote/deploy_cloudrun.py` | Create | Cloud Run-compatible FastAPI server (adapted from deploy_modal.py) |
|
||||
| `audio_separator/remote/api_client.py` | Modify | Add `preset` parameter to separate methods |
|
||||
| `Dockerfile.cloudrun` | Create | Docker image for Cloud Run GPU deployment |
|
||||
| `.github/workflows/deploy-to-cloudrun.yml` | Create | CI/CD: build image → push to Artifact Registry |
|
||||
|
||||
### karaoke-gen repo (`karaoke-gen-modal-gcp-migration` worktree)
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `infrastructure/modules/audio_separator_service.py` | Create | Pulumi: Cloud Run GPU service + model bucket + IAM |
|
||||
| `infrastructure/__main__.py` | Modify | Wire up audio separator service |
|
||||
| `infrastructure/config.py` | Modify | Add audio separator constants |
|
||||
| `infrastructure/modules/cloud_run.py` | Modify | Update `AUDIO_SEPARATOR_API_URL` to Cloud Run URL |
|
||||
| `backend/services/job_manager.py` | Modify | Decouple: lyrics_complete alone triggers screens |
|
||||
| `backend/workers/screens_worker.py` | Modify | Remove audio_complete prerequisite |
|
||||
| `backend/workers/audio_worker.py` | Modify | Switch to preset-based config, drop Demucs |
|
||||
| `karaoke_gen/audio_processor.py` | Modify | Pass presets instead of model filenames |
|
||||
| `frontend/` (instrumental review) | Modify | Add "waiting for separation" state |
|
||||
| `tests/unit/test_audio_remote.py` | Modify | Update for presets, remove Demucs tests |
|
||||
| `.github/workflows/deploy-audio-separator.yml` | Create | CI: deploy Cloud Run revision on image push |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests:** Preset resolution, pipeline decoupling (lyrics triggers screens alone), model name updates
|
||||
- **Integration test:** Deploy Cloud Run service, run full separation with ensemble presets, verify output files
|
||||
- **A/B comparison:** Same songs through Modal (single model) and Cloud Run (ensemble) — quality should be better
|
||||
- **Pipeline test:** Submit job, verify lyrics review available before separation completes
|
||||
- **Frontend test:** Playwright E2E for instrumental review waiting state
|
||||
- **Cold start test:** Wait for scale-down, submit job, measure total time
|
||||
- **Production E2E:** After cutover, run 10 production jobs through full pipeline
|
||||
|
||||
## Cost Estimate
|
||||
|
||||
| Scenario | Monthly cost |
|
||||
|----------|-------------|
|
||||
| 10 jobs/day × 12 min GPU = 2 hrs/day | ~$40/mo |
|
||||
| 30 jobs/day × 12 min GPU = 6 hrs/day | ~$120/mo |
|
||||
| Per-job cost (12 min L4 @ $0.67/hr) | ~$0.13 |
|
||||
|
||||
Well under $1/job budget. No idle cost due to scale-to-zero.
|
||||
|
||||
## Resolved Questions
|
||||
|
||||
- [x] Cloud Run vs GCE VM → **Cloud Run GPU Service** (simplest, scale-to-zero)
|
||||
- [x] Which GPU → **L4** (only option on Cloud Run, 24GB VRAM)
|
||||
- [x] Model upgrade → **Ensemble presets as default** (quality > speed)
|
||||
- [x] Demucs 6-stem → **Drop it**
|
||||
- [x] Auth → **Reuse existing `admin-tokens` secret**
|
||||
- [x] Docker CI → **python-audio-separator repo builds + pushes image**
|
||||
- [x] Ensemble presets UI → **Backend-only; presets defined in audio-separator package**
|
||||
- [x] Speed vs quality → **Quality wins; decouple separation from critical path so user never waits**
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
1. **Quick rollback:** Change `AUDIO_SEPARATOR_API_URL` back to Modal URL in Pulumi config, `pulumi up`. Takes ~2 minutes.
|
||||
2. **Pipeline rollback:** Revert job_manager changes to re-gate screens on `audio_complete`. One commit.
|
||||
3. **Keep Modal running** during the monitoring period (Phase 4.3). Don't decommission until confident.
|
||||
4. **Model rollback:** Preset config can be changed back to direct model filenames in one commit.
|
||||
@@ -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.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,431 @@
|
||||
# Fix ASS Preview/Render Divergence — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Eliminate the divergence between preview and final render by unifying Word text sanitization and CorrectionResult construction, preventing embedded newlines from corrupting ASS subtitle output.
|
||||
|
||||
**Architecture:** Strip whitespace in `Word.__post_init__` (single source of truth for Word invariants), add defensive strip in ASS output, refactor render worker to use the shared `update_correction_result_with_data()` method, and document the lesson learned.
|
||||
|
||||
**Tech Stack:** Python dataclasses, ASS subtitle format, FastAPI workers
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-03-22-fix-ass-preview-render-divergence-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| File | Responsibility | Change |
|
||||
|------|---------------|--------|
|
||||
| `karaoke_gen/lyrics_transcriber/types.py` | Word/Segment data types | Add `__post_init__` to strip text |
|
||||
| `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py` | ASS dialogue event generation | Defensive strip in `_create_ass_text()` |
|
||||
| `backend/workers/render_video_worker.py` | Final video render orchestration | Use `update_correction_result_with_data()` |
|
||||
| `karaoke_gen/lyrics_transcriber/correction/operations.py` | Shared correction operations | Remove redundant `.strip()` calls |
|
||||
| `docs/LESSONS-LEARNED.md` | Project knowledge base | Document this bug class |
|
||||
| `tests/unit/test_word_text_sanitization.py` | New test file | Word stripping + ASS output tests |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add `__post_init__` to Word dataclass
|
||||
|
||||
**Files:**
|
||||
- Modify: `karaoke_gen/lyrics_transcriber/types.py:7-37`
|
||||
- Create: `tests/unit/test_word_text_sanitization.py`
|
||||
|
||||
- [ ] **Step 1: Create test file with failing tests for Word text stripping**
|
||||
|
||||
Create `tests/unit/test_word_text_sanitization.py`:
|
||||
|
||||
```python
|
||||
"""Tests for Word text sanitization — ensures embedded newlines never reach ASS output."""
|
||||
|
||||
import pytest
|
||||
from karaoke_gen.lyrics_transcriber.types import Word, LyricsSegment
|
||||
|
||||
|
||||
class TestWordTextSanitization:
|
||||
"""Word.__post_init__ must strip whitespace/newlines from text."""
|
||||
|
||||
def test_trailing_newline_stripped(self):
|
||||
word = Word(id="w1", text="spell\n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_trailing_double_newline_stripped(self):
|
||||
word = Word(id="w1", text="end\n\n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "end"
|
||||
|
||||
def test_leading_whitespace_stripped(self):
|
||||
word = Word(id="w1", text=" hello", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "hello"
|
||||
|
||||
def test_mixed_whitespace_stripped(self):
|
||||
word = Word(id="w1", text="\n spell \n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_clean_text_unchanged(self):
|
||||
word = Word(id="w1", text="hello", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "hello"
|
||||
|
||||
def test_from_dict_strips_text(self):
|
||||
"""from_dict must also strip — this was the original bug."""
|
||||
word = Word.from_dict({
|
||||
"id": "w1",
|
||||
"text": "spell\n",
|
||||
"start_time": 1.0,
|
||||
"end_time": 2.0,
|
||||
})
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_from_dict_with_double_newline(self):
|
||||
word = Word.from_dict({
|
||||
"id": "w1",
|
||||
"text": "broken\n\n",
|
||||
"start_time": 1.0,
|
||||
"end_time": 2.0,
|
||||
})
|
||||
assert word.text == "broken"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify they fail**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
|
||||
|
||||
Expected: 5 FAIL (trailing newlines not stripped), 2 PASS (clean text, leading whitespace might pass by accident)
|
||||
|
||||
- [ ] **Step 3: Add `__post_init__` to Word dataclass**
|
||||
|
||||
In `karaoke_gen/lyrics_transcriber/types.py`, add after line 17 (after `created_during_correction` field):
|
||||
|
||||
```python
|
||||
def __post_init__(self):
|
||||
"""Strip whitespace/newlines from text.
|
||||
|
||||
Word text from transcription pipelines may contain embedded newline
|
||||
characters at segment boundaries (e.g., "spell\\n"). These corrupt ASS
|
||||
subtitle output by splitting dialogue events across file lines, causing
|
||||
words after the newline to be silently dropped by video renderers.
|
||||
"""
|
||||
self.text = self.text.strip()
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests to verify they pass**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
|
||||
|
||||
Expected: All 7 PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add karaoke_gen/lyrics_transcriber/types.py tests/unit/test_word_text_sanitization.py
|
||||
git commit -m "fix: strip whitespace/newlines from Word text in __post_init__
|
||||
|
||||
Embedded newlines in word text (e.g. 'spell\n') corrupt ASS subtitle
|
||||
dialogue events by splitting them across file lines. Words after the
|
||||
newline are silently dropped by the video renderer.
|
||||
|
||||
This was the root cause of lyrics missing in final renders but
|
||||
appearing correctly in previews (job 0d4b550c)."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Add defensive strip in ASS output
|
||||
|
||||
**Files:**
|
||||
- Modify: `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py:237-262`
|
||||
- Modify: `tests/unit/test_word_text_sanitization.py`
|
||||
|
||||
- [ ] **Step 1: Add test for ASS text generation with newline words**
|
||||
|
||||
Append to `tests/unit/test_word_text_sanitization.py`:
|
||||
|
||||
```python
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.lyrics_line import LyricsLine
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.config import ScreenConfig
|
||||
|
||||
|
||||
class TestASSOutputSanitization:
|
||||
"""ASS output must never contain literal newlines in dialogue text."""
|
||||
|
||||
def _make_segment(self, words_data):
|
||||
"""Helper to create a LyricsSegment from word tuples (text, start, end)."""
|
||||
words = [
|
||||
Word(id=f"w{i}", text=text, start_time=start, end_time=end)
|
||||
for i, (text, start, end) in enumerate(words_data)
|
||||
]
|
||||
text = " ".join(w.text for w in words)
|
||||
return LyricsSegment(
|
||||
id="seg1", text=text, words=words,
|
||||
start_time=words[0].start_time, end_time=words[-1].end_time,
|
||||
)
|
||||
|
||||
def test_ass_text_no_literal_newlines(self):
|
||||
"""Even if Word.__post_init__ were bypassed, ASS output must not contain newlines."""
|
||||
segment = self._make_segment([
|
||||
("the", 54.11, 54.26),
|
||||
("spell", 54.30, 55.14),
|
||||
("we're", 55.18, 55.83),
|
||||
("under", 55.93, 57.24),
|
||||
])
|
||||
config = ScreenConfig(line_height=50)
|
||||
line = LyricsLine(segment=segment, screen_config=config)
|
||||
# Access the private method to test ASS text generation
|
||||
from datetime import timedelta
|
||||
ass_text = line._create_ass_text(timedelta(seconds=54.0))
|
||||
assert "\n" not in ass_text, f"ASS text contains literal newline: {repr(ass_text)}"
|
||||
assert "the" in ass_text
|
||||
assert "spell" in ass_text
|
||||
assert "we're" in ass_text
|
||||
assert "under" in ass_text
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it passes (Word.__post_init__ already strips)**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py::TestASSOutputSanitization -v`
|
||||
|
||||
Expected: PASS (Word.__post_init__ already strips newlines, so this test passes with current code)
|
||||
|
||||
- [ ] **Step 3: Add defensive strip in `_create_ass_text()`**
|
||||
|
||||
In `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py`, change line 257-258 from:
|
||||
|
||||
```python
|
||||
# Apply case transformation to the word text
|
||||
transformed_text = self._apply_case_transform(word.text)
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```python
|
||||
# Apply case transformation to the word text
|
||||
# Defensive strip: Word.__post_init__ should already handle this,
|
||||
# but embedded newlines in ASS dialogue events cause silent word
|
||||
# loss so we guard against it at the output boundary too.
|
||||
clean_word_text = word.text.replace("\n", "").strip()
|
||||
transformed_text = self._apply_case_transform(clean_word_text)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run all sanitization tests**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
|
||||
|
||||
Expected: All PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py tests/unit/test_word_text_sanitization.py
|
||||
git commit -m "fix: defensive strip in ASS output as safety net
|
||||
|
||||
Belt-and-suspenders guard at the ASS output boundary. Even though
|
||||
Word.__post_init__ strips newlines, this prevents any future bypass
|
||||
from producing corrupted ASS dialogue events."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Refactor render worker to use shared CorrectionResult construction
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/workers/render_video_worker.py:153-188`
|
||||
|
||||
- [ ] **Step 1: Refactor the merge logic**
|
||||
|
||||
In `backend/workers/render_video_worker.py`, add the import at the top (after existing lyrics_transcriber imports around line 47):
|
||||
|
||||
```python
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
```
|
||||
|
||||
Then replace the merge logic at lines 164-188. Change from:
|
||||
|
||||
```python
|
||||
# 3. Check if there are updated corrections (from review UI)
|
||||
# The frontend sends only partial data: {corrections, corrected_segments}
|
||||
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
if storage.file_exists(updated_corrections_gcs):
|
||||
job_log.info("Found updated corrections from review, merging")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, merging")
|
||||
updated_path = os.path.join(temp_dir, "corrections_updated.json")
|
||||
storage.download_file(updated_corrections_gcs, updated_path)
|
||||
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
|
||||
# Merge: update the original with the user's corrections
|
||||
if 'corrections' in updated_data:
|
||||
original_data['corrections'] = updated_data['corrections']
|
||||
if 'corrected_segments' in updated_data:
|
||||
original_data['corrected_segments'] = updated_data['corrected_segments']
|
||||
|
||||
job_log.info("Merged user corrections into original data")
|
||||
logger.info(f"Job {job_id}: Merged user corrections into original data")
|
||||
|
||||
# 4. Convert to CorrectionResult
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```python
|
||||
# 3. Load base CorrectionResult from original data
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# 4. Apply user corrections if available (from review UI)
|
||||
# Uses the same method as preview generation to ensure
|
||||
# identical CorrectionResult construction (DRY).
|
||||
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
if storage.file_exists(updated_corrections_gcs):
|
||||
job_log.info("Found updated corrections from review, applying via shared method")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
|
||||
updated_path = os.path.join(temp_dir, "corrections_updated.json")
|
||||
storage.download_file(updated_corrections_gcs, updated_path)
|
||||
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
|
||||
# Same construction path as preview — prevents divergence
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
job_log.info("Applied user corrections via CorrectionOperations")
|
||||
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run existing tests to check for regressions**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/ -v --timeout=60 -x -q 2>&1 | tail -30`
|
||||
|
||||
Expected: All existing tests pass
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add backend/workers/render_video_worker.py
|
||||
git commit -m "refactor: use shared CorrectionResult construction in render worker
|
||||
|
||||
Replace manual dict merge + from_dict() with the same
|
||||
update_correction_result_with_data() method used by preview generation.
|
||||
This eliminates the code path divergence that caused the preview/render
|
||||
ASS subtitle discrepancy."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Clean up redundant `.strip()` in `update_correction_result_with_data()`
|
||||
|
||||
**Files:**
|
||||
- Modify: `karaoke_gen/lyrics_transcriber/correction/operations.py:39-99`
|
||||
|
||||
- [ ] **Step 1: Remove redundant `.strip()` from Word text construction only**
|
||||
|
||||
In `karaoke_gen/lyrics_transcriber/correction/operations.py`, the `update_correction_result_with_data` method (lines 39-99) has `.strip()` on several text fields. Only the `Word` text strip (line 74) is now redundant thanks to `Word.__post_init__`. The others operate on `WordCorrection` fields or `LyricsSegment` text which don't have `__post_init__` — those must stay.
|
||||
|
||||
Change line 74 from:
|
||||
```python
|
||||
text=w["text"].strip(),
|
||||
```
|
||||
to:
|
||||
```python
|
||||
text=w["text"],
|
||||
```
|
||||
|
||||
**Keep** `.strip()` on lines 47, 48, and 70 — those are `WordCorrection.original_word`, `WordCorrection.corrected_word`, and `LyricsSegment.text` respectively, which are not protected by `Word.__post_init__`.
|
||||
|
||||
- [ ] **Step 2: Run all tests**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v && poetry run pytest tests/ -v --timeout=60 -x -q 2>&1 | tail -30`
|
||||
|
||||
Expected: All PASS
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add karaoke_gen/lyrics_transcriber/correction/operations.py
|
||||
git commit -m "refactor: remove redundant .strip() from update_correction_result_with_data
|
||||
|
||||
Word.__post_init__ now handles text stripping. Removing the redundant
|
||||
calls makes it clear that sanitization is Word's responsibility, not
|
||||
the caller's."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Document lesson learned
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/LESSONS-LEARNED.md`
|
||||
|
||||
- [ ] **Step 1: Add the lesson to the Architecture Decisions section**
|
||||
|
||||
In `docs/LESSONS-LEARNED.md`, add a new subsection after the existing "Architecture Decisions" entries (after line ~58). Insert:
|
||||
|
||||
```markdown
|
||||
### Data Types Must Enforce Their Own Invariants (Mar 2026)
|
||||
When a data type has constraints on its fields (e.g., "word text must not contain newlines"), enforce them in the type's constructor (`__post_init__`), not in callers. This bug was caused by `Word` objects being constructed via two different code paths — one that stripped newlines (preview) and one that didn't (final render). The preview accidentally worked while final renders had corrupted subtitles with silently dropped lyrics. The fix: `Word.__post_init__` strips whitespace so ALL construction paths are safe, plus a defensive strip at the ASS output boundary.
|
||||
|
||||
**Key principles:**
|
||||
- **Single source of truth for data invariants** — the type, not the caller, is responsible for field constraints
|
||||
- **Defensive output boundaries** — even with clean inputs, validate at system boundaries (ASS file writing) as a safety net
|
||||
- **Two code paths doing "the same thing" will diverge** — if preview and render both construct CorrectionResult, they must use the same method, not reimplementations
|
||||
|
||||
**Detection clue:** If `corrected.txt` shows correct lyrics but the video is missing words, check for embedded newlines in Word text corrupting ASS dialogue events.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add docs/LESSONS-LEARNED.md
|
||||
git commit -m "docs: document data type invariant enforcement lesson
|
||||
|
||||
Records the Word text newline bug, the architectural principle it
|
||||
violated, and detection clues for similar issues."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Run full test suite and verify
|
||||
|
||||
- [ ] **Step 1: Run the full test suite**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/ -v --timeout=120 -q 2>&1 | tail -40`
|
||||
|
||||
Expected: All tests pass, no regressions
|
||||
|
||||
- [ ] **Step 2: Verify the fix would solve the original bug**
|
||||
|
||||
Run a quick sanity check that Word objects with the problematic data from job `0d4b550c` are now clean:
|
||||
|
||||
```python
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run python -c "
|
||||
from karaoke_gen.lyrics_transcriber.types import Word
|
||||
# Simulate the exact data from the buggy job
|
||||
w1 = Word(id='test', text='spell\n', start_time=54.30, end_time=55.14)
|
||||
w2 = Word.from_dict({'id': 'test', 'text': 'broken\n\n', 'start_time': 59.98, 'end_time': 61.54})
|
||||
assert w1.text == 'spell', f'Expected spell, got {repr(w1.text)}'
|
||||
assert w2.text == 'broken', f'Expected broken, got {repr(w2.text)}'
|
||||
print('PASS: Word text sanitization works correctly')
|
||||
"
|
||||
```
|
||||
|
||||
Expected: `PASS: Word text sanitization works correctly`
|
||||
|
||||
- [ ] **Step 3: Bump version**
|
||||
|
||||
In `pyproject.toml`, bump the patch version (this is a bugfix).
|
||||
|
||||
- [ ] **Step 4: Final commit with version bump**
|
||||
|
||||
```bash
|
||||
git add pyproject.toml
|
||||
git commit -m "chore: bump version for ASS preview/render divergence fix"
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,122 @@
|
||||
# Auto-Updating Disposable Email Blocklist
|
||||
|
||||
## Problem
|
||||
|
||||
The disposable email blocklist is maintained manually — ~160 hardcoded domains in Python plus admin UI additions. New disposable email services appear frequently, and the list falls behind. The community-curated [disposable-email-domains](https://github.com/disposable-email-domains/disposable-email-domains) repo tracks ~4,800 domains and updates regularly.
|
||||
|
||||
## Solution
|
||||
|
||||
Automatically sync the external blocklist daily, while preserving admin control to add custom domains and allowlist false positives.
|
||||
|
||||
## Data Model
|
||||
|
||||
The Firestore `blocklists/config` document is restructured:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `external_domains` | list[str] | Domains synced from the GitHub repo (~4,800). Auto-managed. |
|
||||
| `manual_domains` | list[str] | Domains added by admins via UI. Persist across syncs. |
|
||||
| `allowlisted_domains` | list[str] | Domains explicitly permitted, overriding the external list. |
|
||||
| `blocked_emails` | list[str] | Unchanged. |
|
||||
| `blocked_ips` | list[str] | Unchanged. |
|
||||
| `last_sync_at` | timestamp | Last successful external sync. |
|
||||
| `last_sync_count` | int | Number of domains in the external list at last sync. |
|
||||
| `updated_at` | timestamp | Last manual change. |
|
||||
| `updated_by` | str | Admin who made the last manual change. |
|
||||
|
||||
**Effective blocklist** = `(external_domains + manual_domains) - allowlisted_domains`
|
||||
|
||||
The hardcoded `DEFAULT_DISPOSABLE_DOMAINS` set in Python is removed.
|
||||
|
||||
**Document size**: At ~4,800 domains averaging 15 chars each, `external_domains` is ~80 KB — well within Firestore's 1 MiB document limit. The list has grown slowly (~100 domains/year). If it ever exceeds 20,000 domains, migrate to a subcollection. Cache misses will transfer ~80 KB instead of ~3 KB, but the 5-minute TTL means this happens rarely.
|
||||
|
||||
## Sync Endpoint
|
||||
|
||||
**`POST /api/internal/sync-disposable-domains`**
|
||||
|
||||
- Authenticated via `X-Admin-Token` (same as other internal endpoints)
|
||||
- Fetches `https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/refs/heads/main/disposable_email_blocklist.conf`
|
||||
- Parses as newline-delimited text (one domain per line), strips whitespace/blanks
|
||||
- Replaces `external_domains` in Firestore (full replacement, not incremental)
|
||||
- Updates `last_sync_at` and `last_sync_count`
|
||||
- Invalidates the in-memory cache
|
||||
- Returns summary: domains added/removed since last sync, total count
|
||||
- On fetch failure: returns error, existing list stays intact
|
||||
- Safety limits: 30-second request timeout, reject if response exceeds 2 MB or 50,000 domains
|
||||
- During sync, any `manual_domains` entries that now appear in the fetched external list are automatically removed from `manual_domains` (they're redundant)
|
||||
|
||||
**Cache behavior**: The sync invalidates the cache on the instance handling the request. Other Cloud Run instances may serve stale data for up to 5 minutes (their TTL). This is acceptable for a daily sync.
|
||||
|
||||
**Trigger:** Cloud Scheduler, daily at 3:00 AM UTC. Also callable manually from the admin UI via a "Sync Now" button.
|
||||
|
||||
## Admin UI Changes
|
||||
|
||||
The Blocklists tab at `/admin/rate-limits` is updated:
|
||||
|
||||
### Disposable Domains Section (three sub-sections)
|
||||
|
||||
1. **External Domains** (~4,800) — Read-only list with search/filter. Badge: "external". Shows `last_sync_at` and count. Removing an external domain moves it to the Allowlist.
|
||||
|
||||
2. **Manual Domains** — Existing add/remove behavior. Badge: "manual". For domains admins discover that aren't in the external list.
|
||||
|
||||
3. **Allowlisted Domains** — Domains explicitly permitted despite being on the external list. Badge: "allowed". Removing from the allowlist re-enables blocking.
|
||||
|
||||
### Sync Status Bar
|
||||
|
||||
At the top of the Disposable Domains section: last sync time, domain count, and "Sync Now" button.
|
||||
|
||||
### Unchanged
|
||||
|
||||
Blocked emails and blocked IPs sections remain as-is.
|
||||
|
||||
## Backward Compatibility
|
||||
|
||||
`get_blocklist_config()` continues to return `{"disposable_domains": <set>, "blocked_emails": <set>, "blocked_ips": <set>}`. Internally it computes the effective set from the three new fields. `is_disposable_domain()` and all other callers remain unchanged.
|
||||
|
||||
The GET `/api/admin/rate-limits/blocklists` response is updated to include:
|
||||
- `external_domains`: list (the synced domains)
|
||||
- `manual_domains`: list (admin-added domains)
|
||||
- `allowlisted_domains`: list (override domains)
|
||||
- `last_sync_at`: ISO timestamp or null
|
||||
- `last_sync_count`: int or null
|
||||
- Plus existing `blocked_emails` and `blocked_ips`
|
||||
|
||||
The old `disposable_domains` response field is removed (breaking change for the admin UI only, updated in the same PR).
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
The sync endpoint handles migration on first run:
|
||||
|
||||
1. Detect migration needed: `external_domains` field doesn't exist yet
|
||||
2. Build the current effective set: Firestore `disposable_domains` UNION Python `DEFAULT_DISPOSABLE_DOMAINS`
|
||||
3. Compare against the fetched external list
|
||||
4. Domains in both → covered by `external_domains` (no action)
|
||||
5. Domains only in the current effective set → moved to `manual_domains` (preserves admin additions and hardcoded extras)
|
||||
6. Remove old `disposable_domains` field
|
||||
7. Remove hardcoded `DEFAULT_DISPOSABLE_DOMAINS` from Python — fallback becomes empty set if Firestore unreachable (cached data covers outages)
|
||||
|
||||
Subsequent sync runs just replace `external_domains`.
|
||||
|
||||
## Domain Source Resolution
|
||||
|
||||
When displaying or operating on domains:
|
||||
|
||||
- A domain in `external_domains` → source: "external"
|
||||
- A domain in `manual_domains` → source: "manual"
|
||||
- A domain in `allowlisted_domains` → source: "allowed" (not blocked)
|
||||
- A domain in both `external_domains` and `manual_domains` → source: "external" (manual entry is redundant)
|
||||
|
||||
## Testing
|
||||
|
||||
- **Unit tests**: Sync parsing, migration logic, allowlist override, effective blocklist computation, source tagging
|
||||
- **Integration tests**: Full sync endpoint with Firestore emulator, cache invalidation after sync
|
||||
- **E2E tests**: Admin UI — source badges, sync button, allowlist flow (remove external domain → appears in allowlist → remove from allowlist → blocked again)
|
||||
|
||||
## Infrastructure
|
||||
|
||||
- **Cloud Scheduler job**: Created via Pulumi in `infrastructure/`. Daily at 3:00 AM UTC, hits the sync endpoint with admin token from Secret Manager.
|
||||
- **No new services**: Runs on existing Cloud Run backend.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Wildcard/subdomain matching (the repo also publishes `disposable_email_blocklist_with_wildcards.conf` — deferred)
|
||||
@@ -0,0 +1,99 @@
|
||||
# Fix ASS Preview/Render Divergence
|
||||
|
||||
**Date:** 2026-03-22
|
||||
**Status:** Approved
|
||||
**Job that exposed bug:** `0d4b550c` (The Ataris - All Souls Day)
|
||||
|
||||
## Problem
|
||||
|
||||
Lyrics that render correctly in the preview video are missing words in the final (with_vocals / final) video output. The root cause is that Word objects contain embedded newline characters (e.g., `"spell\n"`, `"broken\n"`) inherited from the transcription pipeline's segment boundary markers. These newlines corrupt ASS subtitle dialogue events by splitting them across file lines, causing the video renderer to silently drop words after the newline.
|
||||
|
||||
The preview path accidentally avoids this bug because `CorrectionOperations.update_correction_result_with_data()` calls `.strip()` on word text, while the final render path uses `Word.from_dict()` which does not strip.
|
||||
|
||||
## Root Cause Analysis
|
||||
|
||||
### Two divergent CorrectionResult construction paths
|
||||
|
||||
**Preview** (`review.py` → `CorrectionOperations.generate_preview_video()`):
|
||||
1. Downloads `corrections.json` → `CorrectionResult.from_dict()`
|
||||
2. Calls `update_correction_result_with_data(result, updated_data)` which constructs new Word objects with `text=w["text"].strip()` — newlines removed
|
||||
|
||||
**Final render** (`render_video_worker.py`):
|
||||
1. Downloads `corrections.json` + `corrections_updated.json`
|
||||
2. Manually merges dicts: replaces `corrections` and `corrected_segments` keys
|
||||
3. Calls `CorrectionResult.from_dict(merged_data)` which constructs Word objects with `text=data["text"]` — newlines preserved
|
||||
4. Newlines in word text corrupt ASS output in `LyricsLine._create_ass_text()`
|
||||
|
||||
### Why only some segments are affected
|
||||
|
||||
Newlines appear on words at segment boundaries from the original transcription (e.g., `"spell\n"` where a line break was detected). When the segment resizer splits a long segment, a word with an embedded newline may end up in the middle of a resized segment rather than at the end. When it's at the end, the newline is harmless trailing whitespace. When it's in the middle, it splits the ASS dialogue event.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Strip in `Word.__post_init__`
|
||||
|
||||
Add text stripping to the Word dataclass `__post_init__` so ALL Word objects are guaranteed clean regardless of construction method:
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class Word:
|
||||
...
|
||||
def __post_init__(self):
|
||||
# Strip whitespace/newlines — embedded newlines corrupt ASS subtitle output
|
||||
self.text = self.text.strip()
|
||||
```
|
||||
|
||||
This is the single-responsibility fix: Word is responsible for its own invariants.
|
||||
|
||||
### 2. Defensive strip in `_create_ass_text()`
|
||||
|
||||
Belt-and-suspenders safety net in the ASS output layer:
|
||||
|
||||
```python
|
||||
# In LyricsLine._create_ass_text():
|
||||
transformed_text = self._apply_case_transform(word.text.replace("\n", "").strip())
|
||||
```
|
||||
|
||||
### 3. Refactor render_video_worker to use shared construction method
|
||||
|
||||
Replace the manual dict merge + `from_dict()` with `CorrectionOperations.update_correction_result_with_data()` — the same method the preview uses:
|
||||
|
||||
```python
|
||||
# Before (render_video_worker.py):
|
||||
if 'corrections' in updated_data:
|
||||
original_data['corrections'] = updated_data['corrections']
|
||||
if 'corrected_segments' in updated_data:
|
||||
original_data['corrected_segments'] = updated_data['corrected_segments']
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# After:
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
```
|
||||
|
||||
### 4. Clean up redundant `.strip()` in `update_correction_result_with_data()`
|
||||
|
||||
Since `Word.__post_init__` now handles stripping, remove the explicit `.strip()` calls in `update_correction_result_with_data()` to avoid giving the impression that stripping is the caller's responsibility.
|
||||
|
||||
### 5. Document the lesson learned
|
||||
|
||||
Add to `docs/LESSONS-LEARNED.md` documenting this class of bug and the architectural principle that prevented its recurrence.
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `karaoke_gen/lyrics_transcriber/types.py` | Add `__post_init__` to Word, strip text |
|
||||
| `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py` | Defensive strip in `_create_ass_text()` |
|
||||
| `backend/workers/render_video_worker.py` | Use `update_correction_result_with_data()` instead of manual merge |
|
||||
| `karaoke_gen/lyrics_transcriber/correction/operations.py` | Remove redundant `.strip()` calls |
|
||||
| `docs/LESSONS-LEARNED.md` | Document the bug and fix |
|
||||
| Tests | Unit tests for Word stripping, integration test for ASS output |
|
||||
|
||||
## What This Does NOT Change
|
||||
|
||||
- The preview and final render still generate separate ASS files (necessary due to resolution-dependent positioning: 360p vs 4K)
|
||||
- The data flow: frontend → GCS → worker remains the same
|
||||
- No changes to the frontend
|
||||
@@ -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.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -57,6 +57,8 @@ function AdminBreadcrumb() {
|
||||
breadcrumbs.push({ label: "Payments" })
|
||||
} else if (segments[1] === "rate-limits") {
|
||||
breadcrumbs.push({ label: "Rate Limits" })
|
||||
} else if (segments[1] === "abuse") {
|
||||
breadcrumbs.push({ label: "Abuse Investigation" })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,9 +22,14 @@ jest.mock("@/lib/api", () => ({
|
||||
removeBlockedEmail: jest.fn(),
|
||||
addBlockedIP: jest.fn(),
|
||||
removeBlockedIP: jest.fn(),
|
||||
syncDisposableDomains: jest.fn(),
|
||||
addAllowlistedDomain: jest.fn(),
|
||||
removeAllowlistedDomain: jest.fn(),
|
||||
getYouTubeQueue: jest.fn(),
|
||||
retryYouTubeUpload: jest.fn(),
|
||||
processYouTubeQueue: jest.fn(),
|
||||
getIpInfo: jest.fn().mockResolvedValue({ status: "success", ip: "192.168.1.100", country_code: "US", isp: "Test ISP" }),
|
||||
getIpInfoBatch: jest.fn().mockResolvedValue({}),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -41,11 +46,15 @@ import { adminApi } from "@/lib/api"
|
||||
|
||||
const mockAdminApi = adminApi as jest.Mocked<typeof adminApi>
|
||||
|
||||
// Mock data
|
||||
// Mock data — new data model with external/manual/allowlisted
|
||||
const mockBlocklists = {
|
||||
disposable_domains: ["tempmail.com", "mailinator.com", "guerrillamail.com"],
|
||||
external_domains: ["tempmail.com", "mailinator.com", "guerrillamail.com"],
|
||||
manual_domains: ["custom-spam.com"],
|
||||
allowlisted_domains: ["false-positive.com"],
|
||||
blocked_emails: ["spammer@example.com", "abuse@test.com"],
|
||||
blocked_ips: ["192.168.1.100"],
|
||||
last_sync_at: "2025-01-09T10:00:00Z",
|
||||
last_sync_count: 4800,
|
||||
updated_at: "2025-01-09T10:00:00Z",
|
||||
updated_by: "admin@nomadkaraoke.com",
|
||||
}
|
||||
@@ -138,7 +147,7 @@ describe("AdminRateLimitsPage", () => {
|
||||
})
|
||||
|
||||
describe("Blocklists Tab", () => {
|
||||
it("displays disposable domains list", async () => {
|
||||
it("displays external domains", async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<AdminRateLimitsPage />)
|
||||
|
||||
@@ -148,12 +157,12 @@ describe("AdminRateLimitsPage", () => {
|
||||
|
||||
await user.click(screen.getByRole("tab", { name: /blocklists/i }))
|
||||
|
||||
// Should show domains
|
||||
// Should show external domains
|
||||
expect(screen.getByText("tempmail.com")).toBeInTheDocument()
|
||||
expect(screen.getByText("mailinator.com")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("filters domains by search", async () => {
|
||||
it("displays manual domains", async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<AdminRateLimitsPage />)
|
||||
|
||||
@@ -163,16 +172,28 @@ describe("AdminRateLimitsPage", () => {
|
||||
|
||||
await user.click(screen.getByRole("tab", { name: /blocklists/i }))
|
||||
|
||||
// Type in search box
|
||||
const searchInput = screen.getByPlaceholderText("Search domains...")
|
||||
expect(screen.getByText("custom-spam.com")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("filters external domains by search", async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<AdminRateLimitsPage />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Rate Limits")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole("tab", { name: /blocklists/i }))
|
||||
|
||||
// Type in external domains search box
|
||||
const searchInput = screen.getByPlaceholderText("Search external domains...")
|
||||
await user.type(searchInput, "temp")
|
||||
|
||||
// Should show filtered results
|
||||
expect(screen.getByText("tempmail.com")).toBeInTheDocument()
|
||||
// mailinator should not match "temp" filter
|
||||
})
|
||||
|
||||
it("adds a disposable domain", async () => {
|
||||
it("adds a manual domain", async () => {
|
||||
mockAdminApi.addDisposableDomain.mockResolvedValue({ success: true, message: "Operation successful" })
|
||||
|
||||
const user = userEvent.setup()
|
||||
@@ -184,13 +205,13 @@ describe("AdminRateLimitsPage", () => {
|
||||
|
||||
await user.click(screen.getByRole("tab", { name: /blocklists/i }))
|
||||
|
||||
// Type new domain
|
||||
// Type new domain in the manual domains add input
|
||||
const input = screen.getByPlaceholderText(
|
||||
"Add domain (e.g., tempmail.com)"
|
||||
)
|
||||
await user.type(input, "newspam.com")
|
||||
|
||||
// Click Add button
|
||||
// Click Add button nearest to the input
|
||||
const addButton = screen
|
||||
.getAllByRole("button", { name: /add/i })
|
||||
.find((btn) => btn.textContent?.includes("Add"))!
|
||||
|
||||
@@ -34,8 +34,11 @@ import {
|
||||
Clock,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Shield,
|
||||
X,
|
||||
} from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { IpInfo } from "@/components/admin/ip-info"
|
||||
|
||||
export default function AdminRateLimitsPage() {
|
||||
const { toast } = useToast()
|
||||
@@ -52,6 +55,10 @@ export default function AdminRateLimitsPage() {
|
||||
const [searchDomain, setSearchDomain] = useState("")
|
||||
const [searchEmail, setSearchEmail] = useState("")
|
||||
const [searchIP, setSearchIP] = useState("")
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const [newAllowlistDomain, setNewAllowlistDomain] = useState("")
|
||||
const [searchAllowlist, setSearchAllowlist] = useState("")
|
||||
const [searchExternalDomain, setSearchExternalDomain] = useState("")
|
||||
|
||||
const loadData = async () => {
|
||||
try {
|
||||
@@ -101,6 +108,51 @@ export default function AdminRateLimitsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleSync = async () => {
|
||||
try {
|
||||
setSyncing(true)
|
||||
const result = await adminApi.syncDisposableDomains()
|
||||
toast({ title: "Success", description: result.message })
|
||||
loadData()
|
||||
} catch (err: any) {
|
||||
toast({ title: "Error", description: err.message, variant: "destructive" })
|
||||
} finally {
|
||||
setSyncing(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveExternalDomain = async (domain: string) => {
|
||||
try {
|
||||
await adminApi.addAllowlistedDomain(domain)
|
||||
toast({ title: "Success", description: `Domain "${domain}" added to allowlist` })
|
||||
loadData()
|
||||
} catch (err: any) {
|
||||
toast({ title: "Error", description: err.message, variant: "destructive" })
|
||||
}
|
||||
}
|
||||
|
||||
const handleAddAllowlist = async () => {
|
||||
if (!newAllowlistDomain.trim()) return
|
||||
try {
|
||||
await adminApi.addAllowlistedDomain(newAllowlistDomain.trim())
|
||||
toast({ title: "Success", description: `Domain "${newAllowlistDomain}" added to allowlist` })
|
||||
setNewAllowlistDomain("")
|
||||
loadData()
|
||||
} catch (err: any) {
|
||||
toast({ title: "Error", description: err.message, variant: "destructive" })
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveAllowlist = async (domain: string) => {
|
||||
try {
|
||||
await adminApi.removeAllowlistedDomain(domain)
|
||||
toast({ title: "Success", description: `Domain "${domain}" removed from allowlist` })
|
||||
loadData()
|
||||
} catch (err: any) {
|
||||
toast({ title: "Error", description: err.message, variant: "destructive" })
|
||||
}
|
||||
}
|
||||
|
||||
const handleAddEmail = async () => {
|
||||
if (!newEmail.trim()) return
|
||||
try {
|
||||
@@ -184,11 +236,19 @@ export default function AdminRateLimitsPage() {
|
||||
}
|
||||
|
||||
// Filter functions
|
||||
const filteredDomains = blocklists?.disposable_domains.filter(d =>
|
||||
const filteredExternalDomains = blocklists?.external_domains?.filter(d =>
|
||||
d.toLowerCase().includes(searchExternalDomain.toLowerCase())
|
||||
) || []
|
||||
|
||||
const filteredManualDomains = blocklists?.manual_domains?.filter(d =>
|
||||
d.toLowerCase().includes(searchDomain.toLowerCase())
|
||||
) || []
|
||||
|
||||
const filteredEmails = blocklists?.blocked_emails.filter(e =>
|
||||
const filteredAllowlisted = blocklists?.allowlisted_domains?.filter(d =>
|
||||
d.toLowerCase().includes(searchAllowlist.toLowerCase())
|
||||
) || []
|
||||
|
||||
const filteredEmails = blocklists?.blocked_emails?.filter(e =>
|
||||
e.toLowerCase().includes(searchEmail.toLowerCase())
|
||||
) || []
|
||||
|
||||
@@ -350,15 +410,89 @@ export default function AdminRateLimitsPage() {
|
||||
|
||||
{/* Blocklists Tab */}
|
||||
<TabsContent value="blocklists" className="space-y-6">
|
||||
{/* Disposable Domains */}
|
||||
{/* Sync Status */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Globe className="w-5 h-5" />
|
||||
Disposable Email Domains
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{blocklists?.last_sync_at
|
||||
? `Last synced ${formatDate(blocklists.last_sync_at)} — ${blocklists.last_sync_count?.toLocaleString() || 0} external domains`
|
||||
: "Never synced"}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button onClick={handleSync} disabled={syncing} variant="outline">
|
||||
{syncing ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
Sync Now
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
{/* External Domains */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Globe className="w-5 h-5" />
|
||||
Disposable Email Domains
|
||||
External Domains
|
||||
<Badge variant="secondary" className="ml-1">{blocklists?.external_domains?.length || 0}</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Blocked disposable email domains ({filteredDomains.length} of {blocklists?.disposable_domains.length || 0})
|
||||
Domains from the external disposable email list. Remove a domain to add it to the allowlist.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search external domains..."
|
||||
value={searchExternalDomain}
|
||||
onChange={(e) => setSearchExternalDomain(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto border rounded-md">
|
||||
<div className="flex flex-wrap gap-2 p-3">
|
||||
{filteredExternalDomains.slice(0, 200).map((domain) => (
|
||||
<Badge key={domain} variant="outline" className="flex items-center gap-1">
|
||||
{domain}
|
||||
<button
|
||||
onClick={() => handleRemoveExternalDomain(domain)}
|
||||
className="ml-1 hover:text-destructive cursor-pointer"
|
||||
title="Add to allowlist"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
{filteredExternalDomains.length > 200 && (
|
||||
<span className="text-muted-foreground text-sm">
|
||||
+{filteredExternalDomains.length - 200} more
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Manual Domains */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Globe className="w-5 h-5" />
|
||||
Manual Domains
|
||||
<Badge variant="secondary" className="ml-1">{blocklists?.manual_domains?.length || 0}</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Manually added disposable email domains.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
@@ -366,7 +500,7 @@ export default function AdminRateLimitsPage() {
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search domains..."
|
||||
placeholder="Search manual domains..."
|
||||
value={searchDomain}
|
||||
onChange={(e) => setSearchDomain(e.target.value)}
|
||||
className="pl-9"
|
||||
@@ -384,27 +518,88 @@ export default function AdminRateLimitsPage() {
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto border rounded-md">
|
||||
<div className="flex flex-wrap gap-2 p-3">
|
||||
{filteredDomains.slice(0, 100).map((domain) => (
|
||||
<Badge key={domain} variant="secondary" className="flex items-center gap-1">
|
||||
{domain}
|
||||
<button
|
||||
onClick={() => handleRemoveDomain(domain)}
|
||||
className="ml-1 hover:text-destructive cursor-pointer"
|
||||
title="Remove domain"
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
{filteredDomains.length > 100 && (
|
||||
<span className="text-muted-foreground text-sm">
|
||||
+{filteredDomains.length - 100} more
|
||||
</span>
|
||||
)}
|
||||
{filteredManualDomains.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm py-4 text-center">
|
||||
No manual domains
|
||||
</p>
|
||||
) : (
|
||||
<div className="max-h-64 overflow-y-auto border rounded-md">
|
||||
<div className="flex flex-wrap gap-2 p-3">
|
||||
{filteredManualDomains.map((domain) => (
|
||||
<Badge key={domain} variant="secondary" className="flex items-center gap-1">
|
||||
{domain}
|
||||
<button
|
||||
onClick={() => handleRemoveDomain(domain)}
|
||||
className="ml-1 hover:text-destructive cursor-pointer"
|
||||
title="Remove domain"
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Allowlisted Domains */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="w-5 h-5" />
|
||||
Allowlisted Domains
|
||||
<Badge variant="secondary" className="ml-1">{blocklists?.allowlisted_domains?.length || 0}</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Domains that override the external blocklist. These domains will not be blocked.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search allowlisted domains..."
|
||||
value={searchAllowlist}
|
||||
onChange={(e) => setSearchAllowlist(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
placeholder="Add domain to allowlist"
|
||||
value={newAllowlistDomain}
|
||||
onChange={(e) => setNewAllowlistDomain(e.target.value)}
|
||||
className="w-64"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleAddAllowlist()}
|
||||
/>
|
||||
<Button onClick={handleAddAllowlist} disabled={!newAllowlistDomain.trim()}>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{filteredAllowlisted.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm py-4 text-center">
|
||||
No allowlisted domains
|
||||
</p>
|
||||
) : (
|
||||
<div className="max-h-64 overflow-y-auto border rounded-md">
|
||||
<div className="flex flex-wrap gap-2 p-3">
|
||||
{filteredAllowlisted.map((domain) => (
|
||||
<Badge key={domain} variant="default" className="flex items-center gap-1 bg-green-600">
|
||||
{domain}
|
||||
<button
|
||||
onClick={() => handleRemoveAllowlist(domain)}
|
||||
className="ml-1 hover:text-white cursor-pointer"
|
||||
title="Remove from allowlist"
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -510,7 +705,7 @@ export default function AdminRateLimitsPage() {
|
||||
<div className="flex flex-wrap gap-2 p-3">
|
||||
{filteredIPs.map((ip) => (
|
||||
<Badge key={ip} variant="destructive" className="flex items-center gap-1">
|
||||
{ip}
|
||||
<IpInfo ip={ip} compact />
|
||||
<button
|
||||
onClick={() => handleRemoveIP(ip)}
|
||||
className="ml-1 hover:text-white cursor-pointer"
|
||||
|
||||
@@ -50,6 +50,7 @@ import {
|
||||
} from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { IpInfo } from "@/components/admin/ip-info"
|
||||
|
||||
export default function AdminUserDetailPage() {
|
||||
const searchParams = useSearchParams()
|
||||
@@ -414,6 +415,54 @@ export default function AdminUserDetailPage() {
|
||||
<span className="text-muted-foreground">Last Updated</span>
|
||||
<span className="text-sm">{formatDate(user.updated_at)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Total Spent</span>
|
||||
<span className="text-sm font-medium">{user.total_spent ? `$${(user.total_spent / 100).toFixed(2)}` : "$0"}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Feedback Submitted</span>
|
||||
<Badge variant={user.has_submitted_feedback ? "default" : "secondary"}>
|
||||
{user.has_submitted_feedback ? "Yes" : "No"}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Identity & Security */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Identity & Security</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-muted-foreground">Signup IP</span>
|
||||
<IpInfo ip={user.signup_ip} />
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Device Fingerprint</span>
|
||||
<code className="text-xs bg-muted px-1.5 py-0.5 rounded">{user.device_fingerprint || "unknown"}</code>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Welcome Credits</span>
|
||||
<Badge variant={user.welcome_credits_granted ? "default" : "secondary"}>
|
||||
{user.welcome_credits_granted ? "Granted" : "Not yet"}
|
||||
</Badge>
|
||||
</div>
|
||||
{user.recent_sessions && user.recent_sessions.length > 0 && (
|
||||
<div className="pt-2 border-t">
|
||||
<p className="text-sm font-medium mb-2">Active Sessions</p>
|
||||
<div className="space-y-2">
|
||||
{user.recent_sessions.map((s, i) => (
|
||||
<div key={i} className="text-xs bg-muted rounded p-2 space-y-1">
|
||||
<div className="flex items-center gap-1"><span className="text-muted-foreground">IP:</span> <IpInfo ip={s.ip_address} compact /></div>
|
||||
{s.device_fingerprint && <div><span className="text-muted-foreground">Fingerprint:</span> {s.device_fingerprint}</div>}
|
||||
{s.user_agent && <div className="truncate"><span className="text-muted-foreground">UA:</span> {s.user_agent}</div>}
|
||||
<div><span className="text-muted-foreground">Last active:</span> {s.last_activity_at ? new Date(s.last_activity_at).toLocaleString() : "unknown"}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -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,23 +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
|
||||
|
||||
@@ -30,32 +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 if the verify response included a tenant subdomain
|
||||
// If we're on the wrong domain, redirect to the correct tenant portal
|
||||
const lastVerifyResponse = (window as any).__LAST_VERIFY_RESPONSE__
|
||||
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")
|
||||
}
|
||||
@@ -64,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">
|
||||
@@ -78,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" />
|
||||
@@ -93,6 +225,7 @@ function VerifyMagicLinkContent() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 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)}
|
||||
|
||||
@@ -225,6 +225,38 @@ describe('AuthDialog', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('shows friendly message when disposable email is rejected', async () => {
|
||||
const mockSendMagicLink = jest.fn().mockResolvedValue(false)
|
||||
mockUseAuth.mockReturnValue({
|
||||
sendMagicLink: mockSendMagicLink,
|
||||
loginWithToken: jest.fn(),
|
||||
isLoading: false,
|
||||
error: 'disposable_email_not_allowed',
|
||||
clearError: jest.fn(),
|
||||
})
|
||||
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
|
||||
|
||||
// Should show the friendly disposable email message
|
||||
expect(screen.getByText(/don't support disposable email/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/no spam, no marketing emails/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/your regular email/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows generic error for non-disposable errors', () => {
|
||||
mockUseAuth.mockReturnValue({
|
||||
sendMagicLink: jest.fn(),
|
||||
loginWithToken: jest.fn(),
|
||||
isLoading: false,
|
||||
error: 'Something went wrong',
|
||||
clearError: jest.fn(),
|
||||
})
|
||||
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
|
||||
|
||||
// Should show generic error text, not the disposable email message
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument()
|
||||
expect(screen.queryByText(/don't support disposable email/i)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows email sent step after successful magic link send', async () => {
|
||||
const mockSendMagicLink = jest.fn().mockResolvedValue(true)
|
||||
mockUseAuth.mockReturnValue({
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
ShieldAlert,
|
||||
BookOpenCheck,
|
||||
Scissors,
|
||||
Fingerprint,
|
||||
MessageSquare,
|
||||
} from "lucide-react"
|
||||
|
||||
import {
|
||||
@@ -70,6 +72,16 @@ const navItems = [
|
||||
href: "/admin/audio-edits",
|
||||
icon: Scissors,
|
||||
},
|
||||
{
|
||||
title: "Feedback",
|
||||
href: "/admin/feedback",
|
||||
icon: MessageSquare,
|
||||
},
|
||||
{
|
||||
title: "Abuse Investigation",
|
||||
href: "/admin/abuse",
|
||||
icon: Fingerprint,
|
||||
},
|
||||
]
|
||||
|
||||
export function AdminSidebar() {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { fetchIpInfo, countryCodeToFlag } from "@/lib/ip-geolocation"
|
||||
import type { IpGeoInfo } from "@/lib/api"
|
||||
import {
|
||||
HoverCard,
|
||||
HoverCardContent,
|
||||
HoverCardTrigger,
|
||||
} from "@/components/ui/hover-card"
|
||||
import { Globe } from "lucide-react"
|
||||
|
||||
/**
|
||||
* Inline IP address display with geolocation enrichment.
|
||||
*
|
||||
* Shows the raw IP plus a compact summary (flag + country + ISP).
|
||||
* Hover to see full details (city, region, ASN, timezone).
|
||||
*
|
||||
* Usage: <IpInfo ip="8.8.8.8" />
|
||||
*/
|
||||
export function IpInfo({
|
||||
ip,
|
||||
compact = false,
|
||||
}: {
|
||||
ip: string | null | undefined
|
||||
compact?: boolean
|
||||
}) {
|
||||
const [geo, setGeo] = useState<IpGeoInfo | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!ip) return
|
||||
setLoading(true)
|
||||
fetchIpInfo(ip).then((result) => {
|
||||
setGeo(result)
|
||||
setLoading(false)
|
||||
})
|
||||
}, [ip])
|
||||
|
||||
if (!ip) {
|
||||
return <span className="text-muted-foreground text-xs">-</span>
|
||||
}
|
||||
|
||||
const hasGeo = geo && geo.status === "success"
|
||||
const flag = hasGeo ? countryCodeToFlag(geo.country_code || "") : ""
|
||||
const ispShort = hasGeo && geo.isp ? truncateIsp(geo.isp) : ""
|
||||
|
||||
// Inline summary
|
||||
const summary = hasGeo ? (
|
||||
<span className="text-muted-foreground text-xs ml-1">
|
||||
{flag} {geo.country_code}
|
||||
{ispShort && <span className="hidden sm:inline"> · {ispShort}</span>}
|
||||
</span>
|
||||
) : loading ? (
|
||||
<span className="text-muted-foreground text-xs ml-1 animate-pulse">...</span>
|
||||
) : null
|
||||
|
||||
if (compact) {
|
||||
// Compact mode: just flag + country code, no IP shown
|
||||
if (!hasGeo) return <span className="font-mono text-xs">{ip}</span>
|
||||
return (
|
||||
<HoverCard openDelay={200}>
|
||||
<HoverCardTrigger asChild>
|
||||
<span className="cursor-help font-mono text-xs">
|
||||
{ip} {summary}
|
||||
</span>
|
||||
</HoverCardTrigger>
|
||||
<HoverCardContent className="w-72" side="top">
|
||||
<IpGeoDetails ip={ip} geo={geo} />
|
||||
</HoverCardContent>
|
||||
</HoverCard>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<HoverCard openDelay={200}>
|
||||
<HoverCardTrigger asChild>
|
||||
<span className="cursor-help inline-flex items-center gap-0.5">
|
||||
<code className="text-xs bg-muted px-1.5 py-0.5 rounded font-mono">{ip}</code>
|
||||
{summary}
|
||||
</span>
|
||||
</HoverCardTrigger>
|
||||
<HoverCardContent className="w-72" side="top">
|
||||
<IpGeoDetails ip={ip} geo={geo} />
|
||||
</HoverCardContent>
|
||||
</HoverCard>
|
||||
)
|
||||
}
|
||||
|
||||
function IpGeoDetails({
|
||||
ip,
|
||||
geo,
|
||||
}: {
|
||||
ip: string
|
||||
geo: IpGeoInfo | null
|
||||
}) {
|
||||
if (!geo || geo.status !== "success") {
|
||||
return (
|
||||
<div className="text-sm">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Globe className="w-4 h-4 text-muted-foreground" />
|
||||
<span className="font-medium">{ip}</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{geo?.status === "private" ? "Private/reserved IP" :
|
||||
geo?.status === "error" ? "Lookup failed" :
|
||||
"No geolocation data available"}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const flag = countryCodeToFlag(geo.country_code || "")
|
||||
|
||||
return (
|
||||
<div className="text-sm space-y-1.5">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Globe className="w-4 h-4 text-muted-foreground" />
|
||||
<span className="font-medium font-mono">{ip}</span>
|
||||
</div>
|
||||
<DetailRow label="Country" value={`${flag} ${geo.country} (${geo.country_code})`} />
|
||||
{geo.region && <DetailRow label="Region" value={geo.region} />}
|
||||
{geo.city && <DetailRow label="City" value={geo.city} />}
|
||||
{geo.isp && <DetailRow label="ISP" value={geo.isp} />}
|
||||
{geo.org && geo.org !== geo.isp && <DetailRow label="Org" value={geo.org} />}
|
||||
{geo.as_number && (
|
||||
<DetailRow label="ASN" value={`${geo.as_number}${geo.as_name ? ` (${geo.as_name})` : ""}`} />
|
||||
)}
|
||||
{geo.timezone && <DetailRow label="Timezone" value={geo.timezone} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DetailRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground text-xs">{label}</span>
|
||||
<span className="text-xs text-right">{value}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function truncateIsp(isp: string): string {
|
||||
// Remove common suffixes to keep it short
|
||||
const cleaned = isp
|
||||
.replace(/,?\s*(Inc|LLC|Ltd|Corp|Corporation|Co\.|Company|Telecommunications|Telecom)\.?$/i, "")
|
||||
.trim()
|
||||
return cleaned.length > 20 ? cleaned.slice(0, 20) + "..." : cleaned
|
||||
}
|
||||
@@ -107,7 +107,21 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
disabled={isLoading}
|
||||
/>
|
||||
{displayError && (
|
||||
<p className="text-xs text-destructive mt-1">{displayError}</p>
|
||||
displayError === "disposable_email_not_allowed" ? (
|
||||
<div className="mt-2 p-3 rounded-md bg-amber-500/10 border border-amber-500/30 text-sm space-y-2">
|
||||
<p className="font-medium text-amber-400">We don't support disposable email addresses</p>
|
||||
<p className="text-muted-foreground">
|
||||
We'd love to help you create karaoke videos! Please use your regular email
|
||||
address so we can send you a notification when your video is ready.
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
We promise — no spam, no marketing emails, ever. We only email you about
|
||||
your karaoke videos.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-destructive mt-1">{displayError}</p>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
|
||||
@@ -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>
|
||||
|
||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user