BlueGit

ict rusty-teams

Files

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

outbox.rs

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