BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / receipts.rs

receipts.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
receipts.rs 7.3 KiB Download Raw
1use chrono::{DateTime, Utc};
2use serde_json::Value;
3use session::Request;
4
5use crate::error::{Error, Result};
6use crate::messages::{MessageTransport, SessionMessageTransport, encode};
7use crate::pins::DEFAULT_REGION;
8
9const READ_PART: usize = 0;
10const READ_AT_PART: usize = 1;
11const MESSAGE_ID_PART: usize = 2;
12const DISABLED_STATUSES: [u16; 2] = [403, 404];
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct MemberHorizon {
16 pub member_id: String,
17 pub read_until: DateTime<Utc>,
18 pub read_at: Option<DateTime<Utc>>,
19 pub message_id: Option<String>,
20 pub raw_parts: Vec<String>,
21}
22
23pub fn parse_horizon(member_id: &str, horizon: &str) -> Option<MemberHorizon> {
24 let raw_parts: Vec<String> = horizon
25 .split(';')
26 .map(|part| part.trim().to_owned())
27 .collect();
28 let read_until = millis_part(&raw_parts, READ_PART)?;
29 Some(MemberHorizon {
30 member_id: member_id.to_owned(),
31 read_until,
32 read_at: millis_part(&raw_parts, READ_AT_PART),
33 message_id: raw_parts
34 .get(MESSAGE_ID_PART)
35 .filter(|part| !part.is_empty())
36 .cloned(),
37 raw_parts,
38 })
39}
40
41fn millis_part(parts: &[String], index: usize) -> Option<DateTime<Utc>> {
42 let millis: i64 = parts.get(index)?.parse().ok()?;
43 DateTime::from_timestamp_millis(millis)
44}
45
46pub fn parse_horizons(body: &Value) -> Result<Vec<MemberHorizon>> {
47 let entries = body
48 .get("consumptionhorizons")
49 .and_then(Value::as_array)
50 .ok_or_else(|| Error::UnexpectedAnswer("no consumptionhorizons list".into()))?;
51 Ok(entries
52 .iter()
53 .filter_map(|entry| {
54 let member_id = entry.get("id")?.as_str()?;
55 parse_horizon(member_id, entry.get("consumptionhorizon")?.as_str()?)
56 })
57 .collect())
58}
59
60pub struct Receipts<T: MessageTransport = SessionMessageTransport> {
61 transport: T,
62 base_url: String,
63}
64
65impl Receipts<SessionMessageTransport> {
66 pub fn new(session: &session::Session) -> Self {
67 Self::with_region(session, DEFAULT_REGION)
68 }
69
70 pub fn with_region(session: &session::Session, region: &str) -> Self {
71 Receipts::with_transport(SessionMessageTransport::new(session), region)
72 }
73}
74
75impl<T: MessageTransport> Receipts<T> {
76 pub fn with_transport(transport: T, region: &str) -> Self {
77 Receipts {
78 transport,
79 base_url: format!("https://teams.cloud.microsoft/api/chatsvc/{region}/v1/threads"),
80 }
81 }
82
83 pub fn horizons_url(&self, conversation_id: &str) -> String {
84 format!(
85 "{}/{}/consumptionhorizons",
86 self.base_url,
87 encode(conversation_id)
88 )
89 }
90
91 /// Empty when the service answers 403 or 404, which counts as receipts disabled.
92 pub async fn consumption_horizons(&self, conversation_id: &str) -> Result<Vec<MemberHorizon>> {
93 let answer = self
94 .transport
95 .send(Request::get(self.horizons_url(conversation_id)))
96 .await?;
97 if DISABLED_STATUSES.contains(&answer.status) {
98 return Ok(Vec::new());
99 }
100 if !answer.is_success() {
101 return Err(Error::Session(session::Error::api(
102 answer.status,
103 "chatsvc",
104 answer.body.clone(),
105 )));
106 }
107 parse_horizons(&answer.body)
108 }
109}
110
111#[cfg(test)]
112mod tests {
113 use std::sync::Mutex;
114
115 use serde_json::json;
116 use session::ApiResponse;
117
118 use super::*;
119
120 struct Canned {
121 status: u16,
122 body: Value,
123 urls: Mutex<Vec<String>>,
124 }
125
126 impl MessageTransport for Canned {
127 async fn send(&self, request: Request) -> Result<ApiResponse> {
128 self.urls.lock().unwrap().push(request.url.clone());
129 Ok(ApiResponse {
130 status: self.status,
131 body: self.body.clone(),
132 retry_after: None,
133 })
134 }
135 }
136
137 fn canned(status: u16, body: Value) -> Receipts<Canned> {
138 Receipts::with_transport(
139 Canned {
140 status,
141 body,
142 urls: Mutex::new(Vec::new()),
143 },
144 "emea",
145 )
146 }
147
148 #[test]
149 fn parses_three_part_horizon() {
150 let horizon = parse_horizon(
151 "8:orgid:a",
152 "1791368146075;1791368146999;6638123456789012345",
153 )
154 .unwrap();
155 assert_eq!(horizon.read_until.timestamp_millis(), 1791368146075);
156 assert_eq!(
157 horizon.read_at.map(|time| time.timestamp_millis()),
158 Some(1791368146999)
159 );
160 assert_eq!(horizon.message_id.as_deref(), Some("6638123456789012345"));
161 assert_eq!(horizon.raw_parts.len(), 3);
162 }
163
164 #[test]
165 fn tolerates_short_and_padded_horizons() {
166 let single = parse_horizon("m", " 1791368146075 ").unwrap();
167 assert_eq!(single.read_at, None);
168 assert_eq!(single.message_id, None);
169 let two = parse_horizon("m", "1791368146075;;").unwrap();
170 assert_eq!(two.read_at, None);
171 assert_eq!(two.message_id, None);
172 }
173
174 #[test]
175 fn rejects_unparseable_horizons() {
176 assert!(parse_horizon("m", "").is_none());
177 assert!(parse_horizon("m", "abc;1;2").is_none());
178 assert!(parse_horizon("m", ";1;2").is_none());
179 assert!(parse_horizon("m", "99999999999999999999;1;2").is_none());
180 }
181
182 #[test]
183 fn parses_body_and_skips_broken_members() {
184 let body = json!({
185 "id": "19:x@thread.v2",
186 "version": "1",
187 "consumptionhorizons": [
188 {"id": "8:orgid:a", "consumptionhorizon": "1;2;3", "messageVisibilityTime": 0},
189 {"id": "8:orgid:b", "consumptionhorizon": ""},
190 {"id": "8:orgid:c"},
191 {"consumptionhorizon": "1;2;3"},
192 {"id": "8:orgid:d", "consumptionhorizon": "5;6;7"}
193 ]
194 });
195 let horizons = parse_horizons(&body).unwrap();
196 let ids: Vec<&str> = horizons
197 .iter()
198 .map(|entry| entry.member_id.as_str())
199 .collect();
200 assert_eq!(ids, ["8:orgid:a", "8:orgid:d"]);
201 }
202
203 #[test]
204 fn body_without_list_is_unexpected() {
205 assert!(matches!(
206 parse_horizons(&json!({"id": "x"})),
207 Err(Error::UnexpectedAnswer(_))
208 ));
209 }
210
211 #[tokio::test]
212 async fn fetches_with_encoded_thread_id() {
213 let receipts = canned(
214 200,
215 json!({"consumptionhorizons": [{"id": "8:orgid:a", "consumptionhorizon": "1;2;3"}]}),
216 );
217 let horizons = receipts
218 .consumption_horizons("19:abc@thread.v2")
219 .await
220 .unwrap();
221 assert_eq!(horizons.len(), 1);
222 assert_eq!(
223 receipts.transport.urls.lock().unwrap()[0],
224 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/consumptionhorizons"
225 );
226 }
227
228 #[tokio::test]
229 async fn forbidden_and_missing_mean_disabled() {
230 for status in [403, 404] {
231 let receipts = canned(status, json!({}));
232 assert!(receipts.consumption_horizons("c").await.unwrap().is_empty());
233 }
234 }
235
236 #[tokio::test]
237 async fn other_failures_are_errors() {
238 let receipts = canned(500, json!({"message": "boom"}));
239 assert!(receipts.consumption_horizons("c").await.is_err());
240 }
241}