Skip to content

Latest commit

 

History

History
1084 lines (899 loc) · 69.5 KB

deploy.md

File metadata and controls

1084 lines (899 loc) · 69.5 KB

Hosting

In short

There are two honest options, and choosing between them is not about technology but about whom you would rather pay, and how much.

Vercel + Neon ~€4/mo: a small VPS
Cost Hobby is free, but for personal, non-commercial use, and pauses a project past its monthly allowance; a class that relies on it wants a paid plan («Which Vercel plan», below) about €4 a month
Changes to the code webhook instead of polling, Postgres, FSM in the database none
The bot's response 1–3 s on a cold start instant
Reliability depends on two other companies' plans and their limits depends on you
Complexity noticeable docker compose up

Vercel is not the free way to serve a class. This page used to head that column «Free» and say to take it if being free was a hard requirement. Vercel offers its free plan, Hobby, for personal, non-commercial use, and this backend spends Hobby's monthly allowance on its own; past it the project is paused, and the bot, the digests and every phone's sync stop together. Hobby is enough to try the project out by yourself. For a deployment others rely on, take the first on a plan with higher function limits, a spend limit and an alert, or take the second, which is simpler, faster and requires rewriting nothing.

A third, the host target, is for what neither serves: native gRPC and the class's changes streamed to a phone as they happen. It is a beta, deployed nowhere yet («Option 3: the host target», below).

Why Vercel does not work "as is"

Three obstacles, and all of them are real.

The bot uses long polling. It holds an open connection to Telegram and waits. On Vercel there are no long-lived processes: a function wakes for a request and dies. Polling there is impossible in principle. What is needed is a webhook — Telegram knocks on your URL for every message.

SQLite does not survive a deploy. A function's file system is ephemeral. The database has to be external; Neon gives free Postgres, and the app already knows how to work with it through a DATABASE_URL with asyncpg.

Dialogue state would be lost between messages. By default aiogram keeps unfinished dialogues in the process's memory. On serverless, each message may land in a new instance, so the bot would forget the date you picked before you typed the assignment's text. Every multi-step flow would break: homework, invitations, substitutions, events, the timetable.

All three are solved. The webhook is app/api/telegram.py, mounted only when a secret is set. Postgres the app already handles. Dialogue state is app/fsm_storage.py, in the same database as the data; the side benefit is that a redeploy no longer cuts off a dialogue in progress. 24 tests cover both mechanisms.

Option 1: Vercel + Neon

What you need

  1. A Neon account — free Postgres.
  2. A Vercel account, on a plan that fits what it will serve: Hobby to try the project out by yourself, a plan with higher function limits for a class that relies on it («Which Vercel plan», below).
  3. A bot token from @BotFather.
  4. Your Telegram id from @userinfobot.

Which Vercel plan

Hobby is offered for personal, non-commercial use, by Vercel's own fair-use guidelines, and it includes a fixed amount of usage a month. On 11 October 2026 vercel.com/docs/plans/hobby gave 1,000,000 function invocations, 4 CPU-hours of Active CPU and 360 GB-hours of provisioned memory. Past any of them, that feature of a Hobby project is paused until 30 days have passed — and for this backend the feature is the function, which is all of it. Read the page again before you choose: the figures are Vercel's to change.

This backend spends that allowance by itself, before anybody uses anything:

  • the external cron calls the tick every five minutes («The clock», below), about 8,600 calls a month;
  • the self-check runs inside every tick, probing the diary's proxy and every «Сетевой город» region in use («The self-check, in every tick», below), so each tick holds the function for longer than the digests alone would;
  • a warm-up ping, if you keep one («If even that is slow», below), is as many again.

Then come the people: every message to the bot is a webhook call, and every phone's sync and every v2 call is another. The more classes a deployment serves, the sooner the month's allowance is gone, and when it is, the bot, the digests and every phone's sync stop at once, with nothing on the phone or in the chat saying why.

So a deployment others rely on wants a plan with higher function limits — on 11 October 2026 that was Pro, at $20 per developer seat a month, with spend management — and a spend limit with an alert set on it, so that a busy month raises a warning rather than a pause. Or it wants the VPS of option 2, which has no allowance to run out of. Hobby is enough to try the project out by yourself.

Releasing through dev and master

One temporary working branch targets dev. Merge only its checked head after the complete applicable CI jobs and review pass, then wait for the resulting dev-push CI. Promote dev to master in a separate pull request and verify that promotion's head again. Keep both persistent branches; automatic cleanup applies to the merged working branch. Do not reset dev to a production merge commit.

Vercel's Production environment must match master, with production aliases assigned automatically. A successful build is only part of the release: after master-push CI, read the production deployment's actual source SHA and target, and verify every API hostname installed APKs can retain. Each alias must point to that deployment and answer the warmup with the expected API/schema capabilities.

A retained branch alias does not follow a branch rename. The old git-main alias stayed on its previous deployment during #724's cutover. Reassign that compatibility alias to each newly verified master deployment, then read it back; checking the canonical hostname and new git-master alias alone misses old phones. Keep protected aliases protected. Their unauthenticated login redirect is not an application failure: use an authorized verification connection and never publish its temporary access URL, headers or credentials. Finish with deployment-scoped error/fatal logs after the warmups and CI; an empty query is a point-in-time check.

Release automation passes the full expected source SHA in the existing APK workflow's optional expected_commit input. The workflow compares it with the actual GITHUB_SHA before supplying signing inputs; a ref that advanced refuses before signing. Blank input retains ordinary manual-run behavior. The operator claims its uncertain dispatch receipt exclusively and reads back the exact run, so concurrent invocations or a timed-out response cannot submit twice blindly.

The exact merge, CI runs and production readback belong in the release PR's description and its tracking issue. The committed handover records the tested features and links to that delivery record; it cannot know its own future merge SHA. A release is not complete until those external outcomes are read back.

Secrets

Never send a token in a conversation, a commit or an issue. The token gives full control of the bot: reading every message, answering in its name, changing it. A leaked token is revoked in @BotFather with /revoke.

The right place is the host's environment variables. In Vercel: Settings → Environment Variables, and be sure to tick Sensitive, or the value can be read back in the interface.

Variable Value
BOT_TOKEN the token from BotFather
OWNER_IDS your Telegram id; several are comma-separated, see "Several owners" below
DATABASE_URL the Neon connection string, with the postgresql+asyncpg:// scheme
TIMEZONE the default time zone for new classes
WEBHOOK_SECRET a random string, see below
RUN_BOT false — polling does not start on serverless
CRON_SECRET a random string, see "The clock" below
BOT_USERNAME the bot's @name without the "@" — for the phone-linking link
PUBLIC_BASE_URL https://your-project.vercel.app — for the calendar and the diary sign-in page
DIARY_SECRET a random string, see "The electronic diary" below
DADATA_TOKEN a DaData key, see "The schools registry" below — without it the school search is simply off
DIARY_PROXY_URL optional: http://user:password@host:port of an HTTP proxy in Russia, for the diaries' requests DIARY_EGRESS sends through it: Petersburg's, which the city drops from abroad, and those of the twelve «Сетевой город» regions known to answer from it (#235, #334, #406). Empty means direct; see "The electronic diary" below
DIARY_EGRESS optional, and best left unset: direct, proxy or relay (#406). Unset, it is proxy where DIARY_PROXY_URL is usable and direct otherwise, which is what production did before the setting existed. direct sends nothing through the proxy even with one set; relay is read as direct until the relay exists (#408). Never a reason to refuse to start; see "The electronic diary" below
MIN_CLIENT_VERSION empty — or the oldest APK versionCode v2 still answers; raise it only once the newer APK is on the phones it would refuse
SENTRY_DSN optional: the DSN of the Sentry project errors and request timings go to, see "Errors and timings: Sentry" below. Empty sends nothing
GITHUB_READ_TOKEN optional: a fine-grained GitHub token, read-only access to public repositories, no other permission; the deploy check sends it, see "The self-check" below. Empty asks GitHub anonymously

Vercel applies them at deploy time: changing a value without rebuilding changes nothing, and the running deployment goes on holding the old one.

Every variable is scoped to an environment, and Preview has its own set (#118). A push to dev or to a pull request's branch builds a Preview, and it must not be pointed at Production's database or at the real bot, because Telegram gives its updates to whichever consumer registered the webhook last. So Preview holds:

  • its own DATABASE_URL, on the Neon branch preview, which was made from production with its data;
  • a second bot's BOT_TOKEN and BOT_USERNAME, and its own WEBHOOK_SECRET and DIARY_SECRET;
  • no CRON_SECRET, DADATA_TOKEN or PUBLIC_BASE_URL, so the tick, the school search, the link to the calendar feed that the bot's «📅 Календарь» offers and the diary's sign-in page are off there, each refusing in view of whoever it concerns.

Four keys are shared with Production: RUN_BOT (false), OWNER_IDS, TIMEZONE and DIARY_PROXY_URL. Two things follow from that. A preview reads and writes a real copy of the class, so what is tried there is tried on data that looks like production's; and RUN_BOT must stay false in Preview, because the key is shared with Production and on Vercel RUN_BOT=true makes the deployment refuse to start (the check in the next section). A preview's bot is a second one with a token of its own, so it cannot take the real bot's updates.

A revision is applied to the Neon branch preview when its pull request is pushed, and to production before the merge (CLAUDE.md, «Run the migration BEFORE the merge that needs it»). Otherwise the preview's code would know a column its database does not, and answer degraded from /api/v1/warmup.

What is missing is said at the door

Six of that table are ones a deployment does not survive, and each wrong one used to surface far from its cause. Now the process refuses to start and lists all of them at once — you do not pay another deploy to find the next. Four are refused when missing; WEBHOOK_SECRET is asked about only once BOT_TOKEN is set, because without a token there is no webhook to protect, so with both empty only the token is listed (#331). The other two are refused only when set to something that cannot be used (#322): an empty OWNER_IDS is left alone on purpose, because after the first owner the roles live in the database, and an unset TIMEZONE takes its default, Europe/Moscow. What stops the process is an OWNER_IDS with no readable id in it, or a TIMEZONE that is not a zone:

Variable What happened without it
DATABASE_URL the default sqlite+aiosqlite:///./lessons.db stood, and aiosqlite is deliberately not in requirements.txt — so everything died with ModuleNotFoundError: No module named 'aiosqlite' from inside SQLAlchemy, naming neither the variable nor the project
BOT_TOKEN neither polling nor webhook: Telegram's requests arrive at a route that was never registered
WEBHOOK_SECRET the webhook is not registered (an unauthenticated one would let anybody forge an update from any id) — the bot is deaf and looks like it is ignoring everyone
RUN_BOT not false — polling on a cold start takes the updates away from the webhook they were meant for
OWNER_IDS the value is there but no id is read from it: only a comma separates, a newline does not, and the field in Vercel is a textarea
TIMEZONE a name that does not exist in this Python build: nothing fails, and resolve quietly gives every new class Moscow

The check is switched on by the VERCEL variable, which the platform sets about itself, and by LESSONS_TARGET=host, which the host's image (option 3) sets about itself; a LESSONS_TARGET that says anything else is refused too, so that a misspelt marker cannot leave a deployment on the local defaults. Guessing "this looks like production" anywhere else would one day mean refusing to start on somebody's laptop, and that is worse than what the check prevents. Your own server (option 2) is configured by hand from the same table.

The rest are optional, and that is deliberate too. They do not fail the deployment; they are written to the log at startup as switched off: DIARY_SECRET (the diary), DADATA_TOKEN (the school search), PUBLIC_BASE_URL (the calendar and the sign-in page), BOT_USERNAME (the phone-linking link), CRON_SECRET (the tick answers 404 and not a single digest goes out) and SENTRY_DSN (no error and no timing is sent to Sentry). Each of them already refuses at its own door — in full view of whoever it concerns. GITHUB_READ_TOKEN is announced the same way, but it never refuses anything: empty, the deploy check below just asks GitHub anonymously, sharing sixty requests an hour with every other function on Vercel's address.

Invent WEBHOOK_SECRET yourself and show it to nobody:

python3 -c "import secrets; print(secrets.token_urlsafe(32))"

Invent CRON_SECRET the same way. Without it the reminder endpoint answers 404: a tick anybody can fire is a way to make the bot write to every subscriber whenever they feel like it.

Several owners

OWNER_IDS takes a list — on one line, comma-separated:

OWNER_IDS=111111111,222222222,333333333

Spaces around the numbers are trimmed, a semicolon is understood the same as a comma, and a trailing comma does no harm. @userinfobot will tell you your own id.

Only a comma (or a semicolon) counts as a separator. The value field in Vercel's interface is multi-line and positively invites one id per line — and then the list is not read at all:

What you typed What was read
111,222,333 111, 222, 333
111, 222, 333 111, 222, 333
111;222;333 111, 222, 333
111,222, 111, 222
111 222 333 nothing
one per line nothing
111,222x,333 111, 333

The last three rows are where people get burnt, and not all three the same way. On Vercel and on the host target, a value that reads as nothing — the space-separated list, one id per line — stops the deployment at the door with DeploymentNotConfigured, naming OWNER_IDS («What is missing is said at the door», above). What is still silent is the last row: a list that is partly readable is not empty, so nothing refuses, the bot starts, writes nothing to the log, and one particular person simply has no owner rights. So is your own server (option 2), where neither VERCEL nor LESSONS_TARGET is set and the check is not switched on at all: there an unreadable list starts a bot in which nobody is an owner. The parsing is in app/config.py, Settings.owner_id_list: anything that does not look like a number is quietly dropped.

The variable is read at build time. An edit does not reach a deployment that is already running — after changing the list you need a Redeploy, or the owners stay as they were.

A role from OWNER_IDS overrides a role in a class: such a person is the owner in every class of that deployment, not in one. OWNER cannot be granted from inside the bot and cannot be reached by escalation (app/bot/roles.py), so removing an owner likewise means editing the variable and redeploying.

The electronic diary

DIARY_SECRET is the key the electronic diary's session is encrypted with (app/crypto.py) — every session, whether this server signed in with a password or a phone signed in itself and registered what the diary gave it. It is the only credential in the project that cannot be stored as a hash: the diary's token is sent upstream on every request, so it is encrypted rather than hashed.

python3 -c "import secrets; print(secrets.token_urlsafe(48))"

Without it the diary is switched off entirely rather than running in plaintext: a silent fallback to plaintext would be invisible — the feature answers, and the only difference is in a column nobody looks at — and deployments live like that for years. "Too short" counts as missing: anything under 32 characters is refused at the same door, and the startup log says the diary is off rather than letting a set-but-unusable key look configured. A client can tell before anybody types a password: GET /api/v1/diary/capabilities answers "enabled": false, and every diary 503 carries X-Diary-Unavailable: disabled.

Three things worth knowing about this key:

  • It is needed only in Vercel's environment. It is not a GitHub Actions repository secret: no workflow imports this code. The tests set their own key (tests/conftest.py), and reminders.yml only pokes an already-deployed tick over HTTP.
  • It has to match across every Vercel environment that talks to the same database. A session sealed in Preview will not open in Production under a different key. Nothing breaks — an unreadable session counts as expired and the person signs in again — but it looks like a bug.
  • Changing the key signs everybody out. That is a legitimate way to revoke every stored diary session at once, if you suspect the database has leaked.

The diary also needs PUBLIC_BASE_URL: without it the bot has nowhere to get the sign-in page's address from, and it says so honestly rather than printing a link that would 404.

From abroad, the diaries need a Russian proxy. dnevnik2.petersburgedu.ru drops connections from outside Russia (#235), several «Сетевой город» regions do the same, and Vercel is outside Russia. The whole server cannot simply move there, because Telegram is blocked from Russian data centres. So the owner's decision of 5 October 2026 is that the bot and the API stay on Vercel and Neon, and only the diaries' requests go through Russia: DIARY_PROXY_URL names an HTTP proxy on a small Russian VPS (RUVDS was chosen), and a diary client sends its requests through it as a CONNECT tunnel (#334).

  • TLS stays end to end, so the proxy sees the diary's host name and never the family's credential.
  • The bot, Telegram, the database, DaData, GitHub and every region the route table leaves direct go direct as before.
  • The value can carry the proxy's password, so it is a secret like the others, and never logged.
  • An empty value means direct, which is right for a deployment inside Russia.
  • An unusable one (not http:// or https://, or no host) is ignored, and the startup log says so without quoting it.

Which diary goes through it is decided region by region (#406). The proxy carried Petersburg alone until 11 October 2026, when the RUVDS Squid ACL was widened to the 19 «Сетевой город» hosts of the allow-list (server/app/providers/netschool/regions.py) and each was asked for its school search through it. Twelve answered. Five answered with a WAF's 403 (Бурятия, Амурская, Приморский край, Томская, Тульская), and two did not answer at all (Рязанская, КЧР). A region that refuses the proxy's address gains nothing from it, so the route is per region, a static table the owner chose over trying one way and then the other: Region.via_proxy marks the twelve, Row.via_proxy marks Petersburg's row in providers/diary/registry.py, and registry.route reads both beside DIARY_EGRESS, which chooses the mode:

  • unset, or proxy: Petersburg and the twelve through the proxy where DIARY_PROXY_URL is usable, every other region direct; with no usable URL, everything direct. This is what production needs, and it sets nothing;
  • direct: nothing through the proxy, even with one set. It takes Petersburg off the proxy too, so there is no setting that undoes the «Сетевой город» half alone: a partial rollback is a revert;
  • relay: read as direct, and announced as such at startup, until the relay exists (#408).

A value that is none of the three is read as unset and announced without being repeated. v2's GetDiaryCapabilities reports the mode and each server's route (api.md).

The proxy should accept CONNECT to the hosts that go through it alone — dnevnik2.petersburgedu.ru:443 and the via_proxy hosts of regions.py, each on 443 except netcity.admsakhalin.ru on 11111, a port a stock squid.conf's SSL_ports does not hold — and ask for a password, or it is an open proxy on the internet. RUVDS's allows all nineteen «Сетевой город» hosts, so a region moved onto the proxy there needs no change on the VPS; anywhere else its host goes into the list first. One request through it to each diary is the test that it works, and the self-check makes one every tick for each region in use («Monitoring» below).

BOT_USERNAME and PUBLIC_BASE_URL are not secrets, but they are not guessable either. The first is needed so the app can show a t.me/<bot>?start=link_<code> link; without it the linking code still works, it is just typed by hand. The second is the address the bot hands out the class's calendar link at; the server does not take it from the request, because behind Vercel the function sees an internal host, and the bot builds the link with no request at all.

Telegram sends the webhook secret in the X-Telegram-Bot-Api-Secret-Token header on every request. Without checking that header your webhook address is an open endpoint anybody can send forged updates to: make themselves an editor, rewrite the timetable, wipe the homework. The check is mandatory.

The schools registry

DADATA_TOKEN is the key to the school search. When a class is created the bot asks for the school and looks it up by name; without a key that step stays what it always was — "type the name by hand".

Why an external service rather than a table in the repository: there is no downloadable all-Russian register of schools. Rosobrnadzor's open data — the very source everything findable on GitHub for this points at — answers 404 today. What there is, is the ЕГРЮЛ company register, where every school appears simply because every school is a legal entity, and DaData, which is a search over it that people actually use.

The key is taken from https://dadata.ru/profile/#info — you want the "API key", not the "secret key". The free plan is 10,000 requests a day. A search is one request, and two when the first finds nothing: an empty answer under the three school ОКВЭД codes is asked again without them, so that somebody who typed their own school's name is not told it does not exist. The results are paged locally, so the pages cost nothing.

Two doors spend that allowance, and one of them is capped. The bot and GET /api/v1/manage/schools search behind a class admin, a few searches per class created, and are not metered here. GET /api/v1/directory/school-regions is asked anonymously, by a phone that belongs to no class yet, so that door gets a fixed share: 4,000 requests per Moscow day, the empty-answer retry included, counted in the database (usage_counters, revision 0016). When the share is spent it answers 503 with X-Directory-Unavailable: spent and «выберите регион из списка» until Moscow midnight, while the other 6,000 stay for the bot's create-class step — which is what the cap exists to protect. Each caller is also held to twenty searches in fifteen minutes. The share is a constant (ANONYMOUS_DAILY_UNITS in app/services/quota.py), not a setting; on a paid plan with a larger allowance, change it there. Whether DaData's own day turns at Moscow midnight is not documented anywhere: if it counts in UTC, the worst case is two anonymous days inside one of DaData's, 8,000, which still leaves the admins 2,000.

Worth knowing:

  • The key lives only in the server's environment. It is not in the APK and must not be: the phone asks our server (GET /api/v1/manage/schools, or the anonymous GET /api/v1/directory/school-regions before it has a class), and the server goes upstream.
  • Twenty is a ceiling, not a number of matches. DaData's endpoint is built for type-ahead suggestions: it returns no more than twenty at a time and has no offset ("the next twenty"). So the answer honestly says «показаны первые 20» rather than «найдено 20», and the only way to reach your school is to add the town or the number.
  • A missing key is not a breakage. The search answers 503 with the words «введите название вручную», and a class is created as before; the anonymous directory answers 503 with X-Directory-Unavailable: disabled, and the region is picked from the list. There is deliberately no fallback list inside the project: a snapshot of the register would confidently answer with last year's schools, and nothing on the screen would tell you which you were looking at.

The Neon connection string

Paste it as it is. The app normalises it into what asyncpg understands by itself: it adds the driver, turns sslmode into a connection parameter, and strips channel_binding and anything else only libpq knows.

Neon offers two strings. Take the one with -pooler in the address. On serverless, instances come and go and each opens its own connections; without the pooler you will hit Postgres's limit before you notice.

There is one non-obvious price for that, and it is handled in the code. PgBouncer in transaction mode hands each transaction whichever backend is free, while asyncpg prepares statements on the connection it saw first. The mismatch surfaces under load rather than at startup, as an error reading prepared statement "__asyncpg_..." already exists. So for a pooler, prepared-statement caching is switched off automatically.

The direct string (without -pooler) works too, and is even marginally faster for a single request — but only if there is one instance. On Vercel there is not.

Creating and updating the schema

The schema is managed by Alembic. The same command serves an empty database and one that is already running:

cd server
DATABASE_URL='postgresql+asyncpg://...' .venv/bin/alembic upgrade head

Revision 0001 is a create_all with checkfirst: on an empty database it creates everything, on a live one only what is not there yet, and it brings that database under Alembic's management without rewriting anything. Revision 0002 widens five Telegram-id columns to 64 bits: Integer on Postgres is int4, and Telegram ids passed 2³¹ back in 2021, so the first person with a modern id crashed the bot on overflow. Columns that are already wide it leaves alone. Then the additive ones: 0003 — personal tasks, homework ticks, reminders, access requests, the log, device linking and the calendar token; 0004 — the Petersburg electronic diary's sessions, with no column for a password, because the password is not stored. 0005 adds a column for which break the canteen falls on; 0006 encrypts the diary credentials (and deletes the existing sessions — sealing them would mean keeping keys that had already sat in backups in the clear) and adds the per-member diary columns; 0007 adds the two foreign keys to classes.id that 0006 forgot to declare; 0008 gives a class a number (1–11) and cuts its year into quarters or half-years; 0009 creates the table of corrections laid over the diary; 0010 adds the class's join mode (classes.join_mode) and the table of personal connect codes; 0011 brings two timestamps in diary_overrides up to NOT NULL, the way the model builds them: 0009 declared them without it, and on a database built by a real alembic run the schema would have diverged from create_all — on ours it does not, because the DDL for 0009 came from the model. 0012 does the same for eight more timestamps across seven tables, and there it was not a no-op: all eight really were nullable, and all eight held no nulls, so it tightened them and rewrote nothing. 0013 adds uq_homework_per_subject_per_day. 0014 widens day_overrides.kind to VARCHAR(10): DayKind gained SELF_STUDY, and a SAEnum stores the member name, so the column is as wide as the longest of them. 0015 adds the columns a second diary provider needs: diary_sessions.provider and region and the three keep-alive clocks, and classes.diary_region, diary_school_id and diary_school_name — eight nullable columns, additive, to go on before the merge. Its downgrade expires every non-Petersburg session first, so code rolled back past this revision cannot read a «Сетевой город» credential as Petersburg's and replay it at the wrong upstream, and unbinds every class bound to «Сетевой город», which the old code would call «Санкт-Петербург» on the admin's card and «не привязан» behind the diary button. 0016 creates usage_counters — one row per external allowance per Moscow day, the anonymous school directory's share of DaData's — and nothing else: one new table, no existing row read or rewritten, additive, and it goes on together with 0015, before #140 merges. Its downgrade drops the table, which loses nothing but the counts. 0017 changes no schema at all: it files the corrections over the diary under the child instead of under a login (#165) — diary_overrides.login keeps its name and now holds the diary's scope, CHILD:petersburg or CHILD:netschool: and the regional server's host, and no other shape (a child the diary lists outside its own numbering gets no corrections at all). It deletes every legacy «Сетевой город» row (its region is inside a hash, recoverable at best for authors still signed in, and such rows exist only where #140's branch ran), deletes all but the newest row wherever two logins corrected the same field of the same child, and rewrites the rest of the old Petersburg rows to CHILD:petersburg. Its docstring carries the two counts to read before the transaction, one per destructive step. On PostgreSQL it first locks the table against writes until it commits, so a correction saved while it runs waits instead of making it roll back. On production, read on 26 September with no correction in it, that was nothing: it went on with 0015 and 0016 before the merge, at 12:26 UTC that day. On a deployment that holds corrections it is better applied just after the merge — see the third shape below. Its downgrade does nothing, on purpose — a login cannot be recovered from a scope, and the old code cannot read or write an upper-case scope under any login — but a revert is not lossless: what older code writes while it runs is filed under logins the new code never reads, and redeploying does not re-run 0017. After any such window, run its statements again, or alembic downgrade 0016 && alembic upgrade head, which re-runs it because the downgrade does nothing.

0018 adds one column, device_tokens.client_version: the app version each phone last sent with a v2 request, written by v2's gate beside last_seen_at and on its clock. It is nullable with no default, additive, and on before the merge; its downgrade drops the column, which loses nothing but the versions.

0019 creates health_checks: one row per check of the tick's self-check, holding what it said last, since when, and when the owner was last told («Monitoring», below). One new table and nothing else, additive, and on before the merge; its downgrade drops the table, which loses nothing but what the checks remembered.

Everything up to 0012 checks with an inspector what is not in the database yet and does not rewrite existing tables, so those can be applied to a live class in the middle of a school day. 0013, 0015 and 0016 ask the inspector too — per constraint, per column, per table — because on an empty database 0001 has already built today's schema, and a second ADD COLUMN or ADD CONSTRAINT there is a hard error that stops the migrate service below; and because a SQLite file scripts.init_db built before a model change is stamped at the old head without the new columns, and only the revision adds them. 0017 asks only whether the table is there; its statements are plain SQL that PostgreSQL and SQLite both run, and a second run finds nothing to do. 0018 asks per column, as 0015 does, and 0019 per table, as 0016 does. The head is 0019.

A migration goes BEFORE the deploy, not after

This is not a matter of taste. A merge to master deploys to Vercel by itself, while the migration is run by hand — and between them is a window in which the code knows about a column the database does not have. Production has already been taken down that way: code with classes.diary_provider left before its revision, nothing failed at startup, and the first ORM query for a class did — that is, the bot's middleware, that is, every update, with an UndefinedColumnError forty lines into the traceback.

The right order is:

  1. the migration on the production database;
  2. only then the merge (which is the deploy).

That works precisely because the additive revisions add: a column the running code does not know about yet is a column it does not read. The other way round is never safe.

A constraint goes the other way. A UNIQUE or a NOT NULL breaks the old code, not the new: where a moment earlier a duplicate was allowed, there is now an IntegrityError nobody catches. 0013 is that shape and says so in its own docstring — it went on after the merge, and services/homework.py is written to be correct with or without it, so the window in between behaved exactly as production did before.

A rewrite of a key is a third shape. 0017 breaks neither code — it changes no column — but the old code and the new file the same rows under different keys, so whichever runs in the window between the migration and the deploy writes rows the other cannot see, and neither order is free of loss. Before the merge, every correction typed in the window is filed under a login the new code never reads. After the merge, nothing typed is lost — the new code writes per-child rows at once, and the rewrite folds the old ones into them, the newer winning — but a reset made in the window is undone: the new code cannot see the legacy row to take it off, so «Сбросить правки» or «Сбросить всё» leaves it, and 0017 then files it under the child and the value comes back for everyone who sees the child. After is still the smaller loss, so it is the order for a deployment that holds corrections — with the window kept to minutes, and with /api/v1/warmup saying «База отстала от кода» through it, which there is expected. Where there is nothing to rewrite — production, on 26 September — the order is free, and it went on with the additive revisions before the merge, which keeps /api/v1/warmup level.

That the database really has caught up with the code is shown by alembic current — it should print the same revision as alembic heads. The same thing over HTTP, without going into the database by hand:

curl -s https://<your-project>.vercel.app/api/v1/warmup

{"status":"ok","schema":"0019"} means it all lines up. "status":"degraded" together with expected_schema names both revisions and says which way they diverged: «База отстала от кода» — the database is behind the code — is an incident, except in the minutes a key rewrite such as 0017 is deliberately applied after the merge (above), while «База впереди кода» — the database is ahead — is the normal window between steps 1 and 2, which the deploy closes. /api/v1/health deliberately does not show this: it opens no database connection at all, or a ping meant to warm things up would keep waking a sleeping Neon.

What to apply them with

In practice this project's migrations are applied through the Neon connector rather than with the alembic command — that is how 0005–0019 were applied: 0015–0017 together on 26 September 2026, before #140 merged, and from 0018 on each to the Neon branch preview when its pull request was pushed and to production before the merge. The Neon project is called lessons; its identifier is not kept in the repository — anybody with access sees it in the Neon console anyway, and in a public repository it is just the address of somebody else's database.

It is not a run of alembic but the revision's DDL executed as one transaction together with the alembic_version stamp. Three rules follow, and each of them has been paid for:

  • The DDL comes from the model, it is not written by hand. CreateTable(Term.__table__).compile(dialect=postgresql.dialect()) prints exactly what create_all would have built — that is, what the revision is obliged to produce. A column type invented by hand diverges from the model silently and surfaces a month later.
  • Read the state first; the stamp is the last action in the same transaction. Otherwise a half-applied revision declares itself whole.
  • Say out loud what a revision destroys before running it. 0006 deliberately deletes every row of diary_sessions; that sentence is needed by the owner before the transaction, not after.

The equivalent for anybody who has a working connection string is alembic upgrade head. It is run locally, with a working connection string, and not from inside a function: a migration takes an ACCESS EXCLUSIVE lock on a table, and doing that on a request's cold start is a bad idea. To see the SQL before executing it:

DATABASE_URL='postgresql+asyncpg://...' .venv/bin/alembic upgrade head --sql

The database's current state is alembic current. Its history is alembic history.

A separate command rather than something automatic at startup: the tables are usually created by FastAPI's lifespan, but a serverless platform may never call lifespan at all. Relying on it means a first request that fails with "no such table" and no intelligible reason.

Registering the webhook

Once, after the deploy:

curl -X POST "https://api.telegram.org/bot<TOKEN>/setWebhook" \
  -d "url=https://<your-project>.vercel.app/api/v1/telegram/webhook" \
  -d "secret_token=<WEBHOOK_SECRET>" \
  -d "drop_pending_updates=true"

To check: https://api.telegram.org/bot<TOKEN>/getWebhookInfo. The last_error_message field will say why Telegram cannot reach you.

You run this command yourself, on your own machine — the token is in it in the clear.

Why the secret is mandatory

Without it webhook_enabled returns false and the endpoint is not mounted at all. That is not over-caution. Telegram signs nothing: it simply sends JSON, and the bot trusts the user_id inside that JSON when deciding who may edit a timetable. With no secret check, anybody who guesses the URL sends a forged update with somebody else's id — and that is not spam, that is taking the bot over completely.

The comparison goes through hmac.compare_digest, so the secret cannot be recovered character by character from how long the answer takes.

One more detail: the endpoint answers 200 even when the handler failed, and the error goes to the log. Telegram retries failed deliveries with a growing delay and eventually switches the webhook off — one bad message must not take the whole bot down.

What to expect

The first message to the bot after an idle period takes 1–3 seconds to handle: the Python function's cold start plus connecting to Neon. After that it is fast, while the instance is alive. For a school diary that is tolerable, but it is not the instant response of an ordinary bot.

Those are two independent delays rather than one, and they add up:

  1. The function's cold start. Vercel does not keep an instance if no request has reached it for a while: the next request first starts the Python interpreter and imports FastAPI, aiogram and SQLAlchemy — and only then reaches the code.
  2. Neon goes to sleep separately from the function. On the free plan Neon's compute node suspends itself on its own idle timeout, whether or not the Vercel function is alive. The first request after that waits for Neon to wake up — and that happens even when the function is already warm.

Both are shortened as far as the code can: the function is pinned to fra1, next to the database (see "Why Vercel does not work 'as is'" above), and create_all at startup runs only for local SQLite, never for Postgres.

If even that is slow

Both delays are the architecture of the serverless path rather than a bug: serverless deliberately keeps nothing permanently running, which is what you are not paying for. There are two ways to remove them entirely.

Do not let it sleep. An external scheduler poking an endpoint every few minutes keeps both the function and Neon awake. Vercel's own Cron on the Hobby plan will not do for this — the minimum interval there is daily, so Neon sleeps many times between firings. You need an external service (cron-job.org, UptimeRobot, healthchecks.io — all have a free plan with an interval from one minute) or your own scheduled workflow in this same GitHub repository.

Where you knock matters. /api/v1/health does not touch the database at all — it keeps only the function warm, while Neon still falls asleep on its own timer. For both endpoints at once there is /api/v1/warmup: the same answer, with one SELECT 1 along the way. Point the ping at that one, every 4–5 minutes.

curl https://<your-project>.vercel.app/api/v1/warmup

That is extra function invocations — about 8,600 a month at one every five minutes, on top of the tick's own — and on Hobby they count against an allowance that pauses the project when it runs out («Which Vercel plan», above).

Do not try not to sleep. A ~€4/mo VPS (option 2 below) does not sleep at all, because the process is not serverless — nothing to rewrite, the same code, just different hosting. If the cold start bothers you more than serverless is worth, that is a simpler answer than maintaining an external ping for ever.

Option 2: your own server

Nothing has to be rewritten — the code already works this way.

git clone https://github.com/lumenpearson/lessons && cd lessons
cp server/.env.example .env    # beside docker-compose.yml; fill in BOT_TOKEN and OWNER_IDS
echo "POSTGRES_PASSWORD=$(python3 -c 'import secrets; print(secrets.token_hex(24))')" >> .env
docker compose up -d --build

docker-compose.yml brings up Postgres, migrates it, and then starts the app. The bot works through polling, so no external address and no webhook are needed at all — the server can sit behind NAT with no public IP.

The .env is the one beside docker-compose.yml, not server/.env. Compose fills every ${...} in the file from the shell or from .env in the directory the file is in, and hands the container exactly what the file lists; the image copies no .env of its own. This step used to say server/.env, which compose never reads, so up stopped at «set BOT_TOKEN in .env» however carefully that file had been filled in.

Every setting the server reads reaches the container. Besides BOT_TOKEN, OWNER_IDS and TIMEZONE, the file hands it WEBHOOK_SECRET, CRON_SECRET, BOT_USERNAME, DIARY_SECRET, DADATA_TOKEN, DIARY_PROXY_URL, DIARY_EGRESS, GITHUB_READ_TOKEN, PUBLIC_BASE_URL, SENTRY_DSN, MIN_CLIENT_VERSION, RUN_BOT, TRUSTED_PROXY_HOPS and LESSONS_STREAMING from the same .env, each arriving as its own default when unset, and server/tests/test_compose.py holds this sentence to the file's list. This image speaks HTTP/1.1, so WatchClass streams over Connect there and native gRPC is option 3's alone. Until #191 none of those was passed, and a container sees only what the file lists: a compose deployment had no diary, no digests and no calendar link whatever .env said. What they are for is the table under Option 1; here, the digests need CRON_SECRET and an external cron exactly as on Vercel («The clock» below), the diary needs DIARY_SECRET and, for its sign-in page, PUBLIC_BASE_URL, and behind a reverse proxy that terminates HTTPS, TRUSTED_PROXY_HOPS=1 is what lets the throttles see the caller rather than the proxy.

The database password is yours, and letters and digits only. POSTGRES_PASSWORD is required — docker compose up refuses to start without it. The file used to carry lessons in plain text, which in a public repository is the password of every deployment that ran it as written (#190). The same value is spliced into DATABASE_URL unescaped, so an @, :, / or % in it would be read as the URL's syntax rather than as the password; token_hex produces none of them.

A volume created before that keeps its old password. Postgres reads POSTGRES_PASSWORD only when it initialises an empty volume, so a deployment that has been up since the file said lessons still has lessons, and migrate fails to sign in with the new value. Change it inside the database once — the postgres image trusts connections from inside its own container, so this needs no password of its own:

docker compose up -d db
docker compose exec db psql -U lessons -c "ALTER ROLE lessons PASSWORD '<POSTGRES_PASSWORD from .env>'"
docker compose up -d --build

The migration is a service of its own, and the server waits for it. migrate runs alembic upgrade head once against the same image and the same database and must finish successfully (condition: service_completed_successfully) before server starts. On a database already at the head it is a no-op that costs a second on every up; what it buys is that the schema exists at all. Until this batch it did not: app.main calls create_all only for SQLite, the image shipped neither alembic.ini nor migrations/, and so docker compose up gave an empty schema, a green /api/v1/health — which opens no connection and therefore cannot see this — and a failure on the first ORM read, which for the bot is the middleware, i.e. every update at once. server/Dockerfile now copies both, and alembic was already a runtime dependency.

A service rather than a line in the server's command, so that a failed migration stops the stack instead of being buried in the API's log, and so that a migration can be run by hand with docker compose run --rm migrate. It needs only DATABASE_URL. get_settings() is called there — migrations/env.py imports app.db, which builds the engine from it at import — but its refusal hangs on VERCEL, and nothing sets VERCEL in the compose file, so BOT_TOKEN and OWNER_IDS are not its business (#322). The same import is why alembic upgrade head refuses wherever VERCEL is set and the deployment's settings are not. GET /api/v1/warmup is what confirms the result, and it is the endpoint that can: it says {"status": "ok", "schema": "0019"} when the two agree and names both revisions when they do not.

The app on the phone needs to reach the API, and the release APK reaches it over https:// only, with a certificate a public CA issued. Compose publishes the server as plain HTTP on port 8000 and terminates no TLS, so something in front of it has to: a reverse proxy with a real certificate (which is where TRUSTED_PROXY_HOPS=1 above comes in), or a tunnel that serves HTTPS, such as Cloudflare Tunnel. A public IP with a forwarded port, or the server's local address on the school network, reaches it as http://192.168.…:8000, and that the release APK refuses where it is typed («Приложение подключается к серверу только по защищённому адресу — он начинается с https://…»), as it refuses a self-signed certificate. This page used to offer the local address as the simple option; it works only with a debug build, and has since the owner's decision of 27 September 2026 (#202). docs/build.md, «Why a debug build speaks HTTP and a release build does not», has why.

Any VPS with 1 GB of memory will do. One class's load is a few hundred requests a day.

Option 3: the host target

The same app as Vercel's, and everything it serves — v1, v2 over REST and Connect, the webhook and the tick — from one long-running process over HTTP/2, which adds what Vercel cannot: native gRPC, and WatchClass, the class's changes streamed to a phone while the app is open (docs/api.md, «The host target, and WatchClass»). It is a whole deployment, chosen instead of Vercel, not beside it: a stream hears only what its own process writes, and on Vercel the bot's webhook would land elsewhere. A beta, and deployed nowhere yet: where it runs is decided when a phone needs it (the server-v2 design, question 3).

docker build -t lessons-host .          # from the repository's root
docker run -p 8000:8000 --env-file host.env lessons-host
  • The image is the root Dockerfile, not server/Dockerfile, which is option 2's. It installs Vercel's lock and the host's (server/requirements-host.txt, compiled against it), then the package without its floors, and runs python -m app.host as a user of its own. Nothing here has built it: there is no Docker where this project is developed. CI's «Host» job installs the same two locks and starts the same command on every change to the server.
  • It says it is a deployment. The image sets LESSONS_TARGET=host, and with it the server refuses to start without what option 1's table asks for, exactly as on Vercel — the database, BOT_TOKEN, WEBHOOK_SECRET and RUN_BOT=false among them («What is missing is said at the door»). host.env is that table's values, and LESSONS_STREAMING=true for the stream.
  • The webhook and the cron point at it. Register the webhook with the host's own HTTPS address («Registering the webhook»), and point the external cron at its /api/v1/cron/tick («The external cron»): the host has no clock either, by the same rule. Telegram hands updates to one consumer, so the webhook can point at the host or at Vercel, never both.
  • One instance. Two would each stream what they wrote and miss what the other did.
  • One stream per phone. A phone that opens WatchClass again under the same device token ends the stream that token held, so the host holds at most one stream per token that has ever opened one — not one per live phone: a phone that joins again mints a new token, and the old token's stream stands as an orphan rather than closing. Under pyvoy, app.host.envoy_config sets an HTTP/2 connection_keepalive on Envoy (a thirty-second interval, to match the stream's own heartbeat, and a ten-second timeout), so a phone that drops off the network without closing its connection is found in tens of seconds rather than kept until the kernel gives up on it — about a quarter of an hour on Linux's defaults, by calculation (#400). Under --server hypercorn, the fallback, there is no equivalent setting, so that gap stands. Meanwhile that stream asks the database for its gate every thirty seconds, on the one pool every request shares.
  • HTTP/2 the whole way. The host serves HTTP/1.1 and HTTP/2 with prior knowledge on one plain port and terminates no TLS, so it sits behind something that does. For native gRPC that proxy must speak HTTP/2 to it: one that downgrades to HTTP/1.1 gets the 415 Vercel gives, and Connect and REST work either way. Behind it, TRUSTED_PROXY_HOPS=1 is what lets the throttles see the caller rather than the proxy, as on option 2. The host takes the client's address from the connection and never from X-Forwarded-For by itself: pyvoy's Envoy did the second until app.host turned it off, and a caller who wrote a new address each time would never have been throttled (#395).
  • Migrations are applied from a workstation, before the deploy that needs them, as for Vercel; the image carries no alembic.
  • The self-check's deploy check reads what Vercel says about the running deployment, so on the host it answers ❔ «not on Vercel»; the schema, v2, the diary's proxy and the regions in use are checked there as anywhere («Monitoring», below).

To run it on a laptop, from server/ with the dev install: pip install -r requirements-host.txt, which resolves for Windows as well as Linux, then python -m app.host, on the local defaults and SQLite, without the marker — --server hypercorn is the fallback the 5 October spike proved beside pyvoy. A host on the local defaults streams only when LESSONS_STREAMING=true.

The files Vercel needs

File What for
api/index.py the entry point; a thin re-export of app.main:app, so that serverless and uvicorn run the same code
vercel.json the region, the install command and the function's maxDuration. There is no rewrite in it and there must not be: with "/(.*)" → "/api/index" Vercel routes by the rewritten path, so FastAPI received a literal /api/index, and the health check, the client API and the Telegram webhook all answered 404 at once. Removed in PR #5 (e99d8ca); this line described something that was not in the file for a year — whoever puts it back will reproduce the same outage
requirements.txt what Vercel installs, because its builder does not read pyproject.toml from a subdirectory. A lock, not a list (#192): every package the function can import, transitive ones included, at one exact version, resolved for CPython 3.12 on Linux. Not written by hand — its header is the uv pip compile command that regenerates it. CI installs the same file together with the package, so the suite runs on the versions production gets; while it held floors, each deploy installed whatever was newest that day
requirements.in the lock's input: server/pyproject.toml's runtime dependencies, character for character, less what the function does without — asyncpg only, no aiosqlite, and no uvicorn, alembic or tzdata. Edit it with pyproject.toml, then regenerate the lock; test_requirements_mirror.py holds the three level
.vercelignore keeps android/, the tests and the documentation out of the bundle

Which to choose

For one class and one person maintaining it, a VPS is simpler: fewer moving parts, no cold starts, and no dependence on other companies' plans and their allowances, which change.

Vercel plus Neon is justified if there will be many classes and you would rather not think about a server at all — on a plan with higher function limits, a spend limit and an alert, because many classes are exactly what spends Hobby's allowance soonest. It is not the way to avoid paying: Hobby is for personal, non-commercial use («Which Vercel plan», above).

The clock: the server has none, and GitHub's will not do

On serverless nothing runs between requests, so the morning and evening digests are sent by whoever calls /api/v1/cron/tick with an X-Cron-Secret header. The only question is who calls.

The clock is an external cron, not GitHub Actions. The .github/workflows/reminders.yml workflow asked for a tick every five minutes — 288 a day — and over five days of measurement got 6.7 a day, in gaps of two to six and a half hours. GitHub runs schedules on a best-effort basis, and on a private repository on the free plan that is what the effort came to. The server survives that — it decides what to send from "what has not been sent yet today" rather than "did the last tick fire", and it marks a digest sent before sending it, so a failure halfway does not send it twice. What the server does not survive is the promise the bot makes: that digests arrive within about five minutes of the stated time. On GitHub's schedule that is six hours from true.

The workflow has not stopped asking for five minutes — on a public repository that costs nothing, and the measurement was made on a private one, so how the schedules behave here is yet to be seen. But its role is different now: a fallback that will notice the external clock has stopped. The clock itself is set up by hand: since 5 October 2026 it is cron-job.org, calling the tick as the table below says, and reminders.yml is the fallback.

The external cron

Anything that can do a GET with a header will do: cron-job.org and UptimeRobot are free, so are Cloudflare Workers with [triggers] crons, and on a VPS it is one line in a systemd timer or a crontab. One job, every five minutes:

Field Value
URL https://your-project.vercel.app/api/v1/cron/tick
Method GET
Header X-Cron-Secret: <the same value as in the server's environment>
Schedule every 5 minutes

To check by hand:

curl -fsS -H "X-Cron-Secret: $CRON_SECRET" \
  "https://your-project.vercel.app/api/v1/cron/tick"

The secret goes off to somebody else's service, and that is a deliberate price. CRON_SECRET grants nothing but the right to call the tick: it neither reads nor changes a class's data, and the worst an extra tick does is send what was due to be sent anyway. Keep it separate from everything else, and change it in both places at once (the server's environment variables and the cron job), or the digests will go silent silently.

Its failure email is the one alarm for a server that is down entirely. Nothing inside the server can say so — the bot is down with it — but the cron service sees every run fail. On cron-job.org that is the job's notifications: an email when the job fails, after three failures in a row (fifteen minutes) rather than after one blip — the owner's choice — and an email when it succeeds again. The job's history is the other half of the check: a run answers 200 with the tick's JSON; 403 Bad cron secret means the header is not the server's CRON_SECRET, and 404 Cron is not configured means the server has none. Either way no digest goes out.

This deployment's job was set up by the owner on cron-job.org on 5 October 2026, at about 18:45 UTC, and production has its CRON_SECRET. What is still to read is the job's history — 200 with JSON, not 403 — and whether its failure email is on (#120).

The fallback workflow

It needs the same two repository secrets (Settings → Secrets and variables → Actions):

Secret Value
SERVER_URL https://your-project.vercel.app
CRON_SECRET the same value as in the server's environment

Without those secrets the workflow does not fail: it writes a notice and exits zero — or the Actions tab would go red for everybody who cloned the repository.

The same tick also sweeps up abandoned bot dialogues and expired records of failed code attempts — on serverless that is the only moment anything can be swept up at all — and it holds «Сетевой город» sessions open, pinging each live one before its 15-to-60-minute idle window runs out, because this project stores no password to sign back in with. For the sweeping, whatever GitHub deigns to run is enough; for the digests and the keep-alive it is not — a session dies in the gaps GitHub leaves — which is why the external cron is not a nice-to-have but the condition of both what the bot promises and whether a «Сетевой город» family stays signed in. The keep-alive runs last in the tick and inside its own guard, so a diary that is slow or down never fails the tick and reddens the clock.

Monitoring: what tells the owner something is wrong

On 5 October 2026 three things went wrong in production and nobody was told: a merge did not deploy for half an hour (#349), the diary's proxy answered nothing for forty minutes, and the external cron had not been set up (#120). Three pieces say so now (the design): the self-check below, the external cron's failure email above, and Sentry.

The self-check, in every tick

Every tick runs four fixed checks, and one more for each «Сетевой город» region in use, each by its own route (server/app/services/health.py), after the digests and the sweeps and before the diary keep-alive, inside their own guard and their own time budget, so none of them can fail the tick. They run before the keep-alive because the keep-alive calls the regional «Сетевой город» servers, each by its route, directly or through the proxy, and when one hangs it holds the request until its own hard stop; the checks stop five seconds before theirs, so an alert always has time to go out, and a check the tick left less than its full five seconds that times out reads unknown rather than raising a false alarm:

Check Ok when
schema the database is at the revision the code expects, or ahead of it in the window a revision applied before its merge opens
v2 v2 loaded, rather than answering 503 under its two prefixes
diary_proxy a HEAD of the Petersburg diary through DIARY_PROXY_URL gets any answer within five seconds; asked only when the setting is set and DIARY_EGRESS sends something through it, so direct and relay read unknown
deploy production runs master's head, or master moved less than fifteen minutes ago; asked on production only
diary_region:<key> a GET /webapi/logindata of the region's server, sent by the route its calls take and with the diary client's own headers, gets any answer but a refusal within five seconds; one row per region in use (#406)

A region's row. A region is in use when a class is bound to it or a live session is on it, and the allow-list still serves it with a password, so a tick probes at most 17 diary servers: Petersburg through diary_proxy and the sixteen password regions, all at once inside the checks' budget. No answer, a 403 or a WAF's page is failing, because a region refusing this server's address is a route that does not work. A region whose route is the proxy and whose probe fails while diary_proxy itself is failing reads unknown: the dead tunnel is one alert, not one per region behind it. A «down» alert, and its reminder, carries a second line saying what to do, by the route the failing probe took: through the proxy, the region may have shut the proxy's address out, so move it to the direct route (via_proxy in regions.py); directly, it may have shut the server's address out, so try it through the proxy and turn via_proxy on if it answers there. The «up» carries no such line. A region that leaves use loses its row at the next tick, failing or not: a region dropped from use while failing simply goes silent, with no «up» and no reminder, and that silence is not a recovery. If it comes back into use it starts afresh, with a new «down». When the regions in use cannot be read at all, no region row is touched that tick.

Each ends ok, failing or unknown, and health_checks keeps what each said last. Unknown is a check that could not run, or one that does not apply here, and it never alerts. The bot writes to every OWNER_IDS account when a check starts failing, when it comes back (with how long it was down), and every six hours while it stays failing — never once per tick. The text names the infrastructure only, and a region's reason names its route but never the proxy's address. In the bot, /health shows the four and a line for each region in use, and /project the whole of «📊 Проект» (docs/bot.md). If the self-check itself fails to commit, the tick rolls the session back, so the keep-alive that runs next on it is unaffected.

The deploy check reads master's head from GitHub's public API, with an ETag, so an unchanged answer is a 304. With GITHUB_READ_TOKEN set the request is authorized: the 304 costs nothing against GitHub's rate limit, and the ceiling is 5,000 requests an hour. Without it the request is anonymous, sharing sixty requests an hour with every Vercel function behind the same address, and a refusal reads as unknown, never as failing, with the reason naming the setting («… (anonymous; set GITHUB_READ_TOKEN)»). A fine-grained token also expires: once it does, the check reads ❔ «the token was refused» until a new one is set, rather than falling back to the anonymous reading above. It learns which commit is running, and which repository to ask, from Vercel's system environment variables (VERCEL_ENV, VERCEL_GIT_COMMIT_SHA, VERCEL_GIT_REPO_OWNER, VERCEL_GIT_REPO_SLUG). They reach a function while the project's Settings → Environment Variables → «Automatically expose System Environment Variables» is on, which is Vercel's default. With it off, the check says so and stays unknown.

Errors and timings: Sentry

SENTRY_DSN is optional. Empty sends nothing and imports nothing of Sentry, and the startup log says it is off. A value Sentry's own SDK could not use is announced off the same way, rather than stopping the API from loading: Settings judges the DSN's shape itself, before anything imports sentry_sdk, and app.main's own call into Sentry is guarded besides, logging only the exception's type, because its message can carry the DSN's key. Set to a usable DSN, the server sends each unhandled error, and each failure the bot's handlers raise, with:

  • the exception's type and its stack — file, function, line;
  • the route template, /api/v1/diary/students/{student_id}/schedule, never the number in it;
  • the release, which is the commit, and the environment, which is Vercel's VERCEL_ENV, so a preview's errors stay apart from production's.

It also times 5 % of requests, named by route template: those are Sentry's request graphs. The rate cannot be overridden by a caller's own sentry-trace header, because nothing upstream of this server propagates one of its own.

What is never sent, because it can carry a child's name or a family's credential (152-ФЗ): request and response bodies; headers, cookies and query strings; the exception's message; local variables and source lines; log lines and breadcrumbs; the spans inside a request. Release-health sessions (a per-minute count of crashed and errored sessions) and client reports (a count of events this process dropped and why) are switched off as well, because neither hook below is asked to scrub them. The SDK is told not to collect the rest, and two hooks then rebuild every event from a list of what may leave (server/app/observability.py). server/tests/test_observability.py sends a request carrying a diary token and a child's name through a failing route, and finds neither in what would leave.

What the owner does, once:

  1. A Sentry account in the EU data region, and a project of the platform «Python / FastAPI». For this deployment both exist: the organisation hubdpi and its project lessons.
  2. The project's DSN into Vercel as SENTRY_DSN, for Production (the owner's choice of 6 October 2026: Production only for now; a Preview value would keep its errors apart under VERCEL_ENV), marked Sensitive; then a redeploy. The DSN is a secret like the others: never in the repository, an issue or a log.
  3. To turn it all off: delete SENTRY_DSN and redeploy. No code changes.

The free plan takes 5,000 errors a month, and a 5 % sample of this project's requests is far inside its allowance for timings.

The privacy policy names Sentry, in «Третьи стороны» and in «Чего сервер не хранит», since its edition 4 (#425): what leaves, what never does, and that this operator's Sentry data is kept in Germany (the organisation's region is de.sentry.io). A deployment without SENTRY_DSN — this one after step 3, or a fork — deletes that point and rewords the sentence in «Чего сервер не хранит» to say the server sends nothing, as the [SENTRY] comment above the point says, and raises the edition.

Where the graphs are

The bot names the dashboards and links none, because a link names the owner's accounts:

What Where
requests, errors and durations by route Vercel → the project → Observability: https://vercel.com/codeilluminators/lessons/observability
errors with their place, and the 5 % of timings Sentry → Issues and Performance: https://hubdpi.sentry.io/projects/lessons/
the database's load, connections and storage the Neon console → the project named lessons → Monitoring; its id stays out of the repository

Longer retention in Vercel is Observability Plus, a paid add-on, and nothing here needs it.