Performance.cpp 18 KB

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