1use std::{collections::HashMap, fmt, sync::Arc};
7
8use stateknot_core::{
9 BoxFuture, BudgetUsage, CancellationSignal, Checkpoint, ChildRunPolicyError, CompiledGraph,
10 Failure, GraphReducer, GraphReducerReference, GraphReference, NodeAttemptStartHead,
11 NodeControl, NodeId, NodeInvocationBindings, NodeStateChange, RetryAdvice,
12};
13use thiserror::Error;
14
15use crate::{GraphChildJoin, JsonSchemaRegistry};
16
17#[derive(Clone)]
24pub struct GraphNodeContext {
25 attempt: NodeAttemptStartHead,
26 checkpoint: Arc<Checkpoint>,
27 cancellation: CancellationSignal,
28 child_join: Option<Arc<GraphChildJoin>>,
29}
30
31impl GraphNodeContext {
32 pub fn new(
39 attempt: NodeAttemptStartHead,
40 checkpoint: Arc<Checkpoint>,
41 cancellation: CancellationSignal,
42 ) -> Result<Self, GraphNodeContextError> {
43 let activation = attempt.activation();
44 if activation.tenant_id() != checkpoint.tenant_id() {
45 return Err(GraphNodeContextError::TenantMismatch);
46 }
47 if activation.run_id() != checkpoint.run_id() {
48 return Err(GraphNodeContextError::RunMismatch);
49 }
50 if activation.base_checkpoint() != &checkpoint.head() {
51 return Err(GraphNodeContextError::CheckpointMismatch);
52 }
53 Ok(Self {
54 attempt,
55 checkpoint,
56 cancellation,
57 child_join: None,
58 })
59 }
60
61 #[must_use]
63 pub const fn attempt(&self) -> &NodeAttemptStartHead {
64 &self.attempt
65 }
66
67 #[must_use]
69 pub fn checkpoint(&self) -> &Checkpoint {
70 &self.checkpoint
71 }
72
73 #[must_use]
75 pub const fn cancellation(&self) -> &CancellationSignal {
76 &self.cancellation
77 }
78
79 #[must_use]
82 pub fn child_join(&self) -> Option<&GraphChildJoin> {
83 self.child_join.as_deref()
84 }
85
86 pub(crate) fn with_child_join(mut self, join: Arc<GraphChildJoin>) -> Self {
87 self.child_join = Some(join);
88 self
89 }
90}
91
92impl fmt::Debug for GraphNodeContext {
93 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94 formatter
95 .debug_struct("GraphNodeContext")
96 .field("attempt", &self.attempt)
97 .field("checkpoint", &self.checkpoint.head())
98 .field("cancellation", &self.cancellation)
99 .finish_non_exhaustive()
100 }
101}
102
103#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
105#[non_exhaustive]
106pub enum GraphNodeContextError {
107 #[error("node execution context crosses a tenant boundary")]
109 TenantMismatch,
110 #[error("node execution context crosses a run boundary")]
112 RunMismatch,
113 #[error("node execution attempt does not belong to the supplied checkpoint")]
115 CheckpointMismatch,
116}
117
118#[derive(Clone, Debug)]
124#[allow(clippy::large_enum_variant)]
127pub enum GraphNodeExecution {
128 Completed {
130 state_change: NodeStateChange,
132 control: NodeControl,
134 bindings: NodeInvocationBindings,
136 usage: BudgetUsage,
138 },
139 ChildJoin(Box<stateknot_core::ChildRunJoinRequest>),
142}
143
144impl GraphNodeExecution {
145 #[must_use]
147 pub const fn new(
148 state_change: NodeStateChange,
149 control: NodeControl,
150 bindings: NodeInvocationBindings,
151 usage: BudgetUsage,
152 ) -> Self {
153 Self::Completed {
154 state_change,
155 control,
156 bindings,
157 usage,
158 }
159 }
160
161 #[must_use]
164 pub fn child_join(request: stateknot_core::ChildRunJoinRequest) -> Self {
165 Self::ChildJoin(Box::new(request))
166 }
167}
168
169#[derive(Clone, Debug)]
177pub struct GraphNodeExecutionError {
178 failure: Failure,
179 usage: BudgetUsage,
180}
181
182impl GraphNodeExecutionError {
183 pub fn new(
190 failure: Failure,
191 usage: BudgetUsage,
192 ) -> Result<Self, GraphNodeExecutionErrorBuildError> {
193 if failure.caused_by_event_id().is_some() {
194 return Err(GraphNodeExecutionErrorBuildError::CausationAlreadyAttached);
195 }
196 if failure.retry_advice() == RetryAdvice::ReconcileFirst {
197 return Err(GraphNodeExecutionErrorBuildError::ReconciliationNotAllowed);
198 }
199 Ok(Self { failure, usage })
200 }
201
202 #[must_use]
204 pub const fn failure(&self) -> &Failure {
205 &self.failure
206 }
207
208 #[must_use]
210 pub const fn usage(&self) -> &BudgetUsage {
211 &self.usage
212 }
213
214 #[must_use]
216 pub fn into_parts(self) -> (Failure, BudgetUsage) {
217 (self.failure, self.usage)
218 }
219}
220
221#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
223#[non_exhaustive]
224pub enum GraphNodeExecutionErrorBuildError {
225 #[error("node failure already contains durable event causation")]
227 CausationAlreadyAttached,
228 #[error("node failure cannot request reconcile-first recovery")]
230 ReconciliationNotAllowed,
231}
232
233#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
239#[non_exhaustive]
240pub enum GraphNodeScheduling {
241 #[default]
243 Exclusive,
244 JournalIsolated,
252}
253
254pub trait GraphNodeExecutor: Send + Sync + 'static {
256 fn graph(&self) -> &GraphReference;
258
259 fn node_id(&self) -> &NodeId;
261
262 fn scheduling(&self) -> GraphNodeScheduling {
268 GraphNodeScheduling::Exclusive
269 }
270
271 fn supports_child_join(&self) -> bool {
274 false
275 }
276
277 fn execute(
279 &self,
280 context: GraphNodeContext,
281 ) -> BoxFuture<'_, Result<GraphNodeExecution, GraphNodeExecutionError>>;
282}
283
284#[derive(Clone)]
286pub struct ExecutableGraph {
287 graph: Arc<CompiledGraph>,
288 schemas: JsonSchemaRegistry,
289 reducer: Arc<dyn GraphReducer>,
290 nodes: Arc<HashMap<NodeId, Arc<dyn GraphNodeExecutor>>>,
291}
292
293impl ExecutableGraph {
294 #[must_use]
296 pub fn graph(&self) -> &CompiledGraph {
297 &self.graph
298 }
299
300 #[must_use]
302 pub const fn schemas(&self) -> &JsonSchemaRegistry {
303 &self.schemas
304 }
305
306 #[must_use]
308 pub fn reducer(&self) -> &(dyn GraphReducer + 'static) {
309 self.reducer.as_ref()
310 }
311
312 #[must_use]
314 pub fn node(&self, node_id: &NodeId) -> Option<&(dyn GraphNodeExecutor + 'static)> {
315 self.nodes.get(node_id).map(Arc::as_ref)
316 }
317
318 #[must_use]
320 pub fn node_executor(&self, node_id: &NodeId) -> Option<Arc<dyn GraphNodeExecutor>> {
321 self.nodes.get(node_id).cloned()
322 }
323
324 #[must_use]
326 pub fn node_count(&self) -> usize {
327 self.nodes.len()
328 }
329}
330
331impl fmt::Debug for ExecutableGraph {
332 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
333 formatter
334 .debug_struct("ExecutableGraph")
335 .field("graph", &self.graph.reference())
336 .field("reducer", self.reducer.reference())
337 .field("nodes", &self.nodes.len())
338 .finish_non_exhaustive()
339 }
340}
341
342pub struct ExecutableGraphRegistryBuilder {
344 schemas: JsonSchemaRegistry,
345 graphs: HashMap<GraphReference, Arc<CompiledGraph>>,
346 graph_identities: HashMap<stateknot_core::CapabilityIdentity, GraphReference>,
347 reducers: HashMap<GraphReducerReference, Arc<dyn GraphReducer>>,
348 reducer_identities: HashMap<stateknot_core::CapabilityIdentity, GraphReducerReference>,
349 nodes: HashMap<(GraphReference, NodeId), Arc<dyn GraphNodeExecutor>>,
350}
351
352impl ExecutableGraphRegistryBuilder {
353 pub const MAX_GRAPHS: usize = 1024;
355 pub const MAX_REDUCERS: usize = 1024;
357 pub const MAX_NODE_EXECUTORS: usize = 65_536;
359
360 #[must_use]
362 pub fn new(schemas: JsonSchemaRegistry) -> Self {
363 Self {
364 schemas,
365 graphs: HashMap::new(),
366 graph_identities: HashMap::new(),
367 reducers: HashMap::new(),
368 reducer_identities: HashMap::new(),
369 nodes: HashMap::new(),
370 }
371 }
372
373 pub fn register_graph(
380 &mut self,
381 graph: CompiledGraph,
382 ) -> Result<(), ExecutableGraphRegistryError> {
383 if self.graphs.len() == Self::MAX_GRAPHS {
384 return Err(ExecutableGraphRegistryError::TooManyGraphs {
385 maximum: Self::MAX_GRAPHS,
386 actual: Self::MAX_GRAPHS + 1,
387 });
388 }
389 let reference = graph.reference();
390 if self.graphs.contains_key(&reference) {
391 return Err(ExecutableGraphRegistryError::DuplicateGraph {
392 reference: Box::new(reference),
393 });
394 }
395 if let Some(existing) = self.graph_identities.get(graph.identity()) {
396 return Err(ExecutableGraphRegistryError::GraphIdentityConflict {
397 existing: Box::new(existing.clone()),
398 rejected: Box::new(reference),
399 });
400 }
401 self.graph_identities
402 .insert(graph.identity().clone(), reference.clone());
403 self.graphs.insert(reference, Arc::new(graph));
404 Ok(())
405 }
406
407 pub fn register_reducer(
414 &mut self,
415 reducer: Arc<dyn GraphReducer>,
416 ) -> Result<(), ExecutableGraphRegistryError> {
417 if self.reducers.len() == Self::MAX_REDUCERS {
418 return Err(ExecutableGraphRegistryError::TooManyReducers {
419 maximum: Self::MAX_REDUCERS,
420 actual: Self::MAX_REDUCERS + 1,
421 });
422 }
423 let reference = reducer.reference().clone();
424 if self.reducers.contains_key(&reference) {
425 return Err(ExecutableGraphRegistryError::DuplicateReducer {
426 reference: Box::new(reference),
427 });
428 }
429 if let Some(existing) = self.reducer_identities.get(reference.identity()) {
430 return Err(ExecutableGraphRegistryError::ReducerIdentityConflict {
431 existing: Box::new(existing.clone()),
432 rejected: Box::new(reference),
433 });
434 }
435 self.reducer_identities
436 .insert(reference.identity().clone(), reference.clone());
437 self.reducers.insert(reference, reducer);
438 Ok(())
439 }
440
441 pub fn register_node(
447 &mut self,
448 executor: Arc<dyn GraphNodeExecutor>,
449 ) -> Result<(), ExecutableGraphRegistryError> {
450 if self.nodes.len() == Self::MAX_NODE_EXECUTORS {
451 return Err(ExecutableGraphRegistryError::TooManyNodeExecutors {
452 maximum: Self::MAX_NODE_EXECUTORS,
453 actual: Self::MAX_NODE_EXECUTORS + 1,
454 });
455 }
456 let key = (executor.graph().clone(), executor.node_id().clone());
457 if self.nodes.contains_key(&key) {
458 return Err(ExecutableGraphRegistryError::DuplicateNodeExecutor {
459 graph: Box::new(key.0),
460 node_id: key.1,
461 });
462 }
463 self.nodes.insert(key, executor);
464 Ok(())
465 }
466
467 pub fn build(self) -> Result<ExecutableGraphRegistry, ExecutableGraphRegistryError> {
475 if self.graphs.is_empty() {
476 return Err(ExecutableGraphRegistryError::EmptyGraphs);
477 }
478
479 for (reference, graph) in &self.graphs {
480 if let Some(policy) = graph.child_runs() {
481 for declaration in policy.declarations() {
482 let target = self.graphs.get(declaration.graph()).ok_or_else(|| {
483 ExecutableGraphRegistryError::MissingChildGraph {
484 parent: Box::new(reference.clone()),
485 child: Box::new(declaration.graph().clone()),
486 }
487 })?;
488 declaration
489 .validate_target(target, policy.limits())
490 .map_err(|source| ExecutableGraphRegistryError::ChildPolicy {
491 graph: Box::new(reference.clone()),
492 source,
493 })?;
494 }
495 }
496 }
497
498 let mut executable = HashMap::with_capacity(self.graphs.len());
499 let mut used_reducers = std::collections::HashSet::new();
500 let mut used_nodes = std::collections::HashSet::new();
501 for (reference, graph) in &self.graphs {
502 for schema in [
503 graph.input_schema(),
504 graph.state_schema(),
505 graph.update_schema(),
506 graph.output_schema(),
507 ] {
508 if !self.schemas.contains(schema) {
509 return Err(ExecutableGraphRegistryError::MissingSchema {
510 graph: Box::new(reference.clone()),
511 schema: Box::new(schema.clone()),
512 });
513 }
514 }
515 let reducer = self.reducers.get(graph.reducer()).cloned().ok_or_else(|| {
516 ExecutableGraphRegistryError::MissingReducer {
517 graph: Box::new(reference.clone()),
518 reducer: Box::new(graph.reducer().clone()),
519 }
520 })?;
521 used_reducers.insert(graph.reducer().clone());
522
523 let mut graph_nodes = HashMap::with_capacity(graph.nodes().len());
524 for node in graph.nodes() {
525 let key = (reference.clone(), node.node_id().clone());
526 let executor = self.nodes.get(&key).cloned().ok_or_else(|| {
527 ExecutableGraphRegistryError::MissingNodeExecutor {
528 graph: Box::new(reference.clone()),
529 node_id: node.node_id().clone(),
530 }
531 })?;
532 let declares_children = graph.child_runs().is_some_and(|policy| {
533 policy
534 .declarations()
535 .iter()
536 .any(|d| d.node_id() == node.node_id())
537 });
538 if (declares_children && executor.scheduling() != GraphNodeScheduling::Exclusive)
539 || (executor.supports_child_join()
540 && (!declares_children
541 || !crate::child_join::schema_available(&self.schemas)))
542 {
543 return Err(ExecutableGraphRegistryError::InvalidChildJoinExecutor);
544 }
545 used_nodes.insert(key);
546 graph_nodes.insert(node.node_id().clone(), executor);
547 }
548 executable.insert(
549 reference.clone(),
550 ExecutableGraph {
551 graph: Arc::clone(graph),
552 schemas: self.schemas.clone(),
553 reducer,
554 nodes: Arc::new(graph_nodes),
555 },
556 );
557 }
558
559 if let Some(reference) = self
560 .reducers
561 .keys()
562 .find(|reference| !used_reducers.contains(*reference))
563 {
564 return Err(ExecutableGraphRegistryError::OrphanReducer {
565 reducer: Box::new(reference.clone()),
566 });
567 }
568 if let Some((graph, node_id)) = self.nodes.keys().find(|key| !used_nodes.contains(*key)) {
569 return Err(ExecutableGraphRegistryError::OrphanNodeExecutor {
570 graph: Box::new(graph.clone()),
571 node_id: node_id.clone(),
572 });
573 }
574
575 Ok(ExecutableGraphRegistry {
576 schemas: self.schemas,
577 graphs: Arc::new(executable),
578 })
579 }
580}
581
582impl fmt::Debug for ExecutableGraphRegistryBuilder {
583 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
584 formatter
585 .debug_struct("ExecutableGraphRegistryBuilder")
586 .field("schemas", &self.schemas)
587 .field("graphs", &self.graphs.len())
588 .field("reducers", &self.reducers.len())
589 .field("nodes", &self.nodes.len())
590 .finish_non_exhaustive()
591 }
592}
593
594#[derive(Clone)]
596pub struct ExecutableGraphRegistry {
597 schemas: JsonSchemaRegistry,
598 graphs: Arc<HashMap<GraphReference, ExecutableGraph>>,
599}
600
601impl ExecutableGraphRegistry {
602 pub(crate) fn has_child_graphs(&self) -> bool {
603 self.graphs
604 .values()
605 .any(|entry| entry.graph().child_runs().is_some())
606 }
607 #[must_use]
609 pub fn resolve(&self, reference: &GraphReference) -> Option<&ExecutableGraph> {
610 self.graphs.get(reference)
611 }
612
613 #[must_use]
615 pub const fn schemas(&self) -> &JsonSchemaRegistry {
616 &self.schemas
617 }
618
619 #[must_use]
621 pub fn len(&self) -> usize {
622 self.graphs.len()
623 }
624
625 #[must_use]
627 pub fn is_empty(&self) -> bool {
628 self.graphs.is_empty()
629 }
630}
631
632impl fmt::Debug for ExecutableGraphRegistry {
633 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
634 formatter
635 .debug_struct("ExecutableGraphRegistry")
636 .field("schemas", &self.schemas.len())
637 .field("graphs", &self.graphs.len())
638 .finish_non_exhaustive()
639 }
640}
641
642#[derive(Clone, Debug, Eq, Error, PartialEq)]
644#[non_exhaustive]
645pub enum ExecutableGraphRegistryError {
646 #[error(
649 "child Join executor requires declared slots, exclusive scheduling and its audit schema"
650 )]
651 InvalidChildJoinExecutor,
652 #[error("executable registry lacks a declared child graph")]
654 MissingChildGraph {
655 parent: Box<GraphReference>,
657 child: Box<GraphReference>,
659 },
660 #[error("executable registry child policy validation failed: {source}")]
662 ChildPolicy {
663 graph: Box<GraphReference>,
665 #[source]
667 source: ChildRunPolicyError,
668 },
669 #[error("executable graph registry must contain at least one graph")]
671 EmptyGraphs,
672 #[error("executable registry contains {actual} graphs; maximum is {maximum}")]
674 TooManyGraphs {
675 maximum: usize,
677 actual: usize,
679 },
680 #[error("executable registry contains {actual} reducers; maximum is {maximum}")]
682 TooManyReducers {
683 maximum: usize,
685 actual: usize,
687 },
688 #[error("executable registry contains {actual} nodes; maximum is {maximum}")]
690 TooManyNodeExecutors {
691 maximum: usize,
693 actual: usize,
695 },
696 #[error("compiled graph reference was registered more than once")]
698 DuplicateGraph {
699 reference: Box<GraphReference>,
701 },
702 #[error("graph owner/name/version identity was reused with another definition")]
704 GraphIdentityConflict {
705 existing: Box<GraphReference>,
707 rejected: Box<GraphReference>,
709 },
710 #[error("graph reducer reference was registered more than once")]
712 DuplicateReducer {
713 reference: Box<GraphReducerReference>,
715 },
716 #[error("reducer owner/name/version identity was reused with another definition")]
718 ReducerIdentityConflict {
719 existing: Box<GraphReducerReference>,
721 rejected: Box<GraphReducerReference>,
723 },
724 #[error("graph node executor was registered more than once")]
726 DuplicateNodeExecutor {
727 graph: Box<GraphReference>,
729 node_id: NodeId,
731 },
732 #[error("compiled graph references an unavailable schema")]
734 MissingSchema {
735 graph: Box<GraphReference>,
737 schema: Box<stateknot_core::SchemaReference>,
739 },
740 #[error("compiled graph references an unavailable reducer")]
742 MissingReducer {
743 graph: Box<GraphReference>,
745 reducer: Box<GraphReducerReference>,
747 },
748 #[error("compiled graph node has no executable implementation")]
750 MissingNodeExecutor {
751 graph: Box<GraphReference>,
753 node_id: NodeId,
755 },
756 #[error("registered reducer is not referenced by any installed graph")]
758 OrphanReducer {
759 reducer: Box<GraphReducerReference>,
761 },
762 #[error("registered node executor is not declared by an installed graph")]
764 OrphanNodeExecutor {
765 graph: Box<GraphReference>,
767 node_id: NodeId,
769 },
770}
771
772#[cfg(test)]
773#[path = "registry_child_tests.rs"]
774mod child_tests;
775
776#[cfg(test)]
777mod tests {
778 use serde_json::{Value, json};
779 use stateknot_core::{
780 BoundedJson, CapabilityIdentity, CapabilityName, CapabilityReference, GraphExecutionLimits,
781 GraphNode, GraphReducerError, GraphReducerInput, GraphRoutes, IssuerId, PrincipalIdentity,
782 ReadyNodes, SchemaId, SchemaReference, SubjectId, Superstep, Version,
783 };
784
785 use super::*;
786 use crate::JsonSchemaRegistryBuilder;
787
788 const DRAFT: &str = "https://json-schema.org/draft/2020-12/schema";
789
790 fn identity(name: &str) -> CapabilityIdentity {
791 CapabilityIdentity::new(
792 PrincipalIdentity::new(
793 IssuerId::new("https://issuer.example.com").unwrap(),
794 SubjectId::new("runtime-tests").unwrap(),
795 ),
796 CapabilityReference::new(CapabilityName::new(name).unwrap(), Version::new(1, 0, 0)),
797 )
798 }
799
800 fn schema_reference(id: &str, document: &Value) -> SchemaReference {
801 SchemaReference::new(
802 id.parse::<SchemaId>().unwrap(),
803 Version::new(1, 0, 0),
804 stateknot_core::Digest::sha256(serde_json_canonicalizer::to_vec(document).unwrap()),
805 )
806 }
807
808 fn schemas() -> (JsonSchemaRegistry, SchemaReference) {
809 let id = "https://schemas.example.com/graph-value/1.0.0";
810 let document = json!({
811 "$schema": DRAFT,
812 "$id": id,
813 "type": "object",
814 "additionalProperties": true
815 });
816 let reference = schema_reference(id, &document);
817 let mut builder = JsonSchemaRegistryBuilder::default();
818 builder.register(reference.clone(), document).unwrap();
819 (builder.build().unwrap(), reference)
820 }
821
822 fn graph(schema: &SchemaReference, reducer: GraphReducerReference) -> (CompiledGraph, NodeId) {
823 let node_id = NodeId::new("finish").unwrap();
824 let node = GraphNode::new(node_id.clone(), None, GraphRoutes::empty(), None, true).unwrap();
825 let graph = CompiledGraph::compile(
826 identity("graph"),
827 schema.clone(),
828 schema.clone(),
829 schema.clone(),
830 schema.clone(),
831 reducer,
832 ReadyNodes::try_new([node_id.clone()]).unwrap(),
833 [node],
834 GraphExecutionLimits::new(Superstep::new(32).unwrap(), 4).unwrap(),
835 )
836 .unwrap();
837 (graph, node_id)
838 }
839
840 struct Reducer {
841 reference: GraphReducerReference,
842 }
843
844 impl GraphReducer for Reducer {
845 fn reference(&self) -> &GraphReducerReference {
846 &self.reference
847 }
848
849 fn reduce(
850 &self,
851 state: &BoundedJson,
852 _: &[GraphReducerInput<'_>],
853 ) -> Result<BoundedJson, GraphReducerError> {
854 Ok(state.clone())
855 }
856 }
857
858 struct Executor {
859 graph: GraphReference,
860 node_id: NodeId,
861 }
862
863 impl GraphNodeExecutor for Executor {
864 fn graph(&self) -> &GraphReference {
865 &self.graph
866 }
867
868 fn node_id(&self) -> &NodeId {
869 &self.node_id
870 }
871
872 fn execute(
873 &self,
874 _: GraphNodeContext,
875 ) -> BoxFuture<'_, Result<GraphNodeExecution, GraphNodeExecutionError>> {
876 Box::pin(async { panic!("registry tests do not execute node code") })
877 }
878 }
879
880 #[test]
881 fn complete_registry_freezes_exact_graph_dependencies() {
882 let (schemas, schema) = schemas();
883 let reducer_reference =
884 GraphReducerReference::new(identity("reducer"), stateknot_core::Digest::sha256(b"v1"));
885 let reducer = Arc::new(Reducer {
886 reference: reducer_reference.clone(),
887 });
888 let (graph, node_id) = graph(&schema, reducer_reference.clone());
889 let graph_reference = graph.reference();
890 let executor: Arc<dyn GraphNodeExecutor> = Arc::new(Executor {
891 graph: graph_reference.clone(),
892 node_id: node_id.clone(),
893 });
894 let mut builder = ExecutableGraphRegistryBuilder::new(schemas);
895 builder.register_node(Arc::clone(&executor)).unwrap();
896 assert!(matches!(
897 builder.register_node(Arc::new(Executor {
898 graph: graph_reference.clone(),
899 node_id: node_id.clone(),
900 })),
901 Err(ExecutableGraphRegistryError::DuplicateNodeExecutor { .. })
902 ));
903 builder.register_reducer(reducer).unwrap();
904 builder.register_graph(graph).unwrap();
905
906 let registry = builder.build().unwrap();
907 let executable = registry.resolve(&graph_reference).unwrap();
908 assert_eq!(registry.len(), 1);
909 assert_eq!(executable.graph().reference(), graph_reference);
910 assert_eq!(executable.reducer().reference(), &reducer_reference);
911 assert_eq!(executable.node(&node_id).unwrap().node_id(), &node_id);
912 assert!(Arc::ptr_eq(
913 &executable.node_executor(&node_id).unwrap(),
914 &executor
915 ));
916 }
917
918 #[test]
919 fn build_rejects_missing_and_orphan_node_code() {
920 let (schemas, schema) = schemas();
921 let reducer_reference = GraphReducerReference::new(
922 identity("reducer"),
923 stateknot_core::Digest::sha256(b"reducer"),
924 );
925 let reducer = Arc::new(Reducer {
926 reference: reducer_reference.clone(),
927 });
928 let (graph, node_id) = graph(&schema, reducer_reference);
929 let graph_reference = graph.reference();
930 let mut missing = ExecutableGraphRegistryBuilder::new(schemas.clone());
931 missing.register_reducer(reducer.clone()).unwrap();
932 missing.register_graph(graph.clone()).unwrap();
933 assert!(matches!(
934 missing.build(),
935 Err(ExecutableGraphRegistryError::MissingNodeExecutor { .. })
936 ));
937
938 let mut orphan = ExecutableGraphRegistryBuilder::new(schemas);
939 orphan.register_reducer(reducer).unwrap();
940 orphan.register_graph(graph).unwrap();
941 orphan
942 .register_node(Arc::new(Executor {
943 graph: graph_reference.clone(),
944 node_id,
945 }))
946 .unwrap();
947 orphan
948 .register_node(Arc::new(Executor {
949 graph: graph_reference,
950 node_id: NodeId::new("undeclared").unwrap(),
951 }))
952 .unwrap();
953 assert!(matches!(
954 orphan.build(),
955 Err(ExecutableGraphRegistryError::OrphanNodeExecutor { .. })
956 ));
957 }
958}