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