BlueGit

ict rusty-teams

Files

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

outbox.rs

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