diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py index 5996cdf..10418e4 100644 --- a/server/src/poorbird/api/app.py +++ b/server/src/poorbird/api/app.py @@ -8,7 +8,7 @@ from fastapi import FastAPI from .. import __version__ from ..config import get_settings from ..logging_setup import configure_logging -from .routes import conditions, device_config, enroll, health +from .routes import commands, conditions, device_config, enroll, health log = logging.getLogger(__name__) @@ -48,8 +48,9 @@ def create_app() -> FastAPI: app.include_router(enroll.router, prefix=API_PREFIX) app.include_router(conditions.router, prefix=API_PREFIX) app.include_router(device_config.router, prefix=API_PREFIX) + app.include_router(commands.router, prefix=API_PREFIX) - # Still to come: /ingest, /commands/{id}/ack, /firmware/{version}.bin. + # Still to come: /ingest, /firmware/{version}.bin. # Phase 3 mounts the UI endpoints. return app diff --git a/server/src/poorbird/api/routes/commands.py b/server/src/poorbird/api/routes/commands.py new file mode 100644 index 0000000..b268446 --- /dev/null +++ b/server/src/poorbird/api/routes/commands.py @@ -0,0 +1,79 @@ +"""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, HTTPException, Response, status +from sqlalchemy import select + +from ...models.devices import DeviceCommand +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"], +) +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) diff --git a/server/tests/test_commands_ack.py b/server/tests/test_commands_ack.py new file mode 100644 index 0000000..a41558a --- /dev/null +++ b/server/tests/test_commands_ack.py @@ -0,0 +1,224 @@ +"""POST /api/v1/commands/{id}/ack, and the full command lifecycle with it.""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +def _make_device(db, name="cam"): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + return d, {"Authorization": f"Bearer {token}"} + + +def _cleanup(db, *devices): + for d in devices: + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + db.delete(db.get(Device, d.id)) + db.commit() + + +@pytest.fixture +def device(db): + d, auth = _make_device(db) + yield d, auth + _cleanup(db, d) + + +@pytest.fixture +def queued(db, device): + d, auth = device + cmd = DeviceCommand(device_id=d.id, type="capture_now") + db.add(cmd) + db.commit() + db.refresh(cmd) + return d, auth, cmd + + +CONDITIONS = {"reason": "heartbeat"} + + +# --- the lifecycle ---------------------------------------------------------- + + +@needs_db +def test_delivered_then_acked(client, queued, db): + """The whole round trip: queued -> delivered by heartbeat -> acked.""" + d, auth, cmd = queued + + assert cmd.delivered_at is None and cmd.acked_at is None + + envelope = client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth).json() + assert [c["id"] for c in envelope["commands"]] == [cmd.id] + + db.refresh(cmd) + assert cmd.delivered_at is not None + assert cmd.acked_at is None # delivered is not the same as done + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", + json={"status": "done", "detail": "captured 3 frames"}, + headers=auth, + ) + assert r.status_code == 204 + assert r.content == b"" + + db.refresh(cmd) + assert cmd.acked_at is not None + assert cmd.ack_status == "done" + assert cmd.result == "captured 3 frames" + + +@needs_db +@pytest.mark.parametrize("outcome", ["done", "failed", "rejected"]) +def test_every_documented_outcome_is_accepted(client, queued, db, outcome): + d, auth, cmd = queued + r = client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": outcome}, headers=auth) + assert r.status_code == 204 + + db.refresh(cmd) + assert cmd.ack_status == outcome + + +@needs_db +def test_an_unknown_outcome_is_422(client, queued): + d, auth, cmd = queued + r = client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "maybe"}, headers=auth) + assert r.status_code == 422 + + +@needs_db +def test_an_empty_detail_is_stored_as_null(client, queued, db): + """The firmware always sends the key, empty when it has nothing to say.""" + d, auth, cmd = queued + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done", "detail": ""}, headers=auth + ) + + db.refresh(cmd) + assert cmd.result is None + + +@needs_db +def test_a_command_can_be_acked_without_having_been_delivered(client, queued, db): + """Odd but harmless, and refusing it would strand a real ack if delivery + bookkeeping ever went wrong.""" + d, auth, cmd = queued + assert cmd.delivered_at is None + + assert ( + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth + ).status_code + == 204 + ) + + +# --- retries ---------------------------------------------------------------- + + +@needs_db +def test_re_acking_is_allowed_and_the_last_word_wins(client, queued, db): + """The device cannot tell a lost response from a lost request, so it + retries. Refusing the second attempt would strand a command that ran.""" + d, auth, cmd = queued + + client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "failed"}, headers=auth) + db.refresh(cmd) + first = cmd.acked_at + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", + json={"status": "done", "detail": "worked on retry"}, + headers=auth, + ) + assert r.status_code == 204 + + db.refresh(cmd) + assert cmd.ack_status == "done" + assert cmd.result == "worked on retry" + assert cmd.acked_at >= first + + +@needs_db +def test_acking_does_not_put_the_command_back_in_the_queue(client, queued, db): + d, auth, cmd = queued + client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth) + client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth) + + again = client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth).json() + assert again["commands"] == [] + + +# --- scoping ---------------------------------------------------------------- + + +@needs_db +def test_another_devices_command_is_404_not_403(client, queued, db): + """Command ids are sequential. A distinct status code would confirm that + an id exists, which is the thing worth not saying.""" + d, auth, cmd = queued + intruder, intruder_auth = _make_device(db, name="intruder") + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=intruder_auth + ) + assert r.status_code == 404 + + db.refresh(cmd) + assert cmd.acked_at is None, "an intruder must not be able to close a command" + + _cleanup(db, intruder) + + +@needs_db +def test_an_unknown_command_id_is_404(client, device): + _, auth = device + assert ( + client.post( + "/api/v1/commands/999999999/ack", json={"status": "done"}, headers=auth + ).status_code + == 404 + ) + + +@needs_db +def test_ack_requires_a_bearer_token(client, queued): + d, auth, cmd = queued + assert client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}).status_code == 401 + + +@needs_db +def test_a_disabled_device_cannot_ack(client, queued, db): + d, auth, cmd = queued + d.enabled = False + db.commit() + assert ( + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth + ).status_code + == 403 + )