BlueGit

ict rusty-teams

Files

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

document.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
document.rs 17.6 KiB Download Raw
1use std::collections::BTreeMap;
2
3use calling::{EndKind, EndReason, MediaPath};
4use serde::Serialize;
5
6use super::markdown;
7use super::scrub::Scrubber;
8use super::series::{level_name, limitation_name};
9use super::{CallRecorder, FeatureRecord, Outcome};
10use crate::model::CallKind;
11
12const SCHEMA: u32 = 1;
13const FILE_STAMP: &str = "%Y%m%dT%H%M%SZ";
14const READABLE_STAMP: &str = "%Y-%m-%d %H:%M:%S";
15const MIN_SAMPLES_FOR_STALLS: u32 = 3;
16const ESCALATION_LABEL: &str = "escalation";
17const TRANSFER_LABEL: &str = "transfer";
18const FAILURE_WORDS: [&str; 3] = ["failed", "rejected", "not understood"];
19const FEATURE_FAILURE_LABELS: [(&str, &str); 11] = [
20 ("raise hand failed", "hand"),
21 ("lower hand failed", "hand"),
22 ("lower all hands failed", "hand"),
23 ("hold failed", "hold"),
24 ("transfer failed", "transfer"),
25 ("reaction failed", "reaction"),
26 ("camera offer failed", "camera"),
27 ("recording consent failed", "recording"),
28 ("caption language failed", "captions"),
29 ("caption start failed", "captions"),
30 ("end meeting failed", "people action"),
31];
32
33pub struct Document {
34 pub stem: String,
35 pub json: String,
36 pub markdown: String,
37}
38
39#[derive(Debug, Serialize)]
40pub struct Report {
41 pub schema: u32,
42 pub app: AppInfo,
43 pub call: CallInfo,
44 pub media: MediaInfo,
45 pub participants: ParticipantInfo,
46 pub problems: Vec<String>,
47 pub stats: StatsInfo,
48 pub features: Vec<FeatureInfo>,
49 pub notices: Vec<NoticeInfo>,
50 pub states: Vec<StateInfo>,
51 pub sdp: Vec<SdpInfo>,
52 pub timeline: Vec<TimelineInfo>,
53}
54
55#[derive(Debug, Serialize)]
56pub struct AppInfo {
57 pub version: &'static str,
58 pub build: &'static str,
59 pub os: &'static str,
60 pub arch: &'static str,
61 pub demo: bool,
62}
63
64#[derive(Debug, Serialize)]
65pub struct CallInfo {
66 pub kind: &'static str,
67 pub direction: &'static str,
68 pub started_utc: String,
69 pub connect_ms: Option<u128>,
70 pub total_ms: Option<u128>,
71 pub connected_ms: Option<u128>,
72 pub end_reason: String,
73 pub engine_ice_connected_ms: Option<u128>,
74 pub engine_peer_connected_ms: Option<u128>,
75}
76
77#[derive(Debug, Serialize)]
78pub struct MediaInfo {
79 pub path: &'static str,
80 pub path_changes: Vec<PathChange>,
81 pub escalations: usize,
82 pub escalation_failures: usize,
83 pub selected_pair: Option<String>,
84 pub tls_version: String,
85 pub dtls_cipher: String,
86 pub srtp_cipher: String,
87}
88
89#[derive(Debug, Serialize)]
90pub struct PathChange {
91 pub at_ms: u128,
92 pub path: &'static str,
93}
94
95#[derive(Debug, Serialize)]
96pub struct ParticipantInfo {
97 pub peak_present: usize,
98 pub known: Vec<String>,
99 pub captions_received: u32,
100}
101
102#[derive(Debug, Serialize)]
103pub struct StatsInfo {
104 pub samples: u32,
105 pub metrics: BTreeMap<&'static str, Range>,
106 pub audio_in_stalled_samples: u32,
107 pub audio_out_stalled_samples: u32,
108 pub health_samples: BTreeMap<&'static str, u32>,
109 pub health_level_changes: Vec<PathChange>,
110 pub quality_limitation_samples: BTreeMap<&'static str, u32>,
111 pub cpu_limited_samples: u32,
112}
113
114#[derive(Debug, Serialize)]
115pub struct Range {
116 pub min: f64,
117 pub max: f64,
118 pub last: f64,
119}
120
121#[derive(Debug, Serialize)]
122pub struct FeatureInfo {
123 pub at_ms: u128,
124 pub feature: &'static str,
125 pub detail: String,
126 pub result: &'static str,
127 pub confirmed_at_ms: Option<u128>,
128 pub error: Option<String>,
129}
130
131#[derive(Debug, Serialize)]
132pub struct NoticeInfo {
133 pub at_ms: u128,
134 pub text: String,
135}
136
137#[derive(Debug, Serialize)]
138pub struct StateInfo {
139 pub at_ms: u128,
140 pub state: String,
141}
142
143#[derive(Debug, Serialize)]
144pub struct SdpInfo {
145 pub engine_ms: u128,
146 pub role: String,
147 pub lines: Vec<SdpLineInfo>,
148}
149
150#[derive(Debug, Serialize)]
151pub struct SdpLineInfo {
152 pub kind: String,
153 pub mid: String,
154 pub direction: String,
155 pub codecs: Vec<String>,
156 pub payloads: usize,
157 pub ssrcs: usize,
158 pub rejected: bool,
159}
160
161#[derive(Debug, Serialize)]
162pub struct TimelineInfo {
163 pub engine_ms: u128,
164 pub label: String,
165 pub detail: String,
166}
167
168fn kind_label(kind: CallKind) -> &'static str {
169 match kind {
170 CallKind::Test => "echo",
171 CallKind::Direct => "1:1",
172 CallKind::Group => "group",
173 CallKind::Meeting => "meeting",
174 }
175}
176
177fn kind_slug(kind: CallKind) -> &'static str {
178 match kind {
179 CallKind::Test => "echo",
180 CallKind::Direct => "1to1",
181 CallKind::Group => "group",
182 CallKind::Meeting => "meeting",
183 }
184}
185
186fn path_name(path: MediaPath) -> &'static str {
187 match path {
188 MediaPath::Pending => "pending",
189 MediaPath::Direct => "direct",
190 MediaPath::Mixer => "mixer",
191 }
192}
193
194fn end_text(reason: &EndReason) -> String {
195 match reason {
196 EndReason::LocalHangup => "local hangup".to_owned(),
197 EndReason::Cancelled => "cancelled before the call connected".to_owned(),
198 EndReason::Dropped => "connection dropped".to_owned(),
199 EndReason::Failed(message) => format!("failed: {message}"),
200 EndReason::Remote(EndKind::Declined) => "remote declined".to_owned(),
201 EndReason::Remote(EndKind::NoAnswer) => "no answer".to_owned(),
202 EndReason::Remote(EndKind::Unavailable) => "remote unavailable".to_owned(),
203 EndReason::Remote(kind) => format!("remote ended ({kind:?})"),
204 }
205}
206
207impl CallRecorder {
208 pub fn document(&self) -> Document {
209 let report = self.report();
210 Document {
211 stem: format!(
212 "{}-{}",
213 self.started_at.format(FILE_STAMP),
214 kind_slug(self.kind)
215 ),
216 json: serde_json::to_string_pretty(&report)
217 .unwrap_or_else(|error| format!("{{\"error\":\"{error}\"}}")),
218 markdown: markdown::render(&report),
219 }
220 }
221
222 fn scrubber(&self) -> Scrubber {
223 let mut scrubber = Scrubber::new();
224 scrubber.register_self(&self.me.mri, &self.me.display_name, &self.me.email);
225 for (mri, name) in &self.people {
226 scrubber.register_person(mri, name);
227 }
228 scrubber
229 }
230
231 fn report(&self) -> Report {
232 let mut scrubber = self.scrubber();
233 let diagnostics = self.diagnostics.clone().unwrap_or_default();
234 let timeline: Vec<TimelineInfo> = diagnostics
235 .timeline
236 .iter()
237 .map(|entry| TimelineInfo {
238 engine_ms: entry.elapsed_ms,
239 label: scrubber.scrub(&entry.label),
240 detail: scrubber.scrub(&entry.detail),
241 })
242 .collect();
243 let features = self.feature_infos(&mut scrubber, &diagnostics.timeline);
244 let notices = self
245 .notices
246 .iter()
247 .map(|(at_ms, text)| NoticeInfo {
248 at_ms: *at_ms,
249 text: scrubber.scrub(text),
250 })
251 .collect();
252 let total_ms = self.ended.as_ref().map(|(at_ms, _)| *at_ms);
253 let end_reason = self.ended.as_ref().map_or_else(
254 || "still running when saved".to_owned(),
255 |(_, reason)| scrubber.scrub(&end_text(reason)),
256 );
257 let escalations = timeline
258 .iter()
259 .filter(|entry| {
260 entry.label == ESCALATION_LABEL && entry.detail.contains("new offer sent")
261 })
262 .count();
263 let escalation_failures = timeline
264 .iter()
265 .filter(|entry| entry.label == "escalation failed")
266 .count();
267 let path = self
268 .paths
269 .last()
270 .map_or("unknown", |(_, path)| path_name(*path));
271 let stats = self.stats_info();
272 let sdp = diagnostics
273 .sdp
274 .iter()
275 .map(|summary| SdpInfo {
276 engine_ms: summary.at_ms,
277 role: summary.role.clone(),
278 lines: summary
279 .lines
280 .iter()
281 .map(|line| SdpLineInfo {
282 kind: line.kind.clone(),
283 mid: line.mid.clone(),
284 direction: line.direction.clone(),
285 codecs: line.codecs.clone(),
286 payloads: line.payload_count,
287 ssrcs: line.ssrc_count,
288 rejected: line.rejected,
289 })
290 .collect(),
291 })
292 .collect();
293 let mut report = Report {
294 schema: SCHEMA,
295 app: AppInfo {
296 version: env!("CARGO_PKG_VERSION"),
297 build: app_base::version::build_version(),
298 os: std::env::consts::OS,
299 arch: std::env::consts::ARCH,
300 demo: self.demo,
301 },
302 call: CallInfo {
303 kind: kind_label(self.kind),
304 direction: if self.incoming {
305 "incoming"
306 } else {
307 "outgoing"
308 },
309 started_utc: self.started_at.format(READABLE_STAMP).to_string(),
310 connect_ms: self.connected_ms,
311 total_ms,
312 connected_ms: self
313 .connected_ms
314 .zip(total_ms)
315 .map(|(connected, total)| total.saturating_sub(connected)),
316 end_reason,
317 engine_ice_connected_ms: diagnostics.ice_connected_ms,
318 engine_peer_connected_ms: diagnostics.peer_connected_ms,
319 },
320 media: MediaInfo {
321 path,
322 path_changes: self
323 .paths
324 .iter()
325 .map(|(at_ms, path)| PathChange {
326 at_ms: *at_ms,
327 path: path_name(*path),
328 })
329 .collect(),
330 escalations,
331 escalation_failures,
332 selected_pair: diagnostics
333 .selected_pair
334 .as_deref()
335 .map(|pair| scrubber.scrub(pair)),
336 tls_version: diagnostics.tls_version.clone(),
337 dtls_cipher: diagnostics.dtls_cipher.clone(),
338 srtp_cipher: diagnostics.srtp_cipher.clone(),
339 },
340 participants: ParticipantInfo {
341 peak_present: self.peak_participants,
342 known: placeholders(&mut scrubber, &self.people),
343 captions_received: self.captions,
344 },
345 problems: Vec::new(),
346 stats,
347 features,
348 notices,
349 states: self
350 .states
351 .iter()
352 .map(|(at_ms, state)| StateInfo {
353 at_ms: *at_ms,
354 state: state.clone(),
355 })
356 .collect(),
357 sdp,
358 timeline,
359 };
360 let abnormal = matches!(
361 self.ended,
362 Some((_, EndReason::Failed(_) | EndReason::Dropped))
363 );
364 report.problems = problems(&report, abnormal);
365 report
366 }
367
368 fn stats_info(&self) -> StatsInfo {
369 let series = &self.series;
370 let metrics: BTreeMap<&'static str, Range> = series
371 .values()
372 .iter()
373 .map(|(name, value)| {
374 (
375 *name,
376 Range {
377 min: value.min,
378 max: value.max,
379 last: value.last,
380 },
381 )
382 })
383 .collect();
384 let samples = series
385 .values()
386 .get("audio_in_packets")
387 .map_or(0, |value| value.samples);
388 let health_names = [
389 calling::NetworkLevel::Good,
390 calling::NetworkLevel::Poor,
391 calling::NetworkLevel::Bad,
392 ];
393 let limitation_names = [
394 calling::Limitation::None,
395 calling::Limitation::Cpu,
396 calling::Limitation::Bandwidth,
397 ];
398 StatsInfo {
399 samples,
400 metrics,
401 audio_in_stalled_samples: series.stalled_audio_in,
402 audio_out_stalled_samples: series.stalled_audio_out,
403 health_samples: health_names
404 .iter()
405 .map(|level| (level_name(*level), series.level_samples[*level as usize]))
406 .collect(),
407 health_level_changes: series
408 .level_changes
409 .iter()
410 .map(|(at_ms, level)| PathChange {
411 at_ms: *at_ms,
412 path: level,
413 })
414 .collect(),
415 quality_limitation_samples: limitation_names
416 .iter()
417 .map(|limitation| {
418 (
419 limitation_name(*limitation),
420 series.limitation_samples[*limitation as usize],
421 )
422 })
423 .collect(),
424 cpu_limited_samples: series.cpu_limited_samples,
425 }
426 }
427
428 fn feature_infos(
429 &self,
430 scrubber: &mut Scrubber,
431 timeline: &[calling::timeline::TimelineEntry],
432 ) -> Vec<FeatureInfo> {
433 let mut records: Vec<FeatureRecord> = self.features.clone();
434 for entry in timeline {
435 if entry.label == TRANSFER_LABEL
436 && let Some(record) = oldest_pending(&mut records, TRANSFER_LABEL)
437 {
438 record.outcome = Outcome::Confirmed(entry.elapsed_ms);
439 }
440 let Some((_, feature)) = FEATURE_FAILURE_LABELS
441 .iter()
442 .find(|(label, _)| entry.label == *label)
443 else {
444 continue;
445 };
446 if let Some(record) = oldest_pending(&mut records, feature) {
447 record.outcome = Outcome::Failed(entry.detail.clone());
448 }
449 }
450 records
451 .into_iter()
452 .map(|record| {
453 let (result, confirmed_at_ms, error) = match record.outcome {
454 Outcome::Requested => ("no confirmation", None, None),
455 Outcome::Confirmed(at_ms) => ("ok", Some(at_ms), None),
456 Outcome::Failed(message) => ("failed", None, Some(scrubber.scrub(&message))),
457 };
458 FeatureInfo {
459 at_ms: record.at_ms,
460 feature: record.feature,
461 detail: scrubber.scrub(&record.detail),
462 result,
463 confirmed_at_ms,
464 error,
465 }
466 })
467 .collect()
468 }
469}
470
471fn oldest_pending<'a>(
472 records: &'a mut [FeatureRecord],
473 feature: &str,
474) -> Option<&'a mut FeatureRecord> {
475 records
476 .iter_mut()
477 .find(|record| record.feature == feature && record.outcome == Outcome::Requested)
478}
479
480fn placeholders(scrubber: &mut Scrubber, people: &[(String, String)]) -> Vec<String> {
481 let mut known = vec![super::scrub::SELF_PLACEHOLDER.to_owned()];
482 for (mri, _) in people {
483 let placeholder = scrubber.person(mri);
484 if !known.contains(&placeholder) {
485 known.push(placeholder);
486 }
487 }
488 known
489}
490
491fn problems(report: &Report, abnormal_end: bool) -> Vec<String> {
492 let mut found = Vec::new();
493 if report.call.connect_ms.is_none() {
494 found.push(format!("Never connected ({}).", report.call.end_reason));
495 } else if abnormal_end {
496 found.push(format!("Ended abnormally: {}.", report.call.end_reason));
497 }
498 let metrics = &report.stats.metrics;
499 let samples = report.stats.samples;
500 if samples > 0
501 && metrics
502 .get("audio_in_packets")
503 .is_some_and(|range| range.max == 0.)
504 {
505 found.push("No inbound audio packets arrived.".to_owned());
506 }
507 if samples > 0
508 && metrics
509 .get("audio_out_packets")
510 .is_some_and(|range| range.max == 0.)
511 {
512 found.push("No outbound audio packets were sent.".to_owned());
513 }
514 if samples >= MIN_SAMPLES_FOR_STALLS && report.stats.audio_in_stalled_samples > 0 {
515 found.push(format!(
516 "Inbound audio stalled in {} of {samples} samples.",
517 report.stats.audio_in_stalled_samples
518 ));
519 }
520 if samples >= MIN_SAMPLES_FOR_STALLS && report.stats.audio_out_stalled_samples > 0 {
521 found.push(format!(
522 "Outbound audio stalled in {} of {samples} samples.",
523 report.stats.audio_out_stalled_samples
524 ));
525 }
526 let degraded: u32 = ["poor", "bad"]
527 .iter()
528 .filter_map(|name| report.stats.health_samples.get(*name))
529 .sum();
530 if degraded > 0 {
531 found.push(format!(
532 "Network health was poor or bad in {degraded} samples."
533 ));
534 }
535 if report.media.escalation_failures > 0 {
536 found.push(format!(
537 "{} escalation(s) failed.",
538 report.media.escalation_failures
539 ));
540 }
541 let failures: Vec<&TimelineInfo> = report
542 .timeline
543 .iter()
544 .filter(|entry| FAILURE_WORDS.iter().any(|word| entry.label.contains(word)))
545 .collect();
546 if !failures.is_empty() {
547 let labels: Vec<&str> = failures
548 .iter()
549 .take(5)
550 .map(|entry| entry.label.as_str())
551 .collect();
552 found.push(format!(
553 "{} failure entries in the timeline: {}.",
554 failures.len(),
555 labels.join(", ")
556 ));
557 }
558 for feature in report
559 .features
560 .iter()
561 .filter(|feature| feature.result == "failed")
562 {
563 found.push(format!(
564 "Feature {} ({}) failed at {} ms.",
565 feature.feature, feature.detail, feature.at_ms
566 ));
567 }
568 found
569}