BlueGit

ict rusty-teams

Files

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

engine.rs

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