mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 09:28:25 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25888ca003 | ||
|
|
bc8b033cb5 |
No files matched your search
+100
-76
@@ -9,6 +9,7 @@ Submission (POST /bulk/submit) and progress (GET /bulk/{batch_id}) live here too
|
||||
(added in later phases).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Literal, Optional
|
||||
@@ -22,6 +23,9 @@ from backend.services.auth_service import AuthResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Strong refs to shielded tasks so they aren't garbage-collected if the request is cancelled.
|
||||
_BACKGROUND_TASKS: set = set()
|
||||
|
||||
router = APIRouter(prefix="/bulk", tags=["bulk"])
|
||||
|
||||
MAX_BULK_SONGS = 100
|
||||
@@ -304,92 +308,112 @@ async def bulk_submit(
|
||||
user_email = auth_result.user_email
|
||||
is_admin = bool(auth_result.is_admin)
|
||||
|
||||
# Upfront credit gate (1 credit/song minimum). Admins bypass.
|
||||
if not is_admin and user_email:
|
||||
from backend.services.user_service import get_user_service
|
||||
locale = get_full_locale_from_request(request)
|
||||
|
||||
available = get_user_service().check_credits(user_email)
|
||||
if available < n:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"error": "insufficient_credits",
|
||||
"message": "You don't have enough credits for this batch.",
|
||||
"credits_available": available,
|
||||
"credits_required": n,
|
||||
# Everything up to dispatch is sync Firestore/GCS work (credit check, default
|
||||
# theme, one create_job + update_job per song). Run it off the event loop: a
|
||||
# 2026-10-22 album batch stalled the loop 26s and 9 other requests with it.
|
||||
def _create_batch_jobs() -> tuple[str, list[str]]:
|
||||
# Upfront credit gate (1 credit/song minimum). Admins bypass.
|
||||
if not is_admin and user_email:
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
available = get_user_service().check_credits(user_email)
|
||||
if available < n:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"error": "insufficient_credits",
|
||||
"message": "You don't have enough credits for this batch.",
|
||||
"credits_available": available,
|
||||
"credits_required": n,
|
||||
},
|
||||
)
|
||||
|
||||
settings = get_settings()
|
||||
theme_service = get_theme_service()
|
||||
theme_id = theme_service.get_default_theme_id()
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
|
||||
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
bulk_settings = body.settings.model_dump()
|
||||
job_manager = JobManager()
|
||||
job_ids: list[str] = []
|
||||
|
||||
for song in body.songs:
|
||||
display_artist = (song.display_artist or song.artist).strip()
|
||||
display_title = (song.display_title or song.title).strip()
|
||||
request_metadata = {
|
||||
"created_from": "bulk",
|
||||
"batch_id": batch_id,
|
||||
"user_email": user_email,
|
||||
}
|
||||
job_create = JobCreate(
|
||||
artist=display_artist,
|
||||
title=display_title,
|
||||
theme_id=theme_id,
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
user_email=user_email,
|
||||
audio_search_artist=song.artist.strip(),
|
||||
audio_search_title=song.title.strip(),
|
||||
auto_download=False,
|
||||
is_private=body.settings.is_private,
|
||||
review_mode=body.settings.review_mode,
|
||||
backing_preference=body.settings.backing_preference,
|
||||
translation_language=body.settings.translation_language,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
discord_webhook_url=settings.default_discord_webhook_url,
|
||||
dropbox_path=settings.default_dropbox_path,
|
||||
gdrive_folder_id=settings.default_gdrive_folder_id,
|
||||
request_metadata=request_metadata,
|
||||
locale=locale,
|
||||
)
|
||||
try:
|
||||
job = job_manager.create_job(job_create, is_admin=is_admin)
|
||||
except InsufficientCreditsError:
|
||||
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
|
||||
# already-created jobs are valid and will proceed.
|
||||
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
|
||||
break
|
||||
|
||||
job_manager.update_job(
|
||||
job.job_id,
|
||||
{
|
||||
"state_data.batch_id": batch_id,
|
||||
"state_data.bulk_settings": bulk_settings,
|
||||
"state_data.bulk_pending_search": True,
|
||||
},
|
||||
)
|
||||
|
||||
settings = get_settings()
|
||||
theme_service = get_theme_service()
|
||||
theme_id = theme_service.get_default_theme_id()
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
|
||||
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
bulk_settings = body.settings.model_dump()
|
||||
job_manager = JobManager()
|
||||
job_ids: list[str] = []
|
||||
|
||||
for song in body.songs:
|
||||
display_artist = (song.display_artist or song.artist).strip()
|
||||
display_title = (song.display_title or song.title).strip()
|
||||
request_metadata = {
|
||||
"created_from": "bulk",
|
||||
"batch_id": batch_id,
|
||||
"user_email": user_email,
|
||||
}
|
||||
job_create = JobCreate(
|
||||
artist=display_artist,
|
||||
title=display_title,
|
||||
theme_id=theme_id,
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
user_email=user_email,
|
||||
audio_search_artist=song.artist.strip(),
|
||||
audio_search_title=song.title.strip(),
|
||||
auto_download=False,
|
||||
is_private=body.settings.is_private,
|
||||
review_mode=body.settings.review_mode,
|
||||
backing_preference=body.settings.backing_preference,
|
||||
translation_language=body.settings.translation_language,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
discord_webhook_url=settings.default_discord_webhook_url,
|
||||
dropbox_path=settings.default_dropbox_path,
|
||||
gdrive_folder_id=settings.default_gdrive_folder_id,
|
||||
request_metadata=request_metadata,
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
try:
|
||||
job = job_manager.create_job(job_create, is_admin=is_admin)
|
||||
except InsufficientCreditsError:
|
||||
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
|
||||
# already-created jobs are valid and will proceed.
|
||||
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
|
||||
break
|
||||
|
||||
job_manager.update_job(
|
||||
job.job_id,
|
||||
{
|
||||
"state_data.batch_id": batch_id,
|
||||
"state_data.bulk_settings": bulk_settings,
|
||||
"state_data.bulk_pending_search": True,
|
||||
},
|
||||
)
|
||||
job_ids.append(job.job_id)
|
||||
|
||||
if not job_ids:
|
||||
raise HTTPException(status_code=402, detail="No jobs could be created")
|
||||
job_ids.append(job.job_id)
|
||||
return batch_id, job_ids
|
||||
|
||||
# Dispatch the batch search worker. Retry once on transient failure. If it
|
||||
# still fails the jobs exist (and are charged) but won't process, so surface
|
||||
# an explicit error with the batch_id — and tell the user NOT to resubmit
|
||||
# (that would create+charge a second batch); the batch can be re-dispatched.
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
if not triggered:
|
||||
|
||||
async def _create_and_dispatch() -> tuple[str, list[str], bool]:
|
||||
batch_id, job_ids = await asyncio.to_thread(_create_batch_jobs)
|
||||
if not job_ids:
|
||||
return batch_id, job_ids, False
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
if not triggered:
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
return batch_id, job_ids, triggered
|
||||
|
||||
# Shielded: if the request is cancelled (client disconnect) mid-way, the jobs
|
||||
# being created and charged in the thread still get dispatched.
|
||||
task = asyncio.create_task(_create_and_dispatch())
|
||||
_BACKGROUND_TASKS.add(task)
|
||||
task.add_done_callback(_BACKGROUND_TASKS.discard)
|
||||
batch_id, job_ids, triggered = await asyncio.shield(task)
|
||||
|
||||
if not job_ids:
|
||||
raise HTTPException(status_code=402, detail="No jobs could be created")
|
||||
if not triggered:
|
||||
logger.critical(
|
||||
"[batch:%s] created %d jobs but FAILED to dispatch bulk-search worker",
|
||||
|
||||
+19
-11
@@ -8,6 +8,7 @@ Handles:
|
||||
- Stripe checkout and webhooks
|
||||
- Admin user management
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import html
|
||||
import logging
|
||||
@@ -1304,10 +1305,21 @@ async def _handle_made_for_you_order(
|
||||
|
||||
logger.info(f"Created made-for-you job {job_id} for {_mask_email(customer_email)} (owned by {_mask_email(ADMIN_EMAIL)})")
|
||||
|
||||
# Mark the session processed straight after creating the job, before any await:
|
||||
# if this task is cancelled at an await below, Stripe's retry must find the
|
||||
# session already handled rather than create a second job for the same order.
|
||||
# Note: Using internal method since this isn't a credit transaction
|
||||
user_service._mark_stripe_session_processed(
|
||||
stripe_session_id=session_id,
|
||||
email=customer_email,
|
||||
amount=0 # No credits, just tracking the session
|
||||
)
|
||||
|
||||
# Prepare theme style assets for the job (same as audio_search endpoint)
|
||||
if effective_theme_id:
|
||||
try:
|
||||
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
style_params_path, theme_style_assets, youtube_desc = await asyncio.to_thread(
|
||||
_prepare_theme_for_job,
|
||||
job_id, effective_theme_id, None # No color overrides for made-for-you
|
||||
)
|
||||
theme_update = {
|
||||
@@ -1321,14 +1333,6 @@ async def _handle_made_for_you_order(
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to prepare theme for made-for-you job {job_id}: {e}")
|
||||
|
||||
# Mark session as processed for idempotency
|
||||
# Note: Using internal method since this isn't a credit transaction
|
||||
user_service._mark_stripe_session_processed(
|
||||
stripe_session_id=session_id,
|
||||
email=customer_email,
|
||||
amount=0 # No credits, just tracking the session
|
||||
)
|
||||
|
||||
# Initialize search_results for later use in email notification
|
||||
search_results = None
|
||||
|
||||
@@ -1341,7 +1345,10 @@ async def _handle_made_for_you_order(
|
||||
try:
|
||||
# Providers return False (not an exception) when the send is rejected, so
|
||||
# check the result rather than assuming success.
|
||||
confirmation_ok = bool(email_service.send_made_for_you_order_confirmation(
|
||||
# Off the event loop: a slow Postmark send (retries + SMTP fallback)
|
||||
# stalled every request on the instance for 22s on 2026-10-22.
|
||||
confirmation_ok = bool(await asyncio.to_thread(
|
||||
email_service.send_made_for_you_order_confirmation,
|
||||
to_email=customer_email,
|
||||
artist=artist,
|
||||
title=title,
|
||||
@@ -1507,7 +1514,8 @@ async def _handle_made_for_you_order(
|
||||
email=ADMIN_EMAIL,
|
||||
expiry_hours=24,
|
||||
)
|
||||
admin_notified = bool(email_service.send_made_for_you_admin_notification(
|
||||
admin_notified = bool(await asyncio.to_thread(
|
||||
email_service.send_made_for_you_admin_notification,
|
||||
to_email=ADMIN_EMAIL,
|
||||
customer_email=customer_email,
|
||||
artist=artist,
|
||||
|
||||
@@ -148,3 +148,48 @@ def test_partial_failure_returns_created_jobs(client, monkeypatch):
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["total"] == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_request_still_dispatches_created_batch(monkeypatch):
|
||||
"""A client disconnect mid-creation must not strand created (and charged) jobs:
|
||||
the create+dispatch step is shielded, so dispatch still runs after cancellation."""
|
||||
import asyncio
|
||||
import threading
|
||||
import backend.api.routes.bulk as bulk
|
||||
from starlette.requests import Request
|
||||
|
||||
_patch_user_service(monkeypatch, credits=10)
|
||||
jm = _patch_job_manager(monkeypatch)
|
||||
started, release = threading.Event(), threading.Event()
|
||||
inner_create = jm.create_job.side_effect
|
||||
|
||||
def _slow_create(job_create, is_admin=False):
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return inner_create(job_create, is_admin=is_admin)
|
||||
|
||||
jm.create_job.side_effect = _slow_create
|
||||
dispatched = []
|
||||
|
||||
async def _trigger(batch_id):
|
||||
dispatched.append(batch_id)
|
||||
return True
|
||||
|
||||
worker = MagicMock()
|
||||
worker.trigger_bulk_search_worker = _trigger
|
||||
monkeypatch.setattr("backend.services.worker_service.get_worker_service", lambda: worker)
|
||||
|
||||
request = Request({"type": "http", "method": "POST", "path": "/api/bulk/submit", "headers": []})
|
||||
body = bulk.BulkSubmitRequest(songs=[{"artist": "A", "title": "B"}], settings={})
|
||||
route = asyncio.create_task(bulk.bulk_submit(request, body, _auth()()))
|
||||
await asyncio.to_thread(started.wait, 5)
|
||||
route.cancel()
|
||||
release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await route
|
||||
for _ in range(100): # let the shielded task finish
|
||||
if dispatched:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
assert len(dispatched) == 1
|
||||
@@ -1026,6 +1026,43 @@ class TestHandleMadeForYouOrder:
|
||||
assert job_create_arg.made_for_you is True, \
|
||||
"Job must be created with made_for_you=True for made-for-you orders"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_marked_processed_before_theme_prep(
|
||||
self, mock_job_manager, mock_email_service, mock_user_service,
|
||||
mock_theme_service, order_metadata
|
||||
):
|
||||
"""The session must be marked processed before the first await after create_job.
|
||||
If the webhook task is cancelled while theme prep runs, Stripe's retry then finds
|
||||
the session handled instead of creating a second job for the same order."""
|
||||
from backend.api.routes.users import _handle_made_for_you_order
|
||||
|
||||
marked_before_theme = []
|
||||
|
||||
def _prepare(*args, **kwargs):
|
||||
marked_before_theme.append(mock_user_service._mark_stripe_session_processed.called)
|
||||
return ("style.json", {}, None)
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service'), \
|
||||
patch('backend.services.audio_search_service.get_audio_search_service') as mock_get_audio, \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', side_effect=_prepare):
|
||||
from backend.services.audio_search_service import NoResultsError
|
||||
mock_audio_service = MagicMock()
|
||||
mock_audio_service.search.side_effect = NoResultsError("No results")
|
||||
mock_get_audio.return_value = mock_audio_service
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_123",
|
||||
metadata=order_metadata,
|
||||
user_service=mock_user_service,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
assert marked_before_theme == [True]
|
||||
mock_user_service._mark_stripe_session_processed.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_job_owned_by_admin_during_processing(
|
||||
self, mock_job_manager, mock_email_service, mock_user_service,
|
||||
|
||||
@@ -223,6 +223,10 @@ BLOCKING_CALLS = {
|
||||
"get_metadata_from_gcs",
|
||||
"upload_file",
|
||||
"download_file",
|
||||
# 2026-10-22 watchdog culprits: the Stripe webhook's made-for-you order emails
|
||||
# (Postmark retries + SMTP fallback, 22s, 11 requests).
|
||||
"send_made_for_you_order_confirmation",
|
||||
"send_made_for_you_admin_notification",
|
||||
}
|
||||
_BLOCKING_MODULE_CALLS = {("requests", "get"), ("requests", "post"), ("requests", "put"),
|
||||
("requests", "delete"), ("requests", "request"), ("time", "sleep")}
|
||||
@@ -328,3 +332,43 @@ async def fixed(request):
|
||||
assert find_blocking_calls_in_async_routes(src) == []
|
||||
hits = find_blocking_calls_in_async_routes(src, routes_only=False)
|
||||
assert [h.split(" line")[0] for h in hits] == ["require_auth: validate_token_full()"]
|
||||
|
||||
|
||||
# Async helpers that a route awaits run on the loop too, but they aren't decorated so the
|
||||
# route-only scan above skips them.
|
||||
AWAITED_ROUTE_HELPERS = {
|
||||
BACKEND / "api" / "routes" / "users.py": {"_handle_made_for_you_order"},
|
||||
}
|
||||
|
||||
|
||||
def test_no_known_blocking_calls_in_awaited_route_helpers():
|
||||
offenders = []
|
||||
for path, helpers in AWAITED_ROUTE_HELPERS.items():
|
||||
for hit in find_blocking_calls_in_async_routes(path.read_text(), routes_only=False):
|
||||
if hit.split(":")[0] in helpers:
|
||||
offenders.append(f"{path.relative_to(BACKEND.parent)}::{hit}")
|
||||
assert not offenders, (
|
||||
"These async route helpers call known-blocking functions on the event loop. "
|
||||
"Use `await asyncio.to_thread(fn, ...)`:\n " + "\n ".join(sorted(offenders))
|
||||
)
|
||||
|
||||
|
||||
def test_bulk_submit_creates_jobs_off_the_loop():
|
||||
"""bulk_submit's per-song create_job/update_job loop stalled the loop 26s
|
||||
(2026-10-22, an album batch). It must stay inside the to_thread helper."""
|
||||
import ast
|
||||
|
||||
tree = ast.parse((BACKEND / "api" / "routes" / "bulk.py").read_text())
|
||||
route = next(n for n in ast.walk(tree)
|
||||
if isinstance(n, ast.AsyncFunctionDef) and n.name == "bulk_submit")
|
||||
direct = []
|
||||
stack = list(route.body)
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if isinstance(node, (ast.FunctionDef, ast.Lambda, ast.ClassDef)):
|
||||
continue
|
||||
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
|
||||
and node.func.attr in {"create_job", "update_job", "check_credits", "get_default_theme_id"}):
|
||||
direct.append(f"{node.func.attr}() line {node.lineno}")
|
||||
stack.extend(ast.iter_child_nodes(node))
|
||||
assert not direct, f"bulk_submit calls sync Firestore/GCS on the loop: {direct}"
|
||||
@@ -5,3 +5,5 @@ config:
|
||||
nomad-cloudflare:googleOauthClientSecret:
|
||||
secure: AAABAF/ZOcl4fY4R+829/6axVvqqq5QeZou0BtO5BkszNcDUwMc1CEnkVlDMdUX9O3SXI2EfWGcdhx9S50uMHbxnZw==
|
||||
nomad-cloudflare:googleOauthClientId: 718638054799-lqgmpmaauc23mc7mu822pspvq0s1tla3.apps.googleusercontent.com
|
||||
nomad-cloudflare:kjboxcc_android_sha256_fingerprints:
|
||||
- FA:C6:17:45:DC:09:03:78:6F:B9:ED:E6:2A:96:2B:39:9F:73:48:F0:BB:6F:89:9B:83:32:66:75:91:03:3B:9C
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.282.1"
|
||||
version = "0.282.2"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
Reference in new issue
Block a user