use crate::node::{InputStreams, Node, NodeExecutionError, OutputStreams};
use crate::nodes::common::BaseNode;
use async_trait::async_trait;
use std::any::Any;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use tokio_stream::{StreamExt, wrappers::ReceiverStream};
type PinnedItemStream =
Pin<Box<dyn tokio_stream::Stream<Item = Arc<dyn Any + Send + Sync>> + Send>>;
pub struct ZipNode {
pub(crate) base: BaseNode,
}
impl ZipNode {
pub fn new(name: String, num_inputs: usize) -> Self {
let mut input_ports = vec!["configuration".to_string()];
for i in 0..num_inputs {
input_ports.push(format!("in_{}", i));
}
Self {
base: BaseNode::new(
name,
input_ports,
vec!["out".to_string(), "error".to_string()],
),
}
}
}
#[async_trait]
impl Node for ZipNode {
fn name(&self) -> &str {
self.base.name()
}
fn set_name(&mut self, name: &str) {
self.base.set_name(name);
}
fn input_port_names(&self) -> &[String] {
self.base.input_port_names()
}
fn output_port_names(&self) -> &[String] {
self.base.output_port_names()
}
fn has_input_port(&self, name: &str) -> bool {
self.base.has_input_port(name)
}
fn has_output_port(&self, name: &str) -> bool {
self.base.has_output_port(name)
}
fn execute(
&self,
mut inputs: InputStreams,
) -> Pin<
Box<dyn std::future::Future<Output = Result<OutputStreams, NodeExecutionError>> + Send + '_>,
> {
Box::pin(async move {
let _config_stream = inputs.remove("configuration");
let mut input_streams: Vec<(usize, crate::node::InputStream)> = Vec::new();
let mut input_indices = Vec::new();
for (port_name, stream) in inputs {
if port_name.starts_with("in_")
&& let Ok(index) = port_name[3..].parse::<usize>()
{
input_indices.push(index);
input_streams.push((index, stream));
}
}
input_streams.sort_by_key(|(idx, _)| *idx);
if input_streams.is_empty() {
return Err("No input streams found (expected in_0, in_1, ...)".into());
}
let (out_tx, out_rx) = tokio::sync::mpsc::channel(10);
let (error_tx, error_rx) = tokio::sync::mpsc::channel(10);
let out_tx_clone = out_tx.clone();
let _error_tx_clone = error_tx.clone();
tokio::spawn(async move {
let mut streams: Vec<PinnedItemStream> = input_streams
.into_iter()
.map(|(_, stream)| Box::pin(stream) as PinnedItemStream)
.collect();
loop {
let mut zipped_items = Vec::new();
let mut all_have_items = true;
for stream in &mut streams {
match stream.next().await {
Some(item) => {
zipped_items.push(item);
}
None => {
all_have_items = false;
break;
}
}
}
if !all_have_items {
break;
}
if zipped_items.len() == streams.len() {
let zipped_array = Arc::new(zipped_items) as Arc<dyn Any + Send + Sync>;
let _ = out_tx_clone.send(zipped_array).await;
}
}
});
let mut outputs = HashMap::new();
outputs.insert(
"out".to_string(),
Box::pin(ReceiverStream::new(out_rx))
as Pin<Box<dyn tokio_stream::Stream<Item = Arc<dyn Any + Send + Sync>> + Send>>,
);
outputs.insert(
"error".to_string(),
Box::pin(ReceiverStream::new(error_rx))
as Pin<Box<dyn tokio_stream::Stream<Item = Arc<dyn Any + Send + Sync>> + Send>>,
);
Ok(outputs)
})
}
}