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
233pub fn merge_writes(acc: &mut Vec<(Selector, Value)>, new: impl IntoIterator<Item = (Selector, Value)>) {
240 for (selector, value) in new {
241 if let Some(pos) = acc.iter().position(|(s, _)| *s == selector) {
242 acc.remove(pos);
243 }
244 acc.push((selector, value));
245 }
246}
247
248#[derive(Debug)]
250pub struct SubgraphRequest {
251 pub index: usize,
253 pub pool: VariablePool,
256 pub resume: Option<FrameSnapshot>,
258}
259
260#[derive(Debug)]
265#[allow(clippy::large_enum_variant)]
266pub enum SubgraphResult {
267 Completed {
268 pool: VariablePool,
270 outputs: IndexMap<String, Value>,
272 writes: Vec<(Selector, Value)>,
275 usage: Usage,
276 broke: bool,
278 },
279 Failed {
280 error: NodeError,
281 usage: Usage,
282 },
283 Paused {
284 snapshot: FrameSnapshot,
285 reasons: Vec<PauseReason>,
286 },
287}
288
289pub trait Subgraph: Send + Sync + fmt::Debug {
291 fn run(&self, request: SubgraphRequest) -> BoxFuture<'_, SubgraphResult>;
292}
293
294pub trait Clock: Send + Sync + fmt::Debug {
296 fn now_ms(&self) -> u64;
298 fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()>;
300 fn supports_timers(&self) -> bool {
302 true
303 }
304}
305
306#[derive(Debug, Default, Clone, Copy)]
309pub struct NoTimerClock;
310
311impl Clock for NoTimerClock {
312 fn now_ms(&self) -> u64 {
313 system_now_ms()
314 }
315 fn sleep(&self, _duration: Duration) -> BoxFuture<'static, ()> {
316 Box::pin(futures::future::ready(()))
317 }
318 fn supports_timers(&self) -> bool {
319 false
320 }
321}
322
323#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
329fn system_now_ms() -> u64 {
330 std::time::SystemTime::now()
331 .duration_since(std::time::UNIX_EPOCH)
332 .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
333 .unwrap_or(0)
334}
335
336#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
337fn system_now_ms() -> u64 {
338 use std::sync::atomic::{AtomicU64, Ordering};
339 static COUNTER: AtomicU64 = AtomicU64::new(0);
340 COUNTER.fetch_add(1, Ordering::Relaxed)
341}
342
343#[cfg(feature = "tokio")]
345#[derive(Debug, Default, Clone, Copy)]
346pub struct TokioClock;
347
348#[cfg(feature = "tokio")]
349impl Clock for TokioClock {
350 fn now_ms(&self) -> u64 {
351 NoTimerClock.now_ms()
352 }
353 fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
358 if tokio::runtime::Handle::try_current().is_ok() {
359 Box::pin(tokio::time::sleep(duration))
360 } else {
361 Box::pin(futures::future::ready(()))
362 }
363 }
364
365 fn supports_timers(&self) -> bool {
367 tokio::runtime::Handle::try_current().is_ok()
368 }
369}
370
371pub fn default_clock() -> Arc<dyn Clock> {
373 #[cfg(feature = "tokio")]
374 {
375 Arc::new(TokioClock)
376 }
377 #[cfg(not(feature = "tokio"))]
378 {
379 Arc::new(NoTimerClock)
380 }
381}
382
383#[derive(Default, Clone)]
387pub struct Services {
388 map: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
389}
390
391impl fmt::Debug for Services {
392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393 write!(f, "Services({} entries)", self.map.len())
394 }
395}
396
397impl Services {
398 pub fn new() -> Self {
399 Self::default()
400 }
401
402 pub fn insert<T: Any + Send + Sync>(&mut self, service: T) -> &mut Self {
404 self.map.insert(TypeId::of::<T>(), Arc::new(service));
405 self
406 }
407
408 pub fn with<T: Any + Send + Sync>(mut self, service: T) -> Self {
410 self.insert(service);
411 self
412 }
413
414 pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
415 self.map.get(&TypeId::of::<T>()).and_then(|s| s.downcast_ref::<T>())
416 }
417}
418
419#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
435pub struct CaptureContent;
436
437pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;
439
440#[derive(Clone)]
442pub struct NodeContext {
443 pub node_id: Arc<str>,
444 pub exec_id: Arc<str>,
445 pub frame: FrameId,
446 pub attempt: u32,
448 pub pool: VariablePool,
450 pub services: Arc<Services>,
451 pub clock: Arc<dyn Clock>,
452 pub resume: Option<Resume>,
454 pub subgraph: Option<Arc<dyn Subgraph>>,
456 pub deadline_ms: Option<u64>,
459 sink: EventSink,
460 secret_values: Option<Arc<SecretSet>>,
462}
463
464impl fmt::Debug for NodeContext {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 f.debug_struct("NodeContext")
467 .field("node_id", &self.node_id)
468 .field("exec_id", &self.exec_id)
469 .field("frame", &self.frame)
470 .field("attempt", &self.attempt)
471 .finish_non_exhaustive()
472 }
473}
474
475impl NodeContext {
476 #[allow(clippy::too_many_arguments)]
478 pub fn new(
479 node_id: impl Into<Arc<str>>,
480 exec_id: impl Into<Arc<str>>,
481 frame: FrameId,
482 attempt: u32,
483 pool: VariablePool,
484 services: Arc<Services>,
485 clock: Arc<dyn Clock>,
486 sink: EventSink,
487 ) -> Self {
488 Self {
489 node_id: node_id.into(),
490 exec_id: exec_id.into(),
491 frame,
492 attempt,
493 pool,
494 services,
495 clock,
496 resume: None,
497 subgraph: None,
498 deadline_ms: None,
499 sink,
500 secret_values: None,
501 }
502 }
503
504 pub fn for_test(node_id: &str, pool: VariablePool) -> Self {
506 Self::new(
507 node_id,
508 format!("{node_id}-exec"),
509 Arc::from(""),
510 1,
511 pool,
512 Arc::new(Services::new()),
513 Arc::new(NoTimerClock),
514 Arc::new(|_| {}),
515 )
516 }
517
518 pub fn with_services(mut self, services: Arc<Services>) -> Self {
519 self.services = services;
520 self
521 }
522
523 pub fn with_sink(mut self, sink: EventSink) -> Self {
524 self.sink = sink;
525 self
526 }
527
528 pub fn with_resume(mut self, resume: Option<Resume>) -> Self {
529 self.resume = resume;
530 self
531 }
532
533 pub fn with_subgraph(mut self, subgraph: Option<Arc<dyn Subgraph>>) -> Self {
534 self.subgraph = subgraph;
535 self
536 }
537
538 pub fn with_deadline(mut self, deadline_ms: Option<u64>) -> Self {
539 self.deadline_ms = deadline_ms;
540 self
541 }
542
543 pub fn with_secret_values(mut self, secret_values: Arc<SecretSet>) -> Self {
545 self.secret_values = Some(secret_values);
546 self
547 }
548
549 pub fn observe_secret(&self, plaintext: &str) {
552 if let Some(secret_values) = &self.secret_values {
553 secret_values.observe_plaintext(plaintext);
554 }
555 }
556
557 pub fn remaining(&self) -> Option<Duration> {
561 self.deadline_ms.map(|deadline| Duration::from_millis(deadline.saturating_sub(self.clock.now_ms())))
562 }
563
564 pub fn service<T: Any + Send + Sync>(&self) -> Option<&T> {
566 self.services.get::<T>()
567 }
568
569 pub fn require_service<T: Any + Send + Sync>(&self, what: &str) -> Result<&T, NodeError> {
571 self.services.get::<T>().ok_or_else(|| NodeError::fatal("missing_service", format!("no {what} configured")))
572 }
573
574 pub fn get(&self, selector: &Selector) -> Option<Value> {
576 self.pool.get(selector)
577 }
578
579 pub fn chunk(&self, field: &str, chunk: impl Into<String>) {
584 self.chunk_shared(&Arc::from(field), chunk);
585 }
586
587 pub fn chunk_shared(&self, field: &Arc<str>, chunk: impl Into<String>) {
599 (self.sink)(Event::NodeChunk {
600 frame: self.frame.clone(),
601 node_id: Arc::clone(&self.node_id),
602 exec_id: Arc::clone(&self.exec_id),
603 field: Arc::clone(field),
604 chunk: chunk.into(),
605 });
606 }
607
608 pub fn progress(&self, name: &str, data: Value) {
610 (self.sink)(Event::NodeProgress {
611 frame: self.frame.clone(),
612 node_id: Arc::clone(&self.node_id),
613 exec_id: Arc::clone(&self.exec_id),
614 name: name.to_owned(),
615 data,
616 });
617 }
618
619 pub fn captures_content(&self) -> bool {
622 self.services.get::<CaptureContent>().is_some()
623 }
624
625 pub fn sink(&self) -> &EventSink {
627 &self.sink
628 }
629}
630
631pub type NodeFactory = Arc<dyn Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync>;
633
634pub type DescriptorFn = fn() -> crate::catalog::NodeDescriptor;
636
637#[derive(Clone)]
644enum DescriptorSlot {
645 Ready(Box<crate::catalog::NodeDescriptor>),
646 Lazy(Arc<LazyDescriptor>),
647}
648
649struct LazyDescriptor {
650 build: DescriptorFn,
651 built: OnceLock<crate::catalog::NodeDescriptor>,
652}
653
654#[derive(Clone, Default)]
656pub struct Registry {
657 factories: HashMap<String, NodeFactory>,
658 descriptors: HashMap<String, DescriptorSlot>,
659}
660
661impl fmt::Debug for Registry {
662 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 let mut kinds: Vec<&String> = self.factories.keys().collect();
664 kinds.sort();
665 f.debug_struct("Registry").field("kinds", &kinds).finish()
666 }
667}
668
669impl Registry {
670 pub fn new() -> Self {
672 Self::default()
673 }
674
675 pub fn with_builtins() -> Self {
677 let mut r = Self::new();
678 crate::nodes::register_builtins(&mut r);
679 r
680 }
681
682 pub fn register<F>(&mut self, kind: &str, factory: F) -> &mut Self
684 where
685 F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
686 {
687 self.factories.insert(kind.to_owned(), Arc::new(factory));
688 self
689 }
690
691 pub fn register_described<F>(&mut self, descriptor: crate::catalog::NodeDescriptor, factory: F) -> &mut Self
694 where
695 F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
696 {
697 let kind = descriptor.kind.clone();
698 self.factories.insert(kind.clone(), Arc::new(factory));
699 self.descriptors.insert(kind, DescriptorSlot::Ready(Box::new(descriptor)));
700 self
701 }
702
703 pub fn register_lazily_described<F>(&mut self, kind: &str, descriptor: DescriptorFn, factory: F) -> &mut Self
708 where
709 F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
710 {
711 self.factories.insert(kind.to_owned(), Arc::new(factory));
712 let slot = LazyDescriptor { build: descriptor, built: OnceLock::new() };
713 self.descriptors.insert(kind.to_owned(), DescriptorSlot::Lazy(Arc::new(slot)));
714 self
715 }
716
717 pub fn describe(&mut self, descriptor: crate::catalog::NodeDescriptor) -> &mut Self {
719 if self.factories.contains_key(&descriptor.kind) {
720 self.descriptors.insert(descriptor.kind.clone(), DescriptorSlot::Ready(Box::new(descriptor)));
721 }
722 self
723 }
724
725 pub fn descriptor(&self, kind: &str) -> Option<crate::catalog::NodeDescriptor> {
727 if !self.factories.contains_key(kind) {
728 return None;
729 }
730 let descriptor = match self.descriptors.get(kind) {
731 None => crate::catalog::NodeDescriptor::bare(kind),
732 Some(DescriptorSlot::Ready(descriptor)) => (**descriptor).clone(),
733 Some(DescriptorSlot::Lazy(slot)) => slot.built.get_or_init(slot.build).clone(),
734 };
735 Some(descriptor)
736 }
737
738 pub fn descriptor_ref(&self, kind: &str) -> Option<&crate::catalog::NodeDescriptor> {
742 match self.descriptors.get(kind)? {
743 DescriptorSlot::Ready(descriptor) => Some(descriptor),
744 DescriptorSlot::Lazy(slot) => Some(slot.built.get_or_init(slot.build)),
745 }
746 }
747
748 pub fn descriptors(&self) -> Vec<crate::catalog::NodeDescriptor> {
750 let mut kinds: Vec<&String> = self.factories.keys().collect();
751 kinds.sort();
752 kinds.into_iter().filter_map(|k| self.descriptor(k)).collect()
753 }
754
755 pub fn alias(&mut self, alias: &str, kind: &str) -> &mut Self {
757 if let Some(f) = self.factories.get(kind).cloned() {
758 self.factories.insert(alias.to_owned(), f);
759 }
760 self
761 }
762
763 pub fn contains(&self, kind: &str) -> bool {
764 self.factories.contains_key(kind)
765 }
766
767 pub fn kinds(&self) -> impl Iterator<Item = &str> {
768 self.factories.keys().map(String::as_str)
769 }
770
771 pub fn build(&self, doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
773 let factory = self.factories.get(&doc.kind).ok_or_else(|| {
774 let suggestion = crate::validate::suggest(&doc.kind, self.kinds());
775 ConfigError::new(
776 doc,
777 format!("unknown node type `{}`{}", doc.kind, crate::validate::did_you_mean(&suggestion)),
778 )
779 })?;
780 factory(doc)
781 }
782}
783
784pub fn parse_config<T: serde::de::DeserializeOwned>(doc: &NodeDoc) -> Result<T, ConfigError> {
786 crate::dsl::parse_config_at(&doc.config).map_err(|(path, e)| {
787 let error = ConfigError::new(doc, e.to_string());
788 if path == "." { error } else { error.at_field(path) }
789 })
790}