Skip to main content

hydro_lang/deploy/
deploy_graph_containerized_ecs.rs

1//! Deployment backend for ECS that generates manifests describing the binaries,
2//! ports, and service naming needed to package and orchestrate Hydro applications.
3
4use std::cell::RefCell;
5use std::collections::BTreeMap;
6use std::pin::Pin;
7use std::rc::Rc;
8
9use bytes::Bytes;
10use dfir_lang::graph::{AsCodeOptions, DfirGraph};
11use futures::{Sink, Stream};
12use proc_macro2::Span;
13use serde::{Deserialize, Serialize};
14use stageleft::QuotedWithContext;
15use syn::parse_quote;
16use tracing::{instrument, trace};
17
18/// Manifest for exporting - describes all processes, clusters, and their configuration
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct HydroManifest {
21    /// Process definitions (single-instance services)
22    pub processes: BTreeMap<String, ProcessManifest>,
23    /// Cluster definitions (multi-instance services)
24    pub clusters: BTreeMap<String, ClusterManifest>,
25}
26
27/// Information the build toolchain needs to compile a trybuild binary.
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct BuildConfig {
30    /// Path to the trybuild project directory
31    pub project_dir: String,
32    /// Path to the target directory
33    pub target_dir: String,
34    /// Example/binary name to build
35    pub bin_name: String,
36    /// Package name containing the example (for -p flag)
37    pub package_name: String,
38    /// Features to enable
39    pub features: Vec<String>,
40}
41
42/// Information about an exposed port.
43#[derive(Debug, Clone, Serialize, Deserialize)]
44#[serde(tag = "protocol", rename_all = "lowercase")]
45pub enum PortInfo {
46    /// A TCP listener.
47    Tcp {
48        /// The port number.
49        port: u16,
50    },
51}
52
53/// Manifest entry for a single process
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct ProcessManifest {
56    /// Build toolchain info for this binary
57    pub build: BuildConfig,
58    /// Ports that need to be exposed, keyed by external port identifier
59    pub ports: BTreeMap<String, PortInfo>,
60    /// Task family name (used for ECS service discovery)
61    pub task_family: String,
62}
63
64/// Manifest entry for a cluster (multiple instances of the same service)
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct ClusterManifest {
67    /// Build configuration for this cluster (same binary for all instances)
68    pub build: BuildConfig,
69    /// Ports that need to be exposed, keyed by external port identifier
70    pub ports: BTreeMap<String, PortInfo>,
71    /// Default number of instances
72    pub default_count: usize,
73    /// Task family prefix (instances will be named {prefix}-0, {prefix}-1, etc.)
74    pub task_family_prefix: String,
75}
76
77use super::deploy_runtime_containerized_ecs::*;
78use crate::compile::builder::ExternalPortId;
79use crate::compile::deploy::DeployResult;
80use crate::compile::deploy_provider::{
81    ClusterSpec, Deploy, ExternalSpec, Node, ProcessSpec, RegisterPort,
82};
83use crate::compile::trybuild::generate::create_graph_trybuild;
84use crate::location::dynamic::LocationId;
85use crate::location::{LocationKey, NetworkHint};
86
87/// Represents a process running in an ecs deployment
88#[derive(Clone)]
89pub struct EcsDeployProcess {
90    id: LocationKey,
91    name: String,
92    next_port: Rc<RefCell<u16>>,
93
94    exposed_ports: Rc<RefCell<BTreeMap<String, PortInfo>>>,
95
96    trybuild_config:
97        Rc<RefCell<Option<(String, crate::compile::trybuild::generate::TrybuildConfig)>>>,
98}
99
100impl Node for EcsDeployProcess {
101    type Port = u16;
102    type Meta = ();
103    type InstantiateEnv = EcsDeploy;
104
105    #[instrument(level = "trace", skip_all, ret, fields(id = %self.id, name = self.name))]
106    fn next_port(&self) -> Self::Port {
107        let port = {
108            let mut borrow = self.next_port.borrow_mut();
109            let port = *borrow;
110            *borrow += 1;
111            port
112        };
113
114        port
115    }
116
117    #[instrument(level = "trace", skip_all, fields(id = %self.id, name = self.name))]
118    fn update_meta(&self, _meta: &Self::Meta) {}
119
120    #[instrument(level = "trace", skip_all, fields(id = %self.id, name = self.name, ?meta, extra_stmts = extra_stmts.len()))]
121    fn instantiate(
122        &self,
123        _env: &mut Self::InstantiateEnv,
124        meta: &mut Self::Meta,
125        graph: DfirGraph,
126        extra_stmts: &[syn::Stmt],
127        sidecars: &[syn::Expr],
128        as_code_options: &AsCodeOptions,
129    ) {
130        let (bin_name, config) = create_graph_trybuild(
131            graph,
132            extra_stmts,
133            sidecars,
134            as_code_options,
135            Some(&self.name),
136            crate::compile::trybuild::generate::DeployMode::Containerized,
137            crate::compile::trybuild::generate::LinkingMode::Static,
138        );
139
140        // Store the trybuild config for export
141        *self.trybuild_config.borrow_mut() = Some((bin_name, config));
142    }
143}
144
145impl EcsDeployProcess {
146    /// Expose a TCP port on this process for external access.
147    ///
148    /// This method records the port in the manifest's `ports` map so that
149    /// downstream tooling (CDK, deployment scripts) can configure security
150    /// groups, load balancers, and service discovery accordingly.
151    pub fn expose_port(&self, port: u16) {
152        let port_name = format!("exposed-{}", port);
153        self.exposed_ports
154            .borrow_mut()
155            .insert(port_name, PortInfo::Tcp { port });
156    }
157}
158
159/// Represents a logical cluster, which can be a variable amount of individual containers.
160#[derive(Clone)]
161pub struct EcsDeployCluster {
162    id: LocationKey,
163    name: String,
164    next_port: Rc<RefCell<u16>>,
165
166    exposed_ports: Rc<RefCell<BTreeMap<String, PortInfo>>>,
167
168    count: usize,
169
170    /// Stored trybuild config for export
171    trybuild_config:
172        Rc<RefCell<Option<(String, crate::compile::trybuild::generate::TrybuildConfig)>>>,
173}
174
175impl Node for EcsDeployCluster {
176    type Port = u16;
177    type Meta = ();
178    type InstantiateEnv = EcsDeploy;
179
180    #[instrument(level = "trace", skip_all, ret, fields(id = %self.id, name = self.name))]
181    fn next_port(&self) -> Self::Port {
182        let port = {
183            let mut borrow = self.next_port.borrow_mut();
184            let port = *borrow;
185            *borrow += 1;
186            port
187        };
188
189        port
190    }
191
192    #[instrument(level = "trace", skip_all, fields(id = %self.id, name = self.name))]
193    fn update_meta(&self, _meta: &Self::Meta) {}
194
195    #[instrument(level = "trace", skip_all, fields(id = %self.id, name = self.name, extra_stmts = extra_stmts.len()))]
196    fn instantiate(
197        &self,
198        _env: &mut Self::InstantiateEnv,
199        _meta: &mut Self::Meta,
200        graph: DfirGraph,
201        extra_stmts: &[syn::Stmt],
202        sidecars: &[syn::Expr],
203        as_code_options: &AsCodeOptions,
204    ) {
205        let (bin_name, config) = create_graph_trybuild(
206            graph,
207            extra_stmts,
208            sidecars,
209            as_code_options,
210            Some(&self.name),
211            crate::compile::trybuild::generate::DeployMode::Containerized,
212            crate::compile::trybuild::generate::LinkingMode::Static,
213        );
214
215        // Store the trybuild config for export
216        *self.trybuild_config.borrow_mut() = Some((bin_name, config));
217    }
218}
219
220/// Represents an external process, outside the control of this deployment but still with some communication into this deployment.
221#[derive(Clone, Debug)]
222pub struct EcsDeployExternal {
223    name: String,
224    next_port: Rc<RefCell<u16>>,
225}
226
227impl Node for EcsDeployExternal {
228    type Port = u16;
229    type Meta = ();
230    type InstantiateEnv = EcsDeploy;
231
232    #[instrument(level = "trace", skip_all, ret, fields(name = self.name))]
233    fn next_port(&self) -> Self::Port {
234        let port = {
235            let mut borrow = self.next_port.borrow_mut();
236            let port = *borrow;
237            *borrow += 1;
238            port
239        };
240
241        port
242    }
243
244    #[instrument(level = "trace", skip_all, fields(name = self.name))]
245    fn update_meta(&self, _meta: &Self::Meta) {}
246
247    #[instrument(level = "trace", skip_all, fields(name = self.name, ?meta, extra_stmts = extra_stmts.len(), sidecars = sidecars.len()))]
248    fn instantiate(
249        &self,
250        _env: &mut Self::InstantiateEnv,
251        meta: &mut Self::Meta,
252        graph: DfirGraph,
253        extra_stmts: &[syn::Stmt],
254        sidecars: &[syn::Expr],
255        _as_code_options: &AsCodeOptions,
256    ) {
257        trace!(name: "surface", surface = graph.surface_syntax_string());
258    }
259}
260
261impl EcsDeployCluster {
262    /// Expose a TCP port on every member of this cluster for external access.
263    ///
264    /// The binary running on this cluster must bind a `TcpListener` on this port.
265    /// This method records the port in the manifest's `ports` map so that
266    /// downstream tooling (CDK, deployment scripts) can configure security
267    /// groups, load balancers, and service discovery accordingly.
268    pub fn expose_port(&self, port: u16) {
269        let port_name = format!("exposed-{}", port);
270        self.exposed_ports
271            .borrow_mut()
272            .insert(port_name, PortInfo::Tcp { port });
273    }
274}
275
276type DynSourceSink<Out, In, InErr> = (
277    Pin<Box<dyn Stream<Item = Out>>>,
278    Pin<Box<dyn Sink<In, Error = InErr>>>,
279);
280
281impl<'a> RegisterPort<'a, EcsDeploy> for EcsDeployExternal {
282    #[instrument(level = "trace", skip_all, fields(name = self.name, %external_port_id, %port))]
283    fn register(&self, external_port_id: ExternalPortId, port: Self::Port) {}
284
285    #[expect(clippy::manual_async_fn, reason = "matches trait signature")]
286    fn as_bytes_bidi(
287        &self,
288        _external_port_id: ExternalPortId,
289    ) -> impl Future<
290        Output = DynSourceSink<Result<bytes::BytesMut, std::io::Error>, Bytes, std::io::Error>,
291    > + 'a {
292        async { unimplemented!() }
293    }
294
295    #[expect(clippy::manual_async_fn, reason = "matches trait signature")]
296    fn as_bincode_bidi<InT, OutT>(
297        &self,
298        _external_port_id: ExternalPortId,
299    ) -> impl Future<Output = DynSourceSink<OutT, InT, std::io::Error>> + 'a
300    where
301        InT: Serialize + 'static,
302        OutT: serde::de::DeserializeOwned + 'static,
303    {
304        async { unimplemented!() }
305    }
306
307    #[expect(clippy::manual_async_fn, reason = "matches trait signature")]
308    fn as_bincode_sink<T>(
309        &self,
310        _external_port_id: ExternalPortId,
311    ) -> impl Future<Output = Pin<Box<dyn Sink<T, Error = std::io::Error>>>> + 'a
312    where
313        T: Serialize + 'static,
314    {
315        async { unimplemented!() }
316    }
317
318    #[expect(clippy::manual_async_fn, reason = "matches trait signature")]
319    fn as_bincode_source<T>(
320        &self,
321        _external_port_id: ExternalPortId,
322    ) -> impl Future<Output = Pin<Box<dyn Stream<Item = T>>>> + 'a
323    where
324        T: serde::de::DeserializeOwned + 'static,
325    {
326        async { unimplemented!() }
327    }
328}
329
330/// Represents an aws ecs deployment.
331pub struct EcsDeploy;
332
333impl Default for EcsDeploy {
334    fn default() -> Self {
335        Self::new()
336    }
337}
338
339impl EcsDeploy {
340    /// Creates a new ecs deployment.
341    pub fn new() -> Self {
342        Self
343    }
344
345    /// Add an internal ecs process to the deployment.
346    pub fn add_ecs_process(&mut self) -> EcsDeployProcessSpec {
347        EcsDeployProcessSpec
348    }
349
350    /// Add an internal ecs cluster to the deployment.
351    pub fn add_ecs_cluster(&mut self, count: usize) -> EcsDeployClusterSpec {
352        EcsDeployClusterSpec { count }
353    }
354
355    /// Add an external process to the deployment.
356    pub fn add_external(&self, name: String) -> EcsDeployExternalSpec {
357        EcsDeployExternalSpec { name }
358    }
359
360    /// Export a deployment manifest describing each process and cluster: its
361    /// binary name, exposed ports, and ECS task-family naming.
362    ///
363    /// The returned [`HydroManifest`] is typically serialized to JSON and
364    /// consumed by a build script (to compile the trybuild binaries) and a
365    /// deployment tool (CDK, custom scripts, etc.) to create container images
366    /// and orchestrate services.
367    #[instrument(level = "trace", skip_all)]
368    pub fn export(&self, nodes: &DeployResult<'_, Self>) -> HydroManifest {
369        let mut manifest = HydroManifest {
370            processes: BTreeMap::new(),
371            clusters: BTreeMap::new(),
372        };
373
374        // processes
375        for (location_id, name_hint, process) in nodes.get_all_processes() {
376            let LocationId::Process(_) = location_id else {
377                unreachable!()
378            };
379
380            let (bin_name, trybuild_config) = process
381                .trybuild_config
382                .borrow()
383                .clone()
384                .expect("trybuild_config should be set after instantiate");
385
386            manifest.processes.insert(
387                name_hint.to_owned(),
388                ProcessManifest {
389                    build: build_info_from_config(&bin_name, &trybuild_config),
390                    ports: process.exposed_ports.borrow().clone(),
391                    task_family: process.name.clone(),
392                },
393            );
394        }
395
396        // clusters
397        for (location_id, name_hint, cluster) in nodes.get_all_clusters() {
398            let LocationId::Cluster(_) = location_id else {
399                unreachable!()
400            };
401
402            let (bin_name, trybuild_config) = cluster
403                .trybuild_config
404                .borrow()
405                .clone()
406                .expect("trybuild_config should be set after instantiate");
407
408            manifest.clusters.insert(
409                name_hint.to_owned(),
410                ClusterManifest {
411                    build: build_info_from_config(&bin_name, &trybuild_config),
412                    ports: cluster.exposed_ports.borrow().clone(),
413                    default_count: cluster.count,
414                    task_family_prefix: cluster.name.clone(),
415                },
416            );
417        }
418
419        manifest
420    }
421}
422
423fn build_info_from_config(
424    bin_name: &str,
425    config: &crate::compile::trybuild::generate::TrybuildConfig,
426) -> BuildConfig {
427    let mut features = vec!["hydro___feature_ecs_runtime".to_owned()];
428    if let Some(extra) = &config.features {
429        features.extend(extra.clone());
430    }
431    let crate_name = config
432        .project_dir
433        .file_name()
434        .and_then(|n| n.to_str())
435        .unwrap_or("unknown")
436        .replace('_', "-");
437
438    let package_name = format!("{}-hydro-trybuild", crate_name);
439
440    BuildConfig {
441        project_dir: config.project_dir.to_string_lossy().into_owned(),
442        target_dir: config.target_dir.to_string_lossy().into_owned(),
443        bin_name: bin_name.to_owned(),
444        package_name,
445        features,
446    }
447}
448
449/// ECS names each cluster's members with `String`s.
450impl crate::compile::deploy_provider::SupportsMemberId<String> for EcsDeploy {}
451
452impl<'a> Deploy<'a> for EcsDeploy {
453    type InstantiateEnv = Self;
454    type Process = EcsDeployProcess;
455    type Cluster = EcsDeployCluster;
456    type External = EcsDeployExternal;
457    type Meta = ();
458
459    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port))]
460    fn o2o_sink_source(
461        _env: &mut Self::InstantiateEnv,
462        p1: &Self::Process,
463        p1_port: &<Self::Process as Node>::Port,
464        p2: &Self::Process,
465        p2_port: &<Self::Process as Node>::Port,
466        name: Option<&str>,
467        networking_info: &crate::networking::NetworkingInfo,
468        _external_types: Option<(&syn::Type, &syn::Type)>,
469    ) -> (syn::Expr, syn::Expr) {
470        match networking_info {
471            crate::networking::NetworkingInfo::Tcp {
472                fault: crate::networking::TcpFault::FailStop,
473            } => {}
474            _ => panic!("Unsupported networking info: {:?}", networking_info),
475        }
476
477        deploy_containerized_o2o(
478            &p2.name,
479            name.expect("channel name is required for containerized deployment"),
480        )
481    }
482
483    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port))]
484    fn o2o_connect(
485        p1: &Self::Process,
486        p1_port: &<Self::Process as Node>::Port,
487        p2: &Self::Process,
488        p2_port: &<Self::Process as Node>::Port,
489    ) -> Box<dyn FnOnce()> {
490        let serialized = format!(
491            "o2o_connect {}:{p1_port:?} -> {}:{p2_port:?}",
492            p1.name, p2.name
493        );
494
495        Box::new(move || {
496            trace!(name: "o2o_connect thunk", %serialized);
497        })
498    }
499
500    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, c2 = c2.name, %c2_port))]
501    fn o2m_sink_source(
502        _env: &mut Self::InstantiateEnv,
503        p1: &Self::Process,
504        p1_port: &<Self::Process as Node>::Port,
505        c2: &Self::Cluster,
506        c2_port: &<Self::Cluster as Node>::Port,
507        name: Option<&str>,
508        networking_info: &crate::networking::NetworkingInfo,
509        _external_types: Option<(&syn::Type, &syn::Type)>,
510    ) -> (syn::Expr, syn::Expr) {
511        match networking_info {
512            crate::networking::NetworkingInfo::Tcp {
513                fault: crate::networking::TcpFault::FailStop,
514            } => {}
515            _ => panic!("Unsupported networking info: {:?}", networking_info),
516        }
517
518        deploy_containerized_o2m(
519            name.expect("channel name is required for containerized deployment"),
520        )
521    }
522
523    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, c2 = c2.name, %c2_port))]
524    fn o2m_connect(
525        p1: &Self::Process,
526        p1_port: &<Self::Process as Node>::Port,
527        c2: &Self::Cluster,
528        c2_port: &<Self::Cluster as Node>::Port,
529    ) -> Box<dyn FnOnce()> {
530        let serialized = format!(
531            "o2m_connect {}:{p1_port:?} -> {}:{c2_port:?}",
532            p1.name, c2.name
533        );
534
535        Box::new(move || {
536            trace!(name: "o2m_connect thunk", %serialized);
537        })
538    }
539
540    #[instrument(level = "trace", skip_all, fields(c1 = c1.name, %c1_port, p2 = p2.name, %p2_port))]
541    fn m2o_sink_source(
542        _env: &mut Self::InstantiateEnv,
543        c1: &Self::Cluster,
544        c1_port: &<Self::Cluster as Node>::Port,
545        p2: &Self::Process,
546        p2_port: &<Self::Process as Node>::Port,
547        name: Option<&str>,
548        networking_info: &crate::networking::NetworkingInfo,
549        _external_types: Option<(&syn::Type, &syn::Type)>,
550    ) -> (syn::Expr, syn::Expr) {
551        match networking_info {
552            crate::networking::NetworkingInfo::Tcp {
553                fault: crate::networking::TcpFault::FailStop,
554            } => {}
555            _ => panic!("Unsupported networking info: {:?}", networking_info),
556        }
557
558        deploy_containerized_m2o(
559            &p2.name,
560            name.expect("channel name is required for containerized deployment"),
561        )
562    }
563
564    #[instrument(level = "trace", skip_all, fields(c1 = c1.name, %c1_port, p2 = p2.name, %p2_port))]
565    fn m2o_connect(
566        c1: &Self::Cluster,
567        c1_port: &<Self::Cluster as Node>::Port,
568        p2: &Self::Process,
569        p2_port: &<Self::Process as Node>::Port,
570    ) -> Box<dyn FnOnce()> {
571        let serialized = format!(
572            "o2m_connect {}:{c1_port:?} -> {}:{p2_port:?}",
573            c1.name, p2.name
574        );
575
576        Box::new(move || {
577            trace!(name: "m2o_connect thunk", %serialized);
578        })
579    }
580
581    #[instrument(level = "trace", skip_all, fields(c1 = c1.name, %c1_port, c2 = c2.name, %c2_port))]
582    fn m2m_sink_source(
583        _env: &mut Self::InstantiateEnv,
584        c1: &Self::Cluster,
585        c1_port: &<Self::Cluster as Node>::Port,
586        c2: &Self::Cluster,
587        c2_port: &<Self::Cluster as Node>::Port,
588        name: Option<&str>,
589        networking_info: &crate::networking::NetworkingInfo,
590        _external_types: Option<(&syn::Type, &syn::Type)>,
591    ) -> (syn::Expr, syn::Expr) {
592        match networking_info {
593            crate::networking::NetworkingInfo::Tcp {
594                fault: crate::networking::TcpFault::FailStop,
595            } => {}
596            _ => panic!("Unsupported networking info: {:?}", networking_info),
597        }
598
599        deploy_containerized_m2m(
600            name.expect("channel name is required for containerized deployment"),
601        )
602    }
603
604    #[instrument(level = "trace", skip_all, fields(c1 = c1.name, %c1_port, c2 = c2.name, %c2_port))]
605    fn m2m_connect(
606        c1: &Self::Cluster,
607        c1_port: &<Self::Cluster as Node>::Port,
608        c2: &Self::Cluster,
609        c2_port: &<Self::Cluster as Node>::Port,
610    ) -> Box<dyn FnOnce()> {
611        let serialized = format!(
612            "m2m_connect {}:{c1_port:?} -> {}:{c2_port:?}",
613            c1.name, c2.name
614        );
615
616        Box::new(move || {
617            trace!(name: "m2m_connect thunk", %serialized);
618        })
619    }
620
621    #[instrument(level = "trace", skip_all, fields(p2 = p2.name, %p2_port, %shared_handle, extra_stmts = extra_stmts.len()))]
622    fn e2o_many_source(
623        extra_stmts: &mut Vec<syn::Stmt>,
624        p2: &Self::Process,
625        p2_port: &<Self::Process as Node>::Port,
626        codec_type: &syn::Type,
627        encode_type: &syn::Type,
628        shared_handle: String,
629    ) -> syn::Expr {
630        p2.exposed_ports
631            .borrow_mut()
632            .insert(shared_handle.clone(), PortInfo::Tcp { port: *p2_port });
633
634        let socket_ident = syn::Ident::new(
635            &format!("__hydro_deploy_many_{}_socket", shared_handle),
636            Span::call_site(),
637        );
638
639        let source_ident = syn::Ident::new(
640            &format!("__hydro_deploy_many_{}_source", shared_handle),
641            Span::call_site(),
642        );
643
644        let sink_ident = syn::Ident::new(
645            &format!("__hydro_deploy_many_{}_sink", shared_handle),
646            Span::call_site(),
647        );
648
649        let membership_ident = syn::Ident::new(
650            &format!("__hydro_deploy_many_{}_membership", shared_handle),
651            Span::call_site(),
652        );
653
654        let bind_addr = format!("0.0.0.0:{}", p2_port);
655
656        extra_stmts.push(syn::parse_quote! {
657            let #socket_ident = tokio::net::TcpListener::bind(#bind_addr).await.unwrap();
658        });
659
660        let root = crate::staging_util::get_this_crate();
661
662        extra_stmts.push(syn::parse_quote! {
663            let (#source_ident, #sink_ident, #membership_ident) = #root::runtime_support::hydro_deploy_integration::multi_connection::tcp_multi_connection::<#encode_type, #codec_type>(#socket_ident);
664        });
665
666        parse_quote!(#source_ident)
667    }
668
669    #[instrument(level = "trace", skip_all, fields(%shared_handle))]
670    fn e2o_many_sink(shared_handle: String) -> syn::Expr {
671        let sink_ident = syn::Ident::new(
672            &format!("__hydro_deploy_many_{}_sink", shared_handle),
673            Span::call_site(),
674        );
675        parse_quote!(#sink_ident)
676    }
677
678    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port, ?codec_type, %shared_handle))]
679    fn e2o_source(
680        extra_stmts: &mut Vec<syn::Stmt>,
681        p1: &Self::External,
682        p1_port: &<Self::External as Node>::Port,
683        p2: &Self::Process,
684        p2_port: &<Self::Process as Node>::Port,
685        codec_type: &syn::Type,
686        _encode_type: &syn::Type,
687        shared_handle: String,
688    ) -> syn::Expr {
689        // Record the port for manifest export
690        p2.exposed_ports
691            .borrow_mut()
692            .insert(shared_handle.clone(), PortInfo::Tcp { port: *p2_port });
693
694        let source_ident = syn::Ident::new(
695            &format!("__hydro_deploy_{}_source", shared_handle),
696            Span::call_site(),
697        );
698
699        let bind_addr = format!("0.0.0.0:{}", p2_port);
700
701        // Always use LazySinkSource for external connections - it creates both sink and source
702        // which is needed for bidirectional connections (unpaired: false)
703        let socket_ident = syn::Ident::new(
704            &format!("__hydro_deploy_{}_socket", shared_handle),
705            Span::call_site(),
706        );
707
708        let sink_ident = syn::Ident::new(
709            &format!("__hydro_deploy_{}_sink", shared_handle),
710            Span::call_site(),
711        );
712
713        extra_stmts.push(syn::parse_quote! {
714            let #socket_ident = tokio::net::TcpListener::bind(#bind_addr).await.unwrap();
715        });
716
717        let create_expr = deploy_containerized_external_sink_source_ident(bind_addr, socket_ident);
718
719        extra_stmts.push(syn::parse_quote! {
720            let (#sink_ident, #source_ident) = (#create_expr).split();
721        });
722
723        parse_quote!(#source_ident)
724    }
725
726    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port, ?many, ?server_hint))]
727    fn e2o_connect(
728        p1: &Self::External,
729        p1_port: &<Self::External as Node>::Port,
730        p2: &Self::Process,
731        p2_port: &<Self::Process as Node>::Port,
732        many: bool,
733        server_hint: NetworkHint,
734    ) -> Box<dyn FnOnce()> {
735        let serialized = format!(
736            "e2o_connect {}:{p1_port:?} -> {}:{p2_port:?}",
737            p1.name, p2.name
738        );
739
740        Box::new(move || {
741            trace!(name: "e2o_connect thunk", %serialized);
742        })
743    }
744
745    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port, %shared_handle))]
746    fn o2e_sink(
747        p1: &Self::Process,
748        p1_port: &<Self::Process as Node>::Port,
749        p2: &Self::External,
750        p2_port: &<Self::External as Node>::Port,
751        shared_handle: String,
752    ) -> syn::Expr {
753        let sink_ident = syn::Ident::new(
754            &format!("__hydro_deploy_{}_sink", shared_handle),
755            Span::call_site(),
756        );
757        parse_quote!(#sink_ident)
758    }
759
760    #[instrument(level = "trace", skip_all, fields(%of_cluster))]
761    fn cluster_ids(of_cluster: LocationKey) -> syn::Expr {
762        cluster_ids().splice_untyped()
763    }
764
765    #[instrument(level = "trace", skip_all)]
766    fn cluster_self_id() -> syn::Expr {
767        cluster_self_id().splice_untyped()
768    }
769
770    #[instrument(level = "trace", skip_all, fields(?location_id))]
771    fn cluster_membership_stream(
772        _env: &mut Self::InstantiateEnv,
773        _at_location: &LocationId,
774        location_id: &LocationId,
775    ) -> syn::Expr {
776        cluster_membership_stream(location_id).splice_untyped()
777    }
778}
779
780#[instrument(level = "trace", skip_all, ret, fields(%name_hint, %location))]
781fn get_ecs_image_name(name_hint: &str, location: LocationKey) -> String {
782    let name_hint = name_hint
783        .split("::")
784        .last()
785        .unwrap()
786        .to_ascii_lowercase()
787        .replace(['.', '_'], "-")
788        .replace("::", "-");
789
790    format!("hy-{name_hint}-{location}")
791}
792
793/// Represents a Process running in an ecs deployment
794#[derive(Clone)]
795pub struct EcsDeployProcessSpec;
796
797impl<'a> ProcessSpec<'a, EcsDeploy> for EcsDeployProcessSpec {
798    #[instrument(level = "trace", skip_all, fields(%id, %name_hint))]
799    fn build(self, id: LocationKey, name_hint: &'_ str) -> <EcsDeploy as Deploy<'a>>::Process {
800        EcsDeployProcess {
801            id,
802            name: get_ecs_image_name(name_hint, id),
803            next_port: Rc::new(RefCell::new(10001)),
804            exposed_ports: Rc::new(RefCell::new(BTreeMap::new())),
805            trybuild_config: Rc::new(RefCell::new(None)),
806        }
807    }
808}
809
810/// Represents a Cluster running across `count` ecs tasks.
811#[derive(Clone)]
812pub struct EcsDeployClusterSpec {
813    count: usize,
814}
815
816impl<'a> ClusterSpec<'a, EcsDeploy> for EcsDeployClusterSpec {
817    #[instrument(level = "trace", skip_all, fields(%id, %name_hint))]
818    fn build(self, id: LocationKey, name_hint: &str) -> <EcsDeploy as Deploy<'a>>::Cluster {
819        EcsDeployCluster {
820            id,
821            name: get_ecs_image_name(name_hint, id),
822            next_port: Rc::new(RefCell::new(10001)),
823            exposed_ports: Rc::new(RefCell::new(BTreeMap::new())),
824            count: self.count,
825            trybuild_config: Rc::new(RefCell::new(None)),
826        }
827    }
828}
829
830/// Represents an external process outside of the management of hydro deploy.
831pub struct EcsDeployExternalSpec {
832    name: String,
833}
834
835impl<'a> ExternalSpec<'a, EcsDeploy> for EcsDeployExternalSpec {
836    #[instrument(level = "trace", skip_all, fields(%id, %name_hint))]
837    fn build(self, id: LocationKey, name_hint: &str) -> <EcsDeploy as Deploy<'a>>::External {
838        EcsDeployExternal {
839            name: self.name,
840            next_port: Rc::new(RefCell::new(10000)),
841        }
842    }
843}