0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-30 09:08:00 -04:00
denoland-deno/cli/state.rs

317 lines
9.2 KiB
Rust
Raw Normal View History

2020-01-02 15:13:47 -05:00
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
2020-09-05 20:34:02 -04:00
use crate::file_fetcher::SourceFileFetcher;
use crate::global_state::GlobalState;
use crate::global_timer::GlobalTimer;
2019-06-09 09:08:20 -04:00
use crate::import_map::ImportMap;
use crate::metrics::Metrics;
use crate::permissions::Permissions;
use crate::tsc::TargetLib;
use crate::web_worker::WebWorkerHandle;
use deno_core::error::AnyError;
use deno_core::ModuleLoadId;
use deno_core::ModuleLoader;
use deno_core::ModuleSpecifier;
2019-11-16 19:17:47 -05:00
use futures::future::FutureExt;
use futures::Future;
use rand::rngs::StdRng;
use rand::SeedableRng;
use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::Path;
2019-11-16 19:17:47 -05:00
use std::pin::Pin;
use std::rc::Rc;
use std::str;
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::Instant;
// This is named "CliState" instead of just "State" to avoid confusion with all
// other state structs (GlobalState, OpState, GothamState).
// TODO(ry) Many of the items in this struct should be moved out and into
// OpState, removing redundant RefCell wrappers if possible.
pub struct CliState {
pub global_state: Arc<GlobalState>,
pub permissions: RefCell<Permissions>,
pub main_module: ModuleSpecifier,
2019-06-09 09:08:20 -04:00
/// 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>,
pub metrics: RefCell<Metrics>,
pub global_timer: RefCell<GlobalTimer>,
pub workers: RefCell<HashMap<u32, (JoinHandle<()>, WebWorkerHandle)>>,
pub next_worker_id: Cell<u32>,
pub start_time: Instant,
pub seeded_rng: Option<RefCell<StdRng>>,
pub target_lib: TargetLib,
pub is_main: bool,
pub is_internal: bool,
}
pub fn exit_unstable(api_name: &str) {
2020-04-27 19:12:38 -04:00
eprintln!(
"Unstable API '{}'. The --unstable flag must be provided.",
api_name
);
std::process::exit(70);
}
impl ModuleLoader for CliState {
2019-06-09 09:08:20 -04:00
fn resolve(
&self,
specifier: &str,
referrer: &str,
2019-08-07 12:55:39 -04:00
is_main: bool,
) -> Result<ModuleSpecifier, AnyError> {
2019-08-07 12:55:39 -04:00
if !is_main {
if let Some(import_map) = &self.import_map {
let result = import_map.resolve(specifier, referrer)?;
2019-10-03 09:16:06 -04:00
if let Some(r) = result {
return Ok(r);
2019-06-09 09:08:20 -04:00
}
}
}
let module_specifier =
ModuleSpecifier::resolve_import(specifier, referrer)?;
2019-06-09 09:08:20 -04:00
Ok(module_specifier)
}
2019-06-12 19:55:59 -04:00
fn load(
&self,
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<ModuleSpecifier>,
_is_dyn_import: bool,
) -> Pin<Box<deno_core::ModuleSourceFuture>> {
let module_specifier = module_specifier.to_owned();
// TODO(bartlomieju): incrementing resolve_count here has no sense...
self.metrics.borrow_mut().resolve_count += 1;
2019-08-07 12:55:39 -04:00
let module_url_specified = module_specifier.to_string();
let global_state = self.global_state.clone();
// TODO(bartlomieju): `fetch_compiled_module` should take `load_id` param
let fut = async move {
let compiled_module = global_state
.fetch_compiled_module(module_specifier, maybe_referrer)
.await?;
Ok(deno_core::ModuleSource {
// Real module name, might be different from initial specifier
// due to redirections.
code: compiled_module.code,
2019-08-07 12:55:39 -04:00
module_url_specified,
module_url_found: compiled_module.name,
})
};
fut.boxed_local()
}
fn prepare_load(
&self,
_load_id: ModuleLoadId,
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<String>,
is_dyn_import: bool,
) -> Pin<Box<dyn Future<Output = Result<(), AnyError>>>> {
let module_specifier = module_specifier.clone();
let target_lib = self.target_lib.clone();
let maybe_import_map = self.import_map.clone();
// Only "main" module is loaded without permission check,
// ie. module that is associated with "is_main" state
// and is not a dynamic import.
let permissions = if self.is_main && !is_dyn_import {
Permissions::allow_all()
} else {
self.permissions.borrow().clone()
};
let global_state = self.global_state.clone();
// TODO(bartlomieju): I'm not sure if it's correct to ignore
// bad referrer - this is the case for `Deno.core.evalContext()` where
// `ref_str` is `<unknown>`.
let maybe_referrer = if let Some(ref_str) = maybe_referrer {
ModuleSpecifier::resolve_url(&ref_str).ok()
} else {
None
};
// TODO(bartlomieju): `prepare_module_load` should take `load_id` param
async move {
global_state
.prepare_module_load(
module_specifier,
maybe_referrer,
target_lib,
permissions,
is_dyn_import,
maybe_import_map,
)
.await
}
.boxed_local()
}
}
impl CliState {
/// If `shared_permission` is None then permissions from globa state are used.
pub fn new(
global_state: &Arc<GlobalState>,
shared_permissions: Option<Permissions>,
main_module: ModuleSpecifier,
maybe_import_map: Option<ImportMap>,
is_internal: bool,
) -> Result<Rc<Self>, AnyError> {
let fl = &global_state.flags;
let state = CliState {
global_state: global_state.clone(),
main_module,
permissions: shared_permissions
.unwrap_or_else(|| global_state.permissions.clone())
.into(),
import_map: maybe_import_map,
metrics: Default::default(),
global_timer: Default::default(),
workers: Default::default(),
next_worker_id: Default::default(),
start_time: Instant::now(),
seeded_rng: fl.seed.map(|v| StdRng::seed_from_u64(v).into()),
target_lib: TargetLib::Main,
is_main: true,
is_internal,
};
Ok(Rc::new(state))
}
/// If `shared_permission` is None then permissions from globa state are used.
pub fn new_for_worker(
global_state: &Arc<GlobalState>,
shared_permissions: Option<Permissions>,
main_module: ModuleSpecifier,
) -> Result<Rc<Self>, AnyError> {
let fl = &global_state.flags;
let state = CliState {
global_state: global_state.clone(),
main_module,
permissions: shared_permissions
.unwrap_or_else(|| global_state.permissions.clone())
.into(),
import_map: None,
metrics: Default::default(),
global_timer: Default::default(),
workers: Default::default(),
next_worker_id: Default::default(),
start_time: Instant::now(),
seeded_rng: fl.seed.map(|v| StdRng::seed_from_u64(v).into()),
target_lib: TargetLib::Worker,
is_main: false,
is_internal: false,
};
Ok(Rc::new(state))
}
#[inline]
pub fn check_read(&self, path: &Path) -> Result<(), AnyError> {
self.permissions.borrow().check_read(path)
}
/// As `check_read()`, but permission error messages will anonymize the path
/// by replacing it with the given `display`.
#[inline]
pub fn check_read_blind(
&self,
path: &Path,
display: &str,
) -> Result<(), AnyError> {
self.permissions.borrow().check_read_blind(path, display)
}
#[inline]
pub fn check_write(&self, path: &Path) -> Result<(), AnyError> {
self.permissions.borrow().check_write(path)
}
#[inline]
pub fn check_env(&self) -> Result<(), AnyError> {
self.permissions.borrow().check_env()
}
#[inline]
pub fn check_net(&self, hostname: &str, port: u16) -> Result<(), AnyError> {
self.permissions.borrow().check_net(hostname, port)
}
#[inline]
pub fn check_net_url(&self, url: &url::Url) -> Result<(), AnyError> {
self.permissions.borrow().check_net_url(url)
}
#[inline]
pub fn check_run(&self) -> Result<(), AnyError> {
self.permissions.borrow().check_run()
}
2020-08-18 16:29:32 -04:00
#[inline]
pub fn check_hrtime(&self) -> Result<(), AnyError> {
self.permissions.borrow().check_hrtime()
2020-08-18 16:29:32 -04:00
}
#[inline]
pub fn check_plugin(&self, filename: &Path) -> Result<(), AnyError> {
self.permissions.borrow().check_plugin(filename)
}
pub fn check_dyn_import(
&self,
module_specifier: &ModuleSpecifier,
) -> Result<(), AnyError> {
let u = module_specifier.as_url();
// TODO(bartlomieju): temporary fix to prevent hitting `unreachable`
// statement that is actually reachable...
SourceFileFetcher::check_if_supported_scheme(u)?;
match u.scheme() {
"http" | "https" => {
self.check_net_url(u)?;
Ok(())
}
"file" => {
let path = u
.to_file_path()
.unwrap()
.into_os_string()
.into_string()
.unwrap();
self.check_read(Path::new(&path))?;
Ok(())
}
_ => unreachable!(),
}
}
#[cfg(test)]
2020-09-05 20:34:02 -04:00
pub fn mock(main_module: &str) -> Rc<Self> {
let module_specifier = ModuleSpecifier::resolve_url_or_path(main_module)
.expect("Invalid entry module");
CliState::new(
&GlobalState::mock(vec!["deno".to_string()], None),
None,
module_specifier,
None,
false,
)
.unwrap()
}
/// Quits the process if the --unstable flag was not provided.
///
/// This is intentionally a non-recoverable check so that people cannot probe
/// for unstable APIs from stable programs.
pub fn check_unstable(&self, api_name: &str) {
// TODO(ry) Maybe use IsolateHandle::terminate_execution here to provide a
// stack trace in JS.
if !self.global_state.flags.unstable {
exit_unstable(api_name);
}
}
}