Skip to main content

wabot_feature_chat_controller/
handler.rs

1//! Inbound-message handler trait — the typed bridge between channels
2//! and macro-generated dispatch code.
3//!
4//! In wabot-ts the binding is "method on a class with a `@cmd()` (etc.)
5//! decorator." In Rust, `#[chat_controller]` walks the impl block and
6//! emits a free function per endpoint that:
7//!
8//! 1. Resolves the chat from the supplied connection.
9//! 2. Builds a per-message child container.
10//! 3. Registers the `Chat`, `ReceivedMessage`, plus any
11//!    `inject_instances` the channel provided.
12//! 4. Resolves the controller from the child container and calls the
13//!    user-defined method, awaiting the future.
14//!
15//! The trait below names the shape of that emitted function. Macro
16//! emissions just register one of these per channel; `run_chat_controllers`
17//! invokes them on every inbound message.
18
19use std::future::Future;
20use std::pin::Pin;
21use std::sync::Arc;
22
23use crate::channel::ChannelMessage;
24use crate::chat::Chat;
25use crate::types::ChatMessage;
26
27use wabot_core::injection::Container;
28
29/// What controllers receive — the channel's incoming message paired
30/// with a typed reply callable. Equivalent of TS's `IReceivedMessage`.
31///
32/// `reply` is bare `Arc<dyn Fn>` rather than the channel's `Box<…>`
33/// so it can be cloned into the child container.
34pub struct ReceivedMessage {
35    pub message: ChatMessage,
36    pub reply: ReplyHandle,
37}
38
39/// Type-erased reply callable, cloneable. Channels emit `Box<dyn Fn>`;
40/// the framework wraps it in this `Arc` once before handing to handlers.
41#[derive(Clone)]
42pub struct ReplyHandle(
43    Arc<
44        dyn Fn(ChatMessage) -> Pin<Box<dyn Future<Output = crate::channel::ReplyResult> + Send>>
45            + Send
46            + Sync,
47    >,
48);
49
50impl ReplyHandle {
51    pub fn new<F, Fut>(f: F) -> Self
52    where
53        F: Fn(ChatMessage) -> Fut + Send + Sync + 'static,
54        Fut: Future<Output = crate::channel::ReplyResult> + Send + 'static,
55    {
56        Self(Arc::new(move |m| Box::pin(f(m))))
57    }
58
59    pub async fn call(&self, msg: ChatMessage) -> crate::channel::ReplyResult {
60        (self.0)(msg).await
61    }
62}
63
64/// Generated by `#[chat_controller]` per `(channel, method)` pair.
65///
66/// The framework calls one of these for every inbound message that
67/// matched the channel's controller-method routing.
68pub type Dispatch = Arc<
69    dyn Fn(DispatchArgs) -> Pin<Box<dyn Future<Output = Result<(), DispatchError>> + Send>>
70        + Send
71        + Sync,
72>;
73
74pub struct DispatchArgs {
75    pub container: Container,
76    pub chat: Chat,
77    pub channel_message: ChannelMessage,
78}
79
80#[derive(Debug, thiserror::Error)]
81pub enum DispatchError {
82    #[error("controller method panicked: {0}")]
83    Panic(String),
84    #[error("controller method returned error: {0}")]
85    Handler(String),
86}