script/dom/
performance.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 std::cell::Cell;
6use std::cmp::Ordering;
7use std::collections::VecDeque;
8
9use base::cross_process_instant::CrossProcessInstant;
10use dom_struct::dom_struct;
11use time::Duration;
12
13use super::bindings::refcounted::Trusted;
14use crate::dom::bindings::cell::DomRefCell;
15use crate::dom::bindings::codegen::Bindings::PerformanceBinding::{
16    DOMHighResTimeStamp, PerformanceEntryList as DOMPerformanceEntryList, PerformanceMethods,
17};
18use crate::dom::bindings::error::{Error, Fallible};
19use crate::dom::bindings::inheritance::Castable;
20use crate::dom::bindings::num::Finite;
21use crate::dom::bindings::reflector::{DomGlobal, reflect_dom_object};
22use crate::dom::bindings::root::DomRoot;
23use crate::dom::bindings::str::DOMString;
24use crate::dom::eventtarget::EventTarget;
25use crate::dom::globalscope::GlobalScope;
26use crate::dom::performanceentry::PerformanceEntry;
27use crate::dom::performancemark::PerformanceMark;
28use crate::dom::performancemeasure::PerformanceMeasure;
29use crate::dom::performancenavigation::PerformanceNavigation;
30use crate::dom::performancenavigationtiming::PerformanceNavigationTiming;
31use crate::dom::performanceobserver::PerformanceObserver as DOMPerformanceObserver;
32use crate::dom::window::Window;
33use crate::script_runtime::CanGc;
34
35const INVALID_ENTRY_NAMES: &[&str] = &[
36    "navigationStart",
37    "unloadEventStart",
38    "unloadEventEnd",
39    "redirectStart",
40    "redirectEnd",
41    "fetchStart",
42    "domainLookupStart",
43    "domainLookupEnd",
44    "connectStart",
45    "connectEnd",
46    "secureConnectionStart",
47    "requestStart",
48    "responseStart",
49    "responseEnd",
50    "domLoading",
51    "domInteractive",
52    "domContentLoadedEventStart",
53    "domContentLoadedEventEnd",
54    "domComplete",
55    "loadEventStart",
56    "loadEventEnd",
57];
58
59/// Implementation of a list of PerformanceEntry items shared by the
60/// Performance and PerformanceObserverEntryList interfaces implementations.
61#[derive(JSTraceable, MallocSizeOf)]
62pub(crate) struct PerformanceEntryList {
63    /// <https://w3c.github.io/performance-timeline/#dfn-performance-entry-buffer>
64    entries: DOMPerformanceEntryList,
65}
66
67impl PerformanceEntryList {
68    pub(crate) fn new(entries: DOMPerformanceEntryList) -> Self {
69        PerformanceEntryList { entries }
70    }
71
72    pub(crate) fn get_entries_by_name_and_type(
73        &self,
74        name: Option<DOMString>,
75        entry_type: Option<DOMString>,
76    ) -> Vec<DomRoot<PerformanceEntry>> {
77        let mut res = self
78            .entries
79            .iter()
80            .filter(|e| {
81                name.as_ref().is_none_or(|name_| *e.name() == *name_) &&
82                    entry_type
83                        .as_ref()
84                        .is_none_or(|type_| *e.entry_type() == *type_)
85            })
86            .cloned()
87            .collect::<Vec<DomRoot<PerformanceEntry>>>();
88        res.sort_by(|a, b| {
89            a.start_time()
90                .partial_cmp(&b.start_time())
91                .unwrap_or(Ordering::Equal)
92        });
93        res
94    }
95
96    pub(crate) fn clear_entries_by_name_and_type(
97        &mut self,
98        name: Option<DOMString>,
99        entry_type: DOMString,
100    ) {
101        self.entries.retain(|e| {
102            *e.entry_type() != *entry_type || name.as_ref().is_some_and(|name_| *e.name() != *name_)
103        });
104    }
105
106    fn get_last_entry_start_time_with_name_and_type(
107        &self,
108        name: DOMString,
109        entry_type: DOMString,
110    ) -> Option<CrossProcessInstant> {
111        self.entries
112            .iter()
113            .rev()
114            .find(|e| *e.entry_type() == *entry_type && *e.name() == *name)
115            .and_then(|entry| entry.start_time())
116    }
117}
118
119impl IntoIterator for PerformanceEntryList {
120    type Item = DomRoot<PerformanceEntry>;
121    type IntoIter = ::std::vec::IntoIter<DomRoot<PerformanceEntry>>;
122
123    fn into_iter(self) -> Self::IntoIter {
124        self.entries.into_iter()
125    }
126}
127
128#[derive(JSTraceable, MallocSizeOf)]
129struct PerformanceObserver {
130    observer: DomRoot<DOMPerformanceObserver>,
131    entry_types: Vec<DOMString>,
132}
133
134#[dom_struct]
135pub(crate) struct Performance {
136    eventtarget: EventTarget,
137    buffer: DomRefCell<PerformanceEntryList>,
138    observers: DomRefCell<Vec<PerformanceObserver>>,
139    pending_notification_observers_task: Cell<bool>,
140    #[no_trace]
141    /// The `timeOrigin` as described in
142    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-time-origin>.
143    time_origin: CrossProcessInstant,
144    /// <https://w3c.github.io/performance-timeline/#dfn-maxbuffersize>
145    /// The max-size of the buffer, set to 0 once the pipeline exits.
146    /// TODO: have one max-size per entry type.
147    resource_timing_buffer_size_limit: Cell<usize>,
148    resource_timing_buffer_current_size: Cell<usize>,
149    resource_timing_buffer_pending_full_event: Cell<bool>,
150    resource_timing_secondary_entries: DomRefCell<VecDeque<DomRoot<PerformanceEntry>>>,
151}
152
153impl Performance {
154    fn new_inherited(time_origin: CrossProcessInstant) -> Performance {
155        Performance {
156            eventtarget: EventTarget::new_inherited(),
157            buffer: DomRefCell::new(PerformanceEntryList::new(Vec::new())),
158            observers: DomRefCell::new(Vec::new()),
159            pending_notification_observers_task: Cell::new(false),
160            time_origin,
161            resource_timing_buffer_size_limit: Cell::new(250),
162            resource_timing_buffer_current_size: Cell::new(0),
163            resource_timing_buffer_pending_full_event: Cell::new(false),
164            resource_timing_secondary_entries: DomRefCell::new(VecDeque::new()),
165        }
166    }
167
168    pub(crate) fn new(
169        global: &GlobalScope,
170        navigation_start: CrossProcessInstant,
171        can_gc: CanGc,
172    ) -> DomRoot<Performance> {
173        reflect_dom_object(
174            Box::new(Performance::new_inherited(navigation_start)),
175            global,
176            can_gc,
177        )
178    }
179
180    pub(crate) fn to_dom_high_res_time_stamp(
181        &self,
182        instant: CrossProcessInstant,
183    ) -> DOMHighResTimeStamp {
184        (instant - self.time_origin).to_dom_high_res_time_stamp()
185    }
186
187    pub(crate) fn maybe_to_dom_high_res_time_stamp(
188        &self,
189        instant: Option<CrossProcessInstant>,
190    ) -> DOMHighResTimeStamp {
191        self.to_dom_high_res_time_stamp(instant.unwrap_or(self.time_origin))
192    }
193
194    /// Clear all buffered performance entries, and disable the buffer.
195    /// Called as part of the window's "clear_js_runtime" workflow,
196    /// performed when exiting a pipeline.
197    pub(crate) fn clear_and_disable_performance_entry_buffer(&self) {
198        let mut buffer = self.buffer.borrow_mut();
199        buffer.entries.clear();
200        self.resource_timing_buffer_size_limit.set(0);
201    }
202
203    // Add a PerformanceObserver to the list of observers with a set of
204    // observed entry types.
205
206    pub(crate) fn add_multiple_type_observer(
207        &self,
208        observer: &DOMPerformanceObserver,
209        entry_types: Vec<DOMString>,
210    ) {
211        let mut observers = self.observers.borrow_mut();
212        match observers.iter().position(|o| *o.observer == *observer) {
213            // If the observer is already in the list, we only update the observed
214            // entry types.
215            Some(p) => observers[p].entry_types = entry_types,
216            // Otherwise, we create and insert the new PerformanceObserver.
217            None => observers.push(PerformanceObserver {
218                observer: DomRoot::from_ref(observer),
219                entry_types,
220            }),
221        };
222    }
223
224    pub(crate) fn add_single_type_observer(
225        &self,
226        observer: &DOMPerformanceObserver,
227        entry_type: &DOMString,
228        buffered: bool,
229    ) {
230        if buffered {
231            let buffer = self.buffer.borrow();
232            let mut new_entries =
233                buffer.get_entries_by_name_and_type(None, Some(entry_type.clone()));
234            if !new_entries.is_empty() {
235                let mut obs_entries = observer.entries();
236                obs_entries.append(&mut new_entries);
237                observer.set_entries(obs_entries);
238            }
239
240            if !self.pending_notification_observers_task.get() {
241                self.pending_notification_observers_task.set(true);
242                let global = &self.global();
243                let owner = Trusted::new(&*global.performance());
244                self.global()
245                    .task_manager()
246                    .performance_timeline_task_source()
247                    .queue(task!(notify_performance_observers: move || {
248                        owner.root().notify_observers();
249                    }));
250            }
251        }
252        let mut observers = self.observers.borrow_mut();
253        match observers.iter().position(|o| *o.observer == *observer) {
254            // If the observer is already in the list, we only update
255            // the observed entry types.
256            Some(p) => {
257                // Append the type if not already present, otherwise do nothing
258                if !observers[p].entry_types.contains(entry_type) {
259                    observers[p].entry_types.push(entry_type.clone())
260                }
261            },
262            // Otherwise, we create and insert the new PerformanceObserver.
263            None => observers.push(PerformanceObserver {
264                observer: DomRoot::from_ref(observer),
265                entry_types: vec![entry_type.clone()],
266            }),
267        };
268    }
269
270    /// Remove a PerformanceObserver from the list of observers.
271    pub(crate) fn remove_observer(&self, observer: &DOMPerformanceObserver) {
272        let mut observers = self.observers.borrow_mut();
273        let index = match observers.iter().position(|o| &(*o.observer) == observer) {
274            Some(p) => p,
275            None => return,
276        };
277
278        observers.remove(index);
279    }
280
281    /// Queue a notification for each performance observer interested in
282    /// this type of performance entry and queue a low priority task to
283    /// notify the observers if no other notification task is already queued.
284    ///
285    /// Algorithm spec:
286    /// <https://w3c.github.io/performance-timeline/#queue-a-performanceentry>
287    /// Also this algorithm has been extented according to :
288    /// <https://w3c.github.io/resource-timing/#sec-extensions-performance-interface>
289    pub(crate) fn queue_entry(&self, entry: &PerformanceEntry, can_gc: CanGc) -> Option<usize> {
290        // https://w3c.github.io/performance-timeline/#dfn-determine-eligibility-for-adding-a-performance-entry
291        if entry.entry_type() == "resource" && !self.should_queue_resource_entry(entry, can_gc) {
292            return None;
293        }
294
295        // Steps 1-3.
296        // Add the performance entry to the list of performance entries that have not
297        // been notified to each performance observer owner, filtering the ones it's
298        // interested in.
299        for o in self
300            .observers
301            .borrow()
302            .iter()
303            .filter(|o| o.entry_types.contains(entry.entry_type()))
304        {
305            o.observer.queue_entry(entry);
306        }
307
308        // Step 4.
309        // add the new entry to the buffer.
310        self.buffer
311            .borrow_mut()
312            .entries
313            .push(DomRoot::from_ref(entry));
314
315        let entry_last_index = self.buffer.borrow_mut().entries.len() - 1;
316
317        // Step 5.
318        // If there is already a queued notification task, we just bail out.
319        if self.pending_notification_observers_task.get() {
320            return None;
321        }
322
323        // Step 6.
324        // Queue a new notification task.
325        self.pending_notification_observers_task.set(true);
326
327        let global = &self.global();
328        let owner = Trusted::new(&*global.performance());
329        self.global()
330            .task_manager()
331            .performance_timeline_task_source()
332            .queue(task!(notify_performance_observers: move || {
333                owner.root().notify_observers();
334            }));
335
336        Some(entry_last_index)
337    }
338
339    /// Observers notifications task.
340    ///
341    /// Algorithm spec (step 7):
342    /// <https://w3c.github.io/performance-timeline/#queue-a-performanceentry>
343    pub(crate) fn notify_observers(&self) {
344        // Step 7.1.
345        self.pending_notification_observers_task.set(false);
346
347        // Step 7.2.
348        // We have to operate over a copy of the performance observers to avoid
349        // the risk of an observer's callback modifying the list of registered
350        // observers. This is a shallow copy, so observers can
351        // disconnect themselves by using the argument of their own callback.
352        let observers: Vec<DomRoot<DOMPerformanceObserver>> = self
353            .observers
354            .borrow()
355            .iter()
356            .map(|o| DomRoot::from_ref(&*o.observer))
357            .collect();
358
359        // Step 7.3.
360        for o in observers.iter() {
361            o.notify(CanGc::note());
362        }
363    }
364
365    fn can_add_resource_timing_entry(&self) -> bool {
366        self.resource_timing_buffer_current_size.get() <=
367            self.resource_timing_buffer_size_limit.get()
368    }
369    fn copy_secondary_resource_timing_buffer(&self, can_gc: CanGc) {
370        while self.can_add_resource_timing_entry() {
371            let entry = self
372                .resource_timing_secondary_entries
373                .borrow_mut()
374                .pop_front();
375            if let Some(ref entry) = entry {
376                self.queue_entry(entry, can_gc);
377            } else {
378                break;
379            }
380        }
381    }
382    // `fire a buffer full event` paragraph of
383    // https://w3c.github.io/resource-timing/#sec-extensions-performance-interface
384    fn fire_buffer_full_event(&self, can_gc: CanGc) {
385        while !self.resource_timing_secondary_entries.borrow().is_empty() {
386            let no_of_excess_entries_before = self.resource_timing_secondary_entries.borrow().len();
387
388            if !self.can_add_resource_timing_entry() {
389                self.upcast::<EventTarget>()
390                    .fire_event(atom!("resourcetimingbufferfull"), can_gc);
391            }
392            self.copy_secondary_resource_timing_buffer(can_gc);
393            let no_of_excess_entries_after = self.resource_timing_secondary_entries.borrow().len();
394            if no_of_excess_entries_before <= no_of_excess_entries_after {
395                self.resource_timing_secondary_entries.borrow_mut().clear();
396                break;
397            }
398        }
399        self.resource_timing_buffer_pending_full_event.set(false);
400    }
401    /// `add a PerformanceResourceTiming entry` paragraph of
402    /// <https://w3c.github.io/resource-timing/#sec-extensions-performance-interface>
403    fn should_queue_resource_entry(&self, entry: &PerformanceEntry, can_gc: CanGc) -> bool {
404        // Step 1 is done in the args list.
405        if !self.resource_timing_buffer_pending_full_event.get() {
406            // Step 2.
407            if self.can_add_resource_timing_entry() {
408                // Step 2.a is done in `queue_entry`
409                // Step 2.b.
410                self.resource_timing_buffer_current_size
411                    .set(self.resource_timing_buffer_current_size.get() + 1);
412                // Step 2.c.
413                return true;
414            }
415            // Step 3.
416            self.resource_timing_buffer_pending_full_event.set(true);
417            self.fire_buffer_full_event(can_gc);
418        }
419        // Steps 4 and 5.
420        self.resource_timing_secondary_entries
421            .borrow_mut()
422            .push_back(DomRoot::from_ref(entry));
423        false
424    }
425
426    pub(crate) fn update_entry(&self, index: usize, entry: &PerformanceEntry) {
427        if let Some(e) = self.buffer.borrow_mut().entries.get_mut(index) {
428            *e = DomRoot::from_ref(entry);
429        }
430    }
431}
432
433impl PerformanceMethods<crate::DomTypeHolder> for Performance {
434    // FIXME(avada): this should be deprecated in the future, but some sites still use it
435    // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/NavigationTiming/Overview.html#performance-timing-attribute
436    fn Timing(&self) -> DomRoot<PerformanceNavigationTiming> {
437        let entries = self.GetEntriesByType(DOMString::from("navigation"));
438        if !entries.is_empty() {
439            return DomRoot::from_ref(
440                entries[0]
441                    .downcast::<PerformanceNavigationTiming>()
442                    .unwrap(),
443            );
444        }
445        unreachable!("Are we trying to expose Performance.timing in workers?");
446    }
447
448    // https://w3c.github.io/navigation-timing/#dom-performance-navigation
449    fn Navigation(&self) -> DomRoot<PerformanceNavigation> {
450        PerformanceNavigation::new(&self.global(), CanGc::note())
451    }
452
453    // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now
454    fn Now(&self) -> DOMHighResTimeStamp {
455        self.to_dom_high_res_time_stamp(CrossProcessInstant::now())
456    }
457
458    // https://www.w3.org/TR/hr-time-2/#dom-performance-timeorigin
459    fn TimeOrigin(&self) -> DOMHighResTimeStamp {
460        (self.time_origin - CrossProcessInstant::epoch()).to_dom_high_res_time_stamp()
461    }
462
463    // https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentries
464    fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> {
465        self.buffer
466            .borrow()
467            .get_entries_by_name_and_type(None, None)
468    }
469
470    // https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbytype
471    fn GetEntriesByType(&self, entry_type: DOMString) -> Vec<DomRoot<PerformanceEntry>> {
472        self.buffer
473            .borrow()
474            .get_entries_by_name_and_type(None, Some(entry_type))
475    }
476
477    // https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbyname
478    fn GetEntriesByName(
479        &self,
480        name: DOMString,
481        entry_type: Option<DOMString>,
482    ) -> Vec<DomRoot<PerformanceEntry>> {
483        self.buffer
484            .borrow()
485            .get_entries_by_name_and_type(Some(name), entry_type)
486    }
487
488    // https://w3c.github.io/user-timing/#dom-performance-mark
489    fn Mark(&self, mark_name: DOMString, can_gc: CanGc) -> Fallible<()> {
490        let global = self.global();
491        // Step 1.
492        if global.is::<Window>() && INVALID_ENTRY_NAMES.contains(&mark_name.as_ref()) {
493            return Err(Error::Syntax);
494        }
495
496        // Steps 2 to 6.
497        let entry = PerformanceMark::new(
498            &global,
499            mark_name,
500            CrossProcessInstant::now(),
501            Duration::ZERO,
502        );
503        // Steps 7 and 8.
504        self.queue_entry(entry.upcast::<PerformanceEntry>(), can_gc);
505
506        // Step 9.
507        Ok(())
508    }
509
510    // https://w3c.github.io/user-timing/#dom-performance-clearmarks
511    fn ClearMarks(&self, mark_name: Option<DOMString>) {
512        self.buffer
513            .borrow_mut()
514            .clear_entries_by_name_and_type(mark_name, DOMString::from("mark"));
515    }
516
517    // https://w3c.github.io/user-timing/#dom-performance-measure
518    fn Measure(
519        &self,
520        measure_name: DOMString,
521        start_mark: Option<DOMString>,
522        end_mark: Option<DOMString>,
523        can_gc: CanGc,
524    ) -> Fallible<()> {
525        // Steps 1 and 2.
526        let end_time = end_mark
527            .map(|name| {
528                self.buffer
529                    .borrow()
530                    .get_last_entry_start_time_with_name_and_type(DOMString::from("mark"), name)
531                    .unwrap_or(self.time_origin)
532            })
533            .unwrap_or_else(CrossProcessInstant::now);
534
535        // Step 3.
536        let start_time = start_mark
537            .and_then(|name| {
538                self.buffer
539                    .borrow()
540                    .get_last_entry_start_time_with_name_and_type(DOMString::from("mark"), name)
541            })
542            .unwrap_or(self.time_origin);
543
544        // Steps 4 to 8.
545        let entry = PerformanceMeasure::new(
546            &self.global(),
547            measure_name,
548            start_time,
549            end_time - start_time,
550        );
551
552        // Step 9 and 10.
553        self.queue_entry(entry.upcast::<PerformanceEntry>(), can_gc);
554
555        // Step 11.
556        Ok(())
557    }
558
559    // https://w3c.github.io/user-timing/#dom-performance-clearmeasures
560    fn ClearMeasures(&self, measure_name: Option<DOMString>) {
561        self.buffer
562            .borrow_mut()
563            .clear_entries_by_name_and_type(measure_name, DOMString::from("measure"));
564    }
565    // https://w3c.github.io/resource-timing/#dom-performance-clearresourcetimings
566    fn ClearResourceTimings(&self) {
567        self.buffer
568            .borrow_mut()
569            .clear_entries_by_name_and_type(None, DOMString::from("resource"));
570        self.resource_timing_buffer_current_size.set(0);
571    }
572
573    // https://w3c.github.io/resource-timing/#dom-performance-setresourcetimingbuffersize
574    fn SetResourceTimingBufferSize(&self, max_size: u32) {
575        self.resource_timing_buffer_size_limit
576            .set(max_size as usize);
577    }
578
579    // https://w3c.github.io/resource-timing/#dom-performance-onresourcetimingbufferfull
580    event_handler!(
581        resourcetimingbufferfull,
582        GetOnresourcetimingbufferfull,
583        SetOnresourcetimingbufferfull
584    );
585}
586
587pub(crate) trait ToDOMHighResTimeStamp {
588    fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp;
589}
590
591impl ToDOMHighResTimeStamp for Duration {
592    fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp {
593        // https://www.w3.org/TR/hr-time-2/#clock-resolution
594        // We need a granularity no finer than 5 microseconds. 5 microseconds isn't an
595        // exactly representable f64 so WPT tests might occasionally corner-case on
596        // rounding.  web-platform-tests/wpt#21526 wants us to use an integer number of
597        // microseconds; the next divisor of milliseconds up from 5 microseconds is 10.
598        let microseconds_rounded = (self.whole_microseconds() as f64 / 10.).floor() * 10.;
599        Finite::wrap(microseconds_rounded / 1000.)
600    }
601}