BlueGit

ict rusty-teams

fix(presence): push presence over Trouter like Teams web

- Subscribe watched users at the presence pubsub API with our Trouter endpoint.
- Apply unifiedPresenceService pushes directly; changes land in about 1 s.
- Resubscribe on a new endpoint and every 30 min.
- Fallback poll: 60 s without realtime, 5 min while live.
- Save only changed presence rows.

Before: presence was refetched only on a re-render after 60 s, pushes were dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
c3adb4903227acba9a7bd9cc401b9e6114dfa40f
Parent
ffb48387
21 files changed +604 −44
Cargo.lock +1 −0
@@ -3477,6 +3477,7 @@ dependencies = [
3477 3477 "session",
3478 3478 "thiserror 2.0.21",
3479 3479 "tokio",
3480 "uuid",
3480 3481 ]
3481 3482
3482 3483 [[package]]
@@ -3477,6 +3477,7 @@ dependencies = [
3477 "session",
3477 "session",
3478 "thiserror 2.0.21",
3478 "thiserror 2.0.21",
3479 "tokio",
3479 "tokio",
3480 "uuid",
3480]
3481]
3481
3482
3482[[package]]
3483[[package]]
Cargo.toml +1 −0
@@ -26,6 +26,7 @@ thiserror = "2"
26 26 tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "io-util", "sync"] }
27 27 tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake"] }
28 28 url = "2"
29 uuid = { version = "1", default-features = false, features = ["v4"] }
29 30
30 31 session = { path = "crates/session" }
31 32 graph = { path = "crates/graph" }
@@ -26,6 +26,7 @@ thiserror = "2"
26tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "io-util", "sync"] }
26tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "io-util", "sync"] }
27tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake"] }
27tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake"] }
28url = "2"
28url = "2"
29uuid = { version = "1", default-features = false, features = ["v4"] }
29
30
30session = { path = "crates/session" }
31session = { path = "crates/session" }
31graph = { path = "crates/graph" }
32graph = { path = "crates/graph" }
ROADMAP.md +1 −1
@@ -148,7 +148,7 @@ Feature parity with the Microsoft Teams desktop client.
148 148
149 149 | Feature | State | Note |
150 150 |---|---|---|
151 | Presence dots | Done | |
151 | Presence dots (live push) | Done | |
152 152 | Last known presence at start | Done | |
153 153 | Set own status and status message | Missing | |
154 154 | Profile card | Missing | |
@@ -148,7 +148,7 @@ Feature parity with the Microsoft Teams desktop client.
148
148
149| Feature | State | Note |
149| Feature | State | Note |
150|---|---|---|
150|---|---|---|
151| Presence dots | Done | |
151| Presence dots (live push) | Done | |
152| Last known presence at start | Done | |
152| Last known presence at start | Done | |
153| Set own status and status message | Missing | |
153| Set own status and status message | Missing | |
154| Profile card | Missing | |
154| Profile card | Missing | |
crates/app/src/app_state.rs +19 −8
@@ -272,26 +272,31 @@ impl AppState {
272 272 }
273 273 }
274 274
275 fn sync_presence(&mut self) {
275 fn sync_presence(&mut self) -> Vec<String> {
276 276 let Some(engine) = self.engine.clone() else {
277 return;
277 return Vec::new();
278 278 };
279 for user_id in self.directory.requested_presence_ids() {
280 if let Some(kind) = data::presence_kind(&engine, &user_id) {
281 self.directory.set_presence(&user_id, kind);
282 }
283 }
279 self.directory
280 .requested_presence_ids()
281 .into_iter()
282 .filter(|user_id| {
283 data::presence_kind(&engine, user_id)
284 .is_some_and(|kind| self.directory.set_presence(user_id, kind))
285 })
286 .collect()
284 287 }
285 288
286 289 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
287 290 let now = Instant::now();
288 let wanted = self.directory.stale_presence(user_ids, now);
291 let pushed = self.live == LiveState::Live;
292 let wanted = self.directory.stale_presence(user_ids, now, pushed);
289 293 if wanted.is_empty() {
290 294 return;
291 295 }
292 296 self.directory.mark_presence_pending(&wanted);
293 297 if let Some(engine) = self.engine.clone() {
294 298 self.directory.mark_presence_requested(&wanted, now);
299 drop(data::watch_presence(&engine, wanted.clone()));
295 300 let done = data::refresh_presence(&engine, wanted.clone());
296 301 self.on_done(done, cx, move |state, cx| {
297 302 state.sync_presence();
@@ -446,6 +451,12 @@ impl AppState {
446 451 }
447 452 cx.emit(AppEvent::Images(keys));
448 453 }
454 BackendEvent::Core(CoreEvent::PresenceChanged) => {
455 let changed = self.sync_presence();
456 self.directory.save_presence(&self.store, &changed);
457 cx.emit(AppEvent::Directory);
458 cx.notify();
459 }
449 460 BackendEvent::Core(_) => {
450 461 if !self.mode.demo {
451 462 self.reload_directory();
@@ -272,26 +272,31 @@ impl AppState {
272 }
272 }
273 }
273 }
274
274
275 fn sync_presence(&mut self) {
275 fn sync_presence(&mut self) -> Vec<String> {
276 let Some(engine) = self.engine.clone() else {
276 let Some(engine) = self.engine.clone() else {
277 return;
277 return Vec::new();
278 };
278 };
279 for user_id in self.directory.requested_presence_ids() {
279 self.directory
280 if let Some(kind) = data::presence_kind(&engine, &user_id) {
280 .requested_presence_ids()
281 self.directory.set_presence(&user_id, kind);
281 .into_iter()
282 }
282 .filter(|user_id| {
283 }
283 data::presence_kind(&engine, user_id)
284 .is_some_and(|kind| self.directory.set_presence(user_id, kind))
285 })
286 .collect()
284 }
287 }
285
288
286 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
289 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
287 let now = Instant::now();
290 let now = Instant::now();
288 let wanted = self.directory.stale_presence(user_ids, now);
291 let pushed = self.live == LiveState::Live;
292 let wanted = self.directory.stale_presence(user_ids, now, pushed);
289 if wanted.is_empty() {
293 if wanted.is_empty() {
290 return;
294 return;
291 }
295 }
292 self.directory.mark_presence_pending(&wanted);
296 self.directory.mark_presence_pending(&wanted);
293 if let Some(engine) = self.engine.clone() {
297 if let Some(engine) = self.engine.clone() {
294 self.directory.mark_presence_requested(&wanted, now);
298 self.directory.mark_presence_requested(&wanted, now);
299 drop(data::watch_presence(&engine, wanted.clone()));
295 let done = data::refresh_presence(&engine, wanted.clone());
300 let done = data::refresh_presence(&engine, wanted.clone());
296 self.on_done(done, cx, move |state, cx| {
301 self.on_done(done, cx, move |state, cx| {
297 state.sync_presence();
302 state.sync_presence();
@@ -446,6 +451,12 @@ impl AppState {
446 }
451 }
447 cx.emit(AppEvent::Images(keys));
452 cx.emit(AppEvent::Images(keys));
448 }
453 }
454 BackendEvent::Core(CoreEvent::PresenceChanged) => {
455 let changed = self.sync_presence();
456 self.directory.save_presence(&self.store, &changed);
457 cx.emit(AppEvent::Directory);
458 cx.notify();
459 }
449 BackendEvent::Core(_) => {
460 BackendEvent::Core(_) => {
450 if !self.mode.demo {
461 if !self.mode.demo {
451 self.reload_directory();
462 self.reload_directory();
crates/app/src/backend.rs +16 −0
@@ -16,6 +16,7 @@ const REFRESH_INTERVAL: Duration = Duration::from_secs(120);
16 16 const REFRESH_SETTLE: Duration = Duration::from_secs(2);
17 17 const PINS_INTERVAL: Duration = Duration::from_secs(90);
18 18 const REALTIME_RETRY: Duration = Duration::from_secs(15);
19 const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
19 20 const MAX_ERROR_CHARS: usize = 120;
20 21 const IMAGE_DIRECTORY: &str = "images";
21 22 const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024;
@@ -129,6 +130,7 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, events: Eve
129 130 nudge,
130 131 ));
131 132 tokio::spawn(pins_loop(session, events.clone()));
133 tokio::spawn(presence_resubscribe_loop(engine.clone()));
132 134 refresh_loop(engine, events, nudges).await;
133 135 }
134 136
@@ -210,6 +212,11 @@ async fn realtime_loop(
210 212 receipt_engine.handle_receipt_status(&receipt_status).await
211 213 });
212 214 }
215 RealtimeEvent::Presence(updates) => engine.apply_presence(&updates),
216 RealtimeEvent::Endpoint(endpoint) => {
217 let engine = engine.clone();
218 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
219 }
213 220 }
214 221 }
215 222 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
@@ -222,6 +229,15 @@ async fn realtime_loop(
222 229 }
223 230 }
224 231
232 async fn presence_resubscribe_loop(engine: Arc<Engine>) {
233 let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE);
234 interval.tick().await;
235 loop {
236 interval.tick().await;
237 let _ = engine.resubscribe_presence().await;
238 }
239 }
240
225 241 pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
226 242 let conversation_id = event.conversation_id.clone()?;
227 243 match event.kind {
@@ -16,6 +16,7 @@ const REFRESH_INTERVAL: Duration = Duration::from_secs(120);
16const REFRESH_SETTLE: Duration = Duration::from_secs(2);
16const REFRESH_SETTLE: Duration = Duration::from_secs(2);
17const PINS_INTERVAL: Duration = Duration::from_secs(90);
17const PINS_INTERVAL: Duration = Duration::from_secs(90);
18const REALTIME_RETRY: Duration = Duration::from_secs(15);
18const REALTIME_RETRY: Duration = Duration::from_secs(15);
19const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
19const MAX_ERROR_CHARS: usize = 120;
20const MAX_ERROR_CHARS: usize = 120;
20const IMAGE_DIRECTORY: &str = "images";
21const IMAGE_DIRECTORY: &str = "images";
21const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024;
22const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024;
@@ -129,6 +130,7 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, events: Eve
129 nudge,
130 nudge,
130 ));
131 ));
131 tokio::spawn(pins_loop(session, events.clone()));
132 tokio::spawn(pins_loop(session, events.clone()));
133 tokio::spawn(presence_resubscribe_loop(engine.clone()));
132 refresh_loop(engine, events, nudges).await;
134 refresh_loop(engine, events, nudges).await;
133}
135}
134
136
@@ -210,6 +212,11 @@ async fn realtime_loop(
210 receipt_engine.handle_receipt_status(&receipt_status).await
212 receipt_engine.handle_receipt_status(&receipt_status).await
211 });
213 });
212 }
214 }
215 RealtimeEvent::Presence(updates) => engine.apply_presence(&updates),
216 RealtimeEvent::Endpoint(endpoint) => {
217 let engine = engine.clone();
218 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
219 }
213 }
220 }
214 }
221 }
215 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
222 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
@@ -222,6 +229,15 @@ async fn realtime_loop(
222 }
229 }
223}
230}
224
231
232async fn presence_resubscribe_loop(engine: Arc<Engine>) {
233 let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE);
234 interval.tick().await;
235 loop {
236 interval.tick().await;
237 let _ = engine.resubscribe_presence().await;
238 }
239}
240
225pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
241pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
226 let conversation_id = event.conversation_id.clone()?;
242 let conversation_id = event.conversation_id.clone()?;
227 match event.kind {
243 match event.kind {
crates/app/src/data.rs +37 −7
@@ -14,6 +14,7 @@ use crate::runtime;
14 14
15 15 const FAVORITES_KIND_MARKER: &str = "favorite";
16 16 const PRESENCE_MAX_AGE: Duration = Duration::from_secs(60);
17 const PUSHED_PRESENCE_MAX_AGE: Duration = Duration::from_secs(5 * 60);
17 18 const MEMBER_FACE_LIMIT: usize = 2;
18 19
19 20 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -229,21 +230,28 @@ impl Directory {
229 230 self.presence_pending.iter().cloned().collect()
230 231 }
231 232
232 pub fn set_presence(&mut self, user_id: &str, kind: PresenceKind) {
233 pub fn set_presence(&mut self, user_id: &str, kind: PresenceKind) -> bool {
233 234 self.presence
234 .insert(user_id.to_owned(), (kind, Instant::now()));
235 .insert(user_id.to_owned(), (kind, Instant::now()))
236 .is_none_or(|(previous, _)| previous != kind)
235 237 }
236 238
237 239 pub fn stale_presence(
238 240 &self,
239 241 user_ids: impl IntoIterator<Item = String>,
240 242 now: Instant,
243 pushed: bool,
241 244 ) -> Vec<String> {
245 let max_age = if pushed {
246 PUSHED_PRESENCE_MAX_AGE
247 } else {
248 PRESENCE_MAX_AGE
249 };
242 250 let mut seen = HashSet::new();
243 251 user_ids
244 252 .into_iter()
245 253 .filter(|user_id| {
246 let fresh = |at: &Instant| now.duration_since(*at) < PRESENCE_MAX_AGE;
254 let fresh = |at: &Instant| now.duration_since(*at) < max_age;
247 255 let known_fresh = self.presence.get(user_id).is_some_and(|(_, at)| fresh(at));
248 256 let asked_fresh = self.presence_requested.get(user_id).is_some_and(fresh);
249 257 !known_fresh && !asked_fresh && seen.insert(user_id.clone())
@@ -444,6 +452,11 @@ pub fn refresh_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
444 452 run(async move { engine.refresh_presence(&user_ids).await })
445 453 }
446 454
455 pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
456 let engine = engine.clone();
457 run(async move { engine.watch_presence(&user_ids).await })
458 }
459
447 460 pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
448 461 let (engine, conversation_id, folder_id) = (
449 462 engine.clone(),
@@ -515,15 +528,32 @@ mod tests {
515 528 }
516 529
517 530 #[test]
518 fn presence_is_refetched_after_a_minute() {
531 fn presence_is_refetched_after_the_max_age() {
519 532 let mut directory = Directory::default();
520 533 let start = Instant::now();
521 let wanted = directory.stale_presence(["u".to_owned()], start);
534 let wanted = directory.stale_presence(["u".to_owned()], start, false);
522 535 assert_eq!(wanted, vec!["u"]);
523 536 directory.mark_presence_requested(&wanted, start);
524 assert!(directory.stale_presence(["u".to_owned()], start).is_empty());
537 assert!(
538 directory
539 .stale_presence(["u".to_owned()], start, false)
540 .is_empty()
541 );
525 542 let later = start + PRESENCE_MAX_AGE + Duration::from_secs(1);
526 assert_eq!(directory.stale_presence(["u".to_owned()], later), vec!["u"]);
543 assert_eq!(
544 directory.stale_presence(["u".to_owned()], later, false),
545 vec!["u"]
546 );
547 assert!(
548 directory
549 .stale_presence(["u".to_owned()], later, true)
550 .is_empty()
551 );
552 let much_later = start + PUSHED_PRESENCE_MAX_AGE + Duration::from_secs(1);
553 assert_eq!(
554 directory.stale_presence(["u".to_owned()], much_later, true),
555 vec!["u"]
556 );
527 557 assert_eq!(directory.presence_of("u").kind(), PresenceKind::Unknown);
528 558 }
529 559
@@ -14,6 +14,7 @@ use crate::runtime;
14
14
15const FAVORITES_KIND_MARKER: &str = "favorite";
15const FAVORITES_KIND_MARKER: &str = "favorite";
16const PRESENCE_MAX_AGE: Duration = Duration::from_secs(60);
16const PRESENCE_MAX_AGE: Duration = Duration::from_secs(60);
17const PUSHED_PRESENCE_MAX_AGE: Duration = Duration::from_secs(5 * 60);
17const MEMBER_FACE_LIMIT: usize = 2;
18const MEMBER_FACE_LIMIT: usize = 2;
18
19
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[derive(Debug, Clone, PartialEq, Eq)]
@@ -229,21 +230,28 @@ impl Directory {
229 self.presence_pending.iter().cloned().collect()
230 self.presence_pending.iter().cloned().collect()
230 }
231 }
231
232
232 pub fn set_presence(&mut self, user_id: &str, kind: PresenceKind) {
233 pub fn set_presence(&mut self, user_id: &str, kind: PresenceKind) -> bool {
233 self.presence
234 self.presence
234 .insert(user_id.to_owned(), (kind, Instant::now()));
235 .insert(user_id.to_owned(), (kind, Instant::now()))
236 .is_none_or(|(previous, _)| previous != kind)
235 }
237 }
236
238
237 pub fn stale_presence(
239 pub fn stale_presence(
238 &self,
240 &self,
239 user_ids: impl IntoIterator<Item = String>,
241 user_ids: impl IntoIterator<Item = String>,
240 now: Instant,
242 now: Instant,
243 pushed: bool,
241 ) -> Vec<String> {
244 ) -> Vec<String> {
245 let max_age = if pushed {
246 PUSHED_PRESENCE_MAX_AGE
247 } else {
248 PRESENCE_MAX_AGE
249 };
242 let mut seen = HashSet::new();
250 let mut seen = HashSet::new();
243 user_ids
251 user_ids
244 .into_iter()
252 .into_iter()
245 .filter(|user_id| {
253 .filter(|user_id| {
246 let fresh = |at: &Instant| now.duration_since(*at) < PRESENCE_MAX_AGE;
254 let fresh = |at: &Instant| now.duration_since(*at) < max_age;
247 let known_fresh = self.presence.get(user_id).is_some_and(|(_, at)| fresh(at));
255 let known_fresh = self.presence.get(user_id).is_some_and(|(_, at)| fresh(at));
248 let asked_fresh = self.presence_requested.get(user_id).is_some_and(fresh);
256 let asked_fresh = self.presence_requested.get(user_id).is_some_and(fresh);
249 !known_fresh && !asked_fresh && seen.insert(user_id.clone())
257 !known_fresh && !asked_fresh && seen.insert(user_id.clone())
@@ -444,6 +452,11 @@ pub fn refresh_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
444 run(async move { engine.refresh_presence(&user_ids).await })
452 run(async move { engine.refresh_presence(&user_ids).await })
445}
453}
446
454
455pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
456 let engine = engine.clone();
457 run(async move { engine.watch_presence(&user_ids).await })
458}
459
447pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
460pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
448 let (engine, conversation_id, folder_id) = (
461 let (engine, conversation_id, folder_id) = (
449 engine.clone(),
462 engine.clone(),
@@ -515,15 +528,32 @@ mod tests {
515 }
528 }
516
529
517 #[test]
530 #[test]
518 fn presence_is_refetched_after_a_minute() {
531 fn presence_is_refetched_after_the_max_age() {
519 let mut directory = Directory::default();
532 let mut directory = Directory::default();
520 let start = Instant::now();
533 let start = Instant::now();
521 let wanted = directory.stale_presence(["u".to_owned()], start);
534 let wanted = directory.stale_presence(["u".to_owned()], start, false);
522 assert_eq!(wanted, vec!["u"]);
535 assert_eq!(wanted, vec!["u"]);
523 directory.mark_presence_requested(&wanted, start);
536 directory.mark_presence_requested(&wanted, start);
524 assert!(directory.stale_presence(["u".to_owned()], start).is_empty());
537 assert!(
538 directory
539 .stale_presence(["u".to_owned()], start, false)
540 .is_empty()
541 );
525 let later = start + PRESENCE_MAX_AGE + Duration::from_secs(1);
542 let later = start + PRESENCE_MAX_AGE + Duration::from_secs(1);
526 assert_eq!(directory.stale_presence(["u".to_owned()], later), vec!["u"]);
543 assert_eq!(
544 directory.stale_presence(["u".to_owned()], later, false),
545 vec!["u"]
546 );
547 assert!(
548 directory
549 .stale_presence(["u".to_owned()], later, true)
550 .is_empty()
551 );
552 let much_later = start + PUSHED_PRESENCE_MAX_AGE + Duration::from_secs(1);
553 assert_eq!(
554 directory.stale_presence(["u".to_owned()], much_later, true),
555 vec!["u"]
556 );
527 assert_eq!(directory.presence_of("u").kind(), PresenceKind::Unknown);
557 assert_eq!(directory.presence_of("u").kind(), PresenceKind::Unknown);
528 }
558 }
529
559
crates/chatsvc/assets/trouter.js +16 −5
@@ -1,5 +1,5 @@
1 1 (() => {
2 const VERSION = 1;
2 const VERSION = 2;
3 3 const GLOBAL_NAME = '__chatsvcTrouter';
4 4 const BINDING_NAME = '__chatsvcRealtime';
5 5 const EPID_KEY = '__chatsvcEpid';
@@ -11,6 +11,8 @@
11 11 const CONNECT_TIMEOUT_MS = 20000;
12 12 const MAX_BACKOFF_MS = 30000;
13 13 const MAX_QUEUE = 200;
14 const MAX_PRESENCE_ENTRIES = 1000;
15 const MAX_PRESENCE_FIELD = 128;
14 16
15 17 if (window.top !== window || !location.origin.startsWith('https://teams.')) return;
16 18 const existing = window[GLOBAL_NAME];
@@ -30,7 +32,7 @@
30 32 };
31 33
32 34 const state = {
33 token: null, host: null, forwardPresence: false, epid: loadEpid(), socket: null, ready: false,
35 token: null, host: null, epid: loadEpid(), socket: null, ready: false,
34 36 closed: false, ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
35 37 };
36 38
@@ -48,6 +50,7 @@
48 50 flush();
49 51 };
50 52 const status = (kind, detail) => forward({channel: 'status', kind, detail: detail || ''});
53 const announceEndpoint = () => forward({channel: 'endpoint', endpointId: state.epid, trouterUri: state.surl + '/unifiedPresenceService'});
51 54
52 55 const conversationOf = (resource) => {
53 56 const link = (resource && (resource.conversationLink || resource.to || resource.id)) || '';
@@ -69,7 +72,12 @@
69 72 const forwardNotification = (path, body) => {
70 73 const receivedAt = Date.now();
71 74 if (path === 'unifiedPresenceService') {
72 if (state.forwardPresence) forward({channel: 'event', resourceType: 'presence', conversationId: null, messageId: null, eventKind: 'presence', receivedAt});
75 const cut = (value) => (typeof value === 'string' ? value.slice(0, MAX_PRESENCE_FIELD) : null);
76 const entries = ((body && Array.isArray(body.presence)) ? body.presence : []).slice(0, MAX_PRESENCE_ENTRIES)
77 .map((entry) => ({mri: cut(entry && entry.mri), availability: cut(entry && entry.presence && entry.presence.availability),
78 activity: cut(entry && entry.presence && entry.presence.activity)}))
79 .filter((entry) => entry.mri && entry.availability);
80 if (entries.length) forward({channel: 'presence', entries});
73 81 return;
74 82 }
75 83 const resource = body && body.resource;
@@ -140,6 +148,7 @@
140 148 activity();
141 149 state.ready = true;
142 150 state.retry = 0;
151 announceEndpoint();
143 152 status('connected');
144 153 } catch (error) {
145 154 status('error', registerDetail(error));
@@ -202,9 +211,11 @@
202 211 ensure: (config) => {
203 212 state.token = config.token;
204 213 state.host = config.host;
205 state.forwardPresence = !!config.forwardPresence;
206 214 connect();
207 if (state.ready) status('connected', 'reattached');
215 if (state.ready) {
216 announceEndpoint();
217 status('connected', 'reattached');
218 }
208 219 flush();
209 220 return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';
210 221 },
@@ -1,5 +1,5 @@
1(() => {
1(() => {
2 const VERSION = 1;
2 const VERSION = 2;
3 const GLOBAL_NAME = '__chatsvcTrouter';
3 const GLOBAL_NAME = '__chatsvcTrouter';
4 const BINDING_NAME = '__chatsvcRealtime';
4 const BINDING_NAME = '__chatsvcRealtime';
5 const EPID_KEY = '__chatsvcEpid';
5 const EPID_KEY = '__chatsvcEpid';
@@ -11,6 +11,8 @@
11 const CONNECT_TIMEOUT_MS = 20000;
11 const CONNECT_TIMEOUT_MS = 20000;
12 const MAX_BACKOFF_MS = 30000;
12 const MAX_BACKOFF_MS = 30000;
13 const MAX_QUEUE = 200;
13 const MAX_QUEUE = 200;
14 const MAX_PRESENCE_ENTRIES = 1000;
15 const MAX_PRESENCE_FIELD = 128;
14
16
15 if (window.top !== window || !location.origin.startsWith('https://teams.')) return;
17 if (window.top !== window || !location.origin.startsWith('https://teams.')) return;
16 const existing = window[GLOBAL_NAME];
18 const existing = window[GLOBAL_NAME];
@@ -30,7 +32,7 @@
30 };
32 };
31
33
32 const state = {
34 const state = {
33 token: null, host: null, forwardPresence: false, epid: loadEpid(), socket: null, ready: false,
35 token: null, host: null, epid: loadEpid(), socket: null, ready: false,
34 closed: false, ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
36 closed: false, ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
35 };
37 };
36
38
@@ -48,6 +50,7 @@
48 flush();
50 flush();
49 };
51 };
50 const status = (kind, detail) => forward({channel: 'status', kind, detail: detail || ''});
52 const status = (kind, detail) => forward({channel: 'status', kind, detail: detail || ''});
53 const announceEndpoint = () => forward({channel: 'endpoint', endpointId: state.epid, trouterUri: state.surl + '/unifiedPresenceService'});
51
54
52 const conversationOf = (resource) => {
55 const conversationOf = (resource) => {
53 const link = (resource && (resource.conversationLink || resource.to || resource.id)) || '';
56 const link = (resource && (resource.conversationLink || resource.to || resource.id)) || '';
@@ -69,7 +72,12 @@
69 const forwardNotification = (path, body) => {
72 const forwardNotification = (path, body) => {
70 const receivedAt = Date.now();
73 const receivedAt = Date.now();
71 if (path === 'unifiedPresenceService') {
74 if (path === 'unifiedPresenceService') {
72 if (state.forwardPresence) forward({channel: 'event', resourceType: 'presence', conversationId: null, messageId: null, eventKind: 'presence', receivedAt});
75 const cut = (value) => (typeof value === 'string' ? value.slice(0, MAX_PRESENCE_FIELD) : null);
76 const entries = ((body && Array.isArray(body.presence)) ? body.presence : []).slice(0, MAX_PRESENCE_ENTRIES)
77 .map((entry) => ({mri: cut(entry && entry.mri), availability: cut(entry && entry.presence && entry.presence.availability),
78 activity: cut(entry && entry.presence && entry.presence.activity)}))
79 .filter((entry) => entry.mri && entry.availability);
80 if (entries.length) forward({channel: 'presence', entries});
73 return;
81 return;
74 }
82 }
75 const resource = body && body.resource;
83 const resource = body && body.resource;
@@ -140,6 +148,7 @@
140 activity();
148 activity();
141 state.ready = true;
149 state.ready = true;
142 state.retry = 0;
150 state.retry = 0;
151 announceEndpoint();
143 status('connected');
152 status('connected');
144 } catch (error) {
153 } catch (error) {
145 status('error', registerDetail(error));
154 status('error', registerDetail(error));
@@ -202,9 +211,11 @@
202 ensure: (config) => {
211 ensure: (config) => {
203 state.token = config.token;
212 state.token = config.token;
204 state.host = config.host;
213 state.host = config.host;
205 state.forwardPresence = !!config.forwardPresence;
206 connect();
214 connect();
207 if (state.ready) status('connected', 'reattached');
215 if (state.ready) {
216 announceEndpoint();
217 status('connected', 'reattached');
218 }
208 flush();
219 flush();
209 return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';
220 return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';
210 },
221 },
crates/chatsvc/examples/live.rs +10 −1
@@ -46,6 +46,16 @@ fn describe(event: &RealtimeEvent) -> String {
46 46 .unwrap_or_else(|| "-".into()),
47 47 ),
48 48 RealtimeEvent::Status(status) => format!("# status {:?} {}", status.kind, status.detail),
49 RealtimeEvent::Presence(updates) => format!("# presence updates={}", updates.len()),
50 RealtimeEvent::Endpoint(endpoint) => format!(
51 "# endpoint host={}",
52 endpoint
53 .trouter_uri
54 .trim_start_matches("https://")
55 .split('/')
56 .next()
57 .unwrap_or("-")
58 ),
49 59 }
50 60 }
51 61
@@ -58,7 +68,6 @@ fn kind_name(kind: EventKind) -> &'static str {
58 68 EventKind::ReadReceipt => "read_receipt",
59 69 EventKind::ThreadActivity => "thread_activity",
60 70 EventKind::Control => "control",
61 EventKind::Presence => "presence",
62 71 EventKind::Other => "other",
63 72 }
64 73 }
@@ -46,6 +46,16 @@ fn describe(event: &RealtimeEvent) -> String {
46 .unwrap_or_else(|| "-".into()),
46 .unwrap_or_else(|| "-".into()),
47 ),
47 ),
48 RealtimeEvent::Status(status) => format!("# status {:?} {}", status.kind, status.detail),
48 RealtimeEvent::Status(status) => format!("# status {:?} {}", status.kind, status.detail),
49 RealtimeEvent::Presence(updates) => format!("# presence updates={}", updates.len()),
50 RealtimeEvent::Endpoint(endpoint) => format!(
51 "# endpoint host={}",
52 endpoint
53 .trouter_uri
54 .trim_start_matches("https://")
55 .split('/')
56 .next()
57 .unwrap_or("-")
58 ),
49 }
59 }
50}
60}
51
61
@@ -58,7 +68,6 @@ fn kind_name(kind: EventKind) -> &'static str {
58 EventKind::ReadReceipt => "read_receipt",
68 EventKind::ReadReceipt => "read_receipt",
59 EventKind::ThreadActivity => "thread_activity",
69 EventKind::ThreadActivity => "thread_activity",
60 EventKind::Control => "control",
70 EventKind::Control => "control",
61 EventKind::Presence => "presence",
62 EventKind::Other => "other",
71 EventKind::Other => "other",
63 }
72 }
64}
73}
crates/chatsvc/src/lib.rs +2 −1
@@ -12,6 +12,7 @@ pub use pins::{
12 12 ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,
13 13 };
14 14 pub use realtime::{
15 EventKind, MessageEvent, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind,
15 EventKind, MessageEvent, PresenceUpdate, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent,
16 StatusKind, TrouterEndpoint,
16 17 };
17 18 pub use receipts::{MemberHorizon, Receipts};
@@ -12,6 +12,7 @@ pub use pins::{
12 ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,
12 ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,
13};
13};
14pub use realtime::{
14pub use realtime::{
15 EventKind, MessageEvent, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind,
15 EventKind, MessageEvent, PresenceUpdate, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent,
16 StatusKind, TrouterEndpoint,
16};
17};
17pub use receipts::{MemberHorizon, Receipts};
18pub use receipts::{MemberHorizon, Receipts};
crates/chatsvc/src/realtime/event.rs +133 −2
@@ -1,9 +1,12 @@
1 1 use chrono::{DateTime, Utc};
2 2 use serde::Deserialize;
3 3
4 use super::host::is_trouter_host;
4 5 use crate::error::{Error, Result};
5 6
6 7 const MAX_FIELD_LENGTH: usize = 256;
8 const ORGID_PREFIX: &str = "8:orgid:";
9 const HTTPS_PREFIX: &str = "https://";
7 10
8 11 #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
9 12 #[serde(rename_all = "snake_case")]
@@ -15,7 +18,6 @@ pub enum EventKind {
15 18 ReadReceipt,
16 19 ThreadActivity,
17 20 Control,
18 Presence,
19 21 #[serde(other)]
20 22 Other,
21 23 }
@@ -44,10 +46,33 @@ pub struct StatusEvent {
44 46 pub detail: String,
45 47 }
46 48
49 #[derive(Debug, Clone, PartialEq, Eq)]
50 pub struct PresenceUpdate {
51 pub user_id: String,
52 pub availability: String,
53 pub activity: Option<String>,
54 }
55
56 #[derive(Debug, Clone, PartialEq, Eq)]
57 pub struct TrouterEndpoint {
58 pub endpoint_id: String,
59 pub trouter_uri: String,
60 }
61
47 62 #[derive(Debug, Clone, PartialEq, Eq)]
48 63 pub enum RealtimeEvent {
49 64 Message(MessageEvent),
50 65 Status(StatusEvent),
66 Presence(Vec<PresenceUpdate>),
67 Endpoint(TrouterEndpoint),
68 }
69
70 #[derive(Deserialize)]
71 struct WirePresence {
72 mri: String,
73 availability: String,
74 #[serde(default)]
75 activity: Option<String>,
51 76 }
52 77
53 78 #[derive(Deserialize)]
@@ -70,6 +95,15 @@ enum Wire {
70 95 #[serde(default)]
71 96 detail: String,
72 97 },
98 Presence {
99 entries: Vec<WirePresence>,
100 },
101 Endpoint {
102 #[serde(rename = "endpointId")]
103 endpoint_id: String,
104 #[serde(rename = "trouterUri")]
105 trouter_uri: String,
106 },
73 107 }
74 108
75 109 pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
@@ -99,6 +133,50 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
99 133 kind,
100 134 detail: bounded(detail),
101 135 })),
136 Wire::Presence { entries } => Ok(RealtimeEvent::Presence(
137 entries
138 .into_iter()
139 .filter_map(|entry| {
140 let user_id = entry.mri.strip_prefix(ORGID_PREFIX)?;
141 Some(PresenceUpdate {
142 user_id: bounded(user_id.to_owned()),
143 availability: bounded(entry.availability),
144 activity: entry
145 .activity
146 .map(bounded)
147 .filter(|value| !value.is_empty()),
148 })
149 })
150 .collect(),
151 )),
152 Wire::Endpoint {
153 endpoint_id,
154 trouter_uri,
155 } => {
156 let host = trouter_uri
157 .strip_prefix(HTTPS_PREFIX)
158 .and_then(|rest| rest.split('/').next())
159 .map(without_port)
160 .filter(|host| is_trouter_host(host));
161 if host.is_none() || endpoint_id.is_empty() {
162 return Err(Error::Decode("endpoint rejected".into()));
163 }
164 Ok(RealtimeEvent::Endpoint(TrouterEndpoint {
165 endpoint_id: bounded(endpoint_id),
166 trouter_uri,
167 }))
168 }
169 }
170 }
171
172 fn without_port(authority: &str) -> &str {
173 match authority.rsplit_once(':') {
174 Some((host, port))
175 if !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit()) =>
176 {
177 host
178 }
179 _ => authority,
102 180 }
103 181 }
104 182
@@ -126,7 +204,7 @@ mod tests {
126 204
127 205 #[test]
128 206 fn null_and_empty_ids_become_none() {
129 let payload = r#"{"channel":"event","resourceType":"presence","eventKind":"presence",
207 let payload = r#"{"channel":"event","resourceType":"typing","eventKind":"typing",
130 208 "conversationId":null,"messageId":"","receivedAt":1}"#;
131 209 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
132 210 panic!("expected message")
@@ -186,6 +264,59 @@ mod tests {
186 264 assert_eq!(status.detail.chars().count(), MAX_FIELD_LENGTH);
187 265 }
188 266
267 #[test]
268 fn decodes_presence_and_skips_foreign_mris() {
269 let payload = r#"{"channel":"presence","entries":[
270 {"mri":"8:orgid:abc","availability":"Busy","activity":"InACall"},
271 {"mri":"8:orgid:def","availability":"Away","activity":""},
272 {"mri":"4:+4912345","availability":"Offline"}]}"#;
273 let RealtimeEvent::Presence(updates) = decode_payload(payload).unwrap() else {
274 panic!("expected presence")
275 };
276 assert_eq!(
277 updates,
278 vec![
279 PresenceUpdate {
280 user_id: "abc".into(),
281 availability: "Busy".into(),
282 activity: Some("InACall".into()),
283 },
284 PresenceUpdate {
285 user_id: "def".into(),
286 availability: "Away".into(),
287 activity: None,
288 },
289 ]
290 );
291 }
292
293 #[test]
294 fn decodes_endpoint_on_a_trouter_host() {
295 let payload = r#"{"channel":"endpoint","endpointId":"e1",
296 "trouterUri":"https://pub-ent-sece-04-f.trouter.teams.microsoft.com:3443/v4/f/x/unifiedPresenceService"}"#;
297 let RealtimeEvent::Endpoint(endpoint) = decode_payload(payload).unwrap() else {
298 panic!("expected endpoint")
299 };
300 assert_eq!(endpoint.endpoint_id, "e1");
301 assert!(endpoint.trouter_uri.ends_with("/unifiedPresenceService"));
302 }
303
304 #[test]
305 fn rejects_endpoints_off_trouter_or_without_https() {
306 for uri in [
307 "https://evil.example/unifiedPresenceService",
308 "http://go-eu.trouter.teams.microsoft.com/x",
309 "https://go-eu.trouter.teams.microsoft.com.evil.com/x",
310 "https://a@go-eu.trouter.teams.microsoft.com/x",
311 "https://go-eu.trouter.teams.microsoft.com:x/x",
312 "go-eu.trouter.teams.microsoft.com/x",
313 ] {
314 let payload =
315 format!(r#"{{"channel":"endpoint","endpointId":"e1","trouterUri":"{uri}"}}"#);
316 assert!(decode_payload(&payload).is_err(), "{uri}");
317 }
318 }
319
189 320 #[test]
190 321 fn rejects_garbage() {
191 322 assert!(decode_payload("not json").is_err());
@@ -1,9 +1,12 @@
1use chrono::{DateTime, Utc};
1use chrono::{DateTime, Utc};
2use serde::Deserialize;
2use serde::Deserialize;
3
3
4use super::host::is_trouter_host;
4use crate::error::{Error, Result};
5use crate::error::{Error, Result};
5
6
6const MAX_FIELD_LENGTH: usize = 256;
7const MAX_FIELD_LENGTH: usize = 256;
8const ORGID_PREFIX: &str = "8:orgid:";
9const HTTPS_PREFIX: &str = "https://";
7
10
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
9#[serde(rename_all = "snake_case")]
12#[serde(rename_all = "snake_case")]
@@ -15,7 +18,6 @@ pub enum EventKind {
15 ReadReceipt,
18 ReadReceipt,
16 ThreadActivity,
19 ThreadActivity,
17 Control,
20 Control,
18 Presence,
19 #[serde(other)]
21 #[serde(other)]
20 Other,
22 Other,
21}
23}
@@ -44,10 +46,33 @@ pub struct StatusEvent {
44 pub detail: String,
46 pub detail: String,
45}
47}
46
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct PresenceUpdate {
51 pub user_id: String,
52 pub availability: String,
53 pub activity: Option<String>,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct TrouterEndpoint {
58 pub endpoint_id: String,
59 pub trouter_uri: String,
60}
61
47#[derive(Debug, Clone, PartialEq, Eq)]
62#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum RealtimeEvent {
63pub enum RealtimeEvent {
49 Message(MessageEvent),
64 Message(MessageEvent),
50 Status(StatusEvent),
65 Status(StatusEvent),
66 Presence(Vec<PresenceUpdate>),
67 Endpoint(TrouterEndpoint),
68}
69
70#[derive(Deserialize)]
71struct WirePresence {
72 mri: String,
73 availability: String,
74 #[serde(default)]
75 activity: Option<String>,
51}
76}
52
77
53#[derive(Deserialize)]
78#[derive(Deserialize)]
@@ -70,6 +95,15 @@ enum Wire {
70 #[serde(default)]
95 #[serde(default)]
71 detail: String,
96 detail: String,
72 },
97 },
98 Presence {
99 entries: Vec<WirePresence>,
100 },
101 Endpoint {
102 #[serde(rename = "endpointId")]
103 endpoint_id: String,
104 #[serde(rename = "trouterUri")]
105 trouter_uri: String,
106 },
73}
107}
74
108
75pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
109pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
@@ -99,6 +133,50 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
99 kind,
133 kind,
100 detail: bounded(detail),
134 detail: bounded(detail),
101 })),
135 })),
136 Wire::Presence { entries } => Ok(RealtimeEvent::Presence(
137 entries
138 .into_iter()
139 .filter_map(|entry| {
140 let user_id = entry.mri.strip_prefix(ORGID_PREFIX)?;
141 Some(PresenceUpdate {
142 user_id: bounded(user_id.to_owned()),
143 availability: bounded(entry.availability),
144 activity: entry
145 .activity
146 .map(bounded)
147 .filter(|value| !value.is_empty()),
148 })
149 })
150 .collect(),
151 )),
152 Wire::Endpoint {
153 endpoint_id,
154 trouter_uri,
155 } => {
156 let host = trouter_uri
157 .strip_prefix(HTTPS_PREFIX)
158 .and_then(|rest| rest.split('/').next())
159 .map(without_port)
160 .filter(|host| is_trouter_host(host));
161 if host.is_none() || endpoint_id.is_empty() {
162 return Err(Error::Decode("endpoint rejected".into()));
163 }
164 Ok(RealtimeEvent::Endpoint(TrouterEndpoint {
165 endpoint_id: bounded(endpoint_id),
166 trouter_uri,
167 }))
168 }
169 }
170}
171
172fn without_port(authority: &str) -> &str {
173 match authority.rsplit_once(':') {
174 Some((host, port))
175 if !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit()) =>
176 {
177 host
178 }
179 _ => authority,
102 }
180 }
103}
181}
104
182
@@ -126,7 +204,7 @@ mod tests {
126
204
127 #[test]
205 #[test]
128 fn null_and_empty_ids_become_none() {
206 fn null_and_empty_ids_become_none() {
129 let payload = r#"{"channel":"event","resourceType":"presence","eventKind":"presence",
207 let payload = r#"{"channel":"event","resourceType":"typing","eventKind":"typing",
130 "conversationId":null,"messageId":"","receivedAt":1}"#;
208 "conversationId":null,"messageId":"","receivedAt":1}"#;
131 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
209 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
132 panic!("expected message")
210 panic!("expected message")
@@ -186,6 +264,59 @@ mod tests {
186 assert_eq!(status.detail.chars().count(), MAX_FIELD_LENGTH);
264 assert_eq!(status.detail.chars().count(), MAX_FIELD_LENGTH);
187 }
265 }
188
266
267 #[test]
268 fn decodes_presence_and_skips_foreign_mris() {
269 let payload = r#"{"channel":"presence","entries":[
270 {"mri":"8:orgid:abc","availability":"Busy","activity":"InACall"},
271 {"mri":"8:orgid:def","availability":"Away","activity":""},
272 {"mri":"4:+4912345","availability":"Offline"}]}"#;
273 let RealtimeEvent::Presence(updates) = decode_payload(payload).unwrap() else {
274 panic!("expected presence")
275 };
276 assert_eq!(
277 updates,
278 vec![
279 PresenceUpdate {
280 user_id: "abc".into(),
281 availability: "Busy".into(),
282 activity: Some("InACall".into()),
283 },
284 PresenceUpdate {
285 user_id: "def".into(),
286 availability: "Away".into(),
287 activity: None,
288 },
289 ]
290 );
291 }
292
293 #[test]
294 fn decodes_endpoint_on_a_trouter_host() {
295 let payload = r#"{"channel":"endpoint","endpointId":"e1",
296 "trouterUri":"https://pub-ent-sece-04-f.trouter.teams.microsoft.com:3443/v4/f/x/unifiedPresenceService"}"#;
297 let RealtimeEvent::Endpoint(endpoint) = decode_payload(payload).unwrap() else {
298 panic!("expected endpoint")
299 };
300 assert_eq!(endpoint.endpoint_id, "e1");
301 assert!(endpoint.trouter_uri.ends_with("/unifiedPresenceService"));
302 }
303
304 #[test]
305 fn rejects_endpoints_off_trouter_or_without_https() {
306 for uri in [
307 "https://evil.example/unifiedPresenceService",
308 "http://go-eu.trouter.teams.microsoft.com/x",
309 "https://go-eu.trouter.teams.microsoft.com.evil.com/x",
310 "https://a@go-eu.trouter.teams.microsoft.com/x",
311 "https://go-eu.trouter.teams.microsoft.com:x/x",
312 "go-eu.trouter.teams.microsoft.com/x",
313 ] {
314 let payload =
315 format!(r#"{{"channel":"endpoint","endpointId":"e1","trouterUri":"{uri}"}}"#);
316 assert!(decode_payload(&payload).is_err(), "{uri}");
317 }
318 }
319
189 #[test]
320 #[test]
190 fn rejects_garbage() {
321 fn rejects_garbage() {
191 assert!(decode_payload("not json").is_err());
322 assert!(decode_payload("not json").is_err());
crates/chatsvc/src/realtime/mod.rs +4 −3
@@ -11,7 +11,10 @@ use session::Session;
11 11 use tokio::sync::{mpsc, oneshot};
12 12 use tokio::task::JoinHandle;
13 13
14 pub use event::{EventKind, MessageEvent, RealtimeEvent, StatusEvent, StatusKind, decode_payload};
14 pub use event::{
15 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
16 TrouterEndpoint, decode_payload,
17 };
15 18 pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
16 19
17 20 use crate::error::Result;
@@ -24,7 +27,6 @@ pub struct RealtimeConfig {
24 27 pub host: Option<String>,
25 28 pub default_host: String,
26 29 pub discover_host: bool,
27 pub forward_presence: bool,
28 30 pub ensure_interval: Duration,
29 31 pub navigation_settle: Duration,
30 32 pub max_reattach_backoff: Duration,
@@ -36,7 +38,6 @@ impl Default for RealtimeConfig {
36 38 host: None,
37 39 default_host: DEFAULT_TROUTER_HOST.to_owned(),
38 40 discover_host: true,
39 forward_presence: false,
40 41 ensure_interval: Duration::from_secs(30),
41 42 navigation_settle: Duration::from_millis(1500),
42 43 max_reattach_backoff: Duration::from_secs(30),
@@ -11,7 +11,10 @@ use session::Session;
11use tokio::sync::{mpsc, oneshot};
11use tokio::sync::{mpsc, oneshot};
12use tokio::task::JoinHandle;
12use tokio::task::JoinHandle;
13
13
14pub use event::{EventKind, MessageEvent, RealtimeEvent, StatusEvent, StatusKind, decode_payload};
14pub use event::{
15 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
16 TrouterEndpoint, decode_payload,
17};
15pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
18pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
16
19
17use crate::error::Result;
20use crate::error::Result;
@@ -24,7 +27,6 @@ pub struct RealtimeConfig {
24 pub host: Option<String>,
27 pub host: Option<String>,
25 pub default_host: String,
28 pub default_host: String,
26 pub discover_host: bool,
29 pub discover_host: bool,
27 pub forward_presence: bool,
28 pub ensure_interval: Duration,
30 pub ensure_interval: Duration,
29 pub navigation_settle: Duration,
31 pub navigation_settle: Duration,
30 pub max_reattach_backoff: Duration,
32 pub max_reattach_backoff: Duration,
@@ -36,7 +38,6 @@ impl Default for RealtimeConfig {
36 host: None,
38 host: None,
37 default_host: DEFAULT_TROUTER_HOST.to_owned(),
39 default_host: DEFAULT_TROUTER_HOST.to_owned(),
38 discover_host: true,
40 discover_host: true,
39 forward_presence: false,
40 ensure_interval: Duration::from_secs(30),
41 ensure_interval: Duration::from_secs(30),
41 navigation_settle: Duration::from_millis(1500),
42 navigation_settle: Duration::from_millis(1500),
42 max_reattach_backoff: Duration::from_secs(30),
43 max_reattach_backoff: Duration::from_secs(30),
crates/chatsvc/src/realtime/runner.rs +3 −3
@@ -13,7 +13,7 @@ pub(super) const BINDING_NAME: &str = "__chatsvcRealtime";
13 13 const WORKER_SOURCE: &str = include_str!("../../assets/trouter.js");
14 14 const ENSURE_BODY: &str = concat!(
15 15 include_str!("../../assets/trouter.js"),
16 "\nreturn window.__chatsvcTrouter.ensure({token, host: args.host, forwardPresence: args.forwardPresence});"
16 "\nreturn window.__chatsvcTrouter.ensure({token, host: args.host});"
17 17 );
18 18 const STOP_EXPRESSION: &str = "window.__chatsvcTrouter ? window.__chatsvcTrouter.stop() : null";
19 19 const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
@@ -80,7 +80,7 @@ impl Runner {
80 80 }
81 81
82 82 pub(super) async fn ensure(&mut self) -> session::Result<Value> {
83 let args = json!({"host": self.host, "forwardPresence": self.config.forward_presence});
83 let args = json!({"host": self.host});
84 84 let outcome = self
85 85 .session
86 86 .run_with_token(
@@ -249,7 +249,7 @@ mod tests {
249 249 assert!(
250 250 ENSURE_BODY
251 251 .trim_end()
252 .ends_with("forwardPresence: args.forwardPresence});")
252 .ends_with("ensure({token, host: args.host});")
253 253 );
254 254 assert_eq!(ENSURE_BODY.matches("const VERSION").count(), 1);
255 255 }
@@ -13,7 +13,7 @@ pub(super) const BINDING_NAME: &str = "__chatsvcRealtime";
13const WORKER_SOURCE: &str = include_str!("../../assets/trouter.js");
13const WORKER_SOURCE: &str = include_str!("../../assets/trouter.js");
14const ENSURE_BODY: &str = concat!(
14const ENSURE_BODY: &str = concat!(
15 include_str!("../../assets/trouter.js"),
15 include_str!("../../assets/trouter.js"),
16 "\nreturn window.__chatsvcTrouter.ensure({token, host: args.host, forwardPresence: args.forwardPresence});"
16 "\nreturn window.__chatsvcTrouter.ensure({token, host: args.host});"
17);
17);
18const STOP_EXPRESSION: &str = "window.__chatsvcTrouter ? window.__chatsvcTrouter.stop() : null";
18const STOP_EXPRESSION: &str = "window.__chatsvcTrouter ? window.__chatsvcTrouter.stop() : null";
19const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
19const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
@@ -80,7 +80,7 @@ impl Runner {
80 }
80 }
81
81
82 pub(super) async fn ensure(&mut self) -> session::Result<Value> {
82 pub(super) async fn ensure(&mut self) -> session::Result<Value> {
83 let args = json!({"host": self.host, "forwardPresence": self.config.forward_presence});
83 let args = json!({"host": self.host});
84 let outcome = self
84 let outcome = self
85 .session
85 .session
86 .run_with_token(
86 .run_with_token(
@@ -249,7 +249,7 @@ mod tests {
249 assert!(
249 assert!(
250 ENSURE_BODY
250 ENSURE_BODY
251 .trim_end()
251 .trim_end()
252 .ends_with("forwardPresence: args.forwardPresence});")
252 .ends_with("ensure({token, host: args.host});")
253 );
253 );
254 assert_eq!(ENSURE_BODY.matches("const VERSION").count(), 1);
254 assert_eq!(ENSURE_BODY.matches("const VERSION").count(), 1);
255 }
255 }
crates/chatsvc/tests/realtime.rs +1 −1
@@ -164,7 +164,7 @@ async fn start_injects_worker_and_ensures_with_default_host() {
164 164 let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
165 165 assert_eq!(
166 166 arguments,
167 serde_json::json!({"forwardPresence": false, "host": "go-eu.trouter.teams.microsoft.com"})
167 serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com"})
168 168 );
169 169 realtime.stop().await;
170 170 }
@@ -164,7 +164,7 @@ async fn start_injects_worker_and_ensures_with_default_host() {
164 let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
164 let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
165 assert_eq!(
165 assert_eq!(
166 arguments,
166 arguments,
167 serde_json::json!({"forwardPresence": false, "host": "go-eu.trouter.teams.microsoft.com"})
167 serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com"})
168 );
168 );
169 realtime.stop().await;
169 realtime.stop().await;
170}
170}
crates/core/examples/live_presence.rs added +65 −0
@@ -0,0 +1,65 @@
1 use std::sync::Arc;
2 use std::time::{Duration, Instant};
3
4 use chatsvc::{Realtime, RealtimeEvent};
5 use graph::Graph;
6 use session::{DEFAULT_ENDPOINT, Session};
7 use store::Store;
8 use teams_core::SyncEngine;
9
10 #[tokio::main]
11 async fn main() {
12 let seconds: u64 = std::env::args()
13 .nth(1)
14 .and_then(|value| value.parse().ok())
15 .unwrap_or(120);
16 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
17 let session = Session::connect(&endpoint).await.expect("browser");
18 let engine = SyncEngine::new(
19 Graph::new(session.clone()),
20 Arc::new(Store::open_in_memory().unwrap()),
21 );
22 engine.refresh_sidebar().await.expect("sidebar");
23 let mut user_ids: Vec<String> = engine
24 .sidebar()
25 .unwrap()
26 .chats
27 .iter()
28 .flat_map(|chat| {
29 chat.members
30 .iter()
31 .filter_map(|member| member.user_id.clone())
32 })
33 .collect();
34 user_ids.sort();
35 user_ids.dedup();
36 engine.watch_presence(&user_ids).await.expect("watch");
37 println!("# watching {} users for {seconds}s", user_ids.len());
38 let mut realtime = Realtime::start(&session).await.expect("realtime start");
39 let started = Instant::now();
40 let deadline = tokio::time::sleep(Duration::from_secs(seconds));
41 tokio::pin!(deadline);
42 loop {
43 tokio::select! {
44 event = realtime.recv() => {
45 let Some(event) = event else { break };
46 let at = started.elapsed().as_secs_f32();
47 match event {
48 RealtimeEvent::Endpoint(endpoint) => {
49 let outcome = engine.presence_endpoint(endpoint).await;
50 println!("{at:6.1}s endpoint subscribe {:?}", outcome.map_err(|error| error.to_string()));
51 }
52 RealtimeEvent::Presence(updates) => {
53 engine.apply_presence(&updates);
54 let known = user_ids.iter().filter(|id| engine.presence(id).is_some()).count();
55 println!("{at:6.1}s presence push {} entries, known {known}/{}", updates.len(), user_ids.len());
56 }
57 RealtimeEvent::Status(status) => println!("{at:6.1}s status {:?} {}", status.kind, status.detail),
58 RealtimeEvent::Message(_) => {}
59 }
60 }
61 _ = &mut deadline => break,
62 }
63 }
64 realtime.stop().await;
65 }
@@ -0,0 +1,65 @@
1use std::sync::Arc;
2use std::time::{Duration, Instant};
3
4use chatsvc::{Realtime, RealtimeEvent};
5use graph::Graph;
6use session::{DEFAULT_ENDPOINT, Session};
7use store::Store;
8use teams_core::SyncEngine;
9
10#[tokio::main]
11async fn main() {
12 let seconds: u64 = std::env::args()
13 .nth(1)
14 .and_then(|value| value.parse().ok())
15 .unwrap_or(120);
16 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
17 let session = Session::connect(&endpoint).await.expect("browser");
18 let engine = SyncEngine::new(
19 Graph::new(session.clone()),
20 Arc::new(Store::open_in_memory().unwrap()),
21 );
22 engine.refresh_sidebar().await.expect("sidebar");
23 let mut user_ids: Vec<String> = engine
24 .sidebar()
25 .unwrap()
26 .chats
27 .iter()
28 .flat_map(|chat| {
29 chat.members
30 .iter()
31 .filter_map(|member| member.user_id.clone())
32 })
33 .collect();
34 user_ids.sort();
35 user_ids.dedup();
36 engine.watch_presence(&user_ids).await.expect("watch");
37 println!("# watching {} users for {seconds}s", user_ids.len());
38 let mut realtime = Realtime::start(&session).await.expect("realtime start");
39 let started = Instant::now();
40 let deadline = tokio::time::sleep(Duration::from_secs(seconds));
41 tokio::pin!(deadline);
42 loop {
43 tokio::select! {
44 event = realtime.recv() => {
45 let Some(event) = event else { break };
46 let at = started.elapsed().as_secs_f32();
47 match event {
48 RealtimeEvent::Endpoint(endpoint) => {
49 let outcome = engine.presence_endpoint(endpoint).await;
50 println!("{at:6.1}s endpoint subscribe {:?}", outcome.map_err(|error| error.to_string()));
51 }
52 RealtimeEvent::Presence(updates) => {
53 engine.apply_presence(&updates);
54 let known = user_ids.iter().filter(|id| engine.presence(id).is_some()).count();
55 println!("{at:6.1}s presence push {} entries, known {known}/{}", updates.len(), user_ids.len());
56 }
57 RealtimeEvent::Status(status) => println!("{at:6.1}s status {:?} {}", status.kind, status.detail),
58 RealtimeEvent::Message(_) => {}
59 }
60 }
61 _ = &mut deadline => break,
62 }
63 }
64 realtime.stop().await;
65}
crates/core/src/engine.rs +7 −0
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
2 2 use std::sync::atomic::{AtomicBool, Ordering};
3 3 use std::sync::{Arc, Mutex};
4 4
5 use chatsvc::TrouterEndpoint;
5 6 use chrono::{DateTime, Duration, Utc};
6 7 use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
7 8 use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
@@ -111,6 +112,9 @@ pub struct SyncEngine<R: Remote = Graph> {
111 112 my_tenant_id: OnceCell<String>,
112 113 pub(crate) folder_source: Option<Arc<dyn FolderSource>>,
113 114 pub(crate) presences: Mutex<HashMap<String, Presence>>,
115 pub(crate) watched_presence: Mutex<HashSet<String>>,
116 pub(crate) presence_endpoint: Mutex<Option<TrouterEndpoint>>,
117 pub(crate) presence_subscribing: tokio::sync::Mutex<()>,
114 118 pub(crate) avatars_in_flight: Mutex<HashSet<String>>,
115 119 pub(crate) images_in_flight: Mutex<HashSet<String>>,
116 120 pub(crate) image_files: Option<ImageFileCache>,
@@ -135,6 +139,9 @@ impl<R: Remote> SyncEngine<R> {
135 139 my_tenant_id: OnceCell::new(),
136 140 folder_source: None,
137 141 presences: Mutex::new(HashMap::new()),
142 watched_presence: Mutex::new(HashSet::new()),
143 presence_endpoint: Mutex::new(None),
144 presence_subscribing: tokio::sync::Mutex::new(()),
138 145 avatars_in_flight: Mutex::new(HashSet::new()),
139 146 images_in_flight: Mutex::new(HashSet::new()),
140 147 image_files: None,
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
2use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::{Arc, Mutex};
3use std::sync::{Arc, Mutex};
4
4
5use chatsvc::TrouterEndpoint;
5use chrono::{DateTime, Duration, Utc};
6use chrono::{DateTime, Duration, Utc};
6use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
7use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
7use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
8use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
@@ -111,6 +112,9 @@ pub struct SyncEngine<R: Remote = Graph> {
111 my_tenant_id: OnceCell<String>,
112 my_tenant_id: OnceCell<String>,
112 pub(crate) folder_source: Option<Arc<dyn FolderSource>>,
113 pub(crate) folder_source: Option<Arc<dyn FolderSource>>,
113 pub(crate) presences: Mutex<HashMap<String, Presence>>,
114 pub(crate) presences: Mutex<HashMap<String, Presence>>,
115 pub(crate) watched_presence: Mutex<HashSet<String>>,
116 pub(crate) presence_endpoint: Mutex<Option<TrouterEndpoint>>,
117 pub(crate) presence_subscribing: tokio::sync::Mutex<()>,
114 pub(crate) avatars_in_flight: Mutex<HashSet<String>>,
118 pub(crate) avatars_in_flight: Mutex<HashSet<String>>,
115 pub(crate) images_in_flight: Mutex<HashSet<String>>,
119 pub(crate) images_in_flight: Mutex<HashSet<String>>,
116 pub(crate) image_files: Option<ImageFileCache>,
120 pub(crate) image_files: Option<ImageFileCache>,
@@ -135,6 +139,9 @@ impl<R: Remote> SyncEngine<R> {
135 my_tenant_id: OnceCell::new(),
139 my_tenant_id: OnceCell::new(),
136 folder_source: None,
140 folder_source: None,
137 presences: Mutex::new(HashMap::new()),
141 presences: Mutex::new(HashMap::new()),
142 watched_presence: Mutex::new(HashSet::new()),
143 presence_endpoint: Mutex::new(None),
144 presence_subscribing: tokio::sync::Mutex::new(()),
138 avatars_in_flight: Mutex::new(HashSet::new()),
145 avatars_in_flight: Mutex::new(HashSet::new()),
139 images_in_flight: Mutex::new(HashSet::new()),
146 images_in_flight: Mutex::new(HashSet::new()),
140 image_files: None,
147 image_files: None,
crates/core/src/presence.rs +98 −11
@@ -1,8 +1,10 @@
1 use chatsvc::{PresenceUpdate, TrouterEndpoint};
1 2 use graph::MAX_PRESENCE_IDS;
2 3
3 4 use crate::engine::SyncEngine;
4 5 use crate::error::Result;
5 6 use crate::events::CoreEvent;
7 use crate::receipts::locked;
6 8 use crate::remote::Remote;
7 9
8 10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -54,21 +56,106 @@ impl<R: Remote> SyncEngine<R> {
54 56 let mut changed = false;
55 57 for chunk in unique.chunks(MAX_PRESENCE_IDS) {
56 58 let found = self.remote.presences(chunk).await?;
57 let mut known = self
58 .presences
59 .lock()
60 .unwrap_or_else(|poisoned| poisoned.into_inner());
61 for entry in found {
62 let presence = Presence {
63 availability: Availability::from_service(&entry.availability),
64 in_call: is_call_activity(entry.activity.as_deref()),
65 };
66 changed |= known.insert(entry.user_id, presence) != Some(presence);
67 }
59 changed |= self.record_presences(found.iter().map(|entry| {
60 (
61 &entry.user_id,
62 entry.availability.as_str(),
63 entry.activity.as_deref(),
64 )
65 }));
68 66 }
69 67 if changed {
70 68 let _ = self.events.send(CoreEvent::PresenceChanged);
71 69 }
72 70 Ok(())
73 71 }
72
73 pub fn apply_presence(&self, updates: &[PresenceUpdate]) {
74 let changed = self.record_presences(updates.iter().map(|update| {
75 (
76 &update.user_id,
77 update.availability.as_str(),
78 update.activity.as_deref(),
79 )
80 }));
81 if changed {
82 let _ = self.events.send(CoreEvent::PresenceChanged);
83 }
84 }
85
86 pub async fn watch_presence(&self, user_ids: &[String]) -> Result<()> {
87 let _subscribing = self.presence_subscribing.lock().await;
88 let added = {
89 let mut watched = locked(&self.watched_presence);
90 let mut added: Vec<String> = user_ids
91 .iter()
92 .filter(|user_id| watched.insert((*user_id).clone()))
93 .cloned()
94 .collect();
95 added.sort();
96 added
97 };
98 let endpoint = locked(&self.presence_endpoint).clone();
99 let Some(endpoint) = endpoint.filter(|_| !added.is_empty()) else {
100 return Ok(());
101 };
102 let outcome = self
103 .remote
104 .subscribe_presence(&endpoint.endpoint_id, &endpoint.trouter_uri, &added, false)
105 .await;
106 if outcome.is_err() {
107 let mut watched = locked(&self.watched_presence);
108 for user_id in &added {
109 watched.remove(user_id);
110 }
111 }
112 outcome
113 }
114
115 /// No-op for the endpoint already subscribed; a failed subscribe forgets it so the next announcement retries.
116 pub async fn presence_endpoint(&self, endpoint: TrouterEndpoint) -> Result<()> {
117 let _subscribing = self.presence_subscribing.lock().await;
118 if locked(&self.presence_endpoint).as_ref() == Some(&endpoint) {
119 return Ok(());
120 }
121 let outcome = self.subscribe_watched(&endpoint).await;
122 *locked(&self.presence_endpoint) = outcome.is_ok().then_some(endpoint);
123 outcome
124 }
125
126 pub async fn resubscribe_presence(&self) -> Result<()> {
127 let _subscribing = self.presence_subscribing.lock().await;
128 let endpoint = locked(&self.presence_endpoint).clone();
129 match endpoint {
130 Some(endpoint) => self.subscribe_watched(&endpoint).await,
131 None => Ok(()),
132 }
133 }
134
135 async fn subscribe_watched(&self, endpoint: &TrouterEndpoint) -> Result<()> {
136 let mut watched: Vec<String> = locked(&self.watched_presence).iter().cloned().collect();
137 watched.sort();
138 if watched.is_empty() {
139 return Ok(());
140 }
141 self.remote
142 .subscribe_presence(&endpoint.endpoint_id, &endpoint.trouter_uri, &watched, true)
143 .await
144 }
145
146 fn record_presences<'a>(
147 &self,
148 found: impl Iterator<Item = (&'a String, &'a str, Option<&'a str>)>,
149 ) -> bool {
150 let mut known = locked(&self.presences);
151 let mut changed = false;
152 for (user_id, availability, activity) in found {
153 let presence = Presence {
154 availability: Availability::from_service(availability),
155 in_call: is_call_activity(activity),
156 };
157 changed |= known.insert(user_id.clone(), presence) != Some(presence);
158 }
159 changed
160 }
74 161 }
@@ -1,8 +1,10 @@
1use chatsvc::{PresenceUpdate, TrouterEndpoint};
1use graph::MAX_PRESENCE_IDS;
2use graph::MAX_PRESENCE_IDS;
2
3
3use crate::engine::SyncEngine;
4use crate::engine::SyncEngine;
4use crate::error::Result;
5use crate::error::Result;
5use crate::events::CoreEvent;
6use crate::events::CoreEvent;
7use crate::receipts::locked;
6use crate::remote::Remote;
8use crate::remote::Remote;
7
9
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -54,21 +56,106 @@ impl<R: Remote> SyncEngine<R> {
54 let mut changed = false;
56 let mut changed = false;
55 for chunk in unique.chunks(MAX_PRESENCE_IDS) {
57 for chunk in unique.chunks(MAX_PRESENCE_IDS) {
56 let found = self.remote.presences(chunk).await?;
58 let found = self.remote.presences(chunk).await?;
57 let mut known = self
59 changed |= self.record_presences(found.iter().map(|entry| {
58 .presences
60 (
59 .lock()
61 &entry.user_id,
60 .unwrap_or_else(|poisoned| poisoned.into_inner());
62 entry.availability.as_str(),
61 for entry in found {
63 entry.activity.as_deref(),
62 let presence = Presence {
64 )
63 availability: Availability::from_service(&entry.availability),
65 }));
64 in_call: is_call_activity(entry.activity.as_deref()),
65 };
66 changed |= known.insert(entry.user_id, presence) != Some(presence);
67 }
68 }
66 }
69 if changed {
67 if changed {
70 let _ = self.events.send(CoreEvent::PresenceChanged);
68 let _ = self.events.send(CoreEvent::PresenceChanged);
71 }
69 }
72 Ok(())
70 Ok(())
73 }
71 }
72
73 pub fn apply_presence(&self, updates: &[PresenceUpdate]) {
74 let changed = self.record_presences(updates.iter().map(|update| {
75 (
76 &update.user_id,
77 update.availability.as_str(),
78 update.activity.as_deref(),
79 )
80 }));
81 if changed {
82 let _ = self.events.send(CoreEvent::PresenceChanged);
83 }
84 }
85
86 pub async fn watch_presence(&self, user_ids: &[String]) -> Result<()> {
87 let _subscribing = self.presence_subscribing.lock().await;
88 let added = {
89 let mut watched = locked(&self.watched_presence);
90 let mut added: Vec<String> = user_ids
91 .iter()
92 .filter(|user_id| watched.insert((*user_id).clone()))
93 .cloned()
94 .collect();
95 added.sort();
96 added
97 };
98 let endpoint = locked(&self.presence_endpoint).clone();
99 let Some(endpoint) = endpoint.filter(|_| !added.is_empty()) else {
100 return Ok(());
101 };
102 let outcome = self
103 .remote
104 .subscribe_presence(&endpoint.endpoint_id, &endpoint.trouter_uri, &added, false)
105 .await;
106 if outcome.is_err() {
107 let mut watched = locked(&self.watched_presence);
108 for user_id in &added {
109 watched.remove(user_id);
110 }
111 }
112 outcome
113 }
114
115 /// No-op for the endpoint already subscribed; a failed subscribe forgets it so the next announcement retries.
116 pub async fn presence_endpoint(&self, endpoint: TrouterEndpoint) -> Result<()> {
117 let _subscribing = self.presence_subscribing.lock().await;
118 if locked(&self.presence_endpoint).as_ref() == Some(&endpoint) {
119 return Ok(());
120 }
121 let outcome = self.subscribe_watched(&endpoint).await;
122 *locked(&self.presence_endpoint) = outcome.is_ok().then_some(endpoint);
123 outcome
124 }
125
126 pub async fn resubscribe_presence(&self) -> Result<()> {
127 let _subscribing = self.presence_subscribing.lock().await;
128 let endpoint = locked(&self.presence_endpoint).clone();
129 match endpoint {
130 Some(endpoint) => self.subscribe_watched(&endpoint).await,
131 None => Ok(()),
132 }
133 }
134
135 async fn subscribe_watched(&self, endpoint: &TrouterEndpoint) -> Result<()> {
136 let mut watched: Vec<String> = locked(&self.watched_presence).iter().cloned().collect();
137 watched.sort();
138 if watched.is_empty() {
139 return Ok(());
140 }
141 self.remote
142 .subscribe_presence(&endpoint.endpoint_id, &endpoint.trouter_uri, &watched, true)
143 .await
144 }
145
146 fn record_presences<'a>(
147 &self,
148 found: impl Iterator<Item = (&'a String, &'a str, Option<&'a str>)>,
149 ) -> bool {
150 let mut known = locked(&self.presences);
151 let mut changed = false;
152 for (user_id, availability, activity) in found {
153 let presence = Presence {
154 availability: Availability::from_service(availability),
155 in_call: is_call_activity(activity),
156 };
157 changed |= known.insert(user_id.clone(), presence) != Some(presence);
158 }
159 changed
160 }
74}
161}
crates/core/src/receipts.rs +1 −1
@@ -59,7 +59,7 @@ impl Default for ReceiptCache {
59 59 }
60 60 }
61 61
62 fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
62 pub(crate) fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
63 63 mutex
64 64 .lock()
65 65 .unwrap_or_else(|poisoned| poisoned.into_inner())
@@ -59,7 +59,7 @@ impl Default for ReceiptCache {
59 }
59 }
60}
60}
61
61
62fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
62pub(crate) fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
63 mutex
63 mutex
64 .lock()
64 .lock()
65 .unwrap_or_else(|poisoned| poisoned.into_inner())
65 .unwrap_or_else(|poisoned| poisoned.into_inner())
crates/core/src/remote.rs +20 −0
@@ -180,6 +180,16 @@ pub trait Remote {
180 180 Err(Error::Unsupported("presence"))
181 181 }
182 182
183 async fn subscribe_presence(
184 &self,
185 _endpoint_id: &str,
186 _trouter_uri: &str,
187 _user_ids: &[String],
188 _purge: bool,
189 ) -> Result<()> {
190 Err(Error::Unsupported("presence subscriptions"))
191 }
192
183 193 async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {
184 194 Err(Error::Unsupported("read receipts"))
185 195 }
@@ -461,6 +471,16 @@ impl Remote for Graph {
461 471 Ok(Graph::presences(self, user_ids).await?)
462 472 }
463 473
474 async fn subscribe_presence(
475 &self,
476 endpoint_id: &str,
477 trouter_uri: &str,
478 user_ids: &[String],
479 purge: bool,
480 ) -> Result<()> {
481 Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)
482 }
483
464 484 async fn consumption_horizons(&self, conversation_id: &str) -> Result<Vec<MemberHorizon>> {
465 485 Ok(Receipts::new(self.session())
466 486 .consumption_horizons(conversation_id)
@@ -180,6 +180,16 @@ pub trait Remote {
180 Err(Error::Unsupported("presence"))
180 Err(Error::Unsupported("presence"))
181 }
181 }
182
182
183 async fn subscribe_presence(
184 &self,
185 _endpoint_id: &str,
186 _trouter_uri: &str,
187 _user_ids: &[String],
188 _purge: bool,
189 ) -> Result<()> {
190 Err(Error::Unsupported("presence subscriptions"))
191 }
192
183 async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {
193 async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {
184 Err(Error::Unsupported("read receipts"))
194 Err(Error::Unsupported("read receipts"))
185 }
195 }
@@ -461,6 +471,16 @@ impl Remote for Graph {
461 Ok(Graph::presences(self, user_ids).await?)
471 Ok(Graph::presences(self, user_ids).await?)
462 }
472 }
463
473
474 async fn subscribe_presence(
475 &self,
476 endpoint_id: &str,
477 trouter_uri: &str,
478 user_ids: &[String],
479 purge: bool,
480 ) -> Result<()> {
481 Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)
482 }
483
464 async fn consumption_horizons(&self, conversation_id: &str) -> Result<Vec<MemberHorizon>> {
484 async fn consumption_horizons(&self, conversation_id: &str) -> Result<Vec<MemberHorizon>> {
465 Ok(Receipts::new(self.session())
485 Ok(Receipts::new(self.session())
466 .consumption_horizons(conversation_id)
486 .consumption_horizons(conversation_id)
crates/core/tests/engine.rs +84 −0
@@ -79,6 +79,7 @@ struct Fake {
79 79 photos: Mutex<HashMap<String, Vec<u8>>>,
80 80 photo_requests: Mutex<Vec<Vec<String>>>,
81 81 presence_answers: Mutex<Vec<Presence>>,
82 presence_subscriptions: Mutex<Vec<(String, Vec<String>, bool)>>,
82 83 hosted_requests: Mutex<Vec<String>>,
83 84 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
84 85 extras_sent: Mutex<Vec<MessageExtras>>,
@@ -562,6 +563,21 @@ impl Remote for Handle {
562 563 .collect())
563 564 }
564 565
566 async fn subscribe_presence(
567 &self,
568 endpoint_id: &str,
569 _trouter_uri: &str,
570 user_ids: &[String],
571 purge: bool,
572 ) -> Result<()> {
573 self.presence_subscriptions.lock().unwrap().push((
574 endpoint_id.to_owned(),
575 user_ids.to_vec(),
576 purge,
577 ));
578 Ok(())
579 }
580
565 581 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
566 582 self.record(format!("search {query}"));
567 583 let configured = self.directory_users.lock().unwrap().clone();
@@ -1647,6 +1663,74 @@ async fn presence_maps_availability_and_announces_changes_once() {
1647 1663 assert!(events.try_recv().is_err());
1648 1664 }
1649 1665
1666 fn trouter_endpoint(endpoint_id: &str) -> chatsvc::TrouterEndpoint {
1667 chatsvc::TrouterEndpoint {
1668 endpoint_id: endpoint_id.to_owned(),
1669 trouter_uri: "https://go-eu.trouter.teams.microsoft.com/v4/f/x/unifiedPresenceService"
1670 .to_owned(),
1671 }
1672 }
1673
1674 #[tokio::test]
1675 async fn presence_subscribes_watched_users_once_the_endpoint_is_known() {
1676 let fake = Arc::new(Fake::default());
1677 let engine = engine_with(&fake, SyncConfig::default());
1678 engine.watch_presence(&ids(&["ada", "bob"])).await.unwrap();
1679 assert!(fake.presence_subscriptions.lock().unwrap().is_empty());
1680 engine
1681 .presence_endpoint(trouter_endpoint("e1"))
1682 .await
1683 .unwrap();
1684 engine.watch_presence(&ids(&["bob", "cy"])).await.unwrap();
1685 engine.watch_presence(&ids(&["cy"])).await.unwrap();
1686 assert_eq!(
1687 *fake.presence_subscriptions.lock().unwrap(),
1688 vec![
1689 ("e1".to_owned(), ids(&["ada", "bob"]), true),
1690 ("e1".to_owned(), ids(&["cy"]), false),
1691 ]
1692 );
1693 engine
1694 .presence_endpoint(trouter_endpoint("e1"))
1695 .await
1696 .unwrap();
1697 assert_eq!(fake.presence_subscriptions.lock().unwrap().len(), 2);
1698 engine.resubscribe_presence().await.unwrap();
1699 engine
1700 .presence_endpoint(trouter_endpoint("e2"))
1701 .await
1702 .unwrap();
1703 assert_eq!(
1704 fake.presence_subscriptions.lock().unwrap()[2..],
1705 [
1706 ("e1".to_owned(), ids(&["ada", "bob", "cy"]), true),
1707 ("e2".to_owned(), ids(&["ada", "bob", "cy"]), true),
1708 ]
1709 );
1710 }
1711
1712 #[tokio::test]
1713 async fn pushed_presence_announces_changes_once() {
1714 let fake = Arc::new(Fake::default());
1715 let engine = engine_with(&fake, SyncConfig::default());
1716 let mut events = engine.subscribe();
1717 let update = |user_id: &str, availability: &str| chatsvc::PresenceUpdate {
1718 user_id: user_id.to_owned(),
1719 availability: availability.to_owned(),
1720 activity: None,
1721 };
1722 let updates = vec![update("ada", "Busy"), update("bob", "Away")];
1723 engine.apply_presence(&updates);
1724 assert_eq!(
1725 engine.presence("ada").unwrap().availability,
1726 Availability::Busy
1727 );
1728 assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged);
1729 assert!(events.try_recv().is_err());
1730 engine.apply_presence(&updates);
1731 assert!(events.try_recv().is_err());
1732 }
1733
1650 1734 struct FakeFolders {
1651 1735 state: Mutex<Vec<ChatFolder>>,
1652 1736 channels: Vec<String>,
@@ -79,6 +79,7 @@ struct Fake {
79 photos: Mutex<HashMap<String, Vec<u8>>>,
79 photos: Mutex<HashMap<String, Vec<u8>>>,
80 photo_requests: Mutex<Vec<Vec<String>>>,
80 photo_requests: Mutex<Vec<Vec<String>>>,
81 presence_answers: Mutex<Vec<Presence>>,
81 presence_answers: Mutex<Vec<Presence>>,
82 presence_subscriptions: Mutex<Vec<(String, Vec<String>, bool)>>,
82 hosted_requests: Mutex<Vec<String>>,
83 hosted_requests: Mutex<Vec<String>>,
83 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
84 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
84 extras_sent: Mutex<Vec<MessageExtras>>,
85 extras_sent: Mutex<Vec<MessageExtras>>,
@@ -562,6 +563,21 @@ impl Remote for Handle {
562 .collect())
563 .collect())
563 }
564 }
564
565
566 async fn subscribe_presence(
567 &self,
568 endpoint_id: &str,
569 _trouter_uri: &str,
570 user_ids: &[String],
571 purge: bool,
572 ) -> Result<()> {
573 self.presence_subscriptions.lock().unwrap().push((
574 endpoint_id.to_owned(),
575 user_ids.to_vec(),
576 purge,
577 ));
578 Ok(())
579 }
580
565 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
581 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
566 self.record(format!("search {query}"));
582 self.record(format!("search {query}"));
567 let configured = self.directory_users.lock().unwrap().clone();
583 let configured = self.directory_users.lock().unwrap().clone();
@@ -1647,6 +1663,74 @@ async fn presence_maps_availability_and_announces_changes_once() {
1647 assert!(events.try_recv().is_err());
1663 assert!(events.try_recv().is_err());
1648}
1664}
1649
1665
1666fn trouter_endpoint(endpoint_id: &str) -> chatsvc::TrouterEndpoint {
1667 chatsvc::TrouterEndpoint {
1668 endpoint_id: endpoint_id.to_owned(),
1669 trouter_uri: "https://go-eu.trouter.teams.microsoft.com/v4/f/x/unifiedPresenceService"
1670 .to_owned(),
1671 }
1672}
1673
1674#[tokio::test]
1675async fn presence_subscribes_watched_users_once_the_endpoint_is_known() {
1676 let fake = Arc::new(Fake::default());
1677 let engine = engine_with(&fake, SyncConfig::default());
1678 engine.watch_presence(&ids(&["ada", "bob"])).await.unwrap();
1679 assert!(fake.presence_subscriptions.lock().unwrap().is_empty());
1680 engine
1681 .presence_endpoint(trouter_endpoint("e1"))
1682 .await
1683 .unwrap();
1684 engine.watch_presence(&ids(&["bob", "cy"])).await.unwrap();
1685 engine.watch_presence(&ids(&["cy"])).await.unwrap();
1686 assert_eq!(
1687 *fake.presence_subscriptions.lock().unwrap(),
1688 vec![
1689 ("e1".to_owned(), ids(&["ada", "bob"]), true),
1690 ("e1".to_owned(), ids(&["cy"]), false),
1691 ]
1692 );
1693 engine
1694 .presence_endpoint(trouter_endpoint("e1"))
1695 .await
1696 .unwrap();
1697 assert_eq!(fake.presence_subscriptions.lock().unwrap().len(), 2);
1698 engine.resubscribe_presence().await.unwrap();
1699 engine
1700 .presence_endpoint(trouter_endpoint("e2"))
1701 .await
1702 .unwrap();
1703 assert_eq!(
1704 fake.presence_subscriptions.lock().unwrap()[2..],
1705 [
1706 ("e1".to_owned(), ids(&["ada", "bob", "cy"]), true),
1707 ("e2".to_owned(), ids(&["ada", "bob", "cy"]), true),
1708 ]
1709 );
1710}
1711
1712#[tokio::test]
1713async fn pushed_presence_announces_changes_once() {
1714 let fake = Arc::new(Fake::default());
1715 let engine = engine_with(&fake, SyncConfig::default());
1716 let mut events = engine.subscribe();
1717 let update = |user_id: &str, availability: &str| chatsvc::PresenceUpdate {
1718 user_id: user_id.to_owned(),
1719 availability: availability.to_owned(),
1720 activity: None,
1721 };
1722 let updates = vec![update("ada", "Busy"), update("bob", "Away")];
1723 engine.apply_presence(&updates);
1724 assert_eq!(
1725 engine.presence("ada").unwrap().availability,
1726 Availability::Busy
1727 );
1728 assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged);
1729 assert!(events.try_recv().is_err());
1730 engine.apply_presence(&updates);
1731 assert!(events.try_recv().is_err());
1732}
1733
1650struct FakeFolders {
1734struct FakeFolders {
1651 state: Mutex<Vec<ChatFolder>>,
1735 state: Mutex<Vec<ChatFolder>>,
1652 channels: Vec<String>,
1736 channels: Vec<String>,
crates/graph/Cargo.toml +1 −0
@@ -14,6 +14,7 @@ serde_json.workspace = true
14 14 session.workspace = true
15 15 thiserror.workspace = true
16 16 tokio.workspace = true
17 uuid.workspace = true
17 18
18 19 [dev-dependencies]
19 20 tokio.workspace = true
@@ -14,6 +14,7 @@ serde_json.workspace = true
14session.workspace = true
14session.workspace = true
15thiserror.workspace = true
15thiserror.workspace = true
16tokio.workspace = true
16tokio.workspace = true
17uuid.workspace = true
17
18
18[dev-dependencies]
19[dev-dependencies]
19tokio.workspace = true
20tokio.workspace = true
crates/graph/src/people.rs +84 −0
@@ -3,6 +3,7 @@ use base64::engine::general_purpose::STANDARD;
3 3 use serde::Deserialize;
4 4 use serde_json::{Value, json};
5 5 use session::{ApiResponse, Method, PRESENCE, Request, Scope};
6 use uuid::Uuid;
6 7
7 8 use crate::client::{BATCH_SIZE, Graph};
8 9 use crate::error::{Error, Result};
@@ -10,9 +11,13 @@ use crate::models::{Photo, Presence};
10 11 use crate::urls;
11 12
12 13 pub const MAX_PRESENCE_IDS: usize = 650;
14 pub const MAX_SUBSCRIBE_IDS: usize = 200;
13 15 const PHOTO_SCOPE: &str = "User.ReadBasic.All";
14 16 const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";
15 17 const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";
18 const PRESENCE_SUBSCRIBE_URL: &str =
19 "https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";
20 const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";
16 21 const ORGID_PREFIX: &str = "8:orgid:";
17 22
18 23 #[derive(Debug, Deserialize)]
@@ -65,6 +70,54 @@ impl Graph {
65 70 }
66 71 Ok(presences)
67 72 }
73
74 pub async fn subscribe_presence(
75 &self,
76 endpoint_id: &str,
77 trouter_uri: &str,
78 user_ids: &[String],
79 purge: bool,
80 ) -> Result<()> {
81 let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
82 let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");
83 for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {
84 let request = Request {
85 method: Method::Post,
86 headers: subscribe_headers(endpoint_id),
87 body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),
88 ..Request::get(url.clone())
89 };
90 let answer = self.session().send(request, &scope).await?;
91 if !(200..300).contains(&answer.status) {
92 return Err(session::Error::api(answer.status, &url, answer.body).into());
93 }
94 }
95 Ok(())
96 }
97 }
98
99 // The service answers 400 naming each of the three x-ms-* client headers when one is missing.
100 fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {
101 vec![
102 ("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
103 ("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
104 ("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),
105 ("x-ms-endpoint-id".into(), endpoint_id.into()),
106 ("x-ms-client-type".into(), "cdlworker".into()),
107 ]
108 }
109
110 fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {
111 let additions: Vec<Value> = user_ids
112 .iter()
113 .map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))
114 .collect();
115 json!({
116 "trouterUri": trouter_uri,
117 "shouldPurgePreviousSubscriptions": purge,
118 "subscriptionsToAdd": additions,
119 "subscriptionsToRemove": [],
120 })
68 121 }
69 122
70 123 fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {
@@ -135,6 +188,37 @@ mod tests {
135 188 assert!(parse_photo("u", answer(403, json!("x"))).is_err());
136 189 }
137 190
191 #[test]
192 fn subscribe_body_carries_mris_and_purge_flag() {
193 let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);
194 assert_eq!(
195 body,
196 json!({
197 "trouterUri": "https://t/unifiedPresenceService",
198 "shouldPurgePreviousSubscriptions": true,
199 "subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],
200 "subscriptionsToRemove": [],
201 })
202 );
203 }
204
205 #[test]
206 fn subscribe_headers_use_a_fresh_correlation_id() {
207 let correlation = |headers: &[(String, String)]| {
208 headers
209 .iter()
210 .find(|(name, _)| name == "x-ms-correlation-id")
211 .map(|(_, value)| value.clone())
212 };
213 let first = subscribe_headers("e");
214 assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));
215 assert!(
216 first
217 .iter()
218 .any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")
219 );
220 }
221
138 222 #[test]
139 223 fn service_presences_strip_the_mri_prefix() {
140 224 let parsed = parse_service_presences(&json!([
@@ -3,6 +3,7 @@ use base64::engine::general_purpose::STANDARD;
3use serde::Deserialize;
3use serde::Deserialize;
4use serde_json::{Value, json};
4use serde_json::{Value, json};
5use session::{ApiResponse, Method, PRESENCE, Request, Scope};
5use session::{ApiResponse, Method, PRESENCE, Request, Scope};
6use uuid::Uuid;
6
7
7use crate::client::{BATCH_SIZE, Graph};
8use crate::client::{BATCH_SIZE, Graph};
8use crate::error::{Error, Result};
9use crate::error::{Error, Result};
@@ -10,9 +11,13 @@ use crate::models::{Photo, Presence};
10use crate::urls;
11use crate::urls;
11
12
12pub const MAX_PRESENCE_IDS: usize = 650;
13pub const MAX_PRESENCE_IDS: usize = 650;
14pub const MAX_SUBSCRIBE_IDS: usize = 200;
13const PHOTO_SCOPE: &str = "User.ReadBasic.All";
15const PHOTO_SCOPE: &str = "User.ReadBasic.All";
14const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";
16const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";
15const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";
17const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";
18const PRESENCE_SUBSCRIBE_URL: &str =
19 "https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";
20const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";
16const ORGID_PREFIX: &str = "8:orgid:";
21const ORGID_PREFIX: &str = "8:orgid:";
17
22
18#[derive(Debug, Deserialize)]
23#[derive(Debug, Deserialize)]
@@ -65,6 +70,54 @@ impl Graph {
65 }
70 }
66 Ok(presences)
71 Ok(presences)
67 }
72 }
73
74 pub async fn subscribe_presence(
75 &self,
76 endpoint_id: &str,
77 trouter_uri: &str,
78 user_ids: &[String],
79 purge: bool,
80 ) -> Result<()> {
81 let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
82 let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");
83 for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {
84 let request = Request {
85 method: Method::Post,
86 headers: subscribe_headers(endpoint_id),
87 body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),
88 ..Request::get(url.clone())
89 };
90 let answer = self.session().send(request, &scope).await?;
91 if !(200..300).contains(&answer.status) {
92 return Err(session::Error::api(answer.status, &url, answer.body).into());
93 }
94 }
95 Ok(())
96 }
97}
98
99// The service answers 400 naming each of the three x-ms-* client headers when one is missing.
100fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {
101 vec![
102 ("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
103 ("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
104 ("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),
105 ("x-ms-endpoint-id".into(), endpoint_id.into()),
106 ("x-ms-client-type".into(), "cdlworker".into()),
107 ]
108}
109
110fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {
111 let additions: Vec<Value> = user_ids
112 .iter()
113 .map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))
114 .collect();
115 json!({
116 "trouterUri": trouter_uri,
117 "shouldPurgePreviousSubscriptions": purge,
118 "subscriptionsToAdd": additions,
119 "subscriptionsToRemove": [],
120 })
68}
121}
69
122
70fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {
123fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {
@@ -135,6 +188,37 @@ mod tests {
135 assert!(parse_photo("u", answer(403, json!("x"))).is_err());
188 assert!(parse_photo("u", answer(403, json!("x"))).is_err());
136 }
189 }
137
190
191 #[test]
192 fn subscribe_body_carries_mris_and_purge_flag() {
193 let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);
194 assert_eq!(
195 body,
196 json!({
197 "trouterUri": "https://t/unifiedPresenceService",
198 "shouldPurgePreviousSubscriptions": true,
199 "subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],
200 "subscriptionsToRemove": [],
201 })
202 );
203 }
204
205 #[test]
206 fn subscribe_headers_use_a_fresh_correlation_id() {
207 let correlation = |headers: &[(String, String)]| {
208 headers
209 .iter()
210 .find(|(name, _)| name == "x-ms-correlation-id")
211 .map(|(_, value)| value.clone())
212 };
213 let first = subscribe_headers("e");
214 assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));
215 assert!(
216 first
217 .iter()
218 .any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")
219 );
220 }
221
138 #[test]
222 #[test]
139 fn service_presences_strip_the_mri_prefix() {
223 fn service_presences_strip_the_mri_prefix() {
140 let parsed = parse_service_presences(&json!([
224 let parsed = parse_service_presences(&json!([