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>
82 lines
2.8 KiB
Python
82 lines
2.8 KiB
Python
"""POST /api/v1/commands/{command_id}/ack -- the other half of the queue.
|
|
|
|
/heartbeat and /ingest hand commands out and mark them delivered. This is
|
|
where the device reports what became of one. The two halves are deliberately
|
|
separate: delivery is recorded when the command goes out, because the ack may
|
|
never arrive -- ``reboot`` and ``sleep_now`` are acked and then the device is
|
|
gone, and a device that dies mid-command never acks at all. ``delivered_at``
|
|
therefore means "we handed it over" and ``acked_at`` means "it ran", and the
|
|
gap between them is the interesting operational signal.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from datetime import UTC, datetime
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
|
from sqlalchemy import select
|
|
|
|
from ...models.devices import DeviceCommand
|
|
from .. import ratelimit
|
|
from ..deps import DbDep, DeviceDep
|
|
from ..schemas import CommandAck
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post(
|
|
"/commands/{command_id}/ack",
|
|
status_code=status.HTTP_204_NO_CONTENT,
|
|
response_class=Response,
|
|
summary="Report the outcome of a command",
|
|
tags=["devices"],
|
|
dependencies=[Depends(ratelimit.by_device("ack", ratelimit.ACK))],
|
|
)
|
|
def ack_command(
|
|
command_id: int,
|
|
body: CommandAck,
|
|
db: DbDep,
|
|
device: DeviceDep,
|
|
) -> Response:
|
|
command = db.scalar(
|
|
select(DeviceCommand).where(
|
|
DeviceCommand.id == command_id,
|
|
# Scoped to the calling device. Command ids are sequential, so
|
|
# without this a device could ack -- and probe for -- every other
|
|
# device's queue.
|
|
DeviceCommand.device_id == device.id,
|
|
)
|
|
)
|
|
|
|
# 404 rather than 403 for someone else's command: a different code here
|
|
# would confirm that the id exists, which is the thing worth not saying.
|
|
if command is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such command")
|
|
|
|
# Re-acking is allowed and the last word wins. The device retries on a
|
|
# timeout, and it cannot tell a lost response from a lost request, so
|
|
# refusing the second attempt would strand a command that did in fact run.
|
|
command.acked_at = datetime.now(UTC)
|
|
command.ack_status = body.status
|
|
# The firmware always sends the key, empty when it has nothing to say.
|
|
command.result = body.detail or None
|
|
|
|
db.commit()
|
|
|
|
log.info(
|
|
"command acked",
|
|
extra={
|
|
"device_id": device.id,
|
|
"command_id": command.id,
|
|
"type": command.type,
|
|
"ack_status": command.ack_status,
|
|
},
|
|
)
|
|
|
|
# Liveness stays with /heartbeat on purpose, so the device list has one
|
|
# source of truth for "when did we last hear from it".
|
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|