Files
karaoke-gen/backend/services/fake_workers/__init__.py
T
Andrew Beveridge ☄️andClaude Opus 5.5 c277bc8ee3 feat: local E2E stack (fake workers + test API) + email-code sign-in (v0.275.0) (#1165)
## 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>
2026-10-15 16:00:24 -04:00

56 lines
1.9 KiB
Python

"""Fake workers for the local E2E stack (``FAKE_WORKERS=1``, never in production).
``WorkerService.trigger_*`` hands every dispatch to :func:`dispatch` when the
setting is on. Each fake runs on its own thread with its own event loop, so it
outlives the request (or short-lived loop) that triggered it, just as a real
Cloud Run Job / Cloud Task would. See ``pipeline.py`` for what each one writes
and docs/TESTING.md § "Local stack" for how tests drive it.
"""
from __future__ import annotations
import asyncio
import logging
import threading
logger = logging.getLogger(__name__)
_threads: set = set()
_threads_lock = threading.Lock()
def fake_workers_enabled(settings=None) -> bool:
"""True only when FAKE_WORKERS is really on (strict, so a MagicMock settings in tests is off)."""
if settings is None:
from backend.config import get_settings
settings = get_settings()
return getattr(settings, "fake_workers", False) is True
def dispatch(kind: str, job_id: str) -> bool:
"""Start fake worker ``kind`` for ``job_id`` in the background. Returns True (dispatched)."""
from backend.services.fake_workers.pipeline import RUNNERS, run
if kind not in RUNNERS:
raise ValueError(f"Unknown fake worker kind: {kind}")
def _target():
try:
asyncio.run(run(kind, job_id))
finally:
with _threads_lock:
_threads.discard(threading.current_thread())
thread = threading.Thread(target=_target, name=f"fake-{kind}-{job_id[:8]}", daemon=True)
with _threads_lock:
_threads.add(thread)
thread.start()
logger.info(f"[job:{job_id}] fake worker dispatched: {kind}")
return True
def active_worker_count() -> int:
"""Fake workers still running (the test API reports it so tests can wait for idle)."""
with _threads_lock:
return sum(1 for t in _threads if t.is_alive())