Skip to main content

hydro_lang/compile/
embedded.rs

1//! "Embedded" deployment backend for Hydro.
2//!
3//! Instead of compiling each location into a standalone binary, this backend generates
4//! a Rust source file containing one function per location. Each function returns a
5//! `dfir_rs::scheduled::graph::Dfir` that can be manually driven by the caller.
6//!
7//! This is useful when you want full control over where and how the projected DFIR
8//! code runs (e.g. embedding it into an existing application).
9//!
10//! # Networking
11//!
12//! Process and cluster networking (o2o, o2m, m2o, m2m) is supported. When a location has network
13//! sends or receives, the generated function takes additional `network_out` and
14//! `network_in` parameters whose types are generated structs with one field per
15//! network port (named after the channel). Network channels must be named via
16//! `.name()` on the networking config.
17//!
18//! - Sinks (`EmbeddedNetworkOut`): one `FnMut(..)` field per outgoing channel, wrapped in a
19//!   [`EmbeddedNetworkOutputChannel`](crate::compile::embedded_runtime::EmbeddedNetworkOutputChannel).
20//! - Sources (`EmbeddedNetworkIn`): one `Stream` field per incoming channel, wrapped in a
21//!   [`EmbeddedNetworkInputChannel`](crate::compile::embedded_runtime::EmbeddedNetworkInputChannel).
22//!
23//! Each location's module also has a marker type per channel end (`outgoing::*` and
24//! `incoming::*`) implementing
25//! [`EmbeddedNetworkChannel`](crate::compile::embedded_runtime::EmbeddedNetworkChannel), which
26//! describes the field's channel end: the guarantees of the stream there (the stream sent, or the
27//! one delivered) and the channel's network config, which the host agrees to.
28//!
29//! The exact field types depend on the channel's serialization:
30//! - With [`bincode`](crate::networking::Bincode) serialization, Hydro serializes to bytes, so
31//!   sinks are `FnMut(Bytes)` and sources are `Stream<Item = Result<BytesMut, io::Error>>`.
32//! - With [`embedded`](crate::networking::Embedded) serialization, the raw element type `T` flows
33//!   across the channel, so sinks are `FnMut(T)` and sources are `Stream<Item = T>` (with no
34//!   transport `Result` — the caller decides how to handle faults).
35//!
36//! Channels addressed to cluster members (demux, cluster sends) also carry the member's ID.
37//! Its type is the `Id` the cluster was created with, which the host chooses.
38//!
39//! The caller is responsible for wiring these together (e.g. via in-memory channels,
40//! sockets, etc.). External ports are not supported.
41
42use std::future::Future;
43use std::io::Error;
44use std::pin::Pin;
45
46use bytes::{Bytes, BytesMut};
47use dfir_lang::diagnostic::Diagnostics;
48use dfir_lang::graph::{AsCodeOptions, DfirGraph};
49use futures::{Sink, Stream};
50use proc_macro2::Span;
51use quote::quote;
52use serde::Serialize;
53use serde::de::DeserializeOwned;
54use slotmap::SparseSecondaryMap;
55
56use super::deploy_provider::{ClusterSpec, Deploy, ExternalSpec, Node, ProcessSpec, RegisterPort};
57use crate::compile::builder::ExternalPortId;
58use crate::compile::ir::NetworkSink;
59use crate::location::dynamic::LocationId;
60use crate::location::{LocationKey, NetworkHint};
61
62/// Marker type for the embedded deployment backend.
63///
64/// All networking methods panic — this backend only supports pure local computation.
65pub enum EmbeddedDeploy {}
66
67/// A trivial node type for embedded deployment. Stores a user-provided function name.
68#[derive(Clone)]
69pub struct EmbeddedNode {
70    /// The function name to use in the generated code for this location.
71    pub fn_name: String,
72    /// The location key for this node, used to register network ports.
73    pub location_key: LocationKey,
74}
75
76impl Node for EmbeddedNode {
77    type Port = ();
78    type Meta = ();
79    type InstantiateEnv = EmbeddedInstantiateEnv;
80
81    fn next_port(&self) -> Self::Port {}
82
83    fn update_meta(&self, _meta: &Self::Meta) {}
84
85    fn instantiate(
86        &self,
87        _env: &mut Self::InstantiateEnv,
88        _meta: &mut Self::Meta,
89        _graph: DfirGraph,
90        _extra_stmts: &[syn::Stmt],
91        _sidecars: &[syn::Expr],
92        _as_code_options: &AsCodeOptions,
93    ) {
94        // No-op: embedded mode doesn't instantiate nodes at deploy time.
95    }
96}
97
98impl<'a> RegisterPort<'a, EmbeddedDeploy> for EmbeddedNode {
99    fn register(&self, _external_port_id: ExternalPortId, _port: Self::Port) {
100        panic!("EmbeddedDeploy does not support external ports");
101    }
102
103    #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
104    fn as_bytes_bidi(
105        &self,
106        _external_port_id: ExternalPortId,
107    ) -> impl Future<
108        Output = super::deploy_provider::DynSourceSink<Result<BytesMut, Error>, Bytes, Error>,
109    > + 'a {
110        async { panic!("EmbeddedDeploy does not support external ports") }
111    }
112
113    #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
114    fn as_bincode_bidi<InT, OutT>(
115        &self,
116        _external_port_id: ExternalPortId,
117    ) -> impl Future<Output = super::deploy_provider::DynSourceSink<OutT, InT, Error>> + 'a
118    where
119        InT: Serialize + 'static,
120        OutT: DeserializeOwned + 'static,
121    {
122        async { panic!("EmbeddedDeploy does not support external ports") }
123    }
124
125    #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
126    fn as_bincode_sink<T>(
127        &self,
128        _external_port_id: ExternalPortId,
129    ) -> impl Future<Output = Pin<Box<dyn Sink<T, Error = Error>>>> + 'a
130    where
131        T: Serialize + 'static,
132    {
133        async { panic!("EmbeddedDeploy does not support external ports") }
134    }
135
136    #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
137    fn as_bincode_source<T>(
138        &self,
139        _external_port_id: ExternalPortId,
140    ) -> impl Future<Output = Pin<Box<dyn Stream<Item = T>>>> + 'a
141    where
142        T: DeserializeOwned + 'static,
143    {
144        async { panic!("EmbeddedDeploy does not support external ports") }
145    }
146}
147
148impl<S: Into<String>> ProcessSpec<'_, EmbeddedDeploy> for S {
149    fn build(self, location_key: LocationKey, _name_hint: &str) -> EmbeddedNode {
150        EmbeddedNode {
151            fn_name: self.into(),
152            location_key,
153        }
154    }
155}
156
157impl<S: Into<String>> ClusterSpec<'_, EmbeddedDeploy> for S {
158    fn build(self, location_key: LocationKey, _name_hint: &str) -> EmbeddedNode {
159        EmbeddedNode {
160            fn_name: self.into(),
161            location_key,
162        }
163    }
164}
165
166impl<S: Into<String>> ExternalSpec<'_, EmbeddedDeploy> for S {
167    fn build(self, location_key: LocationKey, _name_hint: &str) -> EmbeddedNode {
168        EmbeddedNode {
169            fn_name: self.into(),
170            location_key,
171        }
172    }
173}
174
175/// One end of a named network channel at a location.
176#[derive(Clone)]
177struct EmbeddedNetworkPort {
178    name: String,
179    /// Whether each element is paired with a member ID of the peer cluster.
180    /// The ID is the destination when sending and the sender when receiving.
181    is_tagged: bool,
182    /// The raw payload type of an unserialized `EMBEDDED` channel; `None` for bincode.
183    external_type: Option<syn::Type>,
184    /// The location at the other end.
185    peer: LocationKey,
186    /// The channel config's transport and serialization types, and the config written out.
187    transport: syn::Type,
188    serialization: syn::Type,
189    config: String,
190}
191
192impl EmbeddedNetworkPort {
193    fn new(
194        name: &str,
195        is_tagged: bool,
196        external_type: Option<&syn::Type>,
197        peer: LocationKey,
198        networking_info: &crate::networking::NetworkingInfo,
199    ) -> Self {
200        let (transport, serialization, config) =
201            channel_config_types(networking_info, external_type.is_some());
202        EmbeddedNetworkPort {
203            name: name.to_owned(),
204            is_tagged,
205            external_type: external_type.cloned(),
206            peer,
207            transport,
208            serialization,
209            config,
210        }
211    }
212}
213
214/// The `Tr` and `S` types of the network config that `networking_info` describes, as the host's
215/// `ChannelConfiguration` names them, and that config written out.
216fn channel_config_types(
217    networking_info: &crate::networking::NetworkingInfo,
218    external: bool,
219) -> (syn::Type, syn::Type, String) {
220    use crate::compile::ir::{StreamOrder, StreamRetry};
221    use crate::networking::{EmbeddedFault, NetworkingInfo, TcpFault, UdpFault};
222    let root = crate::staging_util::get_this_crate();
223    let fault = |name: &str| -> syn::Type {
224        let ident = syn::Ident::new(name, Span::call_site());
225        syn::parse_quote!(#root::networking::#ident)
226    };
227    let transport: syn::Type = match networking_info {
228        NetworkingInfo::Tcp { fault: f } => {
229            let f = fault(match f {
230                TcpFault::FailStop => "FailStop",
231                TcpFault::Lossy => "Lossy",
232                TcpFault::LossyDelayedForever => "LossyDelayedForever",
233            });
234            syn::parse_quote!(#root::networking::Tcp<#f>)
235        }
236        NetworkingInfo::Udp { fault: f } => {
237            let f = fault(match f {
238                UdpFault::Lossy => "Lossy",
239                UdpFault::LossyDelayedForever => "LossyDelayedForever",
240            });
241            syn::parse_quote!(#root::networking::Udp<#f>)
242        }
243        NetworkingInfo::Embedded {
244            retries,
245            ordering,
246            fault: f,
247        } => {
248            let retries: syn::Type = match retries {
249                StreamRetry::ExactlyOnce => {
250                    syn::parse_quote!(#root::live_collections::stream::ExactlyOnce)
251                }
252                StreamRetry::AtLeastOnce => {
253                    syn::parse_quote!(#root::live_collections::stream::AtLeastOnce)
254                }
255            };
256            let ordering: syn::Type = match ordering {
257                StreamOrder::TotalOrder => {
258                    syn::parse_quote!(#root::live_collections::stream::TotalOrder)
259                }
260                StreamOrder::NoOrder => syn::parse_quote!(#root::live_collections::stream::NoOrder),
261            };
262            let f = fault(match f {
263                EmbeddedFault::FailStop => "FailStop",
264                EmbeddedFault::Lossy => "Lossy",
265                EmbeddedFault::LossyDelayedForever => "LossyDelayedForever",
266            });
267            syn::parse_quote!(#root::networking::EmbeddedTransport<#retries, #ordering, #f>)
268        }
269    };
270    let serialization: syn::Type = if external {
271        syn::parse_quote!(#root::networking::Embedded)
272    } else {
273        syn::parse_quote!(#root::networking::Bincode)
274    };
275    (
276        transport,
277        serialization,
278        config_doc(networking_info, external),
279    )
280}
281
282/// The network config that `networking_info` describes, written out for the docs.
283fn config_doc(networking_info: &crate::networking::NetworkingInfo, external: bool) -> String {
284    use crate::compile::ir::{StreamOrder, StreamRetry};
285    use crate::networking::{EmbeddedFault, NetworkingInfo, TcpFault, UdpFault};
286    let serialization = if external { "" } else { ".bincode()" };
287    match networking_info {
288        NetworkingInfo::Tcp { fault } => {
289            let fault = match fault {
290                TcpFault::FailStop => ".fail_stop()",
291                TcpFault::Lossy => ".lossy(nondet)",
292                TcpFault::LossyDelayedForever => ".lossy_delayed_forever()",
293            };
294            format!("TCP{fault}{serialization}")
295        }
296        NetworkingInfo::Udp { fault } => {
297            let fault = match fault {
298                UdpFault::Lossy => ".lossy(nondet)",
299                UdpFault::LossyDelayedForever => ".lossy_delayed_forever()",
300            };
301            format!("UDP{fault}{serialization}")
302        }
303        NetworkingInfo::Embedded {
304            retries,
305            ordering,
306            fault,
307        } => {
308            // `EMBEDDED` with a `never_*` or `may_*` declaration for each anomaly.
309            let reorder = match ordering {
310                StreamOrder::TotalOrder => ".never_reorders()",
311                StreamOrder::NoOrder => ".may_reorder()",
312            };
313            let duplicate = match retries {
314                StreamRetry::ExactlyOnce => ".never_duplicates()",
315                StreamRetry::AtLeastOnce => ".may_duplicate()",
316            };
317            let loss = match fault {
318                EmbeddedFault::FailStop => ".never_drops()",
319                EmbeddedFault::Lossy => ".may_drop(nondet)",
320                EmbeddedFault::LossyDelayedForever => ".may_delay_forever()",
321            };
322            format!("EMBEDDED{reorder}{duplicate}{loss}")
323        }
324    }
325}
326
327/// A stream input or output, by its field name and element type.
328#[derive(Clone)]
329struct EmbeddedStreamPort {
330    ident: syn::Ident,
331    element_type: syn::Type,
332}
333
334/// Collected embedded input/output registrations, keyed by location.
335///
336/// During `compile_network`, each `HydroSource::Embedded` and `HydroRoot::EmbeddedOutput`
337/// IR node registers its ident, element type, and location key here.
338/// `generate_embedded` then uses this to add the appropriate parameters
339/// to each generated function.
340#[derive(Default)]
341pub struct EmbeddedInstantiateEnv {
342    inputs: SparseSecondaryMap<LocationKey, Vec<EmbeddedStreamPort>>,
343    singleton_inputs: SparseSecondaryMap<LocationKey, Vec<(syn::Ident, syn::Type)>>,
344    outputs: SparseSecondaryMap<LocationKey, Vec<EmbeddedStreamPort>>,
345    /// Sending ends of network channels.
346    network_outputs: SparseSecondaryMap<LocationKey, Vec<EmbeddedNetworkPort>>,
347    /// Receiving ends of network channels.
348    network_inputs: SparseSecondaryMap<LocationKey, Vec<EmbeddedNetworkPort>>,
349    /// The clusters whose membership each location needs.
350    membership_streams: SparseSecondaryMap<LocationKey, Vec<LocationKey>>,
351    boundary: BoundaryGuarantees,
352}
353
354/// The ordering and retries of a stream crossing the boundary.
355#[derive(Clone, Debug)]
356struct EmbeddedStreamGuarantees {
357    order: crate::compile::ir::StreamOrder,
358    retry: crate::compile::ir::StreamRetry,
359}
360
361impl EmbeddedStreamGuarantees {
362    fn of(metadata: &crate::compile::ir::HydroIrMetadata, what: &str) -> Self {
363        use crate::compile::ir::CollectionKind;
364        match &metadata.collection_kind {
365            CollectionKind::Stream { order, retry, .. }
366            | CollectionKind::KeyedStream {
367                value_order: order,
368                value_retry: retry,
369                ..
370            } => EmbeddedStreamGuarantees {
371                order: order.clone(),
372                retry: retry.clone(),
373            },
374            kind => panic!("{what} must be a stream or keyed stream, not {kind:?}"),
375        }
376    }
377}
378
379/// The guarantees of the stream sent on a network channel and of the stream it delivers.
380#[derive(Clone, Debug)]
381struct EmbeddedNetworkGuarantees {
382    sent: EmbeddedStreamGuarantees,
383    received: EmbeddedStreamGuarantees,
384}
385
386/// The guarantees of every stream crossing the boundary, read from the IR before compiling: only
387/// the embedded backend needs them, so they do not go through [`Deploy`].
388#[derive(Default)]
389struct BoundaryGuarantees {
390    inputs: std::collections::HashMap<(LocationKey, String), EmbeddedStreamGuarantees>,
391    outputs: std::collections::HashMap<(LocationKey, String), EmbeddedStreamGuarantees>,
392    networks: std::collections::HashMap<String, EmbeddedNetworkGuarantees>,
393}
394
395impl BoundaryGuarantees {
396    fn collect(ir: &mut [crate::compile::ir::HydroRoot]) -> Self {
397        use crate::compile::ir::{HydroNode, HydroRoot, HydroSource};
398        let location_key = |id: &LocationId, what: &str| match id.root() {
399            LocationId::Process(key) | LocationId::Cluster(key) => *key,
400            _ => panic!("{what} must be on a process or cluster"),
401        };
402        let mut boundary = BoundaryGuarantees::default();
403        let cell = std::cell::RefCell::new(&mut boundary);
404        crate::compile::ir::transform_bottom_up(
405            ir,
406            &mut |root| {
407                if let HydroRoot::EmbeddedOutput { ident, input, .. } = root {
408                    let what = "an embedded output";
409                    cell.borrow_mut().outputs.insert(
410                        (
411                            location_key(&input.metadata().location_id, what),
412                            ident.to_string(),
413                        ),
414                        EmbeddedStreamGuarantees::of(input.metadata(), what),
415                    );
416                }
417            },
418            &mut |node| match node {
419                HydroNode::Source {
420                    source: HydroSource::Embedded(ident),
421                    metadata,
422                } => {
423                    let what = "an embedded input";
424                    cell.borrow_mut().inputs.insert(
425                        (location_key(&metadata.location_id, what), ident.to_string()),
426                        EmbeddedStreamGuarantees::of(metadata, what),
427                    );
428                }
429                HydroNode::Network {
430                    name: Some(name),
431                    input,
432                    metadata,
433                    ..
434                } => {
435                    let what = "a network channel's stream";
436                    cell.borrow_mut().networks.insert(
437                        name.clone(),
438                        EmbeddedNetworkGuarantees {
439                            sent: EmbeddedStreamGuarantees::of(input.metadata(), what),
440                            received: EmbeddedStreamGuarantees::of(metadata, what),
441                        },
442                    );
443                }
444                _ => {}
445            },
446            false,
447        );
448        boundary
449    }
450
451    fn input(&self, location_key: LocationKey, ident: &syn::Ident) -> EmbeddedStreamGuarantees {
452        self.inputs[&(location_key, ident.to_string())].clone()
453    }
454
455    fn output(&self, location_key: LocationKey, ident: &syn::Ident) -> EmbeddedStreamGuarantees {
456        self.outputs[&(location_key, ident.to_string())].clone()
457    }
458
459    fn network(&self, name: &str) -> EmbeddedNetworkGuarantees {
460        self.networks[name].clone()
461    }
462}
463
464/// The host of an embedded program identifies each cluster's members with whatever type it
465/// chooses.
466impl<Id> super::deploy_provider::SupportsMemberId<Id> for EmbeddedDeploy {}
467
468impl<'a> Deploy<'a> for EmbeddedDeploy {
469    type Meta = ();
470    type InstantiateEnv = EmbeddedInstantiateEnv;
471
472    type Process = EmbeddedNode;
473    type Cluster = EmbeddedNode;
474    type External = EmbeddedNode;
475
476    const SUPPORTS_EXTERNAL_SERIALIZATION: bool = true;
477
478    fn o2o_sink_source(
479        env: &mut Self::InstantiateEnv,
480        p1: &Self::Process,
481        _p1_port: &(),
482        p2: &Self::Process,
483        _p2_port: &(),
484        name: Option<&str>,
485        networking_info: &crate::networking::NetworkingInfo,
486        external_types: Option<(&syn::Type, &syn::Type)>,
487    ) -> (syn::Expr, syn::Expr) {
488        let name = name.expect(
489            "EmbeddedDeploy o2o networking requires a channel name. Use `TCP.name(\"my_channel\")` to provide one.",
490        );
491
492        let sink_ident = syn::Ident::new(&format!("__network_out_{name}"), Span::call_site());
493        let source_ident = syn::Ident::new(&format!("__network_in_{name}"), Span::call_site());
494
495        env.network_outputs
496            .entry(p1.location_key)
497            .unwrap()
498            .or_default()
499            .push(EmbeddedNetworkPort::new(
500                name,
501                false,
502                external_types.map(|(i, _)| i),
503                p2.location_key,
504                networking_info,
505            ));
506        env.network_inputs
507            .entry(p2.location_key)
508            .unwrap()
509            .or_default()
510            .push(EmbeddedNetworkPort::new(
511                name,
512                false,
513                external_types.map(|(_, o)| o),
514                p1.location_key,
515                networking_info,
516            ));
517
518        (
519            syn::parse_quote!(#sink_ident),
520            syn::parse_quote!(#source_ident),
521        )
522    }
523
524    /// Embedded sending ends are the host's `FnMut(..)` callbacks (see
525    /// [`EmbeddedNetworkOutputChannel`](crate::compile::embedded_runtime::EmbeddedNetworkOutputChannel)),
526    /// which never pend, so they are called directly rather than driven as a `Sink`.
527    ///
528    /// The `*_sink_source` methods return the callback's binding (hoisted into the generated
529    /// function's prologue), so it is borrowed here: the expression is evaluated inside the tick
530    /// closure on every tick, and moving the callback in would consume it on the first tick.
531    fn network_sink(sink: syn::Expr) -> NetworkSink {
532        NetworkSink::Callback(syn::parse_quote!(&mut #sink))
533    }
534
535    fn o2o_connect(
536        _p1: &Self::Process,
537        _p1_port: &(),
538        _p2: &Self::Process,
539        _p2_port: &(),
540    ) -> Box<dyn FnOnce()> {
541        Box::new(|| {})
542    }
543
544    fn o2m_sink_source(
545        env: &mut Self::InstantiateEnv,
546        p1: &Self::Process,
547        _p1_port: &(),
548        c2: &Self::Cluster,
549        _c2_port: &(),
550        name: Option<&str>,
551        networking_info: &crate::networking::NetworkingInfo,
552        external_types: Option<(&syn::Type, &syn::Type)>,
553    ) -> (syn::Expr, syn::Expr) {
554        let name = name.expect("EmbeddedDeploy o2m networking requires a channel name.");
555        let sink_ident = syn::Ident::new(&format!("__network_out_{name}"), Span::call_site());
556        let source_ident = syn::Ident::new(&format!("__network_in_{name}"), Span::call_site());
557        env.network_outputs
558            .entry(p1.location_key)
559            .unwrap()
560            .or_default()
561            .push(EmbeddedNetworkPort::new(
562                name,
563                true,
564                external_types.map(|(i, _)| i),
565                c2.location_key,
566                networking_info,
567            ));
568        env.network_inputs
569            .entry(c2.location_key)
570            .unwrap()
571            .or_default()
572            .push(EmbeddedNetworkPort::new(
573                name,
574                false,
575                external_types.map(|(_, o)| o),
576                p1.location_key,
577                networking_info,
578            ));
579        (
580            syn::parse_quote!(#sink_ident),
581            syn::parse_quote!(#source_ident),
582        )
583    }
584
585    fn o2m_connect(
586        _p1: &Self::Process,
587        _p1_port: &(),
588        _c2: &Self::Cluster,
589        _c2_port: &(),
590    ) -> Box<dyn FnOnce()> {
591        Box::new(|| {})
592    }
593
594    fn m2o_sink_source(
595        env: &mut Self::InstantiateEnv,
596        c1: &Self::Cluster,
597        _c1_port: &(),
598        p2: &Self::Process,
599        _p2_port: &(),
600        name: Option<&str>,
601        networking_info: &crate::networking::NetworkingInfo,
602        external_types: Option<(&syn::Type, &syn::Type)>,
603    ) -> (syn::Expr, syn::Expr) {
604        let name = name.expect("EmbeddedDeploy m2o networking requires a channel name.");
605        let sink_ident = syn::Ident::new(&format!("__network_out_{name}"), Span::call_site());
606        let source_ident = syn::Ident::new(&format!("__network_in_{name}"), Span::call_site());
607        env.network_outputs
608            .entry(c1.location_key)
609            .unwrap()
610            .or_default()
611            .push(EmbeddedNetworkPort::new(
612                name,
613                false,
614                external_types.map(|(i, _)| i),
615                p2.location_key,
616                networking_info,
617            ));
618        env.network_inputs
619            .entry(p2.location_key)
620            .unwrap()
621            .or_default()
622            .push(EmbeddedNetworkPort::new(
623                name,
624                true,
625                external_types.map(|(_, o)| o),
626                c1.location_key,
627                networking_info,
628            ));
629        (
630            syn::parse_quote!(#sink_ident),
631            syn::parse_quote!(#source_ident),
632        )
633    }
634
635    fn m2o_connect(
636        _c1: &Self::Cluster,
637        _c1_port: &(),
638        _p2: &Self::Process,
639        _p2_port: &(),
640    ) -> Box<dyn FnOnce()> {
641        Box::new(|| {})
642    }
643
644    fn m2m_sink_source(
645        env: &mut Self::InstantiateEnv,
646        c1: &Self::Cluster,
647        _c1_port: &(),
648        c2: &Self::Cluster,
649        _c2_port: &(),
650        name: Option<&str>,
651        networking_info: &crate::networking::NetworkingInfo,
652        external_types: Option<(&syn::Type, &syn::Type)>,
653    ) -> (syn::Expr, syn::Expr) {
654        let name = name.expect("EmbeddedDeploy m2m networking requires a channel name.");
655        let sink_ident = syn::Ident::new(&format!("__network_out_{name}"), Span::call_site());
656        let source_ident = syn::Ident::new(&format!("__network_in_{name}"), Span::call_site());
657        env.network_outputs
658            .entry(c1.location_key)
659            .unwrap()
660            .or_default()
661            .push(EmbeddedNetworkPort::new(
662                name,
663                true,
664                external_types.map(|(i, _)| i),
665                c2.location_key,
666                networking_info,
667            ));
668        env.network_inputs
669            .entry(c2.location_key)
670            .unwrap()
671            .or_default()
672            .push(EmbeddedNetworkPort::new(
673                name,
674                true,
675                external_types.map(|(_, o)| o),
676                c1.location_key,
677                networking_info,
678            ));
679        (
680            syn::parse_quote!(#sink_ident),
681            syn::parse_quote!(#source_ident),
682        )
683    }
684
685    fn m2m_connect(
686        _c1: &Self::Cluster,
687        _c1_port: &(),
688        _c2: &Self::Cluster,
689        _c2_port: &(),
690    ) -> Box<dyn FnOnce()> {
691        Box::new(|| {})
692    }
693
694    fn e2o_many_source(
695        _extra_stmts: &mut Vec<syn::Stmt>,
696        _p2: &Self::Process,
697        _p2_port: &(),
698        _codec_type: &syn::Type,
699        _encode_type: &syn::Type,
700        _shared_handle: String,
701    ) -> syn::Expr {
702        panic!("EmbeddedDeploy does not support networking (e2o)")
703    }
704
705    fn e2o_many_sink(_shared_handle: String) -> syn::Expr {
706        panic!("EmbeddedDeploy does not support networking (e2o)")
707    }
708
709    fn e2o_source(
710        _extra_stmts: &mut Vec<syn::Stmt>,
711        _p1: &Self::External,
712        _p1_port: &(),
713        _p2: &Self::Process,
714        _p2_port: &(),
715        _codec_type: &syn::Type,
716        _encode_type: &syn::Type,
717        _shared_handle: String,
718    ) -> syn::Expr {
719        panic!("EmbeddedDeploy does not support networking (e2o)")
720    }
721
722    fn e2o_connect(
723        _p1: &Self::External,
724        _p1_port: &(),
725        _p2: &Self::Process,
726        _p2_port: &(),
727        _many: bool,
728        _server_hint: NetworkHint,
729    ) -> Box<dyn FnOnce()> {
730        panic!("EmbeddedDeploy does not support networking (e2o)")
731    }
732
733    fn o2e_sink(
734        _p1: &Self::Process,
735        _p1_port: &(),
736        _p2: &Self::External,
737        _p2_port: &(),
738        _shared_handle: String,
739    ) -> syn::Expr {
740        panic!("EmbeddedDeploy does not support networking (o2e)")
741    }
742
743    fn cluster_ids(_of_cluster: LocationKey) -> syn::Expr {
744        panic!("EmbeddedDeploy does not support cluster IDs");
745    }
746
747    fn cluster_self_id() -> syn::Expr {
748        syn::parse_quote!(__cluster_self_id)
749    }
750
751    fn cluster_membership_stream(
752        env: &mut Self::InstantiateEnv,
753        at_location: &LocationId,
754        location_id: &LocationId,
755    ) -> syn::Expr {
756        let at_key = match at_location {
757            LocationId::Process(key) | LocationId::Cluster(key) => *key,
758            _ => panic!("cluster_membership_stream must be called from a process or cluster"),
759        };
760        let cluster_key = match location_id {
761            LocationId::Cluster(key) => *key,
762            _ => panic!("cluster_membership_stream target must be a cluster"),
763        };
764        let vec = env.membership_streams.entry(at_key).unwrap().or_default();
765        let idx = if let Some(pos) = vec.iter().position(|k| *k == cluster_key) {
766            pos
767        } else {
768            vec.push(cluster_key);
769            vec.len() - 1
770        };
771
772        let ident = quote::format_ident!("__membership_{}", idx);
773        syn::parse_quote!(#ident)
774    }
775
776    fn register_embedded_stream_input(
777        env: &mut Self::InstantiateEnv,
778        location_key: LocationKey,
779        ident: &syn::Ident,
780        element_type: &syn::Type,
781    ) {
782        env.inputs
783            .entry(location_key)
784            .unwrap()
785            .or_default()
786            .push(EmbeddedStreamPort {
787                ident: ident.clone(),
788                element_type: element_type.clone(),
789            });
790    }
791
792    fn register_embedded_singleton_input(
793        env: &mut Self::InstantiateEnv,
794        location_key: LocationKey,
795        ident: &syn::Ident,
796        element_type: &syn::Type,
797    ) {
798        env.singleton_inputs
799            .entry(location_key)
800            .unwrap()
801            .or_default()
802            .push((ident.clone(), element_type.clone()));
803    }
804
805    fn register_embedded_output(
806        env: &mut Self::InstantiateEnv,
807        location_key: LocationKey,
808        ident: &syn::Ident,
809        element_type: &syn::Type,
810    ) {
811        env.outputs
812            .entry(location_key)
813            .unwrap()
814            .or_default()
815            .push(EmbeddedStreamPort {
816                ident: ident.clone(),
817                element_type: element_type.clone(),
818            });
819    }
820}
821
822/// The generated pieces for one direction of a location's network channels: the
823/// `EmbeddedNetworkIn` or `EmbeddedNetworkOut` struct, its module of marker types, and the
824/// function parameter. Both directions are generated the same way, one piece per port.
825struct NetworkPortTokens {
826    fields: Vec<syn::Ident>,
827    field_docs: Vec<String>,
828    /// Each field's type: `EmbeddedNetworkInputChannel<Marker, S>` (receiving) or `EmbeddedNetworkOutputChannel<Marker, F>`
829    /// (sending), for the port's marker type (which carries its stream's guarantees and the
830    /// channel's configuration) and generic parameter.
831    field_types: Vec<proc_macro2::TokenStream>,
832    generics: Vec<syn::Ident>,
833    items: Vec<proc_macro2::TokenStream>,
834    marker_defs: Vec<proc_macro2::TokenStream>,
835}
836
837impl NetworkPortTokens {
838    fn new(
839        ports: &[EmbeddedNetworkPort],
840        boundary: &BoundaryGuarantees,
841        fn_names: &SparseSecondaryMap<LocationKey, &str>,
842        generic_prefix: &str,
843        sending: bool,
844        item: impl Fn(&EmbeddedNetworkPort) -> proc_macro2::TokenStream,
845    ) -> Self {
846        let root = crate::staging_util::get_this_crate();
847        let items: Vec<proc_macro2::TokenStream> = ports.iter().map(&item).collect();
848        // Each port's field, which its marker type is named after.
849        let fields: Vec<syn::Ident> = ports
850            .iter()
851            .map(|port| syn::Ident::new(&port.name, Span::call_site()))
852            .collect();
853        let mut marker_defs = Vec::with_capacity(ports.len());
854        let mut field_docs = Vec::with_capacity(ports.len());
855        for (port, marker) in ports.iter().zip(&fields) {
856            let name = &port.name;
857            let peer = fn_names[port.peer];
858            let channel = boundary.network(name);
859            let guarantees = if sending {
860                &channel.sent
861            } else {
862                &channel.received
863            };
864            let doc = format!(
865                "The `{name}` channel's end at this location; its other end is at `{peer}`.\n\n{}",
866                network_end_doc(port, guarantees, sending)
867            );
868            let marker_def = marker_def(&root, marker, &doc, guarantees);
869            let (transport, serialization) = (&port.transport, &port.serialization);
870            marker_defs.push(quote! {
871                #marker_def
872
873                impl #root::compile::embedded_runtime::EmbeddedNetworkChannel for #marker {
874                    type Transport = #transport;
875                    type Serialization = #serialization;
876                }
877            });
878            let (action, module) = if sending {
879                (format!("Sends on `{name}` to `{peer}`"), "outgoing")
880            } else {
881                (format!("Receives `{name}` from `{peer}`"), "incoming")
882            };
883            field_docs.push(format!("{action} (marker type: [`{module}::{marker}`])."));
884        }
885        let generics: Vec<syn::Ident> = (0..ports.len())
886            .map(|i| quote::format_ident!("{}{}", generic_prefix, i))
887            .collect();
888        let module = syn::Ident::new(
889            if sending { "outgoing" } else { "incoming" },
890            Span::call_site(),
891        );
892        // The host acknowledges the channel's configuration at both ends. At the sending end it
893        // acknowledges the stream sent, as for an output; at the receiving end it promises the
894        // stream delivered, as for an input.
895        let wrapper = if sending {
896            quote! { #root::compile::embedded_runtime::EmbeddedNetworkOutputChannel }
897        } else {
898            quote! { #root::compile::embedded_runtime::EmbeddedNetworkInputChannel }
899        };
900        let field_types = fields
901            .iter()
902            .zip(&generics)
903            .map(|(marker, generic)| quote! { #wrapper<#module::#marker, #generic> })
904            .collect();
905        NetworkPortTokens {
906            fields,
907            field_docs,
908            field_types,
909            generics,
910            items,
911            marker_defs,
912        }
913    }
914}
915
916/// The marker type of a field crossing the boundary, implementing `EmbeddedChannel` with its
917/// `guarantees`. Channels are named by strings, so each field gets a type, named after it, for
918/// the type checker to check the host's side against.
919fn marker_def(
920    root: &proc_macro2::TokenStream,
921    marker: &syn::Ident,
922    doc: &str,
923    guarantees: &EmbeddedStreamGuarantees,
924) -> proc_macro2::TokenStream {
925    let ordering = guarantees.order.type_tokens();
926    let retries = guarantees.retry.type_tokens();
927    quote! {
928        #[doc = #doc]
929        #[allow(non_camel_case_types, reason = "named after its field")]
930        pub struct #marker;
931
932        impl #root::compile::embedded_runtime::EmbeddedChannel for #marker {
933            type Ordering = #ordering;
934            type Retries = #retries;
935        }
936    }
937}
938
939/// How a host promises `guarantees` for a stream flowing into the dataflow, in words.
940fn promise_doc(guarantees: &EmbeddedStreamGuarantees, wrapper: &str) -> String {
941    format!(
942        "Promise its guarantees with `{wrapper}::new(.., Promises::new(){})`.",
943        promises_chain(guarantees)
944    )
945}
946
947/// The `Promises` builder calls that promise exactly `guarantees`.
948fn promises_chain(guarantees: &EmbeddedStreamGuarantees) -> String {
949    use crate::compile::ir::{StreamOrder, StreamRetry};
950    [
951        (guarantees.order == StreamOrder::TotalOrder).then_some(".total_order(proof)"),
952        (guarantees.retry == StreamRetry::ExactlyOnce).then_some(".exactly_once(proof)"),
953    ]
954    .into_iter()
955    .flatten()
956    .collect()
957}
958
959/// How a host acknowledges what an output with `guarantees` may do, in words.
960fn acknowledge_doc(guarantees: &EmbeddedStreamGuarantees) -> String {
961    format!(
962        "Acknowledge what it may do with \
963         `EmbeddedOutputChannel::new(.., Acknowledgements::new(){})`.",
964        acknowledgements_chain(guarantees)
965    )
966}
967
968/// The `Acknowledgements` calls for what a stream with `guarantees` may do.
969fn acknowledgements_chain(guarantees: &EmbeddedStreamGuarantees) -> String {
970    use crate::compile::ir::{StreamOrder, StreamRetry};
971    [
972        (guarantees.order == StreamOrder::NoOrder).then_some(".no_order()"),
973        (guarantees.retry == StreamRetry::AtLeastOnce).then_some(".at_least_once()"),
974    ]
975    .into_iter()
976    .flatten()
977    .collect()
978}
979
980/// How the host builds the channel end `port`, for its marker's docs.
981fn network_end_doc(
982    port: &EmbeddedNetworkPort,
983    guarantees: &EmbeddedStreamGuarantees,
984    sending: bool,
985) -> String {
986    let config = &port.config;
987    if sending {
988        format!(
989            "Acknowledge the channel's configuration and what the stream sent on it may do with \
990             `EmbeddedNetworkOutputChannel::new(.., ChannelConfiguration::new({config}), \
991             Acknowledgements::new(){})`.",
992            acknowledgements_chain(guarantees)
993        )
994    } else {
995        format!(
996            "Acknowledge the channel's configuration and promise the guarantees of the stream it \
997             delivers with `EmbeddedNetworkInputChannel::new(.., ChannelConfiguration::new({config}), \
998             Promises::new(){})`.",
999            promises_chain(guarantees)
1000        )
1001    }
1002}
1003
1004/// Options controlling the Rust source emitted by
1005/// [`DeployFlow::generate_embedded_with_options`](super::deploy::DeployFlow::generate_embedded_with_options).
1006///
1007/// This is deliberately *not* the full set of DFIR codegen knobs ([`AsCodeOptions`]). Most of
1008/// those are decided by Hydro on the user's behalf: type guards are excluded because Hydro has
1009/// already type-checked the dataflow and injects its own type hints, the serialized meta graph is
1010/// excluded because nothing consumes it in embedded mode, and runtime metrics tracking is driven by
1011/// [sidecars](crate::telemetry::Sidecar) rather than a raw flag. Only the choices that genuinely
1012/// belong to the embedding developer are exposed here, which also keeps the embedded API stable
1013/// as the underlying DFIR options evolve.
1014#[derive(Clone, Debug, Default)]
1015#[non_exhaustive]
1016pub struct EmbeddedCodegenOptions {
1017    /// Emit a named wrapper function around every DFIR operator so that each operator gets its own
1018    /// stack frame in profiles/flamegraphs.
1019    ///
1020    /// Off by default: the wrappers are purely for profiler attribution (Hydro already type-checks
1021    /// the dataflow), and they make the generated code several times more verbose. Enable this
1022    /// when profiling an embedded Hydro program.
1023    pub require_flame_attribution: bool,
1024}
1025
1026impl EmbeddedCodegenOptions {
1027    /// Returns options with [`Self::require_flame_attribution`] set.
1028    pub fn with_flame_attribution() -> Self {
1029        Self {
1030            require_flame_attribution: true,
1031        }
1032    }
1033}
1034
1035impl super::deploy::DeployFlow<'_, EmbeddedDeploy> {
1036    /// Generates a `syn::File` containing one function per location in the flow.
1037    ///
1038    /// Each generated function has the signature:
1039    /// ```ignore
1040    /// pub fn <fn_name>() -> dfir_rs::scheduled::graph::Dfir<'static>
1041    /// ```
1042    /// where `fn_name` is the `String` passed to `with_process` / `with_cluster`.
1043    ///
1044    /// The returned `Dfir` can be manually executed by the caller.
1045    ///
1046    /// Uses the default [`EmbeddedCodegenOptions`]; see
1047    /// [`Self::generate_embedded_with_options`] to customize them.
1048    ///
1049    /// # Arguments
1050    ///
1051    /// * `crate_name` — the name of the crate containing the Hydro program (used for stageleft
1052    ///   re-exports). Hyphens will be replaced with underscores.
1053    ///
1054    /// # Usage
1055    ///
1056    /// Typically called from a `build.rs` in a wrapper crate:
1057    /// ```ignore
1058    /// // build.rs
1059    /// let deploy = flow.with_process(&process, "my_fn".to_string());
1060    /// let code = deploy.generate_embedded("my_hydro_crate");
1061    /// let out_dir = std::env::var("OUT_DIR").unwrap();
1062    /// std::fs::write(format!("{out_dir}/embedded.rs"), prettyplease::unparse(&code)).unwrap();
1063    /// ```
1064    ///
1065    /// Then in `lib.rs`:
1066    /// ```ignore
1067    /// include!(concat!(env!("OUT_DIR"), "/embedded.rs"));
1068    /// ```
1069    pub fn generate_embedded(self, crate_name: &str) -> syn::File {
1070        self.generate_embedded_with_options(crate_name, &EmbeddedCodegenOptions::default())
1071    }
1072
1073    /// Like [`Self::generate_embedded`], but with explicit [`EmbeddedCodegenOptions`].
1074    pub fn generate_embedded_with_options(
1075        mut self,
1076        crate_name: &str,
1077        codegen_options: &EmbeddedCodegenOptions,
1078    ) -> syn::File {
1079        let mut env = EmbeddedInstantiateEnv {
1080            boundary: BoundaryGuarantees::collect(&mut self.ir),
1081            ..Default::default()
1082        };
1083        let compiled = self.compile_internal(&mut env);
1084
1085        let root = crate::staging_util::get_this_crate();
1086        let orig_crate_name = quote::format_ident!("{}", crate_name.replace('-', "_"));
1087
1088        let mut items: Vec<syn::Item> = Vec::new();
1089
1090        // Sort location keys for deterministic output.
1091        let mut location_keys: Vec<_> = compiled.all_dfir().keys().collect();
1092        location_keys.sort();
1093
1094        // Build a map from location key to fn_name for lookups.
1095        let fn_names: SparseSecondaryMap<LocationKey, &str> = location_keys
1096            .iter()
1097            .map(|&k| {
1098                let name = self
1099                    .processes
1100                    .get(k)
1101                    .map(|n| n.fn_name.as_str())
1102                    .or_else(|| self.clusters.get(k).map(|n| n.fn_name.as_str()))
1103                    .or_else(|| self.externals.get(k).map(|n| n.fn_name.as_str()))
1104                    .expect("location key not found in any node map");
1105                (k, name)
1106            })
1107            .collect();
1108
1109        for location_key in location_keys {
1110            let graph = compiled.all_dfir()[location_key]
1111                .as_ref()
1112                .unwrap_or_else(|err| {
1113                    panic!(
1114                        "Failed to partition DFIR graph for location {location_key}: {}",
1115                        err.diagnostic
1116                    )
1117                });
1118
1119            // Get the user-provided function name from the node.
1120            let fn_name = fn_names[location_key];
1121            let fn_ident = syn::Ident::new(fn_name, Span::call_site());
1122
1123            // Get inputs for this location, sorted by name.
1124            let mut loc_inputs = env.inputs.get(location_key).cloned().unwrap_or_default();
1125            loc_inputs.sort_by(|a, b| a.ident.cmp(&b.ident));
1126
1127            // Get outputs for this location, sorted by name.
1128            let mut loc_outputs = env.outputs.get(location_key).cloned().unwrap_or_default();
1129            loc_outputs.sort_by(|a, b| a.ident.cmp(&b.ident));
1130
1131            let mut diagnostics = Diagnostics::new();
1132            // `as_code_options` is sparse: it only has entries for locations where a sidecar
1133            // edited the options. Locations without sidecars fall back to the defaults.
1134            let mut as_code_options = compiled
1135                .as_code_options
1136                .get(location_key)
1137                .cloned()
1138                .unwrap_or_default();
1139            // Hydro has already type-checked the dataflow and injects its own type hints into
1140            // the DFIR it emits, so the DFIR type guards are redundant here. Excluding them keeps
1141            // the generated (and user-visible) embedded code compact and reviewable. The
1142            // per-operator wrappers can still be requested for flamegraph attribution.
1143            as_code_options.exclude_type_guards = true;
1144            as_code_options.require_flame_attribution = codegen_options.require_flame_attribution;
1145            // The serialized meta graph + diagnostics JSON blobs are only used for runtime
1146            // introspection / debugging of hand-written DFIR; embedded Hydro programs have no use
1147            // for them, and they are large opaque string literals.
1148            as_code_options.exclude_meta = true;
1149            let dfir_tokens = graph
1150                .as_code_with_options(
1151                    &quote! { __root_dfir_rs },
1152                    &as_code_options,
1153                    quote!(),
1154                    &mut diagnostics,
1155                )
1156                .expect("DFIR inline code generation failed with diagnostics.");
1157
1158            // --- Build module items (cluster info, output struct, network structs) ---
1159            let mut mod_items: Vec<proc_macro2::TokenStream> = Vec::new();
1160            let mut extra_fn_generics: Vec<proc_macro2::TokenStream> = Vec::new();
1161            let mut cluster_params: Vec<proc_macro2::TokenStream> = Vec::new();
1162            let mut output_params: Vec<proc_macro2::TokenStream> = Vec::new();
1163            let mut net_out_params: Vec<proc_macro2::TokenStream> = Vec::new();
1164            let mut net_in_params: Vec<proc_macro2::TokenStream> = Vec::new();
1165            let mut extra_destructure: Vec<proc_macro2::TokenStream> = Vec::new();
1166
1167            // For cluster locations whose code reads their own member ID, add a self_id parameter.
1168            if self.clusters.contains_key(location_key)
1169                && self.clusters_reading_self_id.contains(&location_key)
1170            {
1171                let id_type = &self.cluster_id_types[location_key];
1172                cluster_params.push(quote! {
1173                    __cluster_self_id: #id_type
1174                });
1175                // Alias to the name the generated DFIR code expects.
1176                let self_id_ident = syn::Ident::new(
1177                    &format!("__hydro_lang_cluster_self_id_{}", location_key),
1178                    Span::call_site(),
1179                );
1180                extra_destructure.push(quote! {
1181                    let #self_id_ident = __cluster_self_id;
1182                });
1183            }
1184
1185            // For any location that needs cluster membership streams, add parameters.
1186            if let Some(loc_memberships) = env.membership_streams.get(location_key) {
1187                let membership_struct_ident =
1188                    syn::Ident::new("EmbeddedMembershipStreams", Span::call_site());
1189
1190                let mem_generic_idents: Vec<syn::Ident> = loc_memberships
1191                    .iter()
1192                    .enumerate()
1193                    .map(|(i, _)| quote::format_ident!("__Mem{}", i))
1194                    .collect();
1195
1196                let mem_field_names: Vec<syn::Ident> = loc_memberships
1197                    .iter()
1198                    .map(|k| {
1199                        let cluster_fn_name = fn_names[*k];
1200                        syn::Ident::new(cluster_fn_name, Span::call_site())
1201                    })
1202                    .collect();
1203
1204                let mem_items: Vec<proc_macro2::TokenStream> = loc_memberships
1205                    .iter()
1206                    .map(|k| {
1207                        let id_type = &self.cluster_id_types[*k];
1208                        quote! { (#id_type, #root::location::MembershipEvent) }
1209                    })
1210                    .collect();
1211                // Each member's events, in the order they happened, each once.
1212                let mem_guarantees = EmbeddedStreamGuarantees {
1213                    order: crate::compile::ir::StreamOrder::TotalOrder,
1214                    retry: crate::compile::ir::StreamRetry::ExactlyOnce,
1215                };
1216                let mem_marker_defs = mem_field_names.iter().map(|field| {
1217                    marker_def(
1218                        &root,
1219                        field,
1220                        &format!(
1221                            "The membership stream of the `{field}` cluster.\n\n{}",
1222                            promise_doc(&mem_guarantees, "EmbeddedInputChannel")
1223                        ),
1224                        &mem_guarantees,
1225                    )
1226                });
1227
1228                let struct_fields: Vec<proc_macro2::TokenStream> = mem_field_names
1229                    .iter()
1230                    .zip(mem_generic_idents.iter())
1231                    .map(|(field, generic)| {
1232                        let doc = format!(
1233                            "Each member's `Joined` / `Left` events (marker type: [`membership::{field}`])."
1234                        );
1235                        quote! {
1236                            #[doc = #doc]
1237                            pub #field: #root::compile::embedded_runtime::EmbeddedInputChannel<membership::#field, #generic>
1238                        }
1239                    })
1240                    .collect();
1241
1242                let struct_generics: Vec<proc_macro2::TokenStream> = mem_generic_idents
1243                    .iter()
1244                    .zip(&mem_items)
1245                    .map(|(generic, mem_item)| quote! { #generic: __root_dfir_rs::futures::Stream<Item = #mem_item> + Unpin })
1246                    .collect();
1247
1248                for (generic, mem_item) in mem_generic_idents.iter().zip(&mem_items) {
1249                    extra_fn_generics.push(
1250                        quote! { #generic: __root_dfir_rs::futures::Stream<Item = #mem_item> + Unpin + 'a },
1251                    );
1252                }
1253
1254                cluster_params.push(quote! {
1255                    __membership: #fn_ident::#membership_struct_ident<#(#mem_generic_idents),*>
1256                });
1257
1258                for (i, field) in mem_field_names.iter().enumerate() {
1259                    let var_ident =
1260                        syn::Ident::new(&format!("__membership_{}", i), Span::call_site());
1261                    extra_destructure.push(quote! {
1262                        let #var_ident = __membership.#field.into_inner();
1263                    });
1264                }
1265
1266                mod_items.push(quote! {
1267                    pub struct #membership_struct_ident<#(#struct_generics),*> {
1268                        #(#struct_fields),*
1269                    }
1270
1271                    /// Marker types for each membership stream, describing each field of
1272                    /// `EmbeddedMembershipStreams`.
1273                    pub mod membership {
1274                        use super::*;
1275                        #(#mem_marker_defs)*
1276                    }
1277                });
1278            }
1279
1280            // Embedded inputs, passed by value in one struct with a named field per input: a
1281            // `Stream` for each stream input and a plain value for each singleton input.
1282            let mut loc_singleton_inputs = env
1283                .singleton_inputs
1284                .get(location_key)
1285                .cloned()
1286                .unwrap_or_default();
1287            loc_singleton_inputs.sort_by(|a, b| a.0.cmp(&b.0));
1288
1289            let mut input_params: Vec<proc_macro2::TokenStream> = Vec::new();
1290            if !loc_inputs.is_empty() || !loc_singleton_inputs.is_empty() {
1291                let input_struct_ident = syn::Ident::new("EmbeddedInputs", Span::call_site());
1292
1293                let input_generic_idents: Vec<syn::Ident> = loc_inputs
1294                    .iter()
1295                    .enumerate()
1296                    .map(|(i, _)| quote::format_ident!("__In{}", i))
1297                    .collect();
1298
1299                // Every stream input must promise what its `embedded_input` declared, which its
1300                // marker's guarantees state.
1301                let input_marker_defs: Vec<proc_macro2::TokenStream> = loc_inputs
1302                    .iter()
1303                    .map(|input| {
1304                        let guarantees = env.boundary.input(location_key, &input.ident);
1305                        marker_def(
1306                            &root,
1307                            &input.ident,
1308                            &format!(
1309                                "The `{}` stream input.\n\n{}",
1310                                input.ident,
1311                                promise_doc(&guarantees, "EmbeddedInputChannel")
1312                            ),
1313                            &guarantees,
1314                        )
1315                    })
1316                    .collect();
1317
1318                let struct_fields: Vec<proc_macro2::TokenStream> = loc_inputs
1319                    .iter()
1320                    .zip(input_generic_idents.iter())
1321                    .map(|(input, generic)| {
1322                        let ident = &input.ident;
1323                        let doc =
1324                            format!("The `{ident}` stream input (marker type: [`inputs::{ident}`]).");
1325                        quote! {
1326                            #[doc = #doc]
1327                            pub #ident: #root::compile::embedded_runtime::EmbeddedInputChannel<inputs::#ident, #generic>
1328                        }
1329                    })
1330                    .chain(
1331                        loc_singleton_inputs
1332                            .iter()
1333                            .map(|(ident, element_type)| quote! { pub #ident: #element_type }),
1334                    )
1335                    .collect();
1336
1337                let struct_generics: Vec<proc_macro2::TokenStream> = loc_inputs
1338                    .iter()
1339                    .zip(input_generic_idents.iter())
1340                    .map(|(input, generic)| {
1341                        let element_type = &input.element_type;
1342                        quote! { #generic: __root_dfir_rs::futures::Stream<Item = #element_type> + Unpin }
1343                    })
1344                    .collect();
1345
1346                for (input, generic) in loc_inputs.iter().zip(input_generic_idents.iter()) {
1347                    let element_type = &input.element_type;
1348                    extra_fn_generics.push(
1349                        quote! { #generic: __root_dfir_rs::futures::Stream<Item = #element_type> + Unpin + 'a },
1350                    );
1351                }
1352
1353                input_params.push(quote! {
1354                    __inputs: #fn_ident::#input_struct_ident<#(#input_generic_idents),*>
1355                });
1356
1357                for input in &loc_inputs {
1358                    let ident = &input.ident;
1359                    extra_destructure.push(quote! { let #ident = __inputs.#ident.into_inner(); });
1360                }
1361                for (ident, _) in &loc_singleton_inputs {
1362                    extra_destructure.push(quote! { let #ident = __inputs.#ident; });
1363                }
1364
1365                let input_markers_mod = (!input_marker_defs.is_empty()).then(|| {
1366                    quote! {
1367                        /// Marker types for each stream input, describing each stream field of
1368                        /// `EmbeddedInputs`.
1369                        pub mod inputs {
1370                            use super::*;
1371                            #(#input_marker_defs)*
1372                        }
1373                    }
1374                });
1375                mod_items.push(quote! {
1376                    pub struct #input_struct_ident<#(#struct_generics),*> {
1377                        #(#struct_fields),*
1378                    }
1379
1380                    #input_markers_mod
1381                });
1382            }
1383
1384            // Embedded outputs: one `EmbeddedOutputChannel` sink per output, over a marker whose guarantees
1385            // are what the output stream provides, which the host's acknowledgements must cover.
1386            if !loc_outputs.is_empty() {
1387                let output_struct_ident = syn::Ident::new("EmbeddedOutputs", Span::call_site());
1388
1389                let mut struct_generics: Vec<proc_macro2::TokenStream> = Vec::new();
1390                let mut struct_fields: Vec<proc_macro2::TokenStream> = Vec::new();
1391                let mut generics: Vec<syn::Ident> = Vec::new();
1392                let mut marker_defs: Vec<proc_macro2::TokenStream> = Vec::new();
1393                for (i, output) in loc_outputs.iter().enumerate() {
1394                    let ident = &output.ident;
1395                    let element_type = &output.element_type;
1396                    let generic = quote::format_ident!("__Out{}", i);
1397                    let guarantees = env.boundary.output(location_key, ident);
1398                    marker_defs.push(marker_def(
1399                        &root,
1400                        ident,
1401                        &format!("The `{ident}` output.\n\n{}", acknowledge_doc(&guarantees)),
1402                        &guarantees,
1403                    ));
1404                    let doc = format!("The `{ident}` output (marker type: [`outputs::{ident}`]).");
1405                    let sink_bound = quote! { FnMut(#element_type) };
1406                    struct_generics.push(quote! { #generic: #sink_bound });
1407                    extra_fn_generics.push(quote! { #generic: #sink_bound + 'a });
1408                    struct_fields.push(quote! {
1409                        #[doc = #doc]
1410                        pub #ident: #root::compile::embedded_runtime::EmbeddedOutputChannel<outputs::#ident, #generic>
1411                    });
1412                    generics.push(generic);
1413                    extra_destructure
1414                        .push(quote! { let mut #ident = __outputs.#ident.into_inner(); });
1415                }
1416
1417                output_params.push(quote! {
1418                    __outputs: #fn_ident::#output_struct_ident<#(#generics),*>
1419                });
1420
1421                mod_items.push(quote! {
1422                    pub struct #output_struct_ident<#(#struct_generics),*> {
1423                        #(#struct_fields),*
1424                    }
1425
1426                    /// Marker types for each output, describing each field of `EmbeddedOutputs`.
1427                    pub mod outputs {
1428                        use super::*;
1429                        #(#marker_defs)*
1430                    }
1431                });
1432            }
1433
1434            // Network outputs (sinks), plus a marker type per channel describing it.
1435            if let Some(mut ports) = env.network_outputs.remove(location_key) {
1436                ports.sort_by(|a, b| a.name.cmp(&b.name));
1437                let channels = NetworkPortTokens::new(
1438                    &ports,
1439                    &env.boundary,
1440                    &fn_names,
1441                    "__NetOut",
1442                    true,
1443                    |port| {
1444                        let payload = if let Some(ty) = &port.external_type {
1445                            quote! { #ty }
1446                        } else {
1447                            quote! { #root::runtime_support::dfir_rs::bytes::Bytes }
1448                        };
1449                        if port.is_tagged {
1450                            let id_type = &self.cluster_id_types[port.peer];
1451                            quote! { (#id_type, #payload) }
1452                        } else {
1453                            payload
1454                        }
1455                    },
1456                );
1457                let NetworkPortTokens {
1458                    fields,
1459                    field_docs,
1460                    field_types,
1461                    generics,
1462                    items,
1463                    marker_defs,
1464                } = &channels;
1465
1466                for (generic, item) in generics.iter().zip(items) {
1467                    extra_fn_generics.push(quote! { #generic: FnMut(#item) + 'a });
1468                }
1469
1470                net_out_params.push(quote! {
1471                    __network_out: #fn_ident::EmbeddedNetworkOut<#(#generics),*>
1472                });
1473
1474                for (port, field) in ports.iter().zip(fields) {
1475                    let var_ident =
1476                        syn::Ident::new(&format!("__network_out_{}", port.name), Span::call_site());
1477                    extra_destructure
1478                        .push(quote! { let mut #var_ident = __network_out.#field.into_inner(); });
1479                }
1480
1481                mod_items.push(quote! {
1482                    pub struct EmbeddedNetworkOut<#(#generics: FnMut(#items)),*> {
1483                        #(#[doc = #field_docs] pub #fields: #field_types),*
1484                    }
1485
1486                    /// Marker types for the sending end of each of this location's outgoing
1487                    /// channels, describing each field of `EmbeddedNetworkOut`.
1488                    pub mod outgoing {
1489                        use super::*;
1490                        #(#marker_defs)*
1491                    }
1492                });
1493            }
1494
1495            // Network inputs (Stream sources), plus a marker type per channel describing it.
1496            if let Some(mut ports) = env.network_inputs.remove(location_key) {
1497                ports.sort_by(|a, b| a.name.cmp(&b.name));
1498                let channels = NetworkPortTokens::new(
1499                    &ports,
1500                    &env.boundary,
1501                    &fn_names,
1502                    "__NetIn",
1503                    false,
1504                    |port| {
1505                        // With embedded (external) serialization, the raw payload is delivered
1506                        // directly, with no transport `Result` wrapper.
1507                        let id_type = port.is_tagged.then(|| &self.cluster_id_types[port.peer]);
1508                        match (&port.external_type, id_type) {
1509                            (Some(ty), Some(id_type)) => {
1510                                quote! { (#id_type, #ty) }
1511                            }
1512                            (Some(ty), None) => quote! { #ty },
1513                            (None, Some(id_type)) => {
1514                                quote! { Result<(#id_type, __root_dfir_rs::bytes::BytesMut), std::io::Error> }
1515                            }
1516                            (None, None) => {
1517                                quote! { Result<__root_dfir_rs::bytes::BytesMut, std::io::Error> }
1518                            }
1519                        }
1520                    },
1521                );
1522                let NetworkPortTokens {
1523                    fields,
1524                    field_docs,
1525                    field_types,
1526                    generics,
1527                    items,
1528                    marker_defs,
1529                } = &channels;
1530
1531                for (generic, item) in generics.iter().zip(items) {
1532                    extra_fn_generics.push(
1533                        quote! { #generic: __root_dfir_rs::futures::Stream<Item = #item> + Unpin + 'a },
1534                    );
1535                }
1536
1537                net_in_params.push(quote! {
1538                    __network_in: #fn_ident::EmbeddedNetworkIn<#(#generics),*>
1539                });
1540
1541                for (port, field) in ports.iter().zip(fields) {
1542                    let var_ident =
1543                        syn::Ident::new(&format!("__network_in_{}", port.name), Span::call_site());
1544                    extra_destructure
1545                        .push(quote! { let #var_ident = __network_in.#field.into_inner(); });
1546                }
1547
1548                mod_items.push(quote! {
1549                    pub struct EmbeddedNetworkIn<#(#generics: __root_dfir_rs::futures::Stream<Item = #items> + Unpin),*> {
1550                        #(#[doc = #field_docs] pub #fields: #field_types),*
1551                    }
1552
1553                    /// Marker types for the receiving end of each of this location's incoming
1554                    /// channels, describing each field of `EmbeddedNetworkIn`.
1555                    pub mod incoming {
1556                        use super::*;
1557                        #(#marker_defs)*
1558                    }
1559                });
1560            }
1561
1562            // Emit the location's module: its parameter structs and channel marker types.
1563            let output_mod: syn::Item = syn::parse_quote! {
1564                pub mod #fn_ident {
1565                    use super::*;
1566
1567                    #(#mod_items)*
1568                }
1569            };
1570            items.push(output_mod);
1571
1572            // Build the function.
1573            let all_params: Vec<proc_macro2::TokenStream> = cluster_params
1574                .into_iter()
1575                .chain(input_params)
1576                .chain(output_params)
1577                .chain(net_in_params)
1578                .chain(net_out_params)
1579                .collect();
1580
1581            let dfir_metrics_ty = crate::compile::dfir_metrics_state_type(&as_code_options, &root);
1582            let ret_type: syn::Type = syn::parse_quote! { #root::runtime_support::dfir_rs::scheduled::context::Dfir<impl #root::runtime_support::dfir_rs::scheduled::context::TickClosureBoth<Metrics = #dfir_metrics_ty> + 'a> };
1583
1584            let func = syn::parse_quote! {
1585                #[allow(unused, non_snake_case, clippy::suspicious_else_formatting, clippy::clone_on_copy)]
1586                pub fn #fn_ident<'a, #(#extra_fn_generics),*>(#(#all_params),*) -> #ret_type {
1587                    #(#extra_destructure)*
1588                    #dfir_tokens
1589                }
1590            };
1591
1592            items.push(func);
1593        }
1594
1595        syn::parse_quote! {
1596            use #orig_crate_name::__staged::__deps::*;
1597            use #root::prelude::*;
1598            use #root::runtime_support::dfir_rs as __root_dfir_rs;
1599            pub use #orig_crate_name::__staged;
1600
1601            #( #items )*
1602        }
1603    }
1604}