script/dom/performance/
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::performanceentry::{EntryType, PerformanceEntry};
14use super::performancemark::PerformanceMark;
15use super::performancemeasure::PerformanceMeasure;
16use super::performancenavigation::PerformanceNavigation;
17use super::performancenavigationtiming::PerformanceNavigationTiming;
18use super::performanceobserver::PerformanceObserver as DOMPerformanceObserver;
19use crate::dom::bindings::cell::DomRefCell;
20use crate::dom::bindings::codegen::Bindings::PerformanceBinding::{
21    DOMHighResTimeStamp, PerformanceEntryList as DOMPerformanceEntryList, PerformanceMethods,
22};
23use crate::dom::bindings::error::{Error, Fallible};
24use crate::dom::bindings::inheritance::Castable;
25use crate::dom::bindings::num::Finite;
26use crate::dom::bindings::refcounted::Trusted;
27use crate::dom::bindings::reflector::{DomGlobal, reflect_dom_object};
28use crate::dom::bindings::root::DomRoot;
29use crate::dom::bindings::str::DOMString;
30use crate::dom::eventtarget::EventTarget;
31use crate::dom::globalscope::GlobalScope;
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<EntryType>,
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: EntryType,
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: EntryType,
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<EntryType>,
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<EntryType>,
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: EntryType,
228        buffered: bool,
229    ) {
230        if buffered {
231            let buffer = self.buffer.borrow();
232            let mut new_entries = buffer.get_entries_by_name_and_type(None, Some(entry_type));
233            if !new_entries.is_empty() {
234                let mut obs_entries = observer.entries();
235                obs_entries.append(&mut new_entries);
236                observer.set_entries(obs_entries);
237            }
238
239            if !self.pending_notification_observers_task.get() {
240                self.pending_notification_observers_task.set(true);
241                let global = &self.global();
242                let owner = Trusted::new(&*global.performance());
243                self.global()
244                    .task_manager()
245                    .performance_timeline_task_source()
246                    .queue(task!(notify_performance_observers: move || {
247                        owner.root().notify_observers();
248                    }));
249            }
250        }
251        let mut observers = self.observers.borrow_mut();
252        match observers.iter().position(|o| *o.observer == *observer) {
253            // If the observer is already in the list, we only update
254            // the observed entry types.
255            Some(p) => {
256                // Append the type if not already present, otherwise do nothing
257                if !observers[p].entry_types.contains(&entry_type) {
258                    observers[p].entry_types.push(entry_type)
259                }
260            },
261            // Otherwise, we create and insert the new PerformanceObserver.
262            None => observers.push(PerformanceObserver {
263                observer: DomRoot::from_ref(observer),
264                entry_types: vec![entry_type],
265            }),
266        };
267    }
268
269    /// Remove a PerformanceObserver from the list of observers.
270    pub(crate) fn remove_observer(&self, observer: &DOMPerformanceObserver) {
271        let mut observers = self.observers.borrow_mut();
272        let index = match observers.iter().position(|o| &(*o.observer) == observer) {
273            Some(p) => p,
274            None => return,
275        };
276
277        observers.remove(index);
278    }
279
280    /// Queue a notification for each performance observer interested in
281    /// this type of performance entry and queue a low priority task to
282    /// notify the observers if no other notification task is already queued.
283    ///
284    /// Algorithm spec:
285    /// <https://w3c.github.io/performance-timeline/#queue-a-performanceentry>
286    /// Also this algorithm has been extented according to :
287    /// <https://w3c.github.io/resource-timing/#sec-extensions-performance-interface>
288    pub(crate) fn queue_entry(&self, entry: &PerformanceEntry) -> Option<usize> {
289        // https://w3c.github.io/performance-timeline/#dfn-determine-eligibility-for-adding-a-performance-entry
290        if entry.entry_type() == EntryType::Resource && !self.should_queue_resource_entry(entry) {
291            return None;
292        }
293
294        // Steps 1-3.
295        // Add the performance entry to the list of performance entries that have not
296        // been notified to each performance observer owner, filtering the ones it's
297        // interested in.
298        for o in self
299            .observers
300            .borrow()
301            .iter()
302            .filter(|o| o.entry_types.contains(&entry.entry_type()))
303        {
304            o.observer.queue_entry(entry);
305        }
306
307        // Step 4.
308        // add the new entry to the buffer.
309        self.buffer
310            .borrow_mut()
311            .entries
312            .push(DomRoot::from_ref(entry));
313
314        let entry_last_index = self.buffer.borrow_mut().entries.len() - 1;
315
316        // Step 5.
317        // If there is already a queued notification task, we just bail out.
318        if self.pending_notification_observers_task.get() {
319            return None;
320        }
321
322        // Step 6.
323        // Queue a new notification task.
324        self.pending_notification_observers_task.set(true);
325
326        let global = &self.global();
327        let owner = Trusted::new(&*global.performance());
328        self.global()
329            .task_manager()
330            .performance_timeline_task_source()
331            .queue(task!(notify_performance_observers: move || {
332                owner.root().notify_observers();
333            }));
334
335        Some(entry_last_index)
336    }
337
338    /// Observers notifications task.
339    ///
340    /// Algorithm spec (step 7):
341    /// <https://w3c.github.io/performance-timeline/#queue-a-performanceentry>
342    pub(crate) fn notify_observers(&self) {
343        // Step 7.1.
344        self.pending_notification_observers_task.set(false);
345
346        // Step 7.2.
347        // We have to operate over a copy of the performance observers to avoid
348        // the risk of an observer's callback modifying the list of registered
349        // observers. This is a shallow copy, so observers can
350        // disconnect themselves by using the argument of their own callback.
351        let observers: Vec<DomRoot<DOMPerformanceObserver>> = self
352            .observers
353            .borrow()
354            .iter()
355            .map(|o| DomRoot::from_ref(&*o.observer))
356            .collect();
357
358        // Step 7.3.
359        for o in observers.iter() {
360            o.notify(CanGc::note());
361        }
362    }
363
364    fn can_add_resource_timing_entry(&self) -> bool {
365        self.resource_timing_buffer_current_size.get() <=
366            self.resource_timing_buffer_size_limit.get()
367    }
368
369    /// <https://w3c.github.io/resource-timing/#dfn-copy-secondary-buffer>
370    fn copy_secondary_resource_timing_buffer(&self) {
371        // Step 1. While resource timing secondary buffer is not empty and can add resource timing entry returns true, run the following substeps:
372        while self.can_add_resource_timing_entry() {
373            // Step 1.1. Let entry be the oldest PerformanceResourceTiming in resource timing secondary buffer.
374            let entry = self
375                .resource_timing_secondary_entries
376                .borrow_mut()
377                .pop_front();
378            if let Some(ref entry) = entry {
379                // Step 1.2. Add entry to the end of performance entry buffer.
380                self.buffer
381                    .borrow_mut()
382                    .entries
383                    .push(DomRoot::from_ref(entry));
384                // Step 1.3. Increment resource timing buffer current size by 1.
385                self.resource_timing_buffer_current_size
386                    .set(self.resource_timing_buffer_current_size.get() + 1);
387                // Step 1.4. Remove entry from resource timing secondary buffer.
388                // Step 1.5. Decrement resource timing secondary buffer current size by 1.
389                // Handled by popping the entry earlier.
390            } else {
391                break;
392            }
393        }
394    }
395    // `fire a buffer full event` paragraph of
396    /// <https://w3c.github.io/resource-timing/#sec-extensions-performance-interface>
397    fn fire_buffer_full_event(&self, can_gc: CanGc) {
398        while !self.resource_timing_secondary_entries.borrow().is_empty() {
399            let no_of_excess_entries_before = self.resource_timing_secondary_entries.borrow().len();
400
401            if !self.can_add_resource_timing_entry() {
402                self.upcast::<EventTarget>()
403                    .fire_event(atom!("resourcetimingbufferfull"), can_gc);
404            }
405            self.copy_secondary_resource_timing_buffer();
406            let no_of_excess_entries_after = self.resource_timing_secondary_entries.borrow().len();
407            if no_of_excess_entries_before <= no_of_excess_entries_after {
408                self.resource_timing_secondary_entries.borrow_mut().clear();
409                break;
410            }
411        }
412        self.resource_timing_buffer_pending_full_event.set(false);
413    }
414
415    /// <https://w3c.github.io/resource-timing/#dfn-add-a-performanceresourcetiming-entry>
416    fn should_queue_resource_entry(&self, entry: &PerformanceEntry) -> bool {
417        // Step 1. If can add resource timing entry returns true and resource timing buffer full event pending flag is false, run the following substeps:
418        if !self.resource_timing_buffer_pending_full_event.get() {
419            if self.can_add_resource_timing_entry() {
420                // Step 1.a.  Add new entry to the performance entry buffer.
421                //   This is done in queue_entry, which calls this method.
422                // Step 1.b. Increase resource timing buffer current size by 1.
423                self.resource_timing_buffer_current_size
424                    .set(self.resource_timing_buffer_current_size.get() + 1);
425                // Step 1.c. Return.
426                return true;
427            }
428            // Step 2.a. Set resource timing buffer full event pending flag to true.
429            self.resource_timing_buffer_pending_full_event.set(true);
430            // Step 2.b. Queue a task on the performance timeline task source to run fire a buffer full event.
431            let performance = Trusted::new(self);
432            self.global()
433                .task_manager()
434                .performance_timeline_task_source()
435                .queue(task!(fire_a_buffer_full_event: move || {
436                    performance.root().fire_buffer_full_event(CanGc::note());
437                }));
438        }
439        // Step 3. Add new entry to the resource timing secondary buffer.
440        self.resource_timing_secondary_entries
441            .borrow_mut()
442            .push_back(DomRoot::from_ref(entry));
443        // Step 4. Increase resource timing secondary buffer current size by 1.
444        //   This is tracked automatically via `.len()`.
445        false
446    }
447
448    pub(crate) fn update_entry(&self, index: usize, entry: &PerformanceEntry) {
449        if let Some(e) = self.buffer.borrow_mut().entries.get_mut(index) {
450            *e = DomRoot::from_ref(entry);
451        }
452    }
453}
454
455impl PerformanceMethods<crate::DomTypeHolder> for Performance {
456    // FIXME(avada): this should be deprecated in the future, but some sites still use it
457    /// <https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/NavigationTiming/Overview.html#performance-timing-attribute>
458    fn Timing(&self) -> DomRoot<PerformanceNavigationTiming> {
459        let entries = self.GetEntriesByType(DOMString::from("navigation"));
460        if !entries.is_empty() {
461            return DomRoot::from_ref(
462                entries[0]
463                    .downcast::<PerformanceNavigationTiming>()
464                    .unwrap(),
465            );
466        }
467        unreachable!("Are we trying to expose Performance.timing in workers?");
468    }
469
470    /// <https://w3c.github.io/navigation-timing/#dom-performance-navigation>
471    fn Navigation(&self) -> DomRoot<PerformanceNavigation> {
472        PerformanceNavigation::new(&self.global(), CanGc::note())
473    }
474
475    /// <https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now>
476    fn Now(&self) -> DOMHighResTimeStamp {
477        self.to_dom_high_res_time_stamp(CrossProcessInstant::now())
478    }
479
480    /// <https://www.w3.org/TR/hr-time-2/#dom-performance-timeorigin>
481    fn TimeOrigin(&self) -> DOMHighResTimeStamp {
482        (self.time_origin - CrossProcessInstant::epoch()).to_dom_high_res_time_stamp()
483    }
484
485    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentries>
486    fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> {
487        self.buffer
488            .borrow()
489            .get_entries_by_name_and_type(None, None)
490    }
491
492    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbytype>
493    fn GetEntriesByType(&self, entry_type: DOMString) -> Vec<DomRoot<PerformanceEntry>> {
494        let Ok(entry_type) = EntryType::try_from(&*entry_type.str()) else {
495            return Vec::new();
496        };
497        self.buffer
498            .borrow()
499            .get_entries_by_name_and_type(None, Some(entry_type))
500    }
501
502    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbyname>
503    fn GetEntriesByName(
504        &self,
505        name: DOMString,
506        entry_type: Option<DOMString>,
507    ) -> Vec<DomRoot<PerformanceEntry>> {
508        let entry_type = match entry_type {
509            Some(entry_type) => {
510                let Ok(entry_type) = EntryType::try_from(&*entry_type.str()) else {
511                    return Vec::new();
512                };
513                Some(entry_type)
514            },
515            None => None,
516        };
517        self.buffer
518            .borrow()
519            .get_entries_by_name_and_type(Some(name), entry_type)
520    }
521
522    /// <https://w3c.github.io/user-timing/#dom-performance-mark>
523    fn Mark(&self, mark_name: DOMString) -> Fallible<()> {
524        let global = self.global();
525        // Step 1.
526        if global.is::<Window>() && INVALID_ENTRY_NAMES.contains(&&*mark_name.str()) {
527            return Err(Error::Syntax(None));
528        }
529
530        // Steps 2 to 6.
531        let entry = PerformanceMark::new(
532            &global,
533            mark_name,
534            CrossProcessInstant::now(),
535            Duration::ZERO,
536        );
537        // Steps 7 and 8.
538        self.queue_entry(entry.upcast::<PerformanceEntry>());
539
540        // Step 9.
541        Ok(())
542    }
543
544    /// <https://w3c.github.io/user-timing/#dom-performance-clearmarks>
545    fn ClearMarks(&self, mark_name: Option<DOMString>) {
546        self.buffer
547            .borrow_mut()
548            .clear_entries_by_name_and_type(mark_name, EntryType::Mark);
549    }
550
551    /// <https://w3c.github.io/user-timing/#dom-performance-measure>
552    fn Measure(
553        &self,
554        measure_name: DOMString,
555        start_mark: Option<DOMString>,
556        end_mark: Option<DOMString>,
557    ) -> Fallible<()> {
558        // Steps 1 and 2.
559        let end_time = end_mark
560            .map(|name| {
561                self.buffer
562                    .borrow()
563                    .get_last_entry_start_time_with_name_and_type(name, EntryType::Mark)
564                    .unwrap_or(self.time_origin)
565            })
566            .unwrap_or_else(CrossProcessInstant::now);
567
568        // Step 3.
569        let start_time = start_mark
570            .and_then(|name| {
571                self.buffer
572                    .borrow()
573                    .get_last_entry_start_time_with_name_and_type(name, EntryType::Mark)
574            })
575            .unwrap_or(self.time_origin);
576
577        // Steps 4 to 8.
578        let entry = PerformanceMeasure::new(
579            &self.global(),
580            measure_name,
581            start_time,
582            end_time - start_time,
583        );
584
585        // Step 9 and 10.
586        self.queue_entry(entry.upcast::<PerformanceEntry>());
587
588        // Step 11.
589        Ok(())
590    }
591
592    /// <https://w3c.github.io/user-timing/#dom-performance-clearmeasures>
593    fn ClearMeasures(&self, measure_name: Option<DOMString>) {
594        self.buffer
595            .borrow_mut()
596            .clear_entries_by_name_and_type(measure_name, EntryType::Measure);
597    }
598    /// <https://w3c.github.io/resource-timing/#dom-performance-clearresourcetimings>
599    fn ClearResourceTimings(&self) {
600        self.buffer
601            .borrow_mut()
602            .clear_entries_by_name_and_type(None, EntryType::Resource);
603        self.resource_timing_buffer_current_size.set(0);
604    }
605
606    /// <https://w3c.github.io/resource-timing/#dom-performance-setresourcetimingbuffersize>
607    fn SetResourceTimingBufferSize(&self, max_size: u32) {
608        self.resource_timing_buffer_size_limit
609            .set(max_size as usize);
610    }
611
612    // https://w3c.github.io/resource-timing/#dom-performance-onresourcetimingbufferfull
613    event_handler!(
614        resourcetimingbufferfull,
615        GetOnresourcetimingbufferfull,
616        SetOnresourcetimingbufferfull
617    );
618}
619
620pub(crate) trait ToDOMHighResTimeStamp {
621    fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp;
622}
623
624impl ToDOMHighResTimeStamp for Duration {
625    fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp {
626        // https://www.w3.org/TR/hr-time-2/#clock-resolution
627        // We need a granularity no finer than 5 microseconds. 5 microseconds isn't an
628        // exactly representable f64 so WPT tests might occasionally corner-case on
629        // rounding.  web-platform-tests/wpt#21526 wants us to use an integer number of
630        // microseconds; the next divisor of milliseconds up from 5 microseconds is 10.
631        let microseconds_rounded = (self.whole_microseconds() as f64 / 10.).floor() * 10.;
632        Finite::wrap(microseconds_rounded / 1000.)
633    }
634}