state.rs 7.5 KB
Newer Older
1 2
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
use crate::deno_dir;
3
use crate::errors::DenoResult;
4 5
use crate::flags;
use crate::global_timer::GlobalTimer;
6
use crate::ops;
7
use crate::permissions::DenoPermissions;
R
Ryan Dahl 已提交
8
use crate::progress::Progress;
9
use crate::resources;
A
andy finch 已提交
10
use crate::resources::ResourceId;
11
use crate::worker::Worker;
12
use deno::Buf;
13
use deno::Op;
14
use deno::PinnedBuf;
A
andy finch 已提交
15
use futures::future::Shared;
16
use std;
A
andy finch 已提交
17
use std::collections::HashMap;
R
Ryan Dahl 已提交
18
use std::collections::HashSet;
19
use std::env;
20
use std::fs;
21
use std::ops::Deref;
22
use std::sync::atomic::{AtomicUsize, Ordering};
23
use std::sync::Arc;
24
use std::sync::Mutex;
25
use std::time::Instant;
26
use tokio::sync::mpsc as async_mpsc;
27 28 29 30

pub type WorkerSender = async_mpsc::Sender<Buf>;
pub type WorkerReceiver = async_mpsc::Receiver<Buf>;
pub type WorkerChannels = (WorkerSender, WorkerReceiver);
31
pub type UserWorkerTable = HashMap<ResourceId, Shared<Worker>>;
32 33 34 35 36 37 38 39 40

#[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 已提交
41
  pub compiler_starts: AtomicUsize,
42 43
}

R
Ryan Dahl 已提交
44 45 46
/// 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.
47 48
pub struct ThreadSafeState(Arc<State>);

49
#[cfg_attr(feature = "cargo-clippy", allow(stutter))]
50
pub struct State {
51 52
  pub dir: deno_dir::DenoDir,
  pub argv: Vec<String>,
53
  pub permissions: DenoPermissions,
54
  pub flags: flags::DenoFlags,
55 56 57 58 59 60
  /// 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>,
61
  pub metrics: Metrics,
62
  pub worker_channels: Mutex<WorkerChannels>,
63
  pub global_timer: Mutex<GlobalTimer>,
A
andy finch 已提交
64
  pub workers: Mutex<UserWorkerTable>,
65
  pub start_time: Instant,
R
Ryan Dahl 已提交
66
  /// A reference to this worker's resource.
67
  pub resource: resources::Resource,
A
andy finch 已提交
68
  pub dispatch_selector: ops::OpSelector,
R
Ryan Dahl 已提交
69 70
  /// Reference to global progress bar.
  pub progress: Progress,
R
Ryan Dahl 已提交
71 72 73 74 75

  /// 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>>,
76 77
}

78 79 80 81 82 83 84 85 86 87 88 89 90
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
  }
}

91
impl ThreadSafeState {
R
Ryan Dahl 已提交
92
  pub fn dispatch(&self, control: &[u8], zero_copy: Option<PinnedBuf>) -> Op {
A
andy finch 已提交
93
    ops::dispatch_all(self, control, zero_copy, self.dispatch_selector)
94 95 96 97
  }
}

impl ThreadSafeState {
A
andy finch 已提交
98 99 100 101
  pub fn new(
    flags: flags::DenoFlags,
    argv_rest: Vec<String>,
    dispatch_selector: ops::OpSelector,
R
Ryan Dahl 已提交
102
    progress: Progress,
A
andy finch 已提交
103
  ) -> Self {
B
Bert Belder 已提交
104
    let custom_root = env::var("DENO_DIR").map(String::into).ok();
105

106 107 108 109 110 111
    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);

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    // 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,
    };

151
    ThreadSafeState(Arc::new(State {
R
Ryan Dahl 已提交
152 153
      dir: deno_dir::DenoDir::new(custom_root, &config, progress.clone())
        .unwrap(),
154
      argv: argv_rest,
155
      permissions: DenoPermissions::from_flags(&flags),
156
      flags,
157 158
      config,
      config_path,
159
      metrics: Metrics::default(),
160
      worker_channels: Mutex::new(internal_channels),
161
      global_timer: Mutex::new(GlobalTimer::new()),
A
andy finch 已提交
162
      workers: Mutex::new(UserWorkerTable::new()),
163
      start_time: Instant::now(),
164
      resource,
A
andy finch 已提交
165
      dispatch_selector,
R
Ryan Dahl 已提交
166
      progress,
R
Ryan Dahl 已提交
167
      compiled: Mutex::new(HashSet::new()),
168
    }))
169 170
  }

A
andy finch 已提交
171
  /// Read main module from argv
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  pub fn main_module(&self) -> Option<String> {
    if self.argv.len() <= 1 {
      None
    } else {
      let specifier = self.argv[1].clone();
      let referrer = ".";
      match self.dir.resolve_module_url(&specifier, referrer) {
        Ok(url) => Some(url.to_string()),
        Err(e) => {
          debug!("Potentially swallowed error {}", e);
          None
        }
      }
    }
  }

R
Ryan Dahl 已提交
188 189 190 191 192 193 194 195 196 197
  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)
  }

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  #[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]
214 215 216 217 218 219 220
  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)
221 222 223 224 225 226 227
  }

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

228
  #[cfg(test)]
229
  pub fn mock() -> ThreadSafeState {
230
    let argv = vec![String::from("./deno"), String::from("hello.js")];
231 232 233 234
    ThreadSafeState::new(
      flags::DenoFlags::default(),
      argv,
      ops::op_selector_std,
R
Ryan Dahl 已提交
235
      Progress::new(),
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
  }

  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);
  }
}
263 264 265 266 267 268

#[test]
fn thread_safe() {
  fn f<S: Send + Sync>(_: S) {}
  f(ThreadSafeState::mock());
}