#![allow(clippy::type_complexity)]
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::sync::mpsc;
use tokio_stream::{StreamExt, wrappers::ReceiverStream};
#[derive(Debug, PartialEq)]
enum InputPort {
In,
Signal,
}
pub struct ContinueNode {
pub(crate) base: BaseNode,
}
impl ContinueNode {
pub fn new(name: String) -> Self {
Self {
base: BaseNode::new(
name,
vec![
"configuration".to_string(),
"in".to_string(),
"signal".to_string(),
],
vec!["out".to_string(), "error".to_string()],
),
}
}
}
#[async_trait]
impl Node for ContinueNode {
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 signal_stream = inputs.remove("signal").ok_or("Missing 'signal' input")?;
let (out_tx, out_rx) = mpsc::channel(10);
let (error_tx, error_rx) = mpsc::channel(10);
let in_stream = in_stream.map(|item| (InputPort::In, item));
let signal_stream = signal_stream.map(|item| (InputPort::Signal, item));
let out_tx_clone = out_tx.clone();
let _error_tx_clone = error_tx.clone();
tokio::spawn(async move {
let mut in_stream = in_stream;
let mut signal_stream = signal_stream;
let mut skip_next = false;
loop {
tokio::select! {
signal_result = signal_stream.next() => {
if let Some(_signal_item) = signal_result {
skip_next = true;
}
}
in_result = in_stream.next() => {
match in_result {
Some((_, item)) => {
if skip_next {
skip_next = false; } else {
let _ = out_tx_clone.send(item).await;
}
}
None => {
if signal_stream.next().await.is_none() {
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(
"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)
})
}
}