state.rs 11.5 KB
Newer Older
1
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
2 3
use crate::compiler::compile_async;
use crate::compiler::ModuleMetaData;
4
use crate::deno_dir;
5
use crate::errors::DenoError;
6
use crate::errors::DenoResult;
7 8
use crate::flags;
use crate::global_timer::GlobalTimer;
B
Bartek Iwańczuk 已提交
9
use crate::import_map::ImportMap;
10
use crate::msg;
11
use crate::ops;
12
use crate::permissions::DenoPermissions;
R
Ryan Dahl 已提交
13
use crate::progress::Progress;
14
use crate::resources;
A
andy finch 已提交
15
use crate::resources::ResourceId;
16 17
use crate::tokio_util;
use crate::worker::resolve_module_spec;
18
use crate::worker::Worker;
19
use deno::Buf;
20
use deno::Loader;
21
use deno::Op;
22
use deno::PinnedBuf;
23
use futures::future::Either;
A
andy finch 已提交
24
use futures::future::Shared;
25
use futures::Future;
26
use std;
A
andy finch 已提交
27
use std::collections::HashMap;
R
Ryan Dahl 已提交
28
use std::collections::HashSet;
29
use std::env;
30
use std::fs;
31
use std::ops::Deref;
32
use std::sync::atomic::{AtomicUsize, Ordering};
33
use std::sync::Arc;
34
use std::sync::Mutex;
35
use std::time::Instant;
36
use tokio::sync::mpsc as async_mpsc;
37 38 39 40

pub type WorkerSender = async_mpsc::Sender<Buf>;
pub type WorkerReceiver = async_mpsc::Receiver<Buf>;
pub type WorkerChannels = (WorkerSender, WorkerReceiver);
41
pub type UserWorkerTable = HashMap<ResourceId, Shared<Worker>>;
42 43 44 45 46 47 48 49 50

#[derive(Default)]
pub struct Metrics {
  pub ops_dispatched: AtomicUsize,
  pub ops_completed: AtomicUsize,
  pub bytes_sent_control: AtomicUsize,
  pub bytes_sent_data: AtomicUsize,
  pub bytes_received: AtomicUsize,
  pub resolve_count: AtomicUsize,
R
Ryan Dahl 已提交
51
  pub compiler_starts: AtomicUsize,
52 53
}

R
Ryan Dahl 已提交
54 55 56
/// Isolate cannot be passed between threads but ThreadSafeState can.
/// ThreadSafeState satisfies Send and Sync. So any state that needs to be
/// accessed outside the main V8 thread should be inside ThreadSafeState.
57 58
pub struct ThreadSafeState(Arc<State>);

59
#[cfg_attr(feature = "cargo-clippy", allow(stutter))]
60
pub struct State {
B
Bartek Iwańczuk 已提交
61
  pub main_module: Option<String>,
62 63
  pub dir: deno_dir::DenoDir,
  pub argv: Vec<String>,
64
  pub permissions: DenoPermissions,
65
  pub flags: flags::DenoFlags,
66 67 68 69 70 71
  /// When flags contains a `.config_path` option, the content of the
  /// configuration file will be resolved and set.
  pub config: Option<Vec<u8>>,
  /// When flags contains a `.config_path` option, the fully qualified path
  /// name of the passed path will be resolved and set.
  pub config_path: Option<String>,
B
Bartek Iwańczuk 已提交
72 73 74
  /// When flags contains a `.import_map_path` option, the content of the
  /// import map file will be resolved and set.
  pub import_map: Option<ImportMap>,
75
  pub metrics: Metrics,
76
  pub worker_channels: Mutex<WorkerChannels>,
77
  pub global_timer: Mutex<GlobalTimer>,
A
andy finch 已提交
78
  pub workers: Mutex<UserWorkerTable>,
79
  pub start_time: Instant,
R
Ryan Dahl 已提交
80
  /// A reference to this worker's resource.
81
  pub resource: resources::Resource,
A
andy finch 已提交
82
  pub dispatch_selector: ops::OpSelector,
R
Ryan Dahl 已提交
83 84
  /// Reference to global progress bar.
  pub progress: Progress,
R
Ryan Dahl 已提交
85 86 87 88 89

  /// Set of all URLs that have been compiled. This is a hacky way to work
  /// around the fact that --reload will force multiple compilations of the same
  /// module.
  compiled: Mutex<HashSet<String>>,
90 91
}

92 93 94 95 96 97 98 99 100 101 102 103 104
impl Clone for ThreadSafeState {
  fn clone(&self) -> Self {
    ThreadSafeState(self.0.clone())
  }
}

impl Deref for ThreadSafeState {
  type Target = Arc<State>;
  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

105
impl ThreadSafeState {
R
Ryan Dahl 已提交
106
  pub fn dispatch(&self, control: &[u8], zero_copy: Option<PinnedBuf>) -> Op {
A
andy finch 已提交
107
    ops::dispatch_all(self, control, zero_copy, self.dispatch_selector)
108 109 110
  }
}

111
pub fn fetch_module_meta_data_and_maybe_compile_async(
112 113 114 115 116 117 118
  state: &ThreadSafeState,
  specifier: &str,
  referrer: &str,
) -> impl Future<Item = ModuleMetaData, Error = DenoError> {
  let state_ = state.clone();
  let specifier = specifier.to_string();
  let referrer = referrer.to_string();
B
Bartek Iwańczuk 已提交
119
  let is_root = referrer == ".";
120 121

  let f =
B
Bartek Iwańczuk 已提交
122
    futures::future::result(state.resolve(&specifier, &referrer, is_root));
123 124 125 126 127 128 129 130 131 132 133 134 135
  f.and_then(move |module_id| {
    let use_cache = !state_.flags.reload || state_.has_compiled(&module_id);
    let no_fetch = state_.flags.no_fetch;

    state_
      .dir
      .fetch_module_meta_data_async(&specifier, &referrer, use_cache, no_fetch)
      .and_then(move |out| {
        if out.media_type == msg::MediaType::TypeScript
          && !out.has_output_code_and_source_map()
        {
          debug!(">>>>> compile_sync START");
          Either::A(
K
Kitson Kelly 已提交
136
            compile_async(state_.clone(), &out)
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
              .map_err(|e| {
                debug!("compiler error exiting!");
                eprintln!("\n{}", e.to_string());
                std::process::exit(1);
              }).and_then(move |out| {
                debug!(">>>>> compile_sync END");
                Ok(out)
              }),
          )
        } else {
          Either::B(futures::future::ok(out))
        }
      })
  })
}

pub fn fetch_module_meta_data_and_maybe_compile(
  state: &ThreadSafeState,
  specifier: &str,
  referrer: &str,
) -> Result<ModuleMetaData, DenoError> {
  tokio_util::block_on(fetch_module_meta_data_and_maybe_compile_async(
    state, specifier, referrer,
  ))
}

impl Loader for ThreadSafeState {
  type Error = DenoError;

B
Bartek Iwańczuk 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  fn resolve(
    &self,
    specifier: &str,
    referrer: &str,
    is_root: bool,
  ) -> Result<String, Self::Error> {
    if !is_root {
      if let Some(import_map) = &self.import_map {
        match import_map.resolve(specifier, referrer) {
          Ok(result) => {
            if result.is_some() {
              return Ok(result.unwrap());
            }
          }
          Err(err) => {
            // TODO(bartlomieju): this should be coerced to DenoError
            panic!("error resolving using import map: {:?}", err);
          }
        }
      }
    }

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    resolve_module_spec(specifier, referrer).map_err(DenoError::from)
  }

  /// Given an absolute url, load its source code.
  fn load(&self, url: &str) -> Box<deno::SourceCodeInfoFuture<Self::Error>> {
    self.metrics.resolve_count.fetch_add(1, Ordering::SeqCst);
    Box::new(
      fetch_module_meta_data_and_maybe_compile_async(self, url, ".")
        .map_err(|err| {
          eprintln!("{}", err);
          err
        }).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,
        }),
    )
  }
}

209
impl ThreadSafeState {
A
andy finch 已提交
210 211 212 213
  pub fn new(
    flags: flags::DenoFlags,
    argv_rest: Vec<String>,
    dispatch_selector: ops::OpSelector,
R
Ryan Dahl 已提交
214
    progress: Progress,
A
andy finch 已提交
215
  ) -> Self {
B
Bert Belder 已提交
216
    let custom_root = env::var("DENO_DIR").map(String::into).ok();
217

218 219 220 221 222 223
    let (worker_in_tx, worker_in_rx) = async_mpsc::channel::<Buf>(1);
    let (worker_out_tx, worker_out_rx) = async_mpsc::channel::<Buf>(1);
    let internal_channels = (worker_out_tx, worker_in_rx);
    let external_channels = (worker_in_tx, worker_out_rx);
    let resource = resources::add_worker(external_channels);

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    // take the passed flag and resolve the file name relative to the cwd
    let config_file = match &flags.config_path {
      Some(config_file_name) => {
        debug!("Compiler config file: {}", config_file_name);
        let cwd = std::env::current_dir().unwrap();
        Some(cwd.join(config_file_name))
      }
      _ => None,
    };

    // Convert the PathBuf to a canonicalized string.  This is needed by the
    // compiler to properly deal with the configuration.
    let config_path = match &config_file {
      Some(config_file) => Some(
        config_file
          .canonicalize()
          .unwrap()
          .to_str()
          .unwrap()
          .to_owned(),
      ),
      _ => None,
    };

    // Load the contents of the configuration file
    let config = match &config_file {
      Some(config_file) => {
        debug!("Attempt to load config: {}", config_file.to_str().unwrap());
        match fs::read(&config_file) {
          Ok(config_data) => Some(config_data.to_owned()),
          _ => panic!(
            "Error retrieving compiler config file at \"{}\"",
            config_file.to_str().unwrap()
          ),
        }
      }
      _ => None,
    };

B
Bartek Iwańczuk 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    let dir =
      deno_dir::DenoDir::new(custom_root, &config, progress.clone()).unwrap();

    let main_module: Option<String> = if argv_rest.len() <= 1 {
      None
    } else {
      let specifier = argv_rest[1].clone();
      let referrer = ".";
      // TODO: does this really have to be resolved by DenoDir?
      //  Maybe we can call `resolve_module_spec`
      match dir.resolve_module_url(&specifier, referrer) {
        Ok(url) => Some(url.to_string()),
        Err(e) => {
          debug!("Potentially swallowed error {}", e);
          None
        }
      }
    };

    let mut import_map = None;
    if let Some(file_name) = &flags.import_map_path {
      let base_url = match &main_module {
        Some(url) => url,
        None => unreachable!(),
      };

      match ImportMap::load(base_url, file_name) {
        Ok(map) => import_map = Some(map),
        Err(err) => {
          println!("{:?}", err);
          panic!("Error parsing import map");
        }
      }
    }

298
    ThreadSafeState(Arc::new(State {
B
Bartek Iwańczuk 已提交
299 300
      main_module,
      dir,
301
      argv: argv_rest,
302
      permissions: DenoPermissions::from_flags(&flags),
303
      flags,
304 305
      config,
      config_path,
B
Bartek Iwańczuk 已提交
306
      import_map,
307
      metrics: Metrics::default(),
308
      worker_channels: Mutex::new(internal_channels),
309
      global_timer: Mutex::new(GlobalTimer::new()),
A
andy finch 已提交
310
      workers: Mutex::new(UserWorkerTable::new()),
311
      start_time: Instant::now(),
312
      resource,
A
andy finch 已提交
313
      dispatch_selector,
R
Ryan Dahl 已提交
314
      progress,
R
Ryan Dahl 已提交
315
      compiled: Mutex::new(HashSet::new()),
316
    }))
317 318
  }

A
andy finch 已提交
319
  /// Read main module from argv
320
  pub fn main_module(&self) -> Option<String> {
B
Bartek Iwańczuk 已提交
321 322 323
    match &self.main_module {
      Some(url) => Some(url.to_string()),
      None => None,
324 325 326
    }
  }

R
Ryan Dahl 已提交
327 328 329 330 331 332 333 334 335 336
  pub fn mark_compiled(&self, module_id: &str) {
    let mut c = self.compiled.lock().unwrap();
    c.insert(module_id.to_string());
  }

  pub fn has_compiled(&self, module_id: &str) -> bool {
    let c = self.compiled.lock().unwrap();
    c.contains(module_id)
  }

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
  #[inline]
  pub fn check_read(&self, filename: &str) -> DenoResult<()> {
    self.permissions.check_read(filename)
  }

  #[inline]
  pub fn check_write(&self, filename: &str) -> DenoResult<()> {
    self.permissions.check_write(filename)
  }

  #[inline]
  pub fn check_env(&self) -> DenoResult<()> {
    self.permissions.check_env()
  }

  #[inline]
353 354 355 356 357 358 359
  pub fn check_net(&self, host_and_port: &str) -> DenoResult<()> {
    self.permissions.check_net(host_and_port)
  }

  #[inline]
  pub fn check_net_url(&self, url: url::Url) -> DenoResult<()> {
    self.permissions.check_net_url(url)
360 361 362 363 364 365 366
  }

  #[inline]
  pub fn check_run(&self) -> DenoResult<()> {
    self.permissions.check_run()
  }

367
  #[cfg(test)]
K
Kitson Kelly 已提交
368
  pub fn mock(argv: Vec<String>) -> ThreadSafeState {
369 370 371 372
    ThreadSafeState::new(
      flags::DenoFlags::default(),
      argv,
      ops::op_selector_std,
R
Ryan Dahl 已提交
373
      Progress::new(),
374
    )
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
  }

  pub fn metrics_op_dispatched(
    &self,
    bytes_sent_control: usize,
    bytes_sent_data: usize,
  ) {
    self.metrics.ops_dispatched.fetch_add(1, Ordering::SeqCst);
    self
      .metrics
      .bytes_sent_control
      .fetch_add(bytes_sent_control, Ordering::SeqCst);
    self
      .metrics
      .bytes_sent_data
      .fetch_add(bytes_sent_data, Ordering::SeqCst);
  }

  pub fn metrics_op_completed(&self, bytes_received: usize) {
    self.metrics.ops_completed.fetch_add(1, Ordering::SeqCst);
    self
      .metrics
      .bytes_received
      .fetch_add(bytes_received, Ordering::SeqCst);
  }
}
401 402 403 404

#[test]
fn thread_safe() {
  fn f<S: Send + Sync>(_: S) {}
K
Kitson Kelly 已提交
405 406 407 408
  f(ThreadSafeState::mock(vec![
    String::from("./deno"),
    String::from("hello.js"),
  ]));
409
}