Coverage for app / util / time.py: 86%

22 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1from datetime import datetime, timezone 

2from typing import Annotated 

3 

4from pydantic import PlainSerializer 

5 

6from app.common.state import state 

7 

8 

9def aware_utcnow(): 

10 return datetime.now(timezone.utc) 

11 

12 

13def aware_utcfromtimestamp(timestamp): 

14 return datetime.fromtimestamp(timestamp, timezone.utc) 

15 

16 

17def naive_utcnow(): 

18 return aware_utcnow().replace(tzinfo=None) 

19 

20 

21def naive_utcfromtimestamp(timestamp): 

22 return aware_utcfromtimestamp(timestamp).replace(tzinfo=None) 

23 

24 

25def uptime() -> int: 

26 return (aware_utcnow() - state.START_TIME).total_seconds() 

27 

28 

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 (svc-core has the same helpers). 

43 

44 

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) 

48 

49 

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() 

53 

54 

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] 

61 

62 

63def install_utc_json_encoding() -> None: 

64 """Make FastAPI's ``jsonable_encoder`` write datetimes with an offset. 

65 

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 

71 

72 encoders.ENCODERS_BY_TYPE[datetime] = utc_isoformat