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