1use std::{
2 collections::{HashMap, HashSet},
3 future::Future,
4 num::NonZeroUsize,
5 pin::Pin,
6 sync::Mutex,
7 time::Duration,
8};
9
10use async_trait::async_trait;
11use saluki_common::resource_tracking::Track as _;
12use saluki_common::sync::shutdown::ShutdownHandle;
13use saluki_error::{generic_error, ErrorContext as _, GenericError};
14use snafu::Snafu;
15use tokio::{pin, runtime::Handle, select, sync::oneshot};
16use tracing::info;
17
18use super::{
19 built::{BuiltTopology, WorkerPoolConfiguration},
20 condition::{ConditionKind, EdgeCondition, EdgeConditions, EdgeKey},
21 graph::{Graph, GraphError},
22 ComponentId, ComponentOutputId,
23};
24use crate::accounting::{ComponentRegistry, MemoryBounds, MemoryLimiter, UsageExpr};
25use crate::{
26 components::{
27 decoders::DecoderBuilder, destinations::DestinationBuilder, encoders::EncoderBuilder,
28 forwarders::ForwarderBuilder, relays::RelayBuilder, sources::SourceBuilder, transforms::TransformBuilder,
29 BuildContext, ComponentContext, ComponentType,
30 },
31 data_model::event::Event,
32 health::HealthRegistry,
33 runtime::{
34 halt::HaltWatch,
35 state::{DataspaceRegistry, ResourceRegistry},
36 InitializationError, ShutdownStrategy, Supervisable, SupervisorFuture, UnadoptedScope,
37 },
38 support::SubsystemIdentifier,
39 topology::{ids::AsComponentIds, topology_identifier, EventsBuffer, DEFAULT_EVENTS_BUFFER_CAPACITY},
40};
41
42const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
43
44#[derive(Debug, Snafu)]
46#[snafu(context(suffix(false)))]
47pub enum BlueprintError {
48 #[snafu(display("Failed to build/validate topology graph: {}", source))]
50 InvalidGraph {
51 source: GraphError,
53 },
54
55 #[snafu(display("Failed to build component '{}': {}", id, source))]
57 FailedToBuildComponent {
58 id: ComponentId,
60
61 source: GenericError,
63 },
64}
65
66pub struct TopologyBlueprint {
72 name: String,
73 build_state: Mutex<Option<TopologyBuildState>>,
74 health_registry: Option<HealthRegistry>,
75 memory_limiter: Option<MemoryLimiter>,
76 resource_registry: Option<ResourceRegistry>,
77}
78
79struct TopologyBuildState {
83 topology_id: SubsystemIdentifier,
84 graph: Graph,
85 sources: HashMap<ComponentId, Box<dyn SourceBuilder + Send>>,
86 relays: HashMap<ComponentId, Box<dyn RelayBuilder + Send>>,
87 decoders: HashMap<ComponentId, Box<dyn DecoderBuilder + Send>>,
88 transforms: HashMap<ComponentId, Box<dyn TransformBuilder + Send>>,
89 destinations: HashMap<ComponentId, Box<dyn DestinationBuilder + Send>>,
90 encoders: HashMap<ComponentId, Box<dyn EncoderBuilder + Send>>,
91 forwarders: HashMap<ComponentId, Box<dyn ForwarderBuilder + Send>>,
92 component_registry: ComponentRegistry,
93 interconnect_capacity: NonZeroUsize,
94 shutdown_timeout: Duration,
95 worker_pool_config: WorkerPoolConfiguration,
96 environment_ready: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
97 ready_signal: Option<oneshot::Sender<()>>,
98 folded_targets: HashSet<ComponentId>,
100 prunable_components: HashMap<ComponentId, ComponentType>,
102 edge_conditions: EdgeConditions,
104}
105
106impl TopologyBlueprint {
107 pub fn new(name: &str, component_registry: &ComponentRegistry) -> Self {
109 let topology_id = topology_identifier(name);
110 let component_registry = component_registry.clone();
111
112 let build_state = TopologyBuildState {
113 topology_id,
114 graph: Graph::default(),
115 sources: HashMap::new(),
116 relays: HashMap::new(),
117 decoders: HashMap::new(),
118 transforms: HashMap::new(),
119 destinations: HashMap::new(),
120 encoders: HashMap::new(),
121 forwarders: HashMap::new(),
122 component_registry,
123 interconnect_capacity: super::DEFAULT_INTERCONNECT_CAPACITY,
124 shutdown_timeout: DEFAULT_SHUTDOWN_TIMEOUT,
125 worker_pool_config: WorkerPoolConfiguration::Dedicated,
126 environment_ready: None,
127 ready_signal: None,
128 folded_targets: HashSet::new(),
129 prunable_components: HashMap::new(),
130 edge_conditions: EdgeConditions::default(),
131 };
132
133 Self {
134 name: name.to_string(),
135 build_state: Mutex::new(Some(build_state)),
136 health_registry: None,
137 memory_limiter: None,
138 resource_registry: None,
139 }
140 }
141
142 fn state_mut(&mut self) -> &mut TopologyBuildState {
148 self.build_state
149 .get_mut()
150 .expect("topology blueprint mutex poisoned")
151 .as_mut()
152 .expect("topology blueprint already initialized")
153 }
154
155 pub fn with_interconnect_capacity(&mut self, capacity: NonZeroUsize) -> &mut Self {
163 self.state_mut().set_interconnect_capacity(capacity);
164 self
165 }
166
167 pub fn with_shutdown_timeout(&mut self, timeout: Duration) -> &mut Self {
171 self.state_mut().shutdown_timeout = timeout;
172 self
173 }
174
175 pub fn with_health_registry(&mut self, health_registry: HealthRegistry) -> &mut Self {
179 self.health_registry = Some(health_registry);
180 self
181 }
182
183 pub fn with_memory_limiter(&mut self, memory_limiter: MemoryLimiter) -> &mut Self {
187 self.memory_limiter = Some(memory_limiter);
188 self
189 }
190
191 pub fn with_resource_registry(&mut self, resource_registry: ResourceRegistry) -> &mut Self {
199 self.resource_registry = Some(resource_registry);
200 self
201 }
202
203 pub fn with_environment_readiness<F>(&mut self, ready: F) -> &mut Self
209 where
210 F: Future<Output = ()> + Send + 'static,
211 {
212 self.state_mut().environment_ready = Some(Box::pin(ready));
213 self
214 }
215
216 pub fn topology_ready(&mut self) -> TopologyReady {
225 let health_registry = self
226 .health_registry
227 .clone()
228 .expect("health registry must be set before acquiring a topology readiness handle");
229 let component_root = super::topology_identifier(&self.name);
230
231 let (registered_tx, registered_rx) = oneshot::channel();
232 self.state_mut().ready_signal = Some(registered_tx);
233
234 TopologyReady {
235 registered_rx,
236 health_registry,
237 component_root,
238 }
239 }
240
241 pub fn with_ambient_worker_pool(&mut self) -> &mut Self {
246 self.state_mut().worker_pool_config = WorkerPoolConfiguration::Ambient;
247 self
248 }
249
250 pub fn with_explicit_worker_pool(&mut self, handle: Handle) -> &mut Self {
254 self.state_mut().worker_pool_config = WorkerPoolConfiguration::Explicit(handle);
255 self
256 }
257
258 pub fn add_source<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
264 where
265 I: AsRef<str>,
266 B: SourceBuilder + Send + 'static,
267 {
268 self.state_mut().add_source(component_id, builder)?;
269 Ok(self)
270 }
271
272 pub fn add_relay<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
278 where
279 I: AsRef<str>,
280 B: RelayBuilder + Send + 'static,
281 {
282 self.state_mut().add_relay(component_id, builder)?;
283 Ok(self)
284 }
285
286 pub fn add_decoder<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
292 where
293 I: AsRef<str>,
294 B: DecoderBuilder + Send + 'static,
295 {
296 self.state_mut().add_decoder(component_id, builder)?;
297 Ok(self)
298 }
299
300 pub fn add_transform<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
306 where
307 I: AsRef<str>,
308 B: TransformBuilder + Send + 'static,
309 {
310 self.state_mut().add_transform(component_id, builder)?;
311 Ok(self)
312 }
313
314 pub fn add_destination<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
320 where
321 I: AsRef<str>,
322 B: DestinationBuilder + Send + 'static,
323 {
324 self.state_mut().add_destination(component_id, builder)?;
325 Ok(self)
326 }
327
328 pub fn add_encoder<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
334 where
335 I: AsRef<str>,
336 B: EncoderBuilder + Send + 'static,
337 {
338 self.state_mut().add_encoder(component_id, builder)?;
339 Ok(self)
340 }
341
342 pub fn add_forwarder<I, B>(&mut self, component_id: I, builder: B) -> Result<&mut Self, GenericError>
348 where
349 I: AsRef<str>,
350 B: ForwarderBuilder + Send + 'static,
351 {
352 self.state_mut().add_forwarder(component_id, builder)?;
353 Ok(self)
354 }
355
356 pub fn connect_components<MS, SI, MD, DI>(
371 &mut self, upstream_output_component_ids: SI, downstream_component_ids: DI,
372 ) -> Result<&mut Self, GenericError>
373 where
374 SI: AsComponentIds<MS>,
375 DI: AsComponentIds<MD>,
376 {
377 self.state_mut()
378 .connect_components(upstream_output_component_ids, downstream_component_ids)?;
379 Ok(self)
380 }
381
382 pub fn connect_components_in_order<IT, I>(&mut self, ordered_component_ids: IT) -> Result<&mut Self, GenericError>
404 where
405 IT: IntoIterator<Item = I>,
406 I: AsRef<str>,
407 {
408 self.state_mut().connect_components_in_order(ordered_component_ids)?;
409 Ok(self)
410 }
411
412 pub fn connect_components_when<F, T>(
428 &mut self, upstream_output_component_id: F, downstream_component_id: T, condition: EdgeCondition,
429 ) -> Result<&mut Self, GenericError>
430 where
431 F: AsRef<str>,
432 T: AsRef<str>,
433 {
434 self.state_mut().connect_components_when(
435 upstream_output_component_id.as_ref(),
436 downstream_component_id.as_ref(),
437 condition,
438 )?;
439 Ok(self)
440 }
441}
442
443pub struct TopologyReady {
445 registered_rx: oneshot::Receiver<()>,
446 health_registry: HealthRegistry,
447 component_root: SubsystemIdentifier,
448}
449
450impl TopologyReady {
451 pub async fn wait(self) -> bool {
457 if self.registered_rx.await.is_err() {
462 return false;
463 }
464
465 self.health_registry.all_ready_under(self.component_root).await;
467
468 true
469 }
470}
471
472impl TopologyBuildState {
473 fn set_interconnect_capacity(&mut self, capacity: NonZeroUsize) {
474 self.interconnect_capacity = capacity;
475 self.recalculate_bounds();
476 }
477
478 fn sync_prunable_component_bounds(&mut self) {
484 let prunable: HashMap<_, _> = self
485 .graph
486 .clone()
487 .prune_components_without_inputs(self.folded_targets.iter().cloned())
488 .into_iter()
489 .collect();
490
491 for (id, component_type) in &prunable {
492 if !self.prunable_components.contains_key(id) {
493 let identity = self.component_identity(*component_type, id);
494 self.component_registry.bounds_builder(&identity).reset();
495 }
496 }
497 for (id, component_type) in &self.prunable_components {
498 if !prunable.contains_key(id) {
499 if let Some(bounds) = self.component_bounds(id, *component_type) {
500 let identity = self.component_identity(*component_type, id);
501 bounds.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
502 }
503 }
504 }
505
506 self.prunable_components = prunable;
507 }
508
509 fn component_bounds(&self, id: &ComponentId, component_type: ComponentType) -> Option<&dyn MemoryBounds> {
510 match component_type {
511 ComponentType::Source => self.sources.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
512 ComponentType::Relay => self.relays.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
513 ComponentType::Decoder => self.decoders.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
514 ComponentType::Transform => self.transforms.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
515 ComponentType::Destination => self.destinations.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
516 ComponentType::Encoder => self.encoders.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
517 ComponentType::Forwarder => self.forwarders.get(id).map(|b| b.as_ref() as &dyn MemoryBounds),
518 }
519 }
520
521 fn recalculate_bounds(&mut self) {
522 self.sync_prunable_component_bounds();
523 let live_transforms = self
524 .transforms
525 .keys()
526 .filter(|id| !self.prunable_components.contains_key(*id))
527 .count();
528 let live_destinations = self
529 .destinations
530 .keys()
531 .filter(|id| !self.prunable_components.contains_key(*id))
532 .count();
533 let live_decoders = self
534 .decoders
535 .keys()
536 .filter(|id| !self.prunable_components.contains_key(*id))
537 .count();
538
539 let interconnect_capacity = self.interconnect_capacity.get();
540
541 let mut bounds_builder = self.component_registry.bounds_builder(&self.topology_id);
542 let mut bounds_builder = bounds_builder.subcomponent("interconnects");
543 bounds_builder.reset();
544
545 let total_interconnect_capacity = interconnect_capacity * (live_transforms + live_destinations);
550 bounds_builder
551 .minimum()
552 .with_array::<EventsBuffer>("events", total_interconnect_capacity);
553
554 let max_in_flight_event_buffers = ((live_transforms + live_destinations) * interconnect_capacity)
565 + self.sources.len()
566 + live_decoders
567 + live_transforms;
568
569 bounds_builder
570 .firm()
571 .with_expr(UsageExpr::product(
573 "events",
574 UsageExpr::constant("max in-flight event buffers", max_in_flight_event_buffers),
575 UsageExpr::sum(
576 "",
577 UsageExpr::struct_size::<EventsBuffer>("events buffer"),
578 UsageExpr::product(
579 "",
580 UsageExpr::struct_size::<Event>("event"),
581 UsageExpr::constant("default event buffer capacity", DEFAULT_EVENTS_BUFFER_CAPACITY),
582 ),
583 ),
584 ));
585 }
586
587 fn component_identity(&self, component_type: ComponentType, component_id: &ComponentId) -> SubsystemIdentifier {
588 ComponentContext::new(&self.topology_id, component_id.clone(), component_type).identity()
589 }
590
591 fn add_source<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
592 where
593 I: AsRef<str>,
594 B: SourceBuilder + Send + 'static,
595 {
596 let component_id = self
597 .graph
598 .add_source(component_id, &builder)
599 .error_context("Failed to add source to topology graph.")?;
600
601 let identity = self.component_identity(ComponentType::Source, &component_id);
602 builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
603
604 self.recalculate_bounds();
605
606 let _ = self.sources.insert(component_id, Box::new(builder));
607
608 Ok(())
609 }
610
611 fn add_relay<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
612 where
613 I: AsRef<str>,
614 B: RelayBuilder + Send + 'static,
615 {
616 let component_id = self
617 .graph
618 .add_relay(component_id, &builder)
619 .error_context("Failed to add relay to topology graph.")?;
620
621 let identity = self.component_identity(ComponentType::Relay, &component_id);
622 builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
623
624 self.recalculate_bounds();
625
626 let _ = self.relays.insert(component_id, Box::new(builder));
627
628 Ok(())
629 }
630
631 fn add_decoder<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
632 where
633 I: AsRef<str>,
634 B: DecoderBuilder + Send + 'static,
635 {
636 let component_id = self
637 .graph
638 .add_decoder(component_id, &builder)
639 .error_context("Failed to add decoder to topology graph.")?;
640
641 let identity = self.component_identity(ComponentType::Decoder, &component_id);
642 builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
643
644 self.recalculate_bounds();
645
646 let _ = self.decoders.insert(component_id, Box::new(builder));
647
648 Ok(())
649 }
650
651 fn add_transform<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
652 where
653 I: AsRef<str>,
654 B: TransformBuilder + Send + 'static,
655 {
656 let component_id = self
657 .graph
658 .add_transform(component_id, &builder)
659 .error_context("Failed to add transform to topology graph.")?;
660
661 let identity = self.component_identity(ComponentType::Transform, &component_id);
662 builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
663
664 self.recalculate_bounds();
665
666 let _ = self.transforms.insert(component_id, Box::new(builder));
667
668 Ok(())
669 }
670
671 fn add_destination<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
672 where
673 I: AsRef<str>,
674 B: DestinationBuilder + Send + 'static,
675 {
676 let component_id = self
677 .graph
678 .add_destination(component_id, &builder)
679 .error_context("Failed to add destination to topology graph.")?;
680
681 let identity = self.component_identity(ComponentType::Destination, &component_id);
682 builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
683
684 self.recalculate_bounds();
685
686 let _ = self.destinations.insert(component_id, Box::new(builder));
687
688 Ok(())
689 }
690
691 fn add_encoder<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
692 where
693 I: AsRef<str>,
694 B: EncoderBuilder + Send + 'static,
695 {
696 let component_id = self
697 .graph
698 .add_encoder(component_id, &builder)
699 .error_context("Failed to add encoder to topology graph.")?;
700
701 let identity = self.component_identity(ComponentType::Encoder, &component_id);
702 builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
703
704 self.recalculate_bounds();
705
706 let _ = self.encoders.insert(component_id, Box::new(builder));
707
708 Ok(())
709 }
710
711 fn add_forwarder<I, B>(&mut self, component_id: I, builder: B) -> Result<(), GenericError>
712 where
713 I: AsRef<str>,
714 B: ForwarderBuilder + Send + 'static,
715 {
716 let component_id = self
717 .graph
718 .add_forwarder(component_id, &builder)
719 .error_context("Failed to add forwarder to topology graph.")?;
720
721 let identity = self.component_identity(ComponentType::Forwarder, &component_id);
722 builder.specify_bounds(&mut self.component_registry.bounds_builder(&identity));
723
724 self.recalculate_bounds();
725
726 let _ = self.forwarders.insert(component_id, Box::new(builder));
727
728 Ok(())
729 }
730
731 fn connect_components<MS, SI, MD, DI>(
732 &mut self, upstream_output_component_ids: SI, downstream_component_ids: DI,
733 ) -> Result<(), GenericError>
734 where
735 SI: AsComponentIds<MS>,
736 DI: AsComponentIds<MD>,
737 {
738 for upstream_output_component_id in upstream_output_component_ids.as_component_ids() {
739 for downstream_component_id in downstream_component_ids.as_component_ids() {
740 self.graph
741 .add_edge(upstream_output_component_id.as_ref(), downstream_component_id.as_ref())
742 .error_context("Failed to add component connection to topology graph.")?;
743 }
744 }
745
746 self.recalculate_bounds();
748
749 Ok(())
750 }
751
752 fn connect_components_in_order<IT, I>(&mut self, ordered_component_ids: IT) -> Result<(), GenericError>
753 where
754 IT: IntoIterator<Item = I>,
755 I: AsRef<str>,
756 {
757 let mut pending_output_component_id: Option<I> = None;
758 let mut connected_any = false;
759
760 for component_id in ordered_component_ids.into_iter() {
761 if let Some(output_component_id) = pending_output_component_id.take() {
762 self.graph
763 .add_edge(output_component_id.as_ref(), component_id.as_ref())
764 .error_context("Failed to add component connection to topology graph.")?;
765
766 connected_any = true;
767 }
768
769 pending_output_component_id = Some(component_id);
771 }
772
773 if !connected_any {
775 return Err(generic_error!(
776 "Two or more components must be provided for connection."
777 ));
778 }
779
780 self.recalculate_bounds();
782
783 Ok(())
784 }
785
786 fn connect_components_when(
787 &mut self, upstream_output_component_id: &str, downstream_component_id: &str, condition: EdgeCondition,
788 ) -> Result<(), GenericError> {
789 self.graph
790 .add_edge(upstream_output_component_id, downstream_component_id)
791 .error_context("Failed to add component connection to topology graph.")?;
792
793 let upstream_output = ComponentOutputId::try_from(upstream_output_component_id)
795 .map_err(|e| generic_error!("Invalid component output ID '{}': {}", upstream_output_component_id, e))?;
796 let downstream = ComponentId::try_from(downstream_component_id)
797 .map_err(|e| generic_error!("Invalid component ID '{}': {}", downstream_component_id, e))?;
798
799 match condition.0 {
800 ConditionKind::Fixed(true) => {}
801 ConditionKind::Fixed(false) => {
802 self.graph.remove_edge(&upstream_output, &downstream);
805 self.folded_targets.insert(downstream);
806 }
807 ConditionKind::Dynamic { initial, updates } => {
808 let key = EdgeKey {
809 upstream: upstream_output.component_id(),
810 output: upstream_output.output(),
811 downstream,
812 };
813 self.edge_conditions.insert(key, initial, updates);
814 }
815 }
816
817 self.recalculate_bounds();
818
819 Ok(())
820 }
821
822 fn prune_folded_components(&mut self) {
827 let folded_targets = std::mem::take(&mut self.folded_targets);
828 for (id, component_type) in self.graph.prune_components_without_inputs(folded_targets) {
829 match component_type {
830 ComponentType::Source => drop(self.sources.remove(&id)),
831 ComponentType::Relay => drop(self.relays.remove(&id)),
832 ComponentType::Decoder => drop(self.decoders.remove(&id)),
833 ComponentType::Transform => drop(self.transforms.remove(&id)),
834 ComponentType::Destination => drop(self.destinations.remove(&id)),
835 ComponentType::Encoder => drop(self.encoders.remove(&id)),
836 ComponentType::Forwarder => drop(self.forwarders.remove(&id)),
837 }
838 self.edge_conditions.remove_component(&id);
839
840 info!(component_id = %id, component_type = component_type.as_str(), "Removed component with no active inputs.");
841 }
842 }
843
844 async fn build(
850 mut self, name: String, resource_registry: &ResourceRegistry,
851 ) -> Result<BuiltTopology, GenericError> {
852 self.prune_folded_components();
853 self.graph.validate().error_context("Failed to build topology graph.")?;
854
855 let mut component_scopes = HashMap::new();
856
857 let mut sources = HashMap::new();
858 for (id, builder) in self.sources {
859 let component_context = ComponentContext::source(&self.topology_id, id.clone());
860 let allocation_token = self
861 .component_registry
862 .get_resource_group_token(&component_context.identity());
863 let scope = UnadoptedScope::new(component_context.identity().to_string());
867 let source = scope
868 .scope()
869 .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
870 .track_resources(allocation_token)
871 .await
872 .with_error_context(|| format!("Failed to build source '{}'.", id))?;
873
874 component_scopes.insert(component_context.clone(), scope);
875 sources.insert(component_context, (source, self.component_registry.clone()));
876 }
877
878 let mut relays = HashMap::new();
879 for (id, builder) in self.relays {
880 let component_context = ComponentContext::relay(&self.topology_id, id.clone());
881 let allocation_token = self
882 .component_registry
883 .get_resource_group_token(&component_context.identity());
884 let scope = UnadoptedScope::new(component_context.identity().to_string());
888 let relay = scope
889 .scope()
890 .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
891 .track_resources(allocation_token)
892 .await
893 .with_error_context(|| format!("Failed to build relay '{}'.", id))?;
894
895 component_scopes.insert(component_context.clone(), scope);
896 relays.insert(component_context, (relay, self.component_registry.clone()));
897 }
898
899 let mut decoders = HashMap::new();
900 for (id, builder) in self.decoders {
901 let component_context = ComponentContext::decoder(&self.topology_id, id.clone());
902 let allocation_token = self
903 .component_registry
904 .get_resource_group_token(&component_context.identity());
905 let scope = UnadoptedScope::new(component_context.identity().to_string());
909 let decoder = scope
910 .scope()
911 .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
912 .track_resources(allocation_token)
913 .await
914 .with_error_context(|| format!("Failed to build decoder '{}'.", id))?;
915
916 component_scopes.insert(component_context.clone(), scope);
917 decoders.insert(component_context, (decoder, self.component_registry.clone()));
918 }
919
920 let mut transforms = HashMap::new();
921 for (id, builder) in self.transforms {
922 let component_context = ComponentContext::transform(&self.topology_id, id.clone());
923 let allocation_token = self
924 .component_registry
925 .get_resource_group_token(&component_context.identity());
926 let scope = UnadoptedScope::new(component_context.identity().to_string());
930 let transform = scope
931 .scope()
932 .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
933 .track_resources(allocation_token)
934 .await
935 .with_error_context(|| format!("Failed to build transform '{}'.", id))?;
936
937 component_scopes.insert(component_context.clone(), scope);
938 transforms.insert(component_context, (transform, self.component_registry.clone()));
939 }
940
941 let mut destinations = HashMap::new();
942 for (id, builder) in self.destinations {
943 let component_context = ComponentContext::destination(&self.topology_id, id.clone());
944 let allocation_token = self
945 .component_registry
946 .get_resource_group_token(&component_context.identity());
947 let scope = UnadoptedScope::new(component_context.identity().to_string());
951 let destination = scope
952 .scope()
953 .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
954 .track_resources(allocation_token)
955 .await
956 .with_error_context(|| format!("Failed to build destination '{}'.", id))?;
957
958 component_scopes.insert(component_context.clone(), scope);
959 destinations.insert(component_context, (destination, self.component_registry.clone()));
960 }
961
962 let mut encoders = HashMap::new();
963 for (id, builder) in self.encoders {
964 let component_context = ComponentContext::encoder(&self.topology_id, id.clone());
965 let allocation_token = self
966 .component_registry
967 .get_resource_group_token(&component_context.identity());
968 let scope = UnadoptedScope::new(component_context.identity().to_string());
972 let encoder = scope
973 .scope()
974 .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
975 .track_resources(allocation_token)
976 .await
977 .with_error_context(|| format!("Failed to build encoder '{}'.", id))?;
978
979 component_scopes.insert(component_context.clone(), scope);
980 encoders.insert(component_context, (encoder, self.component_registry.clone()));
981 }
982
983 let mut forwarders = HashMap::new();
984 for (id, builder) in self.forwarders {
985 let component_context = ComponentContext::forwarder(&self.topology_id, id.clone());
986 let allocation_token = self
987 .component_registry
988 .get_resource_group_token(&component_context.identity());
989 let scope = UnadoptedScope::new(component_context.identity().to_string());
993 let forwarder = scope
994 .scope()
995 .enter(builder.build(BuildContext::new(component_context.clone(), resource_registry.clone())))
996 .track_resources(allocation_token)
997 .await
998 .with_error_context(|| format!("Failed to build forwarder '{}'.", id))?;
999
1000 component_scopes.insert(component_context.clone(), scope);
1001 forwarders.insert(component_context, (forwarder, self.component_registry.clone()));
1002 }
1003
1004 let topology_token = self.component_registry.get_resource_group_token(&self.topology_id);
1005
1006 Ok(BuiltTopology::from_parts(
1007 name,
1008 self.topology_id,
1009 self.graph,
1010 sources,
1011 relays,
1012 decoders,
1013 transforms,
1014 destinations,
1015 encoders,
1016 forwarders,
1017 component_scopes,
1018 topology_token,
1019 self.interconnect_capacity,
1020 self.worker_pool_config,
1021 self.edge_conditions,
1022 ))
1023 }
1024}
1025
1026#[async_trait]
1027impl Supervisable for TopologyBlueprint {
1028 fn name(&self) -> &str {
1029 &self.name
1030 }
1031
1032 fn shutdown_strategy(&self) -> ShutdownStrategy {
1033 ShutdownStrategy::Graceful(Duration::MAX)
1035 }
1036
1037 fn can_restart(&self) -> bool {
1038 false
1040 }
1041
1042 async fn initialize(&self, shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
1043 let mut build_state = self
1047 .build_state
1048 .lock()
1049 .expect("topology blueprint mutex poisoned")
1050 .take()
1051 .ok_or_else(|| generic_error!("Topology has already been initialized and cannot be run more than once."))?;
1052
1053 let health_registry = self
1054 .health_registry
1055 .clone()
1056 .ok_or_else(|| generic_error!("Topology blueprint is missing its health registry."))?;
1057 let memory_limiter = self
1058 .memory_limiter
1059 .clone()
1060 .ok_or_else(|| generic_error!("Topology blueprint is missing its memory limiter."))?;
1061
1062 let resource_registry = self
1063 .resource_registry
1064 .clone()
1065 .ok_or_else(|| generic_error!("Topology blueprint is missing its resource registry."))?;
1066
1067 let dataspace = DataspaceRegistry::try_current()
1068 .ok_or_else(|| generic_error!("Topology must be initialized within a supervised process context."))?;
1069
1070 let environment_ready = build_state.environment_ready.take();
1078 let ready_signal = build_state.ready_signal.take();
1079 let shutdown_timeout = build_state.shutdown_timeout;
1080 let built = build_state.build(self.name.clone(), &resource_registry).await?;
1081
1082 Ok(Box::pin(async move {
1083 pin!(shutdown);
1084
1085 if let Some(environment_ready) = environment_ready {
1088 select! {
1089 _ = &mut shutdown => return Ok(()),
1090 _ = environment_ready => {},
1091 }
1092 }
1093
1094 let mut topology_sup = built
1097 .spawn_inner(&health_registry, memory_limiter, dataspace.clone(), shutdown_timeout)
1098 .await?;
1099
1100 if let Some(ready_signal) = ready_signal {
1104 let _ = ready_signal.send(());
1105 }
1106
1107 let (topology_shutdown_trigger, topology_shutdown) = ShutdownHandle::paired();
1118 let run = topology_sup.run_with_shutdown_inner(topology_shutdown, HaltWatch::never(), Some(dataspace));
1119 pin!(run);
1120
1121 let mut topology_shutdown_trigger = Some(topology_shutdown_trigger);
1122 loop {
1123 select! {
1124 result = &mut run => return result.map_err(Into::into),
1125 _ = &mut shutdown, if topology_shutdown_trigger.is_some() => {
1126 info!("Topology received shutdown signal. Shutting down...");
1127 topology_shutdown_trigger.take().expect("present per select guard").shutdown();
1128 }
1129 }
1130 }
1131 }))
1132 }
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137 use std::num::NonZeroUsize;
1138 use std::sync::atomic::{AtomicUsize, Ordering};
1139 use std::sync::Arc;
1140 use std::time::Duration;
1141
1142 use async_trait::async_trait;
1143 use saluki_common::sync::shutdown::ShutdownHandle;
1144 use saluki_error::GenericError;
1145 use tokio::sync::oneshot;
1146
1147 use super::{TopologyBlueprint, TopologyReady, WorkerPoolConfiguration};
1148 use crate::accounting::{ComponentRegistry, MemoryBounds, MemoryBoundsBuilder, MemoryLimiter};
1149 use crate::components::BuildContext;
1150 use crate::data_model::event::Event;
1151 use crate::runtime::{self, state::ResourceRegistry, Name};
1152 use crate::test_support::wait_until;
1153 use crate::topology::{ids::get_component_relative_identifier, topology_identifier, ComponentId};
1154 use crate::topology::{EventsBuffer, DEFAULT_EVENTS_BUFFER_CAPACITY};
1155 use crate::{
1156 components::{
1157 destinations::{Destination, DestinationBuilder, DestinationContext},
1158 sources::{Source, SourceBuilder, SourceContext},
1159 ComponentContext,
1160 },
1161 data_model::{event::EventType, payload::PayloadType},
1162 health::HealthRegistry,
1163 runtime::{InitializationError, RestartStrategy, Supervisable, Supervisor, SupervisorError, SupervisorFuture},
1164 support::SubsystemIdentifier,
1165 topology::{
1166 test_util::{
1167 TestDecoderBuilder, TestDestinationBuilder, TestRelayBuilder, TestSourceBuilder, TestTransformBuilder,
1168 },
1169 EdgeCondition, OutputDefinition,
1170 },
1171 };
1172
1173 struct CountingChild {
1177 started: Arc<AtomicUsize>,
1178 }
1179
1180 #[async_trait]
1181 impl Supervisable for CountingChild {
1182 fn name(&self) -> &str {
1183 "child"
1184 }
1185
1186 async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
1187 let started = Arc::clone(&self.started);
1188 Ok(Box::pin(async move {
1189 started.fetch_add(1, Ordering::SeqCst);
1190 process_shutdown.await;
1192 Ok(())
1193 }))
1194 }
1195 }
1196
1197 struct ControlSource {
1201 started: Arc<AtomicUsize>,
1202 spawned_child: Option<Arc<AtomicUsize>>,
1203 }
1204
1205 #[async_trait]
1206 impl Source for ControlSource {
1207 async fn run(self: Box<Self>, mut context: SourceContext) -> Result<(), GenericError> {
1208 self.started.fetch_add(1, Ordering::SeqCst);
1209 let shutdown = context.take_shutdown_handle();
1210 if let Some(started) = self.spawned_child {
1211 runtime::supervisable(CountingChild { started }).spawn();
1214 }
1215 shutdown.await;
1216 Ok(())
1217 }
1218 }
1219
1220 struct ControlSourceBuilder {
1221 outputs: Vec<OutputDefinition<EventType>>,
1222 started: Arc<AtomicUsize>,
1223 spawned_child: Option<Arc<AtomicUsize>>,
1224 }
1225
1226 impl ControlSourceBuilder {
1227 fn new(started: Arc<AtomicUsize>, spawned_child: Option<Arc<AtomicUsize>>) -> Self {
1228 Self {
1229 outputs: vec![OutputDefinition::default_output(EventType::EventD)],
1230 started,
1231 spawned_child,
1232 }
1233 }
1234 }
1235
1236 #[async_trait]
1237 impl SourceBuilder for ControlSourceBuilder {
1238 fn outputs(&self) -> &[OutputDefinition<EventType>] {
1239 &self.outputs
1240 }
1241
1242 async fn build(&self, _: BuildContext) -> Result<Box<dyn Source + Send>, GenericError> {
1243 Ok(Box::new(ControlSource {
1244 started: Arc::clone(&self.started),
1245 spawned_child: self.spawned_child.clone(),
1246 }))
1247 }
1248 }
1249
1250 impl MemoryBounds for ControlSourceBuilder {
1251 fn specify_bounds(&self, _builder: &mut MemoryBoundsBuilder) {}
1252 }
1253
1254 struct BuildSpawningSourceBuilder {
1258 outputs: Vec<OutputDefinition<EventType>>,
1259 source_started: Arc<AtomicUsize>,
1260 child_started: Arc<AtomicUsize>,
1261 child_stopped: Arc<AtomicUsize>,
1262 }
1263
1264 #[async_trait]
1265 impl SourceBuilder for BuildSpawningSourceBuilder {
1266 fn outputs(&self) -> &[OutputDefinition<EventType>] {
1267 &self.outputs
1268 }
1269
1270 async fn build(&self, _: BuildContext) -> Result<Box<dyn Source + Send>, GenericError> {
1271 let (started, stopped) = (Arc::clone(&self.child_started), Arc::clone(&self.child_stopped));
1272 runtime::worker_with_shutdown("built_child", move |shutdown| async move {
1273 started.fetch_add(1, Ordering::SeqCst);
1274 shutdown.await;
1275 stopped.fetch_add(1, Ordering::SeqCst);
1276 })
1277 .spawn_or_detached();
1278
1279 Ok(Box::new(ControlSource {
1280 started: Arc::clone(&self.source_started),
1281 spawned_child: None,
1282 }))
1283 }
1284 }
1285
1286 impl MemoryBounds for BuildSpawningSourceBuilder {
1287 fn specify_bounds(&self, _builder: &mut MemoryBoundsBuilder) {}
1288 }
1289
1290 struct DrainingDestination;
1292
1293 #[async_trait]
1294 impl Destination for DrainingDestination {
1295 async fn run(self: Box<Self>, mut context: DestinationContext) -> Result<(), GenericError> {
1296 while context.events().next().await.is_some() {}
1297 Ok(())
1298 }
1299 }
1300
1301 struct DrainingDestinationBuilder {
1302 input_event_ty: EventType,
1303 }
1304
1305 #[async_trait]
1306 impl DestinationBuilder for DrainingDestinationBuilder {
1307 fn input_event_type(&self) -> EventType {
1308 self.input_event_ty
1309 }
1310
1311 async fn build(&self, _: BuildContext) -> Result<Box<dyn Destination + Send>, GenericError> {
1312 Ok(Box::new(DrainingDestination))
1313 }
1314 }
1315
1316 impl MemoryBounds for DrainingDestinationBuilder {
1317 fn specify_bounds(&self, _builder: &mut MemoryBoundsBuilder) {}
1318 }
1319
1320 struct StuckDestination {
1324 started: Arc<AtomicUsize>,
1325 }
1326
1327 #[async_trait]
1328 impl Destination for StuckDestination {
1329 async fn run(self: Box<Self>, _context: DestinationContext) -> Result<(), GenericError> {
1330 self.started.fetch_add(1, Ordering::SeqCst);
1331 std::future::pending::<()>().await;
1332 Ok(())
1333 }
1334 }
1335
1336 struct StuckDestinationBuilder {
1337 input_event_ty: EventType,
1338 started: Arc<AtomicUsize>,
1339 }
1340
1341 #[async_trait]
1342 impl DestinationBuilder for StuckDestinationBuilder {
1343 fn input_event_type(&self) -> EventType {
1344 self.input_event_ty
1345 }
1346
1347 async fn build(&self, _: BuildContext) -> Result<Box<dyn Destination + Send>, GenericError> {
1348 Ok(Box::new(StuckDestination {
1349 started: Arc::clone(&self.started),
1350 }))
1351 }
1352 }
1353
1354 impl MemoryBounds for StuckDestinationBuilder {
1355 fn specify_bounds(&self, _builder: &mut MemoryBoundsBuilder) {}
1356 }
1357
1358 fn long_running_blueprint(spawned_child: Option<Arc<AtomicUsize>>) -> (TopologyBlueprint, Arc<AtomicUsize>) {
1366 let source_started = Arc::new(AtomicUsize::new(0));
1367 let component_registry = ComponentRegistry::default();
1368 let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1369 blueprint
1370 .add_source(
1371 "source",
1372 ControlSourceBuilder::new(Arc::clone(&source_started), spawned_child),
1373 )
1374 .expect("should not fail to add source")
1375 .add_destination(
1376 "destination",
1377 DrainingDestinationBuilder {
1378 input_event_ty: EventType::EventD,
1379 },
1380 )
1381 .expect("should not fail to add destination");
1382 blueprint
1383 .connect_components_in_order(["source", "destination"])
1384 .expect("should not fail to connect components");
1385 blueprint
1386 .with_health_registry(HealthRegistry::new())
1387 .with_memory_limiter(MemoryLimiter::noop())
1388 .with_resource_registry(ResourceRegistry::new());
1389 (blueprint, source_started)
1390 }
1391
1392 fn stuck_destination_blueprint(shutdown_timeout: Duration) -> (TopologyBlueprint, Arc<AtomicUsize>) {
1401 let destination_started = Arc::new(AtomicUsize::new(0));
1402 let component_registry = ComponentRegistry::default();
1403 let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1404 blueprint
1405 .add_source("source", ControlSourceBuilder::new(Arc::new(AtomicUsize::new(0)), None))
1406 .expect("should not fail to add source")
1407 .add_destination(
1408 "destination",
1409 StuckDestinationBuilder {
1410 input_event_ty: EventType::EventD,
1411 started: Arc::clone(&destination_started),
1412 },
1413 )
1414 .expect("should not fail to add destination");
1415 blueprint
1416 .connect_components_in_order(["source", "destination"])
1417 .expect("should not fail to connect components");
1418 blueprint
1419 .with_health_registry(HealthRegistry::new())
1420 .with_memory_limiter(MemoryLimiter::noop())
1421 .with_resource_registry(ResourceRegistry::new())
1422 .with_shutdown_timeout(shutdown_timeout);
1423 (blueprint, destination_started)
1424 }
1425
1426 fn spawn_supervised_blueprint(
1432 blueprint: TopologyBlueprint,
1433 ) -> (
1434 oneshot::Sender<()>,
1435 tokio::task::JoinHandle<Result<(), SupervisorError>>,
1436 ) {
1437 let mut supervisor = Supervisor::new("test-topology").expect("should not fail to create supervisor");
1438 supervisor.add_worker(blueprint);
1439
1440 let (tx, rx) = oneshot::channel::<()>();
1441 let handle = tokio::spawn(async move { supervisor.run_with_shutdown(rx).await });
1442 (tx, handle)
1443 }
1444
1445 async fn run_blueprint_until_exit(
1448 blueprint: TopologyBlueprint, strategy: RestartStrategy,
1449 ) -> Result<(), SupervisorError> {
1450 let mut supervisor = Supervisor::new("test-topology")
1452 .expect("should not fail to create supervisor")
1453 .with_restart_strategy(strategy);
1454 supervisor.add_worker(runtime::supervisable(blueprint).needed().build());
1455
1456 let (_tx, rx) = oneshot::channel::<()>();
1458 tokio::time::timeout(Duration::from_secs(5), supervisor.run_with_shutdown(rx))
1459 .await
1460 .expect("supervisor should exit promptly")
1461 }
1462
1463 async fn join_topology(
1465 handle: tokio::task::JoinHandle<Result<(), SupervisorError>>,
1466 ) -> Result<(), SupervisorError> {
1467 tokio::time::timeout(Duration::from_secs(5), handle)
1468 .await
1469 .expect("supervisor should exit promptly")
1470 .expect("supervisor task should not panic")
1471 }
1472
1473 fn blueprint_with_components() -> TopologyBlueprint {
1477 let component_registry = ComponentRegistry::default();
1478 let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1479
1480 blueprint
1481 .add_source("source", TestSourceBuilder::default_output(EventType::EventD))
1482 .expect("should not fail to add source")
1483 .add_transform(
1484 "transform",
1485 TestTransformBuilder::default_output(EventType::EventD, EventType::EventD),
1486 )
1487 .expect("should not fail to add transform")
1488 .add_destination(
1489 "destination",
1490 TestDestinationBuilder::with_input_type(EventType::EventD),
1491 )
1492 .expect("should not fail to add destination");
1493
1494 blueprint
1495 }
1496
1497 fn blueprint_with_sources_and_destinations(source_ids: &[&str], destination_ids: &[&str]) -> TopologyBlueprint {
1502 let component_registry = ComponentRegistry::default();
1503 let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1504
1505 for source_id in source_ids {
1506 blueprint
1507 .add_source(*source_id, TestSourceBuilder::default_output(EventType::EventD))
1508 .expect("should not fail to add source");
1509 }
1510
1511 for destination_id in destination_ids {
1512 blueprint
1513 .add_destination(
1514 *destination_id,
1515 TestDestinationBuilder::with_input_type(EventType::EventD),
1516 )
1517 .expect("should not fail to add destination");
1518 }
1519
1520 blueprint
1521 }
1522
1523 fn connected_pairs(blueprint: &TopologyBlueprint) -> Vec<(String, String)> {
1525 let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
1526 let outbound_edges = guard
1527 .as_ref()
1528 .expect("topology blueprint already initialized")
1529 .graph
1530 .get_outbound_directed_edges();
1531
1532 let mut pairs = Vec::new();
1533 for (from, outputs) in &outbound_edges {
1534 for targets in outputs.values() {
1535 for to in targets {
1536 pairs.push((from.component_id().to_string(), to.component_id().to_string()));
1537 }
1538 }
1539 }
1540 pairs.sort();
1541 pairs
1542 }
1543
1544 #[test]
1545 fn connect_components_in_order_errors_with_fewer_than_two_ids() {
1546 let mut blueprint = blueprint_with_components();
1547
1548 let result = blueprint.connect_components_in_order(Vec::<&str>::new()).map(|_| ());
1550 assert!(result.is_err());
1551
1552 let result = blueprint.connect_components_in_order(["source"]).map(|_| ());
1554 assert!(result.is_err());
1555
1556 assert!(connected_pairs(&blueprint).is_empty());
1558 }
1559
1560 #[test]
1561 fn connect_components_in_order_connects_pairwise_left_to_right() {
1562 let mut blueprint = blueprint_with_components();
1563
1564 blueprint
1565 .connect_components_in_order(["source", "transform", "destination"])
1566 .expect("should not fail to connect components in order");
1567
1568 assert_eq!(
1571 connected_pairs(&blueprint),
1572 vec![
1573 ("source".to_string(), "transform".to_string()),
1574 ("transform".to_string(), "destination".to_string()),
1575 ],
1576 );
1577 }
1578
1579 #[test]
1580 fn connect_component_one_to_many_fans_out() {
1581 let mut blueprint = blueprint_with_sources_and_destinations(&["source"], &["dest_a", "dest_b"]);
1584
1585 blueprint
1586 .connect_components("source", ["dest_a", "dest_b"])
1587 .expect("should not fail to connect component");
1588
1589 assert_eq!(
1590 connected_pairs(&blueprint),
1591 vec![
1592 ("source".to_string(), "dest_a".to_string()),
1593 ("source".to_string(), "dest_b".to_string()),
1594 ],
1595 );
1596 }
1597
1598 #[test]
1599 fn connect_component_many_to_one_fans_in() {
1600 let mut blueprint = blueprint_with_sources_and_destinations(&["source_a", "source_b"], &["dest"]);
1603
1604 blueprint
1605 .connect_components(["source_a", "source_b"], "dest")
1606 .expect("should not fail to connect component");
1607
1608 assert_eq!(
1609 connected_pairs(&blueprint),
1610 vec![
1611 ("source_a".to_string(), "dest".to_string()),
1612 ("source_b".to_string(), "dest".to_string()),
1613 ],
1614 );
1615 }
1616
1617 #[test]
1618 fn connect_component_many_to_many_creates_mesh() {
1619 let mut blueprint = blueprint_with_sources_and_destinations(&["source_a", "source_b"], &["dest_a", "dest_b"]);
1622
1623 blueprint
1624 .connect_components(["source_a", "source_b"], ["dest_a", "dest_b"])
1625 .expect("should not fail to connect component");
1626
1627 assert_eq!(
1628 connected_pairs(&blueprint),
1629 vec![
1630 ("source_a".to_string(), "dest_a".to_string()),
1631 ("source_a".to_string(), "dest_b".to_string()),
1632 ("source_b".to_string(), "dest_a".to_string()),
1633 ("source_b".to_string(), "dest_b".to_string()),
1634 ],
1635 );
1636 }
1637
1638 fn connected_blueprint() -> TopologyBlueprint {
1640 let mut blueprint = blueprint_with_components();
1641 blueprint
1642 .connect_components_in_order(["source", "transform", "destination"])
1643 .expect("should not fail to connect components");
1644 blueprint
1645 }
1646
1647 #[tokio::test]
1648 async fn topology_failure_shuts_down_supervisor_without_a_restart() {
1649 let mut blueprint = connected_blueprint();
1657 blueprint
1658 .with_health_registry(HealthRegistry::new())
1659 .with_memory_limiter(MemoryLimiter::noop())
1660 .with_resource_registry(ResourceRegistry::new());
1661 assert!(!blueprint.can_restart());
1662
1663 let result = run_blueprint_until_exit(blueprint, RestartStrategy::default()).await;
1664
1665 assert!(
1666 matches!(result, Err(SupervisorError::SignificantChildExited)),
1667 "the topology failure should stop the supervisor: {result:?}"
1668 );
1669 }
1670
1671 #[tokio::test]
1672 async fn topology_waits_for_environment_readiness_before_starting() {
1673 let gate_reached = Arc::new(AtomicUsize::new(0));
1680 let gate = {
1681 let gate_reached = Arc::clone(&gate_reached);
1682 async move {
1683 gate_reached.fetch_add(1, Ordering::SeqCst);
1684 std::future::pending::<()>().await;
1685 }
1686 };
1687
1688 let mut blueprint = connected_blueprint();
1689 blueprint
1690 .with_health_registry(HealthRegistry::new())
1691 .with_memory_limiter(MemoryLimiter::noop())
1692 .with_resource_registry(ResourceRegistry::new())
1693 .with_environment_readiness(gate);
1694
1695 let (tx, handle) = spawn_supervised_blueprint(blueprint);
1696
1697 wait_until("the topology reached the readiness gate", || {
1700 gate_reached.load(Ordering::SeqCst) >= 1
1701 })
1702 .await;
1703 tx.send(()).expect("should send shutdown signal");
1704
1705 let result = join_topology(handle).await;
1706 assert!(result.is_ok(), "supervisor should shut down cleanly, got: {:?}", result);
1707 }
1708
1709 #[test]
1710 fn topology_ready_waits_for_registration_before_checking_readiness() {
1711 use tokio_test::{assert_pending, assert_ready, task::spawn};
1712
1713 let health_registry = HealthRegistry::new();
1714
1715 let mut other = health_registry
1718 .register_component(&SubsystemIdentifier::from_dotted("env_provider.workload.foo"))
1719 .expect("should register component");
1720 other.mark_ready();
1721
1722 let (registered_tx, registered_rx) = oneshot::channel();
1723 let topology_ready = TopologyReady {
1724 registered_rx,
1725 health_registry: health_registry.clone(),
1726 component_root: topology_identifier("primary"),
1727 };
1728
1729 let mut wait = spawn(topology_ready.wait());
1730
1731 assert_pending!(wait.poll());
1734
1735 let mut source = health_registry
1737 .register_component(&SubsystemIdentifier::from_dotted("topology.primary.sources.in"))
1738 .expect("should register component");
1739
1740 registered_tx.send(()).expect("receiver should be alive");
1743 assert_pending!(wait.poll());
1744
1745 source.mark_ready();
1747 assert!(assert_ready!(wait.poll()));
1748 }
1749
1750 #[tokio::test]
1751 async fn topology_ready_returns_false_when_torn_down_before_registration() {
1752 let health_registry = HealthRegistry::new();
1753
1754 let (registered_tx, registered_rx) = oneshot::channel::<()>();
1755 let topology_ready = TopologyReady {
1756 registered_rx,
1757 health_registry,
1758 component_root: topology_identifier("primary"),
1759 };
1760
1761 drop(registered_tx);
1764
1765 assert!(!topology_ready.wait().await);
1766 }
1767
1768 #[tokio::test]
1769 async fn topology_clean_shutdown_returns_ok() {
1770 let (blueprint, source_started) = long_running_blueprint(None);
1775 let (tx, handle) = spawn_supervised_blueprint(blueprint);
1776
1777 wait_until("the source has started", || source_started.load(Ordering::SeqCst) == 1).await;
1780 tx.send(()).expect("should send shutdown signal");
1781
1782 let result = join_topology(handle).await;
1783 assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1784 }
1785
1786 #[tokio::test]
1787 async fn topology_with_dynamic_condition_shuts_down_cleanly() {
1788 let (mut blueprint, source_started) = long_running_blueprint(None);
1791 let (condition_tx, condition_rx) = tokio::sync::watch::channel(false);
1792 blueprint
1793 .add_destination(
1794 "observer",
1795 DrainingDestinationBuilder {
1796 input_event_ty: EventType::EventD,
1797 },
1798 )
1799 .expect("should not fail to add destination")
1800 .connect_components_when("source", "observer", EdgeCondition::from_watch(condition_rx))
1801 .expect("should not fail to connect components");
1802 let (tx, handle) = spawn_supervised_blueprint(blueprint);
1803
1804 wait_until("the source has started", || source_started.load(Ordering::SeqCst) == 1).await;
1805 condition_tx
1806 .send(true)
1807 .expect("condition should still be watched while the topology runs");
1808 tx.send(()).expect("should send shutdown signal");
1809
1810 let result = join_topology(handle).await;
1811 assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1812 }
1813
1814 #[tokio::test]
1815 async fn component_can_spawn_dynamic_child_via_spawn_handle() {
1816 let child_started = Arc::new(AtomicUsize::new(0));
1821 let (blueprint, _source_started) = long_running_blueprint(Some(Arc::clone(&child_started)));
1822 let (tx, handle) = spawn_supervised_blueprint(blueprint);
1823
1824 wait_until("the dynamic child has started", || {
1826 child_started.load(Ordering::SeqCst) == 1
1827 })
1828 .await;
1829 assert_eq!(
1830 child_started.load(Ordering::SeqCst),
1831 1,
1832 "dynamic child should have started exactly once"
1833 );
1834
1835 tx.send(()).expect("should send shutdown signal");
1836 let result = join_topology(handle).await;
1837 assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1838 }
1839
1840 #[tokio::test]
1841 async fn each_component_runs_as_a_worker_named_by_its_canonical_identity() {
1842 let (blueprint, source_started) = long_running_blueprint(None);
1847
1848 let mut supervisor = Supervisor::new("test-topology").expect("should not fail to create supervisor");
1849 let tree = supervisor.tree_handle();
1850 supervisor.add_worker(blueprint);
1851 let (tx, rx) = oneshot::channel::<()>();
1852 let handle = tokio::spawn(async move { supervisor.run_with_shutdown(rx).await });
1853
1854 wait_until("the source has started", || source_started.load(Ordering::SeqCst) == 1).await;
1855
1856 fn find<'a>(node: &'a runtime::NodeSnapshot, name: &str) -> Option<&'a runtime::NodeSnapshot> {
1857 if node.name == name {
1858 return Some(node);
1859 }
1860 node.children.iter().find_map(|child| find(child, name))
1861 }
1862
1863 let root = tree.snapshot().root;
1864 let topology = find(&root, "topology.test").expect("the topology supervisor is in the tree");
1865 for (name, identity) in [
1866 ("sources.source", "topology.test.sources.source"),
1867 ("destinations.destination", "topology.test.destinations.destination"),
1868 ] {
1869 let component = topology
1870 .children
1871 .iter()
1872 .find(|child| child.name == name)
1873 .unwrap_or_else(|| panic!("{name} should run directly under the topology supervisor"));
1874 assert_eq!(component.kind, runtime::NodeKind::Worker);
1875 assert_eq!(component.process_name.as_deref(), Some(identity));
1876 assert_eq!(
1877 component.resource_group.as_deref(),
1878 Some(identity),
1879 "{name} should own its resource group"
1880 );
1881 }
1882
1883 tx.send(()).expect("should send shutdown signal");
1884 let result = join_topology(handle).await;
1885 assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1886 }
1887
1888 #[tokio::test]
1889 async fn work_spawned_while_a_component_is_built_belongs_to_the_component() {
1890 let source_started = Arc::new(AtomicUsize::new(0));
1895 let child_started = Arc::new(AtomicUsize::new(0));
1896 let child_stopped = Arc::new(AtomicUsize::new(0));
1897
1898 let component_registry = ComponentRegistry::default();
1899 let mut blueprint = TopologyBlueprint::new("test", &component_registry);
1900 blueprint
1901 .add_source(
1902 "spawner",
1903 BuildSpawningSourceBuilder {
1904 outputs: vec![OutputDefinition::default_output(EventType::EventD)],
1905 source_started: Arc::clone(&source_started),
1906 child_started: Arc::clone(&child_started),
1907 child_stopped: Arc::clone(&child_stopped),
1908 },
1909 )
1910 .expect("should not fail to add source")
1911 .add_destination(
1912 "destination",
1913 DrainingDestinationBuilder {
1914 input_event_ty: EventType::EventD,
1915 },
1916 )
1917 .expect("should not fail to add destination");
1918 blueprint
1919 .connect_components_in_order(["spawner", "destination"])
1920 .expect("should not fail to connect components");
1921 blueprint
1922 .with_health_registry(HealthRegistry::new())
1923 .with_memory_limiter(MemoryLimiter::noop())
1924 .with_resource_registry(ResourceRegistry::new());
1925
1926 let mut supervisor = Supervisor::new("test-topology").expect("should not fail to create supervisor");
1927 let tree = supervisor.tree_handle();
1928 supervisor.add_worker(blueprint);
1929 let (tx, rx) = oneshot::channel::<()>();
1930 let handle = tokio::spawn(async move { supervisor.run_with_shutdown(rx).await });
1931
1932 fn find<'a>(node: &'a runtime::NodeSnapshot, name: &str) -> Option<&'a runtime::NodeSnapshot> {
1933 if node.name == name {
1934 return Some(node);
1935 }
1936 node.children.iter().find_map(|child| find(child, name))
1937 }
1938
1939 wait_until("the child spawned while building runs beneath its component", || {
1941 let root = tree.snapshot().root;
1942 find(&root, "sources.spawner").is_some_and(|source| find(source, "built_child").is_some())
1943 })
1944 .await;
1945 assert_eq!(source_started.load(Ordering::SeqCst), 1);
1946 assert_eq!(child_started.load(Ordering::SeqCst), 1);
1947
1948 tx.send(()).expect("should send shutdown signal");
1949 let result = join_topology(handle).await;
1950 assert!(result.is_ok(), "topology should shut down cleanly, got: {:?}", result);
1951 assert_eq!(
1952 child_stopped.load(Ordering::SeqCst),
1953 1,
1954 "the child should have been stopped with its component"
1955 );
1956 }
1957
1958 #[tokio::test]
1959 async fn forced_abort_count_survives_topology_boundary_to_root() {
1960 let (blueprint, destination_started) = stuck_destination_blueprint(Duration::from_millis(100));
1970 let (tx, handle) = spawn_supervised_blueprint(blueprint);
1971
1972 wait_until("the stuck destination has started", || {
1975 destination_started.load(Ordering::SeqCst) == 1
1976 })
1977 .await;
1978 tx.send(()).expect("should send shutdown signal");
1979
1980 let result = join_topology(handle).await;
1981 assert!(
1982 matches!(result, Err(SupervisorError::ShutdownTimedOut { aborted: 1 })),
1983 "a component that ignored shutdown must surface as an unclean shutdown with a count of 1, got {result:?}"
1984 );
1985 }
1986
1987 #[test]
1988 fn component_identity_is_byte_identical_across_subsystems() {
1989 for (topology_name, raw_id) in [("primary", "dsd_in"), ("secondary", "dsd_agg")] {
1994 let topology_root = topology_identifier(topology_name);
1996 let component_context = ComponentContext::source(&topology_root, ComponentId::try_from(raw_id).unwrap());
1997 let component_canonical_id = component_context.identity().to_string();
1998 let component_relative_id =
1999 get_component_relative_identifier(component_context.component_type(), component_context.component_id());
2000
2001 assert_eq!(
2002 component_canonical_id,
2003 format!("topology.{topology_name}.sources.{raw_id}")
2004 );
2005
2006 let registry = ComponentRegistry::default();
2009 registry
2010 .bounds_builder(&component_context.identity())
2011 .firm()
2012 .with_fixed_amount("marker", 1);
2013
2014 let bounds = registry.as_bounds();
2015 let mut node = &bounds;
2016 for segment in component_canonical_id.split('.') {
2017 node = node
2018 .subcomponents()
2019 .into_iter()
2020 .find_map(|(name, child)| (name.as_str() == segment).then_some(child))
2021 .expect("resource-accounting node path must match the canonical identity segment by segment");
2022 }
2023 assert_eq!(
2024 node.total_firm_limit_bytes(),
2025 1,
2026 "the resource-accounting node at the canonical path must hold the declared bounds"
2027 );
2028
2029 let topology_sup = Name::root(topology_root.to_string()).expect("topology name is non-empty");
2032 let process_name =
2033 Name::scoped(&topology_sup, component_relative_id.to_string()).expect("component name is non-empty");
2034 assert_eq!(
2035 &*process_name,
2036 component_canonical_id.as_str(),
2037 "component worker process name must match the canonical identity"
2038 );
2039 }
2040 }
2041
2042 fn blueprint_with_observer() -> TopologyBlueprint {
2044 let mut blueprint = blueprint_with_components();
2045 blueprint
2046 .add_destination("observer", TestDestinationBuilder::with_input_type(EventType::EventD))
2047 .unwrap()
2048 .connect_components_in_order(["source", "transform", "destination"])
2049 .unwrap();
2050 blueprint
2051 }
2052
2053 fn component_id(id: &str) -> ComponentId {
2054 ComponentId::try_from(id).unwrap()
2055 }
2056
2057 fn firm_bound_bytes(blueprint: &TopologyBlueprint) -> usize {
2058 let guard = blueprint.build_state.lock().unwrap();
2059 guard
2060 .as_ref()
2061 .unwrap()
2062 .component_registry
2063 .as_bounds()
2064 .total_firm_limit_bytes()
2065 }
2066
2067 #[test]
2068 fn connection_with_false_condition_prunes_downstream_component() {
2069 let mut blueprint = blueprint_with_observer();
2073 let firm_before = firm_bound_bytes(&blueprint);
2074 blueprint
2075 .connect_components_when("source", "observer", EdgeCondition::fixed(false))
2076 .unwrap();
2077 let firm_after = firm_bound_bytes(&blueprint);
2078 assert!(firm_after < firm_before);
2079
2080 let mut guard = blueprint.build_state.lock().unwrap();
2081 let state = guard.as_mut().unwrap();
2082 state.prune_folded_components();
2083
2084 assert!(!state.destinations.contains_key(&component_id("observer")));
2085 assert!(state.destinations.contains_key(&component_id("destination")));
2086 assert!(state.graph.validate().is_ok());
2087 assert_eq!(
2088 state.component_registry.as_bounds().total_firm_limit_bytes(),
2089 firm_after
2090 );
2091 }
2092
2093 #[test]
2094 fn later_connection_keeps_folded_component() {
2095 let mut blueprint = blueprint_with_observer();
2098 blueprint
2099 .connect_components_when("source", "observer", EdgeCondition::fixed(false))
2100 .unwrap();
2101 let firm_folded = firm_bound_bytes(&blueprint);
2102 blueprint.connect_components("transform", "observer").unwrap();
2103 assert!(firm_bound_bytes(&blueprint) > firm_folded);
2104
2105 let mut guard = blueprint.build_state.lock().unwrap();
2106 let state = guard.as_mut().unwrap();
2107 state.prune_folded_components();
2108
2109 assert!(state.destinations.contains_key(&component_id("observer")));
2110 assert!(state.graph.validate().is_ok());
2111 }
2112
2113 #[test]
2114 fn pruned_decoder_is_excluded_from_event_buffer_bounds() {
2115 let with_pruned_decoder = {
2118 let mut blueprint = blueprint_with_observer();
2119 blueprint
2120 .add_relay("relay", TestRelayBuilder::default_output(PayloadType::Raw))
2121 .unwrap()
2122 .add_decoder(
2123 "decoder",
2124 TestDecoderBuilder::with_input_and_output_type(PayloadType::Raw, EventType::EventD),
2125 )
2126 .unwrap()
2127 .connect_components_when("relay", "decoder", EdgeCondition::fixed(false))
2128 .unwrap()
2129 .connect_components("decoder", "observer")
2130 .unwrap()
2131 .connect_components("source", "observer")
2132 .unwrap();
2133 blueprint
2134 };
2135 let without_decoder = {
2136 let mut blueprint = blueprint_with_observer();
2137 blueprint
2138 .add_relay("relay", TestRelayBuilder::default_output(PayloadType::Raw))
2139 .unwrap()
2140 .connect_components("source", "observer")
2141 .unwrap();
2142 blueprint
2143 };
2144
2145 assert_eq!(
2146 firm_bound_bytes(&with_pruned_decoder),
2147 firm_bound_bytes(&without_decoder)
2148 );
2149 }
2150
2151 #[test]
2152 fn connection_with_true_condition_is_a_normal_connection() {
2153 let mut blueprint = blueprint_with_observer();
2154 blueprint
2155 .connect_components_when("source", "observer", EdgeCondition::fixed(true))
2156 .unwrap();
2157
2158 let mut guard = blueprint.build_state.lock().unwrap();
2159 let state = guard.as_mut().unwrap();
2160 state.prune_folded_components();
2161
2162 assert!(state.destinations.contains_key(&component_id("observer")));
2163 assert!(state.edge_conditions.is_empty());
2164 assert!(state.graph.validate().is_ok());
2165 }
2166
2167 #[test]
2168 fn connection_with_dynamic_condition_keeps_downstream_component() {
2169 let mut blueprint = blueprint_with_observer();
2170 blueprint
2171 .connect_components_when(
2172 "source",
2173 "observer",
2174 EdgeCondition::dynamic(false, futures::stream::empty()),
2175 )
2176 .unwrap();
2177
2178 let mut guard = blueprint.build_state.lock().unwrap();
2179 let state = guard.as_mut().unwrap();
2180 state.prune_folded_components();
2181
2182 assert!(state.destinations.contains_key(&component_id("observer")));
2183 assert!(!state.edge_conditions.is_empty());
2184 assert!(state.graph.validate().is_ok());
2185 }
2186
2187 #[test]
2188 fn recalculate_bounds_accounts_for_interconnect_and_event_buffer_memory() {
2189 let interconnect_capacity = 4usize;
2194 let mut blueprint = blueprint_with_components();
2195 blueprint.with_interconnect_capacity(NonZeroUsize::new(interconnect_capacity).unwrap());
2196
2197 let (sources, transforms, destinations, decoders) = (1usize, 1usize, 1usize, 0usize);
2199
2200 let total_interconnect_capacity = interconnect_capacity * (transforms + destinations);
2203 let expected_min = total_interconnect_capacity * std::mem::size_of::<EventsBuffer>();
2204
2205 let max_in_flight = ((transforms + destinations) * interconnect_capacity) + sources + decoders + transforms;
2208 let per_buffer =
2209 std::mem::size_of::<EventsBuffer>() + (std::mem::size_of::<Event>() * DEFAULT_EVENTS_BUFFER_CAPACITY);
2210 let expected_firm = expected_min + (max_in_flight * per_buffer);
2211
2212 let bounds = {
2213 let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
2214 guard
2215 .as_ref()
2216 .expect("topology blueprint already initialized")
2217 .component_registry
2218 .as_bounds()
2219 };
2220
2221 assert_eq!(
2222 bounds.total_minimum_required_bytes(),
2223 expected_min,
2224 "interconnect minimum bytes should be capacity * non-source components * size_of::<EventsBuffer>()"
2225 );
2226 assert_eq!(
2227 bounds.total_firm_limit_bytes(),
2228 expected_firm,
2229 "firm bytes should add the max in-flight event-buffer memory on top of the minimum"
2230 );
2231 }
2232
2233 #[test]
2234 fn worker_pool_configuration_defaults_to_dedicated() {
2235 let blueprint = blueprint_with_components();
2236 let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
2237 let config = &guard
2238 .as_ref()
2239 .expect("topology blueprint already initialized")
2240 .worker_pool_config;
2241 assert!(
2242 matches!(config, WorkerPoolConfiguration::Dedicated),
2243 "the default worker-pool configuration must be dedicated"
2244 );
2245 }
2246
2247 #[test]
2248 fn with_ambient_worker_pool_selects_ambient() {
2249 let mut blueprint = blueprint_with_components();
2250 blueprint.with_ambient_worker_pool();
2251
2252 let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
2253 let config = &guard
2254 .as_ref()
2255 .expect("topology blueprint already initialized")
2256 .worker_pool_config;
2257 assert!(matches!(config, WorkerPoolConfiguration::Ambient));
2258 }
2259
2260 #[tokio::test]
2261 async fn with_explicit_worker_pool_selects_explicit() {
2262 let mut blueprint = blueprint_with_components();
2263 blueprint.with_explicit_worker_pool(tokio::runtime::Handle::current());
2264
2265 let guard = blueprint.build_state.lock().expect("topology blueprint mutex poisoned");
2266 let config = &guard
2267 .as_ref()
2268 .expect("topology blueprint already initialized")
2269 .worker_pool_config;
2270 assert!(matches!(config, WorkerPoolConfiguration::Explicit(_)));
2271 }
2272}