BlueGit

ict rusty-teams

Files

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

engine.rs

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