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