profile_traits/
time.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use base::cross_process_instant::CrossProcessInstant;
6use ipc_channel::ipc::IpcSender;
7use log::warn;
8use malloc_size_of_derive::MallocSizeOf;
9use serde::{Deserialize, Serialize};
10use time::Duration;
11
12#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
13pub struct TimerMetadata {
14    pub url: String,
15    pub iframe: TimerMetadataFrameType,
16    pub incremental: TimerMetadataReflowType,
17}
18
19#[derive(Clone, Debug, Deserialize, Serialize)]
20pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
21
22impl ProfilerChan {
23    pub fn send(&self, msg: ProfilerMsg) {
24        if let Err(e) = self.0.send(msg) {
25            warn!("Error communicating with the time profiler thread: {}", e);
26        }
27    }
28}
29
30#[derive(Clone, Debug, Deserialize, Serialize)]
31pub enum ProfilerData {
32    NoRecords,
33    Record(Vec<Duration>),
34}
35
36#[derive(Clone, Debug, Deserialize, Serialize)]
37pub enum ProfilerMsg {
38    /// Normal message used for reporting time
39    Time(
40        (ProfilerCategory, Option<TimerMetadata>),
41        (CrossProcessInstant, CrossProcessInstant),
42    ),
43    /// Message used to get time spend entries for a particular ProfilerBuckets (in nanoseconds)
44    Get(
45        (ProfilerCategory, Option<TimerMetadata>),
46        IpcSender<ProfilerData>,
47    ),
48    /// Message used to force print the profiling metrics
49    Print,
50
51    /// Report a layout query that could not be processed immediately for a particular URL.
52    BlockedLayoutQuery(String),
53
54    /// Tells the profiler to shut down.
55    Exit(IpcSender<()>),
56}
57
58/// Usage sites of variants marked “Rust tracing only” are not visible to rust-analyzer.
59#[repr(u32)]
60#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
61pub enum ProfilerCategory {
62    /// The compositor is rasterising or presenting.
63    ///
64    /// Not associated with a specific URL.
65    Compositing = 0x00,
66
67    /// The script thread is doing layout work.
68    Layout = 0x10,
69
70    ImageSaving = 0x51,
71    ScriptAttachLayout = 0x60,
72    ScriptConstellationMsg = 0x61,
73    ScriptDevtoolsMsg = 0x62,
74    ScriptDocumentEvent = 0x63,
75
76    /// Rust tracing only: the script thread is executing a script.
77    /// This may include time doing layout or parse work initiated by the script.
78    ScriptEvaluate = 0x65,
79
80    ScriptEvent = 0x66,
81    ScriptFileRead = 0x67,
82    ScriptFontLoading = 0x68,
83    ScriptImageCacheMsg = 0x69,
84    ScriptInputEvent = 0x6a,
85    ScriptNetworkEvent = 0x6b,
86
87    /// The script thread is parsing HTML, rather than doing other work like evaluating scripts or doing layout.
88    ScriptParseHTML = 0x6c,
89
90    ScriptPlannedNavigation = 0x6d,
91    ScriptResize = 0x6e,
92    ScriptRendering = 0x6f,
93    ScriptSetScrollState = 0x70,
94    ScriptSetViewport = 0x71,
95    ScriptTimerEvent = 0x72,
96    ScriptStylesheetLoad = 0x73,
97    ScriptUpdateReplacedElement = 0x74,
98    ScriptWebSocketEvent = 0x75,
99    ScriptWorkerEvent = 0x76,
100    ScriptServiceWorkerEvent = 0x77,
101
102    /// The script thread is parsing XML, rather than doing other work like evaluating scripts or doing layout.
103    ScriptParseXML = 0x78,
104
105    ScriptEnterFullscreen = 0x79,
106    ScriptExitFullscreen = 0x7a,
107    ScriptWorkletEvent = 0x7b,
108    ScriptGeolocationEvent = 0x7c,
109    ScriptPerformanceEvent = 0x7d,
110    ScriptHistoryEvent = 0x7e,
111    ScriptPortMessage = 0x7f,
112    ScriptWebGPUMsg = 0x80,
113
114    ScriptDatabaseAccessEvent = 0x81,
115
116    /// Web performance metrics.
117    TimeToFirstPaint = 0x90,
118    TimeToFirstContentfulPaint = 0x91,
119    TimeToInteractive = 0x92,
120
121    IpcReceiver = 0x93,
122    IpcBytesReceiver = 0x94,
123}
124
125impl ProfilerCategory {
126    pub const fn variant_name(&self) -> &'static str {
127        match self {
128            ProfilerCategory::Compositing => "Compositing",
129            ProfilerCategory::Layout => "Layout",
130            ProfilerCategory::ImageSaving => "ImageSaving",
131            ProfilerCategory::ScriptAttachLayout => "ScriptAttachLayout",
132            ProfilerCategory::ScriptConstellationMsg => "ScriptConstellationMsg",
133            ProfilerCategory::ScriptDatabaseAccessEvent => "ScriptDatabaseAccessEvent",
134            ProfilerCategory::ScriptDevtoolsMsg => "ScriptDevtoolsMsg",
135            ProfilerCategory::ScriptDocumentEvent => "ScriptDocumentEvent",
136            ProfilerCategory::ScriptEvaluate => "ScriptEvaluate",
137            ProfilerCategory::ScriptEvent => "ScriptEvent",
138            ProfilerCategory::ScriptFileRead => "ScriptFileRead",
139            ProfilerCategory::ScriptFontLoading => "ScriptFontLoading",
140            ProfilerCategory::ScriptGeolocationEvent => "ScriptGeolocationEvent",
141            ProfilerCategory::ScriptImageCacheMsg => "ScriptImageCacheMsg",
142            ProfilerCategory::ScriptInputEvent => "ScriptInputEvent",
143            ProfilerCategory::ScriptNetworkEvent => "ScriptNetworkEvent",
144            ProfilerCategory::ScriptParseHTML => "ScriptParseHTML",
145            ProfilerCategory::ScriptPlannedNavigation => "ScriptPlannedNavigation",
146            ProfilerCategory::ScriptRendering => "ScriptRendering",
147            ProfilerCategory::ScriptResize => "ScriptResize",
148            ProfilerCategory::ScriptSetScrollState => "ScriptSetScrollState",
149            ProfilerCategory::ScriptSetViewport => "ScriptSetViewport",
150            ProfilerCategory::ScriptTimerEvent => "ScriptTimerEvent",
151            ProfilerCategory::ScriptStylesheetLoad => "ScriptStylesheetLoad",
152            ProfilerCategory::ScriptUpdateReplacedElement => "ScriptUpdateReplacedElement",
153            ProfilerCategory::ScriptWebSocketEvent => "ScriptWebSocketEvent",
154            ProfilerCategory::ScriptWorkerEvent => "ScriptWorkerEvent",
155            ProfilerCategory::ScriptServiceWorkerEvent => "ScriptServiceWorkerEvent",
156            ProfilerCategory::ScriptParseXML => "ScriptParseXML",
157            ProfilerCategory::ScriptEnterFullscreen => "ScriptEnterFullscreen",
158            ProfilerCategory::ScriptExitFullscreen => "ScriptExitFullscreen",
159            ProfilerCategory::ScriptWorkletEvent => "ScriptWorkletEvent",
160            ProfilerCategory::ScriptPerformanceEvent => "ScriptPerformanceEvent",
161            ProfilerCategory::ScriptHistoryEvent => "ScriptHistoryEvent",
162            ProfilerCategory::ScriptPortMessage => "ScriptPortMessage",
163            ProfilerCategory::ScriptWebGPUMsg => "ScriptWebGPUMsg",
164            ProfilerCategory::TimeToFirstPaint => "TimeToFirstPaint",
165            ProfilerCategory::TimeToFirstContentfulPaint => "TimeToFirstContentfulPaint",
166            ProfilerCategory::TimeToInteractive => "TimeToInteractive",
167            ProfilerCategory::IpcReceiver => "IpcReceiver",
168            ProfilerCategory::IpcBytesReceiver => "IpcBytesReceiver",
169        }
170    }
171}
172
173#[derive(Clone, Debug, Deserialize, Eq, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
174pub enum TimerMetadataFrameType {
175    RootWindow,
176    IFrame,
177}
178
179#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
180pub enum TimerMetadataReflowType {
181    Incremental,
182    FirstReflow,
183}
184
185#[cfg(feature = "tracing")]
186pub type Span = tracing::Span;
187#[cfg(not(feature = "tracing"))]
188pub type Span = ();
189
190pub fn profile<T, F>(
191    category: ProfilerCategory,
192    meta: Option<TimerMetadata>,
193    profiler_chan: ProfilerChan,
194    #[cfg(feature = "tracing")] span: Span,
195    #[cfg(not(feature = "tracing"))] _span: Span,
196    callback: F,
197) -> T
198where
199    F: FnOnce() -> T,
200{
201    let start_time = CrossProcessInstant::now();
202    let val = {
203        #[cfg(feature = "tracing")]
204        let _enter = span.enter();
205        callback()
206    };
207    let end_time = CrossProcessInstant::now();
208
209    send_profile_data(category, meta, &profiler_chan, start_time, end_time);
210    val
211}
212
213pub fn send_profile_data(
214    category: ProfilerCategory,
215    meta: Option<TimerMetadata>,
216    profiler_chan: &ProfilerChan,
217    start_time: CrossProcessInstant,
218    end_time: CrossProcessInstant,
219) {
220    profiler_chan.send(ProfilerMsg::Time((category, meta), (start_time, end_time)));
221}