use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use dashmap::DashMap;
use serde_json::json;
use crate::tenant::TenantContext;
const CATALOG_TTL: Duration = Duration::from_secs(5 * 60);
#[derive(Clone, Debug)]
pub struct FlowOperation {
pub flow_ref: String,
pub description: String,
pub parameters: serde_json::Value,
}
#[derive(Clone, Debug)]
pub struct FlowToolEntry {
pub description: String,
pub parameters: serde_json::Value,
}
pub trait FlowInvoker: Send + Sync {
fn list_flows(&self) -> Vec<FlowOperation>;
fn invoke<'a>(
&'a self,
flow_ref: &'a str,
args_json: &'a str,
) -> Pin<Box<dyn Future<Output = Result<serde_json::Value, String>> + Send + 'a>>;
fn invoke_interactive<'a>(
&'a self,
flow_ref: &'a str,
args_json: &'a str,
) -> Pin<Box<dyn Future<Output = Result<FlowInvokeOutcome, String>> + Send + 'a>> {
Box::pin(async move {
self.invoke(flow_ref, args_json)
.await
.map(FlowInvokeOutcome::Completed)
})
}
fn resume<'a>(
&'a self,
flow_ref: &'a str,
_snapshot: serde_json::Value,
_input: serde_json::Value,
) -> Pin<Box<dyn Future<Output = Result<FlowInvokeOutcome, String>> + Send + 'a>> {
Box::pin(async move { Err(format!("flow tool '{flow_ref}': resume not supported")) })
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum FlowInvokeOutcome {
Completed(serde_json::Value),
Waiting {
snapshot: serde_json::Value,
presentation: serde_json::Value,
},
}
pub struct FlowToolCatalog {
tools: HashMap<String, FlowToolEntry>,
invoker: Arc<dyn FlowInvoker>,
fetched_at: Instant,
}
impl FlowToolCatalog {
pub fn from_invoker(invoker: Arc<dyn FlowInvoker>) -> Self {
let mut tools = HashMap::new();
for op in invoker.list_flows() {
tools.insert(
op.flow_ref,
FlowToolEntry {
description: op.description,
parameters: op.parameters,
},
);
}
Self {
tools,
invoker,
fetched_at: Instant::now(),
}
}
pub fn tools(&self) -> impl Iterator<Item = (&String, &FlowToolEntry)> {
self.tools.iter()
}
pub fn len(&self) -> usize {
self.tools.len()
}
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
pub fn tool_entry(&self, flow_ref: &str) -> Option<&FlowToolEntry> {
self.tools.get(flow_ref)
}
pub async fn dispatch(&self, flow_ref: &str, args_json: &str) -> serde_json::Value {
if self.tool_entry(flow_ref).is_none() {
return json!({ "error": format!("unknown flow tool '{flow_ref}'") });
}
match self.invoker.invoke(flow_ref, args_json).await {
Ok(value) => value,
Err(e) => json!({ "error": e }),
}
}
pub async fn dispatch_interactive(&self, flow_ref: &str, args_json: &str) -> FlowInvokeOutcome {
if self.tool_entry(flow_ref).is_none() {
return FlowInvokeOutcome::Completed(
json!({ "error": format!("unknown flow tool '{flow_ref}'") }),
);
}
match self.invoker.invoke_interactive(flow_ref, args_json).await {
Ok(outcome) => outcome,
Err(e) => FlowInvokeOutcome::Completed(json!({ "error": e })),
}
}
pub async fn resume(
&self,
flow_ref: &str,
snapshot: serde_json::Value,
input: serde_json::Value,
) -> FlowInvokeOutcome {
match self.invoker.resume(flow_ref, snapshot, input).await {
Ok(outcome) => outcome,
Err(e) => FlowInvokeOutcome::Completed(json!({ "error": e })),
}
}
}
pub struct FlowToolSource {
invoker: Arc<dyn FlowInvoker>,
cache: DashMap<String, Arc<FlowToolCatalog>>,
}
impl FlowToolSource {
pub fn new(invoker: Arc<dyn FlowInvoker>) -> Self {
Self {
invoker,
cache: DashMap::new(),
}
}
fn cache_key(tenant: &TenantContext) -> String {
format!("{}:{}", tenant.tenant_id, tenant.env_id)
}
pub async fn catalog(&self, tenant: &TenantContext) -> Arc<FlowToolCatalog> {
let key = Self::cache_key(tenant);
if let Some(entry) = self.cache.get(&key) {
let snap = entry.value();
if snap.fetched_at.elapsed() < CATALOG_TTL {
return snap.clone();
}
}
let built = Arc::new(FlowToolCatalog::from_invoker(self.invoker.clone()));
self.cache.insert(key, built.clone());
built
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
use std::sync::Arc;
struct FakeInvoker;
impl FlowInvoker for FakeInvoker {
fn list_flows(&self) -> Vec<FlowOperation> {
vec![FlowOperation {
flow_ref: "lookup".into(),
description: "Look things up".into(),
parameters: serde_json::json!({ "type": "object" }),
}]
}
fn invoke<'a>(
&'a self,
flow_ref: &'a str,
args_json: &'a str,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send + 'a>,
> {
Box::pin(async move {
if flow_ref == "lookup" {
Ok(serde_json::json!({ "echoed": args_json }))
} else {
Err(format!("flow '{flow_ref}' not found"))
}
})
}
}
#[tokio::test]
async fn catalog_lists_and_dispatches_flows() {
let cat = FlowToolCatalog::from_invoker(Arc::new(FakeInvoker));
assert_eq!(cat.len(), 1);
let entry = cat.tool_entry("lookup").expect("entry");
assert_eq!(entry.description, "Look things up");
let out = cat.dispatch("lookup", "{\"q\":1}").await;
assert_eq!(out["echoed"], "{\"q\":1}");
}
#[tokio::test]
async fn dispatch_missing_flow_returns_error_value_not_err() {
let cat = FlowToolCatalog::from_invoker(Arc::new(FakeInvoker));
let out = cat.dispatch("nope", "{}").await;
assert!(
out.get("error").is_some(),
"missing flow must yield an error value"
);
}
#[tokio::test]
async fn source_caches_within_ttl_window() {
let source = FlowToolSource::new(Arc::new(FakeInvoker));
let tenant = TenantContext::new("acme", "prod");
let first = source.catalog(&tenant).await;
let second = source.catalog(&tenant).await;
assert!(
Arc::ptr_eq(&first, &second),
"second call must hit TTL cache"
);
}
#[tokio::test]
async fn cache_key_is_tenant_and_env() {
let source = FlowToolSource::new(Arc::new(FakeInvoker));
let prod = TenantContext::new("acme", "prod");
let staging = TenantContext::new("acme", "staging");
let prod_cat = source.catalog(&prod).await;
let staging_cat = source.catalog(&staging).await;
assert!(
!Arc::ptr_eq(&prod_cat, &staging_cat),
"different envs must have independent catalogs"
);
}
#[tokio::test]
async fn default_interactive_methods_wrap_invoke_and_refuse_resume() {
let cat = FlowToolCatalog::from_invoker(Arc::new(FakeInvoker));
let out = cat.dispatch_interactive("lookup", "{}").await;
assert_eq!(
out,
FlowInvokeOutcome::Completed(serde_json::json!({ "echoed": "{}" }))
);
let resumed = cat
.resume("lookup", serde_json::json!({}), serde_json::json!({}))
.await;
let v = match resumed {
FlowInvokeOutcome::Completed(v) => v,
FlowInvokeOutcome::Waiting { .. } => serde_json::Value::Null,
};
assert!(
v["error"]
.as_str()
.unwrap_or("")
.contains("resume not supported"),
"got {v}"
);
}
#[tokio::test]
async fn dispatch_unknown_flow_errors_without_invoking() {
let cat = FlowToolCatalog::from_invoker(Arc::new(FakeInvoker));
let out = cat.dispatch("no_such_flow", "{}").await;
assert!(
out.get("error").is_some(),
"unknown flow must yield an error value"
);
assert!(
out["error"].as_str().unwrap_or("").contains("no_such_flow"),
"error message must name the flow, got: {out}"
);
}
}