Skip to main content

spoolframe_protocol/
diagnostics.rs

1//! Diagnostics an app sends to its server for the admin to read (feature
2//! `spoolframe:diagnostics`): Settings › About › "Send diagnostics".
3//!
4//! A report is one request, and a request is one frame of at most
5//! [`MAX_FRAME`](crate::codec::MAX_FRAME) (1 MiB). So the log is capped
6//! below that, at [`MAX_LOG_BYTES`], with room left for the rest. A report
7//! over any limit is refused whole, saying which part and by how much:
8//! nothing is cut on the way, so what the admin reads is what the app
9//! sent. The app keeps the newest lines when it trims its own log.
10
11use std::fmt;
12
13use serde::{Deserialize, Serialize};
14
15/// The most bytes of `log` a report carries: 960 KiB.
16pub const MAX_LOG_BYTES: usize = 960 * 1024;
17
18/// The most bytes of `note` a report carries: 8 KiB.
19pub const MAX_NOTE_BYTES: usize = 8 * 1024;
20
21/// The most bytes of each of a report's names and versions.
22pub const MAX_FIELD_BYTES: usize = 256;
23
24/// What an app sends (`SendDiagnostics`): what it runs on, its playback
25/// log, and what the user wrote. Its `Debug` gives the log's length, not
26/// the log.
27#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
29pub struct DiagnosticsReport {
30    /// The device's model, as the platform names it (`iPhone16,2`,
31    /// `AppleTV14,1`).
32    pub device_model: String,
33    /// The operating system (`iOS`, `tvOS`, `Android`).
34    pub os_name: String,
35    pub os_version: String,
36    /// The app (`Spoolframe`).
37    pub app_name: String,
38    /// The app's version and build (`1.4.0 (212)`).
39    pub app_version: String,
40    /// The app's playback log, as it keeps it: free-form text.
41    pub log: String,
42    /// What the user wrote about it, if anything.
43    pub note: Option<String>,
44}
45
46/// A text's length, for `Debug` in place of the text.
47struct Bytes(usize);
48
49impl fmt::Debug for Bytes {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        write!(f, "<{} bytes>", self.0)
52    }
53}
54
55impl fmt::Debug for DiagnosticsReport {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.debug_struct("DiagnosticsReport")
58            .field("device_model", &self.device_model)
59            .field("os_name", &self.os_name)
60            .field("os_version", &self.os_version)
61            .field("app_name", &self.app_name)
62            .field("app_version", &self.app_version)
63            .field("log", &Bytes(self.log.len()))
64            .field("note", &self.note.as_ref().map(|n| Bytes(n.len())))
65            .finish()
66    }
67}
68
69impl DiagnosticsReport {
70    /// Why the report cannot be sent, if it cannot: a part over its limit,
71    /// named, with its size and the limit. What the server refuses with
72    /// `InvalidInput`, and the SDK before sending.
73    pub fn refusal(&self) -> Option<String> {
74        let parts = [
75            ("device_model", self.device_model.len(), MAX_FIELD_BYTES),
76            ("os_name", self.os_name.len(), MAX_FIELD_BYTES),
77            ("os_version", self.os_version.len(), MAX_FIELD_BYTES),
78            ("app_name", self.app_name.len(), MAX_FIELD_BYTES),
79            ("app_version", self.app_version.len(), MAX_FIELD_BYTES),
80            ("log", self.log.len(), MAX_LOG_BYTES),
81            (
82                "note",
83                self.note.as_ref().map_or(0, String::len),
84                MAX_NOTE_BYTES,
85            ),
86        ];
87        parts.into_iter().find(|&(_, len, max)| len > max).map(|(name, len, max)| {
88            format!(
89                "the diagnostics' {name} is {len} bytes; at most {max} are sent: keep the newest"
90            )
91        })
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    use crate::codec::{MAX_FRAME, encode};
99    use crate::rpc::{Operation, RpcRequest};
100    use crate::{Request, RequestEnvelope, SessionId};
101
102    fn report(log: String) -> DiagnosticsReport {
103        DiagnosticsReport {
104            device_model: "iPhone16,2".into(),
105            os_name: "iOS".into(),
106            os_version: "26.1".into(),
107            app_name: "Spoolframe".into(),
108            app_version: "1.4.0 (212)".into(),
109            log,
110            note: Some("It froze at the credits".into()),
111        }
112    }
113
114    #[test]
115    fn debug_gives_the_log_s_length_not_the_log() {
116        let text = format!("{:?}", report("secret line\n".repeat(3)));
117        assert!(!text.contains("secret line"), "{text}");
118        assert!(text.contains("<36 bytes>"), "{text}");
119        assert!(text.contains("iPhone16,2"), "{text}");
120    }
121
122    #[test]
123    fn a_log_at_the_cap_is_sent() {
124        assert_eq!(report("a".repeat(MAX_LOG_BYTES)).refusal(), None);
125    }
126
127    #[test]
128    fn a_log_over_the_cap_is_refused_naming_the_log() {
129        let refusal = report("a".repeat(MAX_LOG_BYTES + 1)).refusal().unwrap();
130        assert!(refusal.contains("log is 983041 bytes"), "{refusal}");
131    }
132
133    #[test]
134    fn a_long_note_or_name_is_refused() {
135        let mut long_note = report(String::new());
136        long_note.note = Some("n".repeat(MAX_NOTE_BYTES + 1));
137        assert!(long_note.refusal().unwrap().contains("note"));
138        let mut long_model = report(String::new());
139        long_model.device_model = "m".repeat(MAX_FIELD_BYTES + 1);
140        assert!(long_model.refusal().unwrap().contains("device_model"));
141    }
142
143    /// Every part at its limit still fits in one request frame, with its
144    /// session and operation: the limits are below the frame's.
145    #[test]
146    fn a_report_at_every_limit_fits_one_frame() {
147        let field = "f".repeat(MAX_FIELD_BYTES);
148        let full = DiagnosticsReport {
149            device_model: field.clone(),
150            os_name: field.clone(),
151            os_version: field.clone(),
152            app_name: field.clone(),
153            app_version: field,
154            log: "l".repeat(MAX_LOG_BYTES),
155            note: Some("n".repeat(MAX_NOTE_BYTES)),
156        };
157        assert_eq!(full.refusal(), None);
158        let wire = RpcRequest {
159            envelope: RequestEnvelope {
160                session: Some(SessionId("0".repeat(64))),
161                request: Request::SendDiagnostics { report: full },
162            },
163            operation: Some(Operation {
164                id: "0".repeat(64),
165                instance: "0".repeat(64),
166                expires_at_ms: u64::MAX,
167            }),
168            expected_revision: Some(u64::MAX),
169        };
170        let len = encode(&wire).unwrap().len();
171        assert!(len <= MAX_FRAME as usize, "{len} bytes");
172    }
173}