forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.rs
489 lines (451 loc) · 15.6 KB
/
worker.rs
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use crate::inspector_server::InspectorServer;
use crate::js;
use crate::ops;
use crate::ops::io::Stdio;
use crate::permissions::Permissions;
use crate::BootstrapOptions;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_core::error::AnyError;
use deno_core::error::JsError;
use deno_core::futures::Future;
use deno_core::located_script_name;
use deno_core::CompiledWasmModuleStore;
use deno_core::Extension;
use deno_core::GetErrorClassFn;
use deno_core::JsRuntime;
use deno_core::LocalInspectorSession;
use deno_core::ModuleId;
use deno_core::ModuleLoader;
use deno_core::ModuleSpecifier;
use deno_core::RuntimeOptions;
use deno_core::SharedArrayBufferStore;
use deno_core::SourceMapGetter;
use deno_tls::rustls::RootCertStore;
use deno_web::BlobStore;
use log::debug;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
pub type FormatJsErrorFn = dyn Fn(&JsError) -> String + Sync + Send;
#[derive(Clone, Default)]
pub struct ExitCode(Arc<AtomicI32>);
impl ExitCode {
pub fn get(&self) -> i32 {
self.0.load(Relaxed)
}
pub fn set(&mut self, code: i32) {
self.0.store(code, Relaxed);
}
}
/// This worker is created and used by almost all
/// subcommands in Deno executable.
///
/// It provides ops available in the `Deno` namespace.
///
/// All `WebWorker`s created during program execution
/// are descendants of this worker.
pub struct MainWorker {
pub js_runtime: JsRuntime,
should_break_on_first_statement: bool,
exit_code: ExitCode,
}
pub struct WorkerOptions {
pub bootstrap: BootstrapOptions,
pub extensions: Vec<Extension>,
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
pub root_cert_store: Option<RootCertStore>,
pub seed: Option<u64>,
pub module_loader: Rc<dyn ModuleLoader>,
// Callbacks invoked when creating new instance of WebWorker
pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>,
pub web_worker_preload_module_cb: Arc<ops::worker_host::PreloadModuleCb>,
pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>,
pub source_map_getter: Option<Box<dyn SourceMapGetter>>,
pub maybe_inspector_server: Option<Arc<InspectorServer>>,
pub should_break_on_first_statement: bool,
pub get_error_class_fn: Option<GetErrorClassFn>,
pub origin_storage_dir: Option<std::path::PathBuf>,
pub blob_store: BlobStore,
pub broadcast_channel: InMemoryBroadcastChannel,
pub shared_array_buffer_store: Option<SharedArrayBufferStore>,
pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>,
pub stdio: Stdio,
}
impl MainWorker {
pub fn bootstrap_from_options(
main_module: ModuleSpecifier,
permissions: Permissions,
options: WorkerOptions,
) -> Self {
let bootstrap_options = options.bootstrap.clone();
let mut worker = Self::from_options(main_module, permissions, options);
worker.bootstrap(&bootstrap_options);
worker
}
pub fn from_options(
main_module: ModuleSpecifier,
permissions: Permissions,
mut options: WorkerOptions,
) -> Self {
// Permissions: many ops depend on this
let unstable = options.bootstrap.unstable;
let enable_testing_features = options.bootstrap.enable_testing_features;
let perm_ext = Extension::builder()
.state(move |state| {
state.put::<Permissions>(permissions.clone());
state.put(ops::UnstableChecker { unstable });
state.put(ops::TestingFeaturesEnabled(enable_testing_features));
Ok(())
})
.build();
let exit_code = ExitCode(Arc::new(AtomicI32::new(0)));
// Internal modules
let mut extensions: Vec<Extension> = vec![
// Web APIs
deno_webidl::init(),
deno_console::init(),
deno_url::init(),
deno_web::init::<Permissions>(
options.blob_store.clone(),
options.bootstrap.location.clone(),
),
deno_fetch::init::<Permissions>(deno_fetch::Options {
user_agent: options.bootstrap.user_agent.clone(),
root_cert_store: options.root_cert_store.clone(),
unsafely_ignore_certificate_errors: options
.unsafely_ignore_certificate_errors
.clone(),
file_fetch_handler: Rc::new(deno_fetch::FsFetchHandler),
..Default::default()
}),
deno_websocket::init::<Permissions>(
options.bootstrap.user_agent.clone(),
options.root_cert_store.clone(),
options.unsafely_ignore_certificate_errors.clone(),
),
deno_webstorage::init(options.origin_storage_dir.clone()),
deno_broadcast_channel::init(options.broadcast_channel.clone(), unstable),
deno_crypto::init(options.seed),
deno_webgpu::init(unstable),
// ffi
deno_ffi::init::<Permissions>(unstable),
// Runtime ops
ops::runtime::init(main_module.clone()),
ops::worker_host::init(
options.create_web_worker_cb.clone(),
options.web_worker_preload_module_cb.clone(),
options.format_js_error_fn.clone(),
),
ops::spawn::init(),
ops::fs_events::init(),
ops::fs::init(),
ops::io::init(),
ops::io::init_stdio(options.stdio),
deno_tls::init(),
deno_net::init::<Permissions>(
options.root_cert_store.clone(),
unstable,
options.unsafely_ignore_certificate_errors.clone(),
),
// deno_node::init() // todo(dsherret): re-enable,
ops::os::init(exit_code.clone()),
ops::permissions::init(),
ops::process::init(),
ops::signal::init(),
ops::tty::init(),
deno_http::init(),
ops::http::init(),
// Permissions ext (worker specific state)
perm_ext,
];
extensions.extend(std::mem::take(&mut options.extensions));
let mut js_runtime = JsRuntime::new(RuntimeOptions {
module_loader: Some(options.module_loader.clone()),
startup_snapshot: Some(js::deno_isolate_init()),
source_map_getter: options.source_map_getter,
get_error_class_fn: options.get_error_class_fn,
shared_array_buffer_store: options.shared_array_buffer_store.clone(),
compiled_wasm_module_store: options.compiled_wasm_module_store.clone(),
extensions,
..Default::default()
});
if let Some(server) = options.maybe_inspector_server.clone() {
server.register_inspector(
main_module.to_string(),
&mut js_runtime,
options.should_break_on_first_statement,
);
}
Self {
js_runtime,
should_break_on_first_statement: options.should_break_on_first_statement,
exit_code,
}
}
pub fn bootstrap(&mut self, options: &BootstrapOptions) {
let script = format!("bootstrap.mainRuntime({})", options.as_json());
self
.execute_script(&located_script_name!(), &script)
.expect("Failed to execute bootstrap script");
}
/// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script)
pub fn execute_script(
&mut self,
script_name: &str,
source_code: &str,
) -> Result<(), AnyError> {
self.js_runtime.execute_script(script_name, source_code)?;
Ok(())
}
/// Loads and instantiates specified JavaScript module as "main" module.
pub async fn preload_main_module(
&mut self,
module_specifier: &ModuleSpecifier,
) -> Result<ModuleId, AnyError> {
self
.js_runtime
.load_main_module(module_specifier, None)
.await
}
/// Loads and instantiates specified JavaScript module as "side" module.
pub async fn preload_side_module(
&mut self,
module_specifier: &ModuleSpecifier,
) -> Result<ModuleId, AnyError> {
self
.js_runtime
.load_side_module(module_specifier, None)
.await
}
/// Executes specified JavaScript module.
pub async fn evaluate_module(
&mut self,
id: ModuleId,
) -> Result<(), AnyError> {
self.wait_for_inspector_session();
let mut receiver = self.js_runtime.mod_evaluate(id);
tokio::select! {
// Not using biased mode leads to non-determinism for relatively simple
// programs.
biased;
maybe_result = &mut receiver => {
debug!("received module evaluate {:#?}", maybe_result);
maybe_result.expect("Module evaluation result not provided.")
}
event_loop_result = self.run_event_loop(false) => {
event_loop_result?;
let maybe_result = receiver.await;
maybe_result.expect("Module evaluation result not provided.")
}
}
}
/// Loads, instantiates and executes specified JavaScript module.
pub async fn execute_side_module(
&mut self,
module_specifier: &ModuleSpecifier,
) -> Result<(), AnyError> {
let id = self.preload_side_module(module_specifier).await?;
self.evaluate_module(id).await
}
/// Loads, instantiates and executes specified JavaScript module.
///
/// This module will have "import.meta.main" equal to true.
pub async fn execute_main_module(
&mut self,
module_specifier: &ModuleSpecifier,
) -> Result<(), AnyError> {
let id = self.preload_main_module(module_specifier).await?;
self.evaluate_module(id).await
}
fn wait_for_inspector_session(&mut self) {
if self.should_break_on_first_statement {
self
.js_runtime
.inspector()
.wait_for_session_and_break_on_next_statement()
}
}
/// Create new inspector session. This function panics if Worker
/// was not configured to create inspector.
pub async fn create_inspector_session(&mut self) -> LocalInspectorSession {
let inspector = self.js_runtime.inspector();
inspector.create_local_session()
}
pub fn poll_event_loop(
&mut self,
cx: &mut Context,
wait_for_inspector: bool,
) -> Poll<Result<(), AnyError>> {
self.js_runtime.poll_event_loop(cx, wait_for_inspector)
}
pub async fn run_event_loop(
&mut self,
wait_for_inspector: bool,
) -> Result<(), AnyError> {
self.js_runtime.run_event_loop(wait_for_inspector).await
}
/// A utility function that runs provided future concurrently with the event loop.
///
/// Useful when using a local inspector session.
pub async fn with_event_loop<'a, T>(
&mut self,
mut fut: Pin<Box<dyn Future<Output = T> + 'a>>,
) -> T {
loop {
tokio::select! {
biased;
result = &mut fut => {
return result;
}
_ = self.run_event_loop(false) => {}
};
}
}
/// Return exit code set by the executed code (either in main worker
/// or one of child web workers).
pub fn get_exit_code(&self) -> i32 {
self.exit_code.get()
}
/// Dispatches "load" event to the JavaScript runtime.
///
/// Does not poll event loop, and thus not await any of the "load" event handlers.
pub fn dispatch_load_event(
&mut self,
script_name: &str,
) -> Result<(), AnyError> {
self.execute_script(
script_name,
// NOTE(@bartlomieju): not using `globalThis` here, because user might delete
// it. Instead we're using global `dispatchEvent` function which will
// used a saved reference to global scope.
"dispatchEvent(new Event('load'))",
)
}
/// Dispatches "unload" event to the JavaScript runtime.
///
/// Does not poll event loop, and thus not await any of the "unload" event handlers.
pub fn dispatch_unload_event(
&mut self,
script_name: &str,
) -> Result<(), AnyError> {
self.execute_script(
script_name,
// NOTE(@bartlomieju): not using `globalThis` here, because user might delete
// it. Instead we're using global `dispatchEvent` function which will
// used a saved reference to global scope.
"dispatchEvent(new Event('unload'))",
)
}
/// Dispatches "beforeunload" event to the JavaScript runtime. Returns a boolean
/// indicating if the event was prevented and thus event loop should continue
/// running.
pub fn dispatch_beforeunload_event(
&mut self,
script_name: &str,
) -> Result<bool, AnyError> {
let value = self.js_runtime.execute_script(
script_name,
// NOTE(@bartlomieju): not using `globalThis` here, because user might delete
// it. Instead we're using global `dispatchEvent` function which will
// used a saved reference to global scope.
"dispatchEvent(new Event('beforeunload', { cancelable: true }));",
)?;
let local_value = value.open(&mut self.js_runtime.handle_scope());
Ok(local_value.is_false())
}
}
#[cfg(test)]
mod tests {
use super::*;
use deno_core::resolve_url_or_path;
fn create_test_worker() -> MainWorker {
let main_module = resolve_url_or_path("./hello.js").unwrap();
let permissions = Permissions::default();
let options = WorkerOptions {
bootstrap: BootstrapOptions {
args: vec![],
cpu_count: 1,
debug_flag: false,
enable_testing_features: false,
location: None,
no_color: true,
is_tty: false,
runtime_version: "x".to_string(),
ts_version: "x".to_string(),
unstable: false,
user_agent: "x".to_string(),
},
extensions: vec![],
unsafely_ignore_certificate_errors: None,
root_cert_store: None,
seed: None,
format_js_error_fn: None,
source_map_getter: None,
web_worker_preload_module_cb: Arc::new(|_| unreachable!()),
create_web_worker_cb: Arc::new(|_| unreachable!()),
maybe_inspector_server: None,
should_break_on_first_statement: false,
module_loader: Rc::new(deno_core::FsModuleLoader),
get_error_class_fn: None,
origin_storage_dir: None,
blob_store: BlobStore::default(),
broadcast_channel: InMemoryBroadcastChannel::default(),
shared_array_buffer_store: None,
compiled_wasm_module_store: None,
stdio: Default::default(),
};
MainWorker::bootstrap_from_options(main_module, permissions, options)
}
#[tokio::test]
async fn execute_mod_esm_imports_a() {
let p = test_util::testdata_path().join("esm_imports_a.js");
let module_specifier = resolve_url_or_path(&p.to_string_lossy()).unwrap();
let mut worker = create_test_worker();
let result = worker.execute_main_module(&module_specifier).await;
if let Err(err) = result {
eprintln!("execute_mod err {:?}", err);
}
if let Err(e) = worker.run_event_loop(false).await {
panic!("Future got unexpected error: {:?}", e);
}
}
#[tokio::test]
async fn execute_mod_circular() {
let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.join("tests/circular1.js");
let module_specifier = resolve_url_or_path(&p.to_string_lossy()).unwrap();
let mut worker = create_test_worker();
let result = worker.execute_main_module(&module_specifier).await;
if let Err(err) = result {
eprintln!("execute_mod err {:?}", err);
}
if let Err(e) = worker.run_event_loop(false).await {
panic!("Future got unexpected error: {:?}", e);
}
}
#[tokio::test]
async fn execute_mod_resolve_error() {
// "foo" is not a valid module specifier so this should return an error.
let mut worker = create_test_worker();
let module_specifier = resolve_url_or_path("does-not-exist").unwrap();
let result = worker.execute_main_module(&module_specifier).await;
assert!(result.is_err());
}
#[tokio::test]
async fn execute_mod_002_hello() {
// This assumes cwd is project root (an assumption made throughout the
// tests).
let mut worker = create_test_worker();
let p = test_util::testdata_path().join("001_hello.js");
let module_specifier = resolve_url_or_path(&p.to_string_lossy()).unwrap();
let result = worker.execute_main_module(&module_specifier).await;
assert!(result.is_ok());
}
}