BlueGit

ict rusty-teams

Files

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

mod.rs

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