BlueGit

ict rusty-teams

Files

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

engine.rs

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