BlueGit

ict rusty-teams

Files

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

engine.rs

engine.rs 19.4 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::{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;
19use crate::signaling::{
20 AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,
21};
22use crate::timeline::Timeline;
23use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body};
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
116pub(crate) struct Inner {
117 pub(crate) session: Session,
118 pub(crate) poll_session: Session,
119 pub(crate) config: EngineConfig,
120 pub(crate) identity: SelfIdentity,
121 pub(crate) replier: CallbackReplier,
122 pub(crate) gate: Arc<tokio::sync::Mutex<()>>,
123 endpoint: Mutex<TrouterEndpoint>,
124 routes: Mutex<HashMap<String, mpsc::UnboundedSender<TrouterCallback>>>,
125 rings: Mutex<HashMap<u64, mpsc::UnboundedSender<RingCommand>>>,
126 seen: Mutex<HashMap<(String, String), Instant>>,
127 next_ring_id: AtomicU64,
128 default_camera: Mutex<DeviceChoice>,
129 runtime: tokio::runtime::Handle,
130 events: mpsc::UnboundedSender<EngineEvent>,
131 stop: Mutex<Option<oneshot::Sender<()>>>,
132 tasks: Mutex<Vec<JoinHandle<()>>>,
133}
134
135impl Inner {
136 pub(crate) fn endpoint(&self) -> TrouterEndpoint {
137 self.endpoint.lock().expect("endpoint lock").clone()
138 }
139
140 pub(crate) fn register_route(&self, call_id: &str) -> mpsc::UnboundedReceiver<TrouterCallback> {
141 let (sender, receiver) = mpsc::unbounded_channel();
142 self.routes.lock().expect("routes lock").insert(call_id.to_owned(), sender);
143 receiver
144 }
145
146 pub(crate) fn unregister_route(&self, call_id: &str) {
147 self.routes.lock().expect("routes lock").remove(call_id);
148 }
149
150 pub(crate) fn participant(&self, participant_id: &str) -> Participant {
151 Participant {
152 mri: format!("8:orgid:{}", self.identity.object_id),
153 display_name: self.identity.display_name.clone(),
154 endpoint_id: self.endpoint().endpoint_id,
155 participant_id: participant_id.to_owned(),
156 language_id: "en-gb".into(),
157 }
158 }
159
160 pub(crate) fn callback_links(&self) -> CallbackLinks {
161 CallbackLinks::new(&callback_base(&self.endpoint().trouter_uri), &uuid::Uuid::new_v4().to_string())
162 }
163
164 pub(crate) fn signaling(&self, timeline: Timeline) -> Signaling {
165 Signaling::new(self.session.clone(), self.poll_session.clone(), self.config.routing.clone(), timeline)
166 }
167
168 pub(crate) fn call_options(&self) -> CallOptions {
169 CallOptions {
170 relay_host: self.config.relay_host.clone(),
171 routing: self.config.routing.clone(),
172 trace: self.config.trace,
173 sdp_dump_dir: self.config.dump_dir.as_deref().map(next_call_dump_dir),
174 camera: self.default_camera.lock().expect("default camera lock").clone(),
175 ..CallOptions::default()
176 }
177 }
178
179 fn route(&self, callback: TrouterCallback) {
180 let Some(call_id) = callback_call_id(&callback.path) else {
181 self.replier.reply(callback.request_id, 200, "");
182 return;
183 };
184 let sender = self.routes.lock().expect("routes lock").get(&call_id).cloned();
185 match sender {
186 Some(sender) => {
187 if let Err(rejected) = sender.send(callback) {
188 self.replier.reply(rejected.0.request_id, 200, "");
189 }
190 }
191 None => self.replier.reply(callback.request_id, 200, ""),
192 }
193 }
194
195 fn already_seen(&self, notification: &CallNotification) -> bool {
196 let mut seen = self.seen.lock().expect("seen lock");
197 let now = Instant::now();
198 seen.retain(|_, at| now.duration_since(*at) < SEEN_WINDOW);
199 seen.insert(notification.dedupe_key(), now).is_some()
200 }
201
202 fn emit(&self, event: EngineEvent) {
203 let _ = self.events.send(event);
204 }
205}
206
207#[derive(Clone)]
208pub struct CallEngine {
209 pub(crate) inner: Arc<Inner>,
210}
211
212impl CallEngine {
213 pub async fn start(
214 session: Session,
215 poll_session: Session,
216 config: EngineConfig,
217 ) -> Result<(CallEngine, mpsc::UnboundedReceiver<EngineEvent>)> {
218 let mut realtime = Realtime::start_with(&session, calling_realtime_config(config.ringable, config.instance.clone())).await?;
219 let callbacks = realtime
220 .take_callbacks()
221 .ok_or_else(|| Error::Callback("callback stream already taken".into()))?;
222 let replier = realtime.callback_replier();
223 let endpoint = timeout(ENDPOINT_WAIT, async {
224 while let Some(event) = realtime.recv().await {
225 if let RealtimeEvent::Endpoint(endpoint) = event {
226 return Some(endpoint);
227 }
228 }
229 None
230 })
231 .await
232 .ok()
233 .flatten();
234 let Some(endpoint) = endpoint else {
235 realtime.stop().await;
236 return Err(Error::Callback("Trouter socket never announced its endpoint".into()));
237 };
238 let identity = match fetch_self(&session).await {
239 Ok(identity) => identity,
240 Err(error) => {
241 realtime.stop().await;
242 return Err(error);
243 }
244 };
245 let (events, event_receiver) = mpsc::unbounded_channel();
246 let (stop, stop_receiver) = oneshot::channel();
247 let inner = Arc::new(Inner {
248 session,
249 poll_session,
250 config,
251 identity,
252 replier,
253 gate: Arc::new(tokio::sync::Mutex::new(())),
254 endpoint: Mutex::new(endpoint),
255 routes: Mutex::default(),
256 rings: Mutex::default(),
257 seen: Mutex::default(),
258 next_ring_id: AtomicU64::new(RING_ID_START),
259 default_camera: Mutex::new(DeviceChoice::SystemDefault),
260 runtime: tokio::runtime::Handle::current(),
261 events,
262 stop: Mutex::new(Some(stop)),
263 tasks: Mutex::default(),
264 });
265 let engine = CallEngine { inner: inner.clone() };
266 let pump = tokio::spawn(pump_realtime(realtime, inner.clone(), stop_receiver));
267 let router = tokio::spawn(route_callbacks(callbacks, engine.clone()));
268 inner.tasks.lock().expect("tasks lock").extend([pump, router]);
269 Ok((engine, event_receiver))
270 }
271
272 pub fn session(&self) -> Session {
273 self.inner.session.clone()
274 }
275
276 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
277 self.start_call_with(spec, false)
278 }
279
280 pub fn start_consult(&self, spec: CallSpec) -> CallHandle {
281 self.start_call_with(spec, true)
282 }
283
284 fn start_call_with(&self, spec: CallSpec, concurrent: bool) -> CallHandle {
285 let (handle, control) = call_channel();
286 let engine = self.clone();
287 self.inner.runtime.spawn(async move {
288 let options = CallOptions { concurrent, ..engine.inner.call_options() };
289 let _ = engine.run(Plan::Outgoing(spec), options, control).await;
290 });
291 handle
292 }
293
294 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
295 let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned()?;
296 let (answer, handle) = oneshot::channel();
297 commands.send(RingCommand::Accept(mode, answer)).ok()?;
298 handle.await.ok().flatten()
299 }
300
301 /// Only for a click on Decline: it ends the call for all of the user's devices.
302 pub fn set_default_camera(&self, camera: DeviceChoice) {
303 *self.inner.default_camera.lock().expect("default camera lock") = camera;
304 }
305
306 pub fn decline_ring(&self, ring_id: u64) {
307 self.send_ring_command(ring_id, RingCommand::Decline);
308 }
309
310 /// Stops ringing locally without telling Teams; the call keeps ringing elsewhere.
311 pub fn drop_ring(&self, ring_id: u64) {
312 self.send_ring_command(ring_id, RingCommand::Drop);
313 }
314
315 fn send_ring_command(&self, ring_id: u64, command: RingCommand) {
316 let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned();
317 if let Some(commands) = commands {
318 let _ = commands.send(command);
319 }
320 }
321
322 pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget> {
323 let signaling = self.inner.signaling(Timeline::new(self.inner.config.trace));
324 let from = self.inner.participant(&uuid::Uuid::new_v4().to_string());
325 let (target, conversation) = signaling
326 .resolve_meeting(&from, &self.inner.callback_links(), meeting_data)
327 .await?;
328 let _ = signaling.leave(&conversation, &from, LeaveReason::Cancel).await;
329 Ok(target)
330 }
331
332 pub async fn stop(&self) {
333 let stop = self.inner.stop.lock().expect("stop lock").take();
334 if let Some(stop) = stop {
335 let _ = stop.send(());
336 }
337 let tasks: Vec<JoinHandle<()>> = std::mem::take(&mut *self.inner.tasks.lock().expect("tasks lock"));
338 for task in tasks {
339 let _ = task.await;
340 }
341 }
342}
343
344async fn pump_realtime(mut realtime: Realtime, inner: Arc<Inner>, mut stop: oneshot::Receiver<()>) {
345 let mut last_status = None;
346 loop {
347 tokio::select! {
348 event = realtime.recv() => match event {
349 Some(RealtimeEvent::Endpoint(endpoint)) => *inner.endpoint.lock().expect("endpoint lock") = endpoint,
350 Some(RealtimeEvent::Status(status)) => {
351 if last_status.as_ref() != Some(&status) {
352 eprintln!("calls: trouter {:?} {}", status.kind, status.detail);
353 last_status = Some(status);
354 }
355 }
356 Some(_) => {}
357 None => return,
358 },
359 _ = &mut stop => {
360 realtime.stop().await;
361 return;
362 }
363 }
364 }
365}
366
367async fn route_callbacks(mut callbacks: mpsc::UnboundedReceiver<TrouterCallback>, engine: CallEngine) {
368 while let Some(callback) = callbacks.recv().await {
369 if callback.path.is_empty() {
370 engine.handle_push(callback);
371 } else {
372 engine.inner.route(callback);
373 }
374 }
375}
376
377impl CallEngine {
378 fn handle_push(&self, callback: TrouterCallback) {
379 self.inner.replier.reply(callback.request_id, 200, "");
380 if !self.inner.config.ringable {
381 return;
382 }
383 let Ok(PushEvent::IncomingCall(notification)) = decode_push(&callback.body) else {
384 return;
385 };
386 let notification = *notification;
387 if self.inner.already_seen(&notification) {
388 return;
389 }
390 let ring_id = self.inner.next_ring_id.fetch_add(1, Ordering::SeqCst);
391 let (commands, receiver) = mpsc::unbounded_channel();
392 self.inner.rings.lock().expect("rings lock").insert(ring_id, commands);
393 tokio::spawn(ring_task(self.clone(), notification, ring_id, receiver));
394 }
395}
396
397async fn ring_task(
398 engine: CallEngine,
399 notification: CallNotification,
400 ring_id: u64,
401 mut commands: mpsc::UnboundedReceiver<RingCommand>,
402) {
403 let inner = engine.inner.clone();
404 let links = inner.callback_links();
405 let route_id = links.call_id().to_owned();
406 let mut callbacks = inner.register_route(&route_id);
407 let timeline = Timeline::new(inner.config.trace);
408 let signaling = inner.signaling(timeline.clone());
409 let participant_id = if notification.participant_id.is_empty() {
410 uuid::Uuid::new_v4().to_string()
411 } else {
412 notification.participant_id.clone()
413 };
414 let participant = inner.participant(&participant_id);
415 let cleanup = |inner: &Inner| {
416 inner.unregister_route(&route_id);
417 inner.rings.lock().expect("rings lock").remove(&ring_id);
418 };
419 let Some(attach_url) = notification.links.get("attach") else {
420 cleanup(&inner);
421 return;
422 };
423 let request = AttachRequest {
424 from: &participant,
425 callbacks: &links,
426 controller: notification.conversation_controller.as_deref(),
427 needs_media: notification.offer_sdp.is_none(),
428 };
429 let mut attached = match signaling.attach(attach_url, &request).await {
430 Ok(attached) => attached,
431 Err(error) => {
432 timeline.record("attach failed", error.to_string());
433 cleanup(&inner);
434 return;
435 }
436 };
437 if attached.offer_sdp.is_none() {
438 attached.offer_sdp = notification.offer_sdp.clone();
439 }
440 if let Some(progress) = attached.links.get("progress")
441 && let Err(error) = signaling.send_ringing(progress, &participant).await
442 {
443 timeline.record("ringing progress failed", error.to_string());
444 }
445 inner.emit(EngineEvent::Incoming(IncomingRing {
446 ring_id,
447 caller: notification.caller.clone(),
448 thread_id: notification.thread_id.clone(),
449 video: notification.video,
450 is_group: notification.is_multi_party,
451 subject: notification.subject.clone(),
452 }));
453 loop {
454 tokio::select! {
455 callback = callbacks.recv() => {
456 let Some(callback) = callback else { break };
457 inner.replier.reply(callback.request_id, 200, "");
458 let event = decode_body(&callback).and_then(|body| classify(&callback.path, body));
459 if let Ok((_, CallEvent::End(end))) = event {
460 inner.emit(EngineEvent::RingEnded {
461 ring_id,
462 kind: end.kind(),
463 answered_by: end.accepted_elsewhere_by,
464 });
465 break;
466 }
467 }
468 command = commands.recv() => match command {
469 Some(RingCommand::Accept(accept, answer)) => {
470 let (handle, control) = call_channel();
471 let incoming = IncomingCall {
472 accept,
473 notification,
474 attached,
475 links,
476 participant,
477 callbacks,
478 };
479 let _ = answer.send(Some(handle));
480 inner.rings.lock().expect("rings lock").remove(&ring_id);
481 let options = inner.call_options();
482 tokio::spawn(async move {
483 let _ = engine.run(Plan::Incoming(Box::new(incoming)), options, control).await;
484 });
485 return;
486 }
487 Some(RingCommand::Decline) => {
488 if let Some(call_leg) = attached.links.get("callLeg")
489 && let Err(error) = signaling.decline(call_leg).await
490 {
491 timeline.record("decline failed", error.to_string());
492 }
493 break;
494 }
495 Some(RingCommand::Drop) | None => break,
496 }
497 }
498 }
499 cleanup(&inner);
500}
501
502#[cfg(test)]
503mod tests {
504 use super::*;
505
506 #[test]
507 fn a_new_call_dump_keeps_only_the_newest_earlier_ones() {
508 let base = std::env::temp_dir().join(format!("call-dumps-test-{}", std::process::id()));
509 for millis in 1..=6 {
510 std::fs::create_dir_all(base.join(format!("{millis:015}"))).unwrap();
511 }
512 let next = next_call_dump_dir(&base);
513 let mut left: Vec<String> = std::fs::read_dir(&base).unwrap().flatten().map(|entry| entry.file_name().to_string_lossy().into_owned()).collect();
514 left.sort();
515 let _ = std::fs::remove_dir_all(&base);
516 assert_eq!(left, (3..=6).map(|millis| format!("{millis:015}")).collect::<Vec<_>>());
517 assert!(next.file_name().unwrap().to_string_lossy().into_owned() > format!("{:015}", 6));
518 }
519
520 #[test]
521 fn callback_base_comes_from_the_presence_uri() {
522 assert_eq!(
523 callback_base("https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc//unifiedPresenceService"),
524 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/"
525 );
526 assert_eq!(callback_base("https://h/v4/f/abc/unifiedPresenceService"), "https://h/v4/f/abc/");
527 }
528
529 #[test]
530 fn only_the_ringable_engine_registers_for_calls() {
531 assert!(calling_realtime_config(true, calling_instance_names()).ringable);
532 assert!(!calling_realtime_config(false, calling_instance_names()).ringable);
533 assert!(calling_realtime_config(true, calling_instance_names()).forward_callbacks);
534 }
535}