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 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 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 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 #[non_exhaustive]
153 TopicSubscribe {
154 dataflow_id: Uuid,
155 topics: Vec<(NodeId, DataId)>,
156 #[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 RestartNode {
174 dataflow_id: Uuid,
175 node_id: NodeId,
176 grace_duration: Option<Duration>,
177 },
178 StopNode {
180 dataflow_id: Uuid,
181 node_id: NodeId,
182 grace_duration: Option<Duration>,
183 },
184 TopicPublish {
189 dataflow_id: Uuid,
190 node_id: NodeId,
191 output_id: DataId,
192 data_json: String,
194 },
195 GetParams {
197 dataflow_id: Uuid,
198 node_id: NodeId,
199 },
200 GetParam {
202 dataflow_id: Uuid,
203 node_id: NodeId,
204 key: String,
205 },
206 SetParam {
208 dataflow_id: Uuid,
209 node_id: NodeId,
210 key: String,
211 value: serde_json::Value,
212 },
213 DeleteParam {
215 dataflow_id: Uuid,
216 node_id: NodeId,
217 key: String,
218 },
219 AddNode {
222 dataflow_id: Uuid,
223 node: crate::descriptor::Node,
224 },
225 RemoveNode {
227 dataflow_id: Uuid,
228 node_id: NodeId,
229 grace_duration: Option<std::time::Duration>,
230 },
231 ReplaceNode {
236 dataflow_id: Uuid,
237 node: crate::descriptor::Node,
238 grace_duration: Option<std::time::Duration>,
239 },
240 AddMapping {
242 dataflow_id: Uuid,
243 source_node: NodeId,
244 source_output: DataId,
245 target_node: NodeId,
246 target_input: DataId,
247 },
248 RemoveMapping {
250 dataflow_id: Uuid,
251 source_node: NodeId,
252 source_output: DataId,
253 target_node: NodeId,
254 target_input: DataId,
255 },
256 Hello {
266 dora_version: semver::Version,
267 },
268}
269
270impl ControlRequest {
271 pub fn hello() -> Self {
274 Self::Hello {
275 dora_version: crate::current_crate_version(),
276 }
277 }
278
279 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
291pub 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 #[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 #[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 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 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 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 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 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 #[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 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}