Skip to main content

khive_runtime/
channel_send.rs

1//! Explicit host-supplied routes for custom `comm.send` address kinds.
2
3use 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
13/// The complete result of a custom send operation.
14pub type ChannelSendFuture<'a> = Pin<Box<dyn Future<Output = RuntimeResult<Value>> + Send + 'a>>;
15
16/// A trusted host component's complete custom send policy.
17///
18/// The comm pack validates its ordinary send parameters before calling this route.
19/// `params` retains the caller's original parsed values, including optional-field
20/// presence and address spelling. The runtime and namespace token are the same
21/// ones authorized for the dispatch. The route owns persistence, replay handling,
22/// attachments, and transport submission; no legacy message write or fallback
23/// follows its result. A supplied idempotency key still passes the shared key
24/// validation before the route is called.
25/// Installing a route does not start a channel or a resident task.
26pub 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/// Per-runtime routes, keyed by an exact custom address kind.
36///
37/// Register before runtime construction. Cloning copies the registration map and
38/// shares its callbacks; later registrations do not alter an existing clone.
39#[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    /// Whether no route is registered.
55    pub fn is_empty(&self) -> bool {
56        self.routes.is_empty()
57    }
58
59    /// Register an exact kind without replacing a route, a built-in transport,
60    /// or a local actor address kind.
61    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    /// Select only an explicitly registered `kind:address` route.
99    ///
100    /// Matching is exact. Surrounding whitespace on a registered address is a
101    /// refusal, not an invitation to normalize it or fall back to a local write.
102    /// Unregistered recipients retain the comm pack's existing handling.
103    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}