Skip to content

Commit

Permalink
in BC event-loop, only run tasks related to fully-active documents
Browse files Browse the repository at this point in the history
  • Loading branch information
gterzian committed Feb 3, 2019
1 parent 6b64842 commit 664bb6d
Show file tree
Hide file tree
Showing 12 changed files with 275 additions and 13 deletions.
1 change: 1 addition & 0 deletions components/constellation/constellation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3911,6 +3911,7 @@ where
}

for pipeline_id in pipelines_to_close {
println!("Closing pipeline {:?}", pipeline_id);
self.close_pipeline(pipeline_id, dbc, exit_mode);
}

Expand Down
13 changes: 12 additions & 1 deletion components/script/dom/dedicatedworkerglobalscope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use js::jsapi::JS_AddInterruptCallback;
use js::jsapi::{JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use js::rust::HandleValue;
use msg::constellation_msg::TopLevelBrowsingContextId;
use msg::constellation_msg::{PipelineId, TopLevelBrowsingContextId};
use net_traits::request::{CredentialsMode, Destination, RequestInit};
use net_traits::{load_whole_resource, IpcSend};
use script_traits::{TimerEvent, TimerSource, WorkerGlobalScopeInit, WorkerScriptLoadOrigin};
Expand Down Expand Up @@ -105,6 +105,12 @@ impl QueuedTaskConversion for DedicatedWorkerScriptMsg {
}
}

fn pipeline_id(&self) -> Option<&PipelineId> {
// Workers always return None, since the pipeline_id is only used to check for document activity,
// and this check does not apply to worker event-loops.
None
}

fn into_queued_task(self) -> Option<QueuedTask> {
let (worker, common_worker_msg) = match self {
DedicatedWorkerScriptMsg::CommonWorker(worker, common_worker_msg) => {
Expand All @@ -131,6 +137,11 @@ impl QueuedTaskConversion for DedicatedWorkerScriptMsg {
DedicatedWorkerScriptMsg::CommonWorker(worker.unwrap(), WorkerScriptMsg::Common(script_msg))
}

fn inactive_msg() -> Self {
// Inactive is only relevant in the context of a browsing-context event-loop.
unreachable!("Workers should never receive messages marked as inactive");
}

fn wake_up_msg() -> Self {
DedicatedWorkerScriptMsg::WakeUp
}
Expand Down
12 changes: 12 additions & 0 deletions components/script/dom/serviceworkerglobalscope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use ipc_channel::router::ROUTER;
use js::jsapi::{JSAutoCompartment, JSContext, JS_AddInterruptCallback};
use js::jsval::UndefinedValue;
use msg::constellation_msg::PipelineId;
use net_traits::request::{CredentialsMode, Destination, RequestInit};
use net_traits::{load_whole_resource, CustomResponseMediator, IpcSend};
use script_traits::{
Expand Down Expand Up @@ -65,6 +66,12 @@ impl QueuedTaskConversion for ServiceWorkerScriptMsg {
}
}

fn pipeline_id(&self) -> Option<&PipelineId> {
// Workers always return None, since the pipeline_id is only used to check for document activity,
// and this check does not apply to worker event-loops.
None
}

fn into_queued_task(self) -> Option<QueuedTask> {
let script_msg = match self {
ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(script_msg)) => script_msg,
Expand All @@ -85,6 +92,11 @@ impl QueuedTaskConversion for ServiceWorkerScriptMsg {
ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(script_msg))
}

fn inactive_msg() -> Self {
// Inactive is only relevant in the context of a browsing-context event-loop.
unreachable!("Workers should never receive messages marked as inactive");
}

fn wake_up_msg() -> Self {
ServiceWorkerScriptMsg::WakeUp
}
Expand Down
52 changes: 50 additions & 2 deletions components/script/script_thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,8 @@ pub enum MainThreadScriptMsg {
},
/// Dispatches a job queue.
DispatchJobQueue { scope_url: ServoUrl },
/// A task related to a not fully-active document has been throttled.
Inactive,
/// Wake-up call from the task queue.
WakeUp,
}
Expand All @@ -289,6 +291,19 @@ impl QueuedTaskConversion for MainThreadScriptMsg {
}
}

fn pipeline_id(&self) -> Option<&PipelineId> {
let script_msg = match self {
MainThreadScriptMsg::Common(script_msg) => script_msg,
_ => return None,
};
match script_msg {
CommonScriptMsg::Task(_category, _boxed, pipeline_id, _task_source) => {
pipeline_id.as_ref()
},
_ => return None,
}
}

fn into_queued_task(self) -> Option<QueuedTask> {
let script_msg = match self {
MainThreadScriptMsg::Common(script_msg) => script_msg,
Expand All @@ -309,6 +324,10 @@ impl QueuedTaskConversion for MainThreadScriptMsg {
MainThreadScriptMsg::Common(script_msg)
}

fn inactive_msg() -> Self {
MainThreadScriptMsg::Inactive
}

fn wake_up_msg() -> Self {
MainThreadScriptMsg::WakeUp
}
Expand Down Expand Up @@ -881,6 +900,29 @@ impl ScriptThread {
})
}

pub fn get_currently_not_fully_active_document_ids() -> HashSet<PipelineId> {
SCRIPT_THREAD_ROOT.with(|root| {
root.get().map_or(HashSet::new(), |script_thread| {
let script_thread = unsafe { &*script_thread };
script_thread
.documents
.borrow()
.iter()
.filter_map(|(id, document)| {
if !document.is_fully_active() {
Some(id.clone())
} else {
None
}
})
.fold(HashSet::new(), |mut set, id| {
let _ = set.insert(id);
set
})
})
})
}

pub fn find_window_proxy(id: BrowsingContextId) -> Option<DomRoot<WindowProxy>> {
SCRIPT_THREAD_ROOT.with(|root| {
root.get().and_then(|script_thread| {
Expand Down Expand Up @@ -1169,7 +1211,7 @@ impl ScriptThread {
let mut event = select! {
recv(self.task_queue.select()) -> msg => {
self.task_queue.take_tasks(msg.unwrap());
FromScript(self.task_queue.recv().unwrap())
FromScript(self.task_queue.recv().expect("Spurious wake-up of the event-loop, task-queue has no tasks available"))
},
recv(self.control_port) -> msg => FromConstellation(msg.unwrap()),
recv(self.timer_event_port) -> msg => FromScheduler(msg.unwrap()),
Expand Down Expand Up @@ -1252,6 +1294,10 @@ impl ScriptThread {
Some(index) => sequential[index] = event,
}
},
FromScript(MainThreadScriptMsg::Inactive) => {
// An event came-in from a document that is not fully-active, it has been stored by the task-queue.
// Continue without adding it to "sequential".
},
_ => {
sequential.push(event);
},
Expand Down Expand Up @@ -1460,6 +1506,7 @@ impl ScriptThread {
MainThreadScriptMsg::WorkletLoaded(pipeline_id) => Some(pipeline_id),
MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id, .. } => Some(pipeline_id),
MainThreadScriptMsg::DispatchJobQueue { .. } => None,
MainThreadScriptMsg::Inactive => None,
MainThreadScriptMsg::WakeUp => None,
},
MixedMessage::FromImageCache((pipeline_id, _)) => Some(pipeline_id),
Expand Down Expand Up @@ -1703,6 +1750,7 @@ impl ScriptThread {
MainThreadScriptMsg::DispatchJobQueue { scope_url } => {
self.job_queue_map.run_job(scope_url, self)
},
MainThreadScriptMsg::Inactive => {},
MainThreadScriptMsg::WakeUp => {},
}
}
Expand Down Expand Up @@ -2058,7 +2106,7 @@ impl ScriptThread {

/// Handles activity change message
fn handle_set_document_activity_msg(&self, id: PipelineId, activity: DocumentActivity) {
debug!(
println!(
"Setting activity of {} to be {:?} in {:?}.",
id,
activity,
Expand Down
1 change: 1 addition & 0 deletions components/script/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ where
}

fn run_once(self) {
println!("Task {:?} was cancelled: {:?}", self.inner.name(), self.is_cancelled());
if !self.is_cancelled() {
self.inner.run_once()
}
Expand Down
112 changes: 102 additions & 10 deletions components/script/task_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::worker::TrustedWorkerAddress;
use crate::script_runtime::ScriptThreadEventCategory;
use crate::script_thread::ScriptThread;
use crate::task::TaskBox;
use crate::task_source::TaskSourceName;
use crossbeam_channel::{self, Receiver, Sender};
use msg::constellation_msg::PipelineId;
use std::cell::Cell;
use std::collections::{HashMap, VecDeque};
use std::collections::{HashMap, HashSet, VecDeque};
use std::default::Default;

pub type QueuedTask = (
Expand All @@ -26,8 +27,10 @@ pub type QueuedTask = (
/// Defining the operations used to convert from a msg T to a QueuedTask.
pub trait QueuedTaskConversion {
fn task_source_name(&self) -> Option<&TaskSourceName>;
fn pipeline_id(&self) -> Option<&PipelineId>;
fn into_queued_task(self) -> Option<QueuedTask>;
fn from_queued_task(queued_task: QueuedTask) -> Self;
fn inactive_msg() -> Self;
fn wake_up_msg() -> Self;
fn is_wake_up(&self) -> bool;
}
Expand All @@ -43,6 +46,8 @@ pub struct TaskQueue<T> {
taken_task_counter: Cell<u64>,
/// Tasks that will be throttled for as long as we are "busy".
throttled: DomRefCell<HashMap<TaskSourceName, VecDeque<QueuedTask>>>,
/// Tasks for not fully-active documents.
inactive: DomRefCell<HashMap<PipelineId, VecDeque<QueuedTask>>>,
}

impl<T: QueuedTaskConversion> TaskQueue<T> {
Expand All @@ -53,22 +58,88 @@ impl<T: QueuedTaskConversion> TaskQueue<T> {
msg_queue: DomRefCell::new(VecDeque::new()),
taken_task_counter: Default::default(),
throttled: Default::default(),
inactive: Default::default(),
}
}

/// Process an incoming message, either:
/// 1: making it available for further processing as part of "incoming", or
/// 2: in the case of a not fully-active document, storing it into the "inactive" queue.
fn process_message(
&self,
msg: T,
currently_inactive: &HashSet<PipelineId>,
incoming: &mut Vec<T>,
) {
if msg.is_wake_up() {
return;
}
let mut inactive = self.inactive.borrow_mut();
// Hold back tasks for currently not fully-active documents.
// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active
if let Some(pipeline_id) = msg.pipeline_id() {
if currently_inactive.contains(pipeline_id) {
let (worker, category, boxed, pipeline_id, task_source) = msg.into_queued_task().expect(
"Incoming messages should always be convertible into queued tasks",
);
println!("Storing inactive {:?} for {:?}", boxed.name(), pipeline_id);
let inactive_queue = inactive
.entry(pipeline_id.clone().unwrap())
.or_insert(VecDeque::new());
inactive_queue
.push_back((worker, category, boxed, pipeline_id, task_source));
if incoming.is_empty() {
// Ensure there is at least one message.
// Otherwise if the just stored inactive message
// was the first and last of this iteration,
// it will result in a spurious wake-up of the event-loop.
incoming.push(T::inactive_msg());
}
return;
}
}
incoming.push(msg);
}

/// Release previously held-back tasks for documents that are now fully-active.
fn release_tasks_for_fully_active_documents(
&self,
currently_inactive: &HashSet<PipelineId>,
incoming: &mut Vec<T>,
) {
let previously_inactive: HashSet<PipelineId> = {
let inactive = self.inactive.borrow();
inactive.keys().map(|id| id.clone()).collect()
};
let mut inactive = self.inactive.borrow_mut();
for pipeline_id in previously_inactive.difference(&currently_inactive) {
let (_, inactive_queue) = inactive
.remove_entry(&pipeline_id)
.expect("Inactive should contain this key");
for (worker, category, boxed, pipeline_id, task_source) in inactive_queue {
println!("Releasing inactive {:?} for {:?}", boxed.name(), pipeline_id);
incoming.push(T::from_queued_task((worker, category, boxed, pipeline_id, task_source)));
}
}
}

/// Process incoming tasks, immediately sending priority ones downstream,
/// and categorizing potential throttles.
fn process_incoming_tasks(&self, first_msg: T) {
let mut incoming = Vec::with_capacity(self.port.len() + 1);
if !first_msg.is_wake_up() {
incoming.push(first_msg);
}
fn process_incoming_tasks(&self, first_msg: T, currently_inactive: &HashSet<PipelineId>) {
let mut incoming = vec![];

// 1. Make any previously stored task from now fully-active document available.
self.release_tasks_for_fully_active_documents(currently_inactive, &mut incoming);

// 2. Process the first message(artifact of the fact that select always returns a message).
self.process_message(first_msg, currently_inactive, &mut incoming);

// 3. Process any other incoming message.
while let Ok(msg) = self.port.try_recv() {
if !msg.is_wake_up() {
incoming.push(msg);
}
self.process_message(msg, currently_inactive, &mut incoming);
}

// 4. Filter tasks from non-priority task-sources.
let to_be_throttled: Vec<T> = incoming
.drain_filter(|msg| {
let task_source = match msg.task_source_name() {
Expand Down Expand Up @@ -133,8 +204,9 @@ impl<T: QueuedTaskConversion> TaskQueue<T> {
pub fn take_tasks(&self, first_msg: T) {
// High-watermark: once reached, throttled tasks will be held-back.
const PER_ITERATION_MAX: u64 = 5;
let currently_inactive = ScriptThread::get_currently_not_fully_active_document_ids();
// Always first check for new tasks, but don't reset 'taken_task_counter'.
self.process_incoming_tasks(first_msg);
self.process_incoming_tasks(first_msg, &currently_inactive);
let mut throttled = self.throttled.borrow_mut();
let mut throttled_length: usize = throttled.values().map(|queue| queue.len()).sum();
let task_source_names = TaskSourceName::all();
Expand Down Expand Up @@ -165,6 +237,26 @@ impl<T: QueuedTaskConversion> TaskQueue<T> {
None => continue,
};
let msg = T::from_queued_task(queued_task);

// Hold back tasks for currently inactive documents.
if let Some(pipeline_id) = msg.pipeline_id() {
if currently_inactive.contains(pipeline_id) {
let mut inactive = self.inactive.borrow_mut();
let inactive_queue = inactive
.entry(pipeline_id.clone())
.or_insert(VecDeque::new());
inactive_queue.push_back(msg.into_queued_task().expect(
"Throttled messages should always be convertible into queued tasks",
));
// Reduce the length of throttles,
// but don't add the task to "msg_queue",
// and neither increment "taken_task_counter".
throttled_length = throttled_length - 1;
continue;
}
}

// Make the task available for the event-loop to handle as a message.
let _ = self.msg_queue.borrow_mut().push_back(msg);
self.taken_task_counter
.set(self.taken_task_counter.get() + 1);
Expand Down
Loading

0 comments on commit 664bb6d

Please sign in to comment.