BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / engine.rs

engine.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
engine.rs 22.1 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::sync::{Arc, Mutex};
4use std::time::{Duration, Instant};
5
6use chatsvc::{
7 CallbackReplier, InstanceNames, Realtime, RealtimeConfig, RealtimeEvent, TrouterCallback,
8 TrouterEndpoint,
9};
10use session::Session;
11use tokio::sync::{mpsc, oneshot};
12use tokio::task::JoinHandle;
13use tokio::time::timeout;
14
15use crate::call::{AcceptMode, CallOptions, CallSpec, IncomingCall, Plan};
16use crate::control::{CallControl, CallHandle, call_channel};
17use crate::devices::DeviceChoice;
18use crate::end::EndKind;
19use crate::error::{Error, Result};
20use crate::push::{CallNotification, Caller, PushEvent, decode_push};
21use crate::relay::{DEFAULT_RELAY_HOST, RelayCache};
22use crate::signaling::{
23 AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting,
24 fetch_self,
25};
26use crate::timeline::Timeline;
27use crate::trouter_events::{
28 CallEvent, CallbackLinks, acceptance_acknowledgement, callback_call_id, classify, decode_body,
29 is_acceptance_callback,
30};
31
32const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
33const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
34const SEEN_WINDOW: Duration = Duration::from_secs(120);
35const RING_ID_START: u64 = 1;
36pub const TRACE_ENV: &str = "CALLING_TRACE";
37
38pub fn calling_instance_names() -> InstanceNames {
39 InstanceNames {
40 global: "__callingTrouter".into(),
41 binding: "__callingRealtime".into(),
42 endpoint_storage_key: "__callingEpid".into(),
43 }
44}
45
46pub fn calling_realtime_config(ringable: bool, instance: InstanceNames) -> RealtimeConfig {
47 RealtimeConfig {
48 instance,
49 forward_callbacks: true,
50 ringable,
51 ..RealtimeConfig::default()
52 }
53}
54
55pub(crate) fn callback_base(trouter_uri: &str) -> String {
56 let trimmed = trouter_uri
57 .strip_suffix(PRESENCE_SUFFIX)
58 .unwrap_or(trouter_uri)
59 .trim_end_matches('/');
60 format!("{trimmed}/")
61}
62
63#[derive(Debug, Clone)]
64pub struct EngineConfig {
65 pub ringable: bool,
66 pub routing: TenantRouting,
67 pub relay_host: String,
68 pub trace: bool,
69 pub dump_dir: Option<std::path::PathBuf>,
70 /// Page globals of the Trouter client; a second engine in the same tab needs its own.
71 pub instance: InstanceNames,
72}
73
74const KEPT_CALL_DUMPS: usize = 5;
75
76fn next_call_dump_dir(base: &std::path::Path) -> std::path::PathBuf {
77 let mut earlier: Vec<std::path::PathBuf> = std::fs::read_dir(base)
78 .into_iter()
79 .flatten()
80 .flatten()
81 .map(|entry| entry.path())
82 .filter(|path| path.is_dir())
83 .collect();
84 earlier.sort();
85 for old in earlier
86 .iter()
87 .take((earlier.len() + 1).saturating_sub(KEPT_CALL_DUMPS))
88 {
89 let _ = std::fs::remove_dir_all(old);
90 }
91 let started = std::time::SystemTime::now()
92 .duration_since(std::time::UNIX_EPOCH)
93 .unwrap_or_default();
94 base.join(format!("{:015}", started.as_millis()))
95}
96
97impl Default for EngineConfig {
98 fn default() -> Self {
99 EngineConfig {
100 ringable: true,
101 routing: TenantRouting::default(),
102 relay_host: DEFAULT_RELAY_HOST.to_owned(),
103 trace: std::env::var_os(TRACE_ENV).is_some(),
104 dump_dir: None,
105 instance: calling_instance_names(),
106 }
107 }
108}
109
110#[derive(Debug, Clone, PartialEq)]
111pub struct IncomingRing {
112 pub ring_id: u64,
113 pub caller: Caller,
114 pub thread_id: Option<String>,
115 pub video: bool,
116 pub is_group: bool,
117 pub subject: Option<String>,
118}
119
120#[derive(Debug, Clone, PartialEq)]
121pub enum EngineEvent {
122 Incoming(IncomingRing),
123 RingEnded {
124 ring_id: u64,
125 kind: EndKind,
126 answered_by: Option<String>,
127 },
128}
129
130enum RingCommand {
131 Accept(AcceptMode, oneshot::Sender<Option<CallHandle>>),
132 Decline,
133 Drop,
134}
135
136struct Route {
137 sender: mpsc::UnboundedSender<TrouterCallback>,
138 acceptance_reply: String,
139}
140
141pub(crate) struct Inner {
142 pub(crate) session: Session,
143 pub(crate) poll_session: Session,
144 pub(crate) config: EngineConfig,
145 pub(crate) identity: SelfIdentity,
146 pub(crate) replier: CallbackReplier,
147 pub(crate) gate: Arc<tokio::sync::Mutex<()>>,
148 pub(crate) relay: RelayCache,
149 endpoint: Mutex<TrouterEndpoint>,
150 routes: Mutex<HashMap<String, Route>>,
151 rings: Mutex<HashMap<u64, mpsc::UnboundedSender<RingCommand>>>,
152 seen: Mutex<HashMap<(String, String), Instant>>,
153 next_ring_id: AtomicU64,
154 default_camera: Mutex<DeviceChoice>,
155 runtime: tokio::runtime::Handle,
156 events: mpsc::UnboundedSender<EngineEvent>,
157 stop: Mutex<Option<oneshot::Sender<()>>>,
158 tasks: Mutex<Vec<JoinHandle<()>>>,
159}
160
161impl Inner {
162 pub(crate) fn endpoint(&self) -> TrouterEndpoint {
163 self.endpoint.lock().expect("endpoint lock").clone()
164 }
165
166 pub(crate) fn register_route(
167 &self,
168 links: &CallbackLinks,
169 ) -> mpsc::UnboundedReceiver<TrouterCallback> {
170 let (sender, receiver) = mpsc::unbounded_channel();
171 let route = Route {
172 sender,
173 acceptance_reply: acceptance_acknowledgement(links).to_string(),
174 };
175 self.routes
176 .lock()
177 .expect("routes lock")
178 .insert(links.call_id().to_owned(), route);
179 receiver
180 }
181
182 pub(crate) fn unregister_route(&self, call_id: &str) {
183 self.routes.lock().expect("routes lock").remove(call_id);
184 }
185
186 pub(crate) fn participant(&self, participant_id: &str) -> Participant {
187 Participant {
188 mri: format!("8:orgid:{}", self.identity.object_id),
189 display_name: self.identity.display_name.clone(),
190 endpoint_id: self.endpoint().endpoint_id,
191 participant_id: participant_id.to_owned(),
192 language_id: "en-gb".into(),
193 }
194 }
195
196 pub(crate) fn callback_links(&self) -> CallbackLinks {
197 CallbackLinks::new(
198 &callback_base(&self.endpoint().trouter_uri),
199 &uuid::Uuid::new_v4().to_string(),
200 )
201 }
202
203 pub(crate) fn signaling(&self, timeline: Timeline) -> Signaling {
204 Signaling::new(
205 self.session.clone(),
206 self.poll_session.clone(),
207 self.config.routing.clone(),
208 timeline,
209 )
210 }
211
212 pub(crate) fn call_options(&self) -> CallOptions {
213 CallOptions {
214 relay_host: self.config.relay_host.clone(),
215 routing: self.config.routing.clone(),
216 trace: self.config.trace,
217 sdp_dump_dir: self.config.dump_dir.as_deref().map(next_call_dump_dir),
218 camera: self
219 .default_camera
220 .lock()
221 .expect("default camera lock")
222 .clone(),
223 ..CallOptions::default()
224 }
225 }
226
227 fn route(&self, callback: TrouterCallback) {
228 let Some(call_id) = callback_call_id(&callback.path) else {
229 self.replier.reply(callback.request_id, 200, "");
230 return;
231 };
232 let route = self
233 .routes
234 .lock()
235 .expect("routes lock")
236 .get(&call_id)
237 .map(|route| {
238 let reply = if is_acceptance_callback(&callback.path) {
239 route.acceptance_reply.clone()
240 } else {
241 String::new()
242 };
243 (route.sender.clone(), reply)
244 });
245 match route {
246 Some((sender, reply)) => {
247 self.replier.reply(callback.request_id, 200, reply);
248 let _ = sender.send(callback);
249 }
250 None => self.replier.reply(callback.request_id, 200, ""),
251 }
252 }
253
254 fn already_seen(&self, notification: &CallNotification) -> bool {
255 let mut seen = self.seen.lock().expect("seen lock");
256 let now = Instant::now();
257 seen.retain(|_, at| now.duration_since(*at) < SEEN_WINDOW);
258 seen.insert(notification.dedupe_key(), now).is_some()
259 }
260
261 fn emit(&self, event: EngineEvent) {
262 let _ = self.events.send(event);
263 }
264}
265
266#[derive(Clone)]
267pub struct CallEngine {
268 pub(crate) inner: Arc<Inner>,
269}
270
271impl CallEngine {
272 pub async fn start(
273 session: Session,
274 poll_session: Session,
275 config: EngineConfig,
276 ) -> Result<(CallEngine, mpsc::UnboundedReceiver<EngineEvent>)> {
277 let mut realtime = Realtime::start_with(
278 &session,
279 calling_realtime_config(config.ringable, config.instance.clone()),
280 )
281 .await?;
282 let callbacks = realtime
283 .take_callbacks()
284 .ok_or_else(|| Error::Callback("callback stream already taken".into()))?;
285 let replier = realtime.callback_replier();
286 let mut last_status = None;
287 let endpoint = timeout(ENDPOINT_WAIT, async {
288 while let Some(event) = realtime.recv().await {
289 match event {
290 RealtimeEvent::Endpoint(endpoint) => return Some(endpoint),
291 RealtimeEvent::Status(status) => {
292 last_status = Some(format!("{:?} {}", status.kind, status.detail))
293 }
294 _ => {}
295 }
296 }
297 None
298 })
299 .await
300 .ok()
301 .flatten();
302 let Some(endpoint) = endpoint else {
303 realtime.stop().await;
304 let seen = last_status.map_or_else(
305 || "no status".to_owned(),
306 |status| format!("last status: {status}"),
307 );
308 return Err(Error::Callback(format!(
309 "Trouter socket never announced its endpoint ({seen})"
310 )));
311 };
312 let identity = match fetch_self(&session).await {
313 Ok(identity) => identity,
314 Err(error) => {
315 realtime.stop().await;
316 return Err(error);
317 }
318 };
319 let (events, event_receiver) = mpsc::unbounded_channel();
320 let (stop, stop_receiver) = oneshot::channel();
321 let inner = Arc::new(Inner {
322 session,
323 poll_session,
324 config,
325 identity,
326 replier,
327 gate: Arc::new(tokio::sync::Mutex::new(())),
328 endpoint: Mutex::new(endpoint),
329 routes: Mutex::default(),
330 rings: Mutex::default(),
331 seen: Mutex::default(),
332 next_ring_id: AtomicU64::new(RING_ID_START),
333 relay: RelayCache::default(),
334 default_camera: Mutex::new(DeviceChoice::SystemDefault),
335 runtime: tokio::runtime::Handle::current(),
336 events,
337 stop: Mutex::new(Some(stop)),
338 tasks: Mutex::default(),
339 });
340 let engine = CallEngine {
341 inner: inner.clone(),
342 };
343 let pump = tokio::spawn(pump_realtime(realtime, inner.clone(), stop_receiver));
344 let router = tokio::spawn(route_callbacks(callbacks, engine.clone()));
345 let relay = prefetch_relay(inner.clone());
346 inner
347 .tasks
348 .lock()
349 .expect("tasks lock")
350 .extend([pump, router, relay]);
351 Ok((engine, event_receiver))
352 }
353
354 pub fn session(&self) -> Session {
355 self.inner.session.clone()
356 }
357
358 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
359 self.start_call_with(spec, false, false)
360 }
361
362 pub fn start_video_call(&self, spec: CallSpec) -> CallHandle {
363 self.start_call_with(spec, false, true)
364 }
365
366 pub fn start_consult(&self, spec: CallSpec) -> CallHandle {
367 self.start_call_with(spec, true, false)
368 }
369
370 fn start_call_with(&self, spec: CallSpec, concurrent: bool, start_camera: bool) -> CallHandle {
371 let (handle, control) = call_channel();
372 self.start_call_on(spec, concurrent, start_camera, control);
373 handle
374 }
375
376 pub fn start_call_on(
377 &self,
378 spec: CallSpec,
379 concurrent: bool,
380 start_camera: bool,
381 control: CallControl,
382 ) {
383 let engine = self.clone();
384 self.inner.runtime.spawn(async move {
385 let options = CallOptions {
386 concurrent,
387 start_camera,
388 ..engine.inner.call_options()
389 };
390 let _ = engine.run(Plan::Outgoing(spec), options, control).await;
391 });
392 }
393
394 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
395 let commands = self
396 .inner
397 .rings
398 .lock()
399 .expect("rings lock")
400 .get(&ring_id)
401 .cloned()?;
402 let (answer, handle) = oneshot::channel();
403 commands.send(RingCommand::Accept(mode, answer)).ok()?;
404 handle.await.ok().flatten()
405 }
406
407 /// Only for a click on Decline: it ends the call for all of the user's devices.
408 pub fn set_default_camera(&self, camera: DeviceChoice) {
409 *self
410 .inner
411 .default_camera
412 .lock()
413 .expect("default camera lock") = camera;
414 }
415
416 pub fn decline_ring(&self, ring_id: u64) {
417 self.send_ring_command(ring_id, RingCommand::Decline);
418 }
419
420 /// Stops ringing locally without telling Teams; the call keeps ringing elsewhere.
421 pub fn drop_ring(&self, ring_id: u64) {
422 self.send_ring_command(ring_id, RingCommand::Drop);
423 }
424
425 fn send_ring_command(&self, ring_id: u64, command: RingCommand) {
426 let commands = self
427 .inner
428 .rings
429 .lock()
430 .expect("rings lock")
431 .get(&ring_id)
432 .cloned();
433 if let Some(commands) = commands {
434 let _ = commands.send(command);
435 }
436 }
437
438 pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget> {
439 let signaling = self.inner.signaling(Timeline::new(self.inner.config.trace));
440 let from = self.inner.participant(&uuid::Uuid::new_v4().to_string());
441 let (target, conversation) = signaling
442 .resolve_meeting(&from, &self.inner.callback_links(), meeting_data)
443 .await?;
444 let _ = signaling
445 .leave(&conversation, &from, LeaveReason::Cancel)
446 .await;
447 Ok(target)
448 }
449
450 pub async fn stop(&self) {
451 let stop = self.inner.stop.lock().expect("stop lock").take();
452 if let Some(stop) = stop {
453 let _ = stop.send(());
454 }
455 let tasks: Vec<JoinHandle<()>> =
456 std::mem::take(&mut *self.inner.tasks.lock().expect("tasks lock"));
457 for task in tasks {
458 let _ = task.await;
459 }
460 }
461}
462
463async fn pump_realtime(mut realtime: Realtime, inner: Arc<Inner>, mut stop: oneshot::Receiver<()>) {
464 let mut last_status = None;
465 loop {
466 tokio::select! {
467 event = realtime.recv() => match event {
468 Some(RealtimeEvent::Endpoint(endpoint)) => *inner.endpoint.lock().expect("endpoint lock") = endpoint,
469 Some(RealtimeEvent::Status(status)) => {
470 if last_status.as_ref() != Some(&status) {
471 eprintln!("calls: trouter {:?} {}", status.kind, status.detail);
472 last_status = Some(status);
473 }
474 }
475 Some(_) => {}
476 None => return,
477 },
478 _ = &mut stop => {
479 realtime.stop().await;
480 return;
481 }
482 }
483 }
484}
485
486async fn route_callbacks(
487 mut callbacks: mpsc::UnboundedReceiver<TrouterCallback>,
488 engine: CallEngine,
489) {
490 while let Some(callback) = callbacks.recv().await {
491 if callback.path.is_empty() {
492 engine.handle_push(callback);
493 } else {
494 engine.inner.route(callback);
495 }
496 }
497}
498
499impl CallEngine {
500 fn handle_push(&self, callback: TrouterCallback) {
501 self.inner.replier.reply(callback.request_id, 200, "");
502 if !self.inner.config.ringable {
503 return;
504 }
505 let Ok(PushEvent::IncomingCall(notification)) = decode_push(&callback.body) else {
506 return;
507 };
508 let notification = *notification;
509 if self.inner.already_seen(&notification) {
510 return;
511 }
512 let ring_id = self.inner.next_ring_id.fetch_add(1, Ordering::SeqCst);
513 let (commands, receiver) = mpsc::unbounded_channel();
514 self.inner
515 .rings
516 .lock()
517 .expect("rings lock")
518 .insert(ring_id, commands);
519 tokio::spawn(ring_task(self.clone(), notification, ring_id, receiver));
520 }
521}
522
523fn prefetch_relay(inner: Arc<Inner>) -> JoinHandle<()> {
524 tokio::spawn(async move {
525 let _ = inner.relay.grant(&inner.session).await;
526 })
527}
528
529async fn ring_task(
530 engine: CallEngine,
531 notification: CallNotification,
532 ring_id: u64,
533 mut commands: mpsc::UnboundedReceiver<RingCommand>,
534) {
535 let inner = engine.inner.clone();
536 prefetch_relay(inner.clone());
537 let links = inner.callback_links();
538 let route_id = links.call_id().to_owned();
539 let mut callbacks = inner.register_route(&links);
540 let timeline = Timeline::new(inner.config.trace);
541 let signaling = inner.signaling(timeline.clone());
542 let participant_id = if notification.participant_id.is_empty() {
543 uuid::Uuid::new_v4().to_string()
544 } else {
545 notification.participant_id.clone()
546 };
547 let participant = inner.participant(&participant_id);
548 let cleanup = |inner: &Inner| {
549 inner.unregister_route(&route_id);
550 inner.rings.lock().expect("rings lock").remove(&ring_id);
551 };
552 let Some(attach_url) = notification.links.get("attach") else {
553 cleanup(&inner);
554 return;
555 };
556 let request = AttachRequest {
557 from: &participant,
558 callbacks: &links,
559 controller: notification.conversation_controller.as_deref(),
560 needs_media: notification.offer_sdp.is_none(),
561 };
562 let mut attached = match signaling.attach(attach_url, &request).await {
563 Ok(attached) => attached,
564 Err(error) => {
565 timeline.record("attach failed", error.to_string());
566 cleanup(&inner);
567 return;
568 }
569 };
570 if attached.offer_sdp.is_none() {
571 attached.offer_sdp = notification.offer_sdp.clone();
572 }
573 if let Some(progress) = attached.links.get("progress")
574 && let Err(error) = signaling.send_ringing(progress, &participant).await
575 {
576 timeline.record("ringing progress failed", error.to_string());
577 }
578 inner.emit(EngineEvent::Incoming(IncomingRing {
579 ring_id,
580 caller: notification.caller.clone(),
581 thread_id: notification.thread_id.clone(),
582 video: notification.video,
583 is_group: notification.is_multi_party,
584 subject: notification.subject.clone(),
585 }));
586 loop {
587 tokio::select! {
588 callback = callbacks.recv() => {
589 let Some(callback) = callback else { break };
590 let event = decode_body(&callback).and_then(|body| classify(&callback.path, body));
591 if let Ok((_, CallEvent::End(end))) = event {
592 inner.emit(EngineEvent::RingEnded {
593 ring_id,
594 kind: end.kind(),
595 answered_by: end.accepted_elsewhere_by,
596 });
597 break;
598 }
599 }
600 command = commands.recv() => match command {
601 Some(RingCommand::Accept(accept, answer)) => {
602 let (handle, control) = call_channel();
603 let incoming = IncomingCall {
604 accept,
605 notification,
606 attached,
607 links,
608 participant,
609 callbacks,
610 };
611 let _ = answer.send(Some(handle));
612 inner.rings.lock().expect("rings lock").remove(&ring_id);
613 let options = inner.call_options();
614 tokio::spawn(async move {
615 let _ = engine.run(Plan::Incoming(Box::new(incoming)), options, control).await;
616 });
617 return;
618 }
619 Some(RingCommand::Decline) => {
620 if let Some(call_leg) = attached.links.get("callLeg")
621 && let Err(error) = signaling.decline(call_leg).await
622 {
623 timeline.record("decline failed", error.to_string());
624 }
625 break;
626 }
627 Some(RingCommand::Drop) | None => break,
628 }
629 }
630 }
631 cleanup(&inner);
632}
633
634#[cfg(test)]
635mod tests {
636 use super::*;
637
638 #[test]
639 fn a_new_call_dump_keeps_only_the_newest_earlier_ones() {
640 let base = std::env::temp_dir().join(format!("call-dumps-test-{}", std::process::id()));
641 for millis in 1..=6 {
642 std::fs::create_dir_all(base.join(format!("{millis:015}"))).unwrap();
643 }
644 let next = next_call_dump_dir(&base);
645 let mut left: Vec<String> = std::fs::read_dir(&base)
646 .unwrap()
647 .flatten()
648 .map(|entry| entry.file_name().to_string_lossy().into_owned())
649 .collect();
650 left.sort();
651 let _ = std::fs::remove_dir_all(&base);
652 assert_eq!(
653 left,
654 (3..=6)
655 .map(|millis| format!("{millis:015}"))
656 .collect::<Vec<_>>()
657 );
658 assert!(next.file_name().unwrap().to_string_lossy().into_owned() > format!("{:015}", 6));
659 }
660
661 #[test]
662 fn callback_base_comes_from_the_presence_uri() {
663 assert_eq!(
664 callback_base(
665 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc//unifiedPresenceService"
666 ),
667 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/"
668 );
669 assert_eq!(
670 callback_base("https://h/v4/f/abc/unifiedPresenceService"),
671 "https://h/v4/f/abc/"
672 );
673 }
674
675 #[test]
676 fn only_the_ringable_engine_registers_for_calls() {
677 assert!(calling_realtime_config(true, calling_instance_names()).ringable);
678 assert!(!calling_realtime_config(false, calling_instance_names()).ringable);
679 assert!(calling_realtime_config(true, calling_instance_names()).forward_callbacks);
680 }
681}