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:
1 parent
e83fc757d0
commit
46f54dbe81
3 files changed
+306
-2
No files matched your search
@@ -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
|
||||
)
|
||||
Reference in new issue
Block a user