1mod api;
4mod wire;
5
6use std::fmt;
7use std::sync::Arc;
8use std::time::Duration;
9
10use adk_core::{AdkError, ErrorCategory, ErrorComponent};
11use adk_kernel::KernelError;
12use adk_kernel::channels::{
13 ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
14 InboundOutcome, StopNotice,
15};
16use async_trait::async_trait;
17use chrono::Utc;
18use futures::{SinkExt, StreamExt};
19use serde_json::{Value, json};
20use tokio::sync::mpsc;
21use tokio_tungstenite::tungstenite::Message;
22
23use super::shared::{
24 ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
25 PressedCard, REQUEST_TIMEOUT, Taker, Update, checked_base, dispatch, kit_builder, notice_words,
26 patient, stopped_words,
27};
28use crate::error::{Result, SurfaceError};
29use api::SlackApi;
30use wire::Press;
31
32pub const SLACK_CHANNEL: &str = "slack";
35
36pub const SLACK: &str = "Slack";
38
39const DEFAULT_API_BASE: &str = "https://slack.com/api";
40const MIN_BACKOFF: Duration = Duration::from_secs(1);
41const MAX_BACKOFF: Duration = Duration::from_secs(60);
42const PING_EVERY: Duration = Duration::from_secs(30);
45const SILENT_FOR: Duration = Duration::from_secs(90);
46
47#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
62#[non_exhaustive]
63pub enum SlackError {
64 #[error(
66 "Slack refused a token: check SLACK_APP_TOKEN (an app-level token with \
67 `connections:write`) and SLACK_BOT_TOKEN (the bot token, `xoxb-`)"
68 )]
69 Unauthorized,
70 #[error("Slack asked to wait {retry_after} s before {method}: the app is sending too much")]
72 RateLimited {
73 method: String,
75 retry_after: u64,
77 },
78 #[error("Slack refused {method}: {error}")]
80 Refused {
81 method: String,
83 error: String,
85 },
86 #[error(
88 "Slack could not be reached for {method}: {reason}; check the network and the API address"
89 )]
90 Unreachable {
91 method: String,
93 reason: String,
95 },
96 #[error("Slack's answer to {method} could not be read: {reason}")]
98 InvalidResponse {
99 method: String,
101 reason: String,
103 },
104}
105
106impl SlackError {
107 pub fn code(&self) -> &'static str {
110 match self {
111 Self::Unauthorized => "surface.slack.unauthorized",
112 Self::RateLimited { .. } => "surface.slack.rate_limited",
113 Self::Refused { .. } => "surface.slack.refused",
114 Self::Unreachable { .. } => "surface.slack.unreachable",
115 Self::InvalidResponse { .. } => "surface.slack.invalid_response",
116 }
117 }
118}
119
120impl From<SlackError> for AdkError {
121 fn from(error: SlackError) -> Self {
122 let category = match &error {
123 SlackError::Unauthorized => ErrorCategory::Unauthorized,
124 SlackError::RateLimited { .. } => ErrorCategory::RateLimited,
125 SlackError::Refused { error, .. } => match error.as_str() {
126 "channel_not_found" | "not_in_channel" | "is_archived" | "cannot_dm_bot"
127 | "restricted_action" | "missing_scope" => ErrorCategory::Forbidden,
128 "invalid_arguments" | "invalid_blocks" | "msg_too_long" | "no_text" => {
129 ErrorCategory::InvalidInput
130 }
131 _ => ErrorCategory::Unavailable,
132 },
133 SlackError::Unreachable { .. } => ErrorCategory::Unavailable,
134 SlackError::InvalidResponse { .. } => ErrorCategory::Internal,
135 };
136 AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
137 .with_provider("slack")
138 }
139}
140
141impl From<SlackError> for KernelError {
142 fn from(error: SlackError) -> Self {
143 Self::Core(error.into())
144 }
145}
146
147pub type SlackConnection = ChannelConnection<SlackError>;
149
150pub struct SlackAdapterBuilder {
152 app_token: String,
153 bot_token: String,
154 api_base: String,
155 kit: Kit,
156}
157
158impl fmt::Debug for SlackAdapterBuilder {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 f.debug_struct("SlackAdapterBuilder")
161 .field("api_base", &self.api_base)
162 .finish_non_exhaustive()
163 }
164}
165
166impl SlackAdapterBuilder {
167 #[must_use]
170 pub fn api_base(mut self, url: impl Into<String>) -> Self {
171 self.api_base = url.into();
172 self
173 }
174
175 kit_builder!("Slack");
176
177 pub fn build(self) -> Result<SlackAdapter> {
184 let api = SlackApi::new(&self.api_base, &self.app_token, &self.bot_token)
185 .map_err(SurfaceError::Invalid)?;
186 Ok(SlackAdapter { inner: Arc::new(Inner { api, kit: self.kit }) })
187 }
188}
189
190#[derive(Clone)]
225pub struct SlackAdapter {
226 inner: Arc<Inner>,
227}
228
229struct Inner {
230 api: SlackApi,
231 kit: Kit,
232}
233
234impl fmt::Debug for SlackAdapter {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 f.debug_struct("SlackAdapter").field("channel", &SLACK_CHANNEL).finish_non_exhaustive()
237 }
238}
239
240pub(crate) struct Carried {
242 press: Option<Press>,
244 files: Vec<crate::channels::media::FileRef>,
246}
247
248enum Ended {
250 Reconnect,
252 Failed(String),
254}
255
256impl SlackAdapter {
257 pub fn builder(
260 app_token: impl Into<String>,
261 bot_token: impl Into<String>,
262 ) -> SlackAdapterBuilder {
263 SlackAdapterBuilder {
264 app_token: app_token.into(),
265 bot_token: bot_token.into(),
266 api_base: DEFAULT_API_BASE.to_string(),
267 kit: Kit::default(),
268 }
269 }
270
271 pub fn inbound(&self, envelope: &Value) -> Option<ChannelInbound> {
294 wire::parse(envelope).inbound
295 }
296
297 pub fn start(&self, gateway: ChannelGateway) -> SlackConnection {
307 let adapter = self.clone();
308 ChannelConnection::spawn(async move { adapter.run(gateway).await })
309 }
310
311 async fn run(&self, gateway: ChannelGateway) -> std::result::Result<(), SlackError> {
312 let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
313 let _dispatcher = AbortOnDrop(task);
314 let mut backoff = MIN_BACKOFF;
315 loop {
316 let url = match self.inner.api.open_socket().await {
317 Ok(url) => url,
318 Err(SlackError::Unauthorized) => return Err(SlackError::Unauthorized),
319 Err(error) => {
320 tracing::warn!(error = %error, "the slack socket could not be opened; retrying");
321 tokio::time::sleep(backoff).await;
322 backoff = (backoff * 2).min(MAX_BACKOFF);
323 continue;
324 }
325 };
326 match self.serve(&url, &sender).await {
327 Ended::Reconnect => backoff = MIN_BACKOFF,
328 Ended::Failed(reason) => {
329 tracing::warn!(reason = %reason, "the slack socket ended; connecting again");
330 tokio::time::sleep(backoff).await;
331 backoff = (backoff * 2).min(MAX_BACKOFF);
332 }
333 }
334 }
335 }
336
337 async fn serve(&self, url: &str, sender: &mpsc::UnboundedSender<Update<Carried>>) -> Ended {
339 if let Err(reason) = checked_base(url, "the Slack socket address", true) {
340 return Ended::Failed(reason);
341 }
342 adk_core::ensure_crypto_provider();
343 let connect = tokio_tungstenite::connect_async(url);
344 let mut socket = match tokio::time::timeout(REQUEST_TIMEOUT, connect).await {
345 Ok(Ok((socket, _))) => socket,
346 Ok(Err(error)) => return Ended::Failed(error.to_string()),
347 Err(_) => return Ended::Failed("the socket did not open in time".into()),
348 };
349 let mut ping = tokio::time::interval(PING_EVERY);
350 ping.tick().await;
351 let mut heard = tokio::time::Instant::now();
352 loop {
353 let frame = tokio::select! {
354 _ = ping.tick() => {
355 if heard.elapsed() > SILENT_FOR {
356 return Ended::Failed("the socket went quiet".into());
357 }
358 if let Err(error) = socket.send(Message::Ping(Vec::new().into())).await {
359 return Ended::Failed(error.to_string());
360 }
361 continue;
362 }
363 frame = socket.next() => frame,
364 };
365 heard = tokio::time::Instant::now();
366 let text = match frame {
367 Some(Ok(Message::Text(text))) => text,
368 Some(Ok(Message::Close(_))) | None => {
369 return Ended::Failed("the socket closed".into());
370 }
371 Some(Ok(_)) => continue,
372 Some(Err(error)) => return Ended::Failed(error.to_string()),
373 };
374 let Ok(envelope) = serde_json::from_str::<Value>(text.as_str()) else { continue };
375 match envelope["type"].as_str() {
376 Some("hello") => continue,
377 Some("disconnect") => return Ended::Reconnect,
378 _ => {}
379 }
380 if let Some(id) = envelope["envelope_id"].as_str() {
382 let ack = json!({ "envelope_id": id }).to_string();
383 if let Err(error) = socket.send(Message::Text(ack.into())).await {
384 return Ended::Failed(error.to_string());
385 }
386 }
387 let parsed = wire::parse(&envelope);
388 if parsed.inbound.is_some()
389 && sender
390 .send(Update {
391 inbound: parsed.inbound,
392 press: Some(Carried { press: parsed.press, files: parsed.files }),
393 })
394 .is_err()
395 {
396 return Ended::Failed("the adapter stopped".into());
397 }
398 }
399 }
400
401 async fn clear_buttons(&self, press: &Press) {
403 let Some((channel, ts)) = &press.card else { return };
404 let mut body = wire::answered(press);
405 body["channel"] = json!(channel);
406 body["ts"] = json!(ts);
407 if let Err(error) = self.inner.api.call("chat.update", &body, true).await {
408 tracing::debug!(error = %error, "an answered card's buttons could not be removed");
409 }
410 }
411
412 async fn post(&self, thread: &str, mut body: Value) -> adk_kernel::Result<()> {
413 body["channel"] = json!(thread);
414 let patient = patient(SLACK_CHANNEL, thread);
417 self.inner.api.call("chat.postMessage", &body, patient).await?;
418 Ok(())
419 }
420}
421
422#[async_trait]
423impl Taker for SlackAdapter {
424 type Press = Carried;
425
426 fn channel_name(&self) -> &'static str {
427 SLACK_CHANNEL
428 }
429
430 async fn take(
432 &self,
433 gateway: &ChannelGateway,
434 update: &Update<Carried>,
435 paired: bool,
436 ) -> adk_kernel::Result<()> {
437 let Some(mut inbound) = update.inbound.clone() else { return Ok(()) };
438 let carried = update.press.as_ref();
439 let press = carried.and_then(|carried| carried.press.as_ref());
440 let files = carried.map_or(&[][..], |carried| carried.files.as_slice());
443 if paired && !files.is_empty() {
444 let api = &self.inner.api;
445 let attachments =
446 crate::channels::media::fetch_all(files, |file| api.download(file)).await;
447 inbound = inbound.with_attachments(attachments);
448 }
449 let card = match (&inbound.body, press) {
450 (InboundBody::Answer { decision, .. }, Some(press)) => Some(PressedCard {
451 card: press.card.as_ref().map(|(_, ts)| ts.clone()),
452 decision: decision.clone(),
453 }),
454 _ => None,
455 };
456 let handling = Handling::of(SLACK_CHANNEL, gateway, &inbound, paired, card);
457 let outcome = HANDLING.scope(handling, gateway.receive(inbound)).await;
458 let Some(press) = press else { return outcome.map(drop) };
459 if matches!(
460 outcome?,
461 InboundOutcome::Decided { .. }
462 | InboundOutcome::AlreadyDecided { .. }
463 | InboundOutcome::DecisionChanged { .. }
464 | InboundOutcome::DecisionRefused { .. }
465 ) {
466 self.clear_buttons(press).await;
467 }
468 Ok(())
469 }
470
471 async fn not_taken(&self, update: &Update<Carried>) {
472 let Some(inbound) = &update.inbound else { return };
473 let pressed = update.press.as_ref().is_some_and(|carried| carried.press.is_some());
474 let text = if pressed { ANSWER_NOT_TAKEN } else { MESSAGE_NOT_TAKEN };
475 for body in wire::plain(text) {
476 if let Err(error) = self.post(&inbound.thread, body).await {
477 tracing::debug!(error = %error, "a person could not be told their message was not taken");
478 }
479 }
480 }
481}
482
483#[async_trait]
484impl ChannelSink for SlackAdapter {
485 fn channel(&self) -> &str {
486 SLACK_CHANNEL
487 }
488
489 async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
490 for body in wire::plain(text) {
491 self.post(thread, body).await?;
492 }
493 Ok(())
494 }
495
496 async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
497 let (heading, card) = self.inner.kit.prepare(card).await;
498 self.post(thread, wire::card(&card, &heading, self.inner.kit.offset)).await
499 }
500
501 async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
502 self.post(thread, wire::message(&stopped_words(notice))).await
503 }
504
505 async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
508 self.inner.kit.before_notice(SLACK_CHANNEL, SLACK, thread, notice).await;
509 let words = notice_words(notice, self.inner.kit.offset, Utc::now(), false);
510 self.post(thread, wire::message(&words)).await
511 }
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517
518 #[test]
519 fn errors_say_what_to_do_and_keep_their_category() {
520 let error: AdkError = SlackError::Unauthorized.into();
521 assert_eq!(
522 (error.code, error.category),
523 ("surface.slack.unauthorized", ErrorCategory::Unauthorized)
524 );
525 let refused = SlackError::Refused {
526 method: "chat.postMessage".into(),
527 error: "not_in_channel".into(),
528 };
529 assert_eq!(AdkError::from(refused).category, ErrorCategory::Forbidden);
530 let limited =
531 SlackError::RateLimited { method: "chat.postMessage".into(), retry_after: 90 };
532 assert!(AdkError::from(limited).is_retryable());
533 }
534
535 #[test]
536 fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
537 let error = SlackAdapter::builder("xapp-secret", "xoxb-secret")
538 .api_base("http://example.com/api")
539 .build()
540 .unwrap_err();
541 assert_eq!(error.code(), "surface.invalid");
542 assert!(!error.to_string().contains("secret"), "{error}");
543 assert!(SlackAdapter::builder("", "xoxb-1").build().is_err());
544 assert!(SlackAdapter::builder("xapp-1", "xoxb 1").build().is_err());
545 let adapter = SlackAdapter::builder("xapp-secret", "xoxb-secret").build().unwrap();
546 assert!(!format!("{adapter:?}").contains("secret"));
547 assert_eq!(ChannelSink::channel(&adapter), "slack");
548 }
549}