1use std::any::{Any, TypeId};
11use std::collections::HashMap;
12use std::fmt;
13use std::sync::{Arc, OnceLock};
14use std::time::Duration;
15
16use futures::future::BoxFuture;
17use indexmap::IndexMap;
18
19use crate::dsl::NodeDoc;
20use crate::event::{Event, FrameId, PauseReason, Usage};
21use crate::pool::{Selector, VariablePool};
22use crate::redact::SecretSet;
23use crate::snapshot::FrameSnapshot;
24use crate::value::Value;
25use crate::variables::{VarName, Variables};
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum NodeRole {
31 Root,
33 ScopeStart,
35 Executable,
37 Branch,
39 Response,
41 Container,
43}
44
45#[derive(Clone, Debug, PartialEq, thiserror::Error)]
47#[error("{kind}: {message}")]
48pub struct NodeError {
49 pub kind: String,
51 pub message: String,
52 pub retryable: bool,
54 pub retry_after_ms: Option<u64>,
58}
59
60impl NodeError {
61 pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
62 Self { kind: kind.into(), message: message.into(), retryable: true, retry_after_ms: None }
63 }
64
65 pub fn fatal(kind: impl Into<String>, message: impl Into<String>) -> Self {
67 Self { kind: kind.into(), message: message.into(), retryable: false, retry_after_ms: None }
68 }
69
70 pub fn with_retry_after(mut self, retry_after_ms: Option<u64>) -> Self {
72 self.retry_after_ms = retry_after_ms;
73 self
74 }
75
76 pub fn with_message(mut self, message: impl Into<String>) -> Self {
78 self.message = message.into();
79 self
80 }
81
82 pub fn invalid_input(message: impl Into<String>) -> Self {
83 Self::fatal("invalid_input", message)
84 }
85
86 pub fn timeout(after: Duration) -> Self {
87 Self::new("timeout", format!("node timed out after {} ms", after.as_millis()))
88 }
89}
90
91#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
93#[error("node `{node_id}` ({kind}): {}{message}", field_prefix(.field))]
94pub struct ConfigError {
95 pub node_id: String,
96 pub kind: String,
97 pub message: String,
98 pub field: Option<String>,
101}
102
103fn field_prefix(field: &Option<String>) -> String {
104 field.as_ref().map(|f| format!("{f}: ")).unwrap_or_default()
105}
106
107impl ConfigError {
108 pub fn new(doc: &NodeDoc, message: impl Into<String>) -> Self {
109 Self { node_id: doc.id.clone(), kind: doc.kind.clone(), message: message.into(), field: None }
110 }
111
112 #[must_use]
114 pub fn at_field(mut self, field: impl Into<String>) -> Self {
115 self.field = Some(field.into());
116 self
117 }
118}
119
120#[derive(Clone, Debug, Default, PartialEq)]
122pub struct NodeOutput {
123 pub outputs: Variables,
127 pub branch: Option<String>,
129 pub writes: Vec<(Selector, Value)>,
131 pub usage: Option<Usage>,
132 pub metadata: IndexMap<String, Value>,
134}
135
136impl NodeOutput {
137 pub fn new() -> Self {
138 Self::default()
139 }
140
141 pub fn with(mut self, key: impl Into<VarName>, value: impl Into<Value>) -> Self {
143 self.outputs.insert(key.into(), value.into());
144 self
145 }
146
147 pub fn branch(mut self, handle: impl Into<String>) -> Self {
148 self.branch = Some(handle.into());
149 self
150 }
151
152 pub fn write(mut self, selector: Selector, value: Value) -> Self {
153 self.writes.push((selector, value));
154 self
155 }
156
157 pub fn usage(mut self, usage: Usage) -> Self {
158 self.usage = Some(usage);
159 self
160 }
161
162 pub fn meta(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
163 self.metadata.insert(key.into(), value.into());
164 self
165 }
166}
167
168#[derive(Clone, Debug, PartialEq)]
170pub struct PauseRequest {
171 pub kind: String,
173 pub data: Value,
175 pub state: serde_json::Value,
177}
178
179#[derive(Clone, Debug, PartialEq)]
181pub enum NodeOutcome {
182 Completed(NodeOutput),
183 Paused(PauseRequest),
184}
185
186impl From<NodeOutput> for NodeOutcome {
187 fn from(o: NodeOutput) -> Self {
188 NodeOutcome::Completed(o)
189 }
190}
191
192#[derive(Clone, Debug, PartialEq)]
194pub struct Resume {
195 pub state: serde_json::Value,
197 pub input: Option<Value>,
199}
200
201pub type NodeResult = Result<NodeOutcome, NodeError>;
203
204pub trait Node: Send + Sync + fmt::Debug {
206 fn role(&self) -> NodeRole {
208 NodeRole::Executable
209 }
210
211 fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult>;
213
214 fn inputs(&self) -> Vec<Selector> {
220 Vec::new()
221 }
222
223 fn branch_handles(&self) -> Option<Vec<String>> {
229 None
230 }
231
232 fn tracks_turns(&self) -> bool {
239 false
240 }
241}
242
243pub fn merge_writes(acc: &mut Vec<(Selector, Value)>, new: impl IntoIterator<Item = (Selector, Value)>) {
250 for (selector, value) in new {
251 if let Some(pos) = acc.iter().position(|(s, _)| *s == selector) {
252 acc.remove(pos);
253 }
254 acc.push((selector, value));
255 }
256}
257
258#[derive(Debug)]
260pub struct SubgraphRequest {
261 pub index: usize,
263 pub pool: VariablePool,
266 pub resume: Option<FrameSnapshot>,
268}
269
270#[derive(Debug)]
275#[allow(clippy::large_enum_variant)]
276pub enum SubgraphResult {
277 Completed {
278 pool: VariablePool,
280 outputs: IndexMap<String, Value>,
282 writes: Vec<(Selector, Value)>,
285 usage: Usage,
286 broke: bool,
288 },
289 Failed {
290 error: NodeError,
291 usage: Usage,
292 },
293 Paused {
294 snapshot: FrameSnapshot,
295 reasons: Vec<PauseReason>,
296 },
297}
298
299pub trait Subgraph: Send + Sync + fmt::Debug {
301 fn run(&self, request: SubgraphRequest) -> BoxFuture<'_, SubgraphResult>;
302}
303
304#[cfg(feature = "subagents")]
308pub const CHILD_PAUSE: &str = "child_runs";
309
310#[cfg(feature = "subagents")]
314#[derive(Debug, Clone)]
315pub struct ChildRequest {
316 pub(crate) workflow: String,
317 pub(crate) index: usize,
318 pub(crate) inputs: IndexMap<String, Value>,
320 pub(crate) sys: IndexMap<String, Value>,
322 pub(crate) resume: Option<FrameSnapshot>,
324}
325
326#[cfg(feature = "subagents")]
327impl ChildRequest {
328 pub fn start(workflow: impl Into<String>, index: usize, inputs: IndexMap<String, Value>) -> Self {
330 Self { workflow: workflow.into(), index, inputs, sys: IndexMap::new(), resume: None }
331 }
332
333 pub fn with_sys(mut self, sys: IndexMap<String, Value>) -> Self {
335 self.sys = sys;
336 self
337 }
338
339 pub fn resume(workflow: impl Into<String>, index: usize, snapshot: FrameSnapshot) -> Self {
342 Self { workflow: workflow.into(), index, inputs: IndexMap::new(), sys: IndexMap::new(), resume: Some(snapshot) }
343 }
344}
345
346#[cfg(feature = "subagents")]
347pub(crate) mod sealed {
348 pub trait Sealed {}
350}
351
352#[cfg(feature = "subagents")]
360pub trait ChildRuns: sealed::Sealed + Send + Sync + fmt::Debug {
361 fn workflows(&self) -> Vec<String>;
363 fn inputs_schema(&self, workflow: &str) -> Result<serde_json::Value, NodeError>;
368 fn run(&self, request: ChildRequest) -> BoxFuture<'_, SubgraphResult>;
370 fn max_concurrency(&self) -> usize;
372 fn run_stopped(&self) -> bool;
375}
376
377pub trait Clock: Send + Sync + fmt::Debug {
379 fn now_ms(&self) -> u64;
381 fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()>;
383 fn supports_timers(&self) -> bool {
385 true
386 }
387}
388
389#[derive(Debug, Default, Clone, Copy)]
392pub struct NoTimerClock;
393
394impl Clock for NoTimerClock {
395 fn now_ms(&self) -> u64 {
396 system_now_ms()
397 }
398 fn sleep(&self, _duration: Duration) -> BoxFuture<'static, ()> {
399 Box::pin(futures::future::ready(()))
400 }
401 fn supports_timers(&self) -> bool {
402 false
403 }
404}
405
406#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
412fn system_now_ms() -> u64 {
413 std::time::SystemTime::now()
414 .duration_since(std::time::UNIX_EPOCH)
415 .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
416 .unwrap_or(0)
417}
418
419#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
420fn system_now_ms() -> u64 {
421 use std::sync::atomic::{AtomicU64, Ordering};
422 static COUNTER: AtomicU64 = AtomicU64::new(0);
423 COUNTER.fetch_add(1, Ordering::Relaxed)
424}
425
426#[cfg(feature = "tokio")]
428#[derive(Debug, Default, Clone, Copy)]
429pub struct TokioClock;
430
431#[cfg(feature = "tokio")]
432impl Clock for TokioClock {
433 fn now_ms(&self) -> u64 {
434 NoTimerClock.now_ms()
435 }
436 fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
441 if tokio::runtime::Handle::try_current().is_ok() {
442 Box::pin(tokio::time::sleep(duration))
443 } else {
444 Box::pin(futures::future::ready(()))
445 }
446 }
447
448 fn supports_timers(&self) -> bool {
450 tokio::runtime::Handle::try_current().is_ok()
451 }
452}
453
454pub fn default_clock() -> Arc<dyn Clock> {
456 #[cfg(feature = "tokio")]
457 {
458 Arc::new(TokioClock)
459 }
460 #[cfg(not(feature = "tokio"))]
461 {
462 Arc::new(NoTimerClock)
463 }
464}
465
466#[derive(Default, Clone)]
470pub struct Services {
471 map: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
472}
473
474impl fmt::Debug for Services {
475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476 write!(f, "Services({} entries)", self.map.len())
477 }
478}
479
480impl Services {
481 pub fn new() -> Self {
482 Self::default()
483 }
484
485 pub fn insert<T: Any + Send + Sync>(&mut self, service: T) -> &mut Self {
487 self.map.insert(TypeId::of::<T>(), Arc::new(service));
488 self
489 }
490
491 pub fn with<T: Any + Send + Sync>(mut self, service: T) -> Self {
493 self.insert(service);
494 self
495 }
496
497 pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
498 self.map.get(&TypeId::of::<T>()).and_then(|s| s.downcast_ref::<T>())
499 }
500}
501
502#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
518pub struct CaptureContent;
519
520pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;
522
523#[derive(Clone)]
525pub struct NodeContext {
526 pub node_id: Arc<str>,
527 pub exec_id: Arc<str>,
528 pub frame: FrameId,
529 pub attempt: u32,
531 pub pool: VariablePool,
533 pub services: Arc<Services>,
534 pub clock: Arc<dyn Clock>,
535 pub resume: Option<Resume>,
537 pub subgraph: Option<Arc<dyn Subgraph>>,
539 #[cfg(feature = "subagents")]
541 pub children: Option<Arc<dyn ChildRuns>>,
542 pub deadline_ms: Option<u64>,
545 sink: EventSink,
546 secret_values: Option<Arc<SecretSet>>,
548 budget: Option<Arc<crate::budget::RunBudget>>,
550 progress: Option<Arc<crate::budget::NodeProgress>>,
552}
553
554impl fmt::Debug for NodeContext {
555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
556 f.debug_struct("NodeContext")
557 .field("node_id", &self.node_id)
558 .field("exec_id", &self.exec_id)
559 .field("frame", &self.frame)
560 .field("attempt", &self.attempt)
561 .finish_non_exhaustive()
562 }
563}
564
565impl NodeContext {
566 pub fn idempotency_key(&self) -> String {
580 match self.pool.get(&Selector::of(crate::pool::SYS, "run_id")) {
581 Some(Value::String(run_id)) if !run_id.is_empty() => format!("{run_id}:{}", self.exec_id),
582 _ => self.exec_id.to_string(),
583 }
584 }
585
586 #[allow(clippy::too_many_arguments)]
588 pub fn new(
589 node_id: impl Into<Arc<str>>,
590 exec_id: impl Into<Arc<str>>,
591 frame: FrameId,
592 attempt: u32,
593 pool: VariablePool,
594 services: Arc<Services>,
595 clock: Arc<dyn Clock>,
596 sink: EventSink,
597 ) -> Self {
598 Self {
599 node_id: node_id.into(),
600 exec_id: exec_id.into(),
601 frame,
602 attempt,
603 pool,
604 services,
605 clock,
606 resume: None,
607 subgraph: None,
608 #[cfg(feature = "subagents")]
609 children: None,
610 deadline_ms: None,
611 sink,
612 secret_values: None,
613 budget: None,
614 progress: None,
615 }
616 }
617
618 pub fn with_budget(
621 mut self,
622 budget: Arc<crate::budget::RunBudget>,
623 progress: Option<Arc<crate::budget::NodeProgress>>,
624 ) -> Self {
625 self.budget = Some(budget);
626 self.progress = progress;
627 self
628 }
629
630 pub fn budget(&self) -> Option<&crate::budget::RunBudget> {
632 self.budget.as_deref()
633 }
634
635 pub fn charge(&self, usage: &crate::event::Usage, cost_micros: u64) -> Result<(), NodeError> {
642 if let Some(progress) = &self.progress {
644 progress.add_charged(usage);
645 }
646 match &self.budget {
647 Some(budget) => budget.charge(usage, cost_micros),
648 None => Ok(()),
649 }
650 }
651
652 pub fn check_budget(&self) -> Result<(), NodeError> {
656 match &self.budget {
657 Some(budget) => budget.stop_if_spent(),
658 None => Ok(()),
659 }
660 }
661
662 pub fn charge_final(&self, usage: &crate::event::Usage, cost_micros: u64) {
665 if let Some(progress) = &self.progress {
666 progress.add_charged(usage);
667 }
668 if let Some(budget) = &self.budget {
669 budget.record(usage, cost_micros);
670 }
671 }
672
673 pub fn checkpoint(&self, state: serde_json::Value) {
678 if let Some(progress) = &self.progress {
679 progress.set(state);
680 }
681 }
682
683 pub fn keeps_checkpoints(&self) -> bool {
685 self.progress.is_some()
686 }
687
688 pub fn checkpointed(&self) -> Option<serde_json::Value> {
690 self.progress.as_ref().and_then(|progress| progress.get())
691 }
692
693 pub fn for_test(node_id: &str, pool: VariablePool) -> Self {
695 Self::new(
696 node_id,
697 format!("{node_id}-exec"),
698 Arc::from(""),
699 1,
700 pool,
701 Arc::new(Services::new()),
702 Arc::new(NoTimerClock),
703 Arc::new(|_| {}),
704 )
705 }
706
707 pub fn with_services(mut self, services: Arc<Services>) -> Self {
708 self.services = services;
709 self
710 }
711
712 pub fn with_sink(mut self, sink: EventSink) -> Self {
713 self.sink = sink;
714 self
715 }
716
717 pub fn with_resume(mut self, resume: Option<Resume>) -> Self {
718 self.resume = resume;
719 self
720 }
721
722 pub fn with_subgraph(mut self, subgraph: Option<Arc<dyn Subgraph>>) -> Self {
723 self.subgraph = subgraph;
724 self
725 }
726
727 #[cfg(feature = "subagents")]
729 pub fn with_children(mut self, children: Option<Arc<dyn ChildRuns>>) -> Self {
730 self.children = children;
731 self
732 }
733
734 pub fn with_deadline(mut self, deadline_ms: Option<u64>) -> Self {
735 self.deadline_ms = deadline_ms;
736 self
737 }
738
739 pub fn with_secret_values(mut self, secret_values: Arc<SecretSet>) -> Self {
741 self.secret_values = Some(secret_values);
742 self
743 }
744
745 pub fn observe_secret(&self, plaintext: &str) {
748 if let Some(secret_values) = &self.secret_values {
749 secret_values.observe_plaintext(plaintext);
750 }
751 }
752
753 pub fn secret_values(&self) -> Option<Arc<SecretSet>> {
758 self.secret_values.clone()
759 }
760
761 pub fn remaining(&self) -> Option<Duration> {
765 self.deadline_ms.map(|deadline| Duration::from_millis(deadline.saturating_sub(self.clock.now_ms())))
766 }
767
768 pub fn service<T: Any + Send + Sync>(&self) -> Option<&T> {
770 self.services.get::<T>()
771 }
772
773 pub fn require_service<T: Any + Send + Sync>(&self, what: &str) -> Result<&T, NodeError> {
775 self.services.get::<T>().ok_or_else(|| NodeError::fatal("missing_service", format!("no {what} configured")))
776 }
777
778 pub fn get(&self, selector: &Selector) -> Option<Value> {
780 self.pool.get(selector)
781 }
782
783 pub fn chunk(&self, field: &str, chunk: impl Into<String>) {
788 self.chunk_shared(&Arc::from(field), chunk);
789 }
790
791 pub fn chunk_shared(&self, field: &Arc<str>, chunk: impl Into<String>) {
803 (self.sink)(Event::NodeChunk {
804 frame: self.frame.clone(),
805 node_id: Arc::clone(&self.node_id),
806 exec_id: Arc::clone(&self.exec_id),
807 field: Arc::clone(field),
808 chunk: chunk.into(),
809 });
810 }
811
812 pub fn progress(&self, name: &str, data: Value) {
814 (self.sink)(Event::NodeProgress {
815 frame: self.frame.clone(),
816 node_id: Arc::clone(&self.node_id),
817 exec_id: Arc::clone(&self.exec_id),
818 name: name.to_owned(),
819 data,
820 });
821 }
822
823 pub fn captures_content(&self) -> bool {
826 self.services.get::<CaptureContent>().is_some()
827 }
828
829 pub fn sink(&self) -> &EventSink {
831 &self.sink
832 }
833}
834
835pub type NodeFactory = Arc<dyn Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync>;
837
838pub type DescriptorFn = fn() -> crate::catalog::NodeDescriptor;
840
841#[derive(Clone)]
848enum DescriptorSlot {
849 Ready(Box<crate::catalog::NodeDescriptor>),
850 Lazy(Arc<LazyDescriptor>),
851}
852
853struct LazyDescriptor {
854 build: DescriptorFn,
855 built: OnceLock<crate::catalog::NodeDescriptor>,
856}
857
858#[derive(Clone, Default)]
860pub struct Registry {
861 factories: HashMap<String, NodeFactory>,
862 descriptors: HashMap<String, DescriptorSlot>,
863}
864
865impl fmt::Debug for Registry {
866 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
867 let mut kinds: Vec<&String> = self.factories.keys().collect();
868 kinds.sort_unstable();
869 f.debug_struct("Registry").field("kinds", &kinds).finish()
870 }
871}
872
873impl Registry {
874 pub fn new() -> Self {
876 Self::default()
877 }
878
879 pub fn with_builtins() -> Self {
881 let mut r = Self::new();
882 crate::nodes::register_builtins(&mut r);
883 r
884 }
885
886 pub fn register<F>(&mut self, kind: &str, factory: F) -> &mut Self
888 where
889 F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
890 {
891 self.factories.insert(kind.to_owned(), Arc::new(factory));
892 self
893 }
894
895 pub fn register_described<F>(&mut self, descriptor: crate::catalog::NodeDescriptor, factory: F) -> &mut Self
898 where
899 F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
900 {
901 let kind = descriptor.kind.clone();
902 self.factories.insert(kind.clone(), Arc::new(factory));
903 self.descriptors.insert(kind, DescriptorSlot::Ready(Box::new(descriptor)));
904 self
905 }
906
907 pub fn register_lazily_described<F>(&mut self, kind: &str, descriptor: DescriptorFn, factory: F) -> &mut Self
912 where
913 F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
914 {
915 self.factories.insert(kind.to_owned(), Arc::new(factory));
916 let slot = LazyDescriptor { build: descriptor, built: OnceLock::new() };
917 self.descriptors.insert(kind.to_owned(), DescriptorSlot::Lazy(Arc::new(slot)));
918 self
919 }
920
921 pub fn describe(&mut self, descriptor: crate::catalog::NodeDescriptor) -> &mut Self {
923 if self.factories.contains_key(&descriptor.kind) {
924 self.descriptors.insert(descriptor.kind.clone(), DescriptorSlot::Ready(Box::new(descriptor)));
925 }
926 self
927 }
928
929 pub fn descriptor(&self, kind: &str) -> Option<crate::catalog::NodeDescriptor> {
931 if !self.factories.contains_key(kind) {
932 return None;
933 }
934 let descriptor = match self.descriptors.get(kind) {
935 None => crate::catalog::NodeDescriptor::bare(kind),
936 Some(DescriptorSlot::Ready(descriptor)) => (**descriptor).clone(),
937 Some(DescriptorSlot::Lazy(slot)) => slot.built.get_or_init(slot.build).clone(),
938 };
939 Some(descriptor)
940 }
941
942 pub fn descriptor_ref(&self, kind: &str) -> Option<&crate::catalog::NodeDescriptor> {
946 match self.descriptors.get(kind)? {
947 DescriptorSlot::Ready(descriptor) => Some(descriptor),
948 DescriptorSlot::Lazy(slot) => Some(slot.built.get_or_init(slot.build)),
949 }
950 }
951
952 pub fn descriptors(&self) -> Vec<crate::catalog::NodeDescriptor> {
954 let mut kinds: Vec<&String> = self.factories.keys().collect();
955 kinds.sort_unstable();
956 kinds.into_iter().filter_map(|k| self.descriptor(k)).collect()
957 }
958
959 pub fn alias(&mut self, alias: &str, kind: &str) -> &mut Self {
961 if let Some(f) = self.factories.get(kind).cloned() {
962 self.factories.insert(alias.to_owned(), f);
963 }
964 self
965 }
966
967 pub fn contains(&self, kind: &str) -> bool {
968 self.factories.contains_key(kind)
969 }
970
971 pub fn kinds(&self) -> impl Iterator<Item = &str> {
972 self.factories.keys().map(String::as_str)
973 }
974
975 pub fn build(&self, doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
977 let factory = self.factories.get(&doc.kind).ok_or_else(|| {
978 let suggestion = crate::validate::suggest(&doc.kind, self.kinds());
979 ConfigError::new(
980 doc,
981 format!("unknown node type `{}`{}", doc.kind, crate::validate::did_you_mean(&suggestion)),
982 )
983 })?;
984 factory(doc)
985 }
986}
987
988pub fn parse_config<T: serde::de::DeserializeOwned>(doc: &NodeDoc) -> Result<T, ConfigError> {
990 crate::dsl::parse_config_at(&doc.config).map_err(|(path, e)| {
991 let error = ConfigError::new(doc, e.to_string());
992 if path == "." { error } else { error.at_field(path) }
993 })
994}
995
996#[cfg(test)]
997mod tests {
998 use super::*;
999
1000 #[test]
1001 fn idempotency_keys_name_the_run_and_the_node_execution() {
1002 let mut pool = VariablePool::new();
1003 pool.insert(crate::pool::SYS, "run_id", Value::from("run-7"));
1004 assert_eq!(NodeContext::for_test("h", pool).idempotency_key(), "run-7:h-exec");
1005 let mut pool = VariablePool::new();
1007 pool.insert(crate::pool::SYS, "run_id", Value::from("run-7"));
1008 let mut retry = NodeContext::for_test("h", pool);
1009 retry.attempt = 3;
1010 assert_eq!(retry.idempotency_key(), "run-7:h-exec");
1011 assert_eq!(NodeContext::for_test("h", VariablePool::new()).idempotency_key(), "h-exec");
1013 }
1014}