feat(vps): ship durable ARNavi host with reproducible install and recovery
This commit is contained in:
@@ -0,0 +1,402 @@
|
||||
"""Bounded asyncio TCP receiver and pinned-TLS API; no shell/device control API."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sqlite3
|
||||
import ssl
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import suppress
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from . import arnavi
|
||||
from .commands import COMMAND_SESSION_MAX_IDLE, Commands
|
||||
from .delivery import Delivery
|
||||
from .observation import Observation, http_body
|
||||
from .operations import Operations
|
||||
|
||||
|
||||
class Service:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
self.connections = 0
|
||||
self.commands = Commands(store)
|
||||
self.operations = Operations(store, self.commands)
|
||||
self.observation = Observation(store)
|
||||
self.wake = {}
|
||||
|
||||
async def tracker(self, reader, writer):
|
||||
self.connections += 1
|
||||
session = uuid.uuid4().hex
|
||||
sender = None
|
||||
delivery = None
|
||||
imei = None
|
||||
try:
|
||||
if self.connections > 256:
|
||||
return
|
||||
async with asyncio.timeout(10):
|
||||
header = await reader.readexactly(10)
|
||||
if header[:2] != b"\xff\x23":
|
||||
if (
|
||||
not await self.observe_configuration(reader, header, writer)
|
||||
and header == b"POST /c/in"
|
||||
):
|
||||
delivery = Delivery(writer)
|
||||
await self.configuration_http(reader, writer, header, delivery)
|
||||
return
|
||||
imei = arnavi.identity(header)
|
||||
if not await asyncio.to_thread(self.store.admitted, imei):
|
||||
return
|
||||
delivery = Delivery(writer)
|
||||
self.commands.sessions.setdefault(imei, set()).add(session)
|
||||
self.commands.session_started[imei, session] = time.monotonic()
|
||||
self.commands.session_activity[imei, session] = time.monotonic()
|
||||
self.commands.session_peers[imei, session] = writer.get_extra_info("peername")[0]
|
||||
self.commands.session_ready[imei, session] = False
|
||||
delivery.write(arnavi.header_ack(int(time.time())))
|
||||
await writer.drain()
|
||||
sender = asyncio.create_task(self.send_commands(imei, writer, session, delivery))
|
||||
buffer = b""
|
||||
while True:
|
||||
async with asyncio.timeout(180):
|
||||
chunk = await reader.read(min(4096, arnavi.MAX_PACKAGE - len(buffer)))
|
||||
if not chunk:
|
||||
return
|
||||
buffer += chunk
|
||||
while buffer:
|
||||
parsed = arnavi.parse_package(buffer)
|
||||
if parsed is None:
|
||||
break
|
||||
length, packets = parsed
|
||||
self.commands.session_activity[imei, session] = time.monotonic()
|
||||
await asyncio.to_thread(
|
||||
self.accept_package, imei, buffer[:length], packets, session
|
||||
)
|
||||
self.notify(imei)
|
||||
delivery.write(arnavi.package_ack(buffer[1]))
|
||||
await writer.drain()
|
||||
buffer = buffer[length:]
|
||||
except (
|
||||
ValueError,
|
||||
KeyError,
|
||||
OSError,
|
||||
sqlite3.Error,
|
||||
TimeoutError,
|
||||
asyncio.IncompleteReadError,
|
||||
asyncio.LimitOverrunError,
|
||||
):
|
||||
pass # Deliberately no raw identity/data/credentials in logs.
|
||||
finally:
|
||||
if imei:
|
||||
self.commands.sessions.get(imei, set()).discard(session)
|
||||
self.commands.session_started.pop((imei, session), None)
|
||||
self.commands.session_activity.pop((imei, session), None)
|
||||
self.commands.session_peers.pop((imei, session), None)
|
||||
self.commands.session_ready.pop((imei, session), None)
|
||||
if not self.commands.sessions.get(imei):
|
||||
self.commands.sessions.pop(imei, None)
|
||||
if sender:
|
||||
sender.cancel()
|
||||
await asyncio.gather(sender, return_exceptions=True)
|
||||
self.connections -= 1
|
||||
if delivery:
|
||||
delivery.abort()
|
||||
else:
|
||||
writer.close()
|
||||
|
||||
def accept_package(self, imei, raw, packets, session):
|
||||
# Core may fetch/ack packages concurrently. Publish the packet and its
|
||||
# command evidence together before either Core or B2 can consume it.
|
||||
with self.store.packet_transaction():
|
||||
self.store.append(imei, raw, packets)
|
||||
self.commands.receive(imei, raw, session)
|
||||
self.operations.observe(imei, raw)
|
||||
|
||||
async def observe_configuration(self, reader, header, writer=None):
|
||||
ticket = await asyncio.to_thread(self.observation.claim)
|
||||
if ticket is None:
|
||||
return False
|
||||
raw = bytearray(header)
|
||||
events = [
|
||||
{"offset": 0, "bytes": len(header), "at": time.time(), "monotonic": time.monotonic()}
|
||||
]
|
||||
try:
|
||||
async with asyncio.timeout(8):
|
||||
while len(raw) < 16384:
|
||||
chunk = await reader.read(min(4096, 16384 - len(raw)))
|
||||
if not chunk:
|
||||
break
|
||||
events.append(
|
||||
{
|
||||
"offset": len(raw),
|
||||
"bytes": len(chunk),
|
||||
"at": time.time(),
|
||||
"monotonic": time.monotonic(),
|
||||
}
|
||||
)
|
||||
raw.extend(chunk)
|
||||
if writer is not None:
|
||||
reply = await asyncio.to_thread(self.observation.reply, ticket, bytes(raw))
|
||||
if reply is not None:
|
||||
writer.write(
|
||||
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
|
||||
+ f"Content-Length: {len(reply)}\r\n".encode()
|
||||
+ b"Connection: keep-alive\r\n\r\n"
|
||||
+ reply
|
||||
)
|
||||
await writer.drain()
|
||||
except (TimeoutError, OSError):
|
||||
pass
|
||||
finally:
|
||||
await asyncio.to_thread(self.observation.finish, ticket, bytes(raw), events)
|
||||
return True
|
||||
|
||||
async def configuration_http(self, reader, writer, initial, delivery):
|
||||
if initial != b"POST /c/in":
|
||||
return
|
||||
peer = writer.get_extra_info("peername")[0]
|
||||
for _ in range(8):
|
||||
async with asyncio.timeout(12):
|
||||
header = initial + await reader.readuntil(b"\r\n\r\n")
|
||||
initial = b""
|
||||
if len(header) > 2048:
|
||||
return
|
||||
lengths = [
|
||||
line.split(b":", 1)[1].strip()
|
||||
for line in header.split(b"\r\n")
|
||||
if line.lower().startswith(b"content-length:")
|
||||
]
|
||||
if len(lengths) != 1 or not lengths[0].isdigit():
|
||||
return
|
||||
size = int(lengths[0])
|
||||
if not 20 <= size <= 16384:
|
||||
return
|
||||
body = http_body(header + await reader.readexactly(size))
|
||||
if body is None:
|
||||
return
|
||||
response = await asyncio.to_thread(
|
||||
self.commands.web_receive, body, peer, with_deadline=True
|
||||
)
|
||||
self.notify(str(int.from_bytes(body[4:12], "little")))
|
||||
if response is None:
|
||||
return
|
||||
reply, deadline = response
|
||||
delivery.write(
|
||||
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
|
||||
+ f"Content-Length: {len(reply)}\r\n".encode()
|
||||
+ b"Connection: keep-alive\r\n\r\n"
|
||||
+ reply,
|
||||
deadline,
|
||||
)
|
||||
await writer.drain()
|
||||
|
||||
async def send_commands(self, imei, writer, session, delivery):
|
||||
event = asyncio.Event()
|
||||
observations = []
|
||||
|
||||
def observe(ticket, phase, at, elapsed, reason):
|
||||
# The socket timer never opens SQLite or waits for filesystem I/O.
|
||||
observations.append((ticket, phase, at, elapsed, reason))
|
||||
event.set()
|
||||
|
||||
async def persist():
|
||||
if observations:
|
||||
batch = observations[:]
|
||||
observations.clear()
|
||||
commit = asyncio.create_task(
|
||||
asyncio.to_thread(self.commands.transport.record, batch)
|
||||
)
|
||||
try:
|
||||
await asyncio.shield(commit)
|
||||
except asyncio.CancelledError:
|
||||
# EOF cancels this sender. Finish the extracted batch before
|
||||
# the finally block records closure of its remaining bytes.
|
||||
await commit
|
||||
raise
|
||||
|
||||
self.wake.setdefault(imei, set()).add(event)
|
||||
try:
|
||||
while not writer.is_closing():
|
||||
event.clear()
|
||||
await persist()
|
||||
last_input = self.commands.session_activity.get((imei, session))
|
||||
self.commands.session_ready[imei, session] = (
|
||||
delivery.ready()
|
||||
and last_input is not None
|
||||
and 0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE
|
||||
)
|
||||
await asyncio.to_thread(self.operations.advance, imei)
|
||||
dispatch = await asyncio.to_thread(
|
||||
self.commands.take_delivery, imei, session, with_receipt=True
|
||||
)
|
||||
if dispatch:
|
||||
data, deadline, ticket = dispatch
|
||||
delivery.write(
|
||||
data,
|
||||
deadline,
|
||||
lambda phase, at, elapsed, reason, ticket=ticket: observe(
|
||||
ticket, phase, at, elapsed, reason
|
||||
),
|
||||
)
|
||||
await writer.drain()
|
||||
await persist()
|
||||
delay = await asyncio.to_thread(self.commands.wait_delay, imei)
|
||||
operation_delay = await asyncio.to_thread(self.operations.wait_delay, imei)
|
||||
delay = (
|
||||
min(d for d in (delay, operation_delay) if d is not None)
|
||||
if (delay is not None or operation_delay is not None)
|
||||
else None
|
||||
)
|
||||
with suppress(TimeoutError):
|
||||
await asyncio.wait_for(event.wait(), delay)
|
||||
finally:
|
||||
self.wake.get(imei, set()).discard(event)
|
||||
if not self.wake.get(imei):
|
||||
self.wake.pop(imei, None)
|
||||
delivery.abort()
|
||||
await persist()
|
||||
|
||||
def notify(self, imei):
|
||||
for event in self.wake.get(imei, ()):
|
||||
event.set()
|
||||
|
||||
async def api(self, reader, writer):
|
||||
status, value = 400, {"error": "invalid_request"}
|
||||
try:
|
||||
async with asyncio.timeout(15):
|
||||
header = await reader.readuntil(b"\r\n\r\n")
|
||||
if len(header) > 8192:
|
||||
raise ValueError
|
||||
lines = header.decode("ascii").split("\r\n")
|
||||
method, target, _ = lines[0].split(" ")
|
||||
headers = dict(line.lower().split(": ", 1) for line in lines[1:] if line)
|
||||
size = int(headers.get("content-length", "0"))
|
||||
if not 0 <= size <= 1024 * 1024 or "transfer-encoding" in headers:
|
||||
raise ValueError
|
||||
payload = await reader.readexactly(size) if size else b"{}"
|
||||
body = json.loads(payload)
|
||||
route = urlsplit(target)
|
||||
token = headers.get("authorization", "").removeprefix("bearer ")
|
||||
# Header values must retain case for bearer credentials.
|
||||
for line in lines[1:]:
|
||||
if line.lower().startswith("authorization: bearer "):
|
||||
token = line[len("authorization: bearer ") :]
|
||||
if method == "GET" and route.path == "/health":
|
||||
value = {"ok": True, "service": "ndc-mission-vps-host"}
|
||||
elif method == "POST" and route.path == "/v1/pair":
|
||||
value = await asyncio.to_thread(self.store.pair, body)
|
||||
else:
|
||||
if not await asyncio.to_thread(self.store.authorize, token):
|
||||
raise PermissionError
|
||||
if method == "GET" and route.path == "/v1/status":
|
||||
value = await asyncio.to_thread(self.store.status)
|
||||
elif method == "PUT" and route.path == "/v1/devices":
|
||||
await asyncio.to_thread(self.store.set_devices, body["items"])
|
||||
value = {"ok": True}
|
||||
elif method == "GET" and route.path == "/v1/packets":
|
||||
after = int(parse_qs(route.query).get("after", ["0"])[0])
|
||||
value = await asyncio.to_thread(self.store.fetch, max(0, after))
|
||||
elif method == "POST" and route.path == "/v1/commands":
|
||||
if await asyncio.to_thread(self.operations.pending, body["imei"]):
|
||||
raise ValueError("durable operation owns device queue")
|
||||
value = await asyncio.to_thread(self.commands.submit, body)
|
||||
self.notify(body["imei"])
|
||||
elif method == "POST" and route.path == "/v1/operations":
|
||||
value = await asyncio.to_thread(self.operations.submit, body)
|
||||
self.notify(body["imei"])
|
||||
elif (
|
||||
method == "POST"
|
||||
and route.path.startswith("/v1/operations/")
|
||||
and route.path.endswith("/cancel")
|
||||
):
|
||||
value = await asyncio.to_thread(
|
||||
self.operations.cancel, route.path.split("/")[-2], body.get("kind")
|
||||
)
|
||||
elif (
|
||||
method == "GET"
|
||||
and route.path.startswith("/v1/operations/")
|
||||
and route.path.endswith("/attempts")
|
||||
):
|
||||
before = int(parse_qs(route.query).get("before", [str(2**63 - 1)])[0])
|
||||
value = await asyncio.to_thread(
|
||||
self.operations.history, route.path.split("/")[-2], before
|
||||
)
|
||||
elif method == "GET" and route.path.startswith("/v1/operations/"):
|
||||
value = await asyncio.to_thread(
|
||||
self.operations.get, route.path.rsplit("/", 1)[1]
|
||||
)
|
||||
elif method == "POST" and route.path == "/v1/configuration-observations":
|
||||
value = await asyncio.to_thread(self.observation.arm, body)
|
||||
elif (
|
||||
method == "POST"
|
||||
and route.path.startswith("/v1/configuration-observations/")
|
||||
and route.path.endswith("/close")
|
||||
):
|
||||
value = await asyncio.to_thread(
|
||||
self.observation.close, route.path.split("/")[-2]
|
||||
)
|
||||
elif method == "GET" and route.path.startswith(
|
||||
"/v1/configuration-observations/"
|
||||
):
|
||||
value = await asyncio.to_thread(
|
||||
self.observation.get, route.path.rsplit("/", 1)[1]
|
||||
)
|
||||
elif method == "GET" and route.path.startswith("/v1/commands/"):
|
||||
value = await asyncio.to_thread(
|
||||
self.commands.get, route.path.rsplit("/", 1)[1]
|
||||
)
|
||||
elif method == "POST" and route.path == "/v1/ack":
|
||||
if type(body["through"]) is not int or body["through"] < 0:
|
||||
raise ValueError
|
||||
await asyncio.to_thread(self.store.acknowledge, body["through"])
|
||||
value = {"ok": True}
|
||||
else:
|
||||
raise ValueError
|
||||
status = 200
|
||||
except PermissionError:
|
||||
status, value = 403, {"error": "not_authorized"}
|
||||
except (
|
||||
ValueError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
UnicodeError,
|
||||
asyncio.IncompleteReadError,
|
||||
asyncio.LimitOverrunError,
|
||||
TimeoutError,
|
||||
):
|
||||
pass
|
||||
except (OSError, sqlite3.Error):
|
||||
status, value = 503, {"error": "storage_unavailable"}
|
||||
try:
|
||||
payload = json.dumps(value).encode()
|
||||
writer.write(
|
||||
(
|
||||
f"HTTP/1.1 {status} Result\r\nContent-Type: application/json\r\n"
|
||||
f"Content-Length: {len(payload)}\r\nConnection: close\r\n"
|
||||
"Cache-Control: no-store\r\n\r\n"
|
||||
).encode()
|
||||
+ payload
|
||||
)
|
||||
await writer.drain()
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
writer.close()
|
||||
|
||||
async def run(self):
|
||||
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
tls.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
tls.load_cert_chain(self.store.root / "tls.crt", self.store.root / "tls.key")
|
||||
api = await asyncio.start_server(
|
||||
self.api,
|
||||
"0.0.0.0",
|
||||
self.store.config["api_port"],
|
||||
ssl=tls,
|
||||
ssl_handshake_timeout=8,
|
||||
limit=8192,
|
||||
)
|
||||
tracker = await asyncio.start_server(
|
||||
self.tracker, "0.0.0.0", self.store.config["tracker"]["port"]
|
||||
)
|
||||
async with api, tracker:
|
||||
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
|
||||
Reference in New Issue
Block a user