1use 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#[derive(JSTraceable, MallocSizeOf)]
50pub(crate) struct PerformanceEntryList {
51 entries: DOMPerformanceEntryList,
53}
54
55impl PerformanceEntryList {
56 pub(crate) fn new(entries: DOMPerformanceEntryList) -> Self {
57 PerformanceEntryList { entries }
58 }
59
60 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 result.sort_by(|a, b| {
80 a.start_time()
81 .partial_cmp(&b.start_time())
82 .unwrap_or(Ordering::Equal)
83 });
84
85 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 time_origin: CrossProcessInstant,
137 resource_timing_buffer_size_limit: Cell<usize>,
141 resource_timing_buffer_current_size: Cell<usize>,
143 resource_timing_buffer_pending_full_event: Cell<bool>,
145 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 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 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 Some(p) => observers[p].entry_types = entry_types,
216 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 Some(p) => {
256 if !observers[p].entry_types.contains(&entry_type) {
258 observers[p].entry_types.push(entry_type)
259 }
260 },
261 None => observers.push(PerformanceObserver {
263 observer: DomRoot::from_ref(observer),
264 entry_types: vec![entry_type],
265 }),
266 };
267 }
268
269 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 pub(crate) fn queue_entry(&self, entry: &PerformanceEntry) -> Option<usize> {
289 if entry.entry_type() == EntryType::Resource && !self.should_queue_resource_entry(entry) {
291 return None;
292 }
293
294 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 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 if self.pending_notification_observers_task.get() {
319 return None;
320 }
321
322 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 fn notify_observers(&self, cx: &mut JSContext) {
343 self.pending_notification_observers_task.set(false);
345
346 let observers: Vec<DomRoot<DOMPerformanceObserver>> = self
352 .observers
353 .borrow()
354 .iter()
355 .map(|o| DomRoot::from_ref(&*o.observer))
356 .collect();
357
358 for o in observers.iter() {
360 o.notify(cx);
361 }
362 }
363
364 fn can_add_resource_timing_entry(&self) -> bool {
366 self.resource_timing_buffer_current_size.get() <
369 self.resource_timing_buffer_size_limit.get()
370 }
371
372 fn copy_secondary_resource_timing_buffer(&self) {
374 while self.can_add_resource_timing_entry() {
376 let entry = self
378 .resource_timing_secondary_entries
379 .borrow_mut()
380 .pop_front();
381 if let Some(ref entry) = entry {
382 self.buffer
384 .borrow_mut()
385 .entries
386 .push(DomRoot::from_ref(entry));
387 self.resource_timing_buffer_current_size
389 .set(self.resource_timing_buffer_current_size.get() + 1);
390 } else {
394 break;
395 }
396 }
397 }
398
399 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 fn should_queue_resource_entry(&self, entry: &PerformanceEntry) -> bool {
420 if !self.resource_timing_buffer_pending_full_event.get() {
422 if self.can_add_resource_timing_entry() {
423 self.resource_timing_buffer_current_size
427 .set(self.resource_timing_buffer_current_size.get() + 1);
428 return true;
430 }
431
432 self.resource_timing_buffer_pending_full_event.set(true);
434 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 self.resource_timing_secondary_entries
446 .borrow_mut()
447 .push_back(DomRoot::from_ref(entry));
448
449 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 fn convert_a_name_to_a_timestamp(&self, name: &str) -> Fallible<CrossProcessInstant> {
462 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 if name == "navigationStart" {
471 return Ok(self.time_origin);
472 }
473
474 let end_time = window.Document().performance_timing_attribute(name)?;
481
482 let Some(end_time) = end_time else {
484 return Err(Error::InvalidAccess(Some(format!(
485 "{name} hasn't happened yet"
486 ))));
487 };
488
489 Ok(end_time)
491 }
492
493 fn convert_a_mark_to_a_timestamp(
495 &self,
496 mark: &StringOrDouble,
497 ) -> Fallible<CrossProcessInstant> {
498 match mark {
499 StringOrDouble::String(name) => {
500 if PERFORMANCE_TIMING_ATTRIBUTES.contains(&&*name.str()) {
504 self.convert_a_name_to_a_timestamp(&name.str())
505 }
506 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 StringOrDouble::Double(timestamp) => {
520 if timestamp.is_sign_negative() {
522 return Err(Error::Type(c"Time stamps must not be negative".to_owned()));
523 }
524
525 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 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 fn Navigation(&self) -> DomRoot<PerformanceNavigation> {
552 PerformanceNavigation::new(&self.global(), CanGc::deprecated_note())
553 }
554
555 fn Now(&self) -> DOMHighResTimeStamp {
557 self.to_dom_high_res_time_stamp(CrossProcessInstant::now())
558 }
559
560 fn TimeOrigin(&self) -> DOMHighResTimeStamp {
562 (self.time_origin - CrossProcessInstant::epoch()).to_dom_high_res_time_stamp()
563 }
564
565 fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> {
567 self.buffer
570 .borrow()
571 .get_entries_by_name_and_type(None, None)
572 }
573
574 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 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 fn Mark(
606 &self,
607 cx: &mut JSContext,
608 mark_name: DOMString,
609 mark_options: RootedTraceableBox<PerformanceMarkOptions>,
610 ) -> Fallible<DomRoot<PerformanceMark>> {
611 let entry =
613 PerformanceMark::Constructor(cx, &self.global(), None, mark_name, mark_options)?;
614
615 self.queue_entry(entry.upcast::<PerformanceEntry>());
618
619 Ok(entry)
621 }
622
623 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 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 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 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 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 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 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 if let Some(end) = &options.end {
681 self.convert_a_mark_to_a_timestamp(end)?
682 }
683 else if let Some((start, duration)) =
686 options.start.as_ref().zip(options.duration)
687 {
688 let start = self.convert_a_mark_to_a_timestamp(start)?;
691
692 let duration = self
695 .convert_a_mark_to_a_timestamp(&StringOrDouble::Double(duration))? -
696 self.time_origin;
697
698 start + duration
700 } else {
701 CrossProcessInstant::now()
704 }
705 },
706 _ => {
707 CrossProcessInstant::now()
710 },
711 }
712 };
713
714 let start_time = match &start_or_measure_options {
716 StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) => {
717 if let Some(start) = &options.start {
721 self.convert_a_mark_to_a_timestamp(start)?
722 }
723 else if let Some((duration, end)) = options.duration.zip(options.end.as_ref()) {
726 let duration = self
729 .convert_a_mark_to_a_timestamp(&StringOrDouble::Double(duration))? -
730 self.time_origin;
731
732 let end = self.convert_a_mark_to_a_timestamp(end)?;
735
736 end - duration
738 }
739 else {
741 self.time_origin
742 }
743 },
744 StringOrPerformanceMeasureOptions::String(string) => {
745 self.convert_a_mark_to_a_timestamp(&StringOrDouble::String(string.clone()))?
748 },
749 };
750
751 let entry = PerformanceMeasure::new(
759 &self.global(),
760 measure_name,
761 start_time,
762 end_time - start_time,
763 );
764
765 rooted!(&in(cx) let mut detail = NullValue());
767 if let StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) =
769 &start_or_measure_options &&
770 !options.detail.get().is_null_or_undefined()
771 {
772 let record = structuredclone::write(cx, options.detail.handle(), None)?;
774
775 structuredclone::read(cx, &self.global(), record, detail.handle_mut())?;
777 }
778 entry.set_detail(detail.handle());
783
784 self.queue_entry(entry.upcast::<PerformanceEntry>());
787
788 Ok(entry)
790 }
791
792 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 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 fn SetResourceTimingBufferSize(&self, max_size: u32) {
808 self.resource_timing_buffer_size_limit
809 .set(max_size as usize);
810 }
811
812 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 let microseconds_rounded = (self.whole_microseconds() as f64 / 10.).floor() * 10.;
832 Finite::wrap(microseconds_rounded / 1000.)
833 }
834}