Skip to main content

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::cell::DomRefCell;
13use script_bindings::cformat;
14use script_bindings::codegen::GenericBindings::PerformanceBinding::PerformanceMarkOptions;
15use script_bindings::codegen::GenericBindings::PerformanceMarkBinding::PerformanceMarkMethods;
16use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
17use script_bindings::codegen::GenericUnionTypes::StringOrPerformanceMeasureOptions;
18use script_bindings::reflector::reflect_dom_object;
19use servo_base::cross_process_instant::CrossProcessInstant;
20use time::Duration;
21
22use super::performanceentry::{EntryType, PerformanceEntry};
23use super::performancemark::PerformanceMark;
24use super::performancemeasure::PerformanceMeasure;
25use super::performancenavigation::PerformanceNavigation;
26use super::performancenavigationtiming::PerformanceNavigationTiming;
27use super::performanceobserver::PerformanceObserver as DOMPerformanceObserver;
28use crate::dom::PERFORMANCE_TIMING_ATTRIBUTES;
29use crate::dom::bindings::codegen::Bindings::PerformanceBinding::{
30    DOMHighResTimeStamp, PerformanceEntryList as DOMPerformanceEntryList, PerformanceMethods,
31};
32use crate::dom::bindings::codegen::UnionTypes::StringOrDouble;
33use crate::dom::bindings::error::{Error, Fallible};
34use crate::dom::bindings::inheritance::Castable;
35use crate::dom::bindings::num::Finite;
36use crate::dom::bindings::refcounted::Trusted;
37use crate::dom::bindings::reflector::DomGlobal;
38use crate::dom::bindings::root::DomRoot;
39use crate::dom::bindings::str::DOMString;
40use crate::dom::bindings::structuredclone;
41use crate::dom::bindings::trace::RootedTraceableBox;
42use crate::dom::eventtarget::EventTarget;
43use crate::dom::globalscope::GlobalScope;
44use crate::dom::window::Window;
45use crate::script_runtime::CanGc;
46
47/// Implementation of a list of PerformanceEntry items shared by the
48/// Performance and PerformanceObserverEntryList interfaces implementations.
49#[derive(JSTraceable, MallocSizeOf)]
50pub(crate) struct PerformanceEntryList {
51    /// <https://w3c.github.io/performance-timeline/#dfn-performance-entry-buffer>
52    entries: DOMPerformanceEntryList,
53}
54
55impl PerformanceEntryList {
56    pub(crate) fn new(entries: DOMPerformanceEntryList) -> Self {
57        PerformanceEntryList { entries }
58    }
59
60    /// <https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-map-by-name-and-type>
61    pub(crate) fn get_entries_by_name_and_type(
62        &self,
63        name: Option<DOMString>,
64        entry_type: Option<EntryType>,
65    ) -> Vec<DomRoot<PerformanceEntry>> {
66        let mut result = self
67            .entries
68            .iter()
69            .filter(|e| {
70                name.as_ref().is_none_or(|name_| *e.name() == *name_) &&
71                    entry_type
72                        .as_ref()
73                        .is_none_or(|type_| e.entry_type() == *type_)
74            })
75            .cloned()
76            .collect::<Vec<DomRoot<PerformanceEntry>>>();
77
78        // Step 6. Sort results's entries in chronological order with respect to startTime
79        result.sort_by(|a, b| {
80            a.start_time()
81                .partial_cmp(&b.start_time())
82                .unwrap_or(Ordering::Equal)
83        });
84
85        // Step 7. Return result.
86        result
87    }
88
89    pub(crate) fn clear_entries_by_name_and_type(
90        &mut self,
91        name: Option<DOMString>,
92        entry_type: EntryType,
93    ) {
94        self.entries.retain(|e| {
95            e.entry_type() != entry_type || name.as_ref().is_some_and(|name_| e.name() != name_)
96        });
97    }
98
99    fn get_last_entry_start_time_with_name_and_type(
100        &self,
101        name: DOMString,
102        entry_type: EntryType,
103    ) -> Option<CrossProcessInstant> {
104        self.entries
105            .iter()
106            .rev()
107            .find(|e| e.entry_type() == entry_type && *e.name() == name)
108            .and_then(|entry| entry.start_time())
109    }
110}
111
112impl IntoIterator for PerformanceEntryList {
113    type Item = DomRoot<PerformanceEntry>;
114    type IntoIter = ::std::vec::IntoIter<DomRoot<PerformanceEntry>>;
115
116    fn into_iter(self) -> Self::IntoIter {
117        self.entries.into_iter()
118    }
119}
120
121#[derive(JSTraceable, MallocSizeOf)]
122struct PerformanceObserver {
123    observer: DomRoot<DOMPerformanceObserver>,
124    entry_types: Vec<EntryType>,
125}
126
127#[dom_struct]
128pub(crate) struct Performance {
129    eventtarget: EventTarget,
130    buffer: DomRefCell<PerformanceEntryList>,
131    observers: DomRefCell<Vec<PerformanceObserver>>,
132    pending_notification_observers_task: Cell<bool>,
133    #[no_trace]
134    /// The `timeOrigin` as described in
135    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-time-origin>.
136    time_origin: CrossProcessInstant,
137    /// <https://w3c.github.io/resource-timing/#performance-resource-timing-buffer-size-limit>
138    /// The max-size of the buffer, set to 0 once the pipeline exits.
139    /// TODO: have one max-size per entry type.
140    resource_timing_buffer_size_limit: Cell<usize>,
141    /// <https://w3c.github.io/resource-timing/#performance-resource-timing-buffer-current-size>
142    resource_timing_buffer_current_size: Cell<usize>,
143    /// <https://w3c.github.io/resource-timing/#performance-resource-timing-buffer-full-event-pending-flag>
144    resource_timing_buffer_pending_full_event: Cell<bool>,
145    /// <https://w3c.github.io/resource-timing/#performance-resource-timing-secondary-buffer>
146    resource_timing_secondary_entries: DomRefCell<VecDeque<DomRoot<PerformanceEntry>>>,
147}
148
149impl Performance {
150    fn new_inherited(time_origin: CrossProcessInstant) -> Performance {
151        Performance {
152            eventtarget: EventTarget::new_inherited(),
153            buffer: DomRefCell::new(PerformanceEntryList::new(Vec::new())),
154            observers: DomRefCell::new(Vec::new()),
155            pending_notification_observers_task: Cell::new(false),
156            time_origin,
157            resource_timing_buffer_size_limit: Cell::new(250),
158            resource_timing_buffer_current_size: Cell::new(0),
159            resource_timing_buffer_pending_full_event: Cell::new(false),
160            resource_timing_secondary_entries: DomRefCell::new(VecDeque::new()),
161        }
162    }
163
164    pub(crate) fn new(
165        global: &GlobalScope,
166        navigation_start: CrossProcessInstant,
167        can_gc: CanGc,
168    ) -> DomRoot<Performance> {
169        reflect_dom_object(
170            Box::new(Performance::new_inherited(navigation_start)),
171            global,
172            can_gc,
173        )
174    }
175
176    pub(crate) fn time_origin(&self) -> CrossProcessInstant {
177        self.time_origin
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 |cx| {
247                        owner.root().notify_observers(cx);
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 observer in self
299            .observers
300            .borrow()
301            .iter()
302            .filter(|o| o.entry_types.contains(&entry.entry_type()))
303        {
304            observer.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 |cx| {
332                owner.root().notify_observers(cx);
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    fn notify_observers(&self, cx: &mut JSContext) {
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(cx);
361        }
362    }
363
364    /// <https://w3c.github.io/resource-timing/#performance-can-add-resource-timing-entry>
365    fn can_add_resource_timing_entry(&self) -> bool {
366        // Step 1. If resource timing buffer current size is smaller than resource timing buffer size limit, return true.
367        // Step 2. Return false.
368        self.resource_timing_buffer_current_size.get() <
369            self.resource_timing_buffer_size_limit.get()
370    }
371
372    /// <https://w3c.github.io/resource-timing/#dfn-copy-secondary-buffer>
373    fn copy_secondary_resource_timing_buffer(&self) {
374        // Step 1. While resource timing secondary buffer is not empty and can add resource timing entry returns true, run the following substeps:
375        while self.can_add_resource_timing_entry() {
376            // Step 1.1. Let entry be the oldest PerformanceResourceTiming in resource timing secondary buffer.
377            let entry = self
378                .resource_timing_secondary_entries
379                .borrow_mut()
380                .pop_front();
381            if let Some(ref entry) = entry {
382                // Step 1.2. Add entry to the end of performance entry buffer.
383                self.buffer
384                    .borrow_mut()
385                    .entries
386                    .push(DomRoot::from_ref(entry));
387                // Step 1.3. Increment resource timing buffer current size by 1.
388                self.resource_timing_buffer_current_size
389                    .set(self.resource_timing_buffer_current_size.get() + 1);
390                // Step 1.4. Remove entry from resource timing secondary buffer.
391                // Step 1.5. Decrement resource timing secondary buffer current size by 1.
392                // Handled by popping the entry earlier.
393            } else {
394                break;
395            }
396        }
397    }
398
399    /// <https://w3c.github.io/resource-timing/#dfn-fire-a-buffer-full-event>
400    fn fire_buffer_full_event(&self, cx: &mut js::context::JSContext) {
401        while !self.resource_timing_secondary_entries.borrow().is_empty() {
402            let no_of_excess_entries_before = self.resource_timing_secondary_entries.borrow().len();
403
404            if !self.can_add_resource_timing_entry() {
405                self.upcast::<EventTarget>()
406                    .fire_event(cx, atom!("resourcetimingbufferfull"));
407            }
408            self.copy_secondary_resource_timing_buffer();
409            let no_of_excess_entries_after = self.resource_timing_secondary_entries.borrow().len();
410            if no_of_excess_entries_before <= no_of_excess_entries_after {
411                self.resource_timing_secondary_entries.borrow_mut().clear();
412                break;
413            }
414        }
415        self.resource_timing_buffer_pending_full_event.set(false);
416    }
417
418    /// <https://w3c.github.io/resource-timing/#dfn-add-a-performanceresourcetiming-entry>
419    fn should_queue_resource_entry(&self, entry: &PerformanceEntry) -> bool {
420        // Step 1. If can add resource timing entry returns true and resource timing buffer full event pending flag is false, run the following substeps:
421        if !self.resource_timing_buffer_pending_full_event.get() {
422            if self.can_add_resource_timing_entry() {
423                // Step 1.a.  Add new entry to the performance entry buffer.
424                //   This is done in queue_entry, which calls this method.
425                // Step 1.b. Increase resource timing buffer current size by 1.
426                self.resource_timing_buffer_current_size
427                    .set(self.resource_timing_buffer_current_size.get() + 1);
428                // Step 1.c. Return.
429                return true;
430            }
431
432            // Step 2.a. Set resource timing buffer full event pending flag to true.
433            self.resource_timing_buffer_pending_full_event.set(true);
434            // Step 2.b. Queue a task on the performance timeline task source to run fire a buffer full event.
435            let performance = Trusted::new(self);
436            self.global()
437                .task_manager()
438                .performance_timeline_task_source()
439                .queue(task!(fire_a_buffer_full_event: move |cx| {
440                    performance.root().fire_buffer_full_event(cx);
441                }));
442        }
443
444        // Step 3. Add new entry to the resource timing secondary buffer.
445        self.resource_timing_secondary_entries
446            .borrow_mut()
447            .push_back(DomRoot::from_ref(entry));
448
449        // Step 4. Increase resource timing secondary buffer current size by 1.
450        //   This is tracked automatically via `.len()`.
451        false
452    }
453
454    pub(crate) fn update_entry(&self, index: usize, entry: &PerformanceEntry) {
455        if let Some(e) = self.buffer.borrow_mut().entries.get_mut(index) {
456            *e = DomRoot::from_ref(entry);
457        }
458    }
459
460    /// <https://w3c.github.io/user-timing/#convert-a-name-to-a-timestamp>
461    fn convert_a_name_to_a_timestamp(&self, name: &str) -> Fallible<CrossProcessInstant> {
462        // Step 1. If the global object is not a Window object, throw a TypeError.
463        let Some(window) = DomRoot::downcast::<Window>(self.global()) else {
464            return Err(Error::Type(cformat!(
465                "Cannot use {name} from non-window global"
466            )));
467        };
468
469        // Step 2. If name is navigationStart, return 0.
470        if name == "navigationStart" {
471            return Ok(self.time_origin);
472        }
473
474        // Step 3. Let startTime be the value of navigationStart in the PerformanceTiming interface.
475        // FIXME: We don't implement this value yet, so we assume it's zero (and then we don't need it at all)
476
477        // Step 4. Let endTime be the value of name in the PerformanceTiming interface.
478        //
479        // NOTE: We store all performance values on the document
480        let end_time = window.Document().performance_timing_attribute(name)?;
481
482        // Step 5. If endTime is 0, throw an InvalidAccessError.
483        let Some(end_time) = end_time else {
484            return Err(Error::InvalidAccess(Some(format!(
485                "{name} hasn't happened yet"
486            ))));
487        };
488
489        // Step 6. Return result of subtracting startTime from endTime.
490        Ok(end_time)
491    }
492
493    /// <https://w3c.github.io/user-timing/#convert-a-mark-to-a-timestamp>
494    fn convert_a_mark_to_a_timestamp(
495        &self,
496        mark: &StringOrDouble,
497    ) -> Fallible<CrossProcessInstant> {
498        match mark {
499            StringOrDouble::String(name) => {
500                // Step 1. If mark is a DOMString and it has the same name as a read only attribute in the
501                // PerformanceTiming interface, let end time be the value returned by running the convert
502                // a name to a timestamp algorithm with name set to the value of mark.
503                if PERFORMANCE_TIMING_ATTRIBUTES.contains(&&*name.str()) {
504                    self.convert_a_name_to_a_timestamp(&name.str())
505                }
506                // Step 2. Otherwise, if mark is a DOMString, let end time be the value of the startTime
507                // attribute from the most recent occurrence of a PerformanceMark object in the performance entry
508                // buffer whose name is mark. If no matching entry is found, throw a SyntaxError.
509                else {
510                    self.buffer
511                        .borrow()
512                        .get_last_entry_start_time_with_name_and_type(name.clone(), EntryType::Mark)
513                        .ok_or(Error::Syntax(Some(format!(
514                            "No PerformanceMark named {name} exists"
515                        ))))
516                }
517            },
518            // Step 3. Otherwise, if mark is a DOMHighResTimeStamp:
519            StringOrDouble::Double(timestamp) => {
520                // Step 3.1 If mark is negative, throw a TypeError.
521                if timestamp.is_sign_negative() {
522                    return Err(Error::Type(c"Time stamps must not be negative".to_owned()));
523                }
524
525                // Step 3.2 Otherwise, let end time be mark.
526                // NOTE: I think the spec wants us to return the value.
527                Ok(
528                    self.time_origin +
529                        Duration::microseconds(timestamp.mul_add(1000.0, 0.0) as i64),
530                )
531            },
532        }
533    }
534}
535
536impl PerformanceMethods<crate::DomTypeHolder> for Performance {
537    /// <https://w3c.github.io/navigation-timing/#dom-performance-timing>
538    fn Timing(&self) -> DomRoot<PerformanceNavigationTiming> {
539        let entries = self.GetEntriesByType(DOMString::from("navigation"));
540        if !entries.is_empty() {
541            return DomRoot::from_ref(
542                entries[0]
543                    .downcast::<PerformanceNavigationTiming>()
544                    .unwrap(),
545            );
546        }
547        unreachable!("Are we trying to expose Performance.timing in workers?");
548    }
549
550    /// <https://w3c.github.io/navigation-timing/#dom-performance-navigation>
551    fn Navigation(&self) -> DomRoot<PerformanceNavigation> {
552        PerformanceNavigation::new(&self.global(), CanGc::deprecated_note())
553    }
554
555    /// <https://w3c.github.io/hr-time/#dom-performance-now>
556    fn Now(&self) -> DOMHighResTimeStamp {
557        self.to_dom_high_res_time_stamp(CrossProcessInstant::now())
558    }
559
560    /// <https://www.w3.org/TR/hr-time-2/#dom-performance-timeorigin>
561    fn TimeOrigin(&self) -> DOMHighResTimeStamp {
562        (self.time_origin - CrossProcessInstant::epoch()).to_dom_high_res_time_stamp()
563    }
564
565    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentries>
566    fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> {
567        // > Returns a PerformanceEntryList object returned by the filter buffer map by name and type
568        // > algorithm with name and type set to null.
569        self.buffer
570            .borrow()
571            .get_entries_by_name_and_type(None, None)
572    }
573
574    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbytype>
575    fn GetEntriesByType(&self, entry_type: DOMString) -> Vec<DomRoot<PerformanceEntry>> {
576        let Ok(entry_type) = EntryType::try_from(&*entry_type.str()) else {
577            return Vec::new();
578        };
579        self.buffer
580            .borrow()
581            .get_entries_by_name_and_type(None, Some(entry_type))
582    }
583
584    /// <https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbyname>
585    fn GetEntriesByName(
586        &self,
587        name: DOMString,
588        entry_type: Option<DOMString>,
589    ) -> Vec<DomRoot<PerformanceEntry>> {
590        let entry_type = match entry_type {
591            Some(entry_type) => {
592                let Ok(entry_type) = EntryType::try_from(&*entry_type.str()) else {
593                    return Vec::new();
594                };
595                Some(entry_type)
596            },
597            None => None,
598        };
599        self.buffer
600            .borrow()
601            .get_entries_by_name_and_type(Some(name), entry_type)
602    }
603
604    /// <https://w3c.github.io/user-timing/#dom-performance-mark>
605    fn Mark(
606        &self,
607        cx: &mut JSContext,
608        mark_name: DOMString,
609        mark_options: RootedTraceableBox<PerformanceMarkOptions>,
610    ) -> Fallible<DomRoot<PerformanceMark>> {
611        // Step 1. Run the PerformanceMark constructor and let entry be the newly created object.
612        let entry =
613            PerformanceMark::Constructor(cx, &self.global(), None, mark_name, mark_options)?;
614
615        // Step 2. Queue a PerformanceEntry entry.
616        // Step 3. Add entry to the performance entry buffer. (This is done in queue_entry itself)
617        self.queue_entry(entry.upcast::<PerformanceEntry>());
618
619        // Step 4. Return entry.
620        Ok(entry)
621    }
622
623    /// <https://w3c.github.io/user-timing/#dom-performance-clearmarks>
624    fn ClearMarks(&self, mark_name: Option<DOMString>) {
625        self.buffer
626            .borrow_mut()
627            .clear_entries_by_name_and_type(mark_name, EntryType::Mark);
628    }
629
630    /// <https://w3c.github.io/user-timing/#dom-performance-measure>
631    fn Measure(
632        &self,
633        cx: &mut JSContext,
634        measure_name: DOMString,
635        start_or_measure_options: StringOrPerformanceMeasureOptions,
636        end_mark: Option<DOMString>,
637    ) -> Fallible<DomRoot<PerformanceMeasure>> {
638        // Step 1. If startOrMeasureOptions is a PerformanceMeasureOptions object and at least one of start,
639        // end, duration, and detail exist, run the following checks:
640        if let StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) =
641            &start_or_measure_options &&
642            (options.start.is_some() ||
643                options.duration.is_some() ||
644                options.end.is_some() ||
645                options.detail.get().is_object_or_null())
646        {
647            // Step 1.1 If endMark is given, throw a TypeError.
648            if end_mark.is_some() {
649                return Err(Error::Type(
650                    c"Must not provide endMark if PerformanceMeasureOptions is also provided"
651                        .to_owned(),
652                ));
653            }
654
655            // Step 1.2 If startOrMeasureOptions’s start and end members are both omitted, throw a TypeError.
656            if options.start.is_none() && options.end.is_none() {
657                return Err(Error::Type(
658                    c"Either 'start' or 'end' member of PerformanceMeasureOptions must be provided"
659                        .to_owned(),
660                ));
661            }
662
663            // Step 1.3 If startOrMeasureOptions’s start, duration, and end members all exist, throw a TypeError.
664            if options.start.is_some() && options.duration.is_some() && options.end.is_some() {
665                return Err(Error::Type(c"Either 'start' or 'end' or 'duration' member of PerformanceMeasureOptions must be omitted".to_owned()));
666            }
667        }
668
669        // Step 2. Compute end time as follows:
670        // Step 2.1 If endMark is given, let end time be the value returned
671        // by running the convert a mark to a timestamp algorithm passing in endMark.
672        let end_time = if let Some(end_mark) = end_mark {
673            self.convert_a_mark_to_a_timestamp(&StringOrDouble::String(end_mark))?
674        } else {
675            match &start_or_measure_options {
676                StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) => {
677                    // Step 2.2 Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object,
678                    // and if its end member exists, let end time be the value returned by running the
679                    // convert a mark to a timestamp algorithm passing in startOrMeasureOptions’s end.
680                    if let Some(end) = &options.end {
681                        self.convert_a_mark_to_a_timestamp(end)?
682                    }
683                    // Step 2.3 Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object,
684                    // and if its start and duration members both exist:
685                    else if let Some((start, duration)) =
686                        options.start.as_ref().zip(options.duration)
687                    {
688                        // Step 2.3.1 Let start be the value returned by running the convert a mark to a timestamp
689                        // algorithm passing in start.
690                        let start = self.convert_a_mark_to_a_timestamp(start)?;
691
692                        // Step 2.3.2 Let duration be the value returned by running the convert a mark to a timestamp
693                        // algorithm passing in duration.
694                        let duration = self
695                            .convert_a_mark_to_a_timestamp(&StringOrDouble::Double(duration))? -
696                            self.time_origin;
697
698                        // Step 2.3.3 Let end time be start plus duration.
699                        start + duration
700                    } else {
701                        // Step 2.4 Otherwise, let end time be the value that would be returned by the
702                        // Performance object’s now() method.
703                        CrossProcessInstant::now()
704                    }
705                },
706                _ => {
707                    // Step 2.4 Otherwise, let end time be the value that would be returned by the
708                    // Performance object’s now() method.
709                    CrossProcessInstant::now()
710                },
711            }
712        };
713
714        // Step 3. Compute start time as follows:
715        let start_time = match &start_or_measure_options {
716            StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) => {
717                // Step 3.1 If startOrMeasureOptions is a PerformanceMeasureOptions object, and if its start member exists,
718                // let start time be the value returned by running the convert a mark to a timestamp algorithm passing in
719                // startOrMeasureOptions’s start.
720                if let Some(start) = &options.start {
721                    self.convert_a_mark_to_a_timestamp(start)?
722                }
723                // Step 3.2 Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object,
724                // and if its duration and end members both exist:
725                else if let Some((duration, end)) = options.duration.zip(options.end.as_ref()) {
726                    // Step 3.2.1 Let duration be the value returned by running the convert a mark to a timestamp
727                    // algorithm passing in duration.
728                    let duration = self
729                        .convert_a_mark_to_a_timestamp(&StringOrDouble::Double(duration))? -
730                        self.time_origin;
731
732                    // Step 3.2.2 Let end be the value returned by running the convert a mark to a timestamp algorithm
733                    // passing in end.
734                    let end = self.convert_a_mark_to_a_timestamp(end)?;
735
736                    // Step 3.3.3 Let start time be end minus duration.
737                    end - duration
738                }
739                // Step 3.4 Otherwise, let start time be 0.
740                else {
741                    self.time_origin
742                }
743            },
744            StringOrPerformanceMeasureOptions::String(string) => {
745                // Step 3.3 Otherwise, if startOrMeasureOptions is a DOMString, let start time be the value returned
746                // by running the convert a mark to a timestamp algorithm passing in startOrMeasureOptions.
747                self.convert_a_mark_to_a_timestamp(&StringOrDouble::String(string.clone()))?
748            },
749        };
750
751        // Step 4. Create a new PerformanceMeasure object (entry) with this’s relevant realm.
752        // Step 5. Set entry’s name attribute to measureName.
753        // Step 6. Set entry’s entryType attribute to DOMString "measure".
754        // Step 7. Set entry’s startTime attribute to start time.
755        // Step 8. Set entry’s duration attribute to the duration from start time to end time.
756        // The resulting duration value MAY be negative.
757
758        let entry = PerformanceMeasure::new(
759            &self.global(),
760            measure_name,
761            start_time,
762            end_time - start_time,
763        );
764
765        // Step 9. Set entry’s detail attribute as follows:
766        rooted!(&in(cx) let mut detail = NullValue());
767        // Step 9.1. If startOrMeasureOptions is a PerformanceMeasureOptions object and startOrMeasureOptions’s detail member exists:
768        if let StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) =
769            &start_or_measure_options &&
770            !options.detail.get().is_null_or_undefined()
771        {
772            // Step 9.1.1. Let record be the result of calling the StructuredSerialize algorithm on startOrMeasureOptions’s detail.
773            let record = structuredclone::write(cx, options.detail.handle(), None)?;
774
775            // Step 9.1.2. Set entry’s detail to the result of calling the StructuredDeserialize algorithm on record and the current realm.
776            structuredclone::read(cx, &self.global(), record, detail.handle_mut())?;
777        }
778        // Step 9.2. Otherwise, set it to null.
779        //
780        // Note: This is already the default value we set when creating the detail above
781
782        entry.set_detail(detail.handle());
783
784        // Step 10. Queue a PerformanceEntry entry.
785        // Step 11. Add entry to the performance entry buffer. (This is done in queue_entry itself)
786        self.queue_entry(entry.upcast::<PerformanceEntry>());
787
788        // Step 12. Return entry.
789        Ok(entry)
790    }
791
792    /// <https://w3c.github.io/user-timing/#dom-performance-clearmeasures>
793    fn ClearMeasures(&self, measure_name: Option<DOMString>) {
794        self.buffer
795            .borrow_mut()
796            .clear_entries_by_name_and_type(measure_name, EntryType::Measure);
797    }
798    /// <https://w3c.github.io/resource-timing/#dom-performance-clearresourcetimings>
799    fn ClearResourceTimings(&self) {
800        self.buffer
801            .borrow_mut()
802            .clear_entries_by_name_and_type(None, EntryType::Resource);
803        self.resource_timing_buffer_current_size.set(0);
804    }
805
806    /// <https://w3c.github.io/resource-timing/#performance-setresourcetimingbuffersize>
807    fn SetResourceTimingBufferSize(&self, max_size: u32) {
808        self.resource_timing_buffer_size_limit
809            .set(max_size as usize);
810    }
811
812    // https://w3c.github.io/resource-timing/#dom-performance-onresourcetimingbufferfull
813    event_handler!(
814        resourcetimingbufferfull,
815        GetOnresourcetimingbufferfull,
816        SetOnresourcetimingbufferfull
817    );
818}
819
820pub(crate) trait ToDOMHighResTimeStamp {
821    fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp;
822}
823
824impl ToDOMHighResTimeStamp for Duration {
825    fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp {
826        // https://www.w3.org/TR/hr-time-2/#clock-resolution
827        // We need a granularity no finer than 5 microseconds. 5 microseconds isn't an
828        // exactly representable f64 so WPT tests might occasionally corner-case on
829        // rounding.  web-platform-tests/wpt#21526 wants us to use an integer number of
830        // microseconds; the next divisor of milliseconds up from 5 microseconds is 10.
831        let microseconds_rounded = (self.whole_microseconds() as f64 / 10.).floor() * 10.;
832        Finite::wrap(microseconds_rounded / 1000.)
833    }
834}