BlueGit

ict rusty-teams

Files

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

engine.rs

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