mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 14:25:08 +00:00
The sports plugins cache whole season schedules: 53MB for MLB, 18MB for NHL, 17MB for NCAA baseball. On a Pi 4, orjson.loads of the MLB file takes ~1.8s with the GIL held, and every thread in the display service waits -- the stall watchdog caught the render thread frozen 0.5-1.3s with the interpreter itself blocked, right on these reads. When a season record expired, DiskCache.get paid that whole parse only to find the timestamp too old and throw the result away. CacheManager.set now writes timestamp and ttl ahead of the data, and DiskCache.get reads them from the first 256 bytes of the file, applying the same rule as before (a per-entry ttl wins over max_age; no limit means never stale). A record that is stale is refused without being parsed. Files in the old layout, and records from other writers, don't match the header and are parsed in full as before. Also: ESPN responses in the background data service and espn_dates are parsed with orjson when it is installed (src/common/json_body.py). The stdlib parser behind response.json() takes 3.1s on the MLB season against orjson's 1.8s, both with the GIL held. espn_dates imports it with a fallback, since plugins bundle copies of that module for older cores. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
30 lines
1.0 KiB
Python
30 lines
1.0 KiB
Python
"""Parse an HTTP response body as JSON, with orjson when it is installed.
|
|
|
|
``requests``' ``response.json()`` uses the stdlib parser. For the payloads the
|
|
sports plugins fetch -- a season schedule is tens of MB -- that runs ~1.7x
|
|
slower than orjson on a Pi 4 (3.1s against 1.8s for the 53MB MLB season), and
|
|
both hold the GIL for the whole parse, which freezes the display for as long.
|
|
Nothing else changes: the result is the same Python objects.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
try:
|
|
import orjson
|
|
except ImportError: # optional dependency; see docs/SCROLL_PERFORMANCE.md
|
|
orjson = None
|
|
|
|
|
|
def response_json(response: Any) -> Any:
|
|
"""``response.json()``, parsed by orjson when available."""
|
|
body = getattr(response, "content", None)
|
|
if orjson is None or not isinstance(body, (bytes, bytearray)):
|
|
return response.json()
|
|
try:
|
|
return orjson.loads(body)
|
|
except orjson.JSONDecodeError:
|
|
# Let requests raise its usual error, with its usual message.
|
|
return response.json()
|