1mod api;
5mod wire;
6
7use std::collections::{HashMap, HashSet, VecDeque};
8use std::fmt;
9use std::sync::{Arc, Mutex, PoisonError};
10use std::time::Duration;
11
12use adk_core::{AdkError, ErrorCategory, ErrorComponent};
13use adk_kernel::KernelError;
14use adk_kernel::channels::{
15 ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
16 StopNotice,
17};
18use async_trait::async_trait;
19use chrono::Utc;
20use reqwest::Method;
21use serde_json::{Value, json};
22use tokio::sync::mpsc;
23
24use super::shared::{
25 ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
26 PressedCard, Taker, Update, dispatch, kit_builder, notice_words, paired_binding, patient,
27 stopped_words,
28};
29use crate::error::{Result, SurfaceError};
30use api::{CALL, MatrixApi};
31use wire::CardRef;
32
33pub const MATRIX_CHANNEL: &str = "matrix";
36
37pub const MATRIX: &str = "Matrix";
39
40const DEFAULT_POLL_TIMEOUT: Duration = Duration::from_secs(25);
42const MIN_BACKOFF: Duration = Duration::from_secs(1);
43const MAX_BACKOFF: Duration = Duration::from_secs(60);
44const CARDS_KEPT: usize = 1024;
46const FILTER: &str = r#"{"presence":{"types":[]},"account_data":{"types":[]},"room":{"ephemeral":{"types":[]},"account_data":{"types":[]},"timeline":{"limit":50}}}"#;
49
50#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
65#[non_exhaustive]
66pub enum MatrixError {
67 #[error(
69 "the Matrix homeserver refused the access token: check MATRIX_ACCESS_TOKEN, or log the \
70 bot account in again for a new one"
71 )]
72 Unauthorized,
73 #[error(
75 "the Matrix homeserver asked to wait {retry_after_ms} ms before {endpoint}: the account is sending too much"
76 )]
77 RateLimited {
78 endpoint: String,
80 retry_after_ms: u64,
82 },
83 #[error("the Matrix homeserver refused {endpoint} (HTTP {status}, {errcode}): {error}")]
85 Refused {
86 endpoint: String,
88 status: u16,
90 errcode: String,
92 error: String,
94 },
95 #[error(
97 "the Matrix homeserver could not be reached for {endpoint}: {reason}; check the \
98 network and MATRIX_HOMESERVER"
99 )]
100 Unreachable {
101 endpoint: String,
103 reason: String,
105 },
106 #[error("the Matrix homeserver's answer to {endpoint} could not be read: {reason}")]
108 InvalidResponse {
109 endpoint: String,
111 reason: String,
113 },
114}
115
116impl MatrixError {
117 pub fn code(&self) -> &'static str {
120 match self {
121 Self::Unauthorized => "surface.matrix.unauthorized",
122 Self::RateLimited { .. } => "surface.matrix.rate_limited",
123 Self::Refused { .. } => "surface.matrix.refused",
124 Self::Unreachable { .. } => "surface.matrix.unreachable",
125 Self::InvalidResponse { .. } => "surface.matrix.invalid_response",
126 }
127 }
128}
129
130impl From<MatrixError> for AdkError {
131 fn from(error: MatrixError) -> Self {
132 let category = match &error {
133 MatrixError::Unauthorized => ErrorCategory::Unauthorized,
134 MatrixError::RateLimited { .. } => ErrorCategory::RateLimited,
135 MatrixError::Refused { status: 403, .. } => ErrorCategory::Forbidden,
136 MatrixError::Refused { status: 404, .. } => ErrorCategory::NotFound,
137 MatrixError::Refused { status: 400, .. } => ErrorCategory::InvalidInput,
138 MatrixError::Refused { .. } | MatrixError::Unreachable { .. } => {
139 ErrorCategory::Unavailable
140 }
141 MatrixError::InvalidResponse { .. } => ErrorCategory::Internal,
142 };
143 AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
144 .with_provider("matrix")
145 }
146}
147
148impl From<MatrixError> for KernelError {
149 fn from(error: MatrixError) -> Self {
150 Self::Core(error.into())
151 }
152}
153
154pub type MatrixSync = ChannelConnection<MatrixError>;
156
157pub struct MatrixAdapterBuilder {
159 homeserver: String,
160 token: String,
161 user_id: Option<String>,
162 poll_timeout: Duration,
163 kit: Kit,
164}
165
166impl fmt::Debug for MatrixAdapterBuilder {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 f.debug_struct("MatrixAdapterBuilder")
169 .field("homeserver", &self.homeserver)
170 .field("poll_timeout", &self.poll_timeout)
171 .finish_non_exhaustive()
172 }
173}
174
175impl MatrixAdapterBuilder {
176 #[must_use]
179 pub fn user_id(mut self, user_id: impl Into<String>) -> Self {
180 self.user_id = Some(user_id.into());
181 self
182 }
183
184 #[must_use]
186 pub fn poll_timeout(mut self, timeout: Duration) -> Self {
187 self.poll_timeout = timeout.max(Duration::from_secs(1));
188 self
189 }
190
191 kit_builder!("Matrix");
192
193 pub fn build(self) -> Result<MatrixAdapter> {
200 let api = MatrixApi::new(&self.homeserver, &self.token).map_err(SurfaceError::Invalid)?;
201 Ok(MatrixAdapter {
202 inner: Arc::new(Inner {
203 api,
204 kit: self.kit,
205 poll_timeout: self.poll_timeout,
206 me: Mutex::new(self.user_id),
207 rooms: Mutex::default(),
208 }),
209 })
210 }
211}
212
213#[derive(Clone)]
248pub struct MatrixAdapter {
249 inner: Arc<Inner>,
250}
251
252struct Inner {
253 api: MatrixApi,
254 kit: Kit,
255 poll_timeout: Duration,
256 me: Mutex<Option<String>>,
258 rooms: Mutex<Rooms>,
259}
260
261pub(crate) struct Carried {
263 card: Option<String>,
265 files: Vec<crate::channels::media::FileRef>,
267}
268
269#[derive(Default)]
271struct Rooms {
272 encrypted: HashSet<String>,
274 told: HashSet<String>,
276 groups: HashSet<String>,
278 cards: HashMap<String, CardRef>,
280 order: VecDeque<String>,
281}
282
283impl Rooms {
284 fn keep(&mut self, event: String, card: CardRef) {
285 if self.cards.insert(event.clone(), card).is_none() {
286 self.order.push_back(event);
287 }
288 while self.order.len() > CARDS_KEPT {
289 if let Some(oldest) = self.order.pop_front() {
290 self.cards.remove(&oldest);
291 }
292 }
293 }
294}
295
296impl fmt::Debug for MatrixAdapter {
297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298 f.debug_struct("MatrixAdapter").field("channel", &MATRIX_CHANNEL).finish_non_exhaustive()
299 }
300}
301
302impl MatrixAdapter {
303 pub fn builder(
306 homeserver: impl Into<String>,
307 token: impl Into<String>,
308 ) -> MatrixAdapterBuilder {
309 MatrixAdapterBuilder {
310 homeserver: homeserver.into(),
311 token: token.into(),
312 user_id: None,
313 poll_timeout: DEFAULT_POLL_TIMEOUT,
314 kit: Kit::default(),
315 }
316 }
317
318 fn rooms(&self) -> std::sync::MutexGuard<'_, Rooms> {
319 self.inner.rooms.lock().unwrap_or_else(PoisonError::into_inner)
320 }
321
322 fn me(&self) -> Option<String> {
323 self.inner.me.lock().unwrap_or_else(PoisonError::into_inner).clone()
324 }
325
326 pub async fn inbound(&self, room: &str, event: &Value) -> Option<ChannelInbound> {
352 if event["type"] == "m.reaction" {
353 let (card, _) = wire::reaction(event)?;
354 let card = self.card(room, &card).await?;
355 return wire::answer(room, event, &card);
356 }
357 wire::typed(room, event, self.me().as_deref())
358 }
359
360 async fn card(&self, room: &str, event: &str) -> Option<CardRef> {
363 if let Some(card) = self.rooms().cards.get(event).cloned() {
364 return Some(card);
365 }
366 let me = self.me()?;
367 let path = ["rooms", room, "event", event];
368 let fetched = self.inner.api.call(Method::GET, &path, &[], None, CALL, true).await;
369 let fetched = match fetched {
370 Ok(fetched) => fetched,
371 Err(error) => {
372 tracing::debug!(error = %error, "a reacted-to matrix event could not be read");
373 return None;
374 }
375 };
376 if fetched["sender"].as_str() != Some(me.as_str()) {
377 return None;
378 }
379 let card = wire::card_ref(&fetched["content"])?;
380 self.rooms().keep(event.to_string(), card.clone());
381 Some(card)
382 }
383
384 pub fn start(&self, gateway: ChannelGateway) -> MatrixSync {
394 let adapter = self.clone();
395 ChannelConnection::spawn(async move { adapter.run(gateway).await })
396 }
397
398 async fn run(&self, gateway: ChannelGateway) -> std::result::Result<(), MatrixError> {
399 let mut backoff = MIN_BACKOFF;
400 let me = loop {
401 if let Some(me) = self.me() {
402 break me;
403 }
404 match self
405 .inner
406 .api
407 .call(Method::GET, &["account", "whoami"], &[], None, CALL, true)
408 .await
409 {
410 Ok(whoami) => {
411 if let Some(me) = whoami["user_id"].as_str() {
412 *self.inner.me.lock().unwrap_or_else(PoisonError::into_inner) =
413 Some(me.to_string());
414 }
415 }
416 Err(MatrixError::Unauthorized) => return Err(MatrixError::Unauthorized),
417 Err(error) => {
418 tracing::warn!(error = %error, "the matrix account could not be read; retrying");
419 tokio::time::sleep(backoff).await;
420 backoff = (backoff * 2).min(MAX_BACKOFF);
421 }
422 }
423 };
424 let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
425 let _dispatcher = AbortOnDrop(task);
426 let mut since: Option<String> = None;
427 let timeout = self.inner.poll_timeout.as_millis().to_string();
428 loop {
429 let mut query = vec![("timeout", timeout.as_str()), ("filter", FILTER)];
430 if let Some(since) = &since {
431 query.push(("since", since.as_str()));
432 }
433 let wait = self.inner.poll_timeout + CALL;
434 let batch = match self
435 .inner
436 .api
437 .call(Method::GET, &["sync"], &query, None, wait, false)
438 .await
439 {
440 Ok(batch) => {
441 backoff = MIN_BACKOFF;
442 batch
443 }
444 Err(MatrixError::Unauthorized) => return Err(MatrixError::Unauthorized),
445 Err(MatrixError::RateLimited { retry_after_ms, .. }) => {
446 tokio::time::sleep(Duration::from_millis(retry_after_ms.max(100))).await;
447 continue;
448 }
449 Err(error) => {
450 tracing::warn!(error = %error, "reading matrix rooms failed; retrying");
451 tokio::time::sleep(backoff).await;
452 backoff = (backoff * 2).min(MAX_BACKOFF);
453 continue;
454 }
455 };
456 let first = since.is_none();
457 if let Some(next) = batch["next_batch"].as_str() {
458 since = Some(next.to_string());
459 }
460 self.take_batch(&batch, first, &me, &sender).await;
461 }
462 }
463
464 async fn take_batch(
467 &self,
468 batch: &Value,
469 first: bool,
470 me: &str,
471 sender: &mpsc::UnboundedSender<Update<Carried>>,
472 ) {
473 let rooms = &batch["rooms"];
474 for (room, invite) in rooms["invite"].as_object().into_iter().flatten() {
475 let state = invite["invite_state"]["events"].as_array().cloned().unwrap_or_default();
476 let direct = state.iter().any(|event| {
477 event["type"] == "m.room.member"
478 && event["state_key"] == me
479 && event["content"]["is_direct"] == true
480 });
481 if !direct {
482 tracing::debug!("a matrix invite to a room that is not a direct chat was left");
483 continue;
484 }
485 if state.iter().any(|event| event["type"] == "m.room.encryption") {
486 self.rooms().encrypted.insert(room.clone());
487 }
488 if let Err(error) = self
489 .inner
490 .api
491 .call(Method::POST, &["join", room], &[], Some(&json!({})), CALL, true)
492 .await
493 {
494 tracing::warn!(error = %error, "a matrix direct chat could not be joined");
495 }
496 }
497 for (room, joined) in rooms["join"].as_object().into_iter().flatten() {
498 let timeline = joined["timeline"]["events"].as_array().cloned().unwrap_or_default();
499 let state = joined["state"]["events"].as_array().cloned().unwrap_or_default();
500 let encrypted = {
501 let mut rooms = self.rooms();
502 if state.iter().chain(&timeline).any(|event| event["type"] == "m.room.encryption") {
503 rooms.encrypted.insert(room.clone());
504 }
505 match joined["summary"]["m.joined_member_count"].as_u64() {
506 Some(count) if count > 2 => {
507 rooms.groups.insert(room.clone());
508 }
509 Some(_) => {
510 rooms.groups.remove(room);
511 }
512 None => {}
513 }
514 rooms.encrypted.contains(room)
515 };
516 if first {
517 continue;
518 }
519 let others: Vec<&Value> =
520 timeline.iter().filter(|event| event["sender"].as_str() != Some(me)).collect();
521 if encrypted {
522 let spoke = others.iter().any(|event| {
523 matches!(event["type"].as_str(), Some("m.room.encrypted" | "m.room.message"))
524 });
525 if spoke && self.rooms().told.insert(room.clone()) {
526 let notice = json!({ "msgtype": "m.notice", "body": wire::ENCRYPTED_ROOM });
527 if let Err(error) = self.send(room, "m.room.message", ¬ice).await {
528 tracing::debug!(error = %error, "an encrypted matrix room could not be told");
529 }
530 }
531 continue;
532 }
533 if self.rooms().groups.contains(room) {
534 continue;
535 }
536 for event in others {
537 let Some(inbound) = self.inbound(room, event).await else { continue };
538 let card = wire::reaction(event).map(|(card, _)| card);
539 let files = wire::image(event).into_iter().collect();
540 let carried = Carried { card, files };
541 if sender.send(Update { inbound: Some(inbound), press: Some(carried) }).is_err() {
542 return;
543 }
544 }
545 }
546 }
547
548 async fn send(&self, room: &str, kind: &str, content: &Value) -> adk_kernel::Result<String> {
550 let txn = uuid::Uuid::new_v4().simple().to_string();
551 let patient = patient(MATRIX_CHANNEL, room);
553 let path = ["rooms", room, "send", kind, txn.as_str()];
554 let sent =
555 self.inner.api.call(Method::PUT, &path, &[], Some(content), CALL, patient).await?;
556 Ok(sent["event_id"].as_str().unwrap_or_default().to_string())
557 }
558}
559
560#[async_trait]
561impl Taker for MatrixAdapter {
562 type Press = Carried;
564
565 fn channel_name(&self) -> &'static str {
566 MATRIX_CHANNEL
567 }
568
569 async fn take(
572 &self,
573 gateway: &ChannelGateway,
574 update: &Update<Carried>,
575 paired: bool,
576 ) -> adk_kernel::Result<()> {
577 let Some(mut inbound) = update.inbound.clone() else { return Ok(()) };
578 let carried = update.press.as_ref();
579 let files = carried.map_or(&[][..], |carried| carried.files.as_slice());
582 if paired && !files.is_empty() {
583 let api = &self.inner.api;
584 let attachments =
585 crate::channels::media::fetch_all(files, |file| api.download(file)).await;
586 inbound = inbound.with_attachments(attachments);
587 }
588 let card = match &inbound.body {
589 InboundBody::Answer { decision, .. } => {
590 match paired_binding(gateway, MATRIX_CHANNEL, &inbound.account).await {
591 Ok(Some(binding)) if binding.thread == inbound.thread => {}
592 Ok(_) => {
593 tracing::debug!(
594 "a matrix reaction from an account not paired from its room was ignored"
595 );
596 return Ok(());
597 }
598 Err(()) => {
599 return Err(KernelError::Core(AdkError::new(
600 ErrorComponent::Server,
601 ErrorCategory::Unavailable,
602 "surface.matrix.pairing_unread",
603 "the account's pairing could not be read",
604 )));
605 }
606 }
607 let card = carried.and_then(|carried| carried.card.clone());
608 Some(PressedCard { card, decision: decision.clone() })
609 }
610 _ => None,
611 };
612 let handling = Handling::of(MATRIX_CHANNEL, gateway, &inbound, paired, card);
613 HANDLING.scope(handling, gateway.receive(inbound)).await.map(drop)
614 }
615
616 async fn not_taken(&self, update: &Update<Carried>) {
617 let Some(inbound) = &update.inbound else { return };
618 let pressed = update.press.as_ref().is_some_and(|carried| carried.card.is_some());
619 let text = if pressed { ANSWER_NOT_TAKEN } else { MESSAGE_NOT_TAKEN };
620 for content in wire::plain(text) {
621 if let Err(error) = self.send(&inbound.thread, "m.room.message", &content).await {
622 tracing::debug!(error = %error, "a person could not be told their message was not taken");
623 }
624 }
625 }
626}
627
628#[async_trait]
629impl ChannelSink for MatrixAdapter {
630 fn channel(&self) -> &str {
631 MATRIX_CHANNEL
632 }
633
634 async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
635 for content in wire::plain(text) {
636 self.send(thread, "m.room.message", &content).await?;
637 }
638 Ok(())
639 }
640
641 async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
644 let (heading, card) = self.inner.kit.prepare(card).await;
645 let (content, answers) = wire::card(&card, &heading, self.inner.kit.offset);
646 let event = self.send(thread, "m.room.message", &content).await?;
647 let Some(answers) = answers.filter(|_| !event.is_empty()) else { return Ok(()) };
648 let keys: Vec<String> = answers.answers.iter().map(|(key, _)| key.clone()).collect();
649 self.rooms().keep(event.clone(), answers);
650 for key in keys {
651 if let Err(error) = self.send(thread, "m.reaction", &wire::offer(&event, &key)).await {
652 tracing::debug!(error = %error, "a card's answer key could not be offered");
653 }
654 }
655 Ok(())
656 }
657
658 async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
659 self.send(thread, "m.room.message", &wire::message(&stopped_words(notice))).await.map(drop)
660 }
661
662 async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
665 let card = self.inner.kit.before_notice(MATRIX_CHANNEL, MATRIX, thread, notice).await;
666 let words = notice_words(notice, self.inner.kit.offset, Utc::now(), card.is_some());
667 let mut content = wire::message(&words);
668 if let Some(card) = card.filter(|card| !card.is_empty()) {
669 content["m.relates_to"] = json!({ "m.in_reply_to": { "event_id": card } });
670 }
671 self.send(thread, "m.room.message", &content).await.map(drop)
672 }
673}
674
675#[cfg(test)]
676mod tests {
677 use super::*;
678
679 #[test]
680 fn errors_say_what_to_do_and_keep_their_category() {
681 let error: AdkError = MatrixError::Unauthorized.into();
682 assert_eq!(
683 (error.code, error.category),
684 ("surface.matrix.unauthorized", ErrorCategory::Unauthorized)
685 );
686 let forbidden = MatrixError::Refused {
687 endpoint: "rooms".into(),
688 status: 403,
689 errcode: "M_FORBIDDEN".into(),
690 error: "not in room".into(),
691 };
692 assert_eq!(AdkError::from(forbidden).category, ErrorCategory::Forbidden);
693 }
694
695 #[test]
696 fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
697 let error =
698 MatrixAdapter::builder("http://matrix.example.org", "syt_secret").build().unwrap_err();
699 assert!(!error.to_string().contains("secret"), "{error}");
700 assert!(MatrixAdapter::builder("https://matrix.example.org", "").build().is_err());
701 let adapter =
702 MatrixAdapter::builder("https://matrix.example.org", "syt_secret").build().unwrap();
703 assert!(!format!("{adapter:?}").contains("secret"));
704 assert_eq!(ChannelSink::channel(&adapter), "matrix");
705 }
706
707 #[test]
708 fn the_adapter_remembers_its_newest_cards() {
709 let mut rooms = Rooms::default();
710 let card = CardRef { decision: "d".into(), version: 1, answers: Vec::new() };
711 for index in 0..CARDS_KEPT + 3 {
712 rooms.keep(format!("$e{index}"), card.clone());
713 }
714 assert_eq!(rooms.cards.len(), CARDS_KEPT);
715 assert!(
716 !rooms.cards.contains_key("$e0")
717 && rooms.cards.contains_key(&format!("$e{}", CARDS_KEPT + 2))
718 );
719 }
720}