Skip to main content

bitwarden_ipc/
timeline.rs

1//! Records IPC activity on the browser performance timeline, so it shows up as custom tracks in
2//! the Chrome DevTools Performance panel. A no-op outside of WASM.
3//!
4//! ```text
5//! IPC
6//! ├─ Sent        [msg]   [msg]          one entry per message, at least 1 ms wide
7//! ├─ Received       [msg]     [msg]
8//! ├─ Requests    [── MyRequest ──]      request sent until response received
9//! ├─ Handlers         [MyRequest]       remote handler run
10//! └─ Handshakes  [Noise handshake]
11//! ```
12
13/// DevTools track an entry is drawn on, all grouped under "IPC".
14#[derive(Clone, Copy)]
15pub(crate) enum Track {
16    Sent,
17    Received,
18    Requests,
19    Handlers,
20    Handshakes,
21}
22
23/// How long an entry is drawn for.
24#[derive(Clone, Copy)]
25pub(crate) enum Duration {
26    /// From span creation until drop.
27    Actual,
28    /// From span creation until drop, but at least 1 ms so near-instant
29    /// messages stay visible.
30    AtLeastMessage,
31}
32
33/// Name and key/value rows shown in the DevTools entry summary, e.g. `RpcRequestMessage` with
34/// `[("Destination", "DesktopMain")]`.
35#[cfg_attr(not(all(feature = "wasm", target_arch = "wasm32")), allow(dead_code))]
36pub(crate) struct Entry {
37    pub(crate) name: String,
38    pub(crate) properties: Vec<(&'static str, String)>,
39}
40
41#[cfg(all(feature = "wasm", target_arch = "wasm32"))]
42pub(crate) use wasm::span;
43
44/// Bindings to the `performance` API
45#[cfg(all(feature = "wasm", target_arch = "wasm32"))]
46mod wasm {
47    use wasm_bindgen::prelude::*;
48
49    use super::{Duration, Entry, Track};
50
51    // Chrome DevTools extensibility API: entries with this metadata get a custom track.
52    const DATA_TYPE: &str = "track-entry";
53    const TRACK_GROUP: &str = "IPC";
54
55    /// Minimum drawn duration of a single sent or received message.
56    const MIN_MESSAGE_DURATION_MS: f64 = 1.0;
57
58    #[wasm_bindgen]
59    extern "C" {
60        #[wasm_bindgen(catch, js_namespace = performance, js_name = now)]
61        fn performance_now() -> Result<f64, JsValue>;
62
63        #[wasm_bindgen(catch, js_namespace = performance, js_name = measure)]
64        fn performance_measure(name: &str, options: &JsValue) -> Result<JsValue, JsValue>;
65    }
66
67    /// Records an entry on the timeline when dropped, so early returns and cancelled futures
68    /// are recorded too.
69    pub(crate) struct Span {
70        started: Option<(Track, Duration, Entry, f64)>,
71    }
72
73    /// Starts a span. `entry` is only evaluated where the timeline is available.
74    pub(crate) fn span(track: Track, duration: Duration, entry: impl FnOnce() -> Entry) -> Span {
75        Span {
76            started: performance_now()
77                .ok()
78                .map(|start| (track, duration, entry(), start)),
79        }
80    }
81
82    impl Drop for Span {
83        fn drop(&mut self) {
84            let Some((track, duration, entry, start)) = self.started.take() else {
85                return;
86            };
87            let Ok(now) = performance_now() else {
88                return;
89            };
90
91            let end = match duration {
92                Duration::Actual => now,
93                Duration::AtLeastMessage => now.max(start + MIN_MESSAGE_DURATION_MS),
94            };
95            measure(track, &entry, start, end);
96        }
97    }
98
99    /// Records `entry` from `start` to `end`, e.g. `performance.measure("RpcRequestMessage", {
100    /// start, end, detail: { devtools: { dataType: "track-entry", trackGroup: "IPC", track:
101    /// "Sent", properties: [["Destination", "DesktopMain"]] } } })`.
102    fn measure(track: Track, entry: &Entry, start: f64, end: f64) {
103        let properties = js_sys::Array::new();
104        for (key, value) in &entry.properties {
105            properties.push(&js_sys::Array::of2(&(*key).into(), &value.into()));
106        }
107
108        let devtools = object(&[
109            ("dataType", DATA_TYPE.into()),
110            ("trackGroup", TRACK_GROUP.into()),
111            ("track", track_name(track).into()),
112            ("properties", properties.into()),
113        ]);
114        let detail = object(&[("devtools", devtools)]);
115        let options = object(&[
116            ("start", start.into()),
117            ("end", end.into()),
118            ("detail", detail),
119        ]);
120
121        // Best effort: a rejected measure must not fail the IPC operation.
122        let _ = performance_measure(&entry.name, &options);
123    }
124
125    fn track_name(track: Track) -> &'static str {
126        match track {
127            Track::Sent => "Sent",
128            Track::Received => "Received",
129            Track::Requests => "Requests",
130            Track::Handlers => "Handlers",
131            Track::Handshakes => "Handshakes",
132        }
133    }
134
135    fn object(fields: &[(&str, JsValue)]) -> JsValue {
136        let object = js_sys::Object::new();
137        for (key, value) in fields {
138            let _ = js_sys::Reflect::set(&object, &JsValue::from_str(key), value);
139        }
140        object.into()
141    }
142}
143
144/// No-op span where the timeline is unavailable.
145#[cfg(not(all(feature = "wasm", target_arch = "wasm32")))]
146pub(crate) struct Span;
147
148#[cfg(not(all(feature = "wasm", target_arch = "wasm32")))]
149pub(crate) fn span(_track: Track, _duration: Duration, _entry: impl FnOnce() -> Entry) -> Span {
150    Span
151}