Performance.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibWeb/DOM/Document.h>
  8. #include <LibWeb/DOM/Event.h>
  9. #include <LibWeb/DOM/EventDispatcher.h>
  10. #include <LibWeb/HTML/StructuredSerialize.h>
  11. #include <LibWeb/HTML/Window.h>
  12. #include <LibWeb/HighResolutionTime/Performance.h>
  13. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  14. #include <LibWeb/NavigationTiming/EntryNames.h>
  15. #include <LibWeb/NavigationTiming/PerformanceTiming.h>
  16. #include <LibWeb/PerformanceTimeline/EntryTypes.h>
  17. namespace Web::HighResolutionTime {
  18. Performance::Performance(HTML::Window& window)
  19. : DOM::EventTarget(window.realm())
  20. , m_window(window)
  21. {
  22. m_timer.start();
  23. }
  24. Performance::~Performance() = default;
  25. void Performance::initialize(JS::Realm& realm)
  26. {
  27. Base::initialize(realm);
  28. set_prototype(&Bindings::ensure_web_prototype<Bindings::PerformancePrototype>(realm, "Performance"));
  29. }
  30. void Performance::visit_edges(Cell::Visitor& visitor)
  31. {
  32. Base::visit_edges(visitor);
  33. visitor.visit(m_window.ptr());
  34. visitor.visit(m_timing.ptr());
  35. }
  36. JS::GCPtr<NavigationTiming::PerformanceTiming> Performance::timing()
  37. {
  38. if (!m_timing)
  39. m_timing = heap().allocate<NavigationTiming::PerformanceTiming>(realm(), *m_window);
  40. return m_timing;
  41. }
  42. double Performance::time_origin() const
  43. {
  44. return static_cast<double>(m_timer.origin_time().milliseconds());
  45. }
  46. // https://w3c.github.io/user-timing/#mark-method
  47. WebIDL::ExceptionOr<JS::NonnullGCPtr<UserTiming::PerformanceMark>> Performance::mark(String const& mark_name, UserTiming::PerformanceMarkOptions const& mark_options)
  48. {
  49. auto& realm = this->realm();
  50. // 1. Run the PerformanceMark constructor and let entry be the newly created object.
  51. auto entry = TRY(UserTiming::PerformanceMark::construct_impl(realm, mark_name, mark_options));
  52. // 2. Queue entry.
  53. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object());
  54. VERIFY(window_or_worker);
  55. window_or_worker->queue_performance_entry(entry);
  56. // 3. Add entry to the performance entry buffer.
  57. // FIXME: This seems to be a holdover from moving to the `queue` structure for PerformanceObserver, as this would cause a double append.
  58. // 4. Return entry.
  59. return entry;
  60. }
  61. void Performance::clear_marks(Optional<String> mark_name)
  62. {
  63. auto& realm = this->realm();
  64. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object());
  65. VERIFY(window_or_worker);
  66. // 1. If markName is omitted, remove all PerformanceMark objects from the performance entry buffer.
  67. if (!mark_name.has_value()) {
  68. window_or_worker->clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::mark);
  69. return;
  70. }
  71. // 2. Otherwise, remove all PerformanceMark objects listed in the performance entry buffer whose name is markName.
  72. window_or_worker->remove_entries_from_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::mark, mark_name.value());
  73. // 3. Return undefined.
  74. }
  75. WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> Performance::convert_name_to_timestamp(JS::Realm& realm, String const& name)
  76. {
  77. auto& vm = realm.vm();
  78. // 1. If the global object is not a Window object, throw a TypeError.
  79. if (!is<HTML::Window>(realm.global_object()))
  80. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, TRY_OR_THROW_OOM(vm, String::formatted("'{}' is an attribute in the PerformanceTiming interface and thus can only be used in a Window context", name)) };
  81. // 2. If name is navigationStart, return 0.
  82. if (name == NavigationTiming::EntryNames::navigationStart)
  83. return 0.0;
  84. auto timing_interface = timing();
  85. VERIFY(timing_interface);
  86. // 3. Let startTime be the value of navigationStart in the PerformanceTiming interface.
  87. auto start_time = timing_interface->navigation_start();
  88. // 4. Let endTime be the value of name in the PerformanceTiming interface.
  89. u64 end_time { 0 };
  90. #define __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME(camel_case_name, snake_case_name) \
  91. if (name == NavigationTiming::EntryNames::camel_case_name) \
  92. end_time = timing_interface->snake_case_name();
  93. ENUMERATE_NAVIGATION_TIMING_ENTRY_NAMES
  94. #undef __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME
  95. // 5. If endTime is 0, throw an InvalidAccessError.
  96. if (end_time == 0)
  97. return WebIDL::InvalidAccessError::create(realm, MUST(String::formatted("The '{}' entry in the PerformanceTiming interface is equal to 0, meaning it hasn't happened yet", name)));
  98. // 6. Return result of subtracting startTime from endTime.
  99. return static_cast<HighResolutionTime::DOMHighResTimeStamp>(end_time - start_time);
  100. }
  101. // https://w3c.github.io/user-timing/#dfn-convert-a-mark-to-a-timestamp
  102. WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> Performance::convert_mark_to_timestamp(JS::Realm& realm, Variant<String, HighResolutionTime::DOMHighResTimeStamp> mark)
  103. {
  104. if (mark.has<String>()) {
  105. auto const& mark_string = mark.get<String>();
  106. // 1. If mark is a DOMString and it has the same name as a read only attribute in the PerformanceTiming interface, let end
  107. // time be the value returned by running the convert a name to a timestamp algorithm with name set to the value of mark.
  108. #define __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME(name, _) \
  109. if (mark_string == NavigationTiming::EntryNames::name) \
  110. return convert_name_to_timestamp(realm, mark_string);
  111. ENUMERATE_NAVIGATION_TIMING_ENTRY_NAMES
  112. #undef __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME
  113. // 2. Otherwise, if mark is a DOMString, let end time be the value of the startTime attribute from the most recent occurrence
  114. // of a PerformanceMark object in the performance entry buffer whose name is mark. If no matching entry is found, throw a
  115. // SyntaxError.
  116. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object());
  117. VERIFY(window_or_worker);
  118. auto& tuple = window_or_worker->relevant_performance_entry_tuple(PerformanceTimeline::EntryTypes::mark);
  119. auto& performance_entry_buffer = tuple.performance_entry_buffer;
  120. auto maybe_entry = performance_entry_buffer.last_matching([&mark_string](JS::Handle<PerformanceTimeline::PerformanceEntry> const& entry) {
  121. return entry->name() == mark_string;
  122. });
  123. if (!maybe_entry.has_value())
  124. return WebIDL::SyntaxError::create(realm, MUST(String::formatted("No PerformanceMark object with name '{}' found in the performance timeline", mark_string)));
  125. return maybe_entry.value()->start_time();
  126. }
  127. // 3. Otherwise, if mark is a DOMHighResTimeStamp:
  128. auto mark_time_stamp = mark.get<HighResolutionTime::DOMHighResTimeStamp>();
  129. // 1. If mark is negative, throw a TypeError.
  130. if (mark_time_stamp < 0.0)
  131. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot have negative time values in PerformanceMark"sv };
  132. // 2. Otherwise, let end time be mark.
  133. return mark_time_stamp;
  134. }
  135. // https://w3c.github.io/user-timing/#dom-performance-measure
  136. WebIDL::ExceptionOr<JS::NonnullGCPtr<UserTiming::PerformanceMeasure>> Performance::measure(String const& measure_name, Variant<String, UserTiming::PerformanceMeasureOptions> const& start_or_measure_options, Optional<String> end_mark)
  137. {
  138. auto& realm = this->realm();
  139. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object());
  140. VERIFY(window_or_worker);
  141. auto& vm = this->vm();
  142. // 1. If startOrMeasureOptions is a PerformanceMeasureOptions object and at least one of start, end, duration, and detail
  143. // are present, run the following checks:
  144. auto const* start_or_measure_options_dictionary_object = start_or_measure_options.get_pointer<UserTiming::PerformanceMeasureOptions>();
  145. if (start_or_measure_options_dictionary_object
  146. && (start_or_measure_options_dictionary_object->start.has_value()
  147. || start_or_measure_options_dictionary_object->end.has_value()
  148. || start_or_measure_options_dictionary_object->duration.has_value()
  149. || !start_or_measure_options_dictionary_object->detail.is_undefined())) {
  150. // 1. If endMark is given, throw a TypeError.
  151. if (end_mark.has_value())
  152. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot provide PerformanceMeasureOptions and endMark at the same time"sv };
  153. // 2. If startOrMeasureOptions's start and end members are both omitted, throw a TypeError.
  154. if (!start_or_measure_options_dictionary_object->start.has_value() && !start_or_measure_options_dictionary_object->end.has_value())
  155. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "PerformanceMeasureOptions must contain one or both of 'start' and 'end'"sv };
  156. // 3. If startOrMeasureOptions's start, duration, and end members are all present, throw a TypeError.
  157. if (start_or_measure_options_dictionary_object->start.has_value() && start_or_measure_options_dictionary_object->end.has_value() && start_or_measure_options_dictionary_object->duration.has_value())
  158. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "PerformanceMeasureOptions cannot contain 'start', 'duration' and 'end' properties all at once"sv };
  159. }
  160. // 2. Compute end time as follows:
  161. HighResolutionTime::DOMHighResTimeStamp end_time { 0.0 };
  162. // 1. If endMark is given, let end time be the value returned by running the convert a mark to a timestamp algorithm passing
  163. // in endMark.
  164. if (end_mark.has_value()) {
  165. end_time = TRY(convert_mark_to_timestamp(realm, end_mark.value()));
  166. }
  167. // 2. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its end member is present, let end
  168. // time be the value returned by running the convert a mark to a timestamp algorithm passing in startOrMeasureOptions's end.
  169. else if (start_or_measure_options_dictionary_object && start_or_measure_options_dictionary_object->end.has_value()) {
  170. end_time = TRY(convert_mark_to_timestamp(realm, start_or_measure_options_dictionary_object->end.value()));
  171. }
  172. // 3. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its start and duration members are
  173. // both present:
  174. else if (start_or_measure_options_dictionary_object && start_or_measure_options_dictionary_object->start.has_value() && start_or_measure_options_dictionary_object->duration.has_value()) {
  175. // 1. Let start be the value returned by running the convert a mark to a timestamp algorithm passing in start.
  176. auto start = TRY(convert_mark_to_timestamp(realm, start_or_measure_options_dictionary_object->start.value()));
  177. // 2. Let duration be the value returned by running the convert a mark to a timestamp algorithm passing in duration.
  178. auto duration = TRY(convert_mark_to_timestamp(realm, start_or_measure_options_dictionary_object->duration.value()));
  179. // 3. Let end time be start plus duration.
  180. end_time = start + duration;
  181. }
  182. // 4. Otherwise, let end time be the value that would be returned by the Performance object's now() method.
  183. else {
  184. // FIXME: Performance#now doesn't currently use TimeOrigin's functions, update this and Performance#now to match Performance#now's specification.
  185. end_time = HighResolutionTime::unsafe_shared_current_time();
  186. }
  187. // 3. Compute start time as follows:
  188. HighResolutionTime::DOMHighResTimeStamp start_time { 0.0 };
  189. // 1. If startOrMeasureOptions is a PerformanceMeasureOptions object, and if its start member is present, let start time be
  190. // the value returned by running the convert a mark to a timestamp algorithm passing in startOrMeasureOptions's start.
  191. if (start_or_measure_options_dictionary_object && start_or_measure_options_dictionary_object->start.has_value()) {
  192. start_time = TRY(convert_mark_to_timestamp(realm, start_or_measure_options_dictionary_object->start.value()));
  193. }
  194. // 2. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its duration and end members are
  195. // both present:
  196. else if (start_or_measure_options_dictionary_object && start_or_measure_options_dictionary_object->duration.has_value() && start_or_measure_options_dictionary_object->end.has_value()) {
  197. // 1. Let duration be the value returned by running the convert a mark to a timestamp algorithm passing in duration.
  198. auto duration = TRY(convert_mark_to_timestamp(realm, start_or_measure_options_dictionary_object->duration.value()));
  199. // 2. Let end be the value returned by running the convert a mark to a timestamp algorithm passing in end.
  200. auto end = TRY(convert_mark_to_timestamp(realm, start_or_measure_options_dictionary_object->end.value()));
  201. // 3. Let start time be end minus duration.
  202. start_time = end - duration;
  203. }
  204. // 3. Otherwise, if startOrMeasureOptions is a DOMString, let start time be the value returned by running the convert a mark
  205. // to a timestamp algorithm passing in startOrMeasureOptions.
  206. else if (start_or_measure_options.has<String>()) {
  207. start_time = TRY(convert_mark_to_timestamp(realm, start_or_measure_options.get<String>()));
  208. }
  209. // 4. Otherwise, let start time be 0.
  210. else {
  211. start_time = 0.0;
  212. }
  213. // NOTE: Step 4 (creating the entry) is done after determining values, as we set the values once during creation and never
  214. // change them after.
  215. // 5. Set entry's name attribute to measureName.
  216. // NOTE: Will be done during construction.
  217. // 6. Set entry's entryType attribute to DOMString "measure".
  218. // NOTE: Already done via the `entry_type` virtual function.
  219. // 7. Set entry's startTime attribute to start time.
  220. // NOTE: Will be done during construction.
  221. // 8. Set entry's duration attribute to the duration from start time to end time. The resulting duration value MAY be negative.
  222. auto duration = end_time - start_time;
  223. // 9. Set entry's detail attribute as follows:
  224. JS::Value detail { JS::js_null() };
  225. // 1. If startOrMeasureOptions is a PerformanceMeasureOptions object and startOrMeasureOptions's detail member is present:
  226. if (start_or_measure_options_dictionary_object && !start_or_measure_options_dictionary_object->detail.is_undefined()) {
  227. // 1. Let record be the result of calling the StructuredSerialize algorithm on startOrMeasureOptions's detail.
  228. auto record = TRY(HTML::structured_serialize(vm, start_or_measure_options_dictionary_object->detail));
  229. // 2. Set entry's detail to the result of calling the StructuredDeserialize algorithm on record and the current realm.
  230. detail = TRY(HTML::structured_deserialize(vm, record, realm, Optional<HTML::SerializationMemory> {}));
  231. }
  232. // 2. Otherwise, set it to null.
  233. // NOTE: Already the default value of `detail`.
  234. // 4. Create a new PerformanceMeasure object (entry) with this's relevant realm.
  235. auto entry = realm.heap().allocate<UserTiming::PerformanceMeasure>(realm, realm, measure_name, start_time, duration, detail);
  236. // 10. Queue entry.
  237. window_or_worker->queue_performance_entry(entry);
  238. // 11. Add entry to the performance entry buffer.
  239. // FIXME: This seems to be a holdover from moving to the `queue` structure for PerformanceObserver, as this would cause a double append.
  240. // 12. Return entry.
  241. return entry;
  242. }
  243. // https://w3c.github.io/user-timing/#dom-performance-clearmeasures
  244. void Performance::clear_measures(Optional<String> measure_name)
  245. {
  246. auto& realm = this->realm();
  247. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object());
  248. VERIFY(window_or_worker);
  249. // 1. If measureName is omitted, remove all PerformanceMeasure objects in the performance entry buffer.
  250. if (!measure_name.has_value()) {
  251. window_or_worker->clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::measure);
  252. return;
  253. }
  254. // 2. Otherwise remove all PerformanceMeasure objects listed in the performance entry buffer whose name is measureName.
  255. window_or_worker->remove_entries_from_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::measure, measure_name.value());
  256. // 3. Return undefined.
  257. }
  258. // https://www.w3.org/TR/performance-timeline/#getentries-method
  259. WebIDL::ExceptionOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries() const
  260. {
  261. auto& realm = this->realm();
  262. auto& vm = this->vm();
  263. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object());
  264. VERIFY(window_or_worker);
  265. // Returns a PerformanceEntryList object returned by the filter buffer map by name and type algorithm with name and
  266. // type set to null.
  267. return TRY_OR_THROW_OOM(vm, window_or_worker->filter_buffer_map_by_name_and_type(/* name= */ Optional<String> {}, /* type= */ Optional<String> {}));
  268. }
  269. // https://www.w3.org/TR/performance-timeline/#dom-performance-getentriesbytype
  270. WebIDL::ExceptionOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries_by_type(String const& type) const
  271. {
  272. auto& realm = this->realm();
  273. auto& vm = this->vm();
  274. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object());
  275. VERIFY(window_or_worker);
  276. // Returns a PerformanceEntryList object returned by filter buffer map by name and type algorithm with name set to null,
  277. // and type set to the method's input type parameter.
  278. return TRY_OR_THROW_OOM(vm, window_or_worker->filter_buffer_map_by_name_and_type(/* name= */ Optional<String> {}, type));
  279. }
  280. // https://www.w3.org/TR/performance-timeline/#dom-performance-getentriesbyname
  281. WebIDL::ExceptionOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries_by_name(String const& name, Optional<String> type) const
  282. {
  283. auto& realm = this->realm();
  284. auto& vm = this->vm();
  285. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object());
  286. VERIFY(window_or_worker);
  287. // Returns a PerformanceEntryList object returned by filter buffer map by name and type algorithm with name set to the
  288. // method input name parameter, and type set to null if optional entryType is omitted, or set to the method's input type
  289. // parameter otherwise.
  290. return TRY_OR_THROW_OOM(vm, window_or_worker->filter_buffer_map_by_name_and_type(name, type));
  291. }
  292. }