Concurrency¶
The module is concurrent by construction: a host's cluster servers are
called from many goroutines at once, and the session, subscription and MRP
paths run side by side. This page lists the goroutines a running node
owns, what a host callback may do, the ordering the module guarantees, and
how shutdown ends it all. The race detector run (make race) is a release
gate for these paths.
The goroutines of a running node¶
| Goroutine | Started by | Cadence | Stopped by |
|---|---|---|---|
| UDP read loop (one) | bridge.Start |
per datagram | bridge.Stop (context cancel, socket close) |
| Datagram handlers | the read loop | one per datagram, or per session (below) | returns; bridge.Stop waits for them, bounded by its context |
| TCP accept loop and one reader per connection | bridge.Start with Network.TCP |
per message | bridge.Stop (readers and their handler calls waited for, bounded by its context) |
| ACK pump | bridge.Start, when an ACK tracker is attached |
every 50 ms while an acknowledgement is owed, a reliable message awaits its ack or a timed deadline stands; asleep otherwise, woken by new work | bridge.Stop |
| Subscription engine tick | Node.Start |
every 250 ms | Node.Stop |
| One report per due subscription | the engine tick | at most one at a time per subscription | returns |
| Session reaper | Node.Start |
sweep every minute; evicts sessions idle for 5 minutes | Node.Stop (and waited for) |
| PASE and CASE handler reapers | Node.Start |
sweep every 30 s; evict handlers idle for a minute | Node.Stop |
| Operational-time keeper | Node.Start |
every minute | Node.Stop (and waited for) |
| DNS-SD broadcast schedule | the first Publish of the node's mdns.Responder (timers, no goroutine; the two receive loops start with the sockets) |
1 s doubling to 90 s, until a CASE connection or two days | Node.Stop (the advertiser's Close) |
| Session-triggered re-announce | a session teardown or a terminated subscription | once, bounded by the advertise timeout | bridge.Stop (cancelled and waited for) |
| BDX transfer | a peer's BDX init on a secure session | one per exchange | bridge.Stop (cancelled and waited for, bounded by its context) |
| BDX log transfer | a RetrieveLogsRequest answered over BDX | one at a time | bridge.Stop (DiagnosticLogs' MatterQuiesce cancels it and waits) |
| Binding manager | the first binding work (Node.Start registers the entries) |
on change | Node.Stop |
| Client stack socket | node.New with a non-nil Config.Client |
per datagram, in arrival order per secure session (below) | Node.Stop |
node.New starts no goroutine of its own (only the opt-in client stack
opens its socket there): a node built and dropped leaks nothing it began.
Call Stop on every node New returned all the same, even one you never
started — it closes the store file Store.Path opened.
Every cadence in the table runs on one clock: node.Config.Clock
(bridge.Config.Clock for a host that builds the bridge itself), a
clock.Clock
— the module's one time port, clock.System when unset. No production
code outside the clock package reads the time package's clock
(clock/noraw_test.go fails the build on one), so a test that passes a
clocktest.Fake
moves the ACK pump, the engine tick, the reapers, the commissioning window
and the cluster timers only when it calls Advance. AfterFunc callbacks
run in their own goroutine on either clock. The node's assembler hands the
same clock to the Identify server of every bridged endpoint
(endpoint.Config.Clock) and to the Aggregator's; a device the host builds
with the device layer takes it when the Aggregator adds the device.
fabrictest
runs whole nodes and the module's controller on one clocktest.Fake and an
in-memory network, and moves the clock only while no datagram is in flight,
no host holds counted work in hand and no goroutine of the process is
working — the
Testing in process guide.
Source: transport/udp/listener.go (Listener.Serve), bridge/bridge.go (Bridge.Start, startAckPump), bridge/ackpump.go (ackPumpInterval, runAckPump), im/subscription/manager.go (DefaultTickInterval, Manager.Start), im/subscription/engine.go (Manager.tick), secure/operational/manager.go (SessionIdleTimeout, Manager.StartReaper), node/security.go (security.start), bridge/pase_provider.go and bridge/case_provider.go (StartReaper), node/node.go (operationalTimeInterval, ErrStopped), node/node.go (Node.observedFabricRemoved), node/reannounce.go, mdns/announce.go, bridge/securechannel.go (triggerSessionReannounce), bridge/bdx_responder.go (goResponder), binding/manager.go (Manager.startWorker), node/client.go (newClientStack), node/node.go (the Node struct), clock/clock.go, node/config.go (Config.Clock), endpoint/assembler.go (Config.Clock), node/root.go (buildAggregatorClusters), device/device.go (deviceClock), fabrictest/site.go (Run).
Dispatch and ordering¶
The read loop copies each datagram and hands it on without blocking.
Messages of one secure unicast session are handled one at a time, in
arrival order. The listener keys them by their session id and queues
them, so a Read sent right behind an Invoke sees the Invoke's effect. A
handler that sends and then waits for the peer's answer on the same session
releases its turn first, so the answer is not queued behind it. Examples
are a chunked report waiting for its StatusResponse and the subscription
priming loop. The TCP transport keeps the same contract per connection.
The client stack — a controller's socket and a node's opt-in
Config.Client — keys its datagrams the same way
(message.SessionOrderKey), so a request on a later exchange cannot
overtake the message that finished an earlier one: the BlockAckEof that
completes an OTA download is handled before the ApplyUpdateRequest sent
after it.
Unsecured messages of one initiator are handled in arrival order too. The PASE and CASE handshakes run on session id 0; the listener keys them by the node id of the handshake's initiator (the destination node id of a response, else the source node id of a request), so one initiator's message counters reach its duplicate window in the order they arrived. Messages of different initiators run concurrently.
Everything else runs concurrently: group messages and an unsecured message that names no node id. Concurrent unordered handlers are bounded at 1024. A datagram that arrives when every slot is taken is dropped, and the peer's MRP retransmits it. Per session, at most 256 datagrams queue; beyond that a datagram is dropped too.
Between sessions there is no ordering. Two controllers act on the same server concurrently.
Source: bridge/session_order.go (handleOrderedDatagram, leaveSessionOrder), transport/message/message.go (SessionOrderKey), controller/controller.go (Controller.openNetwork), node/client.go (newClientStack), transport/udp/ordered.go (Listener.ServeOrdered, maxOrderedBacklog), transport/udp/listener.go (maxConcurrentDispatch, Listener.Serve), transport/tcp/doc.go (the package doc).
What a host callback may do¶
The module calls host code from its handler goroutines.
The rule, for every facade callback — OnChanged (typed and
device.Device.OnChanged), OnWrite, Handle<Command> and a
declaration's host ports: it runs inline, on the goroutine of the event
and before the response leaves; the …Async variant (OnChangedAsync)
queues it on the device's own goroutine instead, in order, drained when
the node removes the device or stops. A veto, a handler and a port answer
the request, so they have no queued form: one that may block hands its
work to the host's own goroutine and answers.
Cluster servers (MatterRead, MatterWrite, MatterInvoke). No
dispatcher lock is held while a server is called. A call runs on its
session's turn, so a slow MatterInvoke delays that session's next
message, and other sessions go on. While it runs, the ACK pump sends a
standalone acknowledgement for the request once the standalone-ACK delay
(200 ms) has passed, so the controller does not retransmit. Reads also run on the
subscription engine's report goroutines, at the same time as commands on
other sessions. A server must therefore be safe for concurrent use. The
ctx passed to the server ends when the bridge stops.
OnOff's Sink runs with no lock held that Server.Set or a read
takes. It may confirm through Set, from its own goroutine or another.
Commands, writes and countdown ticks of that server wait behind it.
The other host ports — DeviceEnergyManagement's DemManager hooks,
the media servers' ports, Messages' MessagePresenter, SoilMeasurement's
source — run the same way: with the server's state lock released, so they
may call that server's setters and reads. Commands of the server wait
behind a port that runs, so a port must not issue one; what the command
records after the port returns stands over what the port set meanwhile.
WindowCovering's Mover and MicrowaveOvenControl's Oven run behind the
command queue alike.
node.Config.Observers, and the hooks Node.Observe registers after
them, run synchronously on the event's goroutine. For
fabric events, that is inside the command that caused the event, before
its response is sent, so a blocking observer delays the response.
Node.ObserveAsync queues the same hooks on the node's callback
goroutine instead. An observer returns nothing; its panic is logged.
device.Device.OnChanged callbacks run on the server's own change
notification, with the change's origin (contract.Change.Origin: the
host's Set, a controller's write, a command). Keep them short — the
quickstart only logs — or use OnChangedAsync.
Controller SubscribeRequest.Updated runs on the goroutine that reads
the report, inside the report's exchange. The priming report is delivered
inside Subscribe, before it returns. The reference controller hands each
report to a channel.
client/discovery runs one goroutine per Names that holds all
cache, service and scanner state. User callbacks never run on that loop.
Source: endpoint/dispatcher.go (TopologyDispatcher.Read, Write, Invoke), bridge/session_order.go (leaveSessionOrder), bridge/receive.go, bridge/ackpump.go (owedInboundAck, refreshAckCounter), transport/mrp/ack.go (DefaultStandaloneAckDelay), im/subscription/engine.go (Manager.tick), cluster/onoff/server.go (Sink, Server.Set), node/observers.go (Observers), device/lifecycle.go (OnChanged, OnChangedAsync), device/queue.go, client/interaction/handler.go (Subscriptions.handleReport), client/interaction/subscribe.go (SubscribeRequest.Updated), examples/reference-controller/cli/interact.go (cmdSubscribe), client/discovery/doc.go (the package doc).
Changing the topology¶
Aggregator.Add and Remove reassemble a running node. Each reassembly
takes a fresh snapshot of the set and swaps the new topology in
atomically, so an in-flight request always sees one consistent topology.
Two reassemblies that run at the same time are not ordered: the last one to
finish wins, even when it took its snapshot first. Call Add, Remove
and Forget from one goroutine, or serialise them yourself.
The Snapshotter of a host with its own topology is called at Start and
on every Reassemble, and its result is never cached.
Source: node/aggregator.go (Aggregator.Add, Remove), node/reserve.go (Aggregator.Forget), bridge/bridge.go (Snapshotter, Bridge.Reassemble).
Contexts and shutdown¶
| Call | Context use |
|---|---|
node.New(ctx, cfg) |
bounds the store open and migration, the group load and the store reads. The node's lifetime is its own: a ctx that ends after New returned ends nothing, Stop does |
Node.Start(ctx) |
used for the start-up work (assembly, loading the stored fabrics). A cancelled ctx fails Start |
Node.Run(ctx) |
starts, waits for ctx to end, then stops with a fresh 5-second budget |
Node.Stop(ctx) |
bounds the bridge's wait for its read loop and for the answers to the subscriptions' final reports. It stops the engine and reapers, reports what each subscription owes, closes the sessions with a CloseSession each, withdraws the mDNS records and closes the advertiser |
Stop waits for the read loop and the datagram handlers it dispatched,
the TCP loop with its connection readers and their handler calls, the
handler calls of messages delivered over BLE, the ACK pump, the session re-announce, the BDX responders, the reapers and the
operational-time keeper. The waits for handlers and responders are bounded
by ctx: their context is cancelled first, and one that does not return
— host code that ignores its context — is waited for only until ctx
ends, so a server call can still return after Stop has. Close the
database only after your own servers have returned, or make them tolerate
a closed handle.
A deadline the stack sets for its own work — a store write, an mDNS
publish, a CASE connect, a subscription's re-establishment, Node.Run's
stop budget — runs on the node's clock (clock.WithTimeout): on the system
clock it is context.WithTimeout, under a test's fake clock it expires when
the fake is advanced.
Source: node/node.go (New), node/node.go (Node.Start), node/node.go (Node.Stop), bridge/bridge.go (Bridge.Stop), transport/udp/listener.go (Listener.Serve).