Skip to main content

script/tasks/
task_queue.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//! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue).
6
7use std::collections::VecDeque;
8use std::default::Default;
9
10use crossbeam_channel::{self, Receiver};
11use js::context::JSContext;
12use rustc_hash::{FxHashMap, FxHashSet};
13use script_bindings::cell::DomRefCell;
14use script_bindings::root::DomRoot;
15use servo_base::id::PipelineId;
16
17use crate::dom::GlobalScope;
18use crate::dom::worker::TrustedWorkerAddress;
19use crate::realms::enter_auto_realm;
20use crate::runtime::script_runtime::ScriptThreadEventCategory;
21use crate::tasks::task::TaskBox;
22use crate::tasks::task_source::TaskSourceName;
23
24#[derive(MallocSizeOf)]
25pub(crate) struct QueuedTask {
26    pub(crate) worker: Option<TrustedWorkerAddress>,
27    pub(crate) event_category: ScriptThreadEventCategory,
28    #[ignore_malloc_size_of = "TaskBox is difficult"]
29    pub(crate) task: Box<dyn TaskBox>,
30    pub(crate) pipeline_id: Option<PipelineId>,
31    pub(crate) task_source: TaskSourceName,
32}
33
34/// Defining the operations used to convert from a msg T to a QueuedTask.
35pub(crate) trait QueuedTaskConversion {
36    fn pipeline_id(&self) -> Option<PipelineId>;
37    fn into_queued_task(self) -> Option<QueuedTask>;
38    fn from_queued_task(queued_task: QueuedTask) -> Self;
39    fn inactive_msg() -> Self;
40    fn wake_up_msg() -> Self;
41    fn is_wake_up(&self) -> bool;
42}
43
44#[derive(MallocSizeOf)]
45pub(crate) struct TaskQueue<T> {
46    /// The original port on which the task-sources send tasks as messages.
47    port: Receiver<T>,
48    /// A queue from which the event-loop can drain tasks.
49    msg_queue: DomRefCell<VecDeque<T>>,
50    /// Tasks for not fully-active documents.
51    inactive: DomRefCell<FxHashMap<PipelineId, VecDeque<QueuedTask>>>,
52    /// List of pipelines that have been owned and closed by the parent script thread.
53    closed_pipelines: DomRefCell<FxHashSet<PipelineId>>,
54}
55
56impl<T: QueuedTaskConversion> TaskQueue<T> {
57    pub(crate) fn new(port: Receiver<T>) -> TaskQueue<T> {
58        TaskQueue {
59            port,
60            msg_queue: DomRefCell::new(VecDeque::new()),
61            inactive: Default::default(),
62            closed_pipelines: Default::default(),
63        }
64    }
65
66    /// Remove any tasks for an exiting pipeline. This only clears tasks that
67    /// were stored from a previously inactive pipeline, as others will be drained
68    /// the next time the queue is processed.
69    pub(crate) fn remove_tasks_for_exiting_pipeline(&self, pipeline_id: &PipelineId) {
70        self.inactive.borrow_mut().remove(pipeline_id);
71        self.closed_pipelines.borrow_mut().insert(*pipeline_id);
72    }
73
74    pub(crate) fn is_pipeline_closed(&self, pipeline_id: &PipelineId) -> bool {
75        self.closed_pipelines.borrow().contains(pipeline_id)
76    }
77
78    /// Release previously held-back tasks for documents that are now fully-active.
79    /// <https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active>
80    fn release_tasks_for_fully_active_documents(
81        &self,
82        fully_active: &FxHashSet<PipelineId>,
83    ) -> Vec<T> {
84        self.inactive
85            .borrow_mut()
86            .iter_mut()
87            .filter(|(pipeline_id, _)| fully_active.contains(pipeline_id))
88            .flat_map(|(_, inactive_queue)| {
89                inactive_queue
90                    .drain(0..)
91                    .map(|queued_task| T::from_queued_task(queued_task))
92            })
93            .collect()
94    }
95
96    /// Hold back tasks for currently not fully-active documents.
97    /// <https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active>
98    fn store_task_for_inactive_pipeline(&self, msg: T, pipeline_id: &PipelineId) {
99        if !self.is_pipeline_closed(pipeline_id) {
100            let mut inactive = self.inactive.borrow_mut();
101            let inactive_queue = inactive.entry(*pipeline_id).or_default();
102            inactive_queue.push_back(
103                msg.into_queued_task()
104                    .expect("Incoming messages should always be convertible into queued tasks"),
105            );
106        }
107
108        let mut msg_queue = self.msg_queue.borrow_mut();
109        if msg_queue.is_empty() {
110            // Ensure there is at least one message.
111            // Otherwise if the just stored inactive message (or dropped message)
112            // was the first and last of this iteration,
113            // it will result in a spurious wake-up of the event-loop.
114            msg_queue.push_back(T::inactive_msg());
115        }
116    }
117
118    /// Drain the queue for the current iteration of the event-loop.
119    pub(crate) fn take_tasks(&self, first_message: T, fully_active: &FxHashSet<PipelineId>) {
120        // 1. Make any previously stored task from now fully-active document available.
121        let mut incoming = self.release_tasks_for_fully_active_documents(fully_active);
122
123        // 2. Process the first message (artifact of the fact that select always returns a message).
124        if !first_message.is_wake_up() {
125            incoming.push(first_message);
126        }
127
128        // 3. Process any other incoming message.
129        while let Ok(message) = self.port.try_recv() {
130            if !message.is_wake_up() {
131                incoming.push(message);
132            }
133        }
134
135        for msg in incoming {
136            if let Some(pipeline_id) = msg.pipeline_id() &&
137                !fully_active.contains(&pipeline_id)
138            {
139                self.store_task_for_inactive_pipeline(msg, &pipeline_id);
140                continue;
141            }
142            self.msg_queue.borrow_mut().push_back(msg);
143        }
144    }
145
146    /// Reset the queue for a new iteration of the event-loop,
147    /// returning the port about whose readiness we want to be notified.
148    pub(crate) fn select(&self) -> &crossbeam_channel::Receiver<T> {
149        // We want to be notified when the script-port is ready to receive.
150        // Hence that's the one we need to include in the select.
151        &self.port
152    }
153
154    /// Take a message from the front of the queue, without waiting if empty.
155    pub(crate) fn recv(&self) -> Result<T, ()> {
156        self.msg_queue.borrow_mut().pop_front().ok_or(())
157    }
158
159    /// Take all tasks again and then run `recv()`.
160    pub(crate) fn take_tasks_and_recv(
161        &self,
162        fully_active: &FxHashSet<PipelineId>,
163    ) -> Result<T, ()> {
164        self.take_tasks(T::wake_up_msg(), fully_active);
165        self.recv()
166    }
167
168    pub(crate) fn run_task(
169        &self,
170        cx: &mut JSContext,
171        pipeline_id: Option<PipelineId>,
172        global: Option<DomRoot<GlobalScope>>,
173        task: Box<dyn TaskBox>,
174    ) {
175        // If a task comes in for a pipeline that has already been closed somehow, do not run it.
176        // This is insurance in case tasks slip through. These pipelines have already had their
177        // runtime shut down, so it is never okay to run them.
178        if pipeline_id.is_some() && global.is_none() {
179            return;
180        }
181
182        let Some(global) = global else {
183            task.run_box(cx);
184            return;
185        };
186
187        let mut realm = enter_auto_realm(cx, &*global);
188        let cx = &mut realm.current_realm();
189        task.run_box(cx)
190    }
191}