Version 1. Base path /api/v1. Every change since the first release is
additive - new endpoints, new optional fields - so the version has not moved
and a client built against the original /bundle keeps working unchanged.
A second version, v2, is a proto contract served beside v1 under /api/v2 and /api/rpc,
every one of its seventy-five unary methods: «v2: the contract», at the end of this page.
There is no user account and no password. A device holds a bearer token; a device that has been linked to a Telegram account through the bot acts with whatever role that account has in the class. Everything a device can do without linking is read-only.
A device exchanges a class join code for a long-lived bearer token once, at first launch.
POST /api/v1/join
Content-Type: application/json
{ "code": "DEMO24", "device_name": "Pixel 8" }
{
"token": "s6mZ...43-char-url-safe-string",
"class_id": 1,
"class_name": "9А",
"school": "Демо-школа",
"timezone": "Europe/Moscow",
"diary": { "provider": "netschool", "region": "samara", "school_id": 1234,
"school_name": "МБОУ Школа № 5" }
}diary is the electronic diary the class is bound to in the bot, so that a phone joining a
bound class can sign in there without searching for its school: provider is petersburg
or netschool, and for «Сетевой город» region is the allow-list's key and school_id the
diary's own school id. It is null when the class has no binding this server can use —
none at all, a region since dropped from the allow-list, a region that takes only
Госуслуги, or a «Сетевой город» binding whose school step was never finished — because it
is read through the same registry.binding() the bot reads, and a phone must never be
pointed at a diary this server would refuse. The field is additive: an older app ignores
it. It says which diary, and nothing more; the phone still needs a diary session of its own
(The electronic diary).
The token is stored server-side only as a SHA-256 hash, so a database leak does not yield working credentials. Every later request carries it:
Authorization: Bearer <token>
Codes are eight characters from an alphabet with O, 0, I and 1 removed,
because people type them off a whiteboard. Rotating a class code (owner-only,
«🔁 Сменить код» on the bot's «⚙️ Класс» card; /code only shows the code, to
admins) stops the old code from being redeemed again; devices that already joined
keep working, since their tokens are independent of it (#321).
Failed joins are rate-limited per client address (thirty per fifteen minutes,
counted in the database so the limit survives serverless cold starts); a
blocked client gets 429 with Retry-After.
Successful joins are not counted, so it is the class that bounds them: once a class holds
300 live devices — a revoked one is a tombstone and does not count — its class code is
answered with 409 and a Russian sentence in detail, and mints nothing. That 409 is not
a failed attempt for the limiter either, for the reason the invite-only 403 below is not.
A personal code from the bot still joins a full class: it is minted one phone at a time for
a member the bot knows, and it is the way in left to a family if somebody has used the
class code to fill the class. The number is generous on purpose — MAX_DEVICES_PER_CLASS
in api/public.py says how it was reached — and an admin makes room by revoking old phones.
A class has a join mode — join_mode, either open or invite — and it decides what the
class code is worth.
open is what a class always was: the class code lets in anybody who types it. That is
sensible exactly as far as handing the timetable to all comers is sensible, and entirely
unsensible for a class that does not see it that way: a code read aloud and forwarded is
worth as much as the least careful person holding it, and rotating it throws everybody out
at once rather than the one it leaked through.
invite means the class code stops letting anything in, and POST /join answers it with a
403 carrying a Russian sentence in detail. A phone joins with a personal code: ten
characters, fifteen minutes, one phone, one Telegram account. The bot hands it out only to
somebody it already knows as a member of the class — the «📱 Подключить телефон» button in
the menu — so the question "who let this phone in" always has an answer with a name on it.
A personal code is typed into the same code field and goes to the same POST /join: for
the app that is one screen and one error, not two ways to sign in. It works in open too —
the modes do not exclude each other — and it links the device immediately to the account
that took it. In open a phone joins anonymously and is linked afterwards with a second
code from the bot, which almost nobody does, and the device list fills up with rows nobody
can attribute.
That 403 is not counted as a failed attempt by the rate limiter. The limiter stands
against guessing codes, and this caller has already found one; counting it would mean that a
class switching to invitations locks out everybody still holding the old code.
Switching takes nothing away. invite does not revoke a phone that joined with the
class code, exactly as rotating the code does not — and switching back gives the class code
its force again. It is changed by PATCH /api/v1/manage/class with the join_mode field
(admin) or by a button under «👥 Доступ» in the bot; both write an access.join_mode line
to the log.
| Status | Meaning |
|---|---|
401 |
Missing, malformed, unknown or revoked token — the client must drop its session, not merely report it |
403 |
The device is not linked, or its account lacks the role (detail says which). On /join it is the one refusal below that is not about the code being wrong: the class takes personal invites only |
404 |
Join code, class, homework, task or event does not exist - or is not this class's. On a write to homework, a substitution, an event, a day, a task, /me, or /manage's subjects, bell schedules, devices, access requests, class and term scheme, also a row another write deleted between this one's read and its commit (#384, #654), with the sentence a request for a missing row of that kind gets — Class no longer exists for /me and the scheme, whose class was deleted with its devices and its terms; nothing is written. Two writes answer that race with another status: a term moved by PUT /manage/terms/{index} with its own 422, «Такого периода нет.», and a diary correction with a 409 (below). A timetable import whose class or expected default bell schedule disappeared also answers 404, Unknown bell schedule, and rolls back without recreating the deleted parent (#657) |
409 |
On /join: the class already holds as many live phones as its class code admits. The code is right; a personal code from the bot still joins. On PUT /diary/students/{id}/overrides: the correction was reset or cleared by another write between this one's read and its commit (#654) |
422 |
Parameter out of range or body invalid |
429 |
Too many failed join attempts |
A 404 for somebody else's task is deliberate: an id must not reveal that a
classmate has a list.
One request returns everything the app and the widget need.
| Parameter | Default | Notes |
|---|---|---|
start |
today, in the school's timezone | YYYY-MM-DD, 2000–2100 |
days |
14 |
1–280 — a whole school year, see below |
The ceiling of 280 days is the longest school year (274 days, from 1 September or the next
weekday after it through to 31 May) plus some slack. The old ceiling of 31 days was not a
limit of the server but the size of the client's cache: the app asked for a month, and past
that boundary the calendar drew «Нет данных» — which on a screen is indistinguishable from
"there are no lessons that day". Widening it costs almost nothing: ScheduleResolver makes
the same number of queries for any range and expands the rest from the weekly template in
memory. Measured on the demo class: 6.0 KiB for 31 days against 47.9 KiB for 273.
A class carries its own number and the periods of its school year. The number is a number rather than something parsed out of a name: «9А» may turn out to be «9 инж» or «5-й Б», and a regular expression over that is quietly wrong for the one class written differently. The periods arrive as rows rather than as a formula, because the dates are the school's business: the holidays shift, a region goes on its spring break earlier, a quarantine eats a week.
They also decide which days carry lessons at all. A day inside none of the class's
periods is answered as holiday with an empty lessons, whatever the weekly template
says — so a half-year ending on 28 May ends the lessons on 28 May, and the gap between two
quarters is the holidays in it. The conventional periods are contiguous, so a class that
has never edited them behaves exactly as before, and a class with no periods for that year
falls back to «1 September to 31 May». This is what the dates were always for; until
recently they named the period and nothing more, and the calendar went on drawing a full
day through to 31 May.
{
"api_version": 1,
"school_class": {
"id": 1, "name": "9А", "grade": 9, "letter": "А",
"school": "Демо-школа", "city": "Санкт-Петербург", "timezone": "Europe/Moscow",
"term_kind": "quarter",
"terms": [
{ "index": 1, "kind": "quarter", "starts_on": "2026-09-01", "ends_on": "2026-10-31" }
]
},
"generated_at": "2026-09-09T11:15:38.433+03:00",
"days": [
{
"date": "2026-09-10",
"weekday": 4,
"kind": "normal",
"off_reason": null,
"holiday": null,
"lessons": [
{
"index": 2,
"subject": "Астрономия",
"starts_at": "09:25:00",
"ends_at": "10:10:00",
"room": "305",
"teacher": null,
"color": null,
"is_replaced": true,
"is_cancelled": false,
"note": "Замена: учитель на конференции"
}
],
"events": [
{
"title": "Обед",
"kind": "canteen",
"starts_at": "11:10:00",
"ends_at": "11:25:00",
"location": "Столовая",
"covers_lesson": false
}
],
"homework": [
{ "subject": "Геометрия", "text": "№ 12–15", "attachment_url": null }
],
"note": null
}
],
"next_school_day": { "date": "2026-09-16", "...": "same shape as a day" },
"device": { "linked": true, "role": "editor", "can_edit": true }
}The widget has to render a correct countdown with no network, on a device that may be in a dead zone all day. So the server resolves the weekly template, per-date replacements, holidays, bell schedules and week parity into concrete days, and the client caches the result. The client never sees the template.
next_school_day is resolved by looking past the requested window, up to
three weeks ahead. That is what makes "homework for Monday" work when you ask on
a Friday for a single day, and what makes it survive the winter holidays.
Those three weeks are counted from the last lesson inside the window, so a
window that already runs to the end of the school year gets null: everything
within three weeks of the last day of May is June, and June is out of season for
every class — a term cannot be typed past the year's end. The Android client
asks for exactly that window, so it never receives one; it answers the same
question from its own cache instead. A client that asks for a fortnight is the
one this field is for.
The response carries an ETag. Send it back as If-None-Match and an
unchanged bundle answers 304 with no body. The widget polls on a timer and
nearly every poll finds nothing new, so nearly every poll should cost a hash
comparison rather than two weeks of JSON over mobile data.
The validator is a hash of the body with generated_at blanked out - that
field changes on every request and would otherwise defeat the whole point.
Weak validators (W/"...") and comma-separated lists are accepted.
The Android client does this: it keeps the last tag in its preferences under a
signature of the request it belongs to (class, start, days), so 1
September and a class switch simply stop matching and the next sync asks for
the whole window. A 304 writes nothing to Room and does not wake the widget —
nothing it draws has changed — but it does move the «обновлено N назад»
mark, because that is a claim about the check rather than about the payload.
- Times are local wall time (
HH:MM:SS) inschool_class.timezone. A bell rings at 08:30 regardless of daylight saving, so there is deliberately no UTC offset. school_class.timezonebelongs to the class, not to the deployment. Russia spans eleven zones, so one server routinely hosts classes ten hours apart, andstartdefaulting to "today" is resolved in the class's zone. Clients must derive "now" from this field rather than from the device clock.kindon a day is one ofnormal,holiday,shortened,remote,self_studyorday_off. Two of them empty the day (schedule.KINDS_WITHOUT_LESSONS):holidayis «nobody is at school» andday_offis «we are not» — a difference in what the label means to a reader, not in what happens, and only the first of them ever behaved. A class given «🌿 Отгул» for a Monday got the label printed and then all six lessons listed underneath it, on the day card, on the phone, in the widget, in the calendar feed and in a morning digest that was therefore not silent either.remoteandself_studykeep their lessons on purpose: remote teaching is the same lessons at the same times somewhere else, and set work is plausibly «these lessons, but at home» — dropping them would answer a question nobody asked.PUT /api/v1/daysstill accepts only the first four; the other two are marked in the bot.- Out of season a day carries no lessons. The weekly template is not repeated
outside the class's own terms — over June, July and August, over the days before
a year's first teaching day, and over the gaps an admin left between two terms —
so those days come back with an empty
lessonsarray and, unless somebody marked them by hand in which case their kind and note stand,kind: "holiday". A statutory non-working day is the same shape. Events and homework are returned either way: an excursion in June is a real thing, and it is the lessons that are out of season, not the day. off_reasonsays which of those it is, becausekindcannot: all four arrive asholidayand a calendar wants to draw them differently. It isout_of_year,between_terms,public_holiday, ornull— the key is always there (#321).nullon an ordinary day, including an ordinary empty one — «nobody put lessons on a Sunday» is not a reason, it is the absence of one. A client that has never heard of a value it is sent should treat it asnullrather than guess.holidaynames the date, whether or not it teaches:{"code", "title", "stops_lessons"}.stops_lessonsis true only for a statutory non-working day — «День учителя» is a full Wednesday with a badge on it, «День Победы» is not.titleis Russian, like every other string this server puts on a screen;codeis stable, so a client can write the name in its own language where it knows the date and fall back totitlewhere it does not. The list is inserver/app/services/holidays.py, and the yearly transfers are deliberately not in it: those are set by decree each December, and a wrong non-working day removes a real day of lessons and looks exactly like a correct one.kindon an event is one ofevent,canteen,exam,trip,meeting.- A cancelled lesson stays in the array with
is_cancelled: truerather than disappearing, so the UI can strike it through instead of silently renumbering the day. covers_lessontells the client whether the event replaces a lesson or merely sits in a break. It is what stops "Обед" from hiding a running lesson.devicedescribes what this device may do (see below). It is absent ornullfor nothing: a client that predates it ignores it. The Telegram id the device is linked to is never on the wire.- Unknown enum values must not crash a client - the Android mappers fall back to
normal/event.
A token on its own reads. To write - tick homework, keep a to-do list, and with an editor's role change the class's data - the device's owner tells the bot which phone is theirs.
{
"device_name": "Pixel 8",
"linked": false,
"role": null,
"can_edit": false,
"link_code": "K7PM3X",
"bot_deep_link": "https://t.me/lessons_bot?start=link_K7PM3X"
}While the device is unlinked the response carries a six-character link_code.
The app shows it; the person types /link K7PM3X into the bot, or taps
bot_deep_link, which opens the bot with the code filled in (null when the
deployment has not configured BOT_USERNAME). The code is stable across
polls and single-use: once claimed it is cleared, and the next /me shows
linked: true, the account's role in the class (viewer, editor,
admin, owner, or null for an account the bot does not know) and
can_edit (role of editor or above).
The role is looked up on every request, never stored on the device. Revoking someone in the bot revokes their phone in the same instant; there is no second permission system to keep in step.
Back to read-only. Answers {"linked": false}; the next /me issues a fresh
code. Idempotent. A class deleted between the read and the write — the phone's device
with it — is the 404 Class no longer exists (#654).
| Parameter | Default | Notes |
|---|---|---|
from |
today (class zone) | YYYY-MM-DD |
to |
from + 21 days |
at most 62 days after from |
[
{ "id": 17, "due_date": "2026-09-14", "subject": "Алгебра", "text": "№ 12–15", "attachment_url": null, "done": true }
]Ordered by date, then subject. done is this person's tick - thirty
pupils marking the same assignment each see their own - and is always false
for an unlinked device.
Body {"done": true} or {"done": false}; answers {"id": 17, "done": true}.
Sets rather than toggles, so a retried request lands on the same answer.
Requires a linked device (403 device is not linked); 404 for homework
outside this class. The same tick shows up in the bot's «📚 ДЗ» view.
The class's subject dictionary, sorted by name:
[ { "name": "Алгебра", "short_name": null, "teacher": "Иванова А. П.", "color": "#5B6ABF" } ]What is happening at this moment, computed on the server in the class's zone. The widget normally works this out from the bundle itself; the endpoint is for clients that would rather ask, and it is what the bundle's own arithmetic is checked against.
{
"date": "2026-09-07",
"time": "08:40:30",
"state": "lesson",
"current": { "index": 1, "subject": "Алгебра", "starts_at": "08:30:00", "ends_at": "09:15:00", "...": "LessonOut" },
"next": { "index": 2, "subject": "Физика", "...": "LessonOut" },
"until_next_seconds": 2070,
"next_school_day": "2026-09-14"
}state |
Meaning |
|---|---|
before_school |
Today has lessons and the first has not started; next is that lesson |
lesson |
current is running; next is the one after it, or null for the last |
break |
Between two lessons; next is the one about to start |
after_school |
The last lesson has ended |
day_off |
No lessons today (weekend, holiday, a fully cancelled day) |
no_data |
The class has no timetable at all |
until_next_seconds counts to the next boundary: the end of current during
a lesson, the start of next before school and in a break, null otherwise.
Cancelled lessons are skipped - a cancelled first lesson means the day starts
with the second. Events never change the state: a canteen break sits in a
break, and the countdown follows the bells. next_school_day is the first day
with lessons strictly after today.
A to-do list per person: «купить тетрадь», «сдать реферат до пятницы». The
same list the bot shows under «✅ Мои дела». All five endpoints require a
linked device and are scoped to the linked account; a task belonging to
anybody else is a 404.
GET /api/v1/tasks?include_done=false
POST /api/v1/tasks → 201
PATCH /api/v1/tasks/{id}
DELETE /api/v1/tasks/{id} → 204
POST /api/v1/tasks/{id}/done {"done": true}
A task:
{
"id": 3,
"title": "Купить тетрадь",
"notes": "в клетку",
"subject_name": "Алгебра",
"due_date": "2026-09-15",
"due_time": "18:00:00",
"priority": 2,
"done": false,
"done_at": null,
"homework_id": null,
"remind_at": "2026-09-15T08:00:00",
"created_at": "2026-09-12T10:41:07",
"updated_at": "2026-09-12T10:41:07"
}POST takes title (required, up to 200 characters) and any of the others.
priority is 0 (low), 1 (normal, the default) or 2 (high).
homework_id may point at a homework row of this class - a task created from
an assignment - and is 422 otherwise. remind_at is class wall time; an aware
timestamp (...Z, ...+03:00) is converted, a naive one is taken as is. The
bot sends one message at that moment and clears the field.
PATCH changes only the fields present in the body; null clears a nullable
one, so absent and null are different things. done may be set here too.
Lists come back undone first, then by deadline with undated tasks last, urgent
first.
{ "url": "https://lessons.example.com/api/v1/calendar/hk3G...JqQ.ics" }The class's iCalendar subscription URL, minting the secret on first request
and stable after. The origin is PUBLIC_BASE_URL when configured (behind
Vercel the function sees an internal host), otherwise the request's own.
No bearer - calendar apps cannot send one. The token in the path is the
authentication, which is why it is a secret of its own rather than the join
code: a subscription URL ends up in Google Calendar's settings, on a family
laptop and in the odd screenshot, and none of those should be able to mint
device tokens. An admin rotates it from the bot; 404 on an unknown token.
text/calendar, Cache-Control: private, max-age=900. Sixty days ahead: one
VEVENT per lesson (cancelled ones omitted) and per event, one VTODO per
homework with DUE;VALUE=DATE. Times are DTSTART;TZID=<zone> local wall
time with no VTIMEZONE block - every calendar that matters resolves IANA
names itself. UIDs derive from (class, date, slot), so a re-fetch sees the
same lesson as the same entry and a new substitution replaces it rather than
appearing twice. The feed is the class's and shared, so nobody's personal
tasks are in it.
For a linked device whose account is an editor or above. Each write does
exactly what the matching bot flow does: the same upsert rules, an entry in the
class's audit log («⚙️ Класс → 📜 Журнал») under the linked account, and a
message to every subscriber who asked to hear about that kind of change -
minus the author. Two distinct 403s: device is not linked and
editor role required; the app shows a different screen for each.
Dates must fall between 2000 and 2100 (422 otherwise), like start on the
bundle.
{ "due_date": "2026-09-14", "subject": "Алгебра", "text": "№ 12–15", "attachment_url": null }Upsert by (date, subject): one assignment per subject per day, and sending it
again replaces the text. Answers the row in the GET /homework shape
(id, due_date, subject, text, attachment_url, done). Subscribers
with «ДЗ» notifications on are told.
{"id": 17, "deleted": true}; 404 outside this class.
{ "date": "2026-09-14", "index": 2, "action": "replace", "subject": "Химия", "room": "118", "teacher": null, "note": "учитель на конференции" }One row per (date, lesson number). action is replace (needs at least one
of subject, room, teacher; an omitted subject keeps the template's
and changes the room or teacher), cancel, or clear, which deletes the row
and puts the lesson back on the timetable. Answers the stored row with the
action echoed. Subscribers with «замены и события» on are told.
Every 422 here is about one thing: a row that would be stored, written to the
log, announced to every subscriber — and drawn on no phone, in no widget and in
no calendar feed. There are three of them.
- On create, a number the day rings no bell at (
нет звонка для урока №N в этот день): the day view builds its times out of the bell rows. Only on create — an existing row at such a number has to stay editable, becauseclearis how a class gets out of one. - On create and on update, a
cancelor areplacenaming no subject at a number the weekly template puts nothing on (отменять нечего,замене без предмета нечего заменять): such a row has no subject to inherit and the resolver drops it. The question goes to the template rather than to the resolved day, because on update that day already contains the row being edited — areplacethat added «Астрономия» to an empty number would otherwise vouch for a second write that cleared the subject again. - On any date the resolver draws no lessons on at all: outside the school year — with its own sentence for the summer and for a date before the year has opened — and on a day already marked «выходной» by hand.
replace with a subject at an empty number is fine — that is how a lesson is
added to a day — and clear is always allowed, because it is how a class gets
out of a row it should not have.
A replace or a cancel of a substitution that another write deletes between this
one's read and its commit is a 404 (Unknown substitution, #384), and nothing is
written: the row is not made again behind the back of whoever took it off.
{ "date": "2026-09-14", "starts_at": "12:30", "ends_at": "13:00", "title": "Экскурсия", "kind": "trip", "location": "Эрмитаж", "covers_lesson": true }Always creates: events have no natural key, and two «Обед» rows on one day
are two breaks. ends_at must be after starts_at. covers_lesson defaults
the way the bot does - true for event and trip, false otherwise.
{"id": 42, "deleted": true}; 404 outside this class.
{ "date": "2026-09-14", "kind": "holiday", "note": "День учителя", "bell_schedule_id": null }Marks a whole date. kind: "normal" deletes the mark, so a day never carries a
row that says nothing. bell_schedule_id (for shortened days) must be one
of this class's bell schedules - 422 otherwise, and it must have rows: a day
pointed at an empty schedule draws nothing at all under a card saying
«⏱ Сокращённые уроки». A shortened day without a bell_schedule_id is a 422
as well (#321): the times are what «сокращённые» claims, and without a schedule the
day would announce shortened lessons and draw the usual ones. Answers the stored
row. Four kinds are accepted here — normal, holiday, shortened, remote —
while a day in the bundle can come back as any of six; self_study and day_off
are marked from the bot only. A mark that another write takes off between this
one's read and its commit is a 404 (this date has no mark, #384), and nothing is
written: the mark is not made again behind the back of whoever took it off.
Everything the bot's /class, /subjects, /bells, /devices, /log,
/stats, /export, /import and access requests do, under
/api/v1/manage, so a class admin can run the class from the phone. The bot
is the authority: the same minimum role guards the same operation on both
surfaces, the same rows move when a subject is renamed, and the same line
lands in the audit log. An admin who changes something in the app and then
opens the bot finds the class in the state the app said it was in.
Authorisation is server-side and per request: the bearer token names a device, the device names the Telegram account it was linked to, and that account's role in the class right now decides. Nothing the client sends about itself is consulted, and revoking somebody in the bot revokes their phone in the same instant.
| Method | Path | Role | Does |
|---|---|---|---|
GET |
/manage/class |
admin | The class card |
PATCH |
/manage/class |
admin | Rename, move its year, re-home, change time zone or join mode |
DELETE |
/manage/class |
owner | Delete the class and everything in it |
GET |
/manage/subjects |
editor | The dictionary, with ids |
POST |
/manage/subjects |
admin | Add a subject → 201 |
PATCH |
/manage/subjects/{id} |
admin | Rename / short name / teacher / colour |
DELETE |
/manage/subjects/{id} |
admin | Remove it; 409 while the timetable uses it |
GET |
/manage/bells |
admin | Every bell schedule, default marked |
POST |
/manage/bells |
admin | New schedule → 201 |
PATCH |
/manage/bells/{id} |
admin | Rename, or make it the class default |
PUT |
/manage/bells/{id}/periods |
admin | Replace its rows |
DELETE |
/manage/bells/{id} |
admin | Remove a schedule nothing uses |
GET |
/manage/timetable |
admin | Export the template as text |
POST |
/manage/timetable/import |
admin | Import the same text |
GET |
/manage/devices |
admin | Every phone in the class that is not revoked, linked or not |
POST |
/manage/devices/{id}/revoke |
admin | Switch a phone off |
POST |
/manage/devices/{id}/unlink |
admin | Back to read-only |
GET |
/manage/log |
admin | The audit log, paginated |
GET |
/manage/stats |
editor | The numbers /stats shows |
GET |
/manage/requests |
admin | Who is waiting for a role |
POST |
/manage/requests/{id}/approve |
admin | Grant the role |
POST |
/manage/requests/{id}/decline |
admin | Say no |
Refusals are the two the app already knows, with the role named:
403 device is not linked and 403 editor|admin|owner role required. A
404 is a row that is not this class's - ids are re-scoped by the query that
reads them, so one naming another class's subject finds nothing rather than
editing it. A 409 is a request that is well formed and refused by the
class's own state: a subject name already taken, a bell schedule days still
point at, a device that is not linked.
Every mutation writes one audit line per field changed, under the linked
account, with the same tags the bot writes (subject.rename, bells.edit,
class.name, timetable.import, …). Timestamps in responses here are class
wall time, like every other clock on this API: an admin in Vladivostok
reading a Moscow server's log should not see yesterday evening against this
morning's change.
Days, substitutions, events and homework are not on this surface. They are the
day-to-day writes and they already live under writing class
data at the editor's role - PUT /api/v1/days is the
API's «🏖 Особые дни».
GET /manage/class:
{
"id": 1,
"name": "9А",
"school": "Демо-школа",
"city": "Санкт-Петербург",
"timezone": "Europe/Moscow",
"timezone_label": "МСК (UTC+3) · Москва, Санкт-Петербург",
"join_code": "DEMO24",
"join_mode": "open",
"members": 12,
"devices": 9,
"pending_requests": 1,
"bell_schedule_id": 3,
"calendar_ready": true
}PATCH /manage/class takes any of name, grade, letter, school, city,
timezone, join_mode and answers the card. Only the fields present change; null clears
school or city. Moving grade or letter also recomposes the name from the two,
because that is where the name came from when the class was created: a class that went from
9 to 10 and stayed called «9А» showed the wrong class on every screen that prints one. A
request that names the class as well wins over both — an admin who typed a name has said
what they want — and the class.name audit line is written only when the name actually
changed. name and timezone may not be null or blank, and
timezone must be one of the eleven Russian zones the bot offers (422 unknown timezone otherwise). Changing the zone moves no stored time - a bell rings at
08:30 whatever the zone says - it changes which instant the class calls "now".
join_mode is open or invite and anything else is a 422 naming the field;
what the two mean is under «Кто пускает телефон» above.
DELETE /manage/class is the owner's alone and takes the confirmation the bot
asks for:
{ "confirm_name": "9А" }The name must match exactly, or 422; a sheet in the app is not the check,
because the endpoint is reachable without the sheet. The class, its timetable,
homework, substitutions, events, the log and every device token go with it - including
the caller's own, so the next request from that phone is a 401. Answers
{"id": 1, "deleted": true}.
A client that does not act on that 401 keeps a cached timetable of a class
that no longer exists, and — because the wipe happens on the way in to a new
class — carries it into the next one. The Android app drops its token and its
cache on any 401 from this API family, on the delete it made itself and on
one made from the bot alike; see TokenRejectedTest.
The dictionary is what keeps «Алгебра», «алгебра» and «Алг.» from being three
subjects in the timetable, the homework and the app's colours. GET answers
[{ "id": 4, "name": "Алгебра", "short_name": "Алг", "teacher": "Иванова А. П.", "color": "#5B6ABF" }],
sorted by name; an editor may read it.
It is not a list somebody has to keep up by hand. Every write that names a
subject in the weekly template goes through the dictionary: the entry is found
(ignoring case) or created, the lesson is linked to it by
timetable_entries.subject_id, and the dictionary's spelling is what gets
stored — so «АЛГЕБРА» in a paste joins the class's «Алгебра» instead of
founding a second subject with its own colour. Reading this list, or the
bundle, adopts anything a class typed before the link existed; that costs a
count once the two agree.
Which is why the dictionary is worth filling in. A colour set here reaches every lesson of that subject, and a teacher set here is the fallback for every lesson whose own cell names nobody — both on ordinary lessons and on substitutions. Before, an empty dictionary meant a timetable with no colours at all, whatever was typed into the template.
POST takes name (required) and any of short_name, teacher, color.
PATCH takes the same fields, changing only those present; null clears
short_name, teacher and color. Colours are written as #RRGGBB in any
case, with or without the #, and stored upper-case; anything else is 422.
Both answer:
{ "subject": { "id": 4, "name": "Алгебра и начала анализа", "short_name": null, "teacher": null, "color": null }, "moved": 12 }moved is the point of PATCH name. The timetable, the homework and the
substitutions store the subject as text as well - deliberately, so a lesson keeps
its name when a subject is deleted - so a rename is still a cascade, and all of
it happens in one transaction. moved is how many of those rows went with it.
The template is matched on the link and on the old spelling: the link is the
half that survives a row whose name drifted, the name is the half that catches
rows written before the link existed. Renaming onto a name the class already uses is 409: merging
two subjects is a different operation, and doing it by accident cannot be
undone.
DELETE is refused with 409 while the weekly template still uses the
subject, and the detail says how many lessons do ("12 lesson(s) still use this subject"). It used to succeed and leave the lessons alone — the timetable
keeps the name, so the class kept its timetable and lost only the colour and
the teacher. That stopped meaning anything once the dictionary began keeping
itself: the name is still in the template, so the next read adopts it straight
back, stripped of the colour, the short name and the teacher the deleted row
carried, and the admin was told nothing at all. Two halves of one list are
deleted in one order — out of the timetable, then out of the dictionary. A
subject nothing teaches still deletes in one call, which is what this endpoint
was really for.
Uniqueness ignores case everywhere it is checked — POST, PATCH name and the
bot — because the matcher does. When it did not, «ФИЗИКА» was allowed in beside
«Физика», and the healing read then saw one subject where the dictionary had
two and rewrote every «Физика» lesson onto whichever row it happened to keep:
a read renaming a subject and dropping the colour of the one it abandoned.
A class keeps several - «Обычное», «Сокращённое», «Суббота» - and one of them is the default the day view uses when nothing says otherwise.
{ "id": 3, "name": "Обычное", "is_default": true, "silenced_lessons": 0,
"periods": [ { "index": 1, "starts_at": "08:30:00", "ends_at": "09:15:00" } ] }POST /manage/bells takes name and an optional periods; a new schedule is
never made the default, because one is created in order to be pointed at by
particular days. PATCH takes name and is_default; is_default: false is
422 - a class with no default has no times for an ordinary day, so the way
to stop using one is to make another the default. is_default: true on a
schedule with no rows is 422 too (#321): every ordinary day rings the default,
so the class would go blank on every phone, in the widget, the calendar feed and
the digest at once.
PUT /manage/bells/{id}/periods replaces the rows wholesale, because that is
what editing bells is: move one lesson and every lesson after it shifts.
Between one and twenty rows, index 1-20 and unique, ends_at after
starts_at; an empty list is 422, the same refusal the bot gives: bells are not
erased by sending nothing.
Both writes answer with silenced_lessons: how many weekday rows this request
stopped ringing. Shrinking a schedule, or pointing the class at a shorter one,
leaves every lesson at a number past the new last rung stored in the database
and drawn on no phone, in no widget, in no calendar feed and in no digest —
nothing is deleted and everything is gone. It is counted in rows rather than in
numbers, because one number under two weekdays is two lessons nobody will see.
Zero on a read, on a rename, and on any write that silenced nothing; a client
that ignores it will report a clean save over a class that just lost six
lessons, which is what the bot says out loud in an alert.
DELETE refuses the class default and any schedule a special day still points
at (409, with the count). Both are a SET NULL in the database, which would
silently move those days onto the default schedule - a change nobody asked
for, on dates an admin is not looking at.
A bell-row replacement or change of default keeps its class and schedule
parents until commit. Deletion takes the schedule's exclusive lock before its
ORM period rows, so an editor that started
first can finish before deletion proceeds. It then re-reads the class default
and special-day usage under that lock: if a reference committed after the early
checks or while the lock waited, deletion returns the same existing conflict refusal.
If a schedule was read and another
writer already deleted it, deletion remains an idempotent success without a
duplicate audit entry. An id missing at the initial lookup still answers 404.
GET /manage/timetable answers { "text": "== Понедельник ==\n1. Алгебра, 214\n…", "lessons": 18 }
- byte for byte what «📤 Экспорт» sends, so a text saved out of the bot can be
imported by the app and the other way round. An empty timetable is an empty
string, not a
404.
POST /manage/timetable/import:
{ "text": "== Понедельник ==\n1. Химия, 118\n2. Биология\n\n== Звонки ==\n1. 09:00-09:40", "replace": false }{
"applied": false,
"days": [1],
"lessons": 2,
"bells": 1,
"conflicts": [ { "weekday": 1, "existing": 3, "incoming": 2 } ],
"rejected": ["не строка"]
}The bot shows a preview and asks «Применить». An API has no screen to show one
on, so the preview is the refusal: if a weekday in the paste already has
lessons, nothing is written and the response says what stands to be
overwritten. Sending it again with replace: true is the second tap, and then
applied is true and lessons counts what was written.
The write keeps its class and expected default bell schedule until commit. If
either disappeared after the read, it answers 404, Unknown bell schedule,
and persists no weekday replacement or new schedule. An import that begins
without a default can create one while its class is still present (#657).
Only the weekdays the paste names are touched, so a Tuesday block against a
Monday-only timetable is not a conflict at all, and a day named with nothing
under it is emptied - that is how a paste says «в четверг уроков нет».
rejected echoes the lesson lines the parser could not read, so an admin can fix
the two that were typos rather than re-reading the whole paste — but not every
unreadable line: what the parser could not read in a == Звонки == block is
discarded and reported nowhere, so a mistyped bell is simply absent (#321). It
also carries "понедельник, урок N: нет такого звонка в расписании звонков" for every
lesson numbered past the last bell: the day view builds its times out of the
bell rows, so such a lesson would be stored, counted in lessons and then
drawn nowhere at all. One line per dropped row, named by its weekday — the
ceiling is class-wide, so the same number under two weekdays is two lessons
gone, and one line for both admitted to one of them.
Those lines are not written, and lessons counts only what was. When the same
paste brings a == Звонки == block, the lessons are checked against those,
so one request can legitimately add a ninth bell and a ninth lesson together.
The other direction is reported too: a lesson already stored, on a weekday the
paste did not touch, that the new bells no longer ring stays in the database and
is drawn nowhere, and rejected names it as "…, урок N: больше не звонит — новые звонки короче".
A paste with no weekday header and no bells block in it is 422. A
== Звонки == block replaces the default schedule's rows outright, as it does
in the bot: it is a schedule, not a day, and nothing else points at it.
Commas inside a field. The last field takes everything that is left, so a
teacher Иванов И.И., к.п.н. needs no syntax. A subject or a room containing a
comma is wrapped in double quotes — 1. "Иностранный язык, второй", 305 — and
that is what the export writes; a doubled "" inside such a field is one
literal quote. Without this the export produced a line the import read back as
a different subject in a room called «второй», which is the round trip the two
endpoints exist to promise each other.
GET /manage/devices?include_revoked=false:
[ { "id": 7, "device_name": "Pixel 8", "linked": true, "owner": "@anna", "role": "editor",
"revoked": false, "created_at": "2026-09-01T18:22:04", "last_seen_at": "2026-09-12T07:55:10",
"linked_at": "2026-09-01T18:24:31" } ]Oldest first, and every phone that joined the class, not only the linked ones: a
read-only phone is a row with linked: false (#321); include_revoked=true adds the
revoked ones. role is a lookup, not a stored field - a device acts with
whatever role its owner holds right now - and owner is a display name — the
@username, else the name Telegram gave, else the numeric id, as the bot shows an admin;
there is no telegram_id field on the wire.
POST /manage/devices/{id}/revoke switches a phone off: revoked, not deleted,
because the row is what a token is checked against and keeping it is what makes
the refusal instant and permanent. It is idempotent and logs once. An admin may
revoke the phone they are holding, and then the next request from it is a 401
- that is how a lost phone is dealt with from the one still in a pocket.
POST /manage/devices/{id}/unlink puts a phone back to read-only without
taking it off the class: it keeps reading the timetable and loses the role it
borrowed. A device that is not linked is 409.
GET /manage/log?limit=30&offset=0 (limit 1-100):
{
"entries": [ { "id": 412, "action": "subject.rename", "summary": "предмет «Алгебра» → «Алгебра и начала анализа», строк обновлено: 12", "who": "@anna", "at": "2026-09-12T14:05:33" } ],
"limit": 30,
"offset": 0,
"has_more": true
}Newest first. has_more rather than a total: the log is append-only and
unbounded, and counting it would be a full scan on every page turn. who is a
display name, null for a line the system wrote. summary is plain text -
the bot escapes it at render time, and so must a client that puts it in HTML.
GET /manage/stats, readable by an editor, because it says whether the
timetable is complete and whether homework is being entered - which is what
the person entering it wants to know.
{
"today": "2026-09-12",
"lessons_per_week": 32.5,
"subjects_count": 14,
"subjects": [ { "name": "Алгебра", "hours": 4.0 } ],
"homework_open": 6,
"homework_total": 141,
"members_by_role": { "owner": 1, "admin": 2, "editor": 4, "viewer": 5 },
"devices_active": 9,
"overrides_upcoming": 3,
"events_upcoming": 2
}A lesson that alternates weeks counts as half, which is how a school's own
paperwork writes «часов в неделю». subjects is ordered by hours, then name.
Someone with a read-only phone asks for a role with /request in the bot;
the admins answer here or there.
GET /manage/requests lists the pending ones, oldest first:
[ { "id": 5, "who": "@petya", "requested_role": "editor", "message": "я староста", "created_at": "2026-09-11T19:02:44" } ]POST /manage/requests/{id}/approve grants it. The body is optional;
{ "role": "admin" } grants something other than what was asked for. Answers
{ "id": 5, "status": "approved", "role": "editor", "who": "@petya" }, where
role is the role the member holds afterwards: an existing member is never
lowered, so approving an old request for editor from somebody made an admin
since answers "admin", and the notice they get in Telegram says they are an
admin already rather than that they were made an editor.
Two guards, the bot's own: nobody may grant a role at or above their own
(403 cannot grant a role at or above your own, and owner is granted by the
deployment's OWNER_IDS alone, never through this endpoint), and nobody may
change the role of a peer or a senior (403 cannot change this member's role). Without both, an admin could promote a friend to admin and be demoted
by them a moment later.
POST /manage/requests/{id}/decline closes it with status: "declined" and
role: null. Either way the requester is told in Telegram, because that is
where they asked; a decision stands whether or not the message was delivered.
A request that has already been answered is a 404, so two admins tapping at
once cannot grant twice.
Not for clients. A serverless deployment has no scheduler, so the morning and
evening digests and one-off task reminders are sent by whoever calls this
endpoint, every five minutes, with the X-Cron-Secret header set to the
deployment's CRON_SECRET. That caller is an external cron service;
.github/workflows/reminders.yml in this repository asks for the same five
minutes but is only the fallback, for the measured reason in
deploy.md.
| Status | Meaning |
|---|---|
404 |
CRON_SECRET is unset: the endpoint does not exist, like the webhook without its secret |
403 |
Wrong or missing header (constant-time comparison) |
503 |
BOT_TOKEN is unset: nothing to send with |
200 |
{"morning": 1, "evening": 0, "tasks": 2, "failed": 0, "fsm_purged": 0, "join_attempts_purged": 3, "diary_sessions_purged": 0, "device_tokens_purged": 0, "diary_links_purged": 0, "device_invites_purged": 0, "diary_sessions_kept_alive": 4, "diary_sessions_lost": 1, "diary_keepalive_failed": false} |
What is due is decided from each class's own clock and from what was already sent today, never from when the last tick ran - so a tick that runs twice in a minute or an hour late sends each digest once.
The same tick sweeps the tables that grow between calls — nothing else in this deployment runs between requests:
| What | When it is deleted | Why |
|---|---|---|
Abandoned bot dialogues (fsm_states) |
after two days | fsm_purged; the «current class» preference sits in the same table and is exempt, because it is written once and only read afterwards |
Throttle counters (join_attempts): failed joins, failed diary sign-ins, and every directory search |
after an hour | join_attempts_purged |
Diary sessions (diary_sessions) |
a day after the service refuses one, 30 days after it was last used | a live token for somebody else's service is inside |
Device tokens (device_tokens) |
after 180 days of silence | every POST /join creates a row, and reinstalling the app leaves the old one for ever |
Diary sign-in tickets (diary_link_codes) |
on expiry | diary_links_purged |
Personal connect codes (device_invites) |
a day after they expire | device_invites_purged; a day rather than immediately, because "my code does not work" is asked within minutes, while who connected a phone is remembered by the device token itself |
One table is deliberately not swept: usage_counters, the directory's daily allowance, holds
one row per allowance per day — 365 rows of three columns a year — and yesterday's row is
what says how close yesterday came to the cap.
180 days is comfortably longer than the summer holidays: a phone silent since the end of May has to work in September. A device in use is marked no less than once every 15 minutes, on any read.
The same tick also keeps «Сетевой город» sessions alive. That diary idles a session out
in 15–60 minutes and this project stores no password to sign back in with, so the tick pings
each live one with GET /webapi/context, within a batch cap of 200 taken stalest first
(by the last ping, or for a row never pinged the moment the diary last took it), and a time
budget — no ping starts after 18 seconds of the tick and none is waited for past 24, so the
results are always written before the platform's 30-second ceiling. It never
touches last_used_at — a ping must not look like the family using the session, or the
30-day purge above would never fire. diary_sessions_kept_alive is how many were pinged
alive, diary_sessions_lost how many the upstream had already dropped (they are expired, and
the app is told to sign in again — a 401 or a login page only: a regional server answering
a 5xx or 429, an HTML error page included, is down, and its sessions are left as they are), and diary_keepalive_failed is true when the keep-alive
itself raised — isolated so a diary fault never fails the whole tick and reddens the fallback
clock. Petersburg sessions are not pinged; they refresh from their own answers. This depends
on the external cron, not GitHub's fallback clock, which is too sparse to keep a session
alive; deploy.md says why.
Two guards keep the pings honest. A regional server that drops this deployment's address answers every session on it the same way, so after its first such refusal the tick skips that region's sessions not yet started — at most the pings already in flight are wasted — and they wait for the next tick. And a ping's result is written back only to a row that still holds the sealed credential the ping was sent with: a real read that rotated the cookies while the ping was in the air is never overwritten with the older ones, and a ping that failed on the old credential does not expire a row whose new one is fine. The two counters count rows actually written, not pings sent.
Both unauthenticated. /health returns {"status": "ok", "api_version": 1} and
deliberately opens no database connection at all — a ping meant to keep the function
warm would otherwise keep waking a Neon compute that has scaled to zero. Use it for
container health checks.
/api/v1/warmup is the same plus one round trip, which is what actually wakes the
database (see deploy.md), and since the connection is open anyway it also reports
whether the schema is the one this code was written against. Every answer also carries "v2": true when
v2 is mounted and false when it could not be loaded and /api/v2 and /api/rpc answer 503; it never changes
status. Three answers:
| Body | Meaning | |
|---|---|---|
200 |
{"status": "ok", "api_version": 1, "schema": "0019"} |
the database is reachable and at the revision the code expects |
200 |
{"status": "degraded", …, "schema": …, "expected_schema": …, "detail": …} |
both revisions named, and detail says which way they diverge |
503 |
{"status": "down", "api_version": 1, "detail": "База недоступна."} |
the database could not be reached |
The two directions of degraded are opposites and the text says so: «База отстала от
кода…» is the outage — a deploy landed before its migration, and the first ORM read of
a column that is not there kills the bot's middleware, i.e. every update at once — while
«База впереди кода…» is the documented procedure caught between its two steps, and it
closes on its own. A third wording covers a database with no alembic_version table.
503 rather than a 500 with a traceback: the service cannot serve and it is not the
caller's fault, which is the thing a monitor already knows how to page on. The driver's
own message is logged rather than answered, because a connection error prints the host,
the user and sometimes the password out of the URL, and this endpoint is unauthenticated.
The app draws all of this as a badge on Настройки → О приложении — «Сервер на связи», «Сервер: база и код разошлись», «Сервер не отвечает», «Адрес сервера не задан» — which is the one place in the interface that tells those four apart. See design.md.
A separate surface under /api/v1/diary. Separate because it is a different thing:
/api/v1 hands out the class's timetable, which the bot fills in, while this is one
family's account in a service this project does not run. They have nothing in common but the
server.
There are two such services behind this one surface — «Петербургское образование»
(dnevnik2.petersburgedu.ru) and «Сетевой город. Образование», the diary of about twenty
regions — and the API does not change between them. Which one a session is with is
decided at sign-in and stored on the session; every endpoint below is provider-neutral, and
the client reads the same shapes whichever diary answered. Neither has ever been opened
against a live server from here (see the README's honest status).
Two ways in, one API after. A diary session of ours is opened one of two ways. A client
that signs in with the diary itself — straight at the diary's own address, so that the
password goes to the diary and nowhere else — hands the session the diary gave it to
POST /api/v1/diary/session; this server reads with it once from its own address, seals it
and answers with a token of ours, and the client forgets its copy. A client that does not
sends the login and the password to POST /api/v1/diary/login, and this server signs in on
its behalf. From then on the two are indistinguishable: every read below goes through this
server with our token, and none of an upstream's parameters — Petersburg's p_educations[]
and estimate_type_code, «Сетевой город»'s scid and its weekly-diary shape — crosses the
boundary of our API. If a field is renamed up there tomorrow, one directory is what gets
fixed (app/providers/petersburg/ or app/providers/netschool/), and neither the app nor
this document changes.
The one exception is the registration body, which is the upstream's session and so
carries the upstream's names: Petersburg's X-JWT-Token, «Сетевой город»'s at bearer and
its two session cookies. That is the price of the password never reaching this server: the
diary's sign-in protocol then lives in the client as well as here, and the known-answer
vectors in server/tests/vectors/diary_protocol.json pin both sign-ins so that the two
implementations are tested against one set of bytes.
{
"enabled": true,
"registration": true,
"providers": {
"petersburg": {},
"netschool": { "regions": ["amur", "zabaikalsky", "kamchatka", "…"] }
}
}Anonymous, and it opens no database connection, so it is cheap to ask on every sign-in
screen. enabled is false when the deployment has no DIARY_SECRET — nothing a person
types will help, and a client should say so before asking for a password. registration
says this server takes a session a client opened itself; a server from before that answers
404 here, which answers the question too. netschool.regions are the allow-list's keys
this server signs in to with a password: sixteen of the nineteen, because altai-krai,
primorye and tula take only Госуслуги and are never listed. A region missing from the
list is one a client should not send a password to, since the session it opened could not
be kept here. v2 alone says how each server is reached (GetDiaryCapabilities, #406); this
answer keeps its shape.
POST /api/v1/diary/session
{ "provider": "petersburg", "login": "parent@example.com",
"credential": { "token": "eyJhbGciOi…" } }
POST /api/v1/diary/session
{ "provider": "netschool", "login": "ivanova.m", "region": "samara", "school_id": 1234,
"credential": { "at": "…", "cookies": { "NSSESSIONID": "…", "ESRNSec": "…" },
"ver": "…", "time_out": 45 } }
{
"token": "…",
"login": "ivanova.m",
"provider": "netschool",
"region": "samara",
"school_id": 1234,
"school_name": "МБОУ Школа № 5",
"zone": "Europe/Samara",
"students": [
{ "id": 7, "first_name": "Маша", "last_name": "Иванова", "middle_name": null,
"full_name": "Иванова Маша", "school": null, "class_name": "5Б" }
]
}The body is one of two shapes, chosen by provider, and every level of it refuses a key it
does not know: a password key anywhere is a 422, so no client can send one here, by
mistake or otherwise. login is what the person typed into the client's own form. Nothing
upstream vouches for it, so it names the session — it is what the answer echoes and what
the client prints as the account signed in — and decides nothing: a login copied from
another family reaches nothing of theirs, because what a session reaches is what its own
diary lists (see Corrections over the diary). For «Сетевой
город», region must be an allow-listed key that takes a
password and school_id the diary's own school id — both checked before any upstream call,
so a region this server does not serve never receives a request. In credential,
Petersburg's token must be a JWT; NSSESSIONID is required and ESRNSec, ver and
time_out are sent only if the diary handed them over. Every value is checked as something
that can go back upstream whole — a cookie value holding ; would smuggle a second cookie
onto every read, and an at holding a line break a second header — by the one definition in
app/providers/diary/http.py, which the clients writing those headers apply again.
The check is one read from here. The server reads with the session once, from its own
address: Petersburg's list of pupils, or «Сетевой город»'s four bootstrap calls — the
pupils, the current school year, the context that names the school, and the assignment
types — which fill what a sealed session cannot read without. It then seals what it read
with, possibly rotated by those very reads, exactly as a password sign-in's session is
sealed. The answer never carries the upstream credential back. token and login sit where
/login's answer has them, so a client decodes both the same way; students is what the
check already fetched; zone is the zone the diary cuts its days in — Petersburg's, or the
region's administrative centre — by the same rule the server's own «today» for this session
uses (services/diary.zone_for); school_name is what «Сетевой город» calls the school,
and null for Petersburg.
| Status | What happened | Counted by the limiter |
|---|---|---|
200 |
the session works from here, and it is ours now | — |
403 |
the diary took the session, and there is no pupil behind the account — a staff account, or a pupil's own account that does not list itself | yes |
409 |
the diary refused, from this server's address, the session it had just handed the client. It is not the password | yes |
422 |
not one of the two shapes, a value that cannot be sent upstream whole, or a region this server does not sign in to. detail names what was wrong and never repeats the value: FastAPI's validation answer normally echoes each refused value as input, and here that value is a session or a password |
no |
429 |
ten counted failures, or twenty sessions opened, from this address within fifteen minutes, on /login and /session together; Retry-After says how long |
— |
502 |
the diary answered something nobody can read — for «Сетевой город», that includes a current school year without an id or its dates, since no read can be made without them | yes |
503 |
the diary is off on this server, refuses this server's address, or is not answering; X-Diary-Unavailable says which (see Error codes) |
no |
409 rather than /login's 401 + X-Diary-Reauth. The session worked on the client
seconds ago. Asking for the password again would open another one that fails the same way
from here, and the client would loop; what failed is where the session came from. A client
should say that it is not the password and not retry by itself. Whether either diary
accepts a session opened on a phone in Russia when it is replayed from this project's own
deployment — pinned to Vercel's Frankfurt region (vercel.json) — has never been seen:
no session has been registered against a live diary, and 409 is the designed answer for
the case where it is not.
It shares /login's limiter and its bucket, so ten wrong passwords on one do not buy
ten more tries on the other. What is counted follows the same line as /login's: whatever
the upstream judged, which includes the 409 a replay of a session that was never real
produces; what is forgiven is what never reached it, or reached a diary that did not answer.
A 200 is counted too, on a limit of its own: twenty sessions opened per address in
fifteen minutes, through either door. A session is not free once it is open — the cron
pings every «Сетевой город» one from this server's address for as long as it lives — and
counting failures alone let one real session be replayed into /session without end, each
replay a new row in the keep-alive's queue.
A registered session belongs to no class and no Telegram account. The row carries neither, so the bot's «📒 Мой дневник» does not see it; a phone and the bot hold separate sessions, each signed in on its own. Linking the two is deliberately deferred (#143).
POST /api/v1/diary/login
{ "login": "parent@example.com", "password": "…" }
{ "token": "…", "login": "parent@example.com" }Unchanged by registration, and kept for the clients built before it. provider, region
and school_id are optional. Absent provider means Petersburg, so a client that sends
only a login and a password signs in there exactly as before. For «Сетевой город»,
provider is "netschool", region is a key into the server's own allow-list and
school_id the upstream's school id; both are validated in the route before any upstream
call, so an unknown region, a region the allow-list knows to take only Госуслуги, or a
missing school is a 422. A region whose server answers at sign-in that it takes only
Госуслуги, or refuses this deployment's address, answers 503 with X-Diary-Unavailable,
and the sign-in limiter does not count it, because nothing there looked at the password.
A body it refuses is a 422 that names what was wrong and never repeats the value, a
password refused for its length included, as /session's never has.
This route receives the password, and so does the bot's sign-in page (/diary/signin,
described in bot.md), which is a separate route over the same sign-in: each passes
the password to the diary for the sign-in and writes it down nowhere. Only registration
keeps it off this server altogether.
The password is not stored, on either route. It is needed for the sign-in to somebody
else's service — «Сетевой город» may ask for a role and take a second login request inside
the same sign-in — after which it is forgotten. Only the diary's own session is stored, and
it is refreshed on the fly: the service hands back a fresh token on almost every answer and
we overwrite ours with it, so a session in use does not die of age. When it does finally
stop being accepted, any request answers 401 with an X-Diary-Reauth: required header —
which is a request to sign in again, not "the token is wrong".
The price of that decision is honest: a background sync of the diary lives no longer than the session. The alternative — keeping every family's password in the database to save one sign-in screen every few days — is not worth it.
This session's token is not the same as the class device's. A phone can be connected to a class without a diary and to a diary without a class; one token meaning both would have to be re-minted whenever either half changed.
Failed sign-ins are rate-limited per client address, ten per fifteen minutes, in a bucket of
their own shared by /login and /session: ten wrong diary passwords must not spend a
phone's thirty /join attempts, nor buy ten more tries by session. Sessions opened are held
to twenty per address in the same fifteen minutes, in a bucket of their own. Past either
limit both answer 429 with Retry-After, and it is counted in the database, like the join
limiter, because nothing in this deployment survives between requests. What the limit is for
is that this server's address must not become a way of guessing passwords against somebody
else's school diary. An attempt is counted before the diary is asked, and handed back once
it turns out not to be one (a success for the failure count, a failure for the session
count, a 503 for both): counted after the answer, as it used to be, forty guesses sent at
once all read a count from before any of them had been written, and two dozen reached the
diary inside a window whose limit is ten. The same holds for /join and the directory.
| Endpoint | Answer |
|---|---|
GET /api/v1/diary/students |
the children this account can see |
GET /api/v1/diary/students/{id}/schedule?from=&to= |
the timetable |
GET /api/v1/diary/students/{id}/homework?from=&to= |
the assignments |
GET /api/v1/diary/students/{id}/grades?from=&to= |
the marks |
GET /api/v1/diary/students/{id}/periods |
the school periods |
GET /api/v1/diary/students/{id}/subjects?period_id= |
a period's subjects |
GET /api/v1/diary/students/{id}/teachers |
the teachers |
GET /api/v1/diary/students/{id}/attendance |
the turnstile passages |
GET /api/v1/diary/students/{id}/overrides |
the child's corrections over the diary, whoever wrote them |
PUT /api/v1/diary/students/{id}/overrides |
write a correction |
POST /api/v1/diary/students/{id}/overrides/reset |
reset one, for everyone who sees the child |
DELETE /api/v1/diary/students/{id}/overrides/all |
reset them all, for everyone who sees the child |
POST /api/v1/diary/logout |
forget the session |
from and to are ISO dates; the default is two weeks ahead and the maximum is 62 days.
{id} is a child's identifier from /students, and it is checked against the list this
account may see: somebody else's id answers 404 rather than somebody else's data.
A PUT /overrides whose correction somebody else resets or clears between this write's read
and its commit is a 409 (this field has no correction, #654), and nothing is written: the
correction is not made again behind the back of whoever took it off. A 409 and not the
404 the other writes answer that race with, because on this family a 404 already means
one thing, a child not on this account, and the app reads it so whatever detail says: a
parent whose relative had just cleared a correction would be told the child is not theirs.
The service puts marks, absences, late arrivals and remarks into one list and tells them apart by a numeric code. We tell them apart on the client's behalf:
{ "subject": "Алгебра", "date": "2026-09-11", "value": "Н", "kind": "absence" }value is what gets written into the register's cell; kind is what it actually is:
grade, absence, late, remark, other. A client does not need to know that
"was absent" is code 30000.
Homework is not a separate entity in the service: it is a field of a lesson. /homework
takes it out and hands it back as a list, because that is how people ask for it.
The diary is read-only for us, and that does not change: nothing goes upstream. A correction is a value laid over what came from above, on the way out, and a reset takes it off. Nothing changes in the diary itself, and the teacher does not see the correction.
A lesson and an assignment arrive with a key and a list of corrections:
{
"date": "2026-09-15", "number": 1, "subject": "Алгебра", "room": "204",
"target": "lesson:2026-09-15:n1:Алгебра",
"edits": [
{ "field": "room", "value": "204", "original": "12", "changed_upstream": false }
],
"ambiguous": false
}target is built by the server alone, and the client hands it back verbatim. Two
implementations of a key that has to match byte for byte agree exactly until the first
lesson with no number. A target the server would never build is refused with 422, a
number in it spelled any way but the server's own (hw:id:007, a superscript digit)
included: nothing would ever lay such a correction over anything (#393).
original is what the diary says now, not what it said when the correction was written.
changed_upstream is raised when those two have diverged: a teacher who has finally filled
the homework in must not end up hidden behind a correction written when it was empty. The
correction itself is not reset — a person wrote it, and the code will not throw it away on
their behalf.
ambiguous means that two lessons that day produced one key. That happens when a class is
split into groups: a lesson's number is not unique within a day in the diary, and what tells
such lessons apart is the room and the teacher — that is, exactly the fields being
corrected. The correction is then applied to neither of them, and the client says so.
Not everything can be corrected. On a lesson: homework, room, teacher, topic; on
an assignment: text. Marks and the turnstile are not in that list and will not be: a mark
and a passage are statements about what happened, and an app that lets you rewrite one
produces a forged record that looks official. subject is not correctable because it is
half of the key.
Corrections belong to the child — not to the session, and not to the login. The key is
the diary's server (Petersburg's, or the «Сетевой город» regional server's host) and the
pupil's id on it. A diary session dies every few days, and a correction that went with it
would disappear by itself, silently, before anybody pressed "reset"; and the login is only
what a client typed at
POST /session, which
nothing upstream vouches for, so it decides nothing.
So the corrections are shared by everyone whose own diary lists the child: both
parents, each signed in with their own account; the pupil's own account, when the diary
lists the pupil to themselves; and, literally, any account the diary answers with that
child — a staff account included, should its list ever not be empty (a staff account gets
403 at registration only because its list has so far been empty, which is an observation
rather than a rule). What decides is the {id} check above, before any correction is read
or written: on every call the id is looked up among the pupils this session's own diary
lists, and anything else is a 404. A login gains nothing, because no correction route
reads it: naming another family's login at /session, or a string spelled exactly like the
server's internal key, reaches the pupils one's own diary lists and nothing else.
What sharing means for a client:
- One correction per field per child, and the last writer wins —
originalincluded, so the other adult'schanged_upstreamis measured against what the last writer saw. Nothing checks a version: a client's copy may be stale, because the other adult may have changed or reset a field since its last read. - No row says who wrote it. There is no author column, so a client cannot tell «your correction» from «theirs», and should not say either.
- A reset takes the correction off for everyone who sees the child — one field, or all of
them.
DELETE …/overrides/allnever reaches beyond the one child in its path.
The same pupil number on two diaries is two children: pupil 11 on one regional server is not
pupil 11 on another, nor the Petersburg person whose id is 11. The key follows the server's
host rather than the region's name, so if a region's origin ever moved, its corrections would
stop matching — lost — rather than attach to whichever child the new server gives the same
number.
A session whose region names no server this code knows is sent to sign in again (401 with
X-Diary-Reauth: required) rather than given a guess.
A Petersburg child the diary lists by a plain id rather than by its person id gets no
corrections at all. Nothing says what that number counts, and with the login out of the key
it would be all that told one family's child from another's. Its schedule and homework come
back as the diary has them, its list is empty, a reset answers 204 with nothing to take
off, and PUT answers 422 «Для этого ученика правки недоступны», which the app shows as it
shows any field it cannot correct. No live answer has been seen to take that path.
Two things are assumed and have not been observed: that a «Сетевой город» pupil id is unique
on its server rather than only within a school, and that two parents' accounts see one child
under one id, in either diary. If the id turned out to be per school, the school would have to
come from the diary's own answer — never from the school_id a client sends at /session,
which nothing compares with the diary.
Resetting one correction is POST .../overrides/reset with a body of
{"target": …, "field": …}, not a DELETE with the same fields in the query. target is a
string glued together with colons, and a subject's name is inside it: «ОБЖ и экология»
breaks on &, and a long key gets cut by a proxy's log. A body survives both. The reset is
idempotent: taking off something that was never corrected answers 204 rather than 404 — the
requested state has been reached either way.
GET /overrides lists the corrections for the screen that takes them off, and every row has
original_when_written — what the diary said then. That is deliberately a different
word from the original in a lesson's edits: that one is what the diary says now, that
is, the value the correction is covering right at this moment. The same field is named
differently because it means opposite things, and a client that confused them would show
"before / after" back to front.
Corrections are not applied in the bot. The bot draws a day as one block of text with no button on a lesson, so a correction there would be indistinguishable from what the school wrote and there would be nothing to take it off with — and that is the surface a parent reads more often. The bot stays an unaltered mirror of the diary; the corrections live in the app, where they are visible as corrections and are reversible.
| Code | What happened | What the app should do |
|---|---|---|
401 |
our session's token did not fit | ask them to sign in |
401 + X-Diary-Reauth: required |
the diary's session expired | sign in again — a new session to register, or the password on /login |
403 |
on /diary/session only: the account has no pupil |
say so; signing in again will not change it |
404 |
this account has no such child | — |
409 |
on /diary/session only: the diary will not take this session from this server |
say it is not the password; do not retry by itself |
422 |
on reads, the date range is inverted or wider than 62 days; on PUT .../overrides, the correction was refused: an unknown target — a number in it spelled any way but the server's own included (#393) — an uncorrectable field, or an empty value where empty is not allowed; on /login and /session, a body or a region this server will not sign in with |
on a read, fix the range; on a correction, show detail |
429 |
on /diary/login and /diary/session together, ten counted failures or twenty sessions opened from this address inside fifteen minutes |
wait out Retry-After, and do not blame the password |
502 |
the diary answered incomprehensibly | say that the service has changed |
503 + X-Diary-Unavailable: disabled |
this deployment has no DIARY_SECRET; the diary is off here. A request with a diary token gets this too, before the token is looked at, and its session is kept for when the key is back (#302) |
say it is off on this server; nothing typed will help; keep the token |
503 + X-Diary-Unavailable: address-refused |
the region's server drops this server's address | say it is not the password, and not worth retrying |
503 + X-Diary-Unavailable: upstream |
the diary is not answering — a timeout, a 5xx or a 429, whatever the body, an HTML error page included — or at sign-in answered that it takes only Госуслуги |
offer to retry later; the session is kept |
Every 503 under /api/v1/diary carries X-Diary-Unavailable, /login's included,
because the three cases want three different sentences and detail is Russian prose a
client should not parse. A 503 is also the one refusal the sign-in limiter never counts:
in each case nothing read what was typed.
One code for two different things is the price of both the range and the correction being
checked as a request body. What tells them apart is the call, not the answer: there is
nothing in the body that separates one from the other, so the client decides by which
request it made (android/core/data/.../DiaryModels.kt does exactly that).
502 is the only code that means we are the ones who have to fix something: the service is
undocumented, and when its answer stops being readable, this is how it shows.
| Method | Path | Role | What it does |
|---|---|---|---|
GET |
/api/v1/manage/terms |
admin | the class's periods; the first call creates the usual set |
PUT |
/api/v1/manage/terms/scheme |
admin | {"kind": "quarter"|"semester"} — recreates the year on another scheme |
PUT |
/api/v1/manage/terms/{index} |
admin | {"starts_on", "ends_on"} — moves one period's edges |
The default scheme follows the class's number: years 1–9 are taught in четверти (quarters), 10–11 in полугодия (half-years). The choice is stored separately from the number, so "nobody decided" and "quarters were chosen for year eleven" are different states, and a school is entitled to choose the second.
Changing the scheme recreates the year's periods rather than editing them: four quarters and two half-years do not lie on top of each other, and a leftover third quarter inside a year made of two halves is not a state worth keeping.
Editing the edges answers 422 with a Russian sentence in detail when a period ends before
it starts, runs outside the school year or overlaps its neighbour. A sentence rather than a
per-field error, because what is broken is the relation between this period and the year or
its neighbours, and «Пересекается с периодом 2 (01.11 — 31.12)» is what is worth putting on
the screen.
A period another write replaces between this one's read and its commit — a scheme change
recreates the year — is that same 422 with «Такого периода нет.», the answer for a period
the year does not have (#654); a scheme change in a class deleted meanwhile is the 404
Class no longer exists. Nothing is written either way.
| Method | Path | Role | What it does |
|---|---|---|---|
GET |
/api/v1/manage/schools?q=&page=&page_size=®ion= |
admin | searches the register for a school and returns one page |
{
"items": [
{
"name": "МБОУ \"Гимназия № 3\"",
"full_name": "МУНИЦИПАЛЬНОЕ БЮДЖЕТНОЕ ОБЩЕОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ \"ГИМНАЗИЯ № 3\"",
"ogrn": "1027800000001",
"inn": "7801234567",
"address": "190000, г Санкт-Петербург, ул Восстания, д 8",
"city": "Санкт-Петербург",
"region": "г Санкт-Петербург",
"active": true
}
],
"page": 1,
"pages": 4,
"total": 20,
"truncated": true
}What is found is not stored. The client takes name and sends it to
PATCH /api/v1/manage/class — the class card holds the school's name, as it always did,
rather than a link to somebody's record.
truncated does not mean "there are more pages" — pages counts those. It means "the
register's ceiling was hit": the source (DaData, a search over the ЕГРЮЛ company register) is
built for type-ahead suggestions, returns at most twenty rows at a time, and has no offset.
So what you have is the first twenty of an unknown number, and the only way to reach your
school is a longer query — adding the town or the number. A client that shows "20 found"
would lie about a search that matched three hundred schools.
Every call is one search upstream — two when the first finds nothing, because an empty
answer under the three school ОКВЭД codes is asked again without them and filtered to the
education group — whatever page says: the source has no offset and there is nothing to
resume. A client that pages should ask once with page_size=20 and cut
the answer itself — which is what both the bot and the app do. Four pages of five is four
searches for one question. page_size runs from 1 to 20, and the default is 5 (the size of
an inline keyboard).
region is a ranking hint, not a filter: a school across the road from the city boundary is
still that school.
The codes: 422 for a query shorter than three characters (with a Russian sentence in
detail); 503 when the registry is not configured (DADATA_TOKEN is empty), is not
answering, or answered incomprehensibly. The answer to a 503 is to let the name be typed
by hand rather than retrying the request: in the bot, that is exactly the button that
appears.
Admin, even though it writes nothing: every call spends part of a daily limit on somebody else's service, and only your own class is reason enough to spend it.
The one directory question a phone may ask before it belongs to any class, has a diary or holds any token: «which regions is a school of this name in», so that somebody who types «лицей 1535» is offered Москва rather than a list of eighty-nine regions. Anonymous. Nothing depends on it — picking the region from the list always works, and every failure here says «выберите регион из списка».
GET /api/v1/directory/school-regions?q=лицей 1535
{
"query": "лицей 1535",
"regions": [
{ "region": "moscow", "code": "77", "label": null, "schools": 2,
"cities": ["Москва"], "examples": ["ГБОУ \"Лицей № 1535\""] }
],
"truncated": false,
"generic": false
}It is the same search as /manage/schools — same upstream, same query rules, same twenty-row
ceiling — with the rows grouped by region instead of paged. A row is placed by the two-digit
subject code at the front of the register's region_kladr_id and, when that is missing or
unknown, by the register's own name for the region matched exactly against the region
catalog's spellings of it (diaries.md). region is then the
catalog's key, the one the phone's bundled copy of the same catalog knows, and a placed
region is named from the catalog in the reader's language. A row the catalog cannot place
comes back with region: null, the register's own code, and its own name in label; a
row naming no region at all is left out. Groups are ordered by their best-ranked hit, at most
ten; schools counts the hits in the region, cities and examples show up to three of
each. A branch registered under its head school's number but standing in another region is a
group of its own there, which the bot's picker — deduplicating on the number — never needed.
truncated means what it means on /manage/schools: the ceiling of twenty was reached, so
these are the regions of the first twenty matches. generic means the name is too common to
place. It is answered without asking the register when, once the words a school's name is
made of are taken away (the catalog's school_words, the list the phone reads too), nothing
is left but a number of one or two digits — «Школа № 5», «СОШ 12», «гимназия 3» are in every
region; «лицей 1535» and «гимназия 1 Казань» are asked. It is also set, on top of the
regions found, when a full answer of twenty spans four regions or more. Either way a client
should say so and show the list.
Anonymous means two limits. Every call past validation counts against its caller — twenty
in fifteen minutes, found or not, because a search that finds its school has spent the
same upstream request as one that does not — in a bucket of its own on the table /join
counts in, with the same fifteen-minute window, because every recorded attempt prunes that
whole table to its own window. And every request it sends upstream is spent from a daily
allowance: 4,000 of DaData's 10,000 requests a day, counted per Moscow day in
usage_counters by one atomic statement (services/quota.py), the empty-answer retry
included — and skipped, with an empty answer, when the second unit is not there. The bot's
search and /manage/schools are not charged to it and not capped by it, so no amount of
anonymous searching leaves an admin creating a class with «Лимит запросов исчерпан». Why the
day is Moscow's is in architecture.md.
In this order, and the order is the contract:
| Status | When | Counted against the caller |
|---|---|---|
429 + Retry-After |
the caller has spent its twenty | — |
422 |
q is shorter than three characters after whitespace is collapsed; detail is a Russian sentence |
no |
503 + X-Directory-Unavailable: disabled |
this deployment has no DADATA_TOKEN |
yes |
200 with generic: true |
a type word and a small number, answered without the register | yes |
503 + X-Directory-Unavailable: spent + Retry-After |
today's anonymous share is gone; Retry-After runs to Moscow midnight |
yes |
503 + X-Directory-Unavailable: upstream |
the register failed in any way — not answering, answering something new, or refusing the key or its own daily allowance | yes |
200 |
the regions found, possibly none | yes |
q is cut to 150 characters, and query in the answer is what was searched. The header says
which 503 it is for the reason the diary's does: the client picks its sentence without
reading the Russian. A client should ask on submit or after a pause in typing, never per
keystroke.
Not verified: whether DaData's party rows carry region_kladr_id at all — the name fallback
exists for the case where they do not; the subject codes 90, 93, 94 and 95 of the four
regions admitted in 2022, which the catalog marks as unverified; every one of the catalog's
DaData spellings; DaData's own day boundary; and two requests racing for the last unit on
Postgres, which has been checked on SQLite only. Nothing here has been asked of a live DaData.
Served beside v1, seventy-five methods: every unary one. Everything above this section
is v1, and v1 is unchanged. v2 is the contract in proto/lessons/v2/ at the root of the
repository, checked by Buf, with its Python generated into server/app/contract/.
Sub-project 3 of the programme serves it in three
stages (its design), the second in eight pull
requests. Served: GetScheduleWindow, GetMe, GetDiaryCapabilities and CreateDevice (3a);
ListAuditEntries, the three ClassDeviceService methods and the five SubjectService
methods (3b-1); the five BellService methods, the two TimetableService methods and the
eight ClassService methods (3b-2); the three AccessRequestService methods and the two
DirectoryService methods (3b-3); the other eleven MeService methods, a phone's own
(3b-4); the five HomeworkService methods and the five EventService methods (3b-5); the
two DayService methods and the five SubstitutionService methods (3b-6); ten
DiaryService methods, a diary session's two and its eight reads (3b-7); and its four
corrections (3b-8). A method a deployment does not serve answers UNIMPLEMENTED before it
asks for any credential; WatchClass, the one stream, answers as the next section says.
The Android transport boundary calls CreateDevice, GetScheduleWindow,
Me/link codes, management, directory and diary through its selected v2 binding.
Domain remotes keep wire DTOs and generated messages out of repositories;
server-status metadata remains a small plain-HTTP read. There is no runtime
v1 fallback. Previously installed APKs retain every v1 answer above.
A reasonless missing-v2 response is a server-compatibility refusal, whereas
JOIN_CODE_UNKNOWN is an unknown class/invite code. CLIENT_TOO_OLD preserves
cached data and asks for an APK update; only DEVICE_TOKEN_INVALID revokes the
sync's membership. Management uses that same structured invalid-device reason,
without matching English messages. Diary refusals clear only the address and
diary bearer actually sent, conditionally in storage; a newer account survives
an older request's refusal. These are Android classifications of the existing contract,
not changes to the server's minimum or v1 surface. The proto files are the
reference: every service, method, message and field there carries the comment that says
what it means and what v1 sent in its place. This section says only what a file cannot.
v2 is one package, lessons.v2: seventeen services in twenty files, one file per service
plus options.proto, errors.proto and common.proto. Each method is reachable three ways,
from one handler — server/app/rpc/call.py's invoke, which both transports call:
- REST, under
/api/v2/…. A method'sgoogle.api.httpannotation is its route. It is written/v2/…and served under/api, because this deployment is one function and every path that works on it is there. Standard methods use their verbs:GETreads,POSTcreates,PATCHupdates the fields anupdate_masknames,DELETEcarries no body. Anything else isPOST …:verb, as inPOST /api/v2/me:unlink. Path fields are written in the path, and every field the path and the body do not bind comes from the query string, whatever the verb. - Connect and gRPC-Web, as
POST /api/rpc/lessons.v2.<Service>/<Method>. EveryGetandListis markedNO_SIDE_EFFECTS, so Connect may send it as aGET. Nothing else is marked. - Native gRPC, on the same path and at the root,
/lessons.v2.<Service>/<Method>, where a gRPC client calls when it is given no prefix, on the host target only («The host target, and WatchClass», below): Vercel passes no response trailers, and gRPC carries its status in them.
One method, WatchService.WatchClass, is a server stream: a beta of the host target, with
no REST binding.
On Vercel, which speaks HTTP/1.1, a request with Content-Type: application/grpc or
application/grpc+… is refused with 415 and a sentence saying where native gRPC is served;
gRPC-Web passes. A native gRPC request that reaches the host over HTTP/1.1 — through a proxy
that does not speak HTTP/2 to it — is refused the same way. WatchClass answers
UNIMPLEMENTED with the reason FEATURE_UNSUPPORTED (feature: "streaming") on Vercel,
whatever it is told, and wherever LESSONS_STREAMING is not true. If a deployment cannot
load v2 at all,
/api/v2 and /api/rpc answer 503 in their own error shapes and v1 goes on
(/api/v1/warmup says which, with "v2": true or false).
On both transports, a request that does not decode is INVALID_ARGUMENT with the reason
REQUEST_UNDECODABLE and the fixed sentence «The request could not be decoded», never a
500 and never a sentence that quotes what was sent (#337, #338, #339). That covers a body
that claims Content-Encoding: gzip and is not gzip, a JSON string holding a lone surrogate,
and a header or a query string that is not UTF-8, which is read as Latin-1, as v1 reads it,
and judged where it is used.
On every transport, too, the answers no cache may keep say so: Cache-Control: private, no-store goes on the success of every diary answer (every DiaryService method, the
corrections' writes among them, since they answer with the rows they corrected), of the three
lists that name the class's members (ListClassDevices, ListAccessRequests and
ListAuditEntries, #652), of GetCalendarFeed and CreateCalendarFeed (their answer is a secret URL), of
GetClass and UpdateClass (their answer is the class card, whose join code admits a
phone), of CreateDevice and CreateDiarySession (their answer is a device token or a diary
token) and of CreateLinkCode (its answer links the phone to whoever sends it to the bot).
That is REST's answer, and Connect's whether the call came as a POST or as a GET, and
gRPC-Web's and native gRPC's as a response header. Both transports read one table,
server/app/rpc/caching.py's NEVER_STORED; until #357 only REST did, so a Connect GET of
GetClass could leave the join code in a private cache. No other answer carries a
Cache-Control of its own, and a refusal carries none.
The transports differ in what a body may be. Connect takes gzip (Content-Encoding: gzip) as
well as uncompressed bodies. REST takes uncompressed bodies only: one with any
Content-Encoding but identity is REQUEST_UNDECODABLE, and so is one whose Content-Type
is not application/json or +json (parameters such as ; charset=utf-8 are fine), because
a cross-site page can send a text, form or multipart body without a preflight and would
otherwise spend the visitor's address's join budget (#340, #341). A request without a body is
unaffected.
python -m app.host serves this whole API — v1, v2 over REST and Connect, the webhook and
the tick — and native gRPC, over HTTP/1.1 and HTTP/2 with prior knowledge on one port
(docs/deploy.md, «Option 3: the host target»). It is the same app, and nothing on this
page answers differently there but three things.
- Native gRPC. A refusal is the same
google.rpc.Statusthe other transports carry, ingrpc-status,grpc-messageandgrpc-status-details-bin. A method the contract does not have isUNIMPLEMENTED. WatchClassstreams, whereLESSONS_STREAMINGistrue. The first message is the class'srevisionnow. Another follows whenever the class changes — its card, a member's role, its bells, its timetable or subjects, a term, a day's mark, a substitution, an event or homework — whether the bot, v1 or v2 changed it, and the same one again at least every thirty seconds while nothing does. A revision the phone already holds means nothing changed; on any other it fetchesGetScheduleWindowas it does anyway, and a burst of changes is one message. A host that restarted never repeats a revision from before. A pupil's task, a tick, the diary, the journal and a phone's own row change no revision.changed_atis when the host last saw the class change, unset when it has seen none since it started. Before each message after the first, the stream asks the gate again: a phone revoked, or a class deleted, ends its stream withUNAUTHENTICATED/DEVICE_TOKEN_INVALIDat the next change, or within the thirty seconds. The host is one instance, because a stream hears what that one process writes; a script writing the database directly wakes nobody.- A phone holds one stream. A newer
WatchClassunder the same device token ends the one it held before, at once and cleanly, with no error, and leaves every other phone's stream alone: a stream that ends without an error has been replaced, and a client keeps one per phone rather than reopening it. A closed connection reaches the host at once, but the host only acts on it — ending that stream — at its next message, within the thirty seconds. One that drops off the network without closing it keeps its stream, and a gate every thirty seconds, until the host's kernel gives up on the connection — about a quarter of an hour on Linux's defaults, by calculation — or until the same token opens a new stream, which ends the old one.
- Statuses. A success is
200with the<Method>Responseas canonical JSON, except the eight methods whose proto comment says «REST answers 201», which answer201:CreateBellSchedule,CreateDevice,CreateDiarySession,CreateEvent,CreateHomework,CreateTask,CreateSubjectandCreateSubstitution. - Binding. Path variables bind into the request,
{task.id}included; the body is the whole request (body: "*"), one field, or nothing, as the method's rule says; and every field neither binds comes from the query string, whatever the verb — anUpdate…'supdate_maskis?updateMask=title,done. Dotted names reach nested fields and a repeated name a repeated field; aboolistrueorfalse. Unknown fields and parameters are ignored, as Connect ignores them. A body over 4 MB is refused as Connect refuses it. - Caching. A request with an
if_none_matchfield takes it fromIf-None-Match, which wins over a query parameter of that name; a list,*andW/match as/bundle's do. A response withnot_modifiedset is a304with itsETagand no body; any other response with anetagsends it asETag.GetScheduleWindow's tag is a strong SHA-256 of the window's canonical JSON withoutgeneratedAt, and its answer carries anETagand noCache-Control, as v1's/bundledoes. The answers that must not be stored carryCache-Control: private, no-storehere as over Connect («One contract, three ways to call it», above). - No CORS header, on any answer: v2 answers apps, not pages on other sites.
- A failure to write an answer is Google's
INTERNALbody like any other refusal, never plain text.
- A page is AIP-158's:
page_sizeandpage_tokenin,next_page_tokenout, empty on the last page.ListAuditEntriesreads 30 lines whenpage_sizeis unset, and reads a larger one than 100 as 100; a negative one isVALIDATION_FAILED. A page token is opaque: send back thenext_page_tokenyou were given, unchanged. It names the last line of its page, so a line written between two page turns moves nothing on the next page. A token this list did not hand out, another class's or an edited one, isVALIDATION_FAILEDonpage_token. ListSchoolspages one search. Every call is one search of the directory, whatever the page, because the directory has no offset: ask once withpage_size20 and cut the answer up yourself, as v1's/manage/schoolsadvises. It reads 5 schools whenpage_sizeis unset and a larger one than 20 as 20, where v1 refused it; a negative one isVALIDATION_FAILED. Its token names the first school of the next page, so apage_sizechanged between two calls still starts where the last page ended, and a token past what the search finds now (the directory may find fewer than it did a page ago) is an empty last page.- An
Update…takes anupdate_mask(AIP-134). A masked field the request leaves unset is cleared, as each method's comment says. A path the method does not take isVALIDATION_FAILEDonupdate_mask, and the refusal does not repeat it. Without a mask, or with an empty one, the fields the request sets change and no other, which is what v1'sPATCHdid. The fields apply in the method's own order, whatever the mask's:UpdateSubjectrenames before it sets anything else, because the rename is what can be refused, andUpdateBellSchedulerenames, then replaces the rows, then moves the default, so thatsilenced_lessonscounts once what the request stopped ringing.UpdateClassrefusesjoin_modemasked and leftJOIN_MODE_UNSPECIFIED, onschool_class.join_mode: a class is never opened or closed by a field nobody filled in. Send a mask: an update without one changes every field it carries, so a class card read and sent back whole names the class (its name is no longer recomposed from the grade and the letter), writes an audit line for every field it carries, and pins a timezone the class never stored to the one the card printed.UpdateTaskrefusestitleorprioritymasked and left unset, ontask.titleortask.priority, because neither can be cleared; and since an unsetboolreads as false, a task is taken back from done only under a mask that namesdone.UpdateHomeworktakesattachment_urlaway when it is masked and left unset, and refusesdue_date,subjectortextso;UpdateEventtakeslocationaway, putscovers_lessonback to what the kind means and makeskindan event, and refusesdate,starts_at,ends_atortitle. Akindthat changes while the update leavescovers_lessonalone carries it along when it was what the old kind means, so a trip nobody set apart, turned into a canteen break, stops replacing the lessons, as a break created so would; one somebody set apart from its kind keeps it (#423). An update of either that changes nothing writes nothing and tells nobody.UpdateDayclearsnoteandbell_schedule_idwhen they are masked and left unset — the schedule refused on a shortened day, which would ring the default — and refuseskindso;UpdateSubstitutionclearssubject,room,teacherandnote, and refusesaction. Each checks the resource as it would stand, so a field the mask leaves alone is held too: a substitution left with no subject, room or teacher is refused onsubstitution, and a self-study day changes from v2 only into a kind v2 writes. As for the homework and the events, an update that changes nothing writes nothing and tells nobody. - A preview.
ImportTimetablewithvalidate_onlywrites nothing, whateverreplacesays, and answers what the bot shows before «Применить»:appliedfalse, the weekdays, the lessons the paste holds, the bells, the conflicts, and the lines the parser could not read. A lesson with no bell to ring it is found only when the paste is applied. - A mask's paths in JSON (over REST, in the query or the body, and over Connect's JSON) are
lowerCamelCase:
shortName,isDefault. That is proto3's JSON mapping, and the server turns them into the proto names. A path writtenshort_namein JSON is refused asREQUEST_UNDECODABLE. Over Connect's binary encoding the paths are the proto names,short_name. ClassDevice.client_versionis theX-Lessons-Clientversion a phone last sent to v2, recorded besidelast_seen_atand on its fifteen-minute clock, and absent for a phone that never sent one. v1'sGET /manage/devicesdoes not carry it: v1's answers do not change, and a phone that speaks only v1 never sends the header.
ApproveAccessRequestandDeclineAccessRequesttell whoever asked, in Telegram and in v1's words, once the decision is committed. A refused decision tells nobody, and a notice Telegram will not deliver (the person blocked the bot, or Telegram is down) is logged and dropped: the decision stands.ApproveAccessRequest'sroleis the role the member holds afterwards, which for a member already above the role asked for is their own: an existing member is never lowered. Aroleno value ofRolenames isVALIDATION_FAILEDwhen it arrives, which is in the binary encoding: JSON is read with unknown fields ignored, on both transports, and proto3's parser then drops an unknown enum value, so the request reads as naming no role and grants the one asked for, which the ladder still decides.- The directory's refusals are reasons, where v1 sent
503withX-Directory-Unavailable:DIRECTORY_DISABLEDwithout aDADATA_TOKEN,DIRECTORY_SPENTwhen today's anonymous share is gone (withretry_after_secondsuntil the next Moscow day, and over REST a429withRetry-Afterwhere v1 sent503), andDIRECTORY_UNAVAILABLEwhen the directory fails.ListSchoolRegionsand v1's/directory/school-regionscount a caller once: twenty searches in fifteen minutes, whichever version asks.
- Minting is a write.
CreateLinkCodemints the code a phone shows to be linked, andCreateCalendarFeedthe class's feed secret;GetMeandGetCalendarFeedmint nothing, where v1'sGET /meandGET /calendarminted on a read. The code is the one v1's/meshows too, the same until the bot uses it, and a phone already linked gets none. - The calendar feed asks for a linked account, where v1 let any phone of the class, an
anonymous one included, mint it. Its address is v1's, on the deployment's
PUBLIC_BASE_URL, and the feed itself stays at/api/v1/calendar/{secret}.ics. A deployment with noPUBLIC_BASE_URLoffers no feed: both methods answerUNIMPLEMENTEDwithFEATURE_UNSUPPORTED(feature: "calendar_feed"), and nothing is minted. v1 falls back to the request's own host, which behind Vercel is an internal one. UnlinkMeon a phone that is not linked succeeds, writes nothing, and leaves the phone its link code.- Tasks and ticks are the linked account's. Somebody else's task is
RESOURCE_NOT_FOUND, as one that never existed is, so an id never reveals that a classmate keeps a list. A task'shomework_idnames homework of this class, or the request isVALIDATION_FAILEDontask.homework_id. Aremind_atsent with an offset is taken as v1 takes it, as an instant, and is stored and answered as the class's wall time. v1'sPOST /tasks/{id}/doneisUpdateTaskwithdone.CreateHomeworkTickandDeleteHomeworkTickset the tick rather than toggle it, so either asked twice lands on the same answer, and homework of another class isRESOURCE_NOT_FOUND.
- One assignment per subject per day, and no upsert.
CreateHomeworkrefuses a subject that already has homework that day, in the class's spelling of it, withRESOURCE_EXISTS(resource: "homework",field: "subject"), where v1'sPUT /homeworkreplaced the text;UpdateHomeworkchanges an assignment, and moving it onto a subject that has homework that day is refused the same way.CreateEventalways creates: events have no natural key, and two «Обед» on one day are two breaks. - A window of days.
ListHomeworkandListEventsreadstart_dateandend_dateas v1's/homeworkreadsfromandto: today and 21 days on when unset, 62 days at most. A window v1 refuses isVALIDATION_FAILEDon the field at fault, in v1's words, except that an end before its start is «end_date must not precede start_date»:start_datefor a start out of bounds, or one so near the bound that the end it implies is past it, andend_dateotherwise. A date a write names is held to the same bounds, in v1's words, on its field. - Who may. Any phone of the class reads the homework, with its owner's tick on each row
and none for a phone no account is behind; the events, the reads included, and every write
of both are an editor's, as the contract has them. A
kindno value ofEventKindnames isVALIDATION_FAILEDonevent.kindwhen it arrives, which is in the binary encoding; in JSON it reads as no kind, an event. - The class is told, in v1's words and never its author, once the write is committed and never when it is refused: homework to those who asked to hear about homework, events to those who asked to hear about changes. An event moved to another day is announced once, on its new day. A notice Telegram will not deliver is logged and dropped: the write stands. Deleting an assignment takes every tick on it with it, and a task made from it keeps itself without the link.
- Every date has a kind.
GetDayanswers a date nobody marked asDAY_KIND_NORMAL, neverNOT_FOUND, and a date the bot marked «самоподготовка» or «отгул» asDAY_KIND_SELF_STUDYorDAY_KIND_DAY_OFF.UpdateDaychanges a mark, and withallow_missingmakes one, which is an upsert by date; without it, a date nobody marked isRESOURCE_NOT_FOUNDwithresource: "day".DAY_KIND_NORMALtakes a mark off, and on a date with none, withallow_missing, writes nothing and tells nobody. v2 writes the kinds v1 wrote — normal, holiday, shortened and remote — and refuses the other two onday.kind: they are the bot's. - A shortened day rings a schedule of its own class that rings something. Another class's
schedule, or none on a shortened day, is
VALIDATION_FAILEDonday.bell_schedule_id, and a schedule with no rows isEMPTY_BELL_SCHEDULE, each in v1's words. - One substitution per lesson per day, and no upsert.
CreateSubstitutionrefuses a lesson that already has one that day withRESOURCE_EXISTS(resource: "substitution",field: "index"), where v1'sPUT /overrideschanged it;UpdateSubstitutionchanges one;DeleteSubstitutionputs the lesson back on the timetable, v1's"clear". - A substitution nobody would see is refused with its reason, in v1's words:
NO_LESSON_ON_DAYon a day that draws no lessons, withwhy—"out_of_year","between_terms","public_holiday"or"marked_day_off";NO_BELL_FOR_LESSONat a number the day rings no bell for, withindex, asked of a new substitution only, so that one at a number that no longer rings stays editable and deletable; andLESSON_NOT_ON_TIMETABLE, withindex, for cancelling a lesson the day's template does not have, or replacing one without a subject of its own. The bot asks the same three questions, through the same service. - Who may. Every method of both services is an editor's, the reads included, as the
contract has them.
ListSubstitutionsreads its window asListHomeworkdoes. - The class is told, those who asked to hear about changes and never the author, in v1's words, once the change is committed and never when it is refused.
- What a provider has is said before a password is typed.
GetDiaryCapabilitieslists, for every provider of the server's registry, the regions it signs in to, the ways in a phone may draw a form for (SIGN_IN_METHOD_PASSWORD, for both today) and the data the provider has: Petersburg the schedule, the homework, the marks, the periods, the subjects, the teachers and the turnstile; «Сетевой город» the first four, because its diary has none of the other three and is never asked them. With the diary off,enabledis false and no provider offers a way in or any data; the regions are v1's answer either way. - So is how this server reaches each diary (#406), in two fields v1 does not have.
egressis the deployment'sDIARY_EGRESSas it takes effect:DIARY_EGRESS_PROXYonly where a usableDIARY_PROXY_URLbacks it, andDIARY_EGRESS_DIRECTotherwise —DIARY_EGRESS_RELAYis a value of the enum and never an answer until the relay exists (#408), since arelaydeployment is read as direct.routesis each provider's, oneDiaryRouteper server it reaches: one with no region for Petersburg, which is one server, and one per listed region, inregions' order, for «Сетевой город». One field would not do, because underproxyfive password regions stay direct, and the phone would have to guess which. Both are said whether or not the diary is enabled, since a route is a fact about the deployment rather than about a session; no client reads them yet. - A session is kept as v1's
/sessionkeeps it.CreateDiarySessiontakes the session the phone opened with the diary itself, in the case ofcredentialthat names its provider, validated by v1's own schema, so the two versions refuse the same sessions; a violation is named as v2 spells the field (netschool.cookies.ns_session_id), never with what was sent. The diary reads with it once from this server's address, and the token it answers with is never cached, over either transport. A region this server does not serve isVALIDATION_FAILEDonregionbefore anything is counted or sent. An attempt is counted as v1 counts it, on one budget with v1 for the same caller:DIARY_CREDENTIALS_REJECTED(the diary would not take the session from here, which asking for the password again would not change),DIARY_NO_STUDENTSandDIARY_UPSTREAM_UNREADABLEcount;DIARY_UNAVAILABLE(upstream, oraddress-refusedwhen the region drops this server's address) andDIARY_DISABLEDdo not; past either limit it isTHROTTLED.DeleteDiarySessionis v1's/logout. Android maps that already-open-session refusal toServerRefusedSession, keeping the class-code recovery path. A password actually rejected by the upstream diary before handover remainsWrongPassword; these are different failures. - A read asks the session's own diary who the pupil is, every time. An id it does not
list is
RESOURCE_NOT_FOUNDwithresource: "student", on all seven reads of one pupil, so another family's child is nobody here. A read whoseDiaryFeaturethe session's provider does not declare isUNIMPLEMENTEDwithFEATURE_UNSUPPORTED(feature: "DIARY_FEATURE_SUBJECTS", say) before the diary is asked anything, where v1 answered «Сетевой город»'s subjects, teachers and turnstile with an empty list a client could not tell from an empty diary. - A window from the diary's own today.
ListScheduleDays,ListDiaryHomeworkandListMarksreadstart_dateandend_dateas v1 readfromandto: the diary's today and 14 days on when unset, 62 days at most. A window v2 refuses isVALIDATION_FAILEDon the field at fault, before the diary is asked anything, in the words every list of v2 uses.ListScheduleDayslists each day that has lessons once, in date order. - The family's corrections are laid over as v1 lays them: this child's, in this diary, over the lessons and the homework and never over a mark. No class is told: a correction is a family's own, never the class's.
- And written as v1 writes them, a batch at a time.
ListCorrectionsis v1'sGET /overrides, by target and then field, and carriesCache-Control: private, no-storeas every diaryGETdoes; none of the three writes below carries the header, a correction being no credential.BatchUpdateCorrectionswrites or replaces up to 200 at once, all or none, in one commit: the last writer wins,originalincluded, a target and field named twice in one request keep the later, and the answer is each correction asked for, in order, as stored — both entries of a repeated key alike, each with the value that won. Each is checked as v1 checks one, before anything is written and before the diary is asked anything: a target this server would never build, a field that cannot be corrected or an empty text isVALIDATION_FAILEDnaming the first one refused and its part,corrections[2].target(counted from 0), in v1's Russian; more than 200 isVALIDATION_FAILEDoncorrections. Avalueleft out is stored as an empty string, on a field the diary may leave blank, where v1 refuses a body with none at all.ResetCorrectionstakes the named corrections off, up to 200, all or none, and answers the same whether or not there was anything there; an empty reset succeeds once the pupil resolves, taking off nothing — even for a pupil who can have none. An empty batch succeeds the same way only for a pupil corrections can be filed under: one who can have none is refusedCORRECTIONS_UNAVAILABLEeven by a batch of none.ClearCorrectionstakes every one of this child's off, and none of another's. A pupil the diary lists outside its own numbering can have none: its list is empty, a reset or a clear takes nothing off, and a write isCORRECTIONS_UNAVAILABLE, in v1's words — a request wrong twice over, a bad correction alongside an unknown pupil or alongside one who can have none, isVALIDATION_FAILEDhere either way, where v1 answers404for the former and422«правки недоступны» for the latter. - When the diary ends a session, a read or a correction is
DIARY_REAUTH, and the session stays ended whatever the call does; a session the diary rotated is kept, even by a call that is refused. The same answer meets a session whose region no longer names a server this registry serves: expired rather than asked anything further. A session opened with a diary this deployment does not know, which a later release added, isDIARY_TOKEN_INVALID, left for the release that knows it, and never sent to another diary.
- JSON, on REST and on Connect alike, is canonical proto3 JSON: field names in
lowerCamelCase (
createdAt, where the proto and v1 writecreated_at), 64-bit integers as strings, and enums by name. v1's snake_case does not carry over. - A date is
"YYYY-MM-DD"and a time of day is"HH:MM": naive wall time in the class's zone, as in v1, except that v1 wrote times with seconds ("08:30:00") and v2 does not. A wall-clock moment, such as a task's reminder, is"YYYY-MM-DDTHH:MM". - What really is an instant (when something was written, done or last seen) is a
google.protobuf.Timestamp: an RFC 3339 string in UTC in JSON. v1 sent several of these as the class's wall time with no zone, such as a device'screated_atand an audit entry'sat. A client converts them with the class's zone. - An id this server assigns is a 32-bit number. An id a diary assigns is 64-bit, and proto3 JSON writes a 64-bit number as a string.
- An enum is its value's name:
"DAY_KIND_HOLIDAY", not v1's"holiday". Every enum starts at…_UNSPECIFIED, which is how a field says «none» where v1 saidnull. A client maps a value it does not know to a fallback it states, and that holds inside lists too: a client decodes enum names leniently, element by element, because a new value is an additive change on the server. A strict decoder (kotlinx'scoerceInputValuesdoes not reach list elements) would fail the whole read on the first newDiaryFeature. - Every method answers a
<Method>Response, even where it holds a single resource, so one method's answer can grow without touching another's.
Each method says so itself, in two options declared in options.proto:
(lessons.v2.auth) |
Credential | Who gets through |
|---|---|---|
AUTH_KIND_NONE |
none | anybody: CreateDevice, GetDiaryCapabilities, CreateDiarySession, ListSchoolRegions |
AUTH_KIND_DEVICE |
Authorization: Bearer with the device token |
any phone in the class, linked or not |
AUTH_KIND_DEVICE_LINKED |
the device token | a phone linked to an account; any other is refused with DEVICE_NOT_LINKED |
AUTH_KIND_DIARY |
Authorization: Bearer with the diary token |
a diary session |
The two tokens stay independent, as in v1 («Authentication», above). Which one a method takes is part of the method, not of its path.
(lessons.v2.min_role) is the least role a device method needs:
ROLE_VIEWERis any holder of the class's token, the class code's anonymous one included, and asks no role.ROLE_EDITOR,ROLE_ADMINandROLE_OWNERask the linked account's role in the class on every request, so a role taken away in the bot is gone here in the same instant.
Every method that acts on the class names one, reads included.
Every request may carry X-Lessons-Client: <versionCode>, and an APK's first v2 build sends it.
The server reads it after the request has decoded and the method is known to be served, and
before any credential. With MIN_CLIENT_VERSION set, a version below it is
FAILED_PRECONDITION with the reason CLIENT_TOO_OLD and min_version in its metadata, and a
header that is not a whole number from 1 to 2100000000, the most a versionCode can be, is
VALIDATION_FAILED; without a minimum a malformed header is ignored. A request without the
header is never refused. Then, in this order: a diary method on a deployment without
DIARY_SECRET is DIARY_DISABLED, before any token is read; the bearer; a linked account for
AUTH_KIND_DEVICE_LINKED and for any role above viewer (DEVICE_NOT_LINKED); the role
(ROLE_REQUIRED).
A refusal is a google.rpc.Status. It carries:
- a canonical code;
- the server's own sentence for a person;
- in its details, a
google.rpc.ErrorInfowithdomain"lessons.app", areason, andmetadata.
RPC sends it as the protocol's error. REST sends Google's JSON error body
({"error": {"code", "message", "status", "details"}}) under the standard status:
| Code | HTTP |
|---|---|
INVALID_ARGUMENT, FAILED_PRECONDITION |
400 |
UNAUTHENTICATED |
401 |
PERMISSION_DENIED |
403 |
NOT_FOUND |
404 |
ALREADY_EXISTS |
409 |
RESOURCE_EXHAUSTED |
429 |
INTERNAL |
500 |
UNIMPLEMENTED |
501 |
UNAVAILABLE |
503 |
The reasons are ErrorReason in errors.proto: thirty-three of them, each with its code,
its metadata and what v1 sent instead. A failure the server does not know is INTERNAL, with
a fixed sentence and no detail: what went wrong is logged, never sent, because an exception's
own text can carry what was typed.
A write whose row another write deletes between its read and its commit is
RESOURCE_NOT_FOUND for the resource the method names, in the words and with the resource
an id that names nothing gets (#384). Nothing is written. A day's mark is the one exception
to the words: UpdateDay, allow_missing or not, answers «this date has no mark» without
the advice to set allow_missing, and does not make the mark again. UpdateTermScheme and
UnlinkMe meet the class itself deleted, its terms and devices with it, and answer its
"class"; BatchUpdateCorrections meets a correction somebody reset or cleared and answers
"correction" with «this field has no correction», making none of the batch (#654). A term
has no RESOURCE_NOT_FOUND: UpdateTerm on a term a scheme change replaced is the
TERM_BOUNDS_REFUSED «Такого периода нет.» it answers for a term the year does not have.
ImportTimetable meets a class deleted under it as a foreign key, never as this race, and is
still INTERNAL (#654).
Over Connect the error is its JSON body, under the same status: {"code": "permission_denied", "message": …, "details": [{"type": "google.rpc.ErrorInfo", "value": <base64>, "debug": {…}}]}.
Decode value; debug is the server library's courtesy rendering of the same message.
A client acts on the reason, never on the message. The app's habit of matching
"device is not linked" (#270) ends here. A reason a client does not know, it handles by the
code. VALIDATION_FAILED names each wrong request field in a google.rpc.BadRequest. No
error repeats a request field back: a password or a diary session sent by mistake is never
in a refusal.
GET /now: it served a developer-console preset and nothing else.POST /diary/login: a password through this server, kept in v1 for APKs from before/diary/session. Every APK v2 serves opens its diary session itself./subjectswithout ids beside/manage/subjects: v2 has oneSubjectService, with ids, readable by a viewer.
The calendar feed itself (/api/v1/calendar/{token}.ics), the Telegram webhook, the cron
tick, /diary/signin/{code}, /api/v1/health and /api/v1/warmup stay plain HTTP at their
v1 paths.
The contract grows by addition only: a new field under a new number, a new method, a new enum value, a new reason. It never renames, renumbers or retypes in place (the programme, «Evolving the contract»).
- CI's «Contract» job holds the mechanical half, with Buf's
FILEbreaking rules. A field leaves only with its number and namereserved, which those rules let through (#298). server/tests/test_contract.pyholds each method's route, credential, role and idempotency against the resource map. Buf reads no options, so this is the only check on a method's route, credential and role, and an edit to the map is a breaking change (#299).server/tests/test_contract_json.pyholds what «What the values look like» says against the runtime that will serve it, andserver/tests/test_contract_mirror.pyholds every message that names its v1 schema level with that schema, field by field. A field added to v1 fails there until v2 has it or a row says why not.- build.md, «The v2 contract and Buf», has the commands.