Add POST /commands/{id}/ack, closing the command lifecycle (Phase 2)

/heartbeat hands commands out and marks them delivered; this is where the
device reports what became of one. The two halves stay separate 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
means "handed over", acked_at means "it ran", and the gap between them is
the operational signal worth having.

Three decisions:

- Scoped to the calling device, and a command belonging to someone else is
  404 rather than 403. Command ids are sequential, so a distinct status code
  would confirm that an id exists - and without the scope filter a device
  could close every other device's queue. Pinned by a test that also asserts
  the intruder did not manage to set acked_at.
- Re-acking is allowed and the last word wins. The device cannot tell a lost
  response from a lost request, so it retries; refusing the second attempt
  would strand a command that actually ran.
- An empty detail is stored as NULL. The firmware always sends the key,
  empty when it has nothing to say.

Liveness deliberately stays with /heartbeat, so the device list keeps one
source of truth for when a device was last heard from.

Tests: 109 -> 122, including the full queued -> delivered -> acked round
trip. Verified by removing the device scope from the lookup: the intruder
test fails, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Thomas KarnerandClaude Opus 5 committed 2026-09-21 12:57:18 +02:00
1 parent e83fc757d0
commit 46f54dbe81
3 files changed
+306 -2

No files matched your search

+3 -2
View File
@@ -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
@@ -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)