Coverage for app / util / time.py: 91%
22 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
1from datetime import datetime, timezone
2from typing import Annotated
4from pydantic import PlainSerializer
6from app.common.state import state
9def aware_utcnow():
10 return datetime.now(timezone.utc)
13def aware_utcfromtimestamp(timestamp):
14 return datetime.fromtimestamp(timestamp, timezone.utc)
17def naive_utcnow():
18 return aware_utcnow().replace(tzinfo=None)
21def naive_utcfromtimestamp(timestamp):
22 return aware_utcfromtimestamp(timestamp).replace(tzinfo=None)
25def uptime() -> int:
26 return (aware_utcnow() - state.START_TIME).total_seconds()
29# ─── Timestamps on the wire ───────────────────────────────────────────────────
30#
31# Columns are `timestamp without time zone` holding UTC, so a datetime read
32# from the database is naive. Serialised as-is it has no zone
33# ("2026-09-24T10:00:00"), which every client — a browser's `new Date`, any
34# API consumer — is free to read as its own local time. Everything this
35# service sends therefore marks naive datetimes as UTC on the way out:
36#
37# * pydantic fields — annotate `UTCDateTime`, not `datetime`
38# * ORM rows / dicts — `install_utc_json_encoding()` at startup
39# * hand-built strings — `utc_isoformat(dt)`, not `dt.isoformat()`
40#
41# Only the wire changes: columns, stored JSON and in-process comparisons keep
42# the naive-UTC convention. See docs/system/data/timestamps.md.
45def as_utc(value: datetime) -> datetime:
46 """``value`` with its zone made explicit — a naive value is UTC here."""
47 return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
50def utc_isoformat(value: datetime) -> str:
51 """ISO 8601 with an explicit offset: ``2026-09-24T10:00:00+00:00``."""
52 return as_utc(value).isoformat()
55#: A datetime that serialises to JSON with its UTC offset. Only the JSON form
56#: changes (``when_used="json"``): ``model_dump()`` still hands Python code
57#: the datetime it had, so nothing comparing values in-process is affected.
58UTCDateTime = Annotated[
59 datetime, PlainSerializer(utc_isoformat, return_type=str, when_used="json")
60]
63def install_utc_json_encoding() -> None:
64 """Make FastAPI's ``jsonable_encoder`` write datetimes with an offset.
66 Covers every route that returns ORM rows or plain dicts rather than a
67 pydantic model — the encoder looks the type up at call time, so replacing
68 the entry once, at startup, is enough.
69 """
70 from fastapi import encoders
72 encoders.ENCODERS_BY_TYPE[datetime] = utc_isoformat