BlueGit

ict rusty-teams

Files

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

engine.rs

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