feat(api): limits read unifiedWindows, unknown seven-day windows labelled by model
This commit is contained in:
@@ -737,21 +737,32 @@ def build_app( # noqa: PLR0915
|
||||
await require_token(request, runtime, scope=SCOPE)
|
||||
rows = await conversations.rate_limits(limit=200)
|
||||
latest: dict[str, RateLimit] = {}
|
||||
unified: dict[str, tuple[RateLimit, dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
latest.setdefault(row.window, row)
|
||||
for name, info in _unified_windows(row).items():
|
||||
unified.setdefault(name, (row, info))
|
||||
now = datetime.now(UTC)
|
||||
windows = []
|
||||
for window, row in latest.items():
|
||||
length = WINDOWS.get(window)
|
||||
since = (
|
||||
_aware(row.resets_at) - length
|
||||
if length is not None and row.resets_at is not None
|
||||
else _aware(row.ts)
|
||||
)
|
||||
for window in dict.fromkeys([*latest, *unified]):
|
||||
row = latest.get(window)
|
||||
seen = unified.get(window)
|
||||
public = _limit_public(row) if row else _limit_blank(window, seen)
|
||||
resets = row.resets_at if row else None
|
||||
if seen and _newer_figure(seen, row):
|
||||
carrier, info = seen
|
||||
public["utilization"] = info.get("utilization")
|
||||
public["reported_at"] = _iso(carrier.ts)
|
||||
resets = _unix_dt(info.get("resetsAt")) or resets
|
||||
public["resets_at"] = _iso(resets)
|
||||
length = _window_length(window)
|
||||
anchor = row if row is not None else (seen[0] if seen else None)
|
||||
if length is not None and resets is not None:
|
||||
since = _aware(resets) - length
|
||||
else:
|
||||
since = _aware(anchor.ts) if anchor else now
|
||||
gateway = _sum_usage(await _usage_rows(runtime, since, now))
|
||||
gateway["since"] = since.isoformat(timespec="seconds")
|
||||
# The API sends a figure only when a window nears its limit;
|
||||
# the last one inside this window is the best lower bound.
|
||||
known = next(
|
||||
(
|
||||
r
|
||||
@@ -764,13 +775,13 @@ def build_app( # noqa: PLR0915
|
||||
)
|
||||
windows.append(
|
||||
{
|
||||
**_limit_public(row),
|
||||
**public,
|
||||
"gateway": gateway,
|
||||
"last_known": _limit_public(known) if known else None,
|
||||
}
|
||||
)
|
||||
windows.sort(
|
||||
key=lambda w: (WINDOWS.get(w["window"], timedelta.max), w["window"])
|
||||
key=lambda w: (_window_length(w["window"]) or timedelta.max, w["window"])
|
||||
)
|
||||
return {"windows": windows, "history": [_limit_public(r) for r in rows[:50]]}
|
||||
|
||||
@@ -1052,6 +1063,59 @@ def _queue_item(item: InjectQueueItem | None) -> dict[str, Any] | None:
|
||||
}
|
||||
|
||||
|
||||
def _window_length(name: str) -> timedelta | None:
|
||||
if name.startswith("five_hour"):
|
||||
return timedelta(hours=5)
|
||||
if "seven_day" in name:
|
||||
return timedelta(days=7)
|
||||
return WINDOWS.get(name)
|
||||
|
||||
|
||||
def _unix_dt(value: Any) -> datetime | None:
|
||||
if isinstance(value, int | float) and value > 0:
|
||||
return datetime.fromtimestamp(value, tz=UTC)
|
||||
return None
|
||||
|
||||
|
||||
def _unified_windows(row: RateLimit) -> dict[str, dict[str, Any]]:
|
||||
"""Every window the event carried a figure for, not just the one it was about."""
|
||||
raw = row.raw if isinstance(row.raw, dict) else {}
|
||||
found = raw.get("unifiedWindows")
|
||||
if not isinstance(found, dict):
|
||||
return {}
|
||||
return {
|
||||
str(name): info
|
||||
for name, info in found.items()
|
||||
if isinstance(info, dict) and info.get("utilization") is not None
|
||||
}
|
||||
|
||||
|
||||
def _newer_figure(
|
||||
seen: tuple[RateLimit, dict[str, Any]], row: RateLimit | None
|
||||
) -> bool:
|
||||
if row is None or row.utilization is None:
|
||||
return True
|
||||
return seen[0].id != row.id and _aware(seen[0].ts) > _aware(row.ts)
|
||||
|
||||
|
||||
def _limit_blank(
|
||||
window: str, seen: tuple[RateLimit, dict[str, Any]] | None
|
||||
) -> dict[str, Any]:
|
||||
carrier = seen[0] if seen else None
|
||||
return {
|
||||
"id": None,
|
||||
"ts": _iso(carrier.ts) if carrier else None,
|
||||
"window": window,
|
||||
"status": "allowed",
|
||||
"utilization": None,
|
||||
"resets_at": None,
|
||||
"overage_status": None,
|
||||
"overage_resets_at": None,
|
||||
"agent": carrier.agent_name if carrier else None,
|
||||
"session_id": carrier.session_id if carrier else None,
|
||||
}
|
||||
|
||||
|
||||
def _limit_public(row: RateLimit) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id,
|
||||
|
||||
Reference in New Issue
Block a user