mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-03 08:39:34 +09:00
Compare commits
No files matched your search
@@ -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).
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1220,6 +1220,18 @@ async def reset_job(
|
||||
# Add timeline event
|
||||
clear_updates["timeline"] = ArrayUnion([timeline_event])
|
||||
|
||||
# Special handling for awaiting_audio_edit: restore original input audio
|
||||
# The submit endpoint copies edited audio to input_media_gcs_path,
|
||||
# so we must restore the original path so the user starts fresh.
|
||||
if target_state == "awaiting_audio_edit":
|
||||
original_path = current_state_data.get("original_input_media_gcs_path")
|
||||
if original_path:
|
||||
clear_updates["input_media_gcs_path"] = original_path
|
||||
logger.info(
|
||||
f"Admin reset job {job_id}: Restoring input_media_gcs_path "
|
||||
f"to original: {original_path}"
|
||||
)
|
||||
|
||||
# Execute the update
|
||||
job_ref.update(clear_updates)
|
||||
|
||||
@@ -3291,3 +3303,228 @@ async def get_edit_review_detail(
|
||||
"annotations": annotations,
|
||||
"audio_url": audio_url,
|
||||
}
|
||||
|
||||
|
||||
# ─── Audio Edit Reviews ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class AudioEditReviewSummary(BaseModel):
|
||||
job_id: str
|
||||
artist: str
|
||||
title: str
|
||||
user_email: str
|
||||
status: str
|
||||
created_at: Optional[str] = None
|
||||
updated_at: Optional[str] = None
|
||||
session_count: int = 0
|
||||
total_edits: int = 0
|
||||
original_duration: Optional[float] = None
|
||||
current_duration: Optional[float] = None
|
||||
latest_trigger: Optional[str] = None
|
||||
|
||||
|
||||
class AudioEditReviewListResponse(BaseModel):
|
||||
reviews: List[AudioEditReviewSummary]
|
||||
total: int
|
||||
has_more: bool
|
||||
|
||||
|
||||
@router.get("/audio-edit-reviews", response_model=AudioEditReviewListResponse)
|
||||
def list_audio_edit_reviews(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
exclude_test: bool = False,
|
||||
search: Optional[str] = None,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""List jobs that have audio edit sessions."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
user_service = get_user_service()
|
||||
db = user_service.db
|
||||
fs = FirestoreService()
|
||||
|
||||
STREAM_LIMIT = 10000
|
||||
reviews = []
|
||||
streamed = 0
|
||||
|
||||
for doc in db.collection("jobs").limit(STREAM_LIMIT).stream():
|
||||
streamed += 1
|
||||
data = doc.to_dict()
|
||||
state_data = data.get("state_data") or {}
|
||||
|
||||
# Only include jobs that have been through audio edit
|
||||
# (have edit stack or have audio edit sessions)
|
||||
has_edit_stack = bool(state_data.get("audio_edit_stack"))
|
||||
status = data.get("status", "")
|
||||
is_in_audio_edit = status in (
|
||||
"awaiting_audio_edit", "in_audio_edit", "audio_edit_complete"
|
||||
)
|
||||
|
||||
if not has_edit_stack and not is_in_audio_edit:
|
||||
# Quick check: does this job have any audio edit sessions subcollection?
|
||||
sessions_ref = db.collection("jobs").document(doc.id).collection("audio_edit_sessions")
|
||||
if not next(sessions_ref.limit(1).stream(), None):
|
||||
continue
|
||||
|
||||
email = data.get("user_email", "")
|
||||
if exclude_test and is_test_email(email):
|
||||
continue
|
||||
|
||||
artist = data.get("artist", "")
|
||||
title = data.get("title", "")
|
||||
|
||||
if search:
|
||||
search_lower = search.lower()
|
||||
if (
|
||||
search_lower not in (artist or "").lower()
|
||||
and search_lower not in (title or "").lower()
|
||||
and search_lower not in (email or "").lower()
|
||||
):
|
||||
continue
|
||||
|
||||
# Get session summary info
|
||||
sessions = fs.list_audio_edit_sessions(doc.id)
|
||||
session_count = len(sessions)
|
||||
total_edits = 0
|
||||
latest_trigger = None
|
||||
current_duration = None
|
||||
original_duration = None
|
||||
|
||||
if sessions:
|
||||
latest = sessions[0] # Already sorted by updated_at DESC
|
||||
total_edits = latest.edit_count
|
||||
latest_trigger = latest.trigger
|
||||
current_duration = latest.audio_duration_seconds
|
||||
original_duration = latest.original_duration_seconds
|
||||
|
||||
created_at = data.get("created_at")
|
||||
updated_at = data.get("updated_at")
|
||||
|
||||
def _to_iso(val) -> Optional[str]:
|
||||
if val is None:
|
||||
return None
|
||||
if hasattr(val, 'isoformat'):
|
||||
return val.isoformat()
|
||||
return str(val)
|
||||
|
||||
try:
|
||||
reviews.append(AudioEditReviewSummary(
|
||||
job_id=doc.id,
|
||||
artist=artist or "",
|
||||
title=title or "",
|
||||
user_email=email or "",
|
||||
status=status,
|
||||
created_at=_to_iso(created_at),
|
||||
updated_at=_to_iso(updated_at),
|
||||
session_count=session_count,
|
||||
total_edits=total_edits,
|
||||
original_duration=original_duration,
|
||||
current_duration=current_duration,
|
||||
latest_trigger=latest_trigger,
|
||||
))
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {doc.id}: Error building audio edit review summary: {e}")
|
||||
continue
|
||||
|
||||
if streamed >= STREAM_LIMIT:
|
||||
logger.warning(f"Audio edit reviews stream hit limit ({STREAM_LIMIT}), results may be incomplete")
|
||||
|
||||
reviews.sort(
|
||||
key=lambda r: r.updated_at or r.created_at or "",
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
total = len(reviews)
|
||||
paginated = reviews[offset : offset + limit]
|
||||
|
||||
return AudioEditReviewListResponse(
|
||||
reviews=paginated,
|
||||
total=total,
|
||||
has_more=(offset + limit) < total,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/audio-edit-reviews/{job_id}")
|
||||
async def get_audio_edit_review_detail(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Get full audio edit review detail for one job, including all sessions."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
storage = StorageService()
|
||||
fs = FirestoreService()
|
||||
|
||||
job_meta = {
|
||||
"job_id": job.job_id,
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
"user_email": job.user_email,
|
||||
"status": job.status.value if hasattr(job.status, "value") else str(job.status),
|
||||
"created_at": job.created_at.isoformat() if job.created_at else None,
|
||||
"updated_at": job.updated_at.isoformat() if job.updated_at else None,
|
||||
}
|
||||
|
||||
# Get all sessions
|
||||
sessions = fs.list_audio_edit_sessions(job_id)
|
||||
sessions_data = []
|
||||
for session in sessions:
|
||||
session_dict = session.to_dict()
|
||||
# Convert datetimes to ISO strings
|
||||
for key in ("created_at", "updated_at"):
|
||||
val = session_dict.get(key)
|
||||
if hasattr(val, "isoformat"):
|
||||
session_dict[key] = val.isoformat()
|
||||
sessions_data.append(session_dict)
|
||||
|
||||
# Get current edit stack from state_data
|
||||
state_data = job.state_data or {}
|
||||
edit_stack = state_data.get("audio_edit_stack", [])
|
||||
|
||||
# Generate signed URLs for original and current audio
|
||||
original_audio_url = None
|
||||
current_audio_url = None
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
|
||||
if job.input_media_gcs_path:
|
||||
try:
|
||||
current_audio_url = await transcoding.get_review_audio_url_async(
|
||||
job.input_media_gcs_path, expiration_minutes=120
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not generate current audio URL: {e}")
|
||||
|
||||
# Original audio (before edits)
|
||||
original_path = state_data.get("original_input_media_gcs_path") or job.input_media_gcs_path
|
||||
if original_path and original_path != job.input_media_gcs_path:
|
||||
try:
|
||||
original_audio_url = await transcoding.get_review_audio_url_async(
|
||||
original_path, expiration_minutes=120
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not generate original audio URL: {e}")
|
||||
|
||||
# Load edit log if it exists
|
||||
edit_log = None
|
||||
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
|
||||
try:
|
||||
if storage.file_exists(edit_log_path):
|
||||
edit_log = storage.download_json(edit_log_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not load audio edit log: {e}")
|
||||
|
||||
return {
|
||||
"job": job_meta,
|
||||
"sessions": sessions_data,
|
||||
"edit_stack": edit_stack,
|
||||
"edit_log": edit_log,
|
||||
"original_audio_url": original_audio_url,
|
||||
"current_audio_url": current_audio_url,
|
||||
}
|
||||
@@ -240,24 +240,24 @@ class AudioSelectResponse(BaseModel):
|
||||
selected_provider: str
|
||||
|
||||
|
||||
def extract_request_metadata(request: Request, created_from: str = "audio_search") -> Dict[str, Any]:
|
||||
def extract_request_metadata(request: Request, created_from: str = "audio_search", auth_result=None) -> Dict[str, Any]:
|
||||
"""Extract metadata from request for job tracking."""
|
||||
headers = dict(request.headers)
|
||||
|
||||
|
||||
client_ip = headers.get('x-forwarded-for', '').split(',')[0].strip()
|
||||
if not client_ip and request.client:
|
||||
client_ip = request.client.host
|
||||
|
||||
|
||||
user_agent = headers.get('user-agent', '')
|
||||
environment = headers.get('x-environment', '')
|
||||
client_id = headers.get('x-client-id', '')
|
||||
|
||||
|
||||
custom_headers = {}
|
||||
for key, value in headers.items():
|
||||
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
|
||||
custom_headers[key] = value
|
||||
|
||||
return {
|
||||
|
||||
metadata = {
|
||||
'client_ip': client_ip,
|
||||
'user_agent': user_agent,
|
||||
'environment': environment,
|
||||
@@ -267,6 +267,17 @@ def extract_request_metadata(request: Request, created_from: str = "audio_search
|
||||
'custom_headers': custom_headers,
|
||||
}
|
||||
|
||||
# Add auth context for abuse investigation and analytics
|
||||
if auth_result is not None:
|
||||
metadata['auth_method'] = getattr(auth_result, 'auth_method', None)
|
||||
user_type = getattr(auth_result, 'user_type', None)
|
||||
metadata['user_type'] = user_type.value if hasattr(user_type, 'value') else str(user_type) if user_type else None
|
||||
remaining = getattr(auth_result, 'remaining_uses', None)
|
||||
if remaining is not None:
|
||||
metadata['credits_at_creation'] = remaining
|
||||
|
||||
return metadata
|
||||
|
||||
|
||||
def _extract_gcs_path(filepath: str) -> str:
|
||||
"""
|
||||
@@ -633,8 +644,9 @@ async def search_audio(
|
||||
}
|
||||
)
|
||||
|
||||
# Extract request metadata
|
||||
request_metadata = extract_request_metadata(request, created_from="audio_search")
|
||||
# Extract request metadata (includes auth context + search query info)
|
||||
request_metadata = extract_request_metadata(request, created_from="audio_search", auth_result=auth_result)
|
||||
request_metadata['search_query'] = {'artist': body.artist, 'title': body.title}
|
||||
|
||||
# Apply default theme if none specified
|
||||
# This ensures all karaoke videos use the Nomad theme by default
|
||||
@@ -754,11 +766,11 @@ async def search_audio(
|
||||
|
||||
# Generate GCS path
|
||||
if file_info.file_type == 'style_params':
|
||||
gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
gcs_path = f"jobs/{job_id}/style/style_params.json"
|
||||
else:
|
||||
# style_intro_background -> intro_background, etc.
|
||||
asset_key = file_info.file_type.replace('style_', '')
|
||||
gcs_path = f"uploads/{job_id}/style/{asset_key}{ext}"
|
||||
gcs_path = f"jobs/{job_id}/style/{asset_key}{ext}"
|
||||
|
||||
# Generate signed upload URL
|
||||
signed_url = storage_service.generate_signed_upload_url(
|
||||
|
||||
@@ -268,10 +268,10 @@ storage_service = StorageService()
|
||||
worker_service = get_worker_service()
|
||||
|
||||
|
||||
def extract_request_metadata(request: Request, created_from: str = "upload") -> Dict[str, Any]:
|
||||
def extract_request_metadata(request: Request, created_from: str = "upload", auth_result=None) -> Dict[str, Any]:
|
||||
"""
|
||||
Extract metadata from a FastAPI Request for job tracking.
|
||||
|
||||
|
||||
Captures:
|
||||
- Client IP address (handles X-Forwarded-For for proxies)
|
||||
- User-Agent header
|
||||
@@ -280,34 +280,36 @@ def extract_request_metadata(request: Request, created_from: str = "upload") ->
|
||||
- All custom X-* headers
|
||||
- Server version
|
||||
- Creation source (upload/url)
|
||||
|
||||
- Auth context (method, user type) if auth_result provided
|
||||
|
||||
Args:
|
||||
request: FastAPI Request object
|
||||
created_from: How the job was created ("upload" or "url")
|
||||
|
||||
auth_result: Optional AuthResult from authentication
|
||||
|
||||
Returns:
|
||||
Dict with metadata fields for storage in job.request_metadata
|
||||
"""
|
||||
headers = dict(request.headers)
|
||||
|
||||
|
||||
# Extract client IP (check X-Forwarded-For for proxy scenarios)
|
||||
client_ip = headers.get('x-forwarded-for', '').split(',')[0].strip()
|
||||
if not client_ip and request.client:
|
||||
client_ip = request.client.host
|
||||
|
||||
|
||||
# Extract standard headers
|
||||
user_agent = headers.get('user-agent', '')
|
||||
environment = headers.get('x-environment', '') # test, production, development
|
||||
client_id = headers.get('x-client-id', '') # Customer/user identifier
|
||||
|
||||
|
||||
# Collect all X-* custom headers (excluding standard ones we already captured)
|
||||
custom_headers = {}
|
||||
for key, value in headers.items():
|
||||
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
|
||||
# Normalize header name to original casing if possible
|
||||
custom_headers[key] = value
|
||||
|
||||
return {
|
||||
|
||||
metadata = {
|
||||
'client_ip': client_ip,
|
||||
'user_agent': user_agent,
|
||||
'environment': environment,
|
||||
@@ -317,6 +319,17 @@ def extract_request_metadata(request: Request, created_from: str = "upload") ->
|
||||
'custom_headers': custom_headers,
|
||||
}
|
||||
|
||||
# Add auth context for abuse investigation and analytics
|
||||
if auth_result is not None:
|
||||
metadata['auth_method'] = getattr(auth_result, 'auth_method', None)
|
||||
user_type = getattr(auth_result, 'user_type', None)
|
||||
metadata['user_type'] = user_type.value if hasattr(user_type, 'value') else str(user_type) if user_type else None
|
||||
remaining = getattr(auth_result, 'remaining_uses', None)
|
||||
if remaining is not None:
|
||||
metadata['credits_at_creation'] = remaining
|
||||
|
||||
return metadata
|
||||
|
||||
|
||||
# File extension validation
|
||||
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.flac', '.m4a', '.ogg', '.aac'}
|
||||
@@ -564,7 +577,7 @@ async def upload_and_create_job(
|
||||
)
|
||||
|
||||
# Extract request metadata for tracking and filtering
|
||||
request_metadata = extract_request_metadata(request, created_from="upload")
|
||||
request_metadata = extract_request_metadata(request, created_from="upload", auth_result=auth_result)
|
||||
|
||||
# Parse color_overrides from JSON if provided
|
||||
parsed_color_overrides: Dict[str, str] = {}
|
||||
@@ -709,7 +722,7 @@ async def upload_and_create_job(
|
||||
|
||||
# Upload style files if provided
|
||||
if style_params:
|
||||
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
|
||||
logger.info(f"Uploading style params to GCS: {style_gcs_path}")
|
||||
storage_service.upload_fileobj(
|
||||
style_params.file,
|
||||
@@ -728,7 +741,7 @@ async def upload_and_create_job(
|
||||
(style_cdg_outro_background, "cdg_outro_background"),
|
||||
]:
|
||||
if img_file:
|
||||
gcs_path = f"uploads/{job_id}/style/{asset_key}{Path(img_file.filename).suffix.lower()}"
|
||||
gcs_path = f"jobs/{job_id}/style/{asset_key}{Path(img_file.filename).suffix.lower()}"
|
||||
logger.info(f"Uploading {asset_key} to GCS: {gcs_path}")
|
||||
storage_service.upload_fileobj(
|
||||
img_file.file,
|
||||
@@ -739,7 +752,7 @@ async def upload_and_create_job(
|
||||
|
||||
# Upload font file
|
||||
if style_font:
|
||||
font_gcs_path = f"uploads/{job_id}/style/font{Path(style_font.filename).suffix.lower()}"
|
||||
font_gcs_path = f"jobs/{job_id}/style/font{Path(style_font.filename).suffix.lower()}"
|
||||
logger.info(f"Uploading font to GCS: {font_gcs_path}")
|
||||
storage_service.upload_fileobj(
|
||||
style_font.file,
|
||||
@@ -1063,11 +1076,11 @@ def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
|
||||
if file_type == 'audio':
|
||||
return f"uploads/{job_id}/audio/{filename}"
|
||||
elif file_type == 'style_params':
|
||||
return f"uploads/{job_id}/style/style_params.json"
|
||||
return f"jobs/{job_id}/style/style_params.json"
|
||||
elif file_type.startswith('style_'):
|
||||
# Map style_intro_background -> intro_background, etc.
|
||||
asset_key = file_type.replace('style_', '')
|
||||
return f"uploads/{job_id}/style/{asset_key}{ext}"
|
||||
return f"jobs/{job_id}/style/{asset_key}{ext}"
|
||||
elif file_type == 'lyrics_file':
|
||||
return f"uploads/{job_id}/lyrics/user_lyrics{ext}"
|
||||
elif file_type == 'existing_instrumental':
|
||||
@@ -1195,7 +1208,7 @@ async def create_job_with_upload_urls(
|
||||
)
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="signed_url_upload")
|
||||
request_metadata = extract_request_metadata(request, created_from="signed_url_upload", auth_result=auth_result)
|
||||
|
||||
# Get original audio filename
|
||||
audio_file = audio_files[0]
|
||||
@@ -1360,10 +1373,10 @@ async def mark_uploads_complete(
|
||||
if file_type == 'audio':
|
||||
prefix = f"uploads/{job_id}/audio/"
|
||||
elif file_type == 'style_params':
|
||||
prefix = f"uploads/{job_id}/style/style_params"
|
||||
prefix = f"jobs/{job_id}/style/style_params"
|
||||
elif file_type.startswith('style_'):
|
||||
asset_key = file_type.replace('style_', '')
|
||||
prefix = f"uploads/{job_id}/style/{asset_key}"
|
||||
prefix = f"jobs/{job_id}/style/{asset_key}"
|
||||
elif file_type == 'lyrics_file':
|
||||
prefix = f"uploads/{job_id}/lyrics/user_lyrics"
|
||||
elif file_type == 'existing_instrumental':
|
||||
@@ -1663,7 +1676,7 @@ async def create_job_from_url(
|
||||
)
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="url")
|
||||
request_metadata = extract_request_metadata(request, created_from="url", auth_result=auth_result)
|
||||
|
||||
# Use provided artist/title or leave as None (will be auto-detected by audio worker)
|
||||
artist = body.artist
|
||||
@@ -1857,7 +1870,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
|
||||
elif file_type == 'corrections':
|
||||
return f"jobs/{job_id}/lyrics/corrections.json"
|
||||
elif file_type == 'style_params':
|
||||
return f"uploads/{job_id}/style/style_params.json"
|
||||
return f"jobs/{job_id}/style/style_params.json"
|
||||
else:
|
||||
return f"uploads/{job_id}/other/{filename}"
|
||||
|
||||
@@ -1983,7 +1996,7 @@ async def create_finalise_only_job(
|
||||
)
|
||||
|
||||
# Extract request metadata
|
||||
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload")
|
||||
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload", auth_result=auth_result)
|
||||
|
||||
# Apply default theme if none specified
|
||||
# This ensures all karaoke videos use the Nomad theme by default
|
||||
@@ -2189,7 +2202,7 @@ async def mark_finalise_uploads_complete(
|
||||
elif file_type == 'corrections':
|
||||
prefix = f"jobs/{job_id}/lyrics/corrections"
|
||||
elif file_type == 'style_params':
|
||||
prefix = f"uploads/{job_id}/style/style_params"
|
||||
prefix = f"jobs/{job_id}/style/style_params"
|
||||
else:
|
||||
continue
|
||||
|
||||
@@ -2442,7 +2455,7 @@ async def complete_style_uploads(
|
||||
continue
|
||||
|
||||
asset_key = file_type.replace('style_', '')
|
||||
prefix = f"uploads/{job_id}/style/{asset_key}"
|
||||
prefix = f"jobs/{job_id}/style/{asset_key}"
|
||||
files = storage_service.list_files(prefix)
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
@@ -2483,7 +2496,7 @@ async def complete_style_uploads(
|
||||
style_params["end"]["background_image"] = gcs_uri
|
||||
|
||||
# Upload updated style_params.json
|
||||
style_params_path = f"uploads/{job_id}/style/style_params.json"
|
||||
style_params_path = f"jobs/{job_id}/style/style_params.json"
|
||||
storage_service.upload_json(style_params_path, style_params)
|
||||
update_data["style_params_gcs_path"] = style_params_path
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -76,6 +76,18 @@ def _check_worker_idempotency(job_id: str, worker_name: str) -> Optional[WorkerR
|
||||
message=f"Job {job_id} not found"
|
||||
)
|
||||
|
||||
# Reject workers for jobs in terminal states (failed, cancelled, complete)
|
||||
# This prevents Cloud Tasks retries from triggering workers on dead jobs
|
||||
terminal_statuses = {'failed', 'cancelled', 'complete', 'prep_complete', 'error'}
|
||||
job_status = job.status.value if hasattr(job.status, 'value') else str(job.status)
|
||||
if job_status in terminal_statuses:
|
||||
logger.info(f"[job:{job_id}] Job in terminal state '{job_status}', skipping {worker_name} worker")
|
||||
return WorkerResponse(
|
||||
status="skipped",
|
||||
job_id=job_id,
|
||||
message=f"Job is in terminal state '{job_status}', {worker_name} worker not needed"
|
||||
)
|
||||
|
||||
# Check worker-specific progress in state_data
|
||||
progress_key = f"{worker_name}_progress"
|
||||
worker_progress = job.state_data.get(progress_key, {})
|
||||
@@ -102,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,
|
||||
@@ -468,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,
|
||||
|
||||
@@ -1434,7 +1434,8 @@ DOWNLOAD_FILENAME_SUFFIXES = {
|
||||
"lossy_720p_mp4": " (Final Karaoke Lossy 720p).mp4",
|
||||
"cdg_zip": " (Final Karaoke CDG).zip",
|
||||
"txt_zip": " (Final Karaoke TXT).zip",
|
||||
"with_vocals": " (With Vocals).mkv",
|
||||
"with_vocals_mp4": " (With Vocals).mp4",
|
||||
"with_vocals": " (With Vocals).mkv", # legacy: raw MKV from render step
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1165,7 +1165,7 @@ async def save_audio_edit_session(
|
||||
# Upload edit_data to GCS
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/audio_edit_sessions/{session.session_id}.json"
|
||||
storage.upload_json(edit_data, gcs_path)
|
||||
storage.upload_json(gcs_path, edit_data)
|
||||
session.edit_data_gcs_path = gcs_path
|
||||
|
||||
# Save metadata to Firestore
|
||||
@@ -1338,15 +1338,22 @@ async def get_input_audio_info(
|
||||
state_data = job.state_data or {}
|
||||
edit_stack = state_data.get('audio_edit_stack', [])
|
||||
|
||||
# Get metadata for the original audio
|
||||
metadata = edit_service.get_metadata_from_gcs(job.input_media_gcs_path)
|
||||
# Try cached waveform first (pre-generated by download worker), fall back to on-demand
|
||||
waveform_cache_path = state_data.get('audio_edit_waveform_cache_path')
|
||||
cached = None
|
||||
if waveform_cache_path:
|
||||
cached = analysis_service.load_cached_waveform(waveform_cache_path)
|
||||
|
||||
if cached:
|
||||
orig_amplitudes, orig_duration = cached
|
||||
logger.info(f"Job {job_id}: Using cached waveform data")
|
||||
else:
|
||||
orig_amplitudes, orig_duration = analysis_service.get_waveform_data(
|
||||
gcs_audio_path=job.input_media_gcs_path,
|
||||
job_id=job_id,
|
||||
num_points=1000,
|
||||
)
|
||||
|
||||
# Waveform for original audio
|
||||
orig_amplitudes, orig_duration = analysis_service.get_waveform_data(
|
||||
gcs_audio_path=job.input_media_gcs_path,
|
||||
job_id=job_id,
|
||||
num_points=1000,
|
||||
)
|
||||
original_playback_url = transcoding_service.get_review_audio_url(job.input_media_gcs_path)
|
||||
|
||||
# Determine current audio state
|
||||
@@ -1733,7 +1740,7 @@ async def submit_audio_edit(
|
||||
edit_log = body.get("edit_log")
|
||||
if edit_log:
|
||||
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
|
||||
storage.upload_json(edit_log, edit_log_path)
|
||||
storage.upload_json(edit_log_path, edit_log)
|
||||
logger.info(f"Job {job_id}: Saved audio edit log to {edit_log_path}")
|
||||
|
||||
if edit_stack:
|
||||
@@ -1763,12 +1770,21 @@ async def submit_audio_edit(
|
||||
message="Audio edit complete, starting processing"
|
||||
)
|
||||
|
||||
# Trigger parallel workers (same as normal post-download flow)
|
||||
# Trigger parallel workers in background so the HTTP response returns immediately.
|
||||
# The worker triggers involve Cloud Run Job calls that can take 30+ seconds;
|
||||
# waiting synchronously causes the browser request to time out.
|
||||
worker_service = get_worker_service()
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id),
|
||||
)
|
||||
|
||||
async def _trigger_workers():
|
||||
try:
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to trigger workers after audio edit: {e}")
|
||||
|
||||
asyncio.create_task(_trigger_workers())
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
|
||||
@@ -34,6 +34,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,
|
||||
@@ -147,6 +148,34 @@ 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 = 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."
|
||||
)
|
||||
|
||||
# Check if email service is configured
|
||||
if not email_service.is_configured():
|
||||
logger.error("Email service not configured - cannot send magic links")
|
||||
@@ -155,8 +184,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,8 +198,7 @@ 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
|
||||
@@ -1244,6 +1270,7 @@ async def list_users(
|
||||
query = query.where(filter=FieldFilter('is_active', '==', True))
|
||||
|
||||
# Search by email prefix (case-insensitive via range query)
|
||||
search = search.strip() if search else None
|
||||
if search:
|
||||
search_lower = search.lower()
|
||||
# Use range query for prefix matching
|
||||
@@ -1251,16 +1278,23 @@ async def list_users(
|
||||
query = query.where(filter=FieldFilter('email', '<', search_lower + '\uffff'))
|
||||
|
||||
# Sorting
|
||||
direction = firestore.Query.DESCENDING if sort_order == "desc" else firestore.Query.ASCENDING
|
||||
if sort_by in ["created_at", "last_login_at", "credits", "email"]:
|
||||
query = query.order_by(sort_by, direction=direction)
|
||||
else:
|
||||
query = query.order_by("created_at", direction=direction)
|
||||
# When search is active, Firestore range filters on 'email' conflict with
|
||||
# order_by on a different field (requires composite index). Since we already
|
||||
# fetch all docs and paginate in Python, just sort in Python when searching.
|
||||
sort_field = sort_by if sort_by in ["created_at", "last_login_at", "credits", "email"] else "created_at"
|
||||
if not search:
|
||||
direction = firestore.Query.DESCENDING if sort_order == "desc" else firestore.Query.ASCENDING
|
||||
query = query.order_by(sort_field, direction=direction)
|
||||
|
||||
# Get all docs and filter in Python
|
||||
# Note: This is expensive for large datasets, consider caching
|
||||
all_docs = list(query.stream())
|
||||
|
||||
# Sort in Python when search is active (can't use Firestore order_by with range filter)
|
||||
if search:
|
||||
reverse = sort_order == "desc"
|
||||
all_docs.sort(key=lambda d: (d.to_dict().get(sort_field) is None, d.to_dict().get(sort_field)), reverse=reverse)
|
||||
|
||||
# Filter out test users if exclude_test is True
|
||||
if exclude_test:
|
||||
all_docs = [d for d in all_docs if not is_test_email(d.to_dict().get('email', ''))]
|
||||
|
||||
@@ -421,6 +421,43 @@ class Job(BaseModel):
|
||||
}
|
||||
"""
|
||||
|
||||
# Processing metadata (immutable provenance data written by workers during processing)
|
||||
processing_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
Immutable processing provenance data. Written once by each worker during processing.
|
||||
Never modified after initial write. Used for analytics, debugging, and data export.
|
||||
|
||||
Structure:
|
||||
{
|
||||
"transcription": {
|
||||
"provider": "audioshake",
|
||||
"audioshake_task_id": "...",
|
||||
"audioshake_asset_id": "...",
|
||||
"language_detected": "en",
|
||||
"word_count": 358,
|
||||
"segment_count": 42,
|
||||
},
|
||||
"correction": {
|
||||
"handlers_applied": [...],
|
||||
"corrections_made": 12,
|
||||
"correction_ratio": 0.034,
|
||||
"reference_sources_found": ["genius", "spotify"],
|
||||
"agentic_routing": "rule-based",
|
||||
"duration_seconds": 33.2,
|
||||
},
|
||||
"separation": {
|
||||
"provider": "modal",
|
||||
"clean_model": "...",
|
||||
"duration_seconds": 420.5,
|
||||
},
|
||||
"timing": {
|
||||
"lyrics_worker_seconds": 125.3,
|
||||
"audio_worker_seconds": 420.5,
|
||||
...
|
||||
},
|
||||
}
|
||||
"""
|
||||
|
||||
# Request metadata (captured at job creation for tracking and filtering)
|
||||
request_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
|
||||
@@ -5,6 +5,7 @@ This service wraps the shared karaoke_gen.instrumental_review module
|
||||
to provide GCS-integrated audio analysis capabilities.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
@@ -187,7 +188,78 @@ class AudioAnalysisService:
|
||||
)
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
|
||||
def cache_waveform_data(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
cache_gcs_path: str,
|
||||
num_points: int = 1000,
|
||||
) -> tuple[list[float], float]:
|
||||
"""
|
||||
Generate waveform data and cache it as JSON in GCS.
|
||||
|
||||
Args:
|
||||
gcs_audio_path: Path to the audio file in GCS
|
||||
job_id: Job ID for logging
|
||||
cache_gcs_path: GCS path to store the cached waveform JSON
|
||||
num_points: Number of data points to generate
|
||||
|
||||
Returns:
|
||||
Tuple of (amplitude_values, duration_seconds)
|
||||
"""
|
||||
logger.info(f"[{job_id}] Generating and caching waveform data: {gcs_audio_path}")
|
||||
|
||||
amplitudes, duration = self.get_waveform_data(
|
||||
gcs_audio_path=gcs_audio_path,
|
||||
job_id=job_id,
|
||||
num_points=num_points,
|
||||
)
|
||||
|
||||
cache_data = {
|
||||
"amplitudes": list(amplitudes),
|
||||
"duration_seconds": duration,
|
||||
"num_points": num_points,
|
||||
"source_gcs_path": gcs_audio_path,
|
||||
}
|
||||
self.storage_service.upload_json(cache_gcs_path, cache_data)
|
||||
logger.info(f"[{job_id}] Waveform data cached at {cache_gcs_path}")
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
def load_cached_waveform(
|
||||
self,
|
||||
cache_gcs_path: str,
|
||||
) -> Optional[tuple[list[float], float]]:
|
||||
"""
|
||||
Load cached waveform data from GCS.
|
||||
|
||||
Args:
|
||||
cache_gcs_path: GCS path to the cached waveform JSON
|
||||
|
||||
Returns:
|
||||
Tuple of (amplitude_values, duration_seconds) or None if not found
|
||||
"""
|
||||
try:
|
||||
if not self.storage_service.file_exists(cache_gcs_path):
|
||||
return None
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_path = os.path.join(temp_dir, "waveform.json")
|
||||
self.storage_service.download_file(cache_gcs_path, local_path)
|
||||
with open(local_path) as f:
|
||||
data = json.load(f)
|
||||
|
||||
amplitudes = data.get("amplitudes", [])
|
||||
duration = data.get("duration_seconds", 0.0)
|
||||
if not amplitudes:
|
||||
return None
|
||||
|
||||
return amplitudes, duration
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to load cached waveform from {cache_gcs_path}: {e}")
|
||||
return None
|
||||
|
||||
def generate_waveform_with_mutes(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -34,164 +34,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 = {
|
||||
@@ -293,13 +141,21 @@ 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", [])),
|
||||
}
|
||||
else:
|
||||
# Use defaults if no config exists
|
||||
config = {
|
||||
"disposable_domains": DEFAULT_DISPOSABLE_DOMAINS.copy(),
|
||||
"blocked_emails": set(),
|
||||
@@ -398,13 +254,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 +288,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 +462,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
|
||||
|
||||
@@ -182,11 +182,14 @@ class FirestoreService:
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'url', 'filename', 'audio_search_artist', 'audio_search_title',
|
||||
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url',
|
||||
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
|
||||
'state_data.audio_progress', 'state_data.lyrics_progress',
|
||||
'state_data.audio_complete', 'state_data.lyrics_complete',
|
||||
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
|
||||
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
|
||||
'processing_metadata',
|
||||
]
|
||||
|
||||
def list_jobs_summary(
|
||||
|
||||
@@ -329,7 +329,10 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
# Get artist/title from config for proper naming
|
||||
artist = config.get("artist", "Unknown Artist")
|
||||
title = config.get("title", "Unknown Title")
|
||||
base_name = f"{artist} - {title}"
|
||||
# Sanitize for use in file paths (e.g., title "PORTRAIT/WALK/BORN" → "PORTRAIT_WALK_BORN")
|
||||
safe_artist = re.sub(r'[<>:"/\\|?*]', '_', artist)
|
||||
safe_title = re.sub(r'[<>:"/\\|?*]', '_', title)
|
||||
base_name = f"{safe_artist} - {safe_title}"
|
||||
logger.info(f"Encoding for: {base_name}")
|
||||
|
||||
# Find input files in work_dir
|
||||
|
||||
@@ -748,6 +748,31 @@ class JobManager:
|
||||
self.update_job(job_id, {'state_data': state_data})
|
||||
logger.debug(f"Job {job_id} state_data updated: {key} = {value}")
|
||||
|
||||
def update_processing_metadata(self, job_id: str, section: str, data) -> None:
|
||||
"""
|
||||
Write data into processing_metadata[section] using Firestore dot-notation.
|
||||
|
||||
Each worker writes its own section once. This uses Firestore's nested
|
||||
field update to avoid overwriting other workers' sections.
|
||||
|
||||
The section can use dot-notation for deeper nesting, e.g.
|
||||
'timing.lyrics_worker_seconds' writes to processing_metadata.timing.lyrics_worker_seconds
|
||||
without overwriting other timing entries.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
section: Metadata section path (e.g., 'transcription', 'timing.audio_worker_seconds')
|
||||
data: Value to store (dict for sections, scalar for individual fields)
|
||||
"""
|
||||
try:
|
||||
self.firestore.update_job(job_id, {
|
||||
f"processing_metadata.{section}": data,
|
||||
})
|
||||
logger.debug(f"Job {job_id} processing_metadata.{section} updated")
|
||||
except Exception as e:
|
||||
# Log but don't raise - metadata storage should never fail a job
|
||||
logger.warning(f"Job {job_id}: Failed to update processing_metadata.{section}: {e}")
|
||||
|
||||
def delete_state_data_key(self, job_id: str, key: str) -> bool:
|
||||
"""
|
||||
Delete a specific key from the job's state_data field.
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -334,7 +334,8 @@ class ThemeService:
|
||||
style_params = self._update_asset_paths_in_style(theme_id, style_params)
|
||||
|
||||
# Upload modified style_params.json to job's style folder
|
||||
job_style_path = f"uploads/{job_id}/style/style_params.json"
|
||||
# Uses jobs/ prefix (not uploads/) to avoid GCS lifecycle deletion rule
|
||||
job_style_path = f"jobs/{job_id}/style/style_params.json"
|
||||
self.storage.upload_json(job_style_path, style_params)
|
||||
|
||||
logger.info(f"Prepared job {job_id} style from theme {theme_id}")
|
||||
|
||||
@@ -150,15 +150,15 @@ class TestStyleLoadingFix:
|
||||
}
|
||||
|
||||
# Upload style JSON to GCS (the CORRECT location)
|
||||
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
|
||||
self.storage.upload_string(json.dumps(style_json), style_gcs_path)
|
||||
|
||||
# Upload mock assets
|
||||
assets = {
|
||||
"intro_background": f"uploads/{job_id}/style/intro_background.png",
|
||||
"karaoke_background": f"uploads/{job_id}/style/karaoke_background.png",
|
||||
"end_background": f"uploads/{job_id}/style/end_background.png",
|
||||
"font": f"uploads/{job_id}/style/font.ttf",
|
||||
"intro_background": f"jobs/{job_id}/style/intro_background.png",
|
||||
"karaoke_background": f"jobs/{job_id}/style/karaoke_background.png",
|
||||
"end_background": f"jobs/{job_id}/style/end_background.png",
|
||||
"font": f"jobs/{job_id}/style/font.ttf",
|
||||
}
|
||||
|
||||
for asset_key, gcs_path in assets.items():
|
||||
@@ -255,7 +255,7 @@ class TestStyleLoadingFix:
|
||||
job_id = f"test-bug-{int(time.time() * 1000)}"
|
||||
|
||||
# Upload style to CORRECT location
|
||||
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
|
||||
self.storage.upload_string('{"karaoke": {"font_size": 100}}', style_gcs_path)
|
||||
|
||||
# Create job with styles in CORRECT location
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""
|
||||
Unit tests for admin audio edit review endpoints.
|
||||
|
||||
Tests the GET /api/admin/audio-edit-reviews and
|
||||
GET /api/admin/audio-edit-reviews/{job_id} endpoints.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, AsyncMock
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
|
||||
|
||||
|
||||
# Create a test app with the admin router
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _make_audio_edit_job_doc(job_id, artist="Test Artist", title="Test Song",
|
||||
user_email="user@example.com", status="complete",
|
||||
has_edit_stack=True):
|
||||
"""Create a mock Firestore document for a job with audio edits."""
|
||||
doc = Mock()
|
||||
doc.id = job_id
|
||||
now = datetime.now(timezone.utc)
|
||||
state_data = {}
|
||||
if has_edit_stack:
|
||||
state_data["audio_edit_stack"] = [
|
||||
{"edit_id": "e1", "operation": "cut", "gcs_path": f"jobs/{job_id}/edits/e1.flac"}
|
||||
]
|
||||
|
||||
doc.to_dict.return_value = {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"user_email": user_email,
|
||||
"status": status,
|
||||
"state_data": state_data,
|
||||
"file_urls": {},
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
return doc
|
||||
|
||||
|
||||
def _make_session(job_id, trigger="auto", edit_count=3):
|
||||
"""Create a mock AudioEditSession."""
|
||||
return AudioEditSession(
|
||||
session_id="sess-1",
|
||||
job_id=job_id,
|
||||
user_email="user@example.com",
|
||||
edit_count=edit_count,
|
||||
trigger=trigger,
|
||||
audio_duration_seconds=150.0,
|
||||
original_duration_seconds=225.0,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
summary=AudioEditSessionSummary(
|
||||
total_operations=edit_count,
|
||||
operations_breakdown={"cut": 2, "mute": 1},
|
||||
duration_change_seconds=-75.0,
|
||||
net_duration_seconds=150.0,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestListAudioEditReviews:
|
||||
"""Tests for GET /api/admin/audio-edit-reviews."""
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_returns_jobs_with_edit_stacks(self, mock_get_user_service, MockFS, client):
|
||||
"""Jobs with audio edit stacks should appear."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_audio_edit_job_doc("job-1", has_edit_stack=True),
|
||||
_make_audio_edit_job_doc("job-2", has_edit_stack=False),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
# job-2 has no edit stack and no sessions subcollection
|
||||
sessions_ref = Mock()
|
||||
sessions_ref.limit.return_value.stream.return_value = iter([])
|
||||
mock_db.collection.return_value.document.return_value.collection.return_value = sessions_ref
|
||||
|
||||
# Sessions for job-1
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = [
|
||||
_make_session("job-1")
|
||||
]
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["job_id"] == "job-1"
|
||||
assert data["reviews"][0]["session_count"] == 1
|
||||
assert data["reviews"][0]["total_edits"] == 3
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_search_filter(self, mock_get_user_service, MockFS, client):
|
||||
"""Search should filter by artist, title, and email."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_audio_edit_job_doc("job-1", artist="Beatles", title="Hey Jude"),
|
||||
_make_audio_edit_job_doc("job-2", artist="Queen", title="Bohemian Rhapsody"),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = [_make_session("job-1")]
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews?search=beatles")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["artist"] == "Beatles"
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_pagination(self, mock_get_user_service, MockFS, client):
|
||||
"""Pagination should work with offset and limit."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [_make_audio_edit_job_doc(f"job-{i}") for i in range(5)]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = []
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews?limit=2&offset=0")
|
||||
data = response.json()
|
||||
assert len(data["reviews"]) == 2
|
||||
assert data["total"] == 5
|
||||
assert data["has_more"] is True
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_exclude_test_emails(self, mock_get_user_service, MockFS, client):
|
||||
"""Test emails should be excluded when exclude_test=true."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_audio_edit_job_doc("job-1", user_email="real@example.com"),
|
||||
_make_audio_edit_job_doc("job-2", user_email="test@inbox.testmail.app"),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = []
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews?exclude_test=true")
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["user_email"] == "real@example.com"
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_includes_in_audio_edit_jobs(self, mock_get_user_service, MockFS, client):
|
||||
"""Jobs in audio edit statuses should appear even without edit stack."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_audio_edit_job_doc("job-1", status="in_audio_edit", has_edit_stack=False),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = []
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews")
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["job_id"] == "job-1"
|
||||
|
||||
|
||||
class TestGetAudioEditReviewDetail:
|
||||
"""Tests for GET /api/admin/audio-edit-reviews/{job_id}."""
|
||||
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_returns_404_for_missing_job(self, MockJobManager, MockStorage, client):
|
||||
MockJobManager.return_value.get_job.return_value = None
|
||||
response = client.get("/api/admin/audio-edit-reviews/nonexistent")
|
||||
assert response.status_code == 404
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.AudioTranscodingService")
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_returns_full_detail(self, MockJobManager, MockStorage, MockFS, MockTranscoding, client):
|
||||
"""Should return job metadata, sessions, edit stack, and audio URLs."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job"
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Song"
|
||||
job.user_email = "user@example.com"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.created_at = datetime(2026, 3, 1, tzinfo=timezone.utc)
|
||||
job.updated_at = datetime(2026, 3, 2, tzinfo=timezone.utc)
|
||||
job.input_media_gcs_path = "jobs/test-job/input/edited.flac"
|
||||
job.state_data = {
|
||||
"audio_edit_stack": [
|
||||
{"edit_id": "e1", "operation": "cut", "gcs_path": "jobs/test-job/edits/e1.flac",
|
||||
"duration_before": 225, "duration_after": 150, "timestamp": "2026-03-01T10:00:00"},
|
||||
],
|
||||
"original_input_media_gcs_path": "jobs/test-job/input/original.flac",
|
||||
}
|
||||
MockJobManager.return_value.get_job.return_value = job
|
||||
|
||||
storage = MockStorage.return_value
|
||||
storage.file_exists.return_value = False
|
||||
|
||||
session = _make_session("test-job", trigger="submit")
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = [session]
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews/test-job")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
assert data["job"]["job_id"] == "test-job"
|
||||
assert data["job"]["artist"] == "Test Artist"
|
||||
assert len(data["sessions"]) == 1
|
||||
assert data["sessions"][0]["trigger"] == "submit"
|
||||
assert len(data["edit_stack"]) == 1
|
||||
assert data["edit_stack"][0]["operation"] == "cut"
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_handles_empty_state_gracefully(self, MockJobManager, MockStorage, MockFS, client):
|
||||
"""Should handle jobs with no edit data gracefully."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job"
|
||||
job.artist = "Test"
|
||||
job.title = "Song"
|
||||
job.user_email = "u@e.com"
|
||||
job.status = JobStatus.AWAITING_AUDIO_EDIT
|
||||
job.created_at = None
|
||||
job.updated_at = None
|
||||
job.input_media_gcs_path = None
|
||||
job.state_data = {}
|
||||
MockJobManager.return_value.get_job.return_value = job
|
||||
|
||||
storage = MockStorage.return_value
|
||||
storage.file_exists.return_value = False
|
||||
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = []
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews/test-job")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["sessions"] == []
|
||||
assert data["edit_stack"] == []
|
||||
assert data["edit_log"] is None
|
||||
@@ -1016,3 +1016,103 @@ class TestResetEndpointWithRealJobData:
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
assert response.json()["new_status"] == "pending"
|
||||
|
||||
|
||||
class TestResetJobToAwaitingAudioEdit:
|
||||
"""Tests for resetting job to AWAITING_AUDIO_EDIT state."""
|
||||
|
||||
def test_reset_to_awaiting_audio_edit_success(self, client, mock_job):
|
||||
"""Test resetting a job to awaiting_audio_edit."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_audio_edit"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["new_status"] == "awaiting_audio_edit"
|
||||
|
||||
def test_reset_clears_edit_stack_and_downstream_flags(self, client):
|
||||
"""Test that resetting clears audio edit state and downstream processing flags."""
|
||||
from datetime import UTC
|
||||
job = Job(
|
||||
job_id="test-job-123",
|
||||
status=JobStatus.COMPLETE,
|
||||
artist="Test",
|
||||
title="Song",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={
|
||||
"audio_edit_stack": [{"edit_id": "e1"}],
|
||||
"audio_edit_redo_stack": [{"edit_id": "e2"}],
|
||||
"audio_complete": True,
|
||||
"lyrics_complete": True,
|
||||
"review_complete": True,
|
||||
"screens_progress": {"stage": "complete"},
|
||||
}
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.update_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_audio_edit"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
cleared = data.get("cleared_data", [])
|
||||
assert "audio_edit_stack" in cleared
|
||||
assert "audio_edit_redo_stack" in cleared
|
||||
assert "audio_complete" in cleared
|
||||
assert "lyrics_complete" in cleared
|
||||
assert "review_complete" in cleared
|
||||
assert "screens_progress" in cleared
|
||||
|
||||
def test_reset_restores_original_input_media_path(self, client):
|
||||
"""Critical test: resetting to audio edit must restore the original
|
||||
input_media_gcs_path. The submit endpoint overwrites this with edited
|
||||
audio, so the reset must undo that to let the user start fresh."""
|
||||
from datetime import UTC
|
||||
job = Job(
|
||||
job_id="test-job-123",
|
||||
status=JobStatus.COMPLETE,
|
||||
artist="Test",
|
||||
title="Song",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
input_media_gcs_path="jobs/test-job-123/input/edited.flac",
|
||||
state_data={
|
||||
"original_input_media_gcs_path": "jobs/test-job-123/input/original.flac",
|
||||
"audio_edit_stack": [{"edit_id": "e1"}],
|
||||
}
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.update_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_audio_edit"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
# Verify the Firestore update included restoring the original path
|
||||
# The update goes through job_ref.update() which is the mock_db call
|
||||
# We check the update_job call for status change
|
||||
update_args = mock_jm.update_job.call_args[0][1]
|
||||
assert update_args["status"] == "awaiting_audio_edit"
|
||||
@@ -5,7 +5,9 @@ These tests mock the storage service and shared karaoke_gen modules to verify:
|
||||
- GCS file download/upload operations
|
||||
- Audio analysis delegation to shared AudioAnalyzer
|
||||
- Waveform generation delegation to shared WaveformGenerator
|
||||
- Waveform data caching (cache_waveform_data / load_cached_waveform)
|
||||
"""
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch, ANY
|
||||
import tempfile
|
||||
@@ -292,3 +294,119 @@ class TestGenerateWaveformWithMutes:
|
||||
# Verify return
|
||||
assert result_path == "uploads/job123/waveform_muted.png"
|
||||
|
||||
|
||||
class TestCacheWaveformData:
|
||||
"""Test cache_waveform_data method."""
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_caches_waveform_to_gcs(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""cache_waveform_data should generate waveform and upload JSON to GCS."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
mock_waveform = Mock()
|
||||
mock_waveform.generate_data_only.return_value = ([0.1, 0.5, 0.3], 200.0)
|
||||
mock_waveform_class.return_value = mock_waveform
|
||||
|
||||
service = AudioAnalysisService()
|
||||
|
||||
amplitudes, duration = service.cache_waveform_data(
|
||||
gcs_audio_path="jobs/j1/input/song.flac",
|
||||
job_id="j1",
|
||||
cache_gcs_path="jobs/j1/audio_edit/waveform_original.json",
|
||||
num_points=1000,
|
||||
)
|
||||
|
||||
assert amplitudes == [0.1, 0.5, 0.3]
|
||||
assert duration == 200.0
|
||||
|
||||
# Verify JSON was uploaded with correct structure
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
call_args = mock_storage.upload_json.call_args
|
||||
assert call_args[0][0] == "jobs/j1/audio_edit/waveform_original.json"
|
||||
uploaded_data = call_args[0][1]
|
||||
assert uploaded_data["amplitudes"] == [0.1, 0.5, 0.3]
|
||||
assert uploaded_data["duration_seconds"] == 200.0
|
||||
assert uploaded_data["num_points"] == 1000
|
||||
assert uploaded_data["source_gcs_path"] == "jobs/j1/input/song.flac"
|
||||
|
||||
|
||||
class TestLoadCachedWaveform:
|
||||
"""Test load_cached_waveform method."""
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_returns_none_when_cache_missing(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""Should return None when cache file doesn't exist."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
service = AudioAnalysisService()
|
||||
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_loads_cached_waveform(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""Should load and parse cached waveform JSON from GCS."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
cache_data = {
|
||||
"amplitudes": [0.2, 0.6, 0.4],
|
||||
"duration_seconds": 180.0,
|
||||
"num_points": 1000,
|
||||
"source_gcs_path": "jobs/j1/input/song.flac",
|
||||
}
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
# Simulate download_file writing JSON to the local path
|
||||
def write_json(gcs_path, local_path):
|
||||
with open(local_path, 'w') as f:
|
||||
json.dump(cache_data, f)
|
||||
mock_storage.download_file.side_effect = write_json
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
service = AudioAnalysisService()
|
||||
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
|
||||
|
||||
assert result is not None
|
||||
amplitudes, duration = result
|
||||
assert amplitudes == [0.2, 0.6, 0.4]
|
||||
assert duration == 180.0
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_returns_none_on_error(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""Should return None gracefully on any error."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.download_file.side_effect = Exception("GCS timeout")
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
service = AudioAnalysisService()
|
||||
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
|
||||
|
||||
assert result is None
|
||||
|
||||
@@ -183,6 +183,85 @@ class TestProcessAudioDownload:
|
||||
assert call_kwargs['source_id'] == 'spotify123'
|
||||
|
||||
|
||||
class TestAudioEditPreGeneration:
|
||||
"""Tests for pre-generation of editor assets when requires_audio_edit is set."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pregenerates_assets_when_audio_edit_requested(self):
|
||||
"""Should transcode OGG + cache waveform before transitioning to awaiting_audio_edit."""
|
||||
job = _make_job(state_data={'requires_audio_edit': True})
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService") as MockTS, \
|
||||
patch("backend.services.audio_analysis_service.AudioAnalysisService") as MockAS:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
# First get_job returns the initial job, second returns the one with requires_audio_edit
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.flac", "song.flac")
|
||||
|
||||
mock_ts = MagicMock()
|
||||
MockTS.return_value = mock_ts
|
||||
|
||||
mock_as = MagicMock()
|
||||
mock_as.cache_waveform_data.return_value = ([0.1, 0.5], 200.0)
|
||||
MockAS.return_value = mock_as
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is True
|
||||
# Should have transcoded OGG
|
||||
mock_ts.transcode_if_needed.assert_called_once_with("uploads/test-job-123/audio/song.flac")
|
||||
# Should have cached waveform
|
||||
mock_as.cache_waveform_data.assert_called_once_with(
|
||||
"uploads/test-job-123/audio/song.flac",
|
||||
"test-job-123",
|
||||
"jobs/test-job-123/audio_edit/waveform_original.json",
|
||||
)
|
||||
# Should have stored cache path in state_data
|
||||
mock_jm.update_state_data.assert_any_call(
|
||||
"test-job-123", "audio_edit_waveform_cache_path",
|
||||
"jobs/test-job-123/audio_edit/waveform_original.json",
|
||||
)
|
||||
# Should have transitioned to awaiting_audio_edit
|
||||
calls = mock_jm.transition_to_state.call_args_list
|
||||
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pregeneration_failure_is_nonfatal(self):
|
||||
"""Pre-generation failure should not prevent the job from reaching awaiting_audio_edit."""
|
||||
job = _make_job(state_data={'requires_audio_edit': True})
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService") as MockTS:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.flac", "song.flac")
|
||||
|
||||
# Transcoding fails
|
||||
mock_ts = MagicMock()
|
||||
mock_ts.transcode_if_needed.side_effect = RuntimeError("ffmpeg not found")
|
||||
MockTS.return_value = mock_ts
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
# Should still succeed and transition to awaiting_audio_edit
|
||||
assert result is True
|
||||
calls = mock_jm.transition_to_state.call_args_list
|
||||
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
|
||||
|
||||
|
||||
class TestDownloadAudio:
|
||||
"""Tests for _download_audio routing."""
|
||||
|
||||
|
||||
@@ -170,6 +170,66 @@ class TestGetInputAudioInfo:
|
||||
resp = test_client.get("/api/review/no-audio/input-audio-info")
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_uses_cached_waveform_when_available(self, test_client, mock_job_manager, mock_services):
|
||||
"""When waveform cache exists, should use it instead of on-demand generation."""
|
||||
job = _job(
|
||||
job_id="cached-job",
|
||||
status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/cached-job/input/song.flac",
|
||||
state_data={"audio_edit_waveform_cache_path": "jobs/cached-job/audio_edit/waveform_original.json"},
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_services["analysis"].load_cached_waveform.return_value = ([0.2, 0.6, 0.4], 180.0)
|
||||
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=180.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
resp = test_client.get("/api/review/cached-job/input-audio-info")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["original_duration_seconds"] == 180.0
|
||||
assert data["original_waveform_data"]["amplitudes"] == [0.2, 0.6, 0.4]
|
||||
# Should have used cache, not on-demand generation
|
||||
mock_services["analysis"].load_cached_waveform.assert_called_once_with(
|
||||
"jobs/cached-job/audio_edit/waveform_original.json"
|
||||
)
|
||||
mock_services["analysis"].get_waveform_data.assert_not_called()
|
||||
|
||||
def test_falls_back_to_on_demand_when_cache_missing(self, test_client, mock_job_manager, mock_services):
|
||||
"""When waveform cache path is set but cache doesn't exist, should fall back."""
|
||||
job = _job(
|
||||
job_id="no-cache-job",
|
||||
status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/no-cache-job/input/song.flac",
|
||||
state_data={"audio_edit_waveform_cache_path": "jobs/no-cache-job/audio_edit/waveform_original.json"},
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_services["analysis"].load_cached_waveform.return_value = None
|
||||
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
resp = test_client.get("/api/review/no-cache-job/input-audio-info")
|
||||
assert resp.status_code == 200
|
||||
# Should have fallen back to on-demand
|
||||
mock_services["analysis"].get_waveform_data.assert_called_once()
|
||||
|
||||
def test_on_demand_when_no_cache_path_in_state(self, test_client, mock_job_manager, mock_services, audio_edit_job):
|
||||
"""Jobs without cache path in state_data should use on-demand generation."""
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
resp = test_client.get("/api/review/edit-job-1/input-audio-info")
|
||||
assert resp.status_code == 200
|
||||
# No cache path → should not attempt to load cache
|
||||
mock_services["analysis"].load_cached_waveform.assert_not_called()
|
||||
mock_services["analysis"].get_waveform_data.assert_called_once()
|
||||
|
||||
|
||||
# --- POST /audio-edit/apply ---
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ Tests cover:
|
||||
- Timestamp adjustment for instrumental audio sync
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
|
||||
|
||||
@@ -247,3 +249,77 @@ class TestCDGGenerateFromLRCWithCountdown:
|
||||
|
||||
# Verify _remove_countdown_from_lyrics was NOT called
|
||||
mock_remove.assert_not_called()
|
||||
|
||||
|
||||
class TestCDGFontFallback:
|
||||
"""Test font resolution and fallback behavior in _validate_and_setup_font."""
|
||||
|
||||
@pytest.fixture
|
||||
def generator(self, tmp_path):
|
||||
return CDGGenerator(output_dir=str(tmp_path))
|
||||
|
||||
def test_absolute_path_that_exists_is_unchanged(self, generator, tmp_path):
|
||||
"""An absolute path to an existing font is used as-is."""
|
||||
font_file = tmp_path / "myfont.ttf"
|
||||
font_file.write_bytes(b"fake font")
|
||||
cdg_styles = {"font_path": str(font_file)}
|
||||
generator._validate_and_setup_font(cdg_styles)
|
||||
assert cdg_styles["font_path"] == str(font_file)
|
||||
|
||||
def test_nonexistent_path_falls_back_to_bundled_by_filename(self, generator):
|
||||
"""A path like 'themes/nomad/assets/AvenirNext-Bold.ttf' should resolve
|
||||
to the bundled AvenirNext-Bold.ttf by filename."""
|
||||
cdg_styles = {"font_path": "themes/nomad/assets/AvenirNext-Bold.ttf"}
|
||||
generator._validate_and_setup_font(cdg_styles)
|
||||
assert cdg_styles["font_path"] is not None
|
||||
assert cdg_styles["font_path"].endswith("AvenirNext-Bold.ttf")
|
||||
assert os.path.isfile(cdg_styles["font_path"])
|
||||
|
||||
def test_totally_unknown_font_falls_back_to_arial(self, generator):
|
||||
"""A completely unknown font name falls back to bundled arial.ttf."""
|
||||
cdg_styles = {"font_path": "nonexistent/path/SuperRareFont.ttf"}
|
||||
generator._validate_and_setup_font(cdg_styles)
|
||||
assert cdg_styles["font_path"] is not None
|
||||
assert cdg_styles["font_path"].endswith("arial.ttf")
|
||||
assert os.path.isfile(cdg_styles["font_path"])
|
||||
|
||||
def test_none_font_path_is_left_alone(self, generator):
|
||||
"""If font_path is already None, _validate_and_setup_font returns early."""
|
||||
cdg_styles = {"font_path": None}
|
||||
generator._validate_and_setup_font(cdg_styles)
|
||||
assert cdg_styles["font_path"] is None
|
||||
|
||||
def test_create_toml_data_raises_on_none_font(self, generator):
|
||||
"""_create_toml_data raises RuntimeError if font_path is None."""
|
||||
cdg_styles = {
|
||||
"font_path": None,
|
||||
"clear_mode": "eager",
|
||||
"sync_offset": 0,
|
||||
"background_color": "#000000",
|
||||
"border_color": "#000000",
|
||||
"font_size": 18,
|
||||
"stroke_width": 0,
|
||||
"stroke_style": "octagon",
|
||||
"active_fill": "#ffffff",
|
||||
"active_stroke": "#000000",
|
||||
"inactive_fill": "#888888",
|
||||
"inactive_stroke": "#000000",
|
||||
"title_color": "#ffffff",
|
||||
"artist_color": "#ffffff",
|
||||
"title_screen_background": "/tmp/fake.png",
|
||||
"title_screen_transition": "centertexttoplogobottomtext",
|
||||
"row": 4,
|
||||
"line_tile_height": 3,
|
||||
"lines_per_page": 4,
|
||||
}
|
||||
with pytest.raises(RuntimeError, match="CDG font_path is None"):
|
||||
generator._create_toml_data(
|
||||
title="Test",
|
||||
artist="Artist",
|
||||
audio_file="/tmp/audio.flac",
|
||||
output_name="output",
|
||||
sync_times=[100, 200],
|
||||
instrumentals=[],
|
||||
formatted_lyrics=["HELLO", "WORLD"],
|
||||
cdg_styles=cdg_styles,
|
||||
)
|
||||
@@ -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"}
|
||||
@@ -869,3 +869,47 @@ class TestVideoWorkerDistribution:
|
||||
|
||||
# Should log warning about import error
|
||||
mock_job_log.warning.assert_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handle_native_distribution_with_warnings_does_not_crash(self):
|
||||
"""Test that distribution_warnings path doesn't raise NameError.
|
||||
|
||||
Regression test: _handle_native_distribution used to reference
|
||||
undefined 'settings' variable when distribution_warnings were present.
|
||||
"""
|
||||
from backend.workers.video_worker import _handle_native_distribution
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.dropbox_path = None
|
||||
mock_job.gdrive_folder_id = None
|
||||
mock_job.is_private = False
|
||||
mock_job.artist = "Test Artist"
|
||||
mock_job.title = "Test Song"
|
||||
mock_job.state_data = {}
|
||||
|
||||
mock_job_log = MagicMock()
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
# Result with distribution_warnings triggers the notification path
|
||||
result_with_warnings = {
|
||||
'distribution_warnings': ['Dropbox upload failed: timeout'],
|
||||
}
|
||||
|
||||
# Should NOT raise NameError for undefined 'settings'
|
||||
with patch('backend.workers.video_worker._send_distribution_warning_notification') as mock_notify:
|
||||
await _handle_native_distribution(
|
||||
job_id="test-warnings",
|
||||
job=mock_job,
|
||||
job_log=mock_job_log,
|
||||
job_manager=mock_job_manager,
|
||||
temp_dir="/tmp/test",
|
||||
result=result_with_warnings,
|
||||
)
|
||||
|
||||
# Verify notification was called (proving the code path was exercised)
|
||||
mock_notify.assert_called_once_with(
|
||||
job_id="test-warnings",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
warnings=['Dropbox upload failed: timeout'],
|
||||
)
|
||||
@@ -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
|
||||
@@ -111,10 +111,17 @@ class TestDisposableDomainDetection:
|
||||
|
||||
@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": [],
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@@ -130,7 +137,6 @@ class TestDisposableDomainDetection:
|
||||
|
||||
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
|
||||
@@ -209,6 +215,188 @@ class TestBlocklistManagement:
|
||||
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"],
|
||||
}
|
||||
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_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."""
|
||||
|
||||
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -698,21 +698,21 @@ class TestSignedUrlGCSPathGeneration:
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_params", "style.json")
|
||||
assert path == "uploads/test123/style/style_params.json"
|
||||
assert path == "jobs/test123/style/style_params.json"
|
||||
|
||||
def test_style_background_gcs_path(self):
|
||||
"""Test GCS path generation for style background images."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_intro_background", "bg.png")
|
||||
assert path == "uploads/test123/style/intro_background.png"
|
||||
assert path == "jobs/test123/style/intro_background.png"
|
||||
|
||||
def test_style_font_gcs_path(self):
|
||||
"""Test GCS path generation for font file."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_font", "font.ttf")
|
||||
assert path == "uploads/test123/style/font.ttf"
|
||||
assert path == "jobs/test123/style/font.ttf"
|
||||
|
||||
def test_lyrics_file_gcs_path(self):
|
||||
"""Test GCS path generation for lyrics file."""
|
||||
|
||||
@@ -0,0 +1,781 @@
|
||||
"""
|
||||
Tests for processing_metadata field and related functionality.
|
||||
|
||||
Covers:
|
||||
- Job model has processing_metadata field
|
||||
- processing_metadata is in SUMMARY_FIELD_PATHS (regression test)
|
||||
- update_processing_metadata helper works correctly
|
||||
- AudioShake transcriber stores asset_id in metadata
|
||||
- Corrector passes through transcription metadata
|
||||
- extract_request_metadata includes auth context when provided
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from datetime import datetime
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
class TestProcessingMetadataField:
|
||||
"""Test the processing_metadata field on the Job model."""
|
||||
|
||||
def test_job_has_processing_metadata_field(self):
|
||||
"""processing_metadata should exist and default to empty dict."""
|
||||
job = Job(
|
||||
job_id="test-123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
assert hasattr(job, 'processing_metadata')
|
||||
assert job.processing_metadata == {}
|
||||
|
||||
def test_processing_metadata_serializes(self):
|
||||
"""processing_metadata should serialize to JSON correctly."""
|
||||
job = Job(
|
||||
job_id="test-123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
processing_metadata={
|
||||
"transcription": {
|
||||
"provider": "audioshake",
|
||||
"audioshake_task_id": "task-abc",
|
||||
"audioshake_asset_id": "asset-xyz",
|
||||
},
|
||||
},
|
||||
)
|
||||
data = job.model_dump(mode='json')
|
||||
assert data['processing_metadata']['transcription']['audioshake_task_id'] == "task-abc"
|
||||
assert data['processing_metadata']['transcription']['audioshake_asset_id'] == "asset-xyz"
|
||||
|
||||
def test_processing_metadata_deserializes(self):
|
||||
"""processing_metadata should deserialize from dict correctly."""
|
||||
data = {
|
||||
"job_id": "test-123",
|
||||
"status": "pending",
|
||||
"created_at": datetime.utcnow(),
|
||||
"updated_at": datetime.utcnow(),
|
||||
"processing_metadata": {
|
||||
"separation": {
|
||||
"provider": "modal",
|
||||
"duration_seconds": 420.5,
|
||||
},
|
||||
},
|
||||
}
|
||||
job = Job(**data)
|
||||
assert job.processing_metadata["separation"]["provider"] == "modal"
|
||||
assert job.processing_metadata["separation"]["duration_seconds"] == 420.5
|
||||
|
||||
|
||||
class TestSummaryFieldPaths:
|
||||
"""Regression tests for SUMMARY_FIELD_PATHS."""
|
||||
|
||||
def test_processing_metadata_in_summary_field_paths(self):
|
||||
"""processing_metadata must be in SUMMARY_FIELD_PATHS for dashboard queries."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
assert 'processing_metadata' in FirestoreService.SUMMARY_FIELD_PATHS
|
||||
|
||||
|
||||
class TestUpdateProcessingMetadata:
|
||||
"""Test the JobManager.update_processing_metadata helper."""
|
||||
|
||||
@patch('backend.services.job_manager.FirestoreService')
|
||||
@patch('backend.services.job_manager.StorageService')
|
||||
def test_update_processing_metadata_uses_dot_notation(self, mock_storage_cls, mock_firestore_cls):
|
||||
"""update_processing_metadata should use Firestore dot-notation for nested updates."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore_cls.return_value = mock_firestore
|
||||
|
||||
jm = JobManager()
|
||||
jm.update_processing_metadata("job-123", "transcription", {
|
||||
"provider": "audioshake",
|
||||
"audioshake_task_id": "task-abc",
|
||||
})
|
||||
|
||||
# Should call update_job with dot-notation key
|
||||
mock_firestore.update_job.assert_called_once()
|
||||
call_args = mock_firestore.update_job.call_args
|
||||
assert call_args[0][0] == "job-123"
|
||||
updates = call_args[0][1]
|
||||
assert "processing_metadata.transcription" in updates
|
||||
assert updates["processing_metadata.transcription"]["provider"] == "audioshake"
|
||||
|
||||
@patch('backend.services.job_manager.FirestoreService')
|
||||
@patch('backend.services.job_manager.StorageService')
|
||||
def test_update_processing_metadata_deep_dot_notation(self, mock_storage_cls, mock_firestore_cls):
|
||||
"""Deeper dot-notation paths (e.g. timing.worker_seconds) avoid overwriting sibling fields."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore_cls.return_value = mock_firestore
|
||||
|
||||
jm = JobManager()
|
||||
jm.update_processing_metadata("job-123", "timing.lyrics_worker_seconds", 42.5)
|
||||
|
||||
call_args = mock_firestore.update_job.call_args
|
||||
updates = call_args[0][1]
|
||||
assert "processing_metadata.timing.lyrics_worker_seconds" in updates
|
||||
assert updates["processing_metadata.timing.lyrics_worker_seconds"] == 42.5
|
||||
|
||||
@patch('backend.services.job_manager.FirestoreService')
|
||||
@patch('backend.services.job_manager.StorageService')
|
||||
def test_update_processing_metadata_swallows_errors(self, mock_storage_cls, mock_firestore_cls):
|
||||
"""update_processing_metadata should not raise on failure."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.update_job.side_effect = Exception("Firestore error")
|
||||
mock_firestore_cls.return_value = mock_firestore
|
||||
|
||||
jm = JobManager()
|
||||
# Should not raise
|
||||
jm.update_processing_metadata("job-123", "timing", {"foo": 1})
|
||||
|
||||
|
||||
class TestAudioShakeAssetId:
|
||||
"""Test that AudioShake transcriber stores asset_id in metadata."""
|
||||
|
||||
def test_convert_result_format_includes_asset_id(self):
|
||||
"""_convert_result_format should include asset_id from task_data.assetId."""
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
|
||||
|
||||
# Create a minimal transcriber instance
|
||||
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
|
||||
transcriber.logger = MagicMock()
|
||||
transcriber._last_asset_id = "fallback-asset-id"
|
||||
|
||||
raw_data = {
|
||||
"task_data": {
|
||||
"id": "task-123",
|
||||
"assetId": "asset-456",
|
||||
"duration": 120.5,
|
||||
"targets": [],
|
||||
},
|
||||
"transcription": {
|
||||
"text": "hello world",
|
||||
"lines": [
|
||||
{
|
||||
"text": "hello world",
|
||||
"words": [
|
||||
{"text": "hello", "start": 0.0, "end": 0.5},
|
||||
{"text": "world", "start": 0.6, "end": 1.0},
|
||||
],
|
||||
}
|
||||
],
|
||||
"metadata": {"language": "en"},
|
||||
},
|
||||
}
|
||||
|
||||
result = transcriber._convert_result_format(raw_data)
|
||||
assert result.metadata["task_id"] == "task-123"
|
||||
assert result.metadata["asset_id"] == "asset-456"
|
||||
assert result.metadata["language"] == "en"
|
||||
|
||||
def test_convert_result_format_fallback_asset_id(self):
|
||||
"""asset_id should fall back to _last_asset_id if not in task_data."""
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
|
||||
|
||||
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
|
||||
transcriber.logger = MagicMock()
|
||||
transcriber._last_asset_id = "fallback-asset-id"
|
||||
|
||||
raw_data = {
|
||||
"task_data": {
|
||||
"id": "task-123",
|
||||
# No assetId in task_data
|
||||
"targets": [],
|
||||
},
|
||||
"transcription": {
|
||||
"text": "hello",
|
||||
"lines": [
|
||||
{
|
||||
"text": "hello",
|
||||
"words": [{"text": "hello", "start": 0.0, "end": 0.5}],
|
||||
}
|
||||
],
|
||||
"metadata": {},
|
||||
},
|
||||
}
|
||||
|
||||
result = transcriber._convert_result_format(raw_data)
|
||||
assert result.metadata["asset_id"] == "fallback-asset-id"
|
||||
|
||||
|
||||
class TestCorrectorMetadataPassthrough:
|
||||
"""Test that corrector passes through transcription metadata."""
|
||||
|
||||
def test_correction_result_includes_transcription_metadata(self):
|
||||
"""CorrectionResult.metadata should include transcription_metadata from primary transcription."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
|
||||
from karaoke_gen.lyrics_transcriber.types import (
|
||||
TranscriptionResult, TranscriptionData, LyricsSegment, Word
|
||||
)
|
||||
|
||||
# Create a minimal corrector
|
||||
corrector = LyricsCorrector(cache_dir="/tmp", enabled_handlers=[])
|
||||
|
||||
# Create transcription result with metadata
|
||||
word = Word(id="w1", text="hello", start_time=0.0, end_time=0.5)
|
||||
segment = LyricsSegment(id="s1", text="hello", words=[word], start_time=0.0, end_time=0.5)
|
||||
transcription_data = TranscriptionData(
|
||||
text="hello",
|
||||
words=[word],
|
||||
segments=[segment],
|
||||
source="AudioShake",
|
||||
metadata={
|
||||
"task_id": "task-123",
|
||||
"asset_id": "asset-456",
|
||||
"language": "en",
|
||||
},
|
||||
)
|
||||
transcription_result = TranscriptionResult(
|
||||
name="AudioShake",
|
||||
priority=1,
|
||||
result=transcription_data,
|
||||
)
|
||||
|
||||
# Run corrector with no reference lyrics (will skip correction but still build result)
|
||||
result = corrector.run(
|
||||
transcription_results=[transcription_result],
|
||||
lyrics_results={},
|
||||
)
|
||||
|
||||
# Check that transcription_metadata is passed through
|
||||
assert "transcription_metadata" in result.metadata
|
||||
assert result.metadata["transcription_metadata"]["task_id"] == "task-123"
|
||||
assert result.metadata["transcription_metadata"]["asset_id"] == "asset-456"
|
||||
|
||||
|
||||
class TestExtractRequestMetadataAuthContext:
|
||||
"""Test that extract_request_metadata includes auth context."""
|
||||
|
||||
def _make_request(self):
|
||||
"""Create a minimal mock request."""
|
||||
request = MagicMock()
|
||||
request.headers = {
|
||||
"user-agent": "test-agent",
|
||||
"x-forwarded-for": "1.2.3.4",
|
||||
}
|
||||
request.client = MagicMock()
|
||||
request.client.host = "127.0.0.1"
|
||||
return request
|
||||
|
||||
def test_auth_context_included_when_provided(self):
|
||||
"""Auth context should be in metadata when auth_result is provided."""
|
||||
from backend.api.routes.file_upload import extract_request_metadata
|
||||
|
||||
auth_result = MagicMock()
|
||||
auth_result.auth_method = "session"
|
||||
auth_result.user_type = MagicMock()
|
||||
auth_result.user_type.value = "unlimited"
|
||||
auth_result.remaining_uses = 42
|
||||
|
||||
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
|
||||
assert metadata['auth_method'] == "session"
|
||||
assert metadata['user_type'] == "unlimited"
|
||||
assert metadata['credits_at_creation'] == 42
|
||||
|
||||
def test_no_auth_context_without_auth_result(self):
|
||||
"""No auth context should be added when auth_result is None."""
|
||||
from backend.api.routes.file_upload import extract_request_metadata
|
||||
|
||||
metadata = extract_request_metadata(self._make_request())
|
||||
assert 'auth_method' not in metadata
|
||||
assert 'user_type' not in metadata
|
||||
assert 'credits_at_creation' not in metadata
|
||||
|
||||
def test_audio_search_extract_includes_auth(self):
|
||||
"""audio_search extract_request_metadata should also support auth_result."""
|
||||
from backend.api.routes.audio_search import extract_request_metadata
|
||||
|
||||
auth_result = MagicMock()
|
||||
auth_result.auth_method = "api_key"
|
||||
auth_result.user_type = MagicMock()
|
||||
auth_result.user_type.value = "limited"
|
||||
auth_result.remaining_uses = 5
|
||||
|
||||
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
|
||||
assert metadata['auth_method'] == "api_key"
|
||||
assert metadata['user_type'] == "limited"
|
||||
assert metadata['credits_at_creation'] == 5
|
||||
|
||||
def test_auth_without_remaining_uses(self):
|
||||
"""Should handle auth_result with no remaining_uses (e.g., admin)."""
|
||||
from backend.api.routes.file_upload import extract_request_metadata
|
||||
|
||||
auth_result = MagicMock(spec=['auth_method', 'user_type'])
|
||||
auth_result.auth_method = "admin_token"
|
||||
auth_result.user_type = MagicMock()
|
||||
auth_result.user_type.value = "admin"
|
||||
|
||||
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
|
||||
assert metadata['auth_method'] == "admin_token"
|
||||
assert metadata['user_type'] == "admin"
|
||||
assert 'credits_at_creation' not in metadata
|
||||
|
||||
def test_auth_with_none_user_type(self):
|
||||
"""Should handle auth_result where user_type is None."""
|
||||
from backend.api.routes.file_upload import extract_request_metadata
|
||||
|
||||
auth_result = MagicMock()
|
||||
auth_result.auth_method = "session"
|
||||
auth_result.user_type = None
|
||||
auth_result.remaining_uses = 10
|
||||
|
||||
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
|
||||
assert metadata['auth_method'] == "session"
|
||||
assert metadata['user_type'] is None
|
||||
assert metadata['credits_at_creation'] == 10
|
||||
|
||||
|
||||
class TestStoreLyricsProcessingMetadata:
|
||||
"""Test the _store_lyrics_processing_metadata helper function."""
|
||||
|
||||
def test_extracts_audioshake_ids_from_corrections(self, tmp_path):
|
||||
"""Should extract task_id and asset_id from corrections.json metadata."""
|
||||
import json
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
# Create a mock corrections file
|
||||
lyrics_dir = tmp_path / "lyrics"
|
||||
lyrics_dir.mkdir()
|
||||
corrections_file = lyrics_dir / "Artist - Title (Lyrics Corrections).json"
|
||||
corrections_data = {
|
||||
"metadata": {
|
||||
"transcription_metadata": {
|
||||
"task_id": "task-abc",
|
||||
"asset_id": "asset-xyz",
|
||||
"language": "en",
|
||||
},
|
||||
"enabled_handlers": ["anchor_sequence", "gap_word_count"],
|
||||
"correction_ratio": 0.95,
|
||||
"total_words": 100,
|
||||
"agentic_routing": "rule-based",
|
||||
"anchor_sequences_count": 5,
|
||||
"gap_sequences_count": 3,
|
||||
},
|
||||
"corrections_made": 5,
|
||||
"corrected_segments": [
|
||||
{"words": [{"text": "w1"}, {"text": "w2"}]},
|
||||
{"words": [{"text": "w3"}]},
|
||||
],
|
||||
"reference_lyrics": {"genius": {}, "spotify": {}},
|
||||
}
|
||||
corrections_file.write_text(json.dumps(corrections_data))
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={"lyrics_dir": str(lyrics_dir)},
|
||||
transcription_duration=45.6,
|
||||
cache_stats={"downloaded": 2, "not_found": 1},
|
||||
job_log=job_log,
|
||||
)
|
||||
|
||||
# Check transcription metadata was stored
|
||||
transcription_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "transcription"
|
||||
]
|
||||
assert len(transcription_call) == 1
|
||||
trans_data = transcription_call[0][0][2]
|
||||
assert trans_data["provider"] == "audioshake"
|
||||
assert trans_data["audioshake_task_id"] == "task-abc"
|
||||
assert trans_data["audioshake_asset_id"] == "asset-xyz"
|
||||
assert trans_data["segment_count"] == 2
|
||||
assert trans_data["word_count"] == 3
|
||||
assert trans_data["duration_seconds"] == 45.6
|
||||
|
||||
# Check correction metadata was stored
|
||||
correction_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "correction"
|
||||
]
|
||||
assert len(correction_call) == 1
|
||||
corr_data = correction_call[0][0][2]
|
||||
assert corr_data["corrections_made"] == 5
|
||||
assert corr_data["handlers_applied"] == ["anchor_sequence", "gap_word_count"]
|
||||
assert corr_data["reference_sources_found"] == ["genius", "spotify"]
|
||||
|
||||
# Check cache stats were stored
|
||||
cache_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "cache"
|
||||
]
|
||||
assert len(cache_call) == 1
|
||||
cache_data = cache_call[0][0][2]
|
||||
assert cache_data["transcription_cache_downloaded"] == 2
|
||||
assert cache_data["transcription_cache_not_found"] == 1
|
||||
|
||||
def test_handles_missing_corrections_file(self):
|
||||
"""Should not raise when corrections file is not found."""
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={"lyrics_dir": "/nonexistent/path"},
|
||||
transcription_duration=30.0,
|
||||
cache_stats=None,
|
||||
job_log=job_log,
|
||||
)
|
||||
|
||||
# Should still store duration even without corrections file
|
||||
transcription_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "transcription"
|
||||
]
|
||||
assert len(transcription_call) == 1
|
||||
assert transcription_call[0][0][2]["duration_seconds"] == 30.0
|
||||
|
||||
def test_swallows_exceptions(self):
|
||||
"""Should not raise on unexpected errors."""
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.update_processing_metadata.side_effect = Exception("boom")
|
||||
job_log = MagicMock()
|
||||
|
||||
# Should not raise
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={"lyrics_dir": ""},
|
||||
transcription_duration=10.0,
|
||||
cache_stats=None,
|
||||
job_log=job_log,
|
||||
)
|
||||
job_log.warning.assert_called()
|
||||
|
||||
def test_no_audioshake_ids_when_lyrics_dir_missing(self):
|
||||
"""Without lyrics_dir, corrections.json can't be found — only duration is stored.
|
||||
|
||||
This is the exact bug that shipped in v0.142.0: transcribe_lyrics() didn't
|
||||
include lyrics_dir in its return dict, so _store_lyrics_processing_metadata
|
||||
could never find the corrections file and AudioShake IDs were silently lost.
|
||||
"""
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
# Simulate the pre-fix result dict — no lyrics_dir key at all
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={"lrc_filepath": "/tmp/output.lrc"}, # no lyrics_dir!
|
||||
transcription_duration=45.0,
|
||||
cache_stats=None,
|
||||
job_log=job_log,
|
||||
)
|
||||
|
||||
# Only duration should be stored — no AudioShake IDs, no correction stats
|
||||
transcription_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "transcription"
|
||||
]
|
||||
assert len(transcription_call) == 1
|
||||
trans_data = transcription_call[0][0][2]
|
||||
assert trans_data["duration_seconds"] == 45.0
|
||||
assert "audioshake_task_id" not in trans_data
|
||||
assert "provider" not in trans_data
|
||||
|
||||
# No correction metadata should be stored
|
||||
correction_calls = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "correction"
|
||||
]
|
||||
assert len(correction_calls) == 0
|
||||
|
||||
|
||||
class TestTranscribeLyricsReturnsLyricsDir:
|
||||
"""Contract test: transcribe_lyrics() must include lyrics_dir in its return dict.
|
||||
|
||||
This is the test that would have caught the v0.142.0 bug. The previous test suite
|
||||
only tested _store_lyrics_processing_metadata in isolation with a hand-crafted input
|
||||
that included lyrics_dir — it never verified the actual caller provides that key.
|
||||
|
||||
Testing lesson: When function A calls function B, don't just test B with ideal inputs.
|
||||
Also verify A actually produces those inputs. Test the contract between caller and callee.
|
||||
"""
|
||||
|
||||
@patch('karaoke_gen.lyrics_processor.LyricsTranscriber')
|
||||
@patch('karaoke_gen.lyrics_processor.load_dotenv')
|
||||
def test_transcribe_lyrics_returns_lyrics_dir(self, mock_dotenv, mock_transcriber_cls, tmp_path):
|
||||
"""transcribe_lyrics() result must contain lyrics_dir pointing to the lyrics subdirectory."""
|
||||
from karaoke_gen.lyrics_processor import LyricsProcessor
|
||||
|
||||
# Set up mock transcriber result
|
||||
mock_results = MagicMock()
|
||||
mock_results.lrc_filepath = str(tmp_path / "lyrics" / "output.lrc")
|
||||
mock_results.ass_filepath = str(tmp_path / "lyrics" / "output.ass")
|
||||
mock_results.video_filepath = str(tmp_path / "lyrics" / "output.mkv")
|
||||
mock_results.transcription_corrected = None # skip correction output
|
||||
mock_results.countdown_padding_added = False
|
||||
mock_results.countdown_padding_seconds = 0.0
|
||||
mock_results.padded_audio_filepath = None
|
||||
|
||||
mock_transcriber_cls.return_value.process.return_value = mock_results
|
||||
|
||||
# Create necessary dirs and a dummy audio file
|
||||
lyrics_dir = tmp_path / "lyrics"
|
||||
lyrics_dir.mkdir(exist_ok=True)
|
||||
(tmp_path / "lyrics" / "output.lrc").write_text("[00:00.00] test")
|
||||
(tmp_path / "lyrics" / "output.mkv").write_bytes(b"fake")
|
||||
lrc_dest = tmp_path / "Artist - Title (Karaoke).lrc"
|
||||
mkv_dest = tmp_path / "Artist - Title (With Vocals).mkv"
|
||||
|
||||
processor = LyricsProcessor.__new__(LyricsProcessor)
|
||||
processor.logger = MagicMock()
|
||||
processor.lyrics_file = None
|
||||
processor.render_video = False
|
||||
processor.skip_transcription = False
|
||||
processor.skip_transcription_review = True
|
||||
processor.style_params_json = None
|
||||
processor.subtitle_offset_ms = 0
|
||||
|
||||
with patch.dict('os.environ', {
|
||||
'AUDIOSHAKE_API_TOKEN': 'fake-token',
|
||||
}):
|
||||
result = processor.transcribe_lyrics(
|
||||
input_audio_wav=str(tmp_path / "audio.wav"),
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
track_output_dir=str(tmp_path),
|
||||
)
|
||||
|
||||
# THE KEY ASSERTION: lyrics_dir must be in the result
|
||||
assert "lyrics_dir" in result, (
|
||||
"transcribe_lyrics() must return lyrics_dir so _store_lyrics_processing_metadata "
|
||||
"can find corrections.json. This was the v0.142.0 bug."
|
||||
)
|
||||
assert result["lyrics_dir"] == str(tmp_path / "lyrics")
|
||||
|
||||
def test_lyrics_dir_matches_corrections_file_location(self, tmp_path):
|
||||
"""The lyrics_dir returned by transcribe_lyrics must be where corrections.json lives.
|
||||
|
||||
This verifies the contract: _store_lyrics_processing_metadata looks for corrections
|
||||
files in result['lyrics_dir'], and transcribe_lyrics writes them to {track_output_dir}/lyrics.
|
||||
"""
|
||||
import json
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
# Simulate a result dict with lyrics_dir set correctly
|
||||
lyrics_dir = tmp_path / "lyrics"
|
||||
lyrics_dir.mkdir()
|
||||
|
||||
# Write a corrections file in the same location transcribe_lyrics would
|
||||
corrections_file = lyrics_dir / "Artist - Title (Lyrics Corrections).json"
|
||||
corrections_file.write_text(json.dumps({
|
||||
"metadata": {
|
||||
"transcription_metadata": {"task_id": "t1", "asset_id": "a1"},
|
||||
"enabled_handlers": [],
|
||||
},
|
||||
"corrections_made": 0,
|
||||
"corrected_segments": [],
|
||||
}))
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
# Use the result dict shape that transcribe_lyrics now produces
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={
|
||||
"lyrics_dir": str(lyrics_dir),
|
||||
"lrc_filepath": str(tmp_path / "output.lrc"),
|
||||
},
|
||||
transcription_duration=30.0,
|
||||
cache_stats=None,
|
||||
job_log=job_log,
|
||||
)
|
||||
|
||||
# AudioShake IDs should be extracted successfully
|
||||
transcription_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "transcription"
|
||||
]
|
||||
assert len(transcription_call) == 1
|
||||
trans_data = transcription_call[0][0][2]
|
||||
assert trans_data["provider"] == "audioshake"
|
||||
assert trans_data["audioshake_task_id"] == "t1"
|
||||
assert trans_data["audioshake_asset_id"] == "a1"
|
||||
|
||||
|
||||
class TestStoreAudioSourceMetadata:
|
||||
"""Test the _store_audio_source_metadata helper function."""
|
||||
|
||||
@patch('subprocess.run')
|
||||
def test_parses_ffprobe_output(self, mock_run):
|
||||
"""Should parse ffprobe JSON output and store audio properties."""
|
||||
import json
|
||||
from backend.workers.audio_worker import _store_audio_source_metadata
|
||||
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=0,
|
||||
stdout=json.dumps({
|
||||
"format": {
|
||||
"format_name": "flac",
|
||||
"duration": "210.4",
|
||||
"size": "26541900",
|
||||
"bit_rate": "1008000",
|
||||
},
|
||||
"streams": [
|
||||
{
|
||||
"codec_type": "audio",
|
||||
"codec_name": "flac",
|
||||
"sample_rate": "44100",
|
||||
"channels": 2,
|
||||
"bits_per_raw_sample": "16",
|
||||
}
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_audio_source_metadata(job_manager, "job-123", "/fake/audio.flac", job_log)
|
||||
|
||||
job_manager.update_processing_metadata.assert_called_once()
|
||||
call_args = job_manager.update_processing_metadata.call_args
|
||||
assert call_args[0][1] == "audio_source"
|
||||
data = call_args[0][2]
|
||||
assert data["input_format"] == "flac"
|
||||
assert data["input_codec"] == "flac"
|
||||
assert data["input_sample_rate"] == 44100
|
||||
assert data["input_channels"] == 2
|
||||
assert data["input_bit_depth"] == 16
|
||||
assert data["input_duration_seconds"] == 210.4
|
||||
assert data["input_file_size_bytes"] == 26541900
|
||||
assert data["input_bitrate_kbps"] == 1008
|
||||
|
||||
@patch('subprocess.run')
|
||||
def test_handles_ffprobe_failure(self, mock_run):
|
||||
"""Should not raise when ffprobe fails."""
|
||||
from backend.workers.audio_worker import _store_audio_source_metadata
|
||||
|
||||
mock_run.return_value = MagicMock(returncode=1, stderr="No such file")
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_audio_source_metadata(job_manager, "job-123", "/bad/path", job_log)
|
||||
job_manager.update_processing_metadata.assert_not_called()
|
||||
job_log.warning.assert_called()
|
||||
|
||||
@patch('subprocess.run')
|
||||
def test_handles_missing_audio_stream(self, mock_run):
|
||||
"""Should handle files with no audio stream gracefully."""
|
||||
import json
|
||||
from backend.workers.audio_worker import _store_audio_source_metadata
|
||||
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=0,
|
||||
stdout=json.dumps({
|
||||
"format": {"format_name": "mp4", "duration": "30.0", "size": "1000"},
|
||||
"streams": [{"codec_type": "video", "codec_name": "h264"}],
|
||||
}),
|
||||
)
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_audio_source_metadata(job_manager, "job-123", "/fake/video.mp4", job_log)
|
||||
job_manager.update_processing_metadata.assert_called_once()
|
||||
data = job_manager.update_processing_metadata.call_args[0][2]
|
||||
# Should have format-level data but no audio stream data
|
||||
assert data["input_format"] == "mp4"
|
||||
assert "input_codec" not in data
|
||||
|
||||
|
||||
class TestStoreVideoProcessingMetadata:
|
||||
"""Test the _store_video_processing_metadata helper function."""
|
||||
|
||||
def test_stores_encoding_and_distribution_metadata(self, tmp_path):
|
||||
"""Should store encoding time, formats, and distribution info."""
|
||||
from backend.workers.video_worker import _store_video_processing_metadata
|
||||
|
||||
# Create mock result with some files existing
|
||||
result = MagicMock()
|
||||
result.encoding_time_seconds = 180.5
|
||||
result.youtube_url = "https://youtube.com/watch?v=abc"
|
||||
result.youtube_upload_queued = False
|
||||
result.dropbox_link = "https://dropbox.com/s/xxx"
|
||||
result.gdrive_files = {"4k": "file-id-1"}
|
||||
result.brand_code = "NOMAD0001"
|
||||
|
||||
# Create a temp file to simulate output
|
||||
lossless = tmp_path / "output.mp4"
|
||||
lossless.write_bytes(b"x" * 1000)
|
||||
result.final_video = str(lossless)
|
||||
result.final_video_mkv = None
|
||||
result.final_video_lossy = None
|
||||
result.final_video_720p = None
|
||||
|
||||
job_manager = MagicMock()
|
||||
|
||||
_store_video_processing_metadata(job_manager, "job-123", result, 300.0)
|
||||
|
||||
calls = {c[0][1]: c[0][2] for c in job_manager.update_processing_metadata.call_args_list}
|
||||
|
||||
# Check encoding
|
||||
assert "encoding" in calls
|
||||
assert calls["encoding"]["encoding_time_seconds"] == 180.5
|
||||
assert "lossless_4k_mp4" in calls["encoding"]["output_formats"]
|
||||
assert calls["encoding"]["output_sizes_bytes"]["lossless_4k_mp4"] == 1000
|
||||
|
||||
# Check distribution
|
||||
assert "distribution" in calls
|
||||
assert calls["distribution"]["youtube_video_url"] == "https://youtube.com/watch?v=abc"
|
||||
assert calls["distribution"]["brand_code"] == "NOMAD0001"
|
||||
assert calls["distribution"]["gdrive_file_count"] == 1
|
||||
|
||||
# Check timing (uses deep dot-notation to avoid overwriting other workers' timing)
|
||||
assert "timing.video_worker_seconds" in calls
|
||||
assert calls["timing.video_worker_seconds"] == 300.0
|
||||
|
||||
def test_swallows_exceptions(self):
|
||||
"""Should not raise on errors."""
|
||||
from backend.workers.video_worker import _store_video_processing_metadata
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.update_processing_metadata.side_effect = Exception("boom")
|
||||
result = MagicMock()
|
||||
result.encoding_time_seconds = None
|
||||
|
||||
# Should not raise
|
||||
_store_video_processing_metadata(job_manager, "job-123", result, 100.0)
|
||||
|
||||
|
||||
class TestAudioShakeStartTranscriptionAssetId:
|
||||
"""Test that start_transcription stores _last_asset_id."""
|
||||
|
||||
def test_start_transcription_stores_last_asset_id(self):
|
||||
"""start_transcription should store _last_asset_id for metadata fallback."""
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
|
||||
|
||||
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
|
||||
transcriber.logger = MagicMock()
|
||||
|
||||
# Mock the API and upload optimizer
|
||||
transcriber.api = MagicMock()
|
||||
transcriber.api.upload_file.return_value = "asset-from-upload"
|
||||
transcriber.api.create_task.return_value = "task-from-create"
|
||||
transcriber.upload_optimizer = MagicMock()
|
||||
transcriber.upload_optimizer.prepare_for_upload.return_value = ("/fake/path", None)
|
||||
|
||||
task_id = transcriber.start_transcription("/fake/audio.flac")
|
||||
|
||||
assert task_id == "task-from-create"
|
||||
assert transcriber._last_asset_id == "asset-from-upload"
|
||||
@@ -446,6 +446,20 @@ class TestSummaryEndpoint:
|
||||
assert _prune_state_data({}) == {}
|
||||
assert _prune_state_data({'state_data': None}) == {'state_data': None}
|
||||
|
||||
def test_summary_projection_includes_source_fields(self):
|
||||
"""Verify SUMMARY_FIELD_PATHS includes audio source tracking fields.
|
||||
|
||||
These fields are required for the Source column in the admin dashboard
|
||||
and the source details modal. Without them, the dashboard incorrectly
|
||||
shows audio search jobs as file uploads when audio_search_artist/title
|
||||
are null.
|
||||
"""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
paths = FirestoreService.SUMMARY_FIELD_PATHS
|
||||
for field in ['url', 'filename', 'audio_search_artist', 'audio_search_title',
|
||||
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url']:
|
||||
assert field in paths, f"{field} must be in summary projection for source details modal"
|
||||
|
||||
def test_prune_file_urls_keeps_allowed_keys(self):
|
||||
"""Verify _prune_file_urls keeps only dashboard-required keys."""
|
||||
from backend.api.routes.jobs import _prune_file_urls
|
||||
|
||||
@@ -328,13 +328,13 @@ class TestPreviewStyleLoading:
|
||||
|
||||
# Call the unified style loader function
|
||||
style_assets = {
|
||||
"style_params": "uploads/test123/style/style_params.json",
|
||||
"karaoke_background": "uploads/test123/style/karaoke_background.png",
|
||||
"font": "uploads/test123/style/font.ttf",
|
||||
"style_params": "jobs/test123/style/style_params.json",
|
||||
"karaoke_background": "jobs/test123/style/karaoke_background.png",
|
||||
"font": "jobs/test123/style/font.ttf",
|
||||
}
|
||||
|
||||
styles_path, result_styles = load_styles_from_gcs(
|
||||
style_params_gcs_path="uploads/test123/style/style_params.json",
|
||||
style_params_gcs_path="jobs/test123/style/style_params.json",
|
||||
style_assets=style_assets,
|
||||
temp_dir=str(tmp_path / "workdir"),
|
||||
download_func=mock_download,
|
||||
|
||||
@@ -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()
|
||||
@@ -180,8 +180,8 @@ class TestStyleHelper:
|
||||
# Mock job with style assets
|
||||
job = Mock()
|
||||
job.job_id = "test-123"
|
||||
job.style_assets = {"style_params": "uploads/test/style_params.json"}
|
||||
job.style_params_gcs_path = "uploads/test/style_params.json"
|
||||
job.style_assets = {"style_params": "jobs/test/style_params.json"}
|
||||
job.style_params_gcs_path = "jobs/test/style_params.json"
|
||||
|
||||
# Mock storage to "download" the file
|
||||
storage = Mock()
|
||||
|
||||
@@ -251,7 +251,7 @@ class TestCompleteStyleUploads:
|
||||
self, mock_job_manager, mock_storage_service, admin_auth, pending_job
|
||||
):
|
||||
mock_job_manager.get_job.return_value = pending_job
|
||||
mock_storage_service.list_files.return_value = ["uploads/job-abc/style/karaoke_background.png"]
|
||||
mock_storage_service.list_files.return_value = ["jobs/job-abc/style/karaoke_background.png"]
|
||||
|
||||
# Mock theme service
|
||||
with patch('backend.api.routes.file_upload.get_theme_service') as mock_get_ts:
|
||||
@@ -287,7 +287,7 @@ class TestCompleteStyleUploads:
|
||||
self, mock_job_manager, mock_storage_service, admin_auth, pending_job
|
||||
):
|
||||
mock_job_manager.get_job.return_value = pending_job
|
||||
mock_storage_service.list_files.return_value = ["uploads/job-abc/style/intro_background.png"]
|
||||
mock_storage_service.list_files.return_value = ["jobs/job-abc/style/intro_background.png"]
|
||||
|
||||
with patch('backend.api.routes.file_upload.get_theme_service') as mock_get_ts:
|
||||
mock_ts = Mock()
|
||||
|
||||
@@ -336,7 +336,7 @@ class TestThemeService:
|
||||
|
||||
# Should upload modified style_params.json
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
assert style_path == "uploads/job123/style/style_params.json"
|
||||
assert style_path == "jobs/job123/style/style_params.json"
|
||||
|
||||
def test_prepare_job_style_with_overrides(self, mock_storage, sample_metadata, sample_style_params):
|
||||
"""Test prepare_job_style applies color overrides."""
|
||||
@@ -355,7 +355,7 @@ class TestThemeService:
|
||||
uploaded_path = call_args[0][0] # First positional arg is the path
|
||||
uploaded_style = call_args[0][1] # Second positional arg is the data
|
||||
|
||||
assert uploaded_path == "uploads/job123/style/style_params.json"
|
||||
assert uploaded_path == "jobs/job123/style/style_params.json"
|
||||
# Check that artist_color override was applied
|
||||
assert uploaded_style["intro"]["artist_color"] == "#FF0000"
|
||||
assert uploaded_style["end"]["artist_color"] == "#FF0000"
|
||||
|
||||
@@ -1395,3 +1395,158 @@ class TestLyricsWorkerCountdownState:
|
||||
assert lyrics_metadata['has_countdown_padding'] is True
|
||||
assert lyrics_metadata['countdown_padding_seconds'] == 3.0
|
||||
|
||||
|
||||
class TestVideoWorkerStateGuard:
|
||||
"""Tests for video worker state validation."""
|
||||
|
||||
@pytest.fixture
|
||||
def failed_job(self):
|
||||
return Job(
|
||||
job_id="test-failed",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
state_data={"instrumental_selection": "clean"},
|
||||
file_urls={
|
||||
"stems": {"instrumental_clean": "gs://test"},
|
||||
"screens": {"title": "gs://t", "end": "gs://e"},
|
||||
"videos": {"with_vocals": "gs://v"},
|
||||
"lyrics": {"lrc": "gs://lrc"},
|
||||
},
|
||||
)
|
||||
|
||||
def test_validate_worker_can_run_rejects_failed_job(self, failed_job):
|
||||
"""validate_worker_can_run returns error for failed jobs."""
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
result = validate_worker_can_run("video_worker", failed_job)
|
||||
assert result is not None
|
||||
assert "failed" in result.lower()
|
||||
|
||||
def test_validate_worker_can_run_accepts_instrumental_selected(self):
|
||||
"""validate_worker_can_run allows instrumental_selected jobs."""
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
job = Job(
|
||||
job_id="test-ok",
|
||||
status=JobStatus.INSTRUMENTAL_SELECTED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
)
|
||||
result = validate_worker_can_run("video_worker", job)
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestWorkerIdempotencyTerminalState:
|
||||
"""Tests for _check_worker_idempotency terminal state handling."""
|
||||
|
||||
def test_idempotency_rejects_failed_job(self):
|
||||
"""Idempotency check returns skip response for failed jobs."""
|
||||
from backend.api.routes.internal import _check_worker_idempotency
|
||||
failed_job = Job(
|
||||
job_id="test-failed",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
)
|
||||
with patch("backend.api.routes.internal.JobManager") as MockJM:
|
||||
MockJM.return_value.get_job.return_value = failed_job
|
||||
result = _check_worker_idempotency("test-failed", "video")
|
||||
assert result is not None
|
||||
assert result.status == "skipped"
|
||||
assert "terminal state" in result.message.lower()
|
||||
|
||||
def test_idempotency_rejects_cancelled_job(self):
|
||||
"""Idempotency check returns skip response for cancelled jobs."""
|
||||
from backend.api.routes.internal import _check_worker_idempotency
|
||||
cancelled_job = Job(
|
||||
job_id="test-cancelled",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
)
|
||||
with patch("backend.api.routes.internal.JobManager") as MockJM:
|
||||
MockJM.return_value.get_job.return_value = cancelled_job
|
||||
result = _check_worker_idempotency("test-cancelled", "video")
|
||||
assert result is not None
|
||||
assert result.status == "skipped"
|
||||
|
||||
def test_idempotency_allows_instrumental_selected_job(self):
|
||||
"""Idempotency check allows jobs in non-terminal states."""
|
||||
from backend.api.routes.internal import _check_worker_idempotency
|
||||
job = Job(
|
||||
job_id="test-ok",
|
||||
status=JobStatus.INSTRUMENTAL_SELECTED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
)
|
||||
with patch("backend.api.routes.internal.JobManager") as MockJM:
|
||||
mock_jm = MockJM.return_value
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.update_state_data.return_value = None
|
||||
result = _check_worker_idempotency("test-ok", "video")
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestDistributionWarningsContract:
|
||||
"""Contract tests verifying distribution_warnings code paths don't crash.
|
||||
|
||||
Regression: generate_video_orchestrated() and _handle_native_distribution()
|
||||
both called _send_distribution_warning_notification(settings=settings) but
|
||||
never defined 'settings' in their scope. These tests ensure the notification
|
||||
call site works without NameError.
|
||||
"""
|
||||
|
||||
def test_send_distribution_warning_notification_works_without_settings(self):
|
||||
"""_send_distribution_warning_notification handles settings=None."""
|
||||
from backend.workers.video_worker import _send_distribution_warning_notification
|
||||
|
||||
# Should not crash — settings defaults to None and is fetched internally
|
||||
with patch('backend.workers.video_worker.get_settings') as mock_settings:
|
||||
mock_settings.return_value.get_secret.return_value = None # No pushbullet key
|
||||
_send_distribution_warning_notification(
|
||||
job_id="test-123",
|
||||
artist="Test",
|
||||
title="Song",
|
||||
warnings=["Dropbox failed"],
|
||||
)
|
||||
mock_settings.assert_called_once()
|
||||
|
||||
def test_generate_video_orchestrated_no_settings_reference(self):
|
||||
"""Verify generate_video_orchestrated doesn't reference undefined 'settings'.
|
||||
|
||||
Static analysis: scan the function source for 'settings=settings' which
|
||||
would indicate a NameError if settings is not defined in scope.
|
||||
"""
|
||||
import inspect
|
||||
from backend.workers.video_worker import generate_video_orchestrated
|
||||
|
||||
source = inspect.getsource(generate_video_orchestrated)
|
||||
assert "settings=settings" not in source, (
|
||||
"generate_video_orchestrated references 'settings=settings' but never defines 'settings'. "
|
||||
"Use settings=None or omit the argument — _send_distribution_warning_notification "
|
||||
"handles settings=None internally via get_settings()."
|
||||
)
|
||||
|
||||
def test_handle_native_distribution_no_settings_reference(self):
|
||||
"""Verify _handle_native_distribution doesn't reference undefined 'settings'.
|
||||
|
||||
Static analysis: same check as above for the other call site.
|
||||
"""
|
||||
import inspect
|
||||
from backend.workers.video_worker import _handle_native_distribution
|
||||
|
||||
source = inspect.getsource(_handle_native_distribution)
|
||||
assert "settings=settings" not in source, (
|
||||
"_handle_native_distribution references 'settings=settings' but never defines 'settings'. "
|
||||
"Use settings=None or omit the argument."
|
||||
)
|
||||
|
||||
@@ -140,6 +140,26 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
if job and job.state_data.get('requires_audio_edit'):
|
||||
# Preserve the original input path before any edits
|
||||
job_manager.update_state_data(job_id, 'original_input_media_gcs_path', audio_gcs_path)
|
||||
|
||||
# Pre-generate audio editor assets (OGG transcode + waveform data)
|
||||
# so the editor UI loads instantly. Non-fatal if this fails.
|
||||
waveform_cache_path = f"jobs/{job_id}/audio_edit/waveform_original.json"
|
||||
try:
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
transcoding = AudioTranscodingService()
|
||||
transcoding.transcode_if_needed(audio_gcs_path)
|
||||
logger.info(f"[job:{job_id}] Pre-transcoded input audio to OGG for editor")
|
||||
|
||||
analysis = AudioAnalysisService()
|
||||
analysis.cache_waveform_data(audio_gcs_path, job_id, waveform_cache_path)
|
||||
logger.info(f"[job:{job_id}] Pre-generated waveform data for editor")
|
||||
|
||||
job_manager.update_state_data(job_id, 'audio_edit_waveform_cache_path', waveform_cache_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to pre-generate editor assets (non-fatal): {e}")
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
|
||||
@@ -330,6 +330,9 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
download_span.set_attribute("audio_file", os.path.basename(audio_path))
|
||||
download_span.set_attribute("source", "url" if job.url else "gcs")
|
||||
|
||||
# Capture input audio properties via ffprobe (before any processing)
|
||||
_store_audio_source_metadata(job_manager, job_id, audio_path, job_log)
|
||||
|
||||
# Update progress using state_data (don't change status during parallel processing)
|
||||
# The status is managed at a higher level - workers just track their progress
|
||||
job_manager.update_state_data(job_id, 'audio_progress', {
|
||||
@@ -414,11 +417,22 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
|
||||
logger.info(f"[job:{job_id}] All stems uploaded successfully")
|
||||
|
||||
# Store processing metadata for separation provenance
|
||||
duration = time.time() - start_time
|
||||
job_manager.update_processing_metadata(job_id, "separation", {
|
||||
"provider": "modal",
|
||||
"clean_model": effective_model_names['clean_instrumental_model'],
|
||||
"backing_models": effective_model_names['backing_vocals_models'],
|
||||
"other_models": effective_model_names['other_stems_models'],
|
||||
"stems_generated": list(separation_result.keys()),
|
||||
"duration_seconds": round(sep_duration, 1),
|
||||
})
|
||||
job_manager.update_processing_metadata(job_id, "timing.audio_worker_seconds", round(duration, 1))
|
||||
|
||||
# Mark audio processing complete
|
||||
# This will check if lyrics are also complete and transition to next stage if so
|
||||
job_manager.mark_audio_complete(job_id)
|
||||
|
||||
duration = time.time() - start_time
|
||||
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=audio status=success duration={duration:.1f}s")
|
||||
return True
|
||||
@@ -668,6 +682,67 @@ async def upload_separation_results(
|
||||
logger.info(f"Job {job_id}: Stored instrumental options: {list(instrumental_options.keys())}")
|
||||
|
||||
|
||||
def _store_audio_source_metadata(
|
||||
job_manager: JobManager,
|
||||
job_id: str,
|
||||
audio_path: str,
|
||||
job_log,
|
||||
) -> None:
|
||||
"""Run ffprobe on input audio and store properties in processing_metadata.
|
||||
|
||||
Captures format, codec, sample rate, channels, duration, file size, and bitrate.
|
||||
Non-fatal: failures are logged but don't stop the job.
|
||||
"""
|
||||
import subprocess
|
||||
import json as _json
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"ffprobe", "-v", "quiet", "-print_format", "json",
|
||||
"-show_format", "-show_streams", audio_path,
|
||||
],
|
||||
capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
job_log.warning(f"ffprobe failed (rc={result.returncode}): {result.stderr[:200]}")
|
||||
return
|
||||
|
||||
probe = _json.loads(result.stdout)
|
||||
fmt = probe.get("format", {})
|
||||
# Find audio stream
|
||||
audio_stream = None
|
||||
for stream in probe.get("streams", []):
|
||||
if stream.get("codec_type") == "audio":
|
||||
audio_stream = stream
|
||||
break
|
||||
|
||||
metadata = {
|
||||
"input_format": fmt.get("format_name", "").split(",")[0],
|
||||
"input_duration_seconds": round(float(fmt.get("duration", 0)), 1),
|
||||
"input_file_size_bytes": int(fmt.get("size", 0)),
|
||||
"input_bitrate_kbps": round(int(fmt.get("bit_rate", 0)) / 1000) if fmt.get("bit_rate") else None,
|
||||
}
|
||||
|
||||
if audio_stream:
|
||||
metadata.update({
|
||||
"input_codec": audio_stream.get("codec_name"),
|
||||
"input_sample_rate": int(audio_stream.get("sample_rate", 0)) or None,
|
||||
"input_channels": audio_stream.get("channels"),
|
||||
"input_bit_depth": int(audio_stream.get("bits_per_raw_sample", 0)) or None,
|
||||
})
|
||||
|
||||
job_manager.update_processing_metadata(job_id, "audio_source", metadata)
|
||||
job_log.info(f"Audio source: {metadata.get('input_codec', '?')} "
|
||||
f"{metadata.get('input_sample_rate', '?')}Hz "
|
||||
f"{metadata.get('input_channels', '?')}ch "
|
||||
f"{metadata.get('input_duration_seconds', '?')}s")
|
||||
|
||||
except Exception as e:
|
||||
job_log.warning(f"Failed to capture audio source metadata (non-fatal): {e}")
|
||||
logger.warning(f"Job {job_id}: ffprobe metadata capture failed: {e}")
|
||||
|
||||
|
||||
# ==================== CLI Entry Point for Cloud Run Jobs ====================
|
||||
# This allows the audio worker to be run as a standalone Cloud Run Job.
|
||||
# Usage: python -m backend.workers.audio_worker --job-id <job_id>
|
||||
|
||||
@@ -420,6 +420,12 @@ async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
|
||||
job_log.info("Transcription processing complete")
|
||||
logger.info(f"[job:{job_id}] Transcription complete, uploading results")
|
||||
|
||||
# Store processing metadata for transcription + correction provenance
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager, job_id, result, trans_duration,
|
||||
cache_stats if 'cache_stats' in locals() else None, job_log
|
||||
)
|
||||
|
||||
# Upload lyrics results to GCS
|
||||
with job_span("upload-lyrics-results", job_id):
|
||||
@@ -458,6 +464,8 @@ async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
job_manager.mark_lyrics_complete(job_id)
|
||||
|
||||
duration = time.time() - start_time
|
||||
# Store worker-level timing
|
||||
job_manager.update_processing_metadata(job_id, "timing.lyrics_worker_seconds", round(duration, 1))
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=lyrics status=success duration={duration:.1f}s")
|
||||
return True
|
||||
@@ -699,6 +707,104 @@ async def upload_lyrics_results(
|
||||
logger.info(f"Job {job_id}: All lyrics results uploaded successfully")
|
||||
|
||||
|
||||
def _store_lyrics_processing_metadata(
|
||||
job_manager: JobManager,
|
||||
job_id: str,
|
||||
transcription_result: Dict[str, Any],
|
||||
transcription_duration: float,
|
||||
cache_stats: Optional[Dict[str, Any]],
|
||||
job_log,
|
||||
) -> None:
|
||||
"""Store transcription and correction provenance in processing_metadata.
|
||||
|
||||
Extracts AudioShake task_id/asset_id, correction stats, reference sources,
|
||||
and cache hit/miss info from the transcription result and stores them
|
||||
permanently for future analytics, debugging, and data export.
|
||||
"""
|
||||
try:
|
||||
# Load the corrections.json data from the result to get metadata
|
||||
# The transcription_result is the dict returned by LyricsProcessor.transcribe_lyrics()
|
||||
# which contains file paths, not the corrections data directly.
|
||||
# We need to find and read the corrections JSON from the output directory.
|
||||
corrections_metadata = {}
|
||||
transcription_metadata = {}
|
||||
|
||||
# Try to find corrections file in the result's output directory
|
||||
lyrics_dir = transcription_result.get("lyrics_dir") or ""
|
||||
corrections_file = None
|
||||
|
||||
# Check common paths for corrections JSON
|
||||
if lyrics_dir:
|
||||
for fname in os.listdir(lyrics_dir) if os.path.isdir(lyrics_dir) else []:
|
||||
if fname.endswith("(Lyrics Corrections).json") or fname == "corrections.json":
|
||||
corrections_file = os.path.join(lyrics_dir, fname)
|
||||
break
|
||||
|
||||
if corrections_file and os.path.exists(corrections_file):
|
||||
with open(corrections_file, 'r', encoding='utf-8') as f:
|
||||
corrections_data = json.load(f)
|
||||
|
||||
metadata = corrections_data.get("metadata", {})
|
||||
|
||||
# Extract AudioShake IDs from transcription_metadata passthrough
|
||||
trans_meta = metadata.get("transcription_metadata", {})
|
||||
if trans_meta:
|
||||
transcription_metadata = {
|
||||
"provider": "audioshake",
|
||||
"audioshake_task_id": trans_meta.get("task_id"),
|
||||
"audioshake_asset_id": trans_meta.get("asset_id"),
|
||||
"language_detected": trans_meta.get("language"),
|
||||
}
|
||||
|
||||
# Extract correction stats
|
||||
corrections_metadata = {
|
||||
"handlers_applied": metadata.get("enabled_handlers", []),
|
||||
"corrections_made": corrections_data.get("corrections_made", 0),
|
||||
"correction_ratio": metadata.get("correction_ratio"),
|
||||
"agentic_routing": metadata.get("agentic_routing"),
|
||||
"total_words": metadata.get("total_words"),
|
||||
"anchor_sequences_count": metadata.get("anchor_sequences_count"),
|
||||
"gap_sequences_count": metadata.get("gap_sequences_count"),
|
||||
}
|
||||
|
||||
# Count segments and words from corrected_segments
|
||||
corrected_segments = corrections_data.get("corrected_segments", [])
|
||||
transcription_metadata["segment_count"] = len(corrected_segments)
|
||||
transcription_metadata["word_count"] = sum(
|
||||
len(seg.get("words", [])) for seg in corrected_segments
|
||||
)
|
||||
|
||||
# Determine which reference sources were found
|
||||
reference_lyrics = corrections_data.get("reference_lyrics", {})
|
||||
if reference_lyrics:
|
||||
corrections_metadata["reference_sources_found"] = list(reference_lyrics.keys())
|
||||
|
||||
# Add transcription duration
|
||||
transcription_metadata["duration_seconds"] = round(transcription_duration, 1)
|
||||
|
||||
# Store transcription metadata
|
||||
if transcription_metadata:
|
||||
job_manager.update_processing_metadata(job_id, "transcription", transcription_metadata)
|
||||
|
||||
# Store correction metadata
|
||||
if corrections_metadata:
|
||||
job_manager.update_processing_metadata(job_id, "correction", corrections_metadata)
|
||||
|
||||
# Store cache stats
|
||||
if cache_stats:
|
||||
job_manager.update_processing_metadata(job_id, "cache", {
|
||||
"transcription_cache_downloaded": cache_stats.get("downloaded", 0),
|
||||
"transcription_cache_not_found": cache_stats.get("not_found", 0),
|
||||
})
|
||||
|
||||
job_log.info("Stored processing metadata (transcription + correction provenance)")
|
||||
|
||||
except Exception as e:
|
||||
# Never fail a job because metadata storage failed
|
||||
job_log.warning(f"Failed to store lyrics processing metadata (non-fatal): {e}")
|
||||
logger.warning(f"Job {job_id}: Failed to store lyrics processing metadata: {e}")
|
||||
|
||||
|
||||
# ==================== CLI Entry Point for Cloud Run Jobs ====================
|
||||
# This allows the lyrics worker to be run as a standalone Cloud Run Job.
|
||||
# Usage: python -m backend.workers.lyrics_worker --job-id <job_id>
|
||||
|
||||
@@ -319,6 +319,15 @@ async def process_render_video(job_id: str) -> bool:
|
||||
job_log.info("Uploaded corrected.txt")
|
||||
logger.info(f"Job {job_id}: Uploaded corrected.txt")
|
||||
|
||||
# Store render timing in processing metadata
|
||||
render_duration = time.time() - start_time
|
||||
job_manager.update_processing_metadata(job_id, "rendering", {
|
||||
"render_duration_seconds": round(render_duration, 1),
|
||||
"countdown_padding_added": padding_added,
|
||||
"countdown_padding_seconds": padding_seconds if padding_added else 0,
|
||||
})
|
||||
job_manager.update_processing_metadata(job_id, "timing.render_video_worker_seconds", round(render_duration, 1))
|
||||
|
||||
# 13. Transition based on prep_only flag
|
||||
# Note: Instrumental selection was already made during combined review
|
||||
# (stored in state_data['instrumental_selection'])
|
||||
|
||||
@@ -222,6 +222,8 @@ async def generate_screens(job_id: str) -> bool:
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
# Store worker-level timing
|
||||
job_manager.update_processing_metadata(job_id, "timing.screens_worker_seconds", round(duration, 1))
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=screens status=success duration={duration:.1f}s")
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -173,6 +173,8 @@ async def _encode_via_gce(
|
||||
local_files["final_video_lossy"] = local_path
|
||||
elif "720p" in filename_lower:
|
||||
local_files["final_video_720p"] = local_path
|
||||
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
|
||||
local_files["final_with_vocals_mp4"] = local_path
|
||||
|
||||
job_log.info(f"Downloaded {len(local_files)} encoded files")
|
||||
|
||||
@@ -226,6 +228,14 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
logger.error(f"[job:{job_id}] Prerequisites not met for video generation")
|
||||
return False
|
||||
|
||||
# Validate job status is appropriate for video worker
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
status_error = validate_worker_can_run("video_worker", job)
|
||||
if status_error:
|
||||
logger.warning(f"[job:{job_id}] {status_error}")
|
||||
job_log.warning(status_error)
|
||||
return False
|
||||
|
||||
# Create temporary working directory
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_video_{job_id}_")
|
||||
original_cwd = os.getcwd()
|
||||
@@ -332,6 +342,7 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
'final_video_mkv': result.final_video_mkv,
|
||||
'final_video_lossy': result.final_video_lossy,
|
||||
'final_video_720p': result.final_video_720p,
|
||||
'final_with_vocals_mp4': result.final_with_vocals_mp4,
|
||||
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
|
||||
'final_karaoke_txt_zip': result.final_karaoke_txt_zip,
|
||||
})
|
||||
@@ -360,11 +371,13 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
warnings=result.distribution_warnings,
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
# Store video processing metadata
|
||||
duration = time.time() - start_time
|
||||
_store_video_processing_metadata(job_manager, job_id, result, duration)
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
completion_metadata = {
|
||||
"action": "completed",
|
||||
"brand_code": result.brand_code,
|
||||
@@ -634,11 +647,19 @@ async def generate_video_legacy(job_id: str) -> bool:
|
||||
if not _validate_prerequisites(job):
|
||||
logger.error(f"[job:{job_id}] Prerequisites not met for video generation")
|
||||
return False
|
||||
|
||||
|
||||
# Validate job status is appropriate for video worker
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
status_error = validate_worker_can_run("video_worker", job)
|
||||
if status_error:
|
||||
logger.warning(f"[job:{job_id}] {status_error}")
|
||||
job_log.warning(status_error)
|
||||
return False
|
||||
|
||||
# Create temporary working directory
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_video_{job_id}_")
|
||||
original_cwd = os.getcwd()
|
||||
|
||||
|
||||
# Set up rclone config if needed for Dropbox upload
|
||||
rclone_service = None
|
||||
if getattr(job, 'organised_dir_rclone_root', None):
|
||||
@@ -1101,7 +1122,6 @@ async def _handle_native_distribution(
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
warnings=result['distribution_warnings'],
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
|
||||
@@ -1141,6 +1161,57 @@ def _send_distribution_warning_notification(
|
||||
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
|
||||
|
||||
|
||||
def _store_video_processing_metadata(
|
||||
job_manager: JobManager,
|
||||
job_id: str,
|
||||
result,
|
||||
total_duration: float,
|
||||
) -> None:
|
||||
"""Store encoding, distribution, and output metadata in processing_metadata."""
|
||||
try:
|
||||
# Encoding metadata
|
||||
encoding_data = {
|
||||
"encoding_time_seconds": round(result.encoding_time_seconds, 1) if result.encoding_time_seconds else None,
|
||||
"output_formats": [],
|
||||
}
|
||||
# Track which output formats were generated and their sizes
|
||||
output_sizes = {}
|
||||
for attr, fmt_name in [
|
||||
("final_video", "lossless_4k_mp4"),
|
||||
("final_video_mkv", "lossless_4k_mkv"),
|
||||
("final_video_lossy", "lossy_4k_mp4"),
|
||||
("final_video_720p", "lossy_720p_mp4"),
|
||||
]:
|
||||
path = getattr(result, attr, None)
|
||||
if path and os.path.exists(path):
|
||||
encoding_data["output_formats"].append(fmt_name)
|
||||
output_sizes[fmt_name] = os.path.getsize(path)
|
||||
if output_sizes:
|
||||
encoding_data["output_sizes_bytes"] = output_sizes
|
||||
job_manager.update_processing_metadata(job_id, "encoding", encoding_data)
|
||||
|
||||
# Distribution metadata
|
||||
distribution_data = {}
|
||||
if result.youtube_url:
|
||||
distribution_data["youtube_video_url"] = result.youtube_url
|
||||
if result.youtube_upload_queued:
|
||||
distribution_data["youtube_upload_queued"] = True
|
||||
if result.dropbox_link:
|
||||
distribution_data["dropbox_link"] = result.dropbox_link
|
||||
if result.gdrive_files:
|
||||
distribution_data["gdrive_file_count"] = len(result.gdrive_files)
|
||||
if result.brand_code:
|
||||
distribution_data["brand_code"] = result.brand_code
|
||||
if distribution_data:
|
||||
job_manager.update_processing_metadata(job_id, "distribution", distribution_data)
|
||||
|
||||
# Worker timing
|
||||
job_manager.update_processing_metadata(job_id, "timing.video_worker_seconds", round(total_duration, 1))
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Failed to store video processing metadata (non-fatal): {e}")
|
||||
|
||||
|
||||
def _validate_prerequisites(job) -> bool:
|
||||
"""Validate that all prerequisites are met for video generation."""
|
||||
# Validate job status is appropriate for video worker
|
||||
@@ -1234,7 +1305,9 @@ async def _setup_working_directory(
|
||||
# Download lyrics video (with vocals) - this is the largest file, ~1-2GB
|
||||
log_progress("Downloading karaoke video (largest file, may take 1-2 minutes)...")
|
||||
lyrics_video_url = job.file_urls['videos']['with_vocals']
|
||||
lyrics_video_path = os.path.join(temp_dir, f"{base_name} (With Vocals).mov")
|
||||
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
|
||||
lyrics_video_ext = os.path.splitext(lyrics_video_url)[1] or '.mkv'
|
||||
lyrics_video_path = os.path.join(temp_dir, f"{base_name} (With Vocals){lyrics_video_ext}")
|
||||
storage.download_file(lyrics_video_url, lyrics_video_path)
|
||||
log_progress("Downloaded karaoke video")
|
||||
|
||||
@@ -1422,14 +1495,16 @@ async def _prepare_distribution_directory(
|
||||
except Exception as e:
|
||||
log_progress(f"Could not download {lyrics_key}: {e}")
|
||||
|
||||
# --- Download (With Vocals).mkv to lyrics/ subfolder ---
|
||||
# --- Download (With Vocals) to lyrics/ subfolder ---
|
||||
# Local CLI places the karaoke video with vocals in the lyrics folder
|
||||
videos = job.file_urls.get('videos', {})
|
||||
if videos.get('with_vocals'):
|
||||
with_vocals_dest = os.path.join(lyrics_dir, f"{base_name} (With Vocals).mkv")
|
||||
with_vocals_url = videos['with_vocals']
|
||||
with_vocals_ext = os.path.splitext(with_vocals_url)[1] or '.mkv'
|
||||
with_vocals_dest = os.path.join(lyrics_dir, f"{base_name} (With Vocals){with_vocals_ext}")
|
||||
try:
|
||||
storage.download_file(videos['with_vocals'], with_vocals_dest)
|
||||
log_progress(f"Downloaded with_vocals to lyrics/{base_name} (With Vocals).mkv")
|
||||
storage.download_file(with_vocals_url, with_vocals_dest)
|
||||
log_progress(f"Downloaded with_vocals to lyrics/{base_name} (With Vocals){with_vocals_ext}")
|
||||
except Exception as e:
|
||||
log_progress(f"Could not download with_vocals to lyrics/: {e}")
|
||||
|
||||
@@ -1469,6 +1544,7 @@ async def _upload_results(
|
||||
('final_video_mkv', 'finals', 'lossless_4k_mkv'),
|
||||
('final_video_lossy', 'finals', 'lossy_4k_mp4'),
|
||||
('final_video_720p', 'finals', 'lossy_720p_mp4'),
|
||||
('final_with_vocals_mp4', 'finals', 'with_vocals_mp4'),
|
||||
('final_karaoke_cdg_zip', 'packages', 'cdg_zip'),
|
||||
('final_karaoke_txt_zip', 'packages', 'txt_zip'),
|
||||
]
|
||||
|
||||
@@ -98,6 +98,7 @@ class OrchestratorResult:
|
||||
final_video_mkv: Optional[str] = None # Lossless 4K MKV
|
||||
final_video_lossy: Optional[str] = None # Lossy 4K MP4
|
||||
final_video_720p: Optional[str] = None # Lossy 720p MP4
|
||||
final_with_vocals_mp4: Optional[str] = None # With Vocals MP4 (encoded from raw MKV)
|
||||
final_karaoke_cdg_zip: Optional[str] = None
|
||||
final_karaoke_txt_zip: Optional[str] = None
|
||||
|
||||
@@ -287,7 +288,9 @@ class VideoWorkerOrchestrator:
|
||||
self.job_log.warning("No LRC file available, skipping CDG/TXT packaging")
|
||||
return
|
||||
|
||||
base_name = f"{self.config.artist} - {self.config.title}"
|
||||
safe_artist = sanitize_filename(self.config.artist) if self.config.artist else "Unknown"
|
||||
safe_title = sanitize_filename(self.config.title) if self.config.title else "Unknown"
|
||||
base_name = f"{safe_artist} - {safe_title}"
|
||||
packaging_service = self._get_packaging_service()
|
||||
|
||||
# Generate CDG package
|
||||
@@ -421,6 +424,7 @@ class VideoWorkerOrchestrator:
|
||||
self.result.final_video_mkv = output.lossless_mkv_path
|
||||
self.result.final_video_lossy = output.lossy_4k_mp4_path
|
||||
self.result.final_video_720p = output.lossy_720p_mp4_path
|
||||
self.result.final_with_vocals_mp4 = output.with_vocals_mp4_path
|
||||
self.result.encoding_time_seconds = output.encoding_time_seconds
|
||||
|
||||
# For GCE encoding, download the encoded files from GCS to local directory
|
||||
@@ -450,6 +454,7 @@ class VideoWorkerOrchestrator:
|
||||
self.result.final_video_mkv = output.lossless_mkv_path
|
||||
self.result.final_video_lossy = output.lossy_4k_mp4_path
|
||||
self.result.final_video_720p = output.lossy_720p_mp4_path
|
||||
self.result.final_with_vocals_mp4 = output.with_vocals_mp4_path
|
||||
self.result.encoding_time_seconds = output.encoding_time_seconds
|
||||
|
||||
await self._download_gce_encoded_files(output)
|
||||
@@ -479,6 +484,7 @@ class VideoWorkerOrchestrator:
|
||||
('lossless_mkv_path', 'final_video_mkv'),
|
||||
('lossy_4k_mp4_path', 'final_video_lossy'),
|
||||
('lossy_720p_mp4_path', 'final_video_720p'),
|
||||
('with_vocals_mp4_path', 'final_with_vocals_mp4'),
|
||||
]
|
||||
|
||||
downloaded_count = 0
|
||||
@@ -861,7 +867,8 @@ def create_orchestrator_config_from_job(
|
||||
|
||||
# Input files
|
||||
title_video_path=os.path.join(temp_dir, f"{base_name} (Title).mov"),
|
||||
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals).mov"),
|
||||
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
|
||||
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals){os.path.splitext(job.file_urls.get('videos', {}).get('with_vocals', '.mkv'))[1] or '.mkv'}"),
|
||||
instrumental_audio_path=instrumental_path,
|
||||
end_video_path=os.path.join(temp_dir, f"{base_name} (End).mov"),
|
||||
lrc_file_path=os.path.join(temp_dir, f"{base_name} (Karaoke).lrc"),
|
||||
|
||||
+12
-1
@@ -1713,12 +1713,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 +1748,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`.
|
||||
|
||||
@@ -126,8 +126,9 @@ jobs/{job_id}/
|
||||
│ ├── title.mov
|
||||
│ └── end.mov
|
||||
├── videos/
|
||||
│ └── with_vocals.mkv # Karaoke video
|
||||
│ └── with_vocals.mkv # Raw karaoke video (FLAC audio, large)
|
||||
└── finals/
|
||||
├── with_vocals_mp4.mp4 # Encoded with-vocals (H264/AAC, ~3x smaller)
|
||||
├── lossless_4k.mp4
|
||||
├── lossless_4k.mkv
|
||||
├── lossy_4k.mp4
|
||||
@@ -182,7 +183,7 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
|
||||
| Collection | Purpose | Key Fields |
|
||||
|------------|---------|------------|
|
||||
| `gen_users` | karaoke-gen user accounts | email, credits, role, is_active |
|
||||
| `jobs` | Karaoke generation jobs | job_id, user_email, status, state_data |
|
||||
| `jobs` | Karaoke generation jobs | job_id, user_email, status, state_data, processing_metadata |
|
||||
| `jobs/{job_id}/logs` | Worker log entries (subcollection) | timestamp, level, worker, message, ttl_expiry |
|
||||
| `sessions` | Magic link auth sessions | user_email, token, expires_at |
|
||||
| `magic_links` | Passwordless auth tokens | email, token, expires_at, used |
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -22,6 +22,19 @@ When fuzzy-matching by title returns multiple artists with the same song name (e
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
### 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
|
||||
|
||||
### Separate Collections for Multi-App Projects
|
||||
@@ -773,6 +786,9 @@ Firestore returns timezone-aware datetimes. Compare with `datetime.now(timezone.
|
||||
### GCS Blob Paths vs URIs
|
||||
Methods that accept paths typically want `bucket/path`, not `gs://bucket/path`.
|
||||
|
||||
### GCS Lifecycle Rules Can Delete Job Data
|
||||
The GCS bucket has a lifecycle rule deleting objects under `uploads/` and `temp/` prefixes after 7 days. Style configuration (`style_params.json`) was stored under `uploads/{job_id}/style/` and silently disappeared for jobs not completed within a week. Fix: store job-scoped data under `jobs/` prefix (not subject to lifecycle rules), keeping `uploads/` only for genuinely temporary staging files.
|
||||
|
||||
### Library Caches Need GCS Sync
|
||||
External library caches (like LyricsTranscriber) need explicit sync to GCS for persistence across Cloud Run instances.
|
||||
|
||||
@@ -798,6 +814,9 @@ When adding alternative implementations (GCE vs local encoding), audit ALL side
|
||||
### External Response Validation
|
||||
Add defensive type checking for all external service responses. Lists vs dicts, missing fields cause cryptic failures.
|
||||
|
||||
### Thread All Encoding Outputs Through OrchestratorResult (Mar 2026)
|
||||
The encoding pipeline (`LocalEncodingService`) created a `(With Vocals).mp4` file (3.4x smaller than the raw MKV), but `OrchestratorResult` had no field for it so it was silently dropped. Users got the 134MB raw MKV instead of the 39MB encoded MP4. **Pattern**: When adding output files to encoding, verify the full chain: `EncodingOutput` → `OrchestratorResult` → `_upload_results()` file_mappings → Firestore `file_urls`. Also beware of hardcoded file extensions — the temp directory saved `.mkv` files as `.mov`, causing Dropbox to receive mislabeled files.
|
||||
|
||||
### Brand Code Allocation Must Be Atomic (Feb 2026)
|
||||
Two concurrent jobs both got brand code `NOMADNP-0012` because `get_next_brand_code()` scanned Dropbox folders to find the next number — a classic TOCTOU race condition. Jobs processed 0.86s apart both saw the same state. **Fix**: `brand_code_service.py` uses Firestore transactions to atomically allocate codes. Counter doc per prefix (`NOMAD`, `NOMADNP`) with `next_number` and `recycled` pool. E2E cleanup recycles numbers via `recycle_brand_code()`.
|
||||
|
||||
@@ -912,3 +931,25 @@ The three-layer defense above protects against the **GCE encoding worker** being
|
||||
|
||||
**Key insight:** The job's Firestore document (timeline + log subcollection) should be the single source of truth for "what happened to this job." Cloud Logging has retention limits and requires knowing which service to search. Timeline metadata makes the job self-documenting — any agent or human can read the timeline and understand the full lifecycle without cross-referencing logs.
|
||||
|
||||
### Store Processing Metadata When You Have It (Mar 2026)
|
||||
|
||||
**Problem:** During a data export for AudioShake lyrics correction feedback, we discovered that AudioShake `task_id` and `asset_id` were only held in memory during processing and never persisted. Recovery required paginating the AudioShake API and cross-referencing Cloud Logging — a multi-hour effort for data that was trivially available during processing.
|
||||
|
||||
**Solution:** Added `processing_metadata` as a top-level dict on the Job model, separate from `state_data` (mutable workflow state). Each worker writes its own section (transcription, separation, rendering, etc.) via `job_manager.update_processing_metadata(job_id, section, data)`, which uses Firestore dot-notation to atomically update one section without overwriting others. All metadata writes are wrapped in try/except — failures are logged but never fail jobs.
|
||||
|
||||
**Key insight:** "Store it when you have it." The cost of persisting a few extra fields is negligible; the cost of not having them later (log spelunking, API pagination, one-off recovery scripts) is enormous. When data flows through a worker during processing, capture the provenance metadata before it's lost. See `docs/archive/2026-03-10-store-job-processing-metadata.md` for the full design.
|
||||
|
||||
### Test the Contract, Not Just the Function (Mar 2026)
|
||||
|
||||
**Problem:** The processing metadata feature shipped with a silent bug: `_store_lyrics_processing_metadata()` expected `result["lyrics_dir"]` but `transcribe_lyrics()` never included `lyrics_dir` in its return dict. AudioShake IDs and correction stats were silently lost in production. The test suite had 24 passing tests and didn't catch it.
|
||||
|
||||
**Root cause (testing):** The test for `_store_lyrics_processing_metadata` hand-crafted its input: `transcription_result={"lyrics_dir": str(lyrics_dir)}`. This tested the function in isolation — proving it works *if given correct input* — but never verified the actual caller provides that input. The mock was "too helpful."
|
||||
|
||||
**Pattern — Contract tests:** When function A calls function B with data, test both:
|
||||
1. **Unit test B** with controlled input (existing approach — still valuable)
|
||||
2. **Contract test** verifying A's output contains the keys B expects
|
||||
|
||||
For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_dir`?" — a one-line assertion that would have caught the bug before merge.
|
||||
|
||||
**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.
|
||||
|
||||
@@ -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,8 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **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).
|
||||
@@ -93,6 +96,8 @@
|
||||
|
||||
- **Custom Instrumental Upload Fix** (2026-02-26): Fixed critical bug where uploaded custom instrumentals were ignored during encoding — GCE encoding worker and orchestrator had no `"custom"` case, falling back to clean instrumental instead. Upload endpoint now converts all formats to FLAC for pipeline consistency. Three fixes: (1) GCE encoding worker `find_file` now searches for `custom_instrumental*.flac` when selection is `"custom"`, (2) orchestrator config constructs correct `(Instrumental Custom).flac` path, (3) upload endpoint converts mp3/m4a/wav/etc. to FLAC before storing. Added 10 new regression tests for GCE resolution and orchestrator paths. See [API.md](API.md#upload-custom-instrumental).
|
||||
|
||||
- **Store Processing Metadata Permanently** (2026-03-10): Added `processing_metadata` field to the Job model — a top-level dict where each worker writes immutable provenance data during processing. Stores AudioShake task_id/asset_id (the original ask — these were previously lost after processing), worker timing, separation model names, ffprobe audio properties, correction stats, cache hit/miss data, video encoding details, and auth context at job creation. All metadata writes are non-fatal (wrapped in try/except). Includes `update_processing_metadata` helper on JobManager using Firestore dot-notation for atomic section updates. 23 tests covering model, helpers, all worker functions, and a SUMMARY_FIELD_PATHS regression guard. See [archive/2026-03-10-store-job-processing-metadata.md](archive/2026-03-10-store-job-processing-metadata.md) and [LESSONS-LEARNED.md](LESSONS-LEARNED.md#store-processing-metadata-when-you-have-it-mar-2026).
|
||||
|
||||
- **Custom Instrumental Upload** (2026-02-25): Added `POST /api/jobs/{job_id}/upload-instrumental` endpoint — was missing from backend, causing 404 in production when users tried to upload custom instrumental files during review. Validates uploaded audio duration matches original (±0.5s tolerance) using ffprobe on GCS signed URLs. Fixed frontend bug where "uploaded" selection type was sent to API instead of "custom" (the only value the backend accepts). Added 22 tests covering upload validation, duration checks, and frontend/backend contract. See [API.md](API.md#upload-custom-instrumental).
|
||||
|
||||
- **Unicode Filename Fix** (2026-02-04): Fixed FFmpeg failures (exit code 183) when processing songs with non-ASCII characters in titles. Job `1eab1172` with Russian title "я куплю тебе дом" failed because Python's `str.isalnum()` returns True for ALL Unicode alphanumeric characters (Cyrillic, Arabic, Chinese, emoji, etc.), not just ASCII. These Unicode characters in temp subtitle file paths (`temp_subtitles_zivert___я_куплю_тебе_дом_1770150285852.ass`) caused FFmpeg to fail. **Fix**: Changed filename sanitization from `c.isalnum()` to `c.isascii() and c.isalnum()` in three locations: `video.py:222` (generate_video), `video.py:282` (generate_preview_video), and `remote_cli.py:1970` (output folders). Added comprehensive test suite covering Cyrillic, Chinese, Arabic, emoji, and accented characters. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#unicode-in-file-paths-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
|
||||
```
|
||||
@@ -182,6 +182,36 @@ mock_service.update_job.return_value = None # Match real API
|
||||
|
||||
**Before writing a mock**, check the actual method's return type. Void methods should mock `return_value = None`. Methods that raise on error (rather than returning False) should have mocks that raise exceptions for error cases. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#mocks-must-match-real-return-values-feb-2026) for a production bug caused by this.
|
||||
|
||||
**Critical: Test the Contract Between Caller and Callee**
|
||||
|
||||
When function A calls function B, it's not enough to test B with hand-crafted ideal inputs. You must also verify A actually produces those inputs. This is a "contract test."
|
||||
|
||||
```python
|
||||
# ❌ BAD: Tests _store_metadata in isolation with hand-crafted input
|
||||
# If transcribe_lyrics() never includes "lyrics_dir", this test still passes
|
||||
# but production silently loses all metadata
|
||||
def test_stores_audioshake_ids(tmp_path):
|
||||
_store_lyrics_processing_metadata(
|
||||
transcription_result={"lyrics_dir": str(tmp_path)}, # Too helpful!
|
||||
...
|
||||
)
|
||||
assert call_args["audioshake_task_id"] == "task-abc" # ✅ passes, but useless
|
||||
|
||||
# ✅ GOOD: Also test that the caller produces the expected input
|
||||
def test_transcribe_lyrics_returns_lyrics_dir(tmp_path):
|
||||
result = processor.transcribe_lyrics(audio, artist, title, tmp_path)
|
||||
assert "lyrics_dir" in result # Catches the actual bug
|
||||
```
|
||||
|
||||
**When to write contract tests:**
|
||||
- Function A builds a dict/object and passes it to function B
|
||||
- Function B reads specific keys/fields from that dict/object
|
||||
- The dict/object shape is implicit (no schema, no TypedDict, no dataclass)
|
||||
|
||||
**Especially dangerous:** Non-fatal code paths (try/except that swallows errors). If the function is designed to never crash, a test that only checks "didn't raise" provides zero signal. Assert on the *positive outcome* (data was stored, value was returned) not just the absence of exceptions.
|
||||
|
||||
See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#test-the-contract-not-just-the-function-mar-2026) for the production bug this pattern caused.
|
||||
|
||||
### Integration Tests (`tests/integration/`)
|
||||
|
||||
**Purpose:** Test CLI workflows and component interactions.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Date:** 2026-03-08
|
||||
**Branch:** `feat/sess-20260308-1232-edit-input-audio`
|
||||
**Status:** Planning
|
||||
**Status:** Complete
|
||||
|
||||
## Problem
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Date:** 2026-03-08
|
||||
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
|
||||
**Status:** Planning
|
||||
**Status:** Complete
|
||||
**Depends on:** Phases 2, 4
|
||||
|
||||
## Goal
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# Plan: Pre-generate Audio Editor Assets
|
||||
|
||||
**Created:** 2026-03-09
|
||||
**Branch:** feat/sess-20260309-1749-pregenerate-audio-editor
|
||||
**Status:** In Progress
|
||||
|
||||
## Overview
|
||||
|
||||
The audio editor UI takes 10-20 seconds to load because it generates waveform data and transcodes FLAC→OGG on-demand when the user opens the editor. The lyrics/instrumental review UI doesn't have this problem because `screens_worker` eagerly pre-generates all assets before the job reaches `awaiting_review`.
|
||||
|
||||
We need the same eager pre-generation for audio editing: transcode the input audio to OGG and generate waveform data *during* the download worker, before the job transitions to `awaiting_audio_edit`. Then the `input-audio-info` endpoint serves cached data instead of computing it from scratch.
|
||||
|
||||
## Current Flow (Slow)
|
||||
|
||||
```
|
||||
audio_download_worker: downloads FLAC → saves to GCS → transitions to awaiting_audio_edit
|
||||
(no pre-generation)
|
||||
|
||||
User opens editor → GET /input-audio-info →
|
||||
1. download FLAC from GCS to Cloud Run tmp (~5-8s)
|
||||
2. generate waveform from FLAC (pydub) (~2-3s)
|
||||
3. transcode FLAC→OGG + upload to GCS (~3-5s)
|
||||
4. generate signed URL (~0.5s)
|
||||
Total: ~10-20s
|
||||
```
|
||||
|
||||
## Target Flow (Fast)
|
||||
|
||||
```
|
||||
audio_download_worker: downloads FLAC → saves to GCS →
|
||||
pre-generate:
|
||||
1. transcode FLAC→OGG (reuse AudioTranscodingService)
|
||||
2. generate waveform data → save as JSON to GCS
|
||||
→ transitions to awaiting_audio_edit
|
||||
|
||||
User opens editor → GET /input-audio-info →
|
||||
1. load cached waveform JSON from GCS (~0.5s)
|
||||
2. generate signed URL for cached OGG (~0.5s)
|
||||
Total: ~1s
|
||||
```
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] Add `cache_waveform_data` and `load_cached_waveform` to `AudioAnalysisService`
|
||||
2. [ ] Add pre-generation to `audio_download_worker` before `awaiting_audio_edit` transition
|
||||
3. [ ] Modify `input-audio-info` endpoint to use cached waveform when available
|
||||
4. [ ] Add unit tests for cache methods, download worker, and endpoint cache hit/miss
|
||||
5. [ ] Run full test suite
|
||||
|
||||
## Files to Modify
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `backend/services/audio_analysis_service.py` | Add waveform cache/load methods |
|
||||
| `backend/workers/audio_download_worker.py` | Add pre-generation before state transition |
|
||||
| `backend/api/routes/review.py` | Use cached waveform in `input-audio-info` |
|
||||
| `backend/tests/test_audio_edit_routes.py` | Tests for cache hit/miss |
|
||||
| `backend/tests/test_audio_download_worker.py` | Test for pre-generation call |
|
||||
@@ -0,0 +1,294 @@
|
||||
# Plan: Store Job Processing Metadata Permanently
|
||||
|
||||
**Date**: 2026-03-10
|
||||
**Branch**: `feat/sess-20260309-2358-store-audioshake-ids`
|
||||
**Status**: Implemented (all 6 phases)
|
||||
|
||||
## Problem
|
||||
|
||||
During a data export for AudioShake (lyrics correction feedback), we discovered that AudioShake task_id and asset_id were only stored ephemerally during processing and never persisted. We had to do a complex one-off recovery from Cloud Logging + AudioShake API pagination to reconstruct the mapping.
|
||||
|
||||
This is symptomatic of a broader issue: many pieces of valuable metadata generated during job processing are only logged or held in memory, then discarded. When a future data export, debugging, or analytics need arises, we're left scrambling to recover from logs (which have limited retention).
|
||||
|
||||
## Goals
|
||||
|
||||
1. **Immediate**: Persist AudioShake task_id and asset_id permanently with each job
|
||||
2. **Broader**: Identify and store other high-value processing metadata that would be painful to reconstruct later
|
||||
3. **Principle**: "Store it when you have it" - the cost of storing a few extra fields is negligible compared to the cost of not having them later
|
||||
|
||||
## Design: `processing_metadata` Field
|
||||
|
||||
Add a new top-level dict field `processing_metadata` to the Job model, separate from `state_data` (which is mutable workflow state). `processing_metadata` is **write-once** data captured during processing that describes _how_ the job was processed.
|
||||
|
||||
### Why Not `state_data`?
|
||||
|
||||
- `state_data` is for mutable workflow state (current stems, build IDs, etc.)
|
||||
- `processing_metadata` is for immutable audit/provenance data
|
||||
- Keeps concerns separate: "what stage is the job in" vs "how was it processed"
|
||||
- Easier to project in queries (one field to include vs picking through state_data keys)
|
||||
|
||||
### Schema
|
||||
|
||||
```python
|
||||
# In Job model
|
||||
processing_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
Immutable processing provenance data. Written once by each worker during processing.
|
||||
Never modified after initial write. Used for analytics, debugging, and data export.
|
||||
|
||||
Structure:
|
||||
{
|
||||
"transcription": {
|
||||
"provider": "audioshake",
|
||||
"audioshake_task_id": "cmmjpbo7f...",
|
||||
"audioshake_asset_id": "cmmjpbma4...",
|
||||
"language_detected": "en",
|
||||
"duration_seconds": 125.5,
|
||||
"word_count": 358,
|
||||
"segment_count": 42,
|
||||
},
|
||||
"correction": {
|
||||
"handlers_applied": ["anchor_sequence", "gap_word_count", ...],
|
||||
"corrections_made": 12,
|
||||
"correction_ratio": 0.034,
|
||||
"reference_sources_found": ["genius", "spotify", "lrclib"],
|
||||
"agentic_routing": "rule-based",
|
||||
"duration_seconds": 33.2,
|
||||
},
|
||||
"separation": {
|
||||
"provider": "modal",
|
||||
"clean_model": "model_bs_roformer_ep_317_sdr_12.9755.ckpt",
|
||||
"backing_models": ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
|
||||
"stems_generated": ["clean", "with_backing", "vocals", "backing_vocals"],
|
||||
"duration_seconds": 420.5,
|
||||
},
|
||||
"audio_source": {
|
||||
"input_format": "flac",
|
||||
"input_sample_rate": 44100,
|
||||
"input_channels": 2,
|
||||
"input_duration_seconds": 210.4,
|
||||
"input_file_size_bytes": 26541900,
|
||||
},
|
||||
"rendering": {
|
||||
"render_duration_seconds": 18.7,
|
||||
"encoding_duration_seconds": 180.5,
|
||||
"output_formats": ["lossless_4k_mkv", "lossless_4k_mp4", "lossy_4k_mp4", "lossy_720p_mp4"],
|
||||
"output_sizes_bytes": {
|
||||
"lossless_4k_mkv": 45168200,
|
||||
"lossy_720p_mp4": 34571800,
|
||||
},
|
||||
},
|
||||
"review": {
|
||||
"review_duration_seconds": 450.2,
|
||||
"corrections_made_by_human": 5,
|
||||
"total_words_reviewed": 358,
|
||||
"instrumental_selected": "clean",
|
||||
},
|
||||
"distribution": {
|
||||
"youtube_video_id": "dQw4w9WgXcQ",
|
||||
"youtube_upload_duration_seconds": 240.5,
|
||||
"dropbox_upload_duration_seconds": 120.5,
|
||||
"gdrive_upload_duration_seconds": 95.3,
|
||||
},
|
||||
"cache": {
|
||||
"transcription_cache_hit": true,
|
||||
"lyrics_cache_hits": {"genius": true, "spotify": true, "lrclib": false},
|
||||
},
|
||||
"timing": {
|
||||
"total_processing_seconds": 890.2,
|
||||
"worker_durations": {
|
||||
"audio": 420.5,
|
||||
"lyrics": 125.3,
|
||||
"screens": 45.2,
|
||||
"render_video": 18.7,
|
||||
"video": 180.2,
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Field Projection
|
||||
|
||||
Per the known gotcha (MEMORY.md), when adding new fields the dashboard needs, must add to BOTH:
|
||||
1. `SUMMARY_FIELD_PATHS` in `backend/services/firestore_service.py`
|
||||
2. `_SUMMARY_STATE_DATA_KEYS` in `backend/api/routes/jobs.py`
|
||||
|
||||
For `processing_metadata`, we'll add it to `SUMMARY_FIELD_PATHS` so it's available in job list queries. Since it's a top-level field (not under `state_data`), it doesn't need `_SUMMARY_STATE_DATA_KEYS`.
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 1: AudioShake IDs (Priority - the original ask)
|
||||
|
||||
**Files to modify:**
|
||||
|
||||
1. **`backend/models/job.py`** - Add `processing_metadata` field to Job model
|
||||
2. **`karaoke_gen/lyrics_transcriber/core/controller.py`** - Pass transcription metadata (including task_id) through to CorrectionResult.metadata
|
||||
3. **`backend/workers/lyrics_worker.py`** - Extract AudioShake IDs + transcription metadata from corrections.json and store in `processing_metadata.transcription`
|
||||
4. **`backend/services/firestore_service.py`** - Add `processing_metadata` to `SUMMARY_FIELD_PATHS`
|
||||
5. **`backend/api/routes/jobs.py`** - Ensure `processing_metadata` is included in job responses
|
||||
|
||||
**Detail:**
|
||||
|
||||
In `controller.py`, the `_convert_result_format` method on AudioShakeTranscriber already stores `task_id` in `TranscriptionData.metadata`. The issue is that `LyricsCorrector.run()` builds a new `CorrectionResult.metadata` dict that doesn't include this data. Fix:
|
||||
- In `corrector.py`, pass through the primary transcription's metadata into the CorrectionResult metadata dict
|
||||
- In `lyrics_worker.py`, after loading corrections.json, extract `metadata.transcription_metadata` and write to `processing_metadata`
|
||||
|
||||
Alternatively (simpler): in `lyrics_worker.py`, we already have access to the transcription result object. We can extract the AudioShake IDs directly from it before they're lost, and store them in `processing_metadata`.
|
||||
|
||||
**Chosen approach**: Store in `lyrics_worker.py` right after transcription completes, since we have direct access to the result there. Also flow the metadata through corrections.json for data integrity.
|
||||
|
||||
### Phase 2: Worker Timing & Processing Stats
|
||||
|
||||
**Files to modify:**
|
||||
|
||||
6. **`backend/workers/lyrics_worker.py`** - Add timing data + correction stats to `processing_metadata`
|
||||
7. **`backend/workers/audio_worker.py`** - Add separation timing + model info to `processing_metadata`
|
||||
8. **`backend/workers/screens_worker.py`** - Add screen generation timing
|
||||
9. **`backend/workers/render_video_worker.py`** - Add render timing
|
||||
10. **`backend/workers/video_worker.py`** / **`video_worker_orchestrator.py`** - Add encoding timing + output file sizes
|
||||
|
||||
**For each worker, the pattern is:**
|
||||
```python
|
||||
# At the end of successful processing:
|
||||
job_manager.update_processing_metadata(job_id, 'separation', {
|
||||
'provider': 'modal',
|
||||
'clean_model': model_names.get('clean'),
|
||||
'duration_seconds': round(sep_duration, 1),
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
### Phase 3: Audio Source & Cache Metadata
|
||||
|
||||
**Files to modify:**
|
||||
|
||||
11. **`backend/workers/lyrics_worker.py`** - Cache hit/miss stats
|
||||
12. **`backend/api/routes/jobs.py`** or audio download handler - Input audio metadata (format, sample rate, duration, file size)
|
||||
|
||||
### Phase 4: Review & Distribution Metadata
|
||||
|
||||
**Files to modify:**
|
||||
|
||||
13. **`backend/api/routes/review.py`** - Review completion metadata (duration, corrections count)
|
||||
14. **`backend/workers/video_worker.py`** - YouTube upload metadata (video ID is probably already stored, but upload timing is not)
|
||||
|
||||
### JobManager Helper
|
||||
|
||||
Add a helper method to JobManager for appending to `processing_metadata` without overwriting:
|
||||
|
||||
```python
|
||||
def update_processing_metadata(self, job_id: str, section: str, data: dict):
|
||||
"""Merge data into processing_metadata[section]. Write-once per section."""
|
||||
from google.cloud.firestore_v1 import transforms
|
||||
self.db.collection("jobs").document(job_id).update({
|
||||
f"processing_metadata.{section}": data,
|
||||
})
|
||||
```
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
- **`backend/tests/test_job_model.py`**: Verify `processing_metadata` field exists and defaults to empty dict
|
||||
- **`backend/tests/test_lyrics_worker.py`**: Mock transcription result with AudioShake metadata, verify it's stored in `processing_metadata.transcription`
|
||||
- **`backend/tests/test_audio_worker.py`**: Verify separation metadata stored
|
||||
- **`backend/tests/test_job_manager.py`**: Test `update_processing_metadata` helper
|
||||
|
||||
### Integration Tests
|
||||
- **`backend/tests/integration/`**: Firestore emulator test that processes a job through lyrics worker and verifies `processing_metadata` is written correctly
|
||||
|
||||
### Regression Test
|
||||
- Add a test asserting `processing_metadata` is in `SUMMARY_FIELD_PATHS` (per the known gotcha)
|
||||
|
||||
## Migration
|
||||
|
||||
No migration needed for existing jobs - `processing_metadata` defaults to `{}`. New jobs will populate it as they process. The extraction script (`extract_audioshake_corrections.py`) already handles the one-off backfill for historical AudioShake IDs.
|
||||
|
||||
### Phase 5: Input Audio Metadata (ffprobe at ingest)
|
||||
|
||||
Currently we have ffprobe and pydub available in workers, but never store audio properties permanently. When a user uploads or we download audio, run ffprobe once and store the results.
|
||||
|
||||
**Files to modify:**
|
||||
|
||||
15. **`backend/workers/audio_worker.py`** (or wherever audio is first downloaded to disk) - Run ffprobe on the input audio file and store:
|
||||
|
||||
```json
|
||||
"audio_source": {
|
||||
"input_format": "flac",
|
||||
"input_codec": "flac",
|
||||
"input_sample_rate": 44100,
|
||||
"input_bit_depth": 16,
|
||||
"input_channels": 2,
|
||||
"input_duration_seconds": 210.4,
|
||||
"input_file_size_bytes": 26541900,
|
||||
"input_bitrate_kbps": 1411
|
||||
}
|
||||
```
|
||||
|
||||
This is valuable for:
|
||||
- Understanding what quality of source material produces the best results
|
||||
- Debugging encoding/quality issues
|
||||
- Analytics on user upload patterns
|
||||
- Detecting re-encoded or low-quality uploads
|
||||
|
||||
### Phase 6: User & Abuse-Related Metadata
|
||||
|
||||
**Current state**: `request_metadata` already captures IP, User-Agent, client_id, and custom headers at job creation time. This is good for basic abuse investigation. However, some gaps:
|
||||
|
||||
**6a. Auth context at job creation**
|
||||
|
||||
Store which auth method was used and user tier, so we can correlate job creation patterns with account types during abuse investigation.
|
||||
|
||||
16. **`backend/api/routes/file_upload.py`** - Add to `extract_request_metadata()`:
|
||||
|
||||
```python
|
||||
# Add auth context (already available from auth_result)
|
||||
request_metadata['auth_method'] = auth_result.auth_method # "session", "api_key", "admin_token"
|
||||
request_metadata['user_type'] = auth_result.user_type.value # "admin", "unlimited", "limited", etc.
|
||||
request_metadata['credits_at_creation'] = auth_result.remaining_uses # snapshot of credits when job created
|
||||
```
|
||||
|
||||
**6b. Audio search metadata (for audio search flow jobs)**
|
||||
|
||||
When a job is created from audio search, we know the search query, number of results, and which result was selected. Store these so we can understand search patterns and detect gaming.
|
||||
|
||||
17. **`backend/api/routes/audio_search.py`** - When creating a job from search, store:
|
||||
|
||||
```json
|
||||
"request_metadata": {
|
||||
...existing fields...,
|
||||
"search_query": {"artist": "...", "title": "..."},
|
||||
"search_results_count": 8,
|
||||
"selected_result_rank": 1,
|
||||
"selected_source": "RED"
|
||||
}
|
||||
```
|
||||
|
||||
**Not adding (already handled):**
|
||||
- IP address: Already in `request_metadata.client_ip`
|
||||
- User-Agent: Already in `request_metadata.user_agent`
|
||||
- Email: Already in `job.user_email`
|
||||
- Tenant: Already in `job.tenant_id`
|
||||
- IP blocklist: Already exists in `blocklists/config`
|
||||
- Session IP/UA: Already stored in session documents
|
||||
- Magic link IP/UA: Already stored in magic link documents
|
||||
|
||||
## Scope & Boundaries
|
||||
|
||||
- **In scope**: Storing metadata that already exists in memory during processing
|
||||
- **Out of scope**: Computing new metrics, changing external API calls, frontend changes
|
||||
- **Out of scope**: Backfilling historical jobs (the one-off script handles AudioShake IDs)
|
||||
- **Principle**: Each worker writes its own section. No worker reads another worker's metadata.
|
||||
|
||||
## Estimated Changes
|
||||
|
||||
| Phase | Files | Complexity | Notes |
|
||||
|-------|-------|-----------|-------|
|
||||
| 1 | 5 | Low | AudioShake IDs - the critical fix |
|
||||
| 2 | 5 | Low | Timing data - already computed, just needs storing |
|
||||
| 3 | 2 | Low | Source/cache metadata |
|
||||
| 4 | 2 | Low | Review/distribution metadata |
|
||||
| 5 | 1-2 | Low | ffprobe on input audio, store properties |
|
||||
| 6 | 2 | Low | Auth context + search metadata at job creation |
|
||||
| Tests | 4-5 | Medium | Unit + integration tests |
|
||||
|
||||
Total: ~18 files, mostly small additions (5-15 lines per file).
|
||||
@@ -0,0 +1,153 @@
|
||||
# Plan: Fix style_params.json Lifecycle Deletion, CDG Font Robustness, and Video Worker State Guard
|
||||
|
||||
**Created:** 2026-03-15
|
||||
**Branch:** feat/sess-20260315-1520-investigate-state-transition
|
||||
**Status:** Implemented
|
||||
**Triggered by:** Job 27054772 (CDG generation failure) and Job 2d4a7bab (style_params.json 404 after 7 days)
|
||||
|
||||
## Overview
|
||||
|
||||
Three related issues discovered during investigation of production job failures:
|
||||
|
||||
1. **GCS lifecycle rule deletes `style_params.json` after 7 days** — The bucket has a lifecycle rule deleting objects with `uploads/` prefix after 7 days. `style_params.json` is stored under `uploads/{job_id}/style/` and gets deleted, breaking any job not completed within a week.
|
||||
|
||||
2. **CDG generation crashes with unhelpful error when font download fails** — When the font file can't be resolved, `_validate_and_setup_font()` sets `font_path = None`. Python's `toml.dump()` silently omits `None` values, causing `KeyError: 'font'` downstream in `KaraokeComposer`. The error message is opaque: "CDG generation was enabled but failed."
|
||||
|
||||
3. **Video worker doesn't guard against invalid state transitions** — Unlike other workers (audio, lyrics, render), the video worker doesn't call `validate_worker_can_run()` before transitioning to `GENERATING_VIDEO`. When Cloud Tasks retries a failed job, the worker attempts `failed -> GENERATING_VIDEO` which throws `InvalidStateTransitionError`, producing cascading noise in logs and error messages.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Jobs must work regardless of how long they sit before completion (no 7-day style deadline)
|
||||
- [ ] CDG generation must fail gracefully with a clear error, or fall back to a bundled font
|
||||
- [ ] Video worker retries against failed/cancelled jobs must exit cleanly, not throw state errors
|
||||
- [ ] All existing tests must continue to pass
|
||||
- [ ] Backward compatibility: existing jobs with `uploads/` style paths must still work
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Fix 1: Move `style_params.json` from `uploads/` to `jobs/` prefix
|
||||
|
||||
The `jobs/` prefix is NOT subject to the lifecycle rule and is the natural home for job-scoped data. All other job outputs (stems, lyrics, screens, videos) already live under `jobs/{job_id}/`.
|
||||
|
||||
**Approach**: Change the path generation in `theme_service.prepare_job_style()` and all related upload paths in `file_upload.py` and `audio_search.py` from `uploads/{job_id}/style/` to `jobs/{job_id}/style/`.
|
||||
|
||||
**Backward compatibility**: Existing jobs in Firestore already store their `style_params_gcs_path` as a string field. Old jobs will still have `uploads/...` paths and will work until the lifecycle rule deletes them. No migration needed — workers read the path from the job document, not from a hardcoded pattern. New jobs will get `jobs/...` paths that persist forever.
|
||||
|
||||
**Note**: The `uploads/` prefix will still be used for temporary file upload staging (audio files, etc.) which is appropriate for the lifecycle rule.
|
||||
|
||||
### Fix 2: CDG font fallback to bundled default
|
||||
|
||||
The bundled fonts directory at `karaoke_gen/lyrics_transcriber/output/fonts/` already contains `AvenirNext-Bold.ttf` (the exact font used by the nomad theme). The CDG generator already tries this directory as a fallback, but the check at `_validate_and_setup_font()` looks for the full relative path (e.g., `themes/nomad/assets/AvenirNext-Bold.ttf`) rather than just the filename.
|
||||
|
||||
**Approach**: When the font path can't be resolved, fall back to the bundled font by filename (not full path). If even that fails, fall back to a known bundled font (`arial.ttf`) rather than setting `None`.
|
||||
|
||||
Additionally, add a safety net: if `font_path` is `None` when building the TOML data, raise a clear error instead of letting `toml.dump()` silently omit it.
|
||||
|
||||
### Fix 3: Video worker state guard
|
||||
|
||||
Follow the established pattern from `render_video_worker.py`, `audio_worker.py`, and `lyrics_worker.py`: call `validate_worker_can_run("video_worker", job)` before attempting the state transition. Make it a **hard failure** (return False) for terminal states (`failed`, `cancelled`, `complete`) since there's no point proceeding — unlike the soft warning in other workers.
|
||||
|
||||
Also update `_check_worker_idempotency()` to check for terminal job states, providing an additional safety layer at the HTTP endpoint level.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Move style_params.json to `jobs/` prefix
|
||||
|
||||
1. [ ] **`backend/services/theme_service.py:337`** — Change `f"uploads/{job_id}/style/style_params.json"` to `f"jobs/{job_id}/style/style_params.json"`
|
||||
|
||||
2. [ ] **`backend/api/routes/file_upload.py`** — Update all `uploads/{job_id}/style/` references:
|
||||
- Line 725: Custom style_params upload path
|
||||
- Line 744: Style background image upload path
|
||||
- Line 755: Custom font upload path
|
||||
- Line 1079, 1083: `_get_gcs_path_for_file()` helper
|
||||
- Line 1376, 1379: Signed URL upload finding logic
|
||||
- Line 1873: Second path generation function
|
||||
- Line 2205, 2458: Finalise-only endpoint style finding
|
||||
- Line 2499: Style asset completion endpoint
|
||||
|
||||
3. [ ] **`backend/api/routes/audio_search.py:769,773`** — Update signed URL generation paths
|
||||
|
||||
4. [ ] **Update tests** to expect new `jobs/` prefix:
|
||||
- `backend/tests/test_theme_service.py:339,358`
|
||||
- `backend/tests/test_file_upload.py:701,708,715`
|
||||
- `backend/tests/test_style_upload.py:183-184`
|
||||
- `backend/tests/test_routes_review.py:331-337`
|
||||
- `backend/tests/emulator/test_style_loading_direct.py:153-161,258`
|
||||
- `tests/unit/test_remote_cli.py:699,2562,2644`
|
||||
- `backend/tests/test_style_upload_endpoints.py:254,290`
|
||||
|
||||
Note: `backend/tests/test_change_visibility.py` already uses `jobs/` prefix — no changes needed there.
|
||||
|
||||
### Step 2: CDG font fallback robustness
|
||||
|
||||
5. [ ] **`karaoke_gen/lyrics_transcriber/output/cdg.py` — `_validate_and_setup_font()`** (lines 173-187):
|
||||
- When font not found at full path, try just the filename in the bundled fonts directory
|
||||
- If still not found, fall back to `arial.ttf` from bundled fonts (always present)
|
||||
- Only set `None` if the bundled fonts directory itself doesn't exist (extreme edge case)
|
||||
- Log warning with the fallback path chosen
|
||||
|
||||
6. [ ] **`karaoke_gen/lyrics_transcriber/output/cdg.py` — `_create_toml_data()`** (line 400):
|
||||
- Add explicit check: if `cdg_styles["font_path"]` is None, raise `RuntimeError("CDG font_path is None — cannot generate CDG without a font")`
|
||||
- This prevents the silent `toml.dump()` omission that causes a confusing downstream error
|
||||
|
||||
7. [ ] **Add test** for CDG font fallback behavior:
|
||||
- Test that an unresolvable font path falls back to bundled font
|
||||
- Test that `_create_toml_data` raises if font is None
|
||||
|
||||
### Step 3: Video worker state guard
|
||||
|
||||
8. [ ] **`backend/workers/video_worker.py` — `generate_video_orchestrated()`** (around line 224):
|
||||
- Add `validate_worker_can_run("video_worker", job)` check after `_validate_prerequisites()`
|
||||
- For terminal states (`failed`, `cancelled`, `complete`), return False (hard failure)
|
||||
- Log the rejection clearly
|
||||
|
||||
9. [ ] **`backend/workers/video_worker.py` — `generate_video_legacy()`** (around line 637):
|
||||
- Same guard as above
|
||||
|
||||
10. [ ] **`backend/api/routes/internal.py` — `_check_worker_idempotency()`** (around line 79):
|
||||
- After checking `state_data` progress, also check if job is in a terminal state (`failed`, `cancelled`)
|
||||
- Return "skipped" response for terminal states to prevent Cloud Tasks from triggering workers on dead jobs
|
||||
|
||||
11. [ ] **Add test** for video worker state guard:
|
||||
- Test that video worker returns False when job is in `failed` state
|
||||
- Test that idempotency check rejects terminal-state jobs
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/services/theme_service.py` | Modify | Change style path prefix from `uploads/` to `jobs/` |
|
||||
| `backend/api/routes/file_upload.py` | Modify | Update ~11 `uploads/{job_id}/style/` path references |
|
||||
| `backend/api/routes/audio_search.py` | Modify | Update 2 signed URL path references |
|
||||
| `karaoke_gen/lyrics_transcriber/output/cdg.py` | Modify | Improve font fallback logic, add None guard |
|
||||
| `backend/workers/video_worker.py` | Modify | Add `validate_worker_can_run()` guard to both pipelines |
|
||||
| `backend/api/routes/internal.py` | Modify | Add terminal state check to idempotency function |
|
||||
| `backend/tests/test_theme_service.py` | Modify | Update expected paths |
|
||||
| `backend/tests/test_file_upload.py` | Modify | Update expected paths |
|
||||
| `backend/tests/test_style_upload.py` | Modify | Update expected paths |
|
||||
| `backend/tests/test_routes_review.py` | Modify | Update expected paths |
|
||||
| `backend/tests/test_style_upload_endpoints.py` | Modify | Update expected paths |
|
||||
| `backend/tests/emulator/test_style_loading_direct.py` | Modify | Update expected paths |
|
||||
| `tests/unit/test_remote_cli.py` | Modify | Update expected paths |
|
||||
| `backend/tests/test_cdg_countdown.py` | Modify | Add font fallback tests |
|
||||
| `backend/tests/test_video_worker_orchestrator.py` | Modify | Add state guard test |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Update all existing path assertions to expect `jobs/` prefix. Add new tests for CDG font fallback and video worker state guard.
|
||||
- **Integration tests**: The emulator test in `test_style_loading_direct.py` verifies end-to-end style loading with real GCS operations.
|
||||
- **Run full suite**: `make test 2>&1 | tail -n 500` must pass before committing.
|
||||
|
||||
## Open Questions
|
||||
|
||||
None — all three fixes are well-understood from investigation.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- **Fix 1**: If `jobs/` prefix causes issues, revert the path change. Existing jobs with `uploads/` paths will still work since workers read the path from the job document.
|
||||
- **Fix 2**: CDG font fallback is purely additive — remove the fallback logic to restore original behavior.
|
||||
- **Fix 3**: State guard is purely additive — remove the `validate_worker_can_run` call to restore original behavior.
|
||||
|
||||
## Immediate Manual Fix Applied
|
||||
|
||||
- Re-uploaded `style_params.json` for job `2d4a7bab` so it can be retried before this fix ships.
|
||||
@@ -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}
|
||||
```
|
||||
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,612 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import {
|
||||
adminApi,
|
||||
AudioEditReviewSummary,
|
||||
AudioEditReviewListResponse,
|
||||
AudioEditReviewDetail,
|
||||
} 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 {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Search,
|
||||
Loader2,
|
||||
Eye,
|
||||
Code,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
Check,
|
||||
Clock,
|
||||
Scissors,
|
||||
Play,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
function formatDuration(seconds?: number): string {
|
||||
if (seconds == null || !Number.isFinite(seconds)) return "-"
|
||||
const mins = Math.floor(seconds / 60)
|
||||
const secs = Math.floor(seconds % 60)
|
||||
return `${mins}:${secs.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
function formatDurationChange(original?: number, current?: number): string {
|
||||
if (original == null || current == null) return ""
|
||||
const diff = current - original
|
||||
if (Math.abs(diff) < 0.5) return ""
|
||||
const sign = diff < 0 ? "-" : "+"
|
||||
const abs = Math.abs(diff)
|
||||
const mins = Math.floor(abs / 60)
|
||||
const secs = Math.floor(abs % 60)
|
||||
return `${sign}${mins}:${secs.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
// ─── Edit Stack Viewer ────────────────────────────────────────────────────
|
||||
|
||||
function EditStackViewer({
|
||||
editStack,
|
||||
}: {
|
||||
editStack: AudioEditReviewDetail["edit_stack"]
|
||||
}) {
|
||||
if (editStack.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-32 text-muted-foreground">
|
||||
No edits applied.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{editStack.map((entry, idx) => (
|
||||
<div key={entry.edit_id || idx} className="border rounded-md p-3">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{idx + 1}. {entry.operation}
|
||||
</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(entry.timestamp).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
{entry.duration_before != null && (
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{formatDuration(entry.duration_before)}
|
||||
</span>
|
||||
)}
|
||||
{entry.duration_before != null && entry.duration_after != null && (
|
||||
<span className="text-xs text-muted-foreground">→</span>
|
||||
)}
|
||||
{entry.duration_after != null && (
|
||||
<span className="text-xs font-medium">
|
||||
{formatDuration(entry.duration_after)}
|
||||
</span>
|
||||
)}
|
||||
{entry.params && Object.keys(entry.params).length > 0 && (
|
||||
<span className="text-xs text-muted-foreground ml-2">
|
||||
{Object.entries(entry.params)
|
||||
.map(([k, v]) => `${k}: ${typeof v === "number" ? formatDuration(v) : v}`)
|
||||
.join(", ")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Sessions Viewer ──────────────────────────────────────────────────────
|
||||
|
||||
function SessionsViewer({
|
||||
sessions,
|
||||
}: {
|
||||
sessions: AudioEditReviewDetail["sessions"]
|
||||
}) {
|
||||
if (sessions.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-32 text-muted-foreground">
|
||||
No saved sessions.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{sessions.map((session) => (
|
||||
<Card key={session.session_id}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={
|
||||
session.trigger === "submit"
|
||||
? "default"
|
||||
: session.trigger === "manual"
|
||||
? "secondary"
|
||||
: "outline"
|
||||
}
|
||||
className="text-xs"
|
||||
>
|
||||
{session.trigger}
|
||||
</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{session.edit_count} edit{session.edit_count !== 1 ? "s" : ""}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(session.updated_at).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Duration info */}
|
||||
{session.original_duration_seconds != null && (
|
||||
<div className="flex items-center gap-2 text-sm mb-2">
|
||||
<span className="text-muted-foreground">
|
||||
{formatDuration(session.original_duration_seconds)}
|
||||
</span>
|
||||
<span className="text-muted-foreground">→</span>
|
||||
<span className="font-medium">
|
||||
{formatDuration(session.audio_duration_seconds)}
|
||||
</span>
|
||||
{session.audio_duration_seconds != null && (
|
||||
<span className="text-xs text-red-500">
|
||||
{formatDurationChange(
|
||||
session.original_duration_seconds,
|
||||
session.audio_duration_seconds
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Operations breakdown */}
|
||||
{session.summary?.operations_breakdown && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{Object.entries(session.summary.operations_breakdown).map(
|
||||
([op, count]) => (
|
||||
<Badge key={op} variant="secondary" className="text-xs">
|
||||
{op}: {count}
|
||||
</Badge>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-xs text-muted-foreground mt-2 font-mono truncate">
|
||||
{session.session_id}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Main Page ────────────────────────────────────────────────────────────
|
||||
|
||||
export default function AudioEditsPage() {
|
||||
const { showTestData } = useAdminSettings()
|
||||
|
||||
// List state
|
||||
const [reviews, setReviews] = useState<AudioEditReviewSummary[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [hasMore, setHasMore] = useState(false)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
// Detail dialog state
|
||||
const [detailDialogOpen, setDetailDialogOpen] = useState(false)
|
||||
const [rawDataDialogOpen, setRawDataDialogOpen] = useState(false)
|
||||
const [selectedDetail, setSelectedDetail] = useState<AudioEditReviewDetail | null>(null)
|
||||
const [detailLoading, setDetailLoading] = useState(false)
|
||||
|
||||
const fetchReviews = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data: AudioEditReviewListResponse =
|
||||
await adminApi.listAudioEditReviews({
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
exclude_test: !showTestData,
|
||||
search: searchQuery || undefined,
|
||||
})
|
||||
setReviews(data.reviews)
|
||||
setTotal(data.total)
|
||||
setHasMore(data.has_more)
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
"Failed to load audio edit reviews: " +
|
||||
(err instanceof Error ? err.message : String(err))
|
||||
)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [offset, searchQuery, showTestData])
|
||||
|
||||
useEffect(() => {
|
||||
fetchReviews()
|
||||
}, [fetchReviews])
|
||||
|
||||
const loadDetail = useCallback(async (jobId: string) => {
|
||||
setDetailLoading(true)
|
||||
try {
|
||||
const detail = await adminApi.getAudioEditReview(jobId)
|
||||
setSelectedDetail(detail)
|
||||
return detail
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
"Failed to load detail: " +
|
||||
(err instanceof Error ? err.message : String(err))
|
||||
)
|
||||
return null
|
||||
} finally {
|
||||
setDetailLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleViewDetail = useCallback(
|
||||
async (jobId: string) => {
|
||||
const detail = await loadDetail(jobId)
|
||||
if (detail) setDetailDialogOpen(true)
|
||||
},
|
||||
[loadDetail]
|
||||
)
|
||||
|
||||
const handleViewRawData = useCallback(
|
||||
async (jobId: string) => {
|
||||
const detail = await loadDetail(jobId)
|
||||
if (detail) setRawDataDialogOpen(true)
|
||||
},
|
||||
[loadDetail]
|
||||
)
|
||||
|
||||
const handleSearch = useCallback(() => {
|
||||
setOffset(0)
|
||||
setSearchQuery(searchInput)
|
||||
}, [searchInput])
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") handleSearch()
|
||||
},
|
||||
[handleSearch]
|
||||
)
|
||||
|
||||
const [copiedJson, setCopiedJson] = useState(false)
|
||||
const handleCopyJson = useCallback(() => {
|
||||
if (!selectedDetail) return
|
||||
navigator.clipboard.writeText(JSON.stringify(selectedDetail, null, 2))
|
||||
setCopiedJson(true)
|
||||
toast.success("Copied to clipboard")
|
||||
setTimeout(() => setCopiedJson(false), 2000)
|
||||
}, [selectedDetail])
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Audio Edits</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Review input audio editing sessions and edit history
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search by artist, title, or email..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={handleSearch} variant="secondary">
|
||||
Search
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<Card>
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-base">
|
||||
{loading
|
||||
? "Loading..."
|
||||
: `${total} job${total !== 1 ? "s" : ""} with audio edits`}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{loading ? (
|
||||
<div className="p-4 space-y-3">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-12 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : reviews.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-48 text-muted-foreground">
|
||||
No audio edit reviews found.
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Artist / Title</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Edits</TableHead>
|
||||
<TableHead>Duration</TableHead>
|
||||
<TableHead>Sessions</TableHead>
|
||||
<TableHead>Updated</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{reviews.map((review) => (
|
||||
<TableRow key={review.job_id}>
|
||||
<TableCell>
|
||||
<div className="font-medium">{review.artist}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{review.title}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={
|
||||
review.status === "complete"
|
||||
? "default"
|
||||
: review.status.includes("audio_edit")
|
||||
? "secondary"
|
||||
: "outline"
|
||||
}
|
||||
>
|
||||
{review.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-medium">{review.total_edits}</span>
|
||||
{review.latest_trigger && (
|
||||
<Badge variant="outline" className="ml-1 text-xs">
|
||||
{review.latest_trigger}
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{review.original_duration != null ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-muted-foreground">
|
||||
{formatDuration(review.original_duration)}
|
||||
</span>
|
||||
{review.current_duration != null &&
|
||||
review.current_duration !== review.original_duration && (
|
||||
<>
|
||||
<span className="text-muted-foreground">
|
||||
→
|
||||
</span>
|
||||
<span className="font-medium">
|
||||
{formatDuration(review.current_duration)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
"-"
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{review.session_count}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">
|
||||
{review.updated_at
|
||||
? new Date(review.updated_at).toLocaleDateString()
|
||||
: "-"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewDetail(review.job_id)}
|
||||
disabled={detailLoading}
|
||||
title="View Detail"
|
||||
>
|
||||
<Eye className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewRawData(review.job_id)}
|
||||
disabled={detailLoading}
|
||||
title="View Raw Data"
|
||||
>
|
||||
<Code className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{!loading && total > PAGE_SIZE && (
|
||||
<div className="flex items-center justify-between p-4 border-t">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={offset === 0}
|
||||
onClick={() =>
|
||||
setOffset((o) => Math.max(0, o - PAGE_SIZE))
|
||||
}
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4 mr-1" /> Previous
|
||||
</Button>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Showing {offset + 1}-{Math.min(offset + PAGE_SIZE, total)} of{" "}
|
||||
{total}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!hasMore}
|
||||
onClick={() => setOffset((o) => o + PAGE_SIZE)}
|
||||
>
|
||||
Next <ChevronRight className="w-4 h-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Detail Dialog */}
|
||||
<Dialog open={detailDialogOpen} onOpenChange={setDetailDialogOpen}>
|
||||
<DialogContent className="max-w-3xl w-full max-h-[90vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{selectedDetail
|
||||
? `${selectedDetail.job.artist} - ${selectedDetail.job.title}`
|
||||
: "Loading..."}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex-1 overflow-auto">
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center justify-center h-48">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : selectedDetail ? (
|
||||
<Tabs defaultValue="edit-stack" className="w-full">
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="edit-stack" className="flex-1">
|
||||
<Scissors className="w-3 h-3 mr-1" />
|
||||
Edit Stack ({selectedDetail.edit_stack.length})
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="sessions" className="flex-1">
|
||||
<Clock className="w-3 h-3 mr-1" />
|
||||
Sessions ({selectedDetail.sessions.length})
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="audio" className="flex-1">
|
||||
<Play className="w-3 h-3 mr-1" />
|
||||
Audio
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="edit-stack">
|
||||
<ScrollArea className="h-[500px]">
|
||||
<EditStackViewer editStack={selectedDetail.edit_stack} />
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="sessions">
|
||||
<ScrollArea className="h-[500px]">
|
||||
<SessionsViewer sessions={selectedDetail.sessions} />
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="audio">
|
||||
<div className="space-y-4 p-2">
|
||||
{selectedDetail.original_audio_url && (
|
||||
<div>
|
||||
<div className="text-sm font-medium mb-2">
|
||||
Original Audio
|
||||
</div>
|
||||
<audio
|
||||
controls
|
||||
src={selectedDetail.original_audio_url}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{selectedDetail.current_audio_url && (
|
||||
<div>
|
||||
<div className="text-sm font-medium mb-2">
|
||||
Current Audio
|
||||
{selectedDetail.original_audio_url
|
||||
? " (after edits)"
|
||||
: ""}
|
||||
</div>
|
||||
<audio
|
||||
controls
|
||||
src={selectedDetail.current_audio_url}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!selectedDetail.original_audio_url &&
|
||||
!selectedDetail.current_audio_url && (
|
||||
<div className="flex items-center justify-center h-32 text-muted-foreground">
|
||||
No audio URLs available.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-48 text-muted-foreground">
|
||||
No data available.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Raw Data Dialog */}
|
||||
<Dialog open={rawDataDialogOpen} onOpenChange={setRawDataDialogOpen}>
|
||||
<DialogContent className="max-w-4xl w-full max-h-[85vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Raw Data
|
||||
{selectedDetail && (
|
||||
<span className="text-sm font-normal text-muted-foreground ml-2">
|
||||
{selectedDetail.job.artist} - {selectedDetail.job.title}
|
||||
</span>
|
||||
)}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex-1 overflow-auto">
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button variant="outline" size="sm" onClick={handleCopyJson}>
|
||||
{copiedJson ? (
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
) : (
|
||||
<Copy className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-[500px]">
|
||||
<pre className="text-xs bg-muted/50 p-3 rounded-md overflow-x-auto">
|
||||
{JSON.stringify(selectedDetail, null, 2) ?? "null"}
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
@@ -159,6 +160,9 @@ function AdminJobsPageContent() {
|
||||
const [logFilter, setLogFilter] = useState<string>("all")
|
||||
const [logSearch, setLogSearch] = useState("")
|
||||
|
||||
// Source info modal
|
||||
const [sourceModalOpen, setSourceModalOpen] = useState(false)
|
||||
|
||||
// Delete dialog
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [jobToDelete, setJobToDelete] = useState<Job | null>(null)
|
||||
@@ -618,12 +622,24 @@ function AdminJobsPageContent() {
|
||||
|
||||
// Determine job source with detail data
|
||||
const getJobSource = (job: Job) => {
|
||||
if (job?.url) return { type: "url" as const, icon: Globe, label: "YouTube", detail: job.url }
|
||||
// Check audio_source_type first (most reliable)
|
||||
if (job?.audio_source_type === "youtube_url" || job?.url) {
|
||||
return { type: "url" as const, icon: Globe, label: "YouTube", detail: job.url || "YouTube URL" }
|
||||
}
|
||||
if (job?.audio_source_type === "audio_search") {
|
||||
const parts = [job.audio_search_artist, job.audio_search_title].filter(Boolean)
|
||||
const detail = parts.length > 0 ? parts.join(" - ") : (job.target_file || job.filename || "Audio search")
|
||||
const label = job.source_name ? `Search (${job.source_name})` : "Search"
|
||||
return { type: "search" as const, icon: Search, label, detail }
|
||||
}
|
||||
if (job?.audio_source_type === "file_upload" || job?.filename) {
|
||||
return { type: "upload" as const, icon: Upload, label: "Upload", detail: job.filename || "Uploaded file" }
|
||||
}
|
||||
// Fallback: check fields without audio_source_type (older jobs)
|
||||
if (job?.audio_search_artist || job?.audio_search_title) {
|
||||
const parts = [job.audio_search_artist, job.audio_search_title].filter(Boolean)
|
||||
return { type: "search" as const, icon: Search, label: "Search", detail: parts.join(" - ") }
|
||||
}
|
||||
if (job?.filename) return { type: "upload" as const, icon: Upload, label: "Upload", detail: job.filename }
|
||||
return { type: "unknown" as const, icon: FileText, label: "Unknown", detail: undefined }
|
||||
}
|
||||
|
||||
@@ -1112,34 +1128,18 @@ function AdminJobsPageContent() {
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Source</p>
|
||||
{jobSource.type === "url" && jobSource.detail ? (
|
||||
<a
|
||||
href={jobSource.detail}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm flex items-center gap-1.5 text-primary hover:underline cursor-pointer truncate"
|
||||
title={`Open YouTube video: ${jobSource.detail}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<SourceIcon className="w-3.5 h-3.5 shrink-0" />
|
||||
<span className="truncate">{jobSource.detail.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40)}</span>
|
||||
</a>
|
||||
) : jobSource.type === "search" && jobSource.detail ? (
|
||||
<p className="text-sm flex items-center gap-1.5 truncate" title={`Audio search: ${jobSource.detail}`}>
|
||||
<SourceIcon className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
|
||||
<span className="truncate">{jobSource.detail}</span>
|
||||
</p>
|
||||
) : jobSource.type === "upload" && jobSource.detail ? (
|
||||
<p className="text-sm flex items-center gap-1.5 truncate" title={`Uploaded file: ${jobSource.detail}`}>
|
||||
<SourceIcon className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
|
||||
<span className="truncate">{jobSource.detail}</span>
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm flex items-center gap-1.5 text-muted-foreground">
|
||||
<SourceIcon className="w-3.5 h-3.5" />
|
||||
Unknown
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
className="text-sm flex items-center gap-1.5 text-primary hover:underline cursor-pointer truncate text-left"
|
||||
title="Click for source details"
|
||||
onClick={() => setSourceModalOpen(true)}
|
||||
>
|
||||
<SourceIcon className="w-3.5 h-3.5 shrink-0" />
|
||||
<span className="truncate">
|
||||
{jobSource.type === "url" && jobSource.detail
|
||||
? jobSource.detail.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40)
|
||||
: jobSource.detail || "Unknown"}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Created</p>
|
||||
@@ -1428,6 +1428,91 @@ function AdminJobsPageContent() {
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* ===== SOURCE INFO MODAL ===== */}
|
||||
<Dialog open={sourceModalOpen} onOpenChange={setSourceModalOpen}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<SourceIcon className="w-4 h-4" />
|
||||
Audio Source Details
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{jobSource.label} — {selectedJob.artist} - {selectedJob.title}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3 text-sm">
|
||||
{selectedJob.audio_source_type && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Source Type</span>
|
||||
<span className="font-medium">{selectedJob.audio_source_type.replace(/_/g, " ")}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.source_name && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Provider</span>
|
||||
<span className="font-medium">{selectedJob.source_name}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.source_id && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Source ID</span>
|
||||
<span className="font-mono text-xs">{selectedJob.source_id}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.url && (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">URL</span>
|
||||
<a
|
||||
href={selectedJob.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline truncate font-mono text-xs"
|
||||
>
|
||||
{selectedJob.url}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.filename && (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">Filename</span>
|
||||
<span className="truncate font-mono text-xs">{selectedJob.filename}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.target_file && selectedJob.target_file !== selectedJob.filename && (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">Target File</span>
|
||||
<span className="truncate font-mono text-xs">{selectedJob.target_file}</span>
|
||||
</div>
|
||||
)}
|
||||
{(selectedJob.audio_search_artist || selectedJob.audio_search_title) && (
|
||||
<>
|
||||
{selectedJob.audio_search_artist && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Search Artist</span>
|
||||
<span>{selectedJob.audio_search_artist}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.audio_search_title && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Search Title</span>
|
||||
<span>{selectedJob.audio_search_title}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{selectedJob.download_url && (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">Download URL</span>
|
||||
<span className="truncate font-mono text-xs">{selectedJob.download_url}</span>
|
||||
</div>
|
||||
)}
|
||||
{!selectedJob.audio_source_type && !selectedJob.url && !selectedJob.filename && (
|
||||
<p className="text-muted-foreground italic">No source information available for this job.</p>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* ===== LOGS MODAL ===== */}
|
||||
<Dialog open={logsModalOpen} onOpenChange={setLogsModalOpen}>
|
||||
<DialogContent className="max-w-5xl max-h-[85vh] flex flex-col">
|
||||
|
||||
@@ -22,6 +22,9 @@ 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(),
|
||||
@@ -41,11 +44,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 +145,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 +155,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 +170,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 +203,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,6 +34,8 @@ import {
|
||||
Clock,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Shield,
|
||||
X,
|
||||
} from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
@@ -52,6 +54,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 +107,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 +235,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 +409,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 +499,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 +517,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>
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ describe('AdminJobActions', () => {
|
||||
|
||||
// Reset buttons
|
||||
expect(screen.getByText('Audio')).toBeInTheDocument()
|
||||
expect(screen.getByText('Audio Edit')).toBeInTheDocument()
|
||||
expect(screen.getByText('Review')).toBeInTheDocument()
|
||||
expect(screen.getByText('Reprocess')).toBeInTheDocument()
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -248,6 +248,59 @@ describe('OutputLinks', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('With Vocals MP4 preference', () => {
|
||||
it('prefers finals.with_vocals_mp4 over videos.with_vocals when both exist', () => {
|
||||
const jobWithBoth: Job = {
|
||||
...baseJob,
|
||||
file_urls: {
|
||||
finals: {
|
||||
lossy_4k_mp4: 'gs://bucket/finals/4k.mp4',
|
||||
with_vocals_mp4: 'gs://bucket/finals/with_vocals.mp4',
|
||||
},
|
||||
videos: {
|
||||
with_vocals: 'gs://bucket/videos/with_vocals.mkv',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
render(<OutputLinks job={jobWithBoth} />)
|
||||
|
||||
const vocalsLink = screen.getByText('With Vocals').closest('a')
|
||||
expect(vocalsLink).toHaveAttribute('href',
|
||||
expect.stringContaining('/finals/with_vocals_mp4')
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to videos.with_vocals when finals.with_vocals_mp4 is missing', () => {
|
||||
render(<OutputLinks job={baseJob} />)
|
||||
|
||||
const vocalsLink = screen.getByText('With Vocals').closest('a')
|
||||
expect(vocalsLink).toHaveAttribute('href',
|
||||
expect.stringContaining('/videos/with_vocals')
|
||||
)
|
||||
})
|
||||
|
||||
it('shows With Vocals when only finals.with_vocals_mp4 exists (no legacy MKV)', () => {
|
||||
const mp4OnlyJob: Job = {
|
||||
...baseJob,
|
||||
file_urls: {
|
||||
finals: {
|
||||
lossy_4k_mp4: 'gs://bucket/finals/4k.mp4',
|
||||
with_vocals_mp4: 'gs://bucket/finals/with_vocals.mp4',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
render(<OutputLinks job={mp4OnlyJob} />)
|
||||
|
||||
expect(screen.getByText('With Vocals')).toBeInTheDocument()
|
||||
const vocalsLink = screen.getByText('With Vocals').closest('a')
|
||||
expect(vocalsLink).toHaveAttribute('href',
|
||||
expect.stringContaining('/finals/with_vocals_mp4')
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('handles partial file_urls gracefully', () => {
|
||||
// Reset to non-admin user
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Search,
|
||||
ShieldAlert,
|
||||
BookOpenCheck,
|
||||
Scissors,
|
||||
} from "lucide-react"
|
||||
|
||||
import {
|
||||
@@ -64,6 +65,11 @@ const navItems = [
|
||||
href: "/admin/edit-reviews",
|
||||
icon: BookOpenCheck,
|
||||
},
|
||||
{
|
||||
title: "Audio Edits",
|
||||
href: "/admin/audio-edits",
|
||||
icon: Scissors,
|
||||
},
|
||||
]
|
||||
|
||||
export function AdminSidebar() {
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
CloudOff,
|
||||
Music,
|
||||
Mic,
|
||||
Scissors,
|
||||
} from "lucide-react"
|
||||
|
||||
interface AdminJobActionsProps {
|
||||
@@ -107,6 +108,13 @@ export function AdminJobActions({ job, onRefresh }: AdminJobActionsProps) {
|
||||
{isLoading("reset-awaiting_audio_selection") ? <Loader2 className="w-3 h-3 animate-spin" /> : <Music className="w-3 h-3 mr-0.5" />}
|
||||
Audio
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-blue-400 hover:text-blue-300"
|
||||
onClick={() => handleReset("awaiting_audio_edit", "Audio Edit")}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("reset-awaiting_audio_edit") ? <Loader2 className="w-3 h-3 animate-spin" /> : <Scissors className="w-3 h-3 mr-0.5" />}
|
||||
Audio Edit
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-blue-400 hover:text-blue-300"
|
||||
onClick={() => handleReset("awaiting_review", "Review")}
|
||||
disabled={loading !== null}
|
||||
|
||||
@@ -85,7 +85,8 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
job.status === "in_review" ||
|
||||
job.status === "awaiting_instrumental_selection" ||
|
||||
job.status === "awaiting_audio_selection" ||
|
||||
job.status === "awaiting_audio_edit"
|
||||
job.status === "awaiting_audio_edit" ||
|
||||
job.status === "in_audio_edit"
|
||||
const isComplete = job.status === "complete"
|
||||
const isFailed = job.status === "failed"
|
||||
|
||||
@@ -115,7 +116,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
)
|
||||
}
|
||||
|
||||
if (job.status === "awaiting_audio_edit") {
|
||||
if (job.status === "awaiting_audio_edit" || job.status === "in_audio_edit") {
|
||||
return (
|
||||
<a
|
||||
href={`/app/jobs#/${job.job_id}/audio-edit`}
|
||||
|
||||
@@ -180,6 +180,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
const hasDownloads = !outputsDeleted && downloadUrls && (
|
||||
downloadUrls?.finals?.lossy_720p_mp4 ||
|
||||
downloadUrls?.finals?.lossy_4k_mp4 ||
|
||||
downloadUrls?.finals?.with_vocals_mp4 ||
|
||||
downloadUrls?.videos?.with_vocals ||
|
||||
downloadUrls?.packages?.cdg_zip ||
|
||||
downloadUrls?.packages?.txt_zip
|
||||
@@ -268,9 +269,12 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
720p Video
|
||||
</a>
|
||||
)}
|
||||
{downloadUrls?.videos?.with_vocals && (
|
||||
{(downloadUrls?.finals?.with_vocals_mp4 || downloadUrls?.videos?.with_vocals) && (
|
||||
<a
|
||||
href={api.getDownloadUrl(job.job_id, "videos", "with_vocals")}
|
||||
href={api.getDownloadUrl(job.job_id,
|
||||
downloadUrls?.finals?.with_vocals_mp4 ? "finals" : "videos",
|
||||
downloadUrls?.finals?.with_vocals_mp4 ? "with_vocals_mp4" : "with_vocals"
|
||||
)}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-[#252525] hover:bg-[#333333] text-[var(--text)] border border-[var(--card-border)] transition-colors"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from "@/lib/audio-search-utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info, Search, X } from "lucide-react"
|
||||
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info, Search, X, Scissors, Zap } from "lucide-react"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
|
||||
interface AudioSourceStepProps {
|
||||
@@ -335,36 +335,50 @@ export function AudioSourceStep({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="rounded-lg border p-5 space-y-4"
|
||||
style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}
|
||||
>
|
||||
<h3 className="text-base font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Do you want to review and edit this audio before it gets transcribed?
|
||||
</h3>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Trim, cut, mute, or join sections of the downloaded audio before lyrics are transcribed and synced.
|
||||
Useful for trimming intro/outro from a live version, shortening a lengthy outro, etc.
|
||||
</p>
|
||||
<div className="flex flex-col gap-3">
|
||||
{/* Default: use as-is (recommended for most users) */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAudioEditAnswer(false)}
|
||||
className="group rounded-lg border-2 p-4 transition-all text-left flex items-start gap-4 border-[var(--success)] hover:bg-[rgba(34,197,94,0.06)]"
|
||||
style={{ backgroundColor: 'rgba(34, 197, 94, 0.03)' }}
|
||||
>
|
||||
<div className="mt-0.5 flex-shrink-0 rounded-full p-1.5" style={{ backgroundColor: 'rgba(34, 197, 94, 0.15)' }}>
|
||||
<Zap className="w-5 h-5" style={{ color: 'var(--success)' }} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>Use audio as-is</span>
|
||||
<span className="text-[10px] font-medium uppercase tracking-wide px-1.5 py-0.5 rounded" style={{ backgroundColor: 'rgba(34, 197, 94, 0.15)', color: 'var(--success)' }}>
|
||||
Recommended
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Start processing right away — best for most tracks
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-3 pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAudioEditAnswer(false)}
|
||||
className="flex-1 rounded-lg border-2 p-4 transition-all text-center border-[var(--card-border)] hover:border-[var(--text-muted)]"
|
||||
>
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>No, use as-is</span>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>Proceed directly to transcription</p>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAudioEditAnswer(true)}
|
||||
className="flex-1 rounded-lg border-2 p-4 transition-all text-center border-[var(--card-border)] hover:border-[var(--brand-pink)]"
|
||||
>
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>Yes, I'll edit it first</span>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>Trim, cut, or mute before processing</p>
|
||||
</button>
|
||||
</div>
|
||||
{/* Optional: edit first */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAudioEditAnswer(true)}
|
||||
className="group rounded-lg border-2 p-4 transition-all text-left flex items-start gap-4 border-[var(--card-border)] hover:border-[var(--brand-purple)]"
|
||||
>
|
||||
<div className="mt-0.5 flex-shrink-0 rounded-full p-1.5" style={{ backgroundColor: 'rgba(139, 92, 246, 0.12)' }}>
|
||||
<Scissors className="w-5 h-5" style={{ color: 'var(--brand-purple)' }} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>Edit audio first</span>
|
||||
<p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Trim, cut, or mute sections before processing
|
||||
</p>
|
||||
<p className="text-xs mt-2 flex items-start gap-1.5" style={{ color: 'var(--text-muted)' }}>
|
||||
<Lightbulb className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" style={{ color: 'var(--brand-gold)' }} />
|
||||
<span>Great for live recordings with intros to skip, or tracks with sections you want to remove</span>
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -216,12 +216,30 @@ test.describe('Demo Video Recording', () => {
|
||||
await page.getByRole('button', { name: /^select$/i }).first().click();
|
||||
}
|
||||
await page.waitForTimeout(PACE.afterAction);
|
||||
|
||||
// Audio edit question — choose "Use audio as-is"
|
||||
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
|
||||
await page.waitForTimeout(PACE.afterAction);
|
||||
marker('SCENE_4_END: Audio Selection');
|
||||
|
||||
// =========================================================================
|
||||
// SCENE 5: Customize & Create (Guided Step 3)
|
||||
// SCENE 5: Visibility (Guided Step 3)
|
||||
// =========================================================================
|
||||
marker('SCENE_5_START: Customize & Create');
|
||||
marker('SCENE_5_START: Visibility');
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.waitForTimeout(PACE.beforeImportant);
|
||||
await page.screenshot({ path: 'test-results/demo-04b-visibility.png' });
|
||||
|
||||
// Choose "Publish & Share" for the demo
|
||||
await page.getByRole('button', { name: /publish & share/i }).click();
|
||||
await page.waitForTimeout(PACE.afterAction);
|
||||
marker('SCENE_5_END: Visibility');
|
||||
|
||||
// =========================================================================
|
||||
// SCENE 6: Customize & Create (Guided Step 4)
|
||||
// =========================================================================
|
||||
marker('SCENE_6_START: Customize & Create');
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
@@ -248,12 +266,12 @@ test.describe('Demo Video Recording', () => {
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/demo-06-job-created.png' });
|
||||
marker('SCENE_5_END: Customize & Create');
|
||||
marker('SCENE_6_END: Customize & Create');
|
||||
|
||||
// =========================================================================
|
||||
// SCENE 6: Processing Wait (will be sped up in post-processing)
|
||||
// SCENE 7: Processing Wait (will be sped up in post-processing)
|
||||
// =========================================================================
|
||||
marker('SCENE_6_START: Processing Wait (SPEED_UP)');
|
||||
marker('SCENE_7_START: Processing Wait (SPEED_UP)');
|
||||
|
||||
// Find job card
|
||||
await page.waitForTimeout(3000);
|
||||
@@ -295,12 +313,12 @@ test.describe('Demo Video Recording', () => {
|
||||
|
||||
await page.screenshot({ path: 'test-results/demo-07-ready-for-review.png' });
|
||||
await page.waitForTimeout(PACE.afterStepComplete);
|
||||
marker('SCENE_6_END: Processing Wait (SPEED_UP)');
|
||||
marker('SCENE_7_END: Processing Wait (SPEED_UP)');
|
||||
|
||||
// =========================================================================
|
||||
// SCENE 7: Lyrics Review
|
||||
// SCENE 8: Lyrics Review
|
||||
// =========================================================================
|
||||
marker('SCENE_7_START: Lyrics Review');
|
||||
marker('SCENE_8_START: Lyrics Review');
|
||||
|
||||
// Open review page
|
||||
const reviewLink = jobCard.getByRole('link', { name: /review lyrics/i });
|
||||
@@ -366,12 +384,12 @@ test.describe('Demo Video Recording', () => {
|
||||
await proceedBtn.click();
|
||||
await reviewPage.waitForTimeout(3000);
|
||||
|
||||
marker('SCENE_7_END: Lyrics Review');
|
||||
marker('SCENE_8_END: Lyrics Review');
|
||||
|
||||
// =========================================================================
|
||||
// SCENE 8: Instrumental Selection
|
||||
// SCENE 9: Instrumental Selection
|
||||
// =========================================================================
|
||||
marker('SCENE_8_START: Instrumental Selection');
|
||||
marker('SCENE_9_START: Instrumental Selection');
|
||||
|
||||
// Wait for instrumental UI
|
||||
try {
|
||||
@@ -415,12 +433,12 @@ test.describe('Demo Video Recording', () => {
|
||||
}
|
||||
}
|
||||
|
||||
marker('SCENE_8_END: Instrumental Selection');
|
||||
marker('SCENE_9_END: Instrumental Selection');
|
||||
|
||||
// =========================================================================
|
||||
// SCENE 9: Wait for Completion (will be sped up in post-processing)
|
||||
// SCENE 10: Wait for Completion (will be sped up in post-processing)
|
||||
// =========================================================================
|
||||
marker('SCENE_9_START: Final Rendering (SPEED_UP)');
|
||||
marker('SCENE_10_START: Final Rendering (SPEED_UP)');
|
||||
|
||||
await page.bringToFront();
|
||||
if (await refreshBtn.isVisible().catch(() => false)) {
|
||||
@@ -455,18 +473,18 @@ test.describe('Demo Video Recording', () => {
|
||||
|
||||
await page.waitForTimeout(PACE.afterStepComplete);
|
||||
await page.screenshot({ path: 'test-results/demo-14-complete.png' });
|
||||
marker('SCENE_9_END: Final Rendering (SPEED_UP)');
|
||||
marker('SCENE_10_END: Final Rendering (SPEED_UP)');
|
||||
|
||||
// =========================================================================
|
||||
// SCENE 10: Show Completed Job
|
||||
// SCENE 11: Show Completed Job
|
||||
// =========================================================================
|
||||
marker('SCENE_10_START: Completion');
|
||||
marker('SCENE_11_START: Completion');
|
||||
|
||||
// Let the viewer see the completed state with all download badges
|
||||
await page.waitForTimeout(5000);
|
||||
await page.screenshot({ path: 'test-results/demo-15-final.png' });
|
||||
|
||||
marker('SCENE_10_END: Completion');
|
||||
marker('SCENE_11_END: Completion');
|
||||
|
||||
// =========================================================================
|
||||
// DONE
|
||||
|
||||
@@ -7,7 +7,7 @@ import { TEST_SONG, URLS, TIMEOUTS } from '../helpers/constants';
|
||||
/**
|
||||
* Production E2E Tests: Guided Job Creation Flow
|
||||
*
|
||||
* Tests the 3-step guided job creation flow (Song Info → Choose Audio → Customize & Create)
|
||||
* Tests the 4-step guided job creation flow (Song Info → Choose Audio → Visibility → Customize & Create)
|
||||
* against the real production backend. Uses route interception to capture outgoing
|
||||
* request bodies while still letting them hit the real API.
|
||||
*
|
||||
@@ -167,13 +167,22 @@ test.describe('Guided Job Creation Flow', () => {
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
console.log(' Step 2 complete: selected pick card');
|
||||
|
||||
// Step 3: Click "Create Karaoke Video" with defaults (no overrides, not private)
|
||||
// Audio edit question — choose "Use audio as-is"
|
||||
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
|
||||
console.log(' Selected "Use audio as-is"');
|
||||
|
||||
// Step 3: Visibility — choose "Publish & Share" (default, not private)
|
||||
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.getByRole('button', { name: /publish & share/i }).click();
|
||||
console.log(' Step 3 complete: selected Publish & Share');
|
||||
|
||||
// Step 4: Click "Create Karaoke Video" with defaults (no overrides)
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Step 3 complete: job created');
|
||||
console.log(' Step 4 complete: job created');
|
||||
|
||||
// Assert: search body has correct params
|
||||
expect(searchBody).toBeTruthy();
|
||||
@@ -241,13 +250,21 @@ test.describe('Guided Job Creation Flow', () => {
|
||||
test.skip(!hasPickCard, 'Search returned Tier 3 — skipping pick card test');
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
|
||||
// Step 3: Fill display overrides, check private, and confirm
|
||||
// Audio edit question — choose "Use audio as-is"
|
||||
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
|
||||
console.log(' Selected "Use audio as-is"');
|
||||
|
||||
// Step 3: Visibility — choose "Keep Private"
|
||||
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.getByRole('button', { name: /keep private/i }).click();
|
||||
console.log(' Selected Keep Private');
|
||||
|
||||
// Step 4: Fill display overrides and confirm
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
await page.locator('#guided-display-artist').fill('PIRI (Display)');
|
||||
await page.locator('#guided-display-title').fill('DOG (Display)');
|
||||
await page.locator('#guided-private').check();
|
||||
console.log(' Filled display overrides and checked Private');
|
||||
console.log(' Filled display overrides');
|
||||
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
|
||||
@@ -333,6 +350,19 @@ test.describe('Guided Job Creation Flow', () => {
|
||||
await page.locator('input[type="url"]').fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||||
await page.getByRole('button', { name: /use this url/i }).click();
|
||||
|
||||
// Audio edit question — choose "Use audio as-is"
|
||||
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
|
||||
console.log(' Selected "Use audio as-is"');
|
||||
|
||||
// Step 3: Visibility — choose "Publish & Share"
|
||||
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.getByRole('button', { name: /publish & share/i }).click();
|
||||
console.log(' Selected Publish & Share');
|
||||
|
||||
// Step 4: Customize & Create — click create
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Job created via YouTube URL');
|
||||
@@ -397,7 +427,20 @@ test.describe('Guided Job Creation Flow', () => {
|
||||
await fileInput.setInputFiles(UPLOAD_FIXTURE_PATH);
|
||||
|
||||
// Click upload submit button
|
||||
await page.getByRole('button', { name: /upload.*create/i }).click();
|
||||
await page.getByRole('button', { name: /use this file/i }).click();
|
||||
|
||||
// Audio edit question — choose "Use audio as-is"
|
||||
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
|
||||
console.log(' Selected "Use audio as-is"');
|
||||
|
||||
// Step 3: Visibility — choose "Publish & Share"
|
||||
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.getByRole('button', { name: /publish & share/i }).click();
|
||||
console.log(' Selected Publish & Share');
|
||||
|
||||
// Step 4: Customize & Create — click create
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
@@ -429,7 +429,20 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
|
||||
console.log(' Audio source selected');
|
||||
|
||||
// --- Guided Step 3: Customize & Create ---
|
||||
// --- Audio edit question (appears after selecting audio) ---
|
||||
console.log(' Answering audio edit question...');
|
||||
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
|
||||
console.log(' Selected "Use audio as-is"');
|
||||
|
||||
// --- Guided Step 3: Visibility ---
|
||||
console.log(' Waiting for Visibility step...');
|
||||
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
// Click "Keep Private" — test jobs should never consume public NOMAD brand codes
|
||||
await page.getByRole('button', { name: /keep private/i }).click();
|
||||
console.log(' Selected "Keep Private" (NOMADNP prefix, no GDrive/YouTube)');
|
||||
|
||||
// --- Guided Step 4: Customize & Create ---
|
||||
console.log(' Waiting for Customize & Create step...');
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
@@ -437,11 +450,6 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
await page.waitForTimeout(3000);
|
||||
await page.screenshot({ path: 'test-results/05b-customize-step.png' });
|
||||
|
||||
// Enable private mode - test jobs should never consume public NOMAD brand codes
|
||||
const privateCheckbox = page.locator('#guided-private');
|
||||
await privateCheckbox.check();
|
||||
console.log(' Enabled private mode (NOMADNP prefix, no GDrive/YouTube)');
|
||||
|
||||
// Accept defaults and create
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
console.log(' Clicked "Create Karaoke Video"');
|
||||
|
||||
@@ -472,7 +472,7 @@ test.describe('Admin Job Detail Page', () => {
|
||||
await expect(page).toHaveURL(/\/admin\/users\/detail\/?\?email=user%40example\.com/);
|
||||
});
|
||||
|
||||
test('YouTube source shows clickable external link', async ({ page }) => {
|
||||
test('YouTube source opens modal with clickable link', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
@@ -485,8 +485,15 @@ test.describe('Admin Job Detail Page', () => {
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// YouTube source should show as an external link
|
||||
const sourceLink = page.locator('a[href*="youtube.com"]').first();
|
||||
// Source should be a clickable button
|
||||
const sourceButton = page.locator('button').filter({ hasText: /youtube\.com/ });
|
||||
await expect(sourceButton).toBeVisible();
|
||||
|
||||
// Click to open modal, which should contain the clickable YouTube link
|
||||
await sourceButton.click();
|
||||
const modal = page.getByLabel('Audio Source Details');
|
||||
await expect(modal).toBeVisible();
|
||||
const sourceLink = modal.locator('a[href*="youtube.com"]');
|
||||
await expect(sourceLink).toBeVisible();
|
||||
await expect(sourceLink).toHaveAttribute('target', '_blank');
|
||||
});
|
||||
@@ -714,4 +721,103 @@ test.describe('Admin Job Detail Page', () => {
|
||||
// Button should have disabled styling (opacity-50 class applied by shadcn)
|
||||
await expect(delOutputsButton).toHaveClass(/disabled:opacity-50/);
|
||||
});
|
||||
|
||||
test('shows source details modal for audio search job', async ({ page }) => {
|
||||
const audioSearchJob = {
|
||||
...mockJob,
|
||||
url: undefined,
|
||||
audio_source_type: 'audio_search',
|
||||
source_name: 'RED',
|
||||
source_id: '26048',
|
||||
target_file: '04 - Living in a Bubble.flac',
|
||||
filename: '04 - Living in a Bubble.flac',
|
||||
};
|
||||
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: audioSearchJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Source should show as search with provider name
|
||||
const sourceButton = page.locator('button').filter({ hasText: /Living in a Bubble/ });
|
||||
await expect(sourceButton).toBeVisible();
|
||||
|
||||
// Click to open source modal
|
||||
await sourceButton.click();
|
||||
|
||||
// Modal should display source details
|
||||
const modal = page.getByLabel('Audio Source Details');
|
||||
await expect(modal).toBeVisible();
|
||||
await expect(modal.getByText('audio search', { exact: true })).toBeVisible();
|
||||
await expect(modal.getByText('RED', { exact: true })).toBeVisible();
|
||||
await expect(modal.getByText('26048')).toBeVisible();
|
||||
await expect(modal.getByText('04 - Living in a Bubble.flac')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows source details modal for YouTube job', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Source should be clickable
|
||||
const sourceButton = page.locator('button').filter({ hasText: /youtube\.com/ });
|
||||
await expect(sourceButton).toBeVisible();
|
||||
|
||||
// Click to open source modal
|
||||
await sourceButton.click();
|
||||
|
||||
// Modal should show YouTube URL
|
||||
const modal = page.getByLabel('Audio Source Details');
|
||||
await expect(modal).toBeVisible();
|
||||
await expect(modal.getByText('https://youtube.com/watch?v=abc123')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows source details modal for file upload job', async ({ page }) => {
|
||||
const uploadJob = {
|
||||
...mockJob,
|
||||
url: undefined,
|
||||
audio_source_type: 'file_upload',
|
||||
filename: 'my-song.mp3',
|
||||
};
|
||||
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: uploadJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Source should show filename
|
||||
const sourceButton = page.locator('button').filter({ hasText: /my-song\.mp3/ });
|
||||
await expect(sourceButton).toBeVisible();
|
||||
|
||||
// Click to open source modal
|
||||
await sourceButton.click();
|
||||
|
||||
// Modal should show upload details
|
||||
const modal = page.getByLabel('Audio Source Details');
|
||||
await expect(modal).toBeVisible();
|
||||
await expect(modal.getByText('file upload')).toBeVisible();
|
||||
await expect(modal.getByText('my-song.mp3')).toBeVisible();
|
||||
});
|
||||
});
|
||||
+125
-1
@@ -80,6 +80,12 @@ export interface Job {
|
||||
// Audio search fields
|
||||
audio_search_artist?: string;
|
||||
audio_search_title?: string;
|
||||
// Audio source tracking
|
||||
audio_source_type?: string;
|
||||
source_name?: string;
|
||||
source_id?: string;
|
||||
target_file?: string;
|
||||
download_url?: string;
|
||||
// Theme and branding
|
||||
theme_id?: string;
|
||||
brand_prefix?: string;
|
||||
@@ -2117,6 +2123,34 @@ export const adminApi = {
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async syncDisposableDomains(): Promise<SuccessResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/rate-limits/blocklists/sync`,
|
||||
{ method: 'POST', headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async addAllowlistedDomain(domain: string): Promise<SuccessResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/rate-limits/blocklists/allowlisted-domains`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({ domain }),
|
||||
}
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async removeAllowlistedDomain(domain: string): Promise<SuccessResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/rate-limits/blocklists/allowlisted-domains/${encodeURIComponent(domain)}`,
|
||||
{ method: 'DELETE', headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
// YouTube Upload Queue
|
||||
|
||||
async getYouTubeQueue(): Promise<YouTubeQueueListResponse> {
|
||||
@@ -2271,6 +2305,30 @@ export const adminApi = {
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async listAudioEditReviews(params?: {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
exclude_test?: boolean;
|
||||
search?: string;
|
||||
}): Promise<AudioEditReviewListResponse> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.limit) searchParams.set('limit', String(params.limit));
|
||||
if (params?.offset) searchParams.set('offset', String(params.offset));
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
if (params?.search) searchParams.set('search', params.search);
|
||||
const url = `${API_BASE_URL}/api/admin/audio-edit-reviews${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, { headers: getAuthHeaders() });
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getAudioEditReview(jobId: string): Promise<AudioEditReviewDetail> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/audio-edit-reviews/${encodeURIComponent(jobId)}`,
|
||||
{ headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
};
|
||||
|
||||
export interface EditReviewSummary {
|
||||
@@ -2334,6 +2392,68 @@ export interface EditReviewDetail {
|
||||
audio_url: string | null;
|
||||
}
|
||||
|
||||
// Types for admin audio edit reviews
|
||||
export interface AudioEditReviewSummary {
|
||||
job_id: string;
|
||||
artist: string;
|
||||
title: string;
|
||||
user_email: string;
|
||||
status: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
session_count: number;
|
||||
total_edits: number;
|
||||
original_duration?: number;
|
||||
current_duration?: number;
|
||||
latest_trigger?: string;
|
||||
}
|
||||
|
||||
export interface AudioEditReviewListResponse {
|
||||
reviews: AudioEditReviewSummary[];
|
||||
total: number;
|
||||
has_more: boolean;
|
||||
}
|
||||
|
||||
export interface AudioEditReviewDetail {
|
||||
job: {
|
||||
job_id: string;
|
||||
artist: string;
|
||||
title: string;
|
||||
user_email: string;
|
||||
status: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
};
|
||||
sessions: Array<{
|
||||
session_id: string;
|
||||
job_id: string;
|
||||
user_email: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
edit_count: number;
|
||||
trigger: string;
|
||||
audio_duration_seconds?: number;
|
||||
original_duration_seconds?: number;
|
||||
artist?: string;
|
||||
title?: string;
|
||||
summary: AudioEditSessionSummary;
|
||||
edit_data_gcs_path: string;
|
||||
data_hash: string;
|
||||
}>;
|
||||
edit_stack: Array<{
|
||||
edit_id: string;
|
||||
operation: string;
|
||||
params: Record<string, unknown>;
|
||||
gcs_path: string;
|
||||
duration_before?: number;
|
||||
duration_after?: number;
|
||||
timestamp: string;
|
||||
}>;
|
||||
edit_log: unknown;
|
||||
original_audio_url: string | null;
|
||||
current_audio_url: string | null;
|
||||
}
|
||||
|
||||
// Types for admin completion message API
|
||||
export interface CompletionMessageResponse {
|
||||
job_id: string;
|
||||
@@ -2817,9 +2937,13 @@ export interface YouTubeQueueListResponse {
|
||||
}
|
||||
|
||||
export interface BlocklistsResponse {
|
||||
disposable_domains: string[];
|
||||
external_domains: string[];
|
||||
manual_domains: string[];
|
||||
allowlisted_domains: string[];
|
||||
blocked_emails: string[];
|
||||
blocked_ips: string[];
|
||||
last_sync_at?: string;
|
||||
last_sync_count?: number;
|
||||
updated_at?: string;
|
||||
updated_by?: string;
|
||||
}
|
||||
|
||||
@@ -303,6 +303,54 @@ youtube_queue_scheduler = cloudscheduler.Job(
|
||||
),
|
||||
)
|
||||
|
||||
# ==================== Stale Review Processor ====================
|
||||
|
||||
# Cloud Scheduler job to send review reminders and expire stale review jobs
|
||||
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",
|
||||
),
|
||||
)
|
||||
|
||||
# ==================== Disposable Domain Blocklist Sync ====================
|
||||
|
||||
# Cloud Scheduler job to sync disposable email domain blocklist daily
|
||||
disposable_domains_sync_scheduler = cloudscheduler.Job(
|
||||
"disposable-domains-sync-scheduler",
|
||||
name="disposable-domains-sync-daily",
|
||||
description="Daily sync of disposable email domain blocklist from GitHub",
|
||||
region=REGION,
|
||||
schedule="0 3 * * *", # 3:00 AM UTC daily
|
||||
time_zone="UTC",
|
||||
http_target=cloudscheduler.JobHttpTargetArgs(
|
||||
uri="https://api.nomadkaraoke.com/api/internal/sync-disposable-domains",
|
||||
http_method="POST",
|
||||
oidc_token=cloudscheduler.JobHttpTargetOidcTokenArgs(
|
||||
service_account_email=backend_service_account.email,
|
||||
),
|
||||
),
|
||||
retry_config=cloudscheduler.JobRetryConfigArgs(
|
||||
retry_count=2,
|
||||
min_backoff_duration="60s",
|
||||
max_backoff_duration="300s",
|
||||
),
|
||||
)
|
||||
|
||||
# ==================== Stuck Job Recovery ====================
|
||||
|
||||
# Cloud Scheduler job to detect and recover stuck audio downloads
|
||||
@@ -350,14 +398,28 @@ github_build_runner = github_runners.create_build_runner(
|
||||
github_runner_sa, all_secrets["github-runner-pat"], github_runners_nat
|
||||
)
|
||||
|
||||
# Create GPU runners (spot, for audio-separator integration tests)
|
||||
github_gpu_runner_vms = github_runners.create_gpu_runners(
|
||||
github_runner_sa, all_secrets["github-runner-pat"], github_runners_nat
|
||||
)
|
||||
|
||||
# All runner VM names for the runner manager to track
|
||||
all_runner_names = [vm.name for vm in github_runner_vms] + [github_build_runner.name]
|
||||
all_runner_names = (
|
||||
[vm.name for vm in github_runner_vms]
|
||||
+ [github_build_runner.name]
|
||||
+ [vm.name for vm in github_gpu_runner_vms]
|
||||
)
|
||||
|
||||
# GPU runner names (only started when job requests "gpu" label)
|
||||
gpu_runner_names = [vm.name for vm in github_gpu_runner_vms]
|
||||
|
||||
# Create runner manager (auto-start/stop VMs based on CI activity)
|
||||
runner_manager_resources = runner_manager.create_runner_manager_resources(
|
||||
all_secrets["github-webhook-secret"],
|
||||
all_secrets["github-runner-pat"],
|
||||
all_runner_names,
|
||||
gpu_runner_names=gpu_runner_names,
|
||||
runner_service_account=github_runner_sa,
|
||||
)
|
||||
|
||||
|
||||
@@ -434,6 +496,7 @@ pulumi.export("gdrive_validator_function_url", gdrive_validator_function.url)
|
||||
pulumi.export("gdrive_validator_function_name", gdrive_validator_function.name)
|
||||
pulumi.export("gdrive_validator_scheduler_name", gdrive_validator_scheduler.name)
|
||||
pulumi.export("recover_stuck_downloads_scheduler_name", recover_stuck_downloads_scheduler.name)
|
||||
pulumi.export("disposable_domains_sync_scheduler_name", disposable_domains_sync_scheduler.name)
|
||||
pulumi.export("gdrive_validator_service_account", gdrive_validator_sa.email)
|
||||
|
||||
# VPC networking
|
||||
@@ -449,6 +512,7 @@ pulumi.export("encoding_worker_vm_name", encoding_worker_instance.name)
|
||||
# GitHub runners
|
||||
pulumi.export("github_runner_vm_names", [vm.name for vm in github_runner_vms])
|
||||
pulumi.export("github_build_runner_name", github_build_runner.name)
|
||||
pulumi.export("github_gpu_runner_names", [vm.name for vm in github_gpu_runner_vms])
|
||||
pulumi.export("github_runner_service_account", github_runner_sa.email)
|
||||
pulumi.export("github_runners_nat", github_runners_nat.name)
|
||||
|
||||
|
||||
@@ -23,8 +23,10 @@ from config import (
|
||||
MachineTypes,
|
||||
DiskSizes,
|
||||
NUM_GITHUB_RUNNERS,
|
||||
NUM_GPU_RUNNERS,
|
||||
GENERAL_RUNNER_LABELS,
|
||||
BUILD_RUNNER_LABELS,
|
||||
GPU_RUNNER_LABELS,
|
||||
)
|
||||
from .startup_scripts import read_script
|
||||
|
||||
@@ -228,6 +230,93 @@ def create_build_runner(
|
||||
)
|
||||
|
||||
|
||||
def create_gpu_runners(
|
||||
service_account: serviceaccount.Account,
|
||||
runner_pat_secret: secretmanager.Secret,
|
||||
nat: compute.RouterNat,
|
||||
) -> list[compute.Instance]:
|
||||
"""
|
||||
Create GPU-enabled runners for python-audio-separator integration tests.
|
||||
|
||||
Creates NUM_GPU_RUNNERS n1-standard-4 VMs with 1× NVIDIA T4 GPU each,
|
||||
using spot scheduling for cost optimization (~$0.19/hr vs $0.61/hr on-demand).
|
||||
The runner_manager Cloud Function starts/stops VMs based on CI demand.
|
||||
|
||||
GPU VMs require on_host_maintenance="TERMINATE" (cannot live-migrate).
|
||||
|
||||
Args:
|
||||
service_account: The GitHub runner service account.
|
||||
runner_pat_secret: The Secret Manager secret containing the GitHub PAT.
|
||||
nat: Cloud NAT for outbound internet access.
|
||||
|
||||
Returns:
|
||||
list[compute.Instance]: List of GPU runner VM instances.
|
||||
"""
|
||||
startup_script = read_script("github_runner_gpu.sh")
|
||||
|
||||
gpu_vms = []
|
||||
for i in range(1, NUM_GPU_RUNNERS + 1):
|
||||
instance_name = f"github-gpu-runner-{i}"
|
||||
|
||||
vm = compute.Instance(
|
||||
instance_name,
|
||||
name=instance_name,
|
||||
machine_type=MachineTypes.GITHUB_GPU_RUNNER,
|
||||
zone=ZONE,
|
||||
boot_disk=compute.InstanceBootDiskArgs(
|
||||
initialize_params=compute.InstanceBootDiskInitializeParamsArgs(
|
||||
image="debian-cloud/debian-12",
|
||||
size=DiskSizes.GITHUB_RUNNER,
|
||||
type="pd-ssd",
|
||||
),
|
||||
auto_delete=True,
|
||||
),
|
||||
# 1× NVIDIA T4 GPU for ML model inference
|
||||
guest_accelerators=[
|
||||
compute.InstanceGuestAcceleratorArgs(
|
||||
type="nvidia-tesla-t4",
|
||||
count=1,
|
||||
)
|
||||
],
|
||||
network_interfaces=[
|
||||
compute.InstanceNetworkInterfaceArgs(
|
||||
network="default",
|
||||
)
|
||||
],
|
||||
service_account=compute.InstanceServiceAccountArgs(
|
||||
email=service_account.email,
|
||||
scopes=["https://www.googleapis.com/auth/cloud-platform"],
|
||||
),
|
||||
# On-demand scheduling — GPU VMs MUST use TERMINATE (cannot live-migrate)
|
||||
scheduling=compute.InstanceSchedulingArgs(
|
||||
preemptible=False,
|
||||
automatic_restart=True,
|
||||
on_host_maintenance="TERMINATE", # Required for GPU VMs
|
||||
),
|
||||
metadata={
|
||||
"github-runner-pat-secret": "github-runner-pat",
|
||||
"github-org": "nomadkaraoke",
|
||||
"runner-labels": GPU_RUNNER_LABELS,
|
||||
},
|
||||
metadata_startup_script=startup_script,
|
||||
labels={
|
||||
"purpose": "github-gpu-runner",
|
||||
"managed-by": "pulumi",
|
||||
},
|
||||
tags=["github-runner"],
|
||||
allow_stopping_for_update=True,
|
||||
deletion_protection=False,
|
||||
opts=pulumi.ResourceOptions(
|
||||
depends_on=[runner_pat_secret, nat],
|
||||
delete_before_replace=True,
|
||||
),
|
||||
)
|
||||
|
||||
gpu_vms.append(vm)
|
||||
|
||||
return gpu_vms
|
||||
|
||||
|
||||
def create_instance_group_for_restart(
|
||||
instances: list[compute.Instance],
|
||||
) -> compute.InstanceGroup:
|
||||
|
||||
@@ -7,6 +7,16 @@
|
||||
exec > >(tee /var/log/github-runner-startup.log) 2>&1
|
||||
echo "Starting GitHub Actions runner setup at $(date)"
|
||||
|
||||
# ==================== Stop existing runner service FIRST ====================
|
||||
# CRITICAL: The runner service from a previous boot auto-starts via systemd,
|
||||
# which means it can accept CI jobs before Docker/Python/Java are ready.
|
||||
# Stop it immediately to prevent flaky "docker: command not found" errors.
|
||||
RUNNER_DIR="/home/runner/actions-runner"
|
||||
if [ -f "$RUNNER_DIR/svc.sh" ]; then
|
||||
echo "Stopping existing runner service to prevent premature job acceptance..."
|
||||
(cd "$RUNNER_DIR" && ./svc.sh stop 2>/dev/null) || true
|
||||
fi
|
||||
|
||||
# ==================== Network ====================
|
||||
# Force apt to use IPv4 only — Cloud NAT doesn't support IPv6
|
||||
echo 'Acquire::ForceIPv4 "true";' > /etc/apt/apt.conf.d/99force-ipv4
|
||||
@@ -334,4 +344,90 @@ docker pull fsouza/fake-gcs-server:latest || true
|
||||
|
||||
echo "Docker images pre-warmed"
|
||||
|
||||
# ==================== Audio separator model pre-download ====================
|
||||
# Pre-download ML models used by python-audio-separator integration tests.
|
||||
# These models total ~14GB and would otherwise be downloaded on every CI run.
|
||||
# Stored in /opt/audio-separator-models/ which persists across job runs.
|
||||
echo "Pre-downloading audio separator integration test models..."
|
||||
|
||||
MODEL_DIR="/opt/audio-separator-models"
|
||||
mkdir -p "$MODEL_DIR"
|
||||
chown runner:runner "$MODEL_DIR"
|
||||
|
||||
BASE_URL="https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models"
|
||||
CONFIG_URL="https://raw.githubusercontent.com/TRvlvr/application_data/main/mdx_model_data/mdx_c_configs"
|
||||
META_URL="https://raw.githubusercontent.com/TRvlvr/application_data/main"
|
||||
DEMUCS_URL="https://dl.fbaipublicfiles.com/demucs/hybrid_transformer"
|
||||
FALLBACK_URL="https://github.com/nomadkaraoke/python-audio-separator/releases/download/model-configs"
|
||||
|
||||
download_model() {
|
||||
local url="$1"
|
||||
local dest="$2"
|
||||
local fallback_url="${3:-}"
|
||||
if [ -f "$dest" ] && [ -s "$dest" ]; then
|
||||
return
|
||||
fi
|
||||
echo " Downloading: $(basename $dest)"
|
||||
if curl -fSL --retry 3 --connect-timeout 30 -o "$dest" "$url" 2>/dev/null; then
|
||||
return
|
||||
fi
|
||||
if [ -n "$fallback_url" ]; then
|
||||
echo " Primary URL failed, trying fallback..."
|
||||
curl -fSL --retry 3 --connect-timeout 30 -o "$dest" "$fallback_url" || true
|
||||
fi
|
||||
}
|
||||
|
||||
# Metadata files
|
||||
download_model "$META_URL/filelists/download_checks.json" "$MODEL_DIR/download_checks.json"
|
||||
download_model "$META_URL/vr_model_data/model_data_new.json" "$MODEL_DIR/vr_model_data.json"
|
||||
download_model "$META_URL/mdx_model_data/model_data_new.json" "$MODEL_DIR/mdx_model_data.json"
|
||||
|
||||
# === Core integration test models (8 models) ===
|
||||
download_model "$BASE_URL/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt" "$MODEL_DIR/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956_config.yaml" "$MODEL_DIR/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956_config.yaml"
|
||||
download_model "$BASE_URL/kuielab_b_vocals.onnx" "$MODEL_DIR/kuielab_b_vocals.onnx"
|
||||
download_model "$BASE_URL/MGM_MAIN_v4.pth" "$MODEL_DIR/MGM_MAIN_v4.pth"
|
||||
download_model "$BASE_URL/UVR-MDX-NET-Inst_HQ_4.onnx" "$MODEL_DIR/UVR-MDX-NET-Inst_HQ_4.onnx"
|
||||
download_model "$BASE_URL/2_HP-UVR.pth" "$MODEL_DIR/2_HP-UVR.pth"
|
||||
download_model "$BASE_URL/htdemucs_6s.yaml" "$MODEL_DIR/htdemucs_6s.yaml"
|
||||
download_model "$DEMUCS_URL/5c90dfd2-34c22ccb.th" "$MODEL_DIR/5c90dfd2-34c22ccb.th"
|
||||
download_model "$BASE_URL/model_bs_roformer_ep_937_sdr_10.5309.ckpt" "$MODEL_DIR/model_bs_roformer_ep_937_sdr_10.5309.ckpt"
|
||||
download_model "$CONFIG_URL/model_bs_roformer_ep_937_sdr_10.5309.yaml" "$MODEL_DIR/model_bs_roformer_ep_937_sdr_10.5309.yaml"
|
||||
download_model "$BASE_URL/model_bs_roformer_ep_317_sdr_12.9755.ckpt" "$MODEL_DIR/model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
download_model "$CONFIG_URL/model_bs_roformer_ep_317_sdr_12.9755.yaml" "$MODEL_DIR/model_bs_roformer_ep_317_sdr_12.9755.yaml"
|
||||
|
||||
# === Ensemble preset models (15 models, ~12GB) ===
|
||||
# Model weights — hosted on nomadkaraoke releases (not available on TRvlvr)
|
||||
download_model "$FALLBACK_URL/bs_roformer_instrumental_resurrection_unwa.ckpt" "$MODEL_DIR/bs_roformer_instrumental_resurrection_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/bs_roformer_vocals_resurrection_unwa.ckpt" "$MODEL_DIR/bs_roformer_vocals_resurrection_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/bs_roformer_vocals_revive_v2_unwa.ckpt" "$MODEL_DIR/bs_roformer_vocals_revive_v2_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/bs_roformer_vocals_revive_v3e_unwa.ckpt" "$MODEL_DIR/bs_roformer_vocals_revive_v3e_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_instrumental_becruily.ckpt" "$MODEL_DIR/mel_band_roformer_instrumental_becruily.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_instrumental_fv7z_gabox.ckpt" "$MODEL_DIR/mel_band_roformer_instrumental_fv7z_gabox.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_instrumental_instv8_gabox.ckpt" "$MODEL_DIR/mel_band_roformer_instrumental_instv8_gabox.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_karaoke_becruily.ckpt" "$MODEL_DIR/mel_band_roformer_karaoke_becruily.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_karaoke_gabox_v2.ckpt" "$MODEL_DIR/mel_band_roformer_karaoke_gabox_v2.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_kim_ft2_bleedless_unwa.ckpt" "$MODEL_DIR/mel_band_roformer_kim_ft2_bleedless_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_vocals_becruily.ckpt" "$MODEL_DIR/mel_band_roformer_vocals_becruily.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_vocals_fv4_gabox.ckpt" "$MODEL_DIR/mel_band_roformer_vocals_fv4_gabox.ckpt"
|
||||
download_model "$FALLBACK_URL/melband_roformer_big_beta6x.ckpt" "$MODEL_DIR/melband_roformer_big_beta6x.ckpt"
|
||||
download_model "$FALLBACK_URL/melband_roformer_inst_v1e_plus.ckpt" "$MODEL_DIR/melband_roformer_inst_v1e_plus.ckpt"
|
||||
download_model "$FALLBACK_URL/UVR-MDX-NET-Inst_HQ_5.onnx" "$MODEL_DIR/UVR-MDX-NET-Inst_HQ_5.onnx"
|
||||
# YAML configs for ensemble models
|
||||
download_model "$FALLBACK_URL/config_bs_roformer_instrumental_resurrection_unwa.yaml" "$MODEL_DIR/config_bs_roformer_instrumental_resurrection_unwa.yaml"
|
||||
download_model "$FALLBACK_URL/config_bs_roformer_vocals_resurrection_unwa.yaml" "$MODEL_DIR/config_bs_roformer_vocals_resurrection_unwa.yaml"
|
||||
download_model "$FALLBACK_URL/config_bs_roformer_vocals_revive_unwa.yaml" "$MODEL_DIR/config_bs_roformer_vocals_revive_unwa.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_instrumental_becruily.yaml" "$MODEL_DIR/config_mel_band_roformer_instrumental_becruily.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_instrumental_gabox.yaml" "$MODEL_DIR/config_mel_band_roformer_instrumental_gabox.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_karaoke_becruily.yaml" "$MODEL_DIR/config_mel_band_roformer_karaoke_becruily.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_karaoke_gabox.yaml" "$MODEL_DIR/config_mel_band_roformer_karaoke_gabox.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_kim_ft_unwa.yaml" "$MODEL_DIR/config_mel_band_roformer_kim_ft_unwa.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_vocals_becruily.yaml" "$MODEL_DIR/config_mel_band_roformer_vocals_becruily.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_vocals_gabox.yaml" "$MODEL_DIR/config_mel_band_roformer_vocals_gabox.yaml"
|
||||
download_model "$FALLBACK_URL/config_melbandroformer_big_beta6x.yaml" "$MODEL_DIR/config_melbandroformer_big_beta6x.yaml"
|
||||
download_model "$FALLBACK_URL/config_melbandroformer_inst.yaml" "$MODEL_DIR/config_melbandroformer_inst.yaml"
|
||||
|
||||
chown -R runner:runner "$MODEL_DIR"
|
||||
echo "Audio separator models pre-download complete ($(du -sh $MODEL_DIR | cut -f1))"
|
||||
|
||||
echo "Setup complete!"
|
||||
@@ -0,0 +1,349 @@
|
||||
#!/bin/bash
|
||||
# GitHub Actions GPU Runner startup script
|
||||
# Designed to be IDEMPOTENT - safe to re-run on spot VM preemption/restart.
|
||||
# This is a GPU-specific variant of github_runner.sh:
|
||||
# - Adds NVIDIA driver + CUDA toolkit installation
|
||||
# - Skips Docker, Java, Node.js (not needed for audio-separator CI)
|
||||
# - Includes libsamplerate for audio processing
|
||||
|
||||
# Log to a file for debugging
|
||||
exec > >(tee /var/log/github-runner-startup.log) 2>&1
|
||||
echo "Starting GitHub Actions GPU runner setup at $(date)"
|
||||
|
||||
# ==================== Environment ====================
|
||||
# Prevent interactive prompts during package installation (e.g., keyboard-configuration)
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# ==================== Network ====================
|
||||
# Force apt to use IPv4 only — Cloud NAT doesn't support IPv6
|
||||
echo 'Acquire::ForceIPv4 "true";' > /etc/apt/apt.conf.d/99force-ipv4
|
||||
|
||||
# ==================== Helper ====================
|
||||
install_gpg_key() {
|
||||
local url="$1"
|
||||
local dest="$2"
|
||||
if [ -f "$dest" ]; then
|
||||
echo "GPG key already exists: $dest"
|
||||
return 0
|
||||
fi
|
||||
curl -fsSL "$url" | gpg --batch --dearmor -o "$dest"
|
||||
}
|
||||
|
||||
# ==================== System packages ====================
|
||||
apt-get update
|
||||
apt-get install -y \
|
||||
curl \
|
||||
git \
|
||||
jq \
|
||||
unzip \
|
||||
build-essential \
|
||||
libssl-dev \
|
||||
libffi-dev \
|
||||
software-properties-common \
|
||||
apt-transport-https \
|
||||
ca-certificates \
|
||||
gnupg \
|
||||
lsb-release
|
||||
|
||||
# ==================== NVIDIA drivers ====================
|
||||
if ! command -v nvidia-smi &>/dev/null; then
|
||||
echo "Installing NVIDIA drivers..."
|
||||
# Install kernel headers (required for driver build)
|
||||
apt-get install -y linux-headers-$(uname -r)
|
||||
|
||||
# Add NVIDIA CUDA repository for Debian 12
|
||||
install_gpg_key \
|
||||
"https://developer.download.nvidia.com/compute/cuda/repos/debian12/x86_64/3bf863cc.pub" \
|
||||
"/usr/share/keyrings/cuda-archive-keyring.gpg"
|
||||
echo "deb [signed-by=/usr/share/keyrings/cuda-archive-keyring.gpg] https://developer.download.nvidia.com/compute/cuda/repos/debian12/x86_64/ /" > /etc/apt/sources.list.d/cuda.list
|
||||
apt-get update
|
||||
|
||||
# Install NVIDIA driver + CUDA toolkit
|
||||
# PyTorch bundles its own CUDA runtime, but we need the driver at minimum.
|
||||
# Installing cuda-toolkit gives us nvidia-smi and full CUDA support.
|
||||
apt-get install -y cuda-drivers cuda-toolkit-12-4
|
||||
else
|
||||
echo "NVIDIA drivers already installed, skipping"
|
||||
fi
|
||||
|
||||
# Verify GPU is accessible (retry up to 30 times with 10s delay — driver may need time after install)
|
||||
echo "Verifying GPU..."
|
||||
for attempt in $(seq 1 30); do
|
||||
if nvidia-smi; then
|
||||
echo "GPU verified successfully on attempt $attempt"
|
||||
break
|
||||
fi
|
||||
if [ "$attempt" -eq 30 ]; then
|
||||
echo "ERROR: nvidia-smi failed after 30 attempts — GPU not available"
|
||||
exit 1
|
||||
fi
|
||||
echo "nvidia-smi attempt $attempt failed, retrying in 10s..."
|
||||
sleep 10
|
||||
done
|
||||
|
||||
# ==================== FFmpeg + audio libraries ====================
|
||||
if ! command -v ffmpeg &>/dev/null; then
|
||||
echo "Installing FFmpeg and audio libraries..."
|
||||
apt-get install -y ffmpeg libsamplerate0 libsamplerate-dev
|
||||
else
|
||||
echo "FFmpeg already installed, skipping"
|
||||
fi
|
||||
|
||||
# ==================== Python 3.13 from source ====================
|
||||
# Compile Python 3.13 directly (pyenv is unreliable on Debian 12 with CUDA).
|
||||
# setup-python@v5 doesn't have prebuilt Debian 12 binaries, so we must
|
||||
# provide Python in the tool cache for it to find.
|
||||
PYTHON_PREFIX="/opt/python-3.13"
|
||||
if [ ! -f "$PYTHON_PREFIX/bin/python3.13" ]; then
|
||||
echo "Building Python 3.13 from source..."
|
||||
|
||||
apt-get install -y make build-essential libssl-dev zlib1g-dev \
|
||||
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
|
||||
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
|
||||
|
||||
cd /tmp
|
||||
curl -sSL https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz -o Python-3.13.0.tgz
|
||||
tar xzf Python-3.13.0.tgz
|
||||
cd Python-3.13.0
|
||||
./configure --prefix="$PYTHON_PREFIX" --enable-optimizations --with-ensurepip=install
|
||||
make -j$(nproc)
|
||||
make install
|
||||
rm -rf /tmp/Python-3.13.0*
|
||||
|
||||
# Create convenience symlinks
|
||||
ln -sf "$PYTHON_PREFIX/bin/python3.13" /usr/local/bin/python3.13
|
||||
ln -sf "$PYTHON_PREFIX/bin/python3" /usr/local/bin/python3
|
||||
ln -sf "$PYTHON_PREFIX/bin/pip3" /usr/local/bin/pip3
|
||||
else
|
||||
echo "Python 3.13 already installed at $PYTHON_PREFIX, skipping"
|
||||
fi
|
||||
|
||||
# ==================== Poetry ====================
|
||||
if ! command -v poetry &>/dev/null; then
|
||||
echo "Installing Poetry..."
|
||||
curl -sSL https://install.python-poetry.org | python3 -
|
||||
ln -sf /root/.local/bin/poetry /usr/local/bin/poetry
|
||||
else
|
||||
echo "Poetry already installed, skipping"
|
||||
fi
|
||||
|
||||
# ==================== Google Cloud SDK ====================
|
||||
if ! command -v gcloud &>/dev/null; then
|
||||
echo "Installing Google Cloud SDK..."
|
||||
install_gpg_key \
|
||||
"https://packages.cloud.google.com/apt/doc/apt-key.gpg" \
|
||||
"/usr/share/keyrings/cloud.google.gpg"
|
||||
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" > /etc/apt/sources.list.d/google-cloud-sdk.list
|
||||
apt-get update
|
||||
apt-get install -y google-cloud-cli
|
||||
else
|
||||
echo "Google Cloud SDK already installed, skipping"
|
||||
fi
|
||||
|
||||
# ==================== Create runner user ====================
|
||||
echo "Ensuring runner user exists..."
|
||||
useradd -m -s /bin/bash runner 2>/dev/null || true
|
||||
|
||||
# ==================== GitHub Actions Runner ====================
|
||||
# This section ALWAYS runs — it handles version upgrades and re-registration
|
||||
echo "Setting up GitHub Actions Runner..."
|
||||
RUNNER_VERSION="2.332.0"
|
||||
RUNNER_DIR="/home/runner/actions-runner"
|
||||
|
||||
mkdir -p $RUNNER_DIR
|
||||
|
||||
# Stop existing service if running (for upgrades/re-registration)
|
||||
if [ -f "$RUNNER_DIR/svc.sh" ]; then
|
||||
echo "Stopping existing runner service..."
|
||||
cd $RUNNER_DIR
|
||||
./svc.sh stop 2>/dev/null || true
|
||||
./svc.sh uninstall 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Check if runner needs download/upgrade
|
||||
CURRENT_VERSION=""
|
||||
if [ -f "$RUNNER_DIR/bin/Runner.Listener" ]; then
|
||||
CURRENT_VERSION=$("$RUNNER_DIR/bin/Runner.Listener" --version 2>/dev/null || echo "unknown")
|
||||
fi
|
||||
|
||||
if [ "$CURRENT_VERSION" != "$RUNNER_VERSION" ]; then
|
||||
echo "Upgrading runner from ${CURRENT_VERSION:-none} to ${RUNNER_VERSION}..."
|
||||
cd $RUNNER_DIR
|
||||
curl -sO -L \
|
||||
https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz
|
||||
tar xzf actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz
|
||||
rm -f actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz
|
||||
else
|
||||
echo "Runner already at version ${RUNNER_VERSION}"
|
||||
fi
|
||||
|
||||
chown -R runner:runner $RUNNER_DIR
|
||||
|
||||
# Get GitHub PAT from Secret Manager
|
||||
echo "Fetching GitHub PAT from Secret Manager..."
|
||||
GITHUB_PAT=$(gcloud secrets versions access latest --secret=github-runner-pat)
|
||||
|
||||
if [ -z "$GITHUB_PAT" ]; then
|
||||
echo "ERROR: GitHub PAT not found in Secret Manager"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get runner registration token using PAT (organization-level)
|
||||
echo "Getting runner registration token..."
|
||||
REGISTRATION_TOKEN=$(curl -s -X POST \
|
||||
-H "Authorization: token $GITHUB_PAT" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
https://api.github.com/orgs/nomadkaraoke/actions/runners/registration-token | jq -r .token)
|
||||
|
||||
if [ -z "$REGISTRATION_TOKEN" ] || [ "$REGISTRATION_TOKEN" = "null" ]; then
|
||||
echo "ERROR: Failed to get registration token"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Read runner labels from instance metadata (allows per-VM customization)
|
||||
RUNNER_LABELS=$(curl -s -H "Metadata-Flavor: Google" \
|
||||
http://metadata.google.internal/computeMetadata/v1/instance/attributes/runner-labels)
|
||||
RUNNER_LABELS=${RUNNER_LABELS:-"self-hosted,linux,x64,gcp,gpu"}
|
||||
|
||||
# Configure runner (non-interactive) - registered at organization level
|
||||
echo "Configuring runner..."
|
||||
cd $RUNNER_DIR
|
||||
sudo -u runner ./config.sh \
|
||||
--url https://github.com/nomadkaraoke \
|
||||
--token "$REGISTRATION_TOKEN" \
|
||||
--name "gcp-gpu-runner-$(hostname)" \
|
||||
--labels "$RUNNER_LABELS" \
|
||||
--work "_work" \
|
||||
--unattended \
|
||||
--replace
|
||||
|
||||
# Install runner service (started AFTER all caches are warm — see end of script)
|
||||
echo "Installing runner service..."
|
||||
./svc.sh install runner
|
||||
|
||||
# ==================== Setup Python in tool cache ====================
|
||||
# setup-python action looks for Python in RUNNER_TOOL_CACHE/_tool/Python
|
||||
echo "Setting up Python 3.13 in tool cache for setup-python action..."
|
||||
TOOL_CACHE="/home/runner/actions-runner/_work/_tool"
|
||||
mkdir -p $TOOL_CACHE/Python/3.13.0/x64
|
||||
|
||||
# Copy compiled Python to tool cache (only if build succeeded and not already cached)
|
||||
if [ -f "$PYTHON_PREFIX/bin/python3.13" ] && [ ! -f "$TOOL_CACHE/Python/3.13.0/x64.complete" ]; then
|
||||
cp -r "$PYTHON_PREFIX"/* $TOOL_CACHE/Python/3.13.0/x64/
|
||||
# Ensure python and python3 symlinks exist (setup-python expects them)
|
||||
cd $TOOL_CACHE/Python/3.13.0/x64/bin
|
||||
[ ! -f python ] && ln -s python3.13 python
|
||||
[ ! -f python3 ] && ln -s python3.13 python3
|
||||
touch $TOOL_CACHE/Python/3.13.0/x64.complete
|
||||
echo "Python 3.13 added to tool cache"
|
||||
elif [ -f "$TOOL_CACHE/Python/3.13.0/x64.complete" ]; then
|
||||
echo "Python 3.13 already in tool cache"
|
||||
else
|
||||
echo "ERROR: Python 3.13 build failed — setup-python will not find Python"
|
||||
fi
|
||||
|
||||
# Fix permissions - must own entire _work directory, not just _tool
|
||||
chown -R runner:runner /home/runner/actions-runner/_work
|
||||
|
||||
# ==================== Audio separator model pre-download ====================
|
||||
# Pre-download ML models used by python-audio-separator integration tests.
|
||||
# These models total ~14GB and would otherwise be downloaded on every CI run.
|
||||
# Stored in /opt/audio-separator-models/ which persists across stop/start cycles
|
||||
# (persistent disk, not ephemeral).
|
||||
echo "Pre-downloading audio separator integration test models..."
|
||||
|
||||
MODEL_DIR="/opt/audio-separator-models"
|
||||
mkdir -p "$MODEL_DIR"
|
||||
chown runner:runner "$MODEL_DIR"
|
||||
|
||||
BASE_URL="https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models"
|
||||
CONFIG_URL="https://raw.githubusercontent.com/TRvlvr/application_data/main/mdx_model_data/mdx_c_configs"
|
||||
META_URL="https://raw.githubusercontent.com/TRvlvr/application_data/main"
|
||||
DEMUCS_URL="https://dl.fbaipublicfiles.com/demucs/hybrid_transformer"
|
||||
FALLBACK_URL="https://github.com/nomadkaraoke/python-audio-separator/releases/download/model-configs"
|
||||
|
||||
download_model() {
|
||||
local url="$1"
|
||||
local dest="$2"
|
||||
local fallback_url="${3:-}"
|
||||
if [ -f "$dest" ] && [ -s "$dest" ]; then
|
||||
return
|
||||
fi
|
||||
echo " Downloading: $(basename $dest)"
|
||||
if curl -fSL --retry 3 --connect-timeout 30 -o "$dest" "$url" 2>/dev/null; then
|
||||
return
|
||||
fi
|
||||
if [ -n "$fallback_url" ]; then
|
||||
echo " Primary URL failed, trying fallback..."
|
||||
curl -fSL --retry 3 --connect-timeout 30 -o "$dest" "$fallback_url" || true
|
||||
fi
|
||||
}
|
||||
|
||||
# Metadata files
|
||||
download_model "$META_URL/filelists/download_checks.json" "$MODEL_DIR/download_checks.json"
|
||||
download_model "$META_URL/vr_model_data/model_data_new.json" "$MODEL_DIR/vr_model_data.json"
|
||||
download_model "$META_URL/mdx_model_data/model_data_new.json" "$MODEL_DIR/mdx_model_data.json"
|
||||
|
||||
# === Core integration test models (8 models) ===
|
||||
download_model "$BASE_URL/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt" "$MODEL_DIR/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956_config.yaml" "$MODEL_DIR/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956_config.yaml"
|
||||
download_model "$BASE_URL/kuielab_b_vocals.onnx" "$MODEL_DIR/kuielab_b_vocals.onnx"
|
||||
download_model "$BASE_URL/MGM_MAIN_v4.pth" "$MODEL_DIR/MGM_MAIN_v4.pth"
|
||||
download_model "$BASE_URL/UVR-MDX-NET-Inst_HQ_4.onnx" "$MODEL_DIR/UVR-MDX-NET-Inst_HQ_4.onnx"
|
||||
download_model "$BASE_URL/2_HP-UVR.pth" "$MODEL_DIR/2_HP-UVR.pth"
|
||||
download_model "$BASE_URL/htdemucs_6s.yaml" "$MODEL_DIR/htdemucs_6s.yaml"
|
||||
download_model "$DEMUCS_URL/5c90dfd2-34c22ccb.th" "$MODEL_DIR/5c90dfd2-34c22ccb.th"
|
||||
download_model "$BASE_URL/model_bs_roformer_ep_937_sdr_10.5309.ckpt" "$MODEL_DIR/model_bs_roformer_ep_937_sdr_10.5309.ckpt"
|
||||
download_model "$CONFIG_URL/model_bs_roformer_ep_937_sdr_10.5309.yaml" "$MODEL_DIR/model_bs_roformer_ep_937_sdr_10.5309.yaml"
|
||||
download_model "$BASE_URL/model_bs_roformer_ep_317_sdr_12.9755.ckpt" "$MODEL_DIR/model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
download_model "$CONFIG_URL/model_bs_roformer_ep_317_sdr_12.9755.yaml" "$MODEL_DIR/model_bs_roformer_ep_317_sdr_12.9755.yaml"
|
||||
|
||||
# === Ensemble preset models (15 models, ~12GB) ===
|
||||
# Model weights — hosted on nomadkaraoke releases (not available on TRvlvr)
|
||||
download_model "$FALLBACK_URL/bs_roformer_instrumental_resurrection_unwa.ckpt" "$MODEL_DIR/bs_roformer_instrumental_resurrection_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/bs_roformer_vocals_resurrection_unwa.ckpt" "$MODEL_DIR/bs_roformer_vocals_resurrection_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/bs_roformer_vocals_revive_v2_unwa.ckpt" "$MODEL_DIR/bs_roformer_vocals_revive_v2_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/bs_roformer_vocals_revive_v3e_unwa.ckpt" "$MODEL_DIR/bs_roformer_vocals_revive_v3e_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_instrumental_becruily.ckpt" "$MODEL_DIR/mel_band_roformer_instrumental_becruily.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_instrumental_fv7z_gabox.ckpt" "$MODEL_DIR/mel_band_roformer_instrumental_fv7z_gabox.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_instrumental_instv8_gabox.ckpt" "$MODEL_DIR/mel_band_roformer_instrumental_instv8_gabox.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_karaoke_becruily.ckpt" "$MODEL_DIR/mel_band_roformer_karaoke_becruily.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_karaoke_gabox_v2.ckpt" "$MODEL_DIR/mel_band_roformer_karaoke_gabox_v2.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_kim_ft2_bleedless_unwa.ckpt" "$MODEL_DIR/mel_band_roformer_kim_ft2_bleedless_unwa.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_vocals_becruily.ckpt" "$MODEL_DIR/mel_band_roformer_vocals_becruily.ckpt"
|
||||
download_model "$FALLBACK_URL/mel_band_roformer_vocals_fv4_gabox.ckpt" "$MODEL_DIR/mel_band_roformer_vocals_fv4_gabox.ckpt"
|
||||
download_model "$FALLBACK_URL/melband_roformer_big_beta6x.ckpt" "$MODEL_DIR/melband_roformer_big_beta6x.ckpt"
|
||||
download_model "$FALLBACK_URL/melband_roformer_inst_v1e_plus.ckpt" "$MODEL_DIR/melband_roformer_inst_v1e_plus.ckpt"
|
||||
download_model "$FALLBACK_URL/UVR-MDX-NET-Inst_HQ_5.onnx" "$MODEL_DIR/UVR-MDX-NET-Inst_HQ_5.onnx"
|
||||
# YAML configs for ensemble models
|
||||
download_model "$FALLBACK_URL/config_bs_roformer_instrumental_resurrection_unwa.yaml" "$MODEL_DIR/config_bs_roformer_instrumental_resurrection_unwa.yaml"
|
||||
download_model "$FALLBACK_URL/config_bs_roformer_vocals_resurrection_unwa.yaml" "$MODEL_DIR/config_bs_roformer_vocals_resurrection_unwa.yaml"
|
||||
download_model "$FALLBACK_URL/config_bs_roformer_vocals_revive_unwa.yaml" "$MODEL_DIR/config_bs_roformer_vocals_revive_unwa.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_instrumental_becruily.yaml" "$MODEL_DIR/config_mel_band_roformer_instrumental_becruily.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_instrumental_gabox.yaml" "$MODEL_DIR/config_mel_band_roformer_instrumental_gabox.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_karaoke_becruily.yaml" "$MODEL_DIR/config_mel_band_roformer_karaoke_becruily.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_karaoke_gabox.yaml" "$MODEL_DIR/config_mel_band_roformer_karaoke_gabox.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_kim_ft_unwa.yaml" "$MODEL_DIR/config_mel_band_roformer_kim_ft_unwa.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_vocals_becruily.yaml" "$MODEL_DIR/config_mel_band_roformer_vocals_becruily.yaml"
|
||||
download_model "$FALLBACK_URL/config_mel_band_roformer_vocals_gabox.yaml" "$MODEL_DIR/config_mel_band_roformer_vocals_gabox.yaml"
|
||||
download_model "$FALLBACK_URL/config_melbandroformer_big_beta6x.yaml" "$MODEL_DIR/config_melbandroformer_big_beta6x.yaml"
|
||||
download_model "$FALLBACK_URL/config_melbandroformer_inst.yaml" "$MODEL_DIR/config_melbandroformer_inst.yaml"
|
||||
|
||||
# === Multi-stem test models ===
|
||||
download_model "$BASE_URL/17_HP-Wind_Inst-UVR.pth" "$MODEL_DIR/17_HP-Wind_Inst-UVR.pth"
|
||||
download_model "$FALLBACK_URL/MDX23C-DrumSep-aufr33-jarredou.ckpt" "$MODEL_DIR/MDX23C-DrumSep-aufr33-jarredou.ckpt"
|
||||
download_model "$FALLBACK_URL/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt" "$MODEL_DIR/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt"
|
||||
download_model "$FALLBACK_URL/config_dereverb_mel_band_roformer_anvuew.yaml" "$MODEL_DIR/config_dereverb_mel_band_roformer_anvuew.yaml"
|
||||
|
||||
chown -R runner:runner "$MODEL_DIR"
|
||||
echo "Audio separator models pre-download complete ($(du -sh $MODEL_DIR | cut -f1))"
|
||||
|
||||
# ==================== Start runner service ====================
|
||||
# Start AFTER all caches are warm so the runner only comes online
|
||||
# when the VM is fully ready to accept CI jobs.
|
||||
echo "Starting runner service..."
|
||||
cd $RUNNER_DIR
|
||||
./svc.sh start
|
||||
|
||||
echo "GitHub Actions GPU runner setup complete at $(date)"
|
||||
echo "Runner registered at organization level (nomadkaraoke) with labels: $RUNNER_LABELS"
|
||||
@@ -46,6 +46,7 @@ class MachineTypes:
|
||||
|
||||
GITHUB_RUNNER = "e2-standard-4" # 4 vCPU, 16GB RAM
|
||||
GITHUB_BUILD_RUNNER = "e2-standard-8" # 8 vCPU, 32GB RAM - dedicated Docker build runner
|
||||
GITHUB_GPU_RUNNER = "n1-standard-4" # 4 vCPU, 15GB RAM - GPU runners need N1 series
|
||||
ENCODING_WORKER = "c4d-highcpu-32" # 32 vCPU, AMD EPYC 9B45 Turin - 4.92x faster than c4-standard-8
|
||||
FLACFETCH = "e2-small" # 0.5 vCPU, 2GB RAM
|
||||
|
||||
@@ -90,10 +91,12 @@ class QueueConfigs:
|
||||
# Number of self-hosted GitHub Action runners
|
||||
# Reduced from 20 to 3 - runners auto-scale with start/stop management
|
||||
NUM_GITHUB_RUNNERS = 3
|
||||
NUM_GPU_RUNNERS = 3
|
||||
|
||||
# Runner labels
|
||||
GENERAL_RUNNER_LABELS = "self-hosted,linux,x64,gcp,large-disk"
|
||||
BUILD_RUNNER_LABELS = "self-hosted,linux,x64,gcp,large-disk,docker-build"
|
||||
GPU_RUNNER_LABELS = "self-hosted,linux,x64,gcp,gpu"
|
||||
|
||||
# Google Drive folder ID for validator (public share folder)
|
||||
GDRIVE_FOLDER_ID = "1laRKAyxo0v817SstfM5XkpbWiNKNAMSX"
|
||||
@@ -106,7 +109,7 @@ class RunnerManagerConfig:
|
||||
FUNCTION_NAME = "github-runner-manager"
|
||||
FUNCTION_MEMORY = "512M" # Increased from 256M due to memory usage
|
||||
FUNCTION_TIMEOUT = 300 # 5 minutes
|
||||
IDLE_TIMEOUT_HOURS = 1 # Shorter than Aquarius (3h) since we have more CI activity
|
||||
IDLE_TIMEOUT_HOURS = 0.25 # 15 minutes — solo dev, runners stop at next scheduler check
|
||||
IDLE_CHECK_SCHEDULE = "*/15 * * * *" # Every 15 minutes
|
||||
|
||||
|
||||
|
||||
@@ -3,20 +3,26 @@ GitHub Actions Runner Manager Cloud Function.
|
||||
|
||||
Handles two types of triggers:
|
||||
1. GitHub Webhook (workflow_job.queued) - Starts runner VMs when CI jobs are queued
|
||||
2. Cloud Scheduler (every 15 min) - Stops idle runner VMs after timeout
|
||||
2. Cloud Scheduler (every 15 min) - Stops idle runner VMs after IDLE_TIMEOUT_HOURS
|
||||
|
||||
Runner VMs are tracked by name via the RUNNER_NAMES environment variable, which is
|
||||
set by Pulumi from the list of all runner instance names.
|
||||
|
||||
Environment variables:
|
||||
- GCP_PROJECT: GCP project ID
|
||||
- GCP_ZONE: Zone where runner VMs are located
|
||||
- GCP_ZONE: Default zone where runner VMs are located
|
||||
- WEBHOOK_SECRET_NAME: Secret Manager secret name for webhook verification
|
||||
- RUNNER_PAT_SECRET_NAME: Secret Manager secret name for GitHub PAT
|
||||
- IDLE_TIMEOUT_HOURS: Hours of inactivity before stopping runners (default: 1)
|
||||
- RUNNER_NAMES: Comma-separated list of runner VM names to manage
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import functions_framework
|
||||
@@ -28,11 +34,20 @@ PROJECT_ID = os.environ.get("GCP_PROJECT", "nomadkaraoke")
|
||||
ZONE = os.environ.get("GCP_ZONE", "us-central1-a")
|
||||
WEBHOOK_SECRET_NAME = os.environ.get("WEBHOOK_SECRET_NAME", "github-webhook-secret")
|
||||
RUNNER_PAT_SECRET_NAME = os.environ.get("RUNNER_PAT_SECRET_NAME", "github-runner-pat")
|
||||
IDLE_TIMEOUT_HOURS = int(os.environ.get("IDLE_TIMEOUT_HOURS", "1"))
|
||||
IDLE_TIMEOUT_HOURS = float(os.environ.get("IDLE_TIMEOUT_HOURS", "1"))
|
||||
RUNNER_NAMES = os.environ.get(
|
||||
"RUNNER_NAMES",
|
||||
"github-runner-1,github-runner-2,github-runner-3,github-build-runner",
|
||||
).split(",")
|
||||
# GPU runners are only started when the job explicitly requests the "gpu" label.
|
||||
# This avoids waking ~$1.62/hr of GPU VMs for every CI run.
|
||||
GPU_RUNNER_NAMES = set(
|
||||
os.environ.get("GPU_RUNNER_NAMES", "").split(",")
|
||||
) - {""} # filter empty strings
|
||||
|
||||
# Max time to wait for STOPPING VMs to become TERMINATED before starting them
|
||||
_STOPPING_WAIT_TIMEOUT = 90
|
||||
_STOPPING_POLL_INTERVAL = 5
|
||||
|
||||
# Lazy-loaded clients and secrets
|
||||
_compute_client = None
|
||||
@@ -110,7 +125,7 @@ def verify_webhook_signature(request: Request) -> bool:
|
||||
|
||||
|
||||
def get_runner_instances() -> list[compute_v1.Instance]:
|
||||
"""Get all GitHub runner instances."""
|
||||
"""Get all GitHub runner instances by name."""
|
||||
client = get_compute_client()
|
||||
instances = []
|
||||
|
||||
@@ -125,56 +140,112 @@ def get_runner_instances() -> list[compute_v1.Instance]:
|
||||
except Exception as e:
|
||||
print(f"Error getting instance {instance_name}: {e}")
|
||||
|
||||
print(f"Found {len(instances)} runner instances")
|
||||
return instances
|
||||
|
||||
|
||||
def start_runners() -> dict:
|
||||
def _start_single_runner(instance_name: str) -> tuple[str, str]:
|
||||
"""Start a single runner VM. Returns (instance_name, outcome)."""
|
||||
client = get_compute_client()
|
||||
try:
|
||||
operation = client.start(
|
||||
project=PROJECT_ID,
|
||||
zone=ZONE,
|
||||
instance=instance_name,
|
||||
)
|
||||
operation.result(timeout=300)
|
||||
print(f"{instance_name} started successfully")
|
||||
return instance_name, "started"
|
||||
except Exception as e:
|
||||
print(f"Start failed for {instance_name}: {e}")
|
||||
return instance_name, "failed"
|
||||
|
||||
|
||||
def start_runners(include_gpu: bool = False) -> dict:
|
||||
"""
|
||||
Start any TERMINATED runner VMs.
|
||||
Start any TERMINATED runner VMs, waiting for STOPPING VMs first.
|
||||
|
||||
If VMs are in STOPPING state (e.g. from an idle check that overlaps with
|
||||
new work), waits for them to finish stopping then starts them. This prevents
|
||||
a scenario where all runners are STOPPING and no webhook restarts them.
|
||||
|
||||
Args:
|
||||
include_gpu: If False (default), skip GPU runners to save costs.
|
||||
Only set True when the job explicitly requests GPU labels.
|
||||
|
||||
Returns a dict with lists of started, already_running, and failed instances.
|
||||
"""
|
||||
client = get_compute_client()
|
||||
result = {"started": [], "already_running": [], "failed": []}
|
||||
|
||||
for instance_name in RUNNER_NAMES:
|
||||
try:
|
||||
instance = client.get(
|
||||
project=PROJECT_ID,
|
||||
zone=ZONE,
|
||||
instance=instance_name,
|
||||
)
|
||||
instances = get_runner_instances()
|
||||
|
||||
if instance.status == "TERMINATED":
|
||||
print(f"Starting {instance_name}...")
|
||||
operation = client.start(
|
||||
project=PROJECT_ID,
|
||||
zone=ZONE,
|
||||
instance=instance_name,
|
||||
)
|
||||
# Wait for the operation to complete (timeout after 5 min)
|
||||
# Filter out GPU runners unless explicitly requested
|
||||
if not include_gpu and GPU_RUNNER_NAMES:
|
||||
skipped = [i.name for i in instances if i.name in GPU_RUNNER_NAMES]
|
||||
if skipped:
|
||||
print(f"Skipping GPU runners (not requested): {skipped}")
|
||||
instances = [i for i in instances if i.name not in GPU_RUNNER_NAMES]
|
||||
|
||||
stopping_instances = []
|
||||
to_start = []
|
||||
|
||||
for instance in instances:
|
||||
if instance.status == "TERMINATED":
|
||||
to_start.append(instance.name)
|
||||
elif instance.status in ("STOPPING", "SUSPENDING"):
|
||||
stopping_instances.append(instance.name)
|
||||
elif instance.status == "RUNNING":
|
||||
result["already_running"].append(instance.name)
|
||||
else:
|
||||
print(f"{instance.name} is in state {instance.status}")
|
||||
result["already_running"].append(instance.name)
|
||||
|
||||
# Wait for STOPPING VMs to finish, then add them to the start list
|
||||
if stopping_instances:
|
||||
print(f"Waiting for {len(stopping_instances)} STOPPING VMs: {stopping_instances}")
|
||||
deadline = time.monotonic() + _STOPPING_WAIT_TIMEOUT
|
||||
while stopping_instances and time.monotonic() < deadline:
|
||||
time.sleep(_STOPPING_POLL_INTERVAL)
|
||||
still_stopping = []
|
||||
for name in stopping_instances:
|
||||
try:
|
||||
operation.result(timeout=300)
|
||||
print(f"{instance_name} started successfully")
|
||||
result["started"].append(instance_name)
|
||||
except Exception as op_error:
|
||||
print(f"Start operation failed for {instance_name}: {op_error}")
|
||||
result["failed"].append(instance_name)
|
||||
elif instance.status == "RUNNING":
|
||||
result["already_running"].append(instance_name)
|
||||
else:
|
||||
print(f"{instance_name} is in state {instance.status}")
|
||||
result["already_running"].append(instance_name)
|
||||
inst = client.get(project=PROJECT_ID, zone=ZONE, instance=name)
|
||||
if inst.status == "TERMINATED":
|
||||
to_start.append(name)
|
||||
elif inst.status == "RUNNING":
|
||||
result["already_running"].append(name)
|
||||
else:
|
||||
still_stopping.append(name)
|
||||
except Exception as e:
|
||||
print(f"Error polling {name}: {e}")
|
||||
still_stopping.append(name)
|
||||
stopping_instances = still_stopping
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error with {instance_name}: {e}")
|
||||
result["failed"].append(instance_name)
|
||||
# Any VMs still STOPPING after timeout — log and move on
|
||||
for name in stopping_instances:
|
||||
print(f"{name}: still STOPPING after {_STOPPING_WAIT_TIMEOUT}s, skipping")
|
||||
result["failed"].append(name)
|
||||
|
||||
if not to_start:
|
||||
return result
|
||||
|
||||
# Start all TERMINATED VMs in parallel
|
||||
with ThreadPoolExecutor(max_workers=len(to_start)) as executor:
|
||||
futures = {executor.submit(_start_single_runner, name): name for name in to_start}
|
||||
for future in as_completed(futures):
|
||||
name, outcome = future.result()
|
||||
result[outcome if outcome == "started" else "failed"].append(name)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def update_instance_metadata(instance_name: str, key: str, value: str) -> None:
|
||||
"""Update a single metadata key on an instance."""
|
||||
"""Update a single metadata key on an instance.
|
||||
|
||||
Awaits the operation result to ensure it completes and surfaces errors
|
||||
(e.g. fingerprint conflicts from concurrent writes).
|
||||
"""
|
||||
client = get_compute_client()
|
||||
|
||||
# Get current instance to get fingerprint
|
||||
@@ -200,12 +271,15 @@ def update_instance_metadata(instance_name: str, key: str, value: str) -> None:
|
||||
items=new_items,
|
||||
)
|
||||
|
||||
client.set_metadata(
|
||||
operation = client.set_metadata(
|
||||
project=PROJECT_ID,
|
||||
zone=ZONE,
|
||||
instance=instance_name,
|
||||
metadata_resource=metadata,
|
||||
)
|
||||
# Wait for the operation to complete — without this, the operation can
|
||||
# silently fail (e.g., fingerprint conflict) and we'd never know
|
||||
operation.result(timeout=60)
|
||||
|
||||
|
||||
def get_instance_metadata(instance: compute_v1.Instance, key: str) -> str | None:
|
||||
@@ -220,115 +294,141 @@ def get_instance_metadata(instance: compute_v1.Instance, key: str) -> str | None
|
||||
return None
|
||||
|
||||
|
||||
def _get_instance_age_hours(instance: compute_v1.Instance) -> float:
|
||||
"""Get how long an instance has been running, in hours.
|
||||
|
||||
Uses creationTimestamp as the baseline — this is always available
|
||||
and doesn't depend on metadata writes succeeding.
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
creation_str = instance.creation_timestamp
|
||||
if creation_str:
|
||||
creation_time = datetime.fromisoformat(creation_str.replace("Z", "+00:00"))
|
||||
return (now - creation_time).total_seconds() / 3600
|
||||
# Fallback: if somehow no creation timestamp, assume very old
|
||||
return float("inf")
|
||||
|
||||
|
||||
def check_github_for_pending_jobs() -> bool:
|
||||
"""
|
||||
Check GitHub API for any pending/queued jobs for our runners.
|
||||
Check GitHub API for any pending/queued/in-progress workflow runs.
|
||||
|
||||
Returns True if there are jobs waiting for our self-hosted runners.
|
||||
Returns True if there are runs that might need our self-hosted runners.
|
||||
"""
|
||||
import urllib.request
|
||||
|
||||
pat = get_github_pat()
|
||||
org = "nomadkaraoke"
|
||||
|
||||
# Check for queued workflow runs in karaoke-gen repo
|
||||
url = f"https://api.github.com/repos/{org}/karaoke-gen/actions/runs?status=queued"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {pat}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
)
|
||||
for status in ["queued", "in_progress"]:
|
||||
url = f"https://api.github.com/repos/{org}/karaoke-gen/actions/runs?status={status}"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {pat}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
if data.get("total_count", 0) > 0:
|
||||
print(f"Found {data['total_count']} queued runs in karaoke-gen")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error checking GitHub API: {e}")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
if data.get("total_count", 0) > 0:
|
||||
print(f"Found {data['total_count']} {status} runs in karaoke-gen")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error checking GitHub API ({status}): {e}")
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _stop_single_runner(instance_name: str) -> tuple[str, str]:
|
||||
"""Stop a single runner VM. Returns (instance_name, outcome)."""
|
||||
client = get_compute_client()
|
||||
try:
|
||||
operation = client.stop(
|
||||
project=PROJECT_ID,
|
||||
zone=ZONE,
|
||||
instance=instance_name,
|
||||
)
|
||||
operation.result(timeout=120)
|
||||
print(f"{instance_name}: Stopped successfully")
|
||||
return instance_name, "stopped"
|
||||
except Exception as e:
|
||||
print(f"Error stopping {instance_name}: {e}")
|
||||
return instance_name, "errors"
|
||||
|
||||
|
||||
def check_and_stop_idle_runners() -> dict:
|
||||
"""
|
||||
Check for idle runners and stop them if idle for IDLE_TIMEOUT_HOURS.
|
||||
|
||||
Stops are executed in parallel to minimize the window where new webhooks
|
||||
could race with an in-progress shutdown.
|
||||
|
||||
A runner is considered idle if:
|
||||
1. It's RUNNING
|
||||
2. No jobs are pending/queued on GitHub
|
||||
2. No jobs are pending/queued/in-progress on GitHub
|
||||
3. last-activity metadata is older than IDLE_TIMEOUT_HOURS
|
||||
OR no last-activity metadata and instance is older than IDLE_TIMEOUT_HOURS
|
||||
|
||||
Returns a dict with stopped and kept instances.
|
||||
"""
|
||||
result = {"stopped": [], "kept": [], "errors": []}
|
||||
|
||||
# First check if there are any pending jobs
|
||||
# First check if there are any pending/in-progress jobs.
|
||||
# If so, keep all runners alive but DON'T refresh timestamps —
|
||||
# that would reset idle tracking and prevent eventual shutdown.
|
||||
if check_github_for_pending_jobs():
|
||||
print("Jobs are pending - keeping all runners active")
|
||||
# Update last-activity on all running instances
|
||||
print("Jobs are pending/in-progress — keeping all runners, not updating timestamps")
|
||||
for instance in get_runner_instances():
|
||||
if instance.status == "RUNNING":
|
||||
result["kept"].append(instance.name)
|
||||
# Refresh activity timestamp since there are pending jobs
|
||||
try:
|
||||
update_instance_metadata(
|
||||
instance.name,
|
||||
"last-activity",
|
||||
datetime.now(timezone.utc).isoformat(),
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Error updating metadata for {instance.name}: {e}")
|
||||
return result
|
||||
|
||||
# No pending jobs - check each instance for idle timeout
|
||||
client = get_compute_client()
|
||||
# No pending jobs — check each instance for idle timeout
|
||||
now = datetime.now(timezone.utc)
|
||||
to_stop = []
|
||||
|
||||
for instance in get_runner_instances():
|
||||
if instance.status != "RUNNING":
|
||||
continue
|
||||
|
||||
# Get last-activity timestamp
|
||||
# Get last-activity timestamp from metadata
|
||||
last_activity_str = get_instance_metadata(instance, "last-activity")
|
||||
|
||||
if not last_activity_str:
|
||||
# No activity recorded - set it now and don't stop
|
||||
print(f"{instance.name}: No last-activity metadata, setting now")
|
||||
# No activity recorded — use creation time as fallback.
|
||||
# This ensures VMs without metadata are stopped after IDLE_TIMEOUT_HOURS
|
||||
# rather than staying alive forever in a "set now and keep" loop.
|
||||
idle_hours = _get_instance_age_hours(instance)
|
||||
print(f"{instance.name}: No last-activity metadata, using creation time (age: {idle_hours:.1f}h)")
|
||||
else:
|
||||
try:
|
||||
update_instance_metadata(
|
||||
instance.name,
|
||||
"last-activity",
|
||||
now.isoformat(),
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Error setting metadata for {instance.name}: {e}")
|
||||
last_activity = datetime.fromisoformat(last_activity_str.replace("Z", "+00:00"))
|
||||
idle_hours = (now - last_activity).total_seconds() / 3600
|
||||
except (ValueError, TypeError) as e:
|
||||
print(f"{instance.name}: Invalid last-activity value '{last_activity_str}': {e}")
|
||||
idle_hours = _get_instance_age_hours(instance)
|
||||
|
||||
if idle_hours >= IDLE_TIMEOUT_HOURS:
|
||||
print(f"{instance.name}: Idle for {idle_hours:.1f} hours, queuing for stop...")
|
||||
to_stop.append(instance.name)
|
||||
else:
|
||||
print(f"{instance.name}: Idle for {idle_hours:.1f} hours, keeping...")
|
||||
result["kept"].append(instance.name)
|
||||
continue
|
||||
|
||||
try:
|
||||
last_activity = datetime.fromisoformat(last_activity_str.replace("Z", "+00:00"))
|
||||
idle_hours = (now - last_activity).total_seconds() / 3600
|
||||
if not to_stop:
|
||||
return result
|
||||
|
||||
if idle_hours >= IDLE_TIMEOUT_HOURS:
|
||||
print(f"{instance.name}: Idle for {idle_hours:.1f} hours, stopping...")
|
||||
client.stop(
|
||||
project=PROJECT_ID,
|
||||
zone=ZONE,
|
||||
instance=instance.name,
|
||||
)
|
||||
result["stopped"].append(instance.name)
|
||||
else:
|
||||
print(f"{instance.name}: Idle for {idle_hours:.1f} hours, keeping...")
|
||||
result["kept"].append(instance.name)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error processing {instance.name}: {e}")
|
||||
result["errors"].append(instance.name)
|
||||
# Stop all idle VMs in parallel to minimize the race window
|
||||
print(f"Stopping {len(to_stop)} idle runners in parallel...")
|
||||
with ThreadPoolExecutor(max_workers=len(to_stop)) as executor:
|
||||
futures = {executor.submit(_stop_single_runner, name): name for name in to_stop}
|
||||
for future in as_completed(futures):
|
||||
name, outcome = future.result()
|
||||
result[outcome].append(name)
|
||||
|
||||
return result
|
||||
|
||||
@@ -340,7 +440,7 @@ def handle_request(request: Request):
|
||||
|
||||
Handles:
|
||||
1. Cloud Scheduler triggers (action=check_idle parameter)
|
||||
2. GitHub webhook events (workflow_job.queued)
|
||||
2. GitHub webhook events (workflow_job.queued/completed)
|
||||
"""
|
||||
# Check if this is a scheduler trigger (idle check)
|
||||
action = request.args.get("action")
|
||||
@@ -385,33 +485,28 @@ def handle_request(request: Request):
|
||||
|
||||
# Handle different actions
|
||||
if action == "queued":
|
||||
# Job is queued - ensure runners are started
|
||||
print("Job queued - starting runners if needed")
|
||||
result = start_runners()
|
||||
# Job is queued - ensure runners are started.
|
||||
# Only start GPU runners if the job explicitly requests the "gpu" label.
|
||||
needs_gpu = "gpu" in labels
|
||||
print(f"Job queued - starting runners (gpu={'yes' if needs_gpu else 'no'})")
|
||||
result = start_runners(include_gpu=needs_gpu)
|
||||
return json.dumps(result), 200, {"Content-Type": "application/json"}
|
||||
|
||||
elif action == "in_progress":
|
||||
# Job started - update activity timestamp on all running instances
|
||||
print("Job in progress - updating activity timestamps")
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
for instance in get_runner_instances():
|
||||
if instance.status == "RUNNING":
|
||||
try:
|
||||
update_instance_metadata(instance.name, "last-activity", now)
|
||||
except Exception as e:
|
||||
print(f"Error updating {instance.name}: {e}")
|
||||
return "OK", 200
|
||||
|
||||
elif action == "completed":
|
||||
# Job completed - update activity timestamp
|
||||
print("Job completed - updating activity timestamps")
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
for instance in get_runner_instances():
|
||||
if instance.status == "RUNNING":
|
||||
try:
|
||||
update_instance_metadata(instance.name, "last-activity", now)
|
||||
except Exception as e:
|
||||
print(f"Error updating {instance.name}: {e}")
|
||||
# Job completed — update last-activity on the specific runner that ran it.
|
||||
# Only update the specific runner to avoid fingerprint conflicts from
|
||||
# concurrent webhook calls trying to update all instances simultaneously.
|
||||
runner_name = job.get("runner_name", "")
|
||||
if runner_name:
|
||||
print(f"Job completed on {runner_name} - updating activity timestamp")
|
||||
try:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
update_instance_metadata(runner_name, "last-activity", now)
|
||||
print(f"Updated last-activity on {runner_name}")
|
||||
except Exception as e:
|
||||
print(f"Error updating metadata for {runner_name}: {e}")
|
||||
else:
|
||||
print("Job completed but no runner_name in payload")
|
||||
return "OK", 200
|
||||
|
||||
return "OK", 200
|
||||
@@ -1,15 +1,21 @@
|
||||
"""
|
||||
Tests for runner_manager/main.py
|
||||
|
||||
Focuses on the RUNNER_NAMES configuration and the core functions that
|
||||
iterate over runner instances: get_runner_instances() and start_runners().
|
||||
Covers the critical bug fixes:
|
||||
1. Metadata writes are awaited (operation.result() called)
|
||||
2. Missing last-activity uses creationTimestamp fallback (not "set now and keep")
|
||||
3. Pending jobs don't reset all runner timestamps
|
||||
4. Stops are parallel (ThreadPoolExecutor)
|
||||
5. STOPPING state VMs are waited for then started
|
||||
6. Job completed updates only the specific runner (via runner_name)
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import MagicMock, patch, PropertyMock
|
||||
import time
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
|
||||
# Stub out Cloud Function dependencies not installed in test env
|
||||
for mod in (
|
||||
@@ -20,31 +26,70 @@ for mod in (
|
||||
):
|
||||
sys.modules.setdefault(mod, MagicMock())
|
||||
|
||||
# Make @functions_framework.http a pass-through decorator so handle_request
|
||||
# remains a real callable function in tests
|
||||
sys.modules["functions_framework"].http = lambda f: f
|
||||
|
||||
# We need compute_v1 to have Items and Metadata as usable classes
|
||||
mock_compute_v1 = sys.modules["google.cloud.compute_v1"]
|
||||
mock_compute_v1.Instance = MagicMock
|
||||
mock_compute_v1.Items = MagicMock
|
||||
mock_compute_v1.Metadata = MagicMock
|
||||
|
||||
# Mock the InstancesClient
|
||||
mock_instances_client = MagicMock()
|
||||
mock_compute_v1.InstancesClient.return_value = mock_instances_client
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
|
||||
def _make_instance(name, status="RUNNING", creation_timestamp=None, metadata_items=None):
|
||||
"""Create a mock GCE instance."""
|
||||
instance = MagicMock()
|
||||
instance.name = name
|
||||
instance.status = status
|
||||
instance.creation_timestamp = creation_timestamp or (
|
||||
datetime.now(timezone.utc) - timedelta(hours=5)
|
||||
).isoformat()
|
||||
|
||||
if metadata_items is None:
|
||||
metadata_items = []
|
||||
items = []
|
||||
for k, v in metadata_items:
|
||||
item = MagicMock()
|
||||
item.key = k
|
||||
item.value = v
|
||||
items.append(item)
|
||||
instance.metadata = MagicMock()
|
||||
instance.metadata.items = items
|
||||
instance.metadata.fingerprint = "fp123"
|
||||
return instance
|
||||
|
||||
|
||||
def _import_main(**env_overrides):
|
||||
"""Import main module with clean state and optional env overrides."""
|
||||
if "main" in sys.modules:
|
||||
del sys.modules["main"]
|
||||
env = {
|
||||
"RUNNER_NAMES": "runner-1,runner-2",
|
||||
"GCP_PROJECT": "test-project",
|
||||
"GCP_ZONE": "us-central1-a",
|
||||
**env_overrides,
|
||||
}
|
||||
with patch.dict(os.environ, env):
|
||||
import main
|
||||
main._compute_client = None
|
||||
main._secret_client = None
|
||||
main._webhook_secret = "test-secret"
|
||||
main._github_pat = "ghp_test"
|
||||
return main
|
||||
|
||||
|
||||
class TestRunnerNamesConfig:
|
||||
"""Test that RUNNER_NAMES is parsed correctly from environment."""
|
||||
|
||||
def test_default_runner_names(self):
|
||||
"""Default includes all 3 general runners plus the build runner."""
|
||||
env = {k: v for k, v in os.environ.items() if k != "RUNNER_NAMES"}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
# Re-import to pick up default
|
||||
if "main" in sys.modules:
|
||||
del sys.modules["main"]
|
||||
import main
|
||||
|
||||
assert main.RUNNER_NAMES == [
|
||||
"github-runner-1",
|
||||
"github-runner-2",
|
||||
@@ -53,220 +98,443 @@ class TestRunnerNamesConfig:
|
||||
]
|
||||
|
||||
def test_custom_runner_names_from_env(self):
|
||||
"""RUNNER_NAMES env var overrides the default list."""
|
||||
with patch.dict(os.environ, {"RUNNER_NAMES": "runner-a,runner-b"}):
|
||||
if "main" in sys.modules:
|
||||
del sys.modules["main"]
|
||||
import main
|
||||
|
||||
assert main.RUNNER_NAMES == ["runner-a", "runner-b"]
|
||||
main = _import_main(RUNNER_NAMES="runner-a,runner-b,runner-c")
|
||||
assert main.RUNNER_NAMES == ["runner-a", "runner-b", "runner-c"]
|
||||
|
||||
def test_single_runner_name(self):
|
||||
"""Single runner name without commas works."""
|
||||
with patch.dict(os.environ, {"RUNNER_NAMES": "solo-runner"}):
|
||||
if "main" in sys.modules:
|
||||
del sys.modules["main"]
|
||||
import main
|
||||
|
||||
assert main.RUNNER_NAMES == ["solo-runner"]
|
||||
main = _import_main(RUNNER_NAMES="solo-runner")
|
||||
assert main.RUNNER_NAMES == ["solo-runner"]
|
||||
|
||||
|
||||
class TestGetRunnerInstances:
|
||||
"""Test get_runner_instances() iterates over RUNNER_NAMES."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Reset module state before each test."""
|
||||
if "main" in sys.modules:
|
||||
del sys.modules["main"]
|
||||
# Reset the cached client
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{"RUNNER_NAMES": "github-runner-1,github-runner-2,github-build-runner"},
|
||||
):
|
||||
import main
|
||||
|
||||
self.main = main
|
||||
self.main._compute_client = None
|
||||
|
||||
def test_returns_all_instances(self):
|
||||
"""Should fetch each runner by name from RUNNER_NAMES."""
|
||||
main = _import_main(RUNNER_NAMES="r-1,r-2,r-3")
|
||||
mock_client = MagicMock()
|
||||
mock_instances = []
|
||||
for name in ["github-runner-1", "github-runner-2", "github-build-runner"]:
|
||||
instance = MagicMock()
|
||||
instance.name = name
|
||||
mock_instances.append(instance)
|
||||
|
||||
mock_client.get.side_effect = mock_instances
|
||||
self.main._compute_client = mock_client
|
||||
|
||||
result = self.main.get_runner_instances()
|
||||
instances = [_make_instance(f"r-{i}") for i in range(1, 4)]
|
||||
mock_client.get.side_effect = instances
|
||||
main._compute_client = mock_client
|
||||
|
||||
result = main.get_runner_instances()
|
||||
assert len(result) == 3
|
||||
assert mock_client.get.call_count == 3
|
||||
# Verify each name was queried
|
||||
call_names = [
|
||||
call.kwargs.get("instance") or call[1].get("instance", call[1])
|
||||
for call in mock_client.get.call_args_list
|
||||
]
|
||||
for call_args in mock_client.get.call_args_list:
|
||||
assert call_args == (
|
||||
()
|
||||
) or "instance" in str(call_args)
|
||||
|
||||
def test_handles_missing_instance(self):
|
||||
"""Should skip instances that don't exist (e.g. not yet created)."""
|
||||
main = _import_main(RUNNER_NAMES="r-1,r-2")
|
||||
mock_client = MagicMock()
|
||||
instance1 = MagicMock()
|
||||
instance1.name = "github-runner-1"
|
||||
|
||||
mock_client.get.side_effect = [
|
||||
instance1,
|
||||
_make_instance("r-1"),
|
||||
Exception("Instance not found"),
|
||||
MagicMock(name="github-build-runner"),
|
||||
]
|
||||
self.main._compute_client = mock_client
|
||||
main._compute_client = mock_client
|
||||
|
||||
result = self.main.get_runner_instances()
|
||||
|
||||
# Should still return the 2 that succeeded
|
||||
assert len(result) == 2
|
||||
result = main.get_runner_instances()
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
class TestStartRunners:
|
||||
"""Test start_runners() iterates over RUNNER_NAMES."""
|
||||
|
||||
def setup_method(self):
|
||||
if "main" in sys.modules:
|
||||
del sys.modules["main"]
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{"RUNNER_NAMES": "github-runner-1,github-build-runner"},
|
||||
):
|
||||
import main
|
||||
|
||||
self.main = main
|
||||
self.main._compute_client = None
|
||||
|
||||
def test_starts_terminated_instances(self):
|
||||
"""Should start TERMINATED instances from RUNNER_NAMES."""
|
||||
def test_starts_terminated_instances_in_parallel(self):
|
||||
main = _import_main(RUNNER_NAMES="r-1,r-2")
|
||||
mock_client = MagicMock()
|
||||
|
||||
runner1 = MagicMock()
|
||||
runner1.status = "TERMINATED"
|
||||
runner1.name = "github-runner-1"
|
||||
|
||||
build_runner = MagicMock()
|
||||
build_runner.status = "TERMINATED"
|
||||
build_runner.name = "github-build-runner"
|
||||
|
||||
mock_client.get.side_effect = [runner1, build_runner]
|
||||
# Make start operations succeed
|
||||
mock_client.get.side_effect = [
|
||||
_make_instance("r-1", status="TERMINATED"),
|
||||
_make_instance("r-2", status="TERMINATED"),
|
||||
]
|
||||
mock_op = MagicMock()
|
||||
mock_op.result.return_value = None
|
||||
mock_client.start.return_value = mock_op
|
||||
main._compute_client = mock_client
|
||||
|
||||
self.main._compute_client = mock_client
|
||||
result = main.start_runners()
|
||||
|
||||
result = self.main.start_runners()
|
||||
|
||||
assert "github-runner-1" in result["started"]
|
||||
assert "github-build-runner" in result["started"]
|
||||
assert set(result["started"]) == {"r-1", "r-2"}
|
||||
assert mock_client.start.call_count == 2
|
||||
|
||||
def test_skips_running_instances(self):
|
||||
"""Should not start already-running instances."""
|
||||
def test_skips_gpu_runners_by_default(self):
|
||||
"""GPU runners should not start unless include_gpu=True."""
|
||||
main = _import_main(RUNNER_NAMES="r-1,gpu-1", GPU_RUNNER_NAMES="gpu-1")
|
||||
mock_client = MagicMock()
|
||||
|
||||
runner1 = MagicMock()
|
||||
runner1.status = "RUNNING"
|
||||
runner1.name = "github-runner-1"
|
||||
|
||||
build_runner = MagicMock()
|
||||
build_runner.status = "TERMINATED"
|
||||
build_runner.name = "github-build-runner"
|
||||
|
||||
mock_client.get.side_effect = [runner1, build_runner]
|
||||
mock_client.get.side_effect = [
|
||||
_make_instance("r-1", status="TERMINATED"),
|
||||
_make_instance("gpu-1", status="TERMINATED"),
|
||||
]
|
||||
mock_op = MagicMock()
|
||||
mock_op.result.return_value = None
|
||||
mock_client.start.return_value = mock_op
|
||||
main._compute_client = mock_client
|
||||
|
||||
self.main._compute_client = mock_client
|
||||
result = main.start_runners(include_gpu=False)
|
||||
|
||||
result = self.main.start_runners()
|
||||
|
||||
assert "github-runner-1" in result["already_running"]
|
||||
assert "github-build-runner" in result["started"]
|
||||
assert "r-1" in result["started"]
|
||||
assert "gpu-1" not in result["started"]
|
||||
assert mock_client.start.call_count == 1
|
||||
|
||||
def test_handles_start_failure(self):
|
||||
"""Should report failures without crashing."""
|
||||
def test_starts_gpu_runners_when_requested(self):
|
||||
"""GPU runners should start when include_gpu=True."""
|
||||
main = _import_main(RUNNER_NAMES="r-1,gpu-1", GPU_RUNNER_NAMES="gpu-1")
|
||||
mock_client = MagicMock()
|
||||
|
||||
runner1 = MagicMock()
|
||||
runner1.status = "TERMINATED"
|
||||
runner1.name = "github-runner-1"
|
||||
|
||||
mock_client.get.side_effect = [runner1]
|
||||
mock_client.start.side_effect = Exception("API error")
|
||||
|
||||
self.main._compute_client = mock_client
|
||||
# Patch RUNNER_NAMES to just one for simplicity
|
||||
self.main.RUNNER_NAMES = ["github-runner-1"]
|
||||
|
||||
result = self.main.start_runners()
|
||||
|
||||
assert "github-runner-1" in result["failed"]
|
||||
|
||||
def test_handles_instance_not_found(self):
|
||||
"""Should handle case where instance doesn't exist yet."""
|
||||
mock_client = MagicMock()
|
||||
mock_client.get.side_effect = Exception("Instance not found")
|
||||
|
||||
self.main._compute_client = mock_client
|
||||
self.main.RUNNER_NAMES = ["nonexistent-runner"]
|
||||
|
||||
result = self.main.start_runners()
|
||||
|
||||
assert "nonexistent-runner" in result["failed"]
|
||||
|
||||
|
||||
class TestWebhookHandling:
|
||||
"""Test that webhook handler starts all runners including build runner."""
|
||||
|
||||
def setup_method(self):
|
||||
if "main" in sys.modules:
|
||||
del sys.modules["main"]
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{"RUNNER_NAMES": "github-runner-1,github-build-runner"},
|
||||
):
|
||||
import main
|
||||
|
||||
self.main = main
|
||||
self.main._compute_client = None
|
||||
self.main._webhook_secret = "test-secret"
|
||||
|
||||
def test_queued_event_starts_all_runners(self):
|
||||
"""workflow_job.queued should start all runners in RUNNER_NAMES."""
|
||||
mock_client = MagicMock()
|
||||
|
||||
instances = []
|
||||
for name in ["github-runner-1", "github-build-runner"]:
|
||||
inst = MagicMock()
|
||||
inst.status = "TERMINATED"
|
||||
inst.name = name
|
||||
instances.append(inst)
|
||||
|
||||
mock_client.get.side_effect = instances
|
||||
mock_client.get.side_effect = [
|
||||
_make_instance("r-1", status="TERMINATED"),
|
||||
_make_instance("gpu-1", status="TERMINATED"),
|
||||
]
|
||||
mock_op = MagicMock()
|
||||
mock_op.result.return_value = None
|
||||
mock_client.start.return_value = mock_op
|
||||
main._compute_client = mock_client
|
||||
|
||||
self.main._compute_client = mock_client
|
||||
result = main.start_runners(include_gpu=True)
|
||||
|
||||
result = self.main.start_runners()
|
||||
assert set(result["started"]) == {"r-1", "gpu-1"}
|
||||
|
||||
assert len(result["started"]) == 2
|
||||
assert "github-runner-1" in result["started"]
|
||||
assert "github-build-runner" in result["started"]
|
||||
def test_skips_running_instances(self):
|
||||
main = _import_main(RUNNER_NAMES="r-1,r-2")
|
||||
mock_client = MagicMock()
|
||||
mock_client.get.side_effect = [
|
||||
_make_instance("r-1", status="RUNNING"),
|
||||
_make_instance("r-2", status="TERMINATED"),
|
||||
]
|
||||
mock_op = MagicMock()
|
||||
mock_op.result.return_value = None
|
||||
mock_client.start.return_value = mock_op
|
||||
main._compute_client = mock_client
|
||||
|
||||
result = main.start_runners()
|
||||
|
||||
assert "r-1" in result["already_running"]
|
||||
assert "r-2" in result["started"]
|
||||
assert mock_client.start.call_count == 1
|
||||
|
||||
def test_waits_for_stopping_vms(self):
|
||||
"""STOPPING VMs should be polled until TERMINATED, then started."""
|
||||
main = _import_main(RUNNER_NAMES="r-1")
|
||||
mock_client = MagicMock()
|
||||
|
||||
# First call: get_runner_instances() sees STOPPING
|
||||
stopping_inst = _make_instance("r-1", status="STOPPING")
|
||||
# Poll calls: first still STOPPING, then TERMINATED
|
||||
terminated_inst = _make_instance("r-1", status="TERMINATED")
|
||||
|
||||
mock_client.get.side_effect = [stopping_inst, stopping_inst, terminated_inst]
|
||||
mock_op = MagicMock()
|
||||
mock_op.result.return_value = None
|
||||
mock_client.start.return_value = mock_op
|
||||
main._compute_client = mock_client
|
||||
|
||||
with patch("main.time.sleep"): # skip actual sleeps
|
||||
result = main.start_runners()
|
||||
|
||||
assert "r-1" in result["started"]
|
||||
|
||||
|
||||
class TestUpdateInstanceMetadata:
|
||||
"""Test that metadata writes are properly awaited."""
|
||||
|
||||
def test_awaits_operation_result(self):
|
||||
"""The set_metadata operation must be awaited to catch fingerprint conflicts."""
|
||||
main = _import_main()
|
||||
mock_client = MagicMock()
|
||||
instance = _make_instance("r-1", metadata_items=[("last-activity", "old")])
|
||||
mock_client.get.return_value = instance
|
||||
mock_op = MagicMock()
|
||||
mock_client.set_metadata.return_value = mock_op
|
||||
main._compute_client = mock_client
|
||||
|
||||
main.update_instance_metadata("r-1", "last-activity", "new-value")
|
||||
|
||||
# Critical: operation.result() must be called
|
||||
mock_op.result.assert_called_once_with(timeout=60)
|
||||
|
||||
def test_adds_new_metadata_key(self):
|
||||
main = _import_main()
|
||||
mock_client = MagicMock()
|
||||
instance = _make_instance("r-1", metadata_items=[])
|
||||
mock_client.get.return_value = instance
|
||||
mock_op = MagicMock()
|
||||
mock_client.set_metadata.return_value = mock_op
|
||||
main._compute_client = mock_client
|
||||
|
||||
main.update_instance_metadata("r-1", "last-activity", "2026-01-01T00:00:00+00:00")
|
||||
|
||||
mock_client.set_metadata.assert_called_once()
|
||||
mock_op.result.assert_called_once()
|
||||
|
||||
|
||||
class TestGetInstanceAgeHours:
|
||||
"""Test creationTimestamp fallback logic."""
|
||||
|
||||
def test_returns_age_from_creation_timestamp(self):
|
||||
main = _import_main()
|
||||
two_hours_ago = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
|
||||
instance = _make_instance("r-1", creation_timestamp=two_hours_ago)
|
||||
|
||||
age = main._get_instance_age_hours(instance)
|
||||
assert 1.9 < age < 2.1
|
||||
|
||||
def test_returns_inf_when_no_timestamp(self):
|
||||
main = _import_main()
|
||||
instance = _make_instance("r-1")
|
||||
instance.creation_timestamp = None
|
||||
|
||||
age = main._get_instance_age_hours(instance)
|
||||
assert age == float("inf")
|
||||
|
||||
|
||||
class TestCheckAndStopIdleRunners:
|
||||
"""Test the idle check logic — the most critical function."""
|
||||
|
||||
def _setup(self, runner_names="r-1,r-2"):
|
||||
main = _import_main(RUNNER_NAMES=runner_names)
|
||||
mock_client = MagicMock()
|
||||
main._compute_client = mock_client
|
||||
return main, mock_client
|
||||
|
||||
def test_no_last_activity_uses_creation_timestamp_fallback(self):
|
||||
"""VMs without last-activity metadata should use creation time,
|
||||
NOT set 'now' and keep running (the old bug)."""
|
||||
main, mock_client = self._setup(runner_names="r-1")
|
||||
|
||||
# Instance created 3 hours ago, no last-activity metadata
|
||||
three_hours_ago = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()
|
||||
instance = _make_instance("r-1", status="RUNNING", creation_timestamp=three_hours_ago, metadata_items=[])
|
||||
mock_client.get.side_effect = [instance]
|
||||
|
||||
mock_stop_op = MagicMock()
|
||||
mock_stop_op.result.return_value = None
|
||||
mock_client.stop.return_value = mock_stop_op
|
||||
|
||||
with patch.object(main, "check_github_for_pending_jobs", return_value=False):
|
||||
result = main.check_and_stop_idle_runners()
|
||||
|
||||
assert "r-1" in result["stopped"]
|
||||
|
||||
def test_no_last_activity_keeps_recent_vm(self):
|
||||
"""VM created <1h ago without metadata should be kept."""
|
||||
main, mock_client = self._setup(runner_names="r-1")
|
||||
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=30)).isoformat()
|
||||
instance = _make_instance("r-1", status="RUNNING", creation_timestamp=recent, metadata_items=[])
|
||||
mock_client.get.side_effect = [instance]
|
||||
|
||||
with patch.object(main, "check_github_for_pending_jobs", return_value=False):
|
||||
result = main.check_and_stop_idle_runners()
|
||||
|
||||
assert "r-1" in result["kept"]
|
||||
mock_client.stop.assert_not_called()
|
||||
|
||||
def test_pending_jobs_does_not_refresh_timestamps(self):
|
||||
"""When jobs are pending, runners stay alive but timestamps are NOT refreshed.
|
||||
The old bug: refreshing timestamps prevented runners from ever being idle."""
|
||||
main, mock_client = self._setup(runner_names="r-1")
|
||||
|
||||
instance = _make_instance("r-1", status="RUNNING")
|
||||
mock_client.get.side_effect = [instance]
|
||||
|
||||
with patch.object(main, "check_github_for_pending_jobs", return_value=True):
|
||||
result = main.check_and_stop_idle_runners()
|
||||
|
||||
assert "r-1" in result["kept"]
|
||||
# Critical: set_metadata must NOT be called
|
||||
mock_client.set_metadata.assert_not_called()
|
||||
|
||||
def test_stops_idle_runners_in_parallel(self):
|
||||
"""Multiple idle runners should be stopped in parallel."""
|
||||
main, mock_client = self._setup(runner_names="r-1,r-2")
|
||||
|
||||
two_hours_ago = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
|
||||
instances = [
|
||||
_make_instance("r-1", status="RUNNING", metadata_items=[("last-activity", two_hours_ago)]),
|
||||
_make_instance("r-2", status="RUNNING", metadata_items=[("last-activity", two_hours_ago)]),
|
||||
]
|
||||
mock_client.get.side_effect = instances
|
||||
|
||||
mock_stop_op = MagicMock()
|
||||
mock_stop_op.result.return_value = None
|
||||
mock_client.stop.return_value = mock_stop_op
|
||||
|
||||
with patch.object(main, "check_github_for_pending_jobs", return_value=False):
|
||||
result = main.check_and_stop_idle_runners()
|
||||
|
||||
assert set(result["stopped"]) == {"r-1", "r-2"}
|
||||
|
||||
def test_keeps_recently_active_runners(self):
|
||||
main, mock_client = self._setup(runner_names="r-1")
|
||||
|
||||
recent = (datetime.now(timezone.utc) - timedelta(minutes=30)).isoformat()
|
||||
instance = _make_instance("r-1", status="RUNNING", metadata_items=[("last-activity", recent)])
|
||||
mock_client.get.side_effect = [instance]
|
||||
|
||||
with patch.object(main, "check_github_for_pending_jobs", return_value=False):
|
||||
result = main.check_and_stop_idle_runners()
|
||||
|
||||
assert "r-1" in result["kept"]
|
||||
mock_client.stop.assert_not_called()
|
||||
|
||||
def test_skips_non_running_instances(self):
|
||||
main, mock_client = self._setup(runner_names="r-1")
|
||||
|
||||
instance = _make_instance("r-1", status="TERMINATED")
|
||||
mock_client.get.side_effect = [instance]
|
||||
|
||||
with patch.object(main, "check_github_for_pending_jobs", return_value=False):
|
||||
result = main.check_and_stop_idle_runners()
|
||||
|
||||
assert result == {"stopped": [], "kept": [], "errors": []}
|
||||
|
||||
def test_handles_invalid_last_activity_value(self):
|
||||
"""Invalid timestamp should fall back to creation time."""
|
||||
main, mock_client = self._setup(runner_names="r-1")
|
||||
|
||||
old_creation = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()
|
||||
instance = _make_instance(
|
||||
"r-1", status="RUNNING",
|
||||
creation_timestamp=old_creation,
|
||||
metadata_items=[("last-activity", "not-a-date")],
|
||||
)
|
||||
mock_client.get.side_effect = [instance]
|
||||
|
||||
mock_stop_op = MagicMock()
|
||||
mock_stop_op.result.return_value = None
|
||||
mock_client.stop.return_value = mock_stop_op
|
||||
|
||||
with patch.object(main, "check_github_for_pending_jobs", return_value=False):
|
||||
result = main.check_and_stop_idle_runners()
|
||||
|
||||
assert "r-1" in result["stopped"]
|
||||
|
||||
|
||||
class TestWebhookCompleted:
|
||||
"""Test that job completion updates only the specific runner."""
|
||||
|
||||
def _make_webhook_request(self, payload):
|
||||
"""Create a mock request with valid webhook signature."""
|
||||
import hmac as hmac_mod
|
||||
import hashlib
|
||||
|
||||
body = json.dumps(payload).encode()
|
||||
sig = "sha256=" + hmac_mod.new(b"test-secret", body, hashlib.sha256).hexdigest()
|
||||
headers = {
|
||||
"X-Hub-Signature-256": sig,
|
||||
"X-GitHub-Event": "workflow_job",
|
||||
}
|
||||
|
||||
request = MagicMock()
|
||||
request.args.get.return_value = None
|
||||
request.headers.get.side_effect = lambda h, *a: headers.get(h)
|
||||
request.get_data.return_value = body
|
||||
request.get_json.return_value = payload
|
||||
return request
|
||||
|
||||
def test_completed_updates_specific_runner_only(self):
|
||||
"""Only the runner that ran the job should have its metadata updated."""
|
||||
main = _import_main(RUNNER_NAMES="r-1,r-2")
|
||||
mock_client = MagicMock()
|
||||
instance = _make_instance("r-1", metadata_items=[])
|
||||
mock_client.get.return_value = instance
|
||||
mock_op = MagicMock()
|
||||
mock_client.set_metadata.return_value = mock_op
|
||||
main._compute_client = mock_client
|
||||
|
||||
payload = {
|
||||
"action": "completed",
|
||||
"workflow_job": {
|
||||
"labels": ["self-hosted", "linux"],
|
||||
"runner_name": "r-1",
|
||||
},
|
||||
}
|
||||
request = self._make_webhook_request(payload)
|
||||
|
||||
# Call the underlying function directly (bypasses decorator)
|
||||
main.handle_request(request)
|
||||
|
||||
# Metadata should be updated on r-1 only
|
||||
mock_client.set_metadata.assert_called_once()
|
||||
|
||||
def test_completed_without_runner_name_does_nothing(self):
|
||||
"""If webhook payload has no runner_name, no metadata update should happen."""
|
||||
main = _import_main(RUNNER_NAMES="r-1")
|
||||
mock_client = MagicMock()
|
||||
main._compute_client = mock_client
|
||||
|
||||
payload = {
|
||||
"action": "completed",
|
||||
"workflow_job": {
|
||||
"labels": ["self-hosted"],
|
||||
},
|
||||
}
|
||||
request = self._make_webhook_request(payload)
|
||||
main.handle_request(request)
|
||||
|
||||
mock_client.set_metadata.assert_not_called()
|
||||
|
||||
|
||||
class TestNonSelfHostedJobsIgnored:
|
||||
"""Test that jobs not targeting self-hosted runners are ignored."""
|
||||
|
||||
def test_ubuntu_latest_job_ignored(self):
|
||||
main = _import_main()
|
||||
|
||||
import hmac as hmac_mod
|
||||
import hashlib
|
||||
|
||||
payload = {
|
||||
"action": "queued",
|
||||
"workflow_job": {
|
||||
"labels": ["ubuntu-latest"],
|
||||
},
|
||||
}
|
||||
body = json.dumps(payload).encode()
|
||||
sig = "sha256=" + hmac_mod.new(b"test-secret", body, hashlib.sha256).hexdigest()
|
||||
headers = {
|
||||
"X-Hub-Signature-256": sig,
|
||||
"X-GitHub-Event": "workflow_job",
|
||||
}
|
||||
|
||||
request = MagicMock()
|
||||
request.args.get.return_value = None
|
||||
request.headers.get.side_effect = lambda h, *a: headers.get(h)
|
||||
request.get_data.return_value = body
|
||||
request.get_json.return_value = payload
|
||||
|
||||
response = main.handle_request(request)
|
||||
|
||||
assert "not for self-hosted" in str(response)
|
||||
|
||||
|
||||
class TestCheckGithubForPendingJobs:
|
||||
"""Test the GitHub API check for pending jobs."""
|
||||
|
||||
def test_checks_both_queued_and_in_progress(self):
|
||||
main = _import_main()
|
||||
|
||||
call_count = 0
|
||||
|
||||
def mock_urlopen(req, timeout=None):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
response = MagicMock()
|
||||
response.read.return_value = json.dumps({"total_count": 0}).encode()
|
||||
response.__enter__ = lambda s: response
|
||||
response.__exit__ = lambda s, *a: None
|
||||
return response
|
||||
|
||||
with patch("urllib.request.urlopen", side_effect=mock_urlopen):
|
||||
result = main.check_github_for_pending_jobs()
|
||||
|
||||
assert result is False
|
||||
assert call_count == 2 # queued + in_progress
|
||||
|
||||
def test_returns_true_when_jobs_pending(self):
|
||||
main = _import_main()
|
||||
|
||||
def mock_urlopen(req, timeout=None):
|
||||
response = MagicMock()
|
||||
response.read.return_value = json.dumps({"total_count": 3}).encode()
|
||||
response.__enter__ = lambda s: response
|
||||
response.__exit__ = lambda s, *a: None
|
||||
return response
|
||||
|
||||
with patch("urllib.request.urlopen", side_effect=mock_urlopen):
|
||||
result = main.check_github_for_pending_jobs()
|
||||
|
||||
assert result is True
|
||||
@@ -54,6 +54,7 @@ def grant_runner_manager_permissions(
|
||||
service_account: gcp.serviceaccount.Account,
|
||||
webhook_secret: gcp.secretmanager.Secret,
|
||||
pat_secret: gcp.secretmanager.Secret,
|
||||
runner_service_account: gcp.serviceaccount.Account | None = None,
|
||||
) -> dict:
|
||||
"""Grant permissions to the runner manager service account."""
|
||||
bindings = {}
|
||||
@@ -66,6 +67,17 @@ def grant_runner_manager_permissions(
|
||||
member=service_account.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Service Account User on the runner SA — required to set metadata
|
||||
# on VMs that run as the runner service account. Without this, metadata
|
||||
# writes fail with SERVICE_ACCOUNT_ACCESS_DENIED.
|
||||
if runner_service_account is not None:
|
||||
bindings["runner_sa_user"] = gcp.serviceaccount.IAMMember(
|
||||
"runner-manager-runner-sa-user",
|
||||
service_account_id=runner_service_account.name,
|
||||
role="roles/iam.serviceAccountUser",
|
||||
member=service_account.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Secret Manager accessor for webhook secret
|
||||
bindings["webhook_secret_accessor"] = gcp.secretmanager.SecretIamMember(
|
||||
"runner-manager-webhook-secret-access",
|
||||
@@ -127,6 +139,7 @@ def create_cloud_function(
|
||||
source_archive: gcp.storage.BucketObject,
|
||||
permissions: dict,
|
||||
runner_names: list[pulumi.Output] | None = None,
|
||||
gpu_runner_names: list[pulumi.Output] | None = None,
|
||||
) -> gcp.cloudfunctionsv2.Function:
|
||||
"""Create the Cloud Function (Gen2) for runner management."""
|
||||
env_vars = {
|
||||
@@ -142,6 +155,11 @@ def create_cloud_function(
|
||||
lambda names: ",".join(names)
|
||||
)
|
||||
|
||||
if gpu_runner_names:
|
||||
env_vars["GPU_RUNNER_NAMES"] = pulumi.Output.all(*gpu_runner_names).apply(
|
||||
lambda names: ",".join(names)
|
||||
)
|
||||
|
||||
return gcp.cloudfunctionsv2.Function(
|
||||
"runner-manager-function",
|
||||
name=RunnerManagerConfig.FUNCTION_NAME,
|
||||
@@ -250,6 +268,8 @@ def create_runner_manager_resources(
|
||||
webhook_secret: gcp.secretmanager.Secret,
|
||||
pat_secret: gcp.secretmanager.Secret,
|
||||
runner_names: list[pulumi.Output] | None = None,
|
||||
gpu_runner_names: list[pulumi.Output] | None = None,
|
||||
runner_service_account: gcp.serviceaccount.Account | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
Create all resources for the GitHub Actions runner manager.
|
||||
@@ -258,6 +278,8 @@ def create_runner_manager_resources(
|
||||
webhook_secret: The webhook secret for signature verification.
|
||||
pat_secret: The GitHub PAT secret for API calls.
|
||||
runner_names: List of Pulumi Output VM names for the runner manager to track.
|
||||
gpu_runner_names: Subset of runner_names that are GPU runners (started only for GPU jobs).
|
||||
runner_service_account: The SA that runner VMs run as (for IAM binding).
|
||||
|
||||
Returns:
|
||||
dict: Dictionary of all created resources.
|
||||
@@ -271,6 +293,7 @@ def create_runner_manager_resources(
|
||||
function_sa,
|
||||
webhook_secret,
|
||||
pat_secret,
|
||||
runner_service_account,
|
||||
)
|
||||
|
||||
# Create source storage bucket and archive
|
||||
@@ -284,6 +307,7 @@ def create_runner_manager_resources(
|
||||
source_archive,
|
||||
permissions,
|
||||
runner_names,
|
||||
gpu_runner_names,
|
||||
)
|
||||
|
||||
# Allow unauthenticated invocation (GitHub webhooks)
|
||||
|
||||
@@ -474,6 +474,10 @@ class LyricsProcessor:
|
||||
|
||||
self.logger.info(f"Saved correction data to {corrections_filepath}")
|
||||
|
||||
# Include lyrics_dir so downstream consumers (e.g. _store_lyrics_processing_metadata)
|
||||
# can find corrections.json and other artifacts
|
||||
transcriber_outputs["lyrics_dir"] = lyrics_dir
|
||||
|
||||
# Capture countdown padding information for syncing with instrumental audio
|
||||
transcriber_outputs["countdown_padding_added"] = getattr(results, "countdown_padding_added", False)
|
||||
transcriber_outputs["countdown_padding_seconds"] = getattr(results, "countdown_padding_seconds", 0.0)
|
||||
|
||||
@@ -188,6 +188,21 @@ class LyricsCorrector:
|
||||
span.set_attribute("correction_ratio", correction_ratio)
|
||||
span.set_attribute("duration_seconds", time.time() - start_time)
|
||||
|
||||
# Build metadata dict, including primary transcription metadata for provenance
|
||||
result_metadata = {
|
||||
"anchor_sequences_count": len(anchor_sequences),
|
||||
"gap_sequences_count": len(gap_sequences),
|
||||
"total_words": total_words,
|
||||
"correction_ratio": correction_ratio,
|
||||
"available_handlers": self.all_handlers,
|
||||
"enabled_handlers": enabled_handlers,
|
||||
"agentic_routing": "agentic" if agentic_enabled else "rule-based",
|
||||
}
|
||||
|
||||
# Pass through primary transcription metadata (e.g., AudioShake task_id, asset_id)
|
||||
if primary_transcription.metadata:
|
||||
result_metadata["transcription_metadata"] = primary_transcription.metadata
|
||||
|
||||
result = CorrectionResult(
|
||||
original_segments=primary_transcription.segments,
|
||||
corrected_segments=corrected_segments,
|
||||
@@ -198,15 +213,7 @@ class LyricsCorrector:
|
||||
anchor_sequences=anchor_sequences,
|
||||
resized_segments=[],
|
||||
gap_sequences=gap_sequences,
|
||||
metadata={
|
||||
"anchor_sequences_count": len(anchor_sequences),
|
||||
"gap_sequences_count": len(gap_sequences),
|
||||
"total_words": total_words,
|
||||
"correction_ratio": correction_ratio,
|
||||
"available_handlers": self.all_handlers,
|
||||
"enabled_handlers": enabled_handlers,
|
||||
"agentic_routing": "agentic" if agentic_enabled else "rule-based",
|
||||
},
|
||||
metadata=result_metadata,
|
||||
correction_steps=correction_steps,
|
||||
word_id_map=word_id_map,
|
||||
segment_id_map=segment_id_map,
|
||||
|
||||
@@ -171,20 +171,56 @@ class CDGGenerator:
|
||||
self._write_toml_file(toml_data, output_file)
|
||||
|
||||
def _validate_and_setup_font(self, cdg_styles: dict) -> None:
|
||||
"""Validate and set up font path in CDG styles."""
|
||||
"""Validate and set up font path in CDG styles.
|
||||
|
||||
Resolution order:
|
||||
1. Use font_path as-is if it's an absolute path that exists
|
||||
2. Use font_path as-is if it exists as a relative path
|
||||
3. Try full relative path inside bundled fonts directory
|
||||
4. Try just the filename inside bundled fonts directory
|
||||
5. Fall back to arial.ttf from bundled fonts
|
||||
"""
|
||||
if not cdg_styles.get("font_path"):
|
||||
return
|
||||
|
||||
if not os.path.isabs(cdg_styles["font_path"]) and not os.path.exists(cdg_styles["font_path"]):
|
||||
package_font_path = os.path.join(os.path.dirname(__file__), "fonts", cdg_styles["font_path"])
|
||||
if os.path.exists(package_font_path):
|
||||
cdg_styles["font_path"] = package_font_path
|
||||
self.logger.debug(f"Found font in package fonts directory: {cdg_styles['font_path']}")
|
||||
else:
|
||||
self.logger.warning(
|
||||
f"Font file {cdg_styles['font_path']} not found in package fonts directory {package_font_path}, will use default font"
|
||||
)
|
||||
cdg_styles["font_path"] = None
|
||||
fonts_dir = os.path.join(os.path.dirname(__file__), "fonts")
|
||||
font_path = cdg_styles["font_path"]
|
||||
|
||||
# Already exists (absolute or relative to cwd) — absolutize to avoid CWD issues
|
||||
if os.path.isfile(font_path):
|
||||
cdg_styles["font_path"] = os.path.abspath(font_path)
|
||||
return
|
||||
|
||||
# Try full relative path in bundled fonts dir
|
||||
package_font_path = os.path.join(fonts_dir, font_path)
|
||||
if os.path.isfile(package_font_path):
|
||||
cdg_styles["font_path"] = os.path.abspath(package_font_path)
|
||||
self.logger.debug(f"Found font in package fonts directory: {package_font_path}")
|
||||
return
|
||||
|
||||
# Try just the filename in bundled fonts dir
|
||||
font_filename = os.path.basename(font_path)
|
||||
package_font_by_name = os.path.join(fonts_dir, font_filename)
|
||||
if os.path.isfile(package_font_by_name):
|
||||
cdg_styles["font_path"] = os.path.abspath(package_font_by_name)
|
||||
self.logger.warning(
|
||||
f"Font file {font_path} not found, using bundled font: {font_filename}"
|
||||
)
|
||||
return
|
||||
|
||||
# Last resort: fall back to arial.ttf
|
||||
fallback_font = os.path.join(fonts_dir, "arial.ttf")
|
||||
if os.path.isfile(fallback_font):
|
||||
cdg_styles["font_path"] = os.path.abspath(fallback_font)
|
||||
self.logger.warning(
|
||||
f"Font file {font_path} not found, falling back to bundled arial.ttf"
|
||||
)
|
||||
return
|
||||
|
||||
self.logger.error(
|
||||
f"Font file {font_path} not found and no bundled fonts available in {fonts_dir}"
|
||||
)
|
||||
cdg_styles["font_path"] = None
|
||||
|
||||
def _compose_cdg(self, toml_file: str) -> None:
|
||||
"""Compose CDG using KaraokeComposer."""
|
||||
@@ -387,6 +423,11 @@ class CDGGenerator:
|
||||
cdg_styles: dict,
|
||||
) -> dict:
|
||||
"""Create TOML data structure."""
|
||||
if not cdg_styles.get("font_path"):
|
||||
raise RuntimeError(
|
||||
"CDG font_path is None — cannot generate CDG without a font. "
|
||||
"Check that the font file exists and was downloaded correctly."
|
||||
)
|
||||
safe_output_name = self._get_safe_filename(artist, title, "Karaoke")
|
||||
return {
|
||||
"title": title,
|
||||
|
||||
@@ -293,6 +293,9 @@ class AudioShakeTranscriber(BaseTranscriber):
|
||||
asset_id = self.api.upload_file(upload_filepath)
|
||||
self.logger.debug(f"File uploaded successfully. Asset ID: {asset_id}")
|
||||
|
||||
# Store asset_id for later retrieval in metadata
|
||||
self._last_asset_id = asset_id
|
||||
|
||||
task_id = self.api.create_task(asset_id)
|
||||
self.logger.debug(f"Task created successfully. Task ID: {task_id}")
|
||||
|
||||
@@ -378,6 +381,7 @@ class AudioShakeTranscriber(BaseTranscriber):
|
||||
metadata={
|
||||
"language": transcription_data.get("metadata", {}).get("language"),
|
||||
"task_id": task_data["id"],
|
||||
"asset_id": task_data.get("assetId") or getattr(self, '_last_asset_id', None),
|
||||
"duration": task_data.get("duration"),
|
||||
},
|
||||
)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.140.2"
|
||||
version = "0.143.2"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -696,7 +696,7 @@ class TestRemoteKaraokeClient:
|
||||
},
|
||||
{
|
||||
"file_type": "style_params",
|
||||
"gcs_path": "uploads/new-job-456/style/style_params.json",
|
||||
"gcs_path": "jobs/new-job-456/style/style_params.json",
|
||||
"upload_url": "https://storage.googleapis.com/signed-url-2",
|
||||
"content_type": "application/json"
|
||||
}
|
||||
@@ -2559,7 +2559,7 @@ class TestSearchAudioWithStyleFiles:
|
||||
"style_upload_urls": [
|
||||
{
|
||||
"file_type": "style_params",
|
||||
"gcs_path": "uploads/test-job-123/style/style_params.json",
|
||||
"gcs_path": "jobs/test-job-123/style/style_params.json",
|
||||
"upload_url": "https://storage.googleapis.com/signed-url-1"
|
||||
}
|
||||
]
|
||||
@@ -2641,7 +2641,7 @@ class TestSearchAudioWithStyleFiles:
|
||||
"style_upload_urls": [
|
||||
{
|
||||
"file_type": "style_params",
|
||||
"gcs_path": "uploads/test-job-123/style/style_params.json",
|
||||
"gcs_path": "jobs/test-job-123/style/style_params.json",
|
||||
"upload_url": "https://storage.googleapis.com/signed-url-1"
|
||||
}
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user