hydroflow 0.10.0

Hydro's low-level dataflow runtime and IR
Documentation
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#![cfg(not(target_arch = "wasm32"))]

//! Surface syntax tests of asynchrony and networking.

use std::collections::{BTreeSet, HashSet};
use std::error::Error;
use std::net::{Ipv4Addr, SocketAddr};
use std::time::Duration;

use bytes::Bytes;
use hydroflow::scheduled::graph::Hydroflow;
use hydroflow::util::{collect_ready_async, ready_iter, tcp_lines};
use hydroflow::{assert_graphvis_snapshots, hydroflow_syntax, rassert, rassert_eq};
use multiplatform_test::multiplatform_test;
use tokio::net::{TcpListener, TcpStream, UdpSocket};
use tokio::task::LocalSet;
use tokio_util::codec::{BytesCodec, FramedWrite, LinesCodec};
use tracing::Instrument;

#[multiplatform_test(hydroflow, env_tracing)]
pub async fn test_echo_udp() -> Result<(), Box<dyn Error>> {
    let local = LocalSet::new();

    let server_socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?;
    let server_addr = server_socket.local_addr()?;
    let server_addr: SocketAddr = (Ipv4Addr::LOCALHOST, server_addr.port()).into();

    // Server:
    let serv = local.spawn_local(async {
        let socket = server_socket;
        let (udp_send, udp_recv, _) = hydroflow::util::udp_lines(socket);
        println!("Server live!");

        let (seen_send, seen_recv) = hydroflow::util::unbounded_channel();

        let mut df: Hydroflow = hydroflow_syntax! {
            recv = source_stream(udp_recv)
                -> map(|r| r.unwrap())
                -> tee();
            // Echo
            recv[0] -> dest_sink(udp_send);
            // Testing
            recv[1] -> map(|(s, _addr)| s) -> for_each(|s| seen_send.send(s).unwrap());
        };

        tokio::select! {
            _ = df.run_async() => (),
            _ = tokio::time::sleep(Duration::from_secs(1)) => (),
        };

        let seen: HashSet<_> = collect_ready_async(seen_recv).await;
        rassert_eq!(4, seen.len())?;
        rassert!(seen.contains("Hello"))?;
        rassert!(seen.contains("World"))?;
        rassert!(seen.contains("Raise"))?;
        rassert!(seen.contains("Count"))?;

        Ok(()) as Result<(), Box<dyn Error>>
    });

    // Client A:
    let client_a = local.spawn_local(async move {
        let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
            .await
            .unwrap();
        let (send_udp, recv_udp, _) = hydroflow::util::udp_lines(socket);

        let (seen_send, seen_recv) = hydroflow::util::unbounded_channel();

        let mut df = hydroflow_syntax! {
            recv = source_stream(recv_udp)
                -> map(|r| r.unwrap())
                -> tee();
            recv[0] -> for_each(|x| println!("client A recv: {:?}", x));
            recv[1] -> map(|(s, _addr)| s) -> for_each(|s| seen_send.send(s).unwrap());

            // Sending
            source_iter([ "Hello", "World" ]) -> map(|s| (s.to_owned(), server_addr)) -> dest_sink(send_udp);
        };

        tokio::select! {
            _ = df.run_async() => (),
            _ = tokio::time::sleep(Duration::from_secs(1)) => (),
        };

        let seen: Vec<_> = collect_ready_async(seen_recv).await;
        rassert_eq!(&["Hello".to_owned(), "World".to_owned()], &*seen)?;

        Ok(()) as Result<(), Box<dyn Error>>
    });

    // Client B:
    let client_b = local.spawn_local(async move {
        let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
            .await
            .unwrap();
        let (send_udp, recv_udp, _) = hydroflow::util::udp_lines(socket);

        let (seen_send, seen_recv) = hydroflow::util::unbounded_channel();

        let mut df = hydroflow_syntax! {
            recv = source_stream(recv_udp)
                -> map(|r| r.unwrap())
                -> tee();
            recv[0] -> for_each(|x| println!("client B recv: {:?}", x));
            recv[1] -> map(|(s, _addr)| s) -> for_each(|s| seen_send.send(s).unwrap());

            // Sending
            source_iter([ "Raise", "Count" ]) -> map(|s| (s.to_owned(), server_addr)) -> dest_sink(send_udp);
        };

        tokio::select! {
            _ = df.run_async() => (),
            _ = tokio::time::sleep(Duration::from_secs(1)) => (),
        };

        let seen: Vec<_> = collect_ready_async(seen_recv).await;
        rassert_eq!(&["Raise".to_owned(), "Count".to_owned()], &*seen)?;

        Ok(()) as Result<(), Box<dyn Error>>
    });

    local.await;
    serv.await??;
    client_a.await??;
    client_b.await??;

    Ok(())
}

#[multiplatform_test(hydroflow, env_tracing)]
pub async fn test_echo_tcp() -> Result<(), Box<dyn Error>> {
    let local = LocalSet::new();

    // Port 0 -> picks any available port.
    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?;
    let addr = listener.local_addr()?;

    // Server:
    let serv = local.spawn_local(async move {
        let (server_stream, _) = listener.accept().await?;
        let (server_send, server_recv) = tcp_lines(server_stream);

        println!("Server accepted connection!");

        let (seen_send, seen_recv) = hydroflow::util::unbounded_channel();

        let mut df: Hydroflow = hydroflow_syntax! {
            rev = source_stream(server_recv)
                -> map(|x| x.unwrap())
                -> tee();
            rev[0] -> dest_sink(server_send);
            rev[1] -> for_each(|s| seen_send.send(s).unwrap());
        };

        tokio::time::timeout(Duration::from_secs(1), df.run_async())
            .await
            .expect_err("Expected time out");

        let seen: Vec<_> = collect_ready_async(seen_recv).await;
        rassert_eq!(&["Hello".to_owned(), "World".to_owned()], &*seen)?;

        Ok(()) as Result<(), Box<dyn Error>>
    });

    // Client:
    let client = local.spawn_local(async move {
        let client_stream = TcpStream::connect(addr).await?;
        let (client_send, client_recv) = tcp_lines(client_stream);

        println!("Client connected!");

        let (seen_send, seen_recv) = hydroflow::util::unbounded_channel();

        let mut df = hydroflow_syntax! {
            recv = source_stream(client_recv)
                -> map(|x| x.unwrap())
                -> tee();

            recv[0] -> for_each(|s| println!("echo {}", s));
            recv[1] -> for_each(|s| seen_send.send(s).unwrap());

            source_iter([
                "Hello",
                "World",
            ]) -> dest_sink(client_send);
        };

        println!("Client running!");

        tokio::time::timeout(Duration::from_secs(1), df.run_async())
            .await
            .expect_err("Expected time out");

        let seen: Vec<_> = collect_ready_async(seen_recv).await;
        rassert_eq!(&["Hello".to_owned(), "World".to_owned()], &*seen)?;

        Ok(()) as Result<(), Box<dyn Error>>
    });

    local.await;
    serv.await??;
    client.await??;

    Ok(())
}

#[multiplatform_test(hydroflow, env_tracing)]
pub async fn test_echo() {
    // An edge in the input data = a pair of `usize` vertex IDs.
    let (lines_send, lines_recv) = hydroflow::util::unbounded_channel::<String>();

    // LinesCodec separates each line from `lines_recv` with `\n`.
    let stdout_lines = FramedWrite::new(tokio::io::stdout(), LinesCodec::new());

    let mut df: Hydroflow = hydroflow_syntax! {
        source_stream(lines_recv) -> dest_sink(stdout_lines);
    };
    assert_graphvis_snapshots!(df);
    df.run_available();

    lines_send.send("Hello".to_owned()).unwrap();
    lines_send.send("World".to_owned()).unwrap();
    df.run_available();

    lines_send.send("Hello".to_owned()).unwrap();
    lines_send.send("World".to_owned()).unwrap();
    df.run_available();

    // Allow background thread to catch up.
    tokio::time::sleep(Duration::from_secs(1)).await;
}

#[multiplatform_test(hydroflow, env_tracing)]
pub async fn test_futures_stream_sink() {
    const MAX: usize = 20;

    let (mut send, recv) = futures::channel::mpsc::channel::<usize>(5);
    send.try_send(0).unwrap();

    let (seen_send, seen_recv) = hydroflow::util::unbounded_channel();

    let mut df = hydroflow_syntax! {
        recv = source_stream(recv) -> tee();
        recv[0] -> map(|x| x + 1)
            -> filter(|&x| x < MAX)
            -> dest_sink(send);
        recv[1] -> for_each(|x| seen_send.send(x).unwrap());
    };

    tokio::time::timeout(Duration::from_secs(1), df.run_async())
        .await
        .expect_err("Expected timeout, `run_async` doesn't return.");

    let seen: Vec<_> = collect_ready_async(seen_recv).await;
    assert_eq!(&std::array::from_fn::<_, MAX, _>(|i| i), &*seen);
}

#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_dest_sink_bounded_channel() {
    // In this example we use a _bounded_ channel for our `Sink`. This is for demonstration only,
    // instead you should use [`hydroflow::util::unbounded_channel`]. A bounded channel results in
    // `Hydroflow` buffering items internally instead of within the channel.
    let (send, recv) = tokio::sync::mpsc::channel::<usize>(5);
    let send = tokio_util::sync::PollSender::new(send);
    let mut recv = tokio_stream::wrappers::ReceiverStream::new(recv);

    let mut flow = hydroflow_syntax! {
        source_iter(0..10) -> dest_sink(send);
    };
    tokio::time::timeout(Duration::from_secs(1), flow.run_async())
        .await
        .expect_err("Expected time out");

    // Only 5 elemts received due to buffer size
    let out: Vec<_> = ready_iter(&mut recv).collect();
    assert_eq!(&[0, 1, 2, 3, 4], &*out);

    tokio::task::yield_now().await;

    let out: Vec<_> = ready_iter(&mut recv).collect();
    assert_eq!(&[5, 6, 7, 8, 9], &*out);
}

#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_dest_sink_duplex() {
    use bytes::Bytes;
    use tokio::io::AsyncReadExt;
    use tokio_util::codec;

    // Like a channel, but for a stream of bytes instead of discrete objects.
    let (asyncwrite, mut asyncread) = tokio::io::duplex(256);
    // Now instead handle discrete byte lists by length-encoding them.
    let sink = codec::LengthDelimitedCodec::builder()
        // Use 1 byte len field (max 255) so we don't have to worry about endianness.
        .length_field_length(1)
        .new_write(asyncwrite);

    let mut flow = hydroflow_syntax! {
        source_iter([
            Bytes::from_static(b"hello"),
            Bytes::from_static(b"world"),
        ]) -> dest_sink(sink);
    };
    tokio::time::timeout(Duration::from_secs(1), flow.run_async())
        .await
        .expect_err("Expected time out");

    let mut buf = Vec::<u8>::new();
    asyncread.read_buf(&mut buf).await.unwrap();
    // `\x05` is length prefix of "5".
    assert_eq!(b"\x05hello\x05world", &*buf);
}

#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_dest_asyncwrite_duplex() {
    use tokio::io::AsyncReadExt;

    // Like a channel, but for a stream of bytes instead of discrete objects.
    // This could be an output file, network port, stdout, etc.
    let (asyncwrite, mut asyncread) = tokio::io::duplex(256);
    let sink = FramedWrite::new(asyncwrite, BytesCodec::new());

    let mut flow = hydroflow_syntax! {
        source_iter([
            Bytes::from_static("hello".as_bytes()),
            Bytes::from_static("world".as_bytes()),
        ]) -> dest_sink(sink);
    };
    tokio::time::timeout(Duration::from_secs(1), flow.run_async())
        .await
        .expect_err("Expected time out");

    let mut buf = Vec::<u8>::new();
    asyncread.read_buf(&mut buf).await.unwrap();
    // `\x05` is length prefix of "5".
    assert_eq!(b"helloworld", &*buf);
}

#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_source_stream() {
    let (a_send, a_recv) = hydroflow::util::unbounded_channel::<usize>();
    let (b_send, b_recv) = hydroflow::util::unbounded_channel::<usize>();
    let (c_send, c_recv) = hydroflow::util::unbounded_channel::<usize>();

    let task_a = tokio::task::spawn_local(async move {
        let mut flow = hydroflow_syntax! {
            source_stream(a_recv) -> for_each(|x| { b_send.send(x).unwrap(); });
        };
        flow.run_async().await.unwrap();
    });
    let task_b = tokio::task::spawn_local(async move {
        let mut flow = hydroflow_syntax! {
            source_stream(b_recv) -> for_each(|x| { c_send.send(x).unwrap(); });
        };
        flow.run_async().await.unwrap();
    });

    a_send.send(1).unwrap();
    a_send.send(2).unwrap();
    a_send.send(3).unwrap();

    tokio::select! {
        biased;
        _ = task_a => unreachable!(),
        _ = task_b => unreachable!(),
        _ = tokio::task::yield_now() => (),
    };

    assert_eq!(
        &[1, 2, 3],
        &*collect_ready_async::<Vec<_>, _>(&mut { c_recv }).await
    );
}

/// Check to make sure hf.run_async() does not hang due to replaying stateful operators saturating
/// `run_available()`.
///
/// This test is a little bit race-ey... if for some insane reason a tick (task_b) runs longer than
/// the send loop delay (task_a).
#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_check_state_yielding() {
    let (a_send, a_recv) = hydroflow::util::unbounded_channel::<usize>();
    let (b_send, mut b_recv) = hydroflow::util::unbounded_channel::<usize>();

    let task_a = tokio::task::spawn_local(
        async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            for a in 0..10 {
                tracing::debug!(a = a, "Sending.");
                a_send.send(a).unwrap();
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
            tokio::task::yield_now().await;
        }
        .instrument(tracing::debug_span!("task_a")),
    );

    let task_b = tokio::task::spawn_local(
        async move {
            let mut hf = hydroflow_syntax! {
                source_stream(a_recv)
                    -> reduce::<'static>(|a: &mut _, b| *a += b)
                    -> for_each(|x| b_send.send(x).unwrap());
            };

            tokio::select! {
                biased;
                _ = hf.run_async() => panic!("`run_async()` should run forever."),
                _ = task_a => tracing::info!("`task_a` (sending) complete."),
            }

            assert_eq!(
                [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
                    .into_iter()
                    .collect::<BTreeSet<_>>(),
                collect_ready_async(&mut b_recv).await
            );
        }
        .instrument(tracing::debug_span!("task_b")),
    );

    task_b.await.unwrap();
}

#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_repeat_iter() {
    let (b_send, b_recv) = hydroflow::util::unbounded_channel::<usize>();

    let mut hf = hydroflow_syntax! {
        source_iter(0..3) -> persist::<'static>()
            -> for_each(|x| b_send.send(x).unwrap());
    };
    hf.run_available_async().await;

    let seen: Vec<_> = collect_ready_async(b_recv).await;
    assert_eq!(&[0, 1, 2], &*seen);
}

#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_event_repeat_iter() {
    let (a_send, a_recv) = hydroflow::util::unbounded_channel::<usize>();
    let (b_send, b_recv) = hydroflow::util::unbounded_channel::<usize>();

    let mut hf = hydroflow_syntax! {
        source_iter(0..3) -> persist::<'static>() -> my_union;
        source_stream(a_recv) -> my_union;
        my_union = union() -> for_each(|x| b_send.send(x).unwrap());
    };

    let send_task = tokio::task::spawn({
        async move {
            // Wait, then send `10`.
            tokio::time::sleep(Duration::from_millis(100)).await;
            tracing::debug!("sending `10`.");
            a_send.send(10).unwrap();
        }
        .instrument(tracing::debug_span!("sender"))
    });

    // Run until barrier completes.
    tokio::select! {
        biased; // `run_async` needs to be polled to process the data first, otherwise the task may complete before data is processed.
        _ = hf.run_async() => panic!("`run_async()` should run forever."),
        _ = send_task => tracing::info!("sending complete"),
    };

    let seen: Vec<_> = collect_ready_async(b_recv).await;
    assert_eq!(&[0, 1, 2, 0, 1, 2, 10], &*seen);
}

#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_tcp() {
    let (tx_out, rx_out) = hydroflow::util::unbounded_channel::<String>();

    let (tx, rx, server_addr) =
        hydroflow::util::bind_tcp_lines("127.0.0.1:0".parse().unwrap()).await;
    let mut echo_server = hydroflow_syntax! {
        source_stream(rx)
            -> filter_map(Result::ok)
            -> dest_sink(tx);
    };

    let (tx, rx) = hydroflow::util::connect_tcp_lines();
    let mut echo_client = hydroflow_syntax! {
        source_iter([("Hello".to_owned(), server_addr)])
            -> dest_sink(tx);

        source_stream(rx)
            -> filter_map(Result::ok)
            -> map(|(string, _)| string)
            -> for_each(|x| tx_out.send(x).unwrap());
    };

    tokio::time::timeout(
        Duration::from_millis(200),
        futures::future::join(echo_server.run_async(), echo_client.run_async()),
    )
    .await
    .expect_err("Expected timeout");

    let seen: Vec<_> = collect_ready_async(rx_out).await;
    assert_eq!(&["Hello".to_owned()], &*seen);
}

#[multiplatform_test(hydroflow, env_tracing)]
async fn asynctest_udp() {
    let (tx_out, rx_out) = hydroflow::util::unbounded_channel::<String>();

    let (tx, rx, server_addr) =
        hydroflow::util::bind_udp_lines("127.0.0.1:0".parse().unwrap()).await;
    let mut echo_server = hydroflow_syntax! {
        source_stream(rx)
            -> filter_map(Result::ok)
            -> dest_sink(tx);
    };

    let (tx, rx, _) = hydroflow::util::bind_udp_lines("127.0.0.1:0".parse().unwrap()).await;
    let mut echo_client = hydroflow_syntax! {
        source_iter([("Hello".to_owned(), server_addr)])
            -> dest_sink(tx);

        source_stream(rx)
            -> filter_map(Result::ok)
            -> map(|(string, _)| string)
            -> for_each(|x| tx_out.send(x).unwrap());
    };

    tokio::time::timeout(
        Duration::from_millis(200),
        futures::future::join(echo_server.run_async(), echo_client.run_async()),
    )
    .await
    .expect_err("Expected timeout");

    let seen: Vec<_> = collect_ready_async(rx_out).await;
    assert_eq!(&["Hello".to_owned()], &*seen);
}