feat(vps): ship durable ARNavi host with reproducible install and recovery
This commit is contained in:
@@ -0,0 +1,286 @@
|
||||
"""Crash and response-loss qualification on isolated loopback sockets and SQLite.
|
||||
|
||||
Uses the installed ndc_vps package unchanged. One synthetic tracker at a time,
|
||||
no production database, TLS endpoint, firewall, physical device or service change.
|
||||
The internal HTTP loopback harness does not qualify production TLS transport.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ndc_vps import VERSION
|
||||
from ndc_vps.service import Service
|
||||
from ndc_vps.store import Store
|
||||
|
||||
IMEI = "123456789012345"
|
||||
TOKEN = "synthetic-owner-token-" + "a" * 32
|
||||
|
||||
|
||||
def initialize(root):
|
||||
(root / "host.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"host_id": "vps_" + "a" * 64,
|
||||
"tracker": {"host": "synthetic.example", "port": 9922},
|
||||
}
|
||||
)
|
||||
)
|
||||
store = Store(root)
|
||||
store.set_devices([{"imei": IMEI, "instance_id": "c" * 32}])
|
||||
with store.db() as db:
|
||||
db.execute(
|
||||
"INSERT INTO state VALUES('owner',?)",
|
||||
(
|
||||
json.dumps(
|
||||
{
|
||||
"core_id": "synthetic",
|
||||
"token": hashlib.sha256(TOKEN.encode()).hexdigest(),
|
||||
}
|
||||
),
|
||||
),
|
||||
)
|
||||
return store
|
||||
|
||||
|
||||
async def child(root):
|
||||
service = Service(Store(root))
|
||||
api = await asyncio.start_server(service.api, "127.0.0.1", 0)
|
||||
tracker = await asyncio.start_server(service.tracker, "127.0.0.1", 0)
|
||||
print(
|
||||
json.dumps(
|
||||
{"api": api.sockets[0].getsockname()[1], "tracker": tracker.sockets[0].getsockname()[1]}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
async with api, tracker:
|
||||
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, root):
|
||||
self.root, self.process, self.peer = root, None, None
|
||||
self.store = initialize(root)
|
||||
self.frames = []
|
||||
|
||||
async def start(self):
|
||||
self.process = await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
str(Path(__file__).resolve()),
|
||||
"--child",
|
||||
str(self.root),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
line = await asyncio.wait_for(self.process.stdout.readline(), 8)
|
||||
if not line:
|
||||
raise RuntimeError((await self.process.stderr.read()).decode())
|
||||
self.ports = json.loads(line)
|
||||
|
||||
async def stop(self):
|
||||
if self.peer:
|
||||
self.peer[1].transport.abort()
|
||||
self.peer = None
|
||||
if self.process and self.process.returncode is None:
|
||||
self.process.kill() # Deliberately no graceful drain or in-memory handoff.
|
||||
await asyncio.wait_for(self.process.wait(), 5)
|
||||
|
||||
async def restart(self):
|
||||
await self.stop()
|
||||
await self.start()
|
||||
|
||||
def body(self, **extra):
|
||||
return {
|
||||
"id": uuid.uuid4().hex,
|
||||
"imei": IMEI,
|
||||
"kind": "request-position",
|
||||
"model": 231,
|
||||
"firmware": "0.01",
|
||||
"not_after": time.time() + 15,
|
||||
**extra,
|
||||
}
|
||||
|
||||
async def http(self, method, path, body=None, *, loss=None):
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", self.ports["api"])
|
||||
data = json.dumps(body or {}).encode()
|
||||
header = (
|
||||
f"{method} {path} HTTP/1.1\r\nHost: localhost\r\n"
|
||||
f"Authorization: Bearer {TOKEN}\r\nContent-Length: {len(data)}\r\n\r\n"
|
||||
).encode()
|
||||
try:
|
||||
writer.write(header + (data[:-4] if loss == "before-body" else data))
|
||||
await writer.drain()
|
||||
if loss == "before-body":
|
||||
return None
|
||||
if loss == "after-commit":
|
||||
async with asyncio.timeout(3):
|
||||
while True:
|
||||
with self.store.db() as db:
|
||||
exists = db.execute(
|
||||
"SELECT 1 FROM commands WHERE id=?", (body["id"],)
|
||||
).fetchone()
|
||||
if exists:
|
||||
return None # The client intentionally never observes the HTTP result.
|
||||
await asyncio.sleep(0.02)
|
||||
raw = await asyncio.wait_for(reader.read(), 4)
|
||||
head, payload = raw.split(b"\r\n\r\n", 1)
|
||||
return int(head.split()[1]), json.loads(payload)
|
||||
finally:
|
||||
writer.transport.abort()
|
||||
|
||||
async def get(self, body):
|
||||
status, result = await self.http("GET", "/v1/commands/" + body["id"])
|
||||
assert status == 200, result
|
||||
return result
|
||||
|
||||
async def submit(self, body, **kwargs):
|
||||
value = await self.http("POST", "/v1/commands", body, **kwargs)
|
||||
if value is not None:
|
||||
assert value[0] == 200, value
|
||||
return value[1]
|
||||
|
||||
async def connect(self):
|
||||
if self.peer:
|
||||
self.peer[1].transport.abort()
|
||||
self.peer = await asyncio.open_connection("127.0.0.1", self.ports["tracker"])
|
||||
self.peer[1].write(b"\xff\x23" + int(IMEI).to_bytes(8, "little"))
|
||||
await self.peer[1].drain()
|
||||
assert len(await asyncio.wait_for(self.peer[0].readexactly(9), 2)) == 9
|
||||
|
||||
async def frame(self):
|
||||
first = await asyncio.wait_for(self.peer[0].readexactly(4), 3)
|
||||
raw = first + await asyncio.wait_for(self.peer[0].readexactly(first[1] + 1), 2)
|
||||
assert raw[0] == 0x7B and raw[-1] == 0x7D
|
||||
self.frames.append(raw)
|
||||
return raw
|
||||
|
||||
async def no_frame(self):
|
||||
try:
|
||||
data = await asyncio.wait_for(self.peer[0].read(1), 0.35)
|
||||
except TimeoutError:
|
||||
return
|
||||
raise AssertionError(f"Unexpected data or connection loss: {data.hex()}")
|
||||
|
||||
async def reply(self, frame):
|
||||
payload = struct.pack("<I", int(time.time())) + b"\0" + frame[5:9]
|
||||
raw = b"[\x01\x09\x05\0" + payload + bytes([sum(payload) % 256]) + b"]"
|
||||
self.peer[1].write(raw)
|
||||
await self.peer[1].drain()
|
||||
assert await asyncio.wait_for(self.peer[0].readexactly(4), 2) == b"{\0\x01}"
|
||||
|
||||
|
||||
async def qualify():
|
||||
result = {
|
||||
"session_id": uuid.uuid4().hex,
|
||||
"version": VERSION,
|
||||
"started_utc": datetime.now(UTC).isoformat(),
|
||||
"monotonic": time.monotonic(),
|
||||
"physical_devices_used": False,
|
||||
"production_state_used": False,
|
||||
"cases": [],
|
||||
}
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-vps-faults-") as name:
|
||||
harness = Harness(Path(name))
|
||||
await harness.start()
|
||||
try:
|
||||
# Lost upload before any accepted operation.
|
||||
body = harness.body()
|
||||
await harness.submit(body, loss="before-body")
|
||||
status, _ = await harness.http("GET", "/v1/commands/" + body["id"])
|
||||
assert status == 400
|
||||
await harness.submit(body)
|
||||
await harness.connect()
|
||||
await harness.reply(await harness.frame())
|
||||
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||
result["cases"].append({"name": "lost-request-retry-same-id", "passed": True})
|
||||
|
||||
# Lose HTTP result, then kill the process with a durable queued read.
|
||||
await harness.restart()
|
||||
body = harness.body()
|
||||
await harness.submit(body, loss="after-commit")
|
||||
await harness.restart()
|
||||
queued = await harness.submit(body)
|
||||
assert queued["state"] == "queued" and queued["expires_at"] == body["not_after"]
|
||||
await harness.connect()
|
||||
frame = await harness.frame()
|
||||
await harness.submit(body)
|
||||
await harness.no_frame()
|
||||
await harness.reply(frame)
|
||||
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||
result["cases"].append({"name": "lost-http-response-crash-queued-read", "passed": True})
|
||||
|
||||
# No tracker until after the original deadline, even across SIGKILL.
|
||||
await harness.restart()
|
||||
body = harness.body(not_after=time.time() + 0.8)
|
||||
await harness.submit(body)
|
||||
await harness.restart()
|
||||
await asyncio.sleep(max(0, body["not_after"] - time.time()) + 0.1)
|
||||
await harness.connect()
|
||||
await harness.no_frame()
|
||||
assert (await harness.submit(body))["state"] == "expired"
|
||||
result["cases"].append({"name": "offline-expiry-not-extended-by-crash", "passed": True})
|
||||
|
||||
# TCP accepted the bytes; no command ACK. The runtime must not say success.
|
||||
body = harness.body(not_after=time.time() + 0.8)
|
||||
await harness.submit(body)
|
||||
await harness.frame()
|
||||
await asyncio.sleep(max(0, body["not_after"] - time.time()) + 0.1)
|
||||
assert (await harness.get(body))["state"] == "unconfirmed"
|
||||
await harness.restart()
|
||||
await harness.connect()
|
||||
await harness.no_frame()
|
||||
assert (await harness.submit(body))["state"] == "unconfirmed"
|
||||
result["cases"].append({"name": "tcp-ack-without-command-reply", "passed": True})
|
||||
|
||||
# Effect bytes were received by the synthetic peer; crash before a reply.
|
||||
body = harness.body(kind="set-output", pin=4, enabled=True, password="123456")
|
||||
await harness.submit(body)
|
||||
frame = await harness.frame()
|
||||
assert frame[2] == 0xFC and b"*SERV*8.4.1" in frame
|
||||
await harness.restart()
|
||||
await harness.connect()
|
||||
assert (await harness.submit(body))["state"] == "uncertain"
|
||||
await harness.no_frame()
|
||||
result["cases"].append({"name": "dispatched-output-crash-no-replay", "passed": True})
|
||||
|
||||
# A fresh independent read still works on the same identity after recovery.
|
||||
body = harness.body()
|
||||
await harness.submit(body)
|
||||
await harness.reply(await harness.frame())
|
||||
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||
with harness.store.db() as db:
|
||||
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
|
||||
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 6
|
||||
assert (
|
||||
db.execute("SELECT instance FROM devices WHERE imei=?", (IMEI,)).fetchone()[0]
|
||||
== "c" * 32
|
||||
)
|
||||
result["cases"].append(
|
||||
{"name": "identity-and-history-survive-recovery", "passed": True}
|
||||
)
|
||||
assert len(harness.frames) == 5
|
||||
result["received_command_frames"] = len(harness.frames)
|
||||
finally:
|
||||
await harness.stop()
|
||||
result.update(
|
||||
completed_utc=datetime.now(UTC).isoformat(),
|
||||
elapsed_seconds=time.monotonic() - result["monotonic"],
|
||||
ok=True,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--child":
|
||||
asyncio.run(child(Path(sys.argv[2])))
|
||||
else:
|
||||
print(json.dumps(asyncio.run(qualify()), indent=2))
|
||||
Reference in New Issue
Block a user