1use 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#[derive(JSTraceable, MallocSizeOf)]
51#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
52pub(crate) struct PerformanceEntryList {
53 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 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 result.sort_by(|a, b| {
84 a.start_time()
85 .partial_cmp(&b.start_time())
86 .unwrap_or(Ordering::Equal)
87 });
88
89 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 time_origin: CrossProcessInstant,
133 resource_timing_buffer_size_limit: Cell<usize>,
137 resource_timing_buffer_current_size: Cell<usize>,
139 resource_timing_buffer_pending_full_event: Cell<bool>,
141 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 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 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 Some(p) => observers[p].entry_types = entry_types,
227 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 Some(p) => {
265 if !observers[p].entry_types.contains(&entry_type) {
267 observers[p].entry_types.push(entry_type)
268 }
269 },
270 None => observers.push(PerformanceObserver {
272 observer: Dom::from_ref(observer),
273 entry_types: vec![entry_type],
274 }),
275 };
276 }
277
278 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 pub(crate) fn queue_entry(&self, entry: &PerformanceEntry) -> Option<usize> {
298 if entry.entry_type() == EntryType::Resource && !self.should_queue_resource_entry(entry) {
300 return None;
301 }
302
303 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 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 if self.pending_notification_observers_task.get() {
325 return None;
326 }
327
328 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 fn notify_observers(&self, cx: &mut JSContext) {
348 self.pending_notification_observers_task.set(false);
350
351 let observers: Vec<DomRoot<DOMPerformanceObserver>> = self
357 .observers
358 .borrow()
359 .iter()
360 .map(|o| DomRoot::from_ref(&*o.observer))
361 .collect();
362
363 for o in observers.iter() {
365 o.notify(cx);
366 }
367 }
368
369 fn can_add_resource_timing_entry(&self) -> bool {
371 self.resource_timing_buffer_current_size.get() <
374 self.resource_timing_buffer_size_limit.get()
375 }
376
377 fn copy_secondary_resource_timing_buffer(&self) {
379 while self.can_add_resource_timing_entry() {
381 if let Some(ref entry) = self
383 .resource_timing_secondary_entries
384 .borrow_mut()
385 .pop_front()
386 {
387 self.buffer.borrow_mut().entries.push(Dom::from_ref(entry));
389 self.resource_timing_buffer_current_size
391 .set(self.resource_timing_buffer_current_size.get() + 1);
392 } else {
396 break;
397 }
398 }
399 }
400
401 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 fn should_queue_resource_entry(&self, entry: &PerformanceEntry) -> bool {
422 if !self.resource_timing_buffer_pending_full_event.get() {
424 if self.can_add_resource_timing_entry() {
425 self.resource_timing_buffer_current_size
429 .set(self.resource_timing_buffer_current_size.get() + 1);
430 return true;
432 }
433
434 self.resource_timing_buffer_pending_full_event.set(true);
436 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 self.resource_timing_secondary_entries
448 .borrow_mut()
449 .push_back(Dom::from_ref(entry));
450
451 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 fn convert_a_name_to_a_timestamp(&self, name: &str) -> Fallible<CrossProcessInstant> {
464 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 if name == "navigationStart" {
473 return Ok(self.time_origin);
474 }
475
476 let end_time = window.Document().performance_timing_attribute(name)?;
483
484 let Some(end_time) = end_time else {
486 return Err(Error::InvalidAccess(Some(format!(
487 "{name} hasn't happened yet"
488 ))));
489 };
490
491 Ok(end_time)
493 }
494
495 fn convert_a_mark_to_a_timestamp(
497 &self,
498 mark: &StringOrDouble,
499 ) -> Fallible<CrossProcessInstant> {
500 match mark {
501 StringOrDouble::String(name) => {
502 if PERFORMANCE_TIMING_ATTRIBUTES.contains(&&*name.str()) {
506 self.convert_a_name_to_a_timestamp(&name.str())
507 }
508 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 StringOrDouble::Double(timestamp) => {
522 if timestamp.is_sign_negative() {
524 return Err(Error::Type(c"Time stamps must not be negative".to_owned()));
525 }
526
527 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 fn Timing(&self) -> DomRoot<PerformanceTiming> {
541 DomRoot::from_ref(&*self.timing)
542 }
543
544 fn Navigation(&self) -> DomRoot<PerformanceNavigation> {
546 DomRoot::from_ref(&*self.navigation)
547 }
548
549 fn Now(&self) -> DOMHighResTimeStamp {
551 self.to_dom_high_res_time_stamp(CrossProcessInstant::now())
552 }
553
554 fn TimeOrigin(&self) -> DOMHighResTimeStamp {
556 (self.time_origin - CrossProcessInstant::epoch()).to_dom_high_res_time_stamp()
557 }
558
559 fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> {
561 self.buffer
564 .borrow()
565 .get_entries_by_name_and_type(None, None)
566 }
567
568 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 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 fn Mark(
600 &self,
601 cx: &mut JSContext,
602 mark_name: DOMString,
603 mark_options: RootedTraceableBox<PerformanceMarkOptions>,
604 ) -> Fallible<DomRoot<PerformanceMark>> {
605 let entry =
607 PerformanceMark::Constructor(cx, &self.global(), None, mark_name, mark_options)?;
608
609 self.queue_entry(entry.upcast::<PerformanceEntry>());
612
613 Ok(entry)
615 }
616
617 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 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 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 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 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 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 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 if let Some(end) = &options.end {
675 self.convert_a_mark_to_a_timestamp(end)?
676 }
677 else if let Some((start, duration)) =
680 options.start.as_ref().zip(options.duration)
681 {
682 let start = self.convert_a_mark_to_a_timestamp(start)?;
685
686 let duration = self
689 .convert_a_mark_to_a_timestamp(&StringOrDouble::Double(duration))? -
690 self.time_origin;
691
692 start + duration
694 } else {
695 CrossProcessInstant::now()
698 }
699 },
700 _ => {
701 CrossProcessInstant::now()
704 },
705 }
706 };
707
708 let start_time = match &start_or_measure_options {
710 StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) => {
711 if let Some(start) = &options.start {
715 self.convert_a_mark_to_a_timestamp(start)?
716 }
717 else if let Some((duration, end)) = options.duration.zip(options.end.as_ref()) {
720 let duration = self
723 .convert_a_mark_to_a_timestamp(&StringOrDouble::Double(duration))? -
724 self.time_origin;
725
726 let end = self.convert_a_mark_to_a_timestamp(end)?;
729
730 end - duration
732 }
733 else {
735 self.time_origin
736 }
737 },
738 StringOrPerformanceMeasureOptions::String(string) => {
739 self.convert_a_mark_to_a_timestamp(&StringOrDouble::String(string.clone()))?
742 },
743 };
744
745 let entry = PerformanceMeasure::new(
753 cx,
754 &self.global(),
755 measure_name,
756 start_time,
757 end_time - start_time,
758 );
759
760 rooted!(&in(cx) let mut detail = NullValue());
762 if let StringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) =
764 &start_or_measure_options &&
765 !options.detail.get().is_null_or_undefined()
766 {
767 let record = structuredclone::write(cx, options.detail.handle(), None)?;
769
770 structuredclone::read(cx, &self.global(), record, detail.handle_mut())?;
772 }
773 entry.set_detail(detail.handle());
778
779 self.queue_entry(entry.upcast::<PerformanceEntry>());
782
783 Ok(entry)
785 }
786
787 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 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 fn SetResourceTimingBufferSize(&self, max_size: u32) {
803 self.resource_timing_buffer_size_limit
804 .set(max_size as usize);
805 }
806
807 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 let microseconds_rounded = (self.whole_microseconds() as f64 / 10.).floor() * 10.;
827 Finite::wrap(microseconds_rounded / 1000.)
828 }
829}