Reeve Docs

Docs / Architecture

Protocol integrations

An integration is a plugin. Where it runs is a topology decision, not a trust decision.

Shape When Example
In-process the protocol is just a network socket ESPHome over TCP, Cast over TLS, MQTT clients
Sidecar plus a thin companion plugin a radio is pinned to a host, or the runtime is heavy and native Thread and 802.15.4, Z-Wave, Bluetooth over the host bus, the Matter bridge

A sidecar keeps the backend stateless and horizontally replicable and keeps native build complexity off the host. It is explicitly not a security boundary: the sidecar and its companion plugin are equally trusted, and the sidecar never touches the database; all persistence flows through its plugin. Do not reason about a sidecar as a sandbox, and do not add one for a protocol that is just a socket. The rule is Hardware-bound integrations run beside the backend; how a sidecar is declared, consented to and updated is in workloads.md.

Protocol integrations live in their own repositories and release independently: the inbound Matter controller, Bluetooth, Z-Wave, the discovery host, and the lightweight in-process plugins. A change to the plugin SDK is therefore a cross-repository contract change, and a protocol claim is verified in the owning repository. Only the Matter bridge sidecar, the shared session protocol and the BLE decoding library live in this repository.

The session plane

Adapter and bridge sidecars hold no broker credentials (Sidecars talk to the backend, never to the broker). A managed workload's control plane is a raw WebSocket session the backend terminates at wss://<host>/ws/workloads/{instanceId}, same origin as the API, authenticated by a per-instance, revocable bearer token carried in the authorization header only. The sidecar dials out, sends a hello frame carrying instance id, application version, spec hash and protocol version, then exchanges {messageId, type, payload} frames whose payload models are the shared wire contracts under services/adapter-protocol/.

Frame type Role
HELLO / HELLO_ACK handshake; the acknowledgement echoes the applied spec hash
HEARTBEAT liveness, both ways
ACK delivery acknowledgement
SNAPSHOT the full state push after every connect, in one or more frames
DATA sidecar-originated events, sub-discriminated by an open dataKind string
COMMAND / COMMAND_RESPONSE backend-originated request and its correlated reply
ERROR a protocol fault that does not close the session

The top-level frame type is a closed, by-name enumeration; the data sub-discriminator is an open string that must parse and be retained verbatim when unrecognized, so a read loop survives a newer or hostile peer. Discriminating by name rather than ordinal makes a member reorder harmless.

Presence is server-owned: a socket close or missed heartbeats mark the instance offline. This removes the whole class of ghost-presence bugs that last-will and retained-birth machinery produces, removes broker access control for sidecars, and gives one transport instead of two with precise per-attempt diagnostics. A manual operator exposes nothing beyond the backend URL they already expose.

Standing obligations on a sidecar:

  • After every reconnect it pushes a full device and telemetry snapshot before resuming incremental frames. Reconnection is resync, not replay. Reconnect with exponentially backed-off, fully jittered delays.
  • No frame exceeds 1 MiB of UTF-8 JSON; the gateway closes the session on a larger one. A snapshot that does not fit is sent as several SNAPSHOT frames, each a part of the devices and states; the gateway upserts every entry, so the parts apply as one snapshot. The shared clients split it themselves (SessionProtocol.MaxFrameBytes / MAX_FRAME_BYTES) and fail the session with a snapshot-entry-too-large error, before sending anything, when one entry cannot fit a frame alone.
  • Re-authentication is a reconnect with a fresh token. An in-band mid-session handshake refresh is a violation; the server answers a mid-session hello with an error frame and keeps the session open.
  • Carry what the plugin's parse needs, verbatim. An adapter may stamp non-secret resolved attributes onto state frames under a reserved double-underscore key the canonical parser ignores; those keys survive the ingestion path unaltered. Vendor-specific detail belongs in the discovered-device message's metadata under a key the plugin defines, because the typed scalar fields alone cannot reproduce full fidelity. A secret, bind key or token on a frame is forbidden.
  • Protocol compatibility is checked in both directions and fails closed.

Never open broker egress for an adapter sidecar: it needs exactly one egress, to the backend service. Referencing broker bootstrap keys from an adapter-session workload is a validation error.

The host needs no broker

The host needs no MQTT broker, and Reeve ships none: nothing in device state, automations, the cluster or start-up goes through one. A broker the operator runs serves only genuinely-MQTT integrations, such as Zigbee2MQTT and the MQTT plugin kinds, which connect to the broker the owner names in their configuration (mqtt.outbound). Any MQTT 3.1.1 or 5 broker works. It is not an adapter control plane and not an inter-replica bus. Adapters on the session plane need no broker credentials and must not be given any. The backend-terminated session means no broker user per workload and no externally exposed broker for manual deployments.

The host has no broker settings and hands no broker or credentials to a plugin or a workload. A plugin connection holds mqtt.outbound, names its broker, and is refused otherwise.

Plugins reach the broker through one host-services connection abstraction; no broker library type is exposed to a plugin. Reliability is at-most-once or at-least-once: there is no exactly-once anywhere. Sessions are clean, with no durability across restart; state is refreshed on reconnect. The per-protocol details are in MQTT integrations.

  • Every client id is replica-unique. The broker disconnects the older of two connections sharing an id, so a fixed id across replicas is a permanent reconnect storm. The abstraction owns the id and composes it from a shared replica identity (Transport identity is per replica).
  • Retained messages are never delivered to shared subscriptions. Anything depending on a retained snapshot (bridge state, availability, discovery configuration) stays broadcast, never sharded. Sharding is opt-in per instance, off by default, and applies only to the device-state stream.
  • Shared subscriptions round-robin with no affinity, so state can arrive out of order across replicas. Order tolerance comes from a source-time monotonic guard enforced as a conditional upsert under a row lock, so an older concurrent write from another replica is rejected outright.
  • A deliberately stopped integration leaves a stale "online" behind unless it republishes the retained offline message before disconnecting cleanly; the Will fires only on an ungraceful disconnect.
  • A queued command can actuate minutes late. A message-expiry interval prevents it, but expiry is a newer-protocol feature silently ignored by the older one, so enabling it without negotiating the newer version does nothing. State, availability and discovery publishes never carry an expiry; they have to persist.
  • TLS is opt-in with pinning to a custom root for self-signed brokers. There is no accept-any-cert mode. Outbound TLS clients, MQTTnet included, never resume a session (Outbound TLS clients do not resume sessions).
  • A health check that opens a TCP socket proves nothing about the protocol. Check the real connect and acknowledge exchange, or the check passes against a port that will reject every publish.

The status topic has one voice

A plugin's retained status topic is spoken for by the connection that holds the cluster mutex MqttStatus_{broker host:port}_{topic}_Leader, at every replica count, so instances on different brokers each get a voice. The mutex is decided before each connect, because the Will is a property of the CONNECT: the winner connects with the Will, a peer without it, and a peer that wins a later poll (about every 5 s) disconnects cleanly, reconnects with the Will and publishes online.

  • The leader publishes offline when it stops or loses leadership, a fenced replica included, and only then disconnects and releases, once the link that carries the Will is down. A dropped link or a refused connect releases the mutex.
  • While it leads, the connection watches its own topic and answers the Will payload with online. An offline that lands after a new leader's Birth (the broker's delayed Will for a dead session, a resumed paused leader stepping down) is a blip, not a lasting state.
  • The topic reads offline for the takeover window after a leader ends, at every replica count, a single node restarting included. One code path serves one replica and many; a single node behaves like a cluster of one.

Only the leader connects with the Will, so one peer's dropped link cannot flip the fleet's topic offline.

Rules for any integration across replicas

  • A plugin holding a long-lived per-device connection takes the connection-ownership lease before connecting, or every replica opens its own socket to the same device (Plugins hold no device state and lease before connecting).
  • A correlated request/response stream is never sharded: the response has to return to the replica that issued the request. A stream mixing a correlated response with ongoing events on one channel cannot be classified per channel; route by deserialised message type.
  • A fleet-wide sweep (re-interviewing every stored node) runs only on the replica that owns the adapter's session; individual commands stay available everywhere. If locality cannot be determined, sweeping fails open (every replica sweeps, wastefully) rather than closed (nobody sweeps, and devices never settle). Locality follows shared presence, never a lingering local socket handle.
  • A synchronous command await is honest or absent. When the owning socket is not local, return "no session" rather than fabricating a client-side timeout for a delivery that never awaited a response.
  • Ingestion time is not observation time. Freshness keys off the source's own timestamp where the protocol supplies one, or a replayed state fires an automation for something that happened hours ago. The freshness check gates side effects, not persistence, and fails open on a missing or skewed timestamp.
  • State built from adapter frames is observable; effects stay in the ingestor. Only the replica holding an adapter's session receives its frames. With observation replication on, a plugin that opts in also receives, on every other replica, the frame kinds it lists, through an observer that applies state and nothing else. The ingestor on the owner keeps every effect (device events, key-value replies, commands), so a frame is acted on once, never once per replica. Never opt in a correlated reply or a frame carrying a secret, such as a key-value store holding fabric credentials or camera signalling carrying ICE credentials. A kind not listed never leaves the owner's process. A replica's view can lag or be incomplete, and says so; a command path that needs current state asks for a catch-up and, when the view cannot vouch for itself, reads what it translates against as it would without replication. The plugin-side contract is in the plugin authoring guide.
  • Plugin endpoints gate on the generic integration-management and device-management codes with imperative claim checks, because policy-name authorization only works for policies the host itself registers; no core permission code is named after a plugin's protocol (constraints).
  • Every plugin runs without an integration transport; the transport factory is strictly opt-in. An optional discovery or integration subsystem degrades and keeps retrying; it never aborts host start-up.

Discovery topology

Protocol discovery runs where the protocol lives. Multicast DNS is browsed in-process by the backend, because it only works from a process sharing the devices' layer-2 segment. The other network-level providers (service discovery over UDP, USB, Bluetooth, address leases) run in a per-node discovery workload that scans on demand, once, to completion and then leaves nothing running, forwarding candidates back over the session plane. A permanently resident privileged scanner on every node is a standing cost and a standing attack surface for a function operators invoke rarely. A running plugin instance can also contribute its own discovery source with no core change.

A candidate's source label is data, not a matcher type: core holds no per-vendor discovery code, and candidates are ephemeral and time-limited.

mDNS multicast does not traverse a pod-network overlay, and mDNS-typed candidates are not accepted from a remote forwarder: the forwarded-candidate validator accepts only the non-multicast types. Where multicast does not propagate, protocol discovery silently finds nothing; on a clustered deployment discovery either uses the per-node workload or the operator configures instances by hand. Plugins for such protocols carry a static host-and-port list as the escape hatch, and a controller-backed discovery source is the other way to seed candidates.

Candidate semantics (ephemerality, the metadata allowlist, matcher rules) are in device-model.md and the discovery reference.

Bluetooth

The server never does Bluetooth for Matter. The Matter bridge advertises and commissions over IP and multicast DNS only, with no Bluetooth transport linked in. A new Matter device is commissioned by the phone's own platform commissioner, which does the Bluetooth pairing exchange and network provisioning; the operating system reopens the commissioning window and hands back an address, a passcode and a descriptor, and the app relays those over its authenticated session so the adapter joins the device as a second administrator by address, over IP.

The onboarding seam is generic: any plugin can register an onboarding provider, and the app keys handlers by an onboarding-kind wire string, never by plugin identity, so a replacement plugin needs no client change. The onboarding session lives server-side in shared durable storage and is the source of truth; the provider does not create a device row. The device materialises through the normal asynchronous sync path and is correlated by commissioned node id.

Never trust a device-supplied descriptor for authorization or identity. Vendor, product and type are attacker-influenceable metadata: use them for display and sanity checks, authorise by principal and instance, and de-duplicate by the commissioned node identity.

BLE sensors are a separate path: their advertisements reach Reeve through the Bluetooth plugin's sidecar on a host with a radio, or through ESPHome Bluetooth proxies. Both decode with one library.

The BLE advertisement decoding library

Reeve.Ble.Decoding is the transport-agnostic decode core (encrypted MiBeacon, BTHome v2, a raw GAP parser and a per-address telemetry accumulator), shared by the ESPHome Bluetooth-proxy source and the published Bluetooth plugin so the two cannot drift.

  • It depends only on the logging abstractions and has no in-repository project reference, because a project reference would put an unresolvable dependency on the published package.
  • The accumulator keys time on monotonic timestamps, so an NTP step on a board without a real-time clock does not forget every device. Idle devices are forgotten, the least recently heard entry goes when the accumulator is over capacity, and an entry is stamped before it is published so a sweep never mistakes it for an old one.

Thread networks

Thread handling lives in the Matter plugin, reeve-iot/reeve-plugin-matter. See that repository for its flows, the Thread dataset import and the reeve-epskc helper.

What the host side guarantees:

  • A hub's Thread network reaches the plugin through an instance action flow, not a Thread interface in the SDK. The flow carries the hub's sharing code in a Sensitive field with integrations.manage, encryption at rest and audit, so Reeve.PluginAbstractions, Reeve.Contracts and the host carry nothing Thread-specific.
  • The imported network is plugin state, not configuration. An explicitly configured Thread source always wins, and replacing an imported network is a forget followed by a new import.
  • A phone that already knows a Thread network can supply its dataset through the generic ClientValue step (kind thread.active-operational-dataset), which the Android app fulfils. See client value flows.
  • The sharing code allows ten attempts and nothing retries automatically. A flow that moves to another replica does not spend a second attempt, and a new attempt is a new start of the flow.
  • Moving an OTBR onto the hub's network is a manual operation. The Thread status shows each border router's Active Timestamp for diagnosis.

Integration settings and authentication integrations

  • An instance configuration write runs exactly once under the instance's row lock, or throws. Callers read what was captured afterwards, never a value they assume was written.
  • A stored secret envelope marks its field sensitive whatever the caller's field names say, because this replica may not know the field. Admin reads show secrets only as Has* booleans.
  • Enabling SkipTwoFactor for an identity provider is audited on its own, because it is a security-relevant downgrade that the generic audit row (a provider count) cannot express.
  • An OIDC provider is validated before it is persisted: the issuer is an absolute http(s) URI, and the client secret is non-empty unless one is already stored.
  • The settings store is created on first use: the cookie handler takes it on every request and most requests never decrypt anything.
  • Key loss on the sign-in path never throws, or authentication goes down for the very key loss it reports.

Protection of these secrets is in secrets and audit; the sign-in side is in authentication.

The Matter bridge

The Matter bridge is a sidecar in services/matter-bridge (TypeScript on matter.js) that exposes Reeve's own devices as one local Matter bridge node, which Apple Home, Google Home, Amazon Alexa, Home Assistant and any other controller commission once per ecosystem and then drive over the LAN. Cloud voice fulfilment is not part of the product. How the bridge works is in Matter bridge; running it is in the operator guide.

Other protocol traps

  • Unicast discovery to a device's own address crosses subnet boundaries; broadcast discovery does not. Where a vendor protocol offers both, addressing the device directly is what makes it work across a routed LAN.
  • A push-based device socket needs its own liveness clock. A dead socket that never returns end-of-file looks healthy forever. Declare it dead after a small multiple of the keepalive interval and reconnect with exponential backoff plus jitter.
  • Vendor device identifiers can exceed 32-bit range: carry them as text, not integers. Some device identities are re-keyed on rediscovery, orphaning every reference; prefer the stable protocol identifier the vendor supplies over anything derived from a name.
  • Cast devices present self-signed certificates, so the transport accepts any certificate and there is no pinning knob; the threat model assumes a trusted LAN. Serialise writes to the socket: the TLS stream is not write-thread-safe.
  • The Home Assistant discovery envelope is per-component, not per-device. Each component carries its own state and command topic pair, an optional availability topic, and a shared device block. Command payload tokens come from the discovery document's declared payloads; publishing a canonical token instead of the device's own payload is a silent wire break that looks like a working command.
  • Zigbee2MQTT sends availability either as a bare string or as an object with a state field. Parse both.

Failure modes

Symptom Cause
A shared-subscription setting makes state worse on a single replica Sharding costs retained-on-reconnect delivery and buys nothing below two replicas.
Commands from a non-owning replica take longer than expected They are written as durable rows and the owner delivers on its local socket. Delivery is reliable but the latency is real.
The same physical device appears twice It is heard by two sources. Reconciled at the logical-device layer by attaching several single-writer sources to one device, never by de-duplicating on signal strength inside a driver.
A discovery candidate keeps coming back after dismissal Dismissal hides one row until it expires, and a device whose advertised identifier is unstable produces a fresh candidate each rotation. Stable identifiers dismiss once and stay dismissed.
An MQTT status topic reads offline briefly after a restart The takeover window between leaders; the next leader publishes online.
A sidecar is marked offline while its process is clearly running Presence is server-owned: the socket closed or heartbeats were missed. Check reachability of the backend gateway from the sidecar, not the broker.

See also