# Architecture

```mermaid
flowchart LR
  MQTT[MQTT broker] --> MA[Async MQTT adapter]
  MB[Modbus TCP device] --> BA[Read-only Modbus adapter]
  RTU[Modbus RTU device] --> RA[Serial Modbus adapter]
  MA --> E[Unified Event]
  BA --> E
  RA --> E
  E --> T[Transform]
  T --> V[Validate and quality]
  V --> R[Static rules and projection]
  R --> Q1[Bounded queue A]
  R --> Q2[Bounded queue B]
  Q1 --> S1[Sink A worker and retries]
  Q2 --> S2[Sink B worker and retries]
```

Each device owns its adapter, connection, sequence and collection task. Structured
task groups own all collectors and output workers. A failed device closes its
connection before bounded backoff; another collector continues independently.
Retries are a lifetime budget for the run, not reset by a single successful read.

An adapter yields `Event?`: `Some` is a measurement, `None` means exhaustion,
and a raised error means the reading or session failed. `RejectedReading`
counts an unusable reading without reconnecting or consuming the reconnect
budget. Polling Modbus and
subscribed MQTT keep their distinct internal semantics behind this interface.
The runtime validates event identity against the registered device.

Processors transform a snapshot, annotate quality, filter and project fields.
Processing errors increment a separate counter and drop the event; protocol
errors trigger reconnect. Missing measurements never become numeric zero.

Fan-out snapshots maps into each matching output queue. One task serializes
delivery to each sink, with a write deadline and retry budget. Slow/failing
outputs cannot block device collection or other sinks. Ring slots are cleared
on pop. Capacity controls event count; maximum input frame and field limits
control typical event size. Queue-full policies explicitly drop newest or oldest.

Duration expiry cancels only collection first. Deferred adapter cleanup closes
connections, then routes are closed to producers and share one drain deadline.
The runtime cancels unfinished sink workers when that deadline elapses. Pending
and in-flight events without a terminal delivery result count as dropped.
Process-wide cancellation may interrupt draining; all resources still clean up.
Retries require cooperative async sinks and may repeat partial side effects.

Public model types belong to `model`; adapters and sinks own their concrete
types. `pkg.generated.mbti` files are generated interface contracts. The RTU
adapter uses native calls for serial port configuration and byte I/O.
