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