ADR 0004 — Driver framework inside wyrm-link-sdk
Status: accepted · 2026-10-20
Context
DSA v2 connectors (reference: dslink-java-v2-modbus + driver-framework-java-v2-prototype) proved a concept worth keeping: a connector is a tree Connection → Device → Point, every level is an editable node with declarative parameters and Add/Edit/Remove/Restart actions, and a change at any level reactively rebuilds only what depends on it. The Java implementation has defects (non-atomic edits, races on reconnect, optimistic writes, unbounded backoff, silent config loss) that we must not port.
Decision
wyrm-link-sdk ships two layers:
- Raw layer —
trait Link,LinkCtx,NodeTree, one queryable per link, liveliness,ptokcheck. For drivers with their own topology (MQTT, OPC UA browse, gateways). - Driver framework (
wyrm_link_sdk::driver) — opinionated layer on top of (1) for protocol drivers. A driver declares node kinds and the framework provides everything else.
What the framework provides
| Concern | Design |
|---|---|
| Parameters | One declarative schema per node kind: #[derive(Params)] on a config struct → name, type, enum, default, bounds, description, placeholder, secret flag. Generates ~meta.cfg schema, Add <Kind> action form (pre-filled with defaults), Edit action (pre-filled with current), load-time validation, fuzz values for tests. Parameters are typed structs, parsed once, never string-keyed maps. Amended 2026-10-22 (owner decision: node structure as in the DSA driver framework, dslink-java-v2-modbus): a level may have several node kinds, as DSA’s Add IP Connection beside Add Serial Connection: #[derive(Params)] on an enum of newtype variants gives one kind per variant (Params::kinds), each with its own add_<kind> action and form; the tree stores the node’s kind beside its params on such levels (their params may not be named kind). Fields carry display (label), desc (description), placeholder and editor; a secret is a password field (spec 02 0.1.6). A driver may offer found values for a param (Driver::choices, e.g. serial ports) and a root rescan action (Driver::RESCAN, DSA “Rescan For Serial Ports”). |
| Edit semantics | Validate first, atomically. validate(new) → Err aborts with invalid_parameter{path} and nothing changes. Then diff(old, new) → Rebuild::{None, Self, Subtree, Connection} decides what restarts; drivers may override on_edit(old, new) for fine-grained reaction (e.g. only reschedule a point). Teardown with old config completes before bring-up with new — no async close racing a new open. |
| Lifecycle & liveness | Typed state machine per node: New → Connecting → Connected → Failed → Stopped → StoppedByParent. A child runs only while its parent is Connected; parent failure cascades StoppedByParent. Published as ~val of the node (status) plus ~meta.q. Never a free-form string. Amended 2026-10-22: status is an enum leaf (wy:df-status: Unknown, Connecting, Connected, Failed, Stopped, Stopped by Parent; ~val = index), and the error text is a separate string leaf error (wy:df-error) that exists only while there is an error, as DSA’s Status and Error values. |
| Scheduling | Per-connection owner task that exclusively holds the transport and consumes an mpsc of requests (ping, poll batch, write) — the Rust equivalent of a fair lock. Tick launches I/O only if the previous I/O finished (no pile-up). Backoff on failure: exponential with cap and jitter (1s..60s, ±20 %). |
| Polling | Points are polled all the time by default (amendment 2026-10-20, owner decision: the in-process ~val storage of wyrmd always counts as a subscriber, and reads must be fresh); poll_unsubscribed: false polls only while subscribed (SDK knows subscriber count per key; reliable for process links only). Points grouped into batches by (device, poll_rate); batch plan (address partitioning, max read count, contiguity) is cached and invalidated on edit, not rebuilt every tick. Per-point errors are distinct from whole-batch transport failure. Amended 2026-10-30 (Modbus DSA parity plan, rulings 8 and 9): a poll is bounded by Driver::poll_timeout(conn, plan) (default io_timeout; Modbus: timeout_ms × (1 + retries) × requests + 1 s), so a large plan on a slow line is not cut; Driver::republish(dev) (default none) publishes an unchanged value again once its last publish is that old (a heartbeat, after reads only). Every request of the owner carries the connection’s plan generation; one planned before a re-plan is dropped, never run on what replaced it (a dropped write or action answers busy; rulings P19, P20). |
| Writes | ~set is a request/response: no optimistic update. Framework calls write(point, value); ~val is updated only from read-back (immediate read after write, or next poll) with the write’s status returned in attachment. Write strategy knob per connection (`single |
| Quality | Timeout → uncertain/stale for N misses, then bad/comm_fail; parent down → bad/disconnected; recovery → good. Exact codes in attachment key 1. Amended 2026-10-30: N is Driver::stale_misses (default 3); a point error is bad/device_error and a value a server does not take after an edit bad/config_error, the last value kept in both. There is no “zero on failed poll” (ruling 14). Amended 2026-10-30 (P30): when a device answers for some points of a poll but a point’s result is DriverError::Device (its batch timed out), that point takes the same ladder on its own (uncertain/stale, then bad/comm_fail after N such polls in a row) while the device stays Connected. Amended 2026-10-30 (final review M1–M3, ruling P31): no miss lifts a quality: the stale mark changes only good points, and a point already bad that gets no answer starts its ladder at N. An answered ping forgives only ping misses: the misses its polls earned stay, so a device whose polls time out while its pings answer reaches bad/comm_fail for its points and stays Failed with its error (no Failed/Connected flapping, no Connected over bad points) until a poll answers; a device that fails past N by any mix of misses is Failed too. A poll that cannot run (it waits in the queue behind an action, a long write series or other devices’ polls that time out, or the queue is full) for N poll periods in a row marks its group’s good points uncertain/stale (the ticker, under the plan’s read lock). |
| Persistence | Amended 2026-10-21 (owner decision: the connector owns its config, credentials come with the connection as in DSA). The framework keeps the whole tree, secret fields included, in the link’s data_dir/framework.tree, sealed with ChaCha20-Poly1305 under the link’s store key (secret .store_key, created by the admin per link and delivered with the link secrets), and writes it after every add_*/edit/remove/start/stop. ~def.params is the bootstrap: the file stores its SHA-256, and new bootstrap params (json5 edit, admin update/rollback) replace the stored tree. A file that does not open (other key, tampering) falls back to the bootstrap. Without a data_dir or store key the tree lives in memory. Secret params (#[param(secret)]) never show in ~meta.cfg, export or replies; an edit that leaves a secret empty keeps the stored one only while the destination fields (#[param(dest)], or every field when none is marked) stay the same. Load-time validation failure keeps the node in Failed with ~val.error, never deletes it. Amended 2026-10-30: that holds for params. A tree whose structure is wrong (an invalid name, a point id twice on a device, folders deeper than MAX_FOLDER_DEPTH, an unknown key in a folder) fails the link’s start with that error, stored or bootstrap alike: there is no node to keep it on. |
| Slave/server mode | ServerKind for drivers that can expose the tree as a protocol server (Modbus slave, OPC UA server): shared listener per port keyed by (transport, port), process image per unit, ref-counted shutdown, strict duplicate/overlap rejection at registration.Driver::is_server), not polled; its points take ~set and serve the tree’s values. A server’s Driver::write must not do I/O: the framework calls it under the plan’s read lock after serve, where a re-plan waits for it (final review M6). |
| Actions | Add <Kind>, Edit, Remove, Restart, Start/Stop generated per kind; Start/Stop only on branches, not on points. Drivers add their own (Rescan ports, Discover). Amended 2026-10-22: as in DSA, only the action that applies is declared: stop while the node runs, start while it is stopped. Every action has a name for people and a menu group (spec 02): add_* → new; edit, remove → edit; restart, start/stop, export, rescan → top level. Amended 2026-10-30 (rulings 11, 13, P12, P14–P18): copy {name} on connections, devices, folders and points (group edit; a copied connection or device starts stopped; a folder copy renames its points <id>_<n> and replies renamed); export of the whole tree, a connection, device or folder → {json} (format wyrm-driver-branch/1, branch.rs; secrets "<not exported>"); import {json, name?, overwrite?} of a connection at the root, a device into a connection, a folder into a device or folder (the top node starts stopped, a folder is polled at once; secrets never imported, listed in reenter; an overwrite keeps sealed secrets while the destination fields stay the same); bounds 4 MiB, 5000 nodes, 60 s. Driver actions: Driver::actions(level, kind) on connections and devices, run on the owner task by Driver::invoke between polls (queued with try_send: a full queue answers busy); a framework name is refused. Amended 2026-10-30 (final review I1, ruling P31): one driver action per connection is queued or running at a time; another (any caller, any level) answers busy at once, so actions delay the connection’s polls by one action at most. The Driver::actions/invoke signatures do not change. Root imports: Driver::root_imports + Driver::convert turn another system’s export into connection branches, checked all before the first is imported (Modbus import_dsa). |
| Observability | rtt_ms, errors, polls), rate-limited logs with link=/node= fields, state transitions audited.Driver::DIAGNOSTICS, default false; a driver that does not report outcomes would show counters stuck at 0). With it, each connection and device has value leaves requests, errors, timeouts, exceptions, the driver’s DIAG_EXTRA (Modbus reopens), last_rtt_ms, avg_rtt_ms (EWMA α = 0.1), counted from Driver::take_outcomes after every operation, published on a change at most every 10 s and at once on a read of the node; counts start at 0 on (re)start, a reconnect after a failure keeps them. Those names are reserved for children. |
| Folders | Added 2026-10-30 (ruling 10): with Driver::FOLDERS (default false; Modbus true), folders between a device and its points, at most MAX_FOLDER_DEPTH (4) deep, names only: add_folder, remove (cascades), copy, export, import; no edit (no rename: ids are keys of history watches, ACL and flows). A point id stays unique on its device, so polls, plans and writes go by (device, id) and never see folders; the point’s key gains the folder path. The tree stores folders: {<f>: {points, folders?}} beside a device’s points. |
Driver surface (what a Modbus driver writes)
Corrected 2026-10-30 (ruling 16) to what links/modbus declares; the full params and their bounds are in docs/modbus.md section 3.
#![allow(unused)]
fn main() {
#[derive(Params)] enum Conn { Ip(IpConn), Serial(SerialConn), IpSlave(IpSlaveConn), SerialSlave(SerialSlaveConn) } // one add_<kind> each
#[derive(Params)] struct IpConn { host: String, port: u16 = 502, transport: IpTransport = Tcp, timeout_ms: u32 = 1000 @bounds(100..=10000), write_mode: WriteMode = Auto, retries: u8 = 0 @bounds(0..=5) }
#[derive(Params)] struct Device { unit: u8 = 1 @bounds(0..=255), ping: Ping = Probe, probe_table: Table = Holding, probe_addr: u16 = 0, ping_s: f64 = 5.0 @bounds(0.1..=3600), contiguous_only: bool = false, max_regs: u16 = 125, max_bits: u16 = 2000, republish_s: f64 = 0.0 @bounds(0..=3600) }
impl Params for Point { /* by hand: table, addr, dtype = u16 (binary on bit tables), bit = 0, regs = 1, poll_s = 1.0, scale = 1.0, offset = 0.0, writable, unit, writable_by_master */ }
impl Driver for ModbusDriver {
type Conn = Conn; type Dev = Device; type Point = Point; type Transport = Transport; type Plan = Plan;
async fn open(conn: &Conn) -> Result<Transport, DriverError>;
async fn ping(t: &mut Transport, dev: &Device) -> Result<(), DriverError>;
fn plan(dev: &Device, points: &[(PointId, Point)]) -> Plan;
async fn poll(t: &mut Transport, dev: &Device, plan: &Plan) -> Vec<(PointId, Result<Value, DriverError>)>;
async fn write(t: &mut Transport, dev: &Device, id: &str, p: &Point, v: &Value) -> Result<(), DriverError>;
// optional hooks with defaults: io_timeout, poll_timeout, write_timeout, read_back_on_error, republish,
// stale_misses, choices, RESCAN, actions, invoke, root_imports, convert, DIAGNOSTICS, DIAG_EXTRA,
// take_outcomes, FOLDERS, and the server hooks of ADR 0024
}
}
Everything else — tree, actions, edit, states, scheduling, subscription gating, quality, diagnostics, folders, branches — is the framework.
Consequences
- Drivers are ~300–600 lines and behave identically to operators (same actions, same states, same error reporting).
links/mockis the first framework driver;links/modbusthe first real one. BACnet/DLMS reuse the same kinds with discovery actions.- The framework adds iteration-1 scope;
wyrm-link-sdkis delivered in two steps: raw layer, thendrivermodule beforelinks/modbus.