BlueGit

ict rusty-teams

Files

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

mod.rs

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