BlueGit

ict rusty-teams

Files

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

engine.rs

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