BlueGit

ict rusty-teams

Files

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

mod.rs

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