diff options
author | Aaron O'Mullan <aaron.omullan@gmail.com> | 2021-04-05 18:40:24 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-05 18:40:24 +0200 |
commit | 2aed322dd507a8568b6ee6f4897e9a8e3220f763 (patch) | |
tree | e9a45c0b7688a9881ea9ce132b92554ef2955ad6 /runtime | |
parent | 284e6c303956e8ca20af63b4ecc045438a260fe6 (diff) |
refactor: convert ops to use serde_v8 (#10009)
This commit rewrites most of the ops to use "serde_v8" instead
of "json" serialization.
Diffstat (limited to 'runtime')
-rw-r--r-- | runtime/js/11_timers.js | 4 | ||||
-rw-r--r-- | runtime/js/11_workers.js | 12 | ||||
-rw-r--r-- | runtime/js/30_fs.js | 39 | ||||
-rw-r--r-- | runtime/js/30_net.js | 2 | ||||
-rw-r--r-- | runtime/js/30_os.js | 13 | ||||
-rw-r--r-- | runtime/js/40_fs_events.js | 7 | ||||
-rw-r--r-- | runtime/js/40_permissions.js | 6 | ||||
-rw-r--r-- | runtime/js/40_plugins.js | 2 | ||||
-rw-r--r-- | runtime/js/40_process.js | 2 | ||||
-rw-r--r-- | runtime/js/40_signals.js | 14 | ||||
-rw-r--r-- | runtime/js/40_tls.js | 2 | ||||
-rw-r--r-- | runtime/js/40_tty.js | 4 | ||||
-rw-r--r-- | runtime/js/99_main.js | 2 | ||||
-rw-r--r-- | runtime/ops/fs.rs | 430 | ||||
-rw-r--r-- | runtime/ops/fs_events.rs | 21 | ||||
-rw-r--r-- | runtime/ops/io.rs | 16 | ||||
-rw-r--r-- | runtime/ops/net.rs | 19 | ||||
-rw-r--r-- | runtime/ops/net_unix.rs | 7 | ||||
-rw-r--r-- | runtime/ops/os.rs | 145 | ||||
-rw-r--r-- | runtime/ops/permissions.rs | 14 | ||||
-rw-r--r-- | runtime/ops/plugin.rs | 18 | ||||
-rw-r--r-- | runtime/ops/process.rs | 58 | ||||
-rw-r--r-- | runtime/ops/runtime.rs | 35 | ||||
-rw-r--r-- | runtime/ops/signal.rs | 57 | ||||
-rw-r--r-- | runtime/ops/timers.rs | 43 | ||||
-rw-r--r-- | runtime/ops/tls.rs | 9 | ||||
-rw-r--r-- | runtime/ops/tty.rs | 30 | ||||
-rw-r--r-- | runtime/ops/web_worker.rs | 9 | ||||
-rw-r--r-- | runtime/ops/worker_host.rs | 38 |
29 files changed, 484 insertions, 574 deletions
diff --git a/runtime/js/11_timers.js b/runtime/js/11_timers.js index 200c764b7..046609f75 100644 --- a/runtime/js/11_timers.js +++ b/runtime/js/11_timers.js @@ -10,7 +10,7 @@ } function opStartGlobalTimer(timeout) { - return core.jsonOpSync("op_global_timer_start", { timeout }); + return core.jsonOpSync("op_global_timer_start", timeout); } async function opWaitGlobalTimer() { @@ -22,7 +22,7 @@ } function sleepSync(millis = 0) { - return core.jsonOpSync("op_sleep_sync", { millis }); + return core.jsonOpSync("op_sleep_sync", millis); } // Derived from https://github.com/vadimg/js_bintrees. MIT Licensed. diff --git a/runtime/js/11_workers.js b/runtime/js/11_workers.js index 2917ec004..b11195713 100644 --- a/runtime/js/11_workers.js +++ b/runtime/js/11_workers.js @@ -28,15 +28,15 @@ } function hostTerminateWorker(id) { - core.jsonOpSync("op_host_terminate_worker", { id }); + core.jsonOpSync("op_host_terminate_worker", id); } function hostPostMessage(id, data) { - core.jsonOpSync("op_host_post_message", { id }, data); + core.jsonOpSync("op_host_post_message", id, data); } function hostGetMessage(id) { - return core.jsonOpAsync("op_host_get_message", { id }); + return core.jsonOpAsync("op_host_get_message", id); } const encoder = new TextEncoder(); @@ -197,7 +197,7 @@ } } - const { id } = createWorker( + const id = createWorker( specifier, hasSourceCode, sourceCode, @@ -270,7 +270,7 @@ } else { core.jsonOpSync( "op_host_unhandled_error", - { message: event.error.message }, + event.error.message, ); } } @@ -289,7 +289,7 @@ } else { core.jsonOpSync( "op_host_unhandled_error", - { message: event.error.message }, + event.error.message, ); } } diff --git a/runtime/js/30_fs.js b/runtime/js/30_fs.js index f150c38b6..e79247640 100644 --- a/runtime/js/30_fs.js +++ b/runtime/js/30_fs.js @@ -58,7 +58,7 @@ } function chdir(directory) { - core.jsonOpSync("op_chdir", { directory }); + core.jsonOpSync("op_chdir", directory); } function makeTempDirSync(options = {}) { @@ -101,14 +101,8 @@ await core.jsonOpAsync("op_mkdir_async", mkdirArgs(path, options)); } - function res(response) { - return response.entries; - } - function readDirSync(path) { - return res( - core.jsonOpSync("op_read_dir_sync", { path: pathFromURL(path) }), - )[ + return core.jsonOpSync("op_read_dir_sync", pathFromURL(path))[ Symbol.iterator ](); } @@ -116,11 +110,8 @@ function readDir(path) { const array = core.jsonOpAsync( "op_read_dir_async", - { path: pathFromURL(path) }, - ) - .then( - res, - ); + pathFromURL(path), + ); return { async *[Symbol.asyncIterator]() { yield* await array; @@ -129,19 +120,19 @@ } function readLinkSync(path) { - return core.jsonOpSync("op_read_link_sync", { path: pathFromURL(path) }); + return core.jsonOpSync("op_read_link_sync", pathFromURL(path)); } function readLink(path) { - return core.jsonOpAsync("op_read_link_async", { path: pathFromURL(path) }); + return core.jsonOpAsync("op_read_link_async", pathFromURL(path)); } function realPathSync(path) { - return core.jsonOpSync("op_realpath_sync", { path }); + return core.jsonOpSync("op_realpath_sync", path); } function realPath(path) { - return core.jsonOpAsync("op_realpath_async", { path }); + return core.jsonOpAsync("op_realpath_async", path); } function removeSync( @@ -198,11 +189,11 @@ } function fstatSync(rid) { - return parseFileInfo(core.jsonOpSync("op_fstat_sync", { rid })); + return parseFileInfo(core.jsonOpSync("op_fstat_sync", rid)); } async function fstat(rid) { - return parseFileInfo(await core.jsonOpAsync("op_fstat_async", { rid })); + return parseFileInfo(await core.jsonOpAsync("op_fstat_async", rid)); } async function lstat(path) { @@ -262,7 +253,7 @@ } function umask(mask) { - return core.jsonOpSync("op_umask", { mask }); + return core.jsonOpSync("op_umask", mask); } function linkSync(oldpath, newpath) { @@ -359,19 +350,19 @@ } function fdatasyncSync(rid) { - core.jsonOpSync("op_fdatasync_sync", { rid }); + core.jsonOpSync("op_fdatasync_sync", rid); } async function fdatasync(rid) { - await core.jsonOpAsync("op_fdatasync_async", { rid }); + await core.jsonOpAsync("op_fdatasync_async", rid); } function fsyncSync(rid) { - core.jsonOpSync("op_fsync_sync", { rid }); + core.jsonOpSync("op_fsync_sync", rid); } async function fsync(rid) { - await core.jsonOpAsync("op_fsync_async", { rid }); + await core.jsonOpAsync("op_fsync_async", rid); } window.__bootstrap.fs = { diff --git a/runtime/js/30_net.js b/runtime/js/30_net.js index 9081d0ef1..56fb94f26 100644 --- a/runtime/js/30_net.js +++ b/runtime/js/30_net.js @@ -7,7 +7,7 @@ const { read, write } = window.__bootstrap.io; function shutdown(rid) { - return core.jsonOpAsync("op_shutdown", { rid }); + return core.jsonOpAsync("op_shutdown", rid); } function opAccept(rid, transport) { diff --git a/runtime/js/30_os.js b/runtime/js/30_os.js index 23c3d8de6..0ce831775 100644 --- a/runtime/js/30_os.js +++ b/runtime/js/30_os.js @@ -21,7 +21,12 @@ } function systemCpuInfo() { - return core.jsonOpSync("op_system_cpu_info"); + const { cores, speed } = core.jsonOpSync("op_system_cpu_info"); + // Map nulls to undefined for compatibility + return { + cores: cores ?? undefined, + speed: speed ?? undefined, + }; } // This is an internal only method used by the test harness to override the @@ -44,7 +49,7 @@ return; } - core.jsonOpSync("op_exit", { code }); + core.jsonOpSync("op_exit", code); throw new Error("Code not reachable"); } @@ -53,11 +58,11 @@ } function getEnv(key) { - return core.jsonOpSync("op_get_env", { key })[0]; + return core.jsonOpSync("op_get_env", key) ?? undefined; } function deleteEnv(key) { - core.jsonOpSync("op_delete_env", { key }); + core.jsonOpSync("op_delete_env", key); } const env = { diff --git a/runtime/js/40_fs_events.js b/runtime/js/40_fs_events.js index c48d410f1..06ad3a29c 100644 --- a/runtime/js/40_fs_events.js +++ b/runtime/js/40_fs_events.js @@ -19,9 +19,10 @@ async next() { try { - return await core.jsonOpAsync("op_fs_events_poll", { - rid: this.rid, - }); + const value = await core.jsonOpAsync("op_fs_events_poll", this.rid); + return value + ? { value, done: false } + : { value: undefined, done: true }; } catch (error) { if (error instanceof errors.BadResource) { return { value: undefined, done: true }; diff --git a/runtime/js/40_permissions.js b/runtime/js/40_permissions.js index d7ed5a433..7a81ca425 100644 --- a/runtime/js/40_permissions.js +++ b/runtime/js/40_permissions.js @@ -31,7 +31,7 @@ * @returns {Deno.PermissionState} */ function opQuery(desc) { - return core.jsonOpSync("op_query_permission", desc).state; + return core.jsonOpSync("op_query_permission", desc); } /** @@ -39,7 +39,7 @@ * @returns {Deno.PermissionState} */ function opRevoke(desc) { - return core.jsonOpSync("op_revoke_permission", desc).state; + return core.jsonOpSync("op_revoke_permission", desc); } /** @@ -47,7 +47,7 @@ * @returns {Deno.PermissionState} */ function opRequest(desc) { - return core.jsonOpSync("op_request_permission", desc).state; + return core.jsonOpSync("op_request_permission", desc); } class PermissionStatus extends EventTarget { diff --git a/runtime/js/40_plugins.js b/runtime/js/40_plugins.js index fd037b81f..5ebcfddad 100644 --- a/runtime/js/40_plugins.js +++ b/runtime/js/40_plugins.js @@ -5,7 +5,7 @@ const core = window.Deno.core; function openPlugin(filename) { - return core.jsonOpSync("op_open_plugin", { filename }); + return core.jsonOpSync("op_open_plugin", filename); } window.__bootstrap.plugins = { diff --git a/runtime/js/40_process.js b/runtime/js/40_process.js index 01f554b36..cd8015e94 100644 --- a/runtime/js/40_process.js +++ b/runtime/js/40_process.js @@ -12,7 +12,7 @@ } function opRunStatus(rid) { - return core.jsonOpAsync("op_run_status", { rid }); + return core.jsonOpAsync("op_run_status", rid); } function opRun(request) { diff --git a/runtime/js/40_signals.js b/runtime/js/40_signals.js index 2a70986f8..e222a9199 100644 --- a/runtime/js/40_signals.js +++ b/runtime/js/40_signals.js @@ -7,15 +7,15 @@ const { errors } = window.__bootstrap.errors; function bindSignal(signo) { - return core.jsonOpSync("op_signal_bind", { signo }); + return core.jsonOpSync("op_signal_bind", signo); } function pollSignal(rid) { - return core.jsonOpAsync("op_signal_poll", { rid }); + return core.jsonOpAsync("op_signal_poll", rid); } function unbindSignal(rid) { - core.jsonOpSync("op_signal_unbind", { rid }); + core.jsonOpSync("op_signal_unbind", rid); } // From `kill -l` @@ -209,21 +209,21 @@ #rid = 0; constructor(signo) { - this.#rid = bindSignal(signo).rid; + this.#rid = bindSignal(signo); this.#loop(); } #pollSignal = async () => { - let res; + let done; try { - res = await pollSignal(this.#rid); + done = await pollSignal(this.#rid); } catch (error) { if (error instanceof errors.BadResource) { return true; } throw error; } - return res.done; + return done; }; #loop = async () => { diff --git a/runtime/js/40_tls.js b/runtime/js/40_tls.js index e9f683376..da43afaac 100644 --- a/runtime/js/40_tls.js +++ b/runtime/js/40_tls.js @@ -12,7 +12,7 @@ } function opAcceptTLS(rid) { - return core.jsonOpAsync("op_accept_tls", { rid }); + return core.jsonOpAsync("op_accept_tls", rid); } function opListenTls(args) { diff --git a/runtime/js/40_tty.js b/runtime/js/40_tty.js index 2e98a4f5a..9b23b1ec1 100644 --- a/runtime/js/40_tty.js +++ b/runtime/js/40_tty.js @@ -5,11 +5,11 @@ const core = window.Deno.core; function consoleSize(rid) { - return core.jsonOpSync("op_console_size", { rid }); + return core.jsonOpSync("op_console_size", rid); } function isatty(rid) { - return core.jsonOpSync("op_isatty", { rid }); + return core.jsonOpSync("op_isatty", rid); } const DEFAULT_SET_RAW_OPTIONS = { diff --git a/runtime/js/99_main.js b/runtime/js/99_main.js index a2fff2571..596565bed 100644 --- a/runtime/js/99_main.js +++ b/runtime/js/99_main.js @@ -129,7 +129,7 @@ delete Object.prototype.__proto__; } function opPostMessage(data) { - core.jsonOpSync("op_worker_post_message", {}, data); + core.jsonOpSync("op_worker_post_message", null, data); } function opCloseWorker() { diff --git a/runtime/ops/fs.rs b/runtime/ops/fs.rs index bc166b4ad..d965f768d 100644 --- a/runtime/ops/fs.rs +++ b/runtime/ops/fs.rs @@ -7,9 +7,6 @@ use deno_core::error::bad_resource_id; use deno_core::error::custom_error; use deno_core::error::type_error; use deno_core::error::AnyError; -use deno_core::serde_json; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::OpState; use deno_core::RcRef; use deno_core::ResourceId; @@ -18,6 +15,7 @@ use deno_crypto::rand::thread_rng; use deno_crypto::rand::Rng; use log::debug; use serde::Deserialize; +use serde::Serialize; use std::cell::RefCell; use std::convert::From; use std::env::{current_dir, set_current_dir, temp_dir}; @@ -183,27 +181,27 @@ fn op_open_sync( state: &mut OpState, args: OpenArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<ResourceId, AnyError> { let (path, open_options) = open_helper(state, args)?; let std_file = open_options.open(path)?; let tokio_file = tokio::fs::File::from_std(std_file); let resource = StdFileResource::fs_file(tokio_file); let rid = state.resource_table.add(resource); - Ok(json!(rid)) + Ok(rid) } async fn op_open_async( state: Rc<RefCell<OpState>>, args: OpenArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<ResourceId, AnyError> { let (path, open_options) = open_helper(&mut state.borrow_mut(), args)?; let tokio_file = tokio::fs::OpenOptions::from(open_options) .open(path) .await?; let resource = StdFileResource::fs_file(tokio_file); let rid = state.borrow_mut().resource_table.add(resource); - Ok(json!(rid)) + Ok(rid) } #[derive(Deserialize)] @@ -235,7 +233,7 @@ fn op_seek_sync( state: &mut OpState, args: SeekArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<u64, AnyError> { let (rid, seek_from) = seek_helper(args)?; let pos = StdFileResource::with(state, rid, |r| match r { Ok(std_file) => std_file.seek(seek_from).map_err(AnyError::from), @@ -243,14 +241,14 @@ fn op_seek_sync( "cannot seek on this type of resource".to_string(), )), })?; - Ok(json!(pos)) + Ok(pos) } async fn op_seek_async( state: Rc<RefCell<OpState>>, args: SeekArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<u64, AnyError> { let (rid, seek_from) = seek_helper(args)?; let resource = state @@ -268,35 +266,26 @@ async fn op_seek_async( .await; let pos = (*fs_file).0.as_mut().unwrap().seek(seek_from).await?; - Ok(json!(pos)) -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FdatasyncArgs { - rid: ResourceId, + Ok(pos) } fn op_fdatasync_sync( state: &mut OpState, - args: FdatasyncArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let rid = args.rid; +) -> Result<(), AnyError> { StdFileResource::with(state, rid, |r| match r { Ok(std_file) => std_file.sync_data().map_err(AnyError::from), Err(_) => Err(type_error("cannot sync this type of resource".to_string())), })?; - Ok(json!({})) + Ok(()) } async fn op_fdatasync_async( state: Rc<RefCell<OpState>>, - args: FdatasyncArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let rid = args.rid; - +) -> Result<(), AnyError> { let resource = state .borrow_mut() .resource_table @@ -312,35 +301,26 @@ async fn op_fdatasync_async( .await; (*fs_file).0.as_mut().unwrap().sync_data().await?; - Ok(json!({})) -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FsyncArgs { - rid: ResourceId, + Ok(()) } fn op_fsync_sync( state: &mut OpState, - args: FsyncArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let rid = args.rid; +) -> Result<(), AnyError> { StdFileResource::with(state, rid, |r| match r { Ok(std_file) => std_file.sync_all().map_err(AnyError::from), Err(_) => Err(type_error("cannot sync this type of resource".to_string())), })?; - Ok(json!({})) + Ok(()) } async fn op_fsync_async( state: Rc<RefCell<OpState>>, - args: FsyncArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let rid = args.rid; - +) -> Result<(), AnyError> { let resource = state .borrow_mut() .resource_table @@ -356,37 +336,28 @@ async fn op_fsync_async( .await; (*fs_file).0.as_mut().unwrap().sync_all().await?; - Ok(json!({})) -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FstatArgs { - rid: ResourceId, + Ok(()) } fn op_fstat_sync( state: &mut OpState, - args: FstatArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<FsStat, AnyError> { super::check_unstable(state, "Deno.fstat"); - let metadata = StdFileResource::with(state, args.rid, |r| match r { + let metadata = StdFileResource::with(state, rid, |r| match r { Ok(std_file) => std_file.metadata().map_err(AnyError::from), Err(_) => Err(type_error("cannot stat this type of resource".to_string())), })?; - Ok(get_stat_json(metadata)) + Ok(get_stat(metadata)) } async fn op_fstat_async( state: Rc<RefCell<OpState>>, - args: FstatArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<FsStat, AnyError> { super::check_unstable2(&state, "Deno.fstat"); - - let rid = args.rid; - let resource = state .borrow_mut() .resource_table @@ -402,27 +373,22 @@ async fn op_fstat_async( .await; let metadata = (*fs_file).0.as_mut().unwrap().metadata().await?; - Ok(get_stat_json(metadata)) -} - -#[derive(Deserialize)] -pub struct UmaskArgs { - mask: Option<u32>, + Ok(get_stat(metadata)) } #[allow(clippy::unnecessary_wraps)] fn op_umask( state: &mut OpState, - args: UmaskArgs, + mask: Option<u32>, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<u32, AnyError> { super::check_unstable(state, "Deno.umask"); // TODO implement umask for Windows // see https://github.com/nodejs/node/blob/master/src/node_process_methods.cc // and https://docs.microsoft.com/fr-fr/cpp/c-runtime-library/reference/umask?view=vs-2019 #[cfg(not(unix))] { - let _ = args.mask; // avoid unused warning. + let _ = mask; // avoid unused warning. Err(not_supported()) } #[cfg(unix)] @@ -430,7 +396,7 @@ fn op_umask( use nix::sys::stat::mode_t; use nix::sys::stat::umask; use nix::sys::stat::Mode; - let r = if let Some(mask) = args.mask { + let r = if let Some(mask) = mask { // If mask provided, return previous. umask(Mode::from_bits_truncate(mask as mode_t)) } else { @@ -439,24 +405,19 @@ fn op_umask( let _ = umask(prev); prev }; - Ok(json!(r.bits() as u32)) + Ok(r.bits() as u32) } } -#[derive(Deserialize)] -pub struct ChdirArgs { - directory: String, -} - fn op_chdir( state: &mut OpState, - args: ChdirArgs, + directory: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let d = PathBuf::from(&args.directory); +) -> Result<(), AnyError> { + let d = PathBuf::from(&directory); state.borrow::<Permissions>().read.check(&d)?; set_current_dir(&d)?; - Ok(json!({})) + Ok(()) } #[derive(Deserialize)] @@ -471,7 +432,7 @@ fn op_mkdir_sync( state: &mut OpState, args: MkdirArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = Path::new(&args.path).to_path_buf(); let mode = args.mode.unwrap_or(0o777) & 0o777; state.borrow::<Permissions>().write.check(&path)?; @@ -484,14 +445,14 @@ fn op_mkdir_sync( builder.mode(mode); } builder.create(path)?; - Ok(json!({})) + Ok(()) } async fn op_mkdir_async( state: Rc<RefCell<OpState>>, args: MkdirArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = Path::new(&args.path).to_path_buf(); let mode = args.mode.unwrap_or(0o777) & 0o777; @@ -510,7 +471,7 @@ async fn op_mkdir_async( builder.mode(mode); } builder.create(path)?; - Ok(json!({})) + Ok(()) }) .await .unwrap() @@ -527,7 +488,7 @@ fn op_chmod_sync( state: &mut OpState, args: ChmodArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = Path::new(&args.path).to_path_buf(); let mode = args.mode & 0o777; @@ -538,7 +499,7 @@ fn op_chmod_sync( use std::os::unix::fs::PermissionsExt; let permissions = PermissionsExt::from_mode(mode); std::fs::set_permissions(&path, permissions)?; - Ok(json!({})) + Ok(()) } // TODO Implement chmod for Windows (#4357) #[cfg(not(unix))] @@ -553,7 +514,7 @@ async fn op_chmod_async( state: Rc<RefCell<OpState>>, args: ChmodArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = Path::new(&args.path).to_path_buf(); let mode = args.mode & 0o777; @@ -569,7 +530,7 @@ async fn op_chmod_async( use std::os::unix::fs::PermissionsExt; let permissions = PermissionsExt::from_mode(mode); std::fs::set_permissions(&path, permissions)?; - Ok(json!({})) + Ok(()) } // TODO Implement chmod for Windows (#4357) #[cfg(not(unix))] @@ -595,7 +556,7 @@ fn op_chown_sync( state: &mut OpState, args: ChownArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = Path::new(&args.path).to_path_buf(); state.borrow::<Permissions>().write.check(&path)?; debug!( @@ -610,7 +571,7 @@ fn op_chown_sync( let nix_uid = args.uid.map(Uid::from_raw); let nix_gid = args.gid.map(Gid::from_raw); chown(&path, nix_uid, nix_gid)?; - Ok(json!({})) + Ok(()) } // TODO Implement chown for Windows #[cfg(not(unix))] @@ -623,7 +584,7 @@ async fn op_chown_async( state: Rc<RefCell<OpState>>, args: ChownArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = Path::new(&args.path).to_path_buf(); { @@ -644,7 +605,7 @@ async fn op_chown_async( let nix_uid = args.uid.map(Uid::from_raw); let nix_gid = args.gid.map(Gid::from_raw); chown(&path, nix_uid, nix_gid)?; - Ok(json!({})) + Ok(()) } // TODO Implement chown for Windows #[cfg(not(unix))] @@ -665,7 +626,7 @@ fn op_remove_sync( state: &mut OpState, args: RemoveArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = PathBuf::from(&args.path); let recursive = args.recursive; @@ -700,14 +661,14 @@ fn op_remove_sync( // pipes, sockets, etc... std::fs::remove_file(&path)?; } - Ok(json!({})) + Ok(()) } async fn op_remove_async( state: Rc<RefCell<OpState>>, args: RemoveArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = PathBuf::from(&args.path); let recursive = args.recursive; @@ -746,7 +707,7 @@ async fn op_remove_async( // pipes, sockets, etc... std::fs::remove_file(&path)?; } - Ok(json!({})) + Ok(()) }) .await .unwrap() @@ -763,7 +724,7 @@ fn op_copy_file_sync( state: &mut OpState, args: CopyFileArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let from = PathBuf::from(&args.from); let to = PathBuf::from(&args.to); @@ -781,14 +742,14 @@ fn op_copy_file_sync( // returns size of from as u64 (we ignore) std::fs::copy(&from, &to)?; - Ok(json!({})) + Ok(()) } async fn op_copy_file_async( state: Rc<RefCell<OpState>>, args: CopyFileArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let from = PathBuf::from(&args.from); let to = PathBuf::from(&args.to); @@ -810,29 +771,50 @@ async fn op_copy_file_async( // returns size of from as u64 (we ignore) std::fs::copy(&from, &to)?; - Ok(json!({})) + Ok(()) }) .await .unwrap() } -fn to_msec(maybe_time: Result<SystemTime, io::Error>) -> Value { +fn to_msec(maybe_time: Result<SystemTime, io::Error>) -> Option<u64> { match maybe_time { Ok(time) => { let msec = time .duration_since(UNIX_EPOCH) - .map(|t| t.as_secs_f64() * 1000f64) - .unwrap_or_else(|err| err.duration().as_secs_f64() * -1000f64); - serde_json::Number::from_f64(msec) - .map(Value::Number) - .unwrap_or(Value::Null) + .map(|t| t.as_millis() as u64) + .unwrap_or_else(|err| err.duration().as_millis() as u64); + Some(msec) } - Err(_) => Value::Null, + Err(_) => None, } } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FsStat { + is_file: bool, + is_directory: bool, + is_symlink: bool, + size: u64, + // In milliseconds, like JavaScript. Available on both Unix or Windows. + mtime: Option<u64>, + atime: Option<u64>, + birthtime: Option<u64>, + // Following are only valid under Unix. + dev: u64, + ino: u64, + mode: u32, + nlink: u64, + uid: u32, + gid: u32, + rdev: u64, + blksize: u64, + blocks: u64, +} + #[inline(always)] -fn get_stat_json(metadata: std::fs::Metadata) -> Value { +fn get_stat(metadata: std::fs::Metadata) -> FsStat { // Unix stat member (number types only). 0 if not on unix. macro_rules! usm { ($member:ident) => {{ @@ -849,29 +831,26 @@ fn get_stat_json(metadata: std::fs::Metadata) -> Value { #[cfg(unix)] use std::os::unix::fs::MetadataExt; - let json_val = json!({ - "isFile": metadata.is_file(), - "isDirectory": metadata.is_dir(), - "isSymlink": metadata.file_type().is_symlink(), - "size": metadata.len(), + FsStat { + is_file: metadata.is_file(), + is_directory: metadata.is_dir(), + is_symlink: metadata.file_type().is_symlink(), + size: metadata.len(), // In milliseconds, like JavaScript. Available on both Unix or Windows. - "mtime": to_msec(metadata.modified()), - "atime": to_msec(metadata.accessed()), - "birthtime": to_msec(metadata.created()), + mtime: to_msec(metadata.modified()), + atime: to_msec(metadata.accessed()), + birthtime: to_msec(metadata.created()), // Following are only valid under Unix. - "dev": usm!(dev), - "ino": usm!(ino), - "mode": usm!(mode), - "nlink": usm!(nlink), - "uid": usm!(uid), - "gid": usm!(gid), - "rdev": usm!(rdev), - // TODO(kevinkassimo): *time_nsec requires BigInt. - // Probably should be treated as String if we need to add them. - "blksize": usm!(blksize), - "blocks": usm!(blocks), - }); - json_val + dev: usm!(dev), + ino: usm!(ino), + mode: usm!(mode), + nlink: usm!(nlink), + uid: usm!(uid), + gid: usm!(gid), + rdev: usm!(rdev), + blksize: usm!(blksize), + blocks: usm!(blocks), + } } #[derive(Deserialize)] @@ -885,7 +864,7 @@ fn op_stat_sync( state: &mut OpState, args: StatArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<FsStat, AnyError> { let path = PathBuf::from(&args.path); let lstat = args.lstat; state.borrow::<Permissions>().read.check(&path)?; @@ -895,14 +874,14 @@ fn op_stat_sync( } else { std::fs::metadata(&path)? }; - Ok(get_stat_json(metadata)) + Ok(get_stat(metadata)) } async fn op_stat_async( state: Rc<RefCell<OpState>>, args: StatArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<FsStat, AnyError> { let path = PathBuf::from(&args.path); let lstat = args.lstat; @@ -918,24 +897,18 @@ async fn op_stat_async( } else { std::fs::metadata(&path)? }; - Ok(get_stat_json(metadata)) + Ok(get_stat(metadata)) }) .await .unwrap() } -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct RealpathArgs { - path: String, -} - fn op_realpath_sync( state: &mut OpState, - args: RealpathArgs, + path: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let path = PathBuf::from(&args.path); +) -> Result<String, AnyError> { + let path = PathBuf::from(&path); let permissions = state.borrow::<Permissions>(); permissions.read.check(&path)?; @@ -948,15 +921,15 @@ fn op_realpath_sync( // CreateFile and GetFinalPathNameByHandle on Windows let realpath = canonicalize_path(&path)?; let realpath_str = into_string(realpath.into_os_string())?; - Ok(json!(realpath_str)) + Ok(realpath_str) } async fn op_realpath_async( state: Rc<RefCell<OpState>>, - args: RealpathArgs, + path: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let path = PathBuf::from(&args.path); +) -> Result<String, AnyError> { + let path = PathBuf::from(&path); { let state = state.borrow(); @@ -973,24 +946,27 @@ async fn op_realpath_async( // CreateFile and GetFinalPathNameByHandle on Windows let realpath = canonicalize_path(&path)?; let realpath_str = into_string(realpath.into_os_string())?; - Ok(json!(realpath_str)) + Ok(realpath_str) }) .await .unwrap() } -#[derive(Deserialize)] +#[derive(Serialize)] #[serde(rename_all = "camelCase")] -pub struct ReadDirArgs { - path: String, +pub struct DirEntry { + name: String, + is_file: bool, + is_directory: bool, + is_symlink: bool, } fn op_read_dir_sync( state: &mut OpState, - args: ReadDirArgs, + path: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let path = PathBuf::from(&args.path); +) -> Result<Vec<DirEntry>, AnyError> { + let path = PathBuf::from(&path); state.borrow::<Permissions>().read.check(&path)?; @@ -1000,27 +976,33 @@ fn op_read_dir_sync( let entry = entry.unwrap(); // Not all filenames can be encoded as UTF-8. Skip those for now. if let Ok(name) = into_string(entry.file_name()) { - Some(json!({ - "name": name, - "isFile": entry.file_type().map_or(false, |file_type| file_type.is_file()), - "isDirectory": entry.file_type().map_or(false, |file_type| file_type.is_dir()), - "isSymlink": entry.file_type().map_or(false, |file_type| file_type.is_symlink()), - })) + Some(DirEntry { + name, + is_file: entry + .file_type() + .map_or(false, |file_type| file_type.is_file()), + is_directory: entry + .file_type() + .map_or(false, |file_type| file_type.is_dir()), + is_symlink: entry + .file_type() + .map_or(false, |file_type| file_type.is_symlink()), + }) } else { None } }) - .collect(); + .collect(); - Ok(json!({ "entries": entries })) + Ok(entries) } async fn op_read_dir_async( state: Rc<RefCell<OpState>>, - args: ReadDirArgs, + path: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let path = PathBuf::from(&args.path); +) -> Result<Vec<DirEntry>, AnyError> { + let path = PathBuf::from(&path); { let state = state.borrow(); state.borrow::<Permissions>().read.check(&path)?; @@ -1032,22 +1014,28 @@ async fn op_read_dir_async( let entry = entry.unwrap(); // Not all filenames can be encoded as UTF-8. Skip those for now. if let Ok(name) = into_string(entry.file_name()) { - Some(json!({ - "name": name, - "isFile": entry.file_type().map_or(false, |file_type| file_type.is_file()), - "isDirectory": entry.file_type().map_or(false, |file_type| file_type.is_dir()), - "isSymlink": entry.file_type().map_or(false, |file_type| file_type.is_symlink()), - })) + Some(DirEntry { + name, + is_file: entry + .file_type() + .map_or(false, |file_type| file_type.is_file()), + is_directory: entry + .file_type() + .map_or(false, |file_type| file_type.is_dir()), + is_symlink: entry + .file_type() + .map_or(false, |file_type| file_type.is_symlink()), + }) } else { None } }) - .collect(); + .collect(); - Ok(json!({ "entries": entries })) + Ok(entries) }) .await - .unwrap() + .unwrap() } #[derive(Deserialize)] @@ -1061,7 +1049,7 @@ fn op_rename_sync( state: &mut OpState, args: RenameArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let oldpath = PathBuf::from(&args.oldpath); let newpath = PathBuf::from(&args.newpath); @@ -1071,14 +1059,14 @@ fn op_rename_sync( permissions.write.check(&newpath)?; debug!("op_rename_sync {} {}", oldpath.display(), newpath.display()); std::fs::rename(&oldpath, &newpath)?; - Ok(json!({})) + Ok(()) } async fn op_rename_async( state: Rc<RefCell<OpState>>, args: RenameArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let oldpath = PathBuf::from(&args.oldpath); let newpath = PathBuf::from(&args.newpath); { @@ -1095,7 +1083,7 @@ async fn op_rename_async( newpath.display() ); std::fs::rename(&oldpath, &newpath)?; - Ok(json!({})) + Ok(()) }) .await .unwrap() @@ -1112,7 +1100,7 @@ fn op_link_sync( state: &mut OpState, args: LinkArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let oldpath = PathBuf::from(&args.oldpath); let newpath = PathBuf::from(&args.newpath); @@ -1124,14 +1112,14 @@ fn op_link_sync( debug!("op_link_sync {} {}", oldpath.display(), newpath.display()); std::fs::hard_link(&oldpath, &newpath)?; - Ok(json!({})) + Ok(()) } async fn op_link_async( state: Rc<RefCell<OpState>>, args: LinkArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let oldpath = PathBuf::from(&args.oldpath); let newpath = PathBuf::from(&args.newpath); @@ -1147,7 +1135,7 @@ async fn op_link_async( tokio::task::spawn_blocking(move || { debug!("op_link_async {} {}", oldpath.display(), newpath.display()); std::fs::hard_link(&oldpath, &newpath)?; - Ok(json!({})) + Ok(()) }) .await .unwrap() @@ -1173,7 +1161,7 @@ fn op_symlink_sync( state: &mut OpState, args: SymlinkArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let oldpath = PathBuf::from(&args.oldpath); let newpath = PathBuf::from(&args.newpath); @@ -1188,7 +1176,7 @@ fn op_symlink_sync( { use std::os::unix::fs::symlink; symlink(&oldpath, &newpath)?; - Ok(json!({})) + Ok(()) } #[cfg(not(unix))] { @@ -1214,7 +1202,7 @@ fn op_symlink_sync( } } }; - Ok(json!({})) + Ok(()) } } @@ -1222,7 +1210,7 @@ async fn op_symlink_async( state: Rc<RefCell<OpState>>, args: SymlinkArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let oldpath = PathBuf::from(&args.oldpath); let newpath = PathBuf::from(&args.newpath); @@ -1237,7 +1225,7 @@ async fn op_symlink_async( { use std::os::unix::fs::symlink; symlink(&oldpath, &newpath)?; - Ok(json!({})) + Ok(()) } #[cfg(not(unix))] { @@ -1263,40 +1251,34 @@ async fn op_symlink_async( } } }; - Ok(json!({})) + Ok(()) } }) .await .unwrap() } -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ReadLinkArgs { - path: String, -} - fn op_read_link_sync( state: &mut OpState, - args: ReadLinkArgs, + path: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let path = PathBuf::from(&args.path); +) -> Result<String, AnyError> { + let path = PathBuf::from(&path); state.borrow::<Permissions>().read.check(&path)?; debug!("op_read_link_value {}", path.display()); let target = std::fs::read_link(&path)?.into_os_string(); let targetstr = into_string(target)?; - Ok(json!(targetstr)) + Ok(targetstr) } async fn op_read_link_async( state: Rc<RefCell<OpState>>, - args: ReadLinkArgs, + path: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let path = PathBuf::from(&args.path); +) -> Result<String, AnyError> { + let path = PathBuf::from(&path); { let state = state.borrow(); state.borrow::<Permissions>().read.check(&path)?; @@ -1305,7 +1287,7 @@ async fn op_read_link_async( debug!("op_read_link_async {}", path.display()); let target = std::fs::read_link(&path)?.into_os_string(); let targetstr = into_string(target)?; - Ok(json!(targetstr)) + Ok(targetstr) }) .await .unwrap() @@ -1322,7 +1304,7 @@ fn op_ftruncate_sync( state: &mut OpState, args: FtruncateArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.ftruncate"); let rid = args.rid; let len = args.len as u64; @@ -1330,14 +1312,14 @@ fn op_ftruncate_sync( Ok(std_file) => std_file.set_len(len).map_err(AnyError::from), Err(_) => Err(type_error("cannot truncate this type of resource")), })?; - Ok(json!({})) + Ok(()) } async fn op_ftruncate_async( state: Rc<RefCell<OpState>>, args: FtruncateArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable2(&state, "Deno.ftruncate"); let rid = args.rid; let len = args.len as u64; @@ -1357,7 +1339,7 @@ async fn op_ftruncate_async( .await; (*fs_file).0.as_mut().unwrap().set_len(len).await?; - Ok(json!({})) + Ok(()) } #[derive(Deserialize)] @@ -1371,7 +1353,7 @@ fn op_truncate_sync( state: &mut OpState, args: TruncateArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = PathBuf::from(&args.path); let len = args.len; @@ -1380,14 +1362,14 @@ fn op_truncate_sync( debug!("op_truncate_sync {} {}", path.display(), len); let f = std::fs::OpenOptions::new().write(true).open(&path)?; f.set_len(len)?; - Ok(json!({})) + Ok(()) } async fn op_truncate_async( state: Rc<RefCell<OpState>>, args: TruncateArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let path = PathBuf::from(&args.path); let len = args.len; { @@ -1398,7 +1380,7 @@ async fn op_truncate_async( debug!("op_truncate_async {} {}", path.display(), len); let f = std::fs::OpenOptions::new().write(true).open(&path)?; f.set_len(len)?; - Ok(json!({})) + Ok(()) }) .await .unwrap() @@ -1461,7 +1443,7 @@ fn op_make_temp_dir_sync( state: &mut OpState, args: MakeTempArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let dir = args.dir.map(|s| PathBuf::from(&s)); let prefix = args.prefix.map(String::from); let suffix = args.suffix.map(String::from); @@ -1483,14 +1465,14 @@ fn op_make_temp_dir_sync( )?; let path_str = into_string(path.into_os_string())?; - Ok(json!(path_str)) + Ok(path_str) } async fn op_make_temp_dir_async( state: Rc<RefCell<OpState>>, args: MakeTempArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let dir = args.dir.map(|s| PathBuf::from(&s)); let prefix = args.prefix.map(String::from); let suffix = args.suffix.map(String::from); @@ -1514,7 +1496,7 @@ async fn op_make_temp_dir_async( )?; let path_str = into_string(path.into_os_string())?; - Ok(json!(path_str)) + Ok(path_str) }) .await .unwrap() @@ -1524,7 +1506,7 @@ fn op_make_temp_file_sync( state: &mut OpState, args: MakeTempArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let dir = args.dir.map(|s| PathBuf::from(&s)); let prefix = args.prefix.map(String::from); let suffix = args.suffix.map(String::from); @@ -1546,14 +1528,14 @@ fn op_make_temp_file_sync( )?; let path_str = into_string(path.into_os_string())?; - Ok(json!(path_str)) + Ok(path_str) } async fn op_make_temp_file_async( state: Rc<RefCell<OpState>>, args: MakeTempArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let dir = args.dir.map(|s| PathBuf::from(&s)); let prefix = args.prefix.map(String::from); let suffix = args.suffix.map(String::from); @@ -1577,7 +1559,7 @@ async fn op_make_temp_file_async( )?; let path_str = into_string(path.into_os_string())?; - Ok(json!(path_str)) + Ok(path_str) }) .await .unwrap() @@ -1595,7 +1577,7 @@ fn op_futime_sync( state: &mut OpState, args: FutimeArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.futimeSync"); let rid = args.rid; let atime = filetime::FileTime::from_unix_time(args.atime.0, args.atime.1); @@ -1611,14 +1593,14 @@ fn op_futime_sync( )), })?; - Ok(json!({})) + Ok(()) } async fn op_futime_async( state: Rc<RefCell<OpState>>, args: FutimeArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable2(&state, "Deno.futime"); let rid = args.rid; let atime = filetime::FileTime::from_unix_time(args.atime.0, args.atime.1); @@ -1649,7 +1631,7 @@ async fn op_futime_async( tokio::task::spawn_blocking(move || { filetime::set_file_handle_times(&std_file, Some(atime), Some(mtime))?; - Ok(json!({})) + Ok(()) }) .await .unwrap() @@ -1667,7 +1649,7 @@ fn op_utime_sync( state: &mut OpState, args: UtimeArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.utime"); let path = PathBuf::from(&args.path); @@ -1676,14 +1658,14 @@ fn op_utime_sync( state.borrow::<Permissions>().write.check(&path)?; filetime::set_file_times(path, atime, mtime)?; - Ok(json!({})) + Ok(()) } async fn op_utime_async( state: Rc<RefCell<OpState>>, args: UtimeArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable(&state.borrow(), "Deno.utime"); let path = PathBuf::from(&args.path); @@ -1694,7 +1676,7 @@ async fn op_utime_async( tokio::task::spawn_blocking(move || { filetime::set_file_times(path, atime, mtime)?; - Ok(json!({})) + Ok(()) }) .await .unwrap() @@ -1702,14 +1684,14 @@ async fn op_utime_async( fn op_cwd( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let path = current_dir()?; state .borrow::<Permissions>() .read .check_blind(&path, "CWD")?; let path_str = into_string(path.into_os_string())?; - Ok(json!(path_str)) + Ok(path_str) } diff --git a/runtime/ops/fs_events.rs b/runtime/ops/fs_events.rs index fed28a3d2..a64f31a33 100644 --- a/runtime/ops/fs_events.rs +++ b/runtime/ops/fs_events.rs @@ -3,8 +3,6 @@ use crate::permissions::Permissions; use deno_core::error::bad_resource_id; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::AsyncRefCell; use deno_core::CancelFuture; use deno_core::CancelHandle; @@ -93,7 +91,7 @@ fn op_fs_events_open( state: &mut OpState, args: OpenArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<ResourceId, AnyError> { let (sender, receiver) = mpsc::channel::<Result<FsEvent, AnyError>>(16); let sender = std::sync::Mutex::new(sender); let mut watcher: RecommendedWatcher = @@ -122,30 +120,25 @@ fn op_fs_events_open( cancel: Default::default(), }; let rid = state.resource_table.add(resource); - Ok(json!(rid)) -} - -#[derive(Deserialize)] -pub struct PollArgs { - rid: ResourceId, + Ok(rid) } async fn op_fs_events_poll( state: Rc<RefCell<OpState>>, - args: PollArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<Option<FsEvent>, AnyError> { let resource = state .borrow() .resource_table - .get::<FsEventsResource>(args.rid) + .get::<FsEventsResource>(rid) .ok_or_else(bad_resource_id)?; let mut receiver = RcRef::map(&resource, |r| &r.receiver).borrow_mut().await; let cancel = RcRef::map(resource, |r| &r.cancel); let maybe_result = receiver.recv().or_cancel(cancel).await?; match maybe_result { - Some(Ok(value)) => Ok(json!({ "value": value, "done": false })), + Some(Ok(value)) => Ok(Some(value)), Some(Err(err)) => Err(err), - None => Ok(json!({ "done": true })), + None => Ok(None), } } diff --git a/runtime/ops/io.rs b/runtime/ops/io.rs index e5a571f81..f8ab92704 100644 --- a/runtime/ops/io.rs +++ b/runtime/ops/io.rs @@ -4,8 +4,6 @@ use deno_core::error::null_opbuf; use deno_core::error::resource_unavailable; use deno_core::error::AnyError; use deno_core::error::{bad_resource_id, not_supported}; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::AsyncMutFuture; use deno_core::AsyncRefCell; use deno_core::CancelHandle; @@ -16,7 +14,6 @@ use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::ZeroCopyBuf; -use serde::Deserialize; use std::borrow::Cow; use std::cell::RefCell; use std::io::Read; @@ -610,20 +607,15 @@ async fn op_write_async( Ok(nwritten as u32) } -#[derive(Deserialize)] -struct ShutdownArgs { - rid: ResourceId, -} - async fn op_shutdown( state: Rc<RefCell<OpState>>, - args: ShutdownArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let resource = state .borrow() .resource_table - .get_any(args.rid) + .get_any(rid) .ok_or_else(bad_resource_id)?; if let Some(s) = resource.downcast_rc::<ChildStdinResource>() { s.shutdown().await?; @@ -638,5 +630,5 @@ async fn op_shutdown( } else { return Err(not_supported()); } - Ok(json!({})) + Ok(()) } diff --git a/runtime/ops/net.rs b/runtime/ops/net.rs index 7d81fcee0..224fb5570 100644 --- a/runtime/ops/net.rs +++ b/runtime/ops/net.rs @@ -9,7 +9,6 @@ use deno_core::error::generic_error; use deno_core::error::null_opbuf; use deno_core::error::type_error; use deno_core::error::AnyError; -use deno_core::serde_json; use deno_core::serde_json::json; use deno_core::serde_json::Value; use deno_core::AsyncRefCell; @@ -109,10 +108,9 @@ async fn accept_tcp( async fn op_accept( state: Rc<RefCell<OpState>>, - args: Value, + args: AcceptArgs, _buf: Option<ZeroCopyBuf>, ) -> Result<Value, AnyError> { - let args: AcceptArgs = serde_json::from_value(args)?; match args.transport.as_str() { "tcp" => accept_tcp(state, args, _buf).await, #[cfg(unix)] @@ -163,10 +161,9 @@ async fn receive_udp( async fn op_datagram_receive( state: Rc<RefCell<OpState>>, - args: Value, + args: ReceiveArgs, zero_copy: Option<ZeroCopyBuf>, ) -> Result<Value, AnyError> { - let args: ReceiveArgs = serde_json::from_value(args)?; match args.transport.as_str() { "udp" => receive_udp(state, args, zero_copy).await, #[cfg(unix)] @@ -188,13 +185,13 @@ struct SendArgs { async fn op_datagram_send( state: Rc<RefCell<OpState>>, - args: Value, + args: SendArgs, zero_copy: Option<ZeroCopyBuf>, ) -> Result<Value, AnyError> { let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let zero_copy = zero_copy.clone(); - match serde_json::from_value(args)? { + match args { SendArgs { rid, transport, @@ -257,10 +254,10 @@ struct ConnectArgs { async fn op_connect( state: Rc<RefCell<OpState>>, - args: Value, + args: ConnectArgs, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<Value, AnyError> { - match serde_json::from_value(args)? { + match args { ConnectArgs { transport, transport_args: ArgsEnum::Ip(args), @@ -421,11 +418,11 @@ fn listen_udp( fn op_listen( state: &mut OpState, - args: Value, + args: ListenArgs, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<Value, AnyError> { let permissions = state.borrow::<Permissions>(); - match serde_json::from_value(args)? { + match args { ListenArgs { transport, transport_args: ArgsEnum::Ip(args), diff --git a/runtime/ops/net_unix.rs b/runtime/ops/net_unix.rs index 0cc001ab4..86c5ab8a0 100644 --- a/runtime/ops/net_unix.rs +++ b/runtime/ops/net_unix.rs @@ -17,6 +17,7 @@ use deno_core::RcRef; use deno_core::Resource; use deno_core::ZeroCopyBuf; use serde::Deserialize; +use serde::Serialize; use std::borrow::Cow; use std::cell::RefCell; use std::fs::remove_file; @@ -56,6 +57,12 @@ impl Resource for UnixDatagramResource { } } +#[derive(Serialize)] +pub struct UnixAddr { + pub path: String, + pub transport: String, +} + #[derive(Deserialize)] pub struct UnixListenArgs { pub path: String, diff --git a/runtime/ops/os.rs b/runtime/ops/os.rs index 500c023aa..3e6feacfe 100644 --- a/runtime/ops/os.rs +++ b/runtime/ops/os.rs @@ -1,13 +1,12 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use crate::permissions::Permissions; -use deno_core::error::{type_error, AnyError}; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; +use deno_core::error::{custom_error, type_error, AnyError}; use deno_core::url::Url; use deno_core::OpState; use deno_core::ZeroCopyBuf; use serde::Deserialize; +use serde::Serialize; use std::collections::HashMap; use std::env; @@ -27,9 +26,9 @@ pub fn init(rt: &mut deno_core::JsRuntime) { fn op_exec_path( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let current_exe = env::current_exe().unwrap(); state .borrow::<Permissions>() @@ -39,7 +38,16 @@ fn op_exec_path( // we might get `./` and `../` bits in `exec_path` let exe_url = Url::from_file_path(current_exe).unwrap(); let path = exe_url.to_file_path().unwrap(); - Ok(json!(path)) + + into_string(path.into_os_string()) +} + +// TODO(@AaronO): share this code with fs' into_string() +fn into_string(s: std::ffi::OsString) -> Result<String, AnyError> { + s.into_string().map_err(|s| { + let message = format!("File name or path {:?} is not valid UTF-8", s); + custom_error("InvalidData", message) + }) } #[derive(Deserialize)] @@ -52,7 +60,7 @@ fn op_set_env( state: &mut OpState, args: SetEnv, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { state.borrow::<Permissions>().env.check()?; let invalid_key = args.key.is_empty() || args.key.contains(&['=', '\0'] as &[char]); @@ -61,140 +69,139 @@ fn op_set_env( return Err(type_error("Key or value contains invalid characters.")); } env::set_var(args.key, args.value); - Ok(json!({})) + Ok(()) } fn op_env( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<HashMap<String, String>, AnyError> { state.borrow::<Permissions>().env.check()?; - let v = env::vars().collect::<HashMap<String, String>>(); - Ok(json!(v)) -} - -#[derive(Deserialize)] -pub struct GetEnv { - key: String, + Ok(env::vars().collect()) } fn op_get_env( state: &mut OpState, - args: GetEnv, + key: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<Option<String>, AnyError> { state.borrow::<Permissions>().env.check()?; - if args.key.is_empty() || args.key.contains(&['=', '\0'] as &[char]) { + if key.is_empty() || key.contains(&['=', '\0'] as &[char]) { return Err(type_error("Key contains invalid characters.")); } - let r = match env::var(args.key) { - Err(env::VarError::NotPresent) => json!([]), - v => json!([v?]), + let r = match env::var(key) { + Err(env::VarError::NotPresent) => None, + v => Some(v?), }; Ok(r) } - -#[derive(Deserialize)] -pub struct DeleteEnv { - key: String, -} - fn op_delete_env( state: &mut OpState, - args: DeleteEnv, + key: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { state.borrow::<Permissions>().env.check()?; - if args.key.is_empty() || args.key.contains(&['=', '\0'] as &[char]) { + if key.is_empty() || key.contains(&['=', '\0'] as &[char]) { return Err(type_error("Key contains invalid characters.")); } - env::remove_var(args.key); - Ok(json!({})) -} - -#[derive(Deserialize)] -pub struct Exit { - code: i32, + env::remove_var(key); + Ok(()) } fn op_exit( _state: &mut OpState, - args: Exit, + code: i32, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - std::process::exit(args.code) +) -> Result<(), AnyError> { + std::process::exit(code) } fn op_loadavg( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(f64, f64, f64), AnyError> { super::check_unstable(state, "Deno.loadavg"); state.borrow::<Permissions>().env.check()?; match sys_info::loadavg() { - Ok(loadavg) => Ok(json!([loadavg.one, loadavg.five, loadavg.fifteen])), - Err(_) => Ok(json!([0f64, 0f64, 0f64])), + Ok(loadavg) => Ok((loadavg.one, loadavg.five, loadavg.fifteen)), + Err(_) => Ok((0.0, 0.0, 0.0)), } } fn op_hostname( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { super::check_unstable(state, "Deno.hostname"); state.borrow::<Permissions>().env.check()?; let hostname = sys_info::hostname().unwrap_or_else(|_| "".to_string()); - Ok(json!(hostname)) + Ok(hostname) } fn op_os_release( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { super::check_unstable(state, "Deno.osRelease"); state.borrow::<Permissions>().env.check()?; let release = sys_info::os_release().unwrap_or_else(|_| "".to_string()); - Ok(json!(release)) + Ok(release) +} + +// Copied from sys-info/lib.rs (then tweaked) +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct MemInfo { + pub total: u64, + pub free: u64, + pub available: u64, + pub buffers: u64, + pub cached: u64, + pub swap_total: u64, + pub swap_free: u64, } fn op_system_memory_info( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<Option<MemInfo>, AnyError> { super::check_unstable(state, "Deno.systemMemoryInfo"); state.borrow::<Permissions>().env.check()?; match sys_info::mem_info() { - Ok(info) => Ok(json!({ - "total": info.total, - "free": info.free, - "available": info.avail, - "buffers": info.buffers, - "cached": info.cached, - "swapTotal": info.swap_total, - "swapFree": info.swap_free + Ok(info) => Ok(Some(MemInfo { + total: info.total, + free: info.free, + available: info.avail, + buffers: info.buffers, + cached: info.cached, + swap_total: info.swap_total, + swap_free: info.swap_free, })), - Err(_) => Ok(json!({})), + Err(_) => Ok(None), } } +#[derive(Serialize)] +struct CpuInfo { + cores: Option<u32>, + speed: Option<u64>, +} + fn op_system_cpu_info( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<CpuInfo, AnyError> { super::check_unstable(state, "Deno.systemCpuInfo"); state.borrow::<Permissions>().env.check()?; let cores = sys_info::cpu_num().ok(); let speed = sys_info::cpu_speed().ok(); - Ok(json!({ - "cores": cores, - "speed": speed - })) + Ok(CpuInfo { cores, speed }) } diff --git a/runtime/ops/permissions.rs b/runtime/ops/permissions.rs index 61eed6bf4..be8c9974c 100644 --- a/runtime/ops/permissions.rs +++ b/runtime/ops/permissions.rs @@ -4,8 +4,6 @@ use crate::permissions::Permissions; use deno_core::error::custom_error; use deno_core::error::uri_error; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::url; use deno_core::OpState; use deno_core::ZeroCopyBuf; @@ -29,7 +27,7 @@ pub fn op_query_permission( state: &mut OpState, args: PermissionArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let permissions = state.borrow::<Permissions>(); let path = args.path.as_deref(); let perm = match args.name.as_ref() { @@ -53,14 +51,14 @@ pub fn op_query_permission( )) } }; - Ok(json!({ "state": perm.to_string() })) + Ok(perm.to_string()) } pub fn op_revoke_permission( state: &mut OpState, args: PermissionArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let permissions = state.borrow_mut::<Permissions>(); let path = args.path.as_deref(); let perm = match args.name.as_ref() { @@ -84,14 +82,14 @@ pub fn op_revoke_permission( )) } }; - Ok(json!({ "state": perm.to_string() })) + Ok(perm.to_string()) } pub fn op_request_permission( state: &mut OpState, args: PermissionArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let permissions = state.borrow_mut::<Permissions>(); let path = args.path.as_deref(); let perm = match args.name.as_ref() { @@ -115,7 +113,7 @@ pub fn op_request_permission( )) } }; - Ok(json!({ "state": perm.to_string() })) + Ok(perm.to_string()) } fn parse_host(host_str: &str) -> Result<(String, Option<u16>), AnyError> { diff --git a/runtime/ops/plugin.rs b/runtime/ops/plugin.rs index 709c5730d..0397dbca3 100644 --- a/runtime/ops/plugin.rs +++ b/runtime/ops/plugin.rs @@ -4,8 +4,6 @@ use crate::permissions::Permissions; use deno_core::error::AnyError; use deno_core::futures::prelude::*; use deno_core::plugin_api; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::JsRuntime; use deno_core::Op; use deno_core::OpAsyncFuture; @@ -13,10 +11,10 @@ use deno_core::OpFn; use deno_core::OpId; use deno_core::OpState; use deno_core::Resource; +use deno_core::ResourceId; use deno_core::ZeroCopyBuf; use dlopen::symbor::Library; use log::debug; -use serde::Deserialize; use std::borrow::Cow; use std::path::PathBuf; use std::pin::Pin; @@ -28,18 +26,12 @@ pub fn init(rt: &mut JsRuntime) { super::reg_json_sync(rt, "op_open_plugin", op_open_plugin); } -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct OpenPluginArgs { - filename: String, -} - pub fn op_open_plugin( state: &mut OpState, - args: OpenPluginArgs, + filename: String, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let filename = PathBuf::from(&args.filename); +) -> Result<ResourceId, AnyError> { + let filename = PathBuf::from(&filename); super::check_unstable(state, "Deno.openPlugin"); let permissions = state.borrow::<Permissions>(); @@ -67,7 +59,7 @@ pub fn op_open_plugin( let mut interface = PluginInterface::new(state, &plugin_lib); deno_plugin_init(&mut interface); - Ok(json!(rid)) + Ok(rid) } struct PluginResource { diff --git a/runtime/ops/process.rs b/runtime/ops/process.rs index d6b4dcc1f..c2ca2c687 100644 --- a/runtime/ops/process.rs +++ b/runtime/ops/process.rs @@ -8,8 +8,6 @@ use crate::permissions::Permissions; use deno_core::error::bad_resource_id; use deno_core::error::type_error; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::AsyncMutFuture; use deno_core::AsyncRefCell; use deno_core::OpState; @@ -18,6 +16,7 @@ use deno_core::Resource; use deno_core::ResourceId; use deno_core::ZeroCopyBuf; use serde::Deserialize; +use serde::Serialize; use std::borrow::Cow; use std::cell::RefCell; use std::rc::Rc; @@ -81,11 +80,22 @@ impl ChildResource { } } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +// TODO(@AaronO): maybe find a more descriptive name or a convention for return structs +struct RunInfo { + rid: ResourceId, + pid: Option<u32>, + stdin_rid: Option<ResourceId>, + stdout_rid: Option<ResourceId>, + stderr_rid: Option<ResourceId>, +} + fn op_run( state: &mut OpState, run_args: RunArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<RunInfo, AnyError> { state.borrow::<Permissions>().run.check()?; let args = run_args.cmd; @@ -166,28 +176,28 @@ fn op_run( }; let child_rid = state.resource_table.add(child_resource); - Ok(json!({ - "rid": child_rid, - "pid": pid, - "stdinRid": stdin_rid, - "stdoutRid": stdout_rid, - "stderrRid": stderr_rid, - })) + Ok(RunInfo { + rid: child_rid, + pid, + stdin_rid, + stdout_rid, + stderr_rid, + }) } -#[derive(Deserialize)] +#[derive(Serialize)] #[serde(rename_all = "camelCase")] -pub struct RunStatusArgs { - rid: ResourceId, +struct RunStatus { + got_signal: bool, + exit_code: i32, + exit_signal: i32, } async fn op_run_status( state: Rc<RefCell<OpState>>, - args: RunStatusArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let rid = args.rid; - +) -> Result<RunStatus, AnyError> { { let s = state.borrow(); s.borrow::<Permissions>().run.check()?; @@ -212,11 +222,11 @@ async fn op_run_status( .expect("Should have either an exit code or a signal."); let got_signal = signal.is_some(); - Ok(json!({ - "gotSignal": got_signal, - "exitCode": code.unwrap_or(-1), - "exitSignal": signal.unwrap_or(-1), - })) + Ok(RunStatus { + got_signal, + exit_code: code.unwrap_or(-1), + exit_signal: signal.unwrap_or(-1), + }) } #[cfg(unix)] @@ -280,10 +290,10 @@ fn op_kill( state: &mut OpState, args: KillArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.kill"); state.borrow::<Permissions>().run.check()?; kill(args.pid, args.signo)?; - Ok(json!({})) + Ok(()) } diff --git a/runtime/ops/runtime.rs b/runtime/ops/runtime.rs index 9d29671c9..ef7445b11 100644 --- a/runtime/ops/runtime.rs +++ b/runtime/ops/runtime.rs @@ -1,10 +1,10 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. +use crate::metrics::OpMetrics; use crate::metrics::RuntimeMetrics; use crate::ops::UnstableChecker; use crate::permissions::Permissions; use deno_core::error::AnyError; -use deno_core::serde_json; use deno_core::serde_json::json; use deno_core::serde_json::Value; use deno_core::ModuleSpecifier; @@ -23,9 +23,9 @@ pub fn init(rt: &mut deno_core::JsRuntime, main_module: ModuleSpecifier) { fn op_main_module( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<String, AnyError> { let main = state.borrow::<ModuleSpecifier>().to_string(); let main_url = deno_core::resolve_url_or_path(&main)?; if main_url.scheme() == "file" { @@ -35,15 +35,21 @@ fn op_main_module( .read .check_blind(&main_path, "main_module")?; } - Ok(json!(&main)) + Ok(main) +} + +#[derive(serde::Serialize)] +struct MetricsReturn { + combined: OpMetrics, + ops: Value, } #[allow(clippy::unnecessary_wraps)] fn op_metrics( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<MetricsReturn, AnyError> { let m = state.borrow::<RuntimeMetrics>(); let combined = m.combined_metrics(); let unstable_checker = state.borrow::<UnstableChecker>(); @@ -52,10 +58,13 @@ fn op_metrics( } else { None }; - Ok(json!({ "combined": combined, "ops": maybe_ops })) + Ok(MetricsReturn { + combined, + ops: json!(maybe_ops), + }) } -pub fn ppid() -> Value { +pub fn ppid() -> i64 { #[cfg(windows)] { // Adopted from rustup: @@ -77,7 +86,7 @@ pub fn ppid() -> Value { // and contains our parent's pid let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if snapshot == INVALID_HANDLE_VALUE { - return serde_json::to_value(-1).unwrap(); + return -1; } let mut entry: PROCESSENTRY32 = mem::zeroed(); @@ -87,7 +96,7 @@ pub fn ppid() -> Value { let success = Process32First(snapshot, &mut entry); if success == 0 { CloseHandle(snapshot); - return serde_json::to_value(-1).unwrap(); + return -1; } let this_pid = GetCurrentProcessId(); @@ -95,7 +104,7 @@ pub fn ppid() -> Value { let success = Process32Next(snapshot, &mut entry); if success == 0 { CloseHandle(snapshot); - return serde_json::to_value(-1).unwrap(); + return -1; } } CloseHandle(snapshot); @@ -104,12 +113,12 @@ pub fn ppid() -> Value { // wherein the parent process already exited and the OS // reassigned its ID. let parent_id = entry.th32ParentProcessID; - serde_json::to_value(parent_id).unwrap() + parent_id.into() } } #[cfg(not(windows))] { use std::os::unix::process::parent_id; - serde_json::to_value(parent_id()).unwrap() + parent_id().into() } } diff --git a/runtime/ops/signal.rs b/runtime/ops/signal.rs index ef29ddec7..5235da612 100644 --- a/runtime/ops/signal.rs +++ b/runtime/ops/signal.rs @@ -1,6 +1,5 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use deno_core::error::AnyError; -use deno_core::serde_json::Value; use deno_core::OpState; use deno_core::ZeroCopyBuf; use std::cell::RefCell; @@ -9,8 +8,6 @@ use std::rc::Rc; #[cfg(unix)] use deno_core::error::bad_resource_id; #[cfg(unix)] -use deno_core::serde_json::json; -#[cfg(unix)] use deno_core::AsyncRefCell; #[cfg(unix)] use deno_core::CancelFuture; @@ -21,7 +18,7 @@ use deno_core::RcRef; #[cfg(unix)] use deno_core::Resource; #[cfg(unix)] -use serde::Deserialize; +use deno_core::ResourceId; #[cfg(unix)] use std::borrow::Cow; #[cfg(unix)] @@ -53,45 +50,28 @@ impl Resource for SignalStreamResource { } #[cfg(unix)] -#[derive(Deserialize)] -pub struct BindSignalArgs { - signo: i32, -} - -#[cfg(unix)] -#[derive(Deserialize)] -pub struct SignalArgs { - rid: u32, -} - -#[cfg(unix)] #[allow(clippy::unnecessary_wraps)] fn op_signal_bind( state: &mut OpState, - args: BindSignalArgs, + signo: i32, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<ResourceId, AnyError> { super::check_unstable(state, "Deno.signal"); let resource = SignalStreamResource { - signal: AsyncRefCell::new( - signal(SignalKind::from_raw(args.signo)).expect(""), - ), + signal: AsyncRefCell::new(signal(SignalKind::from_raw(signo)).expect("")), cancel: Default::default(), }; let rid = state.resource_table.add(resource); - Ok(json!({ - "rid": rid, - })) + Ok(rid) } #[cfg(unix)] async fn op_signal_poll( state: Rc<RefCell<OpState>>, - args: SignalArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<bool, AnyError> { super::check_unstable2(&state, "Deno.signal"); - let rid = args.rid; let resource = state .borrow_mut() @@ -102,49 +82,48 @@ async fn op_signal_poll( let mut signal = RcRef::map(&resource, |r| &r.signal).borrow_mut().await; match signal.recv().or_cancel(cancel).await { - Ok(result) => Ok(json!({ "done": result.is_none() })), - Err(_) => Ok(json!({ "done": true })), + Ok(result) => Ok(result.is_none()), + Err(_) => Ok(true), } } #[cfg(unix)] pub fn op_signal_unbind( state: &mut OpState, - args: SignalArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.signal"); - let rid = args.rid; state .resource_table .close(rid) .ok_or_else(bad_resource_id)?; - Ok(json!({})) + Ok(()) } #[cfg(not(unix))] pub fn op_signal_bind( _state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { unimplemented!(); } #[cfg(not(unix))] fn op_signal_unbind( _state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { unimplemented!(); } #[cfg(not(unix))] async fn op_signal_poll( _state: Rc<RefCell<OpState>>, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { unimplemented!(); } diff --git a/runtime/ops/timers.rs b/runtime/ops/timers.rs index c709e3173..428d4ecea 100644 --- a/runtime/ops/timers.rs +++ b/runtime/ops/timers.rs @@ -14,11 +14,8 @@ use deno_core::futures; use deno_core::futures::channel::oneshot; use deno_core::futures::FutureExt; use deno_core::futures::TryFutureExt; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::OpState; use deno_core::ZeroCopyBuf; -use serde::Deserialize; use std::cell::RefCell; use std::future::Future; use std::pin::Pin; @@ -82,17 +79,12 @@ pub fn init(rt: &mut deno_core::JsRuntime) { #[allow(clippy::unnecessary_wraps)] fn op_global_timer_stop( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let global_timer = state.borrow_mut::<GlobalTimer>(); global_timer.cancel(); - Ok(json!({})) -} - -#[derive(Deserialize)] -pub struct GlobalTimerArgs { - timeout: u64, + Ok(()) } // Set up a timer that will be later awaited by JS promise. @@ -105,22 +97,20 @@ pub struct GlobalTimerArgs { #[allow(clippy::unnecessary_wraps)] fn op_global_timer_start( state: &mut OpState, - args: GlobalTimerArgs, + timeout: u64, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let val = args.timeout; - - let deadline = Instant::now() + Duration::from_millis(val); +) -> Result<(), AnyError> { + let deadline = Instant::now() + Duration::from_millis(timeout); let global_timer = state.borrow_mut::<GlobalTimer>(); global_timer.new_timeout(deadline); - Ok(json!({})) + Ok(()) } async fn op_global_timer( state: Rc<RefCell<OpState>>, - _args: Value, + _args: (), _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let maybe_timer_fut = { let mut s = state.borrow_mut(); let global_timer = s.borrow_mut::<GlobalTimer>(); @@ -129,7 +119,7 @@ async fn op_global_timer( if let Some(timer_fut) = maybe_timer_fut { let _ = timer_fut.await; } - Ok(json!({})) + Ok(()) } // Returns a milliseconds and nanoseconds subsec @@ -159,18 +149,13 @@ fn op_now( Ok(result) } -#[derive(Deserialize)] -pub struct SleepArgs { - millis: u64, -} - #[allow(clippy::unnecessary_wraps)] fn op_sleep_sync( state: &mut OpState, - args: SleepArgs, + millis: u64, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.sleepSync"); - sleep(Duration::from_millis(args.millis)); - Ok(json!({})) + sleep(Duration::from_millis(millis)); + Ok(()) } diff --git a/runtime/ops/tls.rs b/runtime/ops/tls.rs index 00f000a97..e0cb992f0 100644 --- a/runtime/ops/tls.rs +++ b/runtime/ops/tls.rs @@ -348,18 +348,11 @@ fn op_listen_tls( })) } -#[derive(Deserialize)] -pub struct AcceptTlsArgs { - rid: ResourceId, -} - async fn op_accept_tls( state: Rc<RefCell<OpState>>, - args: AcceptTlsArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<Value, AnyError> { - let rid = args.rid; - let resource = state .borrow() .resource_table diff --git a/runtime/ops/tty.rs b/runtime/ops/tty.rs index 6253cc837..9af72b5cd 100644 --- a/runtime/ops/tty.rs +++ b/runtime/ops/tty.rs @@ -5,8 +5,6 @@ use deno_core::error::bad_resource_id; use deno_core::error::not_supported; use deno_core::error::resource_unavailable; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::OpState; use deno_core::RcRef; use deno_core::ResourceId; @@ -68,7 +66,7 @@ fn op_set_raw( state: &mut OpState, args: SetRawArgs, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.setRaw"); let rid = args.rid; @@ -147,7 +145,7 @@ fn op_set_raw( return Err(Error::last_os_error().into()); } - Ok(json!({})) + Ok(()) } #[cfg(unix)] { @@ -210,22 +208,15 @@ fn op_set_raw( } } - Ok(json!({})) + Ok(()) } } -#[derive(Deserialize)] -pub struct IsattyArgs { - rid: ResourceId, -} - fn op_isatty( state: &mut OpState, - args: IsattyArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let rid = args.rid; - +) -> Result<bool, AnyError> { let isatty: bool = StdFileResource::with(state, rid, move |r| match r { Ok(std_file) => { #[cfg(windows)] @@ -246,12 +237,7 @@ fn op_isatty( } _ => Ok(false), })?; - Ok(json!(isatty)) -} - -#[derive(Deserialize)] -pub struct ConsoleSizeArgs { - rid: ResourceId, + Ok(isatty) } #[derive(Serialize)] @@ -262,13 +248,11 @@ struct ConsoleSize { fn op_console_size( state: &mut OpState, - args: ConsoleSizeArgs, + rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<ConsoleSize, AnyError> { super::check_unstable(state, "Deno.consoleSize"); - let rid = args.rid; - let size = StdFileResource::with(state, rid, move |r| match r { Ok(std_file) => { #[cfg(windows)] diff --git a/runtime/ops/web_worker.rs b/runtime/ops/web_worker.rs index 7918b97ea..5f63a03b7 100644 --- a/runtime/ops/web_worker.rs +++ b/runtime/ops/web_worker.rs @@ -4,7 +4,6 @@ use crate::web_worker::WebWorkerHandle; use crate::web_worker::WorkerEvent; use deno_core::error::null_opbuf; use deno_core::futures::channel::mpsc; -use deno_core::serde_json::{json, Value}; pub fn init( rt: &mut deno_core::JsRuntime, @@ -16,14 +15,14 @@ pub fn init( super::reg_json_sync( rt, "op_worker_post_message", - move |_state, _args: Value, buf| { + move |_state, _args: (), buf| { let buf = buf.ok_or_else(null_opbuf)?; let msg_buf: Box<[u8]> = (*buf).into(); sender_ .clone() .try_send(WorkerEvent::Message(msg_buf)) .expect("Failed to post message to host"); - Ok(json!({})) + Ok(()) }, ); @@ -31,12 +30,12 @@ pub fn init( super::reg_json_sync( rt, "op_worker_close", - move |_state, _args: Value, _bufs| { + move |_state, _args: (), _bufs| { // Notify parent that we're finished sender.clone().close_channel(); // Terminate execution of current worker handle.terminate(); - Ok(json!({})) + Ok(()) }, ); } diff --git a/runtime/ops/worker_host.rs b/runtime/ops/worker_host.rs index 6891241dd..d8e60171e 100644 --- a/runtime/ops/worker_host.rs +++ b/runtime/ops/worker_host.rs @@ -57,11 +57,6 @@ pub type CreateWebWorkerCb = #[derive(Clone)] pub struct CreateWebWorkerCbHolder(Arc<CreateWebWorkerCb>); -#[derive(Deserialize)] -struct HostUnhandledErrorArgs { - message: String, -} - pub struct WorkerThread { join_handle: JoinHandle<Result<(), AnyError>>, worker_handle: WebWorkerHandle, @@ -95,12 +90,12 @@ pub fn init( super::reg_json_sync( rt, "op_host_unhandled_error", - move |_state, args: HostUnhandledErrorArgs, _zero_copy| { + move |_state, message: String, _zero_copy| { if let Some(mut sender) = sender.clone() { sender - .try_send(WorkerEvent::Error(generic_error(args.message))) + .try_send(WorkerEvent::Error(generic_error(message))) .expect("Failed to propagate error event to parent worker"); - Ok(json!(true)) + Ok(true) } else { Err(generic_error("Cannot be called from main worker.")) } @@ -370,7 +365,7 @@ fn op_create_worker( state: &mut OpState, args: CreateWorkerArgs, _data: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<WorkerId, AnyError> { let specifier = args.specifier.clone(); let maybe_source_code = if args.has_source_code { Some(args.source_code.clone()) @@ -445,21 +440,15 @@ fn op_create_worker( .borrow_mut::<WorkersTable>() .insert(worker_id, worker_thread); - Ok(json!({ "id": worker_id })) -} - -#[derive(Deserialize)] -pub struct WorkerArgs { - id: i32, + Ok(worker_id) } #[allow(clippy::unnecessary_wraps)] fn op_host_terminate_worker( state: &mut OpState, - args: WorkerArgs, + id: WorkerId, _data: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { - let id = args.id as u32; +) -> Result<(), AnyError> { let worker_thread = state .borrow_mut::<WorkersTable>() .remove(&id) @@ -470,7 +459,7 @@ fn op_host_terminate_worker( .join() .expect("Panic in worker thread") .expect("Panic in worker event loop"); - Ok(json!({})) + Ok(()) } fn serialize_worker_event(event: WorkerEvent) -> Value { @@ -532,11 +521,9 @@ fn try_remove_and_close(state: Rc<RefCell<OpState>>, id: u32) { /// Get message from guest worker as host async fn op_host_get_message( state: Rc<RefCell<OpState>>, - args: WorkerArgs, + id: WorkerId, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<Value, AnyError> { - let id = args.id as u32; - let worker_handle = { let s = state.borrow(); let workers_table = s.borrow::<WorkersTable>(); @@ -566,11 +553,10 @@ async fn op_host_get_message( /// Post message to guest worker as host fn op_host_post_message( state: &mut OpState, - args: WorkerArgs, + id: WorkerId, data: Option<ZeroCopyBuf>, -) -> Result<Value, AnyError> { +) -> Result<(), AnyError> { let data = data.ok_or_else(null_opbuf)?; - let id = args.id as u32; let msg = Vec::from(&*data).into_boxed_slice(); debug!("post message to worker {}", id); @@ -579,5 +565,5 @@ fn op_host_post_message( .get(&id) .expect("No worker handle found"); worker_thread.worker_handle.post_message(msg)?; - Ok(json!({})) + Ok(()) } |