Performance.cpp 18 KB

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