Skip to main content

adk_kernel/channels/
testing.rs

1//! The in-memory test channel (spec 3.3 §10 K1).
2
3use std::collections::BTreeMap;
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Mutex, PoisonError};
6
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9
10use super::{ChannelAnswer, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, StopNotice};
11use crate::error::Result;
12
13/// One thing a channel sent to a thread (spec 3.3 §10 K1).
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
16#[non_exhaustive]
17pub enum Delivered {
18    /// An agent's reply or other text.
19    Message {
20        /// The text.
21        text: String,
22    },
23    /// A decision card.
24    Decision {
25        /// The card.
26        card: DecisionCard,
27    },
28    /// The notice that everything was stopped.
29    Stopped {
30        /// The notice.
31        notice: StopNotice,
32    },
33    /// A notice.
34    Notice {
35        /// The notice.
36        notice: ChannelNotice,
37    },
38}
39
40/// A chat channel in process memory (spec 3.3 §10 K1): a [`ChannelSink`] that keeps what it
41/// is sent per thread, and makes the [`ChannelInbound`] values a platform adapter would, for
42/// tests and the contract suite.
43///
44/// It offers a card's [`answers`](DecisionCard::answers) and nothing else, as every adapter
45/// must: [`press`](Self::press) of an answer the card does not offer is `None`.
46///
47/// # Example
48///
49/// ```rust
50/// use adk_kernel::channels::{ChannelSink, InMemoryChannel};
51///
52/// # #[tokio::main(flavor = "current_thread")]
53/// # async fn main() -> adk_kernel::Result<()> {
54/// let chat = InMemoryChannel::new("chat");
55/// chat.send_message("t1", "hello").await?;
56/// assert_eq!(chat.messages("t1"), ["hello"]);
57/// let inbound = chat.text("ana", "t1", "stop all");
58/// assert_eq!(inbound.channel, "chat");
59/// # Ok(())
60/// # }
61/// ```
62#[derive(Debug)]
63pub struct InMemoryChannel {
64    name: String,
65    threads: Mutex<BTreeMap<String, Vec<Delivered>>>,
66    next_message: AtomicU64,
67}
68
69impl InMemoryChannel {
70    /// A channel named `name` with nothing sent.
71    pub fn new(name: impl Into<String>) -> Self {
72        Self { name: name.into(), threads: Mutex::default(), next_message: AtomicU64::new(1) }
73    }
74
75    fn push(&self, thread: &str, delivered: Delivered) {
76        self.threads
77            .lock()
78            .unwrap_or_else(PoisonError::into_inner)
79            .entry(thread.to_string())
80            .or_default()
81            .push(delivered);
82    }
83
84    /// Everything sent to `thread`, in order.
85    pub fn delivered(&self, thread: &str) -> Vec<Delivered> {
86        self.threads
87            .lock()
88            .unwrap_or_else(PoisonError::into_inner)
89            .get(thread)
90            .cloned()
91            .unwrap_or_default()
92    }
93
94    /// Everything sent to `thread` as the JSON that left the machine, one value per line.
95    pub fn wire(&self, thread: &str) -> String {
96        self.delivered(thread)
97            .iter()
98            .map(|delivered| serde_json::to_string(delivered).unwrap_or_default())
99            .collect::<Vec<_>>()
100            .join("\n")
101    }
102
103    /// The texts sent to `thread`.
104    pub fn messages(&self, thread: &str) -> Vec<String> {
105        self.delivered(thread)
106            .into_iter()
107            .filter_map(|delivered| match delivered {
108                Delivered::Message { text } => Some(text),
109                _ => None,
110            })
111            .collect()
112    }
113
114    /// The notices sent to `thread`.
115    pub fn notices(&self, thread: &str) -> Vec<ChannelNotice> {
116        self.delivered(thread)
117            .into_iter()
118            .filter_map(|delivered| match delivered {
119                Delivered::Notice { notice } => Some(notice),
120                _ => None,
121            })
122            .collect()
123    }
124
125    /// The last decision card sent to `thread`.
126    pub fn last_card(&self, thread: &str) -> Option<DecisionCard> {
127        self.delivered(thread).into_iter().rev().find_map(|delivered| match delivered {
128            Delivered::Decision { card } => Some(card),
129            _ => None,
130        })
131    }
132
133    /// The last pairing code sent to `thread`.
134    pub fn pairing_code(&self, thread: &str) -> Option<String> {
135        self.notices(thread).into_iter().rev().find_map(|notice| match notice {
136            ChannelNotice::PairingCode { code, .. } => Some(code),
137            _ => None,
138        })
139    }
140
141    /// Forgets what was sent to `thread`.
142    pub fn clear(&self, thread: &str) {
143        self.threads.lock().unwrap_or_else(PoisonError::into_inner).remove(thread);
144    }
145
146    fn message_id(&self) -> String {
147        format!("m{}", self.next_message.fetch_add(1, Ordering::SeqCst))
148    }
149
150    /// `account` typing `text` in `thread`, as a new message.
151    pub fn text(&self, account: &str, thread: &str, text: &str) -> ChannelInbound {
152        ChannelInbound::text(&self.name, account, thread, self.message_id(), text)
153    }
154
155    /// `account` pressing `answer` on `card` in `thread`, or `None` when the card does not
156    /// offer it.
157    pub fn press(
158        &self,
159        account: &str,
160        thread: &str,
161        card: &DecisionCard,
162        answer: ChannelAnswer,
163    ) -> Option<ChannelInbound> {
164        card.answers.contains(&answer).then(|| {
165            ChannelInbound::answer(&self.name, account, thread, self.message_id(), card, answer)
166        })
167    }
168}
169
170#[async_trait]
171impl ChannelSink for InMemoryChannel {
172    fn channel(&self) -> &str {
173        &self.name
174    }
175
176    async fn send_message(&self, thread: &str, text: &str) -> Result<()> {
177        self.push(thread, Delivered::Message { text: text.to_string() });
178        Ok(())
179    }
180
181    async fn send_decision(&self, thread: &str, card: &DecisionCard) -> Result<()> {
182        self.push(thread, Delivered::Decision { card: card.clone() });
183        Ok(())
184    }
185
186    async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> Result<()> {
187        self.push(thread, Delivered::Stopped { notice: notice.clone() });
188        Ok(())
189    }
190
191    async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> Result<()> {
192        self.push(thread, Delivered::Notice { notice: notice.clone() });
193        Ok(())
194    }
195}