In-process pub/sub (L4 graph)¶
The smallest complete libtracer node: a single-process graph with
no transport and no wire bytes. A publisher writes /sensor/temp; three subscribers each
receive the value a different way:
a direct in-process callback — the
subscribe(src, callback)sugar;a spec-faithful target vertex —
subscribe(src, target)re-dispatches to a handler-backed sink vertex;a thread blocking in
await()— the single-shot readiness primitive.
Delivery to (1) and (2) is a refcount-bump clone of the same rope
value — no byte copy. The example finishes by reading the last-known-value back and
declaring the STREAM ring depth owner-side (vertex_policy_t::retention, which has no wire
surface), then discovering the vertex shape via the :schema control read.
What to notice¶
Handles, not strings, on the hot path — the path is encoded once via the parse-once
path_t("…")constructor;register_vertexreturns avertex_handle_treused for every op.awaitis join-safe — the publisherjoin()s the waiter after the write, so every delivery is complete and visible when the checks run.It self-checks — each delivery path is asserted, so the ctest smoke test guards behavior, not just a clean exit.
Source¶
1/*
2 * SPDX-License-Identifier: Apache-2.0
3 * SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
4 */
5
6/**
7 * @file
8 * @brief In-process publish/subscribe over the L4 graph — the M3 P0 node, end to end.
9 *
10 * No transport, no wire bytes leave the process. A publisher writes
11 * `/sensor/temp`; three subscribers receive the value three different ways:
12 * 1. a direct in-process callback — `subscribe(src, callback)` sugar;
13 * 2. a spec-faithful target vertex — `subscribe(src, target)` → a handler sink;
14 * 3. a thread blocking in `await()` — the single-shot primitive.
15 * Delivery to (1) and (2) is a refcount-bump clone of the same rope value — no
16 * byte copy.
17 *
18 * Runs under ctest as `example_in_process_pubsub`: it @ref check "checks" every
19 * delivered value and returns non-zero on any mismatch, so the smoke test guards
20 * behavior (each subscriber sees the write) rather than merely exiting cleanly.
21 */
22
23#include <atomic>
24#include <chrono>
25#include <cstddef>
26#include <cstdint>
27#include <cstdio>
28#include <iterator>
29#include <thread>
30
31#include "libtracer/tracer.hpp"
32
33namespace {
34
35using namespace std::chrono_literals;
36using tr::graph::path_t;
37using tr::graph::role_t;
38
39/** @brief A 4-byte little-endian VALUE view over @p v (one heap segment). */
40tr::view::view_t value_u32(std::uint32_t v) {
41 tr::view::segment_ptr_t seg = tr::view::heap_alloc(4);
42 for (int i = 0; i < 4; ++i)
43 seg->bytes[static_cast<std::size_t>(i)] = static_cast<std::byte>((v >> (8 * i)) & 0xFF);
44 return tr::view::view_t::over(std::move(seg));
45}
46
47/** @brief Decode a little-endian u32 from @p view's first (≤4) bytes. */
48std::uint32_t as_u32(const tr::view::view_t& view) {
49 const auto b = view.bytes();
50 std::uint32_t v = 0;
51 for (std::size_t i = 0; i < b.size() && i < 4; ++i)
52 v |= static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(b[i])) << (8 * i);
53 return v;
54}
55
56/** @brief Record a failed expectation on @p ok and report it; leaves @p ok false on failure. */
57void check(bool& ok, bool cond, const char* what) {
58 if (!cond) {
59 std::printf(" [FAIL] %s\n", what);
60 ok = false;
61 }
62}
63
64/** @brief This application's clock, in milliseconds: the `now` it hands the graph. */
65std::uint64_t now_ms() {
66 return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
67 std::chrono::steady_clock::now().time_since_epoch())
68 .count());
69}
70
71/**
72 * @brief The application's side of an await's deadline: pass `now` to expire_awaits until
73 * @p done is set. libtracer reads no clock, so this loop is what ends a wait that is due.
74 */
75void drive_until(tr::graph::graph_t& g, const std::atomic<bool>& done) {
76 while (!done.load(std::memory_order_acquire)) {
77 (void)g.expire_awaits(now_ms());
78 std::this_thread::sleep_for(std::chrono::milliseconds(1));
79 }
80}
81
82} // namespace
83
84int main() {
85 constexpr std::uint32_t kSent = 23;
86 tr::graph::graph_t g;
87
88 const tr::graph::vertex_handle_t temp =
89 g.register_vertex(path_t("/sensor/temp"), role_t::STORED_VALUE);
90
91 // Values captured from each delivery path, verified at the end.
92 std::uint32_t cb_got = 0; // subscriber 1 (callback)
93 std::uint32_t sink_got = 0; // subscriber 2 (target vertex handler)
94 std::uint32_t await_got = 0; // subscriber 3 (await)
95
96 // A "sink" vertex backed by a callback handler — the target of a spec-faithful
97 // SUBSCRIBER (subscriber 2 below re-dispatches to it).
98 // Its `on_write` is a `{fn, ctx}` hook: `ctx` is `&sink_got`, which outlives the graph's
99 // use of it, and the value arrives by reference — the very block /sensor/temp published.
100 tr::graph::handlers_t sink;
101 sink.on_write = {[](void* ctx, const tr::graph::value_t& in,
102 const tr::graph::write_ctx_t&) -> tr::graph::result_t<void> {
103 auto& got = *static_cast<std::uint32_t*>(ctx);
104 got = as_u32(in.only());
105 std::printf(" [sink vertex /log/temp] received %u\n", got);
106 return {};
107 },
108 &sink_got};
109 (void)g.register_vertex(path_t("/log/temp"), role_t::HANDLER, sink);
110
111 // subscriber_t 1 — direct in-process callback.
112 auto on_temp = [&cb_got](const tr::graph::value_t& v) {
113 cb_got = as_u32(v.only());
114 std::printf(" [callback sub] received %u\n", cb_got);
115 };
116 (void)g.subscribe(path_t("/sensor/temp"), on_temp);
117 // subscriber_t 2 — spec-faithful target-path subscription -> /log/temp.
118 (void)g.subscribe(path_t("/sensor/temp"), path_t("/log/temp"));
119
120 // subscriber_t 3 — a thread blocking in await().
121 // Its deadline is 2 s on this app's clock (libtracer reads none), so a write that lands
122 // before it parks costs a TIMEOUT, never a hang.
123 std::atomic<bool> answered{false};
124 std::thread waiter([&] {
125 const std::uint64_t now = now_ms();
126 auto r = g.await(temp, now, now + 2000);
127 if (r) {
128 await_got = as_u32((*r)->only());
129 std::printf(" [await sub] received %u\n", await_got);
130 }
131 answered.store(true, std::memory_order_release);
132 });
133 std::this_thread::sleep_for(50ms); // let the waiter park in await()
134
135 std::printf("publisher: write /sensor/temp = %u\n", kSent);
136 (void)g.write(temp, value_u32(kSent));
137 drive_until(g, answered);
138 waiter.join(); // joins-after-write: every delivery is complete + visible here
139
140 // Read back the last-known-value (a clone — keeps the segment alive for us).
141 auto rb = g.read(temp);
142 const std::uint32_t rb_got = rb ? as_u32((*rb)->only()) : 0u;
143 std::printf("read-back /sensor/temp = %u\n", rb_got);
144
145 // Declare the STREAM ring depth OWNER-SIDE (RFC-0022 §3.C — it has no wire surface),
146 // then discover the vertex shape via :schema.
147 (void)g.set_policy(temp, {.retention = tr::graph::retention_t::N, .depth = 8});
148 auto schema = g.read(path_t("/sensor/temp:schema"));
149 std::size_t schema_children = 0;
150 if (schema) {
151 if (auto point = tr::wire::tlv_node_t::over((*schema)->only()))
152 schema_children = static_cast<std::size_t>(std::ranges::distance(point->children()));
153 }
154 std::printf(":schema is a POINT with %zu children\n", schema_children);
155
156 // Guard the semantics, not just a clean exit: every path must see the write.
157 bool ok = true;
158 check(ok, cb_got == kSent, "callback subscriber received the written value");
159 check(ok, sink_got == kSent, "target-vertex subscriber received the written value");
160 check(ok, await_got == kSent, "await subscriber received the written value");
161 check(ok, rb_got == kSent, "read-back returns the last-known-value");
162 check(ok, schema_children == 2, ":schema resolves to a 2-child POINT");
163 return ok ? 0 : 1;
164}
See also: graph module · views · path.