-
-
Notifications
You must be signed in to change notification settings - Fork 621
Expand file tree
/
Copy pathexecutor.rs
More file actions
305 lines (268 loc) · 11.1 KB
/
executor.rs
File metadata and controls
305 lines (268 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use std::{
cell::{Cell, RefCell},
collections::VecDeque,
mem,
pin::{Pin, pin},
rc::Rc,
};
use boa_engine::{
Context, JsResult, JsValue,
job::{GenericJob, Job, JobExecutor, NativeAsyncJob, PromiseJob},
};
use futures_concurrency::future::FutureGroup;
use smol::{future::FutureExt, stream::StreamExt};
use unsend::{Event, EventListener, EventListenerRc};
use crate::{logger::SharedExternalPrinterLogger, uncaught_job_error};
pub(crate) struct Executor {
promise_jobs: RefCell<VecDeque<PromiseJob>>,
async_jobs: RefCell<VecDeque<NativeAsyncJob>>,
generic_jobs: RefCell<VecDeque<GenericJob>>,
finalization_registry_jobs: RefCell<VecDeque<NativeAsyncJob>>,
wake_event: Event<()>,
idle_event: Event<()>,
idle_counter: Cell<u8>,
stop_event: Event<()>,
printer: SharedExternalPrinterLogger,
}
impl Executor {
pub(crate) fn new(printer: SharedExternalPrinterLogger) -> Self {
Self {
promise_jobs: RefCell::default(),
async_jobs: RefCell::default(),
generic_jobs: RefCell::default(),
finalization_registry_jobs: RefCell::default(),
wake_event: Event::new(),
idle_event: Event::new(),
idle_counter: Cell::new(0),
stop_event: Event::new(),
printer,
}
}
pub(crate) fn stop(&self) {
self.promise_jobs.borrow_mut().clear();
self.async_jobs.borrow_mut().clear();
self.generic_jobs.borrow_mut().clear();
self.finalization_registry_jobs.borrow_mut().clear();
self.stop_event.notify(u8::MAX);
}
/// Waits until there are any new jobs to be handled.
///
/// This will also restore the provided `listener` such that it can keep
/// listening for more events.
async fn wait_for_events<'a>(&'a self, mut listener: Pin<&mut EventListener<'a, ()>>) {
self.idle_event.notify(u8::MAX);
self.idle_counter.update(|n| n + 1);
(&mut listener).await;
// Restore the listener after usage.
listener.as_mut().listen();
self.idle_counter.update(|n| n - 1);
}
/// Continually run all pending promise jobs, yielding to the async
/// executor after every successful run.
async fn run_promise_jobs(&self, context: &RefCell<&mut Context>) {
let mut listener = pin!(EventListener::new(&self.wake_event));
loop {
let jobs = mem::take(&mut *self.promise_jobs.borrow_mut());
if jobs.is_empty() {
self.wait_for_events(listener.as_mut()).await;
continue;
}
{
let context = &mut context.borrow_mut();
for job in jobs {
if let Err(e) = job.call(context) {
self.printer.print(uncaught_job_error(&e));
}
}
context.clear_kept_objects();
}
smol::future::yield_now().await;
}
}
/// Continually run a single pending generic job, yielding to the async
/// executor after every successful run.
async fn run_generic_jobs(&self, context: &RefCell<&mut Context>) {
let mut listener = pin!(EventListener::new(&self.wake_event));
loop {
let job = self.generic_jobs.borrow_mut().pop_front();
let Some(job) = job else {
self.wait_for_events(listener.as_mut()).await;
continue;
};
{
let context = &mut context.borrow_mut();
if let Err(err) = job.call(context) {
self.printer.print(uncaught_job_error(&err));
}
context.clear_kept_objects();
}
smol::future::yield_now().await;
}
}
/// Continually run all pending async jobs.
//
/// This does not need to yield to the async executor after every run because
/// it assumes that every async job will eventually yield to the executor.
async fn run_async_jobs(&self, context: &RefCell<&mut Context>) {
let mut group = FutureGroup::new();
let mut listener = pin!(EventListener::new(&self.wake_event));
loop {
if self.async_jobs.borrow().is_empty() && group.is_empty() {
self.wait_for_events(listener.as_mut()).await;
}
for job in mem::take(&mut *self.async_jobs.borrow_mut()) {
group.insert(job.call(context));
}
let wake = async {
(&mut listener).await;
// Restore the listener since it should have been consumed by
// the await.
listener.as_mut().listen();
};
let next_job = async {
if let Some(Err(err)) = group.next().await {
self.printer.print(uncaught_job_error(&err));
}
};
wake.or(next_job).await;
context.borrow_mut().clear_kept_objects();
}
}
/// Continually run all finalization registry async jobs.
///
/// This does not need to yield to the async executor after every run because
/// it assumes that every async job will not block the execution thread.
async fn run_finalization_registry_jobs(&self, context: &RefCell<&mut Context>) {
let mut group = FutureGroup::new();
let mut listener = pin!(EventListener::new(&self.wake_event));
loop {
if self.finalization_registry_jobs.borrow().is_empty() && group.is_empty() {
(&mut listener).await;
// Restore the listener since it should have been consumed by
// the await.
listener.as_mut().listen();
}
for job in mem::take(&mut *self.finalization_registry_jobs.borrow_mut()) {
group.insert(job.call(context));
}
let wake = async {
(&mut listener).await;
// Restore the listener since it should have been consumed by
// the await.
listener.as_mut().listen();
};
let next_job = async {
if let Some(Err(err)) = group.next().await {
self.printer.print(uncaught_job_error(&err));
}
};
wake.or(next_job).await;
}
}
}
impl JobExecutor for Executor {
fn enqueue_job(self: Rc<Self>, job: Job, _context: &mut Context) {
match job {
Job::PromiseJob(job) => self.promise_jobs.borrow_mut().push_back(job),
Job::AsyncJob(job) => self.async_jobs.borrow_mut().push_back(job),
Job::TimeoutJob(job) => {
let event = Rc::new(Event::new());
let listener = EventListenerRc::new(Rc::clone(&event));
job.cancellation_token().push_callback(move |_| {
event.notify(u8::MAX);
});
self.async_jobs
.borrow_mut()
.push_back(NativeAsyncJob::new(async move |context| {
let timer = async {
smol::Timer::after(job.timeout().into()).await;
job.call(&mut context.borrow_mut())
};
let cancel = async {
listener.await;
Ok(JsValue::undefined())
};
timer.or(cancel).await
}));
}
Job::IntervalJob(job) => {
let event = Rc::new(Event::new());
let listener = EventListenerRc::new(Rc::clone(&event));
let printer = self.printer.clone();
job.cancellation_token().push_callback(move |_| {
event.notify(u8::MAX);
});
self.async_jobs
.borrow_mut()
.push_back(NativeAsyncJob::new(async move |context| {
let timer = async {
let mut interval = smol::Timer::interval(job.interval().into());
loop {
interval.next().await;
if let Err(err) = job.call(&mut context.borrow_mut()) {
printer.print(uncaught_job_error(&err));
}
}
};
let cancel = async {
listener.await;
Ok(JsValue::undefined())
};
timer.or(cancel).await
}));
}
Job::GenericJob(job) => self.generic_jobs.borrow_mut().push_back(job),
Job::FinalizationRegistryCleanupJob(job) => {
self.finalization_registry_jobs.borrow_mut().push_back(job);
}
job => self.printer.print(format!("unsupported job type {job:?}")),
}
self.wake_event.notify(u8::MAX);
}
fn run_jobs(self: Rc<Self>, context: &mut Context) -> JsResult<()> {
smol::block_on(self.run_jobs_async(&RefCell::new(context)))
}
async fn run_jobs_async(self: Rc<Self>, context: &RefCell<&mut Context>) -> JsResult<()> {
let executor = smol::LocalExecutor::new();
let async_task = executor.spawn(self.run_async_jobs(context));
let generic_task = executor.spawn(self.run_generic_jobs(context));
let promise_task = executor.spawn(self.run_promise_jobs(context));
let foreground = async {
async_task.await;
generic_task.await;
promise_task.await;
};
let background = async {
let mut listener = pin!(EventListener::new(&self.idle_event));
let mut run_fr_jobs = pin!(self.run_finalization_registry_jobs(context));
loop {
let idle_tasks = self.idle_counter.get();
// We need to have all 3 tasks idle to exit from the event loop.
if idle_tasks >= 3 {
return;
}
// Since there are still pending tasks awaiting for IO
// (probably the async jobs), run any pending finalization registry
// jobs now that the thread is free to do things.
//
// We still need to handle idle event notifications though, because
// only awaiting the finalization registry jobs would never
// exit.
async {
(&mut listener).await;
// Restore the listener since it should have been consumed by
// the await.
listener.as_mut().listen();
}
.or(&mut run_fr_jobs)
.await;
}
};
// Stop signal has priority over everything else.
EventListener::new(&self.stop_event)
.or(executor.run(foreground))
.or(background)
.await;
Ok(())
}
}