BlueGit

ict rusty-teams

Files

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

outbox.rs

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