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

71 lines
3.1 KiB
Python

"""Deterministic audio search for the local stack (no flacfetch, no YouTube).
Returns up to three results for any artist/title, in the shapes the web UI
ranks: a well-seeded lossless torrent (the "BEST CHOICE"), a Spotify match and a
YouTube upload. Downloads are served by ``pipeline.fake_download_audio``, keyed
on nothing but the job, so every provider "works".
"""
from __future__ import annotations
import hashlib
from typing import List
from karaoke_gen.audio_fetcher import AudioSearchResult, NoResultsError
def _source_id(provider: str, artist: str, title: str) -> str:
return hashlib.sha1(f"{provider}:{artist}:{title}".lower().encode()).hexdigest()[:16]
class FakeAudioSearchService:
"""Drop-in for ``AudioSearchService`` (the methods the API routes call)."""
last_remote_search_id = None
def search(self, artist: str, title: str) -> List[AudioSearchResult]:
from backend.services.fake_workers.config import get_fake_config
config = get_fake_config()
duration = int(config.audio_duration_seconds)
candidates = [
AudioSearchResult(
title=title, artist=artist, provider="RED",
url=None, duration=duration, quality="FLAC 16bit CD",
source_id=_source_id("RED", artist, title), seeders=120,
target_file=f"01 - {title}.flac",
raw_result={
"year": 2001, "label": "Fake Records", "release_type": "Album",
"is_lossless": True, "seeders": 120, "match_score": 1.0,
"quality_str": "FLAC 16bit CD", "formatted_duration": f"{duration // 60}:{duration % 60:02d}",
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
},
),
AudioSearchResult(
title=title, artist=artist, provider="Spotify",
url=f"https://open.spotify.com/track/{_source_id('Spotify', artist, title)}",
duration=duration, quality="OGG 320kbps",
source_id=_source_id("Spotify", artist, title),
raw_result={"is_lossless": False, "quality_str": "OGG 320kbps", "match_score": 0.95},
),
AudioSearchResult(
title=f"{artist} - {title} (Official Video)", artist=artist, provider="YouTube",
url=f"https://www.youtube.com/watch?v={_source_id('YouTube', artist, title)[:11]}",
duration=duration, quality="opus 160kbps",
source_id=_source_id("YouTube", artist, title)[:11],
raw_result={"is_lossless": False, "channel": f"{artist}VEVO", "view_count": 1000000},
),
][: config.search_result_count]
if not candidates:
raise NoResultsError(f"No results for {artist} - {title} (fake search)")
for i, result in enumerate(candidates):
result.index = i
return candidates
async def search_async(self, artist: str, title: str) -> List[AudioSearchResult]:
import asyncio
return await asyncio.to_thread(self.search, artist, title)
def select_best(self, results: List[AudioSearchResult]) -> int:
return 0