BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-call-model / src / report / mod.rs

mod.rs

8629da58 History
mod.rs 18.5 KiB Download Raw
1mod document;
2mod markdown;
3mod scrub;
4mod series;
5mod storage;
6
7use std::cell::RefCell;
8use std::rc::Rc;
9use std::time::Instant;
10
11use calling::{CallCommand, CallDiagnostics, CallState, CallUpdate, CaptionState, EndReason, HoldState, MediaPath};
12use chrono::{DateTime, Utc};
13
14pub use document::Document;
15pub use storage::{report_directory, save_report};
16
17use super::model::CallKind;
18use series::StatsSeries;
19
20pub const SETTING_META_KEY: &str = "call_test_report";
21
22pub type SharedRecorder = Rc<RefCell<CallRecorder>>;
23
24#[derive(Debug, Clone, PartialEq)]
25enum Outcome {
26 Requested,
27 Confirmed(u128),
28 Failed(String),
29}
30
31#[derive(Debug, Clone)]
32struct FeatureRecord {
33 at_ms: u128,
34 feature: &'static str,
35 detail: String,
36 outcome: Outcome,
37}
38
39#[derive(Debug, Clone)]
40pub struct OwnIdentity {
41 pub mri: String,
42 pub display_name: String,
43 pub email: String,
44}
45
46#[derive(Debug, Clone)]
47pub struct CallRecorder {
48 started_at: DateTime<Utc>,
49 started: Instant,
50 kind: CallKind,
51 incoming: bool,
52 demo: bool,
53 me: OwnIdentity,
54 people: Vec<(String, String)>,
55 peak_participants: usize,
56 states: Vec<(u128, String)>,
57 connected_ms: Option<u128>,
58 ended: Option<(u128, EndReason)>,
59 features: Vec<FeatureRecord>,
60 notices: Vec<(u128, String)>,
61 captions: u32,
62 series: StatsSeries,
63 others_unmuted: bool,
64 own_unmuted: bool,
65 paths: Vec<(u128, MediaPath)>,
66 diagnostics: Option<CallDiagnostics>,
67}
68
69pub fn load_enabled(store: &store::Store) -> bool {
70 store.meta(SETTING_META_KEY).ok().flatten().as_deref() != Some("0")
71}
72
73pub fn shared(recorder: CallRecorder) -> SharedRecorder {
74 Rc::new(RefCell::new(recorder))
75}
76
77fn on_off(on: bool) -> &'static str {
78 if on { "on" } else { "off" }
79}
80
81impl CallRecorder {
82 pub fn begin(kind: CallKind, incoming: bool, demo: bool, me: OwnIdentity, people: Vec<(String, String)>) -> Self {
83 CallRecorder {
84 started_at: Utc::now(),
85 started: Instant::now(),
86 kind,
87 incoming,
88 demo,
89 me,
90 people,
91 peak_participants: 0,
92 states: Vec::new(),
93 connected_ms: None,
94 ended: None,
95 features: Vec::new(),
96 notices: Vec::new(),
97 captions: 0,
98 series: StatsSeries::default(),
99 others_unmuted: true,
100 own_unmuted: true,
101 paths: Vec::new(),
102 diagnostics: None,
103 }
104 }
105
106 fn elapsed_ms(&self) -> u128 {
107 self.started.elapsed().as_millis()
108 }
109
110 pub fn feature(&mut self, feature: &'static str, detail: impl Into<String>) {
111 let at_ms = self.elapsed_ms();
112 self.features.push(FeatureRecord { at_ms, feature, detail: detail.into(), outcome: Outcome::Requested });
113 }
114
115 pub fn local_feature(&mut self, feature: &'static str, detail: impl Into<String>) {
116 self.feature(feature, detail);
117 self.confirm(feature);
118 }
119
120 pub fn command(&mut self, command: &CallCommand) {
121 if let Some((feature, detail)) = describe(command) {
122 self.feature(feature, detail);
123 }
124 }
125
126 fn settle(&mut self, feature: &str, outcome: Outcome) {
127 if let Some(record) = self
128 .features
129 .iter_mut()
130 .rev()
131 .find(|record| record.feature == feature && record.outcome == Outcome::Requested)
132 {
133 record.outcome = outcome;
134 }
135 }
136
137 fn confirm(&mut self, feature: &str) {
138 let at_ms = self.elapsed_ms();
139 self.settle(feature, Outcome::Confirmed(at_ms));
140 }
141
142 fn remember_person(&mut self, mri: &str, display_name: &str) {
143 if !self.people.iter().any(|(known, _)| known == mri) {
144 self.people.push((mri.to_owned(), display_name.to_owned()));
145 }
146 }
147
148 pub fn observe(&mut self, update: &CallUpdate) {
149 let at_ms = self.elapsed_ms();
150 match update {
151 CallUpdate::State(state) => self.note_state(state, at_ms),
152 CallUpdate::OwnIdentity { mri } => self.me.mri.clone_from(mri),
153 CallUpdate::Muted(muted) => {
154 self.own_unmuted = !muted;
155 self.confirm("mute");
156 }
157 CallUpdate::Camera(_) => self.confirm("camera"),
158 CallUpdate::LocalShare(_) | CallUpdate::ShareSound(_) => self.confirm("share"),
159 CallUpdate::Hold(state) => {
160 self.states.push((at_ms, format!("hold {}", hold_name(*state))));
161 self.confirm("hold");
162 }
163 CallUpdate::Recording(_) => self.confirm("recording"),
164 CallUpdate::OwnHand(_) => self.confirm("hand"),
165 CallUpdate::Reaction { mri, .. } if *mri == self.me.mri => self.confirm("reaction"),
166 CallUpdate::Captions(CaptionState::Failed(message)) => {
167 self.settle("captions", Outcome::Failed(message.clone()));
168 }
169 CallUpdate::Captions(CaptionState::On) => self.confirm("captions"),
170 CallUpdate::Caption(_) => self.captions += 1,
171 CallUpdate::Organizer { outcome: Ok(_), .. } => self.confirm("people action"),
172 CallUpdate::Organizer { outcome: Err(message), .. } => {
173 self.settle("people action", Outcome::Failed(message.clone()));
174 }
175 CallUpdate::Roster(entries) => {
176 for entry in entries {
177 self.remember_person(&entry.mri, &entry.display_name);
178 }
179 self.others_unmuted = entries
180 .iter()
181 .any(|entry| !entry.in_lobby && !entry.muted && entry.mri != self.me.mri);
182 let present = entries.iter().filter(|entry| !entry.in_lobby).count();
183 self.peak_participants = self.peak_participants.max(present);
184 }
185 CallUpdate::Notice(text) => self.notices.push((at_ms, text.clone())),
186 CallUpdate::Health(health) => {
187 self.series.observe_health(health, at_ms);
188 if self.paths.last().map(|(_, path)| *path) != Some(health.path) {
189 self.paths.push((at_ms, health.path));
190 }
191 }
192 CallUpdate::Sample(sample) => {
193 self.series.observe_sample(sample, self.others_unmuted, self.own_unmuted);
194 }
195 CallUpdate::Diagnostics(diagnostics) => self.diagnostics = Some((**diagnostics).clone()),
196 _ => {}
197 }
198 }
199
200 fn note_state(&mut self, state: &CallState, at_ms: u128) {
201 let name = match state {
202 CallState::Idle => "idle",
203 CallState::Connecting => "connecting",
204 CallState::Connected { .. } => "connected",
205 CallState::Reconnecting { .. } => "reconnecting",
206 CallState::Ended { .. } => "ended",
207 };
208 if self.states.last().is_none_or(|(_, last)| last != name) {
209 self.states.push((at_ms, name.to_owned()));
210 }
211 match state {
212 CallState::Connected { .. } if self.connected_ms.is_none() => self.connected_ms = Some(at_ms),
213 CallState::Ended { reason } if self.ended.is_none() => {
214 self.ended = Some((at_ms, reason.clone()));
215 self.confirm("hangup");
216 }
217 _ => {}
218 }
219 }
220}
221
222fn hold_name(state: HoldState) -> &'static str {
223 match state {
224 HoldState::Active => "active",
225 HoldState::Local => "local",
226 HoldState::Remote => "remote",
227 }
228}
229
230fn describe(command: &CallCommand) -> Option<(&'static str, String)> {
231 use CallCommand::*;
232 Some(match command {
233 Mute(mute) => ("mute", format!("{mute:?}").to_lowercase()),
234 SetCamera(on) => ("camera", on_off(*on).to_owned()),
235 StartShare(source) => ("share", format!("start {}", format!("{:?}", source.kind).to_lowercase())),
236 StopShare => ("share", "stop".to_owned()),
237 SetShareSound(on) => ("share", format!("sound {}", on_off(*on))),
238 SetShareMotion(on) => ("share", format!("motion {}", on_off(*on))),
239 SetShareStandout(on) => ("share", format!("standout {}", on_off(*on))),
240 Hold(on) => ("hold", (if *on { "hold" } else { "resume" }).to_owned()),
241 Transfer { target, replaces } => {
242 let way = if replaces.is_some() { "consulted" } else { "blind" };
243 ("transfer", format!("{way} to {}", target.mri))
244 }
245 Invite { callees, group_thread } => {
246 let group = if group_thread.is_some() { ", into a group chat" } else { "" };
247 ("add people", format!("{} invited{group}", callees.len()))
248 }
249 StartRecording { kind, .. } => ("recording", format!("start {kind:?}")),
250 StopRecording { scope } => ("recording", format!("stop {scope:?}")),
251 ConsentToRecording => ("recording", "consent".to_owned()),
252 SetCaptions(on) => ("captions", on_off(*on).to_owned()),
253 SetCaptionLanguage(tag) => ("captions", format!("language {tag}")),
254 SetHand(on) => ("hand", on_off(*on).to_owned()),
255 LowerHand { mri } => ("hand", format!("lower {mri}")),
256 LowerAllHands => ("hand", "lower all".to_owned()),
257 SendReaction(reaction) => ("reaction", format!("{reaction:?}")),
258 Admit { mri } => ("people action", format!("admit {mri}")),
259 AdmitAll => ("people action", "admit all".to_owned()),
260 Deny { mri } => ("people action", format!("deny {mri}")),
261 MuteParticipant { mri } => ("people action", format!("mute {mri}")),
262 MuteAll => ("people action", "mute all".to_owned()),
263 Spotlight { mri } => ("people action", format!("spotlight {mri}")),
264 StopSpotlight { mri } => ("people action", format!("stop spotlight {mri}")),
265 RemoveParticipant { mri } => ("people action", format!("remove {mri}")),
266 SetLock(on) => ("people action", format!("lock {}", on_off(*on))),
267 SetRole { mri, role } => ("people action", format!("role {role:?} for {mri}")),
268 SetAttendeeModality { mri, modality, allowed } => {
269 ("people action", format!("{modality:?} {} for {mri}", if *allowed { "allowed" } else { "blocked" }))
270 }
271 SetAttendeeRestrictions { mic_off, camera_off } => {
272 ("people action", format!("attendee restrictions mic_off={mic_off} camera_off={camera_off}"))
273 }
274 EndMeeting => ("people action", "end meeting for all".to_owned()),
275 OpenWhiteboard { .. } => ("whiteboard", "open".to_owned()),
276 Hangup => ("hangup", "local".to_owned()),
277 _ => return None,
278 })
279}
280
281#[cfg(test)]
282mod tests {
283 use calling::call::VideoReport;
284 use calling::timeline::TimelineEntry;
285 use calling::{
286 Callee, HealthSample, MuteCommand, NetworkLevel, RosterEntry, SdpLine, SdpSummary, StatsSample, TransportDetails,
287 };
288
289 use super::*;
290
291 const PEER_MRI: &str = "8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
292
293 fn recorder() -> CallRecorder {
294 let me = OwnIdentity {
295 mri: "8:orgid:11111111-2222-3333-4444-555555555555".to_owned(),
296 display_name: "Daniel Daeschle".to_owned(),
297 email: "daniel@example.com".to_owned(),
298 };
299 CallRecorder::begin(CallKind::Direct, false, true, me, vec![(PEER_MRI.to_owned(), "Mara Lindqvist".to_owned())])
300 }
301
302 fn sample(packets: u64) -> CallUpdate {
303 CallUpdate::Sample(StatsSample {
304 audio_in_packets: packets,
305 audio_out_packets: packets,
306 video: VideoReport { inbound_width: 1280, inbound_height: 720, ..VideoReport::default() },
307 ..StatsSample::default()
308 })
309 }
310
311 fn diagnostics() -> CallUpdate {
312 let entry = |elapsed_ms, label: &str, detail: &str| TimelineEntry {
313 elapsed_ms,
314 label: label.to_owned(),
315 detail: detail.to_owned(),
316 };
317 CallUpdate::Diagnostics(Box::new(CallDiagnostics {
318 timeline: vec![
319 entry(10, "roster", "Mara Lindqvist 8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee from 203.0.113.9"),
320 entry(20, "raise hand failed", "HTTP 500 for https://emea.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2?token=secret"),
321 entry(30, "escalation", "new peer connection, new offer sent"),
322 ],
323 sdp: vec![SdpSummary {
324 at_ms: 5,
325 role: "local offer".to_owned(),
326 lines: vec![SdpLine {
327 kind: "audio".to_owned(),
328 mid: "0".to_owned(),
329 direction: "sendrecv".to_owned(),
330 codecs: vec!["opus".to_owned()],
331 payload_count: 1,
332 ssrc_count: 1,
333 rejected: false,
334 }],
335 }],
336 ..CallDiagnostics::default()
337 }))
338 }
339
340 fn finished_call() -> CallRecorder {
341 let mut recorder = recorder();
342 recorder.observe(&CallUpdate::State(CallState::Connecting));
343 recorder.observe(&CallUpdate::State(CallState::Connected { since: Instant::now() }));
344 recorder.observe(&CallUpdate::Roster(vec![RosterEntry {
345 mri: PEER_MRI.to_owned(),
346 display_name: "Mara Lindqvist".to_owned(),
347 ..RosterEntry::default()
348 }]));
349 for packets in [100, 200, 200, 300] {
350 recorder.observe(&sample(packets));
351 }
352 recorder.observe(&CallUpdate::Health(calling::CallHealth {
353 level: NetworkLevel::Poor,
354 cpu_limited: false,
355 sample: HealthSample { loss_percent: 6., ..HealthSample::default() },
356 transport: TransportDetails::default(),
357 path: MediaPath::Direct,
358 }));
359 recorder.observe(&CallUpdate::Notice("Mara Lindqvist declined the transfer".to_owned()));
360 recorder.command(&CallCommand::Mute(MuteCommand::Toggle));
361 recorder.observe(&CallUpdate::Muted(true));
362 recorder.command(&CallCommand::SetHand(true));
363 recorder.command(&CallCommand::Transfer {
364 target: Callee { mri: PEER_MRI.to_owned(), display_name: "Mara Lindqvist".to_owned() },
365 replaces: None,
366 });
367 recorder.command(&CallCommand::Hangup);
368 recorder.observe(&CallUpdate::State(CallState::Ended { reason: EndReason::LocalHangup }));
369 recorder.observe(&diagnostics());
370 recorder
371 }
372
373 #[test]
374 fn the_report_names_the_call_its_features_and_findings() {
375 let document = finished_call().document();
376 let json: serde_json::Value = serde_json::from_str(&document.json).expect("valid json");
377 assert_eq!(json["call"]["kind"], "1:1");
378 assert_eq!(json["call"]["direction"], "outgoing");
379 assert_eq!(json["call"]["end_reason"], "local hangup");
380 assert_eq!(json["media"]["path"], "direct");
381 assert_eq!(json["media"]["escalations"], 1);
382 assert_eq!(json["stats"]["samples"], 4);
383 assert_eq!(json["stats"]["audio_in_stalled_samples"], 1);
384 let results: Vec<(&str, &str)> = json["features"]
385 .as_array()
386 .unwrap()
387 .iter()
388 .map(|feature| (feature["feature"].as_str().unwrap(), feature["result"].as_str().unwrap()))
389 .collect();
390 assert_eq!(results, [("mute", "ok"), ("hand", "failed"), ("transfer", "no confirmation"), ("hangup", "ok")]);
391 assert_eq!(json["timeline"].as_array().unwrap().len(), 3);
392 assert_eq!(json["sdp"][0]["lines"][0]["codecs"][0], "opus");
393 assert!(document.markdown.starts_with("# Call test report"));
394 assert!(document.markdown.contains("## Findings"));
395 assert!(document.markdown.contains("Inbound audio stalled in 1 of 4 samples."));
396 assert!(document.stem.ends_with("-1to1"));
397 }
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
415 #[test]
416 fn each_transfer_answer_settles_the_transfer_it_belongs_to() {
417 let mut recorder = recorder();
418 let transfer = CallCommand::Transfer {
419 target: Callee { mri: PEER_MRI.to_owned(), display_name: "Mara Lindqvist".to_owned() },
420 replaces: None,
421 };
422 recorder.command(&transfer);
423 recorder.command(&transfer);
424 let entry = |elapsed_ms, label: &str, detail: &str| TimelineEntry { elapsed_ms, label: label.to_owned(), detail: detail.to_owned() };
425 recorder.observe(&CallUpdate::Diagnostics(Box::new(CallDiagnostics {
426 timeline: vec![
427 entry(10, "transfer accepted", "by the target"),
428 entry(20, "transfer failed", "code 487 subCode 0"),
429 entry(30, "transfer accepted", "by the target"),
430 entry(40, "transfer", "completed"),
431 ],
432 ..CallDiagnostics::default()
433 })));
434 let json: serde_json::Value = serde_json::from_str(&recorder.document().json).expect("valid json");
435 let transfers: Vec<(&str, &serde_json::Value)> = json["features"]
436 .as_array()
437 .unwrap()
438 .iter()
439 .filter(|feature| feature["feature"] == "transfer")
440 .map(|feature| (feature["result"].as_str().unwrap(), &feature["confirmed_at_ms"]))
441 .collect();
442 assert_eq!(transfers, [("failed", &serde_json::Value::Null), ("ok", &serde_json::json!(40))]);
443 }
444
445 #[test]
446 fn neither_file_holds_anything_personal() {
447 let document = finished_call().document();
448 for text in [&document.json, &document.markdown] {
449 for leaked in [
450 "Mara", "Lindqvist", "Daniel", "Daeschle", "aaaaaaaa", "11111111", "example.com", "203.0.113.9", "token=secret", "abc%40thread",
451 ] {
452 assert!(!text.contains(leaked), "{leaked} leaked into: {text}");
453 }
454 assert!(text.contains("person-1"));
455 }
456 }
457
458 #[test]
459 fn a_call_that_never_ended_still_gives_a_report() {
460 let mut recorder = recorder();
461 recorder.observe(&CallUpdate::State(CallState::Connecting));
462 let document = recorder.document();
463 let json: serde_json::Value = serde_json::from_str(&document.json).unwrap();
464 assert_eq!(json["call"]["end_reason"], "still running when saved");
465 assert!(document.markdown.contains("Never connected"));
466 }
467}