Worker.cpp 8.6 KB

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