1use std::collections::{HashMap, HashSet};
2use std::io::Error;
3use std::marker::PhantomData;
4use std::pin::Pin;
5
6use bytes::{Bytes, BytesMut};
7use dfir_lang::graph::AsCodeOptions;
8use futures::{Sink, Stream};
9use proc_macro2::Span;
10use serde::Serialize;
11use serde::de::DeserializeOwned;
12use slotmap::{SecondaryMap, SlotMap, SparseSecondaryMap};
13
14use super::built::build_inner;
15use super::compiled::CompiledFlow;
16use super::deploy_provider::{
17 ClusterSpec, Deploy, ExternalSpec, IntoProcessSpec, Node, ProcessSpec, RegisterPort,
18 SupportsMemberId,
19};
20use super::ir::HydroRoot;
21use crate::live_collections::stream::{Ordering, Retries};
22use crate::location::dynamic::LocationId;
23use crate::location::external_process::{
24 ExternalBincodeBidi, ExternalBincodeSink, ExternalBincodeStream, ExternalBytesPort,
25};
26use crate::location::{Cluster, External, Location, LocationKey, LocationType, Process};
27use crate::staging_util::Invariant;
28use crate::telemetry::Sidecar;
29
30pub struct DeployFlow<'a, D>
31where
32 D: Deploy<'a>,
33{
34 pub(super) ir: Vec<HydroRoot>,
35
36 pub(super) locations: SlotMap<LocationKey, LocationType>,
37 pub(super) location_names: SecondaryMap<LocationKey, String>,
38 pub(super) cluster_id_types: SecondaryMap<LocationKey, syn::Type>,
39
40 pub(super) processes: SparseSecondaryMap<LocationKey, D::Process>,
42 pub(super) clusters: SparseSecondaryMap<LocationKey, D::Cluster>,
43 pub(super) externals: SparseSecondaryMap<LocationKey, D::External>,
44
45 pub(super) sidecars: Vec<super::builder::Sidecar>,
47
48 pub(super) clusters_reading_self_id: HashSet<LocationKey>,
50
51 pub(super) as_code_options: SparseSecondaryMap<LocationKey, AsCodeOptions>,
54
55 pub(super) flow_name: String,
57
58 pub(super) _phantom: Invariant<'a, D>,
59}
60
61impl<'a, D: Deploy<'a>> DeployFlow<'a, D> {
62 pub fn ir(&self) -> &Vec<HydroRoot> {
63 &self.ir
64 }
65
66 pub fn flow_name(&self) -> &str {
68 &self.flow_name
69 }
70
71 pub fn with_process<P>(
72 mut self,
73 process: &Process<'_, P>,
74 spec: impl IntoProcessSpec<'a, D>,
75 ) -> Self {
76 self.processes.insert(
77 process.key,
78 spec.into_process_spec()
79 .build(process.key, &self.location_names[process.key]),
80 );
81 self
82 }
83
84 #[doc(hidden)]
86 pub fn with_process_erased(
87 mut self,
88 process_loc_key: LocationKey,
89 spec: impl IntoProcessSpec<'a, D>,
90 ) -> Self {
91 assert_eq!(
92 Some(&LocationType::Process),
93 self.locations.get(process_loc_key),
94 "No process with the given `LocationKey` was found."
95 );
96 self.processes.insert(
97 process_loc_key,
98 spec.into_process_spec()
99 .build(process_loc_key, &self.location_names[process_loc_key]),
100 );
101 self
102 }
103
104 pub fn with_remaining_processes<S: IntoProcessSpec<'a, D> + 'a>(
105 mut self,
106 spec: impl Fn() -> S,
107 ) -> Self {
108 for (location_key, &location_type) in self.locations.iter() {
109 if LocationType::Process == location_type {
110 self.processes
111 .entry(location_key)
112 .expect("location was removed")
113 .or_insert_with(|| {
114 spec()
115 .into_process_spec()
116 .build(location_key, &self.location_names[location_key])
117 });
118 }
119 }
120 self
121 }
122
123 pub fn with_cluster<C, Id>(
124 mut self,
125 cluster: &Cluster<'_, C, Id>,
126 spec: impl ClusterSpec<'a, D>,
127 ) -> Self
128 where
129 D: SupportsMemberId<Id>,
130 {
131 self.clusters.insert(
132 cluster.key,
133 spec.build(cluster.key, &self.location_names[cluster.key]),
134 );
135 self
136 }
137
138 #[doc(hidden)]
140 pub fn with_cluster_erased(
141 mut self,
142 cluster_loc_key: LocationKey,
143 spec: impl ClusterSpec<'a, D>,
144 ) -> Self {
145 assert_eq!(
146 Some(&LocationType::Cluster),
147 self.locations.get(cluster_loc_key),
148 "No cluster with the given `LocationKey` was found."
149 );
150 self.clusters.insert(
151 cluster_loc_key,
152 spec.build(cluster_loc_key, &self.location_names[cluster_loc_key]),
153 );
154 self
155 }
156
157 pub fn with_remaining_clusters<S: ClusterSpec<'a, D> + 'a>(
158 mut self,
159 spec: impl Fn() -> S,
160 ) -> Self {
161 for (location_key, &location_type) in self.locations.iter() {
162 if LocationType::Cluster == location_type {
163 self.clusters
164 .entry(location_key)
165 .expect("location was removed")
166 .or_insert_with(|| {
167 spec().build(location_key, &self.location_names[location_key])
168 });
169 }
170 }
171 self
172 }
173
174 pub fn with_external<P>(
175 mut self,
176 external: &External<'_, P>,
177 spec: impl ExternalSpec<'a, D>,
178 ) -> Self {
179 self.externals.insert(
180 external.key,
181 spec.build(external.key, &self.location_names[external.key]),
182 );
183 self
184 }
185
186 pub fn with_remaining_externals<S: ExternalSpec<'a, D> + 'a>(
187 mut self,
188 spec: impl Fn() -> S,
189 ) -> Self {
190 for (location_key, &location_type) in self.locations.iter() {
191 if LocationType::External == location_type {
192 self.externals
193 .entry(location_key)
194 .expect("location was removed")
195 .or_insert_with(|| {
196 spec().build(location_key, &self.location_names[location_key])
197 });
198 }
199 }
200 self
201 }
202
203 pub fn with_sidecar_all(mut self, sidecar: &impl Sidecar) -> Self {
205 for (location_key, &location_type) in self.locations.iter() {
206 if !matches!(location_type, LocationType::Process | LocationType::Cluster) {
207 continue;
208 }
209
210 let location_name = &self.location_names[location_key];
211
212 sidecar.edit_as_code_options(
213 self.as_code_options
214 .entry(location_key)
215 .expect("location was removed")
216 .or_default(),
217 );
218
219 let future_expr = sidecar.to_expr(
220 self.flow_name(),
221 location_key,
222 location_type,
223 location_name,
224 "e::format_ident!("{}", super::DFIR_IDENT),
225 );
226 self.sidecars.push(super::builder::Sidecar::Simple {
227 location_key,
228 future_expr: Box::new(future_expr),
229 });
230 }
231
232 self
233 }
234
235 pub fn with_sidecar_internal(
237 mut self,
238 location_key: LocationKey,
239 sidecar: &impl Sidecar,
240 ) -> Self {
241 let location_type = self.locations[location_key];
242 let location_name = &self.location_names[location_key];
243 sidecar.edit_as_code_options(
244 self.as_code_options
245 .entry(location_key)
246 .expect("location was removed")
247 .or_default(),
248 );
249 let future_expr = sidecar.to_expr(
250 self.flow_name(),
251 location_key,
252 location_type,
253 location_name,
254 "e::format_ident!("{}", super::DFIR_IDENT),
255 );
256 self.sidecars.push(super::builder::Sidecar::Simple {
257 location_key,
258 future_expr: Box::new(future_expr),
259 });
260 self
261 }
262
263 pub fn with_sidecar_process(self, process: &Process<'_, ()>, sidecar: &impl Sidecar) -> Self {
265 self.with_sidecar_internal(process.key, sidecar)
266 }
267
268 pub fn with_sidecar_cluster<Id>(
270 self,
271 cluster: &Cluster<'_, (), Id>,
272 sidecar: &impl Sidecar,
273 ) -> Self {
274 self.with_sidecar_internal(cluster.key, sidecar)
275 }
276
277 pub fn preview_compile(&mut self) -> CompiledFlow<'a> {
282 CompiledFlow {
285 dfir: build_inner(&mut self.ir),
286 extra_stmts: SparseSecondaryMap::new(),
287 sidecars: SparseSecondaryMap::new(),
288 as_code_options: SparseSecondaryMap::new(),
289 _phantom: PhantomData,
290 }
291 }
292
293 pub fn compile(mut self) -> CompiledFlow<'a>
297 where
298 D: Deploy<'a, InstantiateEnv = ()>,
299 {
300 self.compile_internal(&mut ())
301 }
302
303 pub(super) fn compile_internal(&mut self, env: &mut D::InstantiateEnv) -> CompiledFlow<'a> {
307 let mut seen_tees: HashMap<_, _> = HashMap::new();
308 let mut seen_cluster_members = HashSet::new();
309 let mut extra_stmts = SparseSecondaryMap::new();
310 for leaf in self.ir.iter_mut() {
311 leaf.compile_network::<D>(
312 &mut extra_stmts,
313 &mut seen_tees,
314 &mut seen_cluster_members,
315 &self.processes,
316 &self.clusters,
317 &self.externals,
318 env,
319 );
320 }
321
322 let mut sidecars: SparseSecondaryMap<LocationKey, Vec<syn::Expr>> =
325 SparseSecondaryMap::new();
326 for decl in std::mem::take(&mut self.sidecars) {
327 match decl {
328 super::builder::Sidecar::Simple {
329 location_key,
330 future_expr,
331 } => {
332 sidecars
333 .entry(location_key)
334 .expect("location was removed")
335 .or_default()
336 .push(*future_expr);
337 }
338 super::builder::Sidecar::Bidi {
339 location_key,
340 sidecar_id,
341 sidecar_closure,
342 } => {
343 use syn::parse_quote;
344
345 let (stream_ident, sink_ident) = sidecar_id.idents();
346
347 let sidecar_closure_expr: &syn::Expr = &sidecar_closure;
348 let setup_stmt: syn::Stmt = parse_quote! {
349 let (#stream_ident, #sink_ident) = (#sidecar_closure_expr)();
350 };
351 extra_stmts
352 .entry(location_key)
353 .expect("location was removed")
354 .or_default()
355 .push(setup_stmt);
356 }
357 }
358 }
359
360 CompiledFlow {
361 dfir: build_inner(&mut self.ir),
362 extra_stmts,
363 sidecars,
364 as_code_options: std::mem::take(&mut self.as_code_options),
365 _phantom: PhantomData,
366 }
367 }
368
369 fn cluster_id_stmts(&self, extra_stmts: &mut SparseSecondaryMap<LocationKey, Vec<syn::Stmt>>) {
371 #[expect(
372 clippy::disallowed_methods,
373 reason = "nondeterministic iteration order, will be sorted"
374 )]
375 let mut all_clusters_sorted = self.clusters.keys().collect::<Vec<_>>();
376 all_clusters_sorted.sort();
377
378 for cluster_key in all_clusters_sorted {
379 let self_id_ident = syn::Ident::new(
380 &format!("__hydro_lang_cluster_self_id_{}", cluster_key),
381 Span::call_site(),
382 );
383 let self_id_expr = D::cluster_self_id();
384 extra_stmts
385 .entry(cluster_key)
386 .expect("location was removed")
387 .or_default()
388 .push(syn::parse_quote! {
389 let #self_id_ident = &*Box::leak(Box::new(#self_id_expr));
390 });
391
392 let process_cluster_locations = self.location_names.keys().filter(|&location_key| {
393 self.processes.contains_key(location_key)
394 || self.clusters.contains_key(location_key)
395 });
396 for other_location in process_cluster_locations {
397 let other_id_ident = syn::Ident::new(
398 &format!("__hydro_lang_cluster_ids_{}", cluster_key),
399 Span::call_site(),
400 );
401 let other_id_expr = D::cluster_ids(cluster_key);
402 extra_stmts
403 .entry(other_location)
404 .expect("location was removed")
405 .or_default()
406 .push(syn::parse_quote! {
407 let #other_id_ident = #other_id_expr;
408 });
409 }
410 }
411 }
412
413 #[must_use]
421 pub fn deploy(mut self, env: &mut D::InstantiateEnv) -> DeployResult<'a, D> {
422 let CompiledFlow {
423 dfir,
424 mut extra_stmts,
425 mut sidecars,
426 mut as_code_options,
427 _phantom,
428 } = self.compile_internal(env);
429
430 let mut compiled = dfir;
431 self.cluster_id_stmts(&mut extra_stmts);
432 let mut meta = D::Meta::default();
433
434 let (processes, clusters, externals) = (
435 self.processes
436 .into_iter()
437 .filter(|&(node_key, ref node)| {
438 if let Some(ir) = compiled.remove(node_key) {
439 let ir = ir.unwrap_or_else(|err| {
440 panic!(
441 "Failed to partition DFIR graph for location {node_key}: {}",
442 err.diagnostic
443 )
444 });
445 node.instantiate(
446 env,
447 &mut meta,
448 ir,
449 extra_stmts.remove(node_key).as_deref().unwrap_or_default(),
450 sidecars.remove(node_key).as_deref().unwrap_or_default(),
451 &as_code_options.remove(node_key).unwrap_or_default(),
452 );
453 true
454 } else {
455 false
456 }
457 })
458 .collect::<SparseSecondaryMap<_, _>>(),
459 self.clusters
460 .into_iter()
461 .filter(|&(cluster_key, ref cluster)| {
462 if let Some(ir) = compiled.remove(cluster_key) {
463 let ir = ir.unwrap_or_else(|err| {
464 panic!(
465 "Failed to partition DFIR graph for location {cluster_key}: {}",
466 err.diagnostic
467 )
468 });
469 cluster.instantiate(
470 env,
471 &mut meta,
472 ir,
473 extra_stmts
474 .remove(cluster_key)
475 .as_deref()
476 .unwrap_or_default(),
477 sidecars.remove(cluster_key).as_deref().unwrap_or_default(),
478 &as_code_options.remove(cluster_key).unwrap_or_default(),
479 );
480 true
481 } else {
482 false
483 }
484 })
485 .collect::<SparseSecondaryMap<_, _>>(),
486 self.externals
487 .into_iter()
488 .inspect(|&(external_key, ref external)| {
489 assert!(!extra_stmts.contains_key(external_key));
490 assert!(!sidecars.contains_key(external_key));
491 assert!(!as_code_options.contains_key(external_key));
492 external.instantiate(
493 env,
494 &mut meta,
495 Default::default(),
496 &[],
497 &[],
498 &Default::default(),
499 );
500 })
501 .collect::<SparseSecondaryMap<_, _>>(),
502 );
503
504 for location_key in self.locations.keys() {
505 if let Some(node) = processes.get(location_key) {
506 node.update_meta(&meta);
507 } else if let Some(cluster) = clusters.get(location_key) {
508 cluster.update_meta(&meta);
509 } else if let Some(external) = externals.get(location_key) {
510 external.update_meta(&meta);
511 }
512 }
513
514 let mut seen_tees_connect = HashMap::new();
515 for leaf in self.ir.iter_mut() {
516 leaf.connect_network(&mut seen_tees_connect);
517 }
518
519 DeployResult {
520 location_names: self.location_names,
521 processes,
522 clusters,
523 externals,
524 }
525 }
526}
527
528pub struct DeployResult<'a, D: Deploy<'a>> {
529 location_names: SecondaryMap<LocationKey, String>,
530 processes: SparseSecondaryMap<LocationKey, D::Process>,
531 clusters: SparseSecondaryMap<LocationKey, D::Cluster>,
532 externals: SparseSecondaryMap<LocationKey, D::External>,
533}
534
535impl<'a, D: Deploy<'a>> DeployResult<'a, D> {
536 pub fn get_process<P>(&self, p: &Process<'_, P>) -> &D::Process {
537 let LocationId::Process(location_key) = p.id() else {
538 panic!("Process ID expected")
539 };
540 self.processes.get(location_key).unwrap()
541 }
542
543 pub fn get_cluster<C, Id>(&self, c: &Cluster<'a, C, Id>) -> &D::Cluster {
544 let LocationId::Cluster(location_key) = c.id() else {
545 panic!("Cluster ID expected")
546 };
547 self.clusters.get(location_key).unwrap()
548 }
549
550 pub fn get_external<P>(&self, e: &External<'_, P>) -> &D::External {
551 self.externals.get(e.key).unwrap()
552 }
553
554 pub fn get_all_processes(&self) -> impl Iterator<Item = (LocationId, &str, &D::Process)> {
555 self.location_names
556 .iter()
557 .filter_map(|(location_key, location_name)| {
558 self.processes
559 .get(location_key)
560 .map(|process| (LocationId::Process(location_key), &**location_name, process))
561 })
562 }
563
564 pub fn get_all_clusters(&self) -> impl Iterator<Item = (LocationId, &str, &D::Cluster)> {
565 self.location_names
566 .iter()
567 .filter_map(|(location_key, location_name)| {
568 self.clusters
569 .get(location_key)
570 .map(|cluster| (LocationId::Cluster(location_key), &**location_name, cluster))
571 })
572 }
573
574 #[deprecated(note = "use `connect` instead")]
575 pub async fn connect_bytes<M>(
576 &self,
577 port: ExternalBytesPort<M>,
578 ) -> (
579 Pin<Box<dyn Stream<Item = Result<BytesMut, Error>>>>,
580 Pin<Box<dyn Sink<Bytes, Error = Error>>>,
581 ) {
582 self.connect(port).await
583 }
584
585 #[deprecated(note = "use `connect` instead")]
586 pub async fn connect_sink_bytes<M>(
587 &self,
588 port: ExternalBytesPort<M>,
589 ) -> Pin<Box<dyn Sink<Bytes, Error = Error>>> {
590 self.connect(port).await.1
591 }
592
593 pub async fn connect_bincode<
594 InT: Serialize + 'static,
595 OutT: DeserializeOwned + 'static,
596 Many,
597 >(
598 &self,
599 port: ExternalBincodeBidi<InT, OutT, Many>,
600 ) -> (
601 Pin<Box<dyn Stream<Item = OutT>>>,
602 Pin<Box<dyn Sink<InT, Error = Error>>>,
603 ) {
604 self.externals
605 .get(port.process_key)
606 .unwrap()
607 .as_bincode_bidi(port.port_id)
608 .await
609 }
610
611 #[deprecated(note = "use `connect` instead")]
612 pub async fn connect_sink_bincode<T: Serialize + DeserializeOwned + 'static, Many>(
613 &self,
614 port: ExternalBincodeSink<T, Many>,
615 ) -> Pin<Box<dyn Sink<T, Error = Error>>> {
616 self.connect(port).await
617 }
618
619 #[deprecated(note = "use `connect` instead")]
620 pub async fn connect_source_bytes(
621 &self,
622 port: ExternalBytesPort,
623 ) -> Pin<Box<dyn Stream<Item = Result<BytesMut, Error>>>> {
624 self.connect(port).await.0
625 }
626
627 #[deprecated(note = "use `connect` instead")]
628 pub async fn connect_source_bincode<
629 T: Serialize + DeserializeOwned + 'static,
630 O: Ordering,
631 R: Retries,
632 >(
633 &self,
634 port: ExternalBincodeStream<T, O, R>,
635 ) -> Pin<Box<dyn Stream<Item = T>>> {
636 self.connect(port).await
637 }
638
639 pub async fn connect<'b, P: ConnectableAsync<&'b Self>>(
640 &'b self,
641 port: P,
642 ) -> <P as ConnectableAsync<&'b Self>>::Output {
643 port.connect(self).await
644 }
645}
646
647#[cfg(stageleft_runtime)]
648#[cfg(feature = "deploy")]
649#[cfg_attr(docsrs, doc(cfg(feature = "deploy")))]
650impl DeployResult<'_, crate::deploy::HydroDeploy> {
651 pub fn raw_port<M>(
653 &self,
654 port: ExternalBytesPort<M>,
655 ) -> hydro_deploy::custom_service::CustomClientPort {
656 self.externals
657 .get(port.process_key)
658 .unwrap()
659 .raw_port(port.port_id)
660 }
661}
662
663pub trait ConnectableAsync<Ctx> {
664 type Output;
665
666 fn connect(self, ctx: Ctx) -> impl Future<Output = Self::Output>;
667}
668
669impl<'a, D: Deploy<'a>, M> ConnectableAsync<&DeployResult<'a, D>> for ExternalBytesPort<M> {
670 type Output = (
671 Pin<Box<dyn Stream<Item = Result<BytesMut, Error>>>>,
672 Pin<Box<dyn Sink<Bytes, Error = Error>>>,
673 );
674
675 async fn connect(self, ctx: &DeployResult<'a, D>) -> Self::Output {
676 ctx.externals
677 .get(self.process_key)
678 .unwrap()
679 .as_bytes_bidi(self.port_id)
680 .await
681 }
682}
683
684impl<'a, D: Deploy<'a>, T: DeserializeOwned + 'static, O: Ordering, R: Retries>
685 ConnectableAsync<&DeployResult<'a, D>> for ExternalBincodeStream<T, O, R>
686{
687 type Output = Pin<Box<dyn Stream<Item = T>>>;
688
689 async fn connect(self, ctx: &DeployResult<'a, D>) -> Self::Output {
690 ctx.externals
691 .get(self.process_key)
692 .unwrap()
693 .as_bincode_source(self.port_id)
694 .await
695 }
696}
697
698impl<'a, D: Deploy<'a>, T: Serialize + 'static, Many> ConnectableAsync<&DeployResult<'a, D>>
699 for ExternalBincodeSink<T, Many>
700{
701 type Output = Pin<Box<dyn Sink<T, Error = Error>>>;
702
703 async fn connect(self, ctx: &DeployResult<'a, D>) -> Self::Output {
704 ctx.externals
705 .get(self.process_key)
706 .unwrap()
707 .as_bincode_sink(self.port_id)
708 .await
709 }
710}