worker.rs 12.6 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 165 166 167 168 169 170 171 172 173 174 175 176 177
  /// Given an absolute url, load its source code.
  fn load(&mut self, url: &str) -> Box<deno::SourceCodeFuture<Self::Error>> {
    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
        }).map(|module_meta_data| module_meta_data.js_source()),
    )
R
Ryan Dahl 已提交
178 179
  }

180 181 182 183
  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 已提交
184
  }
185 186
}

187
impl Future for Worker {
188 189 190 191 192
  type Item = ();
  type Error = JSError;

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

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

231
pub fn fetch_module_meta_data_and_maybe_compile(
232
  state: &ThreadSafeState,
R
Ryan Dahl 已提交
233 234
  specifier: &str,
  referrer: &str,
K
Kitson Kelly 已提交
235
) -> Result<ModuleMetaData, DenoError> {
236 237 238
  tokio_util::block_on(fetch_module_meta_data_and_maybe_compile_async(
    state, specifier, referrer,
  ))
R
Ryan Dahl 已提交
239 240
}

R
Ryan Dahl 已提交
241 242 243
#[cfg(test)]
mod tests {
  use super::*;
244
  use crate::flags;
A
andy finch 已提交
245
  use crate::ops::op_selector_std;
246 247
  use crate::resources;
  use crate::startup_data;
248
  use crate::state::ThreadSafeState;
249 250
  use crate::tokio_util;
  use deno::js_check;
251 252
  use futures::future::lazy;
  use std::sync::atomic::Ordering;
253 254

  #[test]
255
  fn execute_mod_esm_imports_a() {
256 257 258
    let filename = std::env::current_dir()
      .unwrap()
      .join("tests/esm_imports_a.js");
259
    let js_url = Url::from_file_path(filename).unwrap();
260

261
    let argv = vec![String::from("./deno"), js_url.to_string()];
262
    let (flags, rest_argv) = flags::set_flags(argv).unwrap();
263

A
andy finch 已提交
264
    let state = ThreadSafeState::new(flags, rest_argv, op_selector_std);
265 266
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
267 268 269 270 271 272 273 274 275
      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,
      };
276
      tokio_util::panic_on_error(worker)
277 278 279
    }));

    let metrics = &state_.metrics;
280
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
281 282 283 284 285
  }

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

288
    let argv = vec![String::from("./deno"), js_url.to_string()];
289
    let (flags, rest_argv) = flags::set_flags(argv).unwrap();
290

A
andy finch 已提交
291
    let state = ThreadSafeState::new(flags, rest_argv, op_selector_std);
292 293
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
294 295 296 297 298 299 300 301 302
      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,
      };
303
      tokio_util::panic_on_error(worker)
304 305 306
    }));

    let metrics = &state_.metrics;
307
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
308
  }
309 310

  fn create_test_worker() -> Worker {
311
    let state = ThreadSafeState::mock();
312
    let mut worker =
313
      Worker::new("TEST".to_string(), startup_data::deno_isolate_init(), state);
314 315 316 317 318 319 320 321 322 323 324 325 326
    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") {
327
            delete window.onmessage;
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
            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(
375
        worker.execute("onmessage = () => { delete window.onmessage; }"),
376 377 378 379 380
      );

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

381 382
      let worker_future = worker
        .then(move |r| -> Result<(), ()> {
383 384 385 386
          resource.close();
          println!("workers.rs after resource close");
          js_check(r);
          Ok(())
387 388 389 390
        }).shared();

      let worker_future_ = worker_future.clone();
      tokio::spawn(lazy(move || worker_future_.then(|_| Ok(()))));
391 392 393 394 395 396 397 398

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

399
      worker_future.wait().unwrap();
400 401 402
      assert_eq!(resources::get_type(rid), None);
    })
  }
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

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