BlueGit

ict rusty-teams

fix(calls): joins started before calls are ready wait instead of failing

Calls queue for up to 30 s until the engine is ready, Cancel works meanwhile.
Inbound stalls count only while another participant is unmuted, outbound only while we are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-14 · 6 weeks ago

Hash
299a515dd30ec04170adb2b1c100e57e73543e90
Parent
b5cc6b9c
5 files changed +190 −29
crates/app/src/call/join.rs +5 −3
@@ -6,6 +6,7 @@ use teams_core::{
6 6 };
7 7
8 8 use super::actions::{MEETING_UNAVAILABLE_NOTICE, NOT_CONNECTED_NOTICE};
9 use super::launcher::NOT_READY;
9 10 use super::prejoin::{DemoMeeting, MeetingJoin};
10 11 use crate::app_state::{AppState, selection_title};
11 12 use crate::notify::selection_for;
@@ -93,10 +94,11 @@ impl AppState {
93 94 };
94 95 let receiver = runtime::spawn(async move { launcher.resolve_meeting(&meeting_data).await });
95 96 cx.spawn(async move |this, cx| {
96 let resolved = receiver.await.ok().and_then(Result::ok);
97 let resolved = receiver.await.ok().unwrap_or_else(|| Err(String::new()));
97 98 this.update(cx, |state, cx| match resolved {
98 Some(target) => state.join_resolved_meeting(target, mode, cx),
99 None => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),
99 Ok(target) => state.join_resolved_meeting(target, mode, cx),
100 Err(message) if message == NOT_READY => state.raise_notice(message, None, cx),
101 Err(_) => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),
100 102 })
101 103 .ok();
102 104 })
@@ -6,6 +6,7 @@ use teams_core::{
6};
6};
7
7
8use super::actions::{MEETING_UNAVAILABLE_NOTICE, NOT_CONNECTED_NOTICE};
8use super::actions::{MEETING_UNAVAILABLE_NOTICE, NOT_CONNECTED_NOTICE};
9use super::launcher::NOT_READY;
9use super::prejoin::{DemoMeeting, MeetingJoin};
10use super::prejoin::{DemoMeeting, MeetingJoin};
10use crate::app_state::{AppState, selection_title};
11use crate::app_state::{AppState, selection_title};
11use crate::notify::selection_for;
12use crate::notify::selection_for;
@@ -93,10 +94,11 @@ impl AppState {
93 };
94 };
94 let receiver = runtime::spawn(async move { launcher.resolve_meeting(&meeting_data).await });
95 let receiver = runtime::spawn(async move { launcher.resolve_meeting(&meeting_data).await });
95 cx.spawn(async move |this, cx| {
96 cx.spawn(async move |this, cx| {
96 let resolved = receiver.await.ok().and_then(Result::ok);
97 let resolved = receiver.await.ok().unwrap_or_else(|| Err(String::new()));
97 this.update(cx, |state, cx| match resolved {
98 this.update(cx, |state, cx| match resolved {
98 Some(target) => state.join_resolved_meeting(target, mode, cx),
99 Ok(target) => state.join_resolved_meeting(target, mode, cx),
99 None => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),
100 Err(message) if message == NOT_READY => state.raise_notice(message, None, cx),
101 Err(_) => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),
100 })
102 })
101 .ok();
103 .ok();
102 })
104 })
crates/app/src/call/launcher.rs +132 −20
@@ -1,10 +1,12 @@
1 1 use std::future::Future;
2 2 use std::sync::{Arc, Mutex};
3
4 use tokio::sync::watch;
3 5 use std::time::Duration;
4 6
5 7 use calling::meeting::{LiveMeeting, fetch_live_meeting};
6 8 use calling::{
7 AcceptMode, BackgroundCache, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,
9 AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,
8 10 DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,
9 11 call_channel,
10 12 };
@@ -18,11 +20,13 @@ const START_RETRY_STEPS: [Duration; 3] = [
18 20 Duration::from_secs(5),
19 21 ];
20 22 const START_RETRY_STEADY: Duration = Duration::from_secs(10);
21 const NOT_READY: &str = "Calls are not ready yet";
23 pub(super) const NOT_READY: &str =
24 "Could not reach the Teams calling service. Check your connection and try again.";
25 const READY_WAIT: Duration = Duration::from_secs(30);
22 26 const CALL_DUMPS_DIR: &str = "call-dumps";
23 27
24 28 pub struct CallLauncher {
25 engine: Mutex<Option<CallEngine>>,
29 engine: watch::Sender<Option<CallEngine>>,
26 30 default_camera: Mutex<DeviceChoice>,
27 31 }
28 32
@@ -33,7 +37,7 @@ impl CallLauncher {
33 37 on_event: impl Fn(EngineEvent) + Send + 'static,
34 38 ) -> Arc<CallLauncher> {
35 39 let launcher = Arc::new(CallLauncher {
36 engine: Mutex::new(None),
40 engine: watch::channel(None).0,
37 41 default_camera: Mutex::new(DeviceChoice::SystemDefault),
38 42 });
39 43 let running = launcher.clone();
@@ -46,7 +50,7 @@ impl CallLauncher {
46 50 .await;
47 51 crate::diagnostics::record("calls: engine ready, registered with the registrar");
48 52 engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());
49 *running.engine.lock().expect("engine lock") = Some(engine);
53 running.engine.send_replace(Some(engine));
50 54 while let Some(event) = events.recv().await {
51 55 on_event(event);
52 56 }
@@ -55,7 +59,18 @@ impl CallLauncher {
55 59 }
56 60
57 61 fn engine(&self) -> Option<CallEngine> {
58 self.engine.lock().expect("engine lock").clone()
62 self.engine.borrow().clone()
63 }
64
65 async fn ready_engine(&self) -> Option<CallEngine> {
66 wait_until_ready(self.engine.subscribe(), READY_WAIT).await
67 }
68
69 fn start_when_ready(&self, spec: CallSpec, kind: OutgoingKind) -> CallHandle {
70 let (handle, control) = call_channel();
71 let ready = self.engine.subscribe();
72 crate::runtime::handle().spawn(queue_outgoing(ready, READY_WAIT, spec, kind, control));
73 handle
59 74 }
60 75
61 76 pub fn set_default_camera(&self, camera: DeviceChoice) {
@@ -68,26 +83,26 @@ impl CallLauncher {
68 83 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
69 84 match self.engine() {
70 85 Some(engine) => engine.start_call(spec),
71 None => failed_handle(NOT_READY),
86 None => self.start_when_ready(spec, OutgoingKind::Audio),
72 87 }
73 88 }
74 89
75 90 pub fn start_video_call(&self, spec: CallSpec) -> CallHandle {
76 91 match self.engine() {
77 92 Some(engine) => engine.start_video_call(spec),
78 None => failed_handle(NOT_READY),
93 None => self.start_when_ready(spec, OutgoingKind::Video),
79 94 }
80 95 }
81 96
82 97 pub fn start_consult(&self, spec: CallSpec) -> CallHandle {
83 98 match self.engine() {
84 99 Some(engine) => engine.start_consult(spec),
85 None => failed_handle(NOT_READY),
100 None => self.start_when_ready(spec, OutgoingKind::Consult),
86 101 }
87 102 }
88 103
89 104 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
90 self.engine()?.accept_ring(ring_id, mode).await
105 self.ready_engine().await?.accept_ring(ring_id, mode).await
91 106 }
92 107
93 108 pub fn decline_ring(&self, ring_id: u64) {
@@ -128,7 +143,8 @@ impl CallLauncher {
128 143 &self,
129 144 meeting_data: &serde_json::Value,
130 145 ) -> Result<MeetingTarget, String> {
131 self.engine()
146 self.ready_engine()
147 .await
132 148 .ok_or_else(|| NOT_READY.to_owned())?
133 149 .resolve_meeting(meeting_data)
134 150 .await
@@ -136,7 +152,11 @@ impl CallLauncher {
136 152 }
137 153
138 154 pub async fn create_meet_now(&self, subject: &str) -> Result<String, String> {
139 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
155 let session = self
156 .ready_engine()
157 .await
158 .ok_or_else(|| NOT_READY.to_owned())?
159 .session();
140 160 chatsvc::Calendar::new(&session)
141 161 .create_meet_now(subject)
142 162 .await
@@ -147,7 +167,11 @@ impl CallLauncher {
147 167 &self,
148 168 draft: MeetingDraft,
149 169 ) -> Result<chatsvc::CreatedEvent, String> {
150 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
170 let session = self
171 .ready_engine()
172 .await
173 .ok_or_else(|| NOT_READY.to_owned())?
174 .session();
151 175 let graph = graph::Graph::new(session.clone());
152 176 let mut attendees = Vec::with_capacity(draft.people.len());
153 177 for invitee in &draft.people {
@@ -190,7 +214,11 @@ impl CallLauncher {
190 214 reply: chatsvc::Reply,
191 215 send_response: bool,
192 216 ) -> Result<(), String> {
193 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
217 let session = self
218 .ready_engine()
219 .await
220 .ok_or_else(|| NOT_READY.to_owned())?
221 .session();
194 222 chatsvc::Calendar::new(&session)
195 223 .respond(event_id, ical_uid, reply, send_response)
196 224 .await
@@ -248,18 +276,52 @@ async fn start_engine(
248 276 CallEngine::start(session, poll_session, config).await
249 277 }
250 278
251 fn failed_handle(message: &str) -> CallHandle {
252 let (handle, control) = call_channel();
253 control.send(CallUpdate::State(CallState::Ended {
254 reason: EndReason::Failed(message.to_owned()),
255 }));
256 handle
279 #[derive(Clone, Copy)]
280 enum OutgoingKind {
281 Audio,
282 Video,
283 Consult,
284 }
285
286 async fn wait_until_ready<T: Clone>(
287 mut receiver: watch::Receiver<Option<T>>,
288 timeout: Duration,
289 ) -> Option<T> {
290 let ready = tokio::time::timeout(timeout, receiver.wait_for(Option::is_some))
291 .await
292 .ok()?
293 .ok()?;
294 ready.clone()
295 }
296
297 async fn queue_outgoing(
298 ready: watch::Receiver<Option<CallEngine>>,
299 timeout: Duration,
300 spec: CallSpec,
301 kind: OutgoingKind,
302 mut control: CallControl,
303 ) {
304 let ended = |reason| CallUpdate::State(CallState::Ended { reason });
305 match control.until_hangup(wait_until_ready(ready, timeout)).await {
306 Err(_) => control.send(ended(EndReason::Cancelled)),
307 Ok(None) => control.send(ended(EndReason::Failed(NOT_READY.to_owned()))),
308 Ok(Some(engine)) => {
309 let (concurrent, start_camera) = match kind {
310 OutgoingKind::Audio => (false, false),
311 OutgoingKind::Video => (false, true),
312 OutgoingKind::Consult => (true, false),
313 };
314 engine.start_call_on(spec, concurrent, start_camera, control);
315 }
316 }
257 317 }
258 318
259 319 #[cfg(test)]
260 320 mod tests {
261 321 use std::sync::atomic::{AtomicU32, Ordering};
262 322
323 use calling::CallCommand;
324
263 325 use super::*;
264 326
265 327 #[test]
@@ -287,4 +349,54 @@ mod tests {
287 349 assert_eq!(started, 2);
288 350 assert_eq!(attempts.load(Ordering::SeqCst), 3);
289 351 }
352
353 #[tokio::test]
354 async fn waiting_resolves_once_value_arrives() {
355 let (sender, receiver) = watch::channel(None);
356 let waiter = tokio::spawn(wait_until_ready(receiver, Duration::from_secs(5)));
357 sender.send_replace(Some(7u32));
358 assert_eq!(waiter.await.unwrap(), Some(7));
359 }
360
361 #[tokio::test]
362 async fn waiting_returns_immediately_when_already_ready() {
363 let (_sender, receiver) = watch::channel(Some(3u32));
364 assert_eq!(wait_until_ready(receiver, Duration::ZERO).await, Some(3));
365 }
366
367 #[tokio::test]
368 async fn waiting_gives_up_after_the_timeout() {
369 let (_sender, receiver) = watch::channel(None::<u32>);
370 assert_eq!(wait_until_ready(receiver, Duration::from_millis(20)).await, None);
371 }
372
373 #[tokio::test]
374 async fn waiting_gives_up_when_the_launcher_is_gone() {
375 let (sender, receiver) = watch::channel(None::<u32>);
376 drop(sender);
377 assert_eq!(wait_until_ready(receiver, Duration::from_secs(5)).await, None);
378 }
379
380 #[tokio::test]
381 async fn queued_call_fails_with_notice_after_the_timeout() {
382 let (_sender, receiver) = watch::channel(None);
383 let (mut handle, control) = call_channel();
384 queue_outgoing(receiver, Duration::from_millis(20), CallSpec::Echo, OutgoingKind::Audio, control).await;
385 assert_eq!(
386 handle.updates.recv().await,
387 Some(CallUpdate::State(CallState::Ended { reason: EndReason::Failed(NOT_READY.to_owned()) }))
388 );
389 }
390
391 #[tokio::test]
392 async fn queued_call_is_cancelled_by_hangup() {
393 let (_sender, receiver) = watch::channel(None);
394 let (mut handle, control) = call_channel();
395 handle.commands.send(CallCommand::Hangup).unwrap();
396 queue_outgoing(receiver, Duration::from_secs(30), CallSpec::Echo, OutgoingKind::Video, control).await;
397 assert_eq!(
398 handle.updates.recv().await,
399 Some(CallUpdate::State(CallState::Ended { reason: EndReason::Cancelled }))
400 );
401 }
290 402 }
@@ -1,10 +1,12 @@
1use std::future::Future;
1use std::future::Future;
2use std::sync::{Arc, Mutex};
2use std::sync::{Arc, Mutex};
3
4use tokio::sync::watch;
3use std::time::Duration;
5use std::time::Duration;
4
6
5use calling::meeting::{LiveMeeting, fetch_live_meeting};
7use calling::meeting::{LiveMeeting, fetch_live_meeting};
6use calling::{
8use calling::{
7 AcceptMode, BackgroundCache, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,
9 AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,
8 DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,
10 DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,
9 call_channel,
11 call_channel,
10};
12};
@@ -18,11 +20,13 @@ const START_RETRY_STEPS: [Duration; 3] = [
18 Duration::from_secs(5),
20 Duration::from_secs(5),
19];
21];
20const START_RETRY_STEADY: Duration = Duration::from_secs(10);
22const START_RETRY_STEADY: Duration = Duration::from_secs(10);
21const NOT_READY: &str = "Calls are not ready yet";
23pub(super) const NOT_READY: &str =
24 "Could not reach the Teams calling service. Check your connection and try again.";
25const READY_WAIT: Duration = Duration::from_secs(30);
22const CALL_DUMPS_DIR: &str = "call-dumps";
26const CALL_DUMPS_DIR: &str = "call-dumps";
23
27
24pub struct CallLauncher {
28pub struct CallLauncher {
25 engine: Mutex<Option<CallEngine>>,
29 engine: watch::Sender<Option<CallEngine>>,
26 default_camera: Mutex<DeviceChoice>,
30 default_camera: Mutex<DeviceChoice>,
27}
31}
28
32
@@ -33,7 +37,7 @@ impl CallLauncher {
33 on_event: impl Fn(EngineEvent) + Send + 'static,
37 on_event: impl Fn(EngineEvent) + Send + 'static,
34 ) -> Arc<CallLauncher> {
38 ) -> Arc<CallLauncher> {
35 let launcher = Arc::new(CallLauncher {
39 let launcher = Arc::new(CallLauncher {
36 engine: Mutex::new(None),
40 engine: watch::channel(None).0,
37 default_camera: Mutex::new(DeviceChoice::SystemDefault),
41 default_camera: Mutex::new(DeviceChoice::SystemDefault),
38 });
42 });
39 let running = launcher.clone();
43 let running = launcher.clone();
@@ -46,7 +50,7 @@ impl CallLauncher {
46 .await;
50 .await;
47 crate::diagnostics::record("calls: engine ready, registered with the registrar");
51 crate::diagnostics::record("calls: engine ready, registered with the registrar");
48 engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());
52 engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());
49 *running.engine.lock().expect("engine lock") = Some(engine);
53 running.engine.send_replace(Some(engine));
50 while let Some(event) = events.recv().await {
54 while let Some(event) = events.recv().await {
51 on_event(event);
55 on_event(event);
52 }
56 }
@@ -55,7 +59,18 @@ impl CallLauncher {
55 }
59 }
56
60
57 fn engine(&self) -> Option<CallEngine> {
61 fn engine(&self) -> Option<CallEngine> {
58 self.engine.lock().expect("engine lock").clone()
62 self.engine.borrow().clone()
63 }
64
65 async fn ready_engine(&self) -> Option<CallEngine> {
66 wait_until_ready(self.engine.subscribe(), READY_WAIT).await
67 }
68
69 fn start_when_ready(&self, spec: CallSpec, kind: OutgoingKind) -> CallHandle {
70 let (handle, control) = call_channel();
71 let ready = self.engine.subscribe();
72 crate::runtime::handle().spawn(queue_outgoing(ready, READY_WAIT, spec, kind, control));
73 handle
59 }
74 }
60
75
61 pub fn set_default_camera(&self, camera: DeviceChoice) {
76 pub fn set_default_camera(&self, camera: DeviceChoice) {
@@ -68,26 +83,26 @@ impl CallLauncher {
68 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
83 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
69 match self.engine() {
84 match self.engine() {
70 Some(engine) => engine.start_call(spec),
85 Some(engine) => engine.start_call(spec),
71 None => failed_handle(NOT_READY),
86 None => self.start_when_ready(spec, OutgoingKind::Audio),
72 }
87 }
73 }
88 }
74
89
75 pub fn start_video_call(&self, spec: CallSpec) -> CallHandle {
90 pub fn start_video_call(&self, spec: CallSpec) -> CallHandle {
76 match self.engine() {
91 match self.engine() {
77 Some(engine) => engine.start_video_call(spec),
92 Some(engine) => engine.start_video_call(spec),
78 None => failed_handle(NOT_READY),
93 None => self.start_when_ready(spec, OutgoingKind::Video),
79 }
94 }
80 }
95 }
81
96
82 pub fn start_consult(&self, spec: CallSpec) -> CallHandle {
97 pub fn start_consult(&self, spec: CallSpec) -> CallHandle {
83 match self.engine() {
98 match self.engine() {
84 Some(engine) => engine.start_consult(spec),
99 Some(engine) => engine.start_consult(spec),
85 None => failed_handle(NOT_READY),
100 None => self.start_when_ready(spec, OutgoingKind::Consult),
86 }
101 }
87 }
102 }
88
103
89 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
104 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
90 self.engine()?.accept_ring(ring_id, mode).await
105 self.ready_engine().await?.accept_ring(ring_id, mode).await
91 }
106 }
92
107
93 pub fn decline_ring(&self, ring_id: u64) {
108 pub fn decline_ring(&self, ring_id: u64) {
@@ -128,7 +143,8 @@ impl CallLauncher {
128 &self,
143 &self,
129 meeting_data: &serde_json::Value,
144 meeting_data: &serde_json::Value,
130 ) -> Result<MeetingTarget, String> {
145 ) -> Result<MeetingTarget, String> {
131 self.engine()
146 self.ready_engine()
147 .await
132 .ok_or_else(|| NOT_READY.to_owned())?
148 .ok_or_else(|| NOT_READY.to_owned())?
133 .resolve_meeting(meeting_data)
149 .resolve_meeting(meeting_data)
134 .await
150 .await
@@ -136,7 +152,11 @@ impl CallLauncher {
136 }
152 }
137
153
138 pub async fn create_meet_now(&self, subject: &str) -> Result<String, String> {
154 pub async fn create_meet_now(&self, subject: &str) -> Result<String, String> {
139 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
155 let session = self
156 .ready_engine()
157 .await
158 .ok_or_else(|| NOT_READY.to_owned())?
159 .session();
140 chatsvc::Calendar::new(&session)
160 chatsvc::Calendar::new(&session)
141 .create_meet_now(subject)
161 .create_meet_now(subject)
142 .await
162 .await
@@ -147,7 +167,11 @@ impl CallLauncher {
147 &self,
167 &self,
148 draft: MeetingDraft,
168 draft: MeetingDraft,
149 ) -> Result<chatsvc::CreatedEvent, String> {
169 ) -> Result<chatsvc::CreatedEvent, String> {
150 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
170 let session = self
171 .ready_engine()
172 .await
173 .ok_or_else(|| NOT_READY.to_owned())?
174 .session();
151 let graph = graph::Graph::new(session.clone());
175 let graph = graph::Graph::new(session.clone());
152 let mut attendees = Vec::with_capacity(draft.people.len());
176 let mut attendees = Vec::with_capacity(draft.people.len());
153 for invitee in &draft.people {
177 for invitee in &draft.people {
@@ -190,7 +214,11 @@ impl CallLauncher {
190 reply: chatsvc::Reply,
214 reply: chatsvc::Reply,
191 send_response: bool,
215 send_response: bool,
192 ) -> Result<(), String> {
216 ) -> Result<(), String> {
193 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
217 let session = self
218 .ready_engine()
219 .await
220 .ok_or_else(|| NOT_READY.to_owned())?
221 .session();
194 chatsvc::Calendar::new(&session)
222 chatsvc::Calendar::new(&session)
195 .respond(event_id, ical_uid, reply, send_response)
223 .respond(event_id, ical_uid, reply, send_response)
196 .await
224 .await
@@ -248,18 +276,52 @@ async fn start_engine(
248 CallEngine::start(session, poll_session, config).await
276 CallEngine::start(session, poll_session, config).await
249}
277}
250
278
251fn failed_handle(message: &str) -> CallHandle {
279#[derive(Clone, Copy)]
252 let (handle, control) = call_channel();
280enum OutgoingKind {
253 control.send(CallUpdate::State(CallState::Ended {
281 Audio,
254 reason: EndReason::Failed(message.to_owned()),
282 Video,
255 }));
283 Consult,
256 handle
284}
285
286async fn wait_until_ready<T: Clone>(
287 mut receiver: watch::Receiver<Option<T>>,
288 timeout: Duration,
289) -> Option<T> {
290 let ready = tokio::time::timeout(timeout, receiver.wait_for(Option::is_some))
291 .await
292 .ok()?
293 .ok()?;
294 ready.clone()
295}
296
297async fn queue_outgoing(
298 ready: watch::Receiver<Option<CallEngine>>,
299 timeout: Duration,
300 spec: CallSpec,
301 kind: OutgoingKind,
302 mut control: CallControl,
303) {
304 let ended = |reason| CallUpdate::State(CallState::Ended { reason });
305 match control.until_hangup(wait_until_ready(ready, timeout)).await {
306 Err(_) => control.send(ended(EndReason::Cancelled)),
307 Ok(None) => control.send(ended(EndReason::Failed(NOT_READY.to_owned()))),
308 Ok(Some(engine)) => {
309 let (concurrent, start_camera) = match kind {
310 OutgoingKind::Audio => (false, false),
311 OutgoingKind::Video => (false, true),
312 OutgoingKind::Consult => (true, false),
313 };
314 engine.start_call_on(spec, concurrent, start_camera, control);
315 }
316 }
257}
317}
258
318
259#[cfg(test)]
319#[cfg(test)]
260mod tests {
320mod tests {
261 use std::sync::atomic::{AtomicU32, Ordering};
321 use std::sync::atomic::{AtomicU32, Ordering};
262
322
323 use calling::CallCommand;
324
263 use super::*;
325 use super::*;
264
326
265 #[test]
327 #[test]
@@ -287,4 +349,54 @@ mod tests {
287 assert_eq!(started, 2);
349 assert_eq!(started, 2);
288 assert_eq!(attempts.load(Ordering::SeqCst), 3);
350 assert_eq!(attempts.load(Ordering::SeqCst), 3);
289 }
351 }
352
353 #[tokio::test]
354 async fn waiting_resolves_once_value_arrives() {
355 let (sender, receiver) = watch::channel(None);
356 let waiter = tokio::spawn(wait_until_ready(receiver, Duration::from_secs(5)));
357 sender.send_replace(Some(7u32));
358 assert_eq!(waiter.await.unwrap(), Some(7));
359 }
360
361 #[tokio::test]
362 async fn waiting_returns_immediately_when_already_ready() {
363 let (_sender, receiver) = watch::channel(Some(3u32));
364 assert_eq!(wait_until_ready(receiver, Duration::ZERO).await, Some(3));
365 }
366
367 #[tokio::test]
368 async fn waiting_gives_up_after_the_timeout() {
369 let (_sender, receiver) = watch::channel(None::<u32>);
370 assert_eq!(wait_until_ready(receiver, Duration::from_millis(20)).await, None);
371 }
372
373 #[tokio::test]
374 async fn waiting_gives_up_when_the_launcher_is_gone() {
375 let (sender, receiver) = watch::channel(None::<u32>);
376 drop(sender);
377 assert_eq!(wait_until_ready(receiver, Duration::from_secs(5)).await, None);
378 }
379
380 #[tokio::test]
381 async fn queued_call_fails_with_notice_after_the_timeout() {
382 let (_sender, receiver) = watch::channel(None);
383 let (mut handle, control) = call_channel();
384 queue_outgoing(receiver, Duration::from_millis(20), CallSpec::Echo, OutgoingKind::Audio, control).await;
385 assert_eq!(
386 handle.updates.recv().await,
387 Some(CallUpdate::State(CallState::Ended { reason: EndReason::Failed(NOT_READY.to_owned()) }))
388 );
389 }
390
391 #[tokio::test]
392 async fn queued_call_is_cancelled_by_hangup() {
393 let (_sender, receiver) = watch::channel(None);
394 let (mut handle, control) = call_channel();
395 handle.commands.send(CallCommand::Hangup).unwrap();
396 queue_outgoing(receiver, Duration::from_secs(30), CallSpec::Echo, OutgoingKind::Video, control).await;
397 assert_eq!(
398 handle.updates.recv().await,
399 Some(CallUpdate::State(CallState::Ended { reason: EndReason::Cancelled }))
400 );
401 }
290}
402}
crates/app/src/call/report/mod.rs +30 −2
@@ -60,6 +60,8 @@ pub struct CallRecorder {
60 60 notices: Vec<(u128, String)>,
61 61 captions: u32,
62 62 series: StatsSeries,
63 others_unmuted: bool,
64 own_unmuted: bool,
63 65 paths: Vec<(u128, MediaPath)>,
64 66 diagnostics: Option<CallDiagnostics>,
65 67 }
@@ -94,6 +96,8 @@ impl CallRecorder {
94 96 notices: Vec::new(),
95 97 captions: 0,
96 98 series: StatsSeries::default(),
99 others_unmuted: true,
100 own_unmuted: true,
97 101 paths: Vec::new(),
98 102 diagnostics: None,
99 103 }
@@ -146,7 +150,10 @@ impl CallRecorder {
146 150 match update {
147 151 CallUpdate::State(state) => self.note_state(state, at_ms),
148 152 CallUpdate::OwnIdentity { mri } => self.me.mri.clone_from(mri),
149 CallUpdate::Muted(_) => self.confirm("mute"),
153 CallUpdate::Muted(muted) => {
154 self.own_unmuted = !muted;
155 self.confirm("mute");
156 }
150 157 CallUpdate::Camera(_) => self.confirm("camera"),
151 158 CallUpdate::LocalShare(_) | CallUpdate::ShareSound(_) => self.confirm("share"),
152 159 CallUpdate::Hold(state) => {
@@ -169,6 +176,9 @@ impl CallRecorder {
169 176 for entry in entries {
170 177 self.remember_person(&entry.mri, &entry.display_name);
171 178 }
179 self.others_unmuted = entries
180 .iter()
181 .any(|entry| !entry.in_lobby && !entry.muted && entry.mri != self.me.mri);
172 182 let present = entries.iter().filter(|entry| !entry.in_lobby).count();
173 183 self.peak_participants = self.peak_participants.max(present);
174 184 }
@@ -179,7 +189,9 @@ impl CallRecorder {
179 189 self.paths.push((at_ms, health.path));
180 190 }
181 191 }
182 CallUpdate::Sample(sample) => self.series.observe_sample(sample),
192 CallUpdate::Sample(sample) => {
193 self.series.observe_sample(sample, self.others_unmuted, self.own_unmuted);
194 }
183 195 CallUpdate::Diagnostics(diagnostics) => self.diagnostics = Some((**diagnostics).clone()),
184 196 _ => {}
185 197 }
@@ -384,6 +396,22 @@ mod tests {
384 396 assert!(document.stem.ends_with("-1to1"));
385 397 }
386 398
399 #[test]
400 fn a_call_where_everyone_else_is_muted_reports_no_inbound_stall() {
401 let mut recorder = recorder();
402 recorder.observe(&CallUpdate::Roster(vec![RosterEntry {
403 mri: PEER_MRI.to_owned(),
404 display_name: "Mara Lindqvist".to_owned(),
405 muted: true,
406 ..RosterEntry::default()
407 }]));
408 for packets in [100, 100, 100, 100] {
409 recorder.observe(&sample(packets));
410 }
411 let json: serde_json::Value = serde_json::from_str(&recorder.document().json).expect("valid json");
412 assert_eq!(json["stats"]["audio_in_stalled_samples"], 0);
413 }
414
387 415 #[test]
388 416 fn each_transfer_answer_settles_the_transfer_it_belongs_to() {
389 417 let mut recorder = recorder();
@@ -60,6 +60,8 @@ pub struct CallRecorder {
60 notices: Vec<(u128, String)>,
60 notices: Vec<(u128, String)>,
61 captions: u32,
61 captions: u32,
62 series: StatsSeries,
62 series: StatsSeries,
63 others_unmuted: bool,
64 own_unmuted: bool,
63 paths: Vec<(u128, MediaPath)>,
65 paths: Vec<(u128, MediaPath)>,
64 diagnostics: Option<CallDiagnostics>,
66 diagnostics: Option<CallDiagnostics>,
65}
67}
@@ -94,6 +96,8 @@ impl CallRecorder {
94 notices: Vec::new(),
96 notices: Vec::new(),
95 captions: 0,
97 captions: 0,
96 series: StatsSeries::default(),
98 series: StatsSeries::default(),
99 others_unmuted: true,
100 own_unmuted: true,
97 paths: Vec::new(),
101 paths: Vec::new(),
98 diagnostics: None,
102 diagnostics: None,
99 }
103 }
@@ -146,7 +150,10 @@ impl CallRecorder {
146 match update {
150 match update {
147 CallUpdate::State(state) => self.note_state(state, at_ms),
151 CallUpdate::State(state) => self.note_state(state, at_ms),
148 CallUpdate::OwnIdentity { mri } => self.me.mri.clone_from(mri),
152 CallUpdate::OwnIdentity { mri } => self.me.mri.clone_from(mri),
149 CallUpdate::Muted(_) => self.confirm("mute"),
153 CallUpdate::Muted(muted) => {
154 self.own_unmuted = !muted;
155 self.confirm("mute");
156 }
150 CallUpdate::Camera(_) => self.confirm("camera"),
157 CallUpdate::Camera(_) => self.confirm("camera"),
151 CallUpdate::LocalShare(_) | CallUpdate::ShareSound(_) => self.confirm("share"),
158 CallUpdate::LocalShare(_) | CallUpdate::ShareSound(_) => self.confirm("share"),
152 CallUpdate::Hold(state) => {
159 CallUpdate::Hold(state) => {
@@ -169,6 +176,9 @@ impl CallRecorder {
169 for entry in entries {
176 for entry in entries {
170 self.remember_person(&entry.mri, &entry.display_name);
177 self.remember_person(&entry.mri, &entry.display_name);
171 }
178 }
179 self.others_unmuted = entries
180 .iter()
181 .any(|entry| !entry.in_lobby && !entry.muted && entry.mri != self.me.mri);
172 let present = entries.iter().filter(|entry| !entry.in_lobby).count();
182 let present = entries.iter().filter(|entry| !entry.in_lobby).count();
173 self.peak_participants = self.peak_participants.max(present);
183 self.peak_participants = self.peak_participants.max(present);
174 }
184 }
@@ -179,7 +189,9 @@ impl CallRecorder {
179 self.paths.push((at_ms, health.path));
189 self.paths.push((at_ms, health.path));
180 }
190 }
181 }
191 }
182 CallUpdate::Sample(sample) => self.series.observe_sample(sample),
192 CallUpdate::Sample(sample) => {
193 self.series.observe_sample(sample, self.others_unmuted, self.own_unmuted);
194 }
183 CallUpdate::Diagnostics(diagnostics) => self.diagnostics = Some((**diagnostics).clone()),
195 CallUpdate::Diagnostics(diagnostics) => self.diagnostics = Some((**diagnostics).clone()),
184 _ => {}
196 _ => {}
185 }
197 }
@@ -384,6 +396,22 @@ mod tests {
384 assert!(document.stem.ends_with("-1to1"));
396 assert!(document.stem.ends_with("-1to1"));
385 }
397 }
386
398
399 #[test]
400 fn a_call_where_everyone_else_is_muted_reports_no_inbound_stall() {
401 let mut recorder = recorder();
402 recorder.observe(&CallUpdate::Roster(vec![RosterEntry {
403 mri: PEER_MRI.to_owned(),
404 display_name: "Mara Lindqvist".to_owned(),
405 muted: true,
406 ..RosterEntry::default()
407 }]));
408 for packets in [100, 100, 100, 100] {
409 recorder.observe(&sample(packets));
410 }
411 let json: serde_json::Value = serde_json::from_str(&recorder.document().json).expect("valid json");
412 assert_eq!(json["stats"]["audio_in_stalled_samples"], 0);
413 }
414
387 #[test]
415 #[test]
388 fn each_transfer_answer_settles_the_transfer_it_belongs_to() {
416 fn each_transfer_answer_settles_the_transfer_it_belongs_to() {
389 let mut recorder = recorder();
417 let mut recorder = recorder();
crates/app/src/call/report/series.rs +17 −2
@@ -65,14 +65,16 @@ impl StatsSeries {
65 65 }
66 66 }
67 67
68 pub fn observe_sample(&mut self, sample: &StatsSample) {
68 pub fn observe_sample(&mut self, sample: &StatsSample, others_unmuted: bool, own_unmuted: bool) {
69 69 let video = &sample.video;
70 70 if let Some(before) = self.values.get("audio_in_packets")
71 && others_unmuted
71 72 && sample.audio_in_packets <= before.last as u64
72 73 {
73 74 self.stalled_audio_in += 1;
74 75 }
75 76 if let Some(before) = self.values.get("audio_out_packets")
77 && own_unmuted
76 78 && sample.audio_out_packets <= before.last as u64
77 79 {
78 80 self.stalled_audio_out += 1;
@@ -152,7 +154,7 @@ mod tests {
152 154 fn samples_keep_min_max_last_and_count_stalls() {
153 155 let mut series = StatsSeries::default();
154 156 for packets in [10, 20, 20, 35] {
155 series.observe_sample(&sample(packets));
157 series.observe_sample(&sample(packets), true, true);
156 158 }
157 159 let audio_in = series.values()["audio_in_packets"];
158 160 assert_eq!((audio_in.min, audio_in.max, audio_in.last, audio_in.samples), (10., 35., 35., 4));
@@ -160,6 +162,19 @@ mod tests {
160 162 assert_eq!(series.values()["video_in_width"].last, 1280.);
161 163 }
162 164
165 #[test]
166 fn stalls_only_count_while_the_sender_could_be_heard() {
167 let mut series = StatsSeries::default();
168 for packets in [10, 10, 10] {
169 series.observe_sample(&sample(packets), false, false);
170 }
171 assert_eq!((series.stalled_audio_in, series.stalled_audio_out), (0, 0));
172 series.observe_sample(&sample(10), true, false);
173 assert_eq!((series.stalled_audio_in, series.stalled_audio_out), (1, 0));
174 series.observe_sample(&sample(10), false, true);
175 assert_eq!((series.stalled_audio_in, series.stalled_audio_out), (1, 1));
176 }
177
163 178 #[test]
164 179 fn health_keeps_ranges_and_level_changes() {
165 180 let mut series = StatsSeries::default();
@@ -65,14 +65,16 @@ impl StatsSeries {
65 }
65 }
66 }
66 }
67
67
68 pub fn observe_sample(&mut self, sample: &StatsSample) {
68 pub fn observe_sample(&mut self, sample: &StatsSample, others_unmuted: bool, own_unmuted: bool) {
69 let video = &sample.video;
69 let video = &sample.video;
70 if let Some(before) = self.values.get("audio_in_packets")
70 if let Some(before) = self.values.get("audio_in_packets")
71 && others_unmuted
71 && sample.audio_in_packets <= before.last as u64
72 && sample.audio_in_packets <= before.last as u64
72 {
73 {
73 self.stalled_audio_in += 1;
74 self.stalled_audio_in += 1;
74 }
75 }
75 if let Some(before) = self.values.get("audio_out_packets")
76 if let Some(before) = self.values.get("audio_out_packets")
77 && own_unmuted
76 && sample.audio_out_packets <= before.last as u64
78 && sample.audio_out_packets <= before.last as u64
77 {
79 {
78 self.stalled_audio_out += 1;
80 self.stalled_audio_out += 1;
@@ -152,7 +154,7 @@ mod tests {
152 fn samples_keep_min_max_last_and_count_stalls() {
154 fn samples_keep_min_max_last_and_count_stalls() {
153 let mut series = StatsSeries::default();
155 let mut series = StatsSeries::default();
154 for packets in [10, 20, 20, 35] {
156 for packets in [10, 20, 20, 35] {
155 series.observe_sample(&sample(packets));
157 series.observe_sample(&sample(packets), true, true);
156 }
158 }
157 let audio_in = series.values()["audio_in_packets"];
159 let audio_in = series.values()["audio_in_packets"];
158 assert_eq!((audio_in.min, audio_in.max, audio_in.last, audio_in.samples), (10., 35., 35., 4));
160 assert_eq!((audio_in.min, audio_in.max, audio_in.last, audio_in.samples), (10., 35., 35., 4));
@@ -160,6 +162,19 @@ mod tests {
160 assert_eq!(series.values()["video_in_width"].last, 1280.);
162 assert_eq!(series.values()["video_in_width"].last, 1280.);
161 }
163 }
162
164
165 #[test]
166 fn stalls_only_count_while_the_sender_could_be_heard() {
167 let mut series = StatsSeries::default();
168 for packets in [10, 10, 10] {
169 series.observe_sample(&sample(packets), false, false);
170 }
171 assert_eq!((series.stalled_audio_in, series.stalled_audio_out), (0, 0));
172 series.observe_sample(&sample(10), true, false);
173 assert_eq!((series.stalled_audio_in, series.stalled_audio_out), (1, 0));
174 series.observe_sample(&sample(10), false, true);
175 assert_eq!((series.stalled_audio_in, series.stalled_audio_out), (1, 1));
176 }
177
163 #[test]
178 #[test]
164 fn health_keeps_ranges_and_level_changes() {
179 fn health_keeps_ranges_and_level_changes() {
165 let mut series = StatsSeries::default();
180 let mut series = StatsSeries::default();
crates/calling/src/engine.rs +6 −2
@@ -11,7 +11,7 @@ use tokio::time::timeout;
11 11
12 12 use crate::call::{AcceptMode, CallOptions, CallSpec, IncomingCall, Plan};
13 13 use crate::devices::DeviceChoice;
14 use crate::control::{CallHandle, call_channel};
14 use crate::control::{CallControl, CallHandle, call_channel};
15 15 use crate::end::EndKind;
16 16 use crate::error::{Error, Result};
17 17 use crate::push::{CallNotification, Caller, PushEvent, decode_push};
@@ -287,12 +287,16 @@ impl CallEngine {
287 287
288 288 fn start_call_with(&self, spec: CallSpec, concurrent: bool, start_camera: bool) -> CallHandle {
289 289 let (handle, control) = call_channel();
290 self.start_call_on(spec, concurrent, start_camera, control);
291 handle
292 }
293
294 pub fn start_call_on(&self, spec: CallSpec, concurrent: bool, start_camera: bool, control: CallControl) {
290 295 let engine = self.clone();
291 296 self.inner.runtime.spawn(async move {
292 297 let options = CallOptions { concurrent, start_camera, ..engine.inner.call_options() };
293 298 let _ = engine.run(Plan::Outgoing(spec), options, control).await;
294 299 });
295 handle
296 300 }
297 301
298 302 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
@@ -11,7 +11,7 @@ use tokio::time::timeout;
11
11
12use crate::call::{AcceptMode, CallOptions, CallSpec, IncomingCall, Plan};
12use crate::call::{AcceptMode, CallOptions, CallSpec, IncomingCall, Plan};
13use crate::devices::DeviceChoice;
13use crate::devices::DeviceChoice;
14use crate::control::{CallHandle, call_channel};
14use crate::control::{CallControl, CallHandle, call_channel};
15use crate::end::EndKind;
15use crate::end::EndKind;
16use crate::error::{Error, Result};
16use crate::error::{Error, Result};
17use crate::push::{CallNotification, Caller, PushEvent, decode_push};
17use crate::push::{CallNotification, Caller, PushEvent, decode_push};
@@ -287,12 +287,16 @@ impl CallEngine {
287
287
288 fn start_call_with(&self, spec: CallSpec, concurrent: bool, start_camera: bool) -> CallHandle {
288 fn start_call_with(&self, spec: CallSpec, concurrent: bool, start_camera: bool) -> CallHandle {
289 let (handle, control) = call_channel();
289 let (handle, control) = call_channel();
290 self.start_call_on(spec, concurrent, start_camera, control);
291 handle
292 }
293
294 pub fn start_call_on(&self, spec: CallSpec, concurrent: bool, start_camera: bool, control: CallControl) {
290 let engine = self.clone();
295 let engine = self.clone();
291 self.inner.runtime.spawn(async move {
296 self.inner.runtime.spawn(async move {
292 let options = CallOptions { concurrent, start_camera, ..engine.inner.call_options() };
297 let options = CallOptions { concurrent, start_camera, ..engine.inner.call_options() };
293 let _ = engine.run(Plan::Outgoing(spec), options, control).await;
298 let _ = engine.run(Plan::Outgoing(spec), options, control).await;
294 });
299 });
295 handle
296 }
300 }
297
301
298 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
302 pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {