shortstats/CLAUDE.md
ploush 81ef12a9cd
Some checks failed
build / test (push) Failing after 2m48s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
upgrade 1.4.0
2026-11-29 20:43:50 +01:00

54 lines
9.6 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project
shortstats tracks YouTube Shorts statistics from 1 hour to 3 years after publication (full snapshot at 7 days) into PostgreSQL, and serves a private web site ("Shorts Stats") for exploring them with Vega-Lite charts. **Everything is in French**: code comments, docstrings, log/error messages, UI strings, docs, commit history. Keep new text in French.
`docs/01-documentation-technique.md` is the authoritative design document (architecture, schema, roles, chart rules, and the rationale for each choice); read the relevant section before changing behavior. `docs/02-installation.md`, `docs/03-utilisation.md` (also summarized in the site's "Aide" page), `docs/04-sql-minimal.md` cover deployment, usage and the 4 bootstrap SQL commands.
## Commands
```sh
pip install --constraint constraints.txt -e ".[collector,web,dev]" # Python >= 3.12 (images use 3.13)
npm ci && npm run build # bundles Vega into src/shortstats/web/static/vendor/vega-bundle.js (needed to render charts locally)
pytest # all tests (progress lines every 5 s; -v or --progression=0 for pytest's usual output)
pytest tests/unitaires # one category: unitaires | integration | non_regression (or -m unitaires)
pytest tests/unitaires/test_axes.py -k zoom # one file / pattern
REGENERER_REFERENCES=1 pytest tests/non_regression # rewrite frozen references after an intended change
```
Tests that touch PostgreSQL are **skipped** unless `TEST_OWNER_URL`, `TEST_COLLECTOR_URL`, `TEST_WEB_URL` are set, pointing at a database created with `sql/bootstrap.sql` (roles `shortstats_owner` / `shortstats_collector` / `shortstats_web`, passwords `remplacer-mdp-*`). (In CI, `CI` is set and a missing database fails instead.) The session fixture in `tests/conftest.py` runs the migrations itself; `clean_db` truncates all tables between tests. See `.forgejo/workflows/build.yaml` for the exact CI setup (private Postgres on a Unix socket, SCRAM auth). The YouTube API is faked with `tests/outils/fake_youtube.py` (httpx `MockTransport`).
Tests are organized by **category, then feature** (not by release): `tests/unitaires/` (no DB, no app), `tests/integration/` (DB and/or the app's test client), `tests/non_regression/` (frozen references in `references/`: hashes of 6 851 specs built without DB, 379 API renders on a deterministic DB, catalog, periods, route inventory with anonymous responses; migrations replayed on an older schema; legacy configs; fixed bugs; Chromium walkthroughs via Playwright, skipped if not installed). Shared helpers live in `tests/outils/` (fake rows, DB seeding, site client, collector helpers, spec readers, `references.py`, `progression.py`); shared fixtures in `tests/conftest.py`. Put a new test in the category/feature file it belongs to; a structural refactor must keep the references identical (`REFERENCES_SORTIE=<dir>` writes differing results for diffing).
CLI (`shortstats.cli:main`): `migrate`, `collect`, `watch`, `hash-password <user>`, `web`. Configuration is environment-only (`config.py`); every variable also accepts a `NAME_FILE` variant (Docker secrets).
Images: `docker build --target collector|web .` (one Dockerfile, multi-stage; the Vega bundle is built in a Node stage). CI (Forgejo) tests, then builds and pushes both images on `main` and `v*` tags.
## Architecture
Two independent processes from one Python package, communicating **only through PostgreSQL**:
- **Collector** (`collector.py`, `youtube.py`, extra `[collector]`): run periodically by supercronic (`docker/collector-entrypoint.sh`) plus a `watch` process that `LISTEN`s for "Lancer une collecte" requests inserted by the site (`collect_request` table). Discovers Shorts via each channel's `UUSH…` playlist, takes snapshots on a 151-step schedule (hourly on day 1 … monthly to 3 years, most urgent first), reads all comments within a quota cap, and classifies them into themes.
- **Web** (`web/`, extra `[web]`): FastAPI + Jinja2 + uvicorn (`web.app:create_app` factory, which only assembles). Shared context `Site` (`site.py`, in `app.state.site`; routes get it via `SiteDep`, the user via `CurrentUser`); middlewares in `security.py`; templates/assets in `templating.py`; **one router per domain in `routes/`** — protected routers declare `dependencies=[Depends(current_user)]`, public ones are listed in `routes.PUBLIC` (tests enforce both). `render.py` is the render pipeline (its docstring states the feature order). **All SQL lives in `web/data/`**: `repo.py` (`Repo`, the only code that executes queries; `live.py`'s `LISTEN` excepted), `sql_j7.py`, `sql_evolution.py`, `sql_highlight.py` (query builders); elsewhere only the catalogs' field expressions (whitelist) — a test forbids SQL outside `data/`. **Source-dependent behavior goes through `sources.py`** (`source_of(cfg)`: validate, filters, queries, compat, transposed, build, default op) — don't add `if cfg.source == "evolution"` branches. Spec layers are walked and recognized only through `spec_layers.py` (`walk`, `category_of`, `HL_LINE`...). Chart dimensions (label limits, heights, facet/legend reserves) are defined once in `chart_layout.py` (`assemble()` builds single/faceted specs; the page gets `page_layout()` via `data-layout`, read by `render.js`). Chart domain, one role per module, layered without cycles: `chart_catalog` (fields, steps, measures, types) ← `chart_config` (`ChartConfig`, validation, legacy remap, type rules) ← `chart_view` (`View`, filters) ← `chart_aggregate`, `chart_zoom` ← `charts` (Vega-Lite specs for 7-day charts only) ← `chart_controls` (controls under a chart, editor catalog). `evolution.py`, `multi.py` (multiple Y / two axes), `highlight.py`, `legends.py`, `transpose.py`, `marks.py` each layer one feature onto the spec; `transfer.py` handles chart export/import formats. Names used across modules are public (no `_name` imported elsewhere).
- **Front end**: native **ES modules** in `static/js/` (no build step): `util.js` (DOM, formats, `api`), `render.js`, `controls.js`, `dashboard.js` (entry), `editor/` (`menus`, `axes`, `aggregations`, `editor`: modules share an explicit context object `ed`), `share-dialog.js`, `transfer.js`, plus page entries. Only the Vega bundle is a classic script (global `ShortstatsVega`). Assets are served at `/static/<content hash>/…` via `asset('…')` in templates (imported modules inherit the hash; `immutable` cache) — never `?v=` and never the version number. Every new static folder must be listed in `pyproject.toml` package-data (tested). Accounts come from a `users.txt` file (Argon2id, `auth.py`), with per-user password overrides in the DB.
- **Live updates**: collector and site emit `NOTIFY shortstats_events` (inside the transaction); `web/live.py` relays only the event *type* over the `/ws` WebSocket; browsers then re-fetch the page zone (`data-live-on`) or chart through normal authenticated routes. No data travels over the WebSocket.
- **Themes**: users write PCRE2/regex101-style patterns; `regex_adapter.py` translates them to PostgreSQL ARE (`pattern_sources` keeps the input, `patterns` the translation; classification only reads `patterns`). Unsupported constructs are refused, not approximated. `comment_themes.py` is shared by collector and site (adding a theme recomputes the whole history).
### Database and migrations
- Schema `shortstats`. Migrations are numbered SQL files in `src/shortstats/migrations/NNN_name.sql`, applied once each in its own transaction, tracked in `schema_migration`. `{{TIMEZONE}}`, `{{DATABASE}}`, `{{COLLECTOR_ROLE}}`, `{{WEB_ROLE}}` placeholders are substituted by `migrate.py`. Never edit an applied migration; add a new file.
- `grants.sql` is reapplied on every `migrate` and defines least-privilege rights per role. **Any new table/view/column the collector or site needs must be granted there**; tests verify each role can do what it should and nothing else. The site never runs migrations (it doesn't hold owner rights).
- The 151-step snapshot schedule exists both in Python and in the DB (migration 008); tests check they stay identical.
### Invariants enforced by tests
- `deploy/compose.yaml` and `deploy/.env.example` must be copied **verbatim** into fenced blocks of `docs/02-installation.md` (`tests/unitaires/test_documentation.py`). The compose must not contain `build:` and may only mount `./users.txt`.
- Saved/exported/shared chart configs from older versions must keep working: old keys are remapped (e.g. `remap_legacy_config` in `chart_config.py`, step → age in 1.3.2, transfer format 1 → 2).
## Releases
The version number is **never written in the repo**: it comes from git tags (`scripts/version.sh`: `X.Y.Z` on tag `vX.Y.Z`, `X.Y.Z.postN+g<sha>` elsewhere, `+modifie` / `.modifie` with uncommitted changes), fed to the package by `setup.py` (`SHORTSTATS_VERSION` env, else the script) and read back at runtime from package metadata (`shortstats.__version__`). Code may only *display* it (Aide page, `--version`); static asset cache-busting (`?v=`) is a content hash (`assets_version`), never the version. CI computes it once, tests with it, passes it as Docker build arg `VERSION`, and checks the built image reports it. `main` builds are a rolling release (`latest`, `main`, `sha-…`, `X.Y.Z.postN-g<sha>` image tags). `CHANGELOG.md` (French release notes, newest first) needs a `## X.Y.Z` section before tagging (checked by tests on tag builds). The docs' test table (section 12 of the technical doc) says what each release added. Test output uses the progress plugin `tests/progression.py` (`--progression=0` or `-v` for pytest's usual output).