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