Skip to main content

script/dom/workers/
dedicatedworkerglobalscope.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::cell::Cell;
8use std::collections::VecDeque;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::thread::{self, JoinHandle};
12
13use crossbeam_channel::{Receiver, Sender, unbounded};
14#[cfg(feature = "devtools")]
15use devtools_traits::DevtoolScriptControlMsg;
16use dom_struct::dom_struct;
17use fonts::FontContext;
18use js::context::JSContext;
19use js::jsapi::JSObject;
20use js::jsval::UndefinedValue;
21use js::rust::{CustomAutoRooterGuard, HandleValue};
22use net_traits::blob_url_store::UrlWithBlobClaim;
23use net_traits::image_cache::ImageCache;
24use net_traits::policy_container::PolicyContainer;
25use net_traits::request::{
26    CredentialsMode, Destination, InsecureRequestsPolicy, Origin, ParserMetadata,
27    PreloadedResources, Referrer, RequestBuilder, RequestClient, RequestMode,
28};
29use script_bindings::cell::DomRefCell;
30use script_bindings::interfaces::HasOrigin;
31use servo_base::generic_channel::{self, GenericReceiver, GenericSender, RoutedReceiver};
32use servo_base::id::{BrowsingContextId, PipelineId, ScriptEventLoopId, WebViewId};
33use servo_constellation_traits::{
34    ScriptToConstellationMessage, WorkerAnimationFrameTick, WorkerGlobalScopeInit,
35    WorkerScriptLoadOrigin,
36};
37use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
38use style::thread_state::{self, ThreadState};
39
40use crate::conversions::Convert;
41use crate::dom::abstractworker::{MessageData, SimpleWorkerErrorHandler, WorkerScriptMsg};
42use crate::dom::abstractworkerglobalscope::{WorkerEventLoopMethods, run_worker_event_loop};
43use crate::dom::bindings::callback::{ExceptionHandling, RootedCallback, TracedCallback};
44use crate::dom::bindings::codegen::Bindings::AnimationFrameProviderBinding::FrameRequestCallback;
45use crate::dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding;
46use crate::dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods;
47use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
48use crate::dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods;
49use crate::dom::bindings::codegen::Bindings::WorkerBinding::{WorkerOptions, WorkerType};
50use crate::dom::bindings::error::{Error, ErrorInfo, ErrorResult, Fallible};
51use crate::dom::bindings::inheritance::Castable;
52use crate::dom::bindings::num::Finite;
53use crate::dom::bindings::reflector::DomGlobal;
54use crate::dom::bindings::root::DomRoot;
55use crate::dom::bindings::str::DOMString;
56use crate::dom::bindings::structuredclone;
57use crate::dom::bindings::trace::{CustomTraceable, RootedTraceableBox};
58use crate::dom::csp::Violation;
59use crate::dom::errorevent::ErrorEvent;
60use crate::dom::event::{Event, EventBubbles, EventCancelable};
61use crate::dom::eventtarget::EventTarget;
62use crate::dom::globalscope::GlobalScope;
63use crate::dom::html::htmlscriptelement::Script;
64use crate::dom::messageevent::MessageEvent;
65#[cfg(feature = "devtools")]
66use crate::dom::types::DebuggerGlobalScope;
67#[cfg(feature = "webgpu")]
68use crate::dom::webgpu::identityhub::IdentityHub;
69use crate::dom::worker::{TrustedWorkerAddress, Worker};
70use crate::dom::workerglobalscope::{
71    ScriptFetchContext, WorkerDevtoolsControlMsg, WorkerGlobalScope,
72};
73use crate::messaging::{CommonScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
74use crate::realms::enter_auto_realm;
75use crate::runtime::script_runtime::ScriptThreadEventCategory::WorkerEvent;
76use crate::runtime::script_runtime::{IntroductionType, Runtime, ThreadSafeJSContext};
77use crate::scripting::script_module::fetch_a_module_script_graph;
78use crate::tasks::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue};
79use crate::tasks::task_source::TaskSourceName;
80
81/// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular
82/// value for the duration of this object's lifetime. This ensures that the related Worker
83/// object only lives as long as necessary (ie. while events are being executed), while
84/// providing a reference that can be cloned freely.
85pub(crate) struct AutoWorkerReset<'a> {
86    workerscope: &'a DedicatedWorkerGlobalScope,
87    old_worker: Option<TrustedWorkerAddress>,
88}
89
90impl<'a> AutoWorkerReset<'a> {
91    pub(crate) fn new(
92        workerscope: &'a DedicatedWorkerGlobalScope,
93        worker: TrustedWorkerAddress,
94    ) -> AutoWorkerReset<'a> {
95        let old_worker = workerscope.replace_worker(Some(worker));
96        AutoWorkerReset {
97            workerscope,
98            old_worker,
99        }
100    }
101}
102
103impl Drop for AutoWorkerReset<'_> {
104    fn drop(&mut self) {
105        self.workerscope
106            .replace_worker(std::mem::take(&mut self.old_worker));
107    }
108}
109
110/// Messages sent from the owning global.
111pub(crate) enum DedicatedWorkerControlMsg {
112    /// Shutdown the worker.
113    Exit,
114    AnimationFrameProviderUnsupported,
115    SetNetworkOnlineState(bool),
116}
117
118#[derive(MallocSizeOf)]
119pub(crate) enum DedicatedWorkerScriptMsg {
120    /// Standard message from a worker.
121    CommonWorker(TrustedWorkerAddress, WorkerScriptMsg),
122    /// Wake-up call from the task queue.
123    WakeUp,
124}
125
126pub(crate) enum MixedMessage {
127    Worker(DedicatedWorkerScriptMsg),
128    #[cfg(feature = "devtools")]
129    Devtools(DevtoolScriptControlMsg),
130    Control(DedicatedWorkerControlMsg),
131    AnimationFrameTick(WorkerAnimationFrameTick),
132    Timer,
133}
134
135impl QueuedTaskConversion for DedicatedWorkerScriptMsg {
136    fn pipeline_id(&self) -> Option<PipelineId> {
137        // Workers always return None, since the pipeline_id is only used to check for document activity,
138        // and this check does not apply to worker event-loops.
139        None
140    }
141
142    fn into_queued_task(self) -> Option<QueuedTask> {
143        let (worker, common_worker_msg) = match self {
144            DedicatedWorkerScriptMsg::CommonWorker(worker, common_worker_msg) => {
145                (worker, common_worker_msg)
146            },
147            _ => return None,
148        };
149        let script_msg = match common_worker_msg {
150            WorkerScriptMsg::Common(script_msg) => script_msg,
151            _ => return None,
152        };
153        let (event_category, task, pipeline_id, task_source) = match script_msg {
154            CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => {
155                (category, boxed, pipeline_id, task_source)
156            },
157            _ => return None,
158        };
159        Some(QueuedTask {
160            worker: Some(worker),
161            event_category,
162            task,
163            pipeline_id,
164            task_source,
165        })
166    }
167
168    fn from_queued_task(queued_task: QueuedTask) -> Self {
169        let script_msg = CommonScriptMsg::Task(
170            queued_task.event_category,
171            queued_task.task,
172            queued_task.pipeline_id,
173            queued_task.task_source,
174        );
175        DedicatedWorkerScriptMsg::CommonWorker(
176            queued_task.worker.unwrap(),
177            WorkerScriptMsg::Common(script_msg),
178        )
179    }
180
181    fn inactive_msg() -> Self {
182        // Inactive is only relevant in the context of a browsing-context event-loop.
183        panic!("Workers should never receive messages marked as inactive");
184    }
185
186    fn wake_up_msg() -> Self {
187        DedicatedWorkerScriptMsg::WakeUp
188    }
189
190    fn is_wake_up(&self) -> bool {
191        matches!(self, DedicatedWorkerScriptMsg::WakeUp)
192    }
193}
194
195unsafe_no_jsmanaged_fields!(TaskQueue<DedicatedWorkerScriptMsg>);
196
197/// <https://html.spec.whatwg.org/multipage/#dedicatedworkerglobalscope>
198#[dom_struct]
199pub(crate) struct DedicatedWorkerGlobalScope {
200    workerglobalscope: WorkerGlobalScope,
201    /// The [`WebViewId`] of the `WebView` that this worker is associated with.
202    #[no_trace]
203    webview_id: WebViewId,
204    task_queue: TaskQueue<DedicatedWorkerScriptMsg>,
205    own_sender: Sender<DedicatedWorkerScriptMsg>,
206    worker: DomRefCell<Option<TrustedWorkerAddress>>,
207    /// Sender to the parent thread.
208    parent_event_loop_sender: ScriptEventLoopSender,
209    #[ignore_malloc_size_of = "ImageCache"]
210    #[no_trace]
211    image_cache: Arc<dyn ImageCache>,
212    #[no_trace]
213    browsing_context: Option<BrowsingContextId>,
214    #[conditional_malloc_size_of]
215    animation_frame_provider_supported: Arc<AtomicBool>,
216    animation_frame_provider_registered: Cell<bool>,
217    /// <https://html.spec.whatwg.org/multipage/#animation-frame-callback-identifier>
218    animation_frame_ident: Cell<u32>,
219    /// Pending animation frame callbacks for a later worker rendering update.
220    animation_frame_list: DomRefCell<VecDeque<(u32, TracedCallback<FrameRequestCallback>)>>,
221    /// Callbacks snapshotted for the current worker rendering update.s
222    current_animation_frame_list: DomRefCell<VecDeque<(u32, TracedCallback<FrameRequestCallback>)>>,
223    /// Whether we're in the process of running animation callbacks.
224    running_animation_callbacks: Cell<bool>,
225    /// Whether Constellation currently treats this worker as having callbacks.
226    animation_frame_callbacks_active: Cell<bool>,
227    /// A sender for animation frame ticks.
228    #[no_trace]
229    animation_frame_tick_sender: Option<GenericSender<WorkerAnimationFrameTick>>,
230    /// A receiver for animation frame ticks.
231    #[no_trace]
232    animation_frame_tick_receiver: Option<RoutedReceiver<WorkerAnimationFrameTick>>,
233    /// A receiver of control messages.
234    #[no_trace]
235    control_receiver: Receiver<DedicatedWorkerControlMsg>,
236    #[no_trace]
237    queued_worker_tasks: DomRefCell<Vec<MessageData>>,
238}
239
240impl WorkerEventLoopMethods for DedicatedWorkerGlobalScope {
241    type WorkerMsg = DedicatedWorkerScriptMsg;
242    type ControlMsg = DedicatedWorkerControlMsg;
243    type Event = MixedMessage;
244
245    fn task_queue(&self) -> &TaskQueue<DedicatedWorkerScriptMsg> {
246        &self.task_queue
247    }
248
249    fn handle_event(&self, event: MixedMessage, cx: &mut JSContext) -> bool {
250        self.handle_mixed_message(event, cx)
251    }
252
253    fn handle_worker_post_event(
254        &self,
255        worker: &TrustedWorkerAddress,
256    ) -> Option<AutoWorkerReset<'_>> {
257        let ar = AutoWorkerReset::new(self, worker.clone());
258        Some(ar)
259    }
260
261    fn from_control_msg(msg: DedicatedWorkerControlMsg) -> MixedMessage {
262        MixedMessage::Control(msg)
263    }
264
265    fn from_worker_msg(msg: DedicatedWorkerScriptMsg) -> MixedMessage {
266        MixedMessage::Worker(msg)
267    }
268
269    #[cfg(feature = "devtools")]
270    fn from_devtools_msg(msg: DevtoolScriptControlMsg) -> MixedMessage {
271        MixedMessage::Devtools(msg)
272    }
273
274    fn from_timer_msg() -> MixedMessage {
275        MixedMessage::Timer
276    }
277
278    fn from_animation_frame_tick_msg(msg: WorkerAnimationFrameTick) -> Option<MixedMessage> {
279        Some(MixedMessage::AnimationFrameTick(msg))
280    }
281
282    fn animation_frame_tick_receiver(&self) -> Option<&RoutedReceiver<WorkerAnimationFrameTick>> {
283        self.animation_frame_tick_receiver.as_ref()
284    }
285
286    fn control_receiver(&self) -> &Receiver<DedicatedWorkerControlMsg> {
287        &self.control_receiver
288    }
289}
290
291impl DedicatedWorkerGlobalScope {
292    #[allow(clippy::too_many_arguments)]
293    fn new_inherited(
294        init: WorkerGlobalScopeInit,
295        webview_id: WebViewId,
296        worker_name: DOMString,
297        worker_type: WorkerType,
298        worker_url: ServoUrl,
299        from_devtools_receiver: Option<RoutedReceiver<WorkerDevtoolsControlMsg>>,
300        runtime: Runtime,
301        parent_event_loop_sender: ScriptEventLoopSender,
302        own_sender: Sender<DedicatedWorkerScriptMsg>,
303        receiver: Receiver<DedicatedWorkerScriptMsg>,
304        closing: Arc<AtomicBool>,
305        animation_frame_provider_supported: Arc<AtomicBool>,
306        image_cache: Arc<dyn ImageCache>,
307        browsing_context: Option<BrowsingContextId>,
308        animation_frame_tick_sender: Option<GenericSender<WorkerAnimationFrameTick>>,
309        animation_frame_tick_receiver: Option<RoutedReceiver<WorkerAnimationFrameTick>>,
310        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
311        control_receiver: Receiver<DedicatedWorkerControlMsg>,
312        insecure_requests_policy: InsecureRequestsPolicy,
313        font_context: Arc<FontContext>,
314    ) -> DedicatedWorkerGlobalScope {
315        DedicatedWorkerGlobalScope {
316            workerglobalscope: WorkerGlobalScope::new_inherited(
317                init,
318                worker_name,
319                worker_type,
320                worker_url,
321                runtime,
322                from_devtools_receiver,
323                closing,
324                #[cfg(feature = "webgpu")]
325                gpu_id_hub,
326                insecure_requests_policy,
327                font_context,
328                None,
329            ),
330            webview_id,
331            task_queue: TaskQueue::new(receiver),
332            own_sender,
333            parent_event_loop_sender,
334            worker: DomRefCell::new(None),
335            image_cache,
336            browsing_context,
337            animation_frame_provider_supported,
338            animation_frame_provider_registered: Cell::new(false),
339            animation_frame_ident: Cell::new(0),
340            animation_frame_list: DomRefCell::new(VecDeque::new()),
341            current_animation_frame_list: DomRefCell::new(VecDeque::new()),
342            running_animation_callbacks: Cell::new(false),
343            animation_frame_callbacks_active: Cell::new(false),
344            animation_frame_tick_sender,
345            animation_frame_tick_receiver,
346            control_receiver,
347            queued_worker_tasks: Default::default(),
348        }
349    }
350
351    #[expect(clippy::too_many_arguments)]
352    pub(crate) fn new(
353        init: WorkerGlobalScopeInit,
354        webview_id: WebViewId,
355        worker_name: DOMString,
356        worker_type: WorkerType,
357        worker_url: ServoUrl,
358        from_devtools_receiver: Option<RoutedReceiver<WorkerDevtoolsControlMsg>>,
359        runtime: Runtime,
360        parent_event_loop_sender: ScriptEventLoopSender,
361        own_sender: Sender<DedicatedWorkerScriptMsg>,
362        receiver: Receiver<DedicatedWorkerScriptMsg>,
363        closing: Arc<AtomicBool>,
364        animation_frame_provider_supported: Arc<AtomicBool>,
365        image_cache: Arc<dyn ImageCache>,
366        browsing_context: Option<BrowsingContextId>,
367        animation_frame_tick_sender: Option<GenericSender<WorkerAnimationFrameTick>>,
368        animation_frame_tick_receiver: Option<RoutedReceiver<WorkerAnimationFrameTick>>,
369        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
370        control_receiver: Receiver<DedicatedWorkerControlMsg>,
371        insecure_requests_policy: InsecureRequestsPolicy,
372        font_context: Arc<FontContext>,
373        #[cfg(feature = "devtools")] debugger_global: Option<&DebuggerGlobalScope>,
374        cx: &mut js::context::JSContext,
375    ) -> DomRoot<DedicatedWorkerGlobalScope> {
376        let scope = Box::new(DedicatedWorkerGlobalScope::new_inherited(
377            init,
378            webview_id,
379            worker_name,
380            worker_type,
381            worker_url,
382            from_devtools_receiver,
383            runtime,
384            parent_event_loop_sender,
385            own_sender,
386            receiver,
387            closing,
388            animation_frame_provider_supported,
389            image_cache,
390            browsing_context,
391            animation_frame_tick_sender,
392            animation_frame_tick_receiver,
393            #[cfg(feature = "webgpu")]
394            gpu_id_hub,
395            control_receiver,
396            insecure_requests_policy,
397            font_context,
398        ));
399        let scope = DedicatedWorkerGlobalScopeBinding::Wrap::<crate::DomTypeHolder>(
400            cx,
401            &scope.origin(),
402            scope,
403        );
404        #[cfg(feature = "devtools")]
405        scope
406            .upcast::<WorkerGlobalScope>()
407            .init_debugger_global(debugger_global, cx);
408
409        scope
410    }
411
412    /// <https://html.spec.whatwg.org/multipage/#run-a-worker>
413    #[expect(unsafe_code)]
414    #[allow(clippy::too_many_arguments)]
415    pub(crate) fn run_worker_scope(
416        mut init: WorkerGlobalScopeInit,
417        webview_id: WebViewId,
418        worker_url: UrlWithBlobClaim,
419        #[cfg(feature = "devtools")] from_devtools_receiver: GenericReceiver<
420            DevtoolScriptControlMsg,
421        >,
422        worker: TrustedWorkerAddress,
423        parent_event_loop_sender: ScriptEventLoopSender,
424        own_sender: Sender<DedicatedWorkerScriptMsg>,
425        receiver: Receiver<DedicatedWorkerScriptMsg>,
426        worker_load_origin: WorkerScriptLoadOrigin,
427        worker_options: &WorkerOptions,
428        closing: Arc<AtomicBool>,
429        animation_frame_provider_supported: Arc<AtomicBool>,
430        image_cache: Arc<dyn ImageCache>,
431        browsing_context: Option<BrowsingContextId>,
432        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
433        control_receiver: Receiver<DedicatedWorkerControlMsg>,
434        context_sender: Sender<ThreadSafeJSContext>,
435        insecure_requests_policy: InsecureRequestsPolicy,
436        policy_container: Arc<PolicyContainer>,
437        font_context: Arc<FontContext>,
438    ) -> JoinHandle<()> {
439        let event_loop_id = ScriptEventLoopId::installed()
440            .expect("Should always be in a ScriptThread or in a dedicated worker");
441        let current_global = GlobalScope::current().expect("No current global object");
442        let origin = current_global.origin().immutable().clone();
443        let referrer = current_global.get_referrer();
444        let parent = current_global.runtime_handle();
445        let current_global_ancestor_trustworthy = current_global.has_trustworthy_ancestor_origin();
446        let is_secure_context = current_global.is_secure_context();
447        let upgrade_insecure_navigations_set =
448            current_global.upgrade_insecure_navigations_set().clone();
449        let is_nested_browsing_context = current_global.is_nested_browsing_context();
450
451        let worker_type = worker_options.type_;
452        let worker_name = worker_options.name.to_string();
453        let credentials = worker_options.credentials.convert();
454
455        thread::Builder::new()
456            .name(format!("WW:{}", worker_url.debug_compact()))
457            .spawn(move || {
458                thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER);
459                ScriptEventLoopId::install(event_loop_id);
460
461                let WorkerScriptLoadOrigin {
462                    referrer_url,
463                    pipeline_id,
464                    ..
465                } = worker_load_origin;
466
467                let referrer = referrer_url.map(Referrer::ReferrerUrl).unwrap_or(referrer);
468
469                let request_client = RequestClient {
470                    preloaded_resources: PreloadedResources::default(),
471                    policy_container,
472                    origin: Origin::Origin(origin.clone()),
473                    is_nested_browsing_context,
474                    insecure_requests_policy,
475                    upgrade_insecure_navigations_set,
476                    has_trustworthy_ancestor_origin: current_global_ancestor_trustworthy,
477                    network_partition_key: None,
478                };
479
480                let event_loop_sender = ScriptEventLoopSender::DedicatedWorker {
481                    sender: own_sender.clone(),
482                    main_thread_worker: worker.clone(),
483                };
484
485                let runtime = unsafe {
486                    Runtime::new_with_parent(Some(parent), Some(event_loop_sender.clone()))
487                };
488                // SAFETY: We are in a new thread, so this first cx.
489                // It is OK to have it separated of runtime here,
490                // because it will never outlive it (runtime destruction happens at the end of this function)
491                let mut cx = unsafe { runtime.cx() };
492                let cx = &mut cx;
493
494                #[cfg(feature = "devtools")]
495                let debugger_global = DebuggerGlobalScope::new_if_needed(
496                    cx,
497                    pipeline_id,
498                    &init.to_devtools_sender,
499                    &init.from_devtools_sender,
500                    &init.mem_profiler_chan,
501                    &init.time_profiler_chan,
502                    &init.script_to_constellation_chan,
503                    &init.script_to_embedder_chan,
504                    &init.resource_threads,
505                    &init.storage_threads,
506                    #[cfg(feature = "webgpu")]
507                    &gpu_id_hub,
508                );
509
510                let context_for_interrupt = runtime.thread_safe_js_context();
511                let _ = context_sender.send(context_for_interrupt);
512
513                #[cfg(feature = "devtools")]
514                let devtools_mpsc_port = Some(from_devtools_receiver.route_preserving_errors());
515                #[cfg(not(feature = "devtools"))]
516                let devtools_mpsc_port = None;
517                let animation_frame_channel = init
518                    .animation_frame_provider_supported
519                    .then(|| generic_channel::channel().expect("Failed to create generic channel"));
520                let (animation_frame_tick_sender, animation_frame_tick_receiver) =
521                    match animation_frame_channel {
522                        Some((sender, receiver)) => {
523                            (Some(sender), Some(receiver.route_preserving_errors()))
524                        },
525                        None => (None, None),
526                    };
527
528                // Step 8 "Set up a worker environment settings object [...]"
529                //
530                // <https://html.spec.whatwg.org/multipage/#script-settings-for-workers>
531                //
532                // > The origin: Return a unique opaque origin if `worker global
533                // > scope`'s url's scheme is "data", and `inherited origin`
534                // > otherwise.
535                if worker_url.scheme() == "data" {
536                    // Workers created from a data: url are secure if they were created from secure contexts
537                    if is_secure_context {
538                        init.origin = ImmutableOrigin::new_opaque_data_url_worker();
539                    } else {
540                        init.origin = ImmutableOrigin::new_opaque();
541                    }
542                }
543
544                let worker_id = init.worker_id;
545                #[cfg(feature = "devtools")]
546                let devtools_enabled = init.to_devtools_sender.is_some();
547                let dedicated_worker_global_scope = DedicatedWorkerGlobalScope::new(
548                    init,
549                    webview_id,
550                    worker_name.into(),
551                    worker_type,
552                    worker_url.url(),
553                    devtools_mpsc_port,
554                    runtime,
555                    parent_event_loop_sender,
556                    own_sender,
557                    receiver,
558                    closing,
559                    animation_frame_provider_supported,
560                    image_cache,
561                    browsing_context,
562                    animation_frame_tick_sender,
563                    animation_frame_tick_receiver,
564                    #[cfg(feature = "webgpu")]
565                    gpu_id_hub,
566                    control_receiver,
567                    insecure_requests_policy,
568                    font_context,
569                    #[cfg(feature = "devtools")]
570                    debugger_global.as_deref(),
571                    cx,
572                );
573
574                #[cfg(feature = "devtools")]
575                if devtools_enabled && let Some(debugger_global) = &debugger_global {
576                    debugger_global.fire_add_debuggee(
577                        cx,
578                        dedicated_worker_global_scope.upcast(),
579                        pipeline_id,
580                        Some(worker_id),
581                    );
582                }
583                let worker_global_scope =
584                    dedicated_worker_global_scope.upcast::<WorkerGlobalScope>();
585                let global_scope = dedicated_worker_global_scope.upcast::<GlobalScope>();
586
587                // Step 12. Obtain script by switching on options["type"]:
588                {
589                    let _ar = AutoWorkerReset::new(&dedicated_worker_global_scope, worker.clone());
590                    match worker_type {
591                        WorkerType::Classic => {
592                            fetch_a_classic_worker_script(
593                                worker_global_scope,
594                                worker_url,
595                                request_client,
596                                Destination::Worker,
597                                Some(webview_id),
598                                referrer,
599                            );
600                        },
601                        WorkerType::Module => {
602                            let worker_scope = DomRoot::from_ref(worker_global_scope);
603                            fetch_a_module_script_graph(
604                                cx,
605                                global_scope,
606                                worker_url,
607                                request_client,
608                                Destination::Worker,
609                                referrer,
610                                credentials,
611                                Some(IntroductionType::WORKER),
612                                move |cx, module_tree| {
613                                    let module_script = module_tree.map(|module| {
614                                        Script::Module(RootedTraceableBox::new(module))
615                                    });
616                                    worker_scope.on_complete(cx, module_script);
617                                },
618                            );
619                        },
620                    }
621
622                    let reporter_name = format!("dedicated-worker-reporter-{}", worker_id);
623                    global_scope.mem_profiler_chan().run_with_memory_reporting(
624                        || {
625                            // Step 27, Run the responsible event loop specified
626                            // by inside settings until it is destroyed.
627                            // The worker processing model remains on this step
628                            // until the event loop is destroyed,
629                            // which happens after the closing flag is set to true.
630                            while !worker_global_scope.is_closing() {
631                                run_worker_event_loop(
632                                    &*dedicated_worker_global_scope,
633                                    Some(&worker),
634                                    cx,
635                                );
636                            }
637                        },
638                        reporter_name,
639                        event_loop_sender,
640                        CommonScriptMsg::CollectReports,
641                    );
642                }
643
644                // Drop worker rAF state before destroying the JS runtime.
645                dedicated_worker_global_scope.clear_animation_frame_callbacks_and_unregister();
646                global_scope.tear_down();
647                worker_global_scope.clear_js_runtime();
648            })
649            .expect("Thread spawning failed")
650    }
651
652    pub(crate) fn webview_id(&self) -> WebViewId {
653        self.webview_id
654    }
655
656    pub(crate) fn animation_frame_provider_supported(&self) -> bool {
657        self.animation_frame_provider_supported
658            .load(Ordering::SeqCst)
659    }
660
661    pub(crate) fn animation_frame_provider_supported_flag(&self) -> Arc<AtomicBool> {
662        self.animation_frame_provider_supported.clone()
663    }
664
665    fn register_animation_frame_provider(&self) {
666        if !self.animation_frame_provider_supported() {
667            return;
668        }
669
670        let Some(sender) = self.animation_frame_tick_sender.clone() else {
671            return;
672        };
673
674        if self.animation_frame_provider_registered.replace(true) {
675            return;
676        }
677
678        let worker_id = self.upcast::<WorkerGlobalScope>().worker_id();
679        log::debug!(
680            "Registering dedicated worker animation frame provider: worker={worker_id:?} ---->"
681        );
682        let _ = self
683            .upcast::<GlobalScope>()
684            .script_to_constellation_chan()
685            .send(
686                ScriptToConstellationMessage::RegisterWorkerAnimationFrameProvider(
687                    worker_id, sender,
688                ),
689            );
690    }
691
692    fn unregister_animation_frame_provider(&self) {
693        if !self.animation_frame_provider_registered.replace(false) {
694            return;
695        }
696
697        self.animation_frame_callbacks_active.set(false);
698        let worker_id = self.upcast::<WorkerGlobalScope>().worker_id();
699        log::debug!(
700            "Unregistering dedicated worker animation frame provider: worker={worker_id:?} ---->"
701        );
702        let _ = self
703            .upcast::<GlobalScope>()
704            .script_to_constellation_chan()
705            .send(ScriptToConstellationMessage::UnregisterWorkerAnimationFrameProvider(worker_id));
706    }
707
708    fn send_animation_frame_callbacks_state(&self, active: bool) {
709        if !self.animation_frame_provider_supported() {
710            return;
711        }
712
713        let worker_id = self.upcast::<WorkerGlobalScope>().worker_id();
714        log::debug!(
715            "Sending dedicated worker animation frame state: worker={worker_id:?}, active={active} ---->",
716        );
717        let _ = self
718            .upcast::<GlobalScope>()
719            .script_to_constellation_chan()
720            .send(
721                ScriptToConstellationMessage::ChangeWorkerAnimationFrameProviderState(
722                    worker_id, active,
723                ),
724            );
725    }
726
727    fn set_animation_frame_callbacks_active(&self, active: bool) {
728        if self.animation_frame_callbacks_active.replace(active) == active {
729            return;
730        }
731
732        self.send_animation_frame_callbacks_state(active);
733    }
734
735    fn remove_animation_frame_callback_from(
736        list: &DomRefCell<VecDeque<(u32, TracedCallback<FrameRequestCallback>)>>,
737        ident: u32,
738    ) {
739        let mut list = list.borrow_mut();
740        if let Some(position) = list.iter().position(|(handle, _)| *handle == ident) {
741            list.remove(position);
742        }
743    }
744
745    fn has_animation_frame_callbacks(&self) -> bool {
746        !self.animation_frame_list.borrow().is_empty() ||
747            !self.current_animation_frame_list.borrow().is_empty()
748    }
749
750    /// <https://html.spec.whatwg.org/multipage/#dom-animationframeprovider-requestanimationframe>
751    pub(crate) fn request_animation_frame(
752        &self,
753        callback: RootedCallback<FrameRequestCallback>,
754    ) -> Fallible<u32> {
755        // Step 1. If this is not supported, then throw a "NotSupportedError" DOMException.
756        if !self.animation_frame_provider_supported() {
757            return Err(Error::NotSupported(Some(
758                "Animation frame callbacks are not supported for this worker".to_owned(),
759            )));
760        }
761
762        self.register_animation_frame_provider();
763
764        // Step 2. Let target be this's target object.
765        // Step 3. Increment target's animation frame callback identifier by one,
766        // and let handle be the result.
767        let ident = self.animation_frame_ident.get() + 1;
768        self.animation_frame_ident.set(ident);
769
770        // Step 4. Let callbacks be target's map of animation frame callbacks.
771        // Step 5. Set callbacks[handle] to callback.
772        self.animation_frame_list
773            .borrow_mut()
774            .push_back((ident, callback.to_traced()));
775        log::debug!("Queued dedicated worker animation frame callback: handle={ident} ---->");
776        self.set_animation_frame_callbacks_active(true);
777
778        // Step 6. Return handle.
779        Ok(ident)
780    }
781
782    /// <https://html.spec.whatwg.org/multipage/#dom-animationframeprovider-cancelanimationframe>
783    pub(crate) fn cancel_animation_frame(&self, ident: u32) -> ErrorResult {
784        // Step 1. If this is not supported, then throw a "NotSupportedError" DOMException.
785        if !self.animation_frame_provider_supported() {
786            return Err(Error::NotSupported(Some(
787                "Animation frame callbacks are not supported for this worker".to_owned(),
788            )));
789        }
790
791        // Step 2. Let callbacks be this's target object's map of animation frame callbacks.
792        // Step 3. Remove callbacks[handle].
793        Self::remove_animation_frame_callback_from(&self.animation_frame_list, ident);
794
795        Self::remove_animation_frame_callback_from(&self.current_animation_frame_list, ident);
796        log::debug!("Cancelled dedicated worker animation frame callback: handle={ident} ---->");
797
798        if !self.running_animation_callbacks.get() && !self.has_animation_frame_callbacks() {
799            self.set_animation_frame_callbacks_active(false);
800        }
801
802        Ok(())
803    }
804
805    /// <https://html.spec.whatwg.org/multipage/#run-the-animation-frame-callbacks>
806    pub(crate) fn run_the_animation_frame_callbacks(&self, cx: &mut JSContext) {
807        if !self.animation_frame_provider_supported() ||
808            self.upcast::<WorkerGlobalScope>().is_closing()
809        {
810            return;
811        }
812
813        // Step 1. Let callbacks be target's map of animation frame callbacks.
814        // Step 2. Let callbackHandles be the result of getting the keys of callbacks.
815        let callback_count = self.animation_frame_list.borrow().len();
816        log::debug!("Running dedicated worker animation frame callbacks: count={callback_count}");
817        {
818            let mut pending = self.animation_frame_list.borrow_mut();
819            let mut current = self.current_animation_frame_list.borrow_mut();
820            for _ in 0..callback_count {
821                if let Some(ref callback) = pending.pop_front() {
822                    current.push_back(callback.clone());
823                }
824            }
825        }
826
827        self.running_animation_callbacks.set(true);
828        let timing = self.upcast::<GlobalScope>().performance(cx).Now();
829
830        // Step 3. For each handle in callbackHandles, if handle exists in callbacks:
831        for _ in 0..callback_count {
832            // Step 3.1. Let callback be callbacks[handle].
833            // Step 3.2. Remove callbacks[handle].
834            rooted!(&in(cx) let callback = self
835                .current_animation_frame_list
836                .borrow_mut()
837                .pop_front()
838                .map(|(_, callback)| callback));
839
840            if let Some(ref callback) = *callback {
841                // Step 3.3. Invoke callback with « now » and "`report`".
842                let _ = callback.Call__(cx, Finite::wrap(*timing), ExceptionHandling::Report);
843            }
844        }
845
846        self.current_animation_frame_list.borrow_mut().clear();
847        self.running_animation_callbacks.set(false);
848
849        if !self.has_animation_frame_callbacks() {
850            self.set_animation_frame_callbacks_active(false);
851        } else {
852            // Acknowledge the consumed worker tick while staying active; Paint
853            // will drive the next refresh tick.
854            self.send_animation_frame_callbacks_state(true);
855        }
856    }
857
858    pub(crate) fn clear_animation_frame_callbacks_and_unregister(&self) {
859        // Worker shutdown drops pending rAF callbacks and unregisters the tick target.
860        let worker_id = self.upcast::<WorkerGlobalScope>().worker_id();
861        log::debug!(
862            "Clearing dedicated worker animation frame callbacks: worker={worker_id:?} ---->"
863        );
864        self.animation_frame_list.borrow_mut().clear();
865        self.current_animation_frame_list.borrow_mut().clear();
866        self.running_animation_callbacks.set(false);
867        self.animation_frame_callbacks_active.set(false);
868        self.unregister_animation_frame_provider();
869    }
870
871    /// The non-None value of the `worker` field can contain a rooted [`TrustedWorkerAddress`]
872    /// version of the main thread's worker object. This is set while handling messages and then
873    /// unset otherwise, ensuring that the main thread object can be garbage collected. See
874    /// [`AutoWorkerReset`].
875    fn replace_worker(
876        &self,
877        new_worker: Option<TrustedWorkerAddress>,
878    ) -> Option<TrustedWorkerAddress> {
879        let old_worker = std::mem::replace(&mut *self.worker.borrow_mut(), new_worker);
880
881        // The `TaskManager` maintains a handle to this `DedicatedWorkerGlobalScope`'s
882        // event_loop_sender, which might in turn have a `TrustedWorkerAddress` rooting of the main
883        // thread's worker, which prevents garbage collection. Resetting it here ensures that
884        // garbage collection of the main thread object can happen again (assuming the new `worker`
885        // is `None`).
886        self.upcast::<GlobalScope>()
887            .task_manager()
888            .set_sender(self.event_loop_sender());
889
890        old_worker
891    }
892
893    pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
894        self.image_cache.clone()
895    }
896
897    pub(crate) fn event_loop_sender(&self) -> Option<ScriptEventLoopSender> {
898        Some(ScriptEventLoopSender::DedicatedWorker {
899            sender: self.own_sender.clone(),
900            main_thread_worker: self.worker.borrow().clone()?,
901        })
902    }
903
904    pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
905        let (sender, receiver) = unbounded();
906        let main_thread_worker = self.worker.borrow().as_ref().unwrap().clone();
907        (
908            ScriptEventLoopSender::DedicatedWorker {
909                sender,
910                main_thread_worker,
911            },
912            ScriptEventLoopReceiver::DedicatedWorker(receiver),
913        )
914    }
915
916    pub(crate) fn fire_queued_messages(&self, cx: &mut JSContext) {
917        let queue: Vec<_> = self.queued_worker_tasks.borrow_mut().drain(..).collect();
918        for msg in queue {
919            if self.upcast::<WorkerGlobalScope>().is_closing() {
920                return;
921            }
922            self.dispatch_message_event(cx, msg);
923        }
924    }
925
926    fn dispatch_message_event(&self, cx: &mut JSContext, msg: MessageData) {
927        let scope = self.upcast::<WorkerGlobalScope>();
928        let target = self.upcast();
929        let mut realm = enter_auto_realm(cx, self);
930        let cx = &mut realm;
931        rooted!(&in(cx) let mut message = UndefinedValue());
932        if let Ok(ports) =
933            structuredclone::read(cx, scope.upcast(), *msg.data, message.handle_mut())
934        {
935            MessageEvent::dispatch_jsval(
936                cx,
937                target,
938                scope.upcast(),
939                message.handle(),
940                Some(msg.origin.ascii_serialization().as_ref()),
941                None,
942                ports,
943            );
944        } else {
945            MessageEvent::dispatch_error(cx, target, scope.upcast());
946        }
947    }
948
949    fn handle_script_event(&self, msg: WorkerScriptMsg, cx: &mut JSContext) {
950        match msg {
951            WorkerScriptMsg::DOMMessage(message_data) => {
952                if self.upcast::<WorkerGlobalScope>().is_execution_ready() {
953                    self.dispatch_message_event(cx, message_data);
954                } else {
955                    self.queued_worker_tasks.borrow_mut().push(message_data);
956                }
957            },
958            WorkerScriptMsg::Common(msg) => {
959                self.upcast::<WorkerGlobalScope>().process_event(msg, cx);
960            },
961        }
962    }
963
964    /// <https://html.spec.whatwg.org/multipage/#event-loop-processing-model>
965    fn handle_mixed_message(&self, msg: MixedMessage, cx: &mut JSContext) -> bool {
966        if self.upcast::<WorkerGlobalScope>().is_closing() {
967            return false;
968        }
969        // FIXME(#26324): `self.worker` is None in devtools messages.
970        match msg {
971            #[cfg(feature = "devtools")]
972            MixedMessage::Devtools(msg) => self
973                .upcast::<WorkerGlobalScope>()
974                .handle_devtools_message(msg, cx),
975            MixedMessage::Worker(DedicatedWorkerScriptMsg::CommonWorker(linked_worker, msg)) => {
976                let _ar = AutoWorkerReset::new(self, linked_worker);
977                self.handle_script_event(msg, cx);
978            },
979            MixedMessage::Worker(DedicatedWorkerScriptMsg::WakeUp) => {},
980            MixedMessage::Control(DedicatedWorkerControlMsg::Exit) => {
981                return false;
982            },
983            MixedMessage::Control(DedicatedWorkerControlMsg::AnimationFrameProviderUnsupported) => {
984                self.clear_animation_frame_callbacks_and_unregister();
985                self.upcast::<GlobalScope>()
986                    .disable_owned_worker_animation_frame_providers();
987            },
988            MixedMessage::Control(DedicatedWorkerControlMsg::SetNetworkOnlineState(online)) => {
989                if self
990                    .upcast::<WorkerGlobalScope>()
991                    .set_network_online_state(online)
992                {
993                    self.upcast::<GlobalScope>()
994                        .set_network_online_state_on_dedicated_workers(online);
995                }
996            },
997            MixedMessage::AnimationFrameTick(_) => {
998                // Step 6.1.2. Run the animation frame callbacks for that
999                // DedicatedWorkerGlobalScope, passing in now as the timestamp.
1000                self.run_the_animation_frame_callbacks(cx);
1001            },
1002            MixedMessage::Timer => {},
1003        }
1004        true
1005    }
1006
1007    /// Step 7.2 of <https://html.spec.whatwg.org/multipage/#report-an-exception>
1008    pub(crate) fn forward_error_to_worker_object(&self, error_info: ErrorInfo) {
1009        // Step 7.2.1. Let workerObject be the Worker object associated with global.
1010        let worker = self.worker.borrow().as_ref().unwrap().clone();
1011        let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
1012        let task = Box::new(task!(forward_error_to_worker_object: move |cx| {
1013            let worker = worker.root();
1014            let global = worker.global();
1015
1016            // Step 7.2.2. Set notHandled to the result of firing an event named error at workerObject, using ErrorEvent,
1017            // with the cancelable attribute initialized to true, and additional attributes initialized according to errorInfo.
1018            let event = ErrorEvent::new(
1019                cx,
1020                &global,
1021                atom!("error"),
1022                EventBubbles::DoesNotBubble,
1023                EventCancelable::Cancelable,
1024                error_info.message.as_str().into(),
1025                error_info.filename.as_str().into(),
1026                error_info.lineno,
1027                error_info.column,
1028                HandleValue::null(),
1029            );
1030
1031            // Step 7.2.3. If notHandled is true, then report exception for workerObject's relevant global object with omitError set to true.
1032            if event.upcast::<Event>().fire(cx, worker.upcast::<EventTarget>()) {
1033                global.report_an_error(cx, error_info, HandleValue::null());
1034            }
1035        }));
1036        self.parent_event_loop_sender
1037            .send(CommonScriptMsg::Task(
1038                WorkerEvent,
1039                task,
1040                Some(pipeline_id),
1041                TaskSourceName::DOMManipulation,
1042            ))
1043            .unwrap();
1044    }
1045
1046    /// <https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage>
1047    fn post_message_impl(
1048        &self,
1049        cx: &mut JSContext,
1050        message: HandleValue,
1051        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1052    ) -> ErrorResult {
1053        let data = structuredclone::write(cx, message, Some(transfer))?;
1054        let worker = self.worker.borrow().as_ref().unwrap().clone();
1055        let global_scope = self.upcast::<GlobalScope>();
1056        let pipeline_id = global_scope.pipeline_id();
1057        let task = Box::new(task!(post_worker_message: move |cx| {
1058            Worker::handle_message(worker, data, cx);
1059        }));
1060        self.parent_event_loop_sender
1061            .send(CommonScriptMsg::Task(
1062                WorkerEvent,
1063                task,
1064                Some(pipeline_id),
1065                TaskSourceName::DOMManipulation,
1066            ))
1067            .expect("Sending to parent failed");
1068        Ok(())
1069    }
1070
1071    pub(crate) fn browsing_context(&self) -> Option<BrowsingContextId> {
1072        self.browsing_context
1073    }
1074
1075    pub(crate) fn report_csp_violations(&self, violations: Vec<Violation>) {
1076        let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
1077        self.parent_event_loop_sender
1078            .send(CommonScriptMsg::ReportCspViolations(
1079                pipeline_id,
1080                violations,
1081            ))
1082            .unwrap_or_else(|error| {
1083                log::warn!("Failed to send CSP violations to parent event loop: {error}");
1084            });
1085    }
1086
1087    pub(crate) fn forward_simple_error_at_worker(&self) {
1088        let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
1089        let worker = self.worker.borrow().clone().expect("worker must be set");
1090        self.parent_event_loop_sender
1091            .send(CommonScriptMsg::Task(
1092                WorkerEvent,
1093                Box::new(SimpleWorkerErrorHandler::new(worker)),
1094                Some(pipeline_id),
1095                TaskSourceName::DOMManipulation,
1096            ))
1097            .expect("Sending to parent failed");
1098    }
1099}
1100
1101/// <https://html.spec.whatwg.org/multipage/#fetch-a-classic-worker-script>
1102pub(crate) fn fetch_a_classic_worker_script(
1103    workerscope: &WorkerGlobalScope,
1104    url_with_blob_lock: UrlWithBlobClaim,
1105    fetch_client: RequestClient,
1106    destination: Destination,
1107    webview_id: Option<WebViewId>,
1108    referrer: Referrer,
1109) {
1110    let policy_container = fetch_client.policy_container.clone();
1111
1112    // Step 1. Let request be a new request whose URL is url,
1113    let request = RequestBuilder::new(webview_id, url_with_blob_lock.clone(), referrer)
1114        // client is fetchClient,
1115        .client(fetch_client)
1116        .pipeline_id(Some(workerscope.pipeline_id()))
1117        // destination is destination,
1118        .destination(destination)
1119        // TODO initiator type is "other",
1120        // mode is "same-origin",
1121        .mode(RequestMode::SameOrigin)
1122        // credentials mode is "same-origin",
1123        .credentials_mode(CredentialsMode::CredentialsSameOrigin)
1124        // parser metadata is "not parser-inserted",
1125        .parser_metadata(ParserMetadata::NotParserInserted)
1126        // and whose use-URL-credentials flag is set.
1127        .use_url_credentials(true);
1128
1129    let context = ScriptFetchContext::new(url_with_blob_lock.url(), policy_container);
1130    let global = workerscope.upcast::<GlobalScope>();
1131    let task_source = global.task_manager().networking_task_source().to_sendable();
1132    global.fetch(request, context, task_source);
1133}
1134
1135impl DedicatedWorkerGlobalScopeMethods<crate::DomTypeHolder> for DedicatedWorkerGlobalScope {
1136    /// <https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-name>
1137    fn Name(&self) -> DOMString {
1138        self.workerglobalscope.worker_name()
1139    }
1140
1141    /// <https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage>
1142    fn PostMessage(
1143        &self,
1144        cx: &mut JSContext,
1145        message: HandleValue,
1146        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1147    ) -> ErrorResult {
1148        self.post_message_impl(cx, message, transfer)
1149    }
1150
1151    /// <https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage>
1152    fn PostMessage_(
1153        &self,
1154        cx: &mut JSContext,
1155        message: HandleValue,
1156        options: &StructuredSerializeOptions,
1157    ) -> ErrorResult {
1158        auto_root!(&in(cx) let guard =
1159            options
1160                .transfer
1161                .iter()
1162                .map(|js| js.get())
1163                .collect::<Vec<_>>());
1164        self.post_message_impl(cx, message, guard)
1165    }
1166
1167    /// <https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-close>
1168    fn Close(&self) {
1169        // Step 2
1170        self.upcast::<WorkerGlobalScope>().close();
1171    }
1172
1173    /// <https://html.spec.whatwg.org/multipage/#dom-animationframeprovider-requestanimationframe>
1174    fn RequestAnimationFrame(
1175        &self,
1176        callback: RootedCallback<FrameRequestCallback>,
1177    ) -> Fallible<u32> {
1178        self.request_animation_frame(callback)
1179    }
1180
1181    /// <https://html.spec.whatwg.org/multipage/#dom-animationframeprovider-cancelanimationframe>
1182    fn CancelAnimationFrame(&self, ident: u32) -> ErrorResult {
1183        self.cancel_animation_frame(ident)
1184    }
1185
1186    // https://html.spec.whatwg.org/multipage/#handler-dedicatedworkerglobalscope-onmessage
1187    event_handler!(message, GetOnmessage, SetOnmessage);
1188
1189    // https://html.spec.whatwg.org/multipage/#handler-dedicatedworkerglobalscope-onmessageerror
1190    event_handler!(messageerror, GetOnmessageerror, SetOnmessageerror);
1191}
1192
1193impl HasOrigin for DedicatedWorkerGlobalScope {
1194    fn origin(&self) -> MutableOrigin {
1195        self.upcast::<WorkerGlobalScope>().origin()
1196    }
1197}