"""Cadences: the five wordings a schedule may be written in, and nothing else. A schedule is a row that says "enqueue this kind with this payload on this cadence". This module is only the *cadence* half: the grammar, the canonical spelling, and when the next run falls. The row is in `table.py`, the firing is in `queue.py`, and the buttons are in `web/schedules.py`. Five wordings, deliberately, rather than cron: every 15m · every 6h · every 2d · daily at 06:00 · weekly mon 07:00 Cron is five fields of positional punctuation that nobody reads back correctly, and the schedules a small app actually wants are these. A wording outside them raises `ValueError` listing what is accepted, which is the sentence the API hands a person who typed something else. Long weekday names are taken as well as short ones, because `weekly monday 07:00` is what people write; `__str__` gives back the short form, so a row stores one spelling however it was typed. **The interval forms are intervals and the clock forms are clock times.** `every 6h` is six hours later, measured in real elapsed time, so it neither skips nor doubles across a daylight-saving change. `daily at 06:00` is 06:00 on the wall clock of the queue's timezone, on both sides of one — which is the whole reason `next_after` takes a zone rather than doing UTC arithmetic. The two mean different things and a person picking one has already chosen which. Defaults are declared next to `@job`, in the app's own jobs module: from pipeline.schedule import declare declare("nightly tick", "tick", "daily at 06:00", label="A tick, nightly") `declare` fills `SCHEDULES` the way `@job` fills `JOBS`, and `JobQueue.start()` inserts a row for any declared name that has none. It parses the cadence there and then, so a typo is an ImportError at startup rather than a schedule that quietly never fires. """ from __future__ import annotations import re from dataclasses import dataclass, field from datetime import UTC, datetime, time, timedelta, tzinfo from typing import Any, Literal #: Short weekday names, Monday first, which is also `datetime.weekday()`'s #: numbering. The short form is canonical: it is what `__str__` writes and so #: what the table stores, however the row was typed. DAYS: tuple[str, ...] = ("mon", "tue", "wed", "thu", "fri", "sat", "sun") #: The long names, accepted on input for the same index. Spelled out rather #: than derived from `calendar.day_name`, which is locale-dependent — a cadence #: that parses on one machine and not on another is the bug this avoids. LONG_DAYS: tuple[str, ...] = ("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") #: What each interval unit is worth. Seconds are deliberately absent: a queue #: that looks for due schedules every thirty seconds cannot honour "every 10s", #: and a cadence the scheduler cannot keep is worse than one it refuses. UNITS: dict[str, int] = {"m": 60, "h": 3600, "d": 86400} #: What a person is told when the wording is not one of the five. One sentence, #: because it goes out as `{"detail": ...}` and ends up in a toast. FORMS = ("every 15m", "every 6h", "every 2d", "daily at 06:00", "weekly mon 07:00") _EVERY = re.compile(r"^every (\d+) ?([mhd])$") _DAILY = re.compile(r"^daily at (\d{1,2}):(\d{2})$") _WEEKLY = re.compile(r"^weekly ([a-z]+) (\d{1,2}):(\d{2})$") class BadCadence(ValueError): """A wording that is not one of the five. A `ValueError`, so a caller that only knows it is parsing something still catches it.""" def _refuse(text: str, because: str = "is not a cadence") -> BadCadence: """The one refusal, with the forms always in it. Always, even when the wording was nearly right and this could have said only what was wrong with it: the person reading this is typing into a box and what they need is what to type, not a diagnosis. The specific complaint goes in front of the list rather than instead of it. """ return BadCadence( f"{text!r} {because}. Write one of: " + ", ".join(repr(f) for f in FORMS) + " — long weekday names are fine too." ) @dataclass(frozen=True, slots=True) class Cadence: """One of the five wordings, parsed. Immutable, and its own spelling. Built through `parse`; the fields are what the wording said and are left public so a test can assert on them. `str(cadence)` is the canonical form and is what goes in the table, so two spellings of the same thing — `weekly monday 07:00` and `weekly mon 07:00` — are one row and compare equal. """ kind: Literal["every", "daily", "weekly"] #: `every`: how many of `unit`. Unused by the clock forms. n: int = 0 unit: str = "" #: `daily` and `weekly`: the wall-clock time, in the queue's zone. hour: int = 0 minute: int = 0 #: `weekly`: 0 is Monday, matching `datetime.weekday()`. -1 otherwise. day: int = -1 def __str__(self) -> str: if self.kind == "every": return f"every {self.n}{self.unit}" if self.kind == "daily": return f"daily at {self.hour:02d}:{self.minute:02d}" return f"weekly {DAYS[self.day]} {self.hour:02d}:{self.minute:02d}" @property def seconds(self) -> int: """The interval, for the `every` forms. Zero for the clock ones, which have no fixed length — a day is 23 or 25 hours twice a year.""" return self.n * UNITS[self.unit] if self.kind == "every" else 0 @classmethod def parse(cls, text: str) -> Cadence: """One of the five wordings, or `BadCadence` naming all five. Case and inner spacing are forgiven — `Every 15 M` is `every 15m` — because they are typing, not meaning. Everything else is refused: a cadence that is nearly right is the one that has to fail loudly, since the alternative is a row that looks scheduled and never fires. """ said = " ".join(str(text or "").lower().split()) found = _EVERY.match(said) if found: n = int(found.group(1)) if n < 1: raise _refuse(text) return cls(kind="every", n=n, unit=found.group(2)) found = _DAILY.match(said) if found: hour, minute = int(found.group(1)), int(found.group(2)) _check_clock(text, hour, minute) return cls(kind="daily", hour=hour, minute=minute) found = _WEEKLY.match(said) if found: name = found.group(1) day = (DAYS.index(name) if name in DAYS else LONG_DAYS.index(name) if name in LONG_DAYS else -1) if day < 0: raise _refuse(text) hour, minute = int(found.group(2)), int(found.group(3)) _check_clock(text, hour, minute) return cls(kind="weekly", hour=hour, minute=minute, day=day) raise _refuse(text) def next_after(self, moment: datetime, zone: tzinfo = UTC) -> datetime: """When this next falls, strictly after `moment`. Always UTC-aware. Strictly after, so a schedule fired at exactly its own time does not find itself due again on the same instant. `every` is elapsed time and ignores the zone: six hours is six hours, so a run neither vanishes nor doubles when the clocks move. The two clock forms are the opposite and want the zone for exactly that reason — 06:00 is 06:00 on both sides of a change, which means the interval across one is 23 or 25 hours, and that is the thing the wording promised. Walking forward a day at a time rather than doing arithmetic on the date: it is at most eight steps, it handles "later today" and "this weekday next week" with one piece of code, and each candidate is built from a wall-clock time and then converted, which is what keeps the promise above. """ moment = moment if moment.tzinfo else moment.replace(tzinfo=UTC) if self.kind == "every": # Converted to UTC *before* the addition, not after. Adding a # timedelta to an aware datetime is wall-clock arithmetic within # its own zone — `06:30 + 24h` on the day the clocks go forward is # 06:30 the next day, which is 23 real hours. That is exactly the # promise the interval forms do not make, and the whole reason # somebody writes `daily` when they want the other one. return moment.astimezone(UTC) + timedelta(seconds=self.seconds) local = moment.astimezone(zone) for step in range(9): # today, then a full week of weekdays day = local.date() + timedelta(days=step) if self.kind == "weekly" and day.weekday() != self.day: continue when = datetime.combine(day, time(self.hour, self.minute), tzinfo=zone) if when > local: return when.astimezone(UTC) # Unreachable: a daily cadence lands within two steps and a weekly one # within eight. Raised rather than returned-as-None so that if the # calendar ever surprises us it says so here. raise BadCadence(f"{self} never comes round after {moment.isoformat()}") def _check_clock(text: str, hour: int, minute: int) -> None: if not (0 <= hour <= 23 and 0 <= minute <= 59): raise _refuse(text, "is not a time of day — hours run 00-23 and " "minutes 00-59") # ------------------------------------------------------------ declared defaults @dataclass(frozen=True, slots=True) class Declared: """A schedule an app ships with, before any row exists for it. `name` is the handle and is the whole of the reconciliation: a declared name with no row gets one, a declared name that already has one is left exactly as the user edited it. Which means the defaults here are a *starting point*, not a setting — turning one off in the UI survives the next restart, and that is the point of the row being the truth. """ name: str kind: str cadence: str payload: dict[str, Any] = field(default_factory=dict) label: str = "" #: name -> declaration. Filled by `declare` when the app's jobs module is #: imported, exactly as `JOBS` is filled by `@job`, and read once per #: `JobQueue.start()`. Empty in a project that declares none, which is fine: #: every schedule can be added from the UI instead. SCHEDULES: dict[str, Declared] = {} def declare(name: str, kind: str, cadence: str, payload: dict[str, Any] | None = None, label: str = "") -> Declared: """Ship a default schedule. Goes next to `@job`, in the app's jobs module. declare("nightly tick", "tick", "daily at 06:00") declare("hourly count", "count", "every 1h", {"n": 5}) The cadence is parsed here, so a typo is an error the moment the module is imported — at startup, with a traceback pointing at this line — rather than a schedule that sits in the table looking fine and never fires. The kind is *not* checked, because it usually cannot be: `declare` and `@job` are read top to bottom in one file and a declaration above its handler would be refused for a job that exists a dozen lines later. An unregistered kind is caught where it matters instead — `JobQueue` never fires one and `` says `unknown kind` against the row. Declaring the same name twice with different terms is refused, like two handlers on one `@job` name: the second would silently win, and which module imported first is not a thing anybody should have to know. """ Cadence.parse(cadence) declared = Declared(name=name, kind=kind, cadence=str(Cadence.parse(cadence)), payload=dict(payload or {}), label=label) if name in SCHEDULES and SCHEDULES[name] != declared: raise ValueError( f"two different schedules are both declared as {name!r}: " f"{SCHEDULES[name].kind} {SCHEDULES[name].cadence!r} and " f"{declared.kind} {declared.cadence!r}" ) SCHEDULES[name] = declared return declared __all__ = ["DAYS", "FORMS", "LONG_DAYS", "SCHEDULES", "UNITS", "BadCadence", "Cadence", "Declared", "declare"]