Coverage for src/retrospeedlab/backend/main.py: 73%
260 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-03 23:09 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-03 23:09 +0000
1import asyncio
2import os
3from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine
4from contextlib import asynccontextmanager
5from functools import partial
6from time import perf_counter
8import sentry_sdk
9import uvicorn
10from fastapi import FastAPI, Request, Response
11from fastapi.middleware.cors import CORSMiddleware
12from fastapi.responses import RedirectResponse
13from loguru import logger
14from sqlalchemy.orm import Session
15from starlette.routing import Host
17from retrospeedlab.addresses import GAMES_URL, STREAM_URL, WWW_URL
19from .alerts.bugsink import BugsinkAlerts
20from .alerts.gather import Gatherer
21from .alerts.router import router as alerts_router
22from .alerts.rules import ALERTS
23from .alerts.watch import AlertWatch, watch_alerts
24from .articles.metrics import measure_articles
25from .articles.publisher import publish_articles
26from .articles.router import articles_router
27from .autonomy.desk import follow_console
28from .autonomy.router import router as autonomy_router
29from .autonomy.switch import set_up_switch
30from .badges.herald import watch_badges
31from .chat_commands.router import router as chat_router
32from .commentary.chat_relay import ChatRelay
33from .commentary.commentator import Commentator
34from .config import (
35 APP_VERSION,
36 ARTICLE_KEYS,
37 BADGES,
38 BUGSINK_ALERTS_DSN,
39 BUGSINK_API_BASE,
40 BUGSINK_API_TOKEN,
41 DECISIONS,
42 DISCORD,
43 DISCORD_LOGIN,
44 KOFI_VERIFICATION_TOKEN,
45 KUMA_WEBHOOK_TOKEN,
46 OPENROUTER,
47 ORACLE_FEED_KEY,
48 RESTREAM,
49 SSO,
50 STAGE,
51 TWITCH,
52 VIDEO_DIR,
53)
54from .database import Base, engine, utc_now
55from .discord.presence import stay_online
56from .discord.records import RecordHerald
57from .engagement.router import router as engagement_router
58from .engagement.settings import ENGAGEMENT
59from .engagement.shipped import ship_regularly
60from .games.router import router as games_router
61from .games.videos import prune_regularly
62from .ghosts.router import router as ghosts_router
63from .ghosts.store import forget_regularly
64from .github.router import github_router
65from .highscores.router import router as highscores_router
66from .highscores.router import sign_in_router
67from .highscores.saving import new_claims
68from .hosts.router import router as hosts_router
69from .kofi.router import kofi_router, thanks_router
70from .kuma.router import kuma_router
71from .lab_runs.router import router as lab_runs_router
72from .lakehouse.outbox import prune_events_regularly
73from .lakehouse.router import router as lakehouse_router
74from .live.router import commentary, overlay, perks, questions, store
75from .live.router import router as live_router
76from .maintainer.decisions import decisions_router
77from .maintainer.router import router as maintainer_router
78from .narration.watcher import Observer, watch
79from .oauth.router import oauth_router
80from .oauth.session import OAuthSession
81from .oauth.store import seed_refresh_token
82from .observability import init_error_reporting
83from .oracle.feed import SHOWN_ANSWERS, OracleFeed
84from .oracle.router import oracle_router
85from .perks.desk import Apply, PerkDesk
86from .perks.emote_rain import rain_emotes
87from .perks.game_pick import pick_game
88from .perks.pick_prompt import PickPrompt
89from .perks.rewards import EMOTE_RAIN, NAME_WORKER, PICK_GAME
90from .perks.worker_names import name_worker
91from .players.identity import player_sessions
92from .players.router import players_router
93from .predictions.desk import PredictionDesk
94from .predictions.router import predict_router
95from .promotion.metrics import measure_regularly
96from .promotion.schedule import publish_regularly
97from .promotion.service import PROMOTED
98from .promotion.shorts import prune_renders_regularly
99from .promotion.upload import upload_regularly
100from .questions.answerer import Answerer
101from .questions.desk import QuestionDesk
102from .ratings.router import router as ratings_router
103from .recap.poster import recap_daily
104from .recap.reactions import measure_recaps
105from .releases.herald import ReleaseHerald
106from .releases.router import releases_router
107from .reports.router import router as reports_router
108from .restream.grant import PROVIDER as RESTREAM_PROVIDER
109from .restream.grant import restream_client
110from .restream.title_keeper import TitleKeeper
111from .rotation.router import router as rotation_router
112from .seasons.herald import watch_seasons
113from .seasons.router import router as seasons_router
114from .security_headers import secure_headers
115from .share.router import router as share_router
116from .sso.gate import Gate
117from .sso.router import sso_app
118from .stall.watchdog import StallWatch, watch_stalls
119from .tech_stack.router import router as tech_stack_router
120from .tech_stack.traffic import traffic
121from .twitch.channel_keeper import ChannelKeeper
122from .twitch.chat_guard import ChatGuard
123from .twitch.clip_router import clip_router
124from .twitch.clips import ClipMaker
125from .twitch.grant import twitch_client
126from .twitch.redemptions import RedemptionFeed
127from .twitch.rewards import ASK_REWARD, Reward
128from .twitch.support import SupportFeed
130DEVELOPMENT_STAGE = "development"
131DEVELOPMENT_PORT = 9000
132UNKNOWN_CLIENT = "-"
133PREDICTION_FILE = "predictions/bet.json"
134DEVELOPMENT = STAGE == DEVELOPMENT_STAGE
135CRASHED = 1
137init_error_reporting()
138restream = OAuthSession(restream_client(RESTREAM)) if RESTREAM is not None else None
139twitch = OAuthSession(twitch_client(TWITCH)) if TWITCH is not None else None
140clips = ClipMaker(twitch, DISCORD) if twitch is not None else None
141predictions = PredictionDesk(twitch, VIDEO_DIR / PREDICTION_FILE) if twitch is not None else None
142releases = ReleaseHerald(DISCORD, GAMES_URL)
143bugsink_alerts = BugsinkAlerts(BUGSINK_API_BASE, BUGSINK_API_TOKEN, BUGSINK_ALERTS_DSN)
146def _observers() -> list[Observer]:
147 observers: list[Observer] = []
148 if RESTREAM is None or restream is None:
149 logger.info(
150 "Stream titles are off: set RESTREAM_CLIENT_ID, RESTREAM_CLIENT_SECRET, "
151 "RESTREAM_REFRESH_TOKEN and RESTREAM_CHANNEL_IDS"
152 )
153 else:
154 seed_refresh_token(RESTREAM_PROVIDER, RESTREAM.refresh_token)
155 observers.append(TitleKeeper(restream, RESTREAM.channel_ids, OPENROUTER, ENGAGEMENT).observe)
156 if twitch is None or clips is None:
157 logger.info("Twitch category, tags and bio are off: set TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET")
158 else:
159 observers.append(ChannelKeeper(twitch, ENGAGEMENT).observe)
160 observers.append(clips.observe)
161 observers.append(ChatGuard(twitch).observe)
162 if DISCORD is None:
163 logger.info("Discord posts are off: set DISCORD_BOT_TOKEN and the DISCORD_* channels and roles")
164 else:
165 observers.append(RecordHerald(DISCORD, f"{WWW_URL}/progress").observe)
166 if OPENROUTER is None:
167 logger.info("Live commentary and chat are off: set OPENROUTER_API_KEY and OPENROUTER_MODEL")
168 else:
169 observers.append(Commentator(OPENROUTER, commentary, ChatRelay(), ENGAGEMENT).observe)
170 if PROMOTED is not None:
171 observers.append(PROMOTED.scout.observe)
172 return observers
175def _promotion_runs() -> list[Coroutine[None, None, None]]:
176 if PROMOTED is None:
177 return []
178 scout = PROMOTED.scout
179 return [
180 PROMOTED.desk.run(),
181 scout.watch_new_games(),
182 scout.recap_weekly(),
183 measure_regularly(PROMOTED.settings),
184 publish_regularly(PROMOTED.publisher),
185 upload_regularly(PROMOTED.uploader),
186 prune_renders_regularly(PROMOTED.desk.media),
187 publish_articles(ARTICLE_KEYS, PROMOTED.desk.critic),
188 ship_regularly(PROMOTED.console),
189 follow_console(PROMOTED.console),
190 ]
193def _redemption_runs() -> list[Coroutine[None, None, None]]:
194 if twitch is None:
195 logger.info("Channel point rewards are off: set TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET")
196 return []
197 served: dict[Reward, Apply] = {
198 NAME_WORKER: partial(name_worker, perks),
199 PICK_GAME: partial(pick_game, perks),
200 EMOTE_RAIN: partial(rain_emotes, perks, twitch),
201 }
202 support = SupportFeed(twitch)
203 runs = [support.run(), support.watch_scopes(), PickPrompt(twitch).run()]
204 if OPENROUTER is None:
205 logger.info("Ask the AI is off: it needs OpenRouter")
206 feed = RedemptionFeed(twitch, tuple(served), support)
207 return [feed.run(), *runs, *PerkDesk(feed, served).runs()]
208 feed = RedemptionFeed(twitch, (ASK_REWARD, *served), support)
209 desk = QuestionDesk(feed, Answerer(OPENROUTER, store, questions))
210 return [feed.run(), desk.run(), *runs, *PerkDesk(feed, served).runs()]
213# a dead loop leaves the API up but its feature silent, so the whole process exits and Dokku restarts it
214def stop_on_crash(task: asyncio.Task[None]) -> None:
215 if task.cancelled() or (error := task.exception()) is None:
216 return
217 logger.opt(exception=error).error(f"The background task {task.get_name()} crashed, so the backend restarts")
218 sentry_sdk.flush()
219 os._exit(CRASHED)
222def started(run: Coroutine[None, None, None]) -> asyncio.Task[None]:
223 task = asyncio.create_task(run, name=run.__qualname__)
224 task.add_done_callback(stop_on_crash)
225 return task
228@asynccontextmanager
229async def lifespan(_: FastAPI) -> AsyncIterator[None]:
230 Base.metadata.create_all(engine)
231 if PROMOTED is not None:
232 with Session(engine) as session:
233 set_up_switch(session)
234 observers = _observers()
235 runs = [watch(store, observers)] if observers else []
236 runs += _redemption_runs()
237 runs += _promotion_runs()
238 alerts = AlertWatch(ALERTS.rules, Gatherer(ALERTS, store, overlay, utc_now()), bugsink_alerts)
239 runs += [watch_alerts(alerts, ALERTS.check_seconds), releases.watch(), watch_seasons(DISCORD)]
240 runs += (
241 [watch_badges(DISCORD, BADGES), stay_online(DISCORD.token), measure_recaps(DISCORD.token)] if DISCORD else []
242 )
243 runs += [predictions.watch()] if predictions is not None else []
244 runs += [prune_regularly(), forget_regularly(), prune_events_regularly()]
245 runs += [measure_articles(ARTICLE_KEYS)] if ARTICLE_KEYS is not None else []
246 runs += [recap_daily(store, DISCORD, OPENROUTER)]
247 runs += [watch_stalls(StallWatch(store, DISCORD, OPENROUTER, utc_now()))]
248 tasks = [started(run) for run in runs]
249 yield
250 for task in tasks:
251 task.cancel()
254app = FastAPI(
255 title="Retro Speedlab API",
256 description=(
257 "Retro Speedlab speedruns its own AI-designed 8-bit games with frame-exact movies, verified from power-on. "
258 "This API serves the current run, the last run of every RetroSpeedLab24 game, the lab reports and the live "
259 "stream."
260 ),
261 version=APP_VERSION,
262 root_path="" if DEVELOPMENT else "/api",
263 docs_url="/docs" if DEVELOPMENT else None,
264 redoc_url="/redoc" if DEVELOPMENT else None,
265 openapi_url="/openapi.json" if DEVELOPMENT else None,
266 lifespan=lifespan,
267)
269app.add_middleware(
270 CORSMiddleware,
271 allow_origins=[WWW_URL, STREAM_URL, GAMES_URL],
272 allow_credentials=True,
273 allow_methods=["GET", "POST", "PUT", "DELETE"],
274 allow_headers=["*"],
275 expose_headers=["ETag", "X-Seeds"],
276)
277app.middleware("http")(secure_headers)
280def _client(request: Request) -> str:
281 return request.client.host if request.client is not None else UNKNOWN_CLIENT
284@app.middleware("http")
285async def record_traffic(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
286 started = perf_counter()
287 response = await call_next(request)
288 traffic.record(request.method, request.url.path, perf_counter() - started)
289 logger.info(f'{_client(request)} "{request.method} {request.url.path}" {response.status_code}')
290 return response
293app.include_router(reports_router)
294app.include_router(lab_runs_router)
295app.include_router(chat_router)
296if predictions is not None:
297 app.include_router(predict_router(predictions))
298app.include_router(maintainer_router)
299app.include_router(autonomy_router)
300app.include_router(tech_stack_router)
301app.include_router(live_router)
302app.include_router(releases_router(releases))
303app.include_router(github_router(bugsink_alerts))
304app.include_router(games_router)
305app.include_router(highscores_router)
306app.include_router(ghosts_router)
307app.include_router(ratings_router)
308app.include_router(seasons_router)
309app.include_router(lakehouse_router)
310app.include_router(alerts_router)
311app.include_router(hosts_router)
312app.include_router(engagement_router)
313app.include_router(rotation_router)
314app.include_router(share_router)
315app.include_router(thanks_router)
316app.include_router(articles_router(None if SSO is None else Gate(SSO), ARTICLE_KEYS, None if SSO is None else SSO.url))
317if KOFI_VERIFICATION_TOKEN is None:
318 logger.info("Ko-fi thanks are off: set KOFI_VERIFICATION_TOKEN")
319else:
320 app.include_router(kofi_router(KOFI_VERIFICATION_TOKEN, DISCORD))
321if ORACLE_FEED_KEY is None:
322 logger.info("The Oracle on stream is off: set ORACLE_FEED_KEY")
323else:
324 app.include_router(oracle_router(OracleFeed(SHOWN_ANSWERS), ORACLE_FEED_KEY))
325if KUMA_WEBHOOK_TOKEN is None:
326 logger.info("Uptime Kuma alerts are off: set KUMA_WEBHOOK_TOKEN")
327else:
328 app.include_router(kuma_router(KUMA_WEBHOOK_TOKEN, bugsink_alerts))
329if DECISIONS is None:
330 logger.info(
331 "The owner's decisions on ops steps are off: set DISCORD_OWNER_ID, DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET"
332 )
333else:
334 app.include_router(decisions_router(DECISIONS))
335if DISCORD_LOGIN is None:
336 logger.info("Saving highscores is off: set DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET")
337else:
338 claims = new_claims()
339 app.include_router(sign_in_router(DISCORD_LOGIN, player_sessions(), claims))
340 app.include_router(players_router(DISCORD_LOGIN, player_sessions(), claims))
341if SSO is None:
342 logger.info("The owner sign-in is off: set SSO_URL, SSO_SECRET, DISCORD_OWNER_ID and SSO_HOSTS")
343else:
344 app.router.routes.insert(0, Host(SSO.host, app=sso_app(SSO, WWW_URL)))
345for session in (restream, twitch):
346 if session is not None:
347 app.include_router(oauth_router(session))
348if clips is not None:
349 app.include_router(clip_router(clips))
352@app.get("/health", include_in_schema=False)
353def health() -> dict[str, str]:
354 return {"status": "ok"}
357if DEVELOPMENT:
359 @app.get("/", include_in_schema=False)
360 def docs_redirect() -> RedirectResponse:
361 return RedirectResponse(url="/docs")
364def main() -> None:
365 uvicorn.run(
366 "retrospeedlab.backend.main:app",
367 host="0.0.0.0",
368 port=DEVELOPMENT_PORT,
369 reload=True,
370 reload_dirs=["src"],
371 access_log=False,
372 )
375if __name__ == "__main__":
376 main()