dora_message/node_to_daemon.rs
1pub use crate::common::{DataMessage, LogLevel, LogMessage, SharedMemoryId, Timestamped};
2use crate::{
3 DataflowId, current_crate_version,
4 id::{DataId, NodeId},
5 metadata::Metadata,
6 versions_compatible,
7};
8
9/// A request from a node to its daemon.
10///
11/// # Adding a variant
12///
13/// Every new variant must expect a binary [`DaemonReply`](crate::daemon_to_node::DaemonReply),
14/// i.e. [`expects_tcp_binary_reply`](Self::expects_tcp_binary_reply) must
15/// return `true` for it. A daemon cannot decode a variant it predates, so it
16/// cannot tell whether the sender waits for an answer. With this rule, an
17/// undecodable request always waits for one, and the daemon can answer it
18/// with an error while keeping the connection open. Only `SendMessage`,
19/// `OutputSent` and `NodeConfig` get no binary reply; they are part of the
20/// frozen 1.x wire format and must always decode. A change to the metadata
21/// wire format they carry must bump [`Metadata::CURRENT_VERSION`].
22/// [`frame_expects_reply`](Self::frame_expects_reply) is the daemon's fallback
23/// if one still fails to decode. See "Stability scope at 1.0" in
24/// `docs/api-rust.md`.
25#[allow(clippy::large_enum_variant)]
26#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
27#[non_exhaustive]
28pub enum DaemonRequest {
29 Register(NodeRegisterRequest),
30 Subscribe,
31 SendMessage {
32 output_id: DataId,
33 metadata: Metadata,
34 data: Option<DataMessage>,
35 },
36 OutputSent {
37 output_id: DataId,
38 metadata: Metadata,
39 },
40 CloseOutputs(Vec<DataId>),
41 /// Signals that the node is finished sending outputs.
42 OutputsDone,
43 NextEvent,
44 EventStreamDropped,
45 NodeConfig {
46 node_id: NodeId,
47 },
48 /// Store an opaque value in the daemon's dataflow-scoped extension table.
49 ///
50 /// dora attaches no meaning to `namespace`, `key` or `value`: this is the
51 /// out-of-band channel for transports that live outside the tree (see
52 /// `docs/extensions.md`). The daemon tracks who stored a key and who has
53 /// read it, so it can notify readers on removal and reclaim the entry when
54 /// the dataflow ends.
55 ExtensionStore {
56 namespace: String,
57 key: String,
58 value: Vec<u8>,
59 },
60 /// Read an opaque value back. `remove: true` drops it in the same round
61 /// trip, so a consume-once handoff needs one request rather than two.
62 ExtensionLoad {
63 namespace: String,
64 key: String,
65 remove: bool,
66 },
67 /// Drop an opaque value. Every node that stored or loaded the key is sent
68 /// [`NodeEvent::ExtensionDropped`](crate::daemon_to_node::NodeEvent::ExtensionDropped) so it can release whatever the value
69 /// referred to.
70 ExtensionDrop {
71 namespace: String,
72 key: String,
73 },
74 /// An opaque request from a node to the extension registered under
75 /// `namespace` on its daemon. dora never interprets either field.
76 ///
77 /// Complements the extension table (`ExtensionStore`/`ExtensionLoad`/
78 /// `ExtensionDrop`), which brokers descriptor *lifetime*. This one
79 /// carries a call the extension's daemon half must service — the
80 /// tensor-pool uses it for cross-machine registration and pool writes.
81 ExtensionRequest {
82 namespace: String,
83 #[serde(with = "crate::bulk_bytes::vec")]
84 payload: Vec<u8>,
85 },
86}
87
88impl DaemonRequest {
89 /// Bulk bytes this request will contribute to its encoding, for
90 /// [`crate::encode_presized`].
91 ///
92 /// Matched exhaustively on purpose: a new payload-carrying variant that
93 /// forgets to report its size would silently fall back to growing the
94 /// buffer from empty, which is the cost `encode_presized` exists to avoid
95 /// and which no test would catch.
96 pub fn encode_size_hint(&self) -> usize {
97 match self {
98 DaemonRequest::SendMessage { data, .. } => data.as_ref().map_or(0, DataMessage::len),
99 DaemonRequest::Register(_)
100 | DaemonRequest::Subscribe
101 | DaemonRequest::OutputSent { .. }
102 | DaemonRequest::CloseOutputs(_)
103 | DaemonRequest::OutputsDone
104 | DaemonRequest::NextEvent
105 | DaemonRequest::EventStreamDropped
106 | DaemonRequest::NodeConfig { .. } => 0,
107 // The stored value dominates; the namespace and key are short.
108 DaemonRequest::ExtensionStore { value, .. } => value.len(),
109 DaemonRequest::ExtensionLoad { .. } | DaemonRequest::ExtensionDrop { .. } => 0,
110 DaemonRequest::ExtensionRequest { payload, .. } => payload.len(),
111 }
112 }
113
114 pub fn expects_tcp_binary_reply(&self) -> bool {
115 #[allow(clippy::match_like_matches_macro)]
116 match self {
117 // Frozen set: don't add variants here. A new request must expect a
118 // binary reply (see the `DaemonRequest` docs).
119 DaemonRequest::SendMessage { .. }
120 | DaemonRequest::OutputSent { .. }
121 | DaemonRequest::NodeConfig { .. } => false,
122 DaemonRequest::Register(NodeRegisterRequest { .. })
123 | DaemonRequest::Subscribe
124 | DaemonRequest::CloseOutputs(_)
125 | DaemonRequest::OutputsDone
126 | DaemonRequest::NextEvent
127 | DaemonRequest::EventStreamDropped
128 | DaemonRequest::ExtensionRequest { .. }
129 | DaemonRequest::ExtensionStore { .. }
130 | DaemonRequest::ExtensionLoad { .. }
131 | DaemonRequest::ExtensionDrop { .. } => true,
132 }
133 }
134
135 pub fn expects_tcp_json_reply(&self) -> bool {
136 #[allow(clippy::match_like_matches_macro)]
137 match self {
138 DaemonRequest::NodeConfig { .. } => true,
139 DaemonRequest::Register(NodeRegisterRequest { .. })
140 | DaemonRequest::Subscribe
141 | DaemonRequest::CloseOutputs(_)
142 | DaemonRequest::OutputsDone
143 | DaemonRequest::NextEvent
144 | DaemonRequest::SendMessage { .. }
145 | DaemonRequest::OutputSent { .. }
146 | DaemonRequest::EventStreamDropped
147 | DaemonRequest::ExtensionRequest { .. }
148 | DaemonRequest::ExtensionStore { .. }
149 | DaemonRequest::ExtensionLoad { .. }
150 | DaemonRequest::ExtensionDrop { .. } => false,
151 }
152 }
153
154 /// Whether the sender of an encoded `Timestamped<DaemonRequest>` frame
155 /// waits for a reply, judged from the frame's leading variant tag alone.
156 ///
157 /// For a daemon that failed to [`decode`](crate::decode) the frame: it must
158 /// answer a request whose sender blocks on a reply, and must not answer one
159 /// whose sender reads nothing, or the unsolicited frame would shift every
160 /// later request/reply pair on the connection by one.
161 ///
162 /// This is defence in depth. The fire-and-forget requests are
163 /// expected to always decode: a payload change that breaks that, such as a
164 /// new [`Parameter`](crate::metadata::Parameter) kind, must bump
165 /// [`Metadata::CURRENT_VERSION`], which rejects the node at register time.
166 ///
167 /// Returns `false` only for `SendMessage` and `OutputSent` (neither a
168 /// binary nor a JSON reply). Every other tag, including one this crate does
169 /// not know and a frame too short to hold a tag, counts as expecting a
170 /// reply, per the rule on [`DaemonRequest`].
171 pub fn frame_expects_reply(frame: &[u8]) -> bool {
172 // `Timestamped` encodes `inner` first, and postcard writes an enum
173 // variant index as a varint `u32`. The indices are pinned by
174 // `reply_policy_tests::frame_tag_matches_the_reply_policy`.
175 const SEND_MESSAGE: u32 = 2;
176 const OUTPUT_SENT: u32 = 3;
177 !matches!(
178 postcard::take_from_bytes::<u32>(frame),
179 Ok((SEND_MESSAGE | OUTPUT_SENT, _))
180 )
181 }
182}
183
184#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
185pub struct NodeRegisterRequest {
186 pub dataflow_id: DataflowId,
187 pub node_id: NodeId,
188 dora_version: semver::Version,
189 /// The metadata wire-format version this node was built against
190 /// ([`Metadata::CURRENT_VERSION`]).
191 ///
192 /// The `dora_version` semver check above is too coarse to catch a
193 /// message-format break within a release series: two builds that both
194 /// report `1.0.0-rc` are "compatible" by semver even when the payload
195 /// layout differs (as it did across #2366). Carrying the format version
196 /// explicitly lets the daemon reject an incompatible peer at register with
197 /// a clear message, instead of the node desyncing mid-stream into a
198 /// cryptic bad-enum-discriminant deserialization error (#2742).
199 ///
200 /// This covers *layout* drift within one encoding. It cannot cover a change
201 /// of the encoding itself: the register frame is encoded the same way as
202 /// everything else, so a peer from before the bincode→postcard move fails
203 /// while decoding the frame that carries this field, never reaching the
204 /// check. Such changes are gated by the release notes instead.
205 metadata_version: u16,
206}
207
208impl NodeRegisterRequest {
209 pub fn new(dataflow_id: DataflowId, node_id: NodeId) -> Self {
210 Self {
211 dataflow_id,
212 node_id,
213 dora_version: current_crate_version(),
214 metadata_version: Metadata::CURRENT_VERSION,
215 }
216 }
217
218 pub fn check_version(&self) -> Result<(), String> {
219 let crate_version = current_crate_version();
220 let specified_version = &self.dora_version;
221
222 if !versions_compatible(&crate_version, specified_version)? {
223 return Err(format!(
224 "version mismatch: message format v{} is not compatible \
225 with expected message format v{crate_version}",
226 self.dora_version
227 ));
228 }
229
230 // Even when the semver check passes, the payload wire format can still
231 // differ within a release series (#2366 dropped a `Metadata` field
232 // without changing the version). Reject that here so the failure is a
233 // legible register-time error rather than a mid-stream desync (#2742).
234 if self.metadata_version != Metadata::CURRENT_VERSION {
235 return Err(format!(
236 "message wire-format mismatch: node speaks metadata format v{} \
237 but this daemon speaks v{}. The node and daemon were built from \
238 dora revisions with incompatible message formats; rebuild both \
239 from the same revision.",
240 self.metadata_version,
241 Metadata::CURRENT_VERSION
242 ));
243 }
244
245 Ok(())
246 }
247}
248
249#[derive(Debug, serde::Deserialize, serde::Serialize)]
250pub enum DynamicNodeEvent {
251 NodeConfig { node_id: NodeId },
252}
253
254#[cfg(test)]
255mod register_version_tests {
256 use super::*;
257
258 fn request() -> NodeRegisterRequest {
259 NodeRegisterRequest::new(uuid::Uuid::nil(), NodeId::from("test-node".to_string()))
260 }
261
262 #[test]
263 fn new_stamps_current_metadata_version() {
264 assert_eq!(request().metadata_version, Metadata::CURRENT_VERSION);
265 }
266
267 #[test]
268 fn check_version_accepts_a_matching_request() {
269 // A request built by this same crate version passes both the semver
270 // and the wire-format gate.
271 request().check_version().unwrap();
272 }
273
274 #[test]
275 fn check_version_rejects_a_wire_format_mismatch() {
276 // A peer built from a dora revision with a different metadata wire
277 // format — same semver, incompatible bytes. This is the #2366 / #2742
278 // shape: it must be rejected at register with a legible message rather
279 // than desyncing mid-stream into a cryptic deserialization error.
280 let mut req = request();
281 req.metadata_version = Metadata::CURRENT_VERSION.wrapping_add(1);
282 let err = req
283 .check_version()
284 .expect_err("mismatched metadata wire version must be rejected");
285 assert!(
286 err.contains("wire-format") && err.contains(&Metadata::CURRENT_VERSION.to_string()),
287 "error should name the wire-format mismatch and the expected version, got: {err}"
288 );
289 }
290}
291
292#[cfg(test)]
293mod reply_policy_tests {
294 use super::*;
295
296 /// The frozen set of requests that get no binary reply.
297 ///
298 /// Matched exhaustively, so a new `DaemonRequest` variant fails to compile
299 /// here until it is classified. It belongs in the `false` arm: a new
300 /// request must expect a binary reply (see the `DaemonRequest` docs).
301 fn is_frozen_no_binary_reply(request: &DaemonRequest) -> bool {
302 match request {
303 DaemonRequest::SendMessage { .. }
304 | DaemonRequest::OutputSent { .. }
305 | DaemonRequest::NodeConfig { .. } => true,
306 DaemonRequest::Register(_)
307 | DaemonRequest::Subscribe
308 | DaemonRequest::CloseOutputs(_)
309 | DaemonRequest::OutputsDone
310 | DaemonRequest::NextEvent
311 | DaemonRequest::EventStreamDropped
312 | DaemonRequest::ExtensionStore { .. }
313 | DaemonRequest::ExtensionLoad { .. }
314 | DaemonRequest::ExtensionDrop { .. }
315 | DaemonRequest::ExtensionRequest { .. } => false,
316 }
317 }
318
319 fn one_of_each() -> Vec<DaemonRequest> {
320 let metadata = || Metadata::new(uhlc::HLC::default().new_timestamp());
321 let text = || "x".to_string();
322 vec![
323 DaemonRequest::Register(NodeRegisterRequest::new(
324 uuid::Uuid::nil(),
325 NodeId::from(text()),
326 )),
327 DaemonRequest::Subscribe,
328 DaemonRequest::SendMessage {
329 output_id: DataId::from(text()),
330 metadata: metadata(),
331 data: None,
332 },
333 DaemonRequest::OutputSent {
334 output_id: DataId::from(text()),
335 metadata: metadata(),
336 },
337 DaemonRequest::CloseOutputs(Vec::new()),
338 DaemonRequest::OutputsDone,
339 DaemonRequest::NextEvent,
340 DaemonRequest::EventStreamDropped,
341 DaemonRequest::NodeConfig {
342 node_id: NodeId::from(text()),
343 },
344 DaemonRequest::ExtensionStore {
345 namespace: text(),
346 key: text(),
347 value: Vec::new(),
348 },
349 DaemonRequest::ExtensionLoad {
350 namespace: text(),
351 key: text(),
352 remove: false,
353 },
354 DaemonRequest::ExtensionDrop {
355 namespace: text(),
356 key: text(),
357 },
358 DaemonRequest::ExtensionRequest {
359 namespace: text(),
360 payload: Vec::new(),
361 },
362 ]
363 }
364
365 #[test]
366 fn only_the_frozen_requests_skip_the_binary_reply() {
367 for request in one_of_each() {
368 assert_eq!(
369 request.expects_tcp_binary_reply(),
370 !is_frozen_no_binary_reply(&request),
371 "a request other than SendMessage, OutputSent and NodeConfig must \
372 expect a binary reply: {request:?}"
373 );
374 }
375 }
376 #[test]
377 fn frame_tag_matches_the_reply_policy() {
378 for request in one_of_each() {
379 let expects_reply =
380 request.expects_tcp_binary_reply() || request.expects_tcp_json_reply();
381 let frame = crate::encode(&crate::common::Timestamped {
382 inner: request.clone(),
383 timestamp: uhlc::HLC::default().new_timestamp(),
384 })
385 .unwrap();
386 assert_eq!(
387 DaemonRequest::frame_expects_reply(&frame),
388 expects_reply,
389 "the frame tag must classify {request:?} like the reply policy"
390 );
391 // A payload this crate cannot decode keeps the tag's verdict.
392 let mut truncated = frame.clone();
393 truncated.truncate(1);
394 assert_eq!(
395 DaemonRequest::frame_expects_reply(&truncated),
396 expects_reply
397 );
398 }
399 }
400
401 #[test]
402 fn unknown_or_missing_tag_expects_a_reply() {
403 // A variant this crate predates (and a multi-byte varint index).
404 assert!(DaemonRequest::frame_expects_reply(&[200, 1]));
405 assert!(DaemonRequest::frame_expects_reply(&[0x7F]));
406 assert!(DaemonRequest::frame_expects_reply(&[]));
407 }
408}