Skip to main content

script/dom/worklet/
worklet.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//! An implementation of Houdini worklets.
6//!
7//! The goal of this implementation is to maximize responsiveness of worklets,
8//! and in particular to ensure that the thread performing worklet tasks
9//! is never busy GCing or loading worklet code. We do this by providing a custom
10//! thread pool implementation, which only performs GC or code loading on
11//! a backup thread, not on the primary worklet thread.
12
13#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
14
15use std::cell::{self, Cell, RefMut};
16use std::cmp::max;
17use std::collections::hash_map;
18use std::rc::Rc;
19use std::sync::Arc;
20use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
21use std::thread;
22
23use crossbeam_channel::{Receiver, SendError, Sender, unbounded};
24use dom_struct::dom_struct;
25use js::context::JSContext;
26use js::jsapi::{GCReason, JSGCParamKey, JSTracer};
27use js::realm::CurrentRealm;
28use js::rust::wrappers2::{JS_GC, JS_GetGCParameter};
29use malloc_size_of::malloc_size_of_is_0;
30use net_traits::policy_container::PolicyContainer;
31use net_traits::request::{Destination, Origin, PreloadedResources, RequestClient};
32use rustc_hash::FxHashMap;
33use script_bindings::cell::DomRefCell;
34use script_bindings::reflector::{Reflector, reflect_dom_object};
35use servo_base::id::PipelineId;
36use servo_url::{ImmutableOrigin, ServoUrl};
37use style::thread_state::{self, ThreadState};
38use swapper::{Swapper, swapper};
39use uuid::Uuid;
40
41use crate::conversions::Convert;
42use crate::dom::RootedPromise;
43use crate::dom::bindings::codegen::Bindings::RequestBinding::RequestCredentials;
44use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
45use crate::dom::bindings::codegen::Bindings::WorkletBinding::{WorkletMethods, WorkletOptions};
46use crate::dom::bindings::error::Error;
47use crate::dom::bindings::inheritance::Castable;
48use crate::dom::bindings::refcounted::TrustedPromise;
49use crate::dom::bindings::root::{Dom, DomRoot};
50use crate::dom::bindings::str::USVString;
51use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox};
52use crate::dom::globalscope::GlobalScope;
53use crate::dom::promise::Promise;
54use crate::dom::window::Window;
55use crate::dom::workletglobalscope::{
56    WorkletGlobalScope, WorkletGlobalScopeInit, WorkletGlobalScopeType,
57};
58use crate::messaging::{CommonScriptMsg, MainThreadScriptMsg, ScriptEventLoopSender};
59use crate::realms::enter_auto_realm;
60use crate::runtime::script_runtime::{IntroductionType, Runtime, ScriptThreadEventCategory};
61use crate::scripting::script_module::fetch_a_module_script_graph;
62use crate::tasks::task_source::TaskSourceName;
63use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
64
65// Magic numbers
66const WORKLET_THREAD_POOL_SIZE: u32 = 3;
67const MIN_GC_THRESHOLD: u32 = 1_000_000;
68
69type LazyCellWithBoxedInitializer<T> = cell::LazyCell<T, Box<dyn FnOnce() -> T>>;
70
71#[derive(JSTraceable, MallocSizeOf)]
72struct DroppableField {
73    worklet_id: WorkletId,
74    /// The cached version of the script thread's WorkletThreadPool. We keep this cached
75    /// because we may need to access it after the script thread has terminated.
76    /// NOTE: Do not access the `thread_pool` field directly, instead use the
77    /// `Worklet::worklet_thread_pool` method to access the Thread Pool.
78    #[ignore_malloc_size_of = "Difficult to measure memory usage of Rc<...> types"]
79    thread_pool: LazyCellWithBoxedInitializer<Rc<dyn WorkletThreadPool>>,
80
81    /// NOTE: The `is_thread_pool_initialized` field is a temporary workaround because
82    /// using the `LazyCell::get()` method requires Rust version >1.94.0 and is not
83    /// supported by the current MSRV (Minimum Supported Rust Version).
84    is_thread_pool_initialized: Cell<bool>,
85}
86
87impl Drop for DroppableField {
88    fn drop(&mut self) {
89        let worklet_id = self.worklet_id;
90        if self.is_thread_pool_initialized.get() {
91            self.thread_pool.exit_worklet(worklet_id);
92        }
93    }
94}
95
96#[dom_struct]
97/// <https://drafts.css-houdini.org/worklets/#worklet>
98pub(crate) struct Worklet {
99    reflector: Reflector,
100    window: Dom<Window>,
101    global_type: WorkletGlobalScopeType,
102    droppable_field: DroppableField,
103}
104
105impl Worklet {
106    fn new_inherited(
107        window: &Window,
108        global_type: WorkletGlobalScopeType,
109        thread_pool_constructor: Box<dyn FnOnce() -> Rc<dyn WorkletThreadPool>>,
110    ) -> Worklet {
111        Worklet {
112            reflector: Reflector::new(),
113            window: Dom::from_ref(window),
114            global_type,
115            droppable_field: DroppableField {
116                worklet_id: WorkletId::new(),
117                thread_pool: LazyCellWithBoxedInitializer::new(thread_pool_constructor),
118                is_thread_pool_initialized: Cell::new(false),
119            },
120        }
121    }
122
123    pub(crate) fn new(
124        cx: &mut JSContext,
125        window: &Window,
126        global_type: WorkletGlobalScopeType,
127        thread_pool_constructor: Box<dyn FnOnce() -> Rc<dyn WorkletThreadPool>>,
128    ) -> DomRoot<Worklet> {
129        debug!("Creating worklet {:?}.", global_type);
130        reflect_dom_object(
131            cx,
132            Box::new(Worklet::new_inherited(
133                window,
134                global_type,
135                thread_pool_constructor,
136            )),
137            window,
138        )
139    }
140
141    pub(crate) fn worklet_thread_pool(&self) -> Rc<dyn WorkletThreadPool> {
142        self.droppable_field.is_thread_pool_initialized.set(true);
143        self.droppable_field.thread_pool.clone()
144    }
145
146    #[cfg(feature = "testbinding")]
147    pub(crate) fn worklet_id(&self) -> WorkletId {
148        self.droppable_field.worklet_id
149    }
150
151    #[expect(dead_code)]
152    pub(crate) fn worklet_global_scope_type(&self) -> WorkletGlobalScopeType {
153        self.global_type
154    }
155}
156
157impl WorkletMethods<crate::DomTypeHolder> for Worklet {
158    /// <https://html.spec.whatwg.org/multipage/#dom-worklet-addmodule>
159    fn AddModule(
160        &self,
161        realm: &mut CurrentRealm,
162        module_url: USVString,
163        options: &WorkletOptions,
164    ) -> RootedPromise {
165        let promise = Promise::new_in_realm(realm);
166
167        // Step 1. Let outsideSettings be the relevant settings object of this.
168        // Step 2. Let moduleURLRecord be the result of encoding-parsing a URL given moduleURL, relative to outsideSettings.
169        let module_url_record = match self.window.Document().base_url().join(&module_url.0) {
170            Ok(url) => url,
171            Err(err) => {
172                // Step 3. If moduleURLRecord is failure, then return a promise rejected with a "SyntaxError" DOMException.
173                debug!("URL {:?} parse error {:?}.", module_url.0, err);
174                promise.reject_error(realm, Error::Syntax(None));
175
176                return promise;
177            },
178        };
179        debug!("Adding Worklet module {}.", module_url_record);
180
181        let global_scope = self.window.as_global_scope();
182
183        let pending_tasks_struct = PendingTasksStruct::new();
184
185        // NOTE: The following steps are split between `WorkletThread::get_worklet_global_scope` and `WorkledThread::fetch_and_invoke_a_worklet_script` methods:
186        // Step 5. Let workletInstance be this.
187        // Step 6. Run the following steps in parallel:
188        // Step 6.1. If workletInstance's global scopes is empty:
189        // Step 6.1.1. Create a worklet global scope given workletInstance.
190        // Step 6.1.2. Optionally, create additional global scope instances given workletInstance, depending on the specific worklet in question and its specification.
191        // Step 6.1.3. Wait for all steps of the creation process(es) — including those taking place within the worklet agents — to complete, before moving on.
192        // Step 6.2. Let pendingTasks be workletInstance's global scopes's size.
193
194        // Step 6.3. Let addedSuccessfully be false.
195        // NOTE: We skip step 6.3 because we do not implement the `added modules list` yet
196        // <https://html.spec.whatwg.org/multipage/#concept-worklet-added-modules-list>
197
198        self.worklet_thread_pool()
199            .fetch_and_invoke_a_worklet_script(
200                self.window.pipeline_id(),
201                self.droppable_field.worklet_id,
202                self.global_type,
203                self.window.origin().immutable().clone(),
204                global_scope.api_base_url(),
205                module_url_record,
206                global_scope.policy_container(),
207                options.credentials,
208                pending_tasks_struct,
209                &promise,
210                global_scope.inherited_secure_context(),
211            );
212
213        // Step 7. Return promise
214        debug!("Returning promise.");
215        promise
216    }
217}
218
219/// A guid for worklets.
220#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, PartialEq)]
221pub(crate) struct WorkletId(#[no_trace] Uuid);
222
223malloc_size_of_is_0!(WorkletId);
224
225impl WorkletId {
226    fn new() -> WorkletId {
227        WorkletId(Uuid::new_v4())
228    }
229}
230
231/// <https://drafts.css-houdini.org/worklets/#pending-tasks-struct>
232#[derive(Clone, Debug)]
233pub(crate) struct PendingTasksStruct(Arc<AtomicIsize>);
234
235impl PendingTasksStruct {
236    fn new() -> PendingTasksStruct {
237        PendingTasksStruct(Arc::new(AtomicIsize::new(
238            WORKLET_THREAD_POOL_SIZE as isize,
239        )))
240    }
241
242    fn set_counter_to(&self, value: isize) -> isize {
243        self.0.swap(value, Ordering::AcqRel)
244    }
245
246    fn decrement_counter_by(&self, offset: isize) -> isize {
247        self.0.fetch_sub(offset, Ordering::AcqRel)
248    }
249}
250
251pub trait WorkletThreadPool: JSTraceable {
252    /// Loads a worklet module into every thread in this thread pool.
253    /// If all of the threads load successfully, the promise is resolved.
254    /// If any of the threads fails to load, the promise is rejected.
255    /// NOTE: The method implements the Step 6 of AddModule
256    /// <https://html.spec.whatwg.org/multipage/#dom-worklet-addmodule>
257    #[allow(clippy::too_many_arguments)]
258    fn fetch_and_invoke_a_worklet_script(
259        &self,
260        pipeline_id: PipelineId,
261        worklet_id: WorkletId,
262        global_type: WorkletGlobalScopeType,
263        origin: ImmutableOrigin,
264        base_url: ServoUrl,
265        script_url: ServoUrl,
266        policy_container: Arc<PolicyContainer>,
267        credentials: RequestCredentials,
268        pending_tasks_struct: PendingTasksStruct,
269        promise: &RootedPromise,
270        inherited_secure_context: Option<bool>,
271    );
272    /// Request that the [`WorkletGlobalScope`] associated with the [`WorkletId`]
273    /// be removed from all the threads in the thread pool.
274    fn exit_worklet(&self, worklet_id: WorkletId);
275    /// Signal all the threads in the pool that there may be control messages to
276    /// process.
277    fn wake_threads(&self);
278    /// Queue a [`WorkletTask`] for execution on this [`WorkletThreadPool`].
279    /// The task will be executed in the context of the [`WorkletGlobalScope`]
280    /// represented by the [`WorketId`].
281    fn perform_a_worklet_task(&self, worklet_id: WorkletId, worklet_task: WorkletTask);
282}
283
284/// The `StatelessWorkletThreadPool` executes the associated
285/// [`WorkletTask`]s in a dedicated thread pool with the assumption that
286/// the tasks are idempotent. This is useful for the paint worklet, for
287/// example.
288///
289/// The goal is to ensure that there is a primary worklet thread,
290/// which is able to responsively execute worklet code. In particular,
291/// worklet execution should not be delayed by GC, or by script
292/// loading.
293///
294/// To achieve this, we implement a three-thread pool, with the
295/// threads cycling between three thread roles:
296///
297///  * The primary worklet thread is the one available to execute
298///    worklet code.
299///
300///  * The hot backup thread may peform GC, but otherwise is expected
301///    to take over the primary role.
302///
303///  * The cold backup thread may peform script loading and other
304///    long-running tasks.
305///
306/// In the implementation, we use two kinds of messages:
307///
308///  * Data messages are expected to be processed quickly, and include
309///    the worklet tasks to be performed by the primary thread, as
310///    well as requests to change role or quit execution.
311///
312///  * Control messages are expected to be processed more slowly, and
313///    include script loading.
314///
315/// Data messages are targeted at a role, for example, task execution
316/// is expected to be performed by whichever thread is currently
317/// primary. Control messages are targeted at a thread, for example
318/// adding a module is performed in every thread, even if they change roles
319/// in the middle of module loading.
320///
321/// The thread pool lives in the script thread, and is initialized
322/// when a worklet adds a module. It is dropped when the script thread
323/// is dropped, and asks each of the worklet threads to quit.
324///
325/// Layout can end up blocking on the primary worklet thread
326/// (e.g. when invoking a paint callback), so it is important to avoid
327/// deadlock by making sure the primary worklet thread doesn't end up
328/// blocking waiting on layout. In particular, since the constellation
329/// can block waiting on layout, this means the primary worklet thread
330/// can't block waiting on the constellation. In general, the primary
331/// worklet thread shouldn't perform any blocking operations. If a worklet
332/// thread needs to do anything blocking, it should send a control
333/// message, to make sure that the blocking operation is performed
334/// by a backup thread, not by the primary thread.
335
336#[derive(Clone, JSTraceable)]
337pub(crate) struct StatelessWorkletThreadPool {
338    // Channels to send data messages to the three roles.
339    #[no_trace]
340    primary_sender: Sender<WorkletData>,
341    #[no_trace]
342    hot_backup_sender: Sender<WorkletData>,
343    #[no_trace]
344    cold_backup_sender: Sender<WorkletData>,
345    // Channels to send control messages to the three threads.
346    #[no_trace]
347    control_sender_0: Sender<WorkletControl>,
348    #[no_trace]
349    control_sender_1: Sender<WorkletControl>,
350    #[no_trace]
351    control_sender_2: Sender<WorkletControl>,
352}
353
354impl Drop for StatelessWorkletThreadPool {
355    fn drop(&mut self) {
356        let _ = self.cold_backup_sender.send(WorkletData::Quit);
357        let _ = self.hot_backup_sender.send(WorkletData::Quit);
358        let _ = self.primary_sender.send(WorkletData::Quit);
359    }
360}
361
362impl StatelessWorkletThreadPool {
363    /// Create a new thread pool and spawn the threads.
364    /// When the thread pool is dropped, the threads will be asked to quit.
365    pub(crate) fn spawn(global_init: WorkletGlobalScopeInit) -> StatelessWorkletThreadPool {
366        let primary_role = WorkletThreadRole::new(false, false);
367        let hot_backup_role = WorkletThreadRole::new(true, false);
368        let cold_backup_role = WorkletThreadRole::new(false, true);
369        let primary_sender = primary_role.sender.clone();
370        let hot_backup_sender = hot_backup_role.sender.clone();
371        let cold_backup_sender = cold_backup_role.sender.clone();
372        let init = WorkletThreadInit {
373            primary_sender: primary_sender.clone(),
374            hot_backup_sender: hot_backup_sender.clone(),
375            cold_backup_sender: cold_backup_sender.clone(),
376            global_init,
377        };
378        StatelessWorkletThreadPool {
379            primary_sender,
380            hot_backup_sender,
381            cold_backup_sender,
382            control_sender_0: WorkletThread::spawn(primary_role, init.clone(), 0),
383            control_sender_1: WorkletThread::spawn(hot_backup_role, init.clone(), 1),
384            control_sender_2: WorkletThread::spawn(cold_backup_role, init, 2),
385        }
386    }
387}
388
389impl WorkletThreadPool for StatelessWorkletThreadPool {
390    #[allow(clippy::too_many_arguments)]
391    fn fetch_and_invoke_a_worklet_script(
392        &self,
393        pipeline_id: PipelineId,
394        worklet_id: WorkletId,
395        global_type: WorkletGlobalScopeType,
396        origin: ImmutableOrigin,
397        base_url: ServoUrl,
398        script_url: ServoUrl,
399        policy_container: Arc<PolicyContainer>,
400        credentials: RequestCredentials,
401        pending_tasks_struct: PendingTasksStruct,
402        promise: &RootedPromise,
403        inherited_secure_context: Option<bool>,
404    ) {
405        // Send each thread a control message asking it to load the script.
406        for sender in &[
407            &self.control_sender_0,
408            &self.control_sender_1,
409            &self.control_sender_2,
410        ] {
411            let _ = sender.send(WorkletControl::FetchAndInvokeAWorkletScript {
412                pipeline_id,
413                worklet_id,
414                global_type,
415                origin: origin.clone(),
416                base_url: base_url.clone(),
417                script_url: script_url.clone(),
418                policy_container: policy_container.clone(),
419                credentials,
420                pending_tasks_struct: pending_tasks_struct.clone(),
421                promise: TrustedPromise::from(promise),
422                inherited_secure_context,
423            });
424        }
425        self.wake_threads();
426    }
427
428    fn exit_worklet(&self, worklet_id: WorkletId) {
429        for sender in &[
430            &self.control_sender_0,
431            &self.control_sender_1,
432            &self.control_sender_2,
433        ] {
434            let _ = sender.send(WorkletControl::ExitWorklet(worklet_id));
435        }
436        self.wake_threads();
437    }
438
439    fn wake_threads(&self) {
440        // If any of the threads are blocked waiting on data, wake them up.
441        let _ = self.cold_backup_sender.send(WorkletData::WakeUp);
442        let _ = self.hot_backup_sender.send(WorkletData::WakeUp);
443        let _ = self.primary_sender.send(WorkletData::WakeUp);
444    }
445
446    /// Queue the [`WorkletTask`] for execution on the primary thread.
447    fn perform_a_worklet_task(&self, worklet_id: WorkletId, worklet_task: WorkletTask) {
448        let msg = WorkletData::Task(worklet_id, worklet_task);
449        let _ = self.primary_sender.send(msg);
450    }
451}
452
453/// A task which can be performed in the context of a [`WorkletGlobalScope`].
454type WorkletTask = Box<dyn FnOnce(&mut JSContext, &WorkletGlobalScope) + Send>;
455
456/// The data messages sent to worklet threads
457enum WorkletData {
458    Task(WorkletId, WorkletTask),
459    StartSwapRoles(Sender<WorkletData>),
460    FinishSwapRoles(Swapper<WorkletThreadRole>),
461    WakeUp,
462    Quit,
463}
464
465/// The control message sent to worklet threads
466pub(crate) enum WorkletControl {
467    ExitWorklet(WorkletId),
468    FetchAndInvokeAWorkletScript {
469        pipeline_id: PipelineId,
470        worklet_id: WorkletId,
471        global_type: WorkletGlobalScopeType,
472        origin: ImmutableOrigin,
473        base_url: ServoUrl,
474        script_url: ServoUrl,
475        policy_container: Arc<PolicyContainer>,
476        credentials: RequestCredentials,
477        pending_tasks_struct: PendingTasksStruct,
478        promise: TrustedPromise,
479        inherited_secure_context: Option<bool>,
480    },
481    Common(WorkletId, CommonScriptMsg),
482}
483
484/// A role that a worklet thread can be playing.
485///
486/// These roles are used as tokens or capabilities, we track unique
487/// ownership using Rust's types, and use atomic swapping to exchange
488/// them between worklet threads. This ensures that each thread pool has
489/// exactly one primary, one hot backup and one cold backup.
490struct WorkletThreadRole {
491    receiver: Receiver<WorkletData>,
492    sender: Sender<WorkletData>,
493    is_hot_backup: bool,
494    is_cold_backup: bool,
495}
496
497impl WorkletThreadRole {
498    fn new(is_hot_backup: bool, is_cold_backup: bool) -> WorkletThreadRole {
499        let (sender, receiver) = unbounded();
500        WorkletThreadRole {
501            sender,
502            receiver,
503            is_hot_backup,
504            is_cold_backup,
505        }
506    }
507}
508
509/// Data to initialize a worklet thread.
510#[derive(Clone)]
511struct WorkletThreadInit {
512    /// Senders
513    primary_sender: Sender<WorkletData>,
514    hot_backup_sender: Sender<WorkletData>,
515    cold_backup_sender: Sender<WorkletData>,
516
517    /// Data for initializing new worklet global scopes
518    global_init: WorkletGlobalScopeInit,
519}
520
521/// A thread for executing worklets.
522#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
523struct WorkletThread {
524    /// Which role the thread is currently playing
525    role: WorkletThreadRole,
526
527    /// The thread's receiver for control messages
528    control_receiver: Receiver<WorkletControl>,
529    /// The sender for sending control messages to this thread's event loop
530    control_sender: Sender<WorkletControl>,
531
532    /// Senders
533    primary_sender: Sender<WorkletData>,
534    hot_backup_sender: Sender<WorkletData>,
535    cold_backup_sender: Sender<WorkletData>,
536
537    /// Data for initializing new worklet global scopes
538    global_init: WorkletGlobalScopeInit,
539
540    /// The global scopes created by this thread
541    global_scopes: FxHashMap<WorkletId, Dom<WorkletGlobalScope>>,
542
543    /// A one-place buffer for control messages
544    control_buffer: Option<WorkletControl>,
545
546    /// A flag that is set when a `WorkletThread` begins shutting down.
547    closing: Arc<AtomicBool>,
548
549    /// The JS runtime
550    runtime: Runtime,
551    should_gc: bool,
552    gc_threshold: u32,
553}
554
555#[expect(unsafe_code)]
556unsafe impl JSTraceable for WorkletThread {
557    unsafe fn trace(&self, trc: *mut JSTracer) {
558        debug!("Tracing worklet thread.");
559        unsafe { self.global_scopes.trace(trc) };
560    }
561}
562
563impl WorkletThread {
564    #[allow(unsafe_code)]
565    /// Spawn a new worklet thread, returning the channel to send it control messages.
566    fn spawn(
567        role: WorkletThreadRole,
568        init: WorkletThreadInit,
569        thread_index: u8,
570    ) -> Sender<WorkletControl> {
571        let (control_sender, control_receiver) = unbounded();
572        let control_sender_clone = control_sender.clone();
573        let _ = thread::Builder::new()
574            .name(format!("Worklet#{thread_index}"))
575            .spawn(move || {
576                // TODO: add a new IN_WORKLET thread state?
577                // TODO: set interrupt handler?
578                // TODO: configure the JS runtime (e.g. discourage GC, encourage agressive JIT)
579                debug!("Initializing worklet thread.");
580                thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER);
581                let runtime = Runtime::new(None);
582                let mut cx = unsafe { runtime.cx() };
583                let mut thread = RootedTraceableBox::new(WorkletThread {
584                    role,
585                    control_receiver,
586                    control_sender: control_sender_clone,
587                    primary_sender: init.primary_sender,
588                    hot_backup_sender: init.hot_backup_sender,
589                    cold_backup_sender: init.cold_backup_sender,
590                    global_init: init.global_init,
591                    global_scopes: FxHashMap::default(),
592                    control_buffer: None,
593                    runtime,
594                    should_gc: false,
595                    closing: Arc::new(AtomicBool::new(false)),
596                    gc_threshold: MIN_GC_THRESHOLD,
597                });
598                thread.run(&mut cx);
599            })
600            .expect("Couldn't start worklet thread");
601        control_sender
602    }
603
604    /// The main event loop for a worklet thread
605    fn run(&mut self, cx: &mut JSContext) {
606        loop {
607            // The handler for data messages
608            let message = self.role.receiver.recv().unwrap();
609            match message {
610                // The whole point of this thread pool is to perform tasks!
611                WorkletData::Task(id, task) => {
612                    self.perform_a_worklet_task(cx, id, task);
613                },
614                // To start swapping roles, get ready to perform an atomic swap,
615                // and block waiting for the other end to finish it.
616                // NOTE: the cold backup can block on the primary or the hot backup;
617                //       the hot backup can block on the primary;
618                //       the primary can block on nothing;
619                //       this total ordering on thread roles is what guarantees deadlock-freedom.
620                WorkletData::StartSwapRoles(sender) => {
621                    let (our_swapper, their_swapper) = swapper();
622                    match sender.send(WorkletData::FinishSwapRoles(their_swapper)) {
623                        Ok(_) => {},
624                        Err(_) => {
625                            // This might happen if the script thread shuts down while
626                            // waiting for the worklet to finish.
627                            return;
628                        },
629                    };
630                    let _ = our_swapper.swap(&mut self.role);
631                },
632                // To finish swapping roles, perform the atomic swap.
633                // The other end should have already started the swap, so this shouldn't block.
634                WorkletData::FinishSwapRoles(swapper) => {
635                    let _ = swapper.swap(&mut self.role);
636                },
637                // Wake up! There may be control messages to process.
638                WorkletData::WakeUp => {},
639                // Quit!
640                WorkletData::Quit => {
641                    return;
642                },
643            }
644
645            // Only process control messages if we're the cold backup,
646            // otherwise if there are outstanding control messages,
647            // try to become the cold backup.
648            if self.role.is_cold_backup {
649                if let Some(control) = self.control_buffer.take() {
650                    self.process_control(control, cx);
651                }
652                while let Ok(control) = self.control_receiver.try_recv() {
653                    self.process_control(control, cx);
654                }
655
656                for worklet_global_scope in self.global_scopes.values() {
657                    worklet_global_scope.perform_a_microtask_checkpoint(cx);
658                }
659
660                self.gc(cx);
661            } else if self.control_buffer.is_none() &&
662                let Ok(control) = self.control_receiver.try_recv()
663            {
664                self.control_buffer = Some(control);
665                let msg = WorkletData::StartSwapRoles(self.role.sender.clone());
666                let _ = self.cold_backup_sender.send(msg);
667            }
668            // If we are tight on memory, and we're a backup then perform a gc.
669            // If we are tight on memory, and we're the primary then try to become the hot backup.
670            // Hopefully this happens soon!
671            if self.current_memory_usage() > self.gc_threshold {
672                if self.role.is_hot_backup || self.role.is_cold_backup {
673                    self.should_gc = false;
674                    self.gc(cx);
675                } else if !self.should_gc {
676                    self.should_gc = true;
677                    let msg = WorkletData::StartSwapRoles(self.role.sender.clone());
678                    let _ = self.hot_backup_sender.send(msg);
679                }
680            }
681        }
682    }
683
684    /// The current memory usage of the thread
685    #[expect(unsafe_code)]
686    fn current_memory_usage(&self) -> u32 {
687        unsafe { JS_GetGCParameter(self.runtime.cx_no_gc(), JSGCParamKey::JSGC_BYTES) }
688    }
689
690    /// Perform a GC.
691    #[expect(unsafe_code)]
692    fn gc(&mut self, cx: &mut JSContext) {
693        debug!(
694            "BEGIN GC (usage = {}, threshold = {}).",
695            self.current_memory_usage(),
696            self.gc_threshold
697        );
698        unsafe { JS_GC(cx, GCReason::API) };
699        self.gc_threshold = max(MIN_GC_THRESHOLD, self.current_memory_usage() * 2);
700        debug!(
701            "END GC (usage = {}, threshold = {}).",
702            self.current_memory_usage(),
703            self.gc_threshold
704        );
705    }
706
707    /// Get the worklet global scope for a given worklet.
708    /// Creates the worklet global scope if it doesn't exist.
709    fn get_worklet_global_scope(
710        &mut self,
711        cx: &mut JSContext,
712        pipeline_id: PipelineId,
713        worklet_id: WorkletId,
714        inherited_secure_context: Option<bool>,
715        global_type: WorkletGlobalScopeType,
716        base_url: ServoUrl,
717    ) -> DomRoot<WorkletGlobalScope> {
718        match self.global_scopes.entry(worklet_id) {
719            hash_map::Entry::Occupied(entry) => DomRoot::from_ref(entry.get()),
720
721            // Step 6.1. If workletInstance's global scopes is empty:
722            hash_map::Entry::Vacant(entry) => {
723                debug!("Creating new worklet global scope.");
724
725                // Step 6.1.1. Create a worklet global scope given workletInstance.
726                let executor = WorkletExecutor {
727                    worklet_id,
728                    primary_sender: self.primary_sender.clone(),
729                    hot_backup_sender: self.hot_backup_sender.clone(),
730                    cold_backup_sender: self.cold_backup_sender.clone(),
731                    control_sender: self.control_sender.clone(),
732                };
733
734                let result = WorkletGlobalScope::new(
735                    global_type,
736                    pipeline_id,
737                    base_url,
738                    inherited_secure_context,
739                    executor,
740                    &self.global_init,
741                    cx,
742                    self.closing.clone(),
743                );
744                entry.insert(Dom::from_ref(&*result));
745                result
746            },
747        }
748    }
749
750    /// Fetch and invoke a worklet script.
751    /// <https://html.spec.whatwg.org/multipage/#fetch-a-worklet-script-graph>
752    #[allow(clippy::too_many_arguments)]
753    fn fetch_and_invoke_a_worklet_script(
754        &self,
755        global_scope: &WorkletGlobalScope,
756        pipeline_id: PipelineId,
757        origin: ImmutableOrigin,
758        script_url: ServoUrl,
759        policy_container: Arc<PolicyContainer>,
760        credentials: RequestCredentials,
761        pending_tasks_struct: PendingTasksStruct,
762        promise: TrustedPromise,
763        cx: &mut JSContext,
764    ) {
765        debug!("Fetching from {}.", script_url);
766        // TODO: Settings object?
767
768        // TODO: Fetch the script asynchronously?
769        // TODO: Caching.
770        let global = global_scope.upcast::<GlobalScope>();
771
772        // Step 1. Let requestURL be request's URL.
773        let request_client = RequestClient {
774            preloaded_resources: PreloadedResources::default(),
775            policy_container,
776            origin: Origin::Origin(origin),
777            is_nested_browsing_context: global.is_nested_browsing_context(),
778            insecure_requests_policy: global.insecure_requests_policy(),
779            upgrade_insecure_navigations_set: global.upgrade_insecure_navigations_set().clone(),
780            has_trustworthy_ancestor_origin: global.has_trustworthy_ancestor_origin(),
781            network_partition_key: None,
782        };
783
784        // Step 2. If moduleResponsesMap[requestURL] is "fetching", wait in parallel until that entry's value changes, then queue a task on the networking task source to proceed with running the following steps.
785        // NOTE: We do not perform the Step 2 because Worklet currently does not implement a `module responses map`
786        // <https://html.spec.whatwg.org/multipage/#concept-worklet-module-responses-map>
787
788        // `fetch_a_module_script_graph` requires the `on_complete` closure to be cloneable
789        // therefore, we wrap the TrustedPromise in an Rc to make it cloneable and RefCell allows calling `reject_task` and `resolve_task`
790        let promise_task = Rc::new(DomRefCell::new(Some(promise)));
791        let script_thread_sender = self.global_init.to_script_thread_sender.clone();
792        let rooted_global = DomRoot::from_ref(global);
793        let script_url = ensure_blob_referenced_by_url_is_kept_alive(global, script_url);
794
795        // NOTE: We implement the rest of the steps in AddModule here
796        // <https://html.spec.whatwg.org/multipage/#dom-worklet-addmodule>
797        // Step 6.4. For each workletGlobalScope of workletInstance's global scopes,
798        // queue a global task on the networking task source given workletGlobalScope to fetch a worklet script graph given moduleURLRecord,
799        // outsideSettings, workletInstance's worklet destination type, options["credentials"], workletGlobalScope's relevant settings object,
800        // workletInstance's module responses map, and the following steps given script:
801        fetch_a_module_script_graph(
802            cx,
803            global,
804            script_url,
805            request_client,
806            Destination::PaintWorklet,
807            global.get_referrer(),
808            credentials.convert(),
809            Some(IntroductionType::WORKLET),
810            move |cx, module_tree| {
811                match module_tree {
812                    // Step 6.4.1. If script is null:
813                    None => {
814                        debug!("Failed to load script.");
815
816                        reject_promise(
817                            &pending_tasks_struct,
818                            promise_task.safe_borrow_mut(cx.no_gc()),
819                            script_thread_sender.clone(),
820                        );
821                    },
822                    Some(script) => {
823                        let mut realm = enter_auto_realm(cx, &*rooted_global);
824                        let cx = &mut realm.current_realm();
825
826                        // Step 6.4.2. If script's error to rethrow is not null:
827                        // NOTE: The `AddModule` specification in the Step 6.4.2.1.1.2. requires the promise to be rejected with the script's "rethrow error".
828                        // However, the `JSVal` from `rethrow_error` cannot be used with the `promise_task` here because they are from different runtimes.
829                        // So we throw an AbortError instead.
830                        if script.has_rethrow_error() {
831                            // Step 6.4.2.1. and its substeps are handled by `reject_promise` function
832                            reject_promise(
833                                &pending_tasks_struct,
834                                promise_task.safe_borrow_mut(cx.no_gc()),
835                                script_thread_sender.clone(),
836                            );
837
838                            // Step 6.4.2.2. Abort these steps.
839                            return;
840                        }
841
842                        // Step 6.4.4. Run a module script given script.
843                        let module = RootedTraceableBox::new(script);
844                        rooted_global.run_a_module_script(cx, module, false);
845
846                        // NOTE: we are treating all negative values as -1
847                        // Step 6.4.5.1. If pendingTasks is not −1:
848                        // Step 6.4.5.1.1. Set pendingTasks to pendingTasks − 1.
849                        let old_counter = pending_tasks_struct.decrement_counter_by(1);
850                        // Step Step 6.4.5.1.2. If pendingTasks is 0 then, resolve promise.
851                        if old_counter == 1 {
852                            debug!("Resolving promise.");
853
854                            let msg = MainThreadScriptMsg::WorkletLoaded(pipeline_id);
855                            script_thread_sender
856                                .send(msg)
857                                .expect("Worklet thread outlived script thread.");
858
859                            let task = promise_task
860                                .safe_borrow_mut(cx.no_gc())
861                                .take()
862                                .expect("promise_task must be consumed exactly once")
863                                .resolve_task(());
864
865                            let msg = CommonScriptMsg::Task(
866                                ScriptThreadEventCategory::WorkletEvent,
867                                Box::new(task),
868                                None,
869                                TaskSourceName::Networking,
870                            );
871
872                            // Step 6.4.5. Queue a global task on the networking task source given workletInstance's relevant global object to perform the following steps:
873                            let msg = MainThreadScriptMsg::Common(msg);
874                            script_thread_sender
875                                .send(msg)
876                                .expect("Worklet thread outlived script thread.");
877                        }
878                    },
879                }
880            },
881        );
882    }
883
884    /// Run the steps for the `WorkletTask` for a given Worklet.
885    fn perform_a_worklet_task(
886        &self,
887        cx: &mut JSContext,
888        worklet_id: WorkletId,
889        worklet_task: WorkletTask,
890    ) {
891        match self.global_scopes.get(&worklet_id) {
892            Some(global) => worklet_task(cx, global),
893            None => warn!("No such worklet as {:?}.", worklet_id),
894        }
895    }
896
897    /// Process a control message.
898    fn process_control(&mut self, control: WorkletControl, cx: &mut js::context::JSContext) {
899        match control {
900            WorkletControl::ExitWorklet(worklet_id) => {
901                if let Some(global_scope) = self
902                    .global_scopes
903                    .remove(&worklet_id)
904                    .map(|global_scope| global_scope.as_rooted())
905                {
906                    global_scope.upcast::<GlobalScope>().tear_down();
907                }
908            },
909            WorkletControl::FetchAndInvokeAWorkletScript {
910                pipeline_id,
911                worklet_id,
912                global_type,
913                origin,
914                base_url,
915                script_url,
916                policy_container,
917                credentials,
918                pending_tasks_struct,
919                promise,
920                inherited_secure_context,
921            } => {
922                // A worklet global scope is created here as part of the AddModule specs.
923                // <https://html.spec.whatwg.org/multipage/#dom-worklet-addmodule>
924                // 6.1.3. Wait for all steps of the creation process(es) — including those taking place within the worklet agents — to complete, before moving on.
925                let global = self.get_worklet_global_scope(
926                    cx,
927                    pipeline_id,
928                    worklet_id,
929                    inherited_secure_context,
930                    global_type,
931                    base_url,
932                );
933                self.fetch_and_invoke_a_worklet_script(
934                    &global,
935                    pipeline_id,
936                    origin,
937                    script_url,
938                    policy_container,
939                    credentials,
940                    pending_tasks_struct,
941                    promise,
942                    cx,
943                )
944            },
945            WorkletControl::Common(worklet_id, script_msg) => {
946                if let CommonScriptMsg::Task(_, task, _, _) = script_msg &&
947                    let Some(global) = self.global_scopes.get(&worklet_id)
948                {
949                    let mut realm = enter_auto_realm(cx, global.upcast::<GlobalScope>());
950                    let cx = &mut realm;
951                    task.run_box(cx);
952                }
953            },
954        }
955    }
956}
957
958/// This function is an abstraction of steps 6.4.1.1 and 6.4.2.1 of the `AddModule` spec
959/// <https://html.spec.whatwg.org/multipage/#dom-worklet-addmodule>
960pub(crate) fn reject_promise(
961    pending_tasks_struct: &PendingTasksStruct,
962    mut promise_task: RefMut<'_, Option<TrustedPromise>>,
963    script_thread_sender: Sender<MainThreadScriptMsg>,
964) {
965    // Step 6.4.1.1.1.1. Set pendingTasks to −1
966    let old_counter = pending_tasks_struct.set_counter_to(-1);
967
968    // 6.4.1.1.1. If pendingTasks is not −1:
969    if old_counter > 0 {
970        // 6.4.1.1.1.2. Reject promise with an "AbortError" DOMException
971        let task = promise_task
972            .take()
973            .expect("promise_task must be consumed exactly once")
974            .reject_task(Error::Abort(None));
975
976        let msg = CommonScriptMsg::Task(
977            ScriptThreadEventCategory::WorkletEvent,
978            Box::new(task),
979            None,
980            TaskSourceName::Networking,
981        );
982
983        // Step 6.4.1.1. Queue a global task on the networking task source given workletInstance's relevant global object to perform the following steps:
984        let msg = MainThreadScriptMsg::Common(msg);
985        script_thread_sender
986            .send(msg)
987            .expect("Worklet thread outlived script thread.");
988    }
989}
990
991/// An executor of worklet tasks
992#[derive(Clone, JSTraceable, MallocSizeOf)]
993pub(crate) struct WorkletExecutor {
994    worklet_id: WorkletId,
995    #[no_trace]
996    primary_sender: Sender<WorkletData>,
997    #[no_trace]
998    hot_backup_sender: Sender<WorkletData>,
999    #[no_trace]
1000    cold_backup_sender: Sender<WorkletData>,
1001    #[no_trace]
1002    control_sender: Sender<WorkletControl>,
1003}
1004
1005impl WorkletExecutor {
1006    /// If any of the threads are blocked waiting on data, wake them up.
1007    pub(crate) fn wake_threads(&self) -> Result<(), SendError<()>> {
1008        self.cold_backup_sender
1009            .send(WorkletData::WakeUp)
1010            .map_err(|_| SendError(()))?;
1011        self.hot_backup_sender
1012            .send(WorkletData::WakeUp)
1013            .map_err(|_| SendError(()))?;
1014        self.primary_sender
1015            .send(WorkletData::WakeUp)
1016            .map_err(|_| SendError(()))
1017    }
1018
1019    /// Schedule a worklet task to be peformed by the worklet thread pool.
1020    pub(crate) fn schedule_a_worklet_task(&self, task: WorkletTask) {
1021        let _ = self
1022            .primary_sender
1023            .send(WorkletData::Task(self.worklet_id, task));
1024    }
1025
1026    /// Send a [`CommonScriptMsg`] to be send to the worklet thread pool.
1027    pub(crate) fn send_common_message(
1028        &self,
1029        common_message: CommonScriptMsg,
1030    ) -> Result<(), SendError<()>> {
1031        self.control_sender
1032            .send(WorkletControl::Common(self.worklet_id, common_message))
1033            .map_err(|_| SendError(()))?;
1034        self.wake_threads()
1035    }
1036
1037    pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
1038        ScriptEventLoopSender::Worklet(self.clone())
1039    }
1040}