BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / launcher.rs

launcher.rs

launcher.rs 6.9 KiB Download Raw
1use std::future::Future;
2use std::sync::{Arc, Mutex};
3use std::time::Duration;
4
5use calling::meeting::{LiveMeeting, fetch_live_meeting};
6use calling::{
7 AcceptMode, BackgroundCache, CallEngine, DeviceChoice, CallHandle, CallSpec, CallState, CallUpdate, DefaultBackground, EndReason, EngineConfig, EngineEvent, MeetingTarget, call_channel,
8};
9use session::{Session, SessionConfig, Transport};
10
11const START_RETRY_STEPS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(5)];
12const START_RETRY_STEADY: Duration = Duration::from_secs(10);
13const NOT_READY: &str = "Calls are not ready yet";
14
15pub struct CallLauncher {
16 engine: Mutex<Option<CallEngine>>,
17 default_camera: Mutex<DeviceChoice>,
18}
19
20impl CallLauncher {
21 pub fn start(
22 transport: Arc<dyn Transport>,
23 ringable: bool,
24 on_event: impl Fn(EngineEvent) + Send + 'static,
25 ) -> Arc<CallLauncher> {
26 let launcher = Arc::new(CallLauncher {
27 engine: Mutex::new(None),
28 default_camera: Mutex::new(DeviceChoice::SystemDefault),
29 });
30 let running = launcher.clone();
31 crate::runtime::handle().spawn(async move {
32 let (engine, mut events) =
33 start_with_retry(|| start_engine(transport.clone(), ringable), &START_RETRY_STEPS, START_RETRY_STEADY).await;
34 crate::diagnostics::record("calls: engine ready, registered with the registrar");
35 engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());
36 *running.engine.lock().expect("engine lock") = Some(engine);
37 while let Some(event) = events.recv().await {
38 on_event(event);
39 }
40 });
41 launcher
42 }
43
44 fn engine(&self) -> Option<CallEngine> {
45 self.engine.lock().expect("engine lock").clone()
46 }
47
48 pub fn set_default_camera(&self, camera: DeviceChoice) {
49 *self.default_camera.lock().expect("camera lock") = camera.clone();
50 if let Some(engine) = self.engine() {
51 engine.set_default_camera(camera);
52 }
53 }
54
55 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
56 match self.engine() {
57 Some(engine) => engine.start_call(spec),
58 None => failed_handle(NOT_READY),
59 }
60 }
61
62 pub fn start_consult(&self, spec: CallSpec) -> CallHandle {
63 match self.engine() {
64 Some(engine) => engine.start_consult(spec),
65 None => failed_handle(NOT_READY),
66 }
67 }
68
69 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
70 self.engine()?.accept_ring(ring_id, mode).await
71 }
72
73 pub fn decline_ring(&self, ring_id: u64) {
74 if let Some(engine) = self.engine() {
75 engine.decline_ring(ring_id);
76 }
77 }
78
79 pub fn drop_ring(&self, ring_id: u64) {
80 if let Some(engine) = self.engine() {
81 engine.drop_ring(ring_id);
82 }
83 }
84
85 pub async fn refresh_backgrounds(&self, cache: &BackgroundCache, thumbnails: usize) -> Option<Vec<DefaultBackground>> {
86 let session = self.engine()?.session();
87 let catalog = cache.refresh_catalog(&session).await.ok()?;
88 for image in catalog.iter().take(thumbnails) {
89 let _ = cache.ensure_thumbnail(&session, image).await;
90 }
91 Some(catalog)
92 }
93
94 pub async fn download_background(&self, cache: &BackgroundCache, image: &DefaultBackground) -> Option<std::path::PathBuf> {
95 let session = self.engine()?.session();
96 cache.ensure_image(&session, image).await.ok()
97 }
98
99 pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget, String> {
100 self.engine()
101 .ok_or_else(|| NOT_READY.to_owned())?
102 .resolve_meeting(meeting_data)
103 .await
104 .map_err(|error| error.to_string())
105 }
106
107 pub async fn create_meet_now(&self, subject: &str) -> Result<String, String> {
108 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
109 chatsvc::Calendar::new(&session)
110 .create_meet_now(subject)
111 .await
112 .map_err(|error| error.to_string())
113 }
114
115 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
116 let session = self.engine()?.session();
117 fetch_live_meeting(&session, thread_id).await.ok().flatten()
118 }
119}
120
121async fn start_with_retry<T, E, F, S>(mut start: S, steps: &[Duration], steady: Duration) -> T
122where
123 T: Send + 'static,
124 E: std::fmt::Display + Send + 'static,
125 F: Future<Output = Result<T, E>> + Send + 'static,
126 S: FnMut() -> F,
127{
128 let mut last_failure = String::new();
129 let mut failures = 0usize;
130 loop {
131 let failure = match tokio::spawn(start()).await {
132 Ok(Ok(started)) => return started,
133 Ok(Err(error)) => error.to_string(),
134 Err(join_error) => format!("start task panicked: {join_error}"),
135 };
136 let delay = steps.get(failures).copied().unwrap_or(steady);
137 failures += 1;
138 if failure != last_failure {
139 crate::diagnostics::record(format!("calls: engine start failed, retrying in {}s: {failure}", delay.as_secs()));
140 last_failure = failure;
141 }
142 tokio::time::sleep(delay).await;
143 }
144}
145
146async fn start_engine(
147 transport: Arc<dyn Transport>,
148 ringable: bool,
149) -> calling::Result<(CallEngine, tokio::sync::mpsc::UnboundedReceiver<EngineEvent>)> {
150 let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
151 let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
152 let config = EngineConfig {
153 ringable,
154 ..EngineConfig::default()
155 };
156 CallEngine::start(session, poll_session, config).await
157}
158
159fn failed_handle(message: &str) -> CallHandle {
160 let (handle, control) = call_channel();
161 control.send(CallUpdate::State(CallState::Ended {
162 reason: EndReason::Failed(message.to_owned()),
163 }));
164 handle
165}
166
167#[cfg(test)]
168mod tests {
169 use std::sync::atomic::{AtomicU32, Ordering};
170
171 use super::*;
172
173 #[test]
174 fn engine_start_survives_errors_and_panics() {
175 let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
176 let attempts = Arc::new(AtomicU32::new(0));
177 let counter = attempts.clone();
178 let started = runtime.block_on(start_with_retry(
179 move || {
180 let attempt = counter.fetch_add(1, Ordering::SeqCst);
181 async move {
182 match attempt {
183 0 => panic!("boom"),
184 1 => Err("registrar_http_500".to_owned()),
185 _ => Ok(attempt),
186 }
187 }
188 },
189 &[Duration::ZERO],
190 Duration::ZERO,
191 ));
192 assert_eq!(started, 2);
193 assert_eq!(attempts.load(Ordering::SeqCst), 3);
194 }
195}