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 dom_struct::dom_struct;
10use js::context::JSContext;
11use js::jsval::NullValue;
12use script_bindings::cformat;
13use script_bindings::codegen::GenericBindings::PerformanceBinding::PerformanceMarkOptions;
14use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
15use script_bindings::codegen::GenericUnionTypes::StringOrPerformanceMeasureOptions;
16use servo_base::cross_process_instant::CrossProcessInstant;
17use time::Duration;
18
19use super::performanceentry::{EntryType, PerformanceEntry};
20use super::performancemark::PerformanceMark;
21use super::performancemeasure::PerformanceMeasure;
22use super::performancenavigation::PerformanceNavigation;
23use super::performancenavigationtiming::PerformanceNavigationTiming;
24use super::performanceobserver::PerformanceObserver as DOMPerformanceObserver;
25use crate::dom::bindings::cell::DomRefCell;
26use crate::dom::bindings::codegen::Bindings::PerformanceBinding::{
27    DOMHighResTimeStamp, PerformanceEntryList as DOMPerformanceEntryList, PerformanceMethods,
28};
29use crate::dom::bindings::codegen::UnionTypes::StringOrDouble;
30use crate::dom::bindings::error::{Error, Fallible};
31use crate::dom::bindings::inheritance::Castable;
32use crate::dom::bindings::num::Finite;
33use crate::dom::bindings::refcounted::Trusted;
34use crate::dom::bindings::reflector::{DomGlobal, reflect_dom_object};
35use crate::dom::bindings::root::DomRoot;
36use crate::dom::bindings::str::DOMString;
37use crate::dom::bindings::structuredclone;
38use crate::dom::bindings::trace::RootedTraceableBox;
39use crate::dom::eventtarget::EventTarget;
40use crate::dom::globalscope::GlobalScope;
41use crate::dom::window::Window;
42use crate::script_runtime::CanGc;
43
44const INVALID_ENTRY_NAMES: &[&str] = &[
45    "navigationStart",
46    "unloadEventStart",
47    "unloadEventEnd",
48    "redirectStart",
49    "redirectEnd",
50    "fetchStart",
51    "domainLookupStart",
52    "domainLookupEnd",
53    "connectStart",
54    "connectEnd",
55    "secureConnectionStart",
56    "requestStart",
57    "responseStart",
58    "responseEnd",
59    "domLoading",
60    "domInteractive",
61    "domContentLoadedEventStart",
62    "domContentLoadedEventEnd",
63    "domComplete",
64    "loadEventStart",
65    "loadEventEnd",
66];
67
68/// Implementation of a list of PerformanceEntry items shared by the
69/// Performance and PerformanceObserverEntryList interfaces implementations.
70#[derive(JSTraceable, MallocSizeOf)]
71pub(crate) struct PerformanceEntryList {
72    /// <https://w3c.github.io/performance-timeline/#dfn-performance-entry-buffer>
73    entries: DOMPerformanceEntryList,
74}
75
76impl PerformanceEntryList {
77    pub(crate) fn new(entries: DOMPerformanceEntryList) -> Self {
78        PerformanceEntryList { entries }
79    }
80
81    /// <https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-map-by-name-and-type>
82    pub(crate) fn get_entries_by_name_and_type(
83        &self,
84        name: Option<DOMString>,
85        entry_type: Option<EntryType>,
86    ) -> Vec<DomRoot<PerformanceEntry>> {
87        let mut result = self
88            .entries
89            .iter()
90            .filter(|e| {
91                name.as_ref().is_none_or(|name_| *e.name() == *name_) &&
92                    entry_type
93                        .as_ref()
94                        .is_none_or(|type_| e.entry_type() == *type_)
95            })
96            .cloned()
97            .collect::<Vec<DomRoot<PerformanceEntry>>>();
98
99        // Step 6. Sort results's entries in chronological order with respect to startTime
100        result.sort_by(|a, b| {
101            a.start_time()
102                .partial_cmp(&b.start_time())
103                .unwrap_or(Ordering::Equal)
104        });
105
106        // Step 7. Return result.
107        result
108    }
109
110    pub(crate) fn clear_entries_by_name_and_type(
111        &mut self,
112        name: Option<DOMString>,
113        entry_type: EntryType,
114    ) {
115        self.entries.retain(|e| {
116            e.entry_type() != entry_type || name.as_ref().is_some_and(|name_| e.name() != name_)
117        });
118    }
119
120    fn get_last_entry_start_time_with_name_and_type(
121        &self,
122        name: DOMString,
123        entry_type: EntryType,
124    ) -> Option<CrossProcessInstant> {
125        self.entries
126            .iter()
127            .rev()
128            .find(|e| e.entry_type() == entry_type && *e.name() == name)
129            .and_then(|entry| entry.start_time())
130    }
131}
132
133impl IntoIterator for PerformanceEntryList {
134    type Item = DomRoot<PerformanceEntry>;
135    type IntoIter = ::std::vec::IntoIter<DomRoot<PerformanceEntry>>;
136
137    fn into_iter(self) -> Self::IntoIter {
138        self.entries.into_iter()
139    }
140}
141
142#[derive(JSTraceable, MallocSizeOf)]
143struct PerformanceObserver {
144    observer: DomRoot<DOMPerformanceObserver>,
145    entry_types: Vec<EntryType>,
146}
147
148#[dom_struct]
149pub(crate) struct Performance {
150    eventtarget: EventTarget,
151    buffer: DomRefCell<PerformanceEntryList>,
152    observers: DomRefCell<Vec<PerformanceObserver>>,
153    pending_notification_observers_task: Cell<bool>,
154    #[no_trace]
155    /// The `timeOrigin` as described in
156    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-time-origin>.
157    time_origin: CrossProcessInstant,
158    /// <https://w3c.github.io/resource-timing/#performance-resource-timing-buffer-size-limit>
159    /// The max-size of the buffer, set to 0 once the pipeline exits.
160    /// TODO: have one max-size per entry type.
161    resource_timing_buffer_size_limit: Cell<usize>,
162    /// <https://w3c.github.io/resource-timing/#performance-resource-timing-buffer-current-size>
163    resource_timing_buffer_current_size: Cell<usize>,
164    /// <https://w3c.github.io/resource-timing/#performance-resource-timing-buffer-full-event-pending-flag>
165    resource_timing_buffer_pending_full_event: Cell<bool>,
166    /// <https://w3c.github.io/resource-timing/#performance-resource-timing-secondary-buffer>
167    resource_timing_secondary_entries: DomRefCell<VecDeque<DomRoot<PerformanceEntry>>>,
168}
169
170impl Performance {
171    fn new_inherited(time_origin: CrossProcessInstant) -> Performance {
172        Performance {
173            eventtarget: EventTarget::new_inherited(),
174            buffer: DomRefCell::new(PerformanceEntryList::new(Vec::new())),
175            observers: DomRefCell::new(Vec::new()),
176            pending_notification_observers_task: Cell::new(false),
177            time_origin,
178            resource_timing_buffer_size_limit: Cell::new(250),
179            resource_timing_buffer_current_size: Cell::new(0),
180            resource_timing_buffer_pending_full_event: Cell::new(false),
181            resource_timing_secondary_entries: DomRefCell::new(VecDeque::new()),
182        }
183    }
184
185    pub(crate) fn new(
186        global: &GlobalScope,
187        navigation_start: CrossProcessInstant,
188        can_gc: CanGc,
189    ) -> DomRoot<Performance> {
190        reflect_dom_object(
191            Box::new(Performance::new_inherited(navigation_start)),
192            global,
193            can_gc,
194        )
195    }
196
197    pub(crate) fn to_dom_high_res_time_stamp(
198        &self,
199        instant: CrossProcessInstant,
200    ) -> DOMHighResTimeStamp {
201        (instant - self.time_origin).to_dom_high_res_time_stamp()
202    }
203
204    pub(crate) fn maybe_to_dom_high_res_time_stamp(
205        &self,
206        instant: Option<CrossProcessInstant>,
207    ) -> DOMHighResTimeStamp {
208        self.to_dom_high_res_time_stamp(instant.unwrap_or(self.time_origin))
209    }
210
211    /// Clear all buffered performance entries, and disable the buffer.
212    /// Called as part of the window's "clear_js_runtime" workflow,
213    /// performed when exiting a pipeline.
214    pub(crate) fn clear_and_disable_performance_entry_buffer(&self) {
215        let mut buffer = self.buffer.borrow_mut();
216        buffer.entries.clear();
217        self.resource_timing_buffer_size_limit.set(0);
218    }
219
220    // Add a PerformanceObserver to the list of observers with a set of
221    // observed entry types.
222
223    pub(crate) fn add_multiple_type_observer(
224        &self,
225        observer: &DOMPerformanceObserver,
226        entry_types: Vec<EntryType>,
227    ) {
228        let mut observers = self.observers.borrow_mut();
229        match observers.iter().position(|o| *o.observer == *observer) {
230            // If the observer is already in the list, we only update the observed
231            // entry types.
232            Some(p) => observers[p].entry_types = entry_types,
233            // Otherwise, we create and insert the new PerformanceObserver.
234            None => observers.push(PerformanceObserver {
235                observer: DomRoot::from_ref(observer),
236                entry_types,
237            }),
238        };
239    }
240
241    pub(crate) fn add_single_type_observer(
242        &self,
243        observer: &DOMPerformanceObserver,
244        entry_type: EntryType,
245        buffered: bool,
246    ) {
247        if buffered {
248            let buffer = self.buffer.borrow();
249            let mut new_entries = buffer.get_entries_by_name_and_type(None, Some(entry_type));
250            if !new_entries.is_empty() {
251                let mut obs_entries = observer.entries();
252                obs_entries.append(&mut new_entries);
253                observer.set_entries(obs_entries);
254            }
255
256            if !self.pending_notification_observers_task.get() {
257                self.pending_notification_observers_task.set(true);
258                let global = &self.global();
259                let owner = Trusted::new(&*global.performance());
260                self.global()
261                    .task_manager()
262                    .performance_timeline_task_source()
263                    .queue(task!(notify_performance_observers: move || {
264                        owner.root().notify_observers();
265                    }));
266            }
267        }
268        let mut observers = self.observers.borrow_mut();
269        match observers.iter().position(|o| *o.observer == *observer) {
270            // If the observer is already in the list, we only update
271            // the observed entry types.
272            Some(p) => {
273                // Append the type if not already present, otherwise do nothing
274                if !observers[p].entry_types.contains(&entry_type) {
275                    observers[p].entry_types.push(entry_type)
276                }
277            },
278            // Otherwise, we create and insert the new PerformanceObserver.
279            None => observers.push(PerformanceObserver {
280                observer: DomRoot::from_ref(observer),
281                entry_types: vec![entry_type],
282            }),
283        };
284    }
285
286    /// Remove a PerformanceObserver from the list of observers.
287    pub(crate) fn remove_observer(&self, observer: &DOMPerformanceObserver) {
288        let mut observers = self.observers.borrow_mut();
289        let index = match observers.iter().position(|o| &(*o.observer) == observer) {
290            Some(p) => p,
291            None => return,
292        };
293
294        observers.remove(index);
295    }
296
297    /// Queue a notification for each performance observer interested in
298    /// this type of performance entry and queue a low priority task to
299    /// notify the observers if no other notification task is already queued.
300    ///
301    /// Algorithm spec:
302    /// <https://w3c.github.io/performance-timeline/#queue-a-performanceentry>
303    /// Also this algorithm has been extented according to :
304    /// <https://w3c.github.io/resource-timing/#sec-extensions-performance-interface>
305    pub(crate) fn queue_entry(&self, entry: &PerformanceEntry) -> Option<usize> {
306        // https://w3c.github.io/performance-timeline/#dfn-determine-eligibility-for-adding-a-performance-entry
307        if entry.entry_type() == EntryType::Resource && !self.should_queue_resource_entry(entry) {
308            return None;
309        }
310
311        // Steps 1-3.
312        // Add the performance entry to the list of performance entries that have not
313        // been notified to each performance observer owner, filtering the ones it's
314        // interested in.
315        for observer in self
316            .observers
317            .borrow()
318            .iter()
319            .filter(|o| o.entry_types.contains(&entry.entry_type()))
320        {
321            observer.observer.queue_entry(entry);
322        }
323
324        // Step 4.
325        // add the new entry to the buffer.
326        self.buffer
327            .borrow_mut()
328            .entries
329            .push(DomRoot::from_ref(entry));
330
331        let entry_last_index = self.buffer.borrow_mut().entries.len() - 1;
332
333        // Step 5.
334        // If there is already a queued notification task, we just bail out.
335        if self.pending_notification_observers_task.get() {
336            return None;
337        }
338
339        // Step 6.
340        // Queue a new notification task.
341        self.pending_notification_observers_task.set(true);
342
343        let global = &self.global();
344        let owner = Trusted::new(&*global.performance());
345        self.global()
346            .task_manager()
347            .performance_timeline_task_source()
348            .queue(task!(notify_performance_observers: move || {
349                owner.root().notify_observers();
350            }));
351
352        Some(entry_last_index)
353    }
354
355    /// Observers notifications task.
356    ///
357    /// Algorithm spec (step 7):
358    /// <https://w3c.github.io/performance-timeline/#queue-a-performanceentry>
359    pub(crate) fn notify_observers(&self) {
360        // Step 7.1.
361        self.pending_notification_observers_task.set(false);
362
363        // Step 7.2.
364        // We have to operate over a copy of the performance observers to avoid
365        // the risk of an observer's callback modifying the list of registered
366        // observers. This is a shallow copy, so observers can
367        // disconnect themselves by using the argument of their own callback.
368        let observers: Vec<DomRoot<DOMPerformanceObserver>> = self
369            .observers
370            .borrow()
371            .iter()
372            .map(|o| DomRoot::from_ref(&*o.observer))
373            .collect();
374
375        // Step 7.3.
376        for o in observers.iter() {
377            o.notify(CanGc::deprecated_note());
378        }
379    }
380
381    /// <https://w3c.github.io/resource-timing/#performance-can-add-resource-timing-entry>
382    fn can_add_resource_timing_entry(&self) -> bool {
383        // Step 1. If resource timing buffer current size is smaller than resource timing buffer size limit, return true.
384        // Step 2. Return false.
385        self.resource_timing_buffer_current_size.get() <
386            self.resource_timing_buffer_size_limit.get()
387    }
388
389    /// <https://w3c.github.io/resource-timing/#dfn-copy-secondary-buffer>
390    fn copy_secondary_resource_timing_buffer(&self) {
391        // Step 1. While resource timing secondary buffer is not empty and can add resource timing entry returns true, run the following substeps:
392        while self.can_add_resource_timing_entry() {
393            // Step 1.1. Let entry be the oldest PerformanceResourceTiming in resource timing secondary buffer.
394            let entry = self
395                .resource_timing_secondary_entries
396                .borrow_mut()
397                .pop_front();
398            if let Some(ref entry) = entry {
399                // Step 1.2. Add entry to the end of performance entry buffer.
400                self.buffer
401                    .borrow_mut()
402                    .entries
403                    .push(DomRoot::from_ref(entry));
404                // Step 1.3. Increment resource timing buffer current size by 1.
405                self.resource_timing_buffer_current_size
406                    .set(self.resource_timing_buffer_current_size.get() + 1);
407                // Step 1.4. Remove entry from resource timing secondary buffer.
408                // Step 1.5. Decrement resource timing secondary buffer current size by 1.
409                // Handled by popping the entry earlier.
410            } else {
411                break;
412            }
413        }
414    }
415
416    /// <https://w3c.github.io/resource-timing/#dfn-fire-a-buffer-full-event>
417    fn fire_buffer_full_event(&self, cx: &mut js::context::JSContext) {
418        while !self.resource_timing_secondary_entries.borrow().is_empty() {
419            let no_of_excess_entries_before = self.resource_timing_secondary_entries.borrow().len();
420
421            if !self.can_add_resource_timing_entry() {
422                self.upcast::<EventTarget>()
423                    .fire_event(cx, atom!("resourcetimingbufferfull"));
424            }
425            self.copy_secondary_resource_timing_buffer();
426            let no_of_excess_entries_after = self.resource_timing_secondary_entries.borrow().len();
427            if no_of_excess_entries_before <= no_of_excess_entries_after {
428                self.resource_timing_secondary_entries.borrow_mut().clear();
429                break;
430            }
431        }
432        self.resource_timing_buffer_pending_full_event.set(false);
433    }
434
435    /// <https://w3c.github.io/resource-timing/#dfn-add-a-performanceresourcetiming-entry>
436    fn should_queue_resource_entry(&self, entry: &PerformanceEntry) -> bool {
437        // Step 1. If can add resource timing entry returns true and resource timing buffer full event pending flag is false, run the following substeps:
438        if !self.resource_timing_buffer_pending_full_event.get() {
439            if self.can_add_resource_timing_entry() {
440                // Step 1.a.  Add new entry to the performance entry buffer.
441                //   This is done in queue_entry, which calls this method.
442                // Step 1.b. Increase resource timing buffer current size by 1.
443                self.resource_timing_buffer_current_size
444                    .set(self.resource_timing_buffer_current_size.get() + 1);
445                // Step 1.c. Return.
446                return true;
447            }
448
449            // Step 2.a. Set resource timing buffer full event pending flag to true.
450            self.resource_timing_buffer_pending_full_event.set(true);
451            // Step 2.b. Queue a task on the performance timeline task source to run fire a buffer full event.
452            let performance = Trusted::new(self);
453            self.global()
454                .task_manager()
455                .performance_timeline_task_source()
456                .queue(task!(fire_a_buffer_full_event: move |cx| {
457                    performance.root().fire_buffer_full_event(cx);
458                }));
459        }
460
461        // Step 3. Add new entry to the resource timing secondary buffer.
462        self.resource_timing_secondary_entries
463            .borrow_mut()
464            .push_back(DomRoot::from_ref(entry));
465
466        // Step 4. Increase resource timing secondary buffer current size by 1.
467        //   This is tracked automatically via `.len()`.
468        false
469    }
470
471    pub(crate) fn update_entry(&self, index: usize, entry: &PerformanceEntry) {
472        if let Some(e) = self.buffer.borrow_mut().entries.get_mut(index) {
473            *e = DomRoot::from_ref(entry);
474        }
475    }
476
477    /// <https://w3c.github.io/user-timing/#convert-a-name-to-a-timestamp>
478    fn convert_a_name_to_a_timestamp(&self, name: &str) -> Fallible<CrossProcessInstant> {
479        // Step 1. If the global object is not a Window object, throw a TypeError.
480        let Some(window) = DomRoot::downcast::<Window>(self.global()) else {
481            return Err(Error::Type(cformat!(
482                "Cannot use {name} from non-window global"
483            )));
484        };
485
486        // Step 2. If name is navigationStart, return 0.
487        if name == "navigationStart" {
488            return Ok(self.time_origin);
489        }
490
491        // Step 3. Let startTime be the value of navigationStart in the PerformanceTiming interface.
492        // FIXME: We don't implement this value yet, so we assume it's zero (and then we don't need it at all)
493
494        // Step 4. Let endTime be the value of name in the PerformanceTiming interface.
495        // NOTE: We store all performance values on the document
496        let document = window.Document();
497        let end_time = match name {
498            "unloadEventStart" => document.get_unload_event_start(),
499            "unloadEventEnd" => document.get_unload_event_end(),
500            "domInteractive" => document.get_dom_interactive(),
501            "domContentLoadedEventStart" => document.get_dom_content_loaded_event_start(),
502            "domContentLoadedEventEnd" => document.get_dom_content_loaded_event_end(),
503            "domComplete" => document.get_dom_complete(),
504            "loadEventStart" => document.get_load_event_start(),
505            "loadEventEnd" => document.get_load_event_end(),
506            other => {
507                if cfg!(debug_assertions) {
508                    unreachable!("{other:?} is not the name of a timestamp");
509                }
510                return Err(Error::Operation(None));
511            },
512        };
513        // Step 5. If endTime is 0, throw an InvalidAccessError.
514        let Some(end_time) = end_time else {
515            return Err(Error::InvalidAccess(Some(format!(
516                "{name} hasn't happened yet"
517            ))));
518        };
519
520        // Step 6. Return result of subtracting startTime from endTime.
521        Ok(end_time)
522    }
523
524    /// <https://w3c.github.io/user-timing/#convert-a-mark-to-a-timestamp>
525    fn convert_a_mark_to_a_timestamp(
526        &self,
527        mark: &StringOrDouble,
528    ) -> Fallible<CrossProcessInstant> {
529        match mark {
530            StringOrDouble::String(name) => {
531                // Step 1. If mark is a DOMString and it has the same name as a read only attribute in the
532                // PerformanceTiming interface, let end time be the value returned by running the convert
533                // a name to a timestamp algorithm with name set to the value of mark.
534                // TODO: These aren't all fields because servo doesn't support some of them yet
535                if matches!(
536                    &*name.str(),
537                    "navigationStart" |
538                        "unloadEventStart" |
539                        "unloadEventEnd" |
540                        "domInteractive" |
541                        "domContentLoadedEventStart" |
542                        "domContentLoadedEventEnd" |
543                        "domComplete" |
544                        "loadEventStart" |
545                        "loadEventEnd"
546                ) {
547                    self.convert_a_name_to_a_timestamp(&name.str())
548                }
549                // Step 2. Otherwise, if mark is a DOMString, let end time be the value of the startTime
550                // attribute from the most recent occurrence of a PerformanceMark object in the performance entry
551                // buffer whose name is mark. If no matching entry is found, throw a SyntaxError.
552                else {
553                    self.buffer
554                        .borrow()
555                        .get_last_entry_start_time_with_name_and_type(name.clone(), EntryType::Mark)
556                        .ok_or(Error::Syntax(Some(format!(
557                            "No PerformanceMark named {name} exists"
558                        ))))
559                }
560            },
561            // Step 3. Otherwise, if mark is a DOMHighResTimeStamp:
562            StringOrDouble::Double(timestamp) => {
563                // Step 3.1 If mark is negative, throw a TypeError.
564                if timestamp.is_sign_negative() {
565                    return Err(Error::Type(c"Time stamps must not be negative".to_owned()));
566                }
567
568                // Step 3.2 Otherwise, let end time be mark.
569                // NOTE: I think the spec wants us to return the value.
570                Ok(self.time_origin + Duration::milliseconds(timestamp.round() as i64))
571            },
572        }
573    }
574}
575
576impl PerformanceMethods<crate::DomTypeHolder> for Performance {
577    /// <https://w3c.github.io/navigation-timing/#dom-performance-timing>
578    fn Timing(&self) -> DomRoot<PerformanceNavigationTiming> {
579        let entries = self.GetEntriesByType(DOMString::from("navigation"));
580        if !entries.is_empty() {
581            return DomRoot::from_ref(
582                entries[0]
583                    .downcast::<PerformanceNavigationTiming>()
584                    .unwrap(),
585            );
586        }
587        unreachable!("Are we trying to expose Performance.timing in workers?");
588    }
589
590    /// <https://w3c.github.io/navigation-timing/#dom-performance-navigation>
591    fn Navigation(&self) -> DomRoot<PerformanceNavigation> {
592        PerformanceNavigation::new(&self.global(), CanGc::deprecated_note())
593    }
594
595    /// <https://w3c.github.io/hr-time/#dom-performance-now>
596    fn Now(&self) -> DOMHighResTimeStamp {
597        self.to_dom_high_res_time_stamp(CrossProcessInstant::now())
598    }
599
600    /// <https://www.w3.org/TR/hr-time-2/#dom-performance-timeorigin>
601    fn TimeOrigin(&self) -> DOMHighResTimeStamp {
602        (self.time_origin - CrossProcessInstant::epoch()).to_dom_high_res_time_stamp()
603    }
604
605    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentries>
606    fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> {
607        // > Returns a PerformanceEntryList object returned by the filter buffer map by name and type
608        // > algorithm with name and type set to null.
609        self.buffer
610            .borrow()
611            .get_entries_by_name_and_type(None, None)
612    }
613
614    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbytype>
615    fn GetEntriesByType(&self, entry_type: DOMString) -> Vec<DomRoot<PerformanceEntry>> {
616        let Ok(entry_type) = EntryType::try_from(&*entry_type.str()) else {
617            return Vec::new();
618        };
619        self.buffer
620            .borrow()
621            .get_entries_by_name_and_type(None, Some(entry_type))
622    }
623
624    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbyname>
625    fn GetEntriesByName(
626        &self,
627        name: DOMString,
628        entry_type: Option<DOMString>,
629    ) -> Vec<DomRoot<PerformanceEntry>> {
630        let entry_type = match entry_type {
631            Some(entry_type) => {
632                let Ok(entry_type) = EntryType::try_from(&*entry_type.str()) else {
633                    return Vec::new();
634                };
635                Some(entry_type)
636            },
637            None => None,
638        };
639        self.buffer
640            .borrow()
641            .get_entries_by_name_and_type(Some(name), entry_type)
642    }
643
644    /// <https://w3c.github.io/user-timing/#dom-performance-mark>
645    fn Mark(
646        &self,
647        cx: &mut JSContext,
648        mark_name: DOMString,
649        mark_options: RootedTraceableBox<PerformanceMarkOptions>,
650    ) -> Fallible<DomRoot<PerformanceMark>> {
651        // Step 1. Run the PerformanceMark constructor and let entry be the newly created object.
652        // <https://w3c.github.io/user-timing/#the-performancemark-constructor>
653        // The PerformanceMark constructor must run the following steps:
654        // Step 1.1. If the current global object is a Window object and markName uses the same name
655        // as a read only attribute in the PerformanceTiming interface, throw a SyntaxError.
656        let global = self.global();
657        if global.is::<Window>() && INVALID_ENTRY_NAMES.contains(&&*mark_name.str()) {
658            return Err(Error::Syntax(None));
659        }
660        // Step 1.2 - 1.4. Note: These are handled by the PerformanceMark constructor below.
661
662        // Step 1.5. Set entry’s startTime attribute as follows:
663        let start_time = match mark_options.startTime {
664            // Step 1.5.1. If markOptions’s startTime member exists, then:
665            Some(start_time) => {
666                // Step 1.5.1.1. If markOptions’s startTime is negative, throw a TypeError.
667                if start_time.is_sign_negative() {
668                    return Err(Error::Type(c"startTime must not be negative".to_owned()));
669                }
670                // Step 1.5.1.2. Otherwise, set entry’s startTime to the value of markOptions’s startTime.
671                self.time_origin + Duration::microseconds(start_time.mul_add(1000.0, 0.0) as i64)
672            },
673            // Step 1.5.2. Otherwise, set it to the value that would be returned by the Performance object’s now() method.
674            None => CrossProcessInstant::now(),
675        };
676
677        // Step 1.6. Set entry’s duration attribute to 0.
678        let entry = PerformanceMark::new(
679            &global,
680            mark_name,
681            start_time,
682            Duration::ZERO,
683            Default::default(),
684        );
685
686        // Step 1.7. If markOptions’s detail is null, set entry’s detail to null.
687        rooted!(&in(cx) let mut detail = NullValue());
688
689        // Step 1.8 Otherwise:
690        if !mark_options.detail.get().is_null_or_undefined() {
691            // Step 1.8.1. Let record be the result of calling the StructuredSerialize algorithm on markOptions’s detail.
692            let record = structuredclone::write(cx.into(), mark_options.detail.handle(), None)?;
693
694            // Step 1.8.2. Set entry’s detail to the result of calling the StructuredDeserialize algorithm on record and the current realm.
695            structuredclone::read(
696                &self.global(),
697                record,
698                detail.handle_mut(),
699                CanGc::from_cx(cx),
700            )?;
701        }
702        entry.set_detail(detail.handle());
703
704        // Step 2. Queue a PerformanceEntry entry.
705        // Step 3. Add entry to the performance entry buffer. (This is done in queue_entry itself)
706        self.queue_entry(entry.upcast::<PerformanceEntry>());
707
708        // Step 4. Return entry.
709        Ok(entry)
710    }
711
712    /// <https://w3c.github.io/user-timing/#dom-performance-clearmarks>
713    fn ClearMarks(&self, mark_name: Option<DOMString>) {
714        self.buffer
715            .borrow_mut()
716            .clear_entries_by_name_and_type(mark_name, EntryType::Mark);
717    }
718
719    /// <https://w3c.github.io/user-timing/#dom-performance-measure>
720    fn Measure(
721        &self,
722        measure_name: DOMString,
723        start_or_measure_options: StringOrPerformanceMeasureOptions,
724        end_mark: Option<DOMString>,
725    ) -> Fallible<DomRoot<PerformanceMeasure>> {
726        // Step 1. If startOrMeasureOptions is a PerformanceMeasureOptions object and at least one of start,
727        // end, duration, and detail exist, run the following checks:
728        if let StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) =
729            &start_or_measure_options
730        {
731            if options.start.is_some() || options.duration.is_some() || options.end.is_some() {
732                // Step 1.1 If endMark is given, throw a TypeError.
733                if end_mark.is_some() {
734                    return Err(Error::Type(
735                        c"Must not provide endMark if PerformanceMeasureOptions is also provided"
736                            .to_owned(),
737                    ));
738                }
739
740                // Step 1.2 If startOrMeasureOptions’s start and end members are both omitted, throw a TypeError.
741                if options.start.is_none() && options.end.is_none() {
742                    return Err(Error::Type(c"Either 'start' or 'end' member of PerformanceMeasureOptions must be provided".to_owned()));
743                }
744
745                // Step 1.3 If startOrMeasureOptions’s start, duration, and end members all exist, throw a TypeError.
746                if options.start.is_some() && options.duration.is_some() && options.end.is_some() {
747                    return Err(Error::Type(c"Either 'start' or 'end' or 'duration' member of PerformanceMeasureOptions must be omitted".to_owned()));
748                }
749            }
750        }
751
752        // Step 2. Compute end time as follows:
753        // Step 2.1 If endMark is given, let end time be the value returned
754        // by running the convert a mark to a timestamp algorithm passing in endMark.
755        let end_time = if let Some(end_mark) = end_mark {
756            self.convert_a_mark_to_a_timestamp(&StringOrDouble::String(end_mark))?
757        } else {
758            match &start_or_measure_options {
759                StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) => {
760                    // Step 2.2 Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object,
761                    // and if its end member exists, let end time be the value returned by running the
762                    // convert a mark to a timestamp algorithm passing in startOrMeasureOptions’s end.
763                    if let Some(end) = &options.end {
764                        self.convert_a_mark_to_a_timestamp(end)?
765                    }
766                    // Step 2.3 Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object,
767                    // and if its start and duration members both exist:
768                    else if let Some((start, duration)) =
769                        options.start.as_ref().zip(options.duration)
770                    {
771                        // Step 2.3.1 Let start be the value returned by running the convert a mark to a timestamp
772                        // algorithm passing in start.
773                        let start = self.convert_a_mark_to_a_timestamp(start)?;
774
775                        // Step 2.3.2 Let duration be the value returned by running the convert a mark to a timestamp
776                        // algorithm passing in duration.
777                        let duration = self
778                            .convert_a_mark_to_a_timestamp(&StringOrDouble::Double(duration))? -
779                            self.time_origin;
780
781                        // Step 2.3.3 Let end time be start plus duration.
782                        start + duration
783                    } else {
784                        // Step 2.4 Otherwise, let end time be the value that would be returned by the
785                        // Performance object’s now() method.
786                        CrossProcessInstant::now()
787                    }
788                },
789                _ => {
790                    // Step 2.4 Otherwise, let end time be the value that would be returned by the
791                    // Performance object’s now() method.
792                    CrossProcessInstant::now()
793                },
794            }
795        };
796
797        // Step 3. Compute start time as follows:
798        let start_time = match start_or_measure_options {
799            StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) => {
800                // Step 3.1 If startOrMeasureOptions is a PerformanceMeasureOptions object, and if its start member exists,
801                // let start time be the value returned by running the convert a mark to a timestamp algorithm passing in
802                // startOrMeasureOptions’s start.
803                if let Some(start) = &options.start {
804                    self.convert_a_mark_to_a_timestamp(start)?
805                }
806                // Step 3.2 Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object,
807                // and if its duration and end members both exist:
808                else if let Some((duration, end)) = options.duration.zip(options.end.as_ref()) {
809                    // Step 3.2.1 Let duration be the value returned by running the convert a mark to a timestamp
810                    // algorithm passing in duration.
811                    let duration = self
812                        .convert_a_mark_to_a_timestamp(&StringOrDouble::Double(duration))? -
813                        self.time_origin;
814
815                    // Step 3.2.2 Let end be the value returned by running the convert a mark to a timestamp algorithm
816                    // passing in end.
817                    let end = self.convert_a_mark_to_a_timestamp(end)?;
818
819                    // Step 3.3.3 Let start time be end minus duration.
820                    end - duration
821                }
822                // Step 3.4 Otherwise, let start time be 0.
823                else {
824                    self.time_origin
825                }
826            },
827            StringOrPerformanceMeasureOptions::String(string) => {
828                // Step 3.3 Otherwise, if startOrMeasureOptions is a DOMString, let start time be the value returned
829                // by running the convert a mark to a timestamp algorithm passing in startOrMeasureOptions.
830                self.convert_a_mark_to_a_timestamp(&StringOrDouble::String(string))?
831            },
832        };
833
834        // Step 4. Create a new PerformanceMeasure object (entry) with this’s relevant realm.
835        // Step 5. Set entry’s name attribute to measureName.
836        // Step 6. Set entry’s entryType attribute to DOMString "measure".
837        // Step 7. Set entry’s startTime attribute to start time.
838        // Step 8. Set entry’s duration attribute to the duration from start time to end time.
839        // The resulting duration value MAY be negative.
840        // TODO: Step 9. Set entry’s detail attribute as follows:
841        let entry = PerformanceMeasure::new(
842            &self.global(),
843            measure_name,
844            start_time,
845            end_time - start_time,
846            Default::default(),
847        );
848
849        // Step 10. Queue a PerformanceEntry entry.
850        // Step 11. Add entry to the performance entry buffer. (This is done in queue_entry itself)
851        self.queue_entry(entry.upcast::<PerformanceEntry>());
852
853        // Step 12. Return entry.
854        Ok(entry)
855    }
856
857    /// <https://w3c.github.io/user-timing/#dom-performance-clearmeasures>
858    fn ClearMeasures(&self, measure_name: Option<DOMString>) {
859        self.buffer
860            .borrow_mut()
861            .clear_entries_by_name_and_type(measure_name, EntryType::Measure);
862    }
863    /// <https://w3c.github.io/resource-timing/#dom-performance-clearresourcetimings>
864    fn ClearResourceTimings(&self) {
865        self.buffer
866            .borrow_mut()
867            .clear_entries_by_name_and_type(None, EntryType::Resource);
868        self.resource_timing_buffer_current_size.set(0);
869    }
870
871    /// <https://w3c.github.io/resource-timing/#performance-setresourcetimingbuffersize>
872    fn SetResourceTimingBufferSize(&self, max_size: u32) {
873        self.resource_timing_buffer_size_limit
874            .set(max_size as usize);
875    }
876
877    // https://w3c.github.io/resource-timing/#dom-performance-onresourcetimingbufferfull
878    event_handler!(
879        resourcetimingbufferfull,
880        GetOnresourcetimingbufferfull,
881        SetOnresourcetimingbufferfull
882    );
883}
884
885pub(crate) trait ToDOMHighResTimeStamp {
886    fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp;
887}
888
889impl ToDOMHighResTimeStamp for Duration {
890    fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp {
891        // https://www.w3.org/TR/hr-time-2/#clock-resolution
892        // We need a granularity no finer than 5 microseconds. 5 microseconds isn't an
893        // exactly representable f64 so WPT tests might occasionally corner-case on
894        // rounding.  web-platform-tests/wpt#21526 wants us to use an integer number of
895        // microseconds; the next divisor of milliseconds up from 5 microseconds is 10.
896        let microseconds_rounded = (self.whole_microseconds() as f64 / 10.).floor() * 10.;
897        Finite::wrap(microseconds_rounded / 1000.)
898    }
899}