Files
ukmesh/docs/architecture.md

265 lines
14 KiB
Markdown

# Architecture
`meshcore-analytics` has five runtime domains:
- `backend`: MQTT ingest, HTTP API, WebSocket fan-out, database access, owner
sessions, and path-resolution orchestration;
- `frontend`: React application and native MapLibre live/RF layers;
- `hopreach`: canonical whole-region terrain propagation and progressive RF
raster publication;
- `link-worker`: observed relay-path processing into `node_links`;
- operations and edge: Mosquitto, TimescaleDB, Redis, Nginx/Anubis,
Prometheus, Alertmanager, Grafana, Loki, Alloy, and bounded exporters.
## Companion development repositories
CoreScope, Beacon Server and Beacon Web are independent Git submodules under
`third_party`. The optional [DEV launcher](companion-development.md) gives them
separate storage and ports while sharing the local fixture MQTT broker with
UKMesh. They are outside UKMesh's production Compose and release builds.
## Runtime failure boundaries
The websites and app serve static files independently of the backend. Their
proxy locations resolve upstream names at request time, so API and WebSocket
traffic can recover when the backend returns. Monitoring starts independently
of backend readiness. `/readyz` remains the aggregate release check for the
database, MQTT intake and owner ACL. The owner ACL runtime retries its own
startup while public HTTP and ingest start. Protected owner endpoints wait for
the first successful reconciliation.
The `backend` container serves HTTP and WebSockets. The `mqtt-ingest`
container owns the broker session, packet commits and forwarding. They use the
same image and start independently after database migration. The API's local
readiness check is `/api-readyz`. Its aggregate `/readyz` also reads the ingest
container's private readiness endpoint.
In durable mode the intake process acknowledges QoS 1 only after the existing
PostgreSQL commit boundary. It publishes bounded live events to Redis after
persistence. The ingest publisher and WebSocket server both apply privacy
checks. New WebSocket subscribers receive an `initial_state` snapshot. A
network-wide subscriber that has applied a snapshot can reconnect with
`packet_cursor=1&cursor=<last-applied>&initial_state=resume`. The server
acknowledges the cursor with `packet_resume` and replays subsequent committed
public packets in journal order, without querying or serializing the map
snapshot. Both legacy and `initial_state_format=columns-v1` support resume.
The acknowledgment includes the requested cursor and the format for column
clients. On close code 4009, the subscriber records the history gap and
requests a fresh snapshot. Subscribers can omit `initial_state=resume` to
request a full snapshot. Node and link updates outside the packet journal
remain live events.
Compact post-commit notices also let the API invalidate and warm its own
resolver cache, independently of the ingest database work.
With channel-scoped Redis ACLs, allow the existing `meshcore:live` channel and
the private `meshcore:path-observation` channel for both processes.
Owner-dependent forwarding also waits for that pass. MQTT intake can commit
while the forwarding outbox holds pending deliveries. Monitor disk capacity
and outbox recovery during a sustained owner outage.
Treat account provisioning, inventory evidence and transport configuration as
separate operations. Broker credentials reload in Mosquitto. An approved
inventory can be promoted in its mounted directory using the
[live activation procedure](operations.md#owner-authorization-baseline-refresh).
Confirmed grants use the audited `operator-database` authority with explicit
node confirmation. Existing environment-backed grants remain valid. The
provisioner verifies the applied generation and broker file before reporting
success. A recorded grant can wait for the running ACL reconciler and be
verified again without rewriting its approval or restarting a service.
Ingest password rotation owns the MQTT transport. It verifies the new password
on the same broker via an independent session and then reconnects the durable
client. The existing client ID and commit-before-acknowledgement rules apply
throughout. Reconnect verifies subscription acknowledgements, session
resumption and a delivery probe. A broker move also needs a handoff for the
source broker's retained session and unacknowledged messages.
Independent process restarts for MQTT and HTTP still require moving the live
event publisher out of the WebSocket server. Reuse the private Redis live
channel and repair gaps from committed PostgreSQL data. Preserve the publisher
and consumer privacy checks, post-commit link handling and public feed publish
authority. Qualify exact observations and live recovery for both restart
directions before making a separate intake process the default.
## HopReach boundary
The complete HopReach v0.1.32 source is vendored at
`third_party/hopreach`, with the exact upstream revision recorded in
`UPSTREAM_COMMIT`. The vendored base is
[`v0.1.32-ukmesh.4`](https://github.com/gadgethd/hopreach/tree/v0.1.32-ukmesh.4).
The UKMesh coordinator requires the remote GPU protocol and retains the CPU
raster for isolated parity tests. The propagation model retains its equations,
terrain samples, boundary and link budget. Other UK-specific work covers chunk/progressive
orchestration, the internal data adapter, versioned boundary, deployment
profile, and native map consumer.
The private backend router at `/hopreach` emits CoreScope-compatible repeaters
and observed reach evidence. It accepts only internal, non-forwarded traffic;
Nginx does not proxy it. Scope fields remain empty because UK Mesh has no
reliable region-membership source. No predicted geometry enters calibration.
```text
positioned UK repeaters + observed node_links
│
▼
backend /hopreach compatibility API
│ paginated/bounded
▼
HopReach coordinator ── private broker ── GPU worker + raster DEM cache
│ atomic Standard first, then gated Precision
▼
rf_coverage_data (last-known-good + current progressive tiles)
│ read-only mount
▼
app Nginx /rf-coverage/* ── React/MapLibre RF overlay
```
The app can fetch only `meta.json`, `progress.json`, and numeric PNG tile
paths. Coverage is not sent through backend JSON or WebSocket messages.
## Backend domain layout
- `backend/src/api/`: thin route modules, including the internal HopReach
compatibility boundary and static `410 Gone` legacy coverage contracts;
- `backend/src/repositories/`: SQL for node state/reads, packet reads, topology, RF validation, owner
alerts, registration, and operator workflows;
- `backend/src/operations/`: local operator, link-queue, registration, model,
and audit services;
- `backend/src/db/`: execution pools/query/transaction contracts, explicit packet
persistence setup, base schema, and migrations; feature queries live with their
repositories rather than a database facade;
- `backend/src/pathing/` and `backend/src/path-beta/`: pathing orchestration,
resolver implementation, pool, and caches;
- `backend/src/stats/` and `backend/src/owner/`: stats and owner domains.
Public privacy authority distinguishes the current desired generation from a
generation ready for publication. A current counter alone does not authorize a
public response: delivery and snapshot publication retain fresh ready-state
checks around their work.
`createApiRuntime` composes the stats, owner, timeline and health services and
their caches. Startup explicitly starts background work after identity
reconciliation; shutdown closes each runtime's resources after HTTP draining.
Public batch policy readers receive a query capability independently of packet
write-batcher setup, including in standalone WebSocket runtimes.
Workload modules under `backend/src/metrics/` own metric definitions. Process
startup initializes the complete metric inventory and process collectors;
health runtimes explicitly attach and detach their feature collectors. Importing
a metric definition does not start a database probe or Redis client.
Path prior identities and count conversion live below resolver implementations
in `backend/src/path-shared/`. The learner's pure evidence aggregation is
separate from SQL loading and lease-fenced publication. Beta and diagnostic lazy
resolvers retain their different observation grouping and normalization rules
and continue to use the existing common decoder.
Cross-runtime definitions live in [`contracts/`](../contracts/README.md).
Deterministically generated package-local bindings keep standalone builds and
worker-only Docker contexts independent. HTTP schemas remain owned by the
backend contracts and OpenAPI; queue vocabulary does not merge distinct queue
state machines or producer policies.
`region-snapshot-worker` shares the backend image and runs independently of
HTTP serving and the higher-priority privacy rematerialization worker. It
polls the authoritative ready visibility generation and rebuilds expired or
invalid region snapshots in a bounded child process. A PostgreSQL advisory
lock allows one publisher, and the five snapshot tables commit atomically
only after a fresh generation check. APIs withhold a snapshot from an older
privacy generation while repair is pending. See [operations](operations.md#region-snapshot-worker)
for capacity and recovery settings.
## Frontend domain layout
- `frontend/src/features/`: feature-owned models, parsers and data operations;
pages and renderers depend on these modules rather than supplying types to
reusable hooks;
- `frontend/src/components/Map/MapLibreMap.tsx`: dashboard MapLibre lifecycle
owner and controller coordinator;
- `frontend/src/components/Map/liveMapSources.ts`: store subscriptions, dirty
source scheduling, presence expiry and native source publication;
- `frontend/src/components/Map/EmbeddedMap.tsx`: lightweight public regions and
topology basemap lifecycle, with native overlays and no dashboard stores;
- `frontend/src/hooks/useRfCoverage.ts`: last-known-good metadata/progress
polling and safe tile validation;
- `frontend/src/components/Map/RfCoverageOverlay.tsx`: native image sources and
nearest-neighbour raster layers below labels and interactive layers;
- `frontend/src/components/Map/RfCoverageStatus.tsx`: tier controls, legend,
model details, and progress/failure state;
- `frontend/src/features/realtime/`: live node/packet/link stores and wire
protocol; `useNodes` adapts node state to React subscriptions, while map
controllers subscribe directly to link state;
- `frontend/src/store/overlayStore.ts`: path, replay, selection, and dormant
rollback-window planning state.
Resolved public scope is a network/observer/region/privacy-generation value.
Session transitions publish store resets after React commit; delayed HTTP and
WebSocket results cannot publish into an obsolete session. Cached tasks own
their cancellation and deadlines, while individual consumers detach without
cancelling another consumer's request. Aborting tasks keep their physical
concurrency slot until settlement. Runtime-config and owner authentication
bootstrap remain independent of public-data readiness.
## Worker ownership
The coverage/link worker entrypoint parses its environment into immutable
settings and constructs a `WorkerContext`. That context owns RF snapshots,
topology and lazy land-mask state. Computation receives explicit context rather
than consulting mutable process-global calibration dictionaries. Coverage/link
repositories, job handlers and process scheduling have separate owners; RF
equations and lazy geometry loading remain unchanged.
Link graph repositories bind a validated `core` or rebuild-generation schema
through SQL identifiers. Node catalog reads stay in `core`. Rebuild jobs read
and write their staging graph, retain lease/ledger/commit-before-ACK fences, and
do not publish uncommitted graph updates. Graph selection does not depend on a
`search_path` convention.
Link-v3 and retained viewshed-v2 share lease renewal infrastructure and keep
their distinct Redis state transitions. Tagger configuration, SQL repository,
classifier client and polling service are import-safe; its executable entrypoint
owns environment parsing and signal registration.
## Data flow
1. MQTT packets enter the backend, are privacy-normalized, persisted, and
published as bounded live messages.
2. The frontend stores live node/packet/link updates without routing them
through `App` state.
3. The link worker independently derives genuine observed `node_links`.
4. On its nightly schedule, HopReach pages positioned repeaters and optionally
loads observed evidence through the private adapter.
5. Standard tiles are atomically published as each completes. Metadata points
to last-known-good tiles throughout recomputation and restart.
6. After Standard is live and disk checks pass, Precision publishes in the
same manner.
7. The app polls small metadata/progress documents and refreshes only completed
raster tiles. Synthetic journeys and Prometheus/Alertmanager provide
independent operational evidence.
## Operational rules
- application startup does not run historical backfills;
- liveness remains independent of MQTT readiness; dependency checks use
`/readyz`;
- anonymous APIs use closed privacy DTOs and route modules remain thin;
- RF fidelity takes priority over performance: the upstream oracle, parity
suite, and benchmark gate must pass before release;
- calibrated RF remains disabled until validated against representative UK
paths;
- immutable releases use signed digest references and publicly available
corresponding source;
- the HopReach output/DEM volume is persistent and Precision is resource-gated;
- only one calculator may run, and recovery resumes its durable checkpoint;
- the old coverage producer, worker, frontend, WebSocket message, and live API
reads are disabled. `node_coverage`, old images, and the old implementation
remain for one release only as an inactive whole-release rollback path;
- `link-worker` and `node_links` remain live because they represent observed
evidence, not rejected viewshed geometry.
Most containers run read-only with Linux capabilities dropped and
`no-new-privileges`; stateful vendor containers receive only their explicit
volumes. `MapLibreMap.tsx` remains a documented lifecycle-coordination
exception; extraction rules are in `docs/frontend-map.md`.