transport — the wire seam (L4)

In one paragraph

transport_t is the seam between the routing plane and one wire technology: send framed bytes (a single buffer or a scatter-gather iovec), install a sink for inbound frames. It never sees TLV semantics — only bytes. Implementations: loopback_channel_t (in-process dev/test), udp_transport_t (localhost/LAN UDP), tcp_transport_t / tcp_server_transport_t (reliable TCP stream, 4-byte u32-LE length-prefix framing — the prefix is transport framing, not part of the TLV), ws_client_transport_t / ws_server_transport_t (the browser↔robot WebSocket keystone, RFC 6455), transport_can (SocketCAN, classic + CAN-FD), quic_transport_t and webtransport_transport_t (the separate libtracer_quic module, msquic-backed).

The seam

A transport accepts a complete frame’s bytes — a FWD frame — and emits them; inbound frames arrive on the installed sink, which may fire on an internal transport thread. Framing below the TLV is the transport’s own business: a datagram kind needs none, a stream kind adds a u32-LE length ++ frame record (core/include/libtracer/transport_tcp.hpp), a CAN kind fragments and reassembles.

The reference catalog describes the same shape — a small callback-based seam, one frame in, one frame out (10-module-catalog.md §Transport ↔ L4). What is an implementation choice rather than a described property is the concurrency: each socket transport owns a receive thread and calls the sink from it, matching how a real socket’s receive loop feeds the router. The seam’s shape is declared implementation-defined (ADR-0013 — v1 scope boundaries); two conforming nodes share the wire format, not this class.

Routing above the seam — which link a frame leaves by, how a return route is grown, how a link is mounted under /net — belongs to the FWD router, described at fwd-router. This page stops at the byte boundary.

Two delivery tiers

The sink comes in two forms and a transport declares which one it honors.

Tier

Installed by

Frame lifetime

Declared by

Borrowed span

set_receiver(fn, ctx)

valid only for the callback

the default

Owning rope

set_rope_receiver(fn, ctx)

refcounted; may be kept, subroped, forwarded

delivers_ropes() returns true

A transport that can hand up owning frames implements the rope-receiver seam (ADR-0042 — refcounted receiver seam, view delivery, generalized to ropes by ADR-0053 — lazy rope-backed decode, view partial-path routing): it overrides delivers_ropes() (core/include/libtracer/transport.hpp:transport_t::delivers_ropes) and delivers each inbound frame as a rope_t of refcounted links over segments drawn from a host-injected mem_backend_t. A contiguous frame is the single-link case; a scattered one — a CAN reassembly group, a fragmented WebSocket message — crosses the seam as the rope it already is, never a flatten copy. Ownership is the whole point: the borrowed span dies when the callback returns, so a receiver that must outlive the callback needs this tier.

There is deliberately no adapter that wraps a borrowed span into a rope; such a rope’s refcounts would lie about lifetime. fwd_router_t::add_child (core/src/fwd_router.cpp:fwd_router_t::add_child) therefore branches on the link’s declared capability and installs exactly one sink — the rope form for an owning link, the span form otherwise (fwd_router.cpp:link.set_rope_receiver(, fwd_router.cpp:link.set_receiver(, and fwd_router.cpp:bus->set_peer_rope_receiver(, fwd_router.cpp:bus->set_peer_receiver( for the peer-named bus equivalent).

Every socket transport in the tree declares the owning tier: UDP (transport_udp.hpp:udp_transport_t::delivers_ropes), TCP client and server (transport_tcp.hpp:tcp_transport_t::delivers_ropes, transport_tcp.hpp:tcp_server_transport_t::delivers_ropes), WebSocket server and client (transport_ws.hpp:ws_server_transport_t::delivers_ropes, transport_ws.hpp:ws_client_transport_t::delivers_ropes), CAN (transport_can.hpp:can_transport_t::delivers_ropes), QUIC (transport_quic.hpp:quic_transport_t::delivers_ropes) and WebTransport (transport_webtransport.hpp:webtransport_transport_t::delivers_ropes). The borrowed-span path is the base-class default and the tier an out-of-tree transport gets for free.

A scattered frame crosses the owning seam as the rope it already is; trailing transport padding is trimmed by shortening the last link, never by flattening.

Closing the bus module out at build time

The peer-named tier is a module, and a node whose links are all point-to-point does not have to carry it. tr::graph::default_config_t::kBusLinks (core/include/libtracer/config.hpp:default_config_t::kBusLinks) is the knob, and since v0.17.0 its default is false — the lean choice (#1670). A node that needs the tier — a peer_named listener, CAN, the ESP-IDF WS server — opts in with an ADR-0068 override fragment, not a -D (ESP-IDF: CONFIG_LIBTRACER_BUS_LINKS=y; PlatformIO: custom_libtracer_bus_links = yes):

// libtracer/config_override.hpp
namespace tr::graph {
struct bus_node_config_t : default_config_t {
    static constexpr bool kBusLinks = true;
};
using config_t = bus_node_config_t;
}  // namespace tr::graph

The routing plane reaches the facet through exactly one door, tr::net::bus_of (core/include/libtracer/transport.hpp:bus_of), and every consumer asks there: the registry’s mount-shape stamp and its two peer-resolution paths, fwd_router_t::add_child’s peer wiring, and the connection vertex’s synthesized peer listing. transport_t::bus() itself is untouched — still a virtual, still nullptr by default — so a transport may still be a bus; what the knob changes is whether anything asks. Measured on rv32 (-Os -fno-exceptions -fno-rtti, rv32imac_zicsr_zifencei/ilp32, GCC 15.2, per-TU .text): −2,078 B of flash (fwd_router −1,400, transport_vertex −678) and ±0 B of .bss, because the tier is code and per-instance state rather than a static table. A LIBTRACER_NET_PLANE=OFF build gains nothing — it never compiled those translation units.

The PROVIDER side of the same fold is the base-class selection described above (stream_server_base_t). It is what makes the saving reach a listener’s own bytes rather than only the routing plane’s code: measured on the esp32c6 full-node profile (-Os -fno-exceptions -fno-rtti, riscv32-esp-elf 14.2.0), a bus-closed build’s tcp_server_transport_t shrinks 208 B → 168 B at rest, −40 B per listener, with a further −568 B of image .text and ±0 B of .bss. With the module carried the listener’s size does not move and the seam costs +80 B .text / +96 B .rodata once, for the forwarding overrides and the two peer-lifecycle hooks.

Asking for a bus on such a build is refused, never quietly served as a flat link:

door

refusal

LIBTRACER_TRANSPORT_CAN=ON

a static_assert in transport_can.cpp — CAN is a bus by construction, so a bus-less CAN build is broken, not smaller

SPEC{name, config{kind=tcp|ws, peer_named=1}} to a LISTEN module’s conn

the factory answers TYPE_MISMATCH — permanent, because no retry grows this build a bus facet — and creates no connection

a directly constructed peer-named slot_server_t

ok() is false, the came-up predicate every caller already checks

httpd_ws_link_t (ESP-IDF)

a static_assert in httpd_ws_link.cpp — it is peer-named by construction; the component’s CONFIG_LIBTRACER_WS_SERVER selects CONFIG_LIBTRACER_BUS_LINKS, so the component never reaches it

A quiet demotion would be the worse outcome, and specifically so: the listener’s own per-frame tier select reads its constructed mode, so a demoted-at-the-router-only server would keep delivering peer-named into a sink the router never installed.

QUIC and WebTransport

Both live in the separate libtracer_quic target, configured by LIBTRACER_WITH_QUIC (core/CMakeLists.txt:option(LIBTRACER_WITH_QUIC "Configure the, default OFF because msquic must be installed). Core itself contains no #ifdef and no msquic reference: the module extends the transport catalog through register_transport_type, registering quic_transport_factory() under kind quic and webtransport_transport_factory() under kind webtransport.

  • quic_transport_t — TLS 1.3, connection migration, one bidirectional stream carrying the same length-prefix framing as TCP. The hosted, secure link; the MCU class keeps UDP and CAN (ADR-0043 — QUIC/WebTransport optional module, msquic Phase A).

  • webtransport_transport_t — WebTransport over HTTP/3, the browser-reachable form of QUIC: a module-private minimal H3/QPACK handshake layer (core/src/wt_h3.hpp, never installed) in front of one WebTransport bidirectional stream carrying the same framing (ADR-0043 Phase B). The browser side is the TypeScript transport-webtransport package (ADR-0031 — direct browser-to-robot binding and WebTransport).

One msquic dependency serves both, because QUIC is the substrate WebTransport requires.

Their TLS material is app-owned: the certificate, key and CA bundle come from the table of tr::net::tls_profile_t the application hands the factory at registration, never from a creation SPEC. A SPEC can at most name one of those profiles (the kind-private tls key) and set the DIAL-side dev opt-out insecure. A SPEC-created dialer verifies its peer’s certificate by default; the key-by-key reference is connection config.

Interface

class transport_t {
    virtual void send(std::span<const std::byte> frame) = 0;
    // Scatter-gather: ship a rope's to_iovec() as one frame, no flatten copy.
    // The default gathers into a temporary; native transports override
    // (sendmsg/writev/RDMA SGE).
    virtual void send(std::span<const std::span<const std::byte>> iov);

    // Two inbound sinks, {fn, ctx} — no type erasure. ctx must outlive delivery.
    using receiver_fn_t      = receiver_slot_t<>::span_fn_t;  // borrowed span
    using rope_receiver_fn_t = receiver_slot_t<>::rope_fn_t;  // owning rope
    void set_receiver(receiver_fn_t fn, void* ctx) noexcept;
    void set_rope_receiver(rope_receiver_fn_t fn, void* ctx) noexcept;
    template <typename F> void set_receiver(F& sink) noexcept;       // lvalue only
    template <typename F> void set_rope_receiver(F& sink) noexcept;  // lvalue only

    virtual bool delivers_ropes() const;                // false by default
    using link_state_fn_t = void (*)(void* ctx, bool up);
    bool set_link_state_notifier(link_state_fn_t fn, void* ctx) noexcept;  // true: went down first
    virtual bus_link_t* bus();                          // nullptr = point-to-point
};

class loopback_channel_t {                          // dev/test transport
    loopback_endpoint_t& a();  loopback_endpoint_t& b();  // each a transport_t
    void shutdown();                                // join recv threads
};

class udp_transport_t : public transport_t {
    udp_transport_t(std::uint16_t bind_port, const std::string& peer_host,
                    std::uint16_t peer_port,
                    mem::mem_backend_t* backend = &mem::heap_backend(),
                    std::size_t max_frame = 0, std::size_t recv_stack = 0);
    // send(span) = one sendto; send(iov) = one sendmsg(iovec) (sendto for one span) — a composite rope
    // in one syscall. Datagrams land in segments from `backend`; exhaustion drops
    // the datagram and ticks dropped_rx. `max_frame` (the universal :settings key,
    // 0 = kDefaultMaxFrame, one MTU's 1,472 B; at most kMaxDatagram) is the largest
    // datagram accepted, and sizes the RX segment — a longer one is refused
    // and ticks malformed_rx instead of being delivered, while the backend can
    // furnish max_frame + 1 bytes (below that it truncates first, #1074).
};

loopback_channel_t wires two endpoints: a frame sent on one is delivered to the other’s receiver, on that endpoint’s receive thread, modeling asynchronous cross-wire delivery. shutdown() joins both receive threads before the registered receivers are destroyed.

The forward hop that feeds a transport

What the router hands send(iov) on a forward hop is not a re-encoded frame: the hop reads a few headers of the inbound frame by offset, builds the shortened headers in small stack buffers, and scatter-gathers those heads with untouched views of the inbound frame. The hop costs 0 heap allocations / 0 bytes, measured by replacing the global operator new/delete with a counting wrapper around exactly one hop (bench_forward_heap, single-threaded, ZEROHEAP_MAX=0 enforced in perf.yml; ADR-0038 — net-plane performance model).

        flowchart LR
    IN["inbound frame bytes"] --> PEEK["offset peek:<br/>first dst NAME"]
    PEEK --> DEMUX["child_registry_t<br/>NAME → transport"]
    DEMUX --> SG["stack-built heads<br/>+ untouched frame views"]
    SG -->|"send(iov) — one syscall"| T(["transport_t"])
    

Two nodes over a wire

        flowchart LR
    FA["fwd_router A"] -->|send| EA["endpoint a"]
    EA -->|enqueue| QB[("inbox B")]
    QB -->|recv thread| EB["endpoint b"]
    EB -->|receiver| FB["fwd_router B"]
    FB -->|FWD REPLY send| EB2["endpoint b"]
    EB2 -->|enqueue| QA[("inbox A")]
    QA -->|recv thread| EA2["endpoint a"]
    EA2 -->|receiver| FA
    classDef m fill:#fef9c3,stroke:#92400e
    class EA,EB,EA2,EB2 m
    

Consequences

  • One seam, many wires — the router and the whole stack above it are transport-agnostic; a new socket transport plugs in with no change upstream.

  • Deterministic testing — the loopback exercises the full encode → FWD-route → decode path with no sockets, so forward and reply behavior is unit-testable and benchable.

  • Bytes only — a transport cannot accidentally depend on graph semantics, because no graph type crosses the seam.

  • Capability, not configuration — the delivery tier is a property the transport declares, so a link that cannot honor owning delivery can never be asked to.

Pitfalls

  • A borrowed span dies at the callback’s return. Storing the span, or a view_t built over it, hands the router a dangling window on the next receive. A receiver that keeps the frame installs the rope sink and requires delivers_ropes().

  • ctx must outlive every possible delivery. The receive thread is already live when the connection opens, so a sink whose context is a local — or whose context is destroyed before shutdown() — races a frame already in flight. Both sinks and both notifiers must be installed before frames flow.

  • “Before frames flow” is not free on a DIAL link. A transport that connects and spawns its receive thread in one constructor leaves no such window: the peer’s push is provoked by our own connect, so its first message can be decoded before the owner’s next statement runs, and an empty sink drops it with no counter moving (#1025). start_receiving() is the second phase that opens the window — a no-op default, so an owner calls it unconditionally as its last wiring step; ws_client_transport_t and tcp_transport_t DIAL links always defer to it (#1045, #2247): the owner installs its receivers, then calls start_receiving(). The ESP-IDF-native WS client always defers too, in its own shape: its recv thread does the dialling, so the first dial waits behind the start_receiving() latch (ADR-0081’s defer-the-dial arm, #1102, #2249) — one-shot, since reconnects happen only on an already-armed link. webtransport’s DIAL side always defers as well (#1101, #2249) — it owns no receive thread to withhold, so per ADR-0081 §2 the hold is msquic’s per-stream receive window: the frame channel’s RECEIVE events consume zero bytes and start_receiving() re-enables them, while the H3/QPACK state machine keeps consuming its own streams throughout. Nothing is buffered library-side. quic still takes the no-op default, with the LISTEN-side gates its own follow-up (#1114). udp has no DIAL constructor of this shape — it binds an ephemeral port, never ::connects and sends nothing in the constructor, so no peer can learn its source port to push to.

  • On a bus the window needs no provocation at all. can has no dial to defer and no peer flow-control window to hold bytes in, and its RX callback cannot be withheld without starving the liveness bookkeeping it drives (last_heard, the pending/reassembly sweeps). Any bystander traffic already on the wire lands in the window, so the answer is ADR-0081 §4’s other arm — drop, and tick can_transport_t::dropped_presink() (#1103).

  • The callable sugar binds by address. set_receiver(F& sink) and set_rope_receiver(F& sink) take an lvalue; a temporary lambda does not compile, and a callable destroyed early dangles exactly like a stale ctx.

  • Overriding send(iov) is not optional for a scatter-gather wire. The base implementation gathers into a temporary buffer and, when that allocation fails, drops the frame rather than aborting (transport.hpp:transport_t::send(std::span<const std::span<const std::byte>> iov)). A transport with a native sendmsg/writev that does not override it silently pays a copy per forward hop and inherits a drop path it did not intend.

  • The egress gather draws from the link’s own injected store. That temporary — and the iov_table_t overflow block the socket transports’ ::iovec tables grow into — comes from transport_t::egress_source(), a mem::block_source_t the transport factory wires per link (register_builtin_transports’ egress_src argument, fed by transport_vertex_t’s), defaulting to the process net sub-pool (#1777). Both the entry count and the byte count are the sending peer’s choice, so sizing that store is what bounds a node’s egress allocation — ADR-0079’s “bounded node is a property the deployer injects”. Exhaustion is unchanged: the frame is dropped and counted, never truncated. A store whose concurrency contract is single-threaded belongs to a link only one thread sends on.

  • The link-down notifier is a routing seam, not a log hook. It re-enters the routing plane to evict the departed link’s subscriber edges, so it must be fired with no internal transport locks held; a connectionless kind simply never fires it.

Shared scaffolding

Three pieces are shared by every transport rather than reimplemented in each, and they are the reason a new binding is small.

  • receiver_slot_t is the one home of the delivery-tier mechanism: the guarded storage for a receiver pair, the per-frame snapshot, and the owning-rope-versus-borrowed-span tier select. Its callbacks are plain {function pointer, context} pairs, so taking a snapshot on the receive path is a trivial copy under an uncontended lock rather than a heap allocation. Its Tag... pack is how a bus link prepends the sending peer’s HANDLE to both sinks.

  • posix_endpoint_t is the receive-thread scaffold every POSIX socket transport shares: the stop flag, the thread lifecycle, and the bounded poll-and-recheck idioms that let a blocking socket loop notice a clean shutdown. stream_endpoint_t adds what only the stream transports need — the peer-fd atomic, the write mutex, and the teardown-under-write-lock ordering that keeps a concurrent send from writing to a reused descriptor. UDP keeps its datagram shape and uses only the base. slot_server_t is one tier further up, for the MULTI-peer stream servers: it owns the slot vector, the accept/poll/ teardown machinery and the peer query trio, so tcp_server_transport_t and ws_server_transport_t differ only in their framing and handshake — the two hooks it dispatches into them. The ADR-0044 bus FACET is a tier below that again — bus_slot_server_t carries it, flat_slot_server_t does not, and stream_server_base_t picks between them by tr::net::kBusLinks — so a bus-less build’s listener does not contain one.

  • register_builtin_transports is how a node’s transport catalog gets populated. Each register_*_transport lives in its own translation unit, compiled only when that transport is enabled, so a build that drops a transport leaves neither a compiled factory nor a dangling call to it. No preprocessor macro selects a transport: selection is which translation units get compiled.

  • egress_t is the one egress module every POSIX stream link and the ESP-IDF WebSocket client adapt (ADR-0087 §2, #2144, #2277). A send builds at most one shared, refcounted frame (egress_frame_t: the copied head plus a kept value by reference), and a fan-out hands the same frame to every peer. Each (peer, vertex) pair has its own ring of frame references, shaped from the local vertex’s retention depth carried on each send as a graph::delivery_lane_t: depth 1 is a SAMPLE, so a newer frame overwrites the waiting one; depth N is a STREAM, and a full ring applies that vertex’s pressure arm (best-effort sheds the oldest, reliable refuses the newest). A frame from no vertex rides the peer’s control lane (kEgressControlDepth, best-effort). Lanes leave round-robin, FIFO inside each; a ring is drawn from the link’s source when its vertex’s first frame has to wait and goes back when its last one leaves, so an idle peer holds no ring. A sender that finds the peer idle takes the writer role by try-lock and writes its own record from its own memory, taking no mutex at all (#2145): the role is one compare-and-swap and “nothing waits” one atomic read. One that finds a write in flight takes that peer’s own lane lock once (a bit of its role byte, #2310) to leave its reference, and returns, so a stalled peer never delays another peer’s send and no two peers’ sends share a lock. A write the socket cuts short keeps its frame and offset and resumes when the socket reports writability or on the next send. An offer past a full STREAM lane whose turn moved no byte is counted as a stall, and never judged (#2899): the writer never waits and a full lane sheds counted frames, so a send burst against a slow reader keeps the link up. A peer that stopped reading is closed by the application’s liveness check (sweep(now), #2198), and only a failed write that cut a frame mid-way condemns the peer at once. A SAMPLE lane never stalls: its overwrite is its contract. The module reads no clock.

API reference

The seams

class transport_t

A point-to-point (or bus-facet-exposing) transport link: the byte seam between the routing plane and one wire (ws/tcp/udp/quic/CAN).

The router sends complete TLV frames via send and receives them through an installed sink (set_receiver for borrowed spans, or set_rope_receiver for owning refcounted rope frames when delivers_ropes is true). A multi-peer bus link additionally exposes a bus_link_t facet via bus.

Subclassed by tr::net::can_transport_t, tr::net::loopback_endpoint_t, tr::net::noise_link_t< B, Host, Carrier >, tr::net::quic_transport_t, tr::net::self_heal_link_t, tr::net::slot_server_t, tr::net::tcp_transport_t, tr::net::udp_transport_t, tr::net::webtransport_transport_t, tr::net::ws_client_transport_t

Public Types

using receiver_fn_t = receiver_slot_t<>::span_fn_t

The borrowed-span inbound sink fn: (ctx, frame) — the frame is valid only for the callback.

using rope_receiver_fn_t = receiver_slot_t<>::rope_fn_t

The OWNING inbound sink fn (ADR-0042, generalized to ropes per ADR-0053): (ctx, frame) — each frame is a rope_t of refcounted links the receiver may keep, subrope, or forward — a contiguous frame is the trivial single-link case (“delivers views” and “delivers ropes” are ONE capability, not two tiers — CONTEXT.md §ingress rope delivery).

The link-state notifier fn: (ctx, up) — the link carries its own identity via ctx, and up says which way its one connection went.

Public Functions

virtual void send(std::span<const std::byte> frame) = 0

Emit one frame (a complete TLV’s bytes) onto the wire.

  • **void is deliberate, and stays.** A returned status here would be a promise the plane cannot keep: on every real link the frame is queued and written later, on another task, so “sent” at this call site can only ever mean “accepted”, which is what a void already says. Callers MUST NOT read a successful return as delivery.

  • A link that drops a frame MUST count it in drop_stats — dropped_tx for a frame the caller believed sent, dropped_rx / malformed_rx on the ingress side. That counter is the ONLY feedback this plane offers, which is exactly why it is mandatory rather than a courtesy: an uncounted drop is invisible to a deployment, and core/STYLE.md §Introspection forbids the silent loss it hides.

  • The counter is how a monitor closes the loop. The tally is wire-readable as read <any-vertex>:stats.link.<child> (RFC-0010 Amendment 2), so a supervisor polls it and reacts, in place of the per-frame refusal v1 has no room for.

The transport plane is BEST-EFFORT by contract, and a drop MUST be counted.

This is the one place in libtracer where the refuse-by-value law (docs/reference/22-backpressure-and-sizing.md §1, the third reading rule) does not apply, and the reason is not an oversight: there is no wire carrier for backpressure in v1 (the per-edge credit window is parked as the v2 escalation, RFC-0025 §4.6.1 clause 7). A link that could refuse by value would have nobody to refuse to — the caller is a forwarding hop with a frame it cannot un-receive, and the peer cannot be told to slow down. So the contract is:

Note

Re-opening this is scoped to M5

(a real socket transport), where a link that owns its own socket buffer has something to push back WITH. Until then, “counted

shed” IS the transport contract.

inline virtual transport_drop_stats_t drop_stats() const noexcept

This link’s shed-frame counters — the interface-level observability seam.

The DEFAULT is all-zero, which is the honest answer for a link that counts nothing (an in-process or test stub): “no drops observed here”, never a fabricated number. A counting transport overrides it with its drop_tally_t’s snapshot (#932, #2482); a per-peer facade, with its owner’s.

inline virtual void kind_stats(graph::stats_block_t &out) const noexcept

Append this kind’s own nouns to its :stats.link.<child> block, after the three universal ones drop_stats answers.

A kind with counters of its own beyond the shed-frame triple publishes them here: the Noise link’s ten noise_* nouns (RFC-0033 §5.11) are the first. Readers already ignore unknown names (RFC-0010 Amendment 1 §Compatibility), so a kind that adds nouns breaks no reader. The DEFAULT adds nothing. Called only from the cold :stats read path, on any thread, and that includes this link’s own receive callback when the read arrived over it: a kind must not hold its own lock across a delivery. Same snapshot rule as drop_stats.

Parameters:

out – The block being sampled; nouns must be literals (graph::stats_counter_t).

inline virtual void send(std::span<const std::span<const std::byte>> iov)

Scatter-gather send: emit the gathered spans as ONE frame, no flatten copy.

Hand a rope’s to_iovec() straight to the wire. The default gathers into a temporary and calls send(std::span<const std::byte>); transports with native scatter-gather (sendmsg/writev/RDMA SGE) override this to avoid the copy.

**The same best-effort contract as send(std::span<const std::byte>)**: void is deliberate, and a gather this overload cannot complete is DROPPED and COUNTED in drop_stats (dropped_tx) — never truncated, and never silently lost. The default body below is where that rule is enforced for every transport that does not override it.

Parameters:

iov – The spans to emit, in order, as a single frame.

inline virtual void send(std::span<const std::span<const std::byte>> head, const graph::value_t &value, const graph::delivery_lane_t &lane)

Retained send (RFC-0028 §6.9, §8.2): emit head followed by value's bytes as ONE frame, where a link that writes LATER keeps the value by reference instead of gathering a copy of it.

The egress half of the lean value path. A remote delivery is a small head (the FWD header, the op, the return route) in front of a published value; the head is the caller’s and short-lived, the value is a refcounted block. A link that writes in-call (writev under its write lock) needs neither kept, and the DEFAULT below is exactly that: it lowers to send(std::span<const std::span<const std::byte>>) over head ++ value.links(), through an iov table on the stack. A link that QUEUES the frame and writes it from another thread overrides this: it copies the head (header-sized) into its queue slot and RETAINS the value (value_ref_t::keep — one refcount for a published block), so the payload is written from the block it was published in and never gathered. That is the difference between a queued fan-out to K peers costing K payload copies and costing K refcounts.

Same best-effort contract as send(std::span<const std::byte>): void, and a frame the link cannot carry (the iov table’s overflow refused, the value could not be kept, the queue is full) is dropped, never truncated — and counted in drop_stats by every link that counts, which is every link that overrides this.

Warning

An overriding link owns the one hazard the queued form adds (RFC-0028 §9 item 6): the frame’s bytes now leave in several writes from a queue shared with every other frame on the socket, so a partial write MUST end the frame’s stream (close the peer), never let another frame’s bytes follow it.

Parameters:
  • head – The frame’s leading bytes, in order. Borrowed for the call only.

  • value – The payload that completes the frame. Borrowed for the call; a link that writes later keeps it through value_ref_t::keep.

  • lane – The vertex the value comes from and the shape of the per-peer ring it waits in (ADR-0087 §2, #2144): a link that queues per peer keeps one ring per lane, so one vertex’s backlog never displaces another’s. A link that writes in-call ignores it, as the default below does.

inline virtual void send_to(std::uint64_t to, std::span<const std::span<const std::byte>> head, const graph::value_t &value, const graph::delivery_lane_t &lane)

The retained send to the session to names (#2923): a subscription push to a session, which reaches that session and no other.

to is the session’s handle as peer_handle_t::bits(), read off the push edge. The DEFAULT ignores it and calls the retained send, which is right for a link that is one session. A link’s per-session endpoint checks it where the frame enters the session’s egress, and drops and counts the frame (dropped_tx) when another session has taken the slot since. 0 sends to whichever session holds the slot.

inline mem::block_source_t &egress_source() const noexcept

The EGRESS store this link’s per-send gather allocations draw from (ADR-0079’s net-plane failable store, #873 family 1).

Every allocation an outbound frame provokes on this link — the base send(std::span<const std::span<const std::byte>>) gather temporary above, and the tr::net::iov_table_t overflow block of the socket transports that build a gather table — is drawn from HERE rather than from the process-wide mem::heap_source(). The entry count and the byte count are both the SENDING peer’s choice (a rope’s link count x its region count), so this is the seam that makes “bounded node” a property the deployer injects (ADR-0079 §Decision 4) instead of one the library fixes: size the store and the egress path is bounded by it, with exhaustion answered the way it already is — the frame is DROPPED and counted, never truncated and never abort().

The default is the process net sub-pool (#1777): unbounded, as a link nothing was wired into always was.

inline void set_egress_source(mem::block_source_t &src) noexcept

Wire this link’s egress store — the transport-factory injection point.

Same contract as the receiver slots: call it during bring-up, BEFORE frames flow. The built-in factories apply it to every socket they construct (the egress_src argument of register_builtin_transports), which is how a deployer choosing ADR-0079’s MID composition hands the whole net plane its own store, or its NARROW fan gives each link’s own thread a contention-free one. src must outlive this transport.

Warning

A link’s egress store is touched by EVERY thread that sends on that link, so src must declare a concurrency contract covering them (block_source_t §”each source declares its own”). heap_source_t does; a pool_source_t<tr::no_guard_t> or a bump_source_t does NOT, and belongs to a link only one thread ever sends on — which is the ADR-0079 NARROW shape, and the reason it is per-link rather than one node-wide store. None of the six egress sites holds a transport lock across the allocation, so a locking src introduces no lock-ordering obligation here (#1049).

Warning

This setter reaches the allocations a send makes THROUGH this base — it does not re-seat a concrete link’s CONSTRUCTION-BOUND buffers. A mem::block_array_t member takes its source in its own constructor and keeps it for life, so a link that owns one takes the store as a CONSTRUCTOR argument and applies it to both halves there (#873). Wiring such a link only through this setter would leave that buffer on whatever source it was built with.

inline void set_receiver(receiver_fn_t fn, void *ctx) noexcept

Register the borrowed-span sink for inbound frames (the bridge’s ingest).

Must be set before frames flow; delivery may occur on an internal transport thread. The delivered span is valid only for the callback — a receiver that needs to keep the frame uses set_rope_receiver instead.

Parameters:
  • fn – The inbound frame sink; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible delivery.

template<typename F>
inline void set_receiver(F &sink) noexcept

Register the borrowed-span sink from a caller-owned callable.

Zero-erasure sugar over the {fn, ctx} form: sink is bound by address (lvalues only — a temporary would dangle) and MUST outlive every delivery.

inline void set_rope_receiver(rope_receiver_fn_t fn, void *ctx) noexcept

Register the optional OWNING inbound sink (the ADR-0042 receiver seam).

A transport that can hand up owning frames (its delivers_ropes returns true) delivers each inbound frame to the sink as a view::rope_t whose links are refcounted views over segments drawn from a host-injected mem_backend_t — the receiver may pin, subrope, or forward the frame beyond the callback (unlike the borrowed span of set_receiver, which dies when the callback returns). A contiguous frame arrives as a single-link rope; a scattered one (a CAN reassembly group, fragmented WS message) crosses this seam AS THE ROPE IT ALREADY IS — reassembly is chaining views, never a memcpy (ADR-0053 §5). Must be set before frames flow; delivery may occur on an internal transport thread.

A span-only transport never dispatches to this sink, honestly — there is NO adapter that wraps a borrowed span into a rope whose refcounts would lie about lifetime (ADR-0042 §1). A transport that honors this seam MUST override delivers_ropes to return true, so fwd_router_t::add_child installs the receiver matching the link’s capability.

Parameters:
  • fn – The owning frame sink; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible delivery.

template<typename F>
inline void set_rope_receiver(F &sink) noexcept

Register the OWNING sink from a caller-owned callable.

Zero-erasure sugar over the {fn, ctx} form: sink is bound by address (lvalues only — a temporary would dangle) and MUST outlive every delivery.

inline virtual bool start_receiving()

Begin delivering inbound frames — the second half of a two-phase bring-up.

Every sink above says “must be set before frames flow”, and for a transport whose receive thread starts inside its own constructor that contract is UNSATISFIABLE from the outside: the thread is already draining the socket while the owner is still installing its sinks, so a frame the peer pushes the instant the connection comes up is decoded into an empty slot and dropped — silently, with no counter moving (#1025). A DIAL connection is where that bites, because the peer’s push is triggered by our own connect. This is the window: construct (dial + handshake), install the sinks, then call this.

IDEMPOTENT, and the DEFAULT IS A NO-OP — a transport that is already receiving from its constructor has nothing left to do — so an owner may call it unconditionally on any link. transport_vertex_t::make_connection does exactly that, once the link is registered and fwd_router_t::add_child has installed its receiver.

Returns:

false when the receive could not start (#2288: its thread’s stack or record was refused by link_memory_t::stack, or the platform refused the thread). The link is then dead: its connection is closed and ok() is false, and no link-down is fired from this call, because the owner may hold its own locks here. The owner takes the failure as a refused bring-up and rolls the link back. A repeat call answers what the first did not change: true.

inline virtual void shut_down()

Stop for good, short of being destroyed: the counterpart of start_receiving.

It waits for nothing, on every thread (#2813): it stops delivery, shuts the link’s descriptors down (shutdown, never close) and stops the link’s driver, then returns. It joins no thread and waits out no callback, so an owner may call it under a lock that a callback takes; at most it waits out a sender’s one nonblocking write. (A self-heal link still joins its worker off a callback thread, until #2815 removes that worker.) No new inbound frame starts delivery once it returns; a callback already in flight may still finish, and does not put the link back on its wait. A connection’s peer sees the close then, not at the destructor. The destructor is the one join and the one close: it waits out that callback, joins the link’s threads, closes its descriptors and frees, and it runs off every callback thread. Until then the object stays valid and every call on it stays safe, and a send never waits on it: it is shed or counted as a drop, except on a link that keeps its socket or bus until destruction, where it may still leave (see each override). That is the point: an owner that removes a link while a forward that looked it up may still be on its way into it shuts it down at removal and destroys it later, where no such call can remain. transport_vertex_t does that, destroying an owned link at the graph’s next collect(), and its own destructor runs one, so the links it removes are joined before it returns; a link that owns a thread holds its stack and its descriptors until then.

IDEMPOTENT, and safe to follow with the destructor. The DEFAULT IS A NO-OP, which is right for a link with no thread and no descriptor of its own; a link that has either overrides it.

inline virtual std::uint64_t sweep(std::uint64_t now, std::uint64_t deadline)

The application’s clock reached now (#2481): run every deadline it passed and answer the next one.

The one seam through which a link learns time; transport_vertex_t::sweep calls it on every connection’s link, and the application calls it directly on a link it wired by hand (one attached only to the router). What runs is the kind’s own:

  • Frozen peers (#2198). A peer OWES bytes in a direction where something waits on it: a frame of ours it has not taken (TX), or a frame or handshake of its own it has begun and not finished (RX, where the link tracks one). A peer that owes nothing is idle, and an idle peer is never closed here. The link records, per peer, the now of the last call that found it moving or owing nothing; a call that finds it owing in a direction with no byte moved since the previous call, and recorded before deadline, closes it as a remote hangup would and counts the close in the kind’s own counter (sweep_t::frozen).

  • Other windows. A kind with a window of its own (an auth handshake, a Noise retry or attempt) runs it here too, against deadline or its own configured spans.

libtracer reads no clock and runs no timer for this: now and deadline are the application’s, in whatever monotonic unit it picks; a kind’s configured spans (a Noise deadline, a self-heal backoff) are read in that same unit, so a node with self-heal links passes now in milliseconds, the unit of their keys. The return value tells it when to call next, so it sleeps until then with no idle wakeup; a link that later starts owing (a send, a new peer) can be due earlier, so an application that wants that bounded also calls after such events or on a cadence of its own. A link whose application never calls this runs no window and closes no frozen peer; a self-heal link then makes the one attempt the loss starts, and after that retries only on an op or an acquire, never in the background (#2304). Calls must not overlap each other on one link; they may race the link’s own threads.

The DEFAULT runs nothing and answers 0, which is right for a link with no per-peer connection and no window (an in-process link, a datagram link).

Parameters:
  • now – The application’s clock, now.

  • deadline – The oldest progress the application accepts (at most now).

Returns:

The earliest time, in now's units, at which a call has work; 0 when none.

inline virtual bool delivers_ropes() const

The owning-delivery capability (ADR-0042 §1): true iff this transport honors set_rope_receiver by delivering refcounted rope frames.

Liveness: true while this link can still carry frames (#1059).

The uniform PULL-side liveness query, the poll twin of set_link_state_notifier’s push — an owner can ask any link the same question. It is deliberately NOT the concrete types’ ok(): ok() is the CONSTRUCTED predicate (did construction succeed — the bind, the connect, or for a QUIC or WebTransport dial only the start of its handshake, #2306), answered once, right after construction (the make_checked gate), and it never reverts; THIS is the runtime state, set when the connection comes up and cleared by the transport’s own teardown path when its one connection dies. The two diverge: a QUIC dial is ok() before it is up, and after a teardown ok() stays true while link_up() answers false.

The default is TRUE: a connectionless (UDP) or bus (CAN) kind has no closure concept — its link is as up as it ever is — and a multi-peer server outlives any one peer. Connection-oriented transports override it. Implementations read a relaxed atomic (or state that is already atomic): this is a hint, never a synchronisation point, and deliberately carries no is-always-lock-free assertion (one target is an rv32 core without the A extension).

inline virtual peer_handle_t inbound_peer() const noexcept

The peer HANDLE of the frame this link is delivering RIGHT NOW — the WHO seam (#375 Part 2), answerable at either setting of peer_named (ADR-0082).

The bus seam already tags each frame with its peer, so a peer-named link’s consumers never need this. A FLAT link has no such seam by design — one routing identity for every peer it carries — and ADR-0082 is explicit that the two claims are independent: a subject must be reachable at peer_named=false or the decouple is not real. This is the door that makes it reachable WITHOUT the addressing facet: the link states which peer the in-flight frame came from, and nothing about where that peer sits in the graph.

Warning

Valid ONLY for the duration of a receive callback, read on the thread that is running it. Outside one the answer is unspecified (implementations return the last delivery’s handle or a default one); it is never a query about link state.

Returns:

The in-flight frame’s peer, or a default-constructed (not peer_handle_t::valid) handle when this kind has no per-peer identity — the DEFAULT, so a dialer, a datagram kind and every custom transport keep today’s behaviour: the subject falls back to the inbound link’s own name.

inline virtual std::uint64_t inbound_reply_to() const noexcept

Where a reply to the frame this link is delivering RIGHT NOW goes back to: an opaque 64-bit token for send_to (#2911).

A link that carries several sessions answers a request to the session that sent it, not to all of them. The DEFAULT is inbound_peer’s handle as one integer, which is the session on a stream listener and 0 (the link itself) on a link with no per-peer identity. A UDP listener answers the datagram’s source instead. Valid on the same terms as inbound_peer, that is only inside a receive callback, on the thread running it.

inline virtual void send_to(std::uint64_t reply_to, std::span<const std::span<const std::byte>> iov)

Send iov as one frame to the session reply_to names (#2911): the reply to a request, which goes to the session that asked.

reply_to is a token inbound_reply_to answered while the request was delivered. The DEFAULT ignores it and calls send, which is right for a link that is one session. A link that carries several sends to that session alone, and drops and counts the frame (dropped_tx) when that session has gone, so a reply never reaches another session.

inline virtual read_tally_t *inbound_tally() noexcept

The READ tally of the session whose frame this link is delivering RIGHT NOW (#2774), or null when the link itself is the session.

The READ budget’s seam, shaped like inbound_peer and valid on the same terms: only inside a receive callback, on the thread running it. A link that carries several sessions (a stream server’s slots) answers with the delivering session’s tally; the router then counts that READ in it. Null, the DEFAULT, makes the router count the READ against the link’s registration. Asked only by a build whose budget is on.

inline virtual std::string_view peer_subject(peer_handle_t peer, std::span<char> scratch) const

The SUBJECT token of the peer peer names — who wrote this, never where (ADR-0082 §Decision 1).

Called at the resolve TERMINUS, once per locally-terminating operation, to derive the ACL caller context (ADR-0018’s pluggable subject token) and the graph::write_ctx_t a HANDLER sees. It is deliberately NOT bus_link_t::peer_name: that is an ADDRESSING answer gated on the bus facet, and this must answer on a FLAT link too. A kind whose two answers coincide — the stream servers, whose subject is the same p<slot>~<gen> session token their peer name is — implements both from one place.

Warning

The token attests to NOTHING about the far end on its own: it is minted by this node’s own transport at accept, exactly as ADR-0082 §Guidance warns. An authenticated subject is the identity-layer’s job (ADR-0045); this is the per-writer discriminator the ACL evaluates until one exists.

Parameters:
  • peer – The handle to resolve — typically inbound_peer’s answer.

  • scratch – Caller storage the token may be formatted into, at least kPeerNameChars bytes. The returned view points either into scratch or at storage that outlives the call.

Return values:

{} – peer is not peer_handle_t::valid, or this kind mints no per-peer subject — the DEFAULT, on which the terminus falls back to the inbound link’s own name, i.e. exactly the pre-#375 caller context.

Register the link-state notifier — the point-to-point half of the link-teardown eviction seam (RFC-0009 §D extended to peer departure), and the one door a link reports its connection’s ups and downs through.

The transport invokes it (possibly on an internal transport thread) with up = false when its ONE connection dies — remote hangup, protocol CLOSE, or a fatal receive error — and with up = true when that connection comes up after construction. A notifier that only evicts returns at once on up = true: no transport fires an up yet, and a receiver that does not care about ups costs one test for it. fwd_router_t::add_child installs a notifier that evicts the child’s subscriber edges under the child’s registered NAME (fwd_router_t::link_down) on a down. Must be set before frames flow, like the receivers; a connectionless kind (UDP) has no closure concept and never fires it. Fire with no internal transport locks held — the notifier re-enters the routing plane, which takes graph locks.

A down that comes before any notifier is installed is not lost (#2306): the link keeps it, and this call reports it, so the installer runs its notifier once itself — after it lets its own locks go, which this call cannot know. The router does so through notify_down, which now finds its notifier installed. A QUIC dial that fails its handshake before the router installs its notifier is the case. An up before the install is not kept: an installer that needs it reads link_up after this call returns, or an up that came in between is lost.

Parameters:
  • fn – The notifier; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible notification.

Returns:

True iff the link went down before this install: fn was not called for it, and the caller calls it once, with its own locks released.

inline virtual bus_link_t *bus()

The multi-peer (bus) capability (ADR-0044): non-null iff this link reaches many peers and exposes them via bus_link_t.

A point-to-point transport keeps the default nullptr; a bus transport (the CAN binding) returns its own bus_link_t facet, which the router and the connection vertex consult for peer resolution and peer enumeration.

Protected Functions

~transport_t() = default

Destroyed only as the class it is, never through this base.

Protected and non-virtual (#2022). The one owner of a link through this base is tr::mem::poly_ptr_t (a factory’s transport_ptr_t), and it records the concrete destructor, so nothing here needs a virtual one. A virtual one would emit a deleting destructor naming operator delete in every object that emits a link’s vtable, on a build that must name no heap. Own a link as its concrete type, or through tr::mem::make_poly; std::unique_ptr<transport_t> no longer compiles.

inline void notify_down() const

Fire the link-state notifier with up = false — see set_link_state_notifier for the calling discipline. With none installed the fire is kept for the next install.

inline void notify_up() const

Fire the link-state notifier with up = true, when the link’s one connection comes up after construction. With none installed the fire is dropped: an installer reads link_up after its install, or this up is lost.

Protected Attributes

receiver_slot_t rx_

The delivery-tier slot (the ONE tier-select mechanism, ADR-0042 / ADR-0053): adapters dispatch inbound frames through it — rx_.deliver(view) for owning frames, rx_.deliver_borrowed(span) for borrowed ones — and key receive-buffer strategy off rx_.has_rope().

Protected Static Functions

static inline void lower_retained(mem::block_source_t &src, std::span<const std::span<const std::byte>> head, const graph::value_t &value, function_ref_t<void(std::span<const std::span<const std::byte>>)> sink)

Lay head ++ value.links() out as one gathered frame and hand it to sink: the copy path of a retained send, shared by the default and by a link whose own table is too narrow for the value.

The #1620 (c) table: a delivery’s head is a handful of spans and a value is one or two links, so the stack array holds the common frame and the overflow block (from src) is the exception, not a per-send allocation. Overflow refused: the frame is dropped exactly as the base gather drops a refused temporary, and sink is not called.

struct sweep_t

One pass of the application’s clock over a link (#2481, transport_t::sweep): the now and deadline it was given, and the earliest next-due time it found.

Kind-neutral: a kind builds one per transport_t::sweep call, judges each peer through frozen, adds any deadline of its own through due, and returns next.

Public Functions

inline constexpr void due(std::uint64_t at) noexcept

Fold at into next, the earliest wins; 0 (nothing due) is ignored.

inline constexpr bool frozen(bool owing, bool stuck, std::uint64_t &since) noexcept

One verdict of the liveness check (#2198), the rule every kind applies per peer.

A peer that owes bytes and is kept is due again one window (now - deadline) after its record: the first now at which, with the same window, it can be judged frozen. A peer that owes nothing adds nothing, and neither does one this verdict closes.

Parameters:
  • owing – The peer owes a direction progress (a frame of ours it has not taken, or one of its own it has begun and not finished).

  • stuck – It owed a direction progress, and that direction moved no byte since the previous check.

  • since – The peer’s record: the now of the last check that found it moving or owing nothing. A peer that is not stuck is stamped now here.

Returns:

True iff the peer is to be closed. The caller re-stamps since once it has.

Public Members

std::uint64_t now = 0

The application’s clock reading, as passed to the seam.

std::uint64_t deadline = 0

The oldest record that still counts as alive (at most now).

std::uint64_t next = 0

The earliest next-due time found so far, 0 when none.

struct transport_drop_stats_t

One transport’s shed-frame counters, as a generic transport_t* holder can read them (#932).

Before #932 each transport counted some of this behind its own concrete accessors, which a consumer that holds only the interface could not call — so swapping tcp for ws or CAN silently lost all drop observability. This is the ONE shape they all answer with, and since #2482 the only one: a counting link keeps its counters in a drop_tally_t and answers with its snapshot. A transport that does not count a given class leaves it zero. Named drop_stats, not stats: a platform link may already publish a RICHER, kind-specific stats block of its own (httpd_ws_link_t::stats()), and this seam is only the shed-frame subset every kind can answer.

Monotonic since construction, sampled without synchronization: the three fields are read one relaxed load at a time, so a snapshot is eventually-consistent, not an atomic instant across counters.

Public Members

std::uint64_t dropped_rx = 0

Inbound frames shed rather than delivered — backend exhausted, or the frame is undeliverable through the injected resources (backpressure).

std::uint64_t malformed_rx = 0

Inbound frames refused as protocol-malformed; for a stream transport this is also the teardown reason (a desynced stream cannot be re-framed).

std::uint64_t dropped_tx = 0

Outbound frames the caller believed sent that never reached the wire — oversize for the peer’s cap, no peer/dead socket, or a refused gather.

template<drop_classes_t Classes = drop_classes_t{}>
class drop_tally_t

A link’s shed-frame counters: the storage behind transport_t::drop_stats (#2482).

A counting link embeds one and answers transport_t::drop_stats with snapshot. It is a member of the link, never of the transport_t base: a per-peer facade counts nothing of its own, and reports its owner’s tally instead.

Each counter is a relaxed word-wide atomic (core/STYLE.md §Introspection, counting doctrine rules 1 and 5), stepped on the drop arm only. A class Classes leaves out has no storage, cannot be counted (the count operation does not exist), and reads zero in the snapshot. Sampled per the snapshot-coherence clause of core/STYLE.md §Introspection.

With drop_classes_t::dropped_tx_cause, an outbound drop is counted together with its cause, and the last one is kept (one relaxed byte store beside the count), read through dropped_tx_cause rather than the snapshot.

Template Parameters:

Classes – The classes this link can drop; the three counters by default, no cause.

Public Functions

inline void count_dropped_rx(std::size_t n = 1) noexcept

Count n inbound frames shed rather than delivered.

inline void count_malformed_rx(std::size_t n = 1) noexcept

Count n inbound frames refused as protocol-malformed.

inline void count_dropped_tx(std::size_t n = 1) noexcept

Count n outbound frames that never reached the wire.

inline void count_dropped_tx(std::size_t n, drop_cause_t cause) noexcept

Count n outbound frames that never reached the wire, all lost to cause.

inline transport_drop_stats_t snapshot() const noexcept

The three counters, one relaxed load each; a class not counted reads zero.

inline drop_cause_t dropped_tx_cause() const noexcept

The cause of the last outbound drop, NONE before the first (#2788).

struct drop_classes_t

Which of the three transport_drop_stats_t classes a drop_tally_t counts (#2482) — a build-time choice, so a link with no such class pays no word for it.

Public Members

bool dropped_rx = true

Count inbound frames shed (backpressure).

bool malformed_rx = true

Count inbound frames refused as malformed.

bool dropped_tx = true

Count outbound frames that never reached the wire.

bool dropped_tx_cause = false

Keep the cause of the last outbound drop: one byte, for a link that can name it (#2788).

struct peer_handle_t : public tr::wire::pair_t

An opaque per-peer LINK HANDLE — the identity the peer-receiver seam carries (#1294), minted once when a peer becomes audible and valid until it departs.

The seam used to re-supply a peer NAME string on every inbound frame, which forced every consumer that wanted a per-peer identity to re-derive one from that string per frame — a hash and a map find on the subscribe path (#1266), and nothing at all to hang a per-peer auth subject off (#375 Part 2). This handle is that identity, handed down instead.

It is a PAIR — (index, generation), the node-local-index-plus-validate-on-use-stamp primitive the vertex slot, the RFC-0029 path element and the ESP link’s session ref also use — but a DISTINCT type over it: the index is the minting link’s own peer index, not a vertex slot, so a tr::wire::pair_t never converts to one. The two fields are OPAQUE to a consumer: only the minting link knows what an index means, and a consumer may only compare handles, hash them, and hand them back.

It is not a session reference. A session ref (httpd_ws_link_t::session_ref_t, #1146/#1262) is ONE SUPPLIER of a handle, not the handle itself: an announce-census CAN peer has no session at all and still needs a stable link key, so the handle is the general concept and the session ref produces one.

It does not carry the subject. A per-peer auth subject is DERIVED from the handle at the terminus (graph::op_resolver_t’s subject seam) rather than carried in it, which is what keeps the per-frame POD minimal (#1294 ruling 2, ADR-0082).

It is never absent on the bus seam. Every handle the peer-receiver seam hands down is valid(): a link with no meaningful per-peer identity mints kSolePeerHandle

once at link-up and hands that down for every frame, so no consumer of that seam needs a “handle

absent” branch (#1294 ruling 3). A DEFAULT-constructed handle is still the “no peer here” value, and is what a link with no per-peer identity at all reports.

Public Functions

inline constexpr bool valid() const noexcept

True iff this handle names a peer (a zero generation never does).

inline constexpr std::uint64_t bits() const noexcept

The handle’s whole identity as one integer — the key an interning consumer (#1266) hashes, so it never has to know the field split.

Public Static Functions

static inline constexpr peer_handle_t from_bits(std::uint64_t bits) noexcept

The handle bits encoded, back from its one integer.

Friends

friend constexpr bool operator==(peer_handle_t, peer_handle_t) noexcept = default

Handles compare by identity — same index AND same generation.

The optional multi-peer (bus) capability of a transport link (ADR-0044).

A point-to-point link (ws/tcp/udp/quic) carries exactly one peer, so its child NAME fully addresses the far side. A BUS link (CAN) reaches many peers over one wire; this interface is how such a link exposes them to the routing plane with ZERO stored graph state (ADR-0044 §1 — no vertex is ever created for a peer):

  • enumerate_peers synthesizes, on the fly, the names of the peers currently audible on the bus (from the transport kind’s own live announce/heartbeat traffic) — the :children[] listing of the link’s connection vertex;

  • peer_link resolves one such NAME to a directed sending endpoint, the seam child_registry_t falls back to when a FWD’s next dst segment names no static child — so a peer name IS a routable hop segment;

  • set_peer_receiver replaces the flat inbound sink with a peer-named one: each inbound frame arrives tagged with the sending peer’s peer_handle_t, from which peer_name resolves the hop’s inbound NAME — so the return route grown into src names the bus peer to route the reply back to, symmetrically, with no per-request state.

Peer names are transport-defined but MUST be deterministic and collision-safe within the bus (the CAN binding derives them from the structured ID’s node field). All three calls may race the transport’s receive thread; impls synchronize internally.

The per-frame identity is the HANDLE, not the name (#1294). The name is the ADDRESSING surface — enumerate_peers, peer_link and close_peer still speak it, because a name is what a routable dst segment carries. The inbound seam speaks handles, because a name is a string a consumer would have to re-derive an identity from on every frame. peer_name is the one bridge between them.

Subclassed by tr::net::bus_slot_server_t, tr::net::can_transport_t

Public Types

Visitor invoked once per currently-audible peer name — a synchronous, non-owning callable reference (ADR-0083 Q10): passing a lambda costs nothing.

The peer-named inbound sink fn: (ctx, sending peer’s HANDLE, frame bytes).

The OWNING peer-named sink fn (ADR-0053 §5): (ctx, sending peer’s HANDLE, the reassembled frame as the rope it already is — refcounted links the receiver may keep, subrope, or forward past the callback).

The peer-departure notifier fn: (ctx, the departed peer’s HANDLE, its NAME). The handle is the one minted at arrival and is RETIRED by this call — after it the link may hand the same index back at a higher generation.

The peer-ARRIVAL notifier fn: (ctx, the arriving peer’s HANDLE, its NAME). This is where the handle is MINTED, so it is also where a consumer binds whatever hangs off it (an intern slot, #1266; an auth subject, #375 Part 2).

Public Functions

Visit the peers currently audible on the bus (a live-traffic snapshot).

Note

Synthesized on the fly — no call allocates peer state or graph structure.

Resolve a peer HANDLE back to the peer NAME it addresses — the ONE bridge between the handle the inbound seam carries and the name the routing plane grows into src (#1294).

Every kind answers this as a PURE FUNCTION of the handle, because every kind’s peer name already is one: slot_server_t names a peer p<slot>~<gen> for the slot it landed in and the tenancy generation it was minted at, and can_transport_t names one n<node> for its bus node id. So the call takes no lock, allocates nothing, and is safe to make from the delivery callback on the transport’s own receive thread — which is where the router makes it, once per inbound frame, exactly where the name used to arrive for free.

The answer carries the handle’s generation, so it names the SESSION and not merely the slot it occupies: a handle of a departed session formats a name no live peer holds.

Parameters:
  • peer – The handle a delivery was tagged with.

  • scratch – Caller-owned characters the impl MAY format into; at least kPeerNameChars. The returned view points either into scratch or into storage the link owns for its lifetime, so it is valid for as long as BOTH survive.

Return values:

{} – peer is not peer_handle_t::valid, or names no peer of this kind.

Resolve a peer NAME to a directed sending endpoint on this bus.

The returned transport sends to THAT peer only (the bus binding’s directed framing); it is owned by this link and stays valid for the link’s lifetime.

RESOLVE PER USE — never cache the pointer across a possible departure (#1153). Pointer VALIDITY and peer IDENTITY are two different guarantees, and only the first holds for every kind. Where a kind names peers POSITIONALLY, the endpoint is scoped to the SLOT, not to the session that occupied it: after the named peer departs, a pointer resolved for it addresses whatever session inherits the slot, and the endpoint’s own liveness check is satisfied by that stranger. The pointer never dangles; it silently changes who it means. A caller that re-resolves before each send is unexposed, which is why no production caller is affected today — child_registry_t resolves and sends in one expression, and a remote subscriber edge stores the peer’s handle rather than this pointer (peer_link_of).

Which kinds are exposed follows from the naming regime alone:

  • IDENTITY-derived names are immune — can_transport_t names a peer n<node-id> for its own bus node id, so the name, the table key and the endpoint are one identity that no other peer can inherit.

  • POSITIONAL names carry their tenancy — slot_server_t names a peer p<slot>~<gen>, so a recycled slot answers a fresh name and a stale one resolves nothing. The returned POINTER is still slot-scoped: resolve per use.

Return values:

nullptr – peer names no currently-known bus peer.

Resolve a peer HANDLE to a directed sending endpoint on this bus — the peer_link a remote subscriber’s delivery asks, with the name taken out (#1941).

Answers exactly what peer_link answers for peer_name(peer), and is scoped the same way: to the SESSION the handle names, so a departed session’s handle names nobody once its slot is reused. The same resolve-per-use rule holds.

The default IS that composition, so a kind that overrides nothing behaves exactly as before. A kind whose table is indexed by the handle overrides it to skip the name.

Return values:

nullptr – peer names no currently-known bus peer.

Close one peer’s connection by NAME, freeing its slot for reuse.

Tears down exactly the peer peer names, exactly as a remote hangup would: the recycle is asynchronous (the link’s own receive loop observes the close and reclaims the slot), so enumerate_peers stops listing it shortly after this returns true. A point-to-point kind (the default) has no per-peer teardown and returns false; a bus link that supports directed teardown overrides this.

Return values:
  • true – peer named an open connection and its teardown was initiated.

  • false – peer names no open peer, or this kind cannot close one peer.

The MODE AUTHORITY: true iff this link’s peer-named tier exists (#889).

A kind that is a bus by construction (the CAN binding) keeps the default true. A kind whose multi-peer surface is a WIRING-TIME choice — the tcp/ws listeners, constructed peer_named or FLAT — reports that choice here, and its transport_t::bus() returns null for the same reason: without the facet the link keeps point-to-point hop naming, inbound frames carry the registered child NAME, and send() fans out to every open peer.

Each of the six peer-named wiring calls declared below — set_peer_receiver and set_peer_rope_receiver (both spellings each) and set_peer_down_notifier and set_peer_up_notifier — passes this gate, so a link that reports false ends up with an empty peer_rx_ and neither peer-lifecycle notifier. (A DERIVED class can still reach the protected peer_rx_ directly; the gate governs this interface’s own doors.) It is a query, not a knob: bus_link_t is a PUBLIC base, so a flat link’s set_peer_receiver is reachable by an explicit upcast past the null bus(), and before this gate that call silently flipped the link into peer-named delivery the bus() == nullptr contract said did not exist.

A kind whose mode is CONSTRUCTED — the tcp/ws listeners, i.e. slot_server_t — additionally routes its per-frame tier select and its departure seam through the same flag, so for those two “which mode is this link in” has one answer. A kind that is a bus outright keeps its own delivery precedence (the CAN binding still falls back to the flat sink for a single-peer consumer that wired no bus facet), which this gate does not disturb: peer_named() is true there.

Note

Cold path only (wiring frequency, ADR-0047 §4) — an implementation’s own per-frame tier select reads its stored mode directly, never this virtual.

Register the peer-departure notifier — the bus half of the link-teardown eviction seam (RFC-0009 §D extended to peer departure).

The bus adapter invokes it (possibly on an internal transport thread) each time a peer’s session dies — remote hangup, protocol CLOSE, or a teardown initiated by close_peer — carrying the NAME the peer was audible under (the same NAME inbound frames were tagged with, i.e. the routing plane’s inbound link name for that peer). fwd_router_t::add_child installs a notifier that evicts the departed peer’s subscriber edges (fwd_router_t::link_down). Must be set before frames flow, like the receivers; a kind with no departure concept simply never fires it. The peer’s HANDLE rides alongside the name (#1294) so a consumer that keyed per-peer state by handle at arrival can drop it here without a name lookup.

Note

REFUSED on a link that is not peer_named — a flat link’s departure is the whole link’s (transport_t::set_link_state_notifier), so this wiring would be dead.

Parameters:
  • fn – The notifier; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible notification.

Register the peer-ARRIVAL notifier — the seam that says “this node’s own accept

policy just admitted a session”, and the boundary ADR-0044 §Decision 1 was scoped to by its 2026-08-13 amendment (#1223).

The mirror of set_peer_down_notifier, fired from the thread that observed the session become usable — for slot_server_t that is accept() for a raw stream peer and the 101 Switching Protocols publish for a WS peer, i.e. exactly the transition whose inverse fires the departure notifier.

Only an accepting listener fires it, and that is the whole point.

An announce-census bus (CAN, ADR-0030) learns of a peer from ANOTHER node’s traffic, has no closure event by design (RFC-0009 §D.5), and keeps §Decision 1 in full force; it therefore never fires this seam and never grows a session vertex. So “does

this kind fire peer-up” IS the announced-peer / accepted-session line, expressed as a capability rather than as a kind check at the consumer.

fwd_router_t::add_child installs a notifier that registers (or REVIVES) the session’s identity anchor in the graph’s vertex map, so the session gains an index and a saturating generation. Must be set before frames flow, like the receivers.

An arrival is also the RE-TENANT edge for the peer’s SLOT (#1609). A transport that reuses slots (a slot-positional p<slot>~<gen>) fires it once per new session, at the claim, and BEFORE delivering any frame of that session, advancing the generation by one per claim. The router’s notifier first reclaims what the predecessor tenancy left: the slot-keyed anchor generation, and the subscriber edges and pending awaits filed under the predecessor’s name, which peer_name spells from the arriving handle one generation down. So a predecessor whose departure was never reported leaves nothing for the successor to inherit and nothing for a later name-keyed eviction to confuse with the successor’s.

Note

REFUSED on a link that is not peer_named, for the reason set_peer_down_notifier is: a flat link has one routing identity for every peer it carries, so there is no per-session identity to anchor.

Parameters:
  • fn – The notifier; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible notification.

Register the peer-named inbound sink (used INSTEAD of set_receiver).

Must be set before frames flow; delivery may occur on an internal transport thread. When set, it takes precedence over a flat transport_t receiver.

Note

REFUSED on a link that is not peer_named (#889): a flat link has no peer-named tier to install into, and admitting the sink here is exactly the silent mode flip the null bus() contract denied.

Parameters:
  • fn – The sink; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible delivery.

Register the peer-named inbound sink from a caller-owned callable.

Zero-erasure sugar over the {fn, ctx} form: sink is bound by address (lvalues only — a temporary would dangle) and MUST outlive every delivery. Routed through the {fn, ctx} overload, so the mode gate is stated once.

Register the OWNING peer-named sink (ADR-0053 §5) — used INSTEAD of set_peer_receiver when the bus delivers_ropes.

A reassembling bus (CAN groups, fragmented WS) hands the frame up as the rope its reassembly already built — chained refcounted slice views, never a flatten memcpy; transport padding is trimmed by shortening the tail link. A span-only bus never dispatches to this sink (the honesty rule of transport_t::set_rope_receiver): install per delivers_ropes.

Note

REFUSED on a link that is not peer_named (#889), for the same reason set_peer_receiver is.

Parameters:
  • fn – The sink; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible delivery.

Register the OWNING peer-named sink from a caller-owned callable.

Zero-erasure sugar over the {fn, ctx} form: sink is bound by address (lvalues only — a temporary would dangle) and MUST outlive every delivery. Routed through the {fn, ctx} overload, so the mode gate is stated once.

True iff this bus delivers OWNING ropes to the peer-named rope sink (ADR-0053 §5).

template<typename ...Tag>
class receiver_slot_t

The delivery-tier receiver slot every transport adapter shares.

Holds the two inbound sinks of the ADR-0042/ADR-0053 receiver seam — the borrowed-span sink and the owning-rope sink — as trivially-copyable {fn, ctx} pairs, and performs the tier select on delivery: an owning frame prefers the rope sink and falls back to handing the same bytes borrowed; a borrowed frame can only ever go to the span sink (no adapter wraps a span into a rope whose refcounts would lie about lifetime, ADR-0042 §1).

Thread contract: setters may race the transport’s receive thread; every deliver snapshots the pairs under the lock and dispatches OUTSIDE it (a sink may re-enter the transport). The context pointer’s lifetime is the caller’s responsibility and must cover every possible delivery.

Template Parameters:

Tag – Extra leading sink parameters a transport tags deliveries with (e.g. peer_handle_t — a bus link’s sending-peer handle, #1294).

Public Types

using span_fn_t = void (*)(void *ctx, Tag..., std::span<const std::byte>)

The borrowed-span sink: the frame is valid only for the call.

using rope_fn_t = void (*)(void *ctx, Tag..., view::rope_t)

The owning sink: refcounted rope links the sink may keep or forward.

Public Functions

inline void set(span_fn_t fn, void *ctx) noexcept

Install (or clear, with nullptr) the borrowed-span sink.

Parameters:
  • fn – The sink; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible delivery.

inline void set_rope(rope_fn_t fn, void *ctx) noexcept

Install (or clear, with nullptr) the owning-rope sink.

Parameters:
  • fn – The sink; ctx is passed back as its first argument.

  • ctx – Caller-owned context; must outlive every possible delivery.

inline bool has_rope() const noexcept

True iff an owning-rope sink is currently installed.

The receive-loop strategy query: a transport that must choose its buffer strategy BEFORE the blocking read (recv into a refcounted segment vs a borrowed scratch) keys it off this, per iteration.

inline bool has_any() const noexcept

True iff ANY sink (span or rope) is currently installed.

The precedence query for transports with two slots (a bus link’s peer-named slot vs the flat transport_t slot): deliver to the higher-precedence slot iff it has a sink, else fall back.

inline void deliver(Tag... tag, view::view_t frame) const

Deliver one OWNING frame — the tier select.

Prefers the rope sink (the frame crosses as a single-link rope the sink may pin, subrope, or forward); with only a span sink installed, hands the same bytes borrowed (the view is released when the call returns). No sink installed drops the frame.

Parameters:
  • tag – The transport’s delivery tags (the Tag... pack).

  • frame – The frame, narrowed to its exact length, owning its segment.

inline bool deliver_rope(Tag... tag, view::rope_t frame, mem::mem_backend_t &backend = mem::heap_backend()) const

Deliver one OWNING frame that is already a rope (a reassembling bus’s group — chained slice views, never a flatten).

The rope sink takes it as-is (zero-copy). A span-only sink needs contiguous bytes: a single-link rope hands its bytes borrowed (zero-copy); a multi-link rope pays ONE materialize into backend — the span tier’s honesty cost, never the rope tier’s. A REFUSED materialize (an OOM, or a DEVICE link the CPU cannot read) DROPS the frame (#917): before the refusal had a name, its empty view was handed to the span sink as though those were the frame’s bytes — a truncated frame reported as a complete one.

The slot keeps no counter: it answers whether a sink took the frame, and the calling link counts a false on its own drop counter (#2504). The answer is taken from the same snapshot the delivery used, so a sink swapped after a caller’s own has_rope / has_any query is still answered honestly.

Parameters:
  • tag – The transport’s delivery tags (the Tag... pack).

  • frame – The reassembled frame as the rope it already is.

  • backend – Where a span-only fallback materializes a multi-link rope.

Returns:

True iff a sink received the frame; false for an empty slot or a refused materialize, both of them a drop the caller names.

inline void deliver_borrowed(Tag... tag, std::span<const std::byte> frame) const

Deliver one BORROWED frame — span sink only, by construction.

A borrowed span cannot become an owning rope (ADR-0042 §1), so an installed rope sink is honestly ignored here; transports that can hand up owning frames use deliver instead.

Parameters:
  • tag – The transport’s delivery tags (the Tag... pack).

  • frame – The frame bytes, valid only for the duration of the call.

The connection vertex’s link-liveness value (RFC-0014 §4).

The 1-byte VALUE a connection vertex stores — await-able and subscribable, so a subscribe /net/<module>/<name> streams every transition (assign-then-deliver under RFC-0008 §D). Supersedes the binary up/down set_link_state(name, bool). The six states are RFC-0014 §4’s table, in table order, and the byte encoding is normative: the conn/liveness-enum conformance vector plus its bound host test pinned it, and RFC-0014 Amendment 4 (S7) promoted the clause out of proposed pending. DORMANT keeps the old “down” 0x00 so a resting link stays the falsy default.

DIAL links move through DORMANT/DIALING/RECONNECTING/UP; LISTEN links report listen-socket reachability as LISTENING/BIND_FAILED (never per-accepted-peer). The DIAL transitions are driven by the RFC-0014 S5 liveness engine (tr::net::self_heal_link_t, #492) for kinds registered with transport_kind_traits_t::self_heal_dial — which since #1548 is every built-in point-to-point kind (udp, tcp, ws), so a stock DIAL connection is engine-managed. Everywhere else the value is still set manually (eagerly-constructed sockets — every LISTEN link, every bus kind — report UP/LISTENING at creation; provided links report via transport_vertex_t::set_link_state).

Values:

DIAL: vertex exists; no socket (refcount 0).

DIAL: a connect attempt is in flight.

DIAL: retrying toward UP between backoff waits.

DIAL: socket connected, bidirectional.

LISTEN: listen socket bound and accepting.

LISTEN: the listen socket could not bind.

struct transport_kind_traits_t

Per-kind CAPABILITY declarations a transport factory registers with (RFC-0014 §4, S5) — properties of the KIND, not of one connection, so they live in the factory catalog and never on the shared conn_settings_t (the ADR-0043 §5 leanness ruling protects that record; this struct is the catalog’s row, not the SPEC’s).

The defaults preserve every existing registration: a kind registered through the traits-less overload keeps today’s eager-construction behaviour exactly. The built-in point-to-point kinds do NOT take the defaults since #1548 — see kBuiltinPointToPointTraits in builtin_transports.hpp for the row they share and why self_heal_dial there is conditioned on the kSelfHealLinks build knob.

Public Members

bool self_heal_dial = false

Opt this kind’s DIAL connections into the RFC-0014 §4 S5 liveness engine (tr::net::self_heal_link_t).

When set, a DIAL creation constructs NO socket: the vertex is minted DORMANT and the engine dials on demand (an op kicks the dial and is dropped, RFC-0014 Amendment 5), self-heals with backoff while a standing binding holds it, and closes the socket back to dormant on the last release. The kind’s factory is then run once per dial attempt — it must be re-runnable (every built-in socket factory is, and each states why in its own registration comment). LISTEN connections of the same kind are untouched (RFC-0014 §4: a LISTEN link ignores refcount; it binds eagerly at creation as before).

Only for POINT-TO-POINT, connection-oriented kinds: a bus kind (CAN) must keep the default — the engine has no socket at creation, so the router’s bus-facet wiring (bus_of at add_child) would never see the facet.

bool delivers_ropes = false

The kind’s delivery capability (transport_t::delivers_ropes), declared statically because the engine must answer it for fwd_router_t::add_child BEFORE any socket exists. Ignored unless self_heal_dial is set.

The RFC-0014 §4 S5 liveness engine over one owned DIAL connection — a transport_t whose inner socket is constructed, healed, and closed by the engine itself (#492).

transport_vertex_t mints one of these instead of running the kind’s factory when the kind was registered with transport_kind_traits_t::self_heal_dial and the connection’s role is DIAL. The engine owns the factory (a copy), the parsed universal settings, and the SPEC’s raw config bytes, so it can re-run construction on every dial — creation itself constructs NO socket (the vertex is minted DORMANT, RFC-0014 §4’s refcount-0 resting state).

The state machine (DIAL subset of link_state_t, published to the connection vertex through the installed liveness publisher — the engine is the sole writer of these transitions):

  • DORMANT → DIALING: any op kicks the dial and is itself a counted drop (send never waits — RFC-0014 Amendment 5), and acquire kicks the same wake. A caller that must bring the link up and wait awaits up on the connection vertex.

  • DIALING → UP on a successful construct; → RECONNECTING (a standing binding holds) or back to DORMANT (none does — a lone one-shot’s failed dial triggers NO background retry, §4’s transient-hold rule) on a failed one.

  • UP → RECONNECTING on socket loss with refcount > 0: the self-heal retry loop, FOREVER (no give-up bound and no terminal state, the §4 no-synthetic-limits ruling). The loss starts the first attempt; each later one waits for backoff on the application’s clock (see sweep). Ops on a RECONNECTING link fail fast (dropped and counted), never block on a dead peer.

  • UP → DORMANT on socket loss with refcount 0, and on the LAST release (§4: refcount → 0 → close socket, go dormant, stop retrying).

The refcount counts STANDING bindings (acquire / release — the seam the routing plane’s subscription/await integration drives; S6 wires the callers). A one-shot op’s transient hold is implicit in send itself: it wakes a dormant link and is dropped, and its release is invisible at this seam (send is fire-and-forget), so an op-woken socket with no standing binding stays up until loss rather than being torn down per-op. That keep-up is the MAY of §4.1 (Amendment 1, 2026-08-21): the amendment leaves the close-on-transient-release question to the implementation, and this engine exercises the keep-up arm, because a dial per one-shot op is exactly the hidden-handshake latency the RFC’s own §Alternatives rejects. The three §4.1 MUSTs are what this engine is held to, and all three hold here: no background retry at refcount 0, re-dormant with no retry on loss (or on a failed wake-dial) at refcount 0, and close-plus-re-dormant on the last STANDING release.

Time. The engine reads no clock and arms no timer (#2304). Its only time is the now the application passes to sweep, and the retry spacing is backoff compared against it. A link whose application never calls sweep still heals, on events instead of time: each op, each acquire, starts one attempt while the link is RECONNECTING, and absent traffic nothing does (no spin, no background retry). Once sweep has run, those events no longer start retries, so traffic cannot bypass the spacing.

Threading. One worker thread per engine, started lazily on the first transition and joined by stop / the destructor; it is the only thread that dials and the only publisher of liveness, so transitions publish in order. It sleeps until an event wakes it, never on a timeout, so a dormant or backing-off link costs no wakeup. The factory’s dial blocks it, so the thread stays until a dial can run without blocking (#2147’s wait module). Dead sockets are reaped off the notifier thread (a socket’s down-notifier fires ON its own receive thread, which its destructor joins — reaping in place would self-deadlock). The engine takes no lock of transport_vertex_t or the router; the publisher writes the graph vertex directly, so the owner may hold its control mutex while joining this engine (stop()), and the declared lock order is never entered backwards.

Note

Engine-managed kinds are POINT-TO-POINT: bus is nullptr by construction (there is no socket to ask at creation, and a bus kind must not be registered self_heal_dial — its peer facet would be invisible to the router’s bus wiring).

Public Types

The liveness sink the engine publishes every transition through — installed once by the owner (a write of the 1-byte link_state_t VALUE to the connection vertex), before the link is wired into the router.

Public Functions

Bind the engine over factory with the connection’s creation-time config.

Parameters:
  • factory – The kind’s transport factory (copied; re-run on every dial).

  • settings – The parsed universal settings. backoff_ms / connect_timeout_ms of 0 are resolved to the engine defaults HERE, so the factory and the engine see the same effective values (RFC-0014 §4: config overrides the engine’s defaults).

  • raw_config – The SPEC’s config SETTINGS TLV as contiguous bytes (empty = the SPEC carried none): the kind-private keys the factory re-parses on each dial. BORROWED: the owner keeps them, and the text views in settings, alive until this engine is destroyed — transport_vertex_t holds them as the connection’s config copy and drops that copy only after the engine (#1780).

  • inner_delivers_ropes – The kind’s delivery capability (transport_kind_traits_t::delivers_ropes): the engine must answer delivers_ropes BEFORE any socket exists, because fwd_router_t::add_child installs the matching receiver on the ENGINE exactly once, at registration.

  • src – The store each dial’s socket, and the engine’s record of it, is drawn from — the factory’s third argument (receiver pays).

  • stack – The engine’s thread-stack store (link_memory_t::stack, #2288): its worker’s stack and task block. Default tr::mem::stack_source(); must outlive the engine.

Stops the engine (see stop) and destroys any remaining socket. Runs off every callback thread. A send made directly on the engine (not routed by a frame) must be quiesced before the engine is destroyed.

See transport_t::shut_down.

Install the liveness publisher — call after the connection vertex exists and BEFORE the engine is wired into the router (no transition can fire earlier).

The engine’s worker invokes it with no engine lock held, so the sink may take graph locks freely; it must tolerate a write to an already-retired vertex (teardown stops the worker first, but the sink is the safety net).

The owner has written the connection’s birth state: the worker may run (#2353).

A new engine starts no worker, so nothing it reports can be lost before the owner’s DORMANT birth write or overwritten by it. A demand that arrives first (a frame routed to the just-wired link, a binding) is still answered at once and still recorded; it dials from here. Call it once, after set_liveness_publisher.

A STANDING binding takes its hold (RFC-0014 §4: a routed subscription or await that needs the peer reachable).

Non-blocking: a dormant link is kicked toward UP (the worker dials), and so is a RECONNECTING one whose application has not called sweep; the caller that must WAIT for UP uses await on the connection vertex (S6’s verb). While refcount > 0 the engine self-heals on loss, forever.

The standing binding releases its hold.

The LAST release closes an UP socket and re-dormants the link, and stops an in-flight self-heal at its next gate (§4: refcount → 0 → close socket, go dormant, stop retrying). Unbalanced releases are ignored.

Stop the engine: join the worker, tear down every socket. Idempotent.

transport_vertex_t::remove_connection runs this through shut_down once its own locks are released. After it returns send drops everything, and a liveness publish still in flight finds the connection gone. A dial attempt in flight is waited for (the factory’s own connect deadline bounds the wait). On a thread that runs link callbacks (tr::net::on_callback_thread) it waits for nothing: it stops the worker and shuts the sockets down, and the destructor joins and frees them.

The engine’s current liveness state (the owner/test introspection door).

Emit one frame — the §4 op door. UP sends on the inner socket; any other state drops the frame at once, never waiting, and a DORMANT link is kicked toward UP (RFC-0014 Amendment 5). Every drop counts in drop_stats.

Scatter-gather twin of send(std::span<const std::byte>) — same gate.

Retained twin of send(std::span<const std::byte>) — same gate. The inner socket gets the delivery unchanged: lane picks its per-vertex ring and a frame that waits keeps value by reference (ADR-0087 §2).

The kind’s delivery capability, answered for the router at registration time (see the constructor’s inner_delivers_ropes).

Runtime liveness (#1059): true iff the engine is UP.

The CURRENT socket’s counters plus the engine’s own drops: its fail-fast sends (dropped_tx) and the frames its slot could not hand up (dropped_rx, #2504). A healed link’s previous socket takes its counts with it.

The application’s clock (#2481): spaces the heal’s attempts by backoff, and forwards to the CURRENT socket (#2198), whose frozen peer goes down as any other.

While the link is RECONNECTING under a standing binding, the first call stamps the wait at now + backoff and answers it; a call at or past the stamp starts the next attempt and answers now + backoff again (#2304). So a pending reconnect always answers a time after now, never 0, and an application that sleeps until the answer wakes for its retry. The heal’s first attempt after a loss is started by the loss, so between that loss and the next call the link has nothing to answer yet: an application that wants a lost link retried within a bound caps its sleep at that bound, as it does for a peer that starts owing bytes (transport_vertex_t::sweep). backoff is read in now's units: the key is spelled in milliseconds, so a node with self-heal links passes now in milliseconds. Attempts are spaced start to start: a dial that blocks longer than backoff (up to the kind’s own connect bound) is followed by the next with no gap.

The first call also hands the retry spacing to the application for good: from then on an op or an acquire no longer starts a retry on a RECONNECTING link.

The egress

constexpr std::uint16_t tr::net::kEgressControlDepth = 8

The depth of a peer’s control lane: frames that come from no vertex (a reply, a control frame, a forwarded record). Compile-time, and best-effort, as every link’s one queue was before #2144: a full control lane sheds its oldest frame, counted.

class egress_frame_t

One outbound frame, built once and shared by every peer it reaches.

One block from the link’s egress source: this header, then the copied head bytes. A frame that ends with a published value keeps it by reference and its bytes follow the head on the wire. The last release returns the block to the source it came from, on whatever thread drops it.

Public Functions

inline void retain() noexcept

One more reference (a peer’s ring entry).

inline std::span<const std::byte> head() const noexcept

The copied part: the link’s framing and the caller’s head spans.

inline const graph::value_t *value() const noexcept

The payload kept by reference, or null.

inline std::size_t size() const noexcept

The frame’s whole length on the wire.

inline std::size_t span_count() const noexcept

Spans the frame is written from: the head, then one per value link.

inline std::size_t spans_from(std::size_t off, std::span<const std::byte> *out) const noexcept

Write the frame’s spans that lie past its first off bytes into out.

out must hold span_count entries. Empty spans are skipped.

Returns:

The number of spans written.

Public Static Functions

static inline egress_frame_t *make(mem::block_source_t &src, std::size_t head_bytes, function_ref_t<std::size_t(std::span<std::byte>)> fill, const graph::value_t *value = nullptr) noexcept

Draw a frame of head_bytes copied bytes and let fill write them.

Parameters:
  • src – The link’s egress source.

  • head_bytes – Room for the copied part of the frame.

  • fill – Writes the copied part into the span it is given and returns the byte count it wrote; 0 refuses (nothing could be encoded).

  • value – A payload to keep by reference after the copied part, or null.

Returns:

The frame with one reference (the caller’s), or null when src refused the block, fill refused, or value could not be kept.

static inline egress_frame_t *make(mem::block_source_t &src, std::span<const std::span<const std::byte>> spans, const graph::value_t *value = nullptr) noexcept

Draw a frame whose copied part is spans, in order, then value if any.

static inline void release(egress_frame_t *f) noexcept

Drop one reference; the last one returns the block. Null is a no-op.

struct egress_step_t

How one write turn on one frame ended — the link’s write callback answers this.

Public Members

std::size_t moved = 0

Bytes this turn put on the wire.

bool held = false

The socket stopped taking bytes before the frame’s end: the rest waits for the peer’s next turn.

bool failed = false

The socket is dead or refused the call: the frame is abandoned, and so is any byte of it still unwritten.

struct egress_result_t

What one egress_t::send or egress_t::flush cost, for the link’s counters.

Public Members

std::uint32_t shed = 0

Frames this call lost toward the peer: refused (closed peer, reliable ring full, no block), displaced from a full ring, or abandoned by a failed write. The link’s dropped_tx.

std::uint32_t displaced = 0

Of shed, waiting frames a newer one pushed out (the SAMPLE overwrite, the best-effort drop-oldest).

std::uint32_t stalled = 0

Offers that found the peer’s STREAM lane full and whose turn moved nothing: counted only, never a verdict (#2899). A SAMPLE lane never stalls.

bool condemn = false

A failed write cut a frame mid-way: the link closes the peer.

class egress_peer_t

One peer’s egress state: the frame on the wire, the lanes waiting behind it, the writer role and the peer’s own lane lock.

At most 24 B on a 64-bit host (pinned below; 16 B on a 32-bit MCU), and nothing else at rest: a lane — one ring per (peer, vertex), plus the control lane (ADR-0087 §2) — is drawn from the link’s source when that vertex’s first frame has to wait, and returned when its last waiting frame leaves. A peer that keeps up never holds one. The lanes are guarded by a bit of the peer’s own role byte (#2310), so no two peers’ sends share a lock.

Public Functions

inline bool wants_write() const noexcept

Something waits for the socket to take bytes: a waiter should report this peer’s writability and call egress_t::flush when it comes.

inline bool closed() const noexcept

The peer is closed: never opened (egress_t::open), or closed since (egress_t::close).

class egress_t

The link-level half of the egress module: the source its lanes are drawn from.

One per link, and it holds no lock: each peer’s lanes are guarded by that peer’s own lane lock (#2310), a bit of its role byte. The lock is held only for a lane step — an index step, and the lane block drawn or returned with it — never across a write, a frame build or a frame release, and never by a send that finds the peer idle (#2145): it guards the lanes, not the writer election and not the write. A sender that finds it held sleeps on the role byte (tr::park_wait: no clock, and no libstdc++ waiter table on an MCU, #2507) until the holder lets it go, so a holder preempted inside its step gets the CPU back from a higher-priority sender (the #1618 hang a spinner would bring back).

Note

Thread-safe: any number of senders, plus the link’s own receive or wait context.

Public Functions

inline explicit egress_t(mem::block_source_t &src) noexcept

An egress whose lanes are drawn from src.

template<class Direct, class Write, class Arm = no_arm_t, class Current = any_tenant_t>
inline egress_result_t send(egress_peer_t &p, const graph::delivery_lane_t &lane, function_ref_t<egress_frame_t*()> frame, Direct &&direct, Write &&write, function_ref_t<void()> condemn, Arm &&arm = Arm{}, Current &&current = Current{})

Put one record on the wire toward p, or queue it on its vertex’s lane behind the write in flight.

Parameters:
  • p – The destination peer.

  • lane – The vertex the record comes from and the ring it waits in: depth 1 is a SAMPLE (a newer frame overwrites the one waiting), depth N a STREAM whose full ring takes the vertex’s arm. Null key: the control lane (kEgressControlDepth, best-effort). Lanes are served round-robin, FIFO inside each.

  • frame – Builds the shared frame when it is needed — called at most once per call, and only when the record has to wait. Return a frame with one reference the caller keeps (this call adds its own), or null to refuse. A fan-out passes the same lazily-built frame for every peer.

  • direct – Writes the caller’s record from its own memory, from byte 0, when the peer was idle: egress_step_t(void).

  • write – Writes a waiting frame from an offset: egress_step_t(const egress_frame_t&, std::size_t off).

  • condemn – Shuts the peer’s socket down. Called while this call still holds the writer role, so the socket it names cannot have been closed and reused — only when a failed write cut a frame mid-way (egress_result_t::condemn), and perhaps more than once in one call, so it is idempotent (shutdown(2) is).

  • arm – Arms write interest for a frame the socket cut short. Called while this call still holds the writer role, and only once egress_peer_t::wants_write reports the frame (#2775): a waiter that disarms and then looks again either sees the frame or is re-armed here.

  • current – Whether the peer is still the session the record is for (#2911). Asked where the peer cannot be closed and reopened under the answer: holding the writer role, or under the lane lock with the peer open. A record for a session that has gone, whose slot another session took, is shed. The default takes whoever holds the peer.

template<class Write>
inline egress_result_t flush(egress_peer_t &p, Write &&write, function_ref_t<void()> condemn)

The socket of p reported writability: resume its held frame and drain its lanes, unless a sender already holds the role (it drains them itself). Parameters as send.

inline bool condemn_held(egress_peer_t &p, function_ref_t<void()> condemn, bool rx_stuck)

The application’s liveness check closing p (#2198): run condemn if a frame still waits on its wire, or if rx_stuck, inside the writer role, so the socket it shuts down is still the peer’s own (a teardown waits the role out before it closes the fd).

The claim does not wait. A role somebody holds is a write in progress, so the peer is not frozen and nothing runs. Nothing is written here: a lane frame found with the wire free waits on the wire for the peer’s own writability, as a full socket’s would.

Parameters:

rx_stuck – The peer owes the rest of a frame of its own and sent no byte of it since the last check (#2812): it is condemned with nothing on its wire.

Returns:

True iff condemn ran.

inline void close(egress_peer_t &p) noexcept

Close p: refuse every later send, wait out a write in flight, release every frame and every lane. Teardown’s half of the role handoff.

The caller makes the in-flight write return first — shutdown(2) on the socket — and never calls this from inside a write callback on the same peer. It runs once per open: a close of a closed peer returns at once. The wait is on the writer leaving the role (tr::park_wait, #2507), not on a clock.

inline void open(egress_peer_t &p, egress_frame_t *first = nullptr) noexcept

Open p for a session: a peer starts closed, and a closed one holds no frame.

Called once per session, on a closed peer: each open is paired with one close before the next.

Parameters:

first – A frame to put on the wire ahead of anything a sender offers (a WebSocket server’s 101), or null. The egress takes over the caller’s reference. It is held, so the next turn — a send or flush — writes it first.

struct any_tenant_t

The current of a send to whoever holds the peer: every tenancy is current.

Public Functions

inline constexpr bool operator()() const noexcept

Always current.

struct no_arm_t

The arm of a caller with no waiter to arm, and of the waiter’s own turns: an empty call the compiler drops, so such a caller pays nothing for the seam.

Public Functions

inline constexpr void operator()() const noexcept

Arm nothing.

The POSIX scaffold

Every socket wait on a node belongs to its one wait module (ADR-0087 §3, #2147): a link registers each socket it reads and owns no thread for it, and whatever drives the module runs every delivery to completion. The wait has no timeout. A link given no module falls back to a thread of its own that drives a private one.

enum class tr::net::ready_t : std::uint8_t

The readiness bits a tr::net::wait_source_t callback is handed.

Values:

enumerator NONE

Nothing.

enumerator READ

Readable, or a listening socket has a connection to accept.

enumerator WRITE

Writable, reported only while write interest is armed.

enumerator HANGUP

The peer hung up or the socket failed: a read reports which. The epoll adapter reports it from the kernel; the lwIP adapter, whose select folds a hang-up into READ, only for a socket closed while still attached.

struct wait_source_t

One socket registered with a tr::net::wait_module_t, as the {fire, ctx} waiter of ADR-0084 §3 plus the descriptor.

The link that owns the socket owns this record and pays for it (24 B on a 64-bit host), and on the lwIP adapter its place in the list too (next, one pointer more). Set fire, ctx and fd before wait_module_t::attach, and keep the record alive and unmoved until wait_module_t::detach returns.

Subclassed by tr::net::slot_server_t::session_base_t

Public Types

using fire_t = void (*)(void *ctx, wait_source_t &self, std::uint8_t ready)

Runs on the driving thread when the socket is ready.

Param ctx:

The record’s ctx.

Param self:

This record.

Param ready:

The ready_t bits that hold.

Public Members

fire_t fire

The callback: unset until its owner names it, before an attach.

void *ctx = nullptr

Its context: the owning link.

std::conditional_t<kListedWaitSources, wait_source_t*, unlisted_t> next

The next source in the lwIP adapter’s list: the receiving link pays for its own entry, so the module holds no table. Written under the module’s lock; the driver reads it with none, under the source’s firing mark, so both go through std::atomic_ref. Left unset until wait_module_t::attach writes it, as nothing reads it before: a link’s constructor spends no store on it. An empty member, taking no space, in a build without that adapter (tr::net::kListedWaitSources). Declared ahead of the socket so the record ends in its two flags with either adapter, and an owner can place a flag of its own in the tail padding (tr::net::posix_endpoint_t, #2827).

std::atomic<int> fd = {-1}

The socket; -1 for none. Changed only while the record is detached. Atomic because a link’s senders read it too (a server session’s fd is this one).

std::atomic<bool> write = {false}

Write interest, as last armed (wait_module_t::want_write).

std::atomic<bool> attached = {false}

True while attached. Set by wait_module_t::attach before it registers the socket (with no lock on the epoll adapter: a callback reads it only once the kernel reports the socket); cleared only under the module’s lock. Atomic (relaxed) because the epoll adapter’s attach reads and sets it with no lock while a detach may clear it under one; every other ordering comes from the lock or the kernel’s registration.

class wait_module_t

The node’s one wait module (ADR-0087 §3): every socket wait on the node, with no timeout.

Thread safety: attach, detach, disarm, want_write and stop may be called from any thread, and from inside a callback. A detach from another thread waits for that source’s callback if it is in flight, and for nothing else, so once it returns the source’s callback never runs again. It must not be called holding a lock that the detached source’s own callback takes (see the file’s “A detach waits for its own source only”). run is called by one thread at a time.

Public Functions

wait_module_t() noexcept

Opens the wait and its wake; ok reports whether both opened. Draws no memory: each attached source carries its own entry.

~wait_module_t()

Closes the wait and its wake. Every source must have been detached and run must have returned.

inline bool ok() const noexcept

True when the wait and its wake both opened.

bool attach(wait_source_t &s) noexcept

Start waiting on s : read interest, plus write interest when s.write is set.

Return values:

false – The platform refused the registration, or, on the poll adapter, the socket is numbered past FD_SETSIZE; nothing was attached, and nobody already attached was evicted. Neither adapter draws memory, so neither attach nor a dispatch pass fails for want of it.

void detach(wait_source_t &s) noexcept

Stop waiting on s . A no-op for a detached source.

From another thread it waits for s ‘s own callback, if it is in flight, and for no other; from inside a callback it returns at once, and the rest of that batch is redelivered next pass.

void disarm(wait_source_t &s) noexcept

Stop waiting on s , waiting for nothing: detach without its wait, from any thread. A no-op for a detached source.

No new callback of s starts once this returns, but one already in flight may still be running; a later detach waits it out. A link’s shut_down calls this, and its destructor calls detach.

void want_write(wait_source_t &s, bool on) noexcept

Arm or disarm write interest on s .

A link arms it inside its egress writer role when a write leaves a frame held, so the socket cannot be closed under the call, and disarms it on the driving thread once the frame is out. A no-op when the interest is already as asked.

void run() noexcept

Dispatch ready sources until stop is called. The caller’s thread is the node’s I/O context, and every callback runs on it.

Blocks with no timeout between passes. Returns at once if stop was already called.

void stop() noexcept

Make run return: wakes it if it is blocked. Idempotent.

class posix_endpoint_t

The shared wait scaffold of the POSIX socket transports (#2147).

A protected base (inherited privately by the concrete transports) that puts the link’s sockets on a wait_module_t : the node’s, when the link’s config names one, and the link then owns no thread; otherwise a private module driven by one thread of the link’s own (the thread-per-link fallback adapter). Either way the wait has no timeout and every callback runs on the module’s driving thread.

Teardown invariant (derived destructors): call stop_and_join FIRST, before releasing ANY resource a callback touches (sockets, receivers, buffers). It detaches the link’s sources, which waits out a callback in flight, so none runs once it returns.

Lifetime rules: a shut_down only shuts down, on every thread: it waits for nothing and closes nothing (#2813). A link’s descriptors stay owned and open until its destructor runs, and the destructor is the one join.

Stream transports (tcp / ws) layer the shared one-peer fd/teardown discipline on top via stream_endpoint_t — the write-serialization and teardown-under-role invariants live there, with the code.

Subclassed by tr::net::stream_endpoint_t, tr::net::udp_transport_t

Protected Functions

inline explicit posix_endpoint_t(wait_module_t *node = nullptr) noexcept

Constructs not yet waiting.

Parameters:

node – The node’s wait module, or null for the thread-per-link fallback. It must outlive the link.

~posix_endpoint_t()

Stops a fallback thread as a last resort; derived destructors have already called stop_and_join (see the teardown invariant above).

bool start(std::size_t stack_size, mem::block_source_t &src)

Begin waiting: on the node’s module, or on a private one driven by a thread of the link’s own. Call at most once, before the first attach.

The fallback’s thread spawns through static_thread_t (#2288), never std::thread, whose constructor throws on failure (an abort under -fno-exceptions). Its private module and, on ESP-IDF, its task block and stack are drawn from src.

Parameters:
  • stack_size – The fallback thread’s stack in bytes, 0 for the platform default (ignored on the node’s module, whose driver is the application’s).

  • src – The link’s link_memory_t::stack. It MUST outlive stop_and_join.

Return values:

false – The private module or its thread was refused: nothing waits. The caller MUST report it, by leaving the link inert (ok() false) or bringing it down.

bool attach(wait_source_t &s, int fd, wait_source_t::fire_t fire, bool write = false) noexcept

Put s (socket fd , callback fire with this link as context) on the wait.

write arms write interest for the first turn. A write interest armed on s since start (a send held between the two) is kept, never cleared here.

A shut link stays off the wait (#2813): a callback that was already running when the link was shut down (an accept, or a listener put back after its peer left) attaches after the shut-down’s disarm, so it takes s off again. The mark is read after the attach (seq_cst, against stop_waiting’s mark-then-disarm), so either this sees the link shut, or that disarm follows the attach.

Return values:

false – The module refused it, or the link is shut: the caller treats the socket as gone.

inline wait_module_t *waiting() const noexcept

The module this link waits on, or null before start.

inline wait_module_t &waiter() noexcept

The module this link waits on (valid after start).

inline void arm_write(wait_source_t &s) noexcept

Arm write interest on s, from inside the egress writer role, once a write left a frame held and the peer reports it (egress_t::send’s arm). Before start it does nothing: the first attach arms it.

void stop_and_join()

Stop waiting and wait it out (idempotent): stop_waiting , then join the fallback thread and detach src_ , which waits out its callback in flight on the node’s module. MUST be the FIRST act of every derived destructor, which runs off every callback thread (asserted): the link’s one join.

void stop_waiting()

Stop waiting for a shut_down, waiting for nothing (idempotent): mark the link shut, stop the fallback’s driver and take src_ off the wait (wait_module_t::disarm). A callback in flight may still run; a shut link’s descriptors are shut down and stay open, and its destructor closes them after its join.

Note

Out of line (noinline): every destructor and shut_down calls this one body.

void release_fd(std::atomic<int> &slot, int fd) noexcept

Give a socket fd back that slot held: closed, unless the link is shut, when it stays open in slot for the destructor to close.

inline bool shut() const noexcept

True once a teardown shut the link: its buffers and descriptors are left for the destructor.

inline bool shut_seq() const noexcept

shut, read seq_cst: for a check that must be ordered against the mark a teardown stores before it walks the link.

Protected Attributes

wait_source_t src_

The link’s own socket’s registration: a datagram socket, a dialled connection, or a listening socket. Its context is the link. Potentially overlapping, so the shut flag declared after it sits in its tail padding (#2827).

Protected Static Functions

static void release_listen(int fd) noexcept

Shut a listening socket fd down for a shut_down (none when negative): the destructor closes it.

Every library thread is a tr::static_thread_t: its stack and task block come from one block drawn from the link’s link_memory_t::stack source, never the platform heap (#2288).

class static_thread_t

One joinable thread, spawned from a block source where the platform needs memory for it (see the file comment for the per-platform policy).

Not copyable or movable: the running thread holds this object’s address on ESP-IDF only through its own block, but a caller-visible move would still race a concurrent join. The destructor joins.

Public Types

using entry_t = void (*)(void *arg)

The thread body: a plain function taking the argument start was given.

Public Functions

static_thread_t() noexcept = default

No thread.

inline ~static_thread_t()

Joins a still-running thread (a no-op when none was started or it was joined).

bool start(entry_t fn, void *arg, std::size_t stack, const char *name, mem::block_source_t &src) noexcept

Spawn fn(arg) on a new thread.

Parameters:
  • fn – The body; it runs once and the thread ends when it returns.

  • arg – Passed to fn unchanged.

  • stack – Stack bytes, or 0 for the platform default (the pthread default stack on both platforms: CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT on ESP-IDF). On POSIX a hint below the platform floor leaves the default in place.

  • name – Task name on ESP-IDF; must outlive the thread (a literal). Unused on POSIX.

  • src – Where the stack and control block come from on ESP-IDF, and the boot record on POSIX; it MUST outlive the thread (until join returns, or, for a thread that may be detached, the process).

Return values:

false – The spawn failed (the source refused, or the platform did); nothing runs and nothing is held. Also false when a thread is already running here.

void join() noexcept

Wait for the thread to end and release what it held (idempotent). On ESP-IDF this also reaps any detached thread that has finished (see detach).

void detach() noexcept

Let the thread run on without this object; it is no longer joinable here.

POSIX: pthread_detach. ESP-IDF: a static task cannot return its own stack, so its block is PARKED on a process-wide intrusive list (the link lives inside the block; a static lock guards it; nothing is allocated). A parked block whose body has returned is reaped — the task deleted and the block released to its source — by the next start, join or detach on any static_thread_t in the process, so it is held at most until then. The block’s source therefore MUST outlive the process: spawn a thread that may be detached from tr::mem::default_root() or a source of the same lifetime, never from a source that dies with its owner.

bool joinable() const noexcept

True from a successful start until join or detach.

The write helpers below never wait (#2252) and report how one record’s write ended, so a stalled peer is counted, its frame held and resumed on writability, and never blocked on (#838):

enum class tr::net::write_outcome_t : std::uint8_t

How a full-record write to one peer ended (#838).

The stream transports need more than “it returned”: a record that only PARTLY reached the socket has desynced that stream’s framing permanently (every later byte parses under the wrong length), which is a different fault class from a record that never started — and both are different from the peer simply being gone.

Values:

enumerator COMPLETE

Every byte of the record reached the socket.

enumerator STALLED

The socket filled with the record unfinished — the peer is not taking bytes right now.

enumerator FAILED

Abandoned: the socket is dead (#66 lifecycle), or the call itself was rejected past its one re-attempt (counted in write_fault_stats).

struct write_result_t

The result of one full-record write — its outcome plus whether the stream survived it (#838).

Public Members

write_outcome_t outcome = write_outcome_t::COMPLETE

How the write ended.

std::size_t moved = 0

Bytes of the record that reached the socket.

Short of the record’s length on a STALLED write, this is where the rest resumes: the egress keeps the frame and its offset (#2144), so a part write is never a desync on a live connection. On a FAILED one, non-zero means the peer holds a header whose payload will never arrive.

class stream_endpoint_t : protected tr::net::posix_endpoint_t

The one-peer fd/teardown discipline every POSIX STREAM transport shares (tcp dial+listen, ws server, ws client).

Owns the live peer fd (conn_fd_) and the link’s egress (egress_, ADR-0087 §2), and is the ONE home of the invariants that keep a concurrent send() and the driving thread’s connection teardown safe against each other:

Write-serialization invariant: every write to a peer fd is made by the sender holding that peer’s egress WRITER ROLE (egress_send), elected by try-lock: a sender that finds the peer idle writes its own record, one that finds a write in flight queues a reference and returns. So two senders never interleave records on the stream and no publisher waits on another publisher’s write. A record the socket cuts short keeps its frame and offset, and the rest goes on the peer’s next turn, so a part write never desyncs the framing.

One open per peer session: a dialer’s peer opens once, in its constructor; a listener’s stays closed until an accept publishes the fd, and opens once there. Each open is closed once, at the peer’s teardown or in the destructor. A send with no peer sheds, counted.

Teardown-under-role invariant: a driving thread that closes the peer fd first shutdown(2)s it (an in-flight write returns), then closes the peer’s egress — which waits for the writer role to be let go — and only then resets conn_fd_ to -1 and close(2)s it (teardown_peer). So a sender never writes to (or reads) a closed or reused fd, and the shared write mutex is gone.

The one-peer listener shape (accept → per-peer setup → serve → teardown → listen again), on the wait module, lives here too (accept_one, relisten). A protected base, inherited privately by the concrete stream transports; udp stays on plain posix_endpoint_t — a datagram socket has no per-peer fd to tear down and its single-syscall sends need no serialization.

Subclassed by tr::net::slot_server_t, tr::net::tcp_transport_t, tr::net::ws_client_transport_t

Protected Functions

inline stream_endpoint_t()

Constructs a dialer with no peer connected (conn_fd_ = -1); the egress draws from the process net sub-pool.

inline explicit stream_endpoint_t(mem::block_source_t &tx_src, bool dials = true, wait_module_t *node = nullptr)

Constructs with no peer connected, the egress drawing from tx_src.

Parameters:
  • tx_src – The link’s egress store: every shared frame, each (peer, vertex) ring, and a frame’s gather overflow (write_frame).

  • dials – This endpoint dials its one peer: the peer opens here, its one open, and a send before the dial lands, or after it failed, finds no fd and sheds, counted. A listener passes false and its peer stays closed until there is a connection: a one-peer listener’s opens at each accept (accept_one), and a multi-peer server keeps one peer per session.

  • node – The node’s wait module, or null for a thread of the link’s own (posix_endpoint_t).

~stream_endpoint_t()

Closes a leftover peer fd (one the driving thread never tore down).

Runs AFTER the derived destructor, whose first act was stop_and_join (the posix_endpoint_t teardown invariant) — so no thread can race this. A normally-torn-down connection already reset conn_fd_ to -1 and this is a no-op; it only catches a never-spawned thread (a failed dial / handshake left the fd parked) so nothing double-closes.

egress_step_t write_frame(int fd, const egress_frame_t &f, std::size_t off)

One egress write turn: f from its byte off, gathered as one write — the copied head, then a kept value’s links straight from the published block.

The gather table is inline; its overflow comes from io_src_ and is refused rather than thrown, which writes nothing and reports a failed turn (a shed frame, never a desync).

Parameters:
  • fd – The destination fd.

  • f – The frame.

  • off – Bytes of f already on the wire.

egress_frame_t *frame_of(std::span<const ::iovec> rec, const graph::value_t *value = nullptr) const

A shared frame of the gathered record rec: what comes before value's links is copied, and value (whose non-empty links end rec) is kept by reference.

Returns:

The frame, or null when the egress store refused it.

void note_egress(const egress_result_t &r) noexcept

Account one egress call (#838, #2144): every shed frame is a counted dropped_tx, every turn that found the socket full and moved nothing a stalled_tx_.

std::uint64_t sweep_one(std::uint64_t now, std::uint64_t deadline)

The one-peer transport_t::sweep (#2198, #2481): a dialer’s, or a one-peer listener’s, under the slot server’s rule. The peer owes TX while a frame of ours is held on the wire, and RX while a frame of its own is begun and not finished (rx_owed_, #2812); one that owed a direction and moved no byte in it since the last check is frozen. A frozen peer is shut down inside its writer role, so the driving thread runs the ordinary teardown, and counted in frozen_closed_.

Returns:

When the peer is next due, 0 when it owes nothing or was closed.

template<class Direct>
inline void egress_send(function_ref_t<egress_frame_t*()> frame, Direct &&direct, const graph::delivery_lane_t &lane = {})

Put one record on the wire toward the ONE peer through its egress (ADR-0087 §2).

The single-peer senders’ one door. A publisher that finds the peer idle takes the writer role and writes its record straight from its own memory through direct, with the fd read inside the role; one that finds a write in flight puts a reference to the shared frame frame builds in the peer’s ring and returns at once. So no publisher waits on another publisher’s write to a stalled peer (#1619), and the writer itself never waits (#2252): what the socket did not take stays held, and the driving thread resumes it on writability.

Template Parameters:

Direct – Callable egress_step_t(int fd): write the caller’s own record.

Parameters:
  • frame – Builds the shared frame (the record copied, a kept value by reference) when the record has to wait.

  • lane – The ring it waits in: its vertex’s, or the control lane (a default).

template<class Read, class Owed>
inline bool peer_turn(std::uint8_t ready, Read &&read, Owed &&owed)

One readiness turn of the ONE peer’s connection (src_), on the driving thread: writability resumes a held frame, nonblocking (egress_t::flush), so a record the socket cut short finishes without waiting for a later send (#2144); readability (or a hangup) runs read on the socket.

Every turn records what the liveness check reads of the read side (#2812): a readable turn is RX progress (rx_moved_), and owed after the turn is whether the peer still owes the rest of a frame (rx_owed_).

Template Parameters:
  • Read – Callable bool(int fd): read what the socket has; false when the connection must close.

  • Owed – Callable bool(): the link’s ingress is mid-frame.

Returns:

False when the peer is gone: the caller runs depart.

void flush_one(int fd)

Resume the ONE peer’s held frame on fd without waiting, then disarm write interest once nothing is held (driving thread).

void disarm_flushed(wait_source_t &s, const egress_peer_t &peer)

After a flush, set write interest on s to whether peer still holds a frame, then re-arm it if a sender held one meanwhile (driving thread).

void depart()

The ONE peer departed (driving thread): stop waiting on its connection, then teardown_peer it.

void accept_one(int listen_fd, function_ref_t<bool(int)> on_accept, wait_source_t::fire_t fire)

One accept on the one-peer listener, whose listening socket is src_ (driving thread).

Runs on_accept (per-peer setup; false rejects: the socket is closed and the listener keeps waiting), publishes the fd to conn_fd_, moves src_ from the listening socket to the connection, served by fire, and only then opens the peer’s egress: its one open for this connection, closed since construction or the last teardown. A refused registration closes the connection and puts src_ back on the listening socket. A listener accepts nobody else while a peer is connected: the kernel’s backlog holds them. relisten puts src_ back on the listening socket after the peer departs.

void relisten(int listen_fd, wait_source_t::fire_t fire)

After a one-peer listener’s depart, wait on listen_fd again, served by fire.

void teardown_peer(int fd)

Tear the peer connection down (driving thread).

The teardown-under-role invariant as code: shutdown(2) the fd so a write in flight returns, close the peer’s egress (waiting out its writer, releasing its frames), THEN reset conn_fd_ to -1 and close(2) the fd — a concurrent send() either finished against the still-open fd or finds the peer closed and sheds. On a shut link the fd stays open in conn_fd_ for the destructor.

Parameters:

fd – The peer fd the recv loop was serving.

void shut_down_stream()

The transport_t::shut_down of a one-peer stream link: stop waiting (posix_endpoint_t::stop_waiting), then tear the live peer down (teardown_peer), so a later send finds the peer shut and sheds. Idempotent. Joins nothing and closes nothing: the fd is only shut down.

Protected Attributes

std::atomic<int> conn_fd_ = {-1}

The live peer connection (-1 = none).

std::atomic<bool> tx_moved_ = {true}

A byte of ours went out to the ONE peer since the last liveness check (#2198), in the hole after conn_fd_. Set by the writer, taken by sweep_one; a new session sets it.

std::atomic<bool> rx_moved_ = {true}

The ONE peer’s socket was readable since the last liveness check (#2812), in the same hole. Set by peer_turn, taken by sweep_one; a new session sets it.

std::atomic<bool> rx_owed_ = {false}

The ONE peer has begun a frame and not finished it, as of the driving thread’s last turn (#2812), in the same hole. Set by peer_turn, cleared by teardown_peer.

std::atomic<std::size_t> stalled_tx_ = {0}

Write turns that found the peer’s socket full and moved nothing (#838, #2144) — the “how often did a stalled peer refuse us” counter, never a verdict (#2899). Relaxed: a diagnostic tally, not a synchronizer. Word-wide, not 64-bit (core/STYLE.md §Introspection clause 5, #1697): a 64-bit atomic is a libatomic call on every rv32; a 32-bit target wraps after 2^32.

drop_tally_t drops_

This link’s shed-frame counters (#2482). dropped_tx is every outbound frame it never put on the wire: a refused build, a closed peer, a full ring, a failed write. dropped_rx and malformed_rx are the derived kind’s framing refusals.

std::atomic<std::size_t> frozen_closed_ = {0}

Peers the application’s liveness check closed as frozen (#2198) — every one counted. Relaxed: a diagnostic tally.

std::uint64_t live_since_ = 0

The application’s now at the last liveness check that found the ONE peer moving or owing nothing (#2198). Written only by sweep_one.

mem::block_source_t *io_src_

This link’s egress store: shared frames, rings, a frame’s gather overflow (write_frame), and a derived class’s own link buffers (#1780).

egress_t egress_

The egress module (ADR-0087 §2): the rings and frames, from io_src_.

egress_peer_t peer_

The ONE peer’s egress — a dialer’s or a one-peer listener’s. A multi-peer server keeps one per session instead and leaves this one closed.

Protected Static Functions

static write_result_t write_all(int fd, std::span<const std::byte> bytes)

Write what the socket takes now of bytes to fd, never waiting (#2252).

send(2) with MSG_DONTWAIT (and MSG_NOSIGNAL — a vanished peer must not SIGPIPE the process), looped while the socket keeps taking bytes. A full socket ends the write as STALLED with the bytes it took, so no caller waits on a peer that stopped reading, and no write reads a clock. A socket-dead errno drops the rest silently (link-down is #66 lifecycle); every OTHER errno means the call itself was malformed, is re-attempted once and counted in write_fault_stats() rather than mistaken for a disconnect (#948).

Parameters:
  • fd – The destination fd; a negative fd is a no-op.

  • bytes – The bytes to write.

Returns:

How the write ended, and how many bytes reached the socket.

static write_result_t write_all_iov(int fd, std::span<const ::iovec> vec)

Write the gathered vec entries to fd as ONE record, never waiting — the zero-copy scatter-gather twin of write_all.

sendmsg(2) emits every iovec in one syscall; a stream write may stop anywhere, so the loop resumes from the first unwritten byte while the socket takes more. vec is READ-ONLY (#932): the gather is NOT consumed, so the same array may be fanned to many fds with no per-fd copy. The same ONE write-fault policy as write_all (#948).

Parameters:
  • fd – The destination fd; a negative fd is a no-op.

  • vec – The entries to gather, in order, as ONE record.

Returns:

How the write ended, and how many bytes reached the socket.

static egress_step_t write_gather(int fd, std::span<const ::iovec> vec)

One egress write turn of the caller’s own gathered record (the direct write).

See also

write_all_iov for the parameters.

static std::size_t retained_parts(std::span<std::span<const std::byte>> parts, std::span<const std::span<const std::byte>> head, const graph::value_t &value) noexcept

Lay a retained send’s record out as spans: head, then value's links.

Returns:

The span count, or parts.size() + 1 when it does not fit (the caller takes the base’s copy path, transport_t::send(head, value, lane)).

static void condemn_fd(int fd) noexcept

Condemn a peer that earned it: shutdown(SHUT_RDWR) its socket — the egress’s condemn hook, run inside the writer role (#838, #2144).

Shutdown, never close: it takes effect on this line, needs no cooperation from the stalled socket, makes every later write fail at once and raises the readable-at-EOF the driving thread turns into the ordinary remote-departure teardown (the same path slot_server_t::close_peer uses). A negative fd is a no-op.

static inline egress_step_t note_moved(std::atomic<bool> &moved, egress_step_t s) noexcept

Record s ‘s bytes in moved, a peer’s TX progress flag (#2198); returns s.

class slot_server_t : public tr::net::transport_t, protected tr::net::stream_endpoint_t

The MULTI-peer slot/poll machinery every stream SERVER shares (tcp_server_transport_t, ws_server_transport_t) — one listener, N recycled peer slots, all on one wait module (#871, #2147).

The tier above stream_endpoint_t — that one owns a single peer fd, this one owns a VECTOR of them. Everything the two servers used to restate line-for-line lives here exactly once — the slot struct and its threading rule, the bind/listen/getsockname bring-up, the free-slot-or-grow accept with its max_peers refusal and p<slot>~<gen> naming, the poll loop, the two-phase teardown, the peer query trio, and the broadcast’s pristine-iovec-copy-per-peer fan-out. Only the FRAMING and the HANDSHAKE differ between the two servers, and those are the variance points below (the msquic_endpoint_t shape: runtime virtuals, appropriate per ADR-0047 §4 because peer arrival/departure is wiring-frequency, not hot path).

**It is NOT a bus_link_t** (#1438, the provider half of #375 deliverable 3). The queries a bus facet needs are all here — they are questions about the slot table, which exists either way — but the FACET itself (the base subobject, its peer_rx_ slot, its two peer-lifecycle notifier pairs and their vtable entries) lives one tier down in bus_slot_server_t, so a build that closed the ADR-0044 bus module out carries a listener whose LAYOUT does not contain it. Concrete servers derive from tr::net::stream_server_base_t, which is that arm or flat_slot_server_t according to tr::net::kBusLinks.

Slot threading rule, ONE rule for both halves of a slot’s lifecycle: session_base_t::fd / session_base_t::open are MUTATED only on the poll thread — accept publishes the fd, then opens the session’s egress, then open (#891: “open ⇒ fd valid”); teardown clears open, shuts the fd down, closes the session’s egress (which waits out its writer), and only then resets and closes the fd. A sender reads the fd only INSIDE the session’s egress writer role (ADR-0087 §2), which the egress hands over with acquire/release, so it never sees a half-published slot or a closed one. session_base_t::name and the slot table’s growth are guarded by peers_m_, which no write is ever made under (#2263): a broadcast walks the slots by session_base_t::next with no lock, and the driving thread, the table’s only mutator, reads it with none. Every protocol buffer a slot carries is the driving thread’s alone. The destructor’s closing sweep runs after the driving thread is joined. There is no shared write lock: a stalled peer holds only its own role.

Warning

A derived destructor MUST call stop_and_join() as its FIRST act: the driving thread dispatches the variance points below into the derived object, which must still be alive when it does.

Subclassed by tr::net::bus_slot_server_t, tr::net::flat_slot_server_t

Variance points (runtime virtuals — ADR-0047 §4 wiring-frequency).

virtual mem::poly_ptr_t<session_base_t> make_session() = 0

Allocate one fresh slot of the derived server’s session type, with its endpoint facade wired to the slot.

Called under peers_m_ when no free slot exists and the cap allows growth.

virtual transport_t &endpoint_of(session_base_t &s) noexcept = 0

The directed facade peer_link returns for s : the derived slot’s own member. A virtual rather than a pointer in every slot, so a peer pays no bytes for it.

virtual bool on_accept(session_base_t &s, int fd) = 0

Per-accept setup: socket options and the slot’s protocol buffers, run after the slot is named and before its fd is published.

Parameters:
  • s – The slot being admitted (named, not yet published).

  • fd – The accepted socket.

Returns:

The slot’s INITIAL open value — true where the protocol has no handshake (a raw stream peer is open the moment it is accepted), false where the session only carries frames past a handshake the framing hook completes (WS holds open until its 101 is on the wire).

virtual void on_readable(session_base_t &s, int fd) = 0

s ‘s socket is readable: read it and frame what arrives — the derived server’s frame reader, or its handshake parser.

The read is the derived server’s, so each kind receives straight into the buffer its framing draws (ADR-0087 §1) rather than through a chunk of this tier’s. Runs on the driving thread with no transport lock held. The hook owns the decision to teardown_slot, for a peer that closed as for a framing violation.

Parameters:
  • s – The slot whose socket polled readable.

  • fd – Its socket.

virtual void on_slot_reset(session_base_t &s) = 0

Reset the slot’s protocol buffers as it is recycled (teardown side).

Parameters:

s – The slot being freed; its fd is already closed.

inline virtual bool mid_frame(const session_base_t &s) const

s ‘s peer has begun a frame or a handshake it has not finished — the RX half of what a liveness check finds owed (#2198). Poll thread, after on_readable. Default: never.

inline virtual void on_slot_publishing()

TEST SEAM dispatch: run on the accept path with the fd published and the slot not yet open (its egress still closed).

Default: nothing. A derived server overrides it to fire its own hook pointer — the instant a test holds open to prove the two stores are atomic to senders (#891).

static inline slot_server_t &server_of(const session_base_t &s) noexcept

The server s belongs to: its wait context, set when the slot is made.

The peer-LIFECYCLE seam (#1438) — the only two places this tier needs the facet.

publish_peer_up and teardown_slot run HERE, in the tier that owns the slot table, but the notifiers they end in are bus_link_t’s protected members and this tier is no longer a bus_link_t. These two hooks are the join: inert in the base, overridden by bus_slot_server_t to fire notify_peer_up / notify_peer_down.

Virtual rather than the static seam the per-frame tier select uses, because these are the base tier’s own call sites and a base cannot resolve a derived name statically. The cost is two vtable slots per concrete server and one indirect call per peer ARRIVAL and DEPARTURE — wiring frequency, explicitly the tier ADR-0047 §4 admits a runtime virtual at — and zero bytes per listener, since the vptr is already there.

inline virtual void announce_peer_up(peer_handle_t handle, std::string_view peer)

Announce an arrival to the facet (no-op without one).

inline virtual void announce_peer_down(peer_handle_t handle, std::string_view peer)

Announce a departure to the facet (no-op without one).

Public Types

using peer_visitor_t = bus_link_t::peer_visitor_t

The peer-visitor shape the query trio speaks — bus_link_t’s, so the facet arm’s overrides are the same signature and no consumer sees two.

Public Functions

inline virtual transport_drop_stats_t drop_stats() const noexcept override

The server’s shed-frame counters, summed over every peer (#932, #2482).

inline bool ok() const noexcept

True if the listen socket is bound and listening — and, on a target that closed the bus module out, only if this server did not ask to be peer-named (#375).

The came-up predicate make_checked asks (#1059), so the second limb is what turns a kBusLinks = false build’s refusal into an ordinary “this link did not come up” for every door — the SPEC factory and a direct constructor alike. It is a REFUSAL rather than a quiet demotion to FLAT because a demotion is not observable and this is: a deployment that configured peer-named addressing on a build that carries none has a configuration error, and a listener that answers ok() would hide it.

At the default binding the if constexpr is discarded and this is listen_fd_ >= 0, the predicate it always was — same instructions, verified by object-file cmp.

inline std::uint16_t local_port() const noexcept

The actual bound TCP port (resolves an ephemeral 0 request).

inline std::uint64_t stalled_tx() const noexcept

Write turns that found a peer’s socket full and moved nothing, summed over every peer this server has carried (#838, #2144). Counted only: a session that stopped reading is closed by sweep (#2899).

inline std::size_t max_peers() const noexcept

The concurrent-peer admission cap ENFORCED on the accept path: the injected cap, or kDefaultMaxPeers for 0, so never 0.

inline bool peer_named() const noexcept

The mode authority (#889): the peer_named this server was constructed with.

The ONE answer to “which mode is this link in” — bus(), the two servers’ per-frame tier select, and the departure branch in teardown_slot all key off this flag (not off whether a peer sink happens to be installed), and bus_link_t refuses every peer-named wiring call while it is false.

It reads bus_mode, not the constructor argument, so the one answer stays one answer on a target that closed the bus module out: there the server is FLAT in every respect, and ok is what reports that the configuration was refused (#375).

Not override here since #1438: this tier is not a bus_link_t, so there is no virtual to override until bus_slot_server_t re-declares it. The ANSWER is unchanged, and so is every caller’s spelling.

void enumerate_peers(const peer_visitor_t &visit) const

Visit the currently-OPEN peers’ names, p<slot>~<gen> (#426).

std::string_view peer_name(peer_handle_t peer, std::span<char> scratch) const

Resolve an inbound handle back to its peer name, p<slot>~<gen> (#1294).

A pure function of the handle — its index and its tenancy generation — exactly as the accept-side stamp is (ADR-0073 §2), formatted into scratch with no lock and no slot lookup, so the router pays nothing for asking on the delivery callback that a name string used to arrive on.

inline virtual peer_handle_t inbound_peer() const noexcept override

The in-flight frame’s peer — the WHO seam, answered at either setting of peer_named (#375 Part 2, ADR-0082).

A peer-named server tags every frame through the bus seam and never needs this. A FLAT one cannot: it has exactly one routing identity for every peer it carries, and the p<slot>~<gen> tag it computes is thrown away at the delivery fork. This is where that tag survives — stamped on the driving thread immediately before the flat delivery, read back, on that same thread, by the router’s terminus, and cleared once the frame has been handed up. Outside a delivery it answers the default (invalid) handle (#1915).

Warning

Poll-thread state, meaningful ONLY inside a receive callback. It is a plain member and not an atomic on purpose: one server owns one driving thread (ADR-0071’s shared-nothing epoll), the store and every legitimate load happen on it, and paying for an atomic on the per-frame delivery path to make an off-thread read merely defined rather than correct buys nothing.

virtual read_tally_t *inbound_tally() noexcept override

The delivering session’s READ tally (#2774): its slot, found by inbound_peer’s handle; null outside a delivery.

virtual std::string_view peer_subject(peer_handle_t peer, std::span<char> scratch) const override

The SUBJECT token of peer — p<slot>~<gen>, this kind’s session identity.

The same string peer_name answers with, reachable without the bus_link_t facet; see the implementation’s note on why the two coincide in value and not in availability.

transport_t *peer_link(std::string_view peer)

Resolve an open peer’s name to its directed sending endpoint.

Owned by the peer’s slot and pointer-valid for this server’s lifetime (slots are never freed, only recycled). After the peer departs its sends no-op until the slot is reused.

Return values:

nullptr – peer names no currently-open connection.

The endpoint peer_link resolves p<slot>~<gen> to, found by the handle’s slot index instead of by comparing names (#1941). Session-scoped like peer_link, so a departed session’s handle names nobody.

Return values:

nullptr – peer is not valid, or no open session holds it.

virtual void send_to(std::uint64_t reply_to, std::span<const std::span<const std::byte>> iov) override

A reply to the session whose handle reply_to carries, and to no other (#2911).

The token is inbound_reply_to’s: the delivering session’s handle. A session that has gone, or a token that names none, drops the frame and counts it in dropped_tx.

bool close_peer(std::string_view peer)

Close the open peer named peer, freeing its slot for reuse.

Shuts the socket down (SHUT_RDWR) under peers_m_ (teardown un-names a slot under the same lock before it closes the fd); the driving thread’s next pass observes the close and runs the IDENTICAL remote-FIN teardown, so the recycle is asynchronous (the shut-down socket reports a hangup at once) and no buffer the driving thread alone owns is ever touched off-thread.

Return values:
  • true – peer named an open connection and its socket was shut down.

  • false – peer names no currently-open connection.

virtual std::uint64_t sweep(std::uint64_t now, std::uint64_t deadline) override

The application’s liveness check over every open peer (#2198, transport_t::sweep).

A peer owes TX while a frame waits on its wire, and RX while it has begun a frame or a handshake and not finished it (mid_frame). One that owed a direction and moved no byte in it since its record fell below deadline is shut down exactly as close_peer does it, under peers_m_, and counted in frozen_closed. An idle peer — owing nothing — is never closed.

Returns:

When the earliest owing peer is next due, 0 when none owes.

virtual void shut_down() override

See transport_t::shut_down : every session torn down in one walk and the listen socket released (shut_down_slots). One override for both stream servers.

inline std::size_t frozen_closed() const noexcept

Peers the application’s liveness check closed as frozen, summed over every peer this server has carried (#2198).

Protected Functions

inline slot_server_t(std::size_t max_peers, bool peer_named, mem::block_source_t &src = mem::net_source(), mem::block_source_t &state_src = mem::net_source(), wait_module_t *node = nullptr)

Constructs inert: no listen socket, no slots, no thread.

Parameters:
  • max_peers – Requested concurrent-peer admission cap; a deployment-injected bound (RFC-0006) — a connection beyond it is accepted and immediately closed (a clean refusal, not a hung SYN). 0 takes kDefaultMaxPeers; any other value is enforced as given. Read the enforced value back from max_peers.

  • peer_named – Expose the bus_link_t facet (see bus).

  • src – The store every session’s egress rings, the shared frames and the egress gathers are drawn from (the link’s memory.io). Must outlive the server.

  • state_src – The store the slot table, every session and each poll pass’s tables are drawn from (the link’s memory.state, #1780). Must outlive the server.

  • node – The node’s wait module, or null for a thread of the server’s own (posix_endpoint_t).

~slot_server_t()

Closes the listen socket and sweeps every slot’s fd.

Runs AFTER the derived destructor, whose first act was stop_and_join — the poll thread is gone, so nothing races this sweep and no virtual is dispatched from it.

bool bind_listen(std::uint16_t bind_port)

The shared bring-up: socket + SO_REUSEADDR + bind + listen(SOMAXCONN) + getsockname, publishing listen_fd_ and bound_port_.

SOMAXCONN is the OS’s own accept-queue bound — admission is per-connection in the accept path (the max_peers deployment cap), never a synthetic backlog.

Parameters:

bind_port – TCP port to listen on (host byte order; 0 → ephemeral, resolved into local_port).

Return values:

false – The socket could not be bound/listened; the caller must NOT spawn the driving thread (ok() stays false).

void close_listen() noexcept

Close the listen socket, leaving ok() false: a bind that failed, or a poll thread whose spawn was refused (#2288).

bool serve(std::size_t stack_size, mem::block_source_t &stack_src)

Begin serving: wait on the listening socket (#2147). Call it from the DERIVED constructor, last, once every member the variance points touch is initialized.

The listener and every session are sources of one wait module, so no per-peer thread exists (#362) and the wait has no timeout.

Parameters:
  • stack_size – The fallback thread’s stack (see posix_endpoint_t::start).

  • stack_src – The link’s memory.stack.

Return values:

false – The wait could not begin: the caller leaves the listener inert.

void stop_and_join()

Stop waiting on the listener and on every session and wait it out (idempotent; posix_endpoint_t::stop_and_join, then shut_down_slots without the teardown): the FIRST act of a derived destructor, which hides posix_endpoint_t::stop_and_join. The link’s one join, off every callback thread (asserted).

session_base_t *slot_at(std::size_t i)

Session i of the table, or null past its end. Read under peers_m_ , which the accept grows the table under, so a walk by index is safe against a concurrent accept on the link’s driving thread.

void teardown_slot(session_base_t &s)

Tear one slot down and free it for reuse (driving thread only).

Off the wait first, waiting for nothing, so no new callback of the slot starts after (one in flight may tear the same session down beside this one). Then, under peers_m_ , stop name resolution (so no new sender targets the dying slot), clear open and ask whether any other session is still open, in one critical section so that of concurrent teardowns exactly one closes the last open session. Then shut the fd down and close the session’s egress — which waits out a writer in flight — BEFORE resetting the fd and close(2)ing it. on_slot_reset clears the protocol buffers, except on a shut link, whose session buffers live until its destructor. The egress close and the departure seam run once per session, whichever of concurrent teardowns gets there first. The departure seam (RFC-0009 §D.5) fires LAST with no transport lock held — the notifier re-enters the routing plane. Which seam depends on peer_named() — the departed peer’s own name when peer-named, the whole link when flat, and then only once no open session is left (#889).

Parameters:

s – The slot to recycle.

void shut_down_slots(bool tear_down)

The transport_t::shut_down of a stream server: stop waiting, tear every session down exactly as a remote close does (teardown_slot), and shut the listen socket down. Idempotent. Joins nothing and closes nothing: the sockets are shut down, and the destructor closes them.

ONE walk of the table: each slot comes off the wait and, with tear_down, is torn down at once (teardown_slot disarms it first), so a session still waiting may depart on its own callback while an earlier one is torn down.

Parameters:

tear_down – False for stop_and_join : every slot is only detached, which waits out its callback in flight.

void broadcast(std::span<const ::iovec> rec, const graph::value_t *value = nullptr, const graph::delivery_lane_t &lane = {})

Fan one already-encoded gathered record to EVERY open peer through its egress (ADR-0087 §2, #2144).

An idle peer takes rec straight from the caller’s gather (read-only, #932); a peer with a write in flight, or whose socket takes only part of it, gets a reference to ONE shared frame built at most once for the whole fan-out (the framing copied, value kept by reference). Every write is nonblocking, so a stalled peer costs the round one refused syscall and never delays the peers behind it; its frames wait in its own ring for lane. Shed frames and stalls are counted.

The walk takes no lock (#2263): it follows session_base_t::next, so accept, teardown, the receive loop and every other sender run beside it. A session that departs mid-walk has its egress closed, which refuses the claim (a counted shed) or waits out a write already inside it; a session admitted mid-walk may take the record, as it would from a broadcast that began a moment later.

Parameters:
  • rec – The whole record (framing first, payload after), for the direct writes.

  • value – The value whose links end rec, kept by reference in a shared frame (frame_of), or null: the frame copies all of rec.

  • lane – The vertex the record comes from, or the control lane (a default).

void send_to(session_base_t &s, std::span<const ::iovec> rec, const graph::value_t *value = nullptr, const graph::delivery_lane_t &lane = {}, std::uint32_t tenancy = 0)

Send one record to ONE session through its egress — the directed facades’ door. Parameters as broadcast; a departed session sheds, counted.

Parameters:

tenancy – The generation of the session the record is for (#2911), or 0 for whichever session holds s. A slot another session took since sheds the record, counted.

void publish_peer_up(const session_base_t &s)

Announce s as a live, named session — the arrival half of the seam whose departure half is teardown_slot’s notify_peer_down (#1223 step 2).

Called from the POLL THREAD at the moment the slot becomes usable to senders, which is kind-specific and therefore not a single site: a raw stream peer is live the instant it is accepted, a WS peer only once its 101 is on the wire — the same two transitions open itself is stored at, so arrival and departure bracket exactly the same interval. A FLAT (not peer_named) server announces nothing: it has one routing identity for every peer it carries, so there is no per-session identity to announce.

Fired with NO transport lock held, per the bus facet’s arrival-notifier contract — the notifier re-enters the routing plane and takes graph locks.

void open_session(session_base_t &s, std::span<const std::byte> first = {})

Open s to senders: its egress, then first as its first frame (a WS server’s 101; empty: none), then open (driving thread; the fd is already published).

inline bool bus_mode() const noexcept

The constructed mode AS THIS BUILD CAN HONOUR IT — the one predicate every peer-named branch in this class and its two derived servers reads (#375).

peer_named_ is the REQUEST; this is the request conjoined with whether the target carries a bus module at all (tr::graph::default_config_t::kBusLinks). The two differ in exactly one build, the one that closed the module out, and there this is constant false — so the per-frame tier select, the departure seam, the arrival seam and bus() all collapse to their FLAT arms at compile time and the peer-named halves are never emitted. That build cannot reach those arms at run time either, because ok refuses such a server outright; the folding is what makes the refusal FREE rather than merely safe.

Non-virtual and inline on purpose: it is read once per inbound frame on the driving thread, where peer_named()’s virtual would be a per-frame dispatch. At the default binding it IS peer_named_ — one member load, the instruction sequence that was there before.

Protected Attributes

mutable tr::mutex_t peers_m_

Guards the slot vector’s growth and every slot’s NAME — the cross-thread reads (enumerate_peers / peer_link) against the driving thread’s accept/teardown. See the class-level threading rule. Never held across a write (#2263): a broadcast walks first_ instead.

mem::block_array_t<mem::poly_ptr_t<session_base_t>> slots_

The peer slots: insert-only, recycled in place, never freed early.

std::atomic<session_base_t*> first_ = {nullptr}

The slot admitted last, or null: the head of the session_base_t::next chain, newest first (#2263). Stored only by the driving thread, release.

int listen_fd_ = -1

The bound+listening socket (-1 = not bound).

std::uint16_t bound_port_ = 0

The resolved bound port (see local_port()).

std::size_t max_peers_ = 1

The ENFORCED admission cap (RFC-0006), resolved once at construction — never 0.

bool peer_named_ = false

Expose the bus facet — a wiring-time deployment choice. Stored HERE rather than in the facet arm because ok reads it to refuse a peer-named server on a build that carries no facet at all (#375), and that refusal has to work in the arm where the facet does not exist.

peer_handle_t delivering_ = {}

The peer whose frame is being delivered RIGHT NOW — inbound_peer’s storage. Stamped by the derived server’s receive loop immediately before it hands a frame up the FLAT tier, on the driving thread, and never read off it; reset to the default handle after each frame, delivered or not (#1915).

Protected Static Attributes

static constexpr std::size_t kPeerNameChars = 24

Bytes a session’s p<slot>~<gen> name holds, terminator included: p, the widest slot index, ~ and the widest generation.

struct session_base_t : public tr::net::wait_source_t

The protocol-agnostic half of ONE peer slot.

Slots are never destroyed while the server lives — recycled in place on departure — so the endpoint facade peer_link hands out stays pointer-valid for the server’s lifetime. A derived server extends this with its own framing state (a length-prefix framer, a WS reassembler + byte buffers) and owns the concrete endpoint facade object (endpoint_of). Its inherited wait_source_t::ctx is this server, set once when the slot is made, so a facade finds its server through its slot (server_of). See the class-level threading rule for who may touch what.

Public Functions

session_base_t() = default

Constructs a free slot (no fd, not open, unnamed). Its inherited wait_source_t is the session’s registration with the wait module, and its fd is the peer socket: -1 ⇒ free slot.

inline std::string_view name_view() const noexcept

name as a view; empty while the slot is unnamed.

Public Members

std::atomic<bool> open = {false}

True while the session may carry frames.

std::atomic<bool> tx_moved = {false}

A byte of ours went out since the last liveness check (#2198). Set by the writer, taken by sweep; an accept sets it.

std::atomic<bool> rx_moved = {false}

The peer’s socket was readable since the last liveness check (#2198). Set by the driving thread, taken by sweep; an accept sets it.

std::atomic<bool> rx_owed = {false}

The peer has begun a frame or a handshake and not finished it (#2198): mid_frame as of the driving thread’s last pass over it.

char name[kPeerNameChars] = {}

The peer’s routable NAME, p<slot>~<gen> — the slot index and this tenancy’s generation (ADR-0073 §2, #426): stamped at accept, moved out by teardown (the eviction seam), so a reused slot gets a FRESH name and a route held for the previous session names nobody. A legal path segment, unlike the old <ip>:<port>. It identifies a SESSION, not a device — a reconnecting peer may land in a different slot; device-stable identity is a named link (RFC-0014).

peer_handle_t handle

This session’s identity HANDLE, (slot index, generation) — what the peer-receiver seam tags every inbound frame with (#1294).

Minted at accept and RETIRED at teardown (generation = 0, i.e. not peer_handle_t::valid), so a handle minted against the session that used to hold this slot never matches its successor — the same validate-on-use stamp the ESP link’s session ref carries. Written on the driving thread under peers_m_ beside name, and read on that thread by the delivery path.

std::atomic<std::uint32_t> gen_seq = {0}

This slot’s monotonic tenancy counter — the source of the generation handle is minted at. Bumped once per accept (never reused, never zero), so the counter survives the retire that clears handle. Bumped before the egress opens, so a sender inside the egress reads the generation of the session it writes to (#2911): atomic for that reader.

session_read_tally_t read_tally = {}

This session’s READs in the current run (#2774): written by the driving thread, and handed to the router through inbound_tally while it delivers the session’s frame; reset at accept. No byte when the budget is off.

egress_peer_t egress

This session’s egress (ADR-0087 §2, #2144): its frames waiting per vertex, and its writer role. Closed while the slot is free; reset as the slot is recycled, so a stalled peer’s frames are never inherited by its successor in the slot.

std::uint64_t live_since = 0

The application’s now at the last liveness check that found this peer moving, or owing nothing (#2198). Written only by sweep, under peers_m_.

std::atomic<session_base_t*> next = {nullptr}

The slot admitted before this one, or null: the chain broadcast walks without peers_m_ (#2263). Stored once, before this slot is published at the chain’s head, and never again: slots are recycled in place, never freed, so a walker that loaded a slot can always follow it.

Protected Functions

~session_base_t() = default

Destroyed only as the derived slot it is: the slot table’s tr::mem::poly_ptr_t records that slot’s destructor (#2022), so the base carries no vtable and no deleting destructor.

class bus_slot_server_t : public tr::net::slot_server_t, public tr::net::bus_link_t

The stream-server arm WITH the ADR-0044 bus facet — slot_server_t plus the bus_link_t base subobject, its peer_rx_ slot and its two peer-lifecycle notifier pairs (#1438).

Everything a bus facet needs to ANSWER already lives one tier up, because every one of those questions is a question about the slot table: p<slot>~<gen> is a pure function of the slot’s handle either way. What lives HERE is the facet itself — the identity transport_t::bus() hands out, the peer-named receiver slot, and the arrival/departure notifiers — so the four bus_link_t pure virtuals below are one-line forwards to the implementations they always had, not a second copy of them.

Re-declaring them here is also what keeps the names UNAMBIGUOUS: with the same signature reachable through slot_server_t and through bus_link_t, an unqualified server.enumerate_peers(...) would otherwise be an ambiguous lookup; the override in the most-derived tier hides both.

The per-frame peer-delivery seam, live — the tier select in both servers’

receive loops reaches peer_rx_ through exactly these.

inline void deliver_to_peer(peer_handle_t peer, view::view_t frame)

Deliver an owning view up the peer-named tier.

inline bool deliver_to_peer_rope(peer_handle_t peer, view::rope_t frame, mem::mem_backend_t &backend)

Deliver an owning rope up the peer-named tier; a span-only sink materializes a multi-link one from backend, the receiving link’s rx source.

Returns:

Whether a sink received it (receiver_slot_t::deliver_rope, #2504).

Public Types

using peer_visitor_t = bus_link_t::peer_visitor_t

The one visitor shape — declared here so the name reaching this tier through two bases (identical types, ambiguous LOOKUP) resolves to one declaration.

Public Functions

inline virtual bus_link_t *bus() override

The bus_link_t facet (ADR-0044) when constructed peer_named, else nullptr. With the facet the router tags inbound frames per peer (each peer gets its own return-route identity and a dst segment routes back to that one session); without it the link keeps point-to-point hop naming — inbound frames carry the registered child NAME and send() fans out to every open peer.

Note

Departure eviction (RFC-0009 §D.5) follows the same split: peer-named mode evicts just the departed peer’s edges (notify_peer_down(name)), while FLAT mode reports the whole link down (notify_down()) — but only when the LAST open session departs (#889). A flat link has ONE routing identity for all its peers (the registered child NAME), so firing that on a mid-life close would evict the surviving peers’ edges too.

inline virtual bool peer_named() const noexcept override

The mode authority as the facet’s own virtual — slot_server_t::peer_named, so “which mode is this link in” still has exactly one answer (#889).

inline virtual void enumerate_peers(const peer_visitor_t &visit) const override

The facet’s spelling of slot_server_t::enumerate_peers.

inline virtual std::string_view peer_name(peer_handle_t peer, std::span<char> scratch) const override

The facet’s spelling of slot_server_t::peer_name.

inline virtual transport_t *peer_link(std::string_view peer) override

The facet’s spelling of slot_server_t::peer_link.

The facet’s spelling of slot_server_t::peer_link_of.

inline virtual bool close_peer(std::string_view peer) override

The facet’s spelling of slot_server_t::close_peer.

Protected Functions

~bus_slot_server_t() = default

Destroyed only as the concrete server it is, never through this base (#2022): the derived destructor’s stop_and_join must run first.

inline virtual void announce_peer_up(peer_handle_t handle, std::string_view peer) override

Arrival: fire the facet’s peer-up notifier (#1223 step 2).

inline virtual void announce_peer_down(peer_handle_t handle, std::string_view peer) override

Departure: fire the facet’s peer-down notifier (RFC-0009 §D.5).

inline slot_server_t(std::size_t max_peers, bool peer_named, mem::block_source_t &src = mem::net_source(), mem::block_source_t &state_src = mem::net_source(), wait_module_t *node = nullptr)

Constructs inert: no listen socket, no slots, no thread.

Parameters:
  • max_peers – Requested concurrent-peer admission cap; a deployment-injected bound (RFC-0006) — a connection beyond it is accepted and immediately closed (a clean refusal, not a hung SYN). 0 takes kDefaultMaxPeers; any other value is enforced as given. Read the enforced value back from max_peers.

  • peer_named – Expose the bus_link_t facet (see bus).

  • src – The store every session’s egress rings, the shared frames and the egress gathers are drawn from (the link’s memory.io). Must outlive the server.

  • state_src – The store the slot table, every session and each poll pass’s tables are drawn from (the link’s memory.state, #1780). Must outlive the server.

  • node – The node’s wait module, or null for a thread of the server’s own (posix_endpoint_t).

class flat_slot_server_t : public tr::net::slot_server_t

The stream-server arm WITHOUT the ADR-0044 bus facet — the layout a target that closed the bus module out actually gets (#1438).

Adds nothing to slot_server_t but the INERT half of the per-frame peer-delivery seam. Those members exist so the two servers’ tier select is ONE piece of source under both bindings; they are unreachable here, because the select is guarded by slot_server_t::bus_mode(), which this arm only ever compiles as the constant false.

The seam is deliberately NOT virtual, unlike the two peer-lifecycle hooks: it is read once per inbound FRAME, and the concrete servers derive from tr::net::stream_server_base_t, so which arm’s members they see is a compile-time fact. Nothing is dispatched.

The per-frame peer-delivery seam, inert (see @ref bus_slot_server_t for the live

half). Every one of these is dead code under this arm’s own bus_mode().

static inline void deliver_to_peer(peer_handle_t peer, view::view_t frame)

No peer tier to deliver an owning view to.

static inline bool deliver_to_peer_rope(peer_handle_t peer, view::rope_t frame, mem::mem_backend_t &backend)

No peer tier to deliver an owning rope to: never delivered.

Protected Functions

~flat_slot_server_t() = default

Destroyed only as the concrete server it is, never through this base (#2022): the derived destructor’s stop_and_join must run first.

inline slot_server_t(std::size_t max_peers, bool peer_named, mem::block_source_t &src = mem::net_source(), mem::block_source_t &state_src = mem::net_source(), wait_module_t *node = nullptr)

Constructs inert: no listen socket, no slots, no thread.

Parameters:
  • max_peers – Requested concurrent-peer admission cap; a deployment-injected bound (RFC-0006) — a connection beyond it is accepted and immediately closed (a clean refusal, not a hung SYN). 0 takes kDefaultMaxPeers; any other value is enforced as given. Read the enforced value back from max_peers.

  • peer_named – Expose the bus_link_t facet (see bus).

  • src – The store every session’s egress rings, the shared frames and the egress gathers are drawn from (the link’s memory.io). Must outlive the server.

  • state_src – The store the slot table, every session and each poll pass’s tables are drawn from (the link’s memory.state, #1780). Must outlive the server.

  • node – The node’s wait module, or null for a thread of the server’s own (posix_endpoint_t).

Datagram and stream transports

The memory a link draws from, as the one nested member every per-kind link config carries (#1593, RFC-0028 §8.2).

Shared, and deliberately tiny: the transport-vertex lean rule keeps kind-private knobs in the kind’s own config struct, and this holds only the two memory planes every link kind has. A deployer that bounds a node points both at its slab; since RFC-0028 slice 10 a mem_backend_t IS a block_source_t, so one synchronized pool can serve both.

Each must outlive the link, and each must be thread-safe on a target where the link’s receive thread and a sender run concurrently.

Public Functions

io, or the process net sub-pool when a config left it null.

state, or the process net sub-pool when a config left it null.

stack, or the process thread-stack source when a config left it null.

Public Members

The RX memory seam (ADR-0042 §2): each inbound frame is read into a segment drawn from it. Exhaustion is backpressure — the frame is dropped and counted, never an OOM. Default: the process net sub-pool (#1777). A kind whose zero-copy delivery is opt-in (the ESP-IDF httpd_ws_link_t

) defaults it to null, meaning “borrowed

delivery”.

The link’s EGRESS store (ADR-0079, #873): the per-frame scratch a kind draws while one outbound frame is in flight — ws_client_transport_t’s masked-frame copy and the base class’s gather temporary. A kind with no such draw ignores it. Default: the process net sub-pool (#1777), not null. So a node-wide default (transport_vertex_t’s link_memory, #2574) that leaves this out puts every built-in link’s egress store on the net pool instead of the vertex’s egress_src; write .io = nullptr to keep egress_src (#2612).

The link’s connection-STATE store (#1780): what a kind holds for as long as a connection or the link lives — the link’s own endpoint object, a server’s slot table and per-peer sessions, handshake and receive-accumulation buffers, a QUIC stream-context table. Peer-provoked, so the receiving link pays: a refusal at runtime sheds that one peer or frame, counted; only a refusal while the link is being built leaves it inert (ok() false). Default: the process net sub-pool. Kept apart from io so a bound on in-flight egress never caps how many peers can connect, and the reverse.

The link’s THREAD-STACK store (#2288): where each receive or dispatch thread the link spawns (tr::static_thread_t) draws its stack and task block on ESP-IDF, and its boot record on a host. Its own plane, not state, because a stack is the largest single block a link draws: on an MCU it would starve a shared value pool, and a bound on peers or frames must never cap whether a link can receive at all. Default: tr::mem::stack_source(), which on an MCU arena build is a static region of its own. A refused spawn while the link is built leaves it inert (ok() false); one at a later bring-up step brings the link down. Either way the source’s census counts the refusal. Must outlive the link.

struct udp_config_t

udp_transport_t’s knobs as one aggregate (#1593), after the local port and peer.

Public Members

link_memory_t memory = {}

The link’s memory (link_memory_t). rx: when a rope receiver is installed, each datagram is recvfrom’d straight into a fresh segment drawn from it, sized min(kMaxDatagram, rx->max_segment_size()) — so the backend BOUNDS the datagram a node accepts. Exhaustion is backpressure — the datagram is dropped and dropped_rx ticks, never an OOM.

std::size_t max_frame = 0

The universal :settings max_frame receive cap, bytes — the largest datagram accepted (0 → udp_transport_t::kDefaultMaxFrame, one Ethernet MTU; values above udp_transport_t::kMaxDatagram are inert). A longer datagram is refused (malformed_rx ticks), provided the backend can furnish max_frame + 1 bytes (#1074). It also sizes the RX segment, so an owning link holds about max_frame bytes at rest, not 64 KiB (#2132), and a borrowed-span link whose cap fits graph::kUdpStackScratchBytes holds none (#2142).

std::size_t recv_stack = 0

Fallback-thread stack size in bytes, 0 = platform default. The receive loop keeps graph::kUdpStackScratchBytes + 1 bytes on it (#2142), so a nonzero value below udp_transport_t::kMinRecvStack is refused at construction (udp_transport_t::recv_stack_refused), never clamped.

wait_module_t *wait = nullptr

The node’s wait module (#2147): the link puts its sockets on it and owns no thread, and the application drives it (wait_module_t::run). Null: a thread of the link’s own drives a private one, sized by recv_stack. Must outlive the link.

class udp_transport_t : public tr::net::transport_t, private tr::net::posix_endpoint_t

A single-peer UDP datagram transport_t (one datagram = one frame).

Binds a local UDP socket and sends to one peer; a listener-mode instance learns its peer from the first inbound datagram’s source address. Supports the owning rope-receiver seam (ADR-0042 §2): each datagram is received straight into a refcounted segment from a host-injected mem_backend_t, which also bounds the datagram size a node accepts.

The ingress bound gains its second half: the universal :settings max_frame key (effective_max_frame), the same key tcp_transport_t, the ws transports, quic and webtransport accept. A datagram longer than the configured cap is refused and counted in drop_stats().malformed_rx instead of being delivered, and the RX segment is drawn at the cap rather than at kMaxDatagram. Unset, the cap is kDefaultMaxFrame. That refusal is unconditional on the borrowed-span path; on the owning path it holds while the injected backend can furnish max_frame + 1 bytes — a backend bounded tighter than the cap truncates the datagram before the cap is ever consulted (#1074). On the borrowed-span path a datagram longer than the smaller of the cap and the backend’s max_segment_size() is refused whole (#1783). That path receives on the receive thread’s stack when the cap fits graph::kUdpStackScratchBytes (#2142), so the link holds nothing at rest; otherwise, and on the owning path, the link holds ONE segment of max_frame + 1 bytes from memory.rx.

The span a borrowed-span sink is handed is that receive buffer: the receive thread’s stack array or this link’s own segment, writable for the duration of the call. An owner that decrypts in place, as the Noise link does (RFC-0033 §5.8), may write it; nothing else reads it after the callback returns.

Public Functions

udp_transport_t(std::uint16_t bind_port, std::string_view peer_host, std::uint16_t peer_port, const udp_config_t &config = {})

Bind a local UDP socket on bind_port and target peer_host : peer_port.

bind_port 0 = ephemeral (see local_port). peer_host is an IPv4 dotted-quad (e.g. “127.0.0.1”). Listener mode: with an unresolved peer (peer_host empty or peer_port 0) the transport LEARNS its peer from each inbound datagram’s source address — the single-peer UDP-server shape that lets a config-created LISTEN-module connection (#83) reply to a dialing client whose ephemeral port is unknowable in advance; until the first datagram arrives, send is a no-op.

Parameters:

config – The link’s knobs (udp_config_t): memory (the RX seam that bounds the datagram), receive cap, fallback-thread stack.

virtual void shut_down() override

See transport_t::shut_down.

virtual void send(std::span<const std::byte> frame) override

Emit one frame (a complete TLV’s bytes) onto the wire.

  • **void is deliberate, and stays.** A returned status here would be a promise the plane cannot keep: on every real link the frame is queued and written later, on another task, so “sent” at this call site can only ever mean “accepted”, which is what a void already says. Callers MUST NOT read a successful return as delivery.

  • A link that drops a frame MUST count it in drop_stats — dropped_tx for a frame the caller believed sent, dropped_rx / malformed_rx on the ingress side. That counter is the ONLY feedback this plane offers, which is exactly why it is mandatory rather than a courtesy: an uncounted drop is invisible to a deployment, and core/STYLE.md §Introspection forbids the silent loss it hides.

  • The counter is how a monitor closes the loop. The tally is wire-readable as read <any-vertex>:stats.link.<child> (RFC-0010 Amendment 2), so a supervisor polls it and reacts, in place of the per-frame refusal v1 has no room for.

The transport plane is BEST-EFFORT by contract, and a drop MUST be counted.

This is the one place in libtracer where the refuse-by-value law (docs/reference/22-backpressure-and-sizing.md §1, the third reading rule) does not apply, and the reason is not an oversight: there is no wire carrier for backpressure in v1 (the per-edge credit window is parked as the v2 escalation, RFC-0025 §4.6.1 clause 7). A link that could refuse by value would have nobody to refuse to — the caller is a forwarding hop with a frame it cannot un-receive, and the peer cannot be told to slow down. So the contract is:

Note

Re-opening this is scoped to M5

(a real socket transport), where a link that owns its own socket buffer has something to push back WITH. Until then, “counted

shed” IS the transport contract.

virtual void send(std::span<const std::span<const std::byte>> iov) override

Scatter-gather send: emit the gathered spans as ONE frame, no flatten copy.

Hand a rope’s to_iovec() straight to the wire. The default gathers into a temporary and calls send(std::span<const std::byte>); transports with native scatter-gather (sendmsg/writev/RDMA SGE) override this to avoid the copy.

**The same best-effort contract as send(std::span<const std::byte>)**: void is deliberate, and a gather this overload cannot complete is DROPPED and COUNTED in drop_stats (dropped_tx) — never truncated, and never silently lost. The default body below is where that rule is enforced for every transport that does not override it.

Parameters:

iov – The spans to emit, in order, as a single frame.

virtual void send_to(std::uint64_t address, std::span<const std::span<const std::byte>> iov) override

Send iov as one datagram to address, whatever the link’s own peer is.

The addressed form of send, for an owner that keeps its own peer address: the Noise link answers a first message at that datagram’s source and moves its session’s address only on an authenticated message (RFC-0033 §5.4), so it never sends to the peer this link learned from the last datagram. The same best-effort contract as send: a datagram with no socket, no address or no gather store, or one the socket refuses, is dropped and counted in drop_stats().dropped_tx.

Parameters:

address – A packed endpoint, as inbound_source and peer_address give it; 0 is no address.

inline virtual std::uint64_t inbound_reply_to() const noexcept override

A reply goes to the datagram’s source (#2911): inbound_source.

inline std::uint64_t inbound_source() const noexcept

The source of the datagram being delivered, packed as (ip << 16) | port.

Warning

Valid only inside a receive callback, on the receive thread, like transport_t::inbound_peer.

inline std::uint64_t peer_address() const noexcept

The peer send targets, packed as inbound_source packs it: the configured one, or in listener mode the last datagram’s source; 0 = none yet.

inline virtual bool delivers_ropes() const override

True — this transport honors set_rope_receiver (ADR-0042 §2): one datagram = one frame = one refcounted segment from the injected backend, handed up owning; span-only sinks keep the borrowed path.

inline bool ok() const noexcept

True iff the socket bound successfully. False too when recv_stack_refused.

inline bool recv_stack_refused() const noexcept

True iff the constructor refused udp_config_t::recv_stack (#2142): nonzero and below kMinRecvStack, so the receive loop’s stack scratch would not fit. No socket is opened and no thread started; ok is false.

inline std::uint16_t local_port() const noexcept

The bound local port (resolves an ephemeral bind_port of 0).

inline virtual transport_drop_stats_t drop_stats() const noexcept override

This link’s shed-frame counters (#932, #2482).

dropped_rx: datagrams dropped because the RX backend was exhausted (backpressure, ADR-0039 §4 / ADR-0042 §2), never an OOM. malformed_rx: datagrams over effective_max_frame, the peer’s fault; nothing is torn down and the next datagram is served. dropped_tx: no peer learned or configured yet, no socket, a refused gather store, or a sendmsg the socket refused or cut short (#2279). A shed datagram is never retried: the link carries no acks, and the next value supersedes it.

inline std::size_t effective_max_frame() const noexcept

The largest datagram accepted: min(max_frame, kMaxDatagram), with 0 meaning kDefaultMaxFrame. The RX segment is additionally bounded by the injected backend’s max_segment_size(), which never widens this.

Public Static Attributes

static constexpr std::size_t kMaxDatagram = 65536

The largest datagram one frame can occupy — the RX segment size a view receiver’s frames are allocated at (the UDP payload bound, one datagram = one frame = one segment, ADR-0042 §2). It is also the ceiling on effective_max_frame — a datagram cannot be larger than this, so a configured max_frame above it is inert rather than loosening.

static constexpr std::size_t kDefaultMaxFrame = 1472

The receive cap of a link whose max_frame is unset (#2132): 1,472 bytes, the payload of one 1,500-byte Ethernet MTU after the 20-byte IPv4 and 8-byte UDP headers. A longer datagram needs IP fragmentation, which lwIP’s default configuration does not reassemble, so an MCU peer never receives one anyway. The RX segment is drawn one byte past it. A link that carries wider datagrams sets max_frame, up to kMaxDatagram.

static constexpr std::size_t kRecvStackHeadroom = LIBTRACER_UDP_SANITIZED ? 65536 : 8192

The stack the receive thread keeps beside its stack scratch, bytes (#2142): its own frames, the thread’s TLS (glibc carves it from the same stack) and the borrowed sink’s dispatch, which runs on that thread. A margin this check requires, not a measured bound of any one sink’s depth.

8 KiB in an ordinary build. A sanitized build (ASan, TSan or MSan) inflates every frame and the TLS block, so it keeps 64 KiB: an ASan+UBSan Debug build of the receive loop was measured to need about 28 KiB in all, where 8 KiB of headroom overflowed.

static constexpr std::size_t kMinRecvStack = graph::kUdpStackScratchBytes == 0 ? 0 : graph::kUdpStackScratchBytes + 1 + kRecvStackHeadroom

The smallest nonzero udp_config_t::recv_stack this build accepts (#2142): the stack scratch, one byte past it and kRecvStackHeadroom. 0 in a build with no stack scratch (graph::kUdpStackScratchBytes 0), where any size is accepted.

struct tcp_config_t

tcp_transport_t’s knobs as one aggregate (#1593): what both its constructors take after the peer address, in place of positional, defaulted parameters.

Every member defaults to the historical default, so tcp_config_t{} is the unconfigured link and a caller names only what it sets: {.memory = {.rx = &pool}, .max_frame = 4096}.

Public Members

link_memory_t memory = {}

The link’s memory (link_memory_t). rx: each inbound frame is read into a fresh exactly-len-byte segment from it (ADR-0042 §2); exhaustion is backpressure — the frame is drained off the stream, dropped, and drop_stats().dropped_rx ticks; never an OOM.

std::size_t max_frame = 0

Receive cap, bytes (0 → tcp_transport_t::kMaxFrame). TIGHTEN-ONLY: a value above kMaxFrame is clamped to it (length_prefix_framer_t::configured_cap, #1035); a frame inside the cap the backend cannot hold is shed as backpressure, not treated as malformed (#932).

std::size_t recv_stack = 0

Fallback-thread stack size in bytes, 0 = platform default (posix_endpoint_t::start). Non-zero right-sizes the driving thread on an MCU.

wait_module_t *wait = nullptr

The node’s wait module (#2147): the link puts its sockets on it and owns no thread, and the application drives it (wait_module_t::run). Null: a thread of the link’s own drives a private one, sized by recv_stack. Must outlive the link.

class tcp_transport_t : public tr::net::transport_t, private tr::net::stream_endpoint_t

A TCP stream transport_t (M6) — length-prefix framing over one peer.

Every frame is sent as u32-LE length ++ frame bytes; the receive thread reads the prefix (reassembling it across TCP segment boundaries), then reads exactly len bytes straight into a refcounted segment drawn from the injected mem_backend_t (ADR-0042 §2 — no library buffer beyond the per-frame segment). With a view receiver installed the frame is handed up OWNING; the span receiver otherwise gets a borrowed span over the same segment bytes.

Public Functions

tcp_transport_t(std::string_view peer_host, std::uint16_t peer_port, const tcp_config_t &config = {})

DIAL mode: connect to peer_host: (synchronous).

The TCP connect happens in the constructor (the ws_client_transport_t shape) — confirm with ok(); on failure no thread is spawned. The receive thread is NOT spawned here (#1045, #2247): the owner installs its receivers, then calls start_receiving, so no frame can land in an empty sink.

Parameters:
  • peer_host – Dotted-quad IPv4 address of the peer (e.g. “127.0.0.1”).

  • peer_port – TCP port of the peer (host byte order).

  • config – The link’s knobs (tcp_config_t): memory, receive cap, recv-thread stack, wait module.

explicit tcp_transport_t(std::uint16_t bind_port, const tcp_config_t &config = {})

LISTEN mode: bind+listen on bind_port, accept ONE inbound peer.

The same one-peer model as ws_server_transport_t: one connected client at a time; after a peer departs the accept loop resumes for the next. Use ok() to confirm the listen socket bound; the bound port (an ephemeral 0 request resolved) is observable via local_port().

Parameters:
  • bind_port – TCP port to listen on (host byte order; 0 → ephemeral).

  • config – The link’s knobs (tcp_config_t).

~tcp_transport_t()

Stop the receive thread and close all sockets.

virtual void shut_down() override

See transport_t::shut_down.

virtual void send(std::span<const std::byte> frame) override

Send frame as one length-prefixed record on the stream.

Writes u32-LE frame.size() then the frame bytes — one writev, partial writes resumed until complete. No-op until a peer is connected (and after the connection is torn down). Thread-safe (writes are serialized, so two senders can never interleave records on the stream).

Parameters:

frame – A complete TLV’s bytes.

virtual void send(std::span<const std::span<const std::byte>> iov) override

Scatter-gather send: the prefix + every span as ONE record, no gather copy — the length prefix rides as the first iovec entry and the rope’s spans follow, lowered to writev (partials resumed).

Parameters:

iov – The frame’s spans (a rope’s to_iovec()), concatenated on the wire as one length-prefixed frame.

virtual void send(std::span<const std::span<const std::byte>> head, const graph::value_t &value, const graph::delivery_lane_t &lane) override

Retained send (RFC-0028 §6.9): one length-prefixed record of head then value — written in-call when no write is in flight, and otherwise QUEUED as the prefix and head bytes plus one reference to value, never as a copy of it.

The queued form is the one this override exists for: the enqueue-then-write queue used to copy the whole record into its slot, so a large value published while another write was in flight cost a payload copy. The writer that drains the record gathers the head and the value’s links into one sendmsg record under the same write lock and bound as any other record, so the two-frame race on one socket (RFC-0028 §9 item 6) stays whole: a record is written entirely, or a partial write condemns the peer.

Parameters:
  • head – The record’s leading spans (borrowed for the call).

  • value – The payload (kept by reference only if the record is queued).

  • lane – The vertex’s ring the record waits in, if it waits (ADR-0087 §2).

virtual bool start_receiving() override

Put the connection on the wait the DIAL constructor held back (#1045).

The second phase of the two-phase bring-up: the socket is connected and NOTHING has been read off it, so a sink installed before this call cannot have missed a frame.

IDEMPOTENT, and a no-op wherever there is nothing to arm — an armed DIAL link (its thread is already running), a LISTEN link (its accept loop started in the constructor), and a link whose dial failed (ok() false, no socket to serve) — so an owner may call it unconditionally on every link it wires, which is what transport_vertex_t::make_connection does. A DIAL link that is never armed never receives and never reports the link down; it is simply an open socket until it is destroyed.

inline virtual bool delivers_ropes() const override

True — this transport honors set_rope_receiver (ADR-0042): one frame = one refcounted segment from the injected backend, handed up owning; a span-only sink gets the same bytes borrowed.

inline bool ok() const noexcept

The came-up predicate (#1059) — DIAL: the connect succeeded; LISTEN: the listen socket is bound. Answered at construction and never reverting (this accessor used to read the live fd on a DIAL link, i.e. it doubled as liveness; that is link_up now).

Liveness (the transport_t::link_up contract): true while the ONE connection is live — DIAL: from the connect until the recv loop’s teardown; LISTEN: while an accepted peer is connected (false between peers). Derived from the connection fd, which the teardown path already resets under the write lock — state that is already atomic (relaxed; a hint, not a synchronisation point).

inline std::uint16_t local_port() const noexcept

LISTEN mode: the actual bound TCP port (resolves an ephemeral 0).

inline std::uint64_t stalled_tx() const noexcept

Stalls a peer cost (#838, #2144): offers past a full STREAM lane whose turn moved nothing, each one a frame shed. Counted, never a verdict (#2899): a peer that stopped reading is closed by sweep.

inline virtual std::uint64_t sweep(std::uint64_t now, std::uint64_t deadline) override

The application’s liveness check (#2198, transport_t::sweep): a frame held on the wire, or a frame of the peer’s begun and not finished (#2812), that moved no byte since deadline shuts the connection down, counted in frozen_closed.

inline std::size_t frozen_closed() const noexcept

Connections the application’s liveness check closed as frozen (#2198).

inline virtual transport_drop_stats_t drop_stats() const noexcept override

This link’s shed-frame counters (#932, #2482).

dropped_rx: frames dropped because the RX backend was exhausted (backpressure, ADR-0039 §4 / ADR-0042 §2), drained off the stream, never an OOM. malformed_rx: length prefixes announcing more than the frame cap; each tears the connection down, since the stream has lost framing sync. dropped_tx: a record over the cap, a refused gather store, or no live peer to write to (dialing / torn down).

Public Static Attributes

static constexpr std::size_t kMaxFrame = length_prefix_framer_t::kDefaultMaxFrame

The largest frame the length prefix may announce — the shared length_prefix_framer_t::kDefaultMaxFrame (16 MiB) unless :settings max_frame tightens it. A larger prefix is malformed — counted via drop_stats().malformed_rx and the connection is closed (a desynced stream cannot be trusted again).

struct tcp_server_config_t

tcp_server_transport_t’s knobs as one aggregate (#1593), after the bind port.

Public Members

link_memory_t memory = {}

The link’s memory (link_memory_t); rx is the per-connection receive seam — see tcp_config_t::memory.

std::size_t max_frame = 0

Per-connection receive cap (0 → tcp_transport_t::kMaxFrame); tighten-only — see tcp_config_t::max_frame.

std::size_t max_peers = 0

Concurrent-peer admission cap (RFC-0006) — a connection beyond it is accepted and immediately closed. 0 takes kDefaultMaxPeers; any other value is enforced as given. Read the enforced value back from slot_server_t::max_peers.

bool peer_named = false

Expose the bus_link_t facet (see transport_t::bus) — the board↔board wiring choice, same contract as ws_server_transport_t’s.

std::size_t recv_stack = 0

Fallback-thread stack size in bytes, 0 = platform default. One thread serves every peer, so this is the whole server’s recv-stack knob.

wait_module_t *wait = nullptr

The node’s wait module (#2147): the link puts its sockets on it and owns no thread, and the application drives it (wait_module_t::run). Null: a thread of the link’s own drives a private one, sized by recv_stack. Must outlive the link.

class tcp_server_transport_t : public stream_server_base_t

A multi-peer TCP server transport_t — accepts many inbound peers on one listener and exposes them through the bus_link_t facet (ADR-0044).

The raw-stream sibling of ws_server_transport_t (#362): LITERALLY the same slot/poll machinery, since #871 shared as slot_server_t — ONE poll-based thread accepts clients and serves every open connection concurrently; peers occupy SLOTS recycled on departure, so steady-state memory is bounded by the maximum concurrent peers ever reached (or max_peers, the RFC-0006 injected bound). What this class adds to that base is its FRAMING: the shared u32-LE length prefix, read by frame ingress (frame_ingress.hpp, #2141) with no stream buffer, where WS has RFC 6455 packaging. There is NO handshake phase: a peer is open (named p<slot>~<gen>, ADR-0073 §2 / #426) from the moment its connection is accepted. The board↔board listener shape: leaner than WS packaging (no HTTP upgrade, no frame masking) with the same per-peer return-route identity when peer_named.

Public Functions

explicit tcp_server_transport_t(std::uint16_t bind_port, const tcp_server_config_t &config = {})

Bind+listen on bind_port (0 = ephemeral; see local_port()).

Spawns the poll/serve thread immediately. Use ok() to confirm the listen socket bound; the bound port is observable via local_port().

Parameters:
  • bind_port – TCP port to listen on (host byte order; 0 → ephemeral).

  • config – The server’s knobs (tcp_server_config_t): memory, receive cap, peer cap, bus facet, fallback-thread stack, wait module.

~tcp_server_transport_t()

Stop waiting and close all sockets.

void send(std::span<const std::byte> frame) override

Send frame as one length-prefixed record to EVERY open peer (the flat point-to-point surface).

The prefix is encoded once; each peer gets one serialized gathered write through its egress. No-op until a peer is connected. Thread-safe; a stalled peer never delays the others (#2144). A directed single-peer send is peer_link(name)->send(frame).

Parameters:

frame – A complete TLV’s bytes.

void send(std::span<const std::span<const std::byte>> iov) override

Zero-copy scatter-gather broadcast: the length prefix rides as the first iovec entry and the rope’s spans follow — ONE gathered record per open peer, no flatten copy.

Every idle peer writes from the same read-only gather; a peer that has to wait gets one shared frame (ADR-0087 §2). Thread-safe.

Parameters:

iov – The spans to emit, in order, as a single record.

void send(std::span<const std::span<const std::byte>> head, const graph::value_t &value, const graph::delivery_lane_t &lane) override

Retained broadcast (RFC-0028 §6.9): head then value as one record to every open peer; a peer that has to wait holds one shared frame that keeps value by reference, in lane's ring (ADR-0087 §2).

inline bool delivers_ropes() const override

True — every frame reassembles into ONE refcounted segment from the injected backend, handed up owning (ADR-0042); a span-only sink gets the same bytes borrowed. Covers both facets.

WebSocket

struct ws_client_config_t

ws_client_transport_t’s knobs as one aggregate (#1593), after the peer address.

Public Members

link_memory_t memory = {}

The link’s memory (link_memory_t). rx: the receive seam, as the server’s; a single-frame message’s block carries the RFC-0028 §6.9 ingress-loan reserve. io: the ADR-0079 EGRESS store (#873) the masked-frame buffer, the enqueue-then-write queue’s slots (#1661) AND the base class’s gather temporary draw from — one egress store per link; null means the process net sub-pool (mem::net_source(): the static arena on an MCU build, not the heap). Both bound once, at construction.

std::size_t max_frame = 0

Receive cap (0 → ws_server_transport_t::kMaxFrame); tighten-only — see ws_server_config_t::max_frame.

std::size_t recv_stack = 0

Fallback-thread stack size in bytes, 0 = platform default.

wait_module_t *wait = nullptr

The node’s wait module (#2147): the link puts its sockets on it and owns no thread, and the application drives it (wait_module_t::run). Null: a thread of the link’s own drives a private one, sized by recv_stack. Must outlive the link.

std::size_t max_handshake = 0

The DIAL half of the pre-auth handshake budget (#934), resolved through ws_server_transport_t::handshake_cap (0 → the default; tighten-only). It bounds the RESPONSE header block the dialled server may make this node accumulate.

class ws_client_transport_t : public tr::net::transport_t, private tr::net::stream_endpoint_t

A WebSocket (RFC 6455) client transport_t — dials out to one peer.

The mirror of ws_server_transport_t: a board that DIALS OUT to a ws:// peer (device-to-device, or egress through a NAT). The constructor TCP-connects to host:, runs the opening handshake from the client side (sends an HTTP GET Upgrade with a fresh Sec-WebSocket-Key, then verifies the 101 response’s Sec-WebSocket-Accept against ws::accept_key); start_receiving() then spawns the receive loop. Per RFC 6455 §5.1 every client→server frame is MASKED (ws::encode_client_frame); inbound server frames are unmasked and decode the same way the server’s do. ok() confirms the handshake completed.

Public Functions

ws_client_transport_t(std::string_view host, std::uint16_t port, const ws_client_config_t &config = {})

Connect to host: and run the client opening handshake.

TCP-connects, sends the HTTP Upgrade request, and verifies the server’s 101 Sec-WebSocket-Accept; confirm with ok(). The receive loop thread is spawned by start_receiving, once the owner has installed its receivers (#1025, #2247). On any failure the connection is closed and ok() is false.

Parameters:
  • host – Dotted-quad IPv4 address of the peer (e.g. “127.0.0.1”).

  • port – TCP port of the peer (host byte order).

  • config – The link’s knobs (ws_client_config_t): memory (receive seam and egress store), receive cap, fallback-thread stack, liveness window, handshake budget.

~ws_client_transport_t()

Stop waiting and close the socket.

virtual void shut_down() override

See transport_t::shut_down.

virtual void send(std::span<const std::byte> frame) override

Send frame as one client→server MASKED BINARY WebSocket message.

Masks frame once (FIN=1, MASK=1, fresh per-frame key) into one frame drawn from the link’s egress source for this send (#2267), and writes it to the peer; the link keeps no buffer between sends. No-op once the connection has been torn down. Thread-safe (the socket write is guarded).

Parameters:

frame – A complete TLV’s bytes.

virtual void send(std::span<const std::span<const std::byte>> iov) override

Gathered send: iov's spans as one MASKED BINARY message, gathered and masked in one pass (#2145) — never flattened into a temporary first.

virtual void send(std::span<const std::span<const std::byte>> head, const graph::value_t &value, const graph::delivery_lane_t &lane) override

Retained send: head then value as one MASKED BINARY message, waiting in lane's ring if it waits (ADR-0087 §2). A client frame is masked, so the payload is written once, gathered from head and the value’s links and masked in the same pass (#2145); it is never flattened first.

virtual bool start_receiving() override

Put the connection on the wait the constructor held back (#1025).

The second phase of the two-phase bring-up: the socket is connected and handshaken, the bytes the server pipelined behind its 101 are held, and NOTHING has been decoded yet — so a sink installed before this call cannot have missed a frame. The thread’s first act is to drain what the handshake carried over.

Idempotent (an armed client’s thread is already running → no-op) and safe on a failed handshake (ok() false → no-op, nothing to serve). A client that is never started never receives, never answers a PING and never reports the link down; it is simply an open socket until it is destroyed.

inline virtual bool delivers_ropes() const override

True — WS reassembles fragmented messages into ropes (ADR-0053 §5): each message crosses the seam as a rope_t, one owning link per WS fragment (a single link for an unfragmented message), chained by reassembly, never memcpy’d flat.

inline bool ok() const noexcept

The came-up predicate (#1059): the dial and the client opening handshake succeeded. Answered at construction and never reverting — a link that came up and later died still answers true here; liveness is link_up.

Liveness (the transport_t::link_up contract): true from the completed handshake until the recv loop’s teardown — a peer CLOSE, a remote hangup, a fatal receive error or an RFC 6455 breach all clear it (relaxed atomic; the push twin is set_link_state_notifier). A client that is never started never observes the wire and so never reports down (see start_receiving).

inline std::uint64_t stalled_tx() const noexcept

Stalls a server cost (#838, #2144): offers past a full STREAM lane whose turn moved nothing, each one a frame shed. Counted, never a verdict (#2899): a server that stopped reading is closed by sweep.

inline virtual std::uint64_t sweep(std::uint64_t now, std::uint64_t deadline) override

The application’s liveness check (#2198, transport_t::sweep): a frame held on the wire, or a frame of the peer’s begun and not finished (#2812), that moved no byte since deadline shuts the connection down, counted in frozen_closed.

inline std::size_t frozen_closed() const noexcept

Connections the application’s liveness check closed as frozen (#2198).

inline virtual transport_drop_stats_t drop_stats() const noexcept override

This link’s shed-frame counters (#932, #2482).

dropped_rx: messages shed mid-reassembly because the RX backend was exhausted (backpressure, ADR-0039 §4 / ADR-0042 §2), never an OOM. malformed_rx: RFC 6455 violations (an over-cap declared length or reassembled message, a §5.5 control breach, an opening-handshake response past its budget, #934); each fails the connection. dropped_tx: a frame the gather store refused, or no live connection to write to.

inline std::size_t effective_max_frame() const noexcept

The cap actually honored: min(max_frame, backend.max_segment_size()).

inline std::size_t effective_max_handshake() const noexcept

The pre-auth handshake budget actually honored — the server-side accessor’s twin, same name, same tighten-only resolution (#934).

struct ws_server_config_t

ws_server_transport_t’s knobs as one aggregate (#1593), after the bind port.

Every member defaults to the historical default, so ws_server_config_t{} is the unconfigured server and a caller names only what it sets.

Public Members

link_memory_t memory = {}

The link’s memory (link_memory_t). rx: every inbound message fragment is copied into a fresh segment drawn from it (ADR-0042 §2); exhaustion is backpressure — the message is shed and drop_stats().dropped_rx ticks; never an OOM.

std::size_t max_frame = 0

Per-connection receive cap (0 → ws_server_transport_t::kMaxFrame). TIGHTEN-ONLY (length_prefix_framer_t::configured_cap, #1035), and bounded by the backend’s real capacity. Checked against the DECLARED length in the WS frame header, so an oversize announcement is refused before one body byte is buffered.

std::size_t max_peers = 0

Concurrent-peer admission cap (RFC-0006) — a connection beyond it is accepted and immediately closed. 0 takes kDefaultMaxPeers; any other value is enforced as given.

bool peer_named = false

Expose the bus_link_t facet (see transport_t::bus): the browser-tabs server sets it so each tab gets its own return route.

std::size_t recv_stack = 0

Fallback-thread stack size in bytes, 0 = platform default. One thread multiplexes the listener and every peer.

wait_module_t *wait = nullptr

The node’s wait module (#2147): the link puts its sockets on it and owns no thread, and the application drives it (wait_module_t::run). Null: a thread of the link’s own drives a private one, sized by recv_stack. Must outlive the link.

std::size_t max_handshake = 0

PRE-AUTH request-size budget for the opening handshake in bytes (0 → ws_server_transport_t::kMaxHandshakeBytes). TIGHTEN-ONLY (handshake_cap): enforced BEFORE the append, so the byte that would exceed it is never copied; over budget ⇒ malformed_rx ticks and the link is closed (#934).

class ws_server_transport_t : public stream_server_base_t

A WebSocket (RFC 6455) server transport_t — accepts many inbound peers and exposes them through the bus_link_t facet (ADR-0044).

Binds and listens on a TCP port (localhost is fine for tests); one poll-based thread accepts clients and serves every open connection concurrently. Each inbound BINARY message is delivered tagged with its peer’s name (the routable p<slot>~<gen> fallback, ADR-0073 §2 / #426) when a peer-named sink is installed (the router’s bus wiring), or to the flat transport_t receiver otherwise — so a single-client deployment behaves exactly as the point-to-point server always did. The dial-out counterpart is ws_client_transport_t below.

Peer lifecycle: peers occupy SLOTS. A departed peer’s slot is recycled for the next accept, so steady-state memory is bounded by the maximum number of CONCURRENT peers ever reached (or by max_peers when set — the RFC-0006 injected bound), never by the number of connections ever served. That whole slot/poll layer is slot_server_t, shared verbatim with tcp_server_transport_t since #871; what this class adds is the RFC 6455 packaging — the opening handshake and the frame codec.

Public Functions

explicit ws_server_transport_t(std::uint16_t bind_port, const ws_server_config_t &config = {})

Bind+listen on bind_port (0 = ephemeral; see local_port()).

Spawns the poll/serve thread immediately. Use ok() to confirm the listen socket bound. The bound port is observable via local_port().

Parameters:
  • bind_port – TCP port to listen on (host byte order; 0 → ephemeral).

  • config – The server’s knobs (ws_server_config_t): memory, receive cap, peer cap, bus facet, fallback-thread stack, wait module, handshake budget.

~ws_server_transport_t()

Stop waiting and close all sockets.

void send(std::span<const std::byte> frame) override

Send frame as one server→client BINARY WebSocket message to EVERY open peer (the flat point-to-point surface).

Encodes once via ws::try_encode_frame(BINARY, frame) (FIN=1, unmasked) and writes the whole frame to each connected client. No-op until a client is connected. Thread-safe (socket writes are guarded). A directed single-peer send is peer_link(name)->send(frame).

Parameters:

frame – A complete TLV’s bytes.

void send(std::span<const std::span<const std::byte>> iov) override

Zero-copy scatter-gather broadcast: emit the gathered iov spans as ONE server→client BINARY message to EVERY open peer, no flatten copy.

Overrides the base flatten-then-encode default (transport.hpp): server frames are UNMASKED (RFC 6455 §5.1), so the frame header rides as the first iovec entry and the payload spans follow it straight to the wire via one gathered scatter-gather write per peer — no allocation, no copy. Every idle peer writes from the same read-only gather; one that has to wait gets one shared frame (ADR-0087 §2). No-op until a client is connected. Thread-safe; a stalled peer never delays the others (#2144).

Parameters:

iov – The spans to emit, in order, as a single frame.

void send(std::span<const std::span<const std::byte>> head, const graph::value_t &value, const graph::delivery_lane_t &lane) override

Retained broadcast (RFC-0028 §6.9): head then value as one BINARY message to every open peer; a peer that has to wait holds one shared frame that keeps value by reference, in lane's ring (ADR-0087 §2).

inline bool delivers_ropes() const override

True — WS reassembles fragmented messages into ropes (ADR-0053 §5): each message crosses the seam as a rope_t, one owning link per WS fragment (a single link for an unfragmented message), chained by reassembly, never memcpy’d flat. Covers both the transport_t and bus_link_t facets (one override, same contract).

inline std::size_t effective_max_frame() const noexcept

The cap actually honored: min(max_frame, backend.max_segment_size()) — what a declared frame length is compared against, resolved from the two injected resources rather than restated as a number.

inline std::size_t effective_max_handshake() const noexcept

The pre-auth handshake budget actually honored: handshake_cap(max_handshake) as constructed (#934). Unlike effective_max_frame it names no backend — a handshake is accumulated in the slot’s own request buffer, not in an RX segment, so there is no second injected resource to take the min against.

Public Static Functions

static inline constexpr std::size_t handshake_cap(std::size_t max_handshake) noexcept

Resolve a max_handshake request into the honored budget — TIGHTEN-ONLY against kMaxHandshakeBytes, exactly as length_prefix_framer_t::configured_cap is against kDefaultMaxFrame.

0 (unset) keeps the default; a nonzero value yields min(max_handshake, kMaxHandshakeBytes). The value arrives through a config-writable key (ws-private max_handshake), and a config-writable key must never RAISE a pre-auth bound — only narrow it.

Public Static Attributes

static constexpr std::size_t kMaxFrame = length_prefix_framer_t::kDefaultMaxFrame

The largest MESSAGE a peer may announce — the shared length_prefix_framer_t::kDefaultMaxFrame (16 MiB) unless :settings max_frame tightens it, and further bounded by the injected backend’s real capacity.

One WS message is one libtracer frame, so this is the same per-connection receive cap tcp/quic/webtransport apply to their length prefix — it just reads off a WS frame header instead. A frame claiming more, or a fragmented message whose fragments cost more (each one’s payload plus its segment and chain slot), is malformed: drop_stats().malformed_rx ticks and the connection is failed, RFC 6455 §7.1.7.

static constexpr std::size_t kMaxHandshakeBytes = 16u * 1024u

The largest OPENING HANDSHAKE a PRE-AUTH peer may make this node buffer (16 KiB) — the ceiling max_handshake tightens against (#934).

A different budget from kMaxFrame and deliberately so: a frame arrives on an established connection under whatever the deployment allowed, while an HTTP Upgrade request arrives from a host that has done nothing but complete a TCP connect — no ACL, no subscription, no router, nothing authenticated. Pre-auth work is REFUSED EARLY, not carefully allocated: an accumulation that would pass this budget is refused BEFORE the byte that would exceed it is copied, drop_stats().malformed_rx ticks, and the link is closed (the count-then-close disposition, #838’s shape).

The WebSocket wire layer itself — opcodes, frame decode, the accept-key computation — is pure and lives in tr::net::ws:

enum class tr::net::ws::opcode_t : std::uint8_t

RFC 6455 frame opcodes (the subset libtracer cares about).

Values:

enumerator CONT

Continuation frame.

enumerator TEXT

Text (UTF-8) data frame.

enumerator BINARY

Binary data frame.

enumerator CLOSE

Connection close control frame.

enumerator PING

Ping control frame.

enumerator PONG

Pong control frame.

struct frame_t

One decoded RFC 6455 data/control frame (payload already unmasked).

The payload is a VIEW into the buffer the frame was decoded from (#1780): the decoder unmasks in place and copies nothing, so the view is valid until that buffer is changed.

Public Members

opcode_t op

Frame opcode.

bool fin

FIN bit (true = final fragment).

std::span<const std::byte> payload

Unmasked application payload, in the buffer.

inline std::optional<std::pair<frame_t, std::size_t>> tr::net::ws::decode_frame(std::span<std::byte> buf) noexcept

Decode exactly one RFC 6455 frame from the front of buf — the pure outcome-collapsing decoder, byte-for-byte the behaviour it has always had.

Deliberately does NOT apply the §5.5 control-frame rules or the §5.2 reserved-opcode rule (a reserved opcode decodes here, carried through as-is in frame_t::op), and imposes no length cap (kNoPayloadCap): this is the function tests/conformance/ws_diff_fuzz.py holds against the TypeScript decodeFrame, and the two cores must answer identically on every input. All three rules are CONNECTION-FAILURE policy, not decode outcomes — they belong to whoever owns the socket and can shed it. Every transport in this repository therefore uses decode_frame_checked; only a caller that has no connection to fail should use this one. It is safe to leave uncapped precisely because it never buffers on the caller’s behalf: a declared length past the end of buf answers “need more” and allocates nothing.

Parameters:

buf – A byte stream that may contain a partial or whole frame, possibly followed by more frames. A masked frame is unmasked in place (see decode_frame_checked).

Returns:

nullopt if buf does not yet hold a complete frame (need more bytes); otherwise the decoded frame paired with the bytes consumed from the front.

inline decode_result_t tr::net::ws::decode_frame_checked(std::span<std::byte> buf, std::size_t max_payload) noexcept

Decode exactly one RFC 6455 frame from the front of buf, distinguishing “need more bytes” from “the peer broke the protocol” — the form a TRANSPORT uses.

Handles the FIN bit, opcode, the MASK bit with its 4-byte masking key (client→server frames are masked; the payload is unmasked IN buf and the key zeroed, so the returned payload is a view into buf and nothing is copied — #1780), and the 7 / 16 / 64-bit extended length encodings. Both masked and unmasked frames decode.

RFC 6455 §5.5 is enforced here (#848): a CONTROL opcode (0x8-0xF) carrying more than kMaxControlPayload bytes, or arriving with FIN clear, is PROTOCOL_ERROR — and it is diagnosed from the frame HEADER, before the payload has to be buffered, so an absurd declared length costs nothing. Without this a peer could send a 1 MiB PING and have the node echo it straight back: an unauthenticated reflection/amplification primitive, and (because the echo was a std::vector) a peer-triggered abort() on the -fno-exceptions profile.

The DATA path is bounded the same way (#872): a frame whose declared length exceeds max_payload is PROTOCOL_ERROR off the HEADER too. The two rules are separate — §5.5 is a fixed RFC constant about CONTROL frames, max_payload is the deployment’s injected receive cap about every frame — and neither substitutes for the other.

§5.2’s OPCODE half is enforced here too (#1060; the RSV-bit half of §5.2 is not — nothing here examines b0 & 0x70): an opcode outside the six opcode_t names is RESERVED, and receiving one is a Fail the WebSocket Connection condition — so it is PROTOCOL_ERROR off the first header byte, ahead of both length rules. TEXT and PONG are unaffected: they are DEFINED opcodes, they still decode, and what a transport does with them (ignore them) stays the transport’s policy.

Parameters:
  • buf – A byte stream that may contain a partial or whole frame, possibly followed by more frames.

  • max_payload – The transport’s effective receive cap: min(max_frame, backend.max_segment_size()) (length_prefix_framer_t::effective_cap — the no-synthetic-limits doctrine). Deliberately NOT defaulted: a transport that forgets to name its bound is exactly the defect this parameter closes, so omitting it must not compile.

Returns:

NEED_MORE while buf is short of a whole frame, PROTOCOL_ERROR on an RFC 6455 violation or an over-cap declared length (the caller must fail the connection, RFC 6455 §7.1.7), else OK with the frame and the bytes consumed.

constexpr std::size_t tr::net::ws::kMaxControlPayload = 125

The largest payload an RFC 6455 CONTROL frame may carry (§5.5).

“All control frames MUST have a payload length of 125 bytes or less and MUST NOT be

fragmented.” Bounding the reply to a peer’s PING at this is what lets the PONG be built entirely on the stack — no allocation, hence no failure mode to have a drop policy about (#848). It also removes the reflection/amplification primitive an unbounded echo was.

constexpr std::size_t tr::net::ws::kNoPayloadCap = ~std::size_t{0}

The max_payload argument that imposes NO length bound — every representable length passes the DATA-frame check.

Not a limit but the ABSENCE of one: the largest value a std::size_t can hold, so len > kNoPayloadCap is false for every decodable length. It exists for the pure decoder (decode_frame), which by contract collapses outcomes and owns no connection to fail; a TRANSPORT never passes it — it passes its effective receive cap, which comes from the injected backend and :settings max_frame, never from a literal.

inline bool tr::net::ws::try_encode_frame(mem::block_array_t<std::byte> &out, opcode_t op, std::span<const std::byte> payload, bool fin = true) noexcept

Encode one whole server→client RFC 6455 frame into out: given opcode, UNMASKED.

Server frames MUST NOT be masked (RFC 6455 §5.1), so the MASK bit is always 0 and no masking key is emitted. The length uses the smallest legal encoding (7-bit, then the 126 + 2-byte marker, then the 127 + 8-byte marker) — encoded by the shared encode_frame_header() helper, then the payload appended. No shipping path builds a whole server frame (both gather sites in transport_ws.cpp ride the payload by reference behind encode_frame_header); this is the form a test or a tool that wants the bytes uses. Replaces the std::vector-returning encode_frame (#1780).

Parameters:
  • out – The frame store; replaced with the frame.

  • op – The frame opcode.

  • payload – The application payload to send.

  • fin – The FIN bit (default true — a complete, unfragmented message; pass false for a non-final fragment, RFC 6455 §5.4).

Returns:

False when out could not be grown — it is then left empty.

inline std::size_t tr::net::ws::encode_frame_header(std::array<std::byte, kMaxServerFrameHeader> &out, opcode_t op, std::size_t len, bool fin = true)

Encode ONLY a server→client RFC 6455 frame header into out, UNMASKED.

Writes byte0 = (fin?0x80:0)|op, then the payload length in the smallest legal encoding (7-bit, then the 126 + 2-byte u16-BE marker, then the 127 + 8-byte u64-BE marker); the MASK bit is always 0 (server frames MUST NOT be masked, RFC 6455 §5.1). This is the one SERVER-side (unmasked) length-encoding implementation — try_encode_frame appends the payload after it, encode_server_control delegates to it, and both gather sites in transport_ws.cpp ride the payload spans behind it with no copy. The MASKED client side does NOT share it: detail::put_client_frame carries its own ladder, because the MASK bit rides in the same byte as the 7-bit length (0x80u | len) and the 4-byte key follows the length it just wrote.

Parameters:
  • out – The header buffer to fill (kMaxServerFrameHeader bytes suffice).

  • op – The frame opcode.

  • len – The payload length in bytes.

  • fin – The FIN bit (default true — a complete, unfragmented message; pass false for a non-final fragment, RFC 6455 §5.4).

Returns:

The number of header bytes written into out (2, 4, or 10).

inline std::size_t tr::net::ws::encode_server_control(std::array<std::byte, kMaxServerControlFrame> &out, opcode_t op, std::span<const std::byte> payload) noexcept

Encode one whole server→client CONTROL frame (PONG/CLOSE) into out — on the STACK, nothrow, UNMASKED.

The reply to a peer’s PING must not be able to fail: dropping a PONG costs the link (RFC 6455 §5.5.2/§5.5.3 make it the required response, and a peer whose PINGs go unanswered may fail the connection), while closing the session lets whoever caused the heap pressure decide the topology. Since §5.5 bounds a control payload at kMaxControlPayload — enforced by decode_frame_checked — the whole frame fits a fixed stack buffer and there is no failure mode left to have a policy about (#848).

Length encoding is delegated to encode_frame_header, which stays the one SERVER-side (unmasked) length-encoding implementation: every unmasked frame this header emits — try_encode_frame, this function, and both gather sites in transport_ws.cpp — goes through it. The masked client side encodes its own lengths (see detail::put_client_frame and encode_client_control).

Parameters:
  • out – The frame buffer to fill.

  • op – The control opcode (PONG / CLOSE).

  • payload – The control payload to echo (at most kMaxControlPayload bytes).

Return values:

0 – payload exceeds kMaxControlPayload — nothing was written.

Returns:

The number of frame bytes written into out.

inline std::size_t tr::net::ws::encode_client_control(std::array<std::byte, kMaxClientControlFrame> &out, opcode_t op, std::span<const std::byte> payload, std::uint32_t mask_key) noexcept

Encode one whole client→server CONTROL frame into out — on the STACK, nothrow, MASKED (RFC 6455 §5.1).

The client twin of encode_server_control — same reasoning, plus the 4-byte masking key and the payload XOR. A control length is always < 126, so the header is the 2-byte form with MASK=1.

Parameters:
  • out – The frame buffer to fill.

  • op – The control opcode (PONG / CLOSE).

  • payload – The control payload to echo (at most kMaxControlPayload bytes).

  • mask_key – The 32-bit masking key (its 4 bytes form the RFC 6455 key).

Return values:

0 – payload exceeds kMaxControlPayload — nothing was written.

Returns:

The number of frame bytes written into out.

inline std::size_t tr::net::ws::try_encode_client_frame(mem::block_array_t<std::byte> &out, opcode_t op, std::span<const std::span<const std::byte>> parts, std::uint32_t mask_key, bool fin = true) noexcept

Build the masked frame into out, soft-failing on OOM instead of a bad_alloc abort() under -fno-exceptions (#848).

The one WS egress encoder that survives as a nothrow twin rather than being deleted: a client frame MUST be masked (RFC 6455 §5.1), so the bytes on the wire are not the caller’s bytes and cannot be gathered by reference the way the UNMASKED server frames are. Reuse one out buffer across calls and the steady state allocates nothing. On 0 the caller DROPS the frame — the same answer the delivery path already gives under exhaustion.

Why a and not a +

On the profile this encoder ships to, try_reserve cannot express a refusal at all. std::vector::reserve reports exhaustion by throwing, and under -fno-exceptions that is a bare abort() inside reserve that no wrapper can intercept — so there try_reserve still has to guess ahead with a nothrow probe and hope nothing takes the block in between (#923; on a hosted build it catches instead, which is sound but is not the MCU profile). That is the very outcome #848 exists to remove, so this path draws from the failable seam instead (ADR-0065): growth is ONE block_source_t::try_alloc that answers nullptr, on both profiles, with no unguardable second step.

Parameters:
  • out – The reusable frame buffer; its capacity is retained across calls.

  • op – The frame opcode.

  • parts – The application payload, in order: gathered and masked in one pass, so a retained send’s head and value links are never flattened first (#2145).

  • mask_key – The 32-bit masking key (its 4 bytes form the RFC 6455 key).

  • fin – The FIN bit (default true — a complete, unfragmented message).

Return values:

0 – The frame buffer could not be grown — nothing was written, drop the frame.

Returns:

The number of frame bytes written to out.data() (never 0 on success: a client frame is at least a 2-byte header plus the 4-byte masking key).

inline std::size_t tr::net::ws::try_encode_client_frame(mem::block_array_t<std::byte> &out, opcode_t op, std::span<const std::byte> payload, std::uint32_t mask_key, bool fin = true) noexcept

try_encode_client_frame over one contiguous payload.

inline accept_key_t tr::net::ws::accept_key(std::string_view client_key) noexcept

Compute the RFC 6455 Sec-WebSocket-Accept value for a client key.

accept = base64(sha1(client_key + GUID)) where GUID is the fixed magic “258EAFA5-E914-47DA-95CA-C5AB0DC85B11”. The server returns this in the 101 Switching Protocols response to prove it spoke RFC 6455. The two parts are hashed in turn (sha1_t), so nothing is concatenated or allocated.

Parameters:

client_key – The raw Sec-WebSocket-Key header value sent by the client.

Returns:

The Sec-WebSocket-Accept text.

QUIC and WebTransport (the optional module)

struct quic_config_t

quic_transport_t’s knobs as one aggregate (#1593), after the address (and, on a dial, the TLS trust).

Public Members

link_memory_t memory = {}

The link’s memory (link_memory_t). rx: each inbound frame is reassembled into a fresh exactly-len-byte segment from it (ADR-0042 §2); exhaustion is backpressure — the frame is drained, dropped, and drop_stats().dropped_rx ticks.

std::size_t max_frame = 0

Receive cap (:settings max_frame); 0 → quic_transport_t::kMaxFrame. Tighten-only (#1035).

class quic_transport_t : public tr::net::transport_t

The msquic QUIC transport_t (ADR-0043 Phase A) — length-prefix framing over ONE bidirectional stream on one connection.

Every frame is sent as u32-LE length ++ frame bytes (identical to tcp_transport_t, so the two wire framings are interchangeable above the seam). msquic delivers received stream data in callback chunks; the transport reassembles the prefix and exactly-len body bytes into ONE refcounted segment drawn from the injected mem_backend_t (ADR-0042 §2), handed up OWNING when a view receiver is installed. TX copies each frame ONCE into a buffer from config.memory.io that msquic owns until its SEND_COMPLETE event (the msquic buffer-lifetime contract) — the only library-held buffer, and only for the duration of the in-flight send.

Public Functions

quic_transport_t(std::string_view peer_host, std::uint16_t peer_port, quic_dial_tls_t tls = {}, const quic_config_t &config = {})

DIAL mode: start a connection to peer_host:. Returns at once; it never waits for the QUIC handshake (#2306).

ok() says the handshake was started; on false no connection exists and the object is inert. The link comes up on msquic’s CONNECTED callback (link_up), which also opens the bidirectional frame stream; a send before that is dropped and counted in dropped_tx, never queued (the down-link rule). A handshake that fails ends in the link-down notifier, once. Receivers must still be installed before the peer sends (the set_receiver contract).

Parameters:
  • peer_host – Peer hostname or dotted-quad IPv4 (e.g. “127.0.0.1”).

  • peer_port – Peer UDP port (host byte order).

  • tls – Server-certificate trust: a CA bundle, or the DEV-ONLY no-verify flag (see quic_dial_tls_t).

  • config – The link’s knobs (quic_config_t): memory, receive cap.

quic_transport_t(std::uint16_t bind_port, std::string_view cert_file, std::string_view key_file, const quic_config_t &config = {})

LISTEN mode: serve QUIC on bind_port with the PEM certificate at cert_file / private key at key_file, accepting ONE inbound peer at a time (the tcp_transport_t / ws_server_transport_t one-peer model; re-accepts after a peer departs).

Use ok() to confirm the listener started (bad cert paths fail here); the bound port (an ephemeral 0 request resolved) is observable via local_port(). The peer opens the frame stream.

Parameters:
  • bind_port – UDP port to listen on (host byte order; 0 → ephemeral).

  • cert_file – PEM server-certificate path (tools/gen-dev-cert.sh emits a self-signed dev pair).

  • key_file – PEM private-key path matching cert_file.

  • config – The link’s knobs (quic_config_t) — see the DIAL constructor.

~quic_transport_t()

Shut the connection down, drain msquic callbacks, and release the msquic API (listener → stream → connection → registration order).

virtual void shut_down() override

See transport_t::shut_down.

virtual void send(std::span<const std::byte> frame) override

Send frame as one length-prefixed record on the frame stream.

The prefix and frame bytes are copied ONCE into a single heap buffer handed to msquic, which owns it until SEND_COMPLETE (the msquic buffer-lifetime contract; the seam’s spans are only borrowed for this call, so the copy is unavoidable and minimal). No-op until a peer’s stream is up (and after teardown). Thread-safe.

Parameters:

frame – A complete TLV’s bytes.

virtual void send(std::span<const std::span<const std::byte>> iov) override

Scatter-gather send: the prefix + every span as ONE record.

ONE gather copy: msquic’s StreamSend does take multiple QUIC_BUFFERs, but it requires every buffer to stay alive until SEND_COMPLETE while the seam’s spans are only borrowed for this call — so the spans are gathered once into the single owned send buffer (prefix first), exactly the copy the single-span overload makes.

Parameters:

iov – The frame’s spans (a rope’s to_iovec()), concatenated on the wire as one length-prefixed frame.

inline virtual bool delivers_ropes() const override

True — this transport honors set_rope_receiver (ADR-0042).

bool ok() const noexcept

The came-up predicate (#1059) — DIAL: the handshake was started (it completes, or fails, on msquic’s callbacks); LISTEN: the listener is up on its port. Answered at construction and never reverting; liveness is link_up.

std::uint16_t local_port() const noexcept

LISTEN mode: the actual bound UDP port (resolves an ephemeral 0).

Liveness (the transport_t::link_up contract), from the QUIC connection events: true from CONNECTED until the connection shuts down (peer/transport/idle). Relaxed atomic.

bool dial_ended() const noexcept

DIAL: true once this dial’s one connection has ended — its handshake failed or it came up and went down — so an owner tells a failed dial from a pending one (#2306). Set just before the link-down fire. LISTEN: always false.

virtual transport_drop_stats_t drop_stats() const noexcept override

This link’s shed-frame counters (#932, #2482).

dropped_rx: frames dropped because the RX backend was exhausted (backpressure, ADR-0039 §4 / ADR-0042 §2), drained off the stream, never an OOM. malformed_rx: length prefixes announcing more than the frame cap; each shuts the connection down. dropped_tx: a record over THIS CONNECTION’s cap (:settings max_frame, resolved tighten-only against kMaxFrame, the number the peer measures the arriving prefix by, #1409), no live peer stream to write to (dialing / torn down), or a StreamSend msquic refused. H3 handshake material is not counted: it is not a frame.

Public Static Attributes

static constexpr std::size_t kMaxFrame = length_prefix_framer_t::kDefaultMaxFrame

The largest frame the length prefix may announce — the shared length_prefix_framer_t::kDefaultMaxFrame (16 MiB) unless :settings max_frame tightens it. A larger prefix is malformed: counted via drop_stats().malformed_rx and the connection is shut down (a desynced stream cannot be trusted again).

struct quic_dial_tls_t

DIAL-side TLS trust options for quic_transport_t (ADR-0043 Phase A).

QUIC is TLS 1.3 by construction, so the dialer must decide how to trust the server certificate. Exactly one of the two knobs is used: a CA bundle to verify against, or the DEV-ONLY escape hatch that skips verification (the only way to reach a self-signed dev cert, which cannot chain to any CA).

Public Members

std::string_view ca_file

PEM CA bundle path to verify the server certificate against (empty = the system trust store). Borrowed for the constructor call only (#1780).

bool insecure_no_verify = false

DEV ONLY: skip server certificate validation entirely (self-signed dev certs — tools/gen-dev-cert.sh). Never enable in deployment.

struct webtransport_config_t

webtransport_transport_t’s knobs as one aggregate (#1593), after the address (and, on a dial, the CONNECT path and TLS trust).

Public Members

link_memory_t memory = {}

The link’s memory (link_memory_t). rx: each inbound frame lands in a fresh exactly-sized segment from it; exhaustion is backpressure (drop_stats().dropped_rx), never an OOM.

std::size_t max_frame = 0

Per-link RX cap (:settings max_frame); 0 = the default.

std::size_t max_handshake = 0

Pre-auth H3 handshake budget; 0 = kMaxHandshakeBytes. TIGHTEN-ONLY (handshake_cap). A dial bounds the CONNECT RESPONSE’s field section; a listener bounds per-stream classification/HEADERS accumulation and a HEADERS frame’s DECLARED length.

class webtransport_transport_t : public tr::net::transport_t

The WebTransport transport_t (ADR-0043 Phase B): an HTTP/3 extended CONNECT session whose ONE bidirectional WebTransport stream carries the 4-byte u32-LE length-prefix framing.

LISTEN mode is the #92 deliverable: a browser (the TS @avatarsd-llc/libtracer-webtransport package) or the DIAL mode of this class connects with new WebTransport(url) semantics — H3 SETTINGS both ways, extended CONNECT, 200 — and then opens one bidirectional stream that becomes the frame channel. RX frames are reassembled into ONE refcounted segment each from the injected mem_backend_t (ADR-0042 §2, owning delivery); TX copies each frame once into the buffer msquic owns until SEND_COMPLETE — exactly the quic_transport_t contracts.

Public Functions

webtransport_transport_t(std::string_view peer_host, std::uint16_t peer_port, std::string_view path = "/", webtransport_dial_tls_t tls = {}, const webtransport_config_t &config = {})

DIAL mode: start a WebTransport session to . Returns at once; it never waits (#2306).

ok() says the QUIC handshake was started; on false the object is inert. The rest runs on msquic’s callbacks: CONNECTED sends the H3 face and the extended CONNECT, and the 200 opens the frame stream (session_up). A send before the frame stream exists is dropped and counted in dropped_tx, never queued (the down-link rule); a handshake or a CONNECT that fails ends in the link-down notifier, once. Inbound frames are held in msquic’s per-stream flow-control window until the owner installs its receivers and calls start_receiving (#1101, #2249), so a server that pushes the instant the session comes up cannot be decoded into an empty sink.

Parameters:
  • peer_host – Server hostname or dotted-quad IPv4 (the CONNECT :authority host part).

  • peer_port – Server UDP port (host byte order).

  • path – The CONNECT :path (a server-side namespace knob; this server accepts any path — default “/”). Empty is normalised to “/”. A SPEC-created dialer reaches this through the kind-private path config key (#1023).

  • tls – Server-certificate trust (see webtransport_dial_tls_t).

  • config – The link’s knobs (webtransport_config_t): memory, receive cap, handshake budget.

webtransport_transport_t(std::uint16_t bind_port, std::string_view cert_file, std::string_view key_file, const webtransport_config_t &config = {})

LISTEN mode: serve WebTransport (ALPN h3) on bind_port with the PEM certificate at cert_file / key at key_file, accepting ONE session at a time (the quic_transport_t one-peer model; re-accepts after a peer departs).

Use ok() to confirm the listener started; the bound port is observable via local_port(). The session peer opens the frame stream. Browser dev trust: serverCertificateHashes needs an ECDSA cert valid <= 14 days — see the TS package README; the C++ DIAL side accepts any cert under its DEV-ONLY no-verify mode.

Parameters:
  • bind_port – UDP port to listen on (host byte order; 0 → ephemeral).

  • cert_file – PEM server-certificate path.

  • key_file – PEM private-key path matching cert_file.

  • config – The link’s knobs (webtransport_config_t).

~webtransport_transport_t()

Shut the session down, drain msquic callbacks, and release the msquic API (listener → streams → connection → registration order).

virtual void shut_down() override

See transport_t::shut_down.

virtual void send(std::span<const std::byte> frame) override

Send frame as one length-prefixed record on the WebTransport frame stream.

One copy into the buffer msquic owns until SEND_COMPLETE (the quic_transport_t TX contract). No-op until the session’s frame stream is up (and after teardown). Thread-safe.

Parameters:

frame – A complete TLV’s bytes.

virtual void send(std::span<const std::span<const std::byte>> iov) override

Scatter-gather send: the prefix + every span as ONE record (one gather copy — the quic_transport_t rationale).

Parameters:

iov – The frame’s spans (a rope’s to_iovec()), concatenated on the wire as one length-prefixed frame.

virtual bool start_receiving() override

Open this link’s delivery gate — the second phase of every DIAL bring-up (#1101, #2249, ADR-0081 §2).

Re-enables msquic’s receive on the WebTransport frame stream, so everything the peer pushed while the owner was installing its sinks is re-indicated and delivered rather than dropped. IDEMPOTENT, and inert on an armed dialer, a listener, and a dial that never came up, which have nothing to arm, because transport_vertex_t::make_connection calls it on every link it wires. Opening the gate spawns nothing, so it never fails: true.

inline virtual bool delivers_ropes() const override

True — this transport honors set_rope_receiver (ADR-0042).

bool ok() const noexcept

The came-up predicate (#1059) — DIAL: the QUIC handshake was started (the session follows on msquic’s callbacks, session_up); LISTEN: the listener is up on its port. Answered at construction and never reverting; liveness is link_up.

std::uint16_t local_port() const noexcept

LISTEN mode: the actual bound UDP port (resolves an ephemeral 0).

Liveness (the transport_t::link_up contract): true while the WebTransport session is up (session_up) on a connected QUIC link, so a send seen up has its frame channel (#2306). Relaxed atomics.

bool dial_ended() const noexcept

DIAL: true once this dial’s one connection has ended — its handshake failed or it came up and went down — so an owner tells a failed dial from a pending one (#2306). Set just before the link-down fire. LISTEN: always false.

bool session_up() const noexcept

True once the WebTransport session is established — the extended CONNECT was accepted (LISTEN: request validated + 200 sent; DIAL: 200 received).

std::size_t session_path(std::span<char> out) const

The extended CONNECT :path of this endpoint’s session — DIAL: the path this endpoint requests (known from construction); LISTEN: the path the peer’s ACCEPTED CONNECT named, empty until one is accepted.

The listener serves every path (it validates :method/:protocol, never the resource), so this is an observation, not an admission decision: it is how a host sees which resource a session asked for. Copies into the caller’s buffer (#1780: no owning string crosses the API) — thread-safe, and not on any frame path.

STABLE for the life of a session (#1410): a second extended CONNECT on a live session is refused at stream scope, so a peer that has already been answered cannot rewrite what a host observes here. It changes only when the session itself does — connection teardown, or the one-peer replacement path accepting a new peer.

Parameters:

out – Where the path goes: its first min(out.size(), length) characters, no terminator.

Returns:

The path’s full length — larger than out.size() means it was truncated.

std::uint64_t refused_sessions() const noexcept

Extended CONNECT handshakes REFUSED because the node could not afford to answer them (#934).

The LISTEN side reaches two allocations on the strength of one unauthenticated peer’s HEADERS frame: recording the requested :path, and the one owned copy of the 200 response msquic borrows until SEND_COMPLETE. Both are nothrow, and a refusal is COUNT-THEN-CLOSE — this counter, then the connection is shut down with the bad-request code, so the peer’s memory is freed at once and nothing is left half-established. Never moves on a healthy node; a rising value means the node is shedding pre-auth work under memory pressure, which is the event the standing “no peer-provoked path may abort the node” commitment (docs/reference/07-host-embedding.md) makes observable rather than fatal.

Distinct from drop_stats().dropped_rx (a FRAME shed for backpressure on an established session) and from the stream-scoped handshake-buffer refusal, which aborts one stream and leaves an already-established session alone (#919).

virtual transport_drop_stats_t drop_stats() const noexcept override

This link’s shed-frame counters (#932, #2482).

dropped_rx: frames dropped because the RX backend was exhausted (backpressure, ADR-0042 §2), drained off the stream, never an OOM. malformed_rx: length prefixes announcing more than the frame cap; each shuts the session’s connection down. dropped_tx: a record over THIS CONNECTION’s cap (:settings max_frame, resolved tighten-only against kMaxFrame, #1409), no live peer stream to write to, or a StreamSend msquic refused. H3 handshake material is not counted: it is not a frame.

std::size_t live_streams() const noexcept

Stream contexts the live session currently holds — the leak observable (#1163).

A peer opens streams and this endpoint keeps one context per stream until the stream finishes. The count is therefore bounded by what the peer has open at once (PeerBidiStreamCount + PeerUnidiStreamCount + this endpoint’s own H3 streams), and NOT by how many the peer has ever opened. Before #1163 the second bound was the real one: nothing reclaimed a finished stream, so open/close cycling grew this without limit.

Exposed because a count that only ever rises is the signature of that class of bug and a deployment cannot see it otherwise — the same reason drop_stats is public. It is a live gauge, not a monotonic counter: it falls.

std::size_t effective_max_handshake() const noexcept

The pre-auth handshake budget actually honored: handshake_cap(max_handshake) as constructed (#1408). It names no backend — H3 handshake bytes accumulate in the stream context’s own buffer, not in an RX segment, so unlike the frame cap there is no second injected resource to take the min against. Answered on every link, including one whose dial never came up.

Public Static Functions

static inline constexpr std::size_t handshake_cap(std::size_t max_handshake) noexcept

Resolve a max_handshake request into the honored budget — TIGHTEN-ONLY against kMaxHandshakeBytes, exactly as length_prefix_framer_t::configured_cap is against kDefaultMaxFrame.

0 (unset) keeps the default; a nonzero value yields min(max_handshake, kMaxHandshakeBytes). The value arrives through a config-writable key (webtransport-private max_handshake), and a config-writable key must never RAISE a pre-auth bound — only narrow it.

Note

The same shape ws_server_transport_t::handshake_cap carries for the WS plane (#1407), deliberately spelled rather than shared: transport_ws.hpp sits behind LIBTRACER_TRANSPORT_WS and can be configured OFF, so consuming its symbol here would make an optional core module a hard dependency of this optional transport module.

Public Static Attributes

static constexpr std::size_t kMaxFrame = length_prefix_framer_t::kDefaultMaxFrame

The largest frame the length prefix may announce — the shared length_prefix_framer_t::kDefaultMaxFrame (16 MiB) unless :settings max_frame tightens it. A larger prefix is malformed: counted via drop_stats().malformed_rx and the session’s connection is shut down.

static constexpr std::size_t kMaxHandshakeBytes = 16u * 1024u

The largest H3 HANDSHAKE a PRE-AUTH peer may make this node buffer (16 KiB) — the ceiling max_handshake tightens against (#1408).

A different budget from kMaxFrame and deliberately so: a frame arrives on an established session under whatever the deployment allowed, while H3 classification bytes arrive from a host that has done nothing but complete a QUIC handshake and open one stream — no session, no ACL, no subscription, no router, nothing authenticated. Pre-auth work is REFUSED EARLY, not carefully allocated: an accumulation that would pass this budget is refused BEFORE the byte that would exceed it is copied, and a HEADERS or unknown/GREASE frame DECLARING more than it is refused before one body byte is buffered.

The two dispositions this module already distinguishes are unchanged and must not be merged: over-budget is a statement about the PEER, so it shuts the connection down with the bad-request code; running out of memory is a statement about US, so it is stream-scoped (#919) or count-then-close (refused_sessions, #934).

struct webtransport_dial_tls_t

DIAL-side TLS trust options for webtransport_transport_t (the quic_dial_tls_t shape for the HTTP/3 dial).

A browser trusts the server via WebCrypto serverCertificateHashes (dev) or a real certificate; this C++ dial side — used by the self-contained e2e tests and native clients — trusts a CA bundle, or skips validation in the DEV-ONLY mode a self-signed dev cert requires.

Public Members

std::string_view ca_file

PEM CA bundle path to verify the server certificate against (empty = the system trust store). Borrowed for the constructor call only (#1780).

bool insecure_no_verify = false

DEV ONLY: skip server certificate validation entirely (self-signed dev certs — tools/gen-dev-cert.sh). Never enable in deployment.

struct tls_profile_t

One app-registered TLS profile: the trust anchor a DIAL verifies against and the credential a LISTEN serves, under the name a SPEC’s tls key selects.

A profile may fill only the half its links use: a dial-only profile leaves the credential empty, a listen-only one leaves the anchor empty.

Public Members

std::string_view name

The value a SPEC’s tls key selects this profile by. The EMPTY name is the default profile: the one a SPEC that carries no tls key gets.

std::string_view ca_file

DIAL: PEM CA-bundle path the peer’s certificate is verified against; empty = the system trust store.

std::string_view cert_file

LISTEN: PEM server-certificate path. A LISTEN whose profile leaves it empty is refused.

std::string_view key_file

LISTEN: PEM private-key path matching cert_file.

constexpr const tls_profile_t *tr::net::find_tls_profile(std::span<const tls_profile_t> profiles, std::string_view name) noexcept

The profile in profiles named name, or nullptr when the table holds none.

First match wins, so a table that repeats a name keeps its earlier entry. A linear scan, run once per connection creation and never on the frame path.

Parameters:
  • profiles – The app’s table (the factory’s view of it).

  • name – The SPEC’s tls value; empty when the key is absent.

Returns:

The matching profile, or nullptr.

transport_factory_t tr::net::quic_transport_factory(std::span<const tls_profile_t> profiles = {}, mem::mem_backend_t *rx_backend = &mem::net_backend())

The ready-to-register quic transport factory — how this module plugs into the transport catalog (the register_transport_type extension seam; the core has no quic builtin).

Register at setup: net.register_transport_type("quic", quic_transport_factory(profiles)). A subsequent :children[] SPEC whose config carries kind = quic then constructs a quic_transport_t from the parsed settings — DIAL: addr + port; LISTEN: port. Both read two quic-PRIVATE config keys, parsed by the factory itself from the raw config SETTINGS TLV so the shared conn_settings_t stays lean with only the universal keys (the ADR-0043 §5 leanness ruling). Missing fields fail creation with TYPE_MISMATCH; a socket that failed to come up fails with TRANSPORT_DOWN — the TRANSIENT status, because the address resolved and it was the link that did not come up (#929). keepalive is ignored (#66 owns link lifecycle).

TLS material is app-owned. A SPEC can arrive from any writer, so it never carries a file path: the certificate, key and CA bundle come from profiles, the app’s table of tls_profile_t. The SPEC can at most select one by name:

  • tls (NAME) — the profile this link uses. Absent selects the profile named "" (the app’s default), if the table has one. A name the table does not hold is refused with TYPE_MISMATCH before any file is opened.

  • insecure (VALUE, u8; default 0) — 1 skips server-certificate validation entirely. DEV ONLY, and it requires the build capability tr::graph::default_config_t::kAllowInsecureTls (default false): without it a SPEC carrying insecure = nonzero is REFUSED at creation with PERMISSION_DENIED and counted in quic_insecure_refusals() (below), on either role. insecure = 0 is accepted on every build.

A LISTEN serves its profile’s cert_file/key_file; with no profile, or one that leaves either empty, creation answers TYPE_MISMATCH. A SPEC-created dialer verifies the server certificate (#918): against its profile’s ca_file, or, when there is no profile or it names no anchor, against the system trust store, and a certificate that does not chain is REFUSED (creation answers TRANSPORT_DOWN).

Parameters:
  • profiles – The app’s TLS profiles (default: none — dials verify against the system trust store, listens are refused). The factory keeps the span, not a copy: the table and the strings it views must outlive the factory and every transport it constructs.

  • rx_backend – The ADR-0042 §2 receive-segment seam every constructed socket draws its inbound frame segments from (default: the process heap). Must outlive the constructed transports.

Returns:

The factory functor for transport_vertex_t::register_transport_type.

transport_factory_t tr::net::webtransport_transport_factory(std::span<const tls_profile_t> profiles = {}, mem::mem_backend_t *rx_backend = &mem::net_backend())

The ready-to-register webtransport transport factory — how the module plugs this kind into the transport catalog (the register_transport_type extension seam; no core builtin).

Register at setup: net.register_transport_type("webtransport", webtransport_transport_factory(profiles)). A :children[] SPEC whose config carries kind = webtransport then constructs a webtransport_transport_t — DIAL: addr + port plus the OPTIONAL path and trust keys below; LISTEN: port plus a profile that carries the served credential. Both roles additionally read the OPTIONAL tls profile name and max_handshake budget (#1408). All four are kind-PRIVATE config keys parsed by this factory from the raw SPEC config TLV — they never appear on the shared conn_settings_t (the ADR-0043 §5 leanness ruling). Missing fields fail with TYPE_MISMATCH; a session that failed to come up fails with TRANSPORT_DOWN — the TRANSIENT status, because the address resolved and it was the link that did not come up (#929).

The DIAL key (#1023) carries the extended CONNECT :path — the resource the WebTransport session is opened on. NAME, default /, so a SPEC that omits it dials the same / this factory used to hard-code. Reaching a server that serves its session elsewhere needs it: this DIAL side treats any non-200 answer to the extended CONNECT as a failed session, so a wrong resource surfaces as TRANSPORT_DOWN from creation — the same status a rejected certificate gives. The key is kind-private, so it does not collide with the can kind’s unrelated path key (an advertised group path).

The key (#1408) carries the pre-auth H3 handshake budget in bytes — VALUE u32, default 0 = webtransport_transport_t::kMaxHandshakeBytes (16 KiB), read on BOTH roles and TIGHTEN-ONLY (webtransport_transport_t::handshake_cap clamps a larger request). It is the injected spelling of a bound that used to be a file-local literal, so the deployment sets the ceiling rather than the compiler.

TLS material is app-owned, exactly as for the quic kind: a SPEC never carries a file path. The certificate, key and CA bundle come from profiles, and the SPEC’s tls key (NAME) can at most select one by name — absent selects the profile named "", and a name the table does not hold is refused with TYPE_MISMATCH before any file is opened. A LISTEN serves its profile’s cert_file/key_file and is refused without them.

A SPEC-created dialer verifies the server certificate (#918) — against its profile’s ca_file, or, with no profile or no anchor in it, against the system trust store; a certificate that does not chain is REFUSED (creation answers TRANSPORT_DOWN). insecure (VALUE u8, default 0) set to 1 skips validation entirely — DEV ONLY, and it requires the build capability tr::graph::default_config_t::kAllowInsecureTls (default false): without it a SPEC carrying insecure = nonzero is REFUSED at creation with PERMISSION_DENIED and counted in webtransport_insecure_refusals() (below), on either role. insecure = 0 is accepted on every build.

Parameters:
  • profiles – The app’s TLS profiles (default: none — dials verify against the system trust store, listens are refused). The factory keeps the span, not a copy: the table and the strings it views must outlive the factory and every transport it constructs.

  • rx_backend – The ADR-0042 §2 receive-segment seam every constructed endpoint draws inbound frame segments from (default: the process net sub-pool). Must outlive the constructed transports.

Returns:

The factory functor for transport_vertex_t::register_transport_type.

In-process loopback (development and test)

class loopback_channel_t

An in-process loopback channel: two endpoints, each delivering to the other.

A frame sent on a is delivered to b’s receiver (and vice-versa), on that endpoint’s receive thread — modeling async cross-“wire” delivery so forwarding never recurses on the sender’s stack. No sockets; deterministic. The vehicle for exercising FWD forward/reply routing end to end (RFC-0004, ADR-0040). Non-copyable. Call shutdown (or destroy the channel) before the registered receivers are destroyed.

Public Functions

explicit loopback_channel_t(mem::block_source_t &src = mem::net_source())

Construct a channel and start both endpoints’ receive threads.

Parameters:

src – Where every queued frame and both receive threads come from; it MUST outlive the channel. The default is the build’s net sub-pool.

~loopback_channel_t()

Destroy the channel, joining both receive threads first.

inline loopback_endpoint_t &a() noexcept

The first endpoint; a frame sent here is delivered to b.

inline loopback_endpoint_t &b() noexcept

The second endpoint; a frame sent here is delivered to a.

void shutdown()

Join both receive threads so no frame reaches a dead receiver (idempotent).

class loopback_endpoint_t : public tr::net::transport_t

One end of an in-process loopback link (dev/test only).

A transport_t whose send hands the frame to the PEER endpoint’s receiver, on that peer’s receive thread. Constructed and owned by a loopback_channel_t.

Public Functions

virtual void send(std::span<const std::byte> frame) override

Send one frame — delivered to the peer endpoint’s receiver on its recv thread. A frame the source refuses, or sent with no running peer, is dropped and counted in drop_stats (dropped_tx).

virtual void send(std::span<const std::span<const std::byte>> iov) override

Scatter-gather send (#2679): the spans are gathered ONCE, straight into the block drawn from the peer’s source, with no egress-store temporary. Same delivery and drop contract as the span form.

inline virtual transport_drop_stats_t drop_stats() const noexcept override

The frames this endpoint’s send dropped (dropped_tx); the other fields stay zero.

Catalog registration

void tr::net::register_builtin_transports(transport_vertex_t &vertex, mem::mem_backend_t *rx_backend, mem::block_source_t *egress_src = &mem::net_source())

Register every built-in transport factory compiled into this build.

Called once from the transport_vertex_t

constructor. The definition is build-specific and generated from one template, src/builtin_transports.cpp.in (#2439): core CMake and the ESP-IDF component at configure time, PlatformIO in its build script. It calls only the register_*_transport of the transports the build compiles.

Each register_*_transport also reads the vertex’s node-wide link memory default (

transport_vertex_t::link_memory, #2574) and builds every link from it — see builtin_link_memory.

Parameters:
  • vertex – The transport vertex to register the catalog entries on.

  • rx_backend – The ADR-0042 §2 receive-segment seam threaded to owning transports.

  • egress_src – The ADR-0079 net-plane EGRESS store threaded to every socket these factories construct — see with_egress_source. Default: the process net sub-pool (#1777).

void tr::net::register_udp_transport(transport_vertex_t &vertex, mem::mem_backend_t *rx_backend, mem::block_source_t *egress_src = &mem::net_source())

Register the built-in udp transport factory on vertex (needs transport_udp). egress_src is the ADR-0079 egress store — see with_egress_source.

void tr::net::register_tcp_transport(transport_vertex_t &vertex, mem::mem_backend_t *rx_backend, mem::block_source_t *egress_src = &mem::net_source())

Register the built-in tcp transport factory on vertex (needs transport_tcp). egress_src is the ADR-0079 egress store — see with_egress_source.

void tr::net::register_ws_transport(transport_vertex_t &vertex, mem::mem_backend_t *rx_backend, mem::block_source_t *egress_src = &mem::net_source())

Register the built-in ws transport factory on vertex (needs transport_ws). egress_src is the ADR-0079 egress store — see with_egress_source.

inline graph::result_t<transport_ptr_t> tr::net::with_egress_source(graph::result_t<transport_ptr_t> link, mem::block_source_t *egress_src) noexcept

Wire egress_src into a just-constructed link — the EGRESS half of a factory’s memory injection (#873 family 1, ADR-0079’s net-plane failable store).

The rx_backend argument every factory already carries is the INGRESS seam (ADR-0042 §2); this is its egress twin, and the two are deliberately separate objects: an inbound frame becomes a refcounted segment_t the receiver may keep, while an egress gather is a raw, per-send scratch block whose exhaustion answer is “drop this frame”. Applied right after construction and before the link is wired into the router, which is the transport_t::set_egress_source contract (“before frames flow”).

A failed construction passes through untouched, so a factory can wrap its dial_or_listen result in one expression.

Parameters:
  • link – The factory’s result — forwarded on unchanged.

  • egress_src – The store to wire; nullptr leaves the link on the process default.

inline bus_link_t *tr::net::bus_of(transport_t &link)

link's BUS facet, or nullptr on a target that closed the bus module out — the ONE door the routing plane asks through (#375 deliverable 3).

At the default binding this is link.bus() and nothing else: the if constexpr selects the live branch, so every consumer’s machine code is byte-identical to the direct call (verified by object-file cmp — 68 of 68 objects unchanged). Bound tr::graph::default_config_t::kBusLinks false, the call is not merely predicted away — it is not compiled, so the peer-resolution, peer-enumeration and peer-lifecycle code that hangs off a non-null result is unreachable and the linker keeps none of it.

Consumers ask through here rather than reading tr::net::kBusLinks so that the point-to-point answer is spelled once. transport_t::bus() itself is untouched — still a virtual, still return nullptr by default (ADR-0047 §4: peer wiring is a wiring-frequency query, and this adds no template parameter and no dispatch mechanism to any control structure).

Warning

A DIRECT link.bus() call bypasses the gate and is correct only where the caller IS the bus (a transport’s own facet, a test pinning a link’s shape). Anything on the routing plane asks here.

Parameters:

link – The link to interrogate.

Return values:

nullptr – link is point-to-point, or this target carries no bus module at all.

write_fault_stats_t tr::net::write_fault_stats() noexcept

Read the write_fault_stats_t tally (relaxed; a diagnostic read, not a synchronizer).

CAN is a stack of its own — the ID codec, the advertise stream, the splitter and the reassembler as well as the binding — and has its own page.

The transport set closes at link time: it is the sources a target compiles and the factories it registers, with ordinary runtime dispatch inside, and adding a platform transport appends to that set without editing core. Kinds are fixed at build time, but connections stay runtime: a creator-endpoint SPEC write names the kind as data.

See: can, fwd-router, interface map, reference §communication flows, bench suite.