mod api;
mod wire;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use adk_core::{AdkError, ErrorCategory, ErrorComponent};
use adk_kernel::KernelError;
use adk_kernel::channels::{
ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
InboundOutcome, StopNotice,
};
use async_trait::async_trait;
use chrono::Utc;
use futures::{SinkExt, StreamExt};
use serde_json::{Value, json};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
use super::shared::{
ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
PressedCard, REQUEST_TIMEOUT, Taker, Update, checked_base, dispatch, kit_builder, notice_words,
patient, stopped_words,
};
use crate::error::{Result, SurfaceError};
use api::SlackApi;
use wire::Press;
pub const SLACK_CHANNEL: &str = "slack";
pub const SLACK: &str = "Slack";
const DEFAULT_API_BASE: &str = "https://slack.com/api";
const MIN_BACKOFF: Duration = Duration::from_secs(1);
const MAX_BACKOFF: Duration = Duration::from_secs(60);
const PING_EVERY: Duration = Duration::from_secs(30);
const SILENT_FOR: Duration = Duration::from_secs(90);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SlackError {
#[error(
"Slack refused a token: check SLACK_APP_TOKEN (an app-level token with \
`connections:write`) and SLACK_BOT_TOKEN (the bot token, `xoxb-`)"
)]
Unauthorized,
#[error("Slack asked to wait {retry_after} s before {method}: the app is sending too much")]
RateLimited {
method: String,
retry_after: u64,
},
#[error("Slack refused {method}: {error}")]
Refused {
method: String,
error: String,
},
#[error(
"Slack could not be reached for {method}: {reason}; check the network and the API address"
)]
Unreachable {
method: String,
reason: String,
},
#[error("Slack's answer to {method} could not be read: {reason}")]
InvalidResponse {
method: String,
reason: String,
},
}
impl SlackError {
pub fn code(&self) -> &'static str {
match self {
Self::Unauthorized => "surface.slack.unauthorized",
Self::RateLimited { .. } => "surface.slack.rate_limited",
Self::Refused { .. } => "surface.slack.refused",
Self::Unreachable { .. } => "surface.slack.unreachable",
Self::InvalidResponse { .. } => "surface.slack.invalid_response",
}
}
}
impl From<SlackError> for AdkError {
fn from(error: SlackError) -> Self {
let category = match &error {
SlackError::Unauthorized => ErrorCategory::Unauthorized,
SlackError::RateLimited { .. } => ErrorCategory::RateLimited,
SlackError::Refused { error, .. } => match error.as_str() {
"channel_not_found" | "not_in_channel" | "is_archived" | "cannot_dm_bot"
| "restricted_action" | "missing_scope" => ErrorCategory::Forbidden,
"invalid_arguments" | "invalid_blocks" | "msg_too_long" | "no_text" => {
ErrorCategory::InvalidInput
}
_ => ErrorCategory::Unavailable,
},
SlackError::Unreachable { .. } => ErrorCategory::Unavailable,
SlackError::InvalidResponse { .. } => ErrorCategory::Internal,
};
AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
.with_provider("slack")
}
}
impl From<SlackError> for KernelError {
fn from(error: SlackError) -> Self {
Self::Core(error.into())
}
}
pub type SlackConnection = ChannelConnection<SlackError>;
pub struct SlackAdapterBuilder {
app_token: String,
bot_token: String,
api_base: String,
kit: Kit,
}
impl fmt::Debug for SlackAdapterBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SlackAdapterBuilder")
.field("api_base", &self.api_base)
.finish_non_exhaustive()
}
}
impl SlackAdapterBuilder {
#[must_use]
pub fn api_base(mut self, url: impl Into<String>) -> Self {
self.api_base = url.into();
self
}
kit_builder!("Slack");
pub fn build(self) -> Result<SlackAdapter> {
let api = SlackApi::new(&self.api_base, &self.app_token, &self.bot_token)
.map_err(SurfaceError::Invalid)?;
Ok(SlackAdapter { inner: Arc::new(Inner { api, kit: self.kit }) })
}
}
#[derive(Clone)]
pub struct SlackAdapter {
inner: Arc<Inner>,
}
struct Inner {
api: SlackApi,
kit: Kit,
}
impl fmt::Debug for SlackAdapter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SlackAdapter").field("channel", &SLACK_CHANNEL).finish_non_exhaustive()
}
}
pub(crate) struct Carried {
press: Option<Press>,
files: Vec<crate::channels::media::FileRef>,
}
enum Ended {
Reconnect,
Failed(String),
}
impl SlackAdapter {
pub fn builder(
app_token: impl Into<String>,
bot_token: impl Into<String>,
) -> SlackAdapterBuilder {
SlackAdapterBuilder {
app_token: app_token.into(),
bot_token: bot_token.into(),
api_base: DEFAULT_API_BASE.to_string(),
kit: Kit::default(),
}
}
pub fn inbound(&self, envelope: &Value) -> Option<ChannelInbound> {
wire::parse(envelope).inbound
}
pub fn start(&self, gateway: ChannelGateway) -> SlackConnection {
let adapter = self.clone();
ChannelConnection::spawn(async move { adapter.run(gateway).await })
}
async fn run(&self, gateway: ChannelGateway) -> std::result::Result<(), SlackError> {
let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
let _dispatcher = AbortOnDrop(task);
let mut backoff = MIN_BACKOFF;
loop {
let url = match self.inner.api.open_socket().await {
Ok(url) => url,
Err(SlackError::Unauthorized) => return Err(SlackError::Unauthorized),
Err(error) => {
tracing::warn!(error = %error, "the slack socket could not be opened; retrying");
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(MAX_BACKOFF);
continue;
}
};
match self.serve(&url, &sender).await {
Ended::Reconnect => backoff = MIN_BACKOFF,
Ended::Failed(reason) => {
tracing::warn!(reason = %reason, "the slack socket ended; connecting again");
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(MAX_BACKOFF);
}
}
}
}
async fn serve(&self, url: &str, sender: &mpsc::UnboundedSender<Update<Carried>>) -> Ended {
if let Err(reason) = checked_base(url, "the Slack socket address", true) {
return Ended::Failed(reason);
}
adk_core::ensure_crypto_provider();
let connect = tokio_tungstenite::connect_async(url);
let mut socket = match tokio::time::timeout(REQUEST_TIMEOUT, connect).await {
Ok(Ok((socket, _))) => socket,
Ok(Err(error)) => return Ended::Failed(error.to_string()),
Err(_) => return Ended::Failed("the socket did not open in time".into()),
};
let mut ping = tokio::time::interval(PING_EVERY);
ping.tick().await;
let mut heard = tokio::time::Instant::now();
loop {
let frame = tokio::select! {
_ = ping.tick() => {
if heard.elapsed() > SILENT_FOR {
return Ended::Failed("the socket went quiet".into());
}
if let Err(error) = socket.send(Message::Ping(Vec::new().into())).await {
return Ended::Failed(error.to_string());
}
continue;
}
frame = socket.next() => frame,
};
heard = tokio::time::Instant::now();
let text = match frame {
Some(Ok(Message::Text(text))) => text,
Some(Ok(Message::Close(_))) | None => {
return Ended::Failed("the socket closed".into());
}
Some(Ok(_)) => continue,
Some(Err(error)) => return Ended::Failed(error.to_string()),
};
let Ok(envelope) = serde_json::from_str::<Value>(text.as_str()) else { continue };
match envelope["type"].as_str() {
Some("hello") => continue,
Some("disconnect") => return Ended::Reconnect,
_ => {}
}
if let Some(id) = envelope["envelope_id"].as_str() {
let ack = json!({ "envelope_id": id }).to_string();
if let Err(error) = socket.send(Message::Text(ack.into())).await {
return Ended::Failed(error.to_string());
}
}
let parsed = wire::parse(&envelope);
if parsed.inbound.is_some()
&& sender
.send(Update {
inbound: parsed.inbound,
press: Some(Carried { press: parsed.press, files: parsed.files }),
})
.is_err()
{
return Ended::Failed("the adapter stopped".into());
}
}
}
async fn clear_buttons(&self, press: &Press) {
let Some((channel, ts)) = &press.card else { return };
let mut body = wire::answered(press);
body["channel"] = json!(channel);
body["ts"] = json!(ts);
if let Err(error) = self.inner.api.call("chat.update", &body, true).await {
tracing::debug!(error = %error, "an answered card's buttons could not be removed");
}
}
async fn post(&self, thread: &str, mut body: Value) -> adk_kernel::Result<()> {
body["channel"] = json!(thread);
let patient = patient(SLACK_CHANNEL, thread);
self.inner.api.call("chat.postMessage", &body, patient).await?;
Ok(())
}
}
#[async_trait]
impl Taker for SlackAdapter {
type Press = Carried;
fn channel_name(&self) -> &'static str {
SLACK_CHANNEL
}
async fn take(
&self,
gateway: &ChannelGateway,
update: &Update<Carried>,
paired: bool,
) -> adk_kernel::Result<()> {
let Some(mut inbound) = update.inbound.clone() else { return Ok(()) };
let carried = update.press.as_ref();
let press = carried.and_then(|carried| carried.press.as_ref());
let files = carried.map_or(&[][..], |carried| carried.files.as_slice());
if paired && !files.is_empty() {
let api = &self.inner.api;
let attachments =
crate::channels::media::fetch_all(files, |file| api.download(file)).await;
inbound = inbound.with_attachments(attachments);
}
let card = match (&inbound.body, press) {
(InboundBody::Answer { decision, .. }, Some(press)) => Some(PressedCard {
card: press.card.as_ref().map(|(_, ts)| ts.clone()),
decision: decision.clone(),
}),
_ => None,
};
let handling = Handling::of(SLACK_CHANNEL, gateway, &inbound, paired, card);
let outcome = HANDLING.scope(handling, gateway.receive(inbound)).await;
let Some(press) = press else { return outcome.map(drop) };
if matches!(
outcome?,
InboundOutcome::Decided { .. }
| InboundOutcome::AlreadyDecided { .. }
| InboundOutcome::DecisionChanged { .. }
| InboundOutcome::DecisionRefused { .. }
) {
self.clear_buttons(press).await;
}
Ok(())
}
async fn not_taken(&self, update: &Update<Carried>) {
let Some(inbound) = &update.inbound else { return };
let pressed = update.press.as_ref().is_some_and(|carried| carried.press.is_some());
let text = if pressed { ANSWER_NOT_TAKEN } else { MESSAGE_NOT_TAKEN };
for body in wire::plain(text) {
if let Err(error) = self.post(&inbound.thread, body).await {
tracing::debug!(error = %error, "a person could not be told their message was not taken");
}
}
}
}
#[async_trait]
impl ChannelSink for SlackAdapter {
fn channel(&self) -> &str {
SLACK_CHANNEL
}
async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
for body in wire::plain(text) {
self.post(thread, body).await?;
}
Ok(())
}
async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
let (heading, card) = self.inner.kit.prepare(card).await;
self.post(thread, wire::card(&card, &heading, self.inner.kit.offset)).await
}
async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
self.post(thread, wire::message(&stopped_words(notice))).await
}
async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
self.inner.kit.before_notice(SLACK_CHANNEL, SLACK, thread, notice).await;
let words = notice_words(notice, self.inner.kit.offset, Utc::now(), false);
self.post(thread, wire::message(&words)).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn errors_say_what_to_do_and_keep_their_category() {
let error: AdkError = SlackError::Unauthorized.into();
assert_eq!(
(error.code, error.category),
("surface.slack.unauthorized", ErrorCategory::Unauthorized)
);
let refused = SlackError::Refused {
method: "chat.postMessage".into(),
error: "not_in_channel".into(),
};
assert_eq!(AdkError::from(refused).category, ErrorCategory::Forbidden);
let limited =
SlackError::RateLimited { method: "chat.postMessage".into(), retry_after: 90 };
assert!(AdkError::from(limited).is_retryable());
}
#[test]
fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
let error = SlackAdapter::builder("xapp-secret", "xoxb-secret")
.api_base("http://example.com/api")
.build()
.unwrap_err();
assert_eq!(error.code(), "surface.invalid");
assert!(!error.to_string().contains("secret"), "{error}");
assert!(SlackAdapter::builder("", "xoxb-1").build().is_err());
assert!(SlackAdapter::builder("xapp-1", "xoxb 1").build().is_err());
let adapter = SlackAdapter::builder("xapp-secret", "xoxb-secret").build().unwrap();
assert!(!format!("{adapter:?}").contains("secret"));
assert_eq!(ChannelSink::channel(&adapter), "slack");
}
}