In-process token buckets, no Redis and no slowapi - for the same reason the job queue has no Redis (SPEC C8). This is one uvicorn process serving a handful of cameras on a LAN, and slowapi's default storage is in-process anyway, so a dependency would buy convenience rather than capability. That assumption is named in the module: poorbird serve runs a single process, and if the deployment ever gains workers each gets its own buckets and the effective limit multiplies. Move the state to PostgreSQL at that point rather than widening the numbers. Buckets rather than fixed windows, because a camera uploads three to five frames back to back when the radar fires and then goes quiet. A window would reject the tail of a legitimate burst that straddled a boundary. Authenticated endpoints key on the device, so one wedged camera cannot spend another's allowance. /enroll keys on the caller address, since there is no device yet and it is the one place a shared secret could be ground at. This required a Caddyfile change, not a cosmetic one: the :8080 camera block proxied without X-Real-IP, so every camera reached the app as 127.0.0.1 and they would all have shared one enrollment bucket - one noisy device locking the rest out. The header is trusted only because uvicorn binds loopback. Limits are deliberately loose, each derived from what the firmware actually does and noted in the code so the number can be re-derived rather than guessed at. A throttled camera stops delivering photographs, which on a private LAN is worse than the flooding the limit prevents. Throttling answers 429, never 401: the firmware clears its token on a 401, and being busy is not a credential problem. Retry-After gives it something better than a guess. The key table is LRU-bounded. It is keyed partly on caller address, and an unbounded map keyed by something a caller influences is itself a way to exhaust memory. Off by default in tests, which fire far more requests than any camera would. tests/test_ratelimit.py turns it back on and proves the buckets are wired to the routes. Also fixes the same teardown-in-test-body flaw in the new file, found by re-running a deliberate mutation and noticing a leaked device row. Teardown is in fixtures; the mutation now fails its one test and leaves nothing behind. Tests: 158 -> 175. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
73 lines
2.8 KiB
Python
73 lines
2.8 KiB
Python
"""GET /api/v1/config -- the device's settings document.
|
|
|
|
Named device_config.py so it does not read as poorbird.config, which is the
|
|
server's own settings. The route is /config, as API.md specifies.
|
|
|
|
The response is a free-form JSON object by design. ``devices.config`` is one
|
|
JSONB document rather than forty columns because the firmware grows tunables
|
|
faster than a schema should change, and the device merges and clamps whatever
|
|
arrives: keys it does not know are ignored, keys that are absent leave its
|
|
current value alone, and dangerous values are clamped on the device itself
|
|
(app_config.cpp, configApplyJson). Partial documents are therefore not a
|
|
degraded case -- they are the normal one.
|
|
|
|
That is also why there is no response model. Validating this shape belongs on
|
|
the write path, when the admin UI saves a config, not on the way out to a
|
|
device that is going to re-validate it anyway.
|
|
|
|
This is a read. It deliberately does not touch last_seen_at: a GET should not
|
|
have side effects, and /heartbeat is what records liveness (API.md).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Depends
|
|
|
|
from .. import ratelimit
|
|
from ..deps import DeviceDep
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
router = APIRouter()
|
|
|
|
# Settings that live in real columns on `devices` rather than in the JSONB,
|
|
# because the server queries and lists on them. They are still config keys as
|
|
# far as the firmware is concerned, so they have to be merged into the
|
|
# document on the way out or a change to the column would never reach the
|
|
# camera.
|
|
#
|
|
# device_name is the interesting one: enrollment deliberately does not let a
|
|
# device overwrite an operator's rename, and this is the path by which that
|
|
# rename actually reaches the device (app_config.cpp:307).
|
|
_COLUMN_BACKED = (
|
|
("device_name", "name"),
|
|
("heartbeat_interval_s", "heartbeat_interval_s"),
|
|
("status_interval_s", "status_interval_s"),
|
|
)
|
|
|
|
|
|
@router.get(
|
|
"/config",
|
|
summary="The device's full settings document",
|
|
tags=["devices"],
|
|
dependencies=[Depends(ratelimit.by_device("config", ratelimit.CONFIG))],
|
|
)
|
|
def get_config(device: DeviceDep) -> dict[str, Any]:
|
|
# Start from the stored document, then let the column-backed keys win.
|
|
# The columns are the modelled source of truth; a stale copy of one of
|
|
# them inside the JSONB must not shadow it.
|
|
document: dict[str, Any] = dict(device.config or {})
|
|
|
|
for key, attr in _COLUMN_BACKED:
|
|
document[key] = getattr(device, attr)
|
|
|
|
# Last, mirroring configApplyJson, which applies config_version only after
|
|
# the rest of the payload has been processed. This is the only value the
|
|
# device compares, so it must describe the document it arrived with.
|
|
document["config_version"] = device.config_version
|
|
|
|
return document
|