1#![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
65const 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 #[ignore_malloc_size_of = "Difficult to measure memory usage of Rc<...> types"]
79 thread_pool: LazyCellWithBoxedInitializer<Rc<dyn WorkletThreadPool>>,
80
81 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]
97pub(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 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 let module_url_record = match self.window.Document().base_url().join(&module_url.0) {
170 Ok(url) => url,
171 Err(err) => {
172 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 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 debug!("Returning promise.");
215 promise
216 }
217}
218
219#[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#[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 #[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 fn exit_worklet(&self, worklet_id: WorkletId);
275 fn wake_threads(&self);
278 fn perform_a_worklet_task(&self, worklet_id: WorkletId, worklet_task: WorkletTask);
282}
283
284#[derive(Clone, JSTraceable)]
337pub(crate) struct StatelessWorkletThreadPool {
338 #[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 #[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 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 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 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 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
453type WorkletTask = Box<dyn FnOnce(&mut JSContext, &WorkletGlobalScope) + Send>;
455
456enum WorkletData {
458 Task(WorkletId, WorkletTask),
459 StartSwapRoles(Sender<WorkletData>),
460 FinishSwapRoles(Swapper<WorkletThreadRole>),
461 WakeUp,
462 Quit,
463}
464
465pub(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
484struct 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#[derive(Clone)]
511struct WorkletThreadInit {
512 primary_sender: Sender<WorkletData>,
514 hot_backup_sender: Sender<WorkletData>,
515 cold_backup_sender: Sender<WorkletData>,
516
517 global_init: WorkletGlobalScopeInit,
519}
520
521#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
523struct WorkletThread {
524 role: WorkletThreadRole,
526
527 control_receiver: Receiver<WorkletControl>,
529 control_sender: Sender<WorkletControl>,
531
532 primary_sender: Sender<WorkletData>,
534 hot_backup_sender: Sender<WorkletData>,
535 cold_backup_sender: Sender<WorkletData>,
536
537 global_init: WorkletGlobalScopeInit,
539
540 global_scopes: FxHashMap<WorkletId, Dom<WorkletGlobalScope>>,
542
543 control_buffer: Option<WorkletControl>,
545
546 closing: Arc<AtomicBool>,
548
549 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 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 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 fn run(&mut self, cx: &mut JSContext) {
606 loop {
607 let message = self.role.receiver.recv().unwrap();
609 match message {
610 WorkletData::Task(id, task) => {
612 self.perform_a_worklet_task(cx, id, task);
613 },
614 WorkletData::StartSwapRoles(sender) => {
621 let (our_swapper, their_swapper) = swapper();
622 match sender.send(WorkletData::FinishSwapRoles(their_swapper)) {
623 Ok(_) => {},
624 Err(_) => {
625 return;
628 },
629 };
630 let _ = our_swapper.swap(&mut self.role);
631 },
632 WorkletData::FinishSwapRoles(swapper) => {
635 let _ = swapper.swap(&mut self.role);
636 },
637 WorkletData::WakeUp => {},
639 WorkletData::Quit => {
641 return;
642 },
643 }
644
645 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 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 #[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 #[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 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 hash_map::Entry::Vacant(entry) => {
723 debug!("Creating new worklet global scope.");
724
725 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 #[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 let global = global_scope.upcast::<GlobalScope>();
771
772 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 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 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 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 if script.has_rethrow_error() {
831 reject_promise(
833 &pending_tasks_struct,
834 promise_task.safe_borrow_mut(cx.no_gc()),
835 script_thread_sender.clone(),
836 );
837
838 return;
840 }
841
842 let module = RootedTraceableBox::new(script);
844 rooted_global.run_a_module_script(cx, module, false);
845
846 let old_counter = pending_tasks_struct.decrement_counter_by(1);
850 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 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 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 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 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
958pub(crate) fn reject_promise(
961 pending_tasks_struct: &PendingTasksStruct,
962 mut promise_task: RefMut<'_, Option<TrustedPromise>>,
963 script_thread_sender: Sender<MainThreadScriptMsg>,
964) {
965 let old_counter = pending_tasks_struct.set_counter_to(-1);
967
968 if old_counter > 0 {
970 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 let msg = MainThreadScriptMsg::Common(msg);
985 script_thread_sender
986 .send(msg)
987 .expect("Worklet thread outlived script thread.");
988 }
989}
990
991#[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 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 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 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}