worker.rs 12.1 KB
Newer Older
R
Ryan Dahl 已提交
1
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
A
Andy Hayden 已提交
2
use crate::errors::DenoError;
3
use crate::errors::RustOrJsError;
4
use crate::js_errors;
5
use crate::state::ThreadSafeState;
6
use crate::tokio_util;
7
use deno;
8
use deno::Config;
9
use deno::JSError;
R
Ryan Dahl 已提交
10
use deno::StartupData;
11
use futures::Async;
R
Ryan Dahl 已提交
12
use futures::Future;
13 14
use std::sync::Arc;
use std::sync::Mutex;
15
use url::Url;
B
Bartek Iwańczuk 已提交
16

17
/// Wraps deno::Isolate to provide source maps, ops for the CLI, and
18
/// high-level module loading
19
#[derive(Clone)]
20
pub struct Worker {
21
  inner: Arc<Mutex<deno::Isolate>>,
22
  pub state: ThreadSafeState,
23 24
}

25 26 27 28
impl Worker {
  pub fn new(
    _name: String,
    startup_data: StartupData,
29
    state: ThreadSafeState,
30
  ) -> Worker {
31
    let state_ = state.clone();
32 33 34 35
    let mut config = Config::default();
    config.dispatch(move |control_buf, zero_copy_buf| {
      state_.dispatch(control_buf, zero_copy_buf)
    });
36
    Self {
37
      inner: Arc::new(Mutex::new(deno::Isolate::new(startup_data, config))),
A
Andy Hayden 已提交
38
      state,
39 40 41
    }
  }

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

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

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

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

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

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

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

138 139 140 141 142 143
  // 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())
}
144

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

164
impl Future for Worker {
165 166 167 168
  type Item = ();
  type Error = JSError;

  fn poll(&mut self) -> Result<Async<()>, Self::Error> {
169 170
    let mut isolate = self.inner.lock().unwrap();
    isolate.poll().map_err(|err| self.apply_source_map(err))
171 172
  }
}
173

R
Ryan Dahl 已提交
174 175 176
#[cfg(test)]
mod tests {
  use super::*;
177
  use crate::flags;
A
andy finch 已提交
178
  use crate::ops::op_selector_std;
R
Ryan Dahl 已提交
179
  use crate::progress::Progress;
180 181
  use crate::resources;
  use crate::startup_data;
182
  use crate::state::ThreadSafeState;
183 184
  use crate::tokio_util;
  use deno::js_check;
185 186
  use futures::future::lazy;
  use std::sync::atomic::Ordering;
187 188

  #[test]
189
  fn execute_mod_esm_imports_a() {
190 191 192
    let filename = std::env::current_dir()
      .unwrap()
      .join("tests/esm_imports_a.js");
193
    let js_url = Url::from_file_path(filename).unwrap();
194

195
    let argv = vec![String::from("./deno"), js_url.to_string()];
R
Ryan Dahl 已提交
196 197 198 199 200 201
    let state = ThreadSafeState::new(
      flags::DenoFlags::default(),
      argv,
      op_selector_std,
      Progress::new(),
    );
202 203
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
204 205
      let mut worker =
        Worker::new("TEST".to_string(), StartupData::None, state);
206
      let result = worker.execute_mod(&js_url, false);
207 208 209
      if let Err(err) = result {
        eprintln!("execute_mod err {:?}", err);
      }
210
      tokio_util::panic_on_error(worker)
211 212 213
    }));

    let metrics = &state_.metrics;
214
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
R
Ryan Dahl 已提交
215 216
    // Check that we didn't start the compiler.
    assert_eq!(metrics.compiler_starts.load(Ordering::SeqCst), 0);
217 218 219 220 221
  }

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

224
    let argv = vec![String::from("./deno"), js_url.to_string()];
R
Ryan Dahl 已提交
225 226 227 228 229 230
    let state = ThreadSafeState::new(
      flags::DenoFlags::default(),
      argv,
      op_selector_std,
      Progress::new(),
    );
231 232
    let state_ = state.clone();
    tokio_util::run(lazy(move || {
233 234
      let mut worker =
        Worker::new("TEST".to_string(), StartupData::None, state);
235
      let result = worker.execute_mod(&js_url, false);
236 237 238
      if let Err(err) = result {
        eprintln!("execute_mod err {:?}", err);
      }
239
      tokio_util::panic_on_error(worker)
240 241 242
    }));

    let metrics = &state_.metrics;
243
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 2);
R
Ryan Dahl 已提交
244 245
    // Check that we didn't start the compiler.
    assert_eq!(metrics.compiler_starts.load(Ordering::SeqCst), 0);
246
  }
247

R
Ryan Dahl 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  #[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);
268 269 270
      if let Err(err) = result {
        eprintln!("execute_mod err {:?}", err);
      }
R
Ryan Dahl 已提交
271 272 273 274 275
      tokio_util::panic_on_error(worker)
    }));

    let metrics = &state_.metrics;
    assert_eq!(metrics.resolve_count.load(Ordering::SeqCst), 3);
R
Ryan Dahl 已提交
276 277
    // Check that we've only invoked the compiler once.
    assert_eq!(metrics.compiler_starts.load(Ordering::SeqCst), 1);
R
Ryan Dahl 已提交
278 279
  }

280
  fn create_test_worker() -> Worker {
K
Kitson Kelly 已提交
281 282 283 284
    let state = ThreadSafeState::mock(vec![
      String::from("./deno"),
      String::from("hello.js"),
    ]);
285
    let mut worker =
286
      Worker::new("TEST".to_string(), startup_data::deno_isolate_init(), state);
287 288 289 290 291 292 293 294 295 296 297 298 299
    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") {
300
            delete window.onmessage;
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
            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(
348
        worker.execute("onmessage = () => { delete window.onmessage; }"),
349 350 351 352 353
      );

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

354 355
      let worker_future = worker
        .then(move |r| -> Result<(), ()> {
356 357 358 359
          resource.close();
          println!("workers.rs after resource close");
          js_check(r);
          Ok(())
360 361 362 363
        }).shared();

      let worker_future_ = worker_future.clone();
      tokio::spawn(lazy(move || worker_future_.then(|_| Ok(()))));
364 365 366 367 368 369 370 371

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

372
      worker_future.wait().unwrap();
373 374 375
      assert_eq!(resources::get_type(rid), None);
    })
  }
376 377 378

  #[test]
  fn execute_mod_resolve_error() {
R
Ryan Dahl 已提交
379 380
    tokio_util::init(|| {
      // "foo" is not a vailid module specifier so this should return an error.
381
      let mut worker = create_test_worker();
R
Ryan Dahl 已提交
382 383 384 385
      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());
    })
386 387 388 389
  }

  #[test]
  fn execute_mod_002_hello() {
R
Ryan Dahl 已提交
390 391 392
    tokio_util::init(|| {
      // This assumes cwd is project root (an assumption made throughout the
      // tests).
393
      let mut worker = create_test_worker();
R
Ryan Dahl 已提交
394 395 396 397
      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());
    })
398
  }
399
}