Files
karaoke-gen/backend/services/fake_workers/outbox.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

67 lines
2.5 KiB
Python

"""Captured outbound email for the local stack (the console email provider writes here).
Tests read it through ``GET /api/test/emails`` to follow magic links and codes,
the way production E2E reads a testmail.app inbox.
"""
from __future__ import annotations
import html
import logging
import re
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
OUTBOX_COLLECTION = "local_stack_outbox"
_URL_RE = re.compile(r"https?://[^\s\"'<>]+")
# A 6-digit sign-in code: a standalone run of exactly six digits (not part of a
# hex colour like #123456 or a longer number).
_CODE_RE = re.compile(r"(?<![#\w])(\d{6})(?!\w)")
_STYLE_RE = re.compile(r"<(style|script)[^>]*>.*?</\1>", re.S | re.I)
_TAG_RE = re.compile(r"<[^>]+>")
def _visible_text(text_content: Optional[str], html_content: Optional[str]) -> str:
if text_content:
return text_content
return html.unescape(_TAG_RE.sub(" ", _STYLE_RE.sub(" ", html_content or "")))
def _db():
from backend.services.firestore_service import FirestoreService
return FirestoreService().db
def record_email(to_email: str, subject: str, html_content: str, text_content: Optional[str]) -> None:
text = text_content or ""
links = list(dict.fromkeys(
html.unescape(u) for u in _URL_RE.findall(f"{text}\n{html_content or ''}")
))
try:
_db().collection(OUTBOX_COLLECTION).add({
"to": (to_email or "").strip().lower(),
"subject": subject,
"text": text_content,
"html": html_content,
"links": links,
"codes": list(dict.fromkeys(_CODE_RE.findall(_visible_text(text_content, html_content)))),
"created_at": datetime.now(timezone.utc),
})
except Exception as e: # capture is best-effort; never break a send
logger.warning(f"local stack outbox: could not record email to {to_email}: {e}")
def list_emails(to_email: Optional[str] = None, limit: int = 20) -> List[Dict[str, Any]]:
"""Newest first. Filtering happens in memory (the outbox is small and test-only)."""
docs = [d.to_dict() | {"id": d.id} for d in _db().collection(OUTBOX_COLLECTION).stream()]
if to_email:
docs = [d for d in docs if d.get("to") == to_email.strip().lower()]
docs.sort(key=lambda d: d.get("created_at") or datetime.min.replace(tzinfo=timezone.utc), reverse=True)
for d in docs:
if isinstance(d.get("created_at"), datetime):
d["created_at"] = d["created_at"].isoformat()
return docs[:limit]