1pub mod access;
13pub mod capture;
14pub mod discord;
15pub mod discord_ws;
16pub mod github;
17pub mod leader;
18pub mod notification;
19pub mod routing;
20pub mod slack;
21pub mod stream;
22pub mod telegram;
23pub mod tmux;
24pub mod transport;
25
26use std::fmt;
27use std::fmt::Debug;
28use std::fmt::Formatter;
29use std::sync::{Mutex, PoisonError};
30
31use async_trait::async_trait;
32use serde::{Deserialize, Serialize};
33use tokio::sync::mpsc::Receiver;
34use tokio::task::{AbortHandle, JoinHandle};
35
36pub(crate) fn html_escape(s: &str) -> String {
38 s.replace('&', "&")
39 .replace('<', "<")
40 .replace('>', ">")
41}
42
43pub(crate) fn split_utf8(content: &str, max_bytes: usize) -> Vec<String> {
45 if content.len() <= max_bytes {
46 return vec![content.to_string()];
47 }
48
49 let mut chunks = Vec::new();
50 let mut start = 0;
51 let total = content.len();
52
53 while start < total {
54 let mut end = (start + max_bytes).min(total);
55 while end > start && !content.is_char_boundary(end) {
56 end -= 1;
57 }
58 if end == start {
59 if let Some(ch) = content[start..].chars().next() {
61 end = start + ch.len_utf8();
62 } else {
63 break;
64 }
65 }
66 chunks.push(content[start..end].to_string());
67 start = end;
68 }
69
70 chunks
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct IncomingMessage {
76 pub channel: String,
78 pub id: String,
80 pub thread_id: String,
82 pub author: String,
84 pub body: String,
86 pub timestamp: chrono::DateTime<chrono::Utc>,
88 #[serde(default)]
90 pub metadata: serde_json::Value,
91 #[serde(default)]
93 pub topic_id: Option<String>,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct OutgoingMessage {
99 pub thread_id: String,
101 pub body: String,
103 pub reply_to: Option<String>,
105 #[serde(default)]
107 pub metadata: serde_json::Value,
108 #[serde(default)]
110 pub topic_id: Option<String>,
111}
112
113#[derive(Debug, Clone)]
115pub struct OutputChunk {
116 pub content: String,
117 pub is_final: bool,
118}
119
120#[async_trait]
122pub trait Channel: Send + Sync {
123 fn name(&self) -> &str;
125
126 async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>>;
129
130 async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()>;
132
133 async fn ack_interaction(&self, _callback_query_id: &str) -> anyhow::Result<()> {
139 Ok(())
140 }
141
142 async fn health_check(&self) -> anyhow::Result<()>;
144
145 async fn stop(&self) {}
147}
148
149#[derive(Debug, Default)]
151pub(crate) struct Poller(Mutex<Option<AbortHandle>>);
152
153impl Poller {
154 pub(crate) fn set(&self, task: &JoinHandle<()>) {
156 let old = self
157 .0
158 .lock()
159 .unwrap_or_else(PoisonError::into_inner)
160 .replace(task.abort_handle());
161 if let Some(old) = old {
162 old.abort();
163 }
164 }
165
166 pub(crate) fn stop(&self) {
167 let task = self.0.lock().unwrap_or_else(PoisonError::into_inner).take();
168 if let Some(task) = task {
169 task.abort();
170 }
171 }
172}
173
174pub struct ChannelRegistry {
176 channels: Vec<Box<dyn Channel>>,
177}
178
179impl Debug for ChannelRegistry {
180 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
181 f.debug_list()
182 .entries(self.channels.iter().map(|c| c.name()))
183 .finish()
184 }
185}
186
187impl ChannelRegistry {
188 pub fn new() -> Self {
189 Self {
190 channels: Vec::new(),
191 }
192 }
193
194 pub fn register(&mut self, channel: Box<dyn Channel>) {
195 tracing::info!(channel = channel.name(), "registered channel");
196 self.channels.push(channel);
197 }
198
199 pub fn iter(&self) -> impl Iterator<Item = &dyn Channel> {
200 self.channels.iter().map(AsRef::as_ref)
201 }
202}