WorkerGlobalScope.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Array.h>
  7. #include <AK/Vector.h>
  8. #include <LibWeb/Bindings/DedicatedWorkerExposedInterfaces.h>
  9. #include <LibWeb/Bindings/Intrinsics.h>
  10. #include <LibWeb/Bindings/WorkerGlobalScopePrototype.h>
  11. #include <LibWeb/Forward.h>
  12. #include <LibWeb/HTML/EventHandler.h>
  13. #include <LibWeb/HTML/EventNames.h>
  14. #include <LibWeb/HTML/MessageEvent.h>
  15. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  16. #include <LibWeb/HTML/StructuredSerialize.h>
  17. #include <LibWeb/HTML/WorkerGlobalScope.h>
  18. #include <LibWeb/HTML/WorkerLocation.h>
  19. #include <LibWeb/HTML/WorkerNavigator.h>
  20. namespace Web::HTML {
  21. JS_DEFINE_ALLOCATOR(WorkerGlobalScope);
  22. WorkerGlobalScope::WorkerGlobalScope(JS::Realm& realm, Web::Page& page)
  23. : DOM::EventTarget(realm)
  24. , m_page(page)
  25. {
  26. }
  27. WorkerGlobalScope::~WorkerGlobalScope() = default;
  28. void WorkerGlobalScope::initialize_web_interfaces(Badge<WorkerEnvironmentSettingsObject>)
  29. {
  30. auto& realm = this->realm();
  31. Base::initialize(realm);
  32. // FIXME: Handle shared worker
  33. add_dedicated_worker_exposed_interfaces(*this);
  34. Object::set_prototype(&Bindings::ensure_web_prototype<Bindings::WorkerGlobalScopePrototype>(realm, "WorkerGlobalScope"));
  35. WindowOrWorkerGlobalScopeMixin::initialize(realm);
  36. m_navigator = WorkerNavigator::create(*this);
  37. }
  38. void WorkerGlobalScope::visit_edges(Cell::Visitor& visitor)
  39. {
  40. Base::visit_edges(visitor);
  41. WindowOrWorkerGlobalScopeMixin::visit_edges(visitor);
  42. visitor.visit(m_location);
  43. visitor.visit(m_navigator);
  44. }
  45. void WorkerGlobalScope::set_outside_port(NonnullOwnPtr<Core::BufferedLocalSocket> port)
  46. {
  47. m_outside_port = move(port);
  48. // FIXME: Hide this logic in MessagePort
  49. m_outside_port->set_notifications_enabled(true);
  50. m_outside_port->on_ready_to_read = [this] {
  51. auto& vm = this->vm();
  52. auto& realm = this->realm();
  53. auto num_bytes_ready = MUST(m_outside_port->pending_bytes());
  54. switch (m_outside_port_state) {
  55. case PortState::Header: {
  56. if (num_bytes_ready < 8)
  57. break;
  58. auto const magic = MUST(m_outside_port->read_value<u32>());
  59. if (magic != 0xDEADBEEF) {
  60. m_outside_port_state = PortState::Error;
  61. break;
  62. }
  63. m_outside_port_incoming_message_size = MUST(m_outside_port->read_value<u32>());
  64. num_bytes_ready -= 8;
  65. m_outside_port_state = PortState::Data;
  66. }
  67. [[fallthrough]];
  68. case PortState::Data: {
  69. if (num_bytes_ready < m_outside_port_incoming_message_size)
  70. break;
  71. SerializationRecord rec; // FIXME: Keep in class scope
  72. rec.resize(m_outside_port_incoming_message_size / sizeof(u32));
  73. MUST(m_outside_port->read_until_filled(to_bytes(rec.span())));
  74. TemporaryExecutionContext cxt(relevant_settings_object(*this));
  75. MessageEventInit event_init {};
  76. event_init.data = MUST(structured_deserialize(vm, rec, realm, {}));
  77. // FIXME: Fill in the rest of the info from MessagePort
  78. this->dispatch_event(MessageEvent::create(realm, EventNames::message, event_init));
  79. m_outside_port_state = PortState::Header;
  80. break;
  81. }
  82. case PortState::Error:
  83. VERIFY_NOT_REACHED();
  84. break;
  85. }
  86. };
  87. }
  88. // https://html.spec.whatwg.org/multipage/workers.html#importing-scripts-and-libraries
  89. WebIDL::ExceptionOr<void> WorkerGlobalScope::import_scripts(Vector<String> urls)
  90. {
  91. // The algorithm may optionally be customized by supplying custom perform the fetch hooks,
  92. // which if provided will be used when invoking fetch a classic worker-imported script.
  93. // NOTE: Service Workers is an example of a specification that runs this algorithm with its own options for the perform the fetch hook.
  94. // FIXME: 1. If worker global scope's type is "module", throw a TypeError exception.
  95. // FIXME: 2. Let settings object be the current settings object.
  96. // 3. If urls is empty, return.
  97. if (urls.is_empty())
  98. return {};
  99. // FIXME: 4. Parse each value in urls relative to settings object. If any fail, throw a "SyntaxError" DOMException.
  100. // FIXME: 5. For each url in the resulting URL records, run these substeps:
  101. // 1. Fetch a classic worker-imported script given url and settings object, passing along any custom perform the fetch steps provided.
  102. // If this succeeds, let script be the result. Otherwise, rethrow the exception.
  103. // 2. Run the classic script script, with the rethrow errors argument set to true.
  104. // NOTE: script will run until it either returns, fails to parse, fails to catch an exception,
  105. // or gets prematurely aborted by the terminate a worker algorithm defined above.
  106. // If an exception was thrown or if the script was prematurely aborted, then abort all these steps,
  107. // letting the exception or aborting continue to be processed by the calling script.
  108. return {};
  109. }
  110. // https://html.spec.whatwg.org/multipage/workers.html#dom-workerglobalscope-location
  111. JS::NonnullGCPtr<WorkerLocation> WorkerGlobalScope::location() const
  112. {
  113. // The location attribute must return the WorkerLocation object whose associated WorkerGlobalScope object is the WorkerGlobalScope object.
  114. return *m_location;
  115. }
  116. // https://html.spec.whatwg.org/multipage/workers.html#dom-worker-navigator
  117. JS::NonnullGCPtr<WorkerNavigator> WorkerGlobalScope::navigator() const
  118. {
  119. // The navigator attribute of the WorkerGlobalScope interface must return an instance of the WorkerNavigator interface,
  120. // which represents the identity and state of the user agent (the client).
  121. return *m_navigator;
  122. }
  123. WebIDL::ExceptionOr<void> WorkerGlobalScope::post_message(JS::Value message, JS::Value)
  124. {
  125. auto& realm = this->realm();
  126. auto& vm = this->vm();
  127. // FIXME: Use the with-transfer variant, which should(?) prepend the magic + size at the front
  128. auto data = TRY(structured_serialize(vm, message));
  129. Array<u32, 2> header = { 0xDEADBEEF, static_cast<u32>(data.size() * sizeof(u32)) };
  130. if (auto const err = m_outside_port->write_until_depleted(to_readonly_bytes(header.span())); err.is_error())
  131. return WebIDL::DataCloneError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("{}", err.error())));
  132. if (auto const err = m_outside_port->write_until_depleted(to_readonly_bytes(data.span())); err.is_error())
  133. return WebIDL::DataCloneError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("{}", err.error())));
  134. return {};
  135. }
  136. #undef __ENUMERATE
  137. #define __ENUMERATE(attribute_name, event_name) \
  138. void WorkerGlobalScope::set_##attribute_name(WebIDL::CallbackType* value) \
  139. { \
  140. set_event_handler_attribute(event_name, move(value)); \
  141. } \
  142. WebIDL::CallbackType* WorkerGlobalScope::attribute_name() \
  143. { \
  144. return event_handler_attribute(event_name); \
  145. }
  146. ENUMERATE_WORKER_GLOBAL_SCOPE_EVENT_HANDLERS(__ENUMERATE)
  147. #undef __ENUMERATE
  148. }