use crate::node::{InputStreams, Node, NodeExecutionError, OutputStreams};
use crate::nodes::common::{BaseNode, MessageType};
use async_trait::async_trait;
use futures::stream;
use regex::Regex;
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};
#[async_trait]
pub trait MatchFunction: Send + Sync {
async fn apply(&self, value: Arc<dyn Any + Send + Sync>) -> Result<Option<usize>, String>;
}
pub type MatchConfig = Arc<dyn MatchFunction>;
struct MatchFunctionWrapper<F> {
function: F,
}
#[async_trait::async_trait]
impl<F> MatchFunction for MatchFunctionWrapper<F>
where
F: Fn(
Arc<dyn Any + Send + Sync>,
)
-> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Option<usize>, String>> + Send>>
+ Send
+ Sync,
{
async fn apply(&self, value: Arc<dyn Any + Send + Sync>) -> Result<Option<usize>, String> {
(self.function)(value).await
}
}
pub fn match_config<F, Fut>(function: F) -> MatchConfig
where
F: Fn(Arc<dyn Any + Send + Sync>) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<Option<usize>, String>> + Send + 'static,
{
Arc::new(MatchFunctionWrapper {
function: move |v| {
Box::pin(function(v))
as std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Option<usize>, String>> + Send>,
>
},
})
}
pub fn match_regex(patterns: Vec<(Regex, usize)>) -> MatchConfig {
match_config(move |value| {
let patterns = patterns.clone();
async move {
if let Ok(arc_str) = value.clone().downcast::<String>() {
let s = arc_str.as_str();
for (pattern, branch_index) in &patterns {
if pattern.is_match(s) {
return Ok(Some(*branch_index));
}
}
Ok(None) } else if let Ok(arc_str) = value.downcast::<&str>() {
let s = *arc_str;
for (pattern, branch_index) in &patterns {
if pattern.is_match(s) {
return Ok(Some(*branch_index));
}
}
Ok(None) } else {
Err("Expected String or &str for regex matching".to_string())
}
}
})
}
pub fn match_exact<T>(values: Vec<(T, usize)>) -> MatchConfig
where
T: Send + Sync + Clone + PartialEq + 'static,
{
match_config(move |value| {
let values = values.clone();
async move {
if let Ok(arc_t) = value.downcast::<T>() {
let val = (*arc_t).clone();
for (pattern_val, branch_index) in &values {
if &val == pattern_val {
return Ok(Some(*branch_index));
}
}
Ok(None) } else {
Err(format!(
"Expected {} for exact matching",
std::any::type_name::<T>()
))
}
}
})
}
pub fn match_exact_string(patterns: Vec<(&str, usize)>) -> MatchConfig {
let patterns: Vec<(String, usize)> = patterns
.into_iter()
.map(|(s, idx)| (s.to_string(), idx))
.collect();
match_config(move |value| {
let patterns = patterns.clone();
async move {
if let Ok(arc_string) = value.downcast::<String>() {
let s = arc_string.as_str();
for (pattern, branch_index) in &patterns {
if s == pattern {
return Ok(Some(*branch_index));
}
}
Ok(None) } else {
Err("Expected String for exact string matching".to_string())
}
}
})
}
pub fn match_numeric_range<F, Fut>(matcher: F) -> MatchConfig
where
F: Fn(i32) -> Fut + Send + Sync + Clone + 'static,
Fut: std::future::Future<Output = Result<Option<usize>, String>> + Send + 'static,
{
match_config(move |value| {
let matcher = matcher.clone();
async move {
if let Ok(arc_i32) = value.clone().downcast::<i32>() {
return matcher(*arc_i32).await;
}
if let Ok(arc_i64) = value.clone().downcast::<i64>() {
return matcher(*arc_i64 as i32).await;
}
if let Ok(arc_u32) = value.clone().downcast::<u32>() {
return matcher(*arc_u32 as i32).await;
}
if let Ok(arc_u64) = value.clone().downcast::<u64>() {
return matcher(*arc_u64 as i32).await;
}
if let Ok(arc_f32) = value.clone().downcast::<f32>() {
return matcher(*arc_f32 as i32).await;
}
if let Ok(arc_f64) = value.clone().downcast::<f64>() {
return matcher(*arc_f64 as i32).await;
}
Err("Expected numeric type (i32, i64, u32, u64, f32, f64) for range matching".to_string())
}
})
}
pub struct MatchNode {
pub(crate) base: BaseNode,
current_config: Arc<Mutex<Option<MatchConfig>>>,
max_branches: usize,
}
impl MatchNode {
pub fn new(name: String, max_branches: usize) -> Self {
let mut output_ports = vec!["default".to_string(), "error".to_string()];
for i in 0..max_branches {
output_ports.push(format!("out_{}", i));
}
Self {
base: BaseNode::new(
name,
vec!["configuration".to_string(), "in".to_string()],
output_ports,
),
current_config: Arc::new(Mutex::new(None)),
max_branches,
}
}
pub fn has_config(&self) -> bool {
self
.current_config
.try_lock()
.map(|g| g.is_some())
.unwrap_or(false)
}
pub fn max_branches(&self) -> usize {
self.max_branches
}
}
#[async_trait]
impl Node for MatchNode {
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);
let max_branches = self.max_branches;
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 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);
type ChannelPair = (
tokio::sync::mpsc::Sender<Arc<dyn Any + Send + Sync>>,
tokio::sync::mpsc::Receiver<Arc<dyn Any + Send + Sync>>,
);
let mut output_channels: HashMap<String, ChannelPair> = HashMap::new();
for i in 0..max_branches {
let (tx, rx) = tokio::sync::mpsc::channel(10);
output_channels.insert(format!("out_{}", i), (tx, rx));
}
let (default_tx, default_rx) = tokio::sync::mpsc::channel(10);
let (error_tx, error_rx) = tokio::sync::mpsc::channel(10);
output_channels.insert("default".to_string(), (default_tx.clone(), default_rx));
output_channels.insert("error".to_string(), (error_tx.clone(), error_rx));
let mut branch_txs: HashMap<String, tokio::sync::mpsc::Sender<Arc<dyn Any + Send + Sync>>> =
HashMap::new();
for (port, (tx, _)) in &output_channels {
if port != "error" {
branch_txs.insert(port.clone(), tx.clone());
}
}
let error_tx_clone = error_tx.clone();
let config_state_clone = Arc::clone(&config_state);
tokio::spawn(async move {
let mut merged = merged_stream;
let mut current_config: Option<MatchConfig> = None;
while let Some((msg_type, item)) = merged.next().await {
match msg_type {
MessageType::Config => {
if let Ok(arc_arc_fn) = item.clone().downcast::<Arc<Arc<dyn MatchFunction>>>() {
let cfg = Arc::clone(&**arc_arc_fn);
current_config = Some(Arc::clone(&cfg));
*config_state_clone.lock().await = Some(cfg);
} else if let Ok(arc_function) = item.clone().downcast::<Arc<dyn MatchFunction>>() {
let cfg = Arc::clone(&*arc_function);
current_config = Some(Arc::clone(&cfg));
*config_state_clone.lock().await = Some(cfg);
} else {
let error_msg: String =
"Invalid configuration type - expected MatchConfig (Arc<dyn MatchFunction>)"
.to_string();
let error_arc: Arc<dyn Any + Send + Sync> = Arc::new(error_msg);
let _ = error_tx_clone.send(error_arc).await;
}
}
MessageType::Data => {
match ¤t_config {
Some(cfg) => {
let item_clone = item.clone();
match cfg.apply(item).await {
Ok(Some(branch_index)) => {
let port_name = format!("out_{}", branch_index);
if let Some(tx) = branch_txs.get(&port_name) {
let _ = tx.send(item_clone).await;
} else {
if let Some(tx) = branch_txs.get("default") {
let _ = tx.send(item_clone).await;
}
}
}
Ok(None) => {
if let Some(tx) = branch_txs.get("default") {
let _ = tx.send(item_clone).await;
}
}
Err(error_msg) => {
let error_arc: Arc<dyn Any + Send + Sync> = Arc::new(error_msg);
let _ = error_tx_clone.send(error_arc).await;
}
}
}
None => {
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_clone.send(error_arc).await;
}
}
}
}
}
});
let mut outputs = HashMap::new();
for (port, (_, rx)) in output_channels {
outputs.insert(
port.clone(),
Box::pin(ReceiverStream::new(rx))
as Pin<Box<dyn tokio_stream::Stream<Item = Arc<dyn Any + Send + Sync>> + Send>>,
);
}
Ok(outputs)
})
}
}