Worker.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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/Worker.h>
  12. #include <LibWeb/HTML/WorkerDebugConsoleClient.h>
  13. #include <LibWeb/WebIDL/ExceptionOr.h>
  14. namespace Web::HTML {
  15. // https://html.spec.whatwg.org/multipage/workers.html#dedicated-workers-and-the-worker-interface
  16. Worker::Worker(String const& script_url, WorkerOptions const options, DOM::Document& document)
  17. : DOM::EventTarget(document.realm())
  18. , m_script_url(script_url)
  19. , m_options(options)
  20. , m_document(&document)
  21. , m_custom_data()
  22. , m_worker_vm(JS::VM::create(adopt_own(m_custom_data)).release_value_but_fixme_should_propagate_errors())
  23. , m_interpreter(JS::Interpreter::create<JS::GlobalObject>(m_worker_vm))
  24. , m_interpreter_scope(*m_interpreter)
  25. , m_implicit_port(MessagePort::create(document.realm()).release_value_but_fixme_should_propagate_errors())
  26. {
  27. }
  28. JS::ThrowCompletionOr<void> Worker::initialize(JS::Realm& realm)
  29. {
  30. MUST_OR_THROW_OOM(Base::initialize(realm));
  31. set_prototype(&Bindings::ensure_web_prototype<Bindings::WorkerPrototype>(realm, "Worker"));
  32. return {};
  33. }
  34. void Worker::visit_edges(Cell::Visitor& visitor)
  35. {
  36. Base::visit_edges(visitor);
  37. visitor.visit(m_document.ptr());
  38. visitor.visit(m_implicit_port.ptr());
  39. visitor.visit(m_outside_port.ptr());
  40. }
  41. // https://html.spec.whatwg.org/multipage/workers.html#dom-worker
  42. WebIDL::ExceptionOr<JS::NonnullGCPtr<Worker>> Worker::create(String const& script_url, WorkerOptions const options, DOM::Document& document)
  43. {
  44. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Creating worker with script_url = {}", script_url);
  45. // Returns a new Worker object. scriptURL will be fetched and executed in the background,
  46. // creating a new global environment for which worker represents the communication channel.
  47. // options can be used to define the name of that global environment via the name option,
  48. // primarily for debugging purposes. It can also ensure this new global environment supports
  49. // JavaScript modules (specify type: "module"), and if that is specified, can also be used
  50. // to specify how scriptURL is fetched through the credentials option.
  51. // FIXME: 1. The user agent may throw a "SecurityError" DOMException if the request violates
  52. // a policy decision (e.g. if the user agent is configured to not allow the page to start dedicated workers).
  53. // Technically not a fixme if our policy is not to throw errors :^)
  54. // 2. Let outside settings be the current settings object.
  55. auto& outside_settings = document.relevant_settings_object();
  56. // 3. Parse the scriptURL argument relative to outside settings.
  57. auto url = document.parse_url(script_url.to_deprecated_string());
  58. // 4. If this fails, throw a "SyntaxError" DOMException.
  59. if (!url.is_valid()) {
  60. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Invalid URL loaded '{}'.", script_url);
  61. return WebIDL::SyntaxError::create(document.realm(), "url is not valid");
  62. }
  63. // 5. Let worker URL be the resulting URL record.
  64. // 6. Let worker be a new Worker object.
  65. auto worker = MUST_OR_THROW_OOM(document.heap().allocate<Worker>(document.realm(), script_url, options, document));
  66. // 7. Let outside port be a new MessagePort in outside settings's Realm.
  67. auto outside_port = TRY(MessagePort::create(outside_settings.realm()));
  68. // 8. Associate the outside port with worker
  69. worker->m_outside_port = outside_port;
  70. // 9. Run this step in parallel:
  71. // 1. Run a worker given worker, worker URL, outside settings, outside port, and options.
  72. worker->run_a_worker(url, outside_settings, *outside_port, options);
  73. // 10. Return worker
  74. return worker;
  75. }
  76. // https://html.spec.whatwg.org/multipage/workers.html#run-a-worker
  77. void Worker::run_a_worker(AK::URL& url, EnvironmentSettingsObject& outside_settings, MessagePort& outside_port, WorkerOptions const& options)
  78. {
  79. // 1. Let is shared be true if worker is a SharedWorker object, and false otherwise.
  80. // FIXME: SharedWorker support
  81. auto is_shared = false;
  82. auto is_top_level = false;
  83. // 2. Let owner be the relevant owner to add given outside settings.
  84. // FIXME: Support WorkerGlobalScope options
  85. if (!is<HTML::WindowEnvironmentSettingsObject>(outside_settings))
  86. TODO();
  87. // 3. Let parent worker global scope be null.
  88. // 4. If owner is a WorkerGlobalScope object (i.e., we are creating a nested dedicated worker),
  89. // then set parent worker global scope to owner.
  90. // FIXME: Support for nested workers.
  91. // 5. Let unsafeWorkerCreationTime be the unsafe shared current time.
  92. // 6. Let agent be the result of obtaining a dedicated/shared worker agent given outside settings
  93. // and is shared. Run the rest of these steps in that agent.
  94. // NOTE: This is effectively the worker's vm
  95. // 7. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  96. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  97. *m_worker_vm,
  98. [&](JS::Realm& realm) -> JS::Object* {
  99. // 7a. For the global object, if is shared is true, create a new SharedWorkerGlobalScope object.
  100. // 7b. Otherwise, create a new DedicatedWorkerGlobalScope object.
  101. // FIXME: Proper support for both SharedWorkerGlobalScope and DedicatedWorkerGlobalScope
  102. if (is_shared)
  103. TODO();
  104. // FIXME: Make and use subclasses of WorkerGlobalScope, however this requires JS::GlobalObject to
  105. // play nicely with the IDL interpreter, to make spec-compliant extensions, which it currently does not.
  106. m_worker_scope = m_worker_vm->heap().allocate_without_realm<JS::GlobalObject>(realm);
  107. return m_worker_scope.ptr();
  108. },
  109. nullptr);
  110. auto& console_object = *realm_execution_context->realm->intrinsics().console_object();
  111. m_worker_realm = realm_execution_context->realm;
  112. m_console = adopt_ref(*new WorkerDebugConsoleClient(console_object.console()));
  113. console_object.console().set_client(*m_console);
  114. // FIXME: This should be done with IDL
  115. u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable;
  116. m_worker_scope->define_native_function(
  117. m_worker_scope->shape().realm(),
  118. "postMessage",
  119. [this](auto& vm) {
  120. // This is the implementation of the function that the spawned worked calls
  121. // https://html.spec.whatwg.org/multipage/workers.html#dom-dedicatedworkerglobalscope-postmessage
  122. // The postMessage(message, transfer) and postMessage(message, options) methods on DedicatedWorkerGlobalScope
  123. // objects act as if, when invoked, it immediately invoked the respective postMessage(message, transfer) and
  124. // postMessage(message, options) on the port, with the same arguments, and returned the same return value
  125. auto message = vm.argument(0);
  126. // FIXME: `transfer` not support by post_message yet
  127. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Inner post_message");
  128. // FIXME: This is a bit of a hack, in reality, we should m_outside_port->post_message and the onmessage event
  129. // should bubble up to the Worker itself from there.
  130. auto& event_loop = get_vm_event_loop(m_document->realm().vm());
  131. event_loop.task_queue().add(HTML::Task::create(HTML::Task::Source::PostedMessage, nullptr, [this, message] {
  132. MessageEventInit event_init {};
  133. event_init.data = message;
  134. event_init.origin = "<origin>"_string.release_value_but_fixme_should_propagate_errors();
  135. dispatch_event(MessageEvent::create(*m_worker_realm, HTML::EventNames::message, event_init).release_value_but_fixme_should_propagate_errors());
  136. }));
  137. return JS::js_undefined();
  138. },
  139. 2, attr);
  140. // 8. Let worker global scope be the global object of realm execution context's Realm component.
  141. // NOTE: This is the DedicatedWorkerGlobalScope or SharedWorkerGlobalScope object created in the previous step.
  142. // 9. Set up a worker environment settings object with realm execution context,
  143. // outside settings, and unsafeWorkerCreationTime, and let inside settings be the result.
  144. m_inner_settings = WorkerEnvironmentSettingsObject::setup(move(realm_execution_context));
  145. // 10. Set worker global scope's name to the value of options's name member.
  146. // FIXME: name property requires the SharedWorkerGlobalScope or DedicatedWorkerGlobalScope child class to be used
  147. // 11. Append owner to worker global scope's owner set.
  148. // FIXME: support for 'owner' set on WorkerGlobalScope
  149. // 12. If is shared is true, then:
  150. if (is_shared) {
  151. // FIXME: Shared worker support
  152. // 1. Set worker global scope's constructor origin to outside settings's origin.
  153. // 2. Set worker global scope's constructor url to url.
  154. // 3. Set worker global scope's type to the value of options's type member.
  155. // 4. Set worker global scope's credentials to the value of options's credentials member.
  156. }
  157. // 13. Let destination be "sharedworker" if is shared is true, and "worker" otherwise.
  158. // 14. Obtain script by switching on the value of options's type member:
  159. // classic: Fetch a classic worker script given url, outside settings, destination, and inside settings.
  160. // module: Fetch a module worker script graph given url, outside settings, destination, the value of the
  161. // credentials member of options, and inside settings.
  162. if (options.type != "classic") {
  163. dbgln_if(WEB_WORKER_DEBUG, "Unsupported script type {} for LibWeb/Worker", options.type);
  164. TODO();
  165. }
  166. ResourceLoader::the().load(
  167. url,
  168. [this, is_shared, is_top_level, url, &outside_port](auto data, auto&, auto) {
  169. // In both cases, to perform the fetch given request, perform the following steps if the is top-level flag is set:
  170. if (is_top_level) {
  171. // 1. Set request's reserved client to inside settings.
  172. // 2. Fetch request, and asynchronously wait to run the remaining steps
  173. // as part of fetch's process response for the response response.
  174. // Implied
  175. // 3. Set worker global scope's url to response's url.
  176. // 4. Initialize worker global scope's policy container given worker global scope, response, and inside settings.
  177. // FIXME: implement policy container
  178. // 5. If the Run CSP initialization for a global object algorithm returns "Blocked" when executed upon worker
  179. // global scope, set response to a network error. [CSP]
  180. // FIXME: CSP support
  181. // 6. If worker global scope's embedder policy's value is compatible with cross-origin isolation and is shared is true,
  182. // then set agent's agent cluster's cross-origin isolation mode to "logical" or "concrete".
  183. // The one chosen is implementation-defined.
  184. // FIXME: CORS policy support
  185. // 7. If the result of checking a global object's embedder policy with worker global scope, outside settings,
  186. // and response is false, then set response to a network error.
  187. // FIXME: Embed policy support
  188. // 8. Set worker global scope's cross-origin isolated capability to true if agent's agent cluster's cross-origin
  189. // isolation mode is "concrete".
  190. // FIXME: CORS policy support
  191. if (!is_shared) {
  192. // 9. If is shared is false and owner's cross-origin isolated capability is false, then set worker
  193. // global scope's cross-origin isolated capability to false.
  194. // 10. If is shared is false and response's url's scheme is "data", then set worker global scope's
  195. // cross-origin isolated capability to false.
  196. }
  197. }
  198. if (data.is_null()) {
  199. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Failed to load {}", url);
  200. return;
  201. }
  202. // Asynchronously complete the perform the fetch steps with response.
  203. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Script ready!");
  204. auto script = ClassicScript::create(url.to_deprecated_string(), data, *m_inner_settings, AK::URL());
  205. // NOTE: Steps 15-31 below pick up after step 14 in the main context, steps 1-10 above
  206. // are only for validation when used in a top-level case (ie: from a Window)
  207. // 15. Associate worker with worker global scope.
  208. // FIXME: Global scope association
  209. // 16. Let inside port be a new MessagePort object in inside settings's Realm.
  210. auto inside_port = MessagePort::create(m_inner_settings->realm()).release_value_but_fixme_should_propagate_errors();
  211. // 17. Associate inside port with worker global scope.
  212. // FIXME: Global scope association
  213. // 18. Entangle outside port and inside port.
  214. outside_port.entangle_with(*inside_port);
  215. // 19. Create a new WorkerLocation object and associate it with worker global scope.
  216. // 20. Closing orphan workers: Start monitoring the worker such that no sooner than it
  217. // stops being a protected worker, and no later than it stops being a permissible worker,
  218. // worker global scope's closing flag is set to true.
  219. // FIXME: Worker monitoring and cleanup
  220. // 21. Suspending workers: Start monitoring the worker, such that whenever worker global scope's
  221. // closing flag is false and the worker is a suspendable worker, the user agent suspends
  222. // execution of script in that worker until such time as either the closing flag switches to
  223. // true or the worker stops being a suspendable worker
  224. // FIXME: Worker suspending
  225. // 22. Set inside settings's execution ready flag.
  226. // FIXME: Implement worker settings object
  227. // 23. If script is a classic script, then run the classic script script.
  228. // Otherwise, it is a module script; run the module script script.
  229. auto result = script->run();
  230. // 24. Enable outside port's port message queue.
  231. outside_port.start();
  232. // 25. If is shared is false, enable the port message queue of the worker's implicit port.
  233. if (!is_shared)
  234. m_implicit_port->start();
  235. // 26. If is shared is true, then queue a global task on DOM manipulation task source given worker
  236. // global scope to fire an event named connect at worker global scope, using MessageEvent,
  237. // with the data attribute initialized to the empty string, the ports attribute initialized
  238. // to a new frozen array containing inside port, and the source attribute initialized to inside port.
  239. // FIXME: Shared worker support
  240. // 27. Enable the client message queue of the ServiceWorkerContainer object whose associated service
  241. // worker client is worker global scope's relevant settings object.
  242. // FIXME: Understand....and support worker global settings
  243. // 28. Event loop: Run the responsible event loop specified by inside settings until it is destroyed.
  244. },
  245. [](auto&, auto) {
  246. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: HONK! Failed to load script.");
  247. });
  248. }
  249. // https://html.spec.whatwg.org/multipage/workers.html#dom-worker-terminate
  250. WebIDL::ExceptionOr<void> Worker::terminate()
  251. {
  252. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Terminate");
  253. return {};
  254. }
  255. // https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage
  256. void Worker::post_message(JS::Value message, JS::Value)
  257. {
  258. dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Post Message: {}", MUST(message.to_string_without_side_effects()));
  259. // 1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
  260. auto& target_port = m_outside_port;
  261. // 2. Let options be «[ "transfer" → transfer ]».
  262. // 3. Run the message port post message steps providing this, targetPort, message and options.
  263. target_port->post_message(message);
  264. }
  265. #undef __ENUMERATE
  266. #define __ENUMERATE(attribute_name, event_name) \
  267. void Worker::set_##attribute_name(WebIDL::CallbackType* value) \
  268. { \
  269. set_event_handler_attribute(event_name, move(value)); \
  270. } \
  271. WebIDL::CallbackType* Worker::attribute_name() \
  272. { \
  273. return event_handler_attribute(event_name); \
  274. }
  275. ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE)
  276. #undef __ENUMERATE
  277. } // namespace Web::HTML