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