BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / outbox.rs

outbox.rs

outbox.rs 11.2 KiB Download Raw
1use std::collections::HashMap;
2use std::time::Duration;
3
4use chrono::{DateTime, Utc};
5use gpui_kit::Context;
6use store::{MessageRecord, OutboxRecord, OutboxState, OutboxTarget, plain_text};
7use uuid::Uuid;
8
9use crate::app_state::{AppEvent, AppState};
10use crate::backend::Engine;
11use crate::notice::short_error;
12use crate::runtime;
13use crate::stored_outgoing::{decode, encode};
14use crate::outgoing::Outgoing;
15
16const RETRY_BACKOFF: [Duration; 3] = [
17 Duration::from_secs(2),
18 Duration::from_secs(8),
19 Duration::from_secs(30),
20];
21const DUPLICATE_WINDOW_SECONDS: i64 = 5;
22const RECENT_MESSAGES: usize = 30;
23
24pub fn new_outbox_id() -> String {
25 Uuid::new_v4().to_string()
26}
27
28pub fn outbox_record(
29 id: &str,
30 conversation_id: &str,
31 target: OutboxTarget,
32 thread_root_id: Option<&str>,
33 outgoing: &Outgoing,
34 created_at: DateTime<Utc>,
35) -> Option<OutboxRecord> {
36 let stored = encode(outgoing)?;
37 Some(OutboxRecord {
38 id: id.to_owned(),
39 conversation_id: conversation_id.to_owned(),
40 target,
41 thread_root_id: thread_root_id.map(str::to_owned),
42 payload: stored.payload,
43 images: stored.images,
44 state: OutboxState::Sending,
45 last_error: None,
46 created_at,
47 })
48}
49
50pub fn outgoing_of(record: &OutboxRecord) -> Option<Outgoing> {
51 decode(&record.payload, &record.images)
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Delivered {
56 Complete,
57 /// The post went out but its announcement banner could not be set.
58 WithoutBanner,
59}
60
61pub async fn deliver(
62 engine: &Engine,
63 conversation_id: &str,
64 target: OutboxTarget,
65 thread_root_id: Option<&str>,
66 outgoing: &Outgoing,
67) -> teams_core::Result<Delivered> {
68 let extras = outgoing.extras();
69 let html = outgoing.html();
70 let mentions = &outgoing.mentions;
71 let record = match (target, &outgoing.reply) {
72 (_, Some(reply)) => {
73 engine
74 .reply_to_with_extras(conversation_id, &reply.message_id, &html, mentions, &extras)
75 .await
76 }
77 (OutboxTarget::Flat, None) => {
78 engine
79 .send_message_with_extras(conversation_id, &html, None, mentions, &extras)
80 .await
81 }
82 (OutboxTarget::Post, None) => match &outgoing.banner {
83 Some(banner) => {
84 let posted = engine
85 .post_announcement(
86 conversation_id,
87 &html,
88 outgoing.subject.as_deref(),
89 mentions,
90 &extras,
91 banner,
92 )
93 .await;
94 if matches!(posted, Ok(_) | Err(teams_core::Error::PostedWithoutBanner)) {
95 discard_banner_image(banner);
96 }
97 match posted {
98 Err(teams_core::Error::PostedWithoutBanner) => return Ok(Delivered::WithoutBanner),
99 other => other,
100 }
101 }
102 None => {
103 engine
104 .post_to_channel_with_extras(
105 conversation_id,
106 &html,
107 outgoing.subject.as_deref(),
108 mentions,
109 &extras,
110 )
111 .await
112 }
113 },
114 (OutboxTarget::Thread, None) => {
115 engine
116 .send_message_with_extras(conversation_id, &html, thread_root_id, mentions, &extras)
117 .await
118 }
119 }?;
120 if let Some(preview) = &outgoing.link_preview {
121 let _ = engine
122 .attach_link_preview(conversation_id, &record.message_id, preview)
123 .await;
124 }
125 Ok(Delivered::Complete)
126}
127
128fn discard_banner_image(banner: &teams_core::AnnouncementBanner) {
129 if let teams_core::BannerBackground::LocalImage(path) = &banner.background {
130 crate::banner_image::discard_banner_image(std::path::Path::new(path));
131 }
132}
133
134fn is_permanent(error: &teams_core::Error) -> bool {
135 match error {
136 teams_core::Error::Graph(graph::Error::Session(session::Error::Api { status, .. })) => {
137 (400..500).contains(status) && !matches!(status, 408 | 429)
138 }
139 teams_core::Error::Graph(graph::Error::NotAMember)
140 | teams_core::Error::Unsupported(_)
141 | teams_core::Error::BannerImage(_)
142 | teams_core::Error::UnknownConversation(_) => true,
143 _ => false,
144 }
145}
146
147fn comparable(text: &str) -> String {
148 text.chars()
149 .filter(|character| character.is_alphanumeric())
150 .collect()
151}
152
153fn is_duplicate(
154 recent: &[MessageRecord],
155 my_user_id: &str,
156 created_at: DateTime<Utc>,
157 text: &str,
158) -> bool {
159 let wanted = comparable(text);
160 let since = created_at - chrono::Duration::seconds(DUPLICATE_WINDOW_SECONDS);
161 !wanted.is_empty()
162 && recent.iter().any(|message| {
163 !message.deleted
164 && message.sender_id.as_deref() == Some(my_user_id)
165 && message.created_at >= since
166 && comparable(&plain_text(&message.body_html)) == wanted
167 })
168}
169
170async fn already_sent(
171 engine: &Engine,
172 record: &OutboxRecord,
173 outgoing: &Outgoing,
174) -> teams_core::Result<bool> {
175 engine.fetch_newer(&record.conversation_id).await?;
176 let Some(me) = engine.me() else {
177 return Ok(false);
178 };
179 let recent = engine
180 .store()
181 .messages(&record.conversation_id, None, RECENT_MESSAGES)?;
182 Ok(is_duplicate(
183 &recent,
184 &me.user_id,
185 record.created_at,
186 &outgoing.text(),
187 ))
188}
189
190async fn attempt(
191 engine: &Engine,
192 record: &OutboxRecord,
193 outgoing: &Outgoing,
194) -> teams_core::Result<Delivered> {
195 // Graph has no idempotency key: a send cut off by the quit may have gone through.
196 if already_sent(engine, record, outgoing).await? {
197 return Ok(Delivered::Complete);
198 }
199 deliver(
200 engine,
201 &record.conversation_id,
202 record.target,
203 record.thread_root_id.as_deref(),
204 outgoing,
205 )
206 .await
207}
208
209async fn resend(engine: &Engine, record: &OutboxRecord, outgoing: &Outgoing) -> Result<(), String> {
210 let mut failure = String::new();
211 for attempt_number in 0..=RETRY_BACKOFF.len() {
212 if let Some(delay) = attempt_number
213 .checked_sub(1)
214 .map(|index| RETRY_BACKOFF[index])
215 {
216 tokio::time::sleep(delay).await;
217 }
218 match attempt(engine, record, outgoing).await {
219 Ok(_) => return Ok(()),
220 Err(error) if is_permanent(&error) => return Err(short_error(&error)),
221 Err(error) => failure = short_error(&error),
222 }
223 }
224 Err(failure)
225}
226
227async fn resend_record(engine: &Engine, record: OutboxRecord) {
228 let store = engine.store();
229 let outcome = match outgoing_of(&record) {
230 Some(outgoing) => resend(engine, &record, &outgoing).await,
231 None => Err("The saved message could not be read".to_owned()),
232 };
233 match outcome {
234 Ok(()) => store.delete_outbox(&record.id).ok(),
235 Err(error) => store.mark_outbox_failed(&record.id, &error).ok(),
236 };
237}
238
239impl AppState {
240 pub fn resend_outbox(&mut self, cx: &mut Context<Self>) {
241 if self.mode.demo || self.mode.read_only {
242 return;
243 }
244 let Some(engine) = self.engine.clone() else {
245 return;
246 };
247 let Ok(records) = self.store.sending_outbox() else {
248 return;
249 };
250 let mut by_conversation: Vec<(String, Vec<OutboxRecord>)> = Vec::new();
251 let mut positions: HashMap<String, usize> = HashMap::new();
252 for record in records {
253 let position = *positions
254 .entry(record.conversation_id.clone())
255 .or_insert_with(|| {
256 by_conversation.push((record.conversation_id.clone(), Vec::new()));
257 by_conversation.len() - 1
258 });
259 by_conversation[position].1.push(record);
260 }
261 let (finished, mut finished_conversations) = tokio::sync::mpsc::unbounded_channel();
262 for (conversation_id, records) in by_conversation {
263 let (engine, finished) = (engine.clone(), finished.clone());
264 runtime::handle().spawn(async move {
265 for record in records {
266 resend_record(&engine, record).await;
267 let _ = finished.send(conversation_id.clone());
268 }
269 });
270 }
271 drop(finished);
272 cx.spawn(async move |this, cx| {
273 while let Some(conversation_id) = finished_conversations.recv().await {
274 this.update(cx, |state, cx| state.outbox_changed(conversation_id, cx))
275 .ok();
276 }
277 })
278 .detach();
279 }
280
281 pub fn outbox_changed(&mut self, conversation_id: String, cx: &mut Context<Self>) {
282 self.refresh_local_previews(cx);
283 cx.emit(AppEvent::Outbox(conversation_id));
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use chrono::TimeZone;
290
291 use super::*;
292
293 fn message(sender: &str, second: u32, html: &str) -> MessageRecord {
294 MessageRecord {
295 sender_id: Some(sender.to_owned()),
296 created_at: Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap(),
297 body_html: html.to_owned(),
298 ..MessageRecord::default()
299 }
300 }
301
302 fn sent_at(second: u32) -> DateTime<Utc> {
303 Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap()
304 }
305
306 #[test]
307 fn an_own_message_with_the_same_text_after_the_send_is_a_duplicate() {
308 let recent = [message("me", 31, "<p>Hello <at>Ada</at>!</p>")];
309 assert!(is_duplicate(&recent, "me", sent_at(30), "Hello @Ada!"));
310 }
311
312 #[test]
313 fn a_message_up_to_five_seconds_before_the_send_still_counts() {
314 let recent = [message("me", 25, "<p>Hi</p>")];
315 assert!(is_duplicate(&recent, "me", sent_at(30), "Hi"));
316 let recent = [message("me", 24, "<p>Hi</p>")];
317 assert!(!is_duplicate(&recent, "me", sent_at(30), "Hi"));
318 }
319
320 #[test]
321 fn other_senders_other_text_and_empty_text_are_no_duplicates() {
322 let recent = [
323 message("other", 31, "<p>Hi</p>"),
324 message("me", 32, "<p>Bye</p>"),
325 ];
326 assert!(!is_duplicate(&recent, "me", sent_at(30), "Hi"));
327 let image_only = [message("me", 31, "<img src=\"x\">")];
328 assert!(!is_duplicate(&image_only, "me", sent_at(30), ""));
329 }
330
331 #[test]
332 fn deleted_messages_are_no_duplicates() {
333 let mut deleted = message("me", 31, "<p>Hi</p>");
334 deleted.deleted = true;
335 assert!(!is_duplicate(&[deleted], "me", sent_at(30), "Hi"));
336 }
337
338 #[test]
339 fn client_errors_fail_at_once_and_server_errors_retry() {
340 let api = |status| {
341 teams_core::Error::Graph(graph::Error::Session(session::Error::api(
342 status,
343 "https://graph.test",
344 serde_json::json!({}),
345 )))
346 };
347 assert!(is_permanent(&api(403)));
348 assert!(is_permanent(&api(400)));
349 assert!(!is_permanent(&api(429)));
350 assert!(!is_permanent(&api(503)));
351 assert!(!is_permanent(&teams_core::Error::Graph(
352 graph::Error::Download("x".into())
353 )));
354 }
355}