BlueGit

ict rusty-teams

Files

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

document.rs

8629da58 History
document.rs 15.7 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!("{}-{}", self.started_at.format(FILE_STAMP), kind_slug(self.kind)),
212 json: serde_json::to_string_pretty(&report).unwrap_or_else(|error| format!("{{\"error\":\"{error}\"}}")),
213 markdown: markdown::render(&report),
214 }
215 }
216
217 fn scrubber(&self) -> Scrubber {
218 let mut scrubber = Scrubber::new();
219 scrubber.register_self(&self.me.mri, &self.me.display_name, &self.me.email);
220 for (mri, name) in &self.people {
221 scrubber.register_person(mri, name);
222 }
223 scrubber
224 }
225
226 fn report(&self) -> Report {
227 let mut scrubber = self.scrubber();
228 let diagnostics = self.diagnostics.clone().unwrap_or_default();
229 let timeline: Vec<TimelineInfo> = diagnostics
230 .timeline
231 .iter()
232 .map(|entry| TimelineInfo {
233 engine_ms: entry.elapsed_ms,
234 label: scrubber.scrub(&entry.label),
235 detail: scrubber.scrub(&entry.detail),
236 })
237 .collect();
238 let features = self.feature_infos(&mut scrubber, &diagnostics.timeline);
239 let notices = self
240 .notices
241 .iter()
242 .map(|(at_ms, text)| NoticeInfo { at_ms: *at_ms, text: scrubber.scrub(text) })
243 .collect();
244 let total_ms = self.ended.as_ref().map(|(at_ms, _)| *at_ms);
245 let end_reason = self.ended.as_ref().map_or_else(|| "still running when saved".to_owned(), |(_, reason)| scrubber.scrub(&end_text(reason)));
246 let escalations = timeline.iter().filter(|entry| entry.label == ESCALATION_LABEL && entry.detail.contains("new offer sent")).count();
247 let escalation_failures = timeline.iter().filter(|entry| entry.label == "escalation failed").count();
248 let path = self.paths.last().map_or("unknown", |(_, path)| path_name(*path));
249 let stats = self.stats_info();
250 let sdp = diagnostics
251 .sdp
252 .iter()
253 .map(|summary| SdpInfo {
254 engine_ms: summary.at_ms,
255 role: summary.role.clone(),
256 lines: summary
257 .lines
258 .iter()
259 .map(|line| SdpLineInfo {
260 kind: line.kind.clone(),
261 mid: line.mid.clone(),
262 direction: line.direction.clone(),
263 codecs: line.codecs.clone(),
264 payloads: line.payload_count,
265 ssrcs: line.ssrc_count,
266 rejected: line.rejected,
267 })
268 .collect(),
269 })
270 .collect();
271 let mut report = Report {
272 schema: SCHEMA,
273 app: AppInfo {
274 version: env!("CARGO_PKG_VERSION"),
275 build: app_base::version::build_version(),
276 os: std::env::consts::OS,
277 arch: std::env::consts::ARCH,
278 demo: self.demo,
279 },
280 call: CallInfo {
281 kind: kind_label(self.kind),
282 direction: if self.incoming { "incoming" } else { "outgoing" },
283 started_utc: self.started_at.format(READABLE_STAMP).to_string(),
284 connect_ms: self.connected_ms,
285 total_ms,
286 connected_ms: self.connected_ms.zip(total_ms).map(|(connected, total)| total.saturating_sub(connected)),
287 end_reason,
288 engine_ice_connected_ms: diagnostics.ice_connected_ms,
289 engine_peer_connected_ms: diagnostics.peer_connected_ms,
290 },
291 media: MediaInfo {
292 path,
293 path_changes: self.paths.iter().map(|(at_ms, path)| PathChange { at_ms: *at_ms, path: path_name(*path) }).collect(),
294 escalations,
295 escalation_failures,
296 selected_pair: diagnostics.selected_pair.as_deref().map(|pair| scrubber.scrub(pair)),
297 tls_version: diagnostics.tls_version.clone(),
298 dtls_cipher: diagnostics.dtls_cipher.clone(),
299 srtp_cipher: diagnostics.srtp_cipher.clone(),
300 },
301 participants: ParticipantInfo {
302 peak_present: self.peak_participants,
303 known: placeholders(&mut scrubber, &self.people),
304 captions_received: self.captions,
305 },
306 problems: Vec::new(),
307 stats,
308 features,
309 notices,
310 states: self.states.iter().map(|(at_ms, state)| StateInfo { at_ms: *at_ms, state: state.clone() }).collect(),
311 sdp,
312 timeline,
313 };
314 let abnormal = matches!(self.ended, Some((_, EndReason::Failed(_) | EndReason::Dropped)));
315 report.problems = problems(&report, abnormal);
316 report
317 }
318
319 fn stats_info(&self) -> StatsInfo {
320 let series = &self.series;
321 let metrics: BTreeMap<&'static str, Range> = series
322 .values()
323 .iter()
324 .map(|(name, value)| (*name, Range { min: value.min, max: value.max, last: value.last }))
325 .collect();
326 let samples = series.values().get("audio_in_packets").map_or(0, |value| value.samples);
327 let health_names = [calling::NetworkLevel::Good, calling::NetworkLevel::Poor, calling::NetworkLevel::Bad];
328 let limitation_names = [calling::Limitation::None, calling::Limitation::Cpu, calling::Limitation::Bandwidth];
329 StatsInfo {
330 samples,
331 metrics,
332 audio_in_stalled_samples: series.stalled_audio_in,
333 audio_out_stalled_samples: series.stalled_audio_out,
334 health_samples: health_names.iter().map(|level| (level_name(*level), series.level_samples[*level as usize])).collect(),
335 health_level_changes: series.level_changes.iter().map(|(at_ms, level)| PathChange { at_ms: *at_ms, path: level }).collect(),
336 quality_limitation_samples: limitation_names
337 .iter()
338 .map(|limitation| (limitation_name(*limitation), series.limitation_samples[*limitation as usize]))
339 .collect(),
340 cpu_limited_samples: series.cpu_limited_samples,
341 }
342 }
343
344 fn feature_infos(&self, scrubber: &mut Scrubber, timeline: &[calling::timeline::TimelineEntry]) -> Vec<FeatureInfo> {
345 let mut records: Vec<FeatureRecord> = self.features.clone();
346 for entry in timeline {
347 if entry.label == TRANSFER_LABEL
348 && let Some(record) = oldest_pending(&mut records, TRANSFER_LABEL)
349 {
350 record.outcome = Outcome::Confirmed(entry.elapsed_ms);
351 }
352 let Some((_, feature)) = FEATURE_FAILURE_LABELS.iter().find(|(label, _)| entry.label == *label) else {
353 continue;
354 };
355 if let Some(record) = oldest_pending(&mut records, feature) {
356 record.outcome = Outcome::Failed(entry.detail.clone());
357 }
358 }
359 records
360 .into_iter()
361 .map(|record| {
362 let (result, confirmed_at_ms, error) = match record.outcome {
363 Outcome::Requested => ("no confirmation", None, None),
364 Outcome::Confirmed(at_ms) => ("ok", Some(at_ms), None),
365 Outcome::Failed(message) => ("failed", None, Some(scrubber.scrub(&message))),
366 };
367 FeatureInfo {
368 at_ms: record.at_ms,
369 feature: record.feature,
370 detail: scrubber.scrub(&record.detail),
371 result,
372 confirmed_at_ms,
373 error,
374 }
375 })
376 .collect()
377 }
378}
379
380fn oldest_pending<'a>(records: &'a mut [FeatureRecord], feature: &str) -> Option<&'a mut FeatureRecord> {
381 records.iter_mut().find(|record| record.feature == feature && record.outcome == Outcome::Requested)
382}
383
384fn placeholders(scrubber: &mut Scrubber, people: &[(String, String)]) -> Vec<String> {
385 let mut known = vec![super::scrub::SELF_PLACEHOLDER.to_owned()];
386 for (mri, _) in people {
387 let placeholder = scrubber.person(mri);
388 if !known.contains(&placeholder) {
389 known.push(placeholder);
390 }
391 }
392 known
393}
394
395fn problems(report: &Report, abnormal_end: bool) -> Vec<String> {
396 let mut found = Vec::new();
397 if report.call.connect_ms.is_none() {
398 found.push(format!("Never connected ({}).", report.call.end_reason));
399 } else if abnormal_end {
400 found.push(format!("Ended abnormally: {}.", report.call.end_reason));
401 }
402 let metrics = &report.stats.metrics;
403 let samples = report.stats.samples;
404 if samples > 0 && metrics.get("audio_in_packets").is_some_and(|range| range.max == 0.) {
405 found.push("No inbound audio packets arrived.".to_owned());
406 }
407 if samples > 0 && metrics.get("audio_out_packets").is_some_and(|range| range.max == 0.) {
408 found.push("No outbound audio packets were sent.".to_owned());
409 }
410 if samples >= MIN_SAMPLES_FOR_STALLS && report.stats.audio_in_stalled_samples > 0 {
411 found.push(format!("Inbound audio stalled in {} of {samples} samples.", report.stats.audio_in_stalled_samples));
412 }
413 if samples >= MIN_SAMPLES_FOR_STALLS && report.stats.audio_out_stalled_samples > 0 {
414 found.push(format!("Outbound audio stalled in {} of {samples} samples.", report.stats.audio_out_stalled_samples));
415 }
416 let degraded: u32 = ["poor", "bad"].iter().filter_map(|name| report.stats.health_samples.get(*name)).sum();
417 if degraded > 0 {
418 found.push(format!("Network health was poor or bad in {degraded} samples."));
419 }
420 if report.media.escalation_failures > 0 {
421 found.push(format!("{} escalation(s) failed.", report.media.escalation_failures));
422 }
423 let failures: Vec<&TimelineInfo> =
424 report.timeline.iter().filter(|entry| FAILURE_WORDS.iter().any(|word| entry.label.contains(word))).collect();
425 if !failures.is_empty() {
426 let labels: Vec<&str> = failures.iter().take(5).map(|entry| entry.label.as_str()).collect();
427 found.push(format!("{} failure entries in the timeline: {}.", failures.len(), labels.join(", ")));
428 }
429 for feature in report.features.iter().filter(|feature| feature.result == "failed") {
430 found.push(format!("Feature {} ({}) failed at {} ms.", feature.feature, feature.detail, feature.at_ms));
431 }
432 found
433}