worker.rs 14.1 KB
Newer Older
R
Ryan Dahl 已提交
1
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
A
andy finch 已提交
2
use crate::compiler::compile_async;
K
Kitson Kelly 已提交
3
use crate::compiler::ModuleMetaData;
A
Andy Hayden 已提交
4
use crate::errors::DenoError;
5
use crate::errors::RustOrJsError;
6
use crate::js_errors;
7
use crate::js_errors::JSErrorColor;
A
Andy Hayden 已提交
8
use crate::msg;
9
use crate::state::ThreadSafeState;
10
use crate::tokio_util;
11
use deno;
12
use deno::Config;
13
use deno::JSError;
14
use deno::Loader;
R
Ryan Dahl 已提交
15
use deno::StartupData;
A
andy finch 已提交
16
use futures::future::Either;
17
use futures::Async;
R
Ryan Dahl 已提交
18
use futures::Future;
19
use std::sync::atomic::Ordering;
20
use url::Url;
B
Bartek Iwańczuk 已提交
21

22
/// Wraps deno::Isolate to provide source maps, ops for the CLI, and
23
/// high-level module loading
24
pub struct Worker {
25
  inner: deno::Isolate,
26 27
  pub modules: deno::Modules,
  pub state: ThreadSafeState,
28 29
}

30 31 32 33
impl Worker {
  pub fn new(
    _name: String,
    startup_data: StartupData,
34
    state: ThreadSafeState,
35
  ) -> Worker {
36
    let state_ = state.clone();
37 38 39 40
    let mut config = Config::default();
    config.dispatch(move |control_buf, zero_copy_buf| {
      state_.dispatch(control_buf, zero_copy_buf)
    });
41
    Self {
42
      inner: deno::Isolate::new(startup_data, config),
43
      modules: deno::Modules::new(),
A
Andy Hayden 已提交
44
      state,
45 46 47
    }
  }

48
  /// Same as execute2() but the filename defaults to "<anonymous>".
49
  pub fn execute(&mut self, js_source: &str) -> Result<(), JSError> {
50 51 52 53 54 55
    self.execute2("<anonymous>", js_source)
  }

  /// Executes the provided JavaScript source code. The js_filename argument is
  /// provided only for debugging purposes.
  pub fn execute2(
56
    &mut self,
57 58
    js_filename: &str,
    js_source: &str,
59
  ) -> Result<(), JSError> {
60
    self.inner.execute(js_filename, js_source)
61 62
  }

63 64 65 66 67 68 69 70 71
  /// Consumes worker. Executes the provided JavaScript module.
  pub fn execute_mod_async(
    self,
    js_url: &Url,
    is_prefetch: bool,
  ) -> impl Future<Item = Self, Error = (RustOrJsError, Self)> {
    let recursive_load = deno::RecursiveLoad::new(js_url.as_str(), self);
    recursive_load.and_then(
      move |(id, mut self_)| -> Result<Self, (deno::JSErrorOr<DenoError>, Self)> {
R
Ryan Dahl 已提交
72
        self_.state.progress.done();
73 74 75 76 77 78 79 80 81
        if is_prefetch {
          Ok(self_)
        } else {
          let result = self_.inner.mod_evaluate(id);
          if let Err(err) = result {
            Err((deno::JSErrorOr::JSError(err), self_))
          } else {
            Ok(self_)
          }
82
        }
83 84 85
      },
    )
    .map_err(|(err, self_)| {
R
Ryan Dahl 已提交
86
      self_.state.progress.done();
87 88 89 90 91 92 93
      // Convert to RustOrJsError AND apply_source_map.
      let err = match err {
        deno::JSErrorOr::JSError(err) => RustOrJsError::Js(self_.apply_source_map(err)),
        deno::JSErrorOr::Other(err) => RustOrJsError::Rust(err),
      };
      (err, self_)
    })
94 95
  }

96
  /// Consumes worker. Executes the provided JavaScript module.
97
  pub fn execute_mod(
98 99
    self,
    js_url: &Url,
100
    is_prefetch: bool,
101 102
  ) -> Result<Self, (RustOrJsError, Self)> {
    tokio_util::block_on(self.execute_mod_async(js_url, is_prefetch))
103 104
  }

105 106 107 108 109
  /// Applies source map to the error.
  fn apply_source_map(&self, err: JSError) -> JSError {
    js_errors::apply_source_map(&err, &self.state.dir)
  }
}
110

111 112 113 114 115 116 117 118 119 120 121 122 123
// https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
// TODO(ry) Add tests.
// TODO(ry) Move this to core?
pub fn resolve_module_spec(
  specifier: &str,
  base: &str,
) -> Result<String, url::ParseError> {
  // 1. Apply the URL parser to specifier. If the result is not failure, return
  //    the result.
  // let specifier = parse_local_or_remote(specifier)?.to_string();
  if let Ok(specifier_url) = Url::parse(specifier) {
    return Ok(specifier_url.to_string());
  }
124

125 126 127 128
  // 2. If specifier does not start with the character U+002F SOLIDUS (/), the
  //    two-character sequence U+002E FULL STOP, U+002F SOLIDUS (./), or the
  //    three-character sequence U+002E FULL STOP, U+002E FULL STOP, U+002F
  //    SOLIDUS (../), return failure.
B
Bert Belder 已提交
129
  if !specifier.starts_with('/')
130 131 132 133 134 135
    && !specifier.starts_with("./")
    && !specifier.starts_with("../")
  {
    // TODO(ry) This is (probably) not the correct error to return here.
    return Err(url::ParseError::RelativeUrlWithCannotBeABaseBase);
  }
136

137 138 139 140 141 142
  // 3. Return the result of applying the URL parser to specifier with base URL
  //    as the base URL.
  let base_url = Url::parse(base)?;
  let u = base_url.join(&specifier)?;
  Ok(u.to_string())
}
143

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
/// Takes a string representing a path or URL to a module, but of the type
/// passed through the command-line interface for the main module. This is
/// slightly different than specifiers used in import statements: "foo.js" for
/// example is allowed here, whereas in import statements a leading "./" is
/// required ("./foo.js"). This function is aware of the current working
/// directory and returns an absolute URL.
pub fn root_specifier_to_url(
  root_specifier: &str,
) -> Result<Url, url::ParseError> {
  let maybe_url = Url::parse(root_specifier);
  if let Ok(url) = maybe_url {
    Ok(url)
  } else {
    let cwd = std::env::current_dir().unwrap();
    let base = Url::from_directory_path(cwd).unwrap();
    base.join(root_specifier)
R
Ryan Dahl 已提交
160
  }
161
}
R
Ryan Dahl 已提交
162

163 164
impl Loader for Worker {
  type Error = DenoError;
R
Ryan Dahl 已提交
165

166
  fn resolve(specifier: &str, referrer: &str) -> Result<String, Self::Error> {
B
Bert Belder 已提交
167
    resolve_module_spec(specifier, referrer).map_err(DenoError::from)
168 169
  }

170
  /// Given an absolute url, load its source code.
171 172 173 174
  fn load(
    &mut self,
    url: &str,
  ) -> Box<deno::SourceCodeInfoFuture<Self::Error>> {
175 176 177 178 179 180 181 182 183 184
    self
      .state
      .metrics
      .resolve_count
      .fetch_add(1, Ordering::SeqCst);
    Box::new(
      fetch_module_meta_data_and_maybe_compile_async(&self.state, url, ".")
        .map_err(|err| {
          eprintln!("{}", err);
          err
185 186 187 188 189 190
        }).map(|module_meta_data| deno::SourceCodeInfo {
          // Real module name, might be different from initial URL
          // due to redirections.
          code: module_meta_data.js_source(),
          module_name: module_meta_data.module_name,
        }),
191
    )
R
Ryan Dahl 已提交
192 193
  }

194 195
  fn isolate_and_modules<'a: 'b + 'c, 'b, 'c>(
    &'a mut self,
196
  ) -> (&'b mut deno::Isolate, &'c mut deno::Modules) {
197
    (&mut self.inner, &mut self.modules)
R
Ryan Dahl 已提交
198
  }
199 200
}

201
impl Future for Worker {
202 203 204 205 206
  type Item = ();
  type Error = JSError;

  fn poll(&mut self) -> Result<Async<()>, Self::Error> {
    self.inner.poll().map_err(|err| self.apply_source_map(err))
207 208
  }
}
209

210
fn fetch_module_meta_data_and_maybe_compile_async(
211
  state: &ThreadSafeState,
212 213 214
  specifier: &str,
  referrer: &str,
) -> impl Future<Item = ModuleMetaData, Error = DenoError> {
215
  let use_cache = !state.flags.reload;
216
  let no_fetch = state.flags.no_fetch;
217 218 219 220 221
  let state_ = state.clone();
  let specifier = specifier.to_string();
  let referrer = referrer.to_string();
  state
    .dir
222
    .fetch_module_meta_data_async(&specifier, &referrer, use_cache, no_fetch)
A
andy finch 已提交
223
    .and_then(move |out| {
224
      if out.media_type == msg::MediaType::TypeScript
225
        && !out.has_output_code_and_source_map()
226 227
      {
        debug!(">>>>> compile_sync START");
A
andy finch 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241
        Either::A(
          compile_async(state_.clone(), &specifier, &referrer, &out)
            .map_err(|e| {
              debug!("compiler error exiting!");
              eprintln!("{}", JSErrorColor(&e).to_string());
              std::process::exit(1);
            }).and_then(move |out| {
              debug!(">>>>> compile_sync END");
              state_.dir.code_cache(&out)?;
              Ok(out)
            }),
        )
      } else {
        Either::B(futures::future::ok(out))
242 243 244
      }
    })
}
245

246
pub fn fetch_module_meta_data_and_maybe_compile(
247
  state: &ThreadSafeState,
R
Ryan Dahl 已提交
248 249
  specifier: &str,
  referrer: &str,
K
Kitson Kelly 已提交
250
) -> Result<ModuleMetaData, DenoError> {
251 252 253
  tokio_util::block_on(fetch_module_meta_data_and_maybe_compile_async(
    state, specifier, referrer,
  ))
R
Ryan Dahl 已提交
254 255
}

R
Ryan Dahl 已提交
256 257 258
#[cfg(test)]
mod tests {
  use super::*;
259
  use crate::flags;
A
andy finch 已提交
260
  use crate::ops::op_selector_std;
R
Ryan Dahl 已提交
261
  use crate::progress::Progress;
262 263
  use crate::resources;
  use crate::startup_data;
264
  use crate::state::ThreadSafeState;
265 266
  use crate::tokio_util;
  use deno::js_check;
267 268
  use futures::future::lazy;
  use std::sync::atomic::Ordering;
269 270

  #[test]
271
  fn execute_mod_esm_imports_a() {
272 273 274
    let filename = std::env::current_dir()
      .unwrap()
      .join("tests/esm_imports_a.js");
275
    let js_url = Url::from_file_path(filename).unwrap();
276

277
    let argv = vec![String::from("./deno"), js_url.to_string()];
R
Ryan Dahl 已提交
278 279 280 281 282 283
    let state = ThreadSafeState::new(
      flags::DenoFlags::default(),
      argv,
      op_selector_std,
      Progress::new(),
    );
284 285
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
286 287 288 289 290 291 292 293 294
      let worker = Worker::new("TEST".to_string(), StartupData::None, state);
      let result = worker.execute_mod(&js_url, false);
      let worker = match result {
        Err((err, worker)) => {
          eprintln!("execute_mod err {:?}", err);
          worker
        }
        Ok(worker) => worker,
      };
295
      tokio_util::panic_on_error(worker)
296 297 298
    }));

    let metrics = &state_.metrics;
299
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
300 301 302 303 304
  }

  #[test]
  fn execute_mod_circular() {
    let filename = std::env::current_dir().unwrap().join("tests/circular1.js");
305
    let js_url = Url::from_file_path(filename).unwrap();
306

307
    let argv = vec![String::from("./deno"), js_url.to_string()];
R
Ryan Dahl 已提交
308 309 310 311 312 313
    let state = ThreadSafeState::new(
      flags::DenoFlags::default(),
      argv,
      op_selector_std,
      Progress::new(),
    );
314 315
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
316 317 318 319 320 321 322 323 324
      let worker = Worker::new("TEST".to_string(), StartupData::None, state);
      let result = worker.execute_mod(&js_url, false);
      let worker = match result {
        Err((err, worker)) => {
          eprintln!("execute_mod err {:?}", err);
          worker
        }
        Ok(worker) => worker,
      };
325
      tokio_util::panic_on_error(worker)
326 327 328
    }));

    let metrics = &state_.metrics;
329
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
330
  }
331

R
Ryan Dahl 已提交
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
  #[test]
  fn execute_006_url_imports() {
    let filename = std::env::current_dir()
      .unwrap()
      .join("tests/006_url_imports.ts");
    let js_url = Url::from_file_path(filename).unwrap();
    let argv = vec![String::from("deno"), js_url.to_string()];
    let mut flags = flags::DenoFlags::default();
    flags.reload = true;
    let state =
      ThreadSafeState::new(flags, argv, op_selector_std, Progress::new());
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
      let mut worker = Worker::new(
        "TEST".to_string(),
        startup_data::deno_isolate_init(),
        state,
      );
      js_check(worker.execute("denoMain()"));
      let result = worker.execute_mod(&js_url, false);
      let worker = match result {
        Err((err, worker)) => {
          eprintln!("execute_mod err {:?}", err);
          worker
        }
        Ok(worker) => worker,
      };
      tokio_util::panic_on_error(worker)
    }));

    let metrics = &state_.metrics;
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 3);
  }

366
  fn create_test_worker() -> Worker {
367
    let state = ThreadSafeState::mock();
368
    let mut worker =
369
      Worker::new("TEST".to_string(), startup_data::deno_isolate_init(), state);
370 371 372 373 374 375 376 377 378 379 380 381 382
    js_check(worker.execute("denoMain()"));
    js_check(worker.execute("workerMain()"));
    worker
  }

  #[test]
  fn test_worker_messages() {
    tokio_util::init(|| {
      let mut worker = create_test_worker();
      let source = r#"
        onmessage = function(e) {
          console.log("msg from main script", e.data);
          if (e.data == "exit") {
383
            delete window.onmessage;
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
            return;
          } else {
            console.assert(e.data === "hi");
          }
          postMessage([1, 2, 3]);
          console.log("after postMessage");
        }
        "#;
      js_check(worker.execute(source));

      let resource = worker.state.resource.clone();
      let resource_ = resource.clone();

      tokio::spawn(lazy(move || {
        worker.then(move |r| -> Result<(), ()> {
          resource_.close();
          js_check(r);
          Ok(())
        })
      }));

      let msg = json!("hi").to_string().into_boxed_str().into_boxed_bytes();

      let r = resources::post_message_to_worker(resource.rid, msg).wait();
      assert!(r.is_ok());

      let maybe_msg = resources::get_message_from_worker(resource.rid)
        .wait()
        .unwrap();
      assert!(maybe_msg.is_some());
      // Check if message received is [1, 2, 3] in json
      assert_eq!(*maybe_msg.unwrap(), *b"[1,2,3]");

      let msg = json!("exit")
        .to_string()
        .into_boxed_str()
        .into_boxed_bytes();
      let r = resources::post_message_to_worker(resource.rid, msg).wait();
      assert!(r.is_ok());
    })
  }

  #[test]
  fn removed_from_resource_table_on_close() {
    tokio_util::init(|| {
      let mut worker = create_test_worker();
      js_check(
431
        worker.execute("onmessage = () => { delete window.onmessage; }"),
432 433 434 435 436
      );

      let resource = worker.state.resource.clone();
      let rid = resource.rid;

437 438
      let worker_future = worker
        .then(move |r| -> Result<(), ()> {
439 440 441 442
          resource.close();
          println!("workers.rs after resource close");
          js_check(r);
          Ok(())
443 444 445 446
        }).shared();

      let worker_future_ = worker_future.clone();
      tokio::spawn(lazy(move || worker_future_.then(|_| Ok(()))));
447 448 449 450 451 452 453 454

      assert_eq!(resources::get_type(rid), Some("worker".to_string()));

      let msg = json!("hi").to_string().into_boxed_str().into_boxed_bytes();
      let r = resources::post_message_to_worker(rid, msg).wait();
      assert!(r.is_ok());
      debug!("rid {:?}", rid);

455
      worker_future.wait().unwrap();
456 457 458
      assert_eq!(resources::get_type(rid), None);
    })
  }
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

  #[test]
  fn execute_mod_resolve_error() {
    // "foo" is not a vailid module specifier so this should return an error.
    let worker = create_test_worker();
    let js_url = root_specifier_to_url("does-not-exist").unwrap();
    let result = worker.execute_mod_async(&js_url, false).wait();
    assert!(result.is_err());
  }

  #[test]
  fn execute_mod_002_hello() {
    // This assumes cwd is project root (an assumption made throughout the
    // tests).
    let worker = create_test_worker();
    let js_url = root_specifier_to_url("./tests/002_hello.ts").unwrap();
    let result = worker.execute_mod_async(&js_url, false).wait();
    assert!(result.is_ok());
  }
478
}