khive_runtime/
channel_send.rs1use std::collections::{btree_map::Entry, BTreeMap};
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::Arc;
8
9use serde_json::Value;
10
11use crate::{KhiveRuntime, NamespaceToken, RuntimeError, RuntimeResult};
12
13pub type ChannelSendFuture<'a> = Pin<Box<dyn Future<Output = RuntimeResult<Value>> + Send + 'a>>;
15
16pub trait ChannelSendRoute: Send + Sync {
27 fn send<'a>(
28 &'a self,
29 runtime: &'a KhiveRuntime,
30 token: &'a NamespaceToken,
31 params: Value,
32 ) -> ChannelSendFuture<'a>;
33}
34
35#[derive(Clone, Default)]
40pub struct ChannelSendRoutes {
41 routes: BTreeMap<String, Arc<dyn ChannelSendRoute>>,
42}
43
44impl fmt::Debug for ChannelSendRoutes {
45 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46 formatter
47 .debug_struct("ChannelSendRoutes")
48 .field("kinds", &self.routes.keys().collect::<Vec<_>>())
49 .finish()
50 }
51}
52
53impl ChannelSendRoutes {
54 pub fn is_empty(&self) -> bool {
56 self.routes.is_empty()
57 }
58
59 pub fn register(
62 &mut self,
63 kind: impl Into<String>,
64 route: Arc<dyn ChannelSendRoute>,
65 ) -> RuntimeResult<()> {
66 let kind = kind.into();
67 if kind.is_empty()
68 || kind.contains(':')
69 || kind.chars().any(|c| c.is_whitespace() || c.is_control())
70 {
71 return Err(RuntimeError::InvalidInput(
72 "channel send kind must be nonempty and contain no colon, whitespace or control characters"
73 .into(),
74 ));
75 }
76 if [
77 "khive1", "local", "email", "telegram", "actor", "lambda", "agent",
78 ]
79 .iter()
80 .any(|reserved| kind.eq_ignore_ascii_case(reserved))
81 {
82 return Err(RuntimeError::InvalidInput(format!(
83 "channel send kind {kind:?} is reserved"
84 )));
85 }
86 match self.routes.entry(kind) {
87 Entry::Vacant(entry) => {
88 entry.insert(route);
89 Ok(())
90 }
91 Entry::Occupied(entry) => Err(RuntimeError::InvalidInput(format!(
92 "channel send kind {:?} is already registered",
93 entry.key()
94 ))),
95 }
96 }
97
98 pub fn resolve(&self, recipient: &str) -> RuntimeResult<Option<Arc<dyn ChannelSendRoute>>> {
104 let Some((kind, _)) = recipient.trim().split_once(':') else {
105 return Ok(None);
106 };
107 let Some(route) = self.routes.get(kind) else {
108 return Ok(None);
109 };
110 if recipient != recipient.trim() {
111 return Err(RuntimeError::InvalidInput(
112 "registered channel address must not contain surrounding whitespace".into(),
113 ));
114 }
115 Ok(Some(Arc::clone(route)))
116 }
117}