use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::effects::EffectAdmissionContext;
use crate::error::{Result, RustyError};
use crate::middleware::MiddlewareChain;
use crate::state::State;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NodeConfig {
pub thread_id: String,
pub step: usize,
pub resume: Option<Value>,
#[serde(default)]
pub extra: HashMap<String, Value>,
}
#[derive(Debug, Clone)]
pub struct NodeContext {
state: State,
config: NodeConfig,
middleware: MiddlewareChain,
effect_admission: Option<EffectAdmissionContext>,
}
impl NodeContext {
pub fn new(state: State, config: NodeConfig) -> Self {
Self {
state,
config,
middleware: MiddlewareChain::new(),
effect_admission: None,
}
}
pub fn state(&self) -> &State {
&self.state
}
pub fn config(&self) -> &NodeConfig {
&self.config
}
pub fn with_middleware(mut self, chain: MiddlewareChain) -> Self {
self.middleware = chain;
self
}
pub fn middleware(&self) -> &MiddlewareChain {
&self.middleware
}
pub fn effect_admission(&self) -> Option<&EffectAdmissionContext> {
self.effect_admission.as_ref()
}
pub fn with_effect_admission(mut self, context: EffectAdmissionContext) -> Self {
self.effect_admission = Some(context);
self
}
pub(crate) fn with_optional_effect_admission(
mut self,
context: Option<EffectAdmissionContext>,
) -> Self {
self.effect_admission = context;
self
}
pub fn thread_id(&self) -> &str {
&self.config.thread_id
}
pub fn step(&self) -> usize {
self.config.step
}
pub fn resume_value(&self) -> Option<&Value> {
self.config.resume.as_ref()
}
pub fn interrupt(&self, value: Value) -> RustyError {
RustyError::Interrupt { value }
}
}
#[derive(Debug, Clone, Default)]
pub struct NodeOutput {
pub updates: HashMap<String, Value>,
pub command: Option<Command>,
}
impl NodeOutput {
pub fn empty() -> Self {
Self::default()
}
pub fn update(channel: impl Into<String>, value: Value) -> Self {
let mut updates = HashMap::new();
updates.insert(channel.into(), value);
Self {
updates,
command: None,
}
}
pub fn updates(updates: HashMap<String, Value>) -> Self {
Self {
updates,
command: None,
}
}
pub fn from_updates(updates: HashMap<String, Value>) -> Self {
Self::updates(updates)
}
pub fn route(command: Command) -> Self {
Self {
updates: HashMap::new(),
command: Some(command),
}
}
pub fn with_command(mut self, command: Command) -> Self {
self.command = Some(command);
self
}
pub fn with_update(mut self, channel: impl Into<String>, value: Value) -> Self {
self.updates.insert(channel.into(), value);
self
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Command {
#[serde(default)]
pub goto: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resume: Option<Value>,
}
impl Command {
pub fn goto(node: impl Into<String>) -> Self {
Self {
goto: vec![node.into()],
resume: None,
}
}
pub fn goto_many<I, S>(nodes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
goto: nodes.into_iter().map(Into::into).collect(),
resume: None,
}
}
pub fn resume(value: Value) -> Self {
Self {
goto: Vec::new(),
resume: Some(value),
}
}
pub fn is_noop(&self) -> bool {
self.goto.is_empty() && self.resume.is_none()
}
}
#[async_trait]
pub trait Node: Send + Sync {
fn name(&self) -> &str {
"anonymous"
}
fn effect(&self) -> crate::record::Effect {
crate::record::Effect::Pure
}
async fn run(&self, ctx: NodeContext) -> Result<NodeOutput>;
}
#[async_trait]
impl<F, Fut> Node for F
where
F: Fn(NodeContext) -> Fut + Send + Sync,
Fut: Future<Output = Result<NodeOutput>> + Send,
{
async fn run(&self, ctx: NodeContext) -> Result<NodeOutput> {
(self)(ctx).await
}
}
#[async_trait]
impl Node for Arc<dyn Node> {
fn name(&self) -> &str {
self.as_ref().name()
}
async fn run(&self, ctx: NodeContext) -> Result<NodeOutput> {
self.as_ref().run(ctx).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[tokio::test]
async fn closure_implements_node() {
let node = |ctx: NodeContext| async move {
assert_eq!(ctx.thread_id(), "t1");
Ok(NodeOutput::update("x", json!(ctx.step())))
};
let ctx = NodeContext::new(
State::new(),
NodeConfig {
thread_id: "t1".into(),
step: 3,
resume: None,
extra: HashMap::new(),
},
);
let out = Node::run(&node, ctx).await.unwrap();
assert_eq!(out.updates.get("x"), Some(&json!(3)));
assert_eq!(node.name(), "anonymous");
}
#[tokio::test]
async fn interrupt_helper_produces_interrupt_error() {
let node = |ctx: NodeContext| async move {
match ctx.resume_value() {
Some(v) => Ok(NodeOutput::update("answer", v.clone())),
None => Err(ctx.interrupt(json!({"question": "approve?"}))),
}
};
let ctx = NodeContext::new(State::new(), NodeConfig::default());
let err = Node::run(&node, ctx).await.unwrap_err();
assert!(err.is_interrupt());
assert_eq!(
err.interrupt_value(),
Some(&json!({"question": "approve?"}))
);
let resumed = NodeContext::new(
State::new(),
NodeConfig {
resume: Some(json!(true)),
..NodeConfig::default()
},
);
let out = Node::run(&node, resumed).await.unwrap();
assert_eq!(out.updates.get("answer"), Some(&json!(true)));
}
}