Skip to main content

hydro_lang/deploy/
deploy_runtime_containerized.rs

1#![allow(
2    unused,
3    reason = "unused in trybuild but the __staged version is needed"
4)]
5#![allow(missing_docs, reason = "used internally")]
6
7use std::collections::HashMap;
8use std::future::Future;
9use std::net::SocketAddr;
10use std::ops::{Deref, DerefMut};
11use std::pin::Pin;
12use std::sync::Arc;
13use std::task::{Context, Poll};
14use std::time::Duration;
15
16use bytes::BytesMut;
17use futures::{FutureExt, Sink, SinkExt, Stream, StreamExt};
18use proc_macro2::Span;
19use sinktools::demux_map_lazy::LazyDemuxSink;
20use sinktools::lazy::{LazySink, LazySource};
21use sinktools::lazy_sink_source::LazySinkSource;
22use stageleft::runtime_support::{
23    FreeVariableWithContext, FreeVariableWithContextWithProps, QuoteTokens,
24};
25use stageleft::{QuotedWithContext, q};
26use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
27use tokio::net::{TcpListener, TcpStream};
28use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec};
29use tracing::{debug, instrument, warn};
30
31use crate::location::dynamic::LocationId;
32use crate::location::{LocationKey, MemberId, MembershipEvent};
33
34/// The single well-known port that every node listens on.
35pub const CHANNEL_MUX_PORT: u16 = 10000;
36
37/// Magic constant embedded in every [`ChannelMagic`] header.
38pub const CHANNEL_MAGIC: u64 = 0x4859_4452_4F5F_4348;
39
40/// Magic header sent as the very first frame of every channel handshake.
41///
42/// This is a fixed value that never changes across versions, used to confirm
43/// both sides are speaking the same protocol family before anything else.
44#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
45pub struct ChannelMagic {
46    pub magic: u64,
47}
48
49/// Current protocol version for the channel handshake.
50pub const CHANNEL_PROTOCOL_VERSION: u64 = 1;
51
52/// Protocol version sent as the second frame, after [`ChannelMagic`].
53///
54/// Incremented when the handshake format changes. The receiver checks this
55/// to decide how to deserialize the subsequent [`ChannelHandshake`] frame.
56#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
57pub struct ChannelProtocolVersion {
58    pub version: u64,
59}
60
61/// Handshake message sent by the connecting side to identify the channel.
62///
63/// The receiver reads the third frame (after [`ChannelMagic`] and
64/// [`ChannelProtocolVersion`]) to know which logical channel the connection
65/// belongs to, and optionally which cluster member is connecting.
66/// cluster member is connecting.
67#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
68pub struct ChannelHandshake {
69    /// The logical channel name for this connection.
70    pub channel_name: String,
71    /// If the sender is a cluster member, this is its identifier
72    /// (container name for Docker, task ID for ECS, etc.).
73    /// `None` for process-to-process connections.
74    pub sender_id: Option<String>,
75}
76
77/// A dispatched channel connection: optional sender ID and the read stream.
78type MuxConnection = (
79    Option<String>,
80    FramedRead<OwnedReadHalf, LengthDelimitedCodec>,
81);
82
83/// A shared accept loop that listens on a single port and dispatches
84/// incoming connections to the right consumer based on the channel name
85/// sent in the handshake.
86///
87/// Each node creates one of these at startup. Individual channels register
88/// themselves and receive their connection via a mpsc channel.
89pub struct ChannelMux {
90    /// Map from channel name to a sender that delivers accepted connections.
91    channels: std::sync::Mutex<HashMap<String, tokio::sync::mpsc::UnboundedSender<MuxConnection>>>,
92}
93
94impl Default for ChannelMux {
95    fn default() -> Self {
96        Self::new()
97    }
98}
99
100impl ChannelMux {
101    pub fn new() -> Self {
102        Self {
103            channels: std::sync::Mutex::new(HashMap::new()),
104        }
105    }
106
107    pub fn register(
108        &self,
109        channel_name: String,
110    ) -> tokio::sync::mpsc::UnboundedReceiver<MuxConnection> {
111        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
112        let mut channels = self.channels.lock().unwrap();
113        channels.insert(channel_name, tx);
114        rx
115    }
116
117    pub async fn run_accept_loop(self: Arc<Self>, listener: TcpListener) {
118        loop {
119            let (stream, peer) = match listener.accept().await {
120                Ok(v) => v,
121                Err(e) => {
122                    warn!(name: "accept_error", error = %e);
123                    continue;
124                }
125            };
126            debug!(name: "mux_accepting", ?peer);
127
128            let mux = self.clone();
129            tokio::spawn(async move {
130                // Accepted streams are read-only; if a write path is ever added,
131                // set TCP_NODELAY first (see connect_channel).
132                let (rx, _tx) = stream.into_split();
133                let mut source = FramedRead::new(rx, LengthDelimitedCodec::new());
134
135                let Some(Ok(magic_frame)) = source.next().await else {
136                    warn!(name: "magic_failed", ?peer, "no magic frame");
137                    return;
138                };
139
140                let magic: ChannelMagic = match bincode::deserialize(&magic_frame) {
141                    Ok(m) => m,
142                    Err(e) => {
143                        warn!(name: "magic_deserialize_failed", ?peer, error = %e);
144                        return;
145                    }
146                };
147
148                if magic.magic != CHANNEL_MAGIC {
149                    warn!(name: "bad_magic", ?peer, magic = magic.magic, expected = CHANNEL_MAGIC);
150                    return;
151                }
152
153                let Some(Ok(version_frame)) = source.next().await else {
154                    warn!(name: "version_failed", ?peer, "no version frame");
155                    return;
156                };
157
158                let version: ChannelProtocolVersion = match bincode::deserialize(&version_frame) {
159                    Ok(v) => v,
160                    Err(e) => {
161                        warn!(name: "version_deserialize_failed", ?peer, error = %e);
162                        return;
163                    }
164                };
165
166                if version.version != CHANNEL_PROTOCOL_VERSION {
167                    warn!(name: "version_mismatch", ?peer, version = version.version, expected = CHANNEL_PROTOCOL_VERSION);
168                    return;
169                }
170
171                let Some(Ok(handshake_frame)) = source.next().await else {
172                    warn!(name: "handshake_failed", ?peer, "no handshake frame");
173                    return;
174                };
175
176                let handshake: ChannelHandshake = match bincode::deserialize(&handshake_frame) {
177                    Ok(h) => h,
178                    Err(e) => {
179                        warn!(name: "handshake_deserialize_failed", ?peer, error = %e);
180                        return;
181                    }
182                };
183
184                debug!(name: "handshake_received", ?peer, ?handshake);
185
186                let channels = mux.channels.lock().unwrap();
187                if let Some(tx_chan) = channels.get(&handshake.channel_name) {
188                    let _ = tx_chan.send((handshake.sender_id, source));
189                } else {
190                    warn!(
191                        name: "unknown_channel",
192                        channel_name = %handshake.channel_name,
193                        ?peer,
194                        "no registered consumer for channel"
195                    );
196                }
197            });
198        }
199    }
200}
201
202/// Get or initialize the global `ChannelMux` for this process.
203///
204/// The first call creates the `TcpListener` and spawns the accept loop.
205/// Subsequent calls return the same `Arc<ChannelMux>`.
206pub fn get_or_init_channel_mux() -> Arc<ChannelMux> {
207    use std::sync::OnceLock;
208    static MUX: OnceLock<Arc<ChannelMux>> = OnceLock::new();
209
210    MUX.get_or_init(|| {
211        let mux = Arc::new(ChannelMux::new());
212        let mux_clone = mux.clone();
213
214        // Spawn the accept loop in a background task.
215        // We use tokio::spawn which requires a runtime to be active.
216        tokio::spawn(async move {
217            let bind_addr = format!("0.0.0.0:{}", CHANNEL_MUX_PORT);
218            debug!(name: "mux_listening", %bind_addr);
219            let listener = TcpListener::bind(&bind_addr)
220                .await
221                .expect("failed to bind channel mux listener");
222            mux_clone.run_accept_loop(listener).await;
223        });
224
225        mux
226    })
227    .clone()
228}
229
230/// Sends a [`ChannelMagic`], then a [`ChannelProtocolVersion`], then a
231/// [`ChannelHandshake`] as three separate frames over the given sink.
232pub async fn send_handshake(
233    sink: &mut FramedWrite<TcpStream, LengthDelimitedCodec>,
234    channel_name: &str,
235    sender_id: Option<&str>,
236) -> Result<(), std::io::Error> {
237    let magic = ChannelMagic {
238        magic: CHANNEL_MAGIC,
239    };
240    sink.send(bytes::Bytes::from(bincode::serialize(&magic).unwrap()))
241        .await?;
242
243    let version = ChannelProtocolVersion {
244        version: CHANNEL_PROTOCOL_VERSION,
245    };
246    sink.send(bytes::Bytes::from(bincode::serialize(&version).unwrap()))
247        .await?;
248
249    let handshake = ChannelHandshake {
250        channel_name: channel_name.to_owned(),
251        sender_id: sender_id.map(|s| s.to_owned()),
252    };
253    sink.send(bytes::Bytes::from(bincode::serialize(&handshake).unwrap()))
254        .await?;
255    Ok(())
256}
257
258/// Connects to a channel endpoint, enabling `TCP_NODELAY` so Nagle's
259/// algorithm (combined with delayed ACKs) doesn't stall small writes.
260/// Failure to set the option is non-fatal, so we just log a warning.
261pub async fn connect_channel(target: &str) -> Result<TcpStream, std::io::Error> {
262    let stream = TcpStream::connect(target).await?;
263    if let Err(e) = stream.set_nodelay(true) {
264        warn!(name: "set_nodelay_failed", %target, error = %e);
265    }
266    Ok(stream)
267}
268
269pub fn deploy_containerized_o2o(target: &str, channel_name: &str) -> (syn::Expr, syn::Expr) {
270    (
271        q!(LazySink::<_, _, _, bytes::Bytes>::new(move || Box::pin(
272            async move {
273                let channel_name = channel_name;
274                let target = format!("{}:{}", target, self::CHANNEL_MUX_PORT);
275                debug!(name: "connecting", %target, %channel_name);
276
277                let stream = self::connect_channel(&target).await?;
278                let mut sink = FramedWrite::new(stream, LengthDelimitedCodec::new());
279
280                self::send_handshake(&mut sink, channel_name, None).await?;
281
282                Result::<_, std::io::Error>::Ok(sink)
283            }
284        )))
285        .splice_untyped_ctx(&()),
286        q!(LazySource::new(move || Box::pin(async move {
287            let channel_name = channel_name;
288            let mux = self::get_or_init_channel_mux();
289            let mut rx = mux.register(channel_name.to_owned());
290
291            let (_sender_id, source) = rx.recv().await.ok_or_else(|| {
292                std::io::Error::new(std::io::ErrorKind::ConnectionReset, "channel mux closed")
293            })?;
294
295            debug!(name: "o2o_channel_connected", %channel_name);
296
297            Result::<_, std::io::Error>::Ok(source)
298        })))
299        .splice_untyped_ctx(&()),
300    )
301}
302
303pub fn deploy_containerized_o2m(channel_name: &str) -> (syn::Expr, syn::Expr) {
304    (
305        q!(sinktools::demux_map_lazy::<_, _, _, _>(
306            move |key: &String| {
307                let key = key.clone();
308                let channel_name = channel_name.to_owned();
309
310                LazySink::<_, _, _, bytes::Bytes>::new(move || {
311                    Box::pin(async move {
312                        let target = format!("{}:{}", key.as_str(), self::CHANNEL_MUX_PORT);
313                        debug!(name: "connecting", %target, channel_name = %channel_name);
314
315                        let stream = self::connect_channel(&target).await?;
316                        let mut sink = FramedWrite::new(stream, LengthDelimitedCodec::new());
317
318                        self::send_handshake(&mut sink, &channel_name, None).await?;
319
320                        Result::<_, std::io::Error>::Ok(sink)
321                    })
322                })
323            }
324        ))
325        .splice_untyped_ctx(&()),
326        q!(LazySource::new(move || Box::pin(async move {
327            let channel_name = channel_name;
328            let mux = self::get_or_init_channel_mux();
329            let mut rx = mux.register(channel_name.to_owned());
330
331            let (_sender_id, source) = rx.recv().await.ok_or_else(|| {
332                std::io::Error::new(std::io::ErrorKind::ConnectionReset, "channel mux closed")
333            })?;
334
335            debug!(name: "o2m_channel_connected", %channel_name);
336
337            Result::<_, std::io::Error>::Ok(source)
338        })))
339        .splice_untyped_ctx(&()),
340    )
341}
342
343pub fn deploy_containerized_m2o(target_host: &str, channel_name: &str) -> (syn::Expr, syn::Expr) {
344    (
345        q!(LazySink::<_, _, _, bytes::Bytes>::new(move || {
346            Box::pin(async move {
347                let channel_name = channel_name;
348                let target = format!("{}:{}", target_host, self::CHANNEL_MUX_PORT);
349                debug!(name: "connecting", %target, %channel_name);
350
351                let stream = self::connect_channel(&target).await?;
352                let mut sink = FramedWrite::new(stream, LengthDelimitedCodec::new());
353
354                let container_name = std::env::var("CONTAINER_NAME").unwrap();
355                self::send_handshake(&mut sink, channel_name, Some(&container_name)).await?;
356
357                Result::<_, std::io::Error>::Ok(sink)
358            })
359        }))
360        .splice_untyped_ctx(&()),
361        q!(LazySource::new(move || Box::pin(async move {
362            let channel_name = channel_name;
363            let mux = self::get_or_init_channel_mux();
364            let mut rx = mux.register(channel_name.to_owned());
365
366            Result::<_, std::io::Error>::Ok(
367                futures::stream::unfold(rx, |mut rx| {
368                    Box::pin(async move {
369                        let (sender_id, source) = rx.recv().await?;
370                        let from = sender_id.expect("m2o sender must provide container name");
371
372                        debug!(name: "m2o_channel_connected", %from);
373
374                        Some((source.map(move |v| v.map(|v| (from.clone(), v))), rx))
375                    })
376                })
377                .flatten_unordered(None),
378            )
379        })))
380        .splice_untyped_ctx(&()),
381    )
382}
383
384pub fn deploy_containerized_m2m(channel_name: &str) -> (syn::Expr, syn::Expr) {
385    (
386        q!(sinktools::demux_map_lazy::<_, _, _, _>(
387            move |key: &String| {
388                let key = key.clone();
389                let channel_name = channel_name.to_owned();
390
391                LazySink::<_, _, _, bytes::Bytes>::new(move || {
392                    Box::pin(async move {
393                        let target = format!("{}:{}", key.as_str(), self::CHANNEL_MUX_PORT);
394                        debug!(name: "connecting", %target, channel_name = %channel_name);
395
396                        let stream = self::connect_channel(&target).await?;
397                        let mut sink = FramedWrite::new(stream, LengthDelimitedCodec::new());
398
399                        let container_name = std::env::var("CONTAINER_NAME").unwrap();
400                        self::send_handshake(&mut sink, &channel_name, Some(&container_name))
401                            .await?;
402
403                        Result::<_, std::io::Error>::Ok(sink)
404                    })
405                })
406            }
407        ))
408        .splice_untyped_ctx(&()),
409        q!(LazySource::new(move || Box::pin(async move {
410            let channel_name = channel_name;
411            let mux = self::get_or_init_channel_mux();
412            let mut rx = mux.register(channel_name.to_owned());
413
414            Result::<_, std::io::Error>::Ok(
415                futures::stream::unfold(rx, |mut rx| {
416                    Box::pin(async move {
417                        let (sender_id, source) = rx.recv().await?;
418                        let from = sender_id.expect("m2m sender must provide container name");
419
420                        debug!(name: "m2m_channel_connected", %from);
421
422                        Some((source.map(move |v| v.map(|v| (from.clone(), v))), rx))
423                    })
424                })
425                .flatten_unordered(None),
426            )
427        })))
428        .splice_untyped_ctx(&()),
429    )
430}
431
432pub struct SocketIdent {
433    pub socket_ident: syn::Ident,
434}
435
436impl<Ctx> FreeVariableWithContextWithProps<Ctx, ()> for SocketIdent {
437    type O = TcpListener;
438
439    fn to_tokens(self, _ctx: &Ctx) -> (QuoteTokens, ())
440    where
441        Self: Sized,
442    {
443        let ident = self.socket_ident;
444
445        (
446            QuoteTokens {
447                prelude: None,
448                expr: Some(quote::quote! { #ident }),
449            },
450            (),
451        )
452    }
453}
454
455pub fn deploy_containerized_external_sink_source_ident(socket_ident: syn::Ident) -> syn::Expr {
456    let socket_ident = SocketIdent { socket_ident };
457
458    q!(LazySinkSource::<
459        _,
460        FramedRead<OwnedReadHalf, LengthDelimitedCodec>,
461        FramedWrite<OwnedWriteHalf, LengthDelimitedCodec>,
462        bytes::Bytes,
463        std::io::Error,
464    >::new(async move {
465        let (stream, peer) = socket_ident.accept().await?;
466        debug!(name: "external accepting", ?peer);
467        let (rx, tx) = stream.into_split();
468
469        let fr = FramedRead::new(rx, LengthDelimitedCodec::new());
470        let fw = FramedWrite::new(tx, LengthDelimitedCodec::new());
471
472        Result::<_, std::io::Error>::Ok((fr, fw))
473    },))
474    .splice_untyped_ctx(&())
475}
476
477pub fn cluster_ids<'a>() -> impl QuotedWithContext<'a, &'a [String], ()> + Clone {
478    // unimplemented!(); // this is unused.
479
480    // This is a dummy piece of code, since clusters are dynamic when containerized.
481    q!(Box::leak(Box::new([String::from(
482        "INVALID CONTAINER NAME cluster_ids"
483    )]))
484    .as_slice())
485}
486
487#[cfg(feature = "docker_runtime")]
488pub fn cluster_self_id<'a>() -> impl QuotedWithContext<'a, String, ()> + Clone + 'a {
489    q!(std::env::var("CONTAINER_NAME").unwrap())
490}
491
492#[cfg(feature = "docker_runtime")]
493pub fn cluster_membership_stream<'a>(
494    location_id: &LocationId,
495) -> impl QuotedWithContext<'a, Box<dyn Stream<Item = (String, MembershipEvent)> + Unpin>, ()> {
496    let key = location_id.key();
497
498    q!(Box::new(self::docker_membership_stream(
499        std::env::var("DEPLOYMENT_INSTANCE").unwrap(),
500        key
501    ))
502        as Box<
503            dyn Stream<Item = (String, MembershipEvent)> + Unpin,
504        >)
505}
506
507#[cfg(feature = "docker_runtime")]
508// There's a risk of race conditions here since all the containers will be starting up at the same time.
509// So we need to start listening for events and the take a snapshot of currently running containers, since they may have already started up before we started listening to events.
510// Then we need to turn that into a usable stream for the consumer in this current hydro program. The way you do that is by emitting from the snapshot first, and then start emitting from the stream. Keep a hash set around to track whether a container is up or down.
511#[instrument(skip_all, fields(%deployment_instance, %location_key))]
512fn docker_membership_stream(
513    deployment_instance: String,
514    location_key: LocationKey,
515) -> impl Stream<Item = (String, MembershipEvent)> + Unpin {
516    use std::collections::HashSet;
517    use std::sync::{Arc, Mutex};
518
519    use bollard::Docker;
520    use bollard::query_parameters::{EventsOptions, ListContainersOptions};
521    use tokio::sync::mpsc;
522
523    let docker = Docker::connect_with_local_defaults()
524        .unwrap()
525        .with_timeout(Duration::from_secs(1));
526
527    let (event_tx, event_rx) = mpsc::unbounded_channel::<(String, MembershipEvent)>();
528
529    // 1. Start event subscription in a spawned task
530    let events_docker = docker.clone();
531    let events_deployment_instance = deployment_instance.clone();
532    tokio::spawn(async move {
533        let mut filters = HashMap::new();
534        filters.insert("type".to_owned(), vec!["container".to_owned()]);
535        filters.insert(
536            "event".to_owned(),
537            vec!["start".to_owned(), "die".to_owned()],
538        );
539        let event_options = Some(EventsOptions {
540            filters: Some(filters),
541            ..Default::default()
542        });
543
544        let mut events = events_docker.events(event_options);
545        while let Some(event) = events.next().await {
546            if let Some((name, membership_event)) = event.ok().and_then(|e| {
547                let name = e
548                    .actor
549                    .as_ref()
550                    .and_then(|a| a.attributes.as_ref())
551                    .and_then(|attrs| attrs.get("name"))
552                    .map(|s| &**s)?;
553
554                if name.contains(format!("{events_deployment_instance}-{location_key}").as_str()) {
555                    match e.action.as_deref() {
556                        Some("start") => Some((name.to_owned(), MembershipEvent::Joined)),
557                        Some("die") => Some((name.to_owned(), MembershipEvent::Left)),
558                        _ => None,
559                    }
560                } else {
561                    None
562                }
563            }) && event_tx.send((name, membership_event)).is_err()
564            {
565                break;
566            }
567        }
568    });
569
570    // Shared state for deduplication across snapshot and events phases
571    let seen_joined = Arc::new(Mutex::new(HashSet::<String>::new()));
572    let seen_joined_snapshot = seen_joined.clone();
573    let seen_joined_events = seen_joined;
574
575    // 2. Snapshot stream - fetch current containers and emit Joined events
576    let snapshot_stream = futures::stream::once(async move {
577        let mut filters = HashMap::new();
578        filters.insert(
579            "name".to_owned(),
580            vec![format!("{deployment_instance}-{location_key}")],
581        );
582        let options = Some(ListContainersOptions {
583            filters: Some(filters),
584            ..Default::default()
585        });
586
587        docker
588            .list_containers(options)
589            .await
590            .unwrap_or_default()
591            .iter()
592            .filter_map(|c| c.names.as_deref())
593            .filter_map(|names| names.first())
594            .map(|name| name.trim_start_matches('/'))
595            .filter(|&name| seen_joined_snapshot.lock().unwrap().insert(name.to_owned()))
596            .map(|name| (name.to_owned(), MembershipEvent::Joined))
597            .collect::<Vec<_>>()
598    })
599    .flat_map(futures::stream::iter);
600
601    // 3. Events stream - process live events with deduplication
602    let events_stream = tokio_stream::StreamExt::filter_map(
603        tokio_stream::wrappers::UnboundedReceiverStream::new(event_rx),
604        move |(name, event)| {
605            let mut seen = seen_joined_events.lock().unwrap();
606            match event {
607                MembershipEvent::Joined => {
608                    if seen.insert(name.clone()) {
609                        Some((name, MembershipEvent::Joined))
610                    } else {
611                        None
612                    }
613                }
614                MembershipEvent::Left => seen.take(&name).map(|name| (name, MembershipEvent::Left)),
615            }
616        },
617    );
618
619    // 4. Chain snapshot then events
620    Box::pin(
621        snapshot_stream
622            .chain(events_stream)
623            .inspect(|(member_id, event)| debug!(name: "membership_event", ?member_id, ?event)),
624    )
625}