Skip to main content

hydro_lang/location/
mod.rs

1//! Type definitions for distributed locations, which specify where pieces of a Hydro
2//! program will be executed.
3//!
4//! Hydro is a **global**, **distributed** programming model. This means that the data
5//! and computation in a Hydro program can be spread across multiple machines, data
6//! centers, and even continents. To achieve this, Hydro uses the concept of
7//! **locations** to keep track of _where_ data is located and computation is executed.
8//!
9//! Each live collection type (in [`crate::live_collections`]) has a type parameter `L`
10//! which will always be a type that implements the [`Location`] trait (e.g. [`Process`]
11//! and [`Cluster`]). To create distributed programs, Hydro provides a variety of APIs
12//! to allow live collections to be _moved_ between locations via network send/receive.
13//!
14//! See [the Hydro docs](https://hydro.run/docs/hydro/reference/locations/) for more information.
15
16use std::fmt::Debug;
17use std::future::Future;
18#[cfg(feature = "tokio")]
19use std::marker::PhantomData;
20use std::num::ParseIntError;
21#[cfg(feature = "tokio")]
22use std::time::Duration;
23
24#[cfg(feature = "tokio")]
25use bytes::{Bytes, BytesMut};
26use futures::stream::Stream as FuturesStream;
27use proc_macro2::Span;
28use quote::quote;
29#[cfg(feature = "tokio")]
30use serde::de::DeserializeOwned;
31use serde::{Deserialize, Serialize};
32use slotmap::{Key, new_key_type};
33#[cfg(feature = "tokio")]
34use stageleft::quote_type;
35use stageleft::runtime_support::{FreeVariableWithContextWithProps, QuoteTokens};
36use stageleft::{QuotedWithContext, q};
37use syn::parse_quote;
38#[cfg(feature = "tokio")]
39use tokio_util::codec::{Decoder, Encoder, LengthDelimitedCodec};
40
41#[cfg(feature = "tokio")]
42use crate::compile::builder::ExternalPortId;
43#[cfg(feature = "tokio")]
44use crate::compile::ir::DebugInstantiate;
45use crate::compile::ir::{
46    ClusterMembersState, HydroIrOpMetadata, HydroNode, HydroRoot, HydroSource,
47};
48use crate::forward_handle::ForwardRef;
49#[cfg(stageleft_runtime)]
50use crate::forward_handle::{CycleCollection, ForwardHandle};
51use crate::live_collections::boundedness::{Bounded, Unbounded};
52use crate::live_collections::keyed_stream::KeyedStream;
53use crate::live_collections::singleton::Singleton;
54#[cfg(feature = "tokio")]
55use crate::live_collections::stream::AtLeastOnce;
56#[cfg(feature = "sim")]
57#[cfg(stageleft_runtime)]
58use crate::live_collections::stream::networking::serialize_bincode;
59use crate::live_collections::stream::{
60    ExactlyOnce, NoOrder, Ordering, Retries, Stream, TotalOrder,
61};
62#[cfg(stageleft_runtime)]
63use crate::location::dynamic::DynLocation;
64use crate::location::dynamic::{ClusterConsistency, LocationId};
65#[cfg(feature = "tokio")]
66use crate::location::external_process::{
67    ExternalBincodeBidi, ExternalBincodeSink, ExternalBytesPort, Many, NotMany,
68};
69use crate::nondet::NonDet;
70#[cfg(feature = "tokio")]
71use crate::properties::manual_proof;
72#[cfg(feature = "sim")]
73use crate::sim::SimSender;
74use crate::staging_util::get_this_crate;
75
76pub mod dynamic;
77
78pub mod external_process;
79pub use external_process::External;
80
81pub mod process;
82pub use process::Process;
83
84pub mod cluster;
85pub use cluster::Cluster;
86
87pub mod member_id;
88pub use member_id::MemberId;
89
90pub mod tick;
91pub use tick::{Atomic, Tick};
92
93/// An event indicating a change in membership status of a location in a group
94/// (e.g. a node in a [`Cluster`] or an external client connection).
95#[derive(PartialEq, Eq, Clone, Debug, Hash, Serialize, Deserialize)]
96pub enum MembershipEvent {
97    /// The member has joined the group and is now active.
98    Joined,
99    /// The member has left the group and is no longer active.
100    Left,
101}
102
103/// A hint for configuring the network transport used by an external connection.
104///
105/// This controls how the underlying TCP listener is set up when binding
106/// external client connections via methods like [`Location::bind_single_client`]
107/// or [`Location::bidi_external_many_bytes`].
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109pub enum NetworkHint {
110    /// Automatically select the network configuration (e.g. an ephemeral port).
111    Auto,
112    /// Use a TCP port, optionally specifying a fixed port number.
113    ///
114    /// If `None`, an available port will be chosen automatically.
115    /// If `Some(port)`, the given port number will be used.
116    TcpPort(Option<u16>),
117}
118
119#[track_caller]
120pub(crate) fn check_matching_location<'a, L: Location<'a>>(l1: &L, l2: &L) {
121    assert_eq!(Location::id(l1), Location::id(l2), "locations do not match");
122}
123
124#[stageleft::export(LocationKey)]
125new_key_type! {
126    /// A unique identifier for a clock tick.
127    pub struct LocationKey;
128}
129
130impl std::fmt::Display for LocationKey {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        write!(f, "loc{:?}", self.data()) // `"loc1v1"``
133    }
134}
135
136/// This is used for the ECS membership stream.
137/// TODO(mingwei): Make this more robust?
138impl std::str::FromStr for LocationKey {
139    type Err = Option<ParseIntError>;
140
141    fn from_str(s: &str) -> Result<Self, Self::Err> {
142        let nvn = s.strip_prefix("loc").ok_or(None)?;
143        let (idx, ver) = nvn.split_once('v').ok_or(None)?;
144        let idx: u64 = idx.parse()?;
145        let ver: u64 = ver.parse()?;
146        Ok(slotmap::KeyData::from_ffi((ver << 32) | idx).into())
147    }
148}
149
150impl LocationKey {
151    /// TODO(minwgei): Remove this and avoid magic key for simulator external.
152    /// The first location key, used by the simulator as the default external location.
153    pub const FIRST: Self = Self(slotmap::KeyData::from_ffi(0x0000000100000001)); // `1v1`
154
155    /// A key for testing with index 1.
156    #[cfg(test)]
157    pub const TEST_KEY_1: Self = Self(slotmap::KeyData::from_ffi(0x000000FF00000001)); // `1v255`
158
159    /// A key for testing with index 2.
160    #[cfg(test)]
161    pub const TEST_KEY_2: Self = Self(slotmap::KeyData::from_ffi(0x000000FF00000002)); // `2v255`
162}
163
164/// This is used within `q!` code in docker and ECS.
165impl<Ctx> FreeVariableWithContextWithProps<Ctx, ()> for LocationKey {
166    type O = LocationKey;
167
168    fn to_tokens(self, _ctx: &Ctx) -> (QuoteTokens, ())
169    where
170        Self: Sized,
171    {
172        let root = get_this_crate();
173        let n = Key::data(&self).as_ffi();
174        (
175            QuoteTokens {
176                prelude: None,
177                expr: Some(quote! {
178                    #root::location::LocationKey::from(#root::runtime_support::slotmap::KeyData::from_ffi(#n))
179                }),
180            },
181            (),
182        )
183    }
184}
185
186/// A simple enum for the type of a root location.
187#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize)]
188pub enum LocationType {
189    /// A process (single node).
190    Process,
191    /// A cluster (multiple nodes).
192    Cluster,
193    /// An external client.
194    External,
195}
196
197/// A top-level location (i.e. a [`Process`] or [`Cluster`]) that is outside a tick / atomic region.
198pub trait TopLevel<'a>: Location<'a> {}
199
200#[cfg(feature = "sim")]
201#[cfg(stageleft_runtime)]
202fn register_serialized_external_input<'a, At, L, T>(
203    at: &At,
204    from: &External<'_, L>,
205    deserialize_fn: syn::Expr,
206) -> (
207    ExternalPortId,
208    Stream<T, At::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>,
209)
210where
211    At: TopLevel<'a> + Sized,
212{
213    let (port_id, stream, sink) = at.register_serialized_single_client::<_, T, ()>(
214        from,
215        serialize_bincode::<()>(false),
216        deserialize_fn,
217    );
218    sink.complete(stream.location().source_iter(q!([])));
219
220    (port_id, stream)
221}
222
223/// A location where data can be materialized and computation can be executed.
224///
225/// Hydro is a **global**, **distributed** programming model. This means that the data
226/// and computation in a Hydro program can be spread across multiple machines, data
227/// centers, and even continents. To achieve this, Hydro uses the concept of
228/// **locations** to keep track of _where_ data is located and computation is executed.
229///
230/// Each live collection type (in [`crate::live_collections`]) has a type parameter `L`
231/// which will always be a type that implements the [`Location`] trait (e.g. [`Process`]
232/// and [`Cluster`]). To create distributed programs, Hydro provides a variety of APIs
233/// to allow live collections to be _moved_ between locations via network send/receive.
234///
235/// See [the Hydro docs](https://hydro.run/docs/hydro/reference/locations/) for more information.
236#[expect(
237    private_bounds,
238    reason = "only internal Hydro code can define location types"
239)]
240pub trait Location<'a>: DynLocation {
241    /// The root location type for this location.
242    ///
243    /// For top-level locations like [`Process`] and [`Cluster`], this is `Self`.
244    /// For nested locations like [`Tick`], this is the root location that contains it.
245    type Root: Location<'a>;
246
247    /// The scope of simulator hook handles (see [`crate::sim_hooks`]) bindable to
248    /// unsafe operators at this location: [`OnProcess<P>`] for a [`Process<P>`](Process)
249    /// root, [`OnCluster<C>`] for a [`Cluster<C>`](Cluster) root. Operators name this in
250    /// their `NonDet` hook payload, so a handle can only bind to a matching location
251    /// kind.
252    ///
253    /// [`OnProcess<P>`]: crate::sim_hooks::OnProcess
254    /// [`OnCluster<C>`]: crate::sim_hooks::OnCluster
255    type SimHookScope: crate::sim_hooks::BindableHookScope;
256
257    /// Location type with consistency guarantees dropped for the live collection on it.
258    type DropConsistency: Location<'a, DropConsistency = Self::DropConsistency, SimHookScope = Self::SimHookScope>;
259
260    /// Returns the root location for this location.
261    ///
262    /// For top-level locations like [`Process`] and [`Cluster`], this returns `self`.
263    /// For nested locations like [`Tick`], this returns the root location that contains it.
264    fn root(&self) -> Self::Root;
265
266    /// This location but with consistency guarantees dropped for the live collection
267    fn drop_consistency(&self) -> Self::DropConsistency;
268    /// Gets the runtime enum variant for the current consistency level, if this is a cluster.
269    fn consistency() -> Option<ClusterConsistency>;
270
271    /// Updates the consistency guarantees to match that of the given location.
272    fn with_consistency_of<L2: Location<'a, DropConsistency = Self::DropConsistency>>(&self) -> L2 {
273        L2::from_drop_consistency(self.drop_consistency())
274    }
275
276    #[doc(hidden)]
277    fn from_drop_consistency(l2: Self::DropConsistency) -> Self;
278
279    /// Attempts to create a new [`Tick`] clock domain at this location.
280    ///
281    /// Returns `Some(Tick)` if this is a top-level location (like [`Process`] or [`Cluster`]),
282    /// or `None` if this location is already inside a tick (nested ticks are not supported).
283    ///
284    /// Prefer using [`Location::tick`] when you know the location is top-level.
285    fn try_tick(&self) -> Option<Tick<Self>> {
286        if Self::is_top_level() {
287            let id = if let LocationId::Atomic { .. } = self.id() {
288                None
289            } else {
290                Some(self.flow_state().borrow_mut().next_clock_id())
291            };
292            Some(Tick {
293                id,
294                l: self.clone(),
295            })
296        } else {
297            None
298        }
299    }
300
301    /// Returns the unique identifier for this location.
302    fn id(&self) -> LocationId {
303        DynLocation::dyn_id(self)
304    }
305
306    /// Creates a new [`Tick`] clock domain at this location.
307    ///
308    /// A tick represents a logical clock that can be used to batch streaming data
309    /// into discrete time steps. This is useful for implementing iterative algorithms
310    /// or for synchronizing data across multiple streams.
311    ///
312    /// # Example
313    /// ```rust
314    /// # #[cfg(feature = "deploy")] {
315    /// # use hydro_lang::prelude::*;
316    /// # use futures::StreamExt;
317    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
318    /// let tick = process.tick();
319    /// let inside_tick = process
320    ///     .source_iter(q!(vec![1, 2, 3, 4]))
321    ///     .batch(&tick, nondet!(/** test */));
322    /// inside_tick.all_ticks()
323    /// # }, |mut stream| async move {
324    /// // 1, 2, 3, 4
325    /// # for w in vec![1, 2, 3, 4] {
326    /// #     assert_eq!(stream.next().await.unwrap(), w);
327    /// # }
328    /// # }));
329    /// # }
330    /// ```
331    fn tick(&self) -> Tick<Self> {
332        self.try_tick().expect("cannot create nested ticks")
333    }
334
335    /// Creates an unbounded stream that continuously emits unit values `()`.
336    ///
337    /// This is useful for driving computations that need to run continuously,
338    /// such as polling or heartbeat mechanisms.
339    ///
340    /// # Example
341    /// ```rust
342    /// # #[cfg(feature = "deploy")] {
343    /// # use hydro_lang::prelude::*;
344    /// # use futures::StreamExt;
345    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
346    /// let tick = process.tick();
347    /// process.spin()
348    ///     .batch(&tick, nondet!(/** test */))
349    ///     .map(q!(|_| 42))
350    ///     .all_ticks()
351    /// # }, |mut stream| async move {
352    /// // 42, 42, 42, ...
353    /// # assert_eq!(stream.next().await.unwrap(), 42);
354    /// # assert_eq!(stream.next().await.unwrap(), 42);
355    /// # assert_eq!(stream.next().await.unwrap(), 42);
356    /// # }));
357    /// # }
358    /// ```
359    fn spin(&self) -> Stream<(), Self, Unbounded, TotalOrder, ExactlyOnce>
360    where
361        Self: TopLevel<'a> + Sized,
362    {
363        Stream::new(
364            self.clone(),
365            HydroNode::Source {
366                source: HydroSource::Spin(),
367                metadata: self.new_node_metadata(Stream::<
368                    (),
369                    Self,
370                    Unbounded,
371                    TotalOrder,
372                    ExactlyOnce,
373                >::collection_kind()),
374            },
375        )
376    }
377
378    /// Creates a stream from an async [`FuturesStream`].
379    ///
380    /// This is useful for integrating with external async data sources,
381    /// such as network connections or file readers.
382    ///
383    /// # Example
384    /// ```rust
385    /// # #[cfg(feature = "deploy")] {
386    /// # use hydro_lang::prelude::*;
387    /// # use futures::StreamExt;
388    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
389    /// process.source_stream(q!(futures::stream::iter(vec![1, 2, 3])))
390    /// # }, |mut stream| async move {
391    /// // 1, 2, 3
392    /// # for w in vec![1, 2, 3] {
393    /// #     assert_eq!(stream.next().await.unwrap(), w);
394    /// # }
395    /// # }));
396    /// # }
397    /// ```
398    fn source_stream<T, E>(
399        &self,
400        e: impl QuotedWithContext<'a, E, Self>,
401    ) -> Stream<T, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>
402    where
403        E: FuturesStream<Item = T> + Unpin,
404        Self: TopLevel<'a> + Sized,
405    {
406        let e = e.splice_untyped_ctx(self);
407
408        let target_location = self.drop_consistency();
409        Stream::new(
410            target_location.clone(),
411            HydroNode::Source {
412                source: HydroSource::Stream(e.into()),
413                metadata: target_location.new_node_metadata(Stream::<
414                    T,
415                    Self::DropConsistency,
416                    Unbounded,
417                    TotalOrder,
418                    ExactlyOnce,
419                >::collection_kind()),
420            },
421        )
422    }
423
424    /// Creates a bounded stream from an iterator.
425    ///
426    /// The iterator is evaluated once at runtime, and all elements are emitted
427    /// in order. This is useful for creating streams from static data or
428    /// for testing.
429    ///
430    /// # Example
431    /// ```rust
432    /// # #[cfg(feature = "deploy")] {
433    /// # use hydro_lang::prelude::*;
434    /// # use futures::StreamExt;
435    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
436    /// process.source_iter(q!(vec![1, 2, 3, 4]))
437    /// # }, |mut stream| async move {
438    /// // 1, 2, 3, 4
439    /// # for w in vec![1, 2, 3, 4] {
440    /// #     assert_eq!(stream.next().await.unwrap(), w);
441    /// # }
442    /// # }));
443    /// # }
444    /// ```
445    fn source_iter<T, E>(
446        &self,
447        e: impl QuotedWithContext<'a, E, Self>,
448    ) -> Stream<T, Self::DropConsistency, Bounded, TotalOrder, ExactlyOnce>
449    where
450        E: IntoIterator<Item = T>,
451        Self: Sized,
452    {
453        let e = e.splice_typed_ctx(self);
454
455        let target_location = self.drop_consistency();
456        Stream::new(
457            target_location.clone(),
458            HydroNode::Source {
459                source: HydroSource::Iter(e.into()),
460                metadata: target_location.new_node_metadata(Stream::<
461                    T,
462                    Self::DropConsistency,
463                    Bounded,
464                    TotalOrder,
465                    ExactlyOnce,
466                >::collection_kind()),
467            },
468        )
469    }
470
471    #[deprecated(note = "use .source_cluster_membership_stream(...) instead")]
472    /// Creates a stream of membership events for a cluster.
473    ///
474    /// This stream emits [`MembershipEvent::Joined`] when a cluster member joins
475    /// and [`MembershipEvent::Left`] when a cluster member leaves. The stream is
476    /// keyed by the [`MemberId`] of the cluster member.
477    ///
478    /// This is useful for implementing protocols that need to track cluster membership,
479    /// such as broadcasting to all members or detecting failures.
480    ///
481    /// # Non-Determinism
482    /// This stream is non-deterministic because the timing of membership events, for example
483    /// if a node leaves, the membership event may not be received if the node left before the
484    /// stream was created.
485    ///
486    /// # Example
487    /// ```rust
488    /// # #[cfg(feature = "deploy")] {
489    /// # use hydro_lang::prelude::*;
490    /// # use futures::StreamExt;
491    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
492    /// let p1 = flow.process::<()>();
493    /// let workers: Cluster<()> = flow.cluster();
494    /// # // do nothing on each worker
495    /// # workers.source_iter(q!(vec![])).for_each(q!(|_: ()| {}));
496    /// let cluster_members = p1.source_cluster_members(&workers, nondet!(/** late joiners may miss events */));
497    /// # cluster_members.entries().send(&p2, TCP.fail_stop().bincode())
498    /// // if there are 4 members in the cluster, we would see a join event for each
499    /// // { MemberId::<Worker>(0): [MembershipEvent::Join], MemberId::<Worker>(2): [MembershipEvent::Join], ... }
500    /// # }, |mut stream| async move {
501    /// # let mut results = Vec::new();
502    /// # for w in 0..4 {
503    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
504    /// # }
505    /// # results.sort();
506    /// # assert_eq!(results, vec!["(MemberId::<()>(0), Joined)", "(MemberId::<()>(1), Joined)", "(MemberId::<()>(2), Joined)", "(MemberId::<()>(3), Joined)"]);
507    /// # }));
508    /// # }
509    /// ```
510    fn source_cluster_members<C: 'a, Id: Clone + 'a>(
511        &self,
512        cluster: &Cluster<'a, C, Id>,
513        nondet_start: NonDet,
514    ) -> KeyedStream<MemberId<C, Id>, MembershipEvent, Self::DropConsistency, Unbounded>
515    where
516        Self: TopLevel<'a> + Sized,
517    {
518        self.source_cluster_membership_stream(cluster, nondet_start)
519    }
520
521    /// Creates a stream of membership events for a cluster.
522    ///
523    /// This stream emits [`MembershipEvent::Joined`] when a cluster member joins
524    /// and [`MembershipEvent::Left`] when a cluster member leaves. The stream is
525    /// keyed by the [`MemberId`] of the cluster member.
526    ///
527    /// This is useful for implementing protocols that need to track cluster membership,
528    /// such as broadcasting to all members or detecting failures.
529    ///
530    /// # Non-Determinism
531    /// This stream is non-deterministic because the timing of membership events, for example
532    /// if a node leaves, the membership event may not be received if the node left before the
533    /// stream was created.
534    ///
535    /// # Example
536    /// ```rust
537    /// # #[cfg(feature = "deploy")] {
538    /// # use hydro_lang::prelude::*;
539    /// # use futures::StreamExt;
540    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
541    /// let p1 = flow.process::<()>();
542    /// let workers: Cluster<()> = flow.cluster();
543    /// # // do nothing on each worker
544    /// # workers.source_iter(q!(vec![])).for_each(q!(|_: ()| {}));
545    /// let cluster_members = p1.source_cluster_membership_stream(&workers, nondet!(/** late joiners may miss events */));
546    /// # cluster_members.entries().send(&p2, TCP.fail_stop().bincode())
547    /// // if there are 4 members in the cluster, we would see a join event for each
548    /// // { MemberId::<Worker>(0): [MembershipEvent::Join], MemberId::<Worker>(2): [MembershipEvent::Join], ... }
549    /// # }, |mut stream| async move {
550    /// # let mut results = Vec::new();
551    /// # for w in 0..4 {
552    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
553    /// # }
554    /// # results.sort();
555    /// # assert_eq!(results, vec!["(MemberId::<()>(0), Joined)", "(MemberId::<()>(1), Joined)", "(MemberId::<()>(2), Joined)", "(MemberId::<()>(3), Joined)"]);
556    /// # }));
557    /// # }
558    /// ```
559    fn source_cluster_membership_stream<C: 'a, Id: Clone + 'a>(
560        &self,
561        cluster: &Cluster<'a, C, Id>,
562        _nondet_start: NonDet,
563    ) -> KeyedStream<MemberId<C, Id>, MembershipEvent, Self::DropConsistency, Unbounded>
564    where
565        Self: TopLevel<'a> + Sized,
566    {
567        let target_consistency = self.drop_consistency();
568        Stream::new(
569            target_consistency.clone(),
570            HydroNode::Source {
571                source: HydroSource::ClusterMembers(cluster.id(), ClusterMembersState::Uninit),
572                metadata: target_consistency.new_node_metadata(Stream::<
573                    (Id, MembershipEvent),
574                    Self,
575                    Unbounded,
576                    TotalOrder,
577                    ExactlyOnce,
578                >::collection_kind(
579                )),
580            },
581        )
582        .map(q!(|(k, v)| (MemberId::from_tagless(k), v)))
583        .into_keyed()
584    }
585
586    /// Creates a one-way connection from an external process to receive raw bytes.
587    ///
588    /// Returns a port handle for the external process to connect to, and a stream
589    /// of received byte buffers.
590    ///
591    /// For bidirectional communication or typed data, see [`Location::bind_single_client`]
592    /// or [`Location::source_external_bincode`].
593    #[cfg(feature = "tokio")]
594    fn source_external_bytes<L>(
595        &self,
596        from: &External<'_, L>,
597    ) -> (
598        ExternalBytesPort,
599        Stream<BytesMut, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>,
600    )
601    where
602        Self: TopLevel<'a> + Sized,
603    {
604        let (port, stream, sink) =
605            self.bind_single_client::<_, Bytes, LengthDelimitedCodec>(from, NetworkHint::Auto);
606
607        sink.complete(stream.location().source_iter(q!([])));
608
609        (port, stream)
610    }
611
612    /// Creates a one-way connection from an external process to receive bincode-serialized data.
613    ///
614    /// Returns a sink handle for the external process to send data to, and a stream
615    /// of received values.
616    ///
617    /// For bidirectional communication, see [`Location::bind_single_client_bincode`].
618    #[cfg(feature = "tokio")]
619    fn source_external_bincode<L, T, O: Ordering, R: Retries>(
620        &self,
621        from: &External<'_, L>,
622    ) -> (
623        ExternalBincodeSink<T, NotMany, O, R>,
624        Stream<T, Self::DropConsistency, Unbounded, O, R>,
625    )
626    where
627        Self: TopLevel<'a> + Sized,
628        T: Serialize + DeserializeOwned,
629    {
630        let (port, stream, sink) = self.bind_single_client_bincode::<_, T, ()>(from);
631        sink.complete(stream.location().source_iter(q!([])));
632
633        (
634            ExternalBincodeSink {
635                process_key: from.key,
636                port_id: port.port_id,
637                _phantom: PhantomData,
638            },
639            stream.weaken_ordering().weaken_retries(),
640        )
641    }
642
643    /// Sets up a MessagePack-encoded simulated input port on this location for testing.
644    ///
645    /// Returns a handle to send messages to the location as well as a stream
646    /// of received messages. Use [`Location::sim_input_with`] to select another codec.
647    /// This is only available when the `sim` feature is enabled.
648    #[cfg(feature = "sim")]
649    fn sim_input<T, O: Ordering, R: Retries>(
650        &self,
651    ) -> (
652        SimSender<T, O, R>,
653        Stream<T, Self::DropConsistency, Unbounded, O, R>,
654    )
655    where
656        Self: TopLevel<'a> + Sized,
657        T: Serialize + DeserializeOwned,
658    {
659        self.sim_input_with::<crate::sim::codec::RmpCodec, T, O, R>()
660    }
661
662    /// Sets up a simulated input port using the codec `C`.
663    ///
664    /// Returns a handle to send messages to the location as well as a stream
665    /// of received messages. The codec is a type parameter; the message, ordering and
666    /// retries types are usually inferred: `location.sim_input_with::<MyCodec, _, _, _>()`.
667    /// Custom codecs implement [`SimCodec`](crate::sim::codec::SimCodec), which documents
668    /// where they must be defined. This is only available when the `sim` feature is enabled.
669    #[cfg(feature = "sim")]
670    fn sim_input_with<C: crate::sim::codec::SimCodec<T>, T, O: Ordering, R: Retries>(
671        &self,
672    ) -> (
673        SimSender<T, O, R>,
674        Stream<T, Self::DropConsistency, Unbounded, O, R>,
675    )
676    where
677        Self: TopLevel<'a> + Sized,
678    {
679        let external_location: External<'a, ()> = External {
680            key: LocationKey::FIRST,
681            flow_state: self.flow_state().clone(),
682            _phantom: PhantomData,
683        };
684
685        let (external_port_id, stream) = register_serialized_external_input(
686            self,
687            &external_location,
688            crate::sim::codec::staged_deserialize::<T, C>(),
689        );
690
691        (
692            SimSender(external_port_id, PhantomData, C::encode),
693            stream.weaken_ordering().weaken_retries(),
694        )
695    }
696
697    /// Creates an external input stream for embedded deployment mode.
698    ///
699    /// The `name` parameter specifies the name of the field in the generated `EmbeddedInputs`
700    /// struct that will supply data to this stream at runtime: a
701    /// [`EmbeddedInputChannel`](crate::compile::embedded_runtime::EmbeddedInputChannel) around the host's
702    /// `Stream<Item = T> + Unpin`. The stream's ordering `O` and retries `R` are what the
703    /// dataflow relies on, so they are what the host must promise: declare only what the
704    /// dataflow relies on (for example `NoOrder` if it does not use the stream's order), and the
705    /// host promises nothing more.
706    fn embedded_input<T, O: Ordering, R: Retries>(
707        &self,
708        name: impl Into<String>,
709    ) -> Stream<T, Self::DropConsistency, Unbounded, O, R>
710    where
711        Self: TopLevel<'a> + Sized,
712    {
713        let ident = syn::Ident::new(&name.into(), Span::call_site());
714
715        let target_location = self.drop_consistency();
716        Stream::new(
717            target_location.clone(),
718            HydroNode::Source {
719                source: HydroSource::Embedded(ident),
720                metadata: target_location
721                    .new_node_metadata(Stream::<T, Self, Unbounded, O, R>::collection_kind()),
722            },
723        )
724    }
725
726    /// Creates an embedded singleton input for embedded deployment mode.
727    ///
728    /// The `name` parameter specifies the name of the generated function parameter
729    /// that will supply data to this singleton at runtime. The generated function will
730    /// accept a plain `T` parameter with this name.
731    fn embedded_singleton_input<T>(
732        &self,
733        name: impl Into<String>,
734    ) -> Singleton<T, Self::DropConsistency, Bounded>
735    where
736        Self: TopLevel<'a> + Sized,
737    {
738        let ident = syn::Ident::new(&name.into(), Span::call_site());
739
740        let target_location = self.drop_consistency();
741        Singleton::new(
742            target_location.clone(),
743            HydroNode::Source {
744                source: HydroSource::EmbeddedSingleton(ident),
745                metadata: target_location
746                    .new_node_metadata(Singleton::<T, Self, Bounded>::collection_kind()),
747            },
748        )
749    }
750
751    /// Establishes a server on this location to receive a bidirectional connection from a single
752    /// client, identified by the given `External` handle. Returns a port handle for the external
753    /// process to connect to, a stream of incoming messages, and a handle to send outgoing
754    /// messages.
755    ///
756    /// # Example
757    /// ```rust
758    /// # #[cfg(feature = "deploy")] {
759    /// # use hydro_lang::prelude::*;
760    /// # use hydro_deploy::Deployment;
761    /// # use futures::{SinkExt, StreamExt};
762    /// # tokio_test::block_on(async {
763    /// # use bytes::Bytes;
764    /// # use hydro_lang::location::NetworkHint;
765    /// # use tokio_util::codec::LengthDelimitedCodec;
766    /// # let mut flow = FlowBuilder::new();
767    /// let node = flow.process::<()>();
768    /// let external = flow.external::<()>();
769    /// let (port, incoming, outgoing) =
770    ///     node.bind_single_client::<_, Bytes, LengthDelimitedCodec>(&external, NetworkHint::Auto);
771    /// outgoing.complete(incoming.map(q!(|data /* : Bytes */| {
772    ///     let mut resp: Vec<u8> = data.into();
773    ///     resp.push(42);
774    ///     resp.into() // : Bytes
775    /// })));
776    ///
777    /// # let mut deployment = Deployment::new();
778    /// let nodes = flow // ... with_process and with_external
779    /// #     .with_process(&node, deployment.Localhost())
780    /// #     .with_external(&external, deployment.Localhost())
781    /// #     .deploy(&mut deployment);
782    ///
783    /// deployment.deploy().await.unwrap();
784    /// deployment.start().await.unwrap();
785    ///
786    /// let (mut external_out, mut external_in) = nodes.connect(port).await;
787    /// external_in.send(vec![1, 2, 3].into()).await.unwrap();
788    /// assert_eq!(
789    ///     external_out.next().await.unwrap().unwrap(),
790    ///     vec![1, 2, 3, 42]
791    /// );
792    /// # });
793    /// # }
794    /// ```
795    #[cfg(feature = "tokio")]
796    #[expect(clippy::type_complexity, reason = "stream markers")]
797    fn bind_single_client<L, T, Codec: Encoder<T> + Decoder>(
798        &self,
799        from: &External<'_, L>,
800        port_hint: NetworkHint,
801    ) -> (
802        ExternalBytesPort<NotMany>,
803        Stream<<Codec as Decoder>::Item, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>,
804        ForwardHandle<'a, Stream<T, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>>,
805    )
806    where
807        Self: TopLevel<'a> + Sized,
808    {
809        let next_external_port_id = from.flow_state.borrow_mut().next_external_port();
810        let target_consistency = self.drop_consistency();
811
812        let (fwd_ref, to_sink) = target_consistency.forward_ref::<Stream<
813            T,
814            Self::DropConsistency,
815            Unbounded,
816            TotalOrder,
817            ExactlyOnce,
818        >>();
819        let mut flow_state_borrow = self.flow_state().borrow_mut();
820
821        flow_state_borrow.push_root(HydroRoot::SendExternal {
822            to_external_key: from.key,
823            to_port_id: next_external_port_id,
824            to_many: false,
825            unpaired: false,
826            serialize_fn: None,
827            instantiate_fn: DebugInstantiate::Building,
828            input: Box::new(to_sink.ir_node.replace(HydroNode::Placeholder)),
829            op_metadata: HydroIrOpMetadata::new(),
830        });
831        drop(flow_state_borrow);
832
833        let raw_stream: Stream<
834            Result<<Codec as Decoder>::Item, <Codec as Decoder>::Error>,
835            Self::DropConsistency,
836            Unbounded,
837            TotalOrder,
838            ExactlyOnce,
839        > = Stream::new(
840            target_consistency.clone(),
841            HydroNode::ExternalInput {
842                from_external_key: from.key,
843                from_port_id: next_external_port_id,
844                from_many: false,
845                codec_type: quote_type::<Codec>().into(),
846                encode_type: quote_type::<T>().into(),
847                port_hint,
848                instantiate_fn: DebugInstantiate::Building,
849                deserialize_fn: None,
850                metadata: target_consistency.new_node_metadata(Stream::<
851                    Result<<Codec as Decoder>::Item, <Codec as Decoder>::Error>,
852                    Self::DropConsistency,
853                    Unbounded,
854                    TotalOrder,
855                    ExactlyOnce,
856                >::collection_kind(
857                )),
858            },
859        );
860
861        (
862            ExternalBytesPort {
863                process_key: from.key,
864                port_id: next_external_port_id,
865                _phantom: PhantomData,
866            },
867            raw_stream.flatten_ordered(),
868            fwd_ref,
869        )
870    }
871
872    // TODO: Replace this staged-expression helper with codec-parameterized sink and bidi handles.
873    #[doc(hidden)]
874    #[cfg(feature = "tokio")]
875    #[expect(clippy::type_complexity, reason = "stream markers")]
876    fn register_serialized_single_client<L, InT, OutT>(
877        &self,
878        from: &External<'_, L>,
879        serialize_fn: syn::Expr,
880        deserialize_fn: syn::Expr,
881    ) -> (
882        ExternalPortId,
883        Stream<InT, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>,
884        ForwardHandle<'a, Stream<OutT, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>>,
885    )
886    where
887        Self: TopLevel<'a> + Sized,
888    {
889        let next_external_port_id = from.flow_state.borrow_mut().next_external_port();
890
891        let target_consistency = self.drop_consistency();
892        let (fwd_ref, to_sink) = target_consistency.forward_ref::<Stream<
893            OutT,
894            Self::DropConsistency,
895            Unbounded,
896            TotalOrder,
897            ExactlyOnce,
898        >>();
899        let mut flow_state_borrow = self.flow_state().borrow_mut();
900
901        flow_state_borrow.push_root(HydroRoot::SendExternal {
902            to_external_key: from.key,
903            to_port_id: next_external_port_id,
904            to_many: false,
905            unpaired: false,
906            serialize_fn: Some(serialize_fn.into()),
907            instantiate_fn: DebugInstantiate::Building,
908            input: Box::new(to_sink.ir_node.replace(HydroNode::Placeholder)),
909            op_metadata: HydroIrOpMetadata::new(),
910        });
911        drop(flow_state_borrow);
912
913        let raw_stream: Stream<InT, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce> =
914            Stream::new(
915                target_consistency.clone(),
916                HydroNode::ExternalInput {
917                    from_external_key: from.key,
918                    from_port_id: next_external_port_id,
919                    from_many: false,
920                    codec_type: quote_type::<LengthDelimitedCodec>().into(),
921                    encode_type: quote_type::<Bytes>().into(),
922                    port_hint: NetworkHint::Auto,
923                    instantiate_fn: DebugInstantiate::Building,
924                    deserialize_fn: Some(deserialize_fn.into()),
925                    metadata: target_consistency.new_node_metadata(Stream::<
926                        InT,
927                        Self::DropConsistency,
928                        Unbounded,
929                        TotalOrder,
930                        ExactlyOnce,
931                    >::collection_kind(
932                    )),
933                },
934            );
935
936        (next_external_port_id, raw_stream, fwd_ref)
937    }
938
939    /// Establishes a bidirectional connection from a single external client using bincode serialization.
940    ///
941    /// Returns a port handle for the external process to connect to, a stream of incoming messages,
942    /// and a handle to send outgoing messages. This is a convenience wrapper around
943    /// [`Location::bind_single_client`] that uses bincode for serialization.
944    ///
945    /// # Type Parameters
946    /// - `InT`: The type of incoming messages (must implement [`DeserializeOwned`])
947    /// - `OutT`: The type of outgoing messages (must implement [`Serialize`])
948    #[cfg(feature = "tokio")]
949    #[expect(clippy::type_complexity, reason = "stream markers")]
950    fn bind_single_client_bincode<L, InT: DeserializeOwned, OutT: Serialize>(
951        &self,
952        from: &External<'_, L>,
953    ) -> (
954        ExternalBincodeBidi<InT, OutT, NotMany>,
955        Stream<InT, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>,
956        ForwardHandle<'a, Stream<OutT, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>>,
957    )
958    where
959        Self: TopLevel<'a> + Sized,
960    {
961        let root = get_this_crate();
962
963        let out_t_type = quote_type::<OutT>();
964        let ser_fn: syn::Expr = syn::parse_quote! {
965            #root::runtime_support::stageleft::runtime_support::fn1_type_hint::<#out_t_type, _>(
966                |b| #root::runtime_support::bincode::serialize(&b).unwrap().into()
967            )
968        };
969
970        let in_t_type = quote_type::<InT>();
971        let deser_fn: syn::Expr = syn::parse_quote! {
972            |res| {
973                let b = res.unwrap();
974                #root::runtime_support::bincode::deserialize::<#in_t_type>(&b).unwrap()
975            }
976        };
977
978        let (port_id, raw_stream, fwd_ref) =
979            self.register_serialized_single_client::<_, InT, OutT>(from, ser_fn, deser_fn);
980
981        (
982            ExternalBincodeBidi {
983                process_key: from.key,
984                port_id,
985                _phantom: PhantomData,
986            },
987            raw_stream,
988            fwd_ref,
989        )
990    }
991
992    /// Establishes a server on this location to receive bidirectional connections from multiple
993    /// external clients using raw bytes.
994    ///
995    /// Unlike [`Location::bind_single_client`], this method supports multiple concurrent client
996    /// connections. Each client is assigned a unique `u64` identifier.
997    ///
998    /// Returns:
999    /// - A port handle for external processes to connect to
1000    /// - A keyed stream of incoming messages, keyed by client ID
1001    /// - A keyed stream of membership events (client joins/leaves), keyed by client ID
1002    /// - A handle to send outgoing messages, keyed by client ID
1003    #[cfg(feature = "tokio")]
1004    #[expect(clippy::type_complexity, reason = "stream markers")]
1005    fn bidi_external_many_bytes<L, T, Codec: Encoder<T> + Decoder>(
1006        &self,
1007        from: &External<'_, L>,
1008        port_hint: NetworkHint,
1009    ) -> (
1010        ExternalBytesPort<Many>,
1011        KeyedStream<
1012            u64,
1013            <Codec as Decoder>::Item,
1014            Self::DropConsistency,
1015            Unbounded,
1016            TotalOrder,
1017            ExactlyOnce,
1018        >,
1019        KeyedStream<
1020            u64,
1021            MembershipEvent,
1022            Self::DropConsistency,
1023            Unbounded,
1024            TotalOrder,
1025            ExactlyOnce,
1026        >,
1027        ForwardHandle<
1028            'a,
1029            KeyedStream<u64, T, Self::DropConsistency, Unbounded, NoOrder, ExactlyOnce>,
1030        >,
1031    )
1032    where
1033        Self: TopLevel<'a> + Sized,
1034    {
1035        let next_external_port_id = from.flow_state.borrow_mut().next_external_port();
1036
1037        let target_consistency = self.drop_consistency();
1038        let (fwd_ref, to_sink) = target_consistency.forward_ref::<KeyedStream<
1039            u64,
1040            T,
1041            Self::DropConsistency,
1042            Unbounded,
1043            NoOrder,
1044            ExactlyOnce,
1045        >>();
1046        let to_sink_input = Box::new(to_sink.entries().ir_node.replace(HydroNode::Placeholder));
1047        let mut flow_state_borrow = self.flow_state().borrow_mut();
1048
1049        flow_state_borrow.push_root(HydroRoot::SendExternal {
1050            to_external_key: from.key,
1051            to_port_id: next_external_port_id,
1052            to_many: true,
1053            unpaired: false,
1054            serialize_fn: None,
1055            instantiate_fn: DebugInstantiate::Building,
1056            input: to_sink_input,
1057            op_metadata: HydroIrOpMetadata::new(),
1058        });
1059        drop(flow_state_borrow);
1060
1061        let raw_stream: Stream<
1062            Result<(u64, <Codec as Decoder>::Item), <Codec as Decoder>::Error>,
1063            Self::DropConsistency,
1064            Unbounded,
1065            TotalOrder,
1066            ExactlyOnce,
1067        > = Stream::new(
1068            target_consistency.clone(),
1069            HydroNode::ExternalInput {
1070                from_external_key: from.key,
1071                from_port_id: next_external_port_id,
1072                from_many: true,
1073                codec_type: quote_type::<Codec>().into(),
1074                encode_type: quote_type::<T>().into(),
1075                port_hint,
1076                instantiate_fn: DebugInstantiate::Building,
1077                deserialize_fn: None,
1078                metadata: target_consistency.new_node_metadata(Stream::<
1079                    Result<(u64, <Codec as Decoder>::Item), <Codec as Decoder>::Error>,
1080                    Self::DropConsistency,
1081                    Unbounded,
1082                    TotalOrder,
1083                    ExactlyOnce,
1084                >::collection_kind(
1085                )),
1086            },
1087        );
1088
1089        let membership_stream_ident = syn::Ident::new(
1090            &format!(
1091                "__hydro_deploy_many_{}_{}_membership",
1092                from.key, next_external_port_id
1093            ),
1094            Span::call_site(),
1095        );
1096        let membership_stream_expr: syn::Expr = parse_quote!(#membership_stream_ident);
1097        let raw_membership_stream: KeyedStream<
1098            u64,
1099            bool,
1100            Self::DropConsistency,
1101            Unbounded,
1102            TotalOrder,
1103            ExactlyOnce,
1104        > = KeyedStream::new(
1105            target_consistency.clone(),
1106            HydroNode::Source {
1107                source: HydroSource::Stream(membership_stream_expr.into()),
1108                metadata: target_consistency.new_node_metadata(KeyedStream::<
1109                    u64,
1110                    bool,
1111                    Self::DropConsistency,
1112                    Unbounded,
1113                    TotalOrder,
1114                    ExactlyOnce,
1115                >::collection_kind(
1116                )),
1117            },
1118        );
1119
1120        (
1121            ExternalBytesPort {
1122                process_key: from.key,
1123                port_id: next_external_port_id,
1124                _phantom: PhantomData,
1125            },
1126            raw_stream
1127                .flatten_ordered() // TODO(shadaj): this silently drops framing errors, decide on right defaults
1128                .into_keyed(),
1129            raw_membership_stream.map(q!(|join| {
1130                if join {
1131                    MembershipEvent::Joined
1132                } else {
1133                    MembershipEvent::Left
1134                }
1135            })),
1136            fwd_ref,
1137        )
1138    }
1139
1140    /// Establishes a server on this location to receive bidirectional connections from multiple
1141    /// external clients using bincode serialization.
1142    ///
1143    /// Unlike [`Location::bind_single_client_bincode`], this method supports multiple concurrent
1144    /// client connections. Each client is assigned a unique `u64` identifier.
1145    ///
1146    /// Returns:
1147    /// - A port handle for external processes to connect to
1148    /// - A keyed stream of incoming messages, keyed by client ID
1149    /// - A keyed stream of membership events (client joins/leaves), keyed by client ID
1150    /// - A handle to send outgoing messages, keyed by client ID
1151    ///
1152    /// # Type Parameters
1153    /// - `InT`: The type of incoming messages (must implement [`DeserializeOwned`])
1154    /// - `OutT`: The type of outgoing messages (must implement [`Serialize`])
1155    #[cfg(feature = "tokio")]
1156    #[expect(clippy::type_complexity, reason = "stream markers")]
1157    fn bidi_external_many_bincode<L, InT: DeserializeOwned, OutT: Serialize>(
1158        &self,
1159        from: &External<'_, L>,
1160    ) -> (
1161        ExternalBincodeBidi<InT, OutT, Many>,
1162        KeyedStream<u64, InT, Self::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>,
1163        KeyedStream<
1164            u64,
1165            MembershipEvent,
1166            Self::DropConsistency,
1167            Unbounded,
1168            TotalOrder,
1169            ExactlyOnce,
1170        >,
1171        ForwardHandle<
1172            'a,
1173            KeyedStream<u64, OutT, Self::DropConsistency, Unbounded, NoOrder, ExactlyOnce>,
1174        >,
1175    )
1176    where
1177        Self: TopLevel<'a> + Sized,
1178    {
1179        let next_external_port_id = from.flow_state.borrow_mut().next_external_port();
1180
1181        let target_consistency = self.drop_consistency();
1182        let (fwd_ref, to_sink) = target_consistency.forward_ref::<KeyedStream<
1183            u64,
1184            OutT,
1185            Self::DropConsistency,
1186            Unbounded,
1187            NoOrder,
1188            ExactlyOnce,
1189        >>();
1190        let to_sink_input = Box::new(to_sink.entries().ir_node.replace(HydroNode::Placeholder));
1191        let mut flow_state_borrow = self.flow_state().borrow_mut();
1192
1193        let root = get_this_crate();
1194
1195        let out_t_type = quote_type::<OutT>();
1196        let ser_fn: syn::Expr = syn::parse_quote! {
1197            #root::runtime_support::stageleft::runtime_support::fn1_type_hint::<(u64, #out_t_type), _>(
1198                |(id, b)| (id, #root::runtime_support::bincode::serialize(&b).unwrap().into())
1199            )
1200        };
1201
1202        flow_state_borrow.push_root(HydroRoot::SendExternal {
1203            to_external_key: from.key,
1204            to_port_id: next_external_port_id,
1205            to_many: true,
1206            unpaired: false,
1207            serialize_fn: Some(ser_fn.into()),
1208            instantiate_fn: DebugInstantiate::Building,
1209            input: to_sink_input,
1210            op_metadata: HydroIrOpMetadata::new(),
1211        });
1212        drop(flow_state_borrow);
1213
1214        let in_t_type = quote_type::<InT>();
1215
1216        let deser_fn: syn::Expr = syn::parse_quote! {
1217            |res| {
1218                let (id, b) = res.unwrap();
1219                (id, #root::runtime_support::bincode::deserialize::<#in_t_type>(&b).unwrap())
1220            }
1221        };
1222
1223        let raw_stream: KeyedStream<
1224            u64,
1225            InT,
1226            Self::DropConsistency,
1227            Unbounded,
1228            TotalOrder,
1229            ExactlyOnce,
1230        > = KeyedStream::new(
1231            target_consistency.clone(),
1232            HydroNode::ExternalInput {
1233                from_external_key: from.key,
1234                from_port_id: next_external_port_id,
1235                from_many: true,
1236                codec_type: quote_type::<LengthDelimitedCodec>().into(),
1237                encode_type: quote_type::<Bytes>().into(),
1238                port_hint: NetworkHint::Auto,
1239                instantiate_fn: DebugInstantiate::Building,
1240                deserialize_fn: Some(deser_fn.into()),
1241                metadata: target_consistency.new_node_metadata(KeyedStream::<
1242                    u64,
1243                    InT,
1244                    Self::DropConsistency,
1245                    Unbounded,
1246                    TotalOrder,
1247                    ExactlyOnce,
1248                >::collection_kind(
1249                )),
1250            },
1251        );
1252
1253        let membership_stream_ident = syn::Ident::new(
1254            &format!(
1255                "__hydro_deploy_many_{}_{}_membership",
1256                from.key, next_external_port_id
1257            ),
1258            Span::call_site(),
1259        );
1260        let membership_stream_expr: syn::Expr = parse_quote!(#membership_stream_ident);
1261        let raw_membership_stream: KeyedStream<
1262            u64,
1263            bool,
1264            Self::DropConsistency,
1265            Unbounded,
1266            TotalOrder,
1267            ExactlyOnce,
1268        > = KeyedStream::new(
1269            target_consistency.clone(),
1270            HydroNode::Source {
1271                source: HydroSource::Stream(membership_stream_expr.into()),
1272                metadata: target_consistency.new_node_metadata(KeyedStream::<
1273                    u64,
1274                    bool,
1275                    Self::DropConsistency,
1276                    Unbounded,
1277                    TotalOrder,
1278                    ExactlyOnce,
1279                >::collection_kind(
1280                )),
1281            },
1282        );
1283
1284        (
1285            ExternalBincodeBidi {
1286                process_key: from.key,
1287                port_id: next_external_port_id,
1288                _phantom: PhantomData,
1289            },
1290            raw_stream,
1291            raw_membership_stream.map(q!(|join| {
1292                if join {
1293                    MembershipEvent::Joined
1294                } else {
1295                    MembershipEvent::Left
1296                }
1297            })),
1298            fwd_ref,
1299        )
1300    }
1301
1302    /// Bridges user-owned async code to the dataflow as a **bidirectional sidecar**.
1303    ///
1304    /// The closure is called once at startup and must return a
1305    /// `(Stream<InT>, Sink<OutT>)` pair. The framework reads from the stream
1306    /// (items flowing *into* the dataflow) and writes to the sink (items flowing
1307    /// *out* to the sidecar). The user controls buffering, backpressure, and
1308    /// internal lifecycle — Hydro only sees the stream/sink interface.
1309    ///
1310    /// This will hopefully make it easy to integrate hydro with existing frameworks,
1311    /// for example grpc code generated service endpoints.
1312    ///
1313    /// # Returns
1314    /// - A `Stream<InT>` carrying items from the sidecar into the dataflow.
1315    /// - A [`ForwardHandle`] expecting a `Stream<OutT>` that the user completes
1316    ///   with items destined for the sidecar.
1317    ///
1318    /// # Example
1319    ///
1320    /// ```rust
1321    /// # #[cfg(feature = "deploy")] {
1322    /// # use hydro_lang::prelude::*;
1323    /// # use futures::StreamExt;
1324    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1325    /// // Sidecar that echoes whatever it receives back into the dataflow.
1326    /// let (inbound, response_handle) = process.sidecar_bidi::<String, String, _>(q!(|| {
1327    ///     let (to_df_tx, to_df_rx) = tokio::sync::mpsc::channel::<String>(16);
1328    ///     let (from_df_tx, mut from_df_rx) = tokio::sync::mpsc::channel::<String>(16);
1329    ///
1330    ///     // Spawn the sidecar: echoes items from the dataflow back into it.
1331    ///     tokio::spawn(async move {
1332    ///         while let Some(msg) = from_df_rx.recv().await {
1333    ///             to_df_tx.send(msg).await.ok();
1334    ///         }
1335    ///     });
1336    ///
1337    ///     // Return the framework-facing ends (concrete types, no boxing needed).
1338    ///     let stream = tokio_stream::wrappers::ReceiverStream::new(to_df_rx);
1339    ///     let sink = tokio_util::sync::PollSender::new(from_df_tx);
1340    ///     (stream, sink)
1341    /// }));
1342    ///
1343    /// // Send "hello" into the sidecar via the response channel.
1344    /// let input = process.source_stream(q!(futures::stream::iter(vec!["hello".to_string()])));
1345    /// response_handle.complete(input);
1346    ///
1347    /// // The sidecar echoes it back — assert we get "hello" out.
1348    /// inbound
1349    /// # }, |mut stream| async move {
1350    /// #     assert_eq!(stream.next().await.unwrap(), "hello");
1351    /// # }));
1352    /// # }
1353    /// ```
1354    fn sidecar_bidi<InT: 'static, OutT: 'static, F>(
1355        &self,
1356        sidecar: impl QuotedWithContext<'a, F, Self>,
1357    ) -> (
1358        Stream<InT, Self, Unbounded, TotalOrder, ExactlyOnce>,
1359        ForwardHandle<'a, Stream<OutT, Self, Unbounded, NoOrder, ExactlyOnce>>,
1360    )
1361    where
1362        Self: Sized + TopLevel<'a>,
1363    {
1364        let location_key = Location::id(self).key();
1365
1366        let sidecar_id = self.flow_state().borrow_mut().next_sidecar_id();
1367        let (stream_ident, sink_ident) = sidecar_id.idents();
1368
1369        let sidecar_closure: syn::Expr = sidecar.splice_untyped_ctx(self);
1370        self.flow_state()
1371            .borrow_mut()
1372            .sidecars
1373            .push(crate::compile::builder::Sidecar::Bidi {
1374                location_key,
1375                sidecar_id,
1376                sidecar_closure: Box::new(sidecar_closure),
1377            });
1378
1379        // Inbound stream: reads from the stream returned by the sidecar closure
1380        let source_expr: syn::Expr = parse_quote! {
1381            #stream_ident
1382        };
1383        let inbound: Stream<InT, Self, Unbounded, TotalOrder, ExactlyOnce> = Stream::new(
1384            self.clone(),
1385            HydroNode::Source {
1386                source: HydroSource::Stream(source_expr.into()),
1387                metadata: self.new_node_metadata(Stream::<
1388                    InT,
1389                    Self,
1390                    Unbounded,  // TODO: maybe bounded sidecars are interesting..?
1391                    TotalOrder, // TODO: NoOrder..?
1392                    ExactlyOnce,
1393                >::collection_kind()),
1394            },
1395        );
1396
1397        // Outbound: forward_ref cycle feeding the sink returned by the sidecar closure
1398        let (fwd_ref, to_sink): (
1399            ForwardHandle<'a, Stream<OutT, Self, Unbounded, NoOrder, ExactlyOnce>>,
1400            Stream<OutT, Self, Unbounded, NoOrder, ExactlyOnce>,
1401        ) = self.forward_ref();
1402
1403        let sink_expr: syn::Expr = parse_quote! {
1404            #sink_ident
1405        };
1406
1407        let sink_input_ir = to_sink.ir_node.replace(HydroNode::Placeholder);
1408        self.flow_state()
1409            .borrow_mut()
1410            .try_push_root(HydroRoot::DestSink {
1411                sink: sink_expr.into(),
1412                input: Box::new(sink_input_ir),
1413                op_metadata: HydroIrOpMetadata::new(),
1414            });
1415
1416        (inbound, fwd_ref)
1417    }
1418
1419    /// Constructs a [`Singleton`] materialized at this location with the given static value.
1420    ///
1421    /// See also: [`Tick::singleton`], for creating a singleton _within_ a tick, which requires
1422    /// `T: Clone`.
1423    ///
1424    /// # Example
1425    /// ```rust
1426    /// # #[cfg(feature = "deploy")] {
1427    /// # use hydro_lang::prelude::*;
1428    /// # use futures::StreamExt;
1429    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1430    /// let singleton = process.singleton(q!(5));
1431    /// # singleton.into_stream()
1432    /// # }, |mut stream| async move {
1433    /// // 5
1434    /// # assert_eq!(stream.next().await.unwrap(), 5);
1435    /// # }));
1436    /// # }
1437    /// ```
1438    fn singleton<T>(
1439        &self,
1440        e: impl QuotedWithContext<'a, T, Self>,
1441    ) -> Singleton<T, Self::DropConsistency, Bounded>
1442    where
1443        Self: Sized,
1444    {
1445        let e = e.splice_untyped_ctx(self);
1446
1447        let target_location = self.drop_consistency();
1448        Singleton::new(
1449            target_location.clone(),
1450            HydroNode::SingletonSource {
1451                value: e.into(),
1452                first_tick_only: false,
1453                metadata: target_location.new_node_metadata(Singleton::<
1454                    T,
1455                    Self::DropConsistency,
1456                    Bounded,
1457                >::collection_kind()),
1458            },
1459        )
1460    }
1461
1462    /// Constructs a [`Singleton`] by resolving an async [`Future`] to completion.
1463    ///
1464    /// This is a convenience method equivalent to
1465    /// `self.singleton(future_expr).resolve_future_blocking()`, which is a common
1466    /// pattern when initializing a singleton from an async computation.
1467    ///
1468    /// # Example
1469    /// ```rust
1470    /// # #[cfg(feature = "deploy")] {
1471    /// # use hydro_lang::prelude::*;
1472    /// # use futures::StreamExt;
1473    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1474    /// let singleton = process.singleton_future(q!(async { 42 }));
1475    /// singleton.into_stream()
1476    /// # }, |mut stream| async move {
1477    /// // 42
1478    /// # assert_eq!(stream.next().await.unwrap(), 42);
1479    /// # }));
1480    /// # }
1481    /// ```
1482    ///
1483    /// [`Future`]: std::future::Future
1484    fn singleton_future<F>(
1485        &self,
1486        e: impl QuotedWithContext<'a, F, Self>,
1487    ) -> Singleton<F::Output, Self::DropConsistency, Bounded>
1488    where
1489        F: Future,
1490        Self: Sized,
1491    {
1492        self.singleton(e).resolve_future_blocking()
1493    }
1494
1495    /// Generates a stream that emits `()` at a fixed interval.
1496    ///
1497    /// The first tick completes immediately. Missed ticks will be scheduled
1498    /// as soon as possible.
1499    ///
1500    /// The stream is `AtLeastOnce`: it only emits `()`, and every non-empty
1501    /// sequence of `()` is one `AtLeastOnce` equivalence class, so the stream
1502    /// is deterministic as a whole — the non-determinism of *when*, and how
1503    /// many, events fire before a tick is captured entirely by the downstream
1504    /// `batch`'s [`NonDet`] guard, so none is required here.
1505    #[cfg(feature = "tokio")]
1506    fn source_interval(
1507        &self,
1508        interval: impl QuotedWithContext<'a, Duration, Self> + Copy + 'a,
1509    ) -> Stream<(), Self, Unbounded, TotalOrder, AtLeastOnce>
1510    where
1511        Self: TopLevel<'a> + Sized,
1512    {
1513        self.source_stream(q!(tokio_stream::StreamExt::map(
1514            tokio_stream::wrappers::IntervalStream::new(tokio::time::interval(interval)),
1515            |_| ()
1516        )))
1517        .weaken_retries::<AtLeastOnce>()
1518        .assert_has_consistency_of_trusted(
1519            manual_proof!(/** every non-empty sequence of `()` is one `AtLeastOnce` class */),
1520        )
1521    }
1522
1523    /// Generates a stream that emits `()` at a fixed interval, after an
1524    /// initial delay.
1525    ///
1526    /// The stream is `AtLeastOnce`: it only emits `()`, and every non-empty
1527    /// sequence of `()` is one `AtLeastOnce` equivalence class, so the stream
1528    /// is deterministic as a whole — the non-determinism of *when*, and how
1529    /// many, events fire before a tick is captured entirely by the downstream
1530    /// `batch`'s [`NonDet`] guard, so none is required here.
1531    #[cfg(feature = "tokio")]
1532    fn source_interval_delayed(
1533        &self,
1534        delay: impl QuotedWithContext<'a, Duration, Self> + Copy + 'a,
1535        interval: impl QuotedWithContext<'a, Duration, Self> + Copy + 'a,
1536    ) -> Stream<(), Self, Unbounded, TotalOrder, AtLeastOnce>
1537    where
1538        Self: TopLevel<'a> + Sized,
1539    {
1540        self.source_stream(q!(tokio_stream::StreamExt::map(
1541            tokio_stream::wrappers::IntervalStream::new(tokio::time::interval_at(
1542                tokio::time::Instant::now() + delay,
1543                interval,
1544            )),
1545            |_| ()
1546        )))
1547        .weaken_retries::<AtLeastOnce>()
1548        .assert_has_consistency_of_trusted(
1549            manual_proof!(/** every non-empty sequence of `()` is one `AtLeastOnce` class */),
1550        )
1551    }
1552
1553    /// Creates a forward reference, allowing a stream to be used before its source is defined.
1554    ///
1555    /// Returns a `(handle, placeholder)` pair. Use the placeholder in the dataflow graph,
1556    /// then call `handle.complete(actual_stream)` to wire in the real source.
1557    ///
1558    /// This is useful for mutually-dependent dataflows or when the definition order
1559    /// doesn't match the data flow direction. For feedback loops, prefer [`Tick::cycle`]
1560    /// instead, which automatically defers values by one tick.
1561    ///
1562    /// # Panics
1563    /// Panics if the forward reference creates a synchronous cycle (i.e., the completed
1564    /// stream transitively depends on the placeholder without a `defer_tick` or network
1565    /// hop in between).
1566    ///
1567    /// # Example
1568    /// ```rust
1569    /// # #[cfg(feature = "deploy")] {
1570    /// # use hydro_lang::prelude::*;
1571    /// # use hydro_lang::live_collections::stream::NoOrder;
1572    /// # use futures::StreamExt;
1573    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1574    /// // Create a forward reference to define a stream that will be completed later
1575    /// let (complete, forward_stream) = process.forward_ref::<Stream<i32, _, _, NoOrder>>();
1576    ///
1577    /// // Use the forward reference as input to another computation
1578    /// let output: Stream<_, _, _, NoOrder> = forward_stream.map(q!(|x| x * 2));
1579    ///
1580    /// // Complete the forward reference with the actual source
1581    /// let source: Stream<_, _, Unbounded> = process.source_iter(q!([1, 2, 3])).into();
1582    /// complete.complete(source);
1583    /// output
1584    /// # }, |mut stream| async move {
1585    /// // 2, 4, 6
1586    /// # assert_eq!(stream.next().await.unwrap(), 2);
1587    /// # assert_eq!(stream.next().await.unwrap(), 4);
1588    /// # assert_eq!(stream.next().await.unwrap(), 6);
1589    /// # }));
1590    /// # }
1591    /// ```
1592    fn forward_ref<S>(&self) -> (ForwardHandle<'a, S>, S)
1593    where
1594        S: CycleCollection<'a, ForwardRef, Location = Self>,
1595    {
1596        let cycle_id = self.flow_state().borrow_mut().next_cycle_id();
1597        (
1598            ForwardHandle::new(cycle_id, Location::id(self)),
1599            S::create_source(cycle_id, self.clone()),
1600        )
1601    }
1602}
1603
1604#[cfg(feature = "deploy")]
1605#[cfg(test)]
1606mod tests {
1607    use std::collections::HashSet;
1608
1609    use futures::{SinkExt, StreamExt};
1610    use hydro_deploy::Deployment;
1611    use stageleft::q;
1612    use tokio_util::codec::LengthDelimitedCodec;
1613
1614    use crate::compile::builder::FlowBuilder;
1615    use crate::live_collections::stream::{ExactlyOnce, TotalOrder};
1616    use crate::location::{Location, NetworkHint};
1617    use crate::nondet::nondet;
1618
1619    #[tokio::test]
1620    async fn top_level_singleton_replay_cardinality() {
1621        let mut deployment = Deployment::new();
1622
1623        let mut flow = FlowBuilder::new();
1624        let node = flow.process::<()>();
1625        let external = flow.external::<()>();
1626
1627        let (in_port, input) =
1628            node.source_external_bincode::<_, _, TotalOrder, ExactlyOnce>(&external);
1629        let singleton = node.singleton(q!(123));
1630        let tick = node.tick();
1631        let out = input
1632            .batch(&tick, nondet!(/** test */))
1633            .cross_singleton(singleton.clone().snapshot(&tick, nondet!(/** test */)))
1634            .cross_singleton(
1635                singleton
1636                    .snapshot(&tick, nondet!(/** test */))
1637                    .into_stream()
1638                    .count(),
1639            )
1640            .all_ticks()
1641            .send_bincode_external(&external);
1642
1643        let nodes = flow
1644            .with_process(&node, deployment.Localhost())
1645            .with_external(&external, deployment.Localhost())
1646            .deploy(&mut deployment);
1647
1648        deployment.deploy().await.unwrap();
1649
1650        let mut external_in = nodes.connect(in_port).await;
1651        let mut external_out = nodes.connect(out).await;
1652
1653        deployment.start().await.unwrap();
1654
1655        external_in.send(1).await.unwrap();
1656        assert_eq!(external_out.next().await.unwrap(), ((1, 123), 1));
1657
1658        external_in.send(2).await.unwrap();
1659        assert_eq!(external_out.next().await.unwrap(), ((2, 123), 1));
1660    }
1661
1662    #[tokio::test]
1663    async fn tick_singleton_replay_cardinality() {
1664        let mut deployment = Deployment::new();
1665
1666        let mut flow = FlowBuilder::new();
1667        let node = flow.process::<()>();
1668        let external = flow.external::<()>();
1669
1670        let (in_port, input) =
1671            node.source_external_bincode::<_, _, TotalOrder, ExactlyOnce>(&external);
1672        let tick = node.tick();
1673        let singleton = tick.singleton(q!(123));
1674        let out = input
1675            .batch(&tick, nondet!(/** test */))
1676            .cross_singleton(singleton.clone())
1677            .cross_singleton(singleton.into_stream().count())
1678            .all_ticks()
1679            .send_bincode_external(&external);
1680
1681        let nodes = flow
1682            .with_process(&node, deployment.Localhost())
1683            .with_external(&external, deployment.Localhost())
1684            .deploy(&mut deployment);
1685
1686        deployment.deploy().await.unwrap();
1687
1688        let mut external_in = nodes.connect(in_port).await;
1689        let mut external_out = nodes.connect(out).await;
1690
1691        deployment.start().await.unwrap();
1692
1693        external_in.send(1).await.unwrap();
1694        assert_eq!(external_out.next().await.unwrap(), ((1, 123), 1));
1695
1696        external_in.send(2).await.unwrap();
1697        assert_eq!(external_out.next().await.unwrap(), ((2, 123), 1));
1698    }
1699
1700    #[tokio::test]
1701    async fn external_bytes() {
1702        let mut deployment = Deployment::new();
1703
1704        let mut flow = FlowBuilder::new();
1705        let first_node = flow.process::<()>();
1706        let external = flow.external::<()>();
1707
1708        let (in_port, input) = first_node.source_external_bytes(&external);
1709        let out = input.send_bincode_external(&external);
1710
1711        let nodes = flow
1712            .with_process(&first_node, deployment.Localhost())
1713            .with_external(&external, deployment.Localhost())
1714            .deploy(&mut deployment);
1715
1716        deployment.deploy().await.unwrap();
1717
1718        let mut external_in = nodes.connect(in_port).await.1;
1719        let mut external_out = nodes.connect(out).await;
1720
1721        deployment.start().await.unwrap();
1722
1723        external_in.send(vec![1, 2, 3].into()).await.unwrap();
1724
1725        assert_eq!(external_out.next().await.unwrap(), vec![1, 2, 3]);
1726    }
1727
1728    #[tokio::test]
1729    async fn multi_external_source() {
1730        let mut deployment = Deployment::new();
1731
1732        let mut flow = FlowBuilder::new();
1733        let first_node = flow.process::<()>();
1734        let external = flow.external::<()>();
1735
1736        let (in_port, input, _membership, complete_sink) =
1737            first_node.bidi_external_many_bincode(&external);
1738        let out = input.entries().send_bincode_external(&external);
1739        complete_sink.complete(
1740            first_node
1741                .source_iter::<(u64, ()), _>(q!([]))
1742                .into_keyed()
1743                .weaken_ordering(),
1744        );
1745
1746        let nodes = flow
1747            .with_process(&first_node, deployment.Localhost())
1748            .with_external(&external, deployment.Localhost())
1749            .deploy(&mut deployment);
1750
1751        deployment.deploy().await.unwrap();
1752
1753        let (_, mut external_in_1) = nodes.connect_bincode(in_port.clone()).await;
1754        let (_, mut external_in_2) = nodes.connect_bincode(in_port).await;
1755        let external_out = nodes.connect(out).await;
1756
1757        deployment.start().await.unwrap();
1758
1759        external_in_1.send(123).await.unwrap();
1760        external_in_2.send(456).await.unwrap();
1761
1762        assert_eq!(
1763            external_out.take(2).collect::<HashSet<_>>().await,
1764            vec![(0, 123), (1, 456)].into_iter().collect()
1765        );
1766    }
1767
1768    #[tokio::test]
1769    async fn second_connection_only_multi_source() {
1770        let mut deployment = Deployment::new();
1771
1772        let mut flow = FlowBuilder::new();
1773        let first_node = flow.process::<()>();
1774        let external = flow.external::<()>();
1775
1776        let (in_port, input, _membership, complete_sink) =
1777            first_node.bidi_external_many_bincode(&external);
1778        let out = input.entries().send_bincode_external(&external);
1779        complete_sink.complete(
1780            first_node
1781                .source_iter::<(u64, ()), _>(q!([]))
1782                .into_keyed()
1783                .weaken_ordering(),
1784        );
1785
1786        let nodes = flow
1787            .with_process(&first_node, deployment.Localhost())
1788            .with_external(&external, deployment.Localhost())
1789            .deploy(&mut deployment);
1790
1791        deployment.deploy().await.unwrap();
1792
1793        // intentionally skipped to test stream waking logic
1794        let (_, mut _external_in_1) = nodes.connect_bincode(in_port.clone()).await;
1795        let (_, mut external_in_2) = nodes.connect_bincode(in_port).await;
1796        let mut external_out = nodes.connect(out).await;
1797
1798        deployment.start().await.unwrap();
1799
1800        external_in_2.send(456).await.unwrap();
1801
1802        assert_eq!(external_out.next().await.unwrap(), (1, 456));
1803    }
1804
1805    #[tokio::test]
1806    async fn multi_external_bytes() {
1807        let mut deployment = Deployment::new();
1808
1809        let mut flow = FlowBuilder::new();
1810        let first_node = flow.process::<()>();
1811        let external = flow.external::<()>();
1812
1813        let (in_port, input, _membership, complete_sink) = first_node
1814            .bidi_external_many_bytes::<_, bytes::Bytes, LengthDelimitedCodec>(
1815                &external,
1816                NetworkHint::Auto,
1817            );
1818        let out = input.entries().send_bincode_external(&external);
1819        complete_sink.complete(
1820            first_node
1821                .source_iter(q!([]))
1822                .into_keyed()
1823                .weaken_ordering(),
1824        );
1825
1826        let nodes = flow
1827            .with_process(&first_node, deployment.Localhost())
1828            .with_external(&external, deployment.Localhost())
1829            .deploy(&mut deployment);
1830
1831        deployment.deploy().await.unwrap();
1832
1833        let mut external_in_1 = nodes.connect(in_port.clone()).await.1;
1834        let mut external_in_2 = nodes.connect(in_port).await.1;
1835        let external_out = nodes.connect(out).await;
1836
1837        deployment.start().await.unwrap();
1838
1839        external_in_1.send(vec![1, 2, 3].into()).await.unwrap();
1840        external_in_2.send(vec![4, 5].into()).await.unwrap();
1841
1842        assert_eq!(
1843            external_out.take(2).collect::<HashSet<_>>().await,
1844            vec![
1845                (0, (&[1u8, 2, 3] as &[u8]).into()),
1846                (1, (&[4u8, 5] as &[u8]).into())
1847            ]
1848            .into_iter()
1849            .collect()
1850        );
1851    }
1852
1853    #[tokio::test]
1854    async fn single_client_external_bytes() {
1855        let mut deployment = Deployment::new();
1856        let mut flow = FlowBuilder::new();
1857        let first_node = flow.process::<()>();
1858        let external = flow.external::<()>();
1859        let (port, input, complete_sink) = first_node
1860            .bind_single_client::<_, bytes::Bytes, LengthDelimitedCodec>(
1861                &external,
1862                NetworkHint::Auto,
1863            );
1864        complete_sink.complete(input.map(q!(|data| {
1865            let mut resp: Vec<u8> = data.into();
1866            resp.push(42);
1867            resp.into() // : Bytes
1868        })));
1869
1870        let nodes = flow
1871            .with_process(&first_node, deployment.Localhost())
1872            .with_external(&external, deployment.Localhost())
1873            .deploy(&mut deployment);
1874
1875        deployment.deploy().await.unwrap();
1876        deployment.start().await.unwrap();
1877
1878        let (mut external_out, mut external_in) = nodes.connect(port).await;
1879
1880        external_in.send(vec![1, 2, 3].into()).await.unwrap();
1881        assert_eq!(
1882            external_out.next().await.unwrap().unwrap(),
1883            vec![1, 2, 3, 42]
1884        );
1885    }
1886
1887    #[tokio::test]
1888    async fn echo_external_bytes() {
1889        let mut deployment = Deployment::new();
1890
1891        let mut flow = FlowBuilder::new();
1892        let first_node = flow.process::<()>();
1893        let external = flow.external::<()>();
1894
1895        let (port, input, _membership, complete_sink) = first_node
1896            .bidi_external_many_bytes::<_, bytes::Bytes, LengthDelimitedCodec>(
1897                &external,
1898                NetworkHint::Auto,
1899            );
1900        complete_sink
1901            .complete(input.map(q!(|bytes| { bytes.into_iter().map(|x| x + 1).collect() })));
1902
1903        let nodes = flow
1904            .with_process(&first_node, deployment.Localhost())
1905            .with_external(&external, deployment.Localhost())
1906            .deploy(&mut deployment);
1907
1908        deployment.deploy().await.unwrap();
1909
1910        let (mut external_out_1, mut external_in_1) = nodes.connect(port.clone()).await;
1911        let (mut external_out_2, mut external_in_2) = nodes.connect(port).await;
1912
1913        deployment.start().await.unwrap();
1914
1915        external_in_1.send(vec![1, 2, 3].into()).await.unwrap();
1916        external_in_2.send(vec![4, 5].into()).await.unwrap();
1917
1918        assert_eq!(external_out_1.next().await.unwrap().unwrap(), vec![2, 3, 4]);
1919        assert_eq!(external_out_2.next().await.unwrap().unwrap(), vec![5, 6]);
1920    }
1921
1922    #[tokio::test]
1923    async fn echo_external_bincode() {
1924        let mut deployment = Deployment::new();
1925
1926        let mut flow = FlowBuilder::new();
1927        let first_node = flow.process::<()>();
1928        let external = flow.external::<()>();
1929
1930        let (port, input, _membership, complete_sink) =
1931            first_node.bidi_external_many_bincode(&external);
1932        complete_sink.complete(input.map(q!(|text: String| { text.to_uppercase() })));
1933
1934        let nodes = flow
1935            .with_process(&first_node, deployment.Localhost())
1936            .with_external(&external, deployment.Localhost())
1937            .deploy(&mut deployment);
1938
1939        deployment.deploy().await.unwrap();
1940
1941        let (mut external_out_1, mut external_in_1) = nodes.connect_bincode(port.clone()).await;
1942        let (mut external_out_2, mut external_in_2) = nodes.connect_bincode(port).await;
1943
1944        deployment.start().await.unwrap();
1945
1946        external_in_1.send("hi".to_owned()).await.unwrap();
1947        external_in_2.send("hello".to_owned()).await.unwrap();
1948
1949        assert_eq!(external_out_1.next().await.unwrap(), "HI");
1950        assert_eq!(external_out_2.next().await.unwrap(), "HELLO");
1951    }
1952
1953    #[tokio::test]
1954    async fn closure_location_name() {
1955        let mut deployment = Deployment::new();
1956        let mut flow = FlowBuilder::new();
1957
1958        enum ClosureProcess {}
1959
1960        let node = flow.process::<ClosureProcess>();
1961        let external = flow.external::<()>();
1962
1963        let (in_port, input) =
1964            node.source_external_bincode::<_, i32, TotalOrder, ExactlyOnce>(&external);
1965        let out = input.send_bincode_external(&external);
1966
1967        let nodes = flow
1968            .with_process(&node, deployment.Localhost())
1969            .with_external(&external, deployment.Localhost())
1970            .deploy(&mut deployment);
1971
1972        deployment.deploy().await.unwrap();
1973
1974        let mut external_in = nodes.connect(in_port).await;
1975        let mut external_out = nodes.connect(out).await;
1976
1977        deployment.start().await.unwrap();
1978
1979        external_in.send(42).await.unwrap();
1980        assert_eq!(external_out.next().await.unwrap(), 42);
1981    }
1982}