mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-25 16:39:03 +09:00
Compare commits
15
Commits
No files matched your search
@@ -252,6 +252,7 @@ jobs:
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ secrets.E2E_TEST_TOKEN }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
run: |
|
||||
echo "Starting E2E Happy Path Test against Production"
|
||||
echo "Time: $(date)"
|
||||
@@ -1022,9 +1023,34 @@ jobs:
|
||||
- name: Restart GCE Encoding Worker
|
||||
run: |
|
||||
echo "🔄 Restarting encoding worker to pick up new wheel..."
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker" || true
|
||||
echo "✅ Encoding worker restart triggered"
|
||||
|
||||
# Use IAP tunneling - works directly with service account credentials
|
||||
# (avoids SSH key propagation delays that cause silent failures)
|
||||
gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
|
||||
echo "⏳ Waiting for service to start..."
|
||||
sleep 15
|
||||
|
||||
# Verify the restart worked by checking the wheel version
|
||||
NEW_VERSION=$(gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="curl -s http://localhost:8080/health | grep -o '\"wheel_version\":\"[^\"]*\"' | cut -d'\"' -f4")
|
||||
|
||||
EXPECTED_VERSION=$(cat pyproject.toml | grep 'version = ' | head -1 | cut -d'"' -f2)
|
||||
|
||||
if [ "$NEW_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "✅ Encoding worker restarted successfully (v$NEW_VERSION)"
|
||||
else
|
||||
echo "⚠️ Version mismatch: encoder has v$NEW_VERSION, expected v$EXPECTED_VERSION"
|
||||
echo " This may indicate the restart failed or the wheel wasn't downloaded"
|
||||
# Don't fail the build - the encoder will still work, just with old version
|
||||
fi
|
||||
|
||||
- name: Configure Docker for Artifact Registry
|
||||
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
@@ -1166,13 +1192,16 @@ jobs:
|
||||
--memory 16Gi \
|
||||
--cpu 8 \
|
||||
--cpu-boost \
|
||||
--no-cpu-throttling \
|
||||
--execution-environment gen2 \
|
||||
--timeout 1800 \
|
||||
--concurrency 1 \
|
||||
--max-instances 50 \
|
||||
--min-instances 4 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest"
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest"
|
||||
|
||||
- name: Verify deployment and version
|
||||
run: |
|
||||
|
||||
@@ -74,6 +74,7 @@ jobs:
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ inputs.use_test_token && secrets.E2E_TEST_TOKEN || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "Starting E2E Happy Path Test"
|
||||
|
||||
+1
-2
@@ -58,8 +58,7 @@ frontend/.eslintcache
|
||||
# Storybook
|
||||
frontend/storybook-static/
|
||||
|
||||
# PWA files
|
||||
frontend/**/public/sw.js
|
||||
# PWA auto-generated files (our sw.js is hand-written and should be tracked)
|
||||
frontend/**/public/workbox-*.js
|
||||
frontend/**/public/swe-worker-*.js
|
||||
|
||||
|
||||
@@ -105,11 +105,11 @@ EOF
|
||||
### GCE Encoding Worker
|
||||
```bash
|
||||
# SSH to restart service (clears in-memory job queue)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-a --project=nomadkaraoke \
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
|
||||
# Check health
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-a --project=nomadkaraoke \
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="curl -s http://localhost:8080/health"
|
||||
```
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ WORKDIR /app
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
|
||||
COPY backend /app/backend
|
||||
|
||||
# Install all Python dependencies (the slow part - cached in base image)
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
|
||||
@@ -1509,7 +1509,7 @@ class ImpersonateUserResponse(BaseModel):
|
||||
@router.post("/users/{email}/impersonate", response_model=ImpersonateUserResponse)
|
||||
async def impersonate_user(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
@@ -1531,7 +1531,7 @@ async def impersonate_user(
|
||||
user_email: The impersonated user's email
|
||||
message: Success message
|
||||
"""
|
||||
admin_email = auth_data[0]
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
target_email = email.lower()
|
||||
|
||||
# Cannot impersonate yourself
|
||||
|
||||
@@ -858,8 +858,19 @@ async def enroll_beta_tester(
|
||||
detail="Access denied from this location"
|
||||
)
|
||||
|
||||
# 3. Check IP-based enrollment rate limit (1 per 24h per IP)
|
||||
if ip_address:
|
||||
# 3. Check for E2E test bypass (allows automated testing to skip IP rate limit)
|
||||
from backend.config import settings
|
||||
e2e_bypass_key = http_request.headers.get("X-E2E-Bypass-Key")
|
||||
skip_ip_rate_limit = False
|
||||
if e2e_bypass_key and settings.e2e_bypass_key:
|
||||
if e2e_bypass_key == settings.e2e_bypass_key:
|
||||
logger.info(f"Beta enrollment: E2E bypass key validated for {_mask_email(email)}")
|
||||
skip_ip_rate_limit = True
|
||||
else:
|
||||
logger.warning(f"Beta enrollment: Invalid E2E bypass key attempted for {_mask_email(email)}")
|
||||
|
||||
# 4. Check IP-based enrollment rate limit (1 per 24h per IP)
|
||||
if ip_address and not skip_ip_rate_limit:
|
||||
allowed, remaining, message = rate_limit_service.check_beta_ip_limit(ip_address)
|
||||
if not allowed:
|
||||
logger.warning(f"Beta enrollment rejected - IP rate limit: {ip_address} - {message}")
|
||||
@@ -868,7 +879,7 @@ async def enroll_beta_tester(
|
||||
detail="Too many beta enrollments from your location. Please try again tomorrow."
|
||||
)
|
||||
|
||||
# 4. Check for duplicate enrollment via normalized email
|
||||
# 5. Check for duplicate enrollment via normalized email
|
||||
normalized_email = email_validation.normalize_email(email)
|
||||
if normalized_email != email:
|
||||
# Check if normalized version is already enrolled
|
||||
|
||||
@@ -111,6 +111,9 @@ class Settings(BaseSettings):
|
||||
rate_limit_youtube_uploads_per_day: int = int(os.getenv("RATE_LIMIT_YOUTUBE_UPLOADS_PER_DAY", "10"))
|
||||
# Maximum beta enrollments from same IP per day (0 = unlimited)
|
||||
rate_limit_beta_ip_per_day: int = int(os.getenv("RATE_LIMIT_BETA_IP_PER_DAY", "1"))
|
||||
|
||||
# E2E test bypass key for rate limiting (set via secret in production)
|
||||
e2e_bypass_key: str = os.getenv("E2E_BYPASS_KEY", "")
|
||||
default_youtube_description: str = os.getenv(
|
||||
"DEFAULT_YOUTUBE_DESCRIPTION",
|
||||
"Karaoke video created with Nomad Karaoke (https://nomadkaraoke.com)\n\n"
|
||||
|
||||
@@ -40,6 +40,9 @@ class EncodingInput:
|
||||
# Output directory
|
||||
output_dir: str = ""
|
||||
|
||||
# Instrumental selection (clean, with_backing, or custom)
|
||||
instrumental_selection: str = "clean"
|
||||
|
||||
# Additional options
|
||||
options: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@@ -328,6 +331,7 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
"formats": ["mp4_4k_lossless", "mp4_4k_lossy", "mkv_4k", "mp4_720p"],
|
||||
"artist": input_config.artist,
|
||||
"title": input_config.title,
|
||||
"instrumental_selection": input_config.instrumental_selection,
|
||||
}
|
||||
|
||||
# Submit and wait for completion
|
||||
|
||||
@@ -374,22 +374,22 @@ class JobManager:
|
||||
updates['progress'] = progress
|
||||
|
||||
# Generate review token when entering AWAITING_REVIEW state
|
||||
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
|
||||
if new_status == JobStatus.AWAITING_REVIEW:
|
||||
from backend.api.dependencies import generate_review_token, get_review_token_expiry
|
||||
from backend.api.dependencies import generate_review_token
|
||||
review_token = generate_review_token()
|
||||
review_token_expires = get_review_token_expiry(hours=48) # 48 hour expiry
|
||||
updates['review_token'] = review_token
|
||||
updates['review_token_expires_at'] = review_token_expires
|
||||
logger.info(f"Generated review token for job {job_id}, expires in 48 hours")
|
||||
|
||||
updates['review_token_expires_at'] = None # No expiry - token is job-scoped
|
||||
logger.info(f"Generated review token for job {job_id} (no expiry)")
|
||||
|
||||
# Generate instrumental token when entering AWAITING_INSTRUMENTAL_SELECTION state
|
||||
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
|
||||
if new_status == JobStatus.AWAITING_INSTRUMENTAL_SELECTION:
|
||||
from backend.api.dependencies import generate_review_token, get_review_token_expiry
|
||||
from backend.api.dependencies import generate_review_token
|
||||
instrumental_token = generate_review_token() # Reuse same token generator
|
||||
instrumental_token_expires = get_review_token_expiry(hours=48) # 48 hour expiry
|
||||
updates['instrumental_token'] = instrumental_token
|
||||
updates['instrumental_token_expires_at'] = instrumental_token_expires
|
||||
logger.info(f"Generated instrumental token for job {job_id}, expires in 48 hours")
|
||||
updates['instrumental_token_expires_at'] = None # No expiry - token is job-scoped
|
||||
logger.info(f"Generated instrumental token for job {job_id} (no expiry)")
|
||||
|
||||
# If we have state_data_updates, merge them with existing state_data
|
||||
merged_state_data = None
|
||||
|
||||
@@ -11,6 +11,7 @@ from fastapi import FastAPI
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.models.user import User, Session
|
||||
|
||||
|
||||
@@ -20,15 +21,29 @@ app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency - returns admin user."""
|
||||
return ("admin@nomadkaraoke.com", "admin", 1)
|
||||
"""Override for require_admin dependency - returns admin AuthResult."""
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=-1,
|
||||
message="Admin session valid",
|
||||
user_email="admin@nomadkaraoke.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
def get_mock_regular_user():
|
||||
"""Override for require_admin dependency - returns regular user (should fail)."""
|
||||
# This simulates what happens when a non-admin tries to access
|
||||
# In reality, require_admin raises 403, but we test the logic
|
||||
return ("user@example.com", "user", 0)
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.LIMITED,
|
||||
remaining_uses=5,
|
||||
message="User session valid",
|
||||
user_email="user@example.com",
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -845,3 +845,192 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
)
|
||||
|
||||
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental User).mp3"
|
||||
|
||||
def test_create_config_passes_instrumental_selection(self):
|
||||
"""Test that instrumental_selection is passed through to OrchestratorConfig.
|
||||
|
||||
This is a REGRESSION TEST for the bug where orchestrator -> GCE encoding
|
||||
path did not pass instrumental_selection, causing GCE worker to default
|
||||
to 'clean' even when user selected 'with_backing'.
|
||||
|
||||
The bug was:
|
||||
- PR #271 fixed GCE worker to READ instrumental_selection from config
|
||||
- But the orchestrator path (encoding_interface.py) was never updated to SEND it
|
||||
- The legacy path (video_worker.py _encode_via_gce) was already correct
|
||||
- So the bug only manifested when USE_NEW_ORCHESTRATOR=true (the default)
|
||||
|
||||
See: fix(gce): Respect user's instrumental selection in GCE encoding worker (#271)
|
||||
"""
|
||||
job = MagicMock()
|
||||
job.job_id = "test-123"
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Title"
|
||||
job.state_data = {"instrumental_selection": "with_backing"} # User selected backing vocals
|
||||
job.enable_cdg = False
|
||||
job.enable_txt = False
|
||||
job.enable_youtube_upload = False
|
||||
job.brand_prefix = None
|
||||
job.discord_webhook_url = None
|
||||
job.youtube_description_template = None
|
||||
job.dropbox_path = None
|
||||
job.gdrive_folder_id = None
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
temp_dir="/tmp/test",
|
||||
)
|
||||
|
||||
# CRITICAL: instrumental_selection must be passed to OrchestratorConfig
|
||||
# If this fails, the GCE worker will default to 'clean' and ignore user's selection
|
||||
assert config.instrumental_selection == "with_backing", \
|
||||
"instrumental_selection must be passed from job.state_data to OrchestratorConfig"
|
||||
|
||||
# Also verify the instrumental path uses "Backing" not "Clean"
|
||||
assert "Backing" in config.instrumental_audio_path, \
|
||||
"When with_backing is selected, instrumental path should contain 'Backing'"
|
||||
|
||||
|
||||
class TestInstrumentalSelectionEndToEnd:
|
||||
"""End-to-end tests for instrumental selection flow.
|
||||
|
||||
These tests verify that instrumental_selection flows correctly from:
|
||||
job.state_data -> OrchestratorConfig -> EncodingInput -> GCE encoding_config
|
||||
|
||||
This test class was added after discovering that PR #271 only fixed the
|
||||
GCE worker (receiving side) but not the orchestrator (sending side),
|
||||
causing the bug to persist in production where USE_NEW_ORCHESTRATOR=true.
|
||||
"""
|
||||
|
||||
def test_encoding_input_has_instrumental_selection_field(self):
|
||||
"""Test that EncodingInput dataclass includes instrumental_selection.
|
||||
|
||||
Without this field, the orchestrator cannot pass the selection to
|
||||
the encoding backend.
|
||||
"""
|
||||
from backend.services.encoding_interface import EncodingInput
|
||||
|
||||
# Test with explicit selection
|
||||
input_with_backing = EncodingInput(
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
instrumental_selection="with_backing",
|
||||
)
|
||||
assert input_with_backing.instrumental_selection == "with_backing"
|
||||
|
||||
# Test default value
|
||||
input_default = EncodingInput(
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
)
|
||||
assert input_default.instrumental_selection == "clean", \
|
||||
"Default instrumental_selection should be 'clean' for backward compatibility"
|
||||
|
||||
def test_orchestrator_config_has_instrumental_selection_field(self):
|
||||
"""Test that OrchestratorConfig includes instrumental_selection."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
instrumental_selection="with_backing",
|
||||
)
|
||||
assert config.instrumental_selection == "with_backing"
|
||||
|
||||
# Test default
|
||||
config_default = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
)
|
||||
assert config_default.instrumental_selection == "clean"
|
||||
|
||||
def test_gce_encoding_config_includes_instrumental_selection(self):
|
||||
"""Test that GCEEncodingBackend passes instrumental_selection to encoding_config.
|
||||
|
||||
This is the CRITICAL test that would have caught the bug in PR #271.
|
||||
The GCE worker reads config.get("instrumental_selection", "clean"),
|
||||
so if we don't send it, it defaults to 'clean' regardless of user selection.
|
||||
"""
|
||||
from backend.services.encoding_interface import EncodingInput, GCEEncodingBackend
|
||||
|
||||
backend = GCEEncodingBackend(dry_run=True)
|
||||
|
||||
# Create input with 'with_backing' selection
|
||||
encoding_input = EncodingInput(
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
instrumental_selection="with_backing",
|
||||
options={
|
||||
"job_id": "test-123",
|
||||
"input_gcs_path": "gs://bucket/jobs/test-123/",
|
||||
"output_gcs_path": "gs://bucket/jobs/test-123/finals/",
|
||||
},
|
||||
)
|
||||
|
||||
# We can't easily test the actual encoding_config dict without mocking
|
||||
# the service, but we can verify the input has the right value
|
||||
assert encoding_input.instrumental_selection == "with_backing"
|
||||
|
||||
# The fix ensures GCEEncodingBackend.encode() includes this in encoding_config:
|
||||
# encoding_config = {
|
||||
# ...
|
||||
# "instrumental_selection": input_config.instrumental_selection,
|
||||
# }
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_orchestrator_passes_instrumental_selection_to_encoding(self):
|
||||
"""Test full flow: orchestrator creates EncodingInput with instrumental_selection.
|
||||
|
||||
This integration test verifies the complete path:
|
||||
OrchestratorConfig.instrumental_selection -> EncodingInput.instrumental_selection
|
||||
"""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
output_dir="/output",
|
||||
instrumental_selection="with_backing",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Capture the EncodingInput that gets passed to the backend
|
||||
captured_input = None
|
||||
|
||||
async def capture_encode(encoding_input):
|
||||
nonlocal captured_input
|
||||
captured_input = encoding_input
|
||||
from backend.services.encoding_interface import EncodingOutput
|
||||
return EncodingOutput(
|
||||
success=True,
|
||||
lossless_4k_mp4_path="/output/lossless.mp4",
|
||||
encoding_time_seconds=1.0,
|
||||
encoding_backend="mock",
|
||||
)
|
||||
|
||||
with patch.object(orchestrator, "_get_encoding_backend") as mock_get:
|
||||
mock_backend = MagicMock()
|
||||
mock_backend.name = "mock"
|
||||
mock_backend.encode = capture_encode
|
||||
mock_get.return_value = mock_backend
|
||||
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
# CRITICAL ASSERTION: instrumental_selection must be passed through
|
||||
assert captured_input is not None, "encode() should have been called"
|
||||
assert captured_input.instrumental_selection == "with_backing", \
|
||||
"Orchestrator must pass instrumental_selection to EncodingInput"
|
||||
@@ -69,6 +69,9 @@ class OrchestratorConfig:
|
||||
# Keep existing brand code (for re-processing)
|
||||
keep_brand_code: Optional[str] = None
|
||||
|
||||
# Instrumental selection (clean, with_backing, or custom)
|
||||
instrumental_selection: str = "clean"
|
||||
|
||||
# Encoding backend preference
|
||||
encoding_backend: str = "auto" # "auto", "local", "gce"
|
||||
|
||||
@@ -347,6 +350,7 @@ class VideoWorkerOrchestrator:
|
||||
title=self.config.title,
|
||||
brand_code=self.config.keep_brand_code,
|
||||
output_dir=self.config.output_dir,
|
||||
instrumental_selection=self.config.instrumental_selection,
|
||||
options={
|
||||
"job_id": self.config.job_id,
|
||||
"input_gcs_path": input_gcs_path,
|
||||
@@ -734,6 +738,9 @@ def create_orchestrator_config_from_job(
|
||||
# Keep existing brand code
|
||||
keep_brand_code=getattr(job, 'keep_brand_code', None),
|
||||
|
||||
# Instrumental selection (for GCE encoding)
|
||||
instrumental_selection=instrumental_selection,
|
||||
|
||||
# Encoding backend - auto selects GCE if available
|
||||
encoding_backend="auto",
|
||||
|
||||
|
||||
@@ -39,6 +39,9 @@ When UI removes options, backend must apply sensible defaults. Don't rely on eac
|
||||
### Centralize Job Creation Logic
|
||||
When multiple code paths create jobs (file upload, audio search, webhooks), use a shared service for default resolution. The made-for-you webhook handler diverged from regular job creation, missing CDG/TXT defaults because it didn't call the shared `resolve_cdg_txt_defaults()` function. Fix: Create `job_defaults_service.py` with centralized helpers used by ALL job creation paths.
|
||||
|
||||
### Fix Both Sides of Dual Code Paths
|
||||
When fixing a bug in a system with multiple code paths (e.g., legacy vs orchestrator, local vs cloud), verify ALL paths are fixed. PR #271 fixed the GCE worker to READ `instrumental_selection` but only checked the legacy path which was already SENDING it. The orchestrator path (production default) wasn't sending it. **Pattern**: If a component receives config from multiple callers, check ALL callers when fixing the receiving side. Write integration tests that cover each path.
|
||||
|
||||
### Defense in Depth
|
||||
Enforce critical requirements at multiple layers (e.g., reject at creation in JobManager + safety net at processing time).
|
||||
|
||||
@@ -48,6 +51,9 @@ HTTP calls to services that can restart (VMs, containers) need retry logic with
|
||||
### Cross-Domain localStorage
|
||||
Auth tokens in localStorage are domain-isolated. Keep auth on a single domain or use cookies with `domain=.example.com`.
|
||||
|
||||
### Standalone HTML Pages Need Auth Fallback
|
||||
Standalone HTML pages (like instrumental review) that use magic link tokens should also check localStorage for user auth tokens. Priority: full auth token (doesn't expire) > magic link token (expires). This prevents logged-in users from being blocked when their magic link expires.
|
||||
|
||||
### Tab Visibility Refresh
|
||||
Use `visibilitychange` event for immediate refresh when user returns to tab, not just polling intervals.
|
||||
|
||||
@@ -72,6 +78,12 @@ Sanitize user input (artist/title) to ASCII for HTTP headers. Smart quotes, em d
|
||||
### Fonts in Docker
|
||||
Base Docker images have no fonts. Install `fonts-noto-core`, `fonts-noto-cjk` for video rendering.
|
||||
|
||||
### Cloud Run CPU Throttling Kills Background Tasks
|
||||
Cloud Run throttles CPU to near-zero when the main request handler returns, even if background tasks are running. This caused lyrics processing (running as a FastAPI background task) to slow from 17-52 seconds to 8+ minutes, and instances being terminated mid-processing. **Fix**: Add `--no-cpu-throttling` flag to `gcloud run deploy`. Keep `--cpu-boost` for faster cold starts. **Diagnosis**: Look for "Application shutdown" in logs during long operations, and compare processing times (27x slowdown is a telltale sign).
|
||||
|
||||
### Add Progress Logging for Long Operations
|
||||
Operations over ~30 seconds should log progress periodically (time-based, not count-based). Count-based logging like "log every 20 items" can miss entirely if items complete slowly. Time-based logging (every 30s) ensures visibility regardless of processing speed.
|
||||
|
||||
---
|
||||
|
||||
### AuthResult Has Tuple Unpacking But Not Subscripting
|
||||
@@ -148,6 +160,9 @@ Use `pulumi up --skip-preview --yes` when CI service account can't run preview.
|
||||
### Docker Disk Management
|
||||
Self-hosted runners need aggressive disk cleanup. Use threshold-based (70%) not age-based cleanup.
|
||||
|
||||
### Version Sort for Artifact Selection
|
||||
When downloading multiple versioned files (wheels, tarballs), use `sort -V | tail -1` not `ls -t | head -1`. Files downloaded simultaneously have the same timestamp, so time-based sorting picks arbitrarily. Version sorting (`sort -V`) correctly identifies the highest semantic version.
|
||||
|
||||
---
|
||||
|
||||
## Performance Patterns
|
||||
@@ -240,3 +255,4 @@ When mocking tenant middleware, patch both the middleware import path AND the se
|
||||
3. **Design for async human review upfront** - Avoided rearchitecting later
|
||||
4. **Keep docs minimal and current** - Less documentation, always accurate
|
||||
5. **Check gitignore early for new directories** - Especially frontend `lib/` dirs
|
||||
|
||||
@@ -70,6 +70,9 @@ export default function AdminUsersPage() {
|
||||
const [creditReason, setCreditReason] = useState("")
|
||||
const [addingCredits, setAddingCredits] = useState(false)
|
||||
|
||||
// Impersonation state - tracks which user is being impersonated (for loading indicator)
|
||||
const [impersonatingEmail, setImpersonatingEmail] = useState<string | null>(null)
|
||||
|
||||
const loadUsers = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
@@ -158,6 +161,7 @@ export default function AdminUsersPage() {
|
||||
return
|
||||
}
|
||||
|
||||
setImpersonatingEmail(user.email)
|
||||
try {
|
||||
const success = await startImpersonation(user.email)
|
||||
if (success) {
|
||||
@@ -167,6 +171,14 @@ export default function AdminUsersPage() {
|
||||
})
|
||||
// Redirect to main app to see the user's view
|
||||
router.push("/app")
|
||||
} else {
|
||||
// startImpersonation returned false - get the error from auth store
|
||||
const authError = useAuth.getState().error
|
||||
toast({
|
||||
title: "Impersonation Failed",
|
||||
description: authError || "Unable to impersonate user. Please try again.",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
@@ -174,6 +186,8 @@ export default function AdminUsersPage() {
|
||||
description: err.message || "Failed to impersonate user",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setImpersonatingEmail(null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,9 +312,13 @@ export default function AdminUsersPage() {
|
||||
size="icon"
|
||||
onClick={() => handleImpersonate(user)}
|
||||
title="Impersonate user"
|
||||
disabled={user.email === currentUser?.email}
|
||||
disabled={user.email === currentUser?.email || impersonatingEmail !== null}
|
||||
>
|
||||
<LogIn className="w-4 h-4" />
|
||||
{impersonatingEmail === user.email ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<LogIn className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
@@ -236,7 +236,7 @@ function AppPageContent() {
|
||||
<p>No jobs yet. Create one to get started!</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3 max-h-[500px] overflow-y-auto pr-2">
|
||||
<div className="space-y-3">
|
||||
{jobs.map((job) => (
|
||||
<JobCard key={job.job_id} job={job} onRefresh={loadJobs} />
|
||||
))}
|
||||
|
||||
@@ -210,7 +210,7 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
|
||||
{/* Output links for completed jobs */}
|
||||
{isComplete && (
|
||||
<div className="mt-2">
|
||||
<OutputLinks jobId={job.job_id} />
|
||||
<OutputLinks job={job} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useRef, useCallback } from "react"
|
||||
import { api, adminApi } from "@/lib/api"
|
||||
import { useRef, useCallback, useEffect, useState } from "react"
|
||||
import { api, adminApi, Job } from "@/lib/api"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings } from "lucide-react"
|
||||
@@ -18,14 +18,16 @@ import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
interface OutputLinksProps {
|
||||
jobId: string
|
||||
job: Job
|
||||
}
|
||||
|
||||
export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
const [downloadUrls, setDownloadUrls] = useState<Record<string, any> | null>(null)
|
||||
const [youtubeUrl, setYoutubeUrl] = useState<string | null>(null)
|
||||
const [dropboxUrl, setDropboxUrl] = useState<string | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
export function OutputLinks({ job }: OutputLinksProps) {
|
||||
// Use file_urls from job directly - no API call needed
|
||||
const downloadUrls = job.file_urls || null
|
||||
// Use state_data from job directly - no API call needed
|
||||
const youtubeUrl = job.state_data?.youtube_url || null
|
||||
const dropboxUrl = job.state_data?.dropbox_link || null
|
||||
|
||||
const [copiedUrl, setCopiedUrl] = useState<string | null>(null)
|
||||
const [copiedMessage, setCopiedMessage] = useState(false)
|
||||
const [isLoadingMessage, setIsLoadingMessage] = useState(false)
|
||||
@@ -37,6 +39,15 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
const messageTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const emailTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
|
||||
// Cleanup timeouts on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (copyTimeoutRef.current) clearTimeout(copyTimeoutRef.current)
|
||||
if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current)
|
||||
if (emailTimeoutRef.current) clearTimeout(emailTimeoutRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const { user } = useAuth()
|
||||
const { features } = useTenant()
|
||||
const isAdmin = user?.role === 'admin'
|
||||
@@ -45,46 +56,6 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
const showYoutubeLink = features.youtube_upload && youtubeUrl
|
||||
const showDropboxLink = features.dropbox_upload && dropboxUrl
|
||||
|
||||
useEffect(() => {
|
||||
loadOutputLinks()
|
||||
}, [jobId])
|
||||
|
||||
// Cleanup timeouts on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (copyTimeoutRef.current) {
|
||||
clearTimeout(copyTimeoutRef.current)
|
||||
}
|
||||
if (messageTimeoutRef.current) {
|
||||
clearTimeout(messageTimeoutRef.current)
|
||||
}
|
||||
if (emailTimeoutRef.current) {
|
||||
clearTimeout(emailTimeoutRef.current)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function loadOutputLinks() {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const result = await api.getDownloadUrls(jobId)
|
||||
setDownloadUrls(result.download_urls)
|
||||
|
||||
// Extract YouTube and Dropbox URLs from state_data if available
|
||||
const job = await api.getJob(jobId)
|
||||
if (job.state_data?.youtube_url) {
|
||||
setYoutubeUrl(job.state_data.youtube_url)
|
||||
}
|
||||
if (job.state_data?.dropbox_link) {
|
||||
setDropboxUrl(job.state_data.dropbox_link)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to load output links:", err)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = useCallback(async (url: string) => {
|
||||
// Check if clipboard API is available
|
||||
if (!navigator?.clipboard?.writeText) {
|
||||
@@ -118,7 +89,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
|
||||
setIsLoadingMessage(true)
|
||||
try {
|
||||
const response = await adminApi.getCompletionMessage(jobId)
|
||||
const response = await adminApi.getCompletionMessage(job.job_id)
|
||||
await navigator.clipboard.writeText(response.message)
|
||||
setCopiedMessage(true)
|
||||
|
||||
@@ -136,14 +107,14 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
} finally {
|
||||
setIsLoadingMessage(false)
|
||||
}
|
||||
}, [jobId])
|
||||
}, [job.job_id])
|
||||
|
||||
const handleSendEmail = useCallback(async () => {
|
||||
if (!emailInput.trim()) return
|
||||
|
||||
setIsSendingEmail(true)
|
||||
try {
|
||||
await adminApi.sendCompletionEmail(jobId, emailInput.trim(), true)
|
||||
await adminApi.sendCompletionEmail(job.job_id, emailInput.trim(), true)
|
||||
setEmailSent(true)
|
||||
|
||||
// Clear any existing timeout
|
||||
@@ -162,16 +133,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
} finally {
|
||||
setIsSendingEmail(false)
|
||||
}
|
||||
}, [jobId, emailInput])
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
Loading downloads...
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}, [job.job_id, emailInput])
|
||||
|
||||
const hasOutputs = showYoutubeLink || showDropboxLink || (downloadUrls && Object.keys(downloadUrls).length > 0)
|
||||
|
||||
@@ -249,7 +211,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
<>
|
||||
{downloadUrls?.finals?.lossy_4k_mp4 && (
|
||||
<a
|
||||
href={api.getDownloadUrl(jobId, "finals", "lossy_4k_mp4")}
|
||||
href={api.getDownloadUrl(job.job_id, "finals", "lossy_4k_mp4")}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white transition-colors"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
@@ -259,7 +221,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
)}
|
||||
{downloadUrls?.finals?.lossy_720p_mp4 && (
|
||||
<a
|
||||
href={api.getDownloadUrl(jobId, "finals", "lossy_720p_mp4")}
|
||||
href={api.getDownloadUrl(job.job_id, "finals", "lossy_720p_mp4")}
|
||||
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()}
|
||||
>
|
||||
@@ -269,7 +231,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
)}
|
||||
{downloadUrls?.videos?.with_vocals && (
|
||||
<a
|
||||
href={api.getDownloadUrl(jobId, "videos", "with_vocals")}
|
||||
href={api.getDownloadUrl(job.job_id, "videos", "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()}
|
||||
>
|
||||
@@ -279,7 +241,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
)}
|
||||
{downloadUrls?.packages?.cdg_zip && (
|
||||
<a
|
||||
href={api.getDownloadUrl(jobId, "packages", "cdg_zip")}
|
||||
href={api.getDownloadUrl(job.job_id, "packages", "cdg_zip")}
|
||||
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()}
|
||||
>
|
||||
@@ -289,7 +251,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
)}
|
||||
{downloadUrls?.packages?.txt_zip && (
|
||||
<a
|
||||
href={api.getDownloadUrl(jobId, "packages", "txt_zip")}
|
||||
href={api.getDownloadUrl(job.job_id, "packages", "txt_zip")}
|
||||
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()}
|
||||
>
|
||||
@@ -330,7 +292,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
|
||||
</button>
|
||||
</div>
|
||||
<a
|
||||
href={`/admin/jobs/?id=${jobId}`}
|
||||
href={`/admin/jobs/?id=${job.job_id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
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"
|
||||
title="View job details in admin"
|
||||
|
||||
@@ -305,6 +305,21 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
await page.screenshot({ path: 'test-results/02a-beta-form-filled.png' });
|
||||
console.log(' Beta form filled');
|
||||
|
||||
// Intercept the beta enrollment request to add E2E bypass header
|
||||
// This bypasses the IP-based rate limit that blocks repeated enrollments from the same IP
|
||||
const bypassKey = process.env.E2E_BYPASS_KEY;
|
||||
if (bypassKey) {
|
||||
console.log(' Adding E2E bypass header to enrollment request');
|
||||
await page.route('**/api/users/beta/enroll', async (route) => {
|
||||
const request = route.request();
|
||||
const headers = {
|
||||
...request.headers(),
|
||||
'X-E2E-Bypass-Key': bypassKey,
|
||||
};
|
||||
await route.continue({ headers });
|
||||
});
|
||||
}
|
||||
|
||||
// Submit form - look for the submit button
|
||||
const submitButton = page.getByRole('button', { name: /get.*free.*credit|submit|enroll/i });
|
||||
await expect(submitButton).toBeEnabled({ timeout: TIMEOUTS.action });
|
||||
|
||||
@@ -190,6 +190,86 @@ test.describe('User Impersonation', () => {
|
||||
const impersonateButton = adminRow.locator('button[title="Impersonate user"]');
|
||||
await expect(impersonateButton).toBeDisabled();
|
||||
});
|
||||
|
||||
test('clicking impersonate button makes API call', async ({ page }) => {
|
||||
await setAuthToken(page, 'admin-test-token');
|
||||
|
||||
// Track if impersonate API was called
|
||||
const impersonateCalls: string[] = [];
|
||||
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/users/me',
|
||||
response: { body: { user: mockAdminUser } },
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/users/admin/users',
|
||||
response: { body: mockUserList },
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/tenant/config',
|
||||
response: { body: { brand_code: null, is_white_label: false } },
|
||||
},
|
||||
// Mock the impersonate endpoint
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/admin/users/:email/impersonate',
|
||||
response: {
|
||||
body: {
|
||||
session_token: 'impersonation-token-123',
|
||||
user_email: 'user@example.com',
|
||||
message: 'Impersonation started',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Also add a listener to track the actual impersonate call
|
||||
await page.route('**/api/admin/users/*/impersonate', async (route) => {
|
||||
const url = route.request().url();
|
||||
const match = url.match(/\/api\/admin\/users\/([^/]+)\/impersonate/);
|
||||
if (match) {
|
||||
impersonateCalls.push(decodeURIComponent(match[1]));
|
||||
}
|
||||
// Continue to the mock server
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
session_token: 'impersonation-token-123',
|
||||
user_email: decodeURIComponent(match?.[1] || ''),
|
||||
message: 'Impersonation started',
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto('/admin/users');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Find the row for the target user (not admin)
|
||||
const targetUserRow = page.locator('tr').filter({ hasText: 'user@example.com' });
|
||||
await expect(targetUserRow).toBeVisible();
|
||||
|
||||
// Get the impersonate button
|
||||
const impersonateButton = targetUserRow.locator('button[title="Impersonate user"]');
|
||||
await expect(impersonateButton).toBeVisible();
|
||||
await expect(impersonateButton).toBeEnabled();
|
||||
|
||||
// Click the impersonate button
|
||||
await impersonateButton.click();
|
||||
|
||||
// Wait a bit for the API call to be made
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Verify the API was called
|
||||
expect(impersonateCalls.length).toBeGreaterThan(0);
|
||||
expect(impersonateCalls[0]).toBe('user@example.com');
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Impersonation Security', () => {
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 430 KiB After Width: | Height: | Size: 463 KiB |
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Service Worker for Web Push Notifications
|
||||
*
|
||||
* Handles push events and notification clicks for the Karaoke Generator PWA.
|
||||
* This service worker is registered by the ServiceWorkerRegistration component.
|
||||
*/
|
||||
|
||||
// Cache name for static assets (versioned for updates)
|
||||
const CACHE_VERSION = 'v1';
|
||||
const STATIC_CACHE = `karaoke-gen-static-${CACHE_VERSION}`;
|
||||
|
||||
// Assets to cache for offline support
|
||||
const STATIC_ASSETS = [
|
||||
'/nomad-logo.png',
|
||||
'/nomad-karaoke-logo.svg',
|
||||
'/favicon.ico',
|
||||
];
|
||||
|
||||
/**
|
||||
* Install event - cache static assets
|
||||
*/
|
||||
self.addEventListener('install', (event) => {
|
||||
console.log('[SW] Installing service worker...');
|
||||
event.waitUntil(
|
||||
caches.open(STATIC_CACHE).then((cache) => {
|
||||
return cache.addAll(STATIC_ASSETS);
|
||||
}).then(() => {
|
||||
console.log('[SW] Static assets cached');
|
||||
return self.skipWaiting(); // Activate immediately
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Activate event - clean up old caches
|
||||
*/
|
||||
self.addEventListener('activate', (event) => {
|
||||
console.log('[SW] Activating service worker...');
|
||||
event.waitUntil(
|
||||
caches.keys().then((cacheNames) => {
|
||||
return Promise.all(
|
||||
cacheNames
|
||||
.filter((name) => name.startsWith('karaoke-gen-') && name !== STATIC_CACHE)
|
||||
.map((name) => {
|
||||
console.log('[SW] Deleting old cache:', name);
|
||||
return caches.delete(name);
|
||||
})
|
||||
);
|
||||
}).then(() => {
|
||||
console.log('[SW] Service worker activated');
|
||||
return self.clients.claim(); // Take control of all pages
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Push event - show notification when push message received
|
||||
*/
|
||||
self.addEventListener('push', (event) => {
|
||||
console.log('[SW] Push event received');
|
||||
|
||||
let data = {
|
||||
title: 'Karaoke Generator',
|
||||
body: 'You have a notification',
|
||||
icon: '/nomad-logo.png',
|
||||
tag: 'default',
|
||||
url: '/app/',
|
||||
};
|
||||
|
||||
// Parse push data if available
|
||||
if (event.data) {
|
||||
try {
|
||||
const payload = event.data.json();
|
||||
data = {
|
||||
title: payload.title || data.title,
|
||||
body: payload.body || data.body,
|
||||
icon: payload.icon || data.icon,
|
||||
tag: payload.tag || data.tag,
|
||||
url: payload.url || data.url,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('[SW] Error parsing push data:', err);
|
||||
// Try as text
|
||||
const text = event.data.text();
|
||||
if (text) {
|
||||
data.body = text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Show the notification
|
||||
const options = {
|
||||
body: data.body,
|
||||
icon: data.icon,
|
||||
badge: '/favicon-32x32.png',
|
||||
tag: data.tag, // Replaces notifications with same tag
|
||||
renotify: true, // Vibrate/sound even if replacing
|
||||
requireInteraction: true, // Don't auto-dismiss
|
||||
data: {
|
||||
url: data.url,
|
||||
},
|
||||
// Actions for the notification (optional)
|
||||
actions: [
|
||||
{
|
||||
action: 'open',
|
||||
title: 'Open',
|
||||
},
|
||||
{
|
||||
action: 'dismiss',
|
||||
title: 'Dismiss',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(data.title, options)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Notification click event - open the app or focus existing window
|
||||
*/
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
console.log('[SW] Notification clicked:', event.action);
|
||||
|
||||
event.notification.close();
|
||||
|
||||
// Handle dismiss action
|
||||
if (event.action === 'dismiss') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the URL to open
|
||||
const url = event.notification.data?.url || '/app/';
|
||||
const fullUrl = new URL(url, self.location.origin).href;
|
||||
|
||||
// Try to focus an existing window or open a new one
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
|
||||
// Check if there's already a window open
|
||||
for (const client of clients) {
|
||||
// If we find a matching URL, focus it
|
||||
if (client.url === fullUrl && 'focus' in client) {
|
||||
return client.focus();
|
||||
}
|
||||
}
|
||||
|
||||
// Check if there's any window from our origin
|
||||
for (const client of clients) {
|
||||
if (client.url.startsWith(self.location.origin) && 'focus' in client) {
|
||||
// Navigate the existing window and focus it
|
||||
return client.navigate(fullUrl).then((client) => client?.focus());
|
||||
}
|
||||
}
|
||||
|
||||
// No existing window, open a new one
|
||||
if (self.clients.openWindow) {
|
||||
return self.clients.openWindow(fullUrl);
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Notification close event - cleanup if needed
|
||||
*/
|
||||
self.addEventListener('notificationclose', (event) => {
|
||||
console.log('[SW] Notification closed');
|
||||
// Could track analytics here if desired
|
||||
});
|
||||
|
||||
/**
|
||||
* Message event - handle messages from the main app
|
||||
*/
|
||||
self.addEventListener('message', (event) => {
|
||||
console.log('[SW] Message received:', event.data);
|
||||
|
||||
if (event.data?.type === 'SKIP_WAITING') {
|
||||
self.skipWaiting();
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[SW] Service worker loaded');
|
||||
@@ -124,7 +124,7 @@ echo -n "key" | gcloud secrets versions add genius-api-key --data-file=-
|
||||
echo -n "key" | gcloud secrets versions add red-api-key --data-file=-
|
||||
echo -n "url" | gcloud secrets versions add red-api-url --data-file=-
|
||||
|
||||
# GitHub runner PAT (repo scope)
|
||||
# GitHub runner PAT (admin:org scope for org-level runners)
|
||||
echo -n "ghp_xxx" | gcloud secrets versions add github-runner-pat --data-file=-
|
||||
```
|
||||
|
||||
@@ -146,12 +146,14 @@ Note: `deploy.sh` uploads the source ZIP to GCS. Pulumi creates the function res
|
||||
|
||||
## Self-Hosted GitHub Runners
|
||||
|
||||
20 GCP VMs serve as self-hosted runners with:
|
||||
20 GCP VMs serve as organization-level self-hosted runners, available to all repos in the `nomadkaraoke` org:
|
||||
- 200GB SSD (vs 14GB on GitHub-hosted)
|
||||
- Pre-installed: Docker, Python 3.13, Node 20, Java 21, FFmpeg
|
||||
- Labels: `self-hosted`, `linux`, `x64`, `gcp`, `large-disk`
|
||||
|
||||
**Usage in workflows:**
|
||||
**PAT Requirements:** The `github-runner-pat` secret requires `admin:org` scope (specifically `manage_runners:org`) for organization-level runner registration.
|
||||
|
||||
**Usage in workflows (any nomadkaraoke repo):**
|
||||
```yaml
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
```
|
||||
@@ -182,7 +184,7 @@ High-performance VM for video encoding:
|
||||
|
||||
**Troubleshooting:**
|
||||
```bash
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-a -- \
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c -- \
|
||||
"sudo systemctl status encoding-worker"
|
||||
```
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ from config import (
|
||||
DiskSizes,
|
||||
)
|
||||
from modules import database, storage as storage_module, artifact_registry, secrets
|
||||
from modules import cloud_tasks, cloud_run, monitoring
|
||||
from modules import cloud_tasks, cloud_run, monitoring, networking
|
||||
from modules.iam import backend_sa, github_actions_sa, claude_automation_sa, worker_sas
|
||||
from compute import flacfetch_vm, encoding_worker_vm, github_runners
|
||||
|
||||
@@ -58,6 +58,11 @@ all_secrets = secrets.create_secrets()
|
||||
# Cloud Tasks queues
|
||||
queues = cloud_tasks.create_queues()
|
||||
|
||||
# ==================== Networking ====================
|
||||
# VPC connector for Cloud Run to access internal resources (e.g., flacfetch VM)
|
||||
vpc_access_api = networking.enable_vpc_access_api()
|
||||
vpc_connector = networking.create_vpc_connector(vpc_access_api)
|
||||
|
||||
# ==================== Cloud Build IAM ====================
|
||||
# These bindings allow Cloud Build to access Artifact Registry and deploy as the backend SA
|
||||
|
||||
@@ -243,7 +248,14 @@ gdrive_validator_scheduler = cloudscheduler.Job(
|
||||
# Flacfetch VM (audio download service)
|
||||
flacfetch_ip = flacfetch_vm.create_flacfetch_ip()
|
||||
flacfetch_instance = flacfetch_vm.create_flacfetch_vm(flacfetch_ip, flacfetch_sa, bucket)
|
||||
flacfetch_firewall = flacfetch_vm.create_flacfetch_firewall()
|
||||
flacfetch_bittorrent_fw, flacfetch_api_fw = flacfetch_vm.create_flacfetch_firewall()
|
||||
|
||||
# Set flacfetch-api-url secret to use internal IP (requires VPC connector)
|
||||
flacfetch_url_version = secrets.create_flacfetch_internal_url_version(
|
||||
all_secrets["flacfetch-api-url"],
|
||||
flacfetch_instance,
|
||||
vpc_connector,
|
||||
)
|
||||
|
||||
# Encoding Worker VM (video encoding service)
|
||||
encoding_worker_ip = encoding_worker_vm.create_encoding_worker_ip()
|
||||
@@ -323,6 +335,10 @@ pulumi.export("gdrive_validator_function_name", gdrive_validator_function.name)
|
||||
pulumi.export("gdrive_validator_scheduler_name", gdrive_validator_scheduler.name)
|
||||
pulumi.export("gdrive_validator_service_account", gdrive_validator_sa.email)
|
||||
|
||||
# VPC networking
|
||||
pulumi.export("vpc_connector_name", vpc_connector.name)
|
||||
pulumi.export("vpc_connector_self_link", vpc_connector.self_link)
|
||||
|
||||
# Flacfetch
|
||||
pulumi.export("flacfetch_static_ip", flacfetch_ip.address)
|
||||
pulumi.export("flacfetch_service_url", flacfetch_ip.address.apply(lambda ip: f"http://{ip}:8080"))
|
||||
|
||||
@@ -11,6 +11,26 @@ from pulumi_gcp import compute, storage, serviceaccount
|
||||
from config import REGION, ZONE, MachineTypes, DiskSizes
|
||||
from .startup_scripts import read_script
|
||||
|
||||
# Cloudflare IP ranges for firewall rules
|
||||
# Source: https://www.cloudflare.com/ips-v4
|
||||
CLOUDFLARE_IP_RANGES = [
|
||||
"173.245.48.0/20",
|
||||
"103.21.244.0/22",
|
||||
"103.22.200.0/22",
|
||||
"103.31.4.0/22",
|
||||
"141.101.64.0/18",
|
||||
"108.162.192.0/18",
|
||||
"190.93.240.0/20",
|
||||
"188.114.96.0/20",
|
||||
"197.234.240.0/22",
|
||||
"198.41.128.0/17",
|
||||
"162.158.0.0/15",
|
||||
"104.16.0.0/13",
|
||||
"104.24.0.0/14",
|
||||
"172.64.0.0/13",
|
||||
"131.0.72.0/22",
|
||||
]
|
||||
|
||||
|
||||
def create_flacfetch_ip() -> compute.Address:
|
||||
"""
|
||||
@@ -79,27 +99,40 @@ def create_flacfetch_vm(
|
||||
)
|
||||
|
||||
|
||||
def create_flacfetch_firewall() -> compute.Firewall:
|
||||
def create_flacfetch_firewall() -> tuple[compute.Firewall, compute.Firewall]:
|
||||
"""
|
||||
Create firewall rules for flacfetch.
|
||||
|
||||
Opens ports for:
|
||||
- 51413 TCP/UDP: BitTorrent peer connections
|
||||
- 8080 TCP: HTTP API
|
||||
Creates two separate rules:
|
||||
- BitTorrent (51413 TCP/UDP): Open to all for peer connections
|
||||
- HTTP API (8080 TCP): Restricted to Cloudflare IPs only
|
||||
|
||||
Returns:
|
||||
compute.Firewall: The firewall resource.
|
||||
tuple: (bittorrent_firewall, api_firewall) resources.
|
||||
"""
|
||||
return compute.Firewall(
|
||||
"flacfetch-firewall",
|
||||
name="flacfetch-firewall",
|
||||
bittorrent_firewall = compute.Firewall(
|
||||
"flacfetch-bittorrent-firewall",
|
||||
name="flacfetch-bittorrent",
|
||||
network="default",
|
||||
allows=[
|
||||
compute.FirewallAllowArgs(protocol="tcp", ports=["51413"]),
|
||||
compute.FirewallAllowArgs(protocol="udp", ports=["51413"]),
|
||||
compute.FirewallAllowArgs(protocol="tcp", ports=["8080"]),
|
||||
],
|
||||
source_ranges=["0.0.0.0/0"],
|
||||
target_tags=["flacfetch-service"],
|
||||
description="Firewall rules for flacfetch torrent/API service",
|
||||
description="BitTorrent peer connections for flacfetch (open to all)",
|
||||
)
|
||||
|
||||
api_firewall = compute.Firewall(
|
||||
"flacfetch-api-firewall",
|
||||
name="flacfetch-api",
|
||||
network="default",
|
||||
allows=[
|
||||
compute.FirewallAllowArgs(protocol="tcp", ports=["8080"]),
|
||||
],
|
||||
source_ranges=CLOUDFLARE_IP_RANGES,
|
||||
target_tags=["flacfetch-service"],
|
||||
description="HTTP API for flacfetch (Cloudflare IPs only)",
|
||||
)
|
||||
|
||||
return bittorrent_firewall, api_firewall
|
||||
@@ -20,7 +20,7 @@ def create_github_runners(
|
||||
Create GitHub Actions self-hosted runner VM instances.
|
||||
|
||||
Creates NUM_GITHUB_RUNNERS VMs, each configured as a GitHub Actions
|
||||
self-hosted runner for the karaoke-gen repository.
|
||||
self-hosted runner for the nomadkaraoke organization (available to all repos).
|
||||
|
||||
Args:
|
||||
service_account: The GitHub runner service account.
|
||||
|
||||
@@ -124,23 +124,23 @@ if [ -z "$GITHUB_PAT" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get runner registration token using PAT
|
||||
# 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/repos/nomadkaraoke/karaoke-gen/actions/runners/registration-token | jq -r .token)
|
||||
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
|
||||
|
||||
# Configure runner (non-interactive)
|
||||
# Configure runner (non-interactive) - registered at organization level
|
||||
echo "Configuring runner..."
|
||||
cd $RUNNER_DIR
|
||||
sudo -u runner ./config.sh \
|
||||
--url https://github.com/nomadkaraoke/karaoke-gen \
|
||||
--url https://github.com/nomadkaraoke \
|
||||
--token "$REGISTRATION_TOKEN" \
|
||||
--name "gcp-runner-$(hostname)" \
|
||||
--labels "self-hosted,linux,x64,gcp,large-disk" \
|
||||
@@ -154,7 +154,7 @@ echo "Installing runner service..."
|
||||
./svc.sh start
|
||||
|
||||
echo "GitHub Actions runner setup complete at $(date)"
|
||||
echo "Runner registered with labels: self-hosted,linux,x64,gcp,large-disk"
|
||||
echo "Runner registered at organization level (nomadkaraoke) with labels: self-hosted,linux,x64,gcp,large-disk"
|
||||
|
||||
# ==================== Setup Python in tool cache ====================
|
||||
# setup-python action looks for Python in RUNNER_TOOL_CACHE/_tool/Python
|
||||
|
||||
@@ -12,6 +12,7 @@ from . import cloud_tasks
|
||||
from . import cloud_run
|
||||
from . import monitoring
|
||||
from . import iam
|
||||
from . import networking
|
||||
|
||||
__all__ = [
|
||||
"database",
|
||||
@@ -22,4 +23,5 @@ __all__ = [
|
||||
"cloud_run",
|
||||
"monitoring",
|
||||
"iam",
|
||||
"networking",
|
||||
]
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
Networking resources for serverless VPC access.
|
||||
|
||||
Manages VPC connectors that allow Cloud Run to access internal VPC resources
|
||||
like the flacfetch VM via its internal IP address.
|
||||
"""
|
||||
|
||||
import pulumi
|
||||
import pulumi_gcp as gcp
|
||||
from pulumi_gcp import vpcaccess
|
||||
|
||||
from config import PROJECT_ID, REGION
|
||||
|
||||
|
||||
def enable_vpc_access_api() -> gcp.projects.Service:
|
||||
"""Enable the Serverless VPC Access API."""
|
||||
return gcp.projects.Service(
|
||||
"enable-vpcaccess-api",
|
||||
service="vpcaccess.googleapis.com",
|
||||
project=PROJECT_ID,
|
||||
disable_on_destroy=False,
|
||||
)
|
||||
|
||||
|
||||
def create_vpc_connector(
|
||||
api_service: gcp.projects.Service,
|
||||
) -> vpcaccess.Connector:
|
||||
"""
|
||||
Create VPC connector for Cloud Run to access internal resources.
|
||||
|
||||
Uses 10.8.0.0/28 which doesn't overlap with default subnet (10.128.0.0/20).
|
||||
This allows Cloud Run to reach VMs like flacfetch via their internal IPs,
|
||||
bypassing external firewall rules.
|
||||
|
||||
Args:
|
||||
api_service: The VPC Access API service (ensures API is enabled first).
|
||||
|
||||
Returns:
|
||||
vpcaccess.Connector: The VPC connector resource.
|
||||
"""
|
||||
return vpcaccess.Connector(
|
||||
"cloud-run-vpc-connector",
|
||||
name="cloud-run-connector",
|
||||
region=REGION,
|
||||
network="default",
|
||||
ip_cidr_range="10.8.0.0/28",
|
||||
min_instances=2,
|
||||
max_instances=3,
|
||||
machine_type="e2-micro",
|
||||
opts=pulumi.ResourceOptions(depends_on=[api_service]),
|
||||
)
|
||||
@@ -6,7 +6,8 @@ via gcloud or the Cloud Console after resources are created.
|
||||
"""
|
||||
|
||||
import pulumi
|
||||
from pulumi_gcp import secretmanager
|
||||
import pulumi_gcp as gcp
|
||||
from pulumi_gcp import secretmanager, vpcaccess
|
||||
|
||||
|
||||
def create_secrets() -> dict[str, secretmanager.Secret]:
|
||||
@@ -53,6 +54,9 @@ def create_secrets() -> dict[str, secretmanager.Secret]:
|
||||
|
||||
# GitHub
|
||||
"github-runner-pat",
|
||||
|
||||
# E2E Testing
|
||||
"e2e-bypass-key",
|
||||
]
|
||||
|
||||
secrets = {}
|
||||
@@ -67,3 +71,34 @@ def create_secrets() -> dict[str, secretmanager.Secret]:
|
||||
)
|
||||
|
||||
return secrets
|
||||
|
||||
|
||||
def create_flacfetch_internal_url_version(
|
||||
secret: secretmanager.Secret,
|
||||
flacfetch_instance: gcp.compute.Instance,
|
||||
vpc_connector: vpcaccess.Connector,
|
||||
) -> secretmanager.SecretVersion:
|
||||
"""
|
||||
Set flacfetch-api-url secret to use internal IP.
|
||||
|
||||
This allows Cloud Run to reach flacfetch via the VPC connector,
|
||||
bypassing the external firewall that restricts access to Cloudflare IPs.
|
||||
|
||||
Args:
|
||||
secret: The flacfetch-api-url secret.
|
||||
flacfetch_instance: The flacfetch VM instance.
|
||||
vpc_connector: The VPC connector (ensures it exists before setting URL).
|
||||
|
||||
Returns:
|
||||
secretmanager.SecretVersion: The new secret version with internal URL.
|
||||
"""
|
||||
internal_url = flacfetch_instance.network_interfaces[0].network_ip.apply(
|
||||
lambda ip: f"http://{ip}:8080"
|
||||
)
|
||||
|
||||
return secretmanager.SecretVersion(
|
||||
"flacfetch-api-url-internal",
|
||||
secret=secret.id,
|
||||
secret_data=internal_url,
|
||||
opts=pulumi.ResourceOptions(depends_on=[vpc_connector]),
|
||||
)
|
||||
@@ -118,7 +118,9 @@ echo "ENCODING_API_KEY=${ENCODING_API_KEY}" > /opt/encoding-worker/env
|
||||
# This enables hot code updates without rebuilding the image
|
||||
echo "Installing latest karaoke-gen wheel from GCS..."
|
||||
gsutil cp "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl" /tmp/ 2>/dev/null || true
|
||||
WHEEL_FILE=$(ls -t /tmp/karaoke_gen-*.whl 2>/dev/null | head -1)
|
||||
# Use version sort (-V) to get the highest version, not time sort (-t)
|
||||
# All wheels download at the same time, so -t picks arbitrarily
|
||||
WHEEL_FILE=$(ls /tmp/karaoke_gen-*.whl 2>/dev/null | sort -V | tail -1)
|
||||
if [ -n "$WHEEL_FILE" ]; then
|
||||
echo "Installing wheel: $WHEEL_FILE"
|
||||
/opt/encoding-worker/venv/bin/pip install --upgrade --quiet "$WHEEL_FILE" || echo "WARNING: Failed to install wheel"
|
||||
|
||||
@@ -750,18 +750,44 @@
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const encodedBaseApiUrl = urlParams.get('baseApiUrl');
|
||||
const instrumentalToken = urlParams.get('instrumentalToken');
|
||||
|
||||
|
||||
// Check localStorage for full auth token (logged-in users)
|
||||
// This takes priority over instrumentalToken which can expire
|
||||
const fullAuthToken = localStorage.getItem('karaoke_access_token');
|
||||
|
||||
// Determine API base URL - cloud mode uses provided URL, local mode uses default
|
||||
const API_BASE = encodedBaseApiUrl
|
||||
const API_BASE = encodedBaseApiUrl
|
||||
? decodeURIComponent(encodedBaseApiUrl)
|
||||
: '/api/jobs/local';
|
||||
|
||||
// Helper to add token to URL if available
|
||||
|
||||
// Helper to add auth token to URL
|
||||
// Priority: fullAuthToken (doesn't expire) > instrumentalToken (expires after 48h)
|
||||
// This is essential for audio elements which can't use Bearer headers
|
||||
function addTokenToUrl(url) {
|
||||
// Prefer full auth token - it doesn't have the short expiry that magic link tokens have
|
||||
if (fullAuthToken) {
|
||||
const separator = url.includes('?') ? '&' : '?';
|
||||
return `${url}${separator}token=${encodeURIComponent(fullAuthToken)}`;
|
||||
}
|
||||
// Fall back to instrumental token for non-logged-in users
|
||||
if (!instrumentalToken) return url;
|
||||
const separator = url.includes('?') ? '&' : '?';
|
||||
return `${url}${separator}instrumental_token=${encodeURIComponent(instrumentalToken)}`;
|
||||
}
|
||||
|
||||
// Auth-aware fetch helper
|
||||
// Priority: fullAuthToken (Bearer header) > instrumentalToken (query param)
|
||||
function authFetch(url, options = {}) {
|
||||
if (fullAuthToken) {
|
||||
// Use Bearer auth for logged-in users
|
||||
const headers = new Headers(options.headers || {});
|
||||
headers.set('Authorization', `Bearer ${fullAuthToken}`);
|
||||
return fetch(url, { ...options, headers });
|
||||
} else {
|
||||
// Fall back to instrumental token in URL
|
||||
return fetch(addTokenToUrl(url), options);
|
||||
}
|
||||
}
|
||||
|
||||
// HTML escape helper to prevent XSS
|
||||
function escapeHtml(str) {
|
||||
@@ -780,8 +806,8 @@
|
||||
async function init() {
|
||||
try {
|
||||
const [analysisRes, waveformRes] = await Promise.all([
|
||||
fetch(addTokenToUrl(`${API_BASE}/instrumental-analysis`)),
|
||||
fetch(addTokenToUrl(`${API_BASE}/waveform-data?num_points=1000`))
|
||||
authFetch(`${API_BASE}/instrumental-analysis`),
|
||||
authFetch(`${API_BASE}/waveform-data?num_points=1000`)
|
||||
]);
|
||||
|
||||
if (!analysisRes.ok) throw new Error('Failed to load analysis');
|
||||
@@ -1484,7 +1510,7 @@
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await fetch(addTokenToUrl(`${API_BASE}/upload-instrumental`), {
|
||||
const response = await authFetch(`${API_BASE}/upload-instrumental`, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
@@ -1543,7 +1569,7 @@
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(addTokenToUrl(`${API_BASE}/create-custom-instrumental`), {
|
||||
const response = await authFetch(`${API_BASE}/create-custom-instrumental`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ mute_regions: muteRegions })
|
||||
@@ -1593,7 +1619,7 @@
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(addTokenToUrl(`${API_BASE}/select-instrumental`), {
|
||||
const response = await authFetch(`${API_BASE}/select-instrumental`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ selection: selectedOption })
|
||||
|
||||
@@ -13,6 +13,7 @@ from .models.schemas import CorrectionProposal, GapClassification, GapCategory
|
||||
from .workflows.correction_graph import build_correction_graph
|
||||
from .prompts.classifier import build_classification_prompt
|
||||
from .handlers.registry import HandlerRegistry
|
||||
from lyrics_transcriber.utils.tracing import create_span, add_span_attribute
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -211,72 +212,94 @@ class AgenticCorrector:
|
||||
Returns:
|
||||
List of CorrectionProposal objects
|
||||
"""
|
||||
# Step 1: Classify the gap
|
||||
gap_text = ' '.join(w.get('text', '') for w in gap_words)
|
||||
classification = self.classify_gap(
|
||||
gap_id=gap_id,
|
||||
gap_text=gap_text,
|
||||
preceding_words=preceding_words,
|
||||
following_words=following_words,
|
||||
reference_contexts=reference_contexts,
|
||||
artist=artist,
|
||||
title=title
|
||||
)
|
||||
|
||||
if not classification:
|
||||
# Classification failed, flag for human review
|
||||
logger.warning(f"🤖 Classification failed for gap {gap_id}, flagging for review")
|
||||
return [CorrectionProposal(
|
||||
word_ids=[w['id'] for w in gap_words],
|
||||
action="Flag",
|
||||
confidence=0.0,
|
||||
reason="Classification failed - unable to categorize gap",
|
||||
requires_human_review=True,
|
||||
artist=artist,
|
||||
title=title
|
||||
)]
|
||||
|
||||
# Step 2: Route to appropriate handler based on category
|
||||
try:
|
||||
handler = HandlerRegistry.get_handler(
|
||||
category=classification.category,
|
||||
artist=artist,
|
||||
title=title
|
||||
)
|
||||
|
||||
proposals = handler.handle(
|
||||
with create_span("agentic.propose_for_gap", {
|
||||
"gap_id": gap_id,
|
||||
"word_count": len(gap_words),
|
||||
}) as span:
|
||||
# Step 1: Classify the gap
|
||||
gap_text = ' '.join(w.get('text', '') for w in gap_words)
|
||||
classification = self.classify_gap(
|
||||
gap_id=gap_id,
|
||||
gap_words=gap_words,
|
||||
gap_text=gap_text,
|
||||
preceding_words=preceding_words,
|
||||
following_words=following_words,
|
||||
reference_contexts=reference_contexts,
|
||||
classification_reasoning=classification.reasoning
|
||||
)
|
||||
|
||||
# Add classification metadata to proposals
|
||||
for proposal in proposals:
|
||||
if not proposal.gap_category:
|
||||
proposal.gap_category = classification.category
|
||||
if not proposal.artist:
|
||||
proposal.artist = artist
|
||||
if not proposal.title:
|
||||
proposal.title = title
|
||||
|
||||
return proposals
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"🤖 Handler failed for gap {gap_id} (category: {classification.category}): {e}")
|
||||
# Handler failed, flag for human review
|
||||
return [CorrectionProposal(
|
||||
word_ids=[w['id'] for w in gap_words],
|
||||
action="Flag",
|
||||
confidence=0.0,
|
||||
reason=f"Handler error for category {classification.category}: {str(e)}",
|
||||
gap_category=classification.category,
|
||||
requires_human_review=True,
|
||||
artist=artist,
|
||||
title=title
|
||||
)]
|
||||
)
|
||||
|
||||
if not classification:
|
||||
# Classification failed, flag for human review
|
||||
logger.warning(f"🤖 Classification failed for gap {gap_id}, flagging for review")
|
||||
if span:
|
||||
span.set_attribute("classification_failed", True)
|
||||
# Safely extract word IDs, filtering out any missing/None values
|
||||
word_ids = [w.get('id') for w in gap_words if w.get('id') is not None]
|
||||
return [CorrectionProposal(
|
||||
word_ids=word_ids,
|
||||
action="Flag",
|
||||
confidence=0.0,
|
||||
reason="Classification failed - unable to categorize gap",
|
||||
requires_human_review=True,
|
||||
artist=artist,
|
||||
title=title
|
||||
)]
|
||||
|
||||
if span:
|
||||
span.set_attribute("gap_category", classification.category.value if hasattr(classification.category, 'value') else str(classification.category))
|
||||
|
||||
# Step 2: Route to appropriate handler based on category
|
||||
try:
|
||||
handler = HandlerRegistry.get_handler(
|
||||
category=classification.category,
|
||||
artist=artist,
|
||||
title=title
|
||||
)
|
||||
|
||||
proposals = handler.handle(
|
||||
gap_id=gap_id,
|
||||
gap_words=gap_words,
|
||||
preceding_words=preceding_words,
|
||||
following_words=following_words,
|
||||
reference_contexts=reference_contexts,
|
||||
classification_reasoning=classification.reasoning
|
||||
)
|
||||
|
||||
# Add classification metadata to proposals
|
||||
for proposal in proposals:
|
||||
if not proposal.gap_category:
|
||||
proposal.gap_category = classification.category
|
||||
if not proposal.artist:
|
||||
proposal.artist = artist
|
||||
if not proposal.title:
|
||||
proposal.title = title
|
||||
|
||||
if span:
|
||||
span.set_attribute("proposal_count", len(proposals))
|
||||
|
||||
return proposals
|
||||
|
||||
except Exception as e:
|
||||
# Sanitize error message - use exception class name and truncated message
|
||||
error_type = type(e).__name__
|
||||
error_msg_truncated = str(e)[:50] if str(e) else "Unknown error"
|
||||
sanitized_error = f"{error_type}: {error_msg_truncated}"
|
||||
logger.error(f"🤖 Handler failed for gap {gap_id} (category: {classification.category}): {sanitized_error}")
|
||||
if span:
|
||||
span.set_attribute("handler_error", sanitized_error)
|
||||
# Safely extract word IDs, filtering out any missing/None values
|
||||
word_ids = [w.get('id') for w in gap_words if w.get('id') is not None]
|
||||
# Handler failed, flag for human review
|
||||
return [CorrectionProposal(
|
||||
word_ids=word_ids,
|
||||
action="Flag",
|
||||
confidence=0.0,
|
||||
reason=f"Handler error for category {classification.category} ({error_type})",
|
||||
gap_category=classification.category,
|
||||
requires_human_review=True,
|
||||
artist=artist,
|
||||
title=title
|
||||
)]
|
||||
|
||||
def propose(self, prompt: str) -> List[CorrectionProposal]:
|
||||
"""Generate correction proposals using LangGraph + LangChain.
|
||||
|
||||
@@ -8,6 +8,9 @@ from pathlib import Path
|
||||
import json
|
||||
import hashlib
|
||||
|
||||
# Tracing utilities (optional - gracefully handles missing dependency)
|
||||
from lyrics_transcriber.utils.tracing import create_span, add_span_attribute, add_span_event
|
||||
|
||||
from lyrics_transcriber.types import LyricsData, PhraseScore, PhraseType, AnchorSequence, GapSequence, ScoredAnchor, TranscriptionResult, Word
|
||||
from lyrics_transcriber.correction.phrase_analyzer import PhraseAnalyzer
|
||||
from lyrics_transcriber.correction.text_utils import clean_text
|
||||
@@ -381,7 +384,24 @@ class AnchorSequenceFinder:
|
||||
) -> List[ScoredAnchor]:
|
||||
"""Find anchor sequences that appear in both transcription and references with timeout protection."""
|
||||
start_time = time.time()
|
||||
|
||||
|
||||
# Wrap entire operation in a tracing span
|
||||
with create_span("anchor_search.find_anchors", {
|
||||
"transcription.text_length": len(transcribed),
|
||||
"reference.source_count": len(references),
|
||||
"timeout_seconds": self.timeout_seconds,
|
||||
}) as span:
|
||||
return self._find_anchors_impl(transcribed, references, transcription_result, start_time, span)
|
||||
|
||||
def _find_anchors_impl(
|
||||
self,
|
||||
transcribed: str,
|
||||
references: Dict[str, LyricsData],
|
||||
transcription_result: TranscriptionResult,
|
||||
start_time: float,
|
||||
span,
|
||||
) -> List[ScoredAnchor]:
|
||||
"""Internal implementation of find_anchors wrapped in tracing span."""
|
||||
try:
|
||||
self.logger.info(f"🔍 ANCHOR SEARCH: Starting find_anchors with timeout {self.timeout_seconds}s")
|
||||
self.logger.info(f"🔍 ANCHOR SEARCH: Transcribed text length: {len(transcribed)}")
|
||||
@@ -395,6 +415,10 @@ class AnchorSequenceFinder:
|
||||
self.logger.info(f"🔍 ANCHOR SEARCH: Checking cache at {cache_path}")
|
||||
if cached_data := self._load_from_cache(cache_path):
|
||||
self.logger.info("🔍 ANCHOR SEARCH: ✅ Cache hit! Loading anchors from cache")
|
||||
if span:
|
||||
span.set_attribute("cache_hit", True)
|
||||
span.set_attribute("cached_anchors", len(cached_data))
|
||||
span.set_attribute("duration_seconds", time.time() - start_time)
|
||||
try:
|
||||
# Convert cached_data to dictionary before logging
|
||||
if cached_data:
|
||||
@@ -504,10 +528,24 @@ class AnchorSequenceFinder:
|
||||
}
|
||||
|
||||
completed = 0
|
||||
last_progress_log_time = time.time()
|
||||
progress_log_interval = 30 # Log every 30 seconds
|
||||
|
||||
for future in as_completed(future_to_n):
|
||||
n = future_to_n[future]
|
||||
completed += 1
|
||||
|
||||
# Time-based progress logging (every 30 seconds)
|
||||
current_time = time.time()
|
||||
if current_time - last_progress_log_time >= progress_log_interval:
|
||||
elapsed = current_time - start_time
|
||||
progress_pct = (completed / len(n_gram_lengths)) * 100
|
||||
self.logger.info(
|
||||
f"🔍 ANCHOR SEARCH: Progress {completed}/{len(n_gram_lengths)} "
|
||||
f"({progress_pct:.1f}%) - {elapsed:.1f}s elapsed"
|
||||
)
|
||||
last_progress_log_time = current_time
|
||||
|
||||
# Check timeout periodically
|
||||
if self.timeout_seconds > 0:
|
||||
elapsed_time = time.time() - start_time
|
||||
@@ -577,7 +615,14 @@ class AnchorSequenceFinder:
|
||||
|
||||
total_time = time.time() - start_time
|
||||
self.logger.info(f"🔍 ANCHOR SEARCH: 🎉 Anchor sequence computation completed successfully in {total_time:.1f}s")
|
||||
|
||||
|
||||
# Add span attributes for metrics
|
||||
if span:
|
||||
span.set_attribute("candidate_anchors", len(candidate_anchors))
|
||||
span.set_attribute("filtered_anchors", len(filtered_anchors))
|
||||
span.set_attribute("duration_seconds", total_time)
|
||||
span.set_attribute("cache_hit", False)
|
||||
|
||||
return filtered_anchors
|
||||
|
||||
except AnchorSequenceTimeoutError:
|
||||
@@ -592,7 +637,7 @@ class AnchorSequenceFinder:
|
||||
self.logger.error(f"🔍 ANCHOR SEARCH: Traceback: {traceback.format_exc()}")
|
||||
raise
|
||||
finally:
|
||||
# No cleanup needed for time-based timeout checks
|
||||
# No cleanup needed - span is managed by context manager in find_anchors()
|
||||
pass
|
||||
|
||||
def _score_sequence(self, words: List[str], context: str) -> PhraseScore:
|
||||
|
||||
@@ -27,6 +27,7 @@ from lyrics_transcriber.correction.anchor_sequence import AnchorSequenceFinder
|
||||
from lyrics_transcriber.correction.handlers.base import GapCorrectionHandler
|
||||
from lyrics_transcriber.correction.handlers.extend_anchor import ExtendAnchorHandler
|
||||
from lyrics_transcriber.utils.word_utils import WordUtils
|
||||
from lyrics_transcriber.utils.tracing import create_span, add_span_attribute, add_span_event
|
||||
|
||||
|
||||
class LyricsCorrector:
|
||||
@@ -126,66 +127,91 @@ class LyricsCorrector:
|
||||
wrap this method with an outer timeout (e.g., asyncio.wait_for) as a safety
|
||||
net for hung operations.
|
||||
"""
|
||||
start_time = time.time()
|
||||
|
||||
# Optional agentic routing flag from environment; default off for safety
|
||||
agentic_enabled = os.getenv("USE_AGENTIC_AI", "").lower() in {"1", "true", "yes"}
|
||||
self.logger.info(f"🤖 AGENTIC MODE: {'ENABLED' if agentic_enabled else 'DISABLED'} (USE_AGENTIC_AI={os.getenv('USE_AGENTIC_AI', 'NOT_SET')})")
|
||||
if not transcription_results:
|
||||
self.logger.error("No transcription results available")
|
||||
raise ValueError("No primary transcription data available")
|
||||
|
||||
# Store reference lyrics for use in word map
|
||||
self.reference_lyrics = lyrics_results
|
||||
with create_span("lyrics_corrector.run", {
|
||||
"agentic_enabled": agentic_enabled,
|
||||
"reference_sources": len(lyrics_results),
|
||||
"transcription_count": len(transcription_results),
|
||||
}) as span:
|
||||
self.logger.info(f"🤖 AGENTIC MODE: {'ENABLED' if agentic_enabled else 'DISABLED'} (USE_AGENTIC_AI={os.getenv('USE_AGENTIC_AI', 'NOT_SET')})")
|
||||
if not transcription_results:
|
||||
self.logger.error("No transcription results available")
|
||||
raise ValueError("No primary transcription data available")
|
||||
|
||||
# Get primary transcription
|
||||
primary_transcription_result = sorted(transcription_results, key=lambda x: x.priority)[0]
|
||||
primary_transcription = primary_transcription_result.result
|
||||
transcribed_text = " ".join(" ".join(w.text for w in segment.words) for segment in primary_transcription.segments)
|
||||
# Store reference lyrics for use in word map
|
||||
self.reference_lyrics = lyrics_results
|
||||
|
||||
# Find anchor sequences and gaps
|
||||
self.logger.debug("Finding anchor sequences and gaps")
|
||||
anchor_sequences = self.anchor_finder.find_anchors(transcribed_text, lyrics_results, primary_transcription_result)
|
||||
gap_sequences = self.anchor_finder.find_gaps(transcribed_text, anchor_sequences, lyrics_results, primary_transcription_result)
|
||||
# Get primary transcription
|
||||
primary_transcription_result = sorted(transcription_results, key=lambda x: x.priority)[0]
|
||||
primary_transcription = primary_transcription_result.result
|
||||
transcribed_text = " ".join(" ".join(w.text for w in segment.words) for segment in primary_transcription.segments)
|
||||
|
||||
# Store anchor sequences for use in correction handlers
|
||||
self._anchor_sequences = anchor_sequences
|
||||
# Find anchor sequences and gaps
|
||||
self.logger.debug("Finding anchor sequences and gaps")
|
||||
with create_span("lyrics_corrector.find_anchors_and_gaps") as anchor_span:
|
||||
anchor_sequences = self.anchor_finder.find_anchors(transcribed_text, lyrics_results, primary_transcription_result)
|
||||
gap_sequences = self.anchor_finder.find_gaps(transcribed_text, anchor_sequences, lyrics_results, primary_transcription_result)
|
||||
if anchor_span:
|
||||
anchor_span.set_attribute("anchor_count", len(anchor_sequences))
|
||||
anchor_span.set_attribute("gap_count", len(gap_sequences))
|
||||
|
||||
# Process corrections with metadata and optional deadline for agentic timeout
|
||||
corrections, corrected_segments, correction_steps, word_id_map, segment_id_map = self._process_corrections(
|
||||
primary_transcription.segments, gap_sequences, metadata=metadata, deadline=agentic_deadline
|
||||
)
|
||||
# Store anchor sequences for use in correction handlers
|
||||
self._anchor_sequences = anchor_sequences
|
||||
|
||||
# Calculate correction ratio
|
||||
total_words = sum(len(segment.words) for segment in corrected_segments)
|
||||
corrections_made = len(corrections)
|
||||
correction_ratio = 1 - (corrections_made / total_words if total_words > 0 else 0)
|
||||
# Process corrections with metadata and optional deadline for agentic timeout
|
||||
with create_span("lyrics_corrector.process_corrections", {
|
||||
"gap_count": len(gap_sequences),
|
||||
"agentic_enabled": agentic_enabled,
|
||||
}) as process_span:
|
||||
corrections, corrected_segments, correction_steps, word_id_map, segment_id_map = self._process_corrections(
|
||||
primary_transcription.segments, gap_sequences, metadata=metadata, deadline=agentic_deadline
|
||||
)
|
||||
if process_span:
|
||||
process_span.set_attribute("corrections_count", len(corrections))
|
||||
|
||||
# Get the currently enabled handler IDs using the handler's name attribute if available
|
||||
enabled_handlers = [getattr(handler, "name", handler.__class__.__name__) for handler in self.handlers]
|
||||
# Calculate correction ratio
|
||||
total_words = sum(len(segment.words) for segment in corrected_segments)
|
||||
corrections_made = len(corrections)
|
||||
correction_ratio = 1 - (corrections_made / total_words if total_words > 0 else 0)
|
||||
|
||||
result = CorrectionResult(
|
||||
original_segments=primary_transcription.segments,
|
||||
corrected_segments=corrected_segments,
|
||||
corrections=corrections,
|
||||
corrections_made=corrections_made,
|
||||
confidence=correction_ratio,
|
||||
reference_lyrics=lyrics_results,
|
||||
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",
|
||||
},
|
||||
correction_steps=correction_steps,
|
||||
word_id_map=word_id_map,
|
||||
segment_id_map=segment_id_map,
|
||||
)
|
||||
return result
|
||||
# Get the currently enabled handler IDs using the handler's name attribute if available
|
||||
enabled_handlers = [getattr(handler, "name", handler.__class__.__name__) for handler in self.handlers]
|
||||
|
||||
# Add final span attributes
|
||||
if span:
|
||||
span.set_attribute("total_words", total_words)
|
||||
span.set_attribute("corrections_made", corrections_made)
|
||||
span.set_attribute("correction_ratio", correction_ratio)
|
||||
span.set_attribute("duration_seconds", time.time() - start_time)
|
||||
|
||||
result = CorrectionResult(
|
||||
original_segments=primary_transcription.segments,
|
||||
corrected_segments=corrected_segments,
|
||||
corrections=corrections,
|
||||
corrections_made=corrections_made,
|
||||
confidence=correction_ratio,
|
||||
reference_lyrics=lyrics_results,
|
||||
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",
|
||||
},
|
||||
correction_steps=correction_steps,
|
||||
word_id_map=word_id_map,
|
||||
segment_id_map=segment_id_map,
|
||||
)
|
||||
return result
|
||||
|
||||
def _preserve_formatting(self, original: str, new_word: str) -> str:
|
||||
"""Preserve original word's formatting when applying correction."""
|
||||
@@ -465,6 +491,9 @@ class LyricsCorrector:
|
||||
# Get parallel processing config
|
||||
_config = ProviderConfig.from_env()
|
||||
max_workers = _config.max_parallel_gaps
|
||||
|
||||
# Wrap agentic processing in a tracing span
|
||||
add_span_event("agentic_processing_started", {"gap_count": len(gap_sequences), "max_workers": max_workers})
|
||||
self.logger.info(f"🤖 Processing {len(gap_sequences)} gaps in parallel (max_workers={max_workers})")
|
||||
|
||||
# Pre-compute shared data structures once (not per-gap)
|
||||
@@ -585,6 +614,11 @@ class LyricsCorrector:
|
||||
self.logger.info(f"🤖 Gap {result['index']}/{len(gap_sequences)} completed ({proposal_count} proposals)")
|
||||
|
||||
self.logger.info(f"🤖 Parallel processing complete: {completed_count}/{len(gap_sequences)} gaps processed")
|
||||
add_span_event("agentic_processing_completed", {
|
||||
"gaps_processed": completed_count,
|
||||
"gaps_total": len(gap_sequences),
|
||||
"errors": len(errors),
|
||||
})
|
||||
|
||||
# If any errors occurred, fail fast
|
||||
if errors:
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
"""
|
||||
OpenTelemetry tracing utilities for lyrics_transcriber library.
|
||||
|
||||
This module provides tracing utilities that integrate with the backend's
|
||||
OpenTelemetry setup. When running in the backend context (Cloud Run),
|
||||
traces will export to Google Cloud Trace. When running standalone (CLI),
|
||||
tracing is no-op unless explicitly configured.
|
||||
|
||||
Usage:
|
||||
from lyrics_transcriber.utils.tracing import create_span, traced
|
||||
|
||||
# Context manager for spans
|
||||
with create_span("operation_name", {"key": "value"}) as span:
|
||||
span.set_attribute("result_count", 42)
|
||||
# ... do work ...
|
||||
|
||||
# Decorator for functions
|
||||
@traced("custom_name")
|
||||
def my_function():
|
||||
pass
|
||||
"""
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
from contextlib import contextmanager
|
||||
from functools import wraps
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Try to import OpenTelemetry - gracefully handle missing dependency
|
||||
try:
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import Status, StatusCode, Span
|
||||
OTEL_AVAILABLE = True
|
||||
except ImportError:
|
||||
OTEL_AVAILABLE = False
|
||||
trace = None
|
||||
Status = None
|
||||
StatusCode = None
|
||||
Span = None
|
||||
|
||||
|
||||
def get_tracer(name: str = "lyrics_transcriber") -> Any:
|
||||
"""
|
||||
Get a tracer instance.
|
||||
|
||||
If OpenTelemetry is available and configured (by the backend),
|
||||
returns a real tracer. Otherwise returns a no-op tracer.
|
||||
|
||||
Args:
|
||||
name: Tracer name (typically module name)
|
||||
|
||||
Returns:
|
||||
Tracer instance
|
||||
"""
|
||||
if OTEL_AVAILABLE and trace:
|
||||
return trace.get_tracer(name)
|
||||
return None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def create_span(
|
||||
name: str,
|
||||
attributes: Optional[Dict[str, Any]] = None,
|
||||
tracer_name: str = "lyrics_transcriber",
|
||||
):
|
||||
"""
|
||||
Create a traced span as a context manager.
|
||||
|
||||
If OpenTelemetry is not available or not configured, this is a no-op.
|
||||
|
||||
Usage:
|
||||
with create_span("find_anchors", {"word_count": 500}) as span:
|
||||
# ... do work ...
|
||||
if span:
|
||||
span.set_attribute("anchors_found", 42)
|
||||
|
||||
Args:
|
||||
name: Span name (appears in Cloud Trace)
|
||||
attributes: Initial span attributes
|
||||
tracer_name: Tracer name to use
|
||||
|
||||
Yields:
|
||||
The active span, or None if tracing is not available
|
||||
"""
|
||||
tracer = get_tracer(tracer_name)
|
||||
|
||||
if tracer is None:
|
||||
yield None
|
||||
return
|
||||
|
||||
with tracer.start_as_current_span(name) as span:
|
||||
if attributes:
|
||||
for key, value in attributes.items():
|
||||
# Only set if value is a valid type
|
||||
if isinstance(value, (str, int, float, bool)):
|
||||
span.set_attribute(key, value)
|
||||
elif isinstance(value, (list, tuple)) and all(isinstance(v, (str, int, float, bool)) for v in value):
|
||||
span.set_attribute(key, list(value))
|
||||
try:
|
||||
yield span
|
||||
except Exception as e:
|
||||
if OTEL_AVAILABLE and Status and StatusCode:
|
||||
span.set_status(Status(StatusCode.ERROR, str(e)))
|
||||
span.record_exception(e)
|
||||
raise
|
||||
|
||||
|
||||
def traced(
|
||||
name: Optional[str] = None,
|
||||
attributes: Optional[Dict[str, Any]] = None,
|
||||
tracer_name: str = "lyrics_transcriber",
|
||||
):
|
||||
"""
|
||||
Decorator to trace a function.
|
||||
|
||||
If OpenTelemetry is not available or not configured, this is a no-op decorator.
|
||||
|
||||
Usage:
|
||||
@traced("process_correction")
|
||||
def process_correction(job_id: str):
|
||||
...
|
||||
|
||||
@traced(attributes={"operation": "add-lyrics"})
|
||||
async def add_lyrics(job_id: str, source: str):
|
||||
...
|
||||
|
||||
Args:
|
||||
name: Span name (defaults to function name)
|
||||
attributes: Static attributes to add to span
|
||||
tracer_name: Tracer name to use
|
||||
"""
|
||||
def decorator(func):
|
||||
span_name = name or func.__name__
|
||||
|
||||
@wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
with create_span(span_name, attributes, tracer_name) as span:
|
||||
if span:
|
||||
span.set_attribute("function", func.__name__)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
@wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
with create_span(span_name, attributes, tracer_name) as span:
|
||||
if span:
|
||||
span.set_attribute("function", func.__name__)
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
# Return appropriate wrapper based on function type
|
||||
import asyncio
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
return async_wrapper
|
||||
return sync_wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def add_span_attribute(key: str, value: Any) -> None:
|
||||
"""
|
||||
Add an attribute to the current span.
|
||||
|
||||
If no span is active or tracing is not available, this is a no-op.
|
||||
|
||||
Args:
|
||||
key: Attribute name
|
||||
value: Attribute value (must be string, int, float, bool, or list thereof)
|
||||
"""
|
||||
if not OTEL_AVAILABLE or not trace:
|
||||
return
|
||||
|
||||
span = trace.get_current_span()
|
||||
if span and span.is_recording():
|
||||
# Validate type
|
||||
if isinstance(value, (str, int, float, bool)):
|
||||
span.set_attribute(key, value)
|
||||
elif isinstance(value, (list, tuple)) and all(isinstance(v, (str, int, float, bool)) for v in value):
|
||||
span.set_attribute(key, list(value))
|
||||
|
||||
|
||||
def add_span_event(name: str, attributes: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""
|
||||
Add an event to the current span.
|
||||
|
||||
Events are timestamped annotations that appear in the trace timeline.
|
||||
If no span is active or tracing is not available, this is a no-op.
|
||||
|
||||
Args:
|
||||
name: Event name
|
||||
attributes: Event attributes
|
||||
"""
|
||||
if not OTEL_AVAILABLE or not trace:
|
||||
return
|
||||
|
||||
span = trace.get_current_span()
|
||||
if span and span.is_recording():
|
||||
span.add_event(name, attributes=attributes or {})
|
||||
|
||||
|
||||
def set_span_error(error: Exception) -> None:
|
||||
"""
|
||||
Mark the current span as errored.
|
||||
|
||||
If no span is active or tracing is not available, this is a no-op.
|
||||
|
||||
Args:
|
||||
error: The exception that occurred
|
||||
"""
|
||||
if not OTEL_AVAILABLE or not trace or not Status or not StatusCode:
|
||||
return
|
||||
|
||||
span = trace.get_current_span()
|
||||
if span and span.is_recording():
|
||||
span.set_status(Status(StatusCode.ERROR, str(error)))
|
||||
span.record_exception(error)
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.105.0"
|
||||
version = "0.105.7"
|
||||
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"
|
||||
|
||||
Reference in new issue
Block a user