1use std::cell::RefCell;
4use std::collections::HashMap;
5use std::future::Future;
6use std::io::Error;
7use std::pin::Pin;
8use std::rc::Rc;
9use std::sync::Arc;
10
11use bytes::{Bytes, BytesMut};
12use dfir_lang::graph::{AsCodeOptions, DfirGraph};
13use futures::{Sink, SinkExt, Stream, StreamExt};
14use hydro_deploy::custom_service::CustomClientPort;
15use hydro_deploy::rust_crate::RustCrateService;
16use hydro_deploy::rust_crate::ports::{DemuxSink, RustCrateSink, RustCrateSource, TaggedSource};
17use hydro_deploy::rust_crate::tracing_options::TracingOptions;
18use hydro_deploy::{CustomService, Deployment, Host, RustCrate};
19use hydro_deploy_integration::{ConnectedSink, ConnectedSource};
20use nameof::name_of;
21use proc_macro2::Span;
22use serde::Serialize;
23use serde::de::DeserializeOwned;
24use slotmap::SparseSecondaryMap;
25use stageleft::{QuotedWithContext, RuntimeData};
26use syn::parse_quote;
27
28use super::deploy_runtime::*;
29use crate::compile::builder::ExternalPortId;
30use crate::compile::deploy_provider::{
31 ClusterSpec, Deploy, ExternalSpec, IntoProcessSpec, Node, ProcessSpec, RegisterPort,
32};
33use crate::compile::trybuild::generate::{
34 HYDRO_RUNTIME_FEATURES, LinkingMode, TrybuildConfig, create_graph_trybuild,
35};
36use crate::location::dynamic::LocationId;
37use crate::location::{LocationKey, NetworkHint};
38use crate::staging_util::get_this_crate;
39
40pub enum HydroDeploy {}
45
46impl crate::compile::deploy_provider::SupportsMemberId<u32> for HydroDeploy {}
48
49impl<'a> Deploy<'a> for HydroDeploy {
50 type Meta = SparseSecondaryMap<LocationKey, Vec<u32>>;
52 type InstantiateEnv = Deployment;
53
54 type Process = DeployNode;
55 type Cluster = DeployCluster;
56 type External = DeployExternal;
57
58 fn o2o_sink_source(
59 _env: &mut Self::InstantiateEnv,
60 _p1: &Self::Process,
61 p1_port: &<Self::Process as Node>::Port,
62 _p2: &Self::Process,
63 p2_port: &<Self::Process as Node>::Port,
64 _name: Option<&str>,
65 networking_info: &crate::networking::NetworkingInfo,
66 _external_types: Option<(&syn::Type, &syn::Type)>,
67 ) -> (syn::Expr, syn::Expr) {
68 match networking_info {
69 crate::networking::NetworkingInfo::Tcp {
70 fault: crate::networking::TcpFault::FailStop,
71 } => {}
72 _ => panic!("Unsupported networking info: {:?}", networking_info),
73 }
74 let p1_port = p1_port.as_str();
75 let p2_port = p2_port.as_str();
76 deploy_o2o(
77 RuntimeData::new("__hydro_lang_trybuild_cli"),
78 p1_port,
79 p2_port,
80 )
81 }
82
83 fn o2o_connect(
84 p1: &Self::Process,
85 p1_port: &<Self::Process as Node>::Port,
86 p2: &Self::Process,
87 p2_port: &<Self::Process as Node>::Port,
88 ) -> Box<dyn FnOnce()> {
89 let p1 = p1.clone();
90 let p1_port = p1_port.clone();
91 let p2 = p2.clone();
92 let p2_port = p2_port.clone();
93
94 Box::new(move || {
95 let self_underlying_borrow = p1.underlying.borrow();
96 let self_underlying = self_underlying_borrow.as_ref().unwrap();
97 let source_port = self_underlying.get_port(p1_port.clone());
98
99 let other_underlying_borrow = p2.underlying.borrow();
100 let other_underlying = other_underlying_borrow.as_ref().unwrap();
101 let recipient_port = other_underlying.get_port(p2_port.clone());
102
103 source_port.send_to(&recipient_port)
104 })
105 }
106
107 fn o2m_sink_source(
108 _env: &mut Self::InstantiateEnv,
109 _p1: &Self::Process,
110 p1_port: &<Self::Process as Node>::Port,
111 _c2: &Self::Cluster,
112 c2_port: &<Self::Cluster as Node>::Port,
113 _name: Option<&str>,
114 networking_info: &crate::networking::NetworkingInfo,
115 _external_types: Option<(&syn::Type, &syn::Type)>,
116 ) -> (syn::Expr, syn::Expr) {
117 match networking_info {
118 crate::networking::NetworkingInfo::Tcp {
119 fault: crate::networking::TcpFault::FailStop,
120 } => {}
121 _ => panic!("Unsupported networking info: {:?}", networking_info),
122 }
123 let p1_port = p1_port.as_str();
124 let c2_port = c2_port.as_str();
125 deploy_o2m(
126 RuntimeData::new("__hydro_lang_trybuild_cli"),
127 p1_port,
128 c2_port,
129 )
130 }
131
132 fn o2m_connect(
133 p1: &Self::Process,
134 p1_port: &<Self::Process as Node>::Port,
135 c2: &Self::Cluster,
136 c2_port: &<Self::Cluster as Node>::Port,
137 ) -> Box<dyn FnOnce()> {
138 let p1 = p1.clone();
139 let p1_port = p1_port.clone();
140 let c2 = c2.clone();
141 let c2_port = c2_port.clone();
142
143 Box::new(move || {
144 let self_underlying_borrow = p1.underlying.borrow();
145 let self_underlying = self_underlying_borrow.as_ref().unwrap();
146 let source_port = self_underlying.get_port(p1_port.clone());
147
148 let recipient_port = DemuxSink {
149 demux: c2
150 .members
151 .borrow()
152 .iter()
153 .enumerate()
154 .map(|(id, c)| {
155 (
156 id as u32,
157 Arc::new(c.underlying.get_port(c2_port.clone()))
158 as Arc<dyn RustCrateSink + 'static>,
159 )
160 })
161 .collect(),
162 };
163
164 source_port.send_to(&recipient_port)
165 })
166 }
167
168 fn m2o_sink_source(
169 _env: &mut Self::InstantiateEnv,
170 _c1: &Self::Cluster,
171 c1_port: &<Self::Cluster as Node>::Port,
172 _p2: &Self::Process,
173 p2_port: &<Self::Process as Node>::Port,
174 _name: Option<&str>,
175 networking_info: &crate::networking::NetworkingInfo,
176 _external_types: Option<(&syn::Type, &syn::Type)>,
177 ) -> (syn::Expr, syn::Expr) {
178 match networking_info {
179 crate::networking::NetworkingInfo::Tcp {
180 fault: crate::networking::TcpFault::FailStop,
181 } => {}
182 _ => panic!("Unsupported networking info: {:?}", networking_info),
183 }
184 let c1_port = c1_port.as_str();
185 let p2_port = p2_port.as_str();
186 deploy_m2o(
187 RuntimeData::new("__hydro_lang_trybuild_cli"),
188 c1_port,
189 p2_port,
190 )
191 }
192
193 fn m2o_connect(
194 c1: &Self::Cluster,
195 c1_port: &<Self::Cluster as Node>::Port,
196 p2: &Self::Process,
197 p2_port: &<Self::Process as Node>::Port,
198 ) -> Box<dyn FnOnce()> {
199 let c1 = c1.clone();
200 let c1_port = c1_port.clone();
201 let p2 = p2.clone();
202 let p2_port = p2_port.clone();
203
204 Box::new(move || {
205 let other_underlying_borrow = p2.underlying.borrow();
206 let other_underlying = other_underlying_borrow.as_ref().unwrap();
207 let recipient_port = other_underlying.get_port(p2_port.clone()).merge();
208
209 for (i, node) in c1.members.borrow().iter().enumerate() {
210 let source_port = node.underlying.get_port(c1_port.clone());
211
212 TaggedSource {
213 source: Arc::new(source_port),
214 tag: i as u32,
215 }
216 .send_to(&recipient_port);
217 }
218 })
219 }
220
221 fn m2m_sink_source(
222 _env: &mut Self::InstantiateEnv,
223 _c1: &Self::Cluster,
224 c1_port: &<Self::Cluster as Node>::Port,
225 _c2: &Self::Cluster,
226 c2_port: &<Self::Cluster as Node>::Port,
227 _name: Option<&str>,
228 networking_info: &crate::networking::NetworkingInfo,
229 _external_types: Option<(&syn::Type, &syn::Type)>,
230 ) -> (syn::Expr, syn::Expr) {
231 match networking_info {
232 crate::networking::NetworkingInfo::Tcp {
233 fault: crate::networking::TcpFault::FailStop,
234 } => {}
235 _ => panic!("Unsupported networking info: {:?}", networking_info),
236 }
237 let c1_port = c1_port.as_str();
238 let c2_port = c2_port.as_str();
239 deploy_m2m(
240 RuntimeData::new("__hydro_lang_trybuild_cli"),
241 c1_port,
242 c2_port,
243 )
244 }
245
246 fn m2m_connect(
247 c1: &Self::Cluster,
248 c1_port: &<Self::Cluster as Node>::Port,
249 c2: &Self::Cluster,
250 c2_port: &<Self::Cluster as Node>::Port,
251 ) -> Box<dyn FnOnce()> {
252 let c1 = c1.clone();
253 let c1_port = c1_port.clone();
254 let c2 = c2.clone();
255 let c2_port = c2_port.clone();
256
257 Box::new(move || {
258 for (i, sender) in c1.members.borrow().iter().enumerate() {
259 let source_port = sender.underlying.get_port(c1_port.clone());
260
261 let recipient_port = DemuxSink {
262 demux: c2
263 .members
264 .borrow()
265 .iter()
266 .enumerate()
267 .map(|(id, c)| {
268 (
269 id as u32,
270 Arc::new(c.underlying.get_port(c2_port.clone()).merge())
271 as Arc<dyn RustCrateSink + 'static>,
272 )
273 })
274 .collect(),
275 };
276
277 TaggedSource {
278 source: Arc::new(source_port),
279 tag: i as u32,
280 }
281 .send_to(&recipient_port);
282 }
283 })
284 }
285
286 fn e2o_many_source(
287 extra_stmts: &mut Vec<syn::Stmt>,
288 _p2: &Self::Process,
289 p2_port: &<Self::Process as Node>::Port,
290 codec_type: &syn::Type,
291 encode_type: &syn::Type,
292 shared_handle: String,
293 ) -> syn::Expr {
294 let connect_ident = syn::Ident::new(
295 &format!("__hydro_deploy_many_{}_connect", shared_handle),
296 Span::call_site(),
297 );
298 let source_ident = syn::Ident::new(
299 &format!("__hydro_deploy_many_{}_source", shared_handle),
300 Span::call_site(),
301 );
302 let sink_ident = syn::Ident::new(
303 &format!("__hydro_deploy_many_{}_sink", shared_handle),
304 Span::call_site(),
305 );
306 let membership_ident = syn::Ident::new(
307 &format!("__hydro_deploy_many_{}_membership", shared_handle),
308 Span::call_site(),
309 );
310
311 let root = get_this_crate();
312
313 extra_stmts.push(syn::parse_quote! {
314 let #connect_ident = __hydro_lang_trybuild_cli
315 .port(#p2_port)
316 .connect::<#root::runtime_support::hydro_deploy_integration::multi_connection::ConnectedMultiConnection<_, #encode_type, #codec_type>>();
317 });
318
319 extra_stmts.push(syn::parse_quote! {
320 let #source_ident = #connect_ident.source;
321 });
322
323 extra_stmts.push(syn::parse_quote! {
324 let #sink_ident = #connect_ident.sink;
325 });
326
327 extra_stmts.push(syn::parse_quote! {
328 let #membership_ident = #connect_ident.membership;
329 });
330
331 parse_quote!(#source_ident)
332 }
333
334 fn e2o_many_sink(shared_handle: String) -> syn::Expr {
335 let sink_ident = syn::Ident::new(
336 &format!("__hydro_deploy_many_{}_sink", shared_handle),
337 Span::call_site(),
338 );
339 parse_quote!(#sink_ident)
340 }
341
342 fn e2o_source(
343 extra_stmts: &mut Vec<syn::Stmt>,
344 _p1: &Self::External,
345 _p1_port: &<Self::External as Node>::Port,
346 _p2: &Self::Process,
347 p2_port: &<Self::Process as Node>::Port,
348 codec_type: &syn::Type,
349 encode_type: &syn::Type,
350 shared_handle: String,
351 ) -> syn::Expr {
352 let connect_ident = syn::Ident::new(
353 &format!("__hydro_deploy_{}_connect", shared_handle),
354 Span::call_site(),
355 );
356 let source_ident = syn::Ident::new(
357 &format!("__hydro_deploy_{}_source", shared_handle),
358 Span::call_site(),
359 );
360 let sink_ident = syn::Ident::new(
361 &format!("__hydro_deploy_{}_sink", shared_handle),
362 Span::call_site(),
363 );
364
365 let root = get_this_crate();
366
367 extra_stmts.push(syn::parse_quote! {
368 let #connect_ident = __hydro_lang_trybuild_cli
369 .port(#p2_port)
370 .connect::<#root::runtime_support::hydro_deploy_integration::single_connection::ConnectedSingleConnection<_, #encode_type, #codec_type>>();
371 });
372
373 extra_stmts.push(syn::parse_quote! {
374 let #source_ident = #connect_ident.source;
375 });
376
377 extra_stmts.push(syn::parse_quote! {
378 let #sink_ident = #connect_ident.sink;
379 });
380
381 parse_quote!(#source_ident)
382 }
383
384 fn e2o_connect(
385 p1: &Self::External,
386 p1_port: &<Self::External as Node>::Port,
387 p2: &Self::Process,
388 p2_port: &<Self::Process as Node>::Port,
389 _many: bool,
390 server_hint: NetworkHint,
391 ) -> Box<dyn FnOnce()> {
392 let p1 = p1.clone();
393 let p1_port = p1_port.clone();
394 let p2 = p2.clone();
395 let p2_port = p2_port.clone();
396
397 Box::new(move || {
398 let self_underlying_borrow = p1.underlying.borrow();
399 let self_underlying = self_underlying_borrow.as_ref().unwrap();
400 let source_port = self_underlying.declare_many_client();
401
402 let other_underlying_borrow = p2.underlying.borrow();
403 let other_underlying = other_underlying_borrow.as_ref().unwrap();
404 let recipient_port = other_underlying.get_port_with_hint(
405 p2_port.clone(),
406 match server_hint {
407 NetworkHint::Auto => hydro_deploy::PortNetworkHint::Auto,
408 NetworkHint::TcpPort(p) => hydro_deploy::PortNetworkHint::TcpPort(p),
409 },
410 );
411
412 source_port.send_to(&recipient_port);
413
414 p1.client_ports
415 .borrow_mut()
416 .insert(p1_port.clone(), source_port);
417 })
418 }
419
420 fn o2e_sink(
421 _p1: &Self::Process,
422 _p1_port: &<Self::Process as Node>::Port,
423 _p2: &Self::External,
424 _p2_port: &<Self::External as Node>::Port,
425 shared_handle: String,
426 ) -> syn::Expr {
427 let sink_ident = syn::Ident::new(
428 &format!("__hydro_deploy_{}_sink", shared_handle),
429 Span::call_site(),
430 );
431 parse_quote!(#sink_ident)
432 }
433
434 fn cluster_ids(of_cluster: LocationKey) -> syn::Expr {
435 cluster_members(RuntimeData::new("__hydro_lang_trybuild_cli"), of_cluster).splice_untyped()
436 }
437
438 fn cluster_self_id() -> syn::Expr {
439 cluster_self_id(RuntimeData::new("__hydro_lang_trybuild_cli")).splice_untyped()
440 }
441
442 fn cluster_membership_stream(
443 _env: &mut Self::InstantiateEnv,
444 _at_location: &LocationId,
445 location_id: &LocationId,
446 ) -> syn::Expr {
447 cluster_membership_stream(location_id).splice_untyped()
448 }
449}
450
451#[expect(missing_docs, reason = "TODO")]
452pub trait DeployCrateWrapper {
453 fn underlying(&self) -> Arc<RustCrateService>;
454
455 fn stdout(&self) -> tokio::sync::mpsc::UnboundedReceiver<String> {
456 self.underlying().stdout()
457 }
458
459 fn stderr(&self) -> tokio::sync::mpsc::UnboundedReceiver<String> {
460 self.underlying().stderr()
461 }
462
463 fn stdout_filter(
464 &self,
465 prefix: impl Into<String>,
466 ) -> tokio::sync::mpsc::UnboundedReceiver<String> {
467 self.underlying().stdout_filter(prefix.into())
468 }
469
470 fn stderr_filter(
471 &self,
472 prefix: impl Into<String>,
473 ) -> tokio::sync::mpsc::UnboundedReceiver<String> {
474 self.underlying().stderr_filter(prefix.into())
475 }
476}
477
478#[expect(missing_docs, reason = "TODO")]
479#[derive(Clone)]
480pub struct TrybuildHost {
481 host: Arc<dyn Host>,
482 display_name: Option<String>,
483 rustflags: Option<String>,
484 profile: Option<String>,
485 additional_hydro_features: Vec<String>,
486 features: Vec<String>,
487 tracing: Option<TracingOptions>,
488 build_envs: Vec<(String, String)>,
489 env: HashMap<String, String>,
490 pin_to_core: Option<usize>,
491 name_hint: Option<String>,
492 cluster_idx: Option<usize>,
493}
494
495impl From<Arc<dyn Host>> for TrybuildHost {
496 fn from(host: Arc<dyn Host>) -> Self {
497 Self {
498 host,
499 display_name: None,
500 rustflags: None,
501 profile: None,
502 additional_hydro_features: vec![],
503 features: vec![],
504 tracing: None,
505 build_envs: vec![],
506 env: HashMap::new(),
507 pin_to_core: None,
508 name_hint: None,
509 cluster_idx: None,
510 }
511 }
512}
513
514impl<H: Host + 'static> From<Arc<H>> for TrybuildHost {
515 fn from(host: Arc<H>) -> Self {
516 Self {
517 host,
518 display_name: None,
519 rustflags: None,
520 profile: None,
521 additional_hydro_features: vec![],
522 features: vec![],
523 tracing: None,
524 build_envs: vec![],
525 env: HashMap::new(),
526 pin_to_core: None,
527 name_hint: None,
528 cluster_idx: None,
529 }
530 }
531}
532
533#[expect(missing_docs, reason = "TODO")]
534impl TrybuildHost {
535 pub fn new(host: Arc<dyn Host>) -> Self {
536 Self {
537 host,
538 display_name: None,
539 rustflags: None,
540 profile: None,
541 additional_hydro_features: vec![],
542 features: vec![],
543 tracing: None,
544 build_envs: vec![],
545 env: HashMap::new(),
546 pin_to_core: None,
547 name_hint: None,
548 cluster_idx: None,
549 }
550 }
551
552 pub fn display_name(self, display_name: impl Into<String>) -> Self {
553 assert!(
554 self.display_name.is_none(),
555 "{} already set",
556 name_of!(display_name in Self)
557 );
558
559 Self {
560 display_name: Some(display_name.into()),
561 ..self
562 }
563 }
564
565 pub fn rustflags(self, rustflags: impl Into<String>) -> Self {
566 assert!(
567 self.rustflags.is_none(),
568 "{} already set",
569 name_of!(rustflags in Self)
570 );
571
572 Self {
573 rustflags: Some(rustflags.into()),
574 ..self
575 }
576 }
577
578 pub fn profile(self, profile: impl Into<String>) -> Self {
579 assert!(
580 self.profile.is_none(),
581 "{} already set",
582 name_of!(profile in Self)
583 );
584
585 Self {
586 profile: Some(profile.into()),
587 ..self
588 }
589 }
590
591 pub fn additional_hydro_features(
592 mut self,
593 additional_hydro_features: impl IntoIterator<Item = impl Into<String>>,
594 ) -> Self {
595 self.additional_hydro_features
596 .extend(additional_hydro_features.into_iter().map(Into::into));
597 self
598 }
599
600 pub fn additional_hydro_feature(mut self, feature: impl Into<String>) -> Self {
601 self.additional_hydro_features.push(feature.into());
602 self
603 }
604
605 pub fn features(mut self, features: impl IntoIterator<Item = impl Into<String>>) -> Self {
606 self.features.extend(features.into_iter().map(Into::into));
607 self
608 }
609
610 pub fn feature(mut self, feature: impl Into<String>) -> Self {
611 self.features.push(feature.into());
612 self
613 }
614
615 #[must_use]
616 pub fn tracing(self, tracing: TracingOptions) -> Self {
617 assert!(
618 self.tracing.is_none(),
619 "{} already set",
620 name_of!(tracing in Self)
621 );
622
623 Self {
624 tracing: Some(tracing),
625 ..self
626 }
627 }
628
629 pub fn build_env(self, key: impl Into<String>, value: impl Into<String>) -> Self {
630 Self {
631 build_envs: self
632 .build_envs
633 .into_iter()
634 .chain(std::iter::once((key.into(), value.into())))
635 .collect(),
636 ..self
637 }
638 }
639
640 pub fn env(self, key: impl Into<String>, value: impl Into<String>) -> Self {
641 let mut env = self.env;
642 env.insert(key.into(), value.into());
643 Self { env, ..self }
644 }
645
646 #[must_use]
647 pub fn pin_to_core(self, core: usize) -> Self {
648 Self {
649 pin_to_core: Some(core),
650 ..self
651 }
652 }
653}
654
655impl IntoProcessSpec<'_, HydroDeploy> for Arc<dyn Host> {
656 type ProcessSpec = TrybuildHost;
657 fn into_process_spec(self) -> TrybuildHost {
658 TrybuildHost {
659 host: self,
660 display_name: None,
661 rustflags: None,
662 profile: None,
663 additional_hydro_features: vec![],
664 features: vec![],
665 tracing: None,
666 build_envs: vec![],
667 env: HashMap::new(),
668 pin_to_core: None,
669 name_hint: None,
670 cluster_idx: None,
671 }
672 }
673}
674
675impl<H: Host + 'static> IntoProcessSpec<'_, HydroDeploy> for Arc<H> {
676 type ProcessSpec = TrybuildHost;
677 fn into_process_spec(self) -> TrybuildHost {
678 TrybuildHost {
679 host: self,
680 display_name: None,
681 rustflags: None,
682 profile: None,
683 additional_hydro_features: vec![],
684 features: vec![],
685 tracing: None,
686 build_envs: vec![],
687 env: HashMap::new(),
688 pin_to_core: None,
689 name_hint: None,
690 cluster_idx: None,
691 }
692 }
693}
694
695#[expect(missing_docs, reason = "TODO")]
696#[derive(Clone)]
697pub struct DeployExternal {
698 next_port: Rc<RefCell<usize>>,
699 host: Arc<dyn Host>,
700 underlying: Rc<RefCell<Option<Arc<CustomService>>>>,
701 client_ports: Rc<RefCell<HashMap<String, CustomClientPort>>>,
702 allocated_ports: Rc<RefCell<HashMap<ExternalPortId, String>>>,
703}
704
705impl DeployExternal {
706 pub(crate) fn raw_port(&self, external_port_id: ExternalPortId) -> CustomClientPort {
707 self.client_ports
708 .borrow()
709 .get(
710 self.allocated_ports
711 .borrow()
712 .get(&external_port_id)
713 .unwrap(),
714 )
715 .unwrap()
716 .clone()
717 }
718}
719
720impl<'a> RegisterPort<'a, HydroDeploy> for DeployExternal {
721 fn register(&self, external_port_id: ExternalPortId, port: Self::Port) {
722 assert!(
723 self.allocated_ports
724 .borrow_mut()
725 .insert(external_port_id, port.clone())
726 .is_none_or(|old| old == port)
727 );
728 }
729
730 fn as_bytes_bidi(
731 &self,
732 external_port_id: ExternalPortId,
733 ) -> impl Future<
734 Output = (
735 Pin<Box<dyn Stream<Item = Result<BytesMut, Error>>>>,
736 Pin<Box<dyn Sink<Bytes, Error = Error>>>,
737 ),
738 > + 'a {
739 let port = self.raw_port(external_port_id);
740
741 async move {
742 let (source, sink) = port.connect().await.into_source_sink();
743 (
744 Box::pin(source) as Pin<Box<dyn Stream<Item = Result<BytesMut, Error>>>>,
745 Box::pin(sink) as Pin<Box<dyn Sink<Bytes, Error = Error>>>,
746 )
747 }
748 }
749
750 fn as_bincode_bidi<InT, OutT>(
751 &self,
752 external_port_id: ExternalPortId,
753 ) -> impl Future<
754 Output = (
755 Pin<Box<dyn Stream<Item = OutT>>>,
756 Pin<Box<dyn Sink<InT, Error = Error>>>,
757 ),
758 > + 'a
759 where
760 InT: Serialize + 'static,
761 OutT: DeserializeOwned + 'static,
762 {
763 let port = self.raw_port(external_port_id);
764 async move {
765 let (source, sink) = port.connect().await.into_source_sink();
766 (
767 Box::pin(source.map(|item| bincode::deserialize(&item.unwrap()).unwrap()))
768 as Pin<Box<dyn Stream<Item = OutT>>>,
769 Box::pin(
770 sink.with(|item| async move { Ok(bincode::serialize(&item).unwrap().into()) }),
771 ) as Pin<Box<dyn Sink<InT, Error = Error>>>,
772 )
773 }
774 }
775
776 fn as_bincode_sink<T: Serialize + 'static>(
777 &self,
778 external_port_id: ExternalPortId,
779 ) -> impl Future<Output = Pin<Box<dyn Sink<T, Error = Error>>>> + 'a {
780 let port = self.raw_port(external_port_id);
781 async move {
782 let sink = port.connect().await.into_sink();
783 Box::pin(sink.with(|item| async move { Ok(bincode::serialize(&item).unwrap().into()) }))
784 as Pin<Box<dyn Sink<T, Error = Error>>>
785 }
786 }
787
788 fn as_bincode_source<T: DeserializeOwned + 'static>(
789 &self,
790 external_port_id: ExternalPortId,
791 ) -> impl Future<Output = Pin<Box<dyn Stream<Item = T>>>> + 'a {
792 let port = self.raw_port(external_port_id);
793 async move {
794 let source = port.connect().await.into_source();
795 Box::pin(source.map(|item| bincode::deserialize(&item.unwrap()).unwrap()))
796 as Pin<Box<dyn Stream<Item = T>>>
797 }
798 }
799}
800
801impl Node for DeployExternal {
802 type Port = String;
803 type Meta = SparseSecondaryMap<LocationKey, Vec<u32>>;
805 type InstantiateEnv = Deployment;
806
807 fn next_port(&self) -> Self::Port {
808 let next_port = *self.next_port.borrow();
809 *self.next_port.borrow_mut() += 1;
810
811 format!("port_{}", next_port)
812 }
813
814 fn instantiate(
815 &self,
816 env: &mut Self::InstantiateEnv,
817 _meta: &mut Self::Meta,
818 _graph: DfirGraph,
819 extra_stmts: &[syn::Stmt],
820 sidecars: &[syn::Expr],
821 _as_code_options: &AsCodeOptions,
822 ) {
823 assert!(extra_stmts.is_empty());
824 assert!(sidecars.is_empty());
825 let service = env.CustomService(self.host.clone(), vec![]);
826 *self.underlying.borrow_mut() = Some(service);
827 }
828
829 fn update_meta(&self, _meta: &Self::Meta) {}
830}
831
832impl ExternalSpec<'_, HydroDeploy> for Arc<dyn Host> {
833 fn build(self, _key: LocationKey, _name_hint: &str) -> DeployExternal {
834 DeployExternal {
835 next_port: Rc::new(RefCell::new(0)),
836 host: self,
837 underlying: Rc::new(RefCell::new(None)),
838 allocated_ports: Rc::new(RefCell::new(HashMap::new())),
839 client_ports: Rc::new(RefCell::new(HashMap::new())),
840 }
841 }
842}
843
844impl<H: Host + 'static> ExternalSpec<'_, HydroDeploy> for Arc<H> {
845 fn build(self, _key: LocationKey, _name_hint: &str) -> DeployExternal {
846 DeployExternal {
847 next_port: Rc::new(RefCell::new(0)),
848 host: self,
849 underlying: Rc::new(RefCell::new(None)),
850 allocated_ports: Rc::new(RefCell::new(HashMap::new())),
851 client_ports: Rc::new(RefCell::new(HashMap::new())),
852 }
853 }
854}
855
856pub(crate) enum CrateOrTrybuild {
857 Crate(RustCrate, Arc<dyn Host>),
858 Trybuild(TrybuildHost),
859}
860
861#[expect(missing_docs, reason = "TODO")]
862#[derive(Clone)]
863pub struct DeployNode {
864 next_port: Rc<RefCell<usize>>,
865 service_spec: Rc<RefCell<Option<CrateOrTrybuild>>>,
866 underlying: Rc<RefCell<Option<Arc<RustCrateService>>>>,
867}
868
869impl DeployCrateWrapper for DeployNode {
870 fn underlying(&self) -> Arc<RustCrateService> {
871 Arc::clone(self.underlying.borrow().as_ref().unwrap())
872 }
873}
874
875impl Node for DeployNode {
876 type Port = String;
877 type Meta = SparseSecondaryMap<LocationKey, Vec<u32>>;
879 type InstantiateEnv = Deployment;
880
881 fn next_port(&self) -> String {
882 let next_port = *self.next_port.borrow();
883 *self.next_port.borrow_mut() += 1;
884
885 format!("port_{}", next_port)
886 }
887
888 fn update_meta(&self, meta: &Self::Meta) {
889 let underlying_node = self.underlying.borrow();
890 underlying_node.as_ref().unwrap().update_meta(HydroMeta {
891 clusters: meta.clone(),
892 cluster_id: None,
893 });
894 }
895
896 fn instantiate(
897 &self,
898 env: &mut Self::InstantiateEnv,
899 _meta: &mut Self::Meta,
900 graph: DfirGraph,
901 extra_stmts: &[syn::Stmt],
902 sidecars: &[syn::Expr],
903 as_code_options: &AsCodeOptions,
904 ) {
905 let (service, host) = match self.service_spec.borrow_mut().take().unwrap() {
906 CrateOrTrybuild::Crate(c, host) => (c, host),
907 CrateOrTrybuild::Trybuild(trybuild) => {
908 let linking_mode = if !cfg!(target_os = "windows")
910 && trybuild.host.target_type() == hydro_deploy::HostTargetType::Local
911 && trybuild.rustflags.is_none()
912 {
913 LinkingMode::Dynamic
916 } else {
917 LinkingMode::Static
918 };
919 let (bin_name, config) = create_graph_trybuild(
920 graph,
921 extra_stmts,
922 sidecars,
923 as_code_options,
924 trybuild.name_hint.as_deref(),
925 crate::compile::trybuild::generate::DeployMode::HydroDeploy,
926 linking_mode,
927 );
928 let host = trybuild.host.clone();
929 (create_trybuild_service(trybuild, &config, &bin_name), host)
930 }
931 };
932
933 *self.underlying.borrow_mut() = Some(env.add_service(service, host));
934 }
935}
936
937#[expect(missing_docs, reason = "TODO")]
938#[derive(Clone)]
939pub struct DeployClusterNode {
940 underlying: Arc<RustCrateService>,
941}
942
943impl DeployCrateWrapper for DeployClusterNode {
944 fn underlying(&self) -> Arc<RustCrateService> {
945 self.underlying.clone()
946 }
947}
948#[expect(missing_docs, reason = "TODO")]
949#[derive(Clone)]
950pub struct DeployCluster {
951 key: LocationKey,
952 next_port: Rc<RefCell<usize>>,
953 cluster_spec: Rc<RefCell<Option<Vec<CrateOrTrybuild>>>>,
954 members: Rc<RefCell<Vec<DeployClusterNode>>>,
955 name_hint: Option<String>,
956}
957
958impl DeployCluster {
959 #[expect(missing_docs, reason = "TODO")]
960 pub fn members(&self) -> Vec<DeployClusterNode> {
961 self.members.borrow().clone()
962 }
963}
964
965impl Node for DeployCluster {
966 type Port = String;
967 type Meta = SparseSecondaryMap<LocationKey, Vec<u32>>;
969 type InstantiateEnv = Deployment;
970
971 fn next_port(&self) -> String {
972 let next_port = *self.next_port.borrow();
973 *self.next_port.borrow_mut() += 1;
974
975 format!("port_{}", next_port)
976 }
977
978 fn instantiate(
979 &self,
980 env: &mut Self::InstantiateEnv,
981 meta: &mut Self::Meta,
982 graph: DfirGraph,
983 extra_stmts: &[syn::Stmt],
984 sidecars: &[syn::Expr],
985 as_code_options: &AsCodeOptions,
986 ) {
987 let has_trybuild = self
988 .cluster_spec
989 .borrow()
990 .as_ref()
991 .unwrap()
992 .iter()
993 .any(|spec| matches!(spec, CrateOrTrybuild::Trybuild { .. }));
994
995 let linking_mode = if !cfg!(target_os = "windows")
997 && self
998 .cluster_spec
999 .borrow()
1000 .as_ref()
1001 .unwrap()
1002 .iter()
1003 .all(|spec| match spec {
1004 CrateOrTrybuild::Crate(_, _) => true, CrateOrTrybuild::Trybuild(t) => {
1006 t.host.target_type() == hydro_deploy::HostTargetType::Local
1007 && t.rustflags.is_none()
1008 }
1009 }) {
1010 LinkingMode::Dynamic
1012 } else {
1013 LinkingMode::Static
1014 };
1015
1016 let maybe_trybuild = if has_trybuild {
1017 Some(create_graph_trybuild(
1018 graph,
1019 extra_stmts,
1020 sidecars,
1021 as_code_options,
1022 self.name_hint.as_deref(),
1023 crate::compile::trybuild::generate::DeployMode::HydroDeploy,
1024 linking_mode,
1025 ))
1026 } else {
1027 None
1028 };
1029
1030 let cluster_nodes = self
1031 .cluster_spec
1032 .borrow_mut()
1033 .take()
1034 .unwrap()
1035 .into_iter()
1036 .map(|spec| {
1037 let (service, host) = match spec {
1038 CrateOrTrybuild::Crate(c, host) => (c, host),
1039 CrateOrTrybuild::Trybuild(trybuild) => {
1040 let (bin_name, config) = maybe_trybuild.as_ref().unwrap();
1041 let host = trybuild.host.clone();
1042 (create_trybuild_service(trybuild, config, bin_name), host)
1043 }
1044 };
1045
1046 env.add_service(service, host)
1047 })
1048 .collect::<Vec<_>>();
1049 meta.insert(self.key, (0..(cluster_nodes.len() as u32)).collect());
1050 *self.members.borrow_mut() = cluster_nodes
1051 .into_iter()
1052 .map(|n| DeployClusterNode { underlying: n })
1053 .collect();
1054 }
1055
1056 fn update_meta(&self, meta: &Self::Meta) {
1057 for (cluster_id, node) in self.members.borrow().iter().enumerate() {
1058 node.underlying.update_meta(HydroMeta {
1059 clusters: meta.clone(),
1060 cluster_id: Some(cluster_id as u32),
1061 });
1062 }
1063 }
1064}
1065
1066#[expect(missing_docs, reason = "TODO")]
1067#[derive(Clone)]
1068pub struct DeployProcessSpec(RustCrate, Arc<dyn Host>);
1069
1070impl DeployProcessSpec {
1071 #[expect(missing_docs, reason = "TODO")]
1072 pub fn new(t: RustCrate, host: Arc<dyn Host>) -> Self {
1073 Self(t, host)
1074 }
1075}
1076
1077impl ProcessSpec<'_, HydroDeploy> for DeployProcessSpec {
1078 fn build(self, _key: LocationKey, _name_hint: &str) -> DeployNode {
1079 DeployNode {
1080 next_port: Rc::new(RefCell::new(0)),
1081 service_spec: Rc::new(RefCell::new(Some(CrateOrTrybuild::Crate(self.0, self.1)))),
1082 underlying: Rc::new(RefCell::new(None)),
1083 }
1084 }
1085}
1086
1087impl ProcessSpec<'_, HydroDeploy> for TrybuildHost {
1088 fn build(mut self, key: LocationKey, name_hint: &str) -> DeployNode {
1089 self.name_hint = Some(format!("{} (process {})", name_hint, key));
1090 DeployNode {
1091 next_port: Rc::new(RefCell::new(0)),
1092 service_spec: Rc::new(RefCell::new(Some(CrateOrTrybuild::Trybuild(self)))),
1093 underlying: Rc::new(RefCell::new(None)),
1094 }
1095 }
1096}
1097
1098#[expect(missing_docs, reason = "TODO")]
1099#[derive(Clone)]
1100pub struct DeployClusterSpec(Vec<(RustCrate, Arc<dyn Host>)>);
1101
1102impl DeployClusterSpec {
1103 #[expect(missing_docs, reason = "TODO")]
1104 pub fn new(crates: Vec<(RustCrate, Arc<dyn Host>)>) -> Self {
1105 Self(crates)
1106 }
1107}
1108
1109impl ClusterSpec<'_, HydroDeploy> for DeployClusterSpec {
1110 fn build(self, key: LocationKey, _name_hint: &str) -> DeployCluster {
1111 DeployCluster {
1112 key,
1113 next_port: Rc::new(RefCell::new(0)),
1114 cluster_spec: Rc::new(RefCell::new(Some(
1115 self.0
1116 .into_iter()
1117 .map(|(c, h)| CrateOrTrybuild::Crate(c, h))
1118 .collect(),
1119 ))),
1120 members: Rc::new(RefCell::new(vec![])),
1121 name_hint: None,
1122 }
1123 }
1124}
1125
1126impl<T: Into<TrybuildHost>, I: IntoIterator<Item = T>> ClusterSpec<'_, HydroDeploy> for I {
1127 fn build(self, key: LocationKey, name_hint: &str) -> DeployCluster {
1128 let name_hint = format!("{} (cluster {})", name_hint, key);
1129 DeployCluster {
1130 key,
1131 next_port: Rc::new(RefCell::new(0)),
1132 cluster_spec: Rc::new(RefCell::new(Some(
1133 self.into_iter()
1134 .enumerate()
1135 .map(|(idx, b)| {
1136 let mut b = b.into();
1137 b.name_hint = Some(name_hint.clone());
1138 b.cluster_idx = Some(idx);
1139 CrateOrTrybuild::Trybuild(b)
1140 })
1141 .collect(),
1142 ))),
1143 members: Rc::new(RefCell::new(vec![])),
1144 name_hint: Some(name_hint),
1145 }
1146 }
1147}
1148
1149fn create_trybuild_service(
1150 trybuild: TrybuildHost,
1151 config: &TrybuildConfig,
1152 bin_name: &str,
1153) -> RustCrate {
1154 let dir = &config.project_dir;
1155 let crate_dir = match config.linking_mode {
1157 LinkingMode::Dynamic => dir.join("dylib-examples"),
1158 LinkingMode::Static => dir.clone(),
1159 };
1160
1161 let mut ret = RustCrate::new(&crate_dir, dir)
1162 .target_dir(&config.target_dir)
1163 .example(bin_name)
1164 .no_default_features();
1165
1166 if matches!(config.linking_mode, LinkingMode::Dynamic) {
1167 ret = ret.dylib_package(&config.dylib_package_name);
1168 }
1169
1170 if let Some(display_name) = trybuild.display_name {
1171 ret = ret.display_name(display_name);
1172 } else if let Some(name_hint) = trybuild.name_hint {
1173 if let Some(cluster_idx) = trybuild.cluster_idx {
1174 ret = ret.display_name(format!("{} / {}", name_hint, cluster_idx));
1175 } else {
1176 ret = ret.display_name(name_hint);
1177 }
1178 }
1179
1180 if let Some(rustflags) = trybuild.rustflags {
1181 ret = ret.rustflags(rustflags);
1182 }
1183
1184 if let Some(profile) = trybuild.profile {
1185 ret = ret.profile(profile);
1186 }
1187
1188 if let Some(tracing) = trybuild.tracing {
1189 ret = ret.tracing(tracing);
1190 }
1191
1192 if let Some(core) = trybuild.pin_to_core {
1193 ret = ret.pin_to_core(core);
1194 }
1195
1196 ret = ret.features(
1197 vec!["hydro___feature_deploy_integration".to_owned()]
1198 .into_iter()
1199 .chain(
1200 trybuild
1201 .additional_hydro_features
1202 .into_iter()
1203 .map(|runtime_feature| {
1204 assert!(
1205 HYDRO_RUNTIME_FEATURES.iter().any(|f| f == &runtime_feature),
1206 "{runtime_feature} is not a valid Hydro runtime feature"
1207 );
1208 format!("hydro___feature_{runtime_feature}")
1209 }),
1210 )
1211 .chain(trybuild.features),
1212 );
1213
1214 for (key, value) in trybuild.build_envs {
1215 ret = ret.build_env(key, value);
1216 }
1217
1218 for (key, value) in trybuild.env {
1219 ret = ret.env(key, value);
1220 }
1221
1222 ret = ret.build_env("STAGELEFT_TRYBUILD_BUILD_STAGED", "1");
1223 ret = ret.config("build.incremental = false");
1224
1225 if let Some(features) = config.features.as_deref() {
1226 ret = ret.features(features);
1227 }
1228
1229 ret
1230}