Skip to main content

script/dom/workers/
sharedworker.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::{Arc, Condvar, LazyLock, Mutex};
9
10use crossbeam_channel::{Sender, unbounded};
11#[cfg(feature = "devtools")]
12use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
13use dom_struct::dom_struct;
14use js::context::JSContext;
15use js::rust::HandleObject;
16use malloc_size_of_derive::MallocSizeOf;
17use net_traits::pub_domains::reg_suffix;
18use net_traits::request::{CredentialsMode, Referrer};
19use script_bindings::reflector::reflect_dom_object_with_proto;
20#[cfg(feature = "devtools")]
21use servo_base::generic_channel;
22use servo_base::id::WorkerId;
23use servo_constellation_traits::{MessagePortImpl, WorkerScriptLoadOrigin};
24use servo_url::{Host, ImmutableOrigin, ServoUrl};
25use uuid::Uuid;
26
27use crate::conversions::Convert;
28use crate::dom::abstractworker::SimpleWorkerErrorHandler;
29use crate::dom::bindings::codegen::Bindings::SharedWorkerBinding::{
30    SharedWorkerMethods, SharedWorkerOptions,
31};
32use crate::dom::bindings::codegen::Bindings::WorkerBinding::WorkerType;
33use crate::dom::bindings::codegen::UnionTypes::{
34    StringOrSharedWorkerOptions, TrustedScriptURLOrUSVString,
35};
36use crate::dom::bindings::error::{Error, Fallible};
37use crate::dom::bindings::inheritance::Castable;
38use crate::dom::bindings::refcounted::Trusted;
39use crate::dom::bindings::reflector::DomGlobal;
40use crate::dom::bindings::root::{Dom, DomRoot};
41use crate::dom::bindings::trace::CustomTraceable;
42use crate::dom::bindings::transferable::Transferable;
43use crate::dom::eventtarget::EventTarget;
44use crate::dom::globalscope::GlobalScope;
45use crate::dom::messageport::MessagePort;
46use crate::dom::sharedworkerglobalscope::{
47    SharedWorkerControlMsg, SharedWorkerGlobalScope, SharedWorkerScriptMsg,
48};
49use crate::dom::trustedtypes::trustedscripturl::TrustedScriptURL;
50use crate::dom::window::Window;
51use crate::dom::workerglobalscope::prepare_workerscope_init;
52use crate::tasks::task::TaskOnce;
53use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
54
55/// <https://html.spec.whatwg.org/multipage/#shared-workers-and-the-sharedworker-interface>
56#[dom_struct]
57pub(crate) struct SharedWorker {
58    eventtarget: EventTarget,
59    port: Dom<MessagePort>,
60    _control_sender: Sender<SharedWorkerControlMsg>,
61}
62
63pub(crate) type TrustedSharedWorkerAddress = Trusted<SharedWorker>;
64
65/// Key used by the script-side SharedWorker registry.
66#[derive(Clone)]
67struct SharedWorkerKey {
68    storage_key: SharedWorkerStorageKey,
69    constructor_origin: ImmutableOrigin,
70    constructor_url: ServoUrl,
71    name: String,
72}
73
74impl SharedWorkerKey {
75    fn matches(
76        &self,
77        storage_key: &SharedWorkerStorageKey,
78        constructor_origin: &ImmutableOrigin,
79        constructor_url: &ServoUrl,
80        name: &str,
81    ) -> bool {
82        self.storage_key == *storage_key &&
83            self.constructor_origin == *constructor_origin &&
84            self.constructor_url == *constructor_url &&
85            self.name == name
86    }
87}
88
89#[derive(Clone, Eq, MallocSizeOf, PartialEq)]
90enum SharedWorkerSite {
91    Opaque(ImmutableOrigin),
92    Tuple { scheme: String, host: Host },
93}
94
95impl SharedWorkerSite {
96    /// <https://html.spec.whatwg.org/multipage/#obtain-a-site>
97    fn from_origin(origin: ImmutableOrigin) -> Self {
98        match origin {
99            // 1. If origin is an opaque origin, then return origin.
100            ImmutableOrigin::Opaque(_) => SharedWorkerSite::Opaque(origin),
101            // 3. Return (origin's scheme, origin's host's registrable domain).
102            ImmutableOrigin::Tuple(scheme, Host::Domain(domain), _) => SharedWorkerSite::Tuple {
103                scheme,
104                host: Host::Domain(reg_suffix(&domain).to_owned()),
105            },
106            // 2. If origin's host's registrable domain is null, then return
107            // (origin's scheme, origin's host).
108            ImmutableOrigin::Tuple(scheme, host, _) => SharedWorkerSite::Tuple { scheme, host },
109        }
110    }
111}
112
113#[derive(Clone, Eq, MallocSizeOf, PartialEq)]
114pub(crate) struct SharedWorkerStorageKey {
115    origin: ImmutableOrigin,
116    top_level_site: Option<SharedWorkerSite>,
117}
118
119impl SharedWorkerStorageKey {
120    /// <https://storage.spec.whatwg.org/#storage-key>
121    fn for_window(global: &GlobalScope, window: &Window) -> Self {
122        // A storage key is a tuple consisting of an origin (an origin).
123        // This is expected to change; see Client-Side Storage Partitioning.
124        let origin = global.obtain_storage_key_for_non_storage_purposes();
125
126        let top_level_site = window
127            .top_level_document_if_local()
128            .map(|document| SharedWorkerSite::from_origin(document.origin().immutable().clone()));
129
130        SharedWorkerStorageKey {
131            origin,
132            top_level_site,
133        }
134    }
135}
136
137enum SharedWorkerRegistryState {
138    Creating { waiters: usize },
139    Created(SharedWorkerRegistration),
140    Failed { waiters: usize },
141}
142
143struct SharedWorkerRegistryEntry {
144    key: SharedWorkerKey,
145    state: SharedWorkerRegistryState,
146}
147
148// A `SharedWorkerGlobalScope` object has associated constructor origin (an origin), constructor URL (a URL record), and credentials (a credentials mode), and extended lifetime (a boolean).
149#[derive(Clone)]
150struct SharedWorkerRegistration {
151    id: Uuid,
152    worker_type: WorkerType,
153    credentials: CredentialsMode,
154    extended_lifetime: bool,
155    worker_is_secure_context: bool,
156    closing: Arc<AtomicBool>,
157    sender: Sender<SharedWorkerScriptMsg>,
158    _control_sender: Sender<SharedWorkerControlMsg>,
159}
160
161// A user agent has an associated shared worker manager which is the result of starting a new parallel queue.
162// Each user agent has a single shared worker manager for simplicity.
163//
164// TODO: Move this script-side approximation to a proper shared worker manager,
165// likely constellation-owned.
166static SHARED_WORKERS: LazyLock<(Mutex<Vec<SharedWorkerRegistryEntry>>, Condvar)> =
167    LazyLock::new(|| (Mutex::new(Vec::new()), Condvar::new()));
168
169// Servo-internal registry states used to serialize the SharedWorker constructor's
170// manager lookup/create work and avoid duplicate SharedWorker creation. These
171// are not spec states.
172enum SharedWorkerClaimResult {
173    Created(SharedWorkerRegistration),
174    Claimed,
175    Failed,
176}
177
178fn prune_closed_shared_workers(workers: &mut Vec<SharedWorkerRegistryEntry>) {
179    workers.retain(|entry| match &entry.state {
180        SharedWorkerRegistryState::Creating { .. } => true,
181        SharedWorkerRegistryState::Created(worker) => !worker.closing.load(Ordering::SeqCst),
182        SharedWorkerRegistryState::Failed { waiters } => *waiters > 0,
183    });
184}
185
186fn find_matching_shared_worker(
187    workers: &[SharedWorkerRegistryEntry],
188    key: &SharedWorkerKey,
189) -> Option<usize> {
190    workers.iter().position(|entry| {
191        entry.key.matches(
192            &key.storage_key,
193            &key.constructor_origin,
194            &key.constructor_url,
195            &key.name,
196        )
197    })
198}
199
200/// <https://html.spec.whatwg.org/multipage/#dom-sharedworker>
201/// <https://html.spec.whatwg.org/multipage/#shared-worker-manager>
202fn find_or_claim_shared_worker(key: SharedWorkerKey) -> SharedWorkerClaimResult {
203    let (workers, ready) = &*SHARED_WORKERS;
204    let mut workers = workers.lock().expect("SharedWorker registry poisoned");
205
206    prune_closed_shared_workers(&mut workers);
207
208    let Some(index) = find_matching_shared_worker(&workers, &key) else {
209        workers.push(SharedWorkerRegistryEntry {
210            key,
211            state: SharedWorkerRegistryState::Creating { waiters: 0 },
212        });
213        return SharedWorkerClaimResult::Claimed;
214    };
215
216    match &mut workers[index].state {
217        SharedWorkerRegistryState::Creating { waiters } => *waiters += 1,
218        SharedWorkerRegistryState::Created(registration) => {
219            return SharedWorkerClaimResult::Created(registration.clone());
220        },
221        SharedWorkerRegistryState::Failed { waiters } => *waiters += 1,
222    };
223
224    loop {
225        workers = ready.wait(workers).expect("SharedWorker registry poisoned");
226
227        let Some(index) = find_matching_shared_worker(&workers, &key) else {
228            return SharedWorkerClaimResult::Failed;
229        };
230
231        match &mut workers[index].state {
232            SharedWorkerRegistryState::Creating { .. } => {},
233            SharedWorkerRegistryState::Created(registration) => {
234                return SharedWorkerClaimResult::Created(registration.clone());
235            },
236            SharedWorkerRegistryState::Failed { waiters } => {
237                debug_assert!(*waiters > 0);
238                if *waiters > 0 {
239                    *waiters -= 1;
240                }
241                if *waiters == 0 {
242                    workers.remove(index);
243                    // No notify needed here: this waiter has already observed
244                    // the failure and no waiter remains blocked on the condvar.
245                }
246                return SharedWorkerClaimResult::Failed;
247            },
248        }
249    }
250}
251
252fn transition_creating_to_created(
253    key: &SharedWorkerKey,
254    registration: SharedWorkerRegistration,
255) -> bool {
256    let (workers, ready) = &*SHARED_WORKERS;
257    let mut workers = workers.lock().expect("SharedWorker registry poisoned");
258    let index = find_matching_shared_worker(&workers, key);
259    debug_assert!(index.is_some(), "claimed SharedWorker entry should exist");
260    let Some(index) = index else {
261        ready.notify_all();
262        return false;
263    };
264
265    let entry_is_creating = matches!(
266        &workers[index].state,
267        SharedWorkerRegistryState::Creating { .. }
268    );
269    debug_assert!(
270        entry_is_creating,
271        "claimed SharedWorker entry should still be creating"
272    );
273    if !entry_is_creating {
274        ready.notify_all();
275        return false;
276    }
277
278    workers[index].state = SharedWorkerRegistryState::Created(registration);
279    ready.notify_all();
280    true
281}
282
283fn remove_creating_shared_worker(key: &SharedWorkerKey) {
284    let (workers, ready) = &*SHARED_WORKERS;
285    let mut workers = workers.lock().expect("SharedWorker registry poisoned");
286    let index = find_matching_shared_worker(&workers, key);
287    debug_assert!(index.is_some(), "claimed SharedWorker entry should exist");
288    let Some(index) = index else {
289        return;
290    };
291
292    let waiters = match &workers[index].state {
293        SharedWorkerRegistryState::Creating { waiters } => *waiters,
294        state => {
295            debug_assert!(
296                matches!(state, SharedWorkerRegistryState::Creating { .. }),
297                "claimed SharedWorker entry should still be creating"
298            );
299            return;
300        },
301    };
302
303    if waiters == 0 {
304        workers.remove(index);
305    } else {
306        workers[index].state = SharedWorkerRegistryState::Failed { waiters };
307    };
308    ready.notify_all();
309}
310
311fn send_connect_to_created_worker(
312    registration: &SharedWorkerRegistration,
313    inside_port: MessagePortImpl,
314) -> bool {
315    registration
316        .sender
317        .send(SharedWorkerScriptMsg::Connect(inside_port))
318        .is_err()
319}
320
321impl SharedWorker {
322    pub(crate) fn unregister_shared_worker(id: Uuid) {
323        let (workers, ready) = &*SHARED_WORKERS;
324        let mut workers = workers.lock().expect("SharedWorker registry poisoned");
325        let old_len = workers.len();
326        workers.retain(|entry| {
327            !matches!(&entry.state, SharedWorkerRegistryState::Created(worker) if worker.id == id)
328        });
329        if workers.len() != old_len {
330            ready.notify_all();
331        }
332    }
333
334    fn new_inherited(
335        port: &MessagePort,
336        control_sender: Sender<SharedWorkerControlMsg>,
337    ) -> SharedWorker {
338        SharedWorker {
339            eventtarget: EventTarget::new_inherited(),
340            port: Dom::from_ref(port),
341            _control_sender: control_sender,
342        }
343    }
344
345    fn new(
346        global: &GlobalScope,
347        proto: Option<HandleObject>,
348        port: &MessagePort,
349        control_sender: Sender<SharedWorkerControlMsg>,
350        cx: &mut js::context::JSContext,
351    ) -> DomRoot<SharedWorker> {
352        reflect_dom_object_with_proto(
353            cx,
354            Box::new(SharedWorker::new_inherited(port, control_sender)),
355            global,
356            proto,
357        )
358    }
359
360    pub(crate) fn dispatch_simple_error(cx: &mut JSContext, address: TrustedSharedWorkerAddress) {
361        let worker = address.root();
362        worker.upcast().fire_event(cx, atom!("error"));
363    }
364
365    fn queue_simple_error(global: &GlobalScope, address: TrustedSharedWorkerAddress) {
366        global.task_manager().dom_manipulation_task_source().queue(
367            task!(sharedworker_constructor_error: move |cx| {
368                SharedWorker::dispatch_simple_error(cx, address);
369            }),
370        );
371    }
372
373    fn create_entangled_inside_port(
374        cx: &mut JSContext,
375        global: &GlobalScope,
376        outside_port: &MessagePort,
377    ) -> Fallible<MessagePortImpl> {
378        let inside_port = MessagePort::new(cx, global);
379        global.track_message_port(&inside_port, None);
380        global.entangle_ports(
381            *outside_port.message_port_id(),
382            *inside_port.message_port_id(),
383        );
384        let (_, inside_port_impl) = inside_port.transfer(cx)?;
385        Ok(inside_port_impl)
386    }
387
388    /// Step 11 of onComplete of <https://html.spec.whatwg.org/multipage/#run-a-worker>
389    pub(crate) fn enable_outside_port_message_queue(
390        address: TrustedSharedWorkerAddress,
391        cx: &mut JSContext,
392    ) {
393        let worker = address.root();
394        let global = worker.global();
395        // Enable outside port's port message queue.
396        global.start_message_port(cx, worker.port.message_port_id());
397    }
398
399    /// Set online status for all living shared workers.
400    pub(crate) fn set_network_online_state(online: bool) {
401        let (workers, _ready) = &*SHARED_WORKERS;
402        let workers = workers.lock().expect("SharedWorker registry poisoned");
403        for entry in workers.iter() {
404            let SharedWorkerRegistryState::Created(registration) = &entry.state else {
405                continue;
406            };
407            if registration.closing.load(Ordering::SeqCst) {
408                continue;
409            }
410            let _ = registration
411                ._control_sender
412                .send(SharedWorkerControlMsg::SetNetworkOnlineState(online));
413        }
414    }
415}
416
417impl SharedWorkerMethods<crate::DomTypeHolder> for SharedWorker {
418    /// <https://html.spec.whatwg.org/multipage/#dom-sharedworker>
419    fn Constructor(
420        cx: &mut JSContext,
421        window: &Window,
422        proto: Option<HandleObject>,
423        script_url: TrustedScriptURLOrUSVString,
424        options: StringOrSharedWorkerOptions,
425    ) -> Fallible<DomRoot<SharedWorker>> {
426        let global = window.upcast::<GlobalScope>();
427
428        // Step 1. Let compliantScriptURL be the result of invoking the get trusted type
429        // compliant string algorithm with TrustedScriptURL, this's relevant global object,
430        // scriptURL, "SharedWorker constructor", and "script".
431        let compliant_script_url = TrustedScriptURL::get_trusted_type_compliant_string(
432            cx,
433            global,
434            script_url,
435            "SharedWorker constructor",
436        )?;
437
438        // Step 2. If options is a DOMString, set options to a new WorkerOptions
439        // dictionary whose name member is set to the value of options and whose other
440        // members are set to their default values.
441        let worker_options = match options {
442            StringOrSharedWorkerOptions::String(name) => {
443                let mut options = SharedWorkerOptions::empty();
444                options.parent.name = name;
445                options
446            },
447            StringOrSharedWorkerOptions::SharedWorkerOptions(options) => options,
448        };
449        let worker_name = worker_options.parent.name.clone();
450        let worker_type = worker_options.parent.type_;
451        let credentials = worker_options.parent.credentials.convert();
452        let extended_lifetime = worker_options.extendedLifetime;
453
454        // Step 3. Let outsideSettings be this's relevant settings object.
455
456        // Step 4. Let urlRecord be the result of encoding-parsing a URL given
457        // compliantScriptURL, relative to outsideSettings.
458        // Step 5. If urlRecord is failure, then throw a "SyntaxError" DOMException.
459        let Ok(worker_url) = global
460            .encoding_parse_a_url(&compliant_script_url.str())
461            .map(|url| ensure_blob_referenced_by_url_is_kept_alive(global, url))
462        else {
463            return Err(Error::Syntax(None));
464        };
465        let constructor_origin = global.origin().immutable().clone();
466        let constructor_url = worker_url.url();
467
468        // Step 6. Let outsidePort be a new MessagePort in outsideSettings's realm.
469        let outside_port = MessagePort::new(cx, global);
470        global.track_message_port(&outside_port, None);
471
472        // Step 7. Set this's port to outsidePort.
473        // Step 8. Let callerIsSecureContext be true if outsideSettings is a secure
474        // context; otherwise, false.
475        let caller_is_secure_context = global.is_secure_context();
476        // Step 9. Let outsideStorageKey be the result of running obtain a storage
477        // key for non-storage purposes given outsideSettings.
478        let outside_storage_key = SharedWorkerStorageKey::for_window(global, window);
479
480        let worker_name_string = worker_name.to_string();
481        let (control_sender, control_receiver) = unbounded();
482
483        // Step 10. Let worker be this.
484        let worker = SharedWorker::new(global, proto, &outside_port, control_sender.clone(), cx);
485        let worker_addr = Trusted::new(&*worker);
486
487        // Step 11. Enqueue the following steps to the shared worker manager:
488        // Step 11.1. Let workerGlobalScope be null.
489        let shared_worker_key = SharedWorkerKey {
490            storage_key: outside_storage_key.clone(),
491            // Include constructor origin in the key so `data:` SharedWorkers are not reused across origins.
492            constructor_origin: constructor_origin.clone(),
493            constructor_url: constructor_url.clone(),
494            name: worker_name_string,
495        };
496
497        // Step 11.2. For each scope in the list of all `SharedWorkerGlobalScope` objects:
498        // Step 11.2.1. Let workerStorageKey be the result of running obtain a storage key for non-storage purposes given scope's relevant settings object.
499        // Step 11.2.2. If all of the following are true:
500        // workerStorageKey equals outsideStorageKey;
501        // scope's closing flag is false;
502        // scope's constructor URL equals urlRecord; and
503        // scope's name equals options["name"],
504        // Servo also atomically records a Creating entry here when no matching
505        // scope exists, so another same-key constructor cannot race into the
506        // Step 11.6 fresh-worker path.
507        let shared_worker = find_or_claim_shared_worker(shared_worker_key.clone());
508
509        match shared_worker {
510            SharedWorkerClaimResult::Created(registration) => {
511                // Step 11.2.2.1. Set workerGlobalScope to scope.
512                // Step 11.2.2.2. Break.
513                // TODO Step 11.3. If workerGlobalScope is not null, but the user agent has been configured to disallow communication between the worker represented by the workerGlobalScope and the scripts whose settings object is outsideSettings, then set workerGlobalScope to null.
514                // Step 11.4. If workerGlobalScope is not null, and any of the following are true:
515                // workerGlobalScope's type is not equal to options["type"];
516                // workerGlobalScope's credentials is not equal to options["credentials"]; or
517                // workerGlobalScope's extended lifetime is not equal to options["extendedLifetime"],
518                if registration.worker_type != worker_type ||
519                    registration.credentials != credentials ||
520                    registration.extended_lifetime != extended_lifetime
521                {
522                    // Step 11.4.1. Queue a global task on the DOM manipulation task source given worker's relevant global object to fire an event named error at worker.
523                    SharedWorker::queue_simple_error(global, worker_addr);
524                    // Step 11.4.2. Abort these steps.
525                    return Ok(worker);
526                }
527
528                // Step 11.5. If workerGlobalScope is not null:
529                // Step 11.5.1. Let insideSettings be workerGlobalScope's relevant settings object.
530                // Step 11.5.2. Let workerIsSecureContext be true if insideSettings is a secure context; otherwise, false.
531                // Step 11.5.3. If workerIsSecureContext is not callerIsSecureContext:
532                if registration.worker_is_secure_context != caller_is_secure_context {
533                    // Step 11.5.3.1. Queue a global task on the DOM manipulation task source given worker's relevant global object to fire an event named error at worker.
534                    SharedWorker::queue_simple_error(global, worker_addr);
535                    // Step 11.5.3.2. Abort these steps.
536                    return Ok(worker);
537                }
538
539                // Step 11.5.4. Associate worker with workerGlobalScope.
540                // Step 11.5.5. Let insidePort be a new MessagePort in insideSettings's realm.
541                // Step 11.5.6. Entangle outsidePort and insidePort.
542                let inside_port_impl =
543                    SharedWorker::create_entangled_inside_port(cx, global, &outside_port)?;
544                // Step 11.5.7. Queue a global task on the DOM manipulation task source given workerGlobalScope to fire an event named connect at workerGlobalScope, using MessageEvent, with the data attribute initialized to the empty string, the ports attribute initialized to a new frozen array containing only insidePort, and the source attribute initialized to insidePort.
545                if send_connect_to_created_worker(&registration, inside_port_impl) {
546                    SharedWorker::queue_simple_error(global, worker_addr);
547                }
548                // TODO Step 11.5.8. Append the relevant owner to add given outsideSettings to workerGlobalScope's owner set.
549                return Ok(worker);
550            },
551            SharedWorkerClaimResult::Failed => {
552                SharedWorker::queue_simple_error(global, worker_addr);
553                return Ok(worker);
554            },
555            SharedWorkerClaimResult::Claimed => {},
556        }
557
558        let initial_inside_port_impl =
559            match SharedWorker::create_entangled_inside_port(cx, global, &outside_port) {
560                Ok(inside_port_impl) => inside_port_impl,
561                Err(error) => {
562                    remove_creating_shared_worker(&shared_worker_key);
563                    return Err(error);
564                },
565            };
566
567        let parent_event_loop_sender = global
568            .event_loop_sender()
569            .expect("Window global must have an event loop sender");
570
571        let (sender, receiver) = unbounded();
572        let closing = Arc::new(AtomicBool::new(false));
573        let registration_id = Uuid::new_v4();
574
575        let worker_load_origin = WorkerScriptLoadOrigin {
576            referrer_url: match global.get_referrer() {
577                Referrer::Client(url) => Some(url),
578                Referrer::ReferrerUrl(url) => Some(url),
579                _ => None,
580            },
581            referrer_policy: global.get_referrer_policy(),
582            pipeline_id: global.pipeline_id(),
583        };
584
585        #[cfg(feature = "devtools")]
586        let ((devtools_sender, devtools_receiver), worker_id) = {
587            let (devtools_sender, devtools_receiver) = generic_channel::channel().unwrap();
588            let worker_id = Some(WorkerId(Uuid::new_v4()));
589
590            if let Some(chan) = global.devtools_chan() {
591                let webview_id = global
592                    .webview_id()
593                    .expect("Window global must have a WebViewId");
594                let page_info = DevtoolsPageInfo {
595                    title: format!("SharedWorker for {}", worker_url.url()),
596                    url: worker_url.url(),
597                    is_top_level_global: false,
598                    is_service_worker: false,
599                };
600                let _ = chan.send(ScriptToDevtoolsControlMsg::NewGlobal(
601                    (
602                        window.window_proxy().browsing_context_id(),
603                        global.pipeline_id(),
604                        worker_id,
605                        webview_id,
606                    ),
607                    devtools_sender.clone(),
608                    page_info,
609                ));
610            }
611
612            ((devtools_sender, devtools_receiver), worker_id)
613        };
614        #[cfg(not(feature = "devtools"))]
615        let worker_id: Option<WorkerId> = None;
616
617        let init = prepare_workerscope_init(
618            global,
619            #[cfg(feature = "devtools")]
620            Some(devtools_sender),
621            worker_id,
622            #[cfg(feature = "webgl")]
623            window.webgl_chan(),
624        );
625
626        let (setup_sender, setup_receiver) = unbounded();
627        let (registered_sender, registered_receiver) = unbounded();
628
629        // Step 11.6. Otherwise, in parallel, run a worker given worker, urlRecord, outsideSettings, outsidePort, and options.
630        let _join_handle = match SharedWorkerGlobalScope::run_shared_worker_scope(
631            init,
632            window.webview_id(),
633            Some(window.window_proxy().browsing_context_id()),
634            worker_name,
635            worker_type,
636            worker_url,
637            worker_addr.clone(),
638            parent_event_loop_sender,
639            #[cfg(feature = "devtools")]
640            devtools_receiver,
641            sender.clone(),
642            receiver,
643            worker_load_origin,
644            closing.clone(),
645            global.image_cache(),
646            #[cfg(feature = "webgpu")]
647            global.wgpu_id_hub(),
648            control_receiver,
649            setup_sender,
650            registered_receiver,
651            registration_id,
652            credentials,
653            extended_lifetime,
654            constructor_origin,
655            constructor_url,
656            outside_storage_key,
657            global.insecure_requests_policy(),
658            global.policy_container(),
659            Arc::new(global.font_context().new_for_worker()),
660        ) {
661            Ok(join_handle) => join_handle,
662            Err(error) => {
663                error!("Failed to spawn SharedWorker thread: {error}");
664                remove_creating_shared_worker(&shared_worker_key);
665                SharedWorker::queue_simple_error(global, worker_addr);
666                return Ok(worker);
667            },
668        };
669
670        // Step 11.5.2. Let workerIsSecureContext be true if insideSettings is a secure context; otherwise, false.
671        let Ok(worker_is_secure_context) = setup_receiver.recv() else {
672            remove_creating_shared_worker(&shared_worker_key);
673            SharedWorker::queue_simple_error(global, worker_addr);
674            return Ok(worker);
675        };
676
677        let registration = SharedWorkerRegistration {
678            id: registration_id,
679            worker_type,
680            credentials,
681            extended_lifetime,
682            worker_is_secure_context,
683            closing,
684            sender,
685            _control_sender: control_sender,
686        };
687
688        if !transition_creating_to_created(&shared_worker_key, registration.clone()) {
689            SharedWorker::queue_simple_error(global, worker_addr);
690            return Ok(worker);
691        }
692
693        if registered_sender.send(()).is_err() {
694            SharedWorker::unregister_shared_worker(registration_id);
695            SharedWorker::queue_simple_error(global, worker_addr);
696            return Ok(worker);
697        }
698
699        // Step 13. If is shared is true, then queue a global task on the DOM
700        // manipulation task source given worker global scope to fire an event
701        // named connect at worker global scope, using MessageEvent, with the data
702        // attribute initialized to the empty string, the ports attribute
703        // initialized to a new frozen array containing inside port, and the
704        // source attribute initialized to inside port.
705        if send_connect_to_created_worker(&registration, initial_inside_port_impl) {
706            SharedWorker::unregister_shared_worker(registration_id);
707            SharedWorker::queue_simple_error(global, worker_addr);
708            return Ok(worker);
709        }
710
711        Ok(worker)
712    }
713
714    /// <https://html.spec.whatwg.org/multipage/#dom-sharedworker-port>
715    fn Port(&self) -> DomRoot<MessagePort> {
716        // The port getter steps are to return this's port.
717        DomRoot::from_ref(&*self.port)
718    }
719
720    // <https://html.spec.whatwg.org/multipage/#handler-abstractworker-onerror>
721    event_handler!(error, GetOnerror, SetOnerror);
722}
723
724impl TaskOnce for SimpleWorkerErrorHandler<SharedWorker> {
725    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
726    fn run_once(self, cx: &mut JSContext) {
727        SharedWorker::dispatch_simple_error(cx, self.addr);
728    }
729}