use crate::node::{InputStreams, Node, NodeExecutionError, OutputStreams};
use crate::nodes::array::common::array_map;
use crate::nodes::common::{BaseNode, process_configurable_node};
use crate::nodes::map_node::MapConfig;
use async_trait::async_trait;
use std::any::Any;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio_stream::wrappers::ReceiverStream;
pub struct ArrayMapNode {
pub(crate) base: BaseNode,
}
impl ArrayMapNode {
pub fn new(name: String) -> Self {
Self {
base: BaseNode::new(
name,
vec![
"configuration".to_string(),
"in".to_string(),
"function".to_string(),
],
vec!["out".to_string(), "error".to_string()],
),
}
}
}
#[async_trait]
impl Node for ArrayMapNode {
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 in_stream = inputs.remove("in").ok_or("Missing 'in' input")?;
let function_stream = inputs
.remove("function")
.ok_or("Missing 'function' input")?;
let (out_rx, error_rx) = process_configurable_node(
function_stream,
in_stream,
Arc::new(Mutex::new(None::<Arc<MapConfig>>)),
|item: Arc<dyn Any + Send + Sync>, cfg: &Arc<MapConfig>| {
let cfg = cfg.clone();
async move {
array_map(&item, &cfg).await.map(Some)
}
},
);
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)
})
}
}