use crate::node::{InputStreams, Node, NodeExecutionError, OutputStreams};
use crate::nodes::common::{BaseNode, MessageType};
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::sync::Mutex;
use tokio_stream::{StreamExt, wrappers::ReceiverStream};
#[derive(Clone)]
pub struct WhileLoopConfig {
pub condition: Arc<dyn WhileLoopConditionFunction>,
pub max_iterations: usize,
}
#[async_trait]
pub trait WhileLoopConditionFunction: Send + Sync {
async fn apply(&self, value: Arc<dyn Any + Send + Sync>) -> Result<bool, String>;
}
struct WhileLoopConditionFunctionWrapper<F> {
function: F,
}
#[async_trait]
impl<F> WhileLoopConditionFunction for WhileLoopConditionFunctionWrapper<F>
where
F: Fn(
Arc<dyn Any + Send + Sync>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool, String>> + Send>>
+ Send
+ Sync,
{
async fn apply(&self, value: Arc<dyn Any + Send + Sync>) -> Result<bool, String> {
(self.function)(value).await
}
}
pub fn while_loop_config<F, Fut>(function: F, max_iterations: usize) -> WhileLoopConfig
where
F: Fn(Arc<dyn Any + Send + Sync>) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<bool, String>> + Send + 'static,
{
WhileLoopConfig {
condition: Arc::new(WhileLoopConditionFunctionWrapper {
function: move |v| {
Box::pin(function(v))
as std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool, String>> + Send>>
},
}),
max_iterations,
}
}
pub struct WhileLoopNode {
pub(crate) base: BaseNode,
current_config: Arc<Mutex<Option<Arc<WhileLoopConfig>>>>,
}
impl WhileLoopNode {
pub fn new(name: String) -> Self {
Self {
base: BaseNode::new(
name,
vec![
"configuration".to_string(),
"in".to_string(),
"condition".to_string(),
],
vec!["out".to_string(), "break".to_string(), "error".to_string()],
),
current_config: Arc::new(Mutex::new(None)),
}
}
pub fn has_config(&self) -> bool {
self
.current_config
.try_lock()
.map(|g| g.is_some())
.unwrap_or(false)
}
}
#[async_trait]
impl Node for WhileLoopNode {
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 + '_>,
> {
let config_state = Arc::clone(&self.current_config);
Box::pin(async move {
let config_stream = inputs
.remove("configuration")
.ok_or("Missing 'configuration' input")?;
let data_stream = inputs.remove("in").ok_or("Missing 'in' input")?;
let break_stream = inputs
.remove("condition")
.ok_or("Missing 'condition' input")?;
let (break_signal_tx, _) = tokio::sync::broadcast::channel(10);
let break_signal_tx_clone = break_signal_tx.clone();
tokio::spawn(async move {
let mut break_stream = break_stream;
while let Some(_item) = break_stream.next().await {
let _ = break_signal_tx_clone.send(());
}
});
let config_stream = config_stream.map(|item| (MessageType::Config, item));
let data_stream = data_stream.map(|item| (MessageType::Data, item));
let merged_stream = stream::select(config_stream, data_stream);
let (out_tx, out_rx) = tokio::sync::mpsc::channel(10);
let (break_tx, break_rx) = tokio::sync::mpsc::channel(10);
let (error_tx, error_rx) = tokio::sync::mpsc::channel(10);
let config_state_clone = Arc::clone(&config_state);
let out_tx_clone = out_tx.clone();
let break_tx_clone = break_tx.clone();
let error_tx_clone = error_tx.clone();
let break_signal_tx_clone = break_signal_tx.clone();
tokio::spawn(async move {
let mut merged = merged_stream;
let mut current_config: Option<Arc<WhileLoopConfig>> = None;
let mut current_item: Option<Arc<dyn Any + Send + Sync>> = None;
loop {
tokio::select! {
msg_opt = merged.next() => {
if let Some((msg_type, item)) = msg_opt {
match msg_type {
MessageType::Config => {
if let Ok(arc_arc_config) = item.clone().downcast::<Arc<Arc<WhileLoopConfig>>>() {
let config = Arc::clone(&**arc_arc_config);
current_config = Some(Arc::clone(&config));
*config_state_clone.lock().await = Some(config);
} else if let Ok(arc_config) = item.clone().downcast::<Arc<WhileLoopConfig>>() {
let config = Arc::clone(&*arc_config);
current_config = Some(Arc::clone(&config));
*config_state_clone.lock().await = Some(config);
} else {
let error_msg: String = "Invalid configuration type - expected Arc<WhileLoopConfig>".to_string();
let error_arc: Arc<dyn Any + Send + Sync> = Arc::new(error_msg);
let _ = error_tx_clone.send(error_arc).await;
}
}
MessageType::Data => {
if current_item.is_none() {
current_item = Some(item);
let item_clone = current_item.clone().unwrap();
let config_clone = current_config.clone();
let out_tx_task = out_tx_clone.clone();
let break_tx_task = break_tx_clone.clone();
let error_tx_task = error_tx_clone.clone();
let mut break_signal_rx_task = break_signal_tx_clone.subscribe();
tokio::spawn(async move {
if let Some(config) = config_clone {
let item = item_clone;
let mut iter_count = 0;
loop {
if iter_count >= config.max_iterations {
let error_msg: String = format!(
"Maximum iterations ({}) exceeded. Possible infinite loop.",
config.max_iterations
);
let error_arc: Arc<dyn Any + Send + Sync> = Arc::new(error_msg);
let _ = error_tx_task.send(error_arc).await;
break;
}
let condition_result = tokio::select! {
result = config.condition.apply(item.clone()) => result,
_ = break_signal_rx_task.recv() => {
let _ = break_tx_task.send(item).await;
break;
}
};
match condition_result {
Ok(true) => {
iter_count += 1;
}
Ok(false) => {
let _ = out_tx_task.send(item).await;
break;
}
Err(error_msg) => {
let error_arc: Arc<dyn Any + Send + Sync> = Arc::new(error_msg);
let _ = error_tx_task.send(error_arc).await;
break;
}
}
}
} else {
let error_msg: String = "No configuration set. Please send configuration before data.".to_string();
let error_arc: Arc<dyn Any + Send + Sync> = Arc::new(error_msg);
let _ = error_tx_task.send(error_arc).await;
}
});
current_item = None;
}
}
}
} else {
break;
}
}
}
}
});
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(
"break".to_string(),
Box::pin(ReceiverStream::new(break_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)
})
}
}