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