Skip to main content

hydro_lang/live_collections/keyed_stream/
networking.rs

1//! Networking APIs for [`KeyedStream`].
2
3use std::hash::Hash;
4
5use serde::Serialize;
6use serde::de::DeserializeOwned;
7use stageleft::{q, quote_type};
8
9use super::KeyedStream;
10use crate::compile::ir::{DebugInstantiate, HydroNode, NetworkRecv, NetworkSend};
11use crate::live_collections::boundedness::{Boundedness, Unbounded};
12use crate::live_collections::stream::{MinOrder, MinRetries, Ordering, Retries, Stream};
13use crate::location::cluster::Consistency;
14#[cfg(stageleft_runtime)]
15use crate::location::dynamic::DynLocation;
16use crate::location::{Cluster, MemberId, Process};
17use crate::networking::{NetworkFor, TCP};
18
19impl<'a, T, L, L2, Id2: Clone + Eq + Hash + 'a, B: Boundedness, O: Ordering, R: Retries>
20    KeyedStream<MemberId<L2, Id2>, T, Process<'a, L>, B, O, R>
21{
22    #[deprecated = "use KeyedStream::demux(..., TCP.fail_stop().bincode()) instead"]
23    /// Sends each group of this stream to a specific member of a cluster, with the [`MemberId`] key
24    /// identifying the recipient for each group and using [`bincode`] to serialize/deserialize messages.
25    ///
26    /// Each key must be a `MemberId<L2>` and each value must be a `T` where the key specifies
27    /// which cluster member should receive the data. Unlike [`Stream::broadcast_bincode`], this
28    /// API allows precise targeting of specific cluster members rather than broadcasting to
29    /// all members.
30    ///
31    /// # Example
32    /// ```rust
33    /// # #[cfg(feature = "deploy")] {
34    /// # use hydro_lang::prelude::*;
35    /// # use futures::StreamExt;
36    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
37    /// let p1 = flow.process::<()>();
38    /// let workers: Cluster<()> = flow.cluster();
39    /// let numbers: Stream<_, Process<_>, _> = p1.source_iter(q!(vec![0, 1, 2, 3]));
40    /// let on_worker: Stream<_, Cluster<_>, _> = numbers
41    ///     .map(q!(|x| (hydro_lang::location::MemberId::from_raw_id(x), x)))
42    ///     .into_keyed()
43    ///     .demux_bincode(&workers);
44    /// # on_worker.send_bincode(&p2).entries()
45    /// // if there are 4 members in the cluster, each receives one element
46    /// // - MemberId::<()>(0): [0]
47    /// // - MemberId::<()>(1): [1]
48    /// // - MemberId::<()>(2): [2]
49    /// // - MemberId::<()>(3): [3]
50    /// # }, |mut stream| async move {
51    /// # let mut results = Vec::new();
52    /// # for w in 0..4 {
53    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
54    /// # }
55    /// # results.sort();
56    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 0)", "(MemberId::<()>(1), 1)", "(MemberId::<()>(2), 2)", "(MemberId::<()>(3), 3)"]);
57    /// # }));
58    /// # }
59    /// ```
60    pub fn demux_bincode(
61        self,
62        other: &Cluster<'a, L2, Id2>,
63    ) -> Stream<T, Cluster<'a, L2, Id2>, Unbounded, O, R>
64    where
65        T: Serialize + DeserializeOwned,
66    {
67        self.demux(other, TCP.fail_stop().bincode())
68    }
69
70    /// Sends each group of this stream to a specific member of a cluster, with the [`MemberId`] key
71    /// identifying the recipient for each group and using the configuration in `via` to set up the
72    /// message transport.
73    ///
74    /// Each key must be a `MemberId<L2>` and each value must be a `T` where the key specifies
75    /// which cluster member should receive the data. Unlike [`Stream::broadcast`], this
76    /// API allows precise targeting of specific cluster members rather than broadcasting to
77    /// all members.
78    ///
79    /// # Example
80    /// ```rust
81    /// # #[cfg(feature = "deploy")] {
82    /// # use hydro_lang::prelude::*;
83    /// # use futures::StreamExt;
84    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
85    /// let p1 = flow.process::<()>();
86    /// let workers: Cluster<()> = flow.cluster();
87    /// let numbers: Stream<_, Process<_>, _> = p1.source_iter(q!(vec![0, 1, 2, 3]));
88    /// let on_worker: Stream<_, Cluster<_>, _> = numbers
89    ///     .map(q!(|x| (hydro_lang::location::MemberId::from_raw_id(x), x)))
90    ///     .into_keyed()
91    ///     .demux(&workers, TCP.fail_stop().bincode());
92    /// # on_worker.send(&p2, TCP.fail_stop().bincode()).entries()
93    /// // if there are 4 members in the cluster, each receives one element
94    /// // - MemberId::<()>(0): [0]
95    /// // - MemberId::<()>(1): [1]
96    /// // - MemberId::<()>(2): [2]
97    /// // - MemberId::<()>(3): [3]
98    /// # }, |mut stream| async move {
99    /// # let mut results = Vec::new();
100    /// # for w in 0..4 {
101    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
102    /// # }
103    /// # results.sort();
104    /// # assert_eq!(results, vec!["(MemberId::<()>(0), 0)", "(MemberId::<()>(1), 1)", "(MemberId::<()>(2), 2)", "(MemberId::<()>(3), 3)"]);
105    /// # }));
106    /// # }
107    /// ```
108    pub fn demux<N: NetworkFor<T>>(
109        self,
110        to: &Cluster<'a, L2, Id2>,
111        via: N,
112    ) -> Stream<
113        T,
114        // NoConsistency because there each replica member may receive different streams
115        Cluster<'a, L2, Id2>,
116        Unbounded,
117        <O as MinOrder<N::OrderingGuarantee>>::Min,
118        <R as MinRetries<N::RetriesGuarantee>>::Min,
119    >
120    where
121        O: MinOrder<N::OrderingGuarantee>,
122        R: MinRetries<N::RetriesGuarantee>,
123    {
124        let name = via.name();
125        assert!(
126            !to.multiversioned() || name.is_some(),
127            "Cannot send to a multiversioned location without a channel name. Please provide a name for the network."
128        );
129
130        let (serialize, deserialize) = if N::is_embedded() {
131            (
132                NetworkSend::Embedded {
133                    tag: Some(quote_type::<L2>().into()),
134                    element_type: quote_type::<T>().into(),
135                },
136                NetworkRecv::Embedded {
137                    tag: None,
138                    element_type: quote_type::<T>().into(),
139                },
140            )
141        } else {
142            (
143                NetworkSend::Custom {
144                    serialize_fn: Some(N::serialize_thunk(true).into()),
145                },
146                NetworkRecv::Custom {
147                    deserialize_fn: Some(N::deserialize_thunk(None).into()),
148                },
149            )
150        };
151
152        Stream::new(
153            to.clone(),
154            HydroNode::Network {
155                name: name.map(ToOwned::to_owned),
156                networking_info: N::networking_info(),
157                serialize,
158                deserialize,
159                instantiate_fn: DebugInstantiate::Building,
160                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
161                metadata: to.new_node_metadata(Stream::<
162                    T,
163                    Cluster<'a, L2, Id2>,
164                    Unbounded,
165                    <O as MinOrder<N::OrderingGuarantee>>::Min,
166                    <R as MinRetries<N::RetriesGuarantee>>::Min,
167                >::collection_kind()),
168            },
169        )
170    }
171}
172
173impl<'a, K, T, L, L2, Id2: Clone + Eq + Hash + 'a, B: Boundedness, O: Ordering, R: Retries>
174    KeyedStream<(MemberId<L2, Id2>, K), T, Process<'a, L>, B, O, R>
175{
176    #[deprecated = "use KeyedStream::demux(..., TCP.fail_stop().bincode()) instead"]
177    /// Sends each group of this stream to a specific member of a cluster. The input stream has a
178    /// compound key where the first element is the recipient's [`MemberId`] and the second element
179    /// is a key that will be sent along with the value, using [`bincode`] to serialize/deserialize
180    /// messages.
181    ///
182    /// # Example
183    /// ```rust
184    /// # #[cfg(feature = "deploy")] {
185    /// # use hydro_lang::prelude::*;
186    /// # use futures::StreamExt;
187    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
188    /// let p1 = flow.process::<()>();
189    /// let workers: Cluster<()> = flow.cluster();
190    /// let to_send: KeyedStream<_, _, Process<_>, _> = p1
191    ///     .source_iter(q!(vec![0, 1, 2, 3]))
192    ///     .map(q!(|x| ((hydro_lang::location::MemberId::from_raw_id(x), x), x + 123)))
193    ///     .into_keyed();
194    /// let on_worker: KeyedStream<_, _, Cluster<_>, _> = to_send.demux_bincode(&workers);
195    /// # on_worker.entries().send_bincode(&p2).entries()
196    /// // if there are 4 members in the cluster, each receives one element
197    /// // - MemberId::<()>(0): { 0: [123] }
198    /// // - MemberId::<()>(1): { 1: [124] }
199    /// // - ...
200    /// # }, |mut stream| async move {
201    /// # let mut results = Vec::new();
202    /// # for w in 0..4 {
203    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
204    /// # }
205    /// # results.sort();
206    /// # assert_eq!(results, vec!["(MemberId::<()>(0), (0, 123))", "(MemberId::<()>(1), (1, 124))", "(MemberId::<()>(2), (2, 125))", "(MemberId::<()>(3), (3, 126))"]);
207    /// # }));
208    /// # }
209    /// ```
210    pub fn demux_bincode(
211        self,
212        other: &Cluster<'a, L2, Id2>,
213    ) -> KeyedStream<K, T, Cluster<'a, L2, Id2>, Unbounded, O, R>
214    where
215        K: Serialize + DeserializeOwned,
216        T: Serialize + DeserializeOwned,
217    {
218        self.demux(other, TCP.fail_stop().bincode())
219    }
220
221    /// Sends each group of this stream to a specific member of a cluster. The input stream has a
222    /// compound key where the first element is the recipient's [`MemberId`] and the second element
223    /// is a key that will be sent along with the value, using the configuration in `via` to set up
224    /// the message transport.
225    ///
226    /// # Example
227    /// ```rust
228    /// # #[cfg(feature = "deploy")] {
229    /// # use hydro_lang::prelude::*;
230    /// # use futures::StreamExt;
231    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
232    /// let p1 = flow.process::<()>();
233    /// let workers: Cluster<()> = flow.cluster();
234    /// let to_send: KeyedStream<_, _, Process<_>, _> = p1
235    ///     .source_iter(q!(vec![0, 1, 2, 3]))
236    ///     .map(q!(|x| ((hydro_lang::location::MemberId::from_raw_id(x), x), x + 123)))
237    ///     .into_keyed();
238    /// let on_worker: KeyedStream<_, _, Cluster<_>, _> = to_send.demux(&workers, TCP.fail_stop().bincode());
239    /// # on_worker.entries().send(&p2, TCP.fail_stop().bincode()).entries()
240    /// // if there are 4 members in the cluster, each receives one element
241    /// // - MemberId::<()>(0): { 0: [123] }
242    /// // - MemberId::<()>(1): { 1: [124] }
243    /// // - ...
244    /// # }, |mut stream| async move {
245    /// # let mut results = Vec::new();
246    /// # for w in 0..4 {
247    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
248    /// # }
249    /// # results.sort();
250    /// # assert_eq!(results, vec!["(MemberId::<()>(0), (0, 123))", "(MemberId::<()>(1), (1, 124))", "(MemberId::<()>(2), (2, 125))", "(MemberId::<()>(3), (3, 126))"]);
251    /// # }));
252    /// # }
253    /// ```
254    pub fn demux<N: NetworkFor<(K, T)>>(
255        self,
256        to: &Cluster<'a, L2, Id2>,
257        via: N,
258    ) -> KeyedStream<
259        K,
260        T,
261        Cluster<'a, L2, Id2>,
262        Unbounded,
263        <O as MinOrder<N::OrderingGuarantee>>::Min,
264        <R as MinRetries<N::RetriesGuarantee>>::Min,
265    >
266    where
267        O: MinOrder<N::OrderingGuarantee>,
268        R: MinRetries<N::RetriesGuarantee>,
269    {
270        let name = via.name();
271        assert!(
272            !to.multiversioned() || name.is_some(),
273            "Cannot send to a multiversioned location without a channel name. Please provide a name for the network."
274        );
275
276        let (serialize, deserialize) = if N::is_embedded() {
277            (
278                NetworkSend::Embedded {
279                    tag: Some(quote_type::<L2>().into()),
280                    element_type: quote_type::<(K, T)>().into(),
281                },
282                NetworkRecv::Embedded {
283                    tag: None,
284                    element_type: quote_type::<(K, T)>().into(),
285                },
286            )
287        } else {
288            (
289                NetworkSend::Custom {
290                    serialize_fn: Some(N::serialize_thunk(true).into()),
291                },
292                NetworkRecv::Custom {
293                    deserialize_fn: Some(N::deserialize_thunk(None).into()),
294                },
295            )
296        };
297
298        KeyedStream::new(
299            to.clone(),
300            HydroNode::Network {
301                name: name.map(ToOwned::to_owned),
302                networking_info: N::networking_info(),
303                serialize,
304                deserialize,
305                instantiate_fn: DebugInstantiate::Building,
306                input: Box::new(
307                    self.entries()
308                        .map(q!(|((id, k), v)| (id, (k, v))))
309                        .ir_node
310                        .replace(HydroNode::Placeholder),
311                ),
312                metadata: to.new_node_metadata(KeyedStream::<
313                    K,
314                    T,
315                    Cluster<'a, L2, Id2>,
316                    Unbounded,
317                    <O as MinOrder<N::OrderingGuarantee>>::Min,
318                    <R as MinRetries<N::RetriesGuarantee>>::Min,
319                >::collection_kind()),
320            },
321        )
322    }
323}
324
325impl<
326    'a,
327    T,
328    L,
329    Id: Clone + Eq + Hash + 'a,
330    L2,
331    Id2: Clone + Eq + Hash + 'a,
332    B: Boundedness,
333    C: Consistency,
334    O: Ordering,
335    R: Retries,
336> KeyedStream<MemberId<L2, Id2>, T, Cluster<'a, L, Id, C>, B, O, R>
337{
338    #[deprecated = "use KeyedStream::demux(..., TCP.fail_stop().bincode()) instead"]
339    /// Sends each group of this stream at each source member to a specific member of a destination
340    /// cluster, with the [`MemberId`] key identifying the recipient for each group and using
341    /// [`bincode`] to serialize/deserialize messages.
342    ///
343    /// Each key must be a `MemberId<L2>` and each value must be a `T` where the key specifies
344    /// which cluster member should receive the data. Unlike [`Stream::broadcast_bincode`], this
345    /// API allows precise targeting of specific cluster members rather than broadcasting to all
346    /// members.
347    ///
348    /// Each cluster member sends its local stream elements, and they are collected at each
349    /// destination member as a [`KeyedStream`] where keys identify the source cluster member.
350    ///
351    /// # Example
352    /// ```rust
353    /// # #[cfg(feature = "deploy")] {
354    /// # use hydro_lang::prelude::*;
355    /// # use futures::StreamExt;
356    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
357    /// # type Source = ();
358    /// # type Destination = ();
359    /// let source: Cluster<Source> = flow.cluster();
360    /// let to_send: KeyedStream<_, _, Cluster<_>, _> = source
361    ///     .source_iter(q!(vec![0, 1, 2, 3]))
362    ///     .map(q!(|x| (hydro_lang::location::MemberId::from_raw_id(x), x)))
363    ///     .into_keyed();
364    /// let destination: Cluster<Destination> = flow.cluster();
365    /// let all_received = to_send.demux_bincode(&destination); // KeyedStream<MemberId<Source>, i32, ...>
366    /// # all_received.entries().send_bincode(&p2).entries()
367    /// # }, |mut stream| async move {
368    /// // if there are 4 members in the destination cluster, each receives one message from each source member
369    /// // - Destination(0): { Source(0): [0], Source(1): [0], ... }
370    /// // - Destination(1): { Source(0): [1], Source(1): [1], ... }
371    /// // - ...
372    /// # let mut results = Vec::new();
373    /// # for w in 0..16 {
374    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
375    /// # }
376    /// # results.sort();
377    /// # assert_eq!(results, vec![
378    /// #   "(MemberId::<()>(0), (MemberId::<()>(0), 0))", "(MemberId::<()>(0), (MemberId::<()>(1), 0))", "(MemberId::<()>(0), (MemberId::<()>(2), 0))", "(MemberId::<()>(0), (MemberId::<()>(3), 0))",
379    /// #   "(MemberId::<()>(1), (MemberId::<()>(0), 1))", "(MemberId::<()>(1), (MemberId::<()>(1), 1))", "(MemberId::<()>(1), (MemberId::<()>(2), 1))", "(MemberId::<()>(1), (MemberId::<()>(3), 1))",
380    /// #   "(MemberId::<()>(2), (MemberId::<()>(0), 2))", "(MemberId::<()>(2), (MemberId::<()>(1), 2))", "(MemberId::<()>(2), (MemberId::<()>(2), 2))", "(MemberId::<()>(2), (MemberId::<()>(3), 2))",
381    /// #   "(MemberId::<()>(3), (MemberId::<()>(0), 3))", "(MemberId::<()>(3), (MemberId::<()>(1), 3))", "(MemberId::<()>(3), (MemberId::<()>(2), 3))", "(MemberId::<()>(3), (MemberId::<()>(3), 3))"
382    /// # ]);
383    /// # }));
384    /// # }
385    /// ```
386    pub fn demux_bincode(
387        self,
388        other: &Cluster<'a, L2, Id2>,
389    ) -> KeyedStream<MemberId<L, Id>, T, Cluster<'a, L2, Id2>, Unbounded, O, R>
390    where
391        T: Serialize + DeserializeOwned,
392    {
393        self.demux(other, TCP.fail_stop().bincode())
394    }
395
396    /// Sends each group of this stream at each source member to a specific member of a destination
397    /// cluster, with the [`MemberId`] key identifying the recipient for each group and using the
398    /// configuration in `via` to set up the message transport.
399    ///
400    /// Each key must be a `MemberId<L2>` and each value must be a `T` where the key specifies
401    /// which cluster member should receive the data. Unlike [`Stream::broadcast`], this
402    /// API allows precise targeting of specific cluster members rather than broadcasting to all
403    /// members.
404    ///
405    /// Each cluster member sends its local stream elements, and they are collected at each
406    /// destination member as a [`KeyedStream`] where keys identify the source cluster member.
407    ///
408    /// # Example
409    /// ```rust
410    /// # #[cfg(feature = "deploy")] {
411    /// # use hydro_lang::prelude::*;
412    /// # use futures::StreamExt;
413    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
414    /// # type Source = ();
415    /// # type Destination = ();
416    /// let source: Cluster<Source> = flow.cluster();
417    /// let to_send: KeyedStream<_, _, Cluster<_>, _> = source
418    ///     .source_iter(q!(vec![0, 1, 2, 3]))
419    ///     .map(q!(|x| (hydro_lang::location::MemberId::from_raw_id(x), x)))
420    ///     .into_keyed();
421    /// let destination: Cluster<Destination> = flow.cluster();
422    /// let all_received = to_send.demux(&destination, TCP.fail_stop().bincode()); // KeyedStream<MemberId<Source>, i32, ...>
423    /// # all_received.entries().send(&p2, TCP.fail_stop().bincode()).entries()
424    /// # }, |mut stream| async move {
425    /// // if there are 4 members in the destination cluster, each receives one message from each source member
426    /// // - Destination(0): { Source(0): [0], Source(1): [0], ... }
427    /// // - Destination(1): { Source(0): [1], Source(1): [1], ... }
428    /// // - ...
429    /// # let mut results = Vec::new();
430    /// # for w in 0..16 {
431    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
432    /// # }
433    /// # results.sort();
434    /// # assert_eq!(results, vec![
435    /// #   "(MemberId::<()>(0), (MemberId::<()>(0), 0))", "(MemberId::<()>(0), (MemberId::<()>(1), 0))", "(MemberId::<()>(0), (MemberId::<()>(2), 0))", "(MemberId::<()>(0), (MemberId::<()>(3), 0))",
436    /// #   "(MemberId::<()>(1), (MemberId::<()>(0), 1))", "(MemberId::<()>(1), (MemberId::<()>(1), 1))", "(MemberId::<()>(1), (MemberId::<()>(2), 1))", "(MemberId::<()>(1), (MemberId::<()>(3), 1))",
437    /// #   "(MemberId::<()>(2), (MemberId::<()>(0), 2))", "(MemberId::<()>(2), (MemberId::<()>(1), 2))", "(MemberId::<()>(2), (MemberId::<()>(2), 2))", "(MemberId::<()>(2), (MemberId::<()>(3), 2))",
438    /// #   "(MemberId::<()>(3), (MemberId::<()>(0), 3))", "(MemberId::<()>(3), (MemberId::<()>(1), 3))", "(MemberId::<()>(3), (MemberId::<()>(2), 3))", "(MemberId::<()>(3), (MemberId::<()>(3), 3))"
439    /// # ]);
440    /// # }));
441    /// # }
442    /// ```
443    pub fn demux<N: NetworkFor<T>>(
444        self,
445        to: &Cluster<'a, L2, Id2>,
446        via: N,
447    ) -> KeyedStream<
448        MemberId<L, Id>,
449        T,
450        Cluster<'a, L2, Id2>,
451        Unbounded,
452        <O as MinOrder<N::OrderingGuarantee>>::Min,
453        <R as MinRetries<N::RetriesGuarantee>>::Min,
454    >
455    where
456        O: MinOrder<N::OrderingGuarantee>,
457        R: MinRetries<N::RetriesGuarantee>,
458    {
459        let name = via.name();
460        assert!(
461            !to.multiversioned() || name.is_some(),
462            "Cannot send to a multiversioned location without a channel name. Please provide a name for the network."
463        );
464
465        let (serialize, deserialize) = if N::is_embedded() {
466            (
467                NetworkSend::Embedded {
468                    tag: Some(quote_type::<L2>().into()),
469                    element_type: quote_type::<T>().into(),
470                },
471                NetworkRecv::Embedded {
472                    tag: Some(quote_type::<L>().into()),
473                    element_type: quote_type::<T>().into(),
474                },
475            )
476        } else {
477            (
478                NetworkSend::Custom {
479                    serialize_fn: Some(N::serialize_thunk(true).into()),
480                },
481                NetworkRecv::Custom {
482                    deserialize_fn: Some(N::deserialize_thunk(Some(&quote_type::<L>())).into()),
483                },
484            )
485        };
486
487        KeyedStream::new(
488            to.clone(),
489            HydroNode::Network {
490                name: name.map(ToOwned::to_owned),
491                networking_info: N::networking_info(),
492                serialize,
493                deserialize,
494                instantiate_fn: DebugInstantiate::Building,
495                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
496                metadata: to.new_node_metadata(KeyedStream::<
497                    MemberId<L, Id>,
498                    T,
499                    Cluster<'a, L2, Id2>,
500                    Unbounded,
501                    <O as MinOrder<N::OrderingGuarantee>>::Min,
502                    <R as MinRetries<N::RetriesGuarantee>>::Min,
503                >::collection_kind()),
504            },
505        )
506    }
507}
508
509impl<
510    'a,
511    K,
512    V,
513    L,
514    Id: Clone + Eq + Hash + 'a,
515    B: Boundedness,
516    C: Consistency,
517    O: Ordering,
518    R: Retries,
519> KeyedStream<K, V, Cluster<'a, L, Id, C>, B, O, R>
520{
521    #[deprecated = "use KeyedStream::send(..., TCP.fail_stop().bincode()) instead"]
522    /// "Moves" elements of this keyed stream from a cluster to a process by sending them over the
523    /// network, using [`bincode`] to serialize/deserialize messages. The resulting [`KeyedStream`]
524    /// has a compound key where the first element is the sender's [`MemberId`] and the second
525    /// element is the original key.
526    ///
527    /// # Example
528    /// ```rust
529    /// # #[cfg(feature = "deploy")] {
530    /// # use hydro_lang::prelude::*;
531    /// # use futures::StreamExt;
532    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
533    /// # type Source = ();
534    /// # type Destination = ();
535    /// let source: Cluster<Source> = flow.cluster();
536    /// let to_send: KeyedStream<_, _, Cluster<_>, _> = source
537    ///     .source_iter(q!(vec![0, 1, 2, 3]))
538    ///     .map(q!(|x| (x, x + 123)))
539    ///     .into_keyed();
540    /// let destination_process = flow.process::<Destination>();
541    /// let all_received = to_send.send_bincode(&destination_process); // KeyedStream<(MemberId<Source>, i32), i32, ...>
542    /// # all_received.entries().send_bincode(&p2)
543    /// # }, |mut stream| async move {
544    /// // if there are 4 members in the source cluster, the destination process receives four messages from each source member
545    /// // {
546    /// //     (MemberId<Source>(0), 0): [123], (MemberId<Source>(1), 0): [123], ...,
547    /// //     (MemberId<Source>(0), 1): [124], (MemberId<Source>(1), 1): [124], ...,
548    /// //     ...
549    /// // }
550    /// # let mut results = Vec::new();
551    /// # for w in 0..16 {
552    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
553    /// # }
554    /// # results.sort();
555    /// # assert_eq!(results, vec![
556    /// #   "((MemberId::<()>(0), 0), 123)",
557    /// #   "((MemberId::<()>(0), 1), 124)",
558    /// #   "((MemberId::<()>(0), 2), 125)",
559    /// #   "((MemberId::<()>(0), 3), 126)",
560    /// #   "((MemberId::<()>(1), 0), 123)",
561    /// #   "((MemberId::<()>(1), 1), 124)",
562    /// #   "((MemberId::<()>(1), 2), 125)",
563    /// #   "((MemberId::<()>(1), 3), 126)",
564    /// #   "((MemberId::<()>(2), 0), 123)",
565    /// #   "((MemberId::<()>(2), 1), 124)",
566    /// #   "((MemberId::<()>(2), 2), 125)",
567    /// #   "((MemberId::<()>(2), 3), 126)",
568    /// #   "((MemberId::<()>(3), 0), 123)",
569    /// #   "((MemberId::<()>(3), 1), 124)",
570    /// #   "((MemberId::<()>(3), 2), 125)",
571    /// #   "((MemberId::<()>(3), 3), 126)",
572    /// # ]);
573    /// # }));
574    /// # }
575    /// ```
576    pub fn send_bincode<L2>(
577        self,
578        other: &Process<'a, L2>,
579    ) -> KeyedStream<(MemberId<L, Id>, K), V, Process<'a, L2>, Unbounded, O, R>
580    where
581        K: Serialize + DeserializeOwned,
582        V: Serialize + DeserializeOwned,
583    {
584        self.send(other, TCP.fail_stop().bincode())
585    }
586
587    /// "Moves" elements of this keyed stream from a cluster to a process by sending them over the
588    /// network, using the configuration in `via` to set up the message transport. The resulting
589    /// [`KeyedStream`] has a compound key where the first element is the sender's [`MemberId`] and
590    /// the second element is the original key.
591    ///
592    /// # Example
593    /// ```rust
594    /// # #[cfg(feature = "deploy")] {
595    /// # use hydro_lang::prelude::*;
596    /// # use futures::StreamExt;
597    /// # tokio_test::block_on(hydro_lang::test_util::multi_location_test(|flow, p2| {
598    /// # type Source = ();
599    /// # type Destination = ();
600    /// let source: Cluster<Source> = flow.cluster();
601    /// let to_send: KeyedStream<_, _, Cluster<_>, _> = source
602    ///     .source_iter(q!(vec![0, 1, 2, 3]))
603    ///     .map(q!(|x| (x, x + 123)))
604    ///     .into_keyed();
605    /// let destination_process = flow.process::<Destination>();
606    /// let all_received = to_send.send(&destination_process, TCP.fail_stop().bincode()); // KeyedStream<(MemberId<Source>, i32), i32, ...>
607    /// # all_received.entries().send(&p2, TCP.fail_stop().bincode())
608    /// # }, |mut stream| async move {
609    /// // if there are 4 members in the source cluster, the destination process receives four messages from each source member
610    /// // {
611    /// //     (MemberId<Source>(0), 0): [123], (MemberId<Source>(1), 0): [123], ...,
612    /// //     (MemberId<Source>(0), 1): [124], (MemberId<Source>(1), 1): [124], ...,
613    /// //     ...
614    /// // }
615    /// # let mut results = Vec::new();
616    /// # for w in 0..16 {
617    /// #     results.push(format!("{:?}", stream.next().await.unwrap()));
618    /// # }
619    /// # results.sort();
620    /// # assert_eq!(results, vec![
621    /// #   "((MemberId::<()>(0), 0), 123)",
622    /// #   "((MemberId::<()>(0), 1), 124)",
623    /// #   "((MemberId::<()>(0), 2), 125)",
624    /// #   "((MemberId::<()>(0), 3), 126)",
625    /// #   "((MemberId::<()>(1), 0), 123)",
626    /// #   "((MemberId::<()>(1), 1), 124)",
627    /// #   "((MemberId::<()>(1), 2), 125)",
628    /// #   "((MemberId::<()>(1), 3), 126)",
629    /// #   "((MemberId::<()>(2), 0), 123)",
630    /// #   "((MemberId::<()>(2), 1), 124)",
631    /// #   "((MemberId::<()>(2), 2), 125)",
632    /// #   "((MemberId::<()>(2), 3), 126)",
633    /// #   "((MemberId::<()>(3), 0), 123)",
634    /// #   "((MemberId::<()>(3), 1), 124)",
635    /// #   "((MemberId::<()>(3), 2), 125)",
636    /// #   "((MemberId::<()>(3), 3), 126)",
637    /// # ]);
638    /// # }));
639    /// # }
640    /// ```
641    pub fn send<L2, N: NetworkFor<(K, V)>>(
642        self,
643        to: &Process<'a, L2>,
644        via: N,
645    ) -> KeyedStream<
646        (MemberId<L, Id>, K),
647        V,
648        Process<'a, L2>,
649        Unbounded,
650        <O as MinOrder<N::OrderingGuarantee>>::Min,
651        <R as MinRetries<N::RetriesGuarantee>>::Min,
652    >
653    where
654        O: MinOrder<N::OrderingGuarantee>,
655        R: MinRetries<N::RetriesGuarantee>,
656    {
657        let name = via.name();
658        assert!(
659            !to.multiversioned() || name.is_some(),
660            "Cannot send to a multiversioned location without a channel name. Please provide a name for the network."
661        );
662
663        let (serialize, deserialize) = if N::is_embedded() {
664            (
665                NetworkSend::Embedded {
666                    tag: None,
667                    element_type: quote_type::<(K, V)>().into(),
668                },
669                NetworkRecv::Embedded {
670                    tag: Some(quote_type::<L>().into()),
671                    element_type: quote_type::<(K, V)>().into(),
672                },
673            )
674        } else {
675            (
676                NetworkSend::Custom {
677                    serialize_fn: Some(N::serialize_thunk(false).into()),
678                },
679                NetworkRecv::Custom {
680                    deserialize_fn: Some(N::deserialize_thunk(Some(&quote_type::<L>())).into()),
681                },
682            )
683        };
684
685        #[expect(clippy::type_complexity, reason = "stream markers")]
686        let raw_stream: Stream<
687            (MemberId<L, Id>, (K, V)),
688            Process<'a, L2>,
689            Unbounded,
690            <O as MinOrder<N::OrderingGuarantee>>::Min,
691            <R as MinRetries<N::RetriesGuarantee>>::Min,
692        > = Stream::new(
693            to.clone(),
694            HydroNode::Network {
695                name: name.map(ToOwned::to_owned),
696                networking_info: N::networking_info(),
697                serialize,
698                deserialize,
699                instantiate_fn: DebugInstantiate::Building,
700                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
701                metadata: to.new_node_metadata(Stream::<
702                    (MemberId<L, Id>, (K, V)),
703                    Process<'a, L2>,
704                    Unbounded,
705                    <O as MinOrder<N::OrderingGuarantee>>::Min,
706                    <R as MinRetries<N::RetriesGuarantee>>::Min,
707                >::collection_kind()),
708            },
709        );
710
711        raw_stream
712            .map(q!(|(sender, (k, v))| ((sender, k), v)))
713            .into_keyed()
714    }
715}