Skip to main content

dora_message/
cli_to_coordinator.rs

1use std::{collections::BTreeMap, path::PathBuf, time::Duration};
2
3use uuid::Uuid;
4
5use crate::{
6    BuildId, SessionId,
7    common::GitSource,
8    descriptor::Descriptor,
9    id::{DataId, NodeId, OperatorId},
10};
11
12#[allow(clippy::large_enum_variant)]
13#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
14pub enum ControlRequest {
15    Build {
16        session_id: SessionId,
17        #[serde(serialize_with = "crate::descriptor::serialize_without_path_fallback")]
18        dataflow: Descriptor,
19        git_sources: BTreeMap<NodeId, GitSource>,
20        prev_git_sources: BTreeMap<NodeId, GitSource>,
21        /// Allows overwriting the base working dir when CLI and daemon are
22        /// running on the same machine.
23        ///
24        /// Must not be used for multi-machine dataflows.
25        ///
26        /// Note that nodes with git sources still use a subdirectory of
27        /// the base working dir.
28        local_working_dir: Option<PathBuf>,
29        uv: bool,
30    },
31    WaitForBuild {
32        build_id: BuildId,
33    },
34    Start {
35        build_id: Option<BuildId>,
36        session_id: SessionId,
37        #[serde(serialize_with = "crate::descriptor::serialize_without_path_fallback")]
38        dataflow: Descriptor,
39        name: Option<String>,
40        /// Allows overwriting the base working dir when CLI and daemon are
41        /// running on the same machine.
42        ///
43        /// Must not be used for multi-machine dataflows.
44        ///
45        /// Note that nodes with git sources still use a subdirectory of
46        /// the base working dir.
47        local_working_dir: Option<PathBuf>,
48        uv: bool,
49        write_events_to: Option<PathBuf>,
50    },
51    WaitForSpawn {
52        dataflow_id: Uuid,
53    },
54    Reload {
55        dataflow_id: Uuid,
56        node_id: NodeId,
57        operator_id: Option<OperatorId>,
58    },
59    Check {
60        dataflow_uuid: Uuid,
61    },
62    Stop {
63        dataflow_uuid: Uuid,
64        grace_duration: Option<Duration>,
65        #[serde(default)]
66        force: bool,
67    },
68    StopByName {
69        name: String,
70        grace_duration: Option<Duration>,
71        #[serde(default)]
72        force: bool,
73    },
74    Restart {
75        dataflow_uuid: Uuid,
76        grace_duration: Option<Duration>,
77        #[serde(default)]
78        force: bool,
79    },
80    RestartByName {
81        name: String,
82        grace_duration: Option<Duration>,
83        #[serde(default)]
84        force: bool,
85    },
86    Logs {
87        uuid: Option<Uuid>,
88        name: Option<String>,
89        node: String,
90        tail: Option<usize>,
91    },
92    Destroy,
93    List,
94    /// Remove fully-completed dataflows from the coordinator's state.
95    ///
96    /// A dataflow is considered fully completed when no daemon is still
97    /// running it (i.e. it's no longer in `running_dataflows`). Multi-daemon
98    /// dataflows that are still finishing — where some daemons have reported
99    /// results but others haven't — are intentionally skipped so their final
100    /// status is computed correctly when the last daemon completes.
101    ///
102    /// Candidates are enumerated from BOTH the in-memory
103    /// `dataflow_results` map AND the persisted store
104    /// (`Succeeded` / `Failed` records). This lets a restarted
105    /// coordinator still reap historical rows that exist only on
106    /// disk — the recovery loop intentionally does not reload them
107    /// into memory, so without the persisted-store pass they would
108    /// otherwise sit in redb forever and never become reachable for
109    /// `dora clean`. If the persisted-store enumeration itself
110    /// errors, the entire request fails with
111    /// [`ControlRequestReply::Error`](crate::coordinator_to_cli::ControlRequestReply::Error) and no in-memory state is
112    /// mutated — degrading silently to in-memory-only would let the
113    /// CLI claim "nothing to clean" while historical rows are still
114    /// sitting on disk.
115    ///
116    /// For each cleaned dataflow the coordinator removes its persisted
117    /// record first and only then mutates in-memory state, so the reply
118    /// reflects what was actually persisted. The response is
119    /// [`ControlRequestReply::CleanResult`](crate::coordinator_to_cli::ControlRequestReply::CleanResult) carrying two separate
120    /// lists: `cleaned` for dataflows whose redb row (and every
121    /// `dora param` row owned by it — the persisted-store delete
122    /// cascades) is gone, and `failed` for dataflows whose
123    /// persisted-store delete errored. In-memory entries for failed
124    /// candidates are preserved so a later `dora clean` can retry;
125    /// they show up in `failed`, not `cleaned`, so the CLI can tell
126    /// "nothing eligible" apart from "all candidates failed to
127    /// clean". Logs and archived descriptors for successfully cleaned
128    /// dataflows are no longer available afterward. Cached build
129    /// results (`finished_builds`) are intentionally not touched —
130    /// clearing them would break concurrent `dora build` calls with
131    /// "unknown build id" errors.
132    Clean,
133    Info {
134        dataflow_uuid: Uuid,
135    },
136    DaemonConnected,
137    ConnectedMachines,
138    LogSubscribe {
139        dataflow_id: Uuid,
140        level: log::LevelFilter,
141    },
142    BuildLogSubscribe {
143        build_id: BuildId,
144        level: log::LevelFilter,
145    },
146    CliAndDefaultDaemonOnSameMachine,
147    GetNodeInfo,
148    /// Constructed through [`ControlRequest::topic_subscribe`], not by
149    /// literal: the variant is `#[non_exhaustive]` so that the *next* field
150    /// added here is a minor change rather than a 2.0 (see
151    /// [`RegisterResult::Ok`](crate::coordinator_to_daemon::RegisterResult::Ok)).
152    #[non_exhaustive]
153    TopicSubscribe {
154        dataflow_id: Uuid,
155        topics: Vec<(NodeId, DataId)>,
156        /// Binary-frame encoding the client speaks, see
157        /// [`TOPIC_DATA_PROTOCOL_VERSION`](crate::TOPIC_DATA_PROTOCOL_VERSION).
158        ///
159        /// `None` means the client predates the handshake and therefore speaks
160        /// the bincode encoding; the coordinator rejects it rather than let it
161        /// misparse postcard frames.
162        #[serde(default)]
163        protocol_version: Option<u16>,
164    },
165    TopicUnsubscribe {
166        subscription_id: Uuid,
167    },
168    GetTraces,
169    GetTraceSpans {
170        trace_id: String,
171    },
172    /// Restart a specific node without stopping the entire dataflow.
173    RestartNode {
174        dataflow_id: Uuid,
175        node_id: NodeId,
176        grace_duration: Option<Duration>,
177    },
178    /// Stop a specific node without stopping the entire dataflow.
179    StopNode {
180        dataflow_id: Uuid,
181        node_id: NodeId,
182        grace_duration: Option<Duration>,
183    },
184    /// Publish a message to a topic (for debugging/testing).
185    ///
186    /// The coordinator serializes the JSON data into Arrow format and
187    /// publishes it to Zenoh on the appropriate topic key.
188    TopicPublish {
189        dataflow_id: Uuid,
190        node_id: NodeId,
191        output_id: DataId,
192        /// JSON data to publish (will be converted to Arrow UInt8 array)
193        data_json: String,
194    },
195    /// List runtime parameters for a node.
196    GetParams {
197        dataflow_id: Uuid,
198        node_id: NodeId,
199    },
200    /// Get a single runtime parameter value.
201    GetParam {
202        dataflow_id: Uuid,
203        node_id: NodeId,
204        key: String,
205    },
206    /// Set a runtime parameter on a node.
207    SetParam {
208        dataflow_id: Uuid,
209        node_id: NodeId,
210        key: String,
211        value: serde_json::Value,
212    },
213    /// Delete a runtime parameter from a node.
214    DeleteParam {
215        dataflow_id: Uuid,
216        node_id: NodeId,
217        key: String,
218    },
219    // --- Dynamic Topology ---
220    /// Add a node to a running dataflow.
221    AddNode {
222        dataflow_id: Uuid,
223        node: crate::descriptor::Node,
224    },
225    /// Remove a node from a running dataflow.
226    RemoveNode {
227        dataflow_id: Uuid,
228        node_id: NodeId,
229        grace_duration: Option<std::time::Duration>,
230    },
231    /// Atomically replace a running node with a new definition under the
232    /// same id (dora-rs/dora#2927). The replacement must keep the node's
233    /// edges (same input mappings, outputs covering every mapped output);
234    /// a spawn failure leaves the current incarnation running.
235    ReplaceNode {
236        dataflow_id: Uuid,
237        node: crate::descriptor::Node,
238        grace_duration: Option<std::time::Duration>,
239    },
240    /// Add a mapping (connection) between two nodes in a running dataflow.
241    AddMapping {
242        dataflow_id: Uuid,
243        source_node: NodeId,
244        source_output: DataId,
245        target_node: NodeId,
246        target_input: DataId,
247    },
248    /// Remove a mapping (connection) between two nodes in a running dataflow.
249    RemoveMapping {
250        dataflow_id: Uuid,
251        source_node: NodeId,
252        source_output: DataId,
253        target_node: NodeId,
254        target_input: DataId,
255    },
256    /// Protocol version handshake. Sent by the CLI as its first request
257    /// after connecting so the coordinator can reject version-mismatched
258    /// clients before they exchange incompatible messages
259    /// (dora-rs/adora#151).
260    ///
261    /// The coordinator replies with either
262    /// [`ControlRequestReply::HelloOk`](crate::coordinator_to_cli::ControlRequestReply::HelloOk) carrying its own crate version,
263    /// or [`ControlRequestReply::Error`](crate::coordinator_to_cli::ControlRequestReply::Error) with a human-readable mismatch
264    /// message.
265    Hello {
266        dora_version: semver::Version,
267    },
268}
269
270impl ControlRequest {
271    /// Build a Hello request stamped with the current crate version of
272    /// `dora-message` (the wire-protocol version).
273    pub fn hello() -> Self {
274        Self::Hello {
275            dora_version: crate::current_crate_version(),
276        }
277    }
278
279    /// Subscribe to `topics` of a running dataflow, stamped with the
280    /// binary-frame encoding this crate speaks
281    /// ([`TOPIC_DATA_PROTOCOL_VERSION`](crate::TOPIC_DATA_PROTOCOL_VERSION)).
282    pub fn topic_subscribe(dataflow_id: Uuid, topics: Vec<(NodeId, DataId)>) -> Self {
283        Self::TopicSubscribe {
284            dataflow_id,
285            topics,
286            protocol_version: Some(crate::TOPIC_DATA_PROTOCOL_VERSION),
287        }
288    }
289}
290
291/// Check whether a CLI-reported dora version is compatible with this
292/// coordinator's crate version. Returns `Ok(())` on success or a
293/// human-readable error describing the mismatch.
294pub fn check_cli_version(cli_version: &semver::Version) -> Result<(), String> {
295    let crate_version = crate::current_crate_version();
296    if crate::versions_compatible(&crate_version, cli_version)? {
297        Ok(())
298    } else {
299        Err(format!(
300            "dora version mismatch: CLI v{cli_version} is not compatible \
301             with coordinator v{crate_version}. Upgrade the component that \
302             is behind (usually the CLI) so both sides share a semver-compatible \
303             version."
304        ))
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    // ---- dora-rs/adora#151: CLI ↔ coordinator protocol version handshake ----
313
314    #[test]
315    fn hello_stamps_current_crate_version() {
316        let req = ControlRequest::hello();
317        match req {
318            ControlRequest::Hello { dora_version } => {
319                assert_eq!(dora_version, crate::current_crate_version());
320            }
321            other => panic!("expected Hello, got {other:?}"),
322        }
323    }
324
325    #[test]
326    fn topic_subscribe_stamps_current_protocol_version() {
327        assert!(matches!(
328            ControlRequest::topic_subscribe(Uuid::nil(), vec![]),
329            ControlRequest::TopicSubscribe {
330                protocol_version: Some(crate::TOPIC_DATA_PROTOCOL_VERSION),
331                ..
332            }
333        ));
334    }
335
336    /// The wire property the `#[non_exhaustive]` on `TopicSubscribe` is there
337    /// to let us rely on: a request from a *newer* CLI carrying a field this
338    /// coordinator does not know still decodes, and one from an *older* CLI
339    /// missing a `#[serde(default)]` field decodes too. Together they are what
340    /// make appending such a field a minor change.
341    #[test]
342    fn topic_subscribe_tolerates_unknown_and_missing_fields() {
343        let newer = r#"{"TopicSubscribe":{"dataflow_id":"00000000-0000-0000-0000-000000000000","topics":[],"protocol_version":2,"mode":"metadata-only"}}"#;
344        let older = r#"{"TopicSubscribe":{"dataflow_id":"00000000-0000-0000-0000-000000000000","topics":[]}}"#;
345        for (label, json, expected_version) in [("newer", newer, Some(2)), ("older", older, None)] {
346            let req: ControlRequest = serde_json::from_str(json)
347                .unwrap_or_else(|e| panic!("{label} peer's request must decode: {e}"));
348            match req {
349                ControlRequest::TopicSubscribe {
350                    protocol_version, ..
351                } => assert_eq!(protocol_version, expected_version, "{label}"),
352                other => panic!("expected TopicSubscribe, got {other:?}"),
353            }
354        }
355    }
356
357    #[test]
358    fn check_cli_version_accepts_matching_version() {
359        let same = crate::current_crate_version();
360        assert!(check_cli_version(&same).is_ok());
361    }
362
363    #[test]
364    fn check_cli_version_rejects_incompatible_major_bump() {
365        // Semver allows same-major patch bumps but not major jumps.
366        let current = crate::current_crate_version();
367        let incompatible = semver::Version::new(current.major + 1, 0, 0);
368        let err = check_cli_version(&incompatible).expect_err("major bump should reject");
369        assert!(
370            err.contains("version mismatch"),
371            "error must mention mismatch: {err}"
372        );
373        assert!(err.contains("CLI v"), "error must include CLI version");
374    }
375
376    #[test]
377    fn check_cli_version_accepts_compatible_patch_bump() {
378        // A patch bump on the same major is always semver-compatible.
379        let current = crate::current_crate_version();
380        let patched = semver::Version::new(current.major, current.minor, current.patch + 1);
381        assert!(check_cli_version(&patched).is_ok());
382    }
383
384    #[test]
385    fn hello_roundtrips_through_json() {
386        // The handshake is sent as JSON over the WS control channel,
387        // so the enum variant must survive a roundtrip with preserved
388        // version fidelity.
389        let req = ControlRequest::hello();
390        let json = serde_json::to_string(&req).expect("serialize");
391        let decoded: ControlRequest = serde_json::from_str(&json).expect("deserialize");
392        match decoded {
393            ControlRequest::Hello { dora_version } => {
394                assert_eq!(dora_version, crate::current_crate_version());
395            }
396            other => panic!("expected Hello, got {other:?}"),
397        }
398    }
399}
400
401impl ControlRequest {
402    /// Encode a JSON control request, keeping fallback commands beside the
403    /// strict descriptor. Use this at the WebSocket boundary to preserve the
404    /// stable Rust enum and its ordinary serde representation.
405    pub fn to_wire_value(&self) -> Result<serde_json::Value, serde_json::Error> {
406        let mut value = serde_json::to_value(self)?;
407        let (kind, dataflow) = match self {
408            Self::Build { dataflow, .. } => ("Build", dataflow),
409            Self::Start { dataflow, .. } => ("Start", dataflow),
410            _ => return Ok(value),
411        };
412        let fallbacks = dataflow.path_fallbacks();
413        if !fallbacks.is_empty() {
414            let payload = value
415                .get_mut(kind)
416                .and_then(serde_json::Value::as_object_mut)
417                .ok_or_else(|| {
418                    <serde_json::Error as serde::ser::Error>::custom(
419                        "invalid control request shape",
420                    )
421                })?;
422            payload.insert("path_fallbacks".into(), serde_json::to_value(fallbacks)?);
423        }
424        Ok(value)
425    }
426
427    /// Decode a JSON control request and restore its optional fallback map.
428    /// Unknown node ids, malformed maps and conflicting values are request
429    /// errors; the coordinator's normal descriptor validation checks the names
430    /// and node kinds before building or starting anything.
431    pub fn from_wire_value(mut value: serde_json::Value) -> Result<Self, serde_json::Error> {
432        let metadata = value
433            .as_object_mut()
434            .and_then(|map| match map.iter_mut().next() {
435                Some((kind, payload)) if kind == "Build" || kind == "Start" => payload
436                    .as_object_mut()
437                    .and_then(|payload| payload.remove("path_fallbacks")),
438                _ => None,
439            });
440        let fallbacks: BTreeMap<NodeId, String> = match metadata {
441            Some(metadata) => serde_json::from_value(metadata)?,
442            None => BTreeMap::new(),
443        };
444        let mut request: Self = serde_json::from_value(value)?;
445        if let Self::Build { dataflow, .. } | Self::Start { dataflow, .. } = &mut request {
446            for (id, fallback) in fallbacks {
447                let node = dataflow
448                    .nodes
449                    .iter_mut()
450                    .find(|node| node.id == id)
451                    .ok_or_else(|| {
452                        <serde_json::Error as serde::de::Error>::custom(format!(
453                            "path fallback refers to unknown node `{id}`"
454                        ))
455                    })?;
456                if node
457                    .path_fallback
458                    .as_ref()
459                    .is_some_and(|existing| existing != &fallback)
460                {
461                    return Err(<serde_json::Error as serde::de::Error>::custom(format!(
462                        "conflicting path fallbacks for node `{id}`"
463                    )));
464                }
465                node.path_fallback = Some(fallback);
466            }
467        }
468        Ok(request)
469    }
470}
471
472#[cfg(test)]
473mod path_fallback_tests {
474    use super::*;
475    use crate::descriptor::{EnvValue, Node};
476
477    fn requests() -> [ControlRequest; 2] {
478        let mut node = Node::new("module.worker".parse().unwrap());
479        node.path = Some("modules/worker".into());
480        node.path_fallback = Some("worker".into());
481        let dataflow = Descriptor::new(vec![node]);
482        [
483            ControlRequest::Build {
484                session_id: SessionId::generate(),
485                dataflow: dataflow.clone(),
486                git_sources: BTreeMap::new(),
487                prev_git_sources: BTreeMap::new(),
488                local_working_dir: None,
489                uv: false,
490            },
491            ControlRequest::Start {
492                build_id: None,
493                session_id: SessionId::generate(),
494                dataflow,
495                name: None,
496                local_working_dir: None,
497                uv: false,
498                write_events_to: None,
499            },
500        ]
501    }
502
503    #[test]
504    fn module_fallback_is_outside_the_control_request_descriptor() {
505        for request in requests() {
506            let value = request.to_wire_value().unwrap();
507            let payload = value.as_object().unwrap().values().next().unwrap();
508            let dataflow = match &request {
509                ControlRequest::Build { dataflow, .. } | ControlRequest::Start { dataflow, .. } => {
510                    dataflow
511                }
512                _ => unreachable!(),
513            };
514            let mut legacy = dataflow.clone();
515            legacy.nodes[0].path_fallback = None;
516            assert_eq!(payload["dataflow"], serde_json::to_value(&legacy).unwrap());
517            assert_eq!(payload["path_fallbacks"]["module.worker"], "worker");
518            let decoded: ControlRequest = ControlRequest::from_wire_value(value.clone()).unwrap();
519            let restored = match decoded {
520                ControlRequest::Build { dataflow, .. } | ControlRequest::Start { dataflow, .. } => {
521                    dataflow
522                }
523                _ => unreachable!(),
524            };
525            assert_eq!(
526                serde_json::to_value(&restored).unwrap(),
527                serde_json::to_value(dataflow).unwrap()
528            );
529            let mut old_request = value;
530            old_request
531                .as_object_mut()
532                .unwrap()
533                .values_mut()
534                .next()
535                .unwrap()
536                .as_object_mut()
537                .unwrap()
538                .remove("path_fallbacks");
539            let old_request: ControlRequest = ControlRequest::from_wire_value(old_request).unwrap();
540            let old_request = serde_json::to_value(old_request).unwrap();
541            assert!(
542                old_request
543                    .as_object()
544                    .unwrap()
545                    .values()
546                    .next()
547                    .unwrap()
548                    .get("path_fallbacks")
549                    .is_none()
550            );
551        }
552    }
553
554    #[test]
555    fn requests_without_fallback_keep_the_existing_json_shape() {
556        for mut request in requests().into_iter().chain([ControlRequest::List]) {
557            if let ControlRequest::Build { dataflow, .. } | ControlRequest::Start { dataflow, .. } =
558                &mut request
559            {
560                dataflow.nodes[0].path_fallback = None;
561            }
562            let old = serde_json::to_value(&request).unwrap();
563            assert_eq!(request.to_wire_value().unwrap(), old);
564            let restored = ControlRequest::from_wire_value(old.clone()).unwrap();
565            assert_eq!(serde_json::to_value(restored).unwrap(), old);
566        }
567    }
568
569    /// An `env:` value whose CLI-side expansion contains `$` reaches the
570    /// coordinator as the CLI expanded it, and still does after the
571    /// coordinator forwards it, instead of being expanded again against the
572    /// coordinator's environment (#3947). The variable is unset, so a second
573    /// expansion would fail the decode.
574    #[test]
575    fn expanded_env_values_cross_the_wire_verbatim() {
576        let expanded = EnvValue::String("${DORA_TEST_WIRE_SURELY_UNSET}/p$ss".into());
577        for mut request in requests() {
578            if let ControlRequest::Build { dataflow, .. } | ControlRequest::Start { dataflow, .. } =
579                &mut request
580            {
581                dataflow.env = Some(BTreeMap::from([("X".into(), expanded.clone())]));
582                dataflow.nodes[0].env = Some(BTreeMap::from([("Y".into(), expanded.clone())]));
583            }
584            let wire = serde_json::to_vec(&request.to_wire_value().unwrap()).unwrap();
585            let decoded =
586                ControlRequest::from_wire_value(serde_json::from_slice(&wire).unwrap()).unwrap();
587            let (ControlRequest::Build { dataflow, .. } | ControlRequest::Start { dataflow, .. }) =
588                decoded
589            else {
590                unreachable!()
591            };
592            // The coordinator -> daemon hop encodes the descriptor again.
593            let forwarded: Descriptor =
594                serde_json::from_str(&serde_json::to_string(&dataflow).unwrap()).unwrap();
595            for d in [&dataflow, &forwarded] {
596                assert_eq!(d.env.as_ref().unwrap()["X"], expanded);
597                assert_eq!(d.nodes[0].env.as_ref().unwrap()["Y"], expanded);
598            }
599        }
600    }
601
602    #[test]
603    fn malformed_path_fallback_metadata_is_a_decode_error() {
604        for request in requests() {
605            let original = request.to_wire_value().unwrap();
606            for metadata in [
607                serde_json::json!({"missing":"worker"}),
608                serde_json::json!({"module.worker":42}),
609                serde_json::Value::Null,
610            ] {
611                let mut value = original.clone();
612                value.as_object_mut().unwrap().values_mut().next().unwrap()["path_fallbacks"] =
613                    metadata;
614                assert!(ControlRequest::from_wire_value(value).is_err());
615            }
616            let mut conflicting = original;
617            conflicting
618                .as_object_mut()
619                .unwrap()
620                .values_mut()
621                .next()
622                .unwrap()["dataflow"]["nodes"][0]["path_fallback"] = "other".into();
623            assert!(ControlRequest::from_wire_value(conflicting).is_err());
624        }
625    }
626}