#![allow(clippy::type_complexity)]
use crate::node::{InputStreams, Node, NodeExecutionError, OutputStreams};
use crate::nodes::common::BaseNode;
use async_trait::async_trait;
use futures::stream;
use std::any::Any;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use tokio_stream::{StreamExt, wrappers::ReceiverStream};
#[async_trait]
pub trait ScanFunction: Send + Sync {
async fn apply(
&self,
accumulator: Arc<dyn Any + Send + Sync>,
value: Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String>;
}
pub type ScanConfig = Arc<dyn ScanFunction>;
pub struct ScanConfigWrapper(pub ScanConfig);
impl ScanConfigWrapper {
pub fn new(config: ScanConfig) -> Self {
Self(config)
}
}
struct ScanFunctionWrapper<F> {
function: F,
}
#[async_trait]
impl<F> ScanFunction for ScanFunctionWrapper<F>
where
F: Fn(
Arc<dyn Any + Send + Sync>,
Arc<dyn Any + Send + Sync>,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Arc<dyn Any + Send + Sync>, String>> + Send>,
> + Send
+ Sync,
{
async fn apply(
&self,
accumulator: Arc<dyn Any + Send + Sync>,
value: Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
(self.function)(accumulator, value).await
}
}
pub fn scan_config<F, Fut>(function: F) -> ScanConfig
where
F: Fn(Arc<dyn Any + Send + Sync>, Arc<dyn Any + Send + Sync>) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<Arc<dyn Any + Send + Sync>, String>> + Send + 'static,
{
Arc::new(ScanFunctionWrapper {
function: move |acc, v| {
Box::pin(function(acc, v))
as std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Arc<dyn Any + Send + Sync>, String>> + Send>,
>
},
})
}
#[allow(dead_code)]
enum InputPort {
Config,
In,
Initial,
Function,
}
pub struct ScanNode {
pub(crate) base: BaseNode,
}
impl ScanNode {
pub fn new(name: String) -> Self {
Self {
base: BaseNode::new(
name,
vec![
"configuration".to_string(),
"in".to_string(),
"initial".to_string(),
"function".to_string(),
],
vec!["out".to_string(), "error".to_string()],
),
}
}
}
#[async_trait]
impl Node for ScanNode {
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 initial_stream = inputs.remove("initial").ok_or("Missing 'initial' input")?;
let function_stream = inputs
.remove("function")
.ok_or("Missing 'function' input")?;
let in_stream = in_stream.map(|item| (InputPort::In, item));
let initial_stream = initial_stream.map(|item| (InputPort::Initial, item));
let function_stream = function_stream.map(|item| (InputPort::Function, item));
let merged_stream: Pin<
Box<dyn futures::Stream<Item = (InputPort, Arc<dyn Any + Send + Sync>)> + Send>,
> = Box::pin(stream::select_all(vec![
Box::pin(in_stream)
as Pin<Box<dyn futures::Stream<Item = (InputPort, Arc<dyn Any + Send + Sync>)> + Send>>,
Box::pin(initial_stream)
as Pin<Box<dyn futures::Stream<Item = (InputPort, Arc<dyn Any + Send + Sync>)> + Send>>,
Box::pin(function_stream)
as Pin<Box<dyn futures::Stream<Item = (InputPort, Arc<dyn Any + Send + Sync>)> + Send>>,
]));
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 merged_stream = merged_stream;
let mut accumulator: Option<Arc<dyn Any + Send + Sync>> = None;
let mut scan_function: Option<ScanConfig> = None;
let mut data_buffer: Vec<Arc<dyn Any + Send + Sync>> = Vec::new();
while let Some((port, item)) = merged_stream.next().await {
match port {
InputPort::Config => {
}
InputPort::Initial => {
if accumulator.is_none() {
accumulator = Some(item);
}
}
InputPort::Function => {
if scan_function.is_none() {
if let Ok(wrapper) = Arc::downcast::<ScanConfigWrapper>(item.clone()) {
scan_function = Some(wrapper.0.clone());
} else {
let error_msg = format!(
"Invalid scan function type: {} (expected ScanConfigWrapper)",
std::any::type_name_of_val(&*item)
);
let error_arc = Arc::new(error_msg) as Arc<dyn Any + Send + Sync>;
let _ = error_tx_clone.send(error_arc).await;
return;
}
}
}
InputPort::In => {
data_buffer.push(item);
}
}
}
if let (Some(acc), Some(func)) = (&accumulator, &scan_function) {
let _ = out_tx_clone.send(acc.clone()).await;
let mut current_acc = acc.clone();
for item in data_buffer {
match func.apply(current_acc.clone(), item).await {
Ok(new_acc) => {
current_acc = new_acc.clone();
let _ = out_tx_clone.send(new_acc).await;
}
Err(e) => {
let error_arc = Arc::new(e) as Arc<dyn Any + Send + Sync>;
let _ = error_tx_clone.send(error_arc).await;
return;
}
}
}
} else {
let error_msg = if accumulator.is_none() && scan_function.is_none() {
"No initial value and no scan function provided".to_string()
} else if accumulator.is_none() {
"No initial value provided for scan".to_string()
} else {
"No scan function provided".to_string()
};
let error_arc = Arc::new(error_msg) as Arc<dyn Any + Send + Sync>;
let _ = error_tx_clone.send(error_arc).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)
})
}
}