9.6 KiB
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
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 awatchprocess thatLISTENs for "Lancer une collecte" requests inserted by the site (collect_requesttable). Discovers Shorts via each channel'sUUSH…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_appfactory, which only assembles). Shared contextSite(site.py, inapp.state.site; routes get it viaSiteDep, the user viaCurrentUser); middlewares insecurity.py; templates/assets intemplating.py; one router per domain inroutes/— protected routers declaredependencies=[Depends(current_user)], public ones are listed inroutes.PUBLIC(tests enforce both).render.pyis the render pipeline (its docstring states the feature order). All SQL lives inweb/data/:repo.py(Repo, the only code that executes queries;live.py'sLISTENexcepted),sql_j7.py,sql_evolution.py,sql_highlight.py(query builders); elsewhere only the catalogs' field expressions (whitelist) — a test forbids SQL outsidedata/. Source-dependent behavior goes throughsources.py(source_of(cfg): validate, filters, queries, compat, transposed, build, default op) — don't addif cfg.source == "evolution"branches. Spec layers are walked and recognized only throughspec_layers.py(walk,category_of,HL_LINE...). Chart dimensions (label limits, heights, facet/legend reserves) are defined once inchart_layout.py(assemble()builds single/faceted specs; the page getspage_layout()viadata-layout, read byrender.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.pyeach layer one feature onto the spec;transfer.pyhandles chart export/import formats. Names used across modules are public (no_nameimported 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 objected),share-dialog.js,transfer.js, plus page entries. Only the Vega bundle is a classic script (globalShortstatsVega). Assets are served at/static/<content hash>/…viaasset('…')in templates (imported modules inherit the hash;immutablecache) — never?v=and never the version number. Every new static folder must be listed inpyproject.tomlpackage-data (tested). Accounts come from ausers.txtfile (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.pyrelays only the event type over the/wsWebSocket; 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.pytranslates them to PostgreSQL ARE (pattern_sourceskeeps the input,patternsthe translation; classification only readspatterns). Unsupported constructs are refused, not approximated.comment_themes.pyis shared by collector and site (adding a theme recomputes the whole history).
Database and migrations
- Schema
shortstats. Migrations are numbered SQL files insrc/shortstats/migrations/NNN_name.sql, applied once each in its own transaction, tracked inschema_migration.{{TIMEZONE}},{{DATABASE}},{{COLLECTOR_ROLE}},{{WEB_ROLE}}placeholders are substituted bymigrate.py. Never edit an applied migration; add a new file. grants.sqlis reapplied on everymigrateand 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.yamlanddeploy/.env.examplemust be copied verbatim into fenced blocks ofdocs/02-installation.md(tests/unitaires/test_documentation.py). The compose must not containbuild: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_configinchart_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).