# Dropwatch codebase map Read against `main` at `687d794` (2026-11-15). This page is for someone who has never opened the repository. It says what the code does and where, and links to the rules instead of repeating them. When this page and a file disagree, the file is right: fix this page in the same change. The diagrams and the reasons behind the shape are in [architecture/](architecture/README.md); the decisions are in [adr/](adr/README.md); running it is in [guides/](guides/README.md). ## The shape of it Dropwatch is one Python process that does two jobs on one asyncio event loop: a **mining loop** that watches Twitch streams for one account and claims what they earn, and a **FastAPI app** that serves a React dashboard and a JSON API over the loop's state. Everything it keeps is in one SQLite file. There are no other services: no queue, no cache server, no worker processes. ``` browser ──► uvicorn ─► HostCheck ─► FastAPI ├─ /api/health, /me, /setup, /login (public) ├─ /api/* ── require_session ──► views.py / runner / store ├─ /api/events (SSE) ◄── EventBus ◄── runner, sign-in, service └─ /* ── web/dist (the built page) MinerService ─► Runner.safe_tick() every 10 s ─► planner.plan() (pure) │ ├─► Watcher.send() ──► Twitch HLS + spade │ └─► TwitchClient ──► Twitch GQL, catalogue └─ PubSub events ◄── Twitch PubSub websocket Store (sqlite3, data/drops.db) ◄── everything above Notifier ◄── EventBus ──► notify.send_all() ──► Discord, Telegram, ntfy, ... ``` ## Directory map | Path | What is in it | |---|---| | `src/dropwatch/` | The miner and the API (Python 3.12). 37 `.py` files, 5,908 lines. | | `src/dropwatch/cli.py` | Entry point (`dropwatch` script): `signin`, `capture`, `lists`, `run`, `serve`, `openapi`. `serve` wires every part together. | | `src/dropwatch/service.py` | `MinerService`: starts and stops one `Runner` with its Twitch parts; `build_parts` builds them. | | `src/dropwatch/runner.py` | `Runner`: the mining loop. Refresh, plan, watch, claim, switch, pause, channel points, watch streaks, link probing. | | `src/dropwatch/planner.py` | `plan()`: decides what to mine and on which channel. Pure. | | `src/dropwatch/models.py` | Frozen dataclasses (`Campaign`, `Drop`, `LiveChannel`, `Prefs`) and the progress arithmetic. | | `src/dropwatch/store.py` | `Store`: the SQLite schema, additive migrations, every read and write. | | `src/dropwatch/events.py` | `EventBus`: in-process fan-out to the page and the notifier. | | `src/dropwatch/alerts.py` | `Notifier`: when to send a notification. | | `src/dropwatch/notify.py` | `CHANNELS` and `send()`: how to send one, per service. | | `src/dropwatch/backup.py` | Settings › Backup: `make_backup`, `restore_backup`. | | `src/dropwatch/images.py` | `ImageCache`: kept copies of the images History shows. | | `src/dropwatch/maintenance.py` | Database copy before an upgrade, `miner_health`, the `Watchdog`. | | `src/dropwatch/version.py`, `tz.py`, `redact.py` | Build info, time-zone lookup, the log filter that hides the Twitch token. | | `src/dropwatch/api/` | FastAPI: `app.py` (routes, `HostCheck`, `create_app`), `auth.py` (page password, cookie, login limiter), `models.py` (request and response models), `views.py` (state and history snapshots), `sse.py`, `signin.py`. | | `src/dropwatch/twitch/` | The Twitch protocol, ported from TwitchDropsMiner: `gql.py`, `client.py`, `parse.py`, `watch.py`, `pubsub.py`, `catalog.py`, `auth_device.py`, `auth_browser.py`, `constants.py`, `session.py`, `transport.py`, `capture.py`. | | `web/` | The dashboard: React 19, TypeScript, Vite, Tailwind. `web/src/views/` one file per tab, `web/src/screens/` the sign-in screens, `web/src/api/` the API client, generated types and the live-update client. | | `tests/` | 68 pytest files (472 test functions) and recorded, scrubbed Twitch responses in `tests/fixtures/`. The web tests sit next to their components as `*.test.ts(x)`. | | `docker/entrypoint.sh`, `Dockerfile` | The image: build the page with Node, run on `python:3.12-slim`. | | `unraid/dropwatch.xml`, `ca_profile.xml` | The Unraid Community Applications template and publisher profile. | | `.github/workflows/docker.yml` | The only CI workflow: tests, then publish the image on a `v*` tag. | | `docs/api/openapi.json` | The API schema, generated by `dropwatch openapi`. | | `docs/design/`, `docs/superpowers/` | Approved mockups and the original spec and plans. History of the work, not kept current. | | `reference/` | The MIT-licensed upstream projects the Twitch code was ported from, unmodified. Not used at runtime and excluded from lint and the image. | | `brand/` | The logo in every size; `brand/README.md` says which file goes where. | Counts: `git ls-files src | grep -c '\.py$'`, `wc -l src/dropwatch/*.py src/dropwatch/*/*.py`, `ls tests/test_*.py | wc -l`, `grep -c "def test_" tests/*.py`. ## Boot and the request path `main` in `src/dropwatch/cli.py`, for `dropwatch serve`: 1. `safe_backup_on_upgrade` copies `drops.db` to `drops.db.before-` when the build changed (`src/dropwatch/maintenance.py`). This runs before `Store` opens the file, because `Store` migrates it. 2. `Store(data_dir() / "drops.db")` creates missing tables and adds missing columns (`Store.__init__`). 3. `setup_logging` attaches `RedactFilter`, which replaces the current Twitch token with `***` in every log line. 4. `serve` builds the `EventBus`, `MinerService`, `SignInManager`, `ImageCache` and the FastAPI app, then starts three background tasks: `Notifier.run` (started first, so no event is missed), `keep_images`, and, only when `DROPWATCH_EXIT_WHEN_STUCK=1`, `watch_health`. 5. `MinerService.start()` starts mining if a Twitch session is saved, then `uvicorn.Server.serve()` runs until the process is stopped. The request path, from `create_app` in `src/dropwatch/api/app.py`: 1. `HostCheck` (ASGI middleware) answers 400 to any `Host` that is not an IP address, a bare name, a private suffix or a name in `DROPWATCH_HOSTS`. 2. Routers, in include order: `public` and `private_auth` from `api/auth.py`, then `api` from `api/app.py`. `private_auth` and `api` carry `Depends(require_session)`, which checks the `dm_session` cookie. 3. `_serve_web` mounts `/assets` and a catch-all `/{path:path}` that serves `index.html`. It is added last so it never shadows an API route, and it returns 404 for anything under `api/`. There is no other middleware: no CORS, no compression, no request logging (`access_log=False`). ## Subsystems ### The mining loop `MinerService._loop` (`src/dropwatch/service.py`) calls `Runner.safe_tick()` and sleeps for what it returns: about 10 s (`PLAY_INTERVAL`), or a back-off of 60 s doubling to 600 s after an error. A second task, `MinerService._events`, feeds PubSub events to `Runner.safe_handle`. Neither lets an exception out. When the state becomes `signed_out` the loop ends, the session is deleted and a `signin` event says so. `Runner.tick` (`src/dropwatch/runner.py`) in order: end a pause or a watch-streak visit that is due, `refresh()` every 5 minutes (`REFRESH_EVERY`), play each channel-points stream (`_tick_points`), play the drop channel (`Watcher.send`), count failures and set a channel aside after 9 (`FAILS_BEFORE_SWITCH`), and resync progress after 18 silent ticks (`STALL_TICKS`). `refresh()` re-reads campaigns when they are due (`campaigns_every_minutes`, default 60) and live channels every time, then runs `_plan`, which calls `planner.plan()` and acts on the result. Start with the module docstring of `runner.py`, then `tick`. ### Deciding what to mine `plan()` in `src/dropwatch/planner.py` takes campaigns, live channels, `Prefs` and `now`, and returns a `Plan`: the current choice and the queue, Needs you, done, waiting and outside lists. Order: Priority games in list order, then pins, then known-linked before unknown-link campaigns, then least spare time first (`campaign_ratio` in `models.py`). `_hold_current` keeps the current campaign unless a challenger has 20% less spare time (`HYSTERESIS`). Channels rank favourite, then allowed, then any, by viewers. ### Twitch All Twitch traffic is in `src/dropwatch/twitch/`. `Gql` posts persisted queries (hashes in `GQL_OPS`, `constants.py`) at most 5 a second, in batches of 20, with 3 tries. `TwitchClient` builds the reads the runner needs on top of it. `Watcher` simulates HLS playback and posts the minute-watched event. `PubSub` keeps one websocket. `Catalog` reads the public campaign list the TV login cannot see. Sign-in is `DeviceCodeSignIn` (`auth_device.py`); `BrowserSignIn` (`auth_browser.py`) is a PC-only fallback that needs the optional `browser` extra. Start with `twitch/constants.py`, then `client.py`. ### Identity and the page password There is one Twitch account per install (the `session` table holds one row, `CHECK (id = 1)`) and one page password for everyone who opens the dashboard. `api/auth.py` owns setup, login, logout, the `dm_session` cookie (30 days, `HttpOnly`, `SameSite=Strict`) and `LoginLimiter` (5 wrong passwords per address per 15 minutes, in memory). `Store` keeps the argon2 hash and only the sha256 of each session token. There are no roles: a signed-in browser can do everything. ### Data `src/dropwatch/store.py` owns all of it: 12 tables in `SCHEMA` plus key-value rows in `settings`. Migrations are additive and run in `Store.__init__` (`ALTER TABLE ... ADD COLUMN` when a column is missing). Calls are synchronous `sqlite3` on the event loop thread. Files beside the database: `catalog.json` (the last good catalogue) and `images/` (kept images). See [data-flows.md](architecture/data-flows.md#key-data-structures) for every shape. ### Live updates `EventBus` (`src/dropwatch/events.py`) gives each subscriber a queue of 100 and drops the oldest when one is full, so a slow browser never slows the miner. `/api/events` streams it as server-sent events (`api/sse.py`), with a ping every 15 s, and ends when the page session is gone. The page treats any event as "something changed" and re-fetches `/api/state` after 500 ms (`web/src/api/live.ts`). ### Notifications `Notifier` (`src/dropwatch/alerts.py`) subscribes to the same bus and runs time-based checks every 30 s. It decides what to say; `notify.send_all` sends it to every configured channel, one HTTPS POST each with a 10 s budget. The 7 services and their fields are the `CHANNELS` table in `src/dropwatch/notify.py`. ### The dashboard `web/src/App.tsx` picks a screen from `/api/me` (setup, login, or the tabs) and the hash route (`web/src/router.ts`). `web/src/store.tsx` holds the one shared store: who is signed in, the miner's state, whether the miner is reachable, and toasts. `web/src/api/client.ts` wraps `fetch`; its types come from `web/src/api/types.ts`, generated from `docs/api/openapi.json`. Views: Overview, Priorities, Channel points, History, Activity, Settings. ### Build, release and deployment `Dockerfile` builds the page in `node:24.16.0-bookworm-slim`, then installs the Python package with `uv` into `python:3.12.7-slim-bookworm`. It refuses to build without `DROPWATCH_COMMIT`. `docker/entrypoint.sh` chowns `/data` to `PUID:PGID` and `exec`s the miner through `setpriv`, so it is PID 1. The `docker` workflow runs the Python and web tests and then pushes `ghcr.io/kernelpanic-studios/dropwatch:` and `:latest` on a `v*` tag. Unraid installs from `unraid/dropwatch.xml`, which Community Applications reads from `main`. The release steps are in [development.md](development.md#releasing). ## Sources of truth | Concept | Authoritative file | Enforced by | |---|---|---| | API routes and shapes | `src/dropwatch/api/app.py`, `api/auth.py`, `api/models.py` | `tests/test_openapi.py` (`docs/api/openapi.json` must match a fresh build) | | The page's API types | `docs/api/openapi.json` | `web/src/api/types.freshness.test.ts` (regenerates `types.ts` and compares) | | Which routes need a page session | the router each route is on | `tests/test_auth_api.py` (`PRIVATE` must equal every non-public route, and each must answer 401) | | Database schema | `SCHEMA` and the migrations in `Store.__init__` | Indirectly, by the store tests; no check that an old database migrates to the current shape | | Settings keys, types and defaults | `SETTINGS` and `SETTING_DEFAULTS` in `store.py` | **No guard** on the copies in `SettingsIn` and `SettingsOut` (`api/models.py`); a missing default fails only where a test builds `SettingsOut`. The settings table in [configuration.md](guides/configuration.md) is generated: `tests/test_docs_generated.py` | | Notification services and fields | `CHANNELS` in `notify.py` | `tests/test_notify_send.py` (every channel has fields and a hint); the field tables in [notifications.md](guides/notifications.md) are generated: `tests/test_docs_generated.py` | | What Activity shows of each event | `ACTIVITY_FIELDS` in `api/app.py` | **No guard.** A new `log_event` kind missing from it is stored but never shown | | Live event kinds the page listens to | `EVENT_KINDS` in `web/src/api/live.ts` | **No guard.** `claim_failed` is published on the bus but not listened to (harmless today: nothing on the page needs it) | | Twitch query hashes | `GQL_OPS` in `twitch/constants.py` | Recorded fixtures in `tests/fixtures/` | | Version | `version` in `pyproject.toml` | `tests/test_openapi.py` (the schema carries it); `web/package.json` repeats it with **no guard** | | Runtime dependencies and their licences | `uv.lock`, `web/package-lock.json` | `tests/test_docs_generated.py` ([third-party-packages.md](third-party-packages.md) must match, and every licence must be on the allowed list) | | Lint rules | `[tool.ruff]` in `pyproject.toml` | Run by hand (`uv run ruff check src tests`); **not run in CI** |