streamweave 0.10.1

Composable, async, stream-first computation in pure Rust
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
//! Tests for GroupByNode
#![allow(unused_imports, dead_code, unused, clippy::type_complexity)]

use crate::node::{InputStreams, Node, OutputStreams};
use crate::nodes::reduction::{GroupByConfig, GroupByConfigWrapper, GroupByNode, group_by_config};
use futures::StreamExt;
use std::any::Any;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;

/// Helper to create input streams from channels
fn create_input_streams() -> (
  mpsc::Sender<Arc<dyn Any + Send + Sync>>,
  mpsc::Sender<Arc<dyn Any + Send + Sync>>,
  mpsc::Sender<Arc<dyn Any + Send + Sync>>,
  InputStreams,
) {
  let (config_tx, config_rx) = mpsc::channel(10);
  let (in_tx, in_rx) = mpsc::channel(10);
  let (key_function_tx, key_function_rx) = mpsc::channel(10);

  let mut inputs = HashMap::new();
  inputs.insert(
    "configuration".to_string(),
    Box::pin(ReceiverStream::new(config_rx)) as crate::node::InputStream,
  );
  inputs.insert(
    "in".to_string(),
    Box::pin(ReceiverStream::new(in_rx)) as crate::node::InputStream,
  );
  inputs.insert(
    "key_function".to_string(),
    Box::pin(ReceiverStream::new(key_function_rx)) as crate::node::InputStream,
  );

  (config_tx, in_tx, key_function_tx, inputs)
}

#[tokio::test]
async fn test_group_by_node_creation() {
  let node = GroupByNode::new("test_group_by".to_string());
  assert_eq!(node.name(), "test_group_by");
  assert!(node.has_input_port("configuration"));
  assert!(node.has_input_port("in"));
  assert!(node.has_input_port("key_function"));
  assert!(node.has_output_port("out"));
  assert!(node.has_output_port("error"));
}

#[tokio::test]
async fn test_group_by_simple() {
  let node = GroupByNode::new("test_group_by".to_string());

  let (_config_tx, in_tx, key_function_tx, inputs) = create_input_streams();
  let mut outputs: OutputStreams = match node.execute(inputs).await {
    Ok(outputs) => outputs,
    Err(e) => panic!("Node execution failed: {}", e),
  };

  // Create a key function that extracts the value itself as a string
  let key_function: GroupByConfig =
    group_by_config(|value: Arc<dyn Any + Send + Sync>| async move {
      if let Ok(arc_i32) = value.clone().downcast::<i32>() {
        Ok(arc_i32.to_string())
      } else {
        Err("Expected i32".to_string())
      }
    });

  // Send key function
  let _ = key_function_tx
    .send(Arc::new(GroupByConfigWrapper::new(key_function)) as Arc<dyn Any + Send + Sync>)
    .await;

  // Send values: 1, 2, 1, 3, 2 → groups: {"1": [1, 1], "2": [2, 2], "3": [3]}
  let _ = in_tx
    .send(Arc::new(1i32) as Arc<dyn Any + Send + Sync>)
    .await;
  let _ = in_tx
    .send(Arc::new(2i32) as Arc<dyn Any + Send + Sync>)
    .await;
  let _ = in_tx
    .send(Arc::new(1i32) as Arc<dyn Any + Send + Sync>)
    .await;
  let _ = in_tx
    .send(Arc::new(3i32) as Arc<dyn Any + Send + Sync>)
    .await;
  let _ = in_tx
    .send(Arc::new(2i32) as Arc<dyn Any + Send + Sync>)
    .await;
  drop(in_tx); // Close the input stream
  drop(key_function_tx); // Close the key function stream

  let out_stream = outputs.remove("out").unwrap();
  let mut results: Vec<Arc<dyn Any + Send + Sync>> = Vec::new();
  let mut stream = out_stream;
  let timeout = tokio::time::sleep(tokio::time::Duration::from_millis(200));
  tokio::pin!(timeout);

  loop {
    tokio::select! {
      result = stream.next() => {
        if let Some(item) = result {
          results.push(item);
        } else {
          break;
        }
      }
      _ = &mut timeout => break,
    }
  }

  assert_eq!(results.len(), 1);
  if let Ok(grouped) = results[0]
    .clone()
    .downcast::<HashMap<String, Arc<dyn Any + Send + Sync>>>()
  {
    // Check that we have 3 groups
    assert_eq!(grouped.len(), 3);

    // Check group "1" has 2 items
    if let Some(items_arc) = grouped.get("1") {
      if let Ok(items) = items_arc
        .clone()
        .downcast::<Vec<Arc<dyn Any + Send + Sync>>>()
      {
        assert_eq!(items.len(), 2);
        if let (Ok(item1), Ok(item2)) = (
          items[0].clone().downcast::<i32>(),
          items[1].clone().downcast::<i32>(),
        ) {
          assert_eq!(*item1, 1i32);
          assert_eq!(*item2, 1i32);
        } else {
          panic!("Items in group '1' are not i32");
        }
      } else {
        panic!("Group '1' is not a Vec");
      }
    } else {
      panic!("Group '1' not found");
    }

    // Check group "2" has 2 items
    if let Some(items_arc) = grouped.get("2") {
      if let Ok(items) = items_arc
        .clone()
        .downcast::<Vec<Arc<dyn Any + Send + Sync>>>()
      {
        assert_eq!(items.len(), 2);
      } else {
        panic!("Group '2' is not a Vec");
      }
    } else {
      panic!("Group '2' not found");
    }

    // Check group "3" has 1 item
    if let Some(items_arc) = grouped.get("3") {
      if let Ok(items) = items_arc
        .clone()
        .downcast::<Vec<Arc<dyn Any + Send + Sync>>>()
      {
        assert_eq!(items.len(), 1);
      } else {
        panic!("Group '3' is not a Vec");
      }
    } else {
      panic!("Group '3' not found");
    }
  } else {
    panic!("Result is not a HashMap<String, Arc<dyn Any + Send + Sync>>");
  }
}

#[tokio::test]
async fn test_group_by_empty_stream() {
  let node = GroupByNode::new("test_group_by".to_string());

  let (_config_tx, in_tx, key_function_tx, inputs) = create_input_streams();
  let mut outputs: OutputStreams = match node.execute(inputs).await {
    Ok(outputs) => outputs,
    Err(e) => panic!("Node execution failed: {}", e),
  };

  // Create a key function
  let key_function: GroupByConfig =
    group_by_config(|value: Arc<dyn Any + Send + Sync>| async move {
      if let Ok(arc_i32) = value.clone().downcast::<i32>() {
        Ok(arc_i32.to_string())
      } else {
        Err("Expected i32".to_string())
      }
    });

  // Send key function
  let _ = key_function_tx
    .send(Arc::new(GroupByConfigWrapper::new(key_function)) as Arc<dyn Any + Send + Sync>)
    .await;

  // Send no values: empty stream → result should be empty HashMap
  drop(in_tx); // Close the input stream immediately
  drop(key_function_tx); // Close the key function stream

  let out_stream = outputs.remove("out").unwrap();
  let mut results: Vec<Arc<dyn Any + Send + Sync>> = Vec::new();
  let mut stream = out_stream;
  let timeout = tokio::time::sleep(tokio::time::Duration::from_millis(200));
  tokio::pin!(timeout);

  loop {
    tokio::select! {
      result = stream.next() => {
        if let Some(item) = result {
          results.push(item);
        } else {
          break;
        }
      }
      _ = &mut timeout => break,
    }
  }

  assert_eq!(results.len(), 1);
  if let Ok(grouped) = results[0]
    .clone()
    .downcast::<HashMap<String, Arc<dyn Any + Send + Sync>>>()
  {
    // Empty stream should result in empty HashMap
    assert_eq!(grouped.len(), 0);
  } else {
    panic!("Result is not a HashMap<String, Arc<dyn Any + Send + Sync>>");
  }
}

#[tokio::test]
async fn test_group_by_key_function_error() {
  let node = GroupByNode::new("test_group_by".to_string());

  let (_config_tx, in_tx, key_function_tx, inputs) = create_input_streams();
  let mut outputs: OutputStreams = match node.execute(inputs).await {
    Ok(outputs) => outputs,
    Err(e) => panic!("Node execution failed: {}", e),
  };

  // Create a key function that returns an error for negative values
  let key_function: GroupByConfig =
    group_by_config(|value: Arc<dyn Any + Send + Sync>| async move {
      if let Ok(arc_i32) = value.clone().downcast::<i32>() {
        if *arc_i32 < 0 {
          Err("Negative values not allowed".to_string())
        } else {
          Ok(arc_i32.to_string())
        }
      } else {
        Err("Expected i32".to_string())
      }
    });

  // Send key function
  let _ = key_function_tx
    .send(Arc::new(GroupByConfigWrapper::new(key_function)) as Arc<dyn Any + Send + Sync>)
    .await;

  // Send values: 1, -2, 3 → should error on -2
  let _ = in_tx
    .send(Arc::new(1i32) as Arc<dyn Any + Send + Sync>)
    .await;
  let _ = in_tx
    .send(Arc::new(-2i32) as Arc<dyn Any + Send + Sync>)
    .await;
  let _ = in_tx
    .send(Arc::new(3i32) as Arc<dyn Any + Send + Sync>)
    .await;
  drop(in_tx);
  drop(key_function_tx);

  // Check error output
  let error_stream = outputs.remove("error").unwrap();
  let mut errors: Vec<String> = Vec::new();
  let mut stream = error_stream;
  let timeout = tokio::time::sleep(tokio::time::Duration::from_millis(200));
  tokio::pin!(timeout);

  loop {
    tokio::select! {
      result = stream.next() => {
        if let Some(item) = result {
          if let Ok(arc_str) = Arc::downcast::<String>(item.clone()) {
            errors.push((*arc_str).clone());
          }
        } else {
          break;
        }
      }
      _ = &mut timeout => break,
    }
  }

  assert_eq!(errors.len(), 1);
  assert_eq!(&*errors[0], "Negative values not allowed");

  // Check that valid items are still grouped
  let out_stream = outputs.remove("out").unwrap();
  let mut results: Vec<Arc<dyn Any + Send + Sync>> = Vec::new();
  let mut stream = out_stream;
  let timeout = tokio::time::sleep(tokio::time::Duration::from_millis(200));
  tokio::pin!(timeout);

  loop {
    tokio::select! {
      result = stream.next() => {
        if let Some(item) = result {
          results.push(item);
        } else {
          break;
        }
      }
      _ = &mut timeout => break,
    }
  }

  assert_eq!(results.len(), 1);
  if let Ok(grouped) = results[0]
    .clone()
    .downcast::<HashMap<String, Arc<dyn Any + Send + Sync>>>()
  {
    // Should have groups for "1" and "3" (valid values)
    assert!(grouped.contains_key("1"));
    assert!(grouped.contains_key("3"));
    assert!(!grouped.contains_key("-2")); // Error value not grouped
  } else {
    panic!("Result is not a HashMap<String, Arc<dyn Any + Send + Sync>>");
  }
}

#[tokio::test]
async fn test_group_by_string_values() {
  let node = GroupByNode::new("test_group_by".to_string());

  let (_config_tx, in_tx, key_function_tx, inputs) = create_input_streams();
  let mut outputs: OutputStreams = match node.execute(inputs).await {
    Ok(outputs) => outputs,
    Err(e) => panic!("Node execution failed: {}", e),
  };

  // Create a key function that extracts first character
  let key_function: GroupByConfig =
    group_by_config(|value: Arc<dyn Any + Send + Sync>| async move {
      if let Ok(arc_str) = Arc::downcast::<String>(value.clone()) {
        if let Some(first_char) = arc_str.chars().next() {
          Ok::<String, String>(first_char.to_string())
        } else {
          Err::<String, String>("Empty string".to_string())
        }
      } else {
        Err::<String, String>("Expected String".to_string())
      }
    });

  // Send key function
  let _ = key_function_tx
    .send(Arc::new(GroupByConfigWrapper::new(key_function)) as Arc<dyn Any + Send + Sync>)
    .await;

  // Send values: "apple", "banana", "apricot" → groups: {"a": ["apple", "apricot"], "b": ["banana"]}
  let _ = in_tx
    .send(Arc::new("apple".to_string()) as Arc<dyn Any + Send + Sync>)
    .await;
  let _ = in_tx
    .send(Arc::new("banana".to_string()) as Arc<dyn Any + Send + Sync>)
    .await;
  let _ = in_tx
    .send(Arc::new("apricot".to_string()) as Arc<dyn Any + Send + Sync>)
    .await;
  drop(in_tx);
  drop(key_function_tx);

  let out_stream = outputs.remove("out").unwrap();
  let mut results: Vec<Arc<dyn Any + Send + Sync>> = Vec::new();
  let mut stream = out_stream;
  let timeout = tokio::time::sleep(tokio::time::Duration::from_millis(200));
  tokio::pin!(timeout);

  loop {
    tokio::select! {
      result = stream.next() => {
        if let Some(item) = result {
          results.push(item);
        } else {
          break;
        }
      }
      _ = &mut timeout => break,
    }
  }

  assert_eq!(results.len(), 1);
  if let Ok(grouped) = results[0]
    .clone()
    .downcast::<HashMap<String, Arc<dyn Any + Send + Sync>>>()
  {
    assert_eq!(grouped.len(), 2);
    assert!(grouped.contains_key("a"));
    assert!(grouped.contains_key("b"));
  } else {
    panic!("Result is not a HashMap<String, Arc<dyn Any + Send + Sync>>");
  }
}