Worker.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. /*
  2. * Copyright (c) 2022, Ben Abraham <ben.d.abraham@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <LibJS/Runtime/ConsoleObject.h>
  8. #include <LibJS/Runtime/Realm.h>
  9. #include <LibWeb/Bindings/MainThreadVM.h>
  10. #include <LibWeb/HTML/Scripting/Environments.h>
  11. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  12. #include <LibWeb/HTML/Worker.h>
  13. #include <LibWeb/HTML/WorkerDebugConsoleClient.h>
  14. #include <LibWeb/WebIDL/ExceptionOr.h>
  15. namespace Web::HTML {
  16. JS_DEFINE_ALLOCATOR(Worker);
  17. // https://html.spec.whatwg.org/multipage/workers.html#dedicated-workers-and-the-worker-interface
  18. Worker::Worker(String const& script_url, WorkerOptions const options, DOM::Document& document)
  19. : DOM::EventTarget(document.realm())
  20. , m_script_url(script_url)
  21. , m_options(options)
  22. , m_document(&document)
  23. {
  24. }
  25. void Worker::initialize(JS::Realm& realm)
  26. {
  27. Base::initialize(realm);
  28. set_prototype(&Bindings::ensure_web_prototype<Bindings::WorkerPrototype>(realm, "Worker"));
  29. }
  30. void Worker::visit_edges(Cell::Visitor& visitor)
  31. {
  32. Base::visit_edges(visitor);
  33. visitor.visit(m_document);
  34. visitor.visit(m_outside_port);
  35. }
  36. // https://html.spec.whatwg.org/multipage/workers.html#dom-worker
  37. WebIDL::ExceptionOr<JS::NonnullGCPtr<Worker>> Worker::create(String const& script_url, WorkerOptions const options, DOM::Document& document)
  38. {
  39. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Creating worker with script_url = {}", script_url);
  40. // Returns a new Worker object. scriptURL will be fetched and executed in the background,
  41. // creating a new global environment for which worker represents the communication channel.
  42. // options can be used to define the name of that global environment via the name option,
  43. // primarily for debugging purposes. It can also ensure this new global environment supports
  44. // JavaScript modules (specify type: "module"), and if that is specified, can also be used
  45. // to specify how scriptURL is fetched through the credentials option.
  46. // FIXME: 1. The user agent may throw a "SecurityError" DOMException if the request violates
  47. // a policy decision (e.g. if the user agent is configured to not allow the page to start dedicated workers).
  48. // Technically not a fixme if our policy is not to throw errors :^)
  49. // 2. Let outside settings be the current settings object.
  50. auto& outside_settings = document.relevant_settings_object();
  51. // 3. Parse the scriptURL argument relative to outside settings.
  52. auto url = document.parse_url(script_url.to_deprecated_string());
  53. // 4. If this fails, throw a "SyntaxError" DOMException.
  54. if (!url.is_valid()) {
  55. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Invalid URL loaded '{}'.", script_url);
  56. return WebIDL::SyntaxError::create(document.realm(), "url is not valid"_fly_string);
  57. }
  58. // 5. Let worker URL be the resulting URL record.
  59. // 6. Let worker be a new Worker object.
  60. auto worker = document.heap().allocate<Worker>(document.realm(), script_url, options, document);
  61. // 7. Let outside port be a new MessagePort in outside settings's Realm.
  62. auto outside_port = MessagePort::create(outside_settings.realm());
  63. // 8. Associate the outside port with worker
  64. worker->m_outside_port = outside_port;
  65. // 9. Run this step in parallel:
  66. // 1. Run a worker given worker, worker URL, outside settings, outside port, and options.
  67. worker->run_a_worker(url, outside_settings, *outside_port, options);
  68. // 10. Return worker
  69. return worker;
  70. }
  71. // https://html.spec.whatwg.org/multipage/workers.html#run-a-worker
  72. void Worker::run_a_worker(AK::URL& url, EnvironmentSettingsObject& outside_settings, MessagePort&, WorkerOptions const& options)
  73. {
  74. // 1. Let is shared be true if worker is a SharedWorker object, and false otherwise.
  75. // FIXME: SharedWorker support
  76. // 2. Let owner be the relevant owner to add given outside settings.
  77. // FIXME: Support WorkerGlobalScope options
  78. if (!is<HTML::WindowEnvironmentSettingsObject>(outside_settings))
  79. TODO();
  80. // 3. Let parent worker global scope be null.
  81. // 4. If owner is a WorkerGlobalScope object (i.e., we are creating a nested dedicated worker),
  82. // then set parent worker global scope to owner.
  83. // FIXME: Support for nested workers.
  84. // 5. Let unsafeWorkerCreationTime be the unsafe shared current time.
  85. // 6. Let agent be the result of obtaining a dedicated/shared worker agent given outside settings
  86. // and is shared. Run the rest of these steps in that agent.
  87. // Note: This spawns a new process to act as the 'agent' for the worker.
  88. m_agent = heap().allocate_without_realm<WorkerAgent>(url, options);
  89. auto& socket = m_agent->socket();
  90. // FIXME: Hide this logic in MessagePort
  91. socket.set_notifications_enabled(true);
  92. socket.on_ready_to_read = [this] {
  93. auto& socket = this->m_agent->socket();
  94. auto& vm = this->vm();
  95. auto& realm = this->realm();
  96. auto num_bytes_ready = MUST(socket.pending_bytes());
  97. switch (m_outside_port_state) {
  98. case PortState::Header: {
  99. if (num_bytes_ready < 8)
  100. break;
  101. auto const magic = MUST(socket.read_value<u32>());
  102. if (magic != 0xDEADBEEF) {
  103. m_outside_port_state = PortState::Error;
  104. break;
  105. }
  106. m_outside_port_incoming_message_size = MUST(socket.read_value<u32>());
  107. num_bytes_ready -= 8;
  108. m_outside_port_state = PortState::Data;
  109. }
  110. [[fallthrough]];
  111. case PortState::Data: {
  112. if (num_bytes_ready < m_outside_port_incoming_message_size)
  113. break;
  114. SerializationRecord rec; // FIXME: Keep in class scope
  115. rec.resize(m_outside_port_incoming_message_size / sizeof(u32));
  116. MUST(socket.read_until_filled(to_bytes(rec.span())));
  117. TemporaryExecutionContext cxt(relevant_settings_object(*this));
  118. VERIFY(&realm == vm.current_realm());
  119. MessageEventInit event_init {};
  120. event_init.data = MUST(structured_deserialize(vm, rec, realm, {}));
  121. // FIXME: Fill in the rest of the info from MessagePort
  122. this->dispatch_event(MessageEvent::create(realm, EventNames::message, event_init));
  123. m_outside_port_state = PortState::Header;
  124. break;
  125. }
  126. case PortState::Error:
  127. VERIFY_NOT_REACHED();
  128. break;
  129. }
  130. };
  131. }
  132. // https://html.spec.whatwg.org/multipage/workers.html#dom-worker-terminate
  133. WebIDL::ExceptionOr<void> Worker::terminate()
  134. {
  135. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Terminate");
  136. return {};
  137. }
  138. // https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage
  139. WebIDL::ExceptionOr<void> Worker::post_message(JS::Value message, JS::Value)
  140. {
  141. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Post Message: {}", message.to_string_without_side_effects());
  142. // FIXME: 1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
  143. // FIXME: 2. Let options be «[ "transfer" → transfer ]».
  144. // FIXME: 3. Run the message port post message steps providing this, targetPort, message and options.
  145. auto& realm = this->realm();
  146. auto& vm = this->vm();
  147. // FIXME: Use the with-transfer variant, which should(?) prepend the magic + size at the front
  148. auto data = TRY(structured_serialize(vm, message));
  149. Array<u32, 2> header = { 0xDEADBEEF, static_cast<u32>(data.size() * sizeof(u32)) };
  150. if (auto const err = m_agent->socket().write_until_depleted(to_readonly_bytes(header.span())); err.is_error())
  151. return WebIDL::DataCloneError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("{}", err.error())));
  152. if (auto const err = m_agent->socket().write_until_depleted(to_readonly_bytes(data.span())); err.is_error())
  153. return WebIDL::DataCloneError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("{}", err.error())));
  154. return {};
  155. }
  156. #undef __ENUMERATE
  157. #define __ENUMERATE(attribute_name, event_name) \
  158. void Worker::set_##attribute_name(WebIDL::CallbackType* value) \
  159. { \
  160. set_event_handler_attribute(event_name, move(value)); \
  161. } \
  162. WebIDL::CallbackType* Worker::attribute_name() \
  163. { \
  164. return event_handler_attribute(event_name); \
  165. }
  166. ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE)
  167. #undef __ENUMERATE
  168. } // namespace Web::HTML