worker.rs 12.9 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 72 73 74 75 76 77 78 79 80
  /// 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_)
          }
81
        }
82 83 84 85 86 87 88 89 90 91
      },
    )
    .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_)
    })
92 93
  }

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

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

109 110 111 112 113 114 115 116 117 118 119 120 121
// 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());
  }
122

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

135 136 137 138 139 140
  // 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())
}
141

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
/// 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 已提交
158
  }
159
}
R
Ryan Dahl 已提交
160

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

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

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

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

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

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

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

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

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

  #[test]
267
  fn execute_mod_esm_imports_a() {
268 269 270
    let filename = std::env::current_dir()
      .unwrap()
      .join("tests/esm_imports_a.js");
271
    let js_url = Url::from_file_path(filename).unwrap();
272

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

    let metrics = &state_.metrics;
291
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
292 293 294 295 296
  }

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

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

    let metrics = &state_.metrics;
317
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
318
  }
319 320

  fn create_test_worker() -> Worker {
321
    let state = ThreadSafeState::mock();
322
    let mut worker =
323
      Worker::new("TEST".to_string(), startup_data::deno_isolate_init(), state);
324 325 326 327 328 329 330 331 332 333 334 335 336
    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") {
337
            delete window.onmessage;
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
            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(
385
        worker.execute("onmessage = () => { delete window.onmessage; }"),
386 387 388 389 390
      );

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

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

      let worker_future_ = worker_future.clone();
      tokio::spawn(lazy(move || worker_future_.then(|_| Ok(()))));
401 402 403 404 405 406 407 408

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

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

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