use std::cell::Cell;
use std::cmp::Ordering;
use std::collections::VecDeque;
use base::cross_process_instant::CrossProcessInstant;
use dom_struct::dom_struct;
use time_03::Duration;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::PerformanceBinding::{
DOMHighResTimeStamp, PerformanceEntryList as DOMPerformanceEntryList, PerformanceMethods,
};
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::performanceentry::PerformanceEntry;
use crate::dom::performancemark::PerformanceMark;
use crate::dom::performancemeasure::PerformanceMeasure;
use crate::dom::performancenavigation::PerformanceNavigation;
use crate::dom::performancenavigationtiming::PerformanceNavigationTiming;
use crate::dom::performanceobserver::PerformanceObserver as DOMPerformanceObserver;
use crate::dom::window::Window;
use crate::script_runtime::CanGc;
const INVALID_ENTRY_NAMES: &[&str] = &[
"navigationStart",
"unloadEventStart",
"unloadEventEnd",
"redirectStart",
"redirectEnd",
"fetchStart",
"domainLookupStart",
"domainLookupEnd",
"connectStart",
"connectEnd",
"secureConnectionStart",
"requestStart",
"responseStart",
"responseEnd",
"domLoading",
"domInteractive",
"domContentLoadedEventStart",
"domContentLoadedEventEnd",
"domComplete",
"loadEventStart",
"loadEventEnd",
];
#[derive(JSTraceable, MallocSizeOf)]
pub struct PerformanceEntryList {
entries: DOMPerformanceEntryList,
}
impl PerformanceEntryList {
pub fn new(entries: DOMPerformanceEntryList) -> Self {
PerformanceEntryList { entries }
}
pub fn get_entries_by_name_and_type(
&self,
name: Option<DOMString>,
entry_type: Option<DOMString>,
) -> Vec<DomRoot<PerformanceEntry>> {
let mut res = self
.entries
.iter()
.filter(|e| {
name.as_ref().map_or(true, |name_| *e.name() == *name_) &&
entry_type
.as_ref()
.map_or(true, |type_| *e.entry_type() == *type_)
})
.cloned()
.collect::<Vec<DomRoot<PerformanceEntry>>>();
res.sort_by(|a, b| {
a.start_time()
.partial_cmp(&b.start_time())
.unwrap_or(Ordering::Equal)
});
res
}
pub fn clear_entries_by_name_and_type(
&mut self,
name: Option<DOMString>,
entry_type: DOMString,
) {
self.entries.retain(|e| {
*e.entry_type() != *entry_type || name.as_ref().is_some_and(|name_| *e.name() != *name_)
});
}
fn get_last_entry_start_time_with_name_and_type(
&self,
name: DOMString,
entry_type: DOMString,
) -> Option<CrossProcessInstant> {
self.entries
.iter()
.rev()
.find(|e| *e.entry_type() == *entry_type && *e.name() == *name)
.and_then(|entry| entry.start_time())
}
}
impl IntoIterator for PerformanceEntryList {
type Item = DomRoot<PerformanceEntry>;
type IntoIter = ::std::vec::IntoIter<DomRoot<PerformanceEntry>>;
fn into_iter(self) -> Self::IntoIter {
self.entries.into_iter()
}
}
#[derive(JSTraceable, MallocSizeOf)]
struct PerformanceObserver {
observer: DomRoot<DOMPerformanceObserver>,
entry_types: Vec<DOMString>,
}
#[dom_struct]
pub struct Performance {
eventtarget: EventTarget,
buffer: DomRefCell<PerformanceEntryList>,
observers: DomRefCell<Vec<PerformanceObserver>>,
pending_notification_observers_task: Cell<bool>,
#[no_trace]
time_origin: CrossProcessInstant,
resource_timing_buffer_size_limit: Cell<usize>,
resource_timing_buffer_current_size: Cell<usize>,
resource_timing_buffer_pending_full_event: Cell<bool>,
resource_timing_secondary_entries: DomRefCell<VecDeque<DomRoot<PerformanceEntry>>>,
}
impl Performance {
fn new_inherited(time_origin: CrossProcessInstant) -> Performance {
Performance {
eventtarget: EventTarget::new_inherited(),
buffer: DomRefCell::new(PerformanceEntryList::new(Vec::new())),
observers: DomRefCell::new(Vec::new()),
pending_notification_observers_task: Cell::new(false),
time_origin,
resource_timing_buffer_size_limit: Cell::new(250),
resource_timing_buffer_current_size: Cell::new(0),
resource_timing_buffer_pending_full_event: Cell::new(false),
resource_timing_secondary_entries: DomRefCell::new(VecDeque::new()),
}
}
pub fn new(
global: &GlobalScope,
navigation_start: CrossProcessInstant,
) -> DomRoot<Performance> {
reflect_dom_object(
Box::new(Performance::new_inherited(navigation_start)),
global,
)
}
pub(crate) fn to_dom_high_res_time_stamp(
&self,
instant: CrossProcessInstant,
) -> DOMHighResTimeStamp {
(instant - self.time_origin).to_dom_high_res_time_stamp()
}
pub(crate) fn maybe_to_dom_high_res_time_stamp(
&self,
instant: Option<CrossProcessInstant>,
) -> DOMHighResTimeStamp {
self.to_dom_high_res_time_stamp(instant.unwrap_or(self.time_origin))
}
pub fn clear_and_disable_performance_entry_buffer(&self) {
let mut buffer = self.buffer.borrow_mut();
buffer.entries.clear();
self.resource_timing_buffer_size_limit.set(0);
}
pub fn add_multiple_type_observer(
&self,
observer: &DOMPerformanceObserver,
entry_types: Vec<DOMString>,
) {
let mut observers = self.observers.borrow_mut();
match observers.iter().position(|o| *o.observer == *observer) {
Some(p) => observers[p].entry_types = entry_types,
None => observers.push(PerformanceObserver {
observer: DomRoot::from_ref(observer),
entry_types,
}),
};
}
pub fn add_single_type_observer(
&self,
observer: &DOMPerformanceObserver,
entry_type: &DOMString,
buffered: bool,
) {
if buffered {
let buffer = self.buffer.borrow();
let mut new_entries =
buffer.get_entries_by_name_and_type(None, Some(entry_type.clone()));
if !new_entries.is_empty() {
let mut obs_entries = observer.entries();
obs_entries.append(&mut new_entries);
observer.set_entries(obs_entries);
}
if !self.pending_notification_observers_task.get() {
self.pending_notification_observers_task.set(true);
let task_source = self.global().performance_timeline_task_source();
task_source.queue_notification(&self.global());
}
}
let mut observers = self.observers.borrow_mut();
match observers.iter().position(|o| *o.observer == *observer) {
Some(p) => {
if !observers[p].entry_types.contains(entry_type) {
observers[p].entry_types.push(entry_type.clone())
}
},
None => observers.push(PerformanceObserver {
observer: DomRoot::from_ref(observer),
entry_types: vec![entry_type.clone()],
}),
};
}
pub fn remove_observer(&self, observer: &DOMPerformanceObserver) {
let mut observers = self.observers.borrow_mut();
let index = match observers.iter().position(|o| &(*o.observer) == observer) {
Some(p) => p,
None => return,
};
observers.remove(index);
}
pub fn queue_entry(&self, entry: &PerformanceEntry, can_gc: CanGc) -> Option<usize> {
if entry.entry_type() == "resource" && !self.should_queue_resource_entry(entry, can_gc) {
return None;
}
for o in self
.observers
.borrow()
.iter()
.filter(|o| o.entry_types.contains(entry.entry_type()))
{
o.observer.queue_entry(entry);
}
self.buffer
.borrow_mut()
.entries
.push(DomRoot::from_ref(entry));
let entry_last_index = self.buffer.borrow_mut().entries.len() - 1;
if self.pending_notification_observers_task.get() {
return None;
}
self.pending_notification_observers_task.set(true);
let task_source = self.global().performance_timeline_task_source();
task_source.queue_notification(&self.global());
Some(entry_last_index)
}
pub fn notify_observers(&self) {
self.pending_notification_observers_task.set(false);
let observers: Vec<DomRoot<DOMPerformanceObserver>> = self
.observers
.borrow()
.iter()
.map(|o| DomRoot::from_ref(&*o.observer))
.collect();
for o in observers.iter() {
o.notify();
}
}
fn can_add_resource_timing_entry(&self) -> bool {
self.resource_timing_buffer_current_size.get() <=
self.resource_timing_buffer_size_limit.get()
}
fn copy_secondary_resource_timing_buffer(&self, can_gc: CanGc) {
while self.can_add_resource_timing_entry() {
let entry = self
.resource_timing_secondary_entries
.borrow_mut()
.pop_front();
if let Some(ref entry) = entry {
self.queue_entry(entry, can_gc);
} else {
break;
}
}
}
fn fire_buffer_full_event(&self, can_gc: CanGc) {
while !self.resource_timing_secondary_entries.borrow().is_empty() {
let no_of_excess_entries_before = self.resource_timing_secondary_entries.borrow().len();
if !self.can_add_resource_timing_entry() {
self.upcast::<EventTarget>()
.fire_event(atom!("resourcetimingbufferfull"), can_gc);
}
self.copy_secondary_resource_timing_buffer(can_gc);
let no_of_excess_entries_after = self.resource_timing_secondary_entries.borrow().len();
if no_of_excess_entries_before <= no_of_excess_entries_after {
self.resource_timing_secondary_entries.borrow_mut().clear();
break;
}
}
self.resource_timing_buffer_pending_full_event.set(false);
}
fn should_queue_resource_entry(&self, entry: &PerformanceEntry, can_gc: CanGc) -> bool {
if !self.resource_timing_buffer_pending_full_event.get() {
if self.can_add_resource_timing_entry() {
self.resource_timing_buffer_current_size
.set(self.resource_timing_buffer_current_size.get() + 1);
return true;
}
self.resource_timing_buffer_pending_full_event.set(true);
self.fire_buffer_full_event(can_gc);
}
self.resource_timing_secondary_entries
.borrow_mut()
.push_back(DomRoot::from_ref(entry));
false
}
pub fn update_entry(&self, index: usize, entry: &PerformanceEntry) {
if let Some(e) = self.buffer.borrow_mut().entries.get_mut(index) {
*e = DomRoot::from_ref(entry);
}
}
}
impl PerformanceMethods for Performance {
fn Timing(&self) -> DomRoot<PerformanceNavigationTiming> {
let entries = self.GetEntriesByType(DOMString::from("navigation"));
if !entries.is_empty() {
return DomRoot::from_ref(
entries[0]
.downcast::<PerformanceNavigationTiming>()
.unwrap(),
);
}
unreachable!("Are we trying to expose Performance.timing in workers?");
}
fn Navigation(&self) -> DomRoot<PerformanceNavigation> {
PerformanceNavigation::new(&self.global())
}
fn Now(&self) -> DOMHighResTimeStamp {
self.to_dom_high_res_time_stamp(CrossProcessInstant::now())
}
fn TimeOrigin(&self) -> DOMHighResTimeStamp {
(self.time_origin - CrossProcessInstant::epoch()).to_dom_high_res_time_stamp()
}
fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> {
self.buffer
.borrow()
.get_entries_by_name_and_type(None, None)
}
fn GetEntriesByType(&self, entry_type: DOMString) -> Vec<DomRoot<PerformanceEntry>> {
self.buffer
.borrow()
.get_entries_by_name_and_type(None, Some(entry_type))
}
fn GetEntriesByName(
&self,
name: DOMString,
entry_type: Option<DOMString>,
) -> Vec<DomRoot<PerformanceEntry>> {
self.buffer
.borrow()
.get_entries_by_name_and_type(Some(name), entry_type)
}
fn Mark(&self, mark_name: DOMString, can_gc: CanGc) -> Fallible<()> {
let global = self.global();
if global.is::<Window>() && INVALID_ENTRY_NAMES.contains(&mark_name.as_ref()) {
return Err(Error::Syntax);
}
let entry = PerformanceMark::new(
&global,
mark_name,
CrossProcessInstant::now(),
Duration::ZERO,
);
self.queue_entry(entry.upcast::<PerformanceEntry>(), can_gc);
Ok(())
}
fn ClearMarks(&self, mark_name: Option<DOMString>) {
self.buffer
.borrow_mut()
.clear_entries_by_name_and_type(mark_name, DOMString::from("mark"));
}
fn Measure(
&self,
measure_name: DOMString,
start_mark: Option<DOMString>,
end_mark: Option<DOMString>,
can_gc: CanGc,
) -> Fallible<()> {
let end_time = end_mark
.map(|name| {
self.buffer
.borrow()
.get_last_entry_start_time_with_name_and_type(DOMString::from("mark"), name)
.unwrap_or(self.time_origin)
})
.unwrap_or_else(CrossProcessInstant::now);
let start_time = start_mark
.and_then(|name| {
self.buffer
.borrow()
.get_last_entry_start_time_with_name_and_type(DOMString::from("mark"), name)
})
.unwrap_or(self.time_origin);
let entry = PerformanceMeasure::new(
&self.global(),
measure_name,
start_time,
end_time - start_time,
);
self.queue_entry(entry.upcast::<PerformanceEntry>(), can_gc);
Ok(())
}
fn ClearMeasures(&self, measure_name: Option<DOMString>) {
self.buffer
.borrow_mut()
.clear_entries_by_name_and_type(measure_name, DOMString::from("measure"));
}
fn ClearResourceTimings(&self) {
self.buffer
.borrow_mut()
.clear_entries_by_name_and_type(None, DOMString::from("resource"));
self.resource_timing_buffer_current_size.set(0);
}
fn SetResourceTimingBufferSize(&self, max_size: u32) {
self.resource_timing_buffer_size_limit
.set(max_size as usize);
}
event_handler!(
resourcetimingbufferfull,
GetOnresourcetimingbufferfull,
SetOnresourcetimingbufferfull
);
}
pub(crate) trait ToDOMHighResTimeStamp {
fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp;
}
impl ToDOMHighResTimeStamp for Duration {
fn to_dom_high_res_time_stamp(&self) -> DOMHighResTimeStamp {
let microseconds_rounded = (self.whole_microseconds() as f64 / 10.).floor() * 10.;
Finite::wrap(microseconds_rounded / 1000.)
}
}