#5207 "UniFi Overview tab: func.strftime is SQLite-only": the WAN and client sparklines bucketed with strftime('%s'), which Postgres lacks, so /plugins/unifi/rows failed. Traefik's date_bin bucket moves to core/time_range.time_bucket and both plugins use it. Devices list offline and failing first, and a state other than online is named (Upgrading, Adopting, Heartbeat missed...) instead of drawn as Down. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
57 lines
2.0 KiB
Python
57 lines
2.0 KiB
Python
# steward/core/time_range.py
|
|
"""Shared time-range utilities for scoping queries and sparkline data."""
|
|
from __future__ import annotations
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import TypeVar
|
|
|
|
from sqlalchemy import func
|
|
|
|
RANGES: dict[str, timedelta] = {
|
|
"1h": timedelta(hours=1),
|
|
"6h": timedelta(hours=6),
|
|
"24h": timedelta(hours=24),
|
|
"7d": timedelta(days=7),
|
|
"30d": timedelta(days=30),
|
|
}
|
|
|
|
RANGE_OPTIONS: list[str] = list(RANGES.keys())
|
|
DEFAULT_RANGE = "24h"
|
|
|
|
|
|
def parse_range(range_str: str | None) -> tuple[datetime, str]:
|
|
"""Return (since_datetime, range_key) from a query-param string like '24h'."""
|
|
key = range_str if range_str in RANGES else DEFAULT_RANGE
|
|
since = datetime.now(timezone.utc) - RANGES[key]
|
|
return since, key
|
|
|
|
|
|
def bucket_seconds(since: datetime, target_points: int = 80) -> int:
|
|
"""Return bucket width in seconds so that (now - since) / width ≈ target_points.
|
|
|
|
Minimum is 60s (one poll interval) so raw data is never re-averaged below
|
|
the collection resolution.
|
|
"""
|
|
range_secs = (datetime.now(timezone.utc) - since).total_seconds()
|
|
return max(60, int(range_secs / target_points))
|
|
|
|
|
|
def time_bucket(column, seconds: int):
|
|
"""The start of the `seconds`-wide window a timestamp falls in, aligned to
|
|
the epoch, as a Postgres timestamp labelled "bucket". Group and order by
|
|
it. (An integer epoch divided by an int rendered as numeric division in
|
|
Postgres, so no two scrapes shared a bucket, and overflowed int4 after
|
|
2038 (#5256); strftime('%s') is SQLite-only (#5207).)"""
|
|
return func.date_bin(func.make_interval(0, 0, 0, 0, 0, 0, int(seconds)), column,
|
|
func.to_timestamp(0)).label("bucket")
|
|
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
def subsample(seq: list[T], n: int = 80) -> list[T]:
|
|
"""Return at most n evenly-distributed elements from seq (preserves order)."""
|
|
if len(seq) <= n:
|
|
return seq
|
|
indices = sorted({int(round(i * (len(seq) - 1) / (n - 1))) for i in range(n)})
|
|
return [seq[i] for i in indices]
|