Skip to main content

hydro_lang/deploy/
deploy_graph_containerized.rs

1//! Deployment backend for Hydro that uses Docker to provision and launch services.
2
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::pin::Pin;
6use std::rc::Rc;
7
8use bollard::Docker;
9use bollard::models::{ContainerCreateBody, EndpointSettings, HostConfig, NetworkCreateRequest};
10use bollard::query_parameters::{
11    BuildImageOptions, CreateContainerOptions, InspectContainerOptions, KillContainerOptions,
12    RemoveContainerOptions, StartContainerOptions,
13};
14use bollard::secret::NetworkingConfig;
15use bytes::Bytes;
16use dfir_lang::graph::{AsCodeOptions, DfirGraph};
17use futures::{Sink, SinkExt, Stream, StreamExt};
18use http_body_util::Full;
19// Re-export LinuxCompileType so users can configure compile type without depending on hydro_deploy directly.
20pub use hydro_deploy::LinuxCompileType;
21use hydro_deploy::RustCrate;
22use hydro_deploy::rust_crate::build::{BuildError, build_crate_memoized};
23use nanoid::nanoid;
24use proc_macro2::Span;
25use sinktools::lazy::LazySink;
26use stageleft::QuotedWithContext;
27use syn::parse_quote;
28use tar::{Builder, Header};
29use tokio::net::TcpStream;
30use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec};
31use tracing::{Instrument, instrument, trace, warn};
32
33use super::deploy_runtime_containerized::*;
34use crate::compile::builder::ExternalPortId;
35use crate::compile::deploy::DeployResult;
36use crate::compile::deploy_provider::{
37    ClusterSpec, Deploy, ExternalSpec, Node, ProcessSpec, RegisterPort,
38};
39use crate::compile::trybuild::generate::{LinkingMode, create_graph_trybuild};
40use crate::location::dynamic::LocationId;
41use crate::location::{LocationKey, NetworkHint};
42
43/// represents a docker network
44#[derive(Clone, Debug)]
45pub struct DockerNetwork {
46    name: String,
47}
48
49impl DockerNetwork {
50    /// creates a new docker network (will actually be created when `deployment.start()` is called).
51    pub fn new(name: String) -> Self {
52        Self {
53            name: format!("{name}-{}", nanoid::nanoid!(6, &CONTAINER_ALPHABET)),
54        }
55    }
56}
57
58/// Represents a process running in a docker container
59#[derive(Clone)]
60pub struct DockerDeployProcess {
61    key: LocationKey,
62    name: String,
63    next_port: Rc<RefCell<u16>>,
64    rust_crate: Rc<RefCell<Option<RustCrate>>>,
65
66    exposed_ports: Rc<RefCell<Vec<u16>>>,
67
68    docker_container_name: Rc<RefCell<Option<String>>>,
69
70    rustflags: Option<String>,
71
72    config: Vec<String>,
73
74    network: DockerNetwork,
75
76    base_image: Option<String>,
77
78    linux_compile_type: LinuxCompileType,
79
80    features: Vec<String>,
81}
82
83impl Node for DockerDeployProcess {
84    type Port = u16;
85    type Meta = ();
86    type InstantiateEnv = DockerDeploy;
87
88    #[instrument(level = "trace", skip_all, ret, fields(key = %self.key, name = self.name))]
89    fn next_port(&self) -> Self::Port {
90        let port = {
91            let mut borrow = self.next_port.borrow_mut();
92            let port = *borrow;
93            *borrow += 1;
94            port
95        };
96
97        port
98    }
99
100    #[instrument(level = "trace", skip_all, fields(key = %self.key, name = self.name))]
101    fn update_meta(&self, _meta: &Self::Meta) {}
102
103    #[instrument(level = "trace", skip_all, fields(key = %self.key, name = self.name, ?meta, extra_stmts = extra_stmts.len(), sidecars = sidecars.len()))]
104    fn instantiate(
105        &self,
106        _env: &mut Self::InstantiateEnv,
107        meta: &mut Self::Meta,
108        graph: DfirGraph,
109        extra_stmts: &[syn::Stmt],
110        sidecars: &[syn::Expr],
111        as_code_options: &AsCodeOptions,
112    ) {
113        let (bin_name, config) = create_graph_trybuild(
114            graph,
115            extra_stmts,
116            sidecars,
117            as_code_options,
118            Some(&self.name),
119            crate::compile::trybuild::generate::DeployMode::Containerized,
120            LinkingMode::Static,
121        );
122
123        let mut ret = RustCrate::new(&config.project_dir, &config.project_dir)
124            .target_dir(config.target_dir)
125            .example(bin_name)
126            .no_default_features();
127
128        ret = ret.display_name("test_display_name");
129
130        ret = ret.features(vec!["hydro___feature_docker_runtime".to_owned()]);
131
132        if let Some(features) = config.features {
133            ret = ret.features(features);
134        }
135
136        if !self.features.is_empty() {
137            ret = ret.features(self.features.clone());
138        }
139
140        ret = ret.build_env("STAGELEFT_TRYBUILD_BUILD_STAGED", "1");
141        ret = ret.config("build.incremental = false");
142
143        *self.rust_crate.borrow_mut() = Some(ret);
144    }
145}
146
147/// Represents a logical cluster, which can be a variable amount of individual containers.
148#[derive(Clone)]
149pub struct DockerDeployCluster {
150    key: LocationKey,
151    name: String,
152    next_port: Rc<RefCell<u16>>,
153    rust_crate: Rc<RefCell<Option<RustCrate>>>,
154
155    exposed_ports: Rc<RefCell<Vec<u16>>>,
156
157    docker_container_name: Rc<RefCell<Vec<String>>>,
158
159    rustflags: Option<String>,
160
161    config: Vec<String>,
162
163    count: usize,
164
165    base_image: Option<String>,
166
167    linux_compile_type: LinuxCompileType,
168
169    features: Vec<String>,
170}
171
172impl Node for DockerDeployCluster {
173    type Port = u16;
174    type Meta = ();
175    type InstantiateEnv = DockerDeploy;
176
177    #[instrument(level = "trace", skip_all, ret, fields(key = %self.key, name = self.name))]
178    fn next_port(&self) -> Self::Port {
179        let port = {
180            let mut borrow = self.next_port.borrow_mut();
181            let port = *borrow;
182            *borrow += 1;
183            port
184        };
185
186        port
187    }
188
189    #[instrument(level = "trace", skip_all, fields(key = %self.key, name = self.name))]
190    fn update_meta(&self, _meta: &Self::Meta) {}
191
192    #[instrument(level = "trace", skip_all, fields(key = %self.key, name = self.name, extra_stmts = extra_stmts.len()))]
193    fn instantiate(
194        &self,
195        _env: &mut Self::InstantiateEnv,
196        _meta: &mut Self::Meta,
197        graph: DfirGraph,
198        extra_stmts: &[syn::Stmt],
199        sidecars: &[syn::Expr],
200        as_code_options: &AsCodeOptions,
201    ) {
202        let (bin_name, config) = create_graph_trybuild(
203            graph,
204            extra_stmts,
205            sidecars,
206            as_code_options,
207            Some(&self.name),
208            crate::compile::trybuild::generate::DeployMode::Containerized,
209            LinkingMode::Static,
210        );
211
212        let mut ret = RustCrate::new(&config.project_dir, &config.project_dir)
213            .target_dir(config.target_dir)
214            .example(bin_name)
215            .no_default_features();
216
217        ret = ret.display_name("test_display_name");
218
219        ret = ret.features(vec!["hydro___feature_docker_runtime".to_owned()]);
220
221        if let Some(features) = config.features {
222            ret = ret.features(features);
223        }
224
225        if !self.features.is_empty() {
226            ret = ret.features(self.features.clone());
227        }
228
229        ret = ret.build_env("STAGELEFT_TRYBUILD_BUILD_STAGED", "1");
230        ret = ret.config("build.incremental = false");
231
232        *self.rust_crate.borrow_mut() = Some(ret);
233    }
234}
235
236/// Represents an external process, outside the control of this deployment but still with some communication into this deployment.
237#[derive(Clone, Debug)]
238#[expect(
239    dead_code,
240    reason = "fields used via Rc<RefCell> in RegisterPort impl and ExternalBytesPort construction"
241)]
242pub struct DockerDeployExternal {
243    /// The location key for this external, used for port handle construction.
244    pub(crate) key: LocationKey,
245    name: String,
246    next_port: Rc<RefCell<u16>>,
247
248    /// Counter for generating `ExternalPortId` values at deploy time.
249    next_external_port_id: Rc<RefCell<crate::Counter<ExternalPortId>>>,
250
251    ports: Rc<RefCell<HashMap<ExternalPortId, u16>>>,
252
253    connection_info: Rc<RefCell<HashMap<u16, (Rc<RefCell<Option<String>>>, u16, DockerNetwork)>>>,
254}
255
256impl Node for DockerDeployExternal {
257    type Port = u16;
258    type Meta = ();
259    type InstantiateEnv = DockerDeploy;
260
261    #[instrument(level = "trace", skip_all, ret, fields(name = self.name))]
262    fn next_port(&self) -> Self::Port {
263        let port = {
264            let mut borrow = self.next_port.borrow_mut();
265            let port = *borrow;
266            *borrow += 1;
267            port
268        };
269
270        port
271    }
272
273    #[instrument(level = "trace", skip_all, fields(name = self.name))]
274    fn update_meta(&self, _meta: &Self::Meta) {}
275
276    #[instrument(level = "trace", skip_all, fields(name = self.name, ?meta, extra_stmts = extra_stmts.len(), sidecars = sidecars.len()))]
277    fn instantiate(
278        &self,
279        _env: &mut Self::InstantiateEnv,
280        meta: &mut Self::Meta,
281        graph: DfirGraph,
282        extra_stmts: &[syn::Stmt],
283        sidecars: &[syn::Expr],
284        _as_code_options: &AsCodeOptions,
285    ) {
286        trace!(name: "surface", surface = graph.surface_syntax_string());
287    }
288}
289
290impl DockerDeployProcess {
291    /// Expose a TCP port on this process for external access.
292    ///
293    /// The binary running on this process must bind a `TcpListener` on this port.
294    /// This method ensures the port appears in the Docker image's `EXPOSE` directives
295    /// and is available for endpoint discovery via [`Self::get_tcp_endpoint`].
296    pub fn expose_port(&self, port: u16) {
297        self.exposed_ports.borrow_mut().push(port);
298    }
299
300    /// Returns the TCP endpoint `(host, port)` for this process exposing
301    /// the given container port. Queries Docker for the dynamically allocated
302    /// host port mapping.
303    pub async fn get_tcp_endpoint(&self, container_port: u16) -> (String, u16) {
304        let name = self
305            .docker_container_name
306            .borrow()
307            .as_ref()
308            .expect("container not yet started")
309            .clone();
310        let host_port = find_dynamically_allocated_docker_port(&name, container_port).await;
311        ("localhost".to_owned(), host_port)
312    }
313}
314
315impl DockerDeployCluster {
316    /// Expose a TCP port on every member of this cluster for external access.
317    ///
318    /// The binary running on this cluster must bind a `TcpListener` on this port.
319    /// This method ensures the port appears in the Docker image's `EXPOSE` directives
320    /// and is available for endpoint discovery via [`Self::get_all_tcp_endpoints`].
321    pub fn expose_port(&self, port: u16) {
322        self.exposed_ports.borrow_mut().push(port);
323    }
324
325    /// Returns TCP endpoints `(host, port)` for all cluster members exposing
326    /// the given container port. Queries Docker for the dynamically allocated
327    /// host port mapping.
328    pub async fn get_all_tcp_endpoints(&self, container_port: u16) -> Vec<(String, u16)> {
329        let names = self.docker_container_name.borrow().clone();
330        let mut endpoints = Vec::with_capacity(names.len());
331        for name in names {
332            let host_port = find_dynamically_allocated_docker_port(&name, container_port).await;
333            endpoints.push(("localhost".to_owned(), host_port));
334        }
335        endpoints
336    }
337}
338
339type DynSourceSink<Out, In, InErr> = (
340    Pin<Box<dyn Stream<Item = Out>>>,
341    Pin<Box<dyn Sink<In, Error = InErr>>>,
342);
343
344impl<'a> RegisterPort<'a, DockerDeploy> for DockerDeployExternal {
345    #[instrument(level = "trace", skip_all, fields(name = self.name, %external_port_id, %port))]
346    fn register(&self, external_port_id: ExternalPortId, port: Self::Port) {
347        self.ports.borrow_mut().insert(external_port_id, port);
348    }
349
350    fn as_bytes_bidi(
351        &self,
352        external_port_id: ExternalPortId,
353    ) -> impl Future<
354        Output = DynSourceSink<Result<bytes::BytesMut, std::io::Error>, Bytes, std::io::Error>,
355    > + 'a {
356        let guard =
357            tracing::trace_span!("as_bytes_bidi", name = %self.name, %external_port_id).entered();
358
359        let local_port = *self.ports.borrow().get(&external_port_id).unwrap();
360        let (docker_container_name, remote_port, _) = self
361            .connection_info
362            .borrow()
363            .get(&local_port)
364            .unwrap()
365            .clone();
366
367        let docker_container_name = docker_container_name.borrow().as_ref().unwrap().clone();
368
369        async move {
370            let local_port =
371                find_dynamically_allocated_docker_port(&docker_container_name, remote_port).await;
372            let remote_ip_address = "localhost";
373
374            trace!(name: "as_bytes_bidi_connecting", to = %remote_ip_address, to_port = %local_port);
375
376            let stream = TcpStream::connect(format!("{remote_ip_address}:{local_port}"))
377                .await
378                .unwrap();
379
380            trace!(name: "as_bytes_bidi_connected", to = %remote_ip_address, to_port = %local_port);
381
382            let (rx, tx) = stream.into_split();
383
384            let source = Box::pin(
385                FramedRead::new(rx, LengthDelimitedCodec::new()),
386            ) as Pin<Box<dyn Stream<Item = Result<bytes::BytesMut, std::io::Error>>>>;
387
388            let sink = Box::pin(FramedWrite::new(tx, LengthDelimitedCodec::new()))
389                as Pin<Box<dyn Sink<Bytes, Error = std::io::Error>>>;
390
391            (source, sink)
392        }
393        .instrument(guard.exit())
394    }
395
396    fn as_bincode_bidi<InT, OutT>(
397        &self,
398        external_port_id: ExternalPortId,
399    ) -> impl Future<Output = DynSourceSink<OutT, InT, std::io::Error>> + 'a
400    where
401        InT: serde::Serialize + 'static,
402        OutT: serde::de::DeserializeOwned + 'static,
403    {
404        let guard =
405            tracing::trace_span!("as_bincode_bidi", name = %self.name, %external_port_id).entered();
406
407        let local_port = *self.ports.borrow().get(&external_port_id).unwrap();
408        let (docker_container_name, remote_port, _) = self
409            .connection_info
410            .borrow()
411            .get(&local_port)
412            .unwrap()
413            .clone();
414
415        let docker_container_name = docker_container_name.borrow().as_ref().unwrap().clone();
416
417        async move {
418            let local_port =
419                find_dynamically_allocated_docker_port(&docker_container_name, remote_port).await;
420            let remote_ip_address = "localhost";
421
422            trace!(name: "as_bincode_bidi_connecting", to = %remote_ip_address, to_port = %local_port);
423
424            let stream = TcpStream::connect(format!("{remote_ip_address}:{local_port}"))
425                .await
426                .unwrap();
427
428            trace!(name: "as_bincode_bidi_connected", to = %remote_ip_address, to_port = %local_port);
429
430            let (rx, tx) = stream.into_split();
431
432            let source = Box::pin(
433                FramedRead::new(rx, LengthDelimitedCodec::new())
434                    .map(|v| bincode::deserialize(&v.unwrap()).unwrap()),
435            ) as Pin<Box<dyn Stream<Item = OutT>>>;
436
437            let sink = Box::pin(
438                FramedWrite::new(tx, LengthDelimitedCodec::new()).with(move |v: InT| async move {
439                    Ok::<_, std::io::Error>(Bytes::from(bincode::serialize(&v).unwrap()))
440                }),
441            ) as Pin<Box<dyn Sink<InT, Error = std::io::Error>>>;
442
443            (source, sink)
444        }
445        .instrument(guard.exit())
446    }
447
448    fn as_bincode_sink<T>(
449        &self,
450        external_port_id: ExternalPortId,
451    ) -> impl Future<Output = Pin<Box<dyn Sink<T, Error = std::io::Error>>>> + 'a
452    where
453        T: serde::Serialize + 'static,
454    {
455        let guard =
456            tracing::trace_span!("as_bincode_sink", name = %self.name, %external_port_id).entered();
457
458        let local_port = *self.ports.borrow().get(&external_port_id).unwrap();
459        let (docker_container_name, remote_port, _) = self
460            .connection_info
461            .borrow()
462            .get(&local_port)
463            .unwrap()
464            .clone();
465
466        let docker_container_name = docker_container_name.borrow().as_ref().unwrap().clone();
467
468        async move {
469            let local_port = find_dynamically_allocated_docker_port(&docker_container_name, remote_port).await;
470            let remote_ip_address = "localhost";
471
472            Box::pin(
473                LazySink::new(move || {
474                    Box::pin(async move {
475                        trace!(name: "as_bincode_sink_connecting", to = %remote_ip_address, to_port = %local_port);
476
477                        let stream =
478                            TcpStream::connect(format!("{remote_ip_address}:{local_port}"))
479                                .await?;
480
481                        trace!(name: "as_bincode_sink_connected", to = %remote_ip_address, to_port = %local_port);
482
483                        Result::<_, std::io::Error>::Ok(FramedWrite::new(
484                            stream,
485                            LengthDelimitedCodec::new(),
486                        ))
487                    })
488                })
489                .with(move |v| async move {
490                    Ok(Bytes::from(bincode::serialize(&v).unwrap()))
491                }),
492            ) as Pin<Box<dyn Sink<T, Error = std::io::Error>>>
493        }
494        .instrument(guard.exit())
495    }
496
497    fn as_bincode_source<T>(
498        &self,
499        external_port_id: ExternalPortId,
500    ) -> impl Future<Output = Pin<Box<dyn Stream<Item = T>>>> + 'a
501    where
502        T: serde::de::DeserializeOwned + 'static,
503    {
504        let guard =
505            tracing::trace_span!("as_bincode_sink", name = %self.name, %external_port_id).entered();
506
507        let local_port = *self.ports.borrow().get(&external_port_id).unwrap();
508        let (docker_container_name, remote_port, _) = self
509            .connection_info
510            .borrow()
511            .get(&local_port)
512            .unwrap()
513            .clone();
514
515        let docker_container_name = docker_container_name.borrow().as_ref().unwrap().clone();
516
517        async move {
518
519            let local_port = find_dynamically_allocated_docker_port(&docker_container_name, remote_port).await;
520            let remote_ip_address = "localhost";
521
522            trace!(name: "as_bincode_source_connecting", to = %remote_ip_address, to_port = %local_port);
523
524            let stream = TcpStream::connect(format!("{remote_ip_address}:{local_port}"))
525                .await
526                .unwrap();
527
528            trace!(name: "as_bincode_source_connected", to = %remote_ip_address, to_port = %local_port);
529
530            Box::pin(
531                FramedRead::new(stream, LengthDelimitedCodec::new())
532                    .map(|v| bincode::deserialize(&v.unwrap()).unwrap()),
533            ) as Pin<Box<dyn Stream<Item = T>>>
534        }
535        .instrument(guard.exit())
536    }
537}
538
539#[instrument(level = "trace", skip_all, fields(%docker_container_name, %destination_port))]
540async fn find_dynamically_allocated_docker_port(
541    docker_container_name: &str,
542    destination_port: u16,
543) -> u16 {
544    let docker = Docker::connect_with_local_defaults().unwrap();
545
546    let container_info = docker
547        .inspect_container(docker_container_name, None::<InspectContainerOptions>)
548        .await
549        .unwrap();
550
551    trace!(name: "port struct", container_info = ?container_info.network_settings.as_ref().unwrap().ports.as_ref().unwrap());
552
553    // container_info={"1001/tcp": Some([PortBinding { host_ip: Some("0.0.0.0"), host_port: Some("32771") }, PortBinding { host_ip: Some("::"), host_port: Some("32771") }])} destination_port=1001
554    let remote_port = container_info
555        .network_settings
556        .as_ref()
557        .unwrap()
558        .ports
559        .as_ref()
560        .unwrap()
561        .get(&format!("{destination_port}/tcp"))
562        .unwrap()
563        .as_ref()
564        .unwrap()
565        .iter()
566        .find(|v| v.host_ip == Some("0.0.0.0".to_owned()))
567        .unwrap()
568        .host_port
569        .as_ref()
570        .unwrap()
571        .parse()
572        .unwrap();
573
574    remote_port
575}
576
577/// For deploying to a local docker instance
578pub struct DockerDeploy {
579    docker_processes: Vec<DockerDeployProcessSpec>,
580    docker_clusters: Vec<DockerDeployClusterSpec>,
581    network: DockerNetwork,
582    deployment_instance: String,
583}
584
585#[instrument(level = "trace", skip_all, fields(%image_name, %container_name, %network_name, %deployment_instance))]
586async fn create_and_start_container(
587    docker: &Docker,
588    container_name: &str,
589    image_name: &str,
590    network_name: &str,
591    deployment_instance: &str,
592) -> Result<(), anyhow::Error> {
593    let config = ContainerCreateBody {
594        image: Some(image_name.to_owned()),
595        hostname: Some(container_name.to_owned()),
596        host_config: Some(HostConfig {
597            binds: Some(vec!["/var/run/docker.sock:/var/run/docker.sock".to_owned()]),
598            publish_all_ports: Some(true),
599            port_bindings: Some(HashMap::new()), /* Due to a bug in docker, if you don't send empty port bindings with publish_all_ports set to true and with a docker image that has EXPOSE directives in it, docker will crash because it will try to write to a map in memory that it has not initialized yet. Setting port_bindings explicitly to an empty map will initialize it first so that it does not break. */
600            ..Default::default()
601        }),
602        env: Some(vec![
603            format!("CONTAINER_NAME={container_name}"),
604            format!("DEPLOYMENT_INSTANCE={deployment_instance}"),
605            "RUST_LOG=trace".to_owned(),
606        ]),
607        networking_config: Some(NetworkingConfig {
608            endpoints_config: Some(HashMap::from([(
609                network_name.to_owned(),
610                EndpointSettings {
611                    ..Default::default()
612                },
613            )])),
614        }),
615        tty: Some(true),
616        ..Default::default()
617    };
618
619    let options = CreateContainerOptions {
620        name: Some(container_name.to_owned()),
621        ..Default::default()
622    };
623
624    tracing::error!("Config: {}", serde_json::to_string_pretty(&config).unwrap());
625    docker.create_container(Some(options), config).await?;
626    docker
627        .start_container(container_name, None::<StartContainerOptions>)
628        .await?;
629
630    Ok(())
631}
632
633#[instrument(level = "trace", skip_all, fields(%image_name))]
634async fn build_and_create_image(
635    rust_crate: &Rc<RefCell<Option<RustCrate>>>,
636    rustflags: Option<&str>,
637    config: &[String],
638    exposed_ports: &[u16],
639    image_name: &str,
640    base_image: Option<&str>,
641    linux_compile_type: LinuxCompileType,
642) -> Result<(), anyhow::Error> {
643    let mut rust_crate = rust_crate.borrow_mut().take().unwrap();
644
645    if let Some(rustflags) = rustflags {
646        rust_crate = rust_crate.rustflags(rustflags);
647    }
648
649    for cfg in config {
650        rust_crate = rust_crate.config(cfg);
651    }
652
653    let build_output = match build_crate_memoized(
654        rust_crate.get_build_params(hydro_deploy::HostTargetType::Linux(linux_compile_type)),
655    )
656    .await
657    {
658        Ok(build_output) => build_output,
659        Err(BuildError::FailedToBuildCrate {
660            exit_status,
661            diagnostics,
662            text_lines,
663            stderr_lines,
664        }) => {
665            let diagnostics = diagnostics
666                .into_iter()
667                .map(|d| d.rendered.unwrap())
668                .collect::<Vec<_>>()
669                .join("\n");
670            let text_lines = text_lines.join("\n");
671            let stderr_lines = stderr_lines.join("\n");
672
673            anyhow::bail!(
674                r"
675Failed to build crate {exit_status:?}
676--- diagnostics
677---
678{diagnostics}
679---
680---
681---
682
683--- text_lines
684---
685---
686{text_lines}
687---
688---
689---
690
691--- stderr_lines
692---
693---
694{stderr_lines}
695---
696---
697---"
698            );
699        }
700        Err(err) => {
701            anyhow::bail!("Failed to build crate {err:?}");
702        }
703    };
704
705    let docker = Docker::connect_with_local_defaults()?;
706
707    let mut tar_data = Vec::new();
708    {
709        let mut tar = Builder::new(&mut tar_data);
710
711        let exposed_ports = exposed_ports
712            .iter()
713            .map(|port| format!("EXPOSE {port}/tcp"))
714            .collect::<Vec<_>>()
715            .join("\n");
716
717        let from_image = base_image.unwrap_or("scratch");
718        let dockerfile_content = format!(
719            r#"
720                FROM {from_image}
721                {exposed_ports}
722                COPY app /app
723                CMD ["/app"]
724            "#,
725        );
726
727        trace!(name: "dockerfile", %dockerfile_content);
728
729        let mut header = Header::new_gnu();
730        header.set_path("Dockerfile")?;
731        header.set_size(dockerfile_content.len() as u64);
732        header.set_cksum();
733        tar.append(&header, dockerfile_content.as_bytes())?;
734
735        let mut header = Header::new_gnu();
736        header.set_path("app")?;
737        header.set_size(build_output.bin_data.len() as u64);
738        header.set_mode(0o755);
739        header.set_cksum();
740        tar.append(&header, &build_output.bin_data[..])?;
741
742        tar.finish()?;
743    }
744
745    let build_options = BuildImageOptions {
746        dockerfile: "Dockerfile".to_owned(),
747        t: Some(image_name.to_owned()),
748        rm: true,
749        ..Default::default()
750    };
751
752    use bollard::errors::Error;
753
754    let body = http_body_util::Either::Left(Full::new(Bytes::from(tar_data)));
755    let mut build_stream = docker.build_image(build_options, None, Some(body));
756    while let Some(msg) = build_stream.next().await {
757        match msg {
758            Ok(_) => {}
759            Err(e) => match e {
760                Error::DockerStreamError { error } => {
761                    return Err(anyhow::anyhow!(
762                        "Docker build failed: DockerStreamError: {{ error: {error} }}"
763                    ));
764                }
765                _ => return Err(anyhow::anyhow!("Docker build failed: {}", e)),
766            },
767        }
768    }
769
770    Ok(())
771}
772
773impl DockerDeploy {
774    /// Create a new deployment
775    pub fn new(network: DockerNetwork) -> Self {
776        Self {
777            docker_processes: Vec::new(),
778            docker_clusters: Vec::new(),
779            network,
780            deployment_instance: nanoid!(6, &CONTAINER_ALPHABET),
781        }
782    }
783
784    /// Add an internal docker service to the deployment.
785    pub fn add_localhost_docker(
786        &mut self,
787        rustflags: Option<String>,
788        config: Vec<String>,
789    ) -> DockerDeployProcessSpec {
790        let process = DockerDeployProcessSpec {
791            rustflags,
792            config,
793            network: self.network.clone(),
794            deployment_instance: self.deployment_instance.clone(),
795            base_image: None,
796            linux_compile_type: LinuxCompileType::Musl,
797            features: vec![],
798        };
799
800        self.docker_processes.push(process.clone());
801
802        process
803    }
804
805    /// Add an internal docker cluster to the deployment.
806    pub fn add_localhost_docker_cluster(
807        &mut self,
808        rustflags: Option<String>,
809        config: Vec<String>,
810        count: usize,
811    ) -> DockerDeployClusterSpec {
812        let cluster = DockerDeployClusterSpec {
813            rustflags,
814            config,
815            count,
816            deployment_instance: self.deployment_instance.clone(),
817            base_image: None,
818            linux_compile_type: LinuxCompileType::Musl,
819            features: vec![],
820        };
821
822        self.docker_clusters.push(cluster.clone());
823
824        cluster
825    }
826
827    /// Add an external process to the deployment.
828    pub fn add_external(&self, name: String) -> DockerDeployExternalSpec {
829        DockerDeployExternalSpec { name }
830    }
831
832    /// Get the deployment instance from this deployment.
833    pub fn get_deployment_instance(&self) -> String {
834        self.deployment_instance.clone()
835    }
836
837    /// Create docker images.
838    #[instrument(level = "trace", skip_all)]
839    pub async fn provision(&self, nodes: &DeployResult<'_, Self>) -> Result<(), anyhow::Error> {
840        for (_, _, process) in nodes.get_all_processes() {
841            let exposed_ports = process.exposed_ports.borrow().clone();
842
843            build_and_create_image(
844                &process.rust_crate,
845                process.rustflags.as_deref(),
846                &process.config,
847                &exposed_ports,
848                &process.name,
849                process.base_image.as_deref(),
850                process.linux_compile_type,
851            )
852            .await?;
853        }
854
855        for (_, _, cluster) in nodes.get_all_clusters() {
856            let exposed_ports = cluster.exposed_ports.borrow().clone();
857            build_and_create_image(
858                &cluster.rust_crate,
859                cluster.rustflags.as_deref(),
860                &cluster.config,
861                &exposed_ports,
862                &cluster.name,
863                cluster.base_image.as_deref(),
864                cluster.linux_compile_type,
865            )
866            .await?;
867        }
868
869        Ok(())
870    }
871
872    /// Start the deployment, tell docker to create containers from the existing provisioned images.
873    #[instrument(level = "trace", skip_all)]
874    pub async fn start(&self, nodes: &DeployResult<'_, Self>) -> Result<(), anyhow::Error> {
875        let docker = Docker::connect_with_local_defaults()?;
876
877        match docker
878            .create_network(NetworkCreateRequest {
879                name: self.network.name.clone(),
880                driver: Some("bridge".to_owned()),
881                ..Default::default()
882            })
883            .await
884        {
885            Ok(v) => v.id,
886            Err(e) => {
887                panic!("Failed to create docker network: {e:?}");
888            }
889        };
890
891        for (_, _, process) in nodes.get_all_processes() {
892            let docker_container_name: String = get_docker_container_name(&process.name, None);
893            *process.docker_container_name.borrow_mut() = Some(docker_container_name.clone());
894
895            create_and_start_container(
896                &docker,
897                &docker_container_name,
898                &process.name,
899                &self.network.name,
900                &self.deployment_instance,
901            )
902            .await?;
903        }
904
905        for (_, _, cluster) in nodes.get_all_clusters() {
906            for num in 0..cluster.count {
907                let docker_container_name = get_docker_container_name(&cluster.name, Some(num));
908                cluster
909                    .docker_container_name
910                    .borrow_mut()
911                    .push(docker_container_name.clone());
912
913                create_and_start_container(
914                    &docker,
915                    &docker_container_name,
916                    &cluster.name,
917                    &self.network.name,
918                    &self.deployment_instance,
919                )
920                .await?;
921            }
922        }
923
924        Ok(())
925    }
926
927    /// Stop the deployment, destroy all containers
928    #[instrument(level = "trace", skip_all)]
929    pub async fn stop(&mut self, nodes: &DeployResult<'_, Self>) -> Result<(), anyhow::Error> {
930        let docker = Docker::connect_with_local_defaults()?;
931
932        for (_, _, process) in nodes.get_all_processes() {
933            let docker_container_name: String = get_docker_container_name(&process.name, None);
934
935            docker
936                .kill_container(&docker_container_name, None::<KillContainerOptions>)
937                .await?;
938        }
939
940        for (_, _, cluster) in nodes.get_all_clusters() {
941            for num in 0..cluster.count {
942                let docker_container_name = get_docker_container_name(&cluster.name, Some(num));
943
944                docker
945                    .kill_container(&docker_container_name, None::<KillContainerOptions>)
946                    .await?;
947            }
948        }
949
950        Ok(())
951    }
952
953    /// remove containers, images, and networks.
954    #[instrument(level = "trace", skip_all)]
955    pub async fn cleanup(&mut self, nodes: &DeployResult<'_, Self>) -> Result<(), anyhow::Error> {
956        let docker = Docker::connect_with_local_defaults()?;
957
958        for (_, _, process) in nodes.get_all_processes() {
959            let docker_container_name: String = get_docker_container_name(&process.name, None);
960
961            docker
962                .remove_container(&docker_container_name, None::<RemoveContainerOptions>)
963                .await?;
964        }
965
966        for (_, _, cluster) in nodes.get_all_clusters() {
967            for num in 0..cluster.count {
968                let docker_container_name = get_docker_container_name(&cluster.name, Some(num));
969
970                docker
971                    .remove_container(&docker_container_name, None::<RemoveContainerOptions>)
972                    .await?;
973            }
974        }
975
976        docker
977            .remove_network(&self.network.name)
978            .await
979            .map_err(|e| anyhow::anyhow!("Failed to remove docker network: {e:?}"))?;
980
981        use bollard::query_parameters::RemoveImageOptions;
982
983        for (_, _, process) in nodes.get_all_processes() {
984            docker
985                .remove_image(&process.name, None::<RemoveImageOptions>, None)
986                .await?;
987        }
988
989        for (_, _, cluster) in nodes.get_all_clusters() {
990            docker
991                .remove_image(&cluster.name, None::<RemoveImageOptions>, None)
992                .await?;
993        }
994
995        Ok(())
996    }
997}
998
999/// Docker names each cluster's members with `String`s.
1000impl crate::compile::deploy_provider::SupportsMemberId<String> for DockerDeploy {}
1001
1002impl<'a> Deploy<'a> for DockerDeploy {
1003    type Meta = ();
1004    type InstantiateEnv = Self;
1005
1006    type Process = DockerDeployProcess;
1007    type Cluster = DockerDeployCluster;
1008    type External = DockerDeployExternal;
1009
1010    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port))]
1011    fn o2o_sink_source(
1012        _env: &mut Self::InstantiateEnv,
1013        p1: &Self::Process,
1014        p1_port: &<Self::Process as Node>::Port,
1015        p2: &Self::Process,
1016        p2_port: &<Self::Process as Node>::Port,
1017        name: Option<&str>,
1018        networking_info: &crate::networking::NetworkingInfo,
1019        _external_types: Option<(&syn::Type, &syn::Type)>,
1020    ) -> (syn::Expr, syn::Expr) {
1021        match networking_info {
1022            crate::networking::NetworkingInfo::Tcp {
1023                fault: crate::networking::TcpFault::FailStop,
1024            } => {}
1025            _ => panic!("Unsupported networking info: {:?}", networking_info),
1026        }
1027
1028        deploy_containerized_o2o(
1029            &p2.name,
1030            name.expect("channel name is required for containerized deployment"),
1031        )
1032    }
1033
1034    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port))]
1035    fn o2o_connect(
1036        p1: &Self::Process,
1037        p1_port: &<Self::Process as Node>::Port,
1038        p2: &Self::Process,
1039        p2_port: &<Self::Process as Node>::Port,
1040    ) -> Box<dyn FnOnce()> {
1041        let serialized = format!("o2o_connect {}:{p1_port} -> {}:{p2_port}", p1.name, p2.name);
1042
1043        Box::new(move || {
1044            trace!(name: "o2o_connect thunk", %serialized);
1045        })
1046    }
1047
1048    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, c2 = c2.name, %c2_port))]
1049    fn o2m_sink_source(
1050        _env: &mut Self::InstantiateEnv,
1051        p1: &Self::Process,
1052        p1_port: &<Self::Process as Node>::Port,
1053        c2: &Self::Cluster,
1054        c2_port: &<Self::Cluster as Node>::Port,
1055        name: Option<&str>,
1056        networking_info: &crate::networking::NetworkingInfo,
1057        _external_types: Option<(&syn::Type, &syn::Type)>,
1058    ) -> (syn::Expr, syn::Expr) {
1059        match networking_info {
1060            crate::networking::NetworkingInfo::Tcp {
1061                fault: crate::networking::TcpFault::FailStop,
1062            } => {}
1063            _ => panic!("Unsupported networking info: {:?}", networking_info),
1064        }
1065
1066        deploy_containerized_o2m(
1067            name.expect("channel name is required for containerized deployment"),
1068        )
1069    }
1070
1071    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, c2 = c2.name, %c2_port))]
1072    fn o2m_connect(
1073        p1: &Self::Process,
1074        p1_port: &<Self::Process as Node>::Port,
1075        c2: &Self::Cluster,
1076        c2_port: &<Self::Cluster as Node>::Port,
1077    ) -> Box<dyn FnOnce()> {
1078        let serialized = format!("o2m_connect {}:{p1_port} -> {}:{c2_port}", p1.name, c2.name);
1079
1080        Box::new(move || {
1081            trace!(name: "o2m_connect thunk", %serialized);
1082        })
1083    }
1084
1085    #[instrument(level = "trace", skip_all, fields(c1 = c1.name, %c1_port, p2 = p2.name, %p2_port))]
1086    fn m2o_sink_source(
1087        _env: &mut Self::InstantiateEnv,
1088        c1: &Self::Cluster,
1089        c1_port: &<Self::Cluster as Node>::Port,
1090        p2: &Self::Process,
1091        p2_port: &<Self::Process as Node>::Port,
1092        name: Option<&str>,
1093        networking_info: &crate::networking::NetworkingInfo,
1094        _external_types: Option<(&syn::Type, &syn::Type)>,
1095    ) -> (syn::Expr, syn::Expr) {
1096        match networking_info {
1097            crate::networking::NetworkingInfo::Tcp {
1098                fault: crate::networking::TcpFault::FailStop,
1099            } => {}
1100            _ => panic!("Unsupported networking info: {:?}", networking_info),
1101        }
1102
1103        deploy_containerized_m2o(
1104            &p2.name,
1105            name.expect("channel name is required for containerized deployment"),
1106        )
1107    }
1108
1109    #[instrument(level = "trace", skip_all, fields(c1 = c1.name, %c1_port, p2 = p2.name, %p2_port))]
1110    fn m2o_connect(
1111        c1: &Self::Cluster,
1112        c1_port: &<Self::Cluster as Node>::Port,
1113        p2: &Self::Process,
1114        p2_port: &<Self::Process as Node>::Port,
1115    ) -> Box<dyn FnOnce()> {
1116        let serialized = format!("o2m_connect {}:{c1_port} -> {}:{p2_port}", c1.name, p2.name);
1117
1118        Box::new(move || {
1119            trace!(name: "m2o_connect thunk", %serialized);
1120        })
1121    }
1122
1123    #[instrument(level = "trace", skip_all, fields(c1 = c1.name, %c1_port, c2 = c2.name, %c2_port))]
1124    fn m2m_sink_source(
1125        _env: &mut Self::InstantiateEnv,
1126        c1: &Self::Cluster,
1127        c1_port: &<Self::Cluster as Node>::Port,
1128        c2: &Self::Cluster,
1129        c2_port: &<Self::Cluster as Node>::Port,
1130        name: Option<&str>,
1131        networking_info: &crate::networking::NetworkingInfo,
1132        _external_types: Option<(&syn::Type, &syn::Type)>,
1133    ) -> (syn::Expr, syn::Expr) {
1134        match networking_info {
1135            crate::networking::NetworkingInfo::Tcp {
1136                fault: crate::networking::TcpFault::FailStop,
1137            } => {}
1138            _ => panic!("Unsupported networking info: {:?}", networking_info),
1139        }
1140
1141        deploy_containerized_m2m(
1142            name.expect("channel name is required for containerized deployment"),
1143        )
1144    }
1145
1146    #[instrument(level = "trace", skip_all, fields(c1 = c1.name, %c1_port, c2 = c2.name, %c2_port))]
1147    fn m2m_connect(
1148        c1: &Self::Cluster,
1149        c1_port: &<Self::Cluster as Node>::Port,
1150        c2: &Self::Cluster,
1151        c2_port: &<Self::Cluster as Node>::Port,
1152    ) -> Box<dyn FnOnce()> {
1153        let serialized = format!("m2m_connect {}:{c1_port} -> {}:{c2_port}", c1.name, c2.name);
1154
1155        Box::new(move || {
1156            trace!(name: "m2m_connect thunk", %serialized);
1157        })
1158    }
1159
1160    #[instrument(level = "trace", skip_all, fields(p2 = p2.name, %p2_port, %shared_handle, extra_stmts = extra_stmts.len()))]
1161    fn e2o_many_source(
1162        extra_stmts: &mut Vec<syn::Stmt>,
1163        p2: &Self::Process,
1164        p2_port: &<Self::Process as Node>::Port,
1165        codec_type: &syn::Type,
1166        encode_type: &syn::Type,
1167        shared_handle: String,
1168    ) -> syn::Expr {
1169        p2.exposed_ports.borrow_mut().push(*p2_port);
1170
1171        let socket_ident = syn::Ident::new(
1172            &format!("__hydro_deploy_many_{}_socket", shared_handle),
1173            Span::call_site(),
1174        );
1175
1176        let source_ident = syn::Ident::new(
1177            &format!("__hydro_deploy_many_{}_source", shared_handle),
1178            Span::call_site(),
1179        );
1180
1181        let sink_ident = syn::Ident::new(
1182            &format!("__hydro_deploy_many_{}_sink", shared_handle),
1183            Span::call_site(),
1184        );
1185
1186        let membership_ident = syn::Ident::new(
1187            &format!("__hydro_deploy_many_{}_membership", shared_handle),
1188            Span::call_site(),
1189        );
1190
1191        let bind_addr = format!("0.0.0.0:{}", p2_port);
1192
1193        extra_stmts.push(syn::parse_quote! {
1194            let #socket_ident = tokio::net::TcpListener::bind(#bind_addr).await.unwrap();
1195        });
1196
1197        let root = crate::staging_util::get_this_crate();
1198
1199        extra_stmts.push(syn::parse_quote! {
1200            let (#source_ident, #sink_ident, #membership_ident) = #root::runtime_support::hydro_deploy_integration::multi_connection::tcp_multi_connection::<#encode_type, #codec_type>(#socket_ident);
1201        });
1202
1203        parse_quote!(#source_ident)
1204    }
1205
1206    #[instrument(level = "trace", skip_all, fields(%shared_handle))]
1207    fn e2o_many_sink(shared_handle: String) -> syn::Expr {
1208        let sink_ident = syn::Ident::new(
1209            &format!("__hydro_deploy_many_{}_sink", shared_handle),
1210            Span::call_site(),
1211        );
1212        parse_quote!(#sink_ident)
1213    }
1214
1215    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port, %shared_handle))]
1216    fn e2o_source(
1217        extra_stmts: &mut Vec<syn::Stmt>,
1218        p1: &Self::External,
1219        p1_port: &<Self::External as Node>::Port,
1220        p2: &Self::Process,
1221        p2_port: &<Self::Process as Node>::Port,
1222        _codec_type: &syn::Type,
1223        _encode_type: &syn::Type,
1224        shared_handle: String,
1225    ) -> syn::Expr {
1226        p1.connection_info.borrow_mut().insert(
1227            *p1_port,
1228            (
1229                p2.docker_container_name.clone(),
1230                *p2_port,
1231                p2.network.clone(),
1232            ),
1233        );
1234
1235        p2.exposed_ports.borrow_mut().push(*p2_port);
1236
1237        let socket_ident = syn::Ident::new(
1238            &format!("__hydro_deploy_{}_socket", shared_handle),
1239            Span::call_site(),
1240        );
1241
1242        let source_ident = syn::Ident::new(
1243            &format!("__hydro_deploy_{}_source", shared_handle),
1244            Span::call_site(),
1245        );
1246
1247        let sink_ident = syn::Ident::new(
1248            &format!("__hydro_deploy_{}_sink", shared_handle),
1249            Span::call_site(),
1250        );
1251
1252        let bind_addr = format!("0.0.0.0:{}", p2_port);
1253
1254        extra_stmts.push(syn::parse_quote! {
1255            let #socket_ident = tokio::net::TcpListener::bind(#bind_addr).await.unwrap();
1256        });
1257
1258        let create_expr = deploy_containerized_external_sink_source_ident(socket_ident);
1259
1260        extra_stmts.push(syn::parse_quote! {
1261            let (#sink_ident, #source_ident) = (#create_expr).split();
1262        });
1263
1264        parse_quote!(#source_ident)
1265    }
1266
1267    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port, ?many, ?server_hint))]
1268    fn e2o_connect(
1269        p1: &Self::External,
1270        p1_port: &<Self::External as Node>::Port,
1271        p2: &Self::Process,
1272        p2_port: &<Self::Process as Node>::Port,
1273        many: bool,
1274        server_hint: NetworkHint,
1275    ) -> Box<dyn FnOnce()> {
1276        assert!(
1277            server_hint == NetworkHint::Auto,
1278            "Docker deployment only supports NetworkHint::Auto, got {:?}",
1279            server_hint
1280        );
1281
1282        // For many connections, we need to populate connection_info so as_bincode_bidi can find it
1283        if many {
1284            p1.connection_info.borrow_mut().insert(
1285                *p1_port,
1286                (
1287                    p2.docker_container_name.clone(),
1288                    *p2_port,
1289                    p2.network.clone(),
1290                ),
1291            );
1292        }
1293
1294        let serialized = format!("e2o_connect {}:{p1_port} -> {}:{p2_port}", p1.name, p2.name);
1295
1296        Box::new(move || {
1297            trace!(name: "e2o_connect thunk", %serialized);
1298        })
1299    }
1300
1301    #[instrument(level = "trace", skip_all, fields(p1 = p1.name, %p1_port, p2 = p2.name, %p2_port, %shared_handle))]
1302    fn o2e_sink(
1303        p1: &Self::Process,
1304        p1_port: &<Self::Process as Node>::Port,
1305        p2: &Self::External,
1306        p2_port: &<Self::External as Node>::Port,
1307        shared_handle: String,
1308    ) -> syn::Expr {
1309        let sink_ident = syn::Ident::new(
1310            &format!("__hydro_deploy_{}_sink", shared_handle),
1311            Span::call_site(),
1312        );
1313        parse_quote!(#sink_ident)
1314    }
1315
1316    #[instrument(level = "trace", skip_all, fields(%of_cluster))]
1317    fn cluster_ids(of_cluster: LocationKey) -> syn::Expr {
1318        cluster_ids().splice_untyped()
1319    }
1320
1321    #[instrument(level = "trace", skip_all)]
1322    fn cluster_self_id() -> syn::Expr {
1323        cluster_self_id().splice_untyped()
1324    }
1325
1326    #[instrument(level = "trace", skip_all, fields(?location_id))]
1327    fn cluster_membership_stream(
1328        _env: &mut Self::InstantiateEnv,
1329        _at_location: &LocationId,
1330        location_id: &LocationId,
1331    ) -> syn::Expr {
1332        cluster_membership_stream(location_id).splice_untyped()
1333    }
1334}
1335
1336const CONTAINER_ALPHABET: [char; 36] = [
1337    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
1338    'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
1339];
1340
1341fn is_valid_docker_image_name(name: &str) -> bool {
1342    regex::Regex::new(r"^[a-z0-9]+([._-][a-z0-9]+)*$")
1343        .unwrap()
1344        .is_match(name)
1345}
1346
1347#[instrument(level = "trace", skip_all, ret, fields(%name_hint, %location_key, %deployment_instance))]
1348fn get_docker_image_name(
1349    name_hint: &str,
1350    location_key: LocationKey,
1351    deployment_instance: &str,
1352) -> String {
1353    let name_hint: String = name_hint
1354        .split("::")
1355        .last()
1356        .unwrap()
1357        .to_ascii_lowercase()
1358        .split(['.', '_', '-'])
1359        .filter(|s| !s.is_empty())
1360        .collect::<Vec<_>>()
1361        .join("-");
1362
1363    let image_name = format!("hy-{name_hint}-{deployment_instance}-{location_key}");
1364
1365    assert!(
1366        is_valid_docker_image_name(&image_name),
1367        "Generated Docker image name '{image_name}' is not a valid Docker image name. \
1368         Docker image names may only contain lowercase alphanumeric characters \
1369         separated by single '.', '_', or '-' characters, and must start and end \
1370         with an alphanumeric character. The most likely cause is your location \
1371         struct name '{name_hint}'"
1372    );
1373
1374    image_name
1375}
1376
1377#[instrument(level = "trace", skip_all, ret, fields(%image_name, ?instance))]
1378fn get_docker_container_name(image_name: &str, instance: Option<usize>) -> String {
1379    if let Some(instance) = instance {
1380        format!("{image_name}-{instance}")
1381    } else {
1382        image_name.to_owned()
1383    }
1384}
1385/// Represents a Process running in a docker container
1386#[derive(Clone)]
1387pub struct DockerDeployProcessSpec {
1388    rustflags: Option<String>,
1389    config: Vec<String>,
1390    network: DockerNetwork,
1391    deployment_instance: String,
1392    base_image: Option<String>,
1393    linux_compile_type: LinuxCompileType,
1394    features: Vec<String>,
1395}
1396
1397impl<'a> ProcessSpec<'a, DockerDeploy> for DockerDeployProcessSpec {
1398    #[instrument(level = "trace", skip_all, fields(%key, %name_hint))]
1399    fn build(self, key: LocationKey, name_hint: &'_ str) -> <DockerDeploy as Deploy<'a>>::Process {
1400        DockerDeployProcess {
1401            key,
1402            name: get_docker_image_name(name_hint, key, &self.deployment_instance),
1403
1404            next_port: Rc::new(RefCell::new(1000)),
1405            rust_crate: Rc::new(RefCell::new(None)),
1406
1407            exposed_ports: Rc::new(RefCell::new(Vec::new())),
1408
1409            docker_container_name: Rc::new(RefCell::new(None)),
1410
1411            rustflags: self.rustflags,
1412            config: self.config,
1413
1414            network: self.network.clone(),
1415
1416            base_image: self.base_image,
1417            linux_compile_type: self.linux_compile_type,
1418            features: self.features,
1419        }
1420    }
1421}
1422
1423/// Represents a Cluster running across `count` docker containers.
1424#[derive(Clone)]
1425pub struct DockerDeployClusterSpec {
1426    rustflags: Option<String>,
1427    config: Vec<String>,
1428    count: usize,
1429    deployment_instance: String,
1430    base_image: Option<String>,
1431    linux_compile_type: LinuxCompileType,
1432    features: Vec<String>,
1433}
1434
1435impl<'a> ClusterSpec<'a, DockerDeploy> for DockerDeployClusterSpec {
1436    #[instrument(level = "trace", skip_all, fields(%key, %name_hint))]
1437    fn build(self, key: LocationKey, name_hint: &str) -> <DockerDeploy as Deploy<'a>>::Cluster {
1438        DockerDeployCluster {
1439            key,
1440            name: get_docker_image_name(name_hint, key, &self.deployment_instance),
1441
1442            next_port: Rc::new(RefCell::new(1000)),
1443            rust_crate: Rc::new(RefCell::new(None)),
1444
1445            exposed_ports: Rc::new(RefCell::new(Vec::new())),
1446
1447            docker_container_name: Rc::new(RefCell::new(Vec::new())),
1448
1449            rustflags: self.rustflags,
1450            config: self.config,
1451
1452            count: self.count,
1453
1454            base_image: self.base_image,
1455            linux_compile_type: self.linux_compile_type,
1456            features: self.features,
1457        }
1458    }
1459}
1460
1461impl DockerDeployProcessSpec {
1462    /// Set the base Docker image for this process.
1463    /// Defaults to `scratch` if not specified.
1464    pub fn base_image(mut self, image: impl Into<String>) -> Self {
1465        self.base_image = Some(image.into());
1466        self
1467    }
1468
1469    /// Set the Linux compile type (glibc or musl) for this process.
1470    /// Defaults to `Musl` if not specified.
1471    pub fn linux_compile_type(mut self, compile_type: LinuxCompileType) -> Self {
1472        self.linux_compile_type = compile_type;
1473        self
1474    }
1475
1476    /// Add features to enable when compiling the final binary.
1477    pub fn features(mut self, features: impl IntoIterator<Item = impl Into<String>>) -> Self {
1478        self.features.extend(features.into_iter().map(Into::into));
1479        self
1480    }
1481
1482    /// Add a single feature to enable when compiling the final binary.
1483    pub fn feature(mut self, feature: impl Into<String>) -> Self {
1484        self.features.push(feature.into());
1485        self
1486    }
1487}
1488
1489impl DockerDeployClusterSpec {
1490    /// Set the base Docker image for this cluster.
1491    /// Defaults to `scratch` if not specified.
1492    pub fn base_image(mut self, image: impl Into<String>) -> Self {
1493        self.base_image = Some(image.into());
1494        self
1495    }
1496
1497    /// Set the Linux compile type (glibc or musl) for this cluster.
1498    /// Defaults to `Musl` if not specified.
1499    pub fn linux_compile_type(mut self, compile_type: LinuxCompileType) -> Self {
1500        self.linux_compile_type = compile_type;
1501        self
1502    }
1503
1504    /// Add features to enable when compiling the final binary.
1505    pub fn features(mut self, features: impl IntoIterator<Item = impl Into<String>>) -> Self {
1506        self.features.extend(features.into_iter().map(Into::into));
1507        self
1508    }
1509
1510    /// Add a single feature to enable when compiling the final binary.
1511    pub fn feature(mut self, feature: impl Into<String>) -> Self {
1512        self.features.push(feature.into());
1513        self
1514    }
1515}
1516
1517/// Represents an external process outside of the management of hydro deploy.
1518pub struct DockerDeployExternalSpec {
1519    name: String,
1520}
1521
1522impl<'a> ExternalSpec<'a, DockerDeploy> for DockerDeployExternalSpec {
1523    #[instrument(level = "trace", skip_all, fields(%key, %name_hint))]
1524    fn build(self, key: LocationKey, name_hint: &str) -> <DockerDeploy as Deploy<'a>>::External {
1525        DockerDeployExternal {
1526            key,
1527            name: self.name,
1528            next_port: Rc::new(RefCell::new(10000)),
1529            next_external_port_id: Rc::new(RefCell::new(crate::Counter::default())),
1530            ports: Rc::new(RefCell::new(HashMap::new())),
1531            connection_info: Rc::new(RefCell::new(HashMap::new())),
1532        }
1533    }
1534}