worker.rs 12.8 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 12
use deno;
use deno::JSError;
13
use deno::Loader;
R
Ryan Dahl 已提交
14
use deno::StartupData;
A
andy finch 已提交
15
use futures::future::Either;
16
use futures::Async;
R
Ryan Dahl 已提交
17
use futures::Future;
18
use std::sync::atomic::Ordering;
19
use url::Url;
B
Bartek Iwańczuk 已提交
20

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

29 30 31 32
impl Worker {
  pub fn new(
    _name: String,
    startup_data: StartupData,
33
    state: ThreadSafeState,
34
  ) -> Worker {
35
    let state_ = state.clone();
36
    Self {
37
      inner: deno::Isolate::new(startup_data, state_),
38
      modules: deno::Modules::new(),
A
Andy Hayden 已提交
39
      state,
40 41 42
    }
  }

43
  /// Same as execute2() but the filename defaults to "<anonymous>".
44
  pub fn execute(&mut self, js_source: &str) -> Result<(), JSError> {
45 46 47 48 49 50
    self.execute2("<anonymous>", js_source)
  }

  /// Executes the provided JavaScript source code. The js_filename argument is
  /// provided only for debugging purposes.
  pub fn execute2(
51
    &mut self,
52 53
    js_filename: &str,
    js_source: &str,
54
  ) -> Result<(), JSError> {
55
    self.inner.execute(js_filename, js_source)
56 57
  }

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  /// 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)> {
        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_)
          }
76
        }
77 78 79 80 81 82 83 84 85 86
      },
    )
    .map_err(|(err, self_)| {
      // 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_)
    })
87 88
  }

89
  /// Consumes worker. Executes the provided JavaScript module.
90
  pub fn execute_mod(
91 92
    self,
    js_url: &Url,
93
    is_prefetch: bool,
94 95
  ) -> Result<Self, (RustOrJsError, Self)> {
    tokio_util::block_on(self.execute_mod_async(js_url, is_prefetch))
96 97
  }

98 99 100 101 102
  /// Applies source map to the error.
  fn apply_source_map(&self, err: JSError) -> JSError {
    js_errors::apply_source_map(&err, &self.state.dir)
  }
}
103

104 105 106 107 108 109 110 111 112 113 114 115 116
// 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());
  }
117

118 119 120 121
  // 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 已提交
122
  if !specifier.starts_with('/')
123 124 125 126 127 128
    && !specifier.starts_with("./")
    && !specifier.starts_with("../")
  {
    // TODO(ry) This is (probably) not the correct error to return here.
    return Err(url::ParseError::RelativeUrlWithCannotBeABaseBase);
  }
129

130 131 132 133 134 135
  // 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())
}
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
/// 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 已提交
153
  }
154
}
R
Ryan Dahl 已提交
155

156 157 158
impl Loader for Worker {
  type Dispatch = ThreadSafeState;
  type Error = DenoError;
R
Ryan Dahl 已提交
159

160
  fn resolve(specifier: &str, referrer: &str) -> Result<String, Self::Error> {
B
Bert Belder 已提交
161
    resolve_module_spec(specifier, referrer).map_err(DenoError::from)
162 163
  }

164
  /// Given an absolute url, load its source code.
165 166 167 168
  fn load(
    &mut self,
    url: &str,
  ) -> Box<deno::SourceCodeInfoFuture<Self::Error>> {
169 170 171 172 173 174 175 176 177 178
    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
179 180 181 182 183 184
        }).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,
        }),
185
    )
R
Ryan Dahl 已提交
186 187
  }

188 189 190 191
  fn isolate_and_modules<'a: 'b + 'c, 'b, 'c>(
    &'a mut self,
  ) -> (&'b mut deno::Isolate<Self::Dispatch>, &'c mut deno::Modules) {
    (&mut self.inner, &mut self.modules)
R
Ryan Dahl 已提交
192
  }
193 194
}

195
impl Future for Worker {
196 197 198 199 200
  type Item = ();
  type Error = JSError;

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

204
fn fetch_module_meta_data_and_maybe_compile_async(
205
  state: &ThreadSafeState,
206 207 208
  specifier: &str,
  referrer: &str,
) -> impl Future<Item = ModuleMetaData, Error = DenoError> {
209
  let use_cache = !state.flags.reload;
210 211 212 213 214
  let state_ = state.clone();
  let specifier = specifier.to_string();
  let referrer = referrer.to_string();
  state
    .dir
215
    .fetch_module_meta_data_async(&specifier, &referrer, use_cache)
A
andy finch 已提交
216
    .and_then(move |out| {
217
      if out.media_type == msg::MediaType::TypeScript
218
        && !out.has_output_code_and_source_map()
219 220
      {
        debug!(">>>>> compile_sync START");
A
andy finch 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234
        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))
235 236 237
      }
    })
}
238

239
pub fn fetch_module_meta_data_and_maybe_compile(
240
  state: &ThreadSafeState,
R
Ryan Dahl 已提交
241 242
  specifier: &str,
  referrer: &str,
K
Kitson Kelly 已提交
243
) -> Result<ModuleMetaData, DenoError> {
244 245 246
  tokio_util::block_on(fetch_module_meta_data_and_maybe_compile_async(
    state, specifier, referrer,
  ))
R
Ryan Dahl 已提交
247 248
}

R
Ryan Dahl 已提交
249 250 251
#[cfg(test)]
mod tests {
  use super::*;
252
  use crate::flags;
A
andy finch 已提交
253
  use crate::ops::op_selector_std;
254 255
  use crate::resources;
  use crate::startup_data;
256
  use crate::state::ThreadSafeState;
257 258
  use crate::tokio_util;
  use deno::js_check;
259 260
  use futures::future::lazy;
  use std::sync::atomic::Ordering;
261 262

  #[test]
263
  fn execute_mod_esm_imports_a() {
264 265 266
    let filename = std::env::current_dir()
      .unwrap()
      .join("tests/esm_imports_a.js");
267
    let js_url = Url::from_file_path(filename).unwrap();
268

269
    let argv = vec![String::from("./deno"), js_url.to_string()];
270 271
    let state =
      ThreadSafeState::new(flags::DenoFlags::default(), argv, op_selector_std);
272 273
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
274 275 276 277 278 279 280 281 282
      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,
      };
283
      tokio_util::panic_on_error(worker)
284 285 286
    }));

    let metrics = &state_.metrics;
287
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
288 289 290 291 292
  }

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

295
    let argv = vec![String::from("./deno"), js_url.to_string()];
296 297
    let state =
      ThreadSafeState::new(flags::DenoFlags::default(), argv, op_selector_std);
298 299
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
300 301 302 303 304 305 306 307 308
      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,
      };
309
      tokio_util::panic_on_error(worker)
310 311 312
    }));

    let metrics = &state_.metrics;
313
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
314
  }
315 316

  fn create_test_worker() -> Worker {
317
    let state = ThreadSafeState::mock();
318
    let mut worker =
319
      Worker::new("TEST".to_string(), startup_data::deno_isolate_init(), state);
320 321 322 323 324 325 326 327 328 329 330 331 332
    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") {
333
            delete window.onmessage;
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
            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(
381
        worker.execute("onmessage = () => { delete window.onmessage; }"),
382 383 384 385 386
      );

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

387 388
      let worker_future = worker
        .then(move |r| -> Result<(), ()> {
389 390 391 392
          resource.close();
          println!("workers.rs after resource close");
          js_check(r);
          Ok(())
393 394 395 396
        }).shared();

      let worker_future_ = worker_future.clone();
      tokio::spawn(lazy(move || worker_future_.then(|_| Ok(()))));
397 398 399 400 401 402 403 404

      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);

405
      worker_future.wait().unwrap();
406 407 408
      assert_eq!(resources::get_type(rid), None);
    })
  }
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

  #[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());
  }
428
}