Performance.cpp 19 KB

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