Coverage for app / services / rules / periods.py: 99%
90 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Quota periods — the stretch of time a rate limit or cost cap counts over.
4``rolling`` is the trailing window quotas always had (``window_seconds``):
5the last hour, the last day, always moving. The calendar periods are what a
6budget is: this day, this week from Monday, this calendar month — each
7starting again from nothing at its boundary, which is what "$500 a month"
8means to the person who wrote it.
10UTC throughout, like svc-ai's spending ceiling (``spend_guard.periods``): one
11boundary for every member of an organisation, wherever they are.
13One class per period, registered here and served in the rule catalogue
14(``quota_periods``), so the builder's picker, the generators' vocabulary and
15the check on a saved rule all read the same list.
16"""
18from __future__ import annotations
20from abc import ABC, abstractmethod
21from datetime import datetime, timedelta
22from typing import Any, ClassVar
24#: The period a quota counts over when it names none — the trailing window,
25#: so every rule written before periods existed counts as it always did.
26DEFAULT = "rolling"
29def _midnight(now: datetime) -> datetime:
30 return now.replace(hour=0, minute=0, second=0, microsecond=0)
33class Period(ABC):
34 """A stretch of time a quota counts over."""
36 #: Stable key stored on the action block.
37 key: ClassVar[str]
38 label: ClassVar[str]
39 description: ClassVar[str] = ""
40 #: True for a period that starts again at a boundary (a budget); False
41 #: for the trailing window, which never resets — it moves.
42 calendar: ClassVar[bool] = True
43 #: An allowance's period as a rule's summary says it ("$100 a month").
44 per_label: ClassVar[str] = ""
46 def per(self, window_seconds: int) -> str:
47 """The period as a summary says it: "a month", or a trailing
48 window's own length ("per 24 hours")."""
49 return self.per_label
51 @abstractmethod
52 def start(self, now: datetime, window_seconds: int) -> datetime:
53 """When the period counting at ``now`` began."""
55 def resets_at(self, now: datetime) -> datetime | None:
56 """When the period counting at ``now`` starts again; None for a
57 trailing window, which frees up gradually instead."""
58 return None
60 def previous_start(self, now: datetime, window_seconds: int) -> datetime | None:
61 """When the period before the one counting at ``now`` began — the
62 one a budget's page sets this one beside. None for a trailing
63 window, which has no previous period, only an earlier stretch."""
64 if not self.calendar:
65 return None
66 return self.start(
67 self.start(now, window_seconds) - timedelta(microseconds=1),
68 window_seconds,
69 )
71 def spec(self) -> dict[str, Any]:
72 return {
73 "key": self.key,
74 "label": self.label,
75 "description": self.description,
76 "calendar": self.calendar,
77 }
80_REGISTRY: dict[str, Period] = {}
83def register_period(cls: type[Period]) -> type[Period]:
84 instance = cls()
85 if instance.key in _REGISTRY:
86 raise RuntimeError(f"Quota period '{instance.key}' is already registered.")
87 _REGISTRY[instance.key] = instance
88 return cls
91@register_period
92class RollingPeriod(Period):
93 key = "rolling"
94 label = "Trailing window"
95 description = (
96 "The last stretch of the window's length, always moving: an hour's "
97 "limit frees up as each call made an hour ago drops out of it."
98 )
99 calendar = False
101 def start(self, now: datetime, window_seconds: int) -> datetime:
102 return now - timedelta(seconds=max(1, int(window_seconds)))
104 def per(self, window_seconds: int) -> str:
105 return f"per {duration(window_seconds)}"
108@register_period
109class DayPeriod(Period):
110 key = "day"
111 label = "Each day (UTC)"
112 description = "From midnight UTC, starting again at the next midnight."
113 per_label = "a day"
115 def start(self, now: datetime, window_seconds: int) -> datetime:
116 return _midnight(now)
118 def resets_at(self, now: datetime) -> datetime | None:
119 return _midnight(now) + timedelta(days=1)
122@register_period
123class WeekPeriod(Period):
124 key = "week"
125 label = "Each week (UTC, from Monday)"
126 description = "From Monday at midnight UTC, starting again the next Monday."
127 per_label = "a week"
129 def start(self, now: datetime, window_seconds: int) -> datetime:
130 return _midnight(now) - timedelta(days=now.weekday())
132 def resets_at(self, now: datetime) -> datetime | None:
133 return self.start(now, 0) + timedelta(weeks=1)
136@register_period
137class MonthPeriod(Period):
138 key = "month"
139 label = "Each calendar month (UTC)"
140 description = (
141 "From the 1st at midnight UTC, starting again on the 1st of the next "
142 "month — a monthly budget."
143 )
144 per_label = "a month"
146 def start(self, now: datetime, window_seconds: int) -> datetime:
147 return _midnight(now).replace(day=1)
149 def resets_at(self, now: datetime) -> datetime | None:
150 first = self.start(now, 0)
151 if first.month == 12:
152 return first.replace(year=first.year + 1, month=1)
153 return first.replace(month=first.month + 1)
156def duration(seconds: int) -> str:
157 """A whole stretch of time in its largest unit: "hour", "24 hours",
158 "7 days" — singular without a count, as "per hour" reads."""
159 seconds = max(1, int(seconds))
160 for unit, size in (("day", 86_400), ("hour", 3_600), ("minute", 60)):
161 if seconds % size == 0:
162 count = seconds // size
163 if unit == "day" and count == 1:
164 return "24 hours"
165 return unit if count == 1 else f"{count} {unit}s"
166 return f"{seconds} seconds"
169def get_period(key: Any) -> Period | None:
170 """The period registered as ``key``, or None."""
171 return _REGISTRY.get(str(key)) if key else None
174def keys() -> tuple[str, ...]:
175 """Every registered period, in registration order."""
176 return tuple(_REGISTRY)
179def catalogue() -> list[dict[str, Any]]:
180 """What the rule builder and the generators are offered."""
181 return [period.spec() for period in _REGISTRY.values()]