1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use hydro_lang::*;
use hydro_std::compartmentalize::{DecoupleClusterStream, DecoupleProcessStream, PartitionStream};
use stageleft::IntoQuotedMut;

pub fn partition<'a, F: Fn((ClusterId<()>, String)) -> (ClusterId<()>, String) + 'a>(
    cluster1: Cluster<'a, ()>,
    cluster2: Cluster<'a, ()>,
    dist_policy: impl IntoQuotedMut<'a, F, Cluster<'a, ()>>,
) -> (Cluster<'a, ()>, Cluster<'a, ()>) {
    cluster1
        .source_iter(q!(vec!(CLUSTER_SELF_ID)))
        .map(q!(move |id| (
            ClusterId::<()>::from_raw(id.raw_id),
            format!("Hello from {}", id.raw_id)
        )))
        .send_partitioned(&cluster2, dist_policy)
        .for_each(q!(move |message| println!(
            "My self id is {}, my message is {:?}",
            CLUSTER_SELF_ID.raw_id, message
        )));
    (cluster1, cluster2)
}

pub fn decouple_cluster<'a>(flow: &FlowBuilder<'a>) -> (Cluster<'a, ()>, Cluster<'a, ()>) {
    let cluster1 = flow.cluster();
    let cluster2 = flow.cluster();
    cluster1
        .source_iter(q!(vec!(CLUSTER_SELF_ID)))
        // .for_each(q!(|message| println!("hey, {}", message)))
        .inspect(q!(|message| println!("Cluster1 node sending message: {}", message)))
        .decouple_cluster(&cluster2)
        .for_each(q!(move |message| println!(
            "My self id is {}, my message is {}",
            CLUSTER_SELF_ID, message
        )));
    (cluster1, cluster2)
}

pub fn decouple_process<'a>(flow: &FlowBuilder<'a>) -> (Process<'a, ()>, Process<'a, ()>) {
    let process1 = flow.process();
    let process2 = flow.process();
    process1
        .source_iter(q!(0..3))
        .decouple_process(&process2)
        .for_each(q!(|message| println!("I received message is {}", message)));
    (process1, process2)
}

pub fn simple_cluster<'a>(flow: &FlowBuilder<'a>) -> (Process<'a, ()>, Cluster<'a, ()>) {
    let process = flow.process();
    let cluster = flow.cluster();

    let numbers = process.source_iter(q!(0..5));
    let ids = process.source_iter(cluster.members()).map(q!(|&id| id));

    ids.cross_product(numbers)
        .map(q!(|(id, n)| (id, (id, n))))
        .send_bincode(&cluster)
        .inspect(q!(move |n| println!(
            "cluster received: {:?} (self cluster id: {})",
            n, CLUSTER_SELF_ID
        )))
        .send_bincode(&process)
        .for_each(q!(|(id, d)| println!("node received: ({}, {:?})", id, d)));

    (process, cluster)
}

#[cfg(test)]
mod tests {
    use hydro_deploy::Deployment;
    use hydro_lang::deploy::DeployCrateWrapper;
    use hydro_lang::ClusterId;
    use stageleft::q;

    #[tokio::test]
    async fn simple_cluster() {
        let mut deployment = Deployment::new();

        let builder = hydro_lang::FlowBuilder::new();
        let (node, cluster) = super::simple_cluster(&builder);
        let built = builder.with_default_optimize();

        insta::assert_debug_snapshot!(built.ir());

        let nodes = built
            .with_process(&node, deployment.Localhost())
            .with_cluster(&cluster, (0..2).map(|_| deployment.Localhost()))
            .deploy(&mut deployment);

        deployment.deploy().await.unwrap();

        let mut node_stdout = nodes.get_process(&node).stdout().await;
        let cluster_stdouts = futures::future::join_all(
            nodes
                .get_cluster(&cluster)
                .members()
                .iter()
                .map(|node| node.stdout()),
        )
        .await;

        deployment.start().await.unwrap();

        for (i, mut stdout) in cluster_stdouts.into_iter().enumerate() {
            for j in 0..5 {
                assert_eq!(
                    stdout.recv().await.unwrap(),
                    format!("cluster received: (ClusterId::<()>({}), {}) (self cluster id: ClusterId::<()>({}))", i, j, i)
                );
            }
        }

        let mut node_outs = vec![];
        for _i in 0..10 {
            node_outs.push(node_stdout.recv().await.unwrap());
        }
        node_outs.sort();

        for (i, n) in node_outs.into_iter().enumerate() {
            assert_eq!(
                n,
                format!(
                    "node received: (ClusterId::<()>({}), (ClusterId::<()>({}), {}))",
                    i / 5,
                    i / 5,
                    i % 5
                )
            );
        }
    }

    #[tokio::test]
    async fn decouple_process() {
        let mut deployment = Deployment::new();

        let builder = hydro_lang::FlowBuilder::new();
        let (process1, process2) = super::decouple_process(&builder);
        let built = builder.with_default_optimize();

        let nodes = built
            .with_process(&process1, deployment.Localhost())
            .with_process(&process2, deployment.Localhost())
            .deploy(&mut deployment);

        deployment.deploy().await.unwrap();
        let mut process2_stdout = nodes.get_process(&process2).stdout().await;
        deployment.start().await.unwrap();
        for i in 0..3 {
            let expected_message = format!("I received message is {}", i);
            assert_eq!(process2_stdout.recv().await.unwrap(), expected_message);
        }
    }

    #[tokio::test]
    async fn decouple_cluster() {
        let mut deployment = Deployment::new();

        let builder = hydro_lang::FlowBuilder::new();
        let (cluster1, cluster2) = super::decouple_cluster(&builder);
        let built = builder.with_default_optimize();

        let nodes = built
            .with_cluster(&cluster1, (0..3).map(|_| deployment.Localhost()))
            .with_cluster(&cluster2, (0..3).map(|_| deployment.Localhost()))
            .deploy(&mut deployment);

        deployment.deploy().await.unwrap();

        let cluster2_stdouts = futures::future::join_all(
            nodes
                .get_cluster(&cluster2)
                .members()
                .iter()
                .map(|node| node.stdout()),
        )
        .await;

        deployment.start().await.unwrap();

        for (i, mut stdout) in cluster2_stdouts.into_iter().enumerate() {
            for _j in 0..1 {
                let expected_message = format!(
                    "My self id is ClusterId::<()>({}), my message is ClusterId::<()>({})",
                    i, i
                );
                assert_eq!(stdout.recv().await.unwrap(), expected_message);
            }
        }
    }

    #[tokio::test]
    async fn partition() {
        let mut deployment = Deployment::new();

        let num_nodes = 3;
        let num_partitions = 2;
        let builder = hydro_lang::FlowBuilder::new();
        let (cluster1, cluster2) = super::partition(
            builder.cluster::<()>(),
            builder.cluster::<()>(),
            q!(move |(id, msg)| (
                ClusterId::<()>::from_raw(id.raw_id * num_partitions as u32),
                msg
            )),
        );
        let built = builder.with_default_optimize();

        let nodes = built
            .with_cluster(&cluster1, (0..num_nodes).map(|_| deployment.Localhost()))
            .with_cluster(
                &cluster2,
                (0..num_nodes * num_partitions).map(|_| deployment.Localhost()),
            )
            .deploy(&mut deployment);

        deployment.deploy().await.unwrap();

        let cluster2_stdouts = futures::future::join_all(
            nodes
                .get_cluster(&cluster2)
                .members()
                .iter()
                .map(|node| node.stdout()),
        )
        .await;

        deployment.start().await.unwrap();

        for (cluster2_id, mut stdout) in cluster2_stdouts.into_iter().enumerate() {
            if cluster2_id % num_partitions == 0 {
                let expected_message = format!(
                    r#"My self id is {}, my message is "Hello from {}""#,
                    cluster2_id,
                    cluster2_id / num_partitions
                );
                assert_eq!(stdout.recv().await.unwrap(), expected_message);
            }
        }
    }
}