mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
## Summary - **Local stack:** `scripts/local-stack.sh up --frontend` runs the **real** backend on the Firestore + GCS emulators with `FAKE_WORKERS=1`. In-process fake workers move jobs through their real states in seconds, using tiny real media, so web Playwright and mobile Maestro full-journey tests can run offline against the same endpoints. - **Email-code sign-in** (nomad-mobile spec §4.1): `POST /api/users/auth/send-code` + `verify-code`. The code logic is shared with kjbox via `LoginCodeStore`, and sends are throttled per email and per IP. - **Bug fix found by the new suite:** `confirm-duration` moved jobs to `separating_stage1`, from which they can never reach review. It now resumes at `downloading`. No prod job had taken this path yet. ## Changes - `backend/services/fake_workers/`: dispatch seam in `WorkerService.trigger_*`, plus fake search, download, checkout and outbox, scenarios, and per-user config. The real stem upload, transcode, backing-vocals analysis and preview render are reused. Every check is strict (`is True`), so a MagicMock settings object never enables the fakes, and startup **refuses FAKE_WORKERS in production**. - `/api/test/*` router (mounted only in that mode): `status`, `scenario`, `fake-config`, `emails`, `reset`, plus the fake Stripe checkout page. Paying it runs the real webhook handler. - `frontend/e2e/local-stack/` (9 specs, ~50s): - sign-up → make → review → instrumental → download - buy and cancel credits - duration confirm, failed, complete and review states - code sign-in and lockout - New required CI job `local-stack-e2e`. - Docs: TESTING.md § Local stack, DEVELOPMENT.md, API.md, README, LESSONS-LEARNED. - `MAX_SIGNUPS_PER_IP` can now be set by env. Only the local stack raises it; production keeps the default of 2. ## Testing - [x] Backend unit: 6175 passed - [x] Emulator: 152 passed - [x] Frontend Jest: 1706 passed - [x] Local-stack Playwright: 9/9 passed (CI mode) ## Review - [x] CodeRabbit CLI review completed locally. 1 minor finding declined: it suggested swallowing infrastructure errors in send-code as fake "sent" responses, which would hide real outages from users. @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01AGuxtgoscF6RJGtpjHPg3W --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
115 lines
4.5 KiB
Python
115 lines
4.5 KiB
Python
"""Runtime knobs for the fake workers, stored in Firestore so every API process sees them.
|
|
|
|
Tests change them through ``PUT /api/test/fake-config`` (see
|
|
``backend/api/routes/test_support.py``) and reset them with ``POST /api/test/reset``.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from dataclasses import asdict, dataclass, fields
|
|
from typing import Any, Dict, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
CONFIG_COLLECTION = "local_stack"
|
|
CONFIG_DOC = "fake_config"
|
|
|
|
# Worker kinds the fakes implement. ``fail_at`` must be one of these.
|
|
WORKER_KINDS = ("audio_download", "audio", "lyrics", "screens", "render_video", "video")
|
|
|
|
|
|
@dataclass
|
|
class FakeConfig:
|
|
# Seconds each fake worker waits before doing its work, so a UI (or test) can
|
|
# observe the intermediate states. 0 makes the whole pipeline near-instant.
|
|
step_delay_seconds: float = 0.5
|
|
# True: the fake screens worker auto-approves the review (skips straight to
|
|
# render) unless the job asked for review_mode="always_review". False: every job
|
|
# parks at AWAITING_REVIEW for a human (the default, exercises the review UI).
|
|
auto_approve: bool = False
|
|
# Fail the job inside this worker (one of WORKER_KINDS), or None.
|
|
fail_at: Optional[str] = None
|
|
# Length of the generated song audio. Longer than the credits charged for the
|
|
# job sends it to AWAITING_DURATION_CONFIRM (the real duration reconciliation).
|
|
audio_duration_seconds: int = 30
|
|
# Number of results the fake audio search returns (0 = "no results").
|
|
search_result_count: int = 3
|
|
|
|
@classmethod
|
|
def from_dict(cls, data: Optional[Dict[str, Any]]) -> "FakeConfig":
|
|
known = {f.name for f in fields(cls)}
|
|
return cls(**{k: v for k, v in (data or {}).items() if k in known})
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return asdict(self)
|
|
|
|
def validate(self) -> None:
|
|
if self.fail_at is not None and self.fail_at not in WORKER_KINDS:
|
|
raise ValueError(f"fail_at must be one of {WORKER_KINDS} or null")
|
|
if self.step_delay_seconds < 0 or self.step_delay_seconds > 60:
|
|
raise ValueError("step_delay_seconds must be between 0 and 60")
|
|
if not 5 <= self.audio_duration_seconds <= 1800:
|
|
raise ValueError("audio_duration_seconds must be between 5 and 1800")
|
|
if not 0 <= self.search_result_count <= 3:
|
|
raise ValueError("search_result_count must be between 0 and 3")
|
|
|
|
|
|
USER_CONFIG_COLLECTION = "local_stack_user_config"
|
|
|
|
|
|
def _default_db():
|
|
from backend.services.firestore_service import FirestoreService
|
|
|
|
return FirestoreService().db
|
|
|
|
|
|
def _doc(db, email: Optional[str] = None):
|
|
if email:
|
|
return db.collection(USER_CONFIG_COLLECTION).document(email.strip().lower())
|
|
return db.collection(CONFIG_COLLECTION).document(CONFIG_DOC)
|
|
|
|
|
|
def _read(db, email: Optional[str] = None) -> Dict[str, Any]:
|
|
snap = _doc(db, email).get()
|
|
return (snap.to_dict() or {}) if snap.exists else {}
|
|
|
|
|
|
def get_fake_config(db=None, email: Optional[str] = None) -> FakeConfig:
|
|
"""Defaults, overlaid with the global config, overlaid with ``email``'s overrides.
|
|
|
|
Per-user overrides let tests that each use their own user run in parallel
|
|
against one stack without fighting over the global knobs.
|
|
"""
|
|
db = db or _default_db()
|
|
try:
|
|
merged = _read(db)
|
|
if email:
|
|
merged.update(_read(db, email))
|
|
return FakeConfig.from_dict(merged)
|
|
except Exception as e: # emulator hiccup: fall back to defaults, never stall a job
|
|
logger.warning(f"fake_workers: could not read config, using defaults: {e}")
|
|
return FakeConfig()
|
|
|
|
|
|
def set_fake_config(updates: Dict[str, Any], db=None, email: Optional[str] = None) -> FakeConfig:
|
|
"""Merge ``updates`` into the global config (or ``email``'s overrides) and return the effective config."""
|
|
db = db or _default_db()
|
|
known = {f.name for f in fields(FakeConfig)}
|
|
unknown = set(updates) - known
|
|
if unknown:
|
|
raise ValueError(f"Unknown fake config keys: {sorted(unknown)}")
|
|
stored = _read(db, email)
|
|
stored.update(updates)
|
|
base = get_fake_config(db).to_dict() if email else {}
|
|
FakeConfig.from_dict({**base, **stored}).validate()
|
|
_doc(db, email).set(stored)
|
|
return get_fake_config(db, email)
|
|
|
|
|
|
def clear_fake_config(db=None) -> None:
|
|
"""Drop the global config and every per-user override (POST /api/test/reset)."""
|
|
db = db or _default_db()
|
|
_doc(db).delete()
|
|
for snap in db.collection(USER_CONFIG_COLLECTION).stream():
|
|
snap.reference.delete()
|