From 2aed322dd507a8568b6ee6f4897e9a8e3220f763 Mon Sep 17 00:00:00 2001 From: Aaron O'Mullan Date: Mon, 5 Apr 2021 18:40:24 +0200 Subject: [PATCH] refactor: convert ops to use serde_v8 (#10009) This commit rewrites most of the ops to use "serde_v8" instead of "json" serialization. --- op_crates/crypto/01_crypto.js | 2 +- op_crates/crypto/lib.rs | 8 +- op_crates/fetch/26_fetch.js | 22 +- op_crates/fetch/lib.rs | 82 +++--- op_crates/url/lib.rs | 68 ++--- op_crates/webgpu/binding.rs | 25 +- op_crates/webgpu/buffer.rs | 25 +- op_crates/webgpu/bundle.rs | 58 ++-- op_crates/webgpu/command_encoder.rs | 66 ++--- op_crates/webgpu/compute_pass.rs | 48 ++-- op_crates/webgpu/error.rs | 41 +++ op_crates/webgpu/lib.rs | 86 +++--- op_crates/webgpu/pipeline.rs | 51 ++-- op_crates/webgpu/queue.rs | 16 +- op_crates/webgpu/render_pass.rs | 84 +++--- op_crates/webgpu/sampler.rs | 11 +- op_crates/webgpu/shader.rs | 11 +- op_crates/webgpu/texture.rs | 18 +- op_crates/websocket/01_websocket.js | 6 +- op_crates/websocket/lib.rs | 34 +-- runtime/js/11_timers.js | 4 +- runtime/js/11_workers.js | 12 +- runtime/js/30_fs.js | 39 +-- runtime/js/30_net.js | 2 +- runtime/js/30_os.js | 13 +- runtime/js/40_fs_events.js | 7 +- runtime/js/40_permissions.js | 6 +- runtime/js/40_plugins.js | 2 +- runtime/js/40_process.js | 2 +- runtime/js/40_signals.js | 14 +- runtime/js/40_tls.js | 2 +- runtime/js/40_tty.js | 4 +- runtime/js/99_main.js | 2 +- runtime/ops/fs.rs | 430 +++++++++++++--------------- runtime/ops/fs_events.rs | 21 +- runtime/ops/io.rs | 16 +- runtime/ops/net.rs | 19 +- runtime/ops/net_unix.rs | 7 + runtime/ops/os.rs | 145 +++++----- runtime/ops/permissions.rs | 14 +- runtime/ops/plugin.rs | 18 +- runtime/ops/process.rs | 58 ++-- runtime/ops/runtime.rs | 35 ++- runtime/ops/signal.rs | 57 ++-- runtime/ops/timers.rs | 43 +-- runtime/ops/tls.rs | 9 +- runtime/ops/tty.rs | 30 +- runtime/ops/web_worker.rs | 9 +- runtime/ops/worker_host.rs | 38 +-- 49 files changed, 840 insertions(+), 980 deletions(-) diff --git a/op_crates/crypto/01_crypto.js b/op_crates/crypto/01_crypto.js index ce13dc74c1..f0cb1d823c 100644 --- a/op_crates/crypto/01_crypto.js +++ b/op_crates/crypto/01_crypto.js @@ -37,7 +37,7 @@ arrayBufferView.byteOffset, arrayBufferView.byteLength, ); - core.jsonOpSync("op_crypto_get_random_values", {}, ui8); + core.jsonOpSync("op_crypto_get_random_values", null, ui8); return arrayBufferView; } diff --git a/op_crates/crypto/lib.rs b/op_crates/crypto/lib.rs index 9fc61d871c..c74b1b2c24 100644 --- a/op_crates/crypto/lib.rs +++ b/op_crates/crypto/lib.rs @@ -4,8 +4,6 @@ use deno_core::error::null_opbuf; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::JsRuntime; use deno_core::OpState; use deno_core::ZeroCopyBuf; @@ -29,9 +27,9 @@ pub fn init(isolate: &mut JsRuntime) { pub fn op_crypto_get_random_values( state: &mut OpState, - _args: Value, + _args: (), zero_copy: Option, -) -> Result { +) -> Result<(), AnyError> { let mut zero_copy = zero_copy.ok_or_else(null_opbuf)?; let maybe_seeded_rng = state.try_borrow_mut::(); if let Some(seeded_rng) = maybe_seeded_rng { @@ -41,7 +39,7 @@ pub fn op_crypto_get_random_values( rng.fill(&mut *zero_copy); } - Ok(json!({})) + Ok(()) } pub fn get_declaration() -> PathBuf { diff --git a/op_crates/fetch/26_fetch.js b/op_crates/fetch/26_fetch.js index d4b2680ec0..0fd825e162 100644 --- a/op_crates/fetch/26_fetch.js +++ b/op_crates/fetch/26_fetch.js @@ -884,29 +884,29 @@ if (body != null) { zeroCopy = new Uint8Array(body.buffer, body.byteOffset, body.byteLength); } - return core.jsonOpSync("op_fetch", args, ...(zeroCopy ? [zeroCopy] : [])); + return core.jsonOpSync("op_fetch", args, zeroCopy); } /** - * @param {{rid: number}} args + * @param {number} rid * @returns {Promise<{status: number, statusText: string, headers: Record, url: string, responseRid: number}>} */ - function opFetchSend(args) { - return core.jsonOpAsync("op_fetch_send", args); + function opFetchSend(rid) { + return core.jsonOpAsync("op_fetch_send", rid); } /** - * @param {{rid: number}} args + * @param {number} rid * @param {Uint8Array} body * @returns {Promise} */ - function opFetchRequestWrite(args, body) { + function opFetchRequestWrite(rid, body) { const zeroCopy = new Uint8Array( body.buffer, body.byteOffset, body.byteLength, ); - return core.jsonOpAsync("op_fetch_request_write", args, zeroCopy); + return core.jsonOpAsync("op_fetch_request_write", rid, zeroCopy); } const NULL_BODY_STATUS = [101, 204, 205, 304]; @@ -1276,7 +1276,7 @@ */ async write(chunk, controller) { try { - await opFetchRequestWrite({ rid: requestBodyRid }, chunk); + await opFetchRequestWrite(requestBodyRid, chunk); } catch (err) { controller.error(err); } @@ -1288,7 +1288,7 @@ body.pipeTo(writer); } - return await opFetchSend({ rid: requestRid }); + return await opFetchSend(requestRid); } /** @@ -1400,9 +1400,9 @@ async pull(controller) { try { const chunk = new Uint8Array(16 * 1024 + 256); - const { read } = await core.jsonOpAsync( + const read = await core.jsonOpAsync( "op_fetch_response_read", - { rid }, + rid, chunk, ); if (read != 0) { diff --git a/op_crates/fetch/lib.rs b/op_crates/fetch/lib.rs index 19f2566c40..1d36bfc09d 100644 --- a/op_crates/fetch/lib.rs +++ b/op_crates/fetch/lib.rs @@ -10,8 +10,6 @@ use deno_core::error::AnyError; use deno_core::futures::Future; use deno_core::futures::Stream; use deno_core::futures::StreamExt; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::url::Url; use deno_core::AsyncRefCell; use deno_core::CancelFuture; @@ -34,6 +32,7 @@ use reqwest::Client; use reqwest::Method; use reqwest::Response; use serde::Deserialize; +use serde::Serialize; use std::borrow::Cow; use std::cell::RefCell; use std::convert::From; @@ -121,11 +120,18 @@ pub struct FetchArgs { has_body: bool, } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FetchReturn { + request_rid: ResourceId, + request_body_rid: Option, +} + pub fn op_fetch( state: &mut OpState, args: FetchArgs, data: Option, -) -> Result +) -> Result where FP: FetchPermissions + 'static, { @@ -164,7 +170,7 @@ where let mut request = client.request(method, url); - let maybe_request_body_rid = if args.has_body { + let request_body_rid = if args.has_body { match data { None => { // If no body is passed, we return a writer for streaming the body. @@ -201,27 +207,31 @@ where .resource_table .add(FetchRequestResource(Box::pin(fut))); - Ok(json!({ - "requestRid": request_rid, - "requestBodyRid": maybe_request_body_rid - })) + Ok(FetchReturn { + request_rid, + request_body_rid, + }) } -#[derive(Deserialize)] +#[derive(Serialize)] #[serde(rename_all = "camelCase")] -pub struct FetchSendArgs { - rid: ResourceId, +pub struct FetchResponse { + status: u16, + status_text: String, + headers: Vec<(String, String)>, + url: String, + response_rid: ResourceId, } pub async fn op_fetch_send( state: Rc>, - args: FetchSendArgs, + rid: ResourceId, _data: Option, -) -> Result { +) -> Result { let request = state .borrow_mut() .resource_table - .take::(args.rid) + .take::(rid) .ok_or_else(bad_resource_id)?; let request = Rc::try_unwrap(request) @@ -266,27 +276,20 @@ pub async fn op_fetch_send( cancel: CancelHandle::default(), }); - Ok(json!({ - "status": status.as_u16(), - "statusText": status.canonical_reason().unwrap_or(""), - "headers": res_headers, - "url": url, - "responseRid": rid, - })) -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FetchRequestWriteArgs { - rid: ResourceId, + Ok(FetchResponse { + status: status.as_u16(), + status_text: status.canonical_reason().unwrap_or("").to_string(), + headers: res_headers, + url, + response_rid: rid, + }) } pub async fn op_fetch_request_write( state: Rc>, - args: FetchRequestWriteArgs, + rid: ResourceId, data: Option, -) -> Result { - let rid = args.rid; +) -> Result<(), AnyError> { let data = data.ok_or_else(null_opbuf)?; let buf = Vec::from(&*data); @@ -299,21 +302,14 @@ pub async fn op_fetch_request_write( let cancel = RcRef::map(resource, |r| &r.cancel); body.send(Ok(buf)).or_cancel(cancel).await??; - Ok(json!({})) -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FetchResponseReadArgs { - rid: ResourceId, + Ok(()) } pub async fn op_fetch_response_read( state: Rc>, - args: FetchResponseReadArgs, + rid: ResourceId, data: Option, -) -> Result { - let rid = args.rid; +) -> Result { let data = data.ok_or_else(null_opbuf)?; let resource = state @@ -325,7 +321,7 @@ pub async fn op_fetch_response_read( let cancel = RcRef::map(resource, |r| &r.cancel); let mut buf = data.clone(); let read = reader.read(&mut buf).try_or_cancel(cancel).await?; - Ok(json!({ "read": read })) + Ok(read) } struct FetchRequestResource( @@ -391,7 +387,7 @@ pub fn op_create_http_client( state: &mut OpState, args: CreateHttpClientOptions, _zero_copy: Option, -) -> Result +) -> Result where FP: FetchPermissions + 'static, { @@ -411,7 +407,7 @@ where .unwrap(); let rid = state.resource_table.add(HttpClientResource::new(client)); - Ok(json!(rid)) + Ok(rid) } fn get_cert_data( diff --git a/op_crates/url/lib.rs b/op_crates/url/lib.rs index f7615725fd..f216768c33 100644 --- a/op_crates/url/lib.rs +++ b/op_crates/url/lib.rs @@ -4,8 +4,6 @@ use deno_core::error::generic_error; use deno_core::error::type_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::form_urlencoded; use deno_core::url::quirks; use deno_core::url::Url; @@ -34,13 +32,28 @@ pub struct UrlParseArgs { set_username: Option, } +#[derive(Serialize)] +pub struct UrlParts { + href: String, + hash: String, + host: String, + hostname: String, + origin: String, + password: String, + pathname: String, + port: String, + protocol: String, + search: String, + username: String, +} + /// Parse `UrlParseArgs::href` with an optional `UrlParseArgs::base_href`, or an /// optional part to "set" after parsing. Return `UrlParts`. pub fn op_url_parse( _state: &mut deno_core::OpState, args: UrlParseArgs, _zero_copy: Option, -) -> Result { +) -> Result { let base_url = args .base_href .as_ref() @@ -75,20 +88,6 @@ pub fn op_url_parse( .map_err(|_| uri_error("Invalid username"))?; } - #[derive(Serialize)] - struct UrlParts<'a> { - href: &'a str, - hash: &'a str, - host: &'a str, - hostname: &'a str, - origin: &'a str, - password: &'a str, - pathname: &'a str, - port: &'a str, - protocol: &'a str, - search: &'a str, - username: &'a str, - } // TODO(nayeemrmn): Panic that occurs in rust-url for the `non-spec:` // url-constructor wpt tests: https://github.com/servo/rust-url/issues/670. let username = catch_unwind(|| quirks::username(&url)).map_err(|_| { @@ -102,41 +101,42 @@ pub fn op_url_parse( .unwrap_or_default() )) })?; - Ok(json!(UrlParts { - href: quirks::href(&url), - hash: quirks::hash(&url), - host: quirks::host(&url), - hostname: quirks::hostname(&url), - origin: &quirks::origin(&url), - password: quirks::password(&url), - pathname: quirks::pathname(&url), - port: quirks::port(&url), - protocol: quirks::protocol(&url), - search: quirks::search(&url), - username, - })) + Ok(UrlParts { + href: quirks::href(&url).to_string(), + hash: quirks::hash(&url).to_string(), + host: quirks::host(&url).to_string(), + hostname: quirks::hostname(&url).to_string(), + origin: quirks::origin(&url), + password: quirks::password(&url).to_string(), + pathname: quirks::pathname(&url).to_string(), + port: quirks::port(&url).to_string(), + protocol: quirks::protocol(&url).to_string(), + search: quirks::search(&url).to_string(), + username: username.to_string(), + }) } pub fn op_url_parse_search_params( _state: &mut deno_core::OpState, args: String, _zero_copy: Option, -) -> Result { +) -> Result, AnyError> { let search_params: Vec<_> = form_urlencoded::parse(args.as_bytes()) .into_iter() + .map(|(k, v)| (k.as_ref().to_owned(), v.as_ref().to_owned())) .collect(); - Ok(json!(search_params)) + Ok(search_params) } pub fn op_url_stringify_search_params( _state: &mut deno_core::OpState, args: Vec<(String, String)>, _zero_copy: Option, -) -> Result { +) -> Result { let search = form_urlencoded::Serializer::new(String::new()) .extend_pairs(args) .finish(); - Ok(json!(search)) + Ok(search) } /// Load and execute the javascript code. diff --git a/op_crates/webgpu/binding.rs b/op_crates/webgpu/binding.rs index 296a968f1e..fd4e75784d 100644 --- a/op_crates/webgpu/binding.rs +++ b/op_crates/webgpu/binding.rs @@ -2,15 +2,13 @@ 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::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; use serde::Deserialize; use std::borrow::Cow; -use super::error::WebGpuError; +use super::error::WebGpuResult; pub(crate) struct WebGpuBindGroupLayout( pub(crate) wgpu_core::id::BindGroupLayoutId, @@ -83,7 +81,7 @@ pub fn op_webgpu_create_bind_group_layout( state: &mut OpState, args: CreateBindGroupLayoutArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -207,10 +205,7 @@ pub fn op_webgpu_create_bind_group_layout( .resource_table .add(WebGpuBindGroupLayout(bind_group_layout)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -225,7 +220,7 @@ pub fn op_webgpu_create_pipeline_layout( state: &mut OpState, args: CreatePipelineLayoutArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -259,10 +254,7 @@ pub fn op_webgpu_create_pipeline_layout( .resource_table .add(super::pipeline::WebGpuPipelineLayout(pipeline_layout)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -288,7 +280,7 @@ pub fn op_webgpu_create_bind_group( state: &mut OpState, args: CreateBindGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -356,8 +348,5 @@ pub fn op_webgpu_create_bind_group( let rid = state.resource_table.add(WebGpuBindGroup(bind_group)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } diff --git a/op_crates/webgpu/buffer.rs b/op_crates/webgpu/buffer.rs index ade4122d53..19fc428cb1 100644 --- a/op_crates/webgpu/buffer.rs +++ b/op_crates/webgpu/buffer.rs @@ -4,8 +4,6 @@ use deno_core::error::bad_resource_id; use deno_core::error::null_opbuf; use deno_core::error::AnyError; use deno_core::futures::channel::oneshot; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::OpState; use deno_core::Resource; use deno_core::ResourceId; @@ -17,7 +15,7 @@ use std::rc::Rc; use std::time::Duration; use super::error::DomExceptionOperationError; -use super::error::WebGpuError; +use super::error::WebGpuResult; pub(crate) struct WebGpuBuffer(pub(crate) wgpu_core::id::BufferId); impl Resource for WebGpuBuffer { @@ -47,7 +45,7 @@ pub fn op_webgpu_create_buffer( state: &mut OpState, args: CreateBufferArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -70,10 +68,7 @@ pub fn op_webgpu_create_buffer( let rid = state.resource_table.add(WebGpuBuffer(buffer)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -90,7 +85,7 @@ pub async fn op_webgpu_buffer_get_map_async( state: Rc>, args: BufferGetMapAsyncArgs, _bufs: Option, -) -> Result { +) -> Result { let (sender, receiver) = oneshot::channel::>(); let device; @@ -164,7 +159,7 @@ pub async fn op_webgpu_buffer_get_map_async( tokio::try_join!(device_poll_fut, receiver_fut)?; - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -179,7 +174,7 @@ pub fn op_webgpu_buffer_get_mapped_range( state: &mut OpState, args: BufferGetMappedRangeArgs, zero_copy: Option, -) -> Result { +) -> Result { let mut zero_copy = zero_copy.ok_or_else(null_opbuf)?; let instance = state.borrow::(); let buffer_resource = state @@ -204,9 +199,7 @@ pub fn op_webgpu_buffer_get_mapped_range( .resource_table .add(WebGpuBufferMapped(slice_pointer, args.size as usize)); - Ok(json!({ - "rid": rid, - })) + Ok(WebGpuResult::rid(rid)) } #[derive(Deserialize)] @@ -220,7 +213,7 @@ pub fn op_webgpu_buffer_unmap( state: &mut OpState, args: BufferUnmapArgs, zero_copy: Option, -) -> Result { +) -> Result { let mapped_resource = state .resource_table .take::(args.mapped_rid) @@ -242,5 +235,5 @@ pub fn op_webgpu_buffer_unmap( let maybe_err = gfx_select!(buffer => instance.buffer_unmap(buffer)).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } diff --git a/op_crates/webgpu/bundle.rs b/op_crates/webgpu/bundle.rs index 58915b1080..72abb18e69 100644 --- a/op_crates/webgpu/bundle.rs +++ b/op_crates/webgpu/bundle.rs @@ -3,8 +3,6 @@ use deno_core::error::bad_resource_id; use deno_core::error::null_opbuf; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; @@ -13,7 +11,7 @@ use std::borrow::Cow; use std::cell::RefCell; use std::rc::Rc; -use super::error::WebGpuError; +use super::error::WebGpuResult; use super::texture::serialize_texture_format; struct WebGpuRenderBundleEncoder( @@ -46,7 +44,7 @@ pub fn op_webgpu_create_render_bundle_encoder( state: &mut OpState, args: CreateRenderBundleEncoderArgs, _zero_copy: Option, -) -> Result { +) -> Result { let device_resource = state .resource_table .get::(args.device_rid) @@ -85,10 +83,7 @@ pub fn op_webgpu_create_render_bundle_encoder( render_bundle_encoder, ))); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from), - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -102,7 +97,7 @@ pub fn op_webgpu_render_bundle_encoder_finish( state: &mut OpState, args: RenderBundleEncoderFinishArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_bundle_encoder_resource = state .resource_table .take::(args.render_bundle_encoder_rid) @@ -124,10 +119,7 @@ pub fn op_webgpu_render_bundle_encoder_finish( let rid = state.resource_table.add(WebGpuRenderBundle(render_bundle)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -145,7 +137,7 @@ pub fn op_webgpu_render_bundle_encoder_set_bind_group( state: &mut OpState, args: RenderBundleEncoderSetBindGroupArgs, zero_copy: Option, -) -> Result { +) -> Result { let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let bind_group_resource = state @@ -188,7 +180,7 @@ pub fn op_webgpu_render_bundle_encoder_set_bind_group( } }; - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -202,7 +194,7 @@ pub fn op_webgpu_render_bundle_encoder_push_debug_group( state: &mut OpState, args: RenderBundleEncoderPushDebugGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_bundle_encoder_resource = state .resource_table .get::(args.render_bundle_encoder_rid) @@ -216,7 +208,7 @@ pub fn op_webgpu_render_bundle_encoder_push_debug_group( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -229,7 +221,7 @@ pub fn op_webgpu_render_bundle_encoder_pop_debug_group( state: &mut OpState, args: RenderBundleEncoderPopDebugGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_bundle_encoder_resource = state .resource_table .get::(args.render_bundle_encoder_rid) @@ -241,7 +233,7 @@ pub fn op_webgpu_render_bundle_encoder_pop_debug_group( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -255,7 +247,7 @@ pub fn op_webgpu_render_bundle_encoder_insert_debug_marker( state: &mut OpState, args: RenderBundleEncoderInsertDebugMarkerArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_bundle_encoder_resource = state .resource_table .get::(args.render_bundle_encoder_rid) @@ -269,7 +261,7 @@ pub fn op_webgpu_render_bundle_encoder_insert_debug_marker( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -283,7 +275,7 @@ pub fn op_webgpu_render_bundle_encoder_set_pipeline( state: &mut OpState, args: RenderBundleEncoderSetPipelineArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pipeline_resource = state .resource_table .get::(args.pipeline) @@ -298,7 +290,7 @@ pub fn op_webgpu_render_bundle_encoder_set_pipeline( render_pipeline_resource.0, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -315,7 +307,7 @@ pub fn op_webgpu_render_bundle_encoder_set_index_buffer( state: &mut OpState, args: RenderBundleEncoderSetIndexBufferArgs, _zero_copy: Option, -) -> Result { +) -> Result { let buffer_resource = state .resource_table .get::(args.buffer) @@ -335,7 +327,7 @@ pub fn op_webgpu_render_bundle_encoder_set_index_buffer( std::num::NonZeroU64::new(args.size), ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -352,7 +344,7 @@ pub fn op_webgpu_render_bundle_encoder_set_vertex_buffer( state: &mut OpState, args: RenderBundleEncoderSetVertexBufferArgs, _zero_copy: Option, -) -> Result { +) -> Result { let buffer_resource = state .resource_table .get::(args.buffer) @@ -370,7 +362,7 @@ pub fn op_webgpu_render_bundle_encoder_set_vertex_buffer( std::num::NonZeroU64::new(args.size), ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -387,7 +379,7 @@ pub fn op_webgpu_render_bundle_encoder_draw( state: &mut OpState, args: RenderBundleEncoderDrawArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_bundle_encoder_resource = state .resource_table .get::(args.render_bundle_encoder_rid) @@ -401,7 +393,7 @@ pub fn op_webgpu_render_bundle_encoder_draw( args.first_instance, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -419,7 +411,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indexed( state: &mut OpState, args: RenderBundleEncoderDrawIndexedArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_bundle_encoder_resource = state .resource_table .get::(args.render_bundle_encoder_rid) @@ -434,7 +426,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indexed( args.first_instance, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -449,7 +441,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indirect( state: &mut OpState, args: RenderBundleEncoderDrawIndirectArgs, _zero_copy: Option, -) -> Result { +) -> Result { let buffer_resource = state .resource_table .get::(args.indirect_buffer) @@ -465,5 +457,5 @@ pub fn op_webgpu_render_bundle_encoder_draw_indirect( args.indirect_offset, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } diff --git a/op_crates/webgpu/command_encoder.rs b/op_crates/webgpu/command_encoder.rs index 801682f565..724ce72c4a 100644 --- a/op_crates/webgpu/command_encoder.rs +++ b/op_crates/webgpu/command_encoder.rs @@ -2,8 +2,6 @@ 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::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; @@ -11,7 +9,7 @@ use serde::Deserialize; use std::borrow::Cow; use std::cell::RefCell; -use super::error::WebGpuError; +use super::error::WebGpuResult; pub(crate) struct WebGpuCommandEncoder( pub(crate) wgpu_core::id::CommandEncoderId, @@ -51,7 +49,7 @@ pub fn op_webgpu_create_command_encoder( state: &mut OpState, args: CreateCommandEncoderArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -73,10 +71,7 @@ pub fn op_webgpu_create_command_encoder( .resource_table .add(WebGpuCommandEncoder(command_encoder)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from), - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -117,7 +112,7 @@ pub fn op_webgpu_command_encoder_begin_render_pass( state: &mut OpState, args: CommandEncoderBeginRenderPassArgs, _zero_copy: Option, -) -> Result { +) -> Result { let command_encoder_resource = state .resource_table .get::(args.command_encoder_rid) @@ -236,9 +231,7 @@ pub fn op_webgpu_command_encoder_begin_render_pass( render_pass, ))); - Ok(json!({ - "rid": rid, - })) + Ok(WebGpuResult::rid(rid)) } #[derive(Deserialize)] @@ -252,7 +245,7 @@ pub fn op_webgpu_command_encoder_begin_compute_pass( state: &mut OpState, args: CommandEncoderBeginComputePassArgs, _zero_copy: Option, -) -> Result { +) -> Result { let command_encoder_resource = state .resource_table .get::(args.command_encoder_rid) @@ -273,9 +266,7 @@ pub fn op_webgpu_command_encoder_begin_compute_pass( compute_pass, ))); - Ok(json!({ - "rid": rid, - })) + Ok(WebGpuResult::rid(rid)) } #[derive(Deserialize)] @@ -293,7 +284,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_buffer( state: &mut OpState, args: CommandEncoderCopyBufferToBufferArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -320,7 +311,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_buffer( args.size )).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -362,7 +353,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_texture( state: &mut OpState, args: CommandEncoderCopyBufferToTextureArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -409,7 +400,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_texture( } )).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -425,7 +416,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_buffer( state: &mut OpState, args: CommandEncoderCopyTextureToBufferArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -471,7 +462,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_buffer( } )).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -487,7 +478,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_texture( state: &mut OpState, args: CommandEncoderCopyTextureToTextureArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -537,7 +528,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_texture( } )).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -551,7 +542,7 @@ pub fn op_webgpu_command_encoder_push_debug_group( state: &mut OpState, args: CommandEncoderPushDebugGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -563,7 +554,7 @@ pub fn op_webgpu_command_encoder_push_debug_group( .command_encoder_push_debug_group(command_encoder, &args.group_label)) .err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -576,7 +567,7 @@ pub fn op_webgpu_command_encoder_pop_debug_group( state: &mut OpState, args: CommandEncoderPopDebugGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -586,7 +577,7 @@ pub fn op_webgpu_command_encoder_pop_debug_group( let maybe_err = gfx_select!(command_encoder => instance.command_encoder_pop_debug_group(command_encoder)).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -600,7 +591,7 @@ pub fn op_webgpu_command_encoder_insert_debug_marker( state: &mut OpState, args: CommandEncoderInsertDebugMarkerArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -613,7 +604,7 @@ pub fn op_webgpu_command_encoder_insert_debug_marker( &args.marker_label )).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -628,7 +619,7 @@ pub fn op_webgpu_command_encoder_write_timestamp( state: &mut OpState, args: CommandEncoderWriteTimestampArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -648,7 +639,7 @@ pub fn op_webgpu_command_encoder_write_timestamp( )) .err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -666,7 +657,7 @@ pub fn op_webgpu_command_encoder_resolve_query_set( state: &mut OpState, args: CommandEncoderResolveQuerySetArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let command_encoder_resource = state .resource_table @@ -693,7 +684,7 @@ pub fn op_webgpu_command_encoder_resolve_query_set( )) .err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -707,7 +698,7 @@ pub fn op_webgpu_command_encoder_finish( state: &mut OpState, args: CommandEncoderFinishArgs, _zero_copy: Option, -) -> Result { +) -> Result { let command_encoder_resource = state .resource_table .take::(args.command_encoder_rid) @@ -728,8 +719,5 @@ pub fn op_webgpu_command_encoder_finish( .resource_table .add(WebGpuCommandBuffer(command_buffer)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } diff --git a/op_crates/webgpu/compute_pass.rs b/op_crates/webgpu/compute_pass.rs index 2e1fb1ac14..e8ec642e99 100644 --- a/op_crates/webgpu/compute_pass.rs +++ b/op_crates/webgpu/compute_pass.rs @@ -3,8 +3,6 @@ use deno_core::error::bad_resource_id; use deno_core::error::null_opbuf; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; @@ -12,7 +10,7 @@ use serde::Deserialize; use std::borrow::Cow; use std::cell::RefCell; -use super::error::WebGpuError; +use super::error::WebGpuResult; pub(crate) struct WebGpuComputePass( pub(crate) RefCell, @@ -34,7 +32,7 @@ pub fn op_webgpu_compute_pass_set_pipeline( state: &mut OpState, args: ComputePassSetPipelineArgs, _zero_copy: Option, -) -> Result { +) -> Result { let compute_pipeline_resource = state .resource_table .get::(args.pipeline) @@ -49,7 +47,7 @@ pub fn op_webgpu_compute_pass_set_pipeline( compute_pipeline_resource.0, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -65,7 +63,7 @@ pub fn op_webgpu_compute_pass_dispatch( state: &mut OpState, args: ComputePassDispatchArgs, _zero_copy: Option, -) -> Result { +) -> Result { let compute_pass_resource = state .resource_table .get::(args.compute_pass_rid) @@ -78,7 +76,7 @@ pub fn op_webgpu_compute_pass_dispatch( args.z, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -93,7 +91,7 @@ pub fn op_webgpu_compute_pass_dispatch_indirect( state: &mut OpState, args: ComputePassDispatchIndirectArgs, _zero_copy: Option, -) -> Result { +) -> Result { let buffer_resource = state .resource_table .get::(args.indirect_buffer) @@ -109,7 +107,7 @@ pub fn op_webgpu_compute_pass_dispatch_indirect( args.indirect_offset, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -124,7 +122,7 @@ pub fn op_webgpu_compute_pass_begin_pipeline_statistics_query( state: &mut OpState, args: ComputePassBeginPipelineStatisticsQueryArgs, _zero_copy: Option, -) -> Result { +) -> Result { let compute_pass_resource = state .resource_table .get::(args.compute_pass_rid) @@ -142,7 +140,7 @@ pub fn op_webgpu_compute_pass_begin_pipeline_statistics_query( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -155,7 +153,7 @@ pub fn op_webgpu_compute_pass_end_pipeline_statistics_query( state: &mut OpState, args: ComputePassEndPipelineStatisticsQueryArgs, _zero_copy: Option, -) -> Result { +) -> Result { let compute_pass_resource = state .resource_table .get::(args.compute_pass_rid) @@ -167,7 +165,7 @@ pub fn op_webgpu_compute_pass_end_pipeline_statistics_query( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -182,7 +180,7 @@ pub fn op_webgpu_compute_pass_write_timestamp( state: &mut OpState, args: ComputePassWriteTimestampArgs, _zero_copy: Option, -) -> Result { +) -> Result { let compute_pass_resource = state .resource_table .get::(args.compute_pass_rid) @@ -200,7 +198,7 @@ pub fn op_webgpu_compute_pass_write_timestamp( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -214,7 +212,7 @@ pub fn op_webgpu_compute_pass_end_pass( state: &mut OpState, args: ComputePassEndPassArgs, _zero_copy: Option, -) -> Result { +) -> Result { let command_encoder_resource = state .resource_table .get::( @@ -236,7 +234,7 @@ pub fn op_webgpu_compute_pass_end_pass( )) .err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -254,7 +252,7 @@ pub fn op_webgpu_compute_pass_set_bind_group( state: &mut OpState, args: ComputePassSetBindGroupArgs, zero_copy: Option, -) -> Result { +) -> Result { let bind_group_resource = state .resource_table .get::(args.bind_group) @@ -283,7 +281,7 @@ pub fn op_webgpu_compute_pass_set_bind_group( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -297,7 +295,7 @@ pub fn op_webgpu_compute_pass_push_debug_group( state: &mut OpState, args: ComputePassPushDebugGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let compute_pass_resource = state .resource_table .get::(args.compute_pass_rid) @@ -312,7 +310,7 @@ pub fn op_webgpu_compute_pass_push_debug_group( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -325,7 +323,7 @@ pub fn op_webgpu_compute_pass_pop_debug_group( state: &mut OpState, args: ComputePassPopDebugGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let compute_pass_resource = state .resource_table .get::(args.compute_pass_rid) @@ -335,7 +333,7 @@ pub fn op_webgpu_compute_pass_pop_debug_group( &mut compute_pass_resource.0.borrow_mut(), ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -349,7 +347,7 @@ pub fn op_webgpu_compute_pass_insert_debug_marker( state: &mut OpState, args: ComputePassInsertDebugMarkerArgs, _zero_copy: Option, -) -> Result { +) -> Result { let compute_pass_resource = state .resource_table .get::(args.compute_pass_rid) @@ -364,5 +362,5 @@ pub fn op_webgpu_compute_pass_insert_debug_marker( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } diff --git a/op_crates/webgpu/error.rs b/op_crates/webgpu/error.rs index 15036512ee..57e2e675f2 100644 --- a/op_crates/webgpu/error.rs +++ b/op_crates/webgpu/error.rs @@ -1,6 +1,8 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use deno_core::error::AnyError; +use deno_core::ResourceId; use serde::Serialize; +use std::convert::From; use std::fmt; use wgpu_core::binding_model::CreateBindGroupError; use wgpu_core::binding_model::CreateBindGroupLayoutError; @@ -27,6 +29,45 @@ use wgpu_core::resource::CreateSamplerError; use wgpu_core::resource::CreateTextureError; use wgpu_core::resource::CreateTextureViewError; +#[derive(Serialize)] +pub struct WebGpuResult { + pub rid: Option, + pub err: Option, +} + +impl WebGpuResult { + pub fn rid(rid: ResourceId) -> Self { + Self { + rid: Some(rid), + err: None, + } + } + + pub fn rid_err>( + rid: ResourceId, + err: Option, + ) -> Self { + Self { + rid: Some(rid), + err: err.map(|e| e.into()), + } + } + + pub fn maybe_err>(err: Option) -> Self { + Self { + rid: None, + err: err.map(|e| e.into()), + } + } + + pub fn empty() -> Self { + Self { + rid: None, + err: None, + } + } +} + #[derive(Serialize)] #[serde(tag = "type", content = "value")] #[serde(rename_all = "kebab-case")] diff --git a/op_crates/webgpu/lib.rs b/op_crates/webgpu/lib.rs index b1c8a631d4..0dd18ca8eb 100644 --- a/op_crates/webgpu/lib.rs +++ b/op_crates/webgpu/lib.rs @@ -4,13 +4,12 @@ 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::OpState; 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::path::PathBuf; @@ -19,7 +18,7 @@ pub use wgpu_core; pub use wgpu_types; use error::DomExceptionOperationError; -use error::WebGpuError; +use error::WebGpuResult; #[macro_use] mod macros { @@ -113,8 +112,8 @@ pub fn get_declaration() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_webgpu.d.ts") } -fn deserialize_features(features: &wgpu_types::Features) -> Vec<&str> { - let mut return_features: Vec<&str> = vec![]; +fn deserialize_features(features: &wgpu_types::Features) -> Vec<&'static str> { + let mut return_features: Vec<&'static str> = vec![]; if features.contains(wgpu_types::Features::DEPTH_CLAMPING) { return_features.push("depth-clamping"); @@ -191,11 +190,27 @@ pub struct RequestAdapterArgs { power_preference: Option, } +#[derive(Serialize)] +#[serde(untagged)] +pub enum GpuAdapterDeviceOrErr { + Error { err: String }, + Features(GpuAdapterDevice), +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GpuAdapterDevice { + rid: ResourceId, + name: Option, + limits: wgpu_types::Limits, + features: Vec<&'static str>, +} + pub async fn op_webgpu_request_adapter( state: Rc>, args: RequestAdapterArgs, _bufs: Option, -) -> Result { +) -> Result { let mut state = state.borrow_mut(); check_unstable(&state, "navigator.gpu.requestAdapter"); let instance = if let Some(instance) = state.try_borrow::() { @@ -231,9 +246,9 @@ pub async fn op_webgpu_request_adapter( let adapter = match res { Ok(adapter) => adapter, Err(err) => { - return Ok(json!({ - "err": err.to_string() - })) + return Ok(GpuAdapterDeviceOrErr::Error { + err: err.to_string(), + }) } }; let name = gfx_select!(adapter => instance.adapter_get_info(adapter))?.name; @@ -243,25 +258,13 @@ pub async fn op_webgpu_request_adapter( let adapter_limits = gfx_select!(adapter => instance.adapter_limits(adapter))?; - let limits = json!({ - "maxBindGroups": adapter_limits.max_bind_groups, - "maxDynamicUniformBuffersPerPipelineLayout": adapter_limits.max_dynamic_uniform_buffers_per_pipeline_layout, - "maxDynamicStorageBuffersPerPipelineLayout": adapter_limits.max_dynamic_storage_buffers_per_pipeline_layout, - "maxSampledTexturesPerShaderStage": adapter_limits.max_sampled_textures_per_shader_stage, - "maxSamplersPerShaderStage": adapter_limits.max_samplers_per_shader_stage, - "maxStorageBuffersPerShaderStage": adapter_limits.max_storage_buffers_per_shader_stage, - "maxStorageTexturesPerShaderStage": adapter_limits.max_storage_textures_per_shader_stage, - "maxUniformBuffersPerShaderStage": adapter_limits.max_uniform_buffers_per_shader_stage, - "maxUniformBufferBindingSize": adapter_limits.max_uniform_buffer_binding_size - }); - let rid = state.resource_table.add(WebGpuAdapter(adapter)); - Ok(json!({ - "rid": rid, - "name": name, - "features": features, - "limits": limits + Ok(GpuAdapterDeviceOrErr::Features(GpuAdapterDevice { + rid, + name: Some(name), + features, + limits: adapter_limits, })) } @@ -300,7 +303,7 @@ pub async fn op_webgpu_request_device( state: Rc>, args: RequestDeviceArgs, _bufs: Option, -) -> Result { +) -> Result { let mut state = state.borrow_mut(); let adapter_resource = state .resource_table @@ -437,25 +440,15 @@ pub async fn op_webgpu_request_device( gfx_select!(device => instance.device_features(device))?; let features = deserialize_features(&device_features); let limits = gfx_select!(device => instance.device_limits(device))?; - let json_limits = json!({ - "maxBindGroups": limits.max_bind_groups, - "maxDynamicUniformBuffersPerPipelineLayout": limits.max_dynamic_uniform_buffers_per_pipeline_layout, - "maxDynamicStorageBuffersPerPipelineLayout": limits.max_dynamic_storage_buffers_per_pipeline_layout, - "maxSampledTexturesPerShaderStage": limits.max_sampled_textures_per_shader_stage, - "maxSamplersPerShaderStage": limits.max_samplers_per_shader_stage, - "maxStorageBuffersPerShaderStage": limits.max_storage_buffers_per_shader_stage, - "maxStorageTexturesPerShaderStage": limits.max_storage_textures_per_shader_stage, - "maxUniformBuffersPerShaderStage": limits.max_uniform_buffers_per_shader_stage, - "maxUniformBufferBindingSize": limits.max_uniform_buffer_binding_size, - }); let rid = state.resource_table.add(WebGpuDevice(device)); - Ok(json!({ - "rid": rid, - "features": features, - "limits": json_limits, - })) + Ok(GpuAdapterDevice { + rid, + name: None, + features, + limits, + }) } #[derive(Deserialize)] @@ -473,7 +466,7 @@ pub fn op_webgpu_create_query_set( state: &mut OpState, args: CreateQuerySetArgs, _zero_copy: Option, -) -> Result { +) -> Result { let device_resource = state .resource_table .get::(args.device_rid) @@ -544,8 +537,5 @@ pub fn op_webgpu_create_query_set( let rid = state.resource_table.add(WebGpuQuerySet(query_set)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from), - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } diff --git a/op_crates/webgpu/pipeline.rs b/op_crates/webgpu/pipeline.rs index 10e300a57e..8eb291b97c 100644 --- a/op_crates/webgpu/pipeline.rs +++ b/op_crates/webgpu/pipeline.rs @@ -2,15 +2,14 @@ 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::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; use serde::Deserialize; +use serde::Serialize; use std::borrow::Cow; -use super::error::WebGpuError; +use super::error::{WebGpuError, WebGpuResult}; pub(crate) struct WebGpuPipelineLayout( pub(crate) wgpu_core::id::PipelineLayoutId, @@ -163,7 +162,7 @@ pub fn op_webgpu_create_compute_pipeline( state: &mut OpState, args: CreateComputePipelineArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -213,10 +212,7 @@ pub fn op_webgpu_create_compute_pipeline( .resource_table .add(WebGpuComputePipeline(compute_pipeline)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from), - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -226,11 +222,19 @@ pub struct ComputePipelineGetBindGroupLayoutArgs { index: u32, } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PipelineLayout { + rid: ResourceId, + label: String, + err: Option, +} + pub fn op_webgpu_compute_pipeline_get_bind_group_layout( state: &mut OpState, args: ComputePipelineGetBindGroupLayoutArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let compute_pipeline_resource = state .resource_table @@ -246,11 +250,11 @@ pub fn op_webgpu_compute_pipeline_get_bind_group_layout( .resource_table .add(super::binding::WebGpuBindGroupLayout(bind_group_layout)); - Ok(json!({ - "rid": rid, - "label": label, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(PipelineLayout { + rid, + label, + err: maybe_err.map(WebGpuError::from), + }) } #[derive(Deserialize)] @@ -367,7 +371,7 @@ pub fn op_webgpu_create_render_pipeline( state: &mut OpState, args: CreateRenderPipelineArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -601,10 +605,7 @@ pub fn op_webgpu_create_render_pipeline( .resource_table .add(WebGpuRenderPipeline(render_pipeline)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -618,7 +619,7 @@ pub fn op_webgpu_render_pipeline_get_bind_group_layout( state: &mut OpState, args: RenderPipelineGetBindGroupLayoutArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let render_pipeline_resource = state .resource_table @@ -634,9 +635,9 @@ pub fn op_webgpu_render_pipeline_get_bind_group_layout( .resource_table .add(super::binding::WebGpuBindGroupLayout(bind_group_layout)); - Ok(json!({ - "rid": rid, - "label": label, - "err": maybe_err.map(WebGpuError::from), - })) + Ok(PipelineLayout { + rid, + label, + err: maybe_err.map(WebGpuError::from), + }) } diff --git a/op_crates/webgpu/queue.rs b/op_crates/webgpu/queue.rs index c96e2a1589..93fd955020 100644 --- a/op_crates/webgpu/queue.rs +++ b/op_crates/webgpu/queue.rs @@ -3,14 +3,12 @@ use deno_core::error::bad_resource_id; use deno_core::error::null_opbuf; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::OpState; use deno_core::ResourceId; use deno_core::ZeroCopyBuf; use serde::Deserialize; -use super::error::WebGpuError; +use super::error::WebGpuResult; type WebGpuQueue = super::WebGpuDevice; @@ -25,7 +23,7 @@ pub fn op_webgpu_queue_submit( state: &mut OpState, args: QueueSubmitArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let queue_resource = state .resource_table @@ -46,7 +44,7 @@ pub fn op_webgpu_queue_submit( let maybe_err = gfx_select!(queue => instance.queue_submit(queue, &ids)).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -71,7 +69,7 @@ pub fn op_webgpu_write_buffer( state: &mut OpState, args: QueueWriteBufferArgs, zero_copy: Option, -) -> Result { +) -> Result { let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let instance = state.borrow::(); let buffer_resource = state @@ -97,7 +95,7 @@ pub fn op_webgpu_write_buffer( )) .err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -113,7 +111,7 @@ pub fn op_webgpu_write_texture( state: &mut OpState, args: QueueWriteTextureArgs, zero_copy: Option, -) -> Result { +) -> Result { let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let instance = state.borrow::(); let texture_resource = state @@ -157,5 +155,5 @@ pub fn op_webgpu_write_texture( )) .err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } diff --git a/op_crates/webgpu/render_pass.rs b/op_crates/webgpu/render_pass.rs index bf3bd092d5..38ebd6db82 100644 --- a/op_crates/webgpu/render_pass.rs +++ b/op_crates/webgpu/render_pass.rs @@ -3,8 +3,6 @@ use deno_core::error::bad_resource_id; use deno_core::error::null_opbuf; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; @@ -12,7 +10,7 @@ use serde::Deserialize; use std::borrow::Cow; use std::cell::RefCell; -use super::error::WebGpuError; +use super::error::WebGpuResult; pub(crate) struct WebGpuRenderPass( pub(crate) RefCell, @@ -39,7 +37,7 @@ pub fn op_webgpu_render_pass_set_viewport( state: &mut OpState, args: RenderPassSetViewportArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -55,7 +53,7 @@ pub fn op_webgpu_render_pass_set_viewport( args.max_depth, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -72,7 +70,7 @@ pub fn op_webgpu_render_pass_set_scissor_rect( state: &mut OpState, args: RenderPassSetScissorRectArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -86,7 +84,7 @@ pub fn op_webgpu_render_pass_set_scissor_rect( args.height, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -109,7 +107,7 @@ pub fn op_webgpu_render_pass_set_blend_color( state: &mut OpState, args: RenderPassSetBlendColorArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -125,7 +123,7 @@ pub fn op_webgpu_render_pass_set_blend_color( }, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -139,7 +137,7 @@ pub fn op_webgpu_render_pass_set_stencil_reference( state: &mut OpState, args: RenderPassSetStencilReferenceArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -150,7 +148,7 @@ pub fn op_webgpu_render_pass_set_stencil_reference( args.reference, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -165,7 +163,7 @@ pub fn op_webgpu_render_pass_begin_pipeline_statistics_query( state: &mut OpState, args: RenderPassBeginPipelineStatisticsQueryArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -183,7 +181,7 @@ pub fn op_webgpu_render_pass_begin_pipeline_statistics_query( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -196,7 +194,7 @@ pub fn op_webgpu_render_pass_end_pipeline_statistics_query( state: &mut OpState, args: RenderPassEndPipelineStatisticsQueryArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -208,7 +206,7 @@ pub fn op_webgpu_render_pass_end_pipeline_statistics_query( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -223,7 +221,7 @@ pub fn op_webgpu_render_pass_write_timestamp( state: &mut OpState, args: RenderPassWriteTimestampArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -241,7 +239,7 @@ pub fn op_webgpu_render_pass_write_timestamp( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -255,7 +253,7 @@ pub fn op_webgpu_render_pass_execute_bundles( state: &mut OpState, args: RenderPassExecuteBundlesArgs, _zero_copy: Option, -) -> Result { +) -> Result { let mut render_bundle_ids = vec![]; for rid in &args.bundles { @@ -279,7 +277,7 @@ pub fn op_webgpu_render_pass_execute_bundles( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -293,7 +291,7 @@ pub fn op_webgpu_render_pass_end_pass( state: &mut OpState, args: RenderPassEndPassArgs, _zero_copy: Option, -) -> Result { +) -> Result { let command_encoder_resource = state .resource_table .get::( @@ -310,7 +308,7 @@ pub fn op_webgpu_render_pass_end_pass( let maybe_err = gfx_select!(command_encoder => instance.command_encoder_run_render_pass(command_encoder, render_pass)).err(); - Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) + Ok(WebGpuResult::maybe_err(maybe_err)) } #[derive(Deserialize)] @@ -328,7 +326,7 @@ pub fn op_webgpu_render_pass_set_bind_group( state: &mut OpState, args: RenderPassSetBindGroupArgs, zero_copy: Option, -) -> Result { +) -> Result { let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let bind_group_resource = state .resource_table @@ -370,7 +368,7 @@ pub fn op_webgpu_render_pass_set_bind_group( } }; - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -384,7 +382,7 @@ pub fn op_webgpu_render_pass_push_debug_group( state: &mut OpState, args: RenderPassPushDebugGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -399,7 +397,7 @@ pub fn op_webgpu_render_pass_push_debug_group( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -412,7 +410,7 @@ pub fn op_webgpu_render_pass_pop_debug_group( state: &mut OpState, args: RenderPassPopDebugGroupArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -422,7 +420,7 @@ pub fn op_webgpu_render_pass_pop_debug_group( &mut render_pass_resource.0.borrow_mut(), ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -436,7 +434,7 @@ pub fn op_webgpu_render_pass_insert_debug_marker( state: &mut OpState, args: RenderPassInsertDebugMarkerArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -451,7 +449,7 @@ pub fn op_webgpu_render_pass_insert_debug_marker( ); } - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -465,7 +463,7 @@ pub fn op_webgpu_render_pass_set_pipeline( state: &mut OpState, args: RenderPassSetPipelineArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pipeline_resource = state .resource_table .get::(args.pipeline) @@ -480,7 +478,7 @@ pub fn op_webgpu_render_pass_set_pipeline( render_pipeline_resource.0, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -497,7 +495,7 @@ pub fn op_webgpu_render_pass_set_index_buffer( state: &mut OpState, args: RenderPassSetIndexBufferArgs, _zero_copy: Option, -) -> Result { +) -> Result { let buffer_resource = state .resource_table .get::(args.buffer) @@ -514,7 +512,7 @@ pub fn op_webgpu_render_pass_set_index_buffer( std::num::NonZeroU64::new(args.size), ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -531,7 +529,7 @@ pub fn op_webgpu_render_pass_set_vertex_buffer( state: &mut OpState, args: RenderPassSetVertexBufferArgs, _zero_copy: Option, -) -> Result { +) -> Result { let buffer_resource = state .resource_table .get::(args.buffer) @@ -549,7 +547,7 @@ pub fn op_webgpu_render_pass_set_vertex_buffer( std::num::NonZeroU64::new(args.size), ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -566,7 +564,7 @@ pub fn op_webgpu_render_pass_draw( state: &mut OpState, args: RenderPassDrawArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -580,7 +578,7 @@ pub fn op_webgpu_render_pass_draw( args.first_instance, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -598,7 +596,7 @@ pub fn op_webgpu_render_pass_draw_indexed( state: &mut OpState, args: RenderPassDrawIndexedArgs, _zero_copy: Option, -) -> Result { +) -> Result { let render_pass_resource = state .resource_table .get::(args.render_pass_rid) @@ -613,7 +611,7 @@ pub fn op_webgpu_render_pass_draw_indexed( args.first_instance, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -628,7 +626,7 @@ pub fn op_webgpu_render_pass_draw_indirect( state: &mut OpState, args: RenderPassDrawIndirectArgs, _zero_copy: Option, -) -> Result { +) -> Result { let buffer_resource = state .resource_table .get::(args.indirect_buffer) @@ -644,7 +642,7 @@ pub fn op_webgpu_render_pass_draw_indirect( args.indirect_offset, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } #[derive(Deserialize)] @@ -659,7 +657,7 @@ pub fn op_webgpu_render_pass_draw_indexed_indirect( state: &mut OpState, args: RenderPassDrawIndexedIndirectArgs, _zero_copy: Option, -) -> Result { +) -> Result { let buffer_resource = state .resource_table .get::(args.indirect_buffer) @@ -675,5 +673,5 @@ pub fn op_webgpu_render_pass_draw_indexed_indirect( args.indirect_offset, ); - Ok(json!({})) + Ok(WebGpuResult::empty()) } diff --git a/op_crates/webgpu/sampler.rs b/op_crates/webgpu/sampler.rs index b759d0c117..5e0ebc61ef 100644 --- a/op_crates/webgpu/sampler.rs +++ b/op_crates/webgpu/sampler.rs @@ -2,15 +2,13 @@ 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::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; use serde::Deserialize; use std::borrow::Cow; -use super::error::WebGpuError; +use super::error::WebGpuResult; pub(crate) struct WebGpuSampler(pub(crate) wgpu_core::id::SamplerId); impl Resource for WebGpuSampler { @@ -83,7 +81,7 @@ pub fn op_webgpu_create_sampler( state: &mut OpState, args: CreateSamplerArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -123,8 +121,5 @@ pub fn op_webgpu_create_sampler( let rid = state.resource_table.add(WebGpuSampler(sampler)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } diff --git a/op_crates/webgpu/shader.rs b/op_crates/webgpu/shader.rs index 63578ce64a..0e653b470e 100644 --- a/op_crates/webgpu/shader.rs +++ b/op_crates/webgpu/shader.rs @@ -3,15 +3,13 @@ use deno_core::error::bad_resource_id; use deno_core::error::null_opbuf; use deno_core::error::AnyError; -use deno_core::serde_json::json; -use deno_core::serde_json::Value; use deno_core::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; use serde::Deserialize; use std::borrow::Cow; -use super::error::WebGpuError; +use super::error::WebGpuResult; pub(crate) struct WebGpuShaderModule(pub(crate) wgpu_core::id::ShaderModuleId); impl Resource for WebGpuShaderModule { @@ -33,7 +31,7 @@ pub fn op_webgpu_create_shader_module( state: &mut OpState, args: CreateShaderModuleArgs, zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -77,8 +75,5 @@ pub fn op_webgpu_create_shader_module( let rid = state.resource_table.add(WebGpuShaderModule(shader_module)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } diff --git a/op_crates/webgpu/texture.rs b/op_crates/webgpu/texture.rs index 24824215cb..28b8ca1a4f 100644 --- a/op_crates/webgpu/texture.rs +++ b/op_crates/webgpu/texture.rs @@ -2,15 +2,13 @@ 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::ResourceId; use deno_core::ZeroCopyBuf; use deno_core::{OpState, Resource}; use serde::Deserialize; use std::borrow::Cow; -use super::error::WebGpuError; +use super::error::WebGpuResult; pub(crate) struct WebGpuTexture(pub(crate) wgpu_core::id::TextureId); impl Resource for WebGpuTexture { fn name(&self) -> Cow { @@ -148,7 +146,7 @@ pub fn op_webgpu_create_texture( state: &mut OpState, args: CreateTextureArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let device_resource = state .resource_table @@ -186,10 +184,7 @@ pub fn op_webgpu_create_texture( let rid = state.resource_table.add(WebGpuTexture(texture)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } #[derive(Deserialize)] @@ -210,7 +205,7 @@ pub fn op_webgpu_create_texture_view( state: &mut OpState, args: CreateTextureViewArgs, _zero_copy: Option, -) -> Result { +) -> Result { let instance = state.borrow::(); let texture_resource = state .resource_table @@ -250,8 +245,5 @@ pub fn op_webgpu_create_texture_view( let rid = state.resource_table.add(WebGpuTextureView(texture_view)); - Ok(json!({ - "rid": rid, - "err": maybe_err.map(WebGpuError::from) - })) + Ok(WebGpuResult::rid_err(rid, maybe_err)) } diff --git a/op_crates/websocket/01_websocket.js b/op_crates/websocket/01_websocket.js index 67fc0e4812..60fd7d4672 100644 --- a/op_crates/websocket/01_websocket.js +++ b/op_crates/websocket/01_websocket.js @@ -99,9 +99,7 @@ this.#url = wsURL.href; - core.jsonOpSync("op_ws_check_permission", { - url: this.#url, - }); + core.jsonOpSync("op_ws_check_permission", this.#url); if (protocols && typeof protocols === "string") { protocols = [protocols]; @@ -311,7 +309,7 @@ while (this.#readyState === OPEN) { const message = await core.jsonOpAsync( "op_ws_next_event", - { rid: this.#rid }, + this.#rid, ); switch (message.kind) { diff --git a/op_crates/websocket/lib.rs b/op_crates/websocket/lib.rs index 79ddbbee27..1e6eaafb7e 100644 --- a/op_crates/websocket/lib.rs +++ b/op_crates/websocket/lib.rs @@ -82,28 +82,22 @@ impl Resource for WsStreamResource { impl WsStreamResource {} -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CheckPermissionArgs { - url: String, -} - // This op is needed because creating a WS instance in JavaScript is a sync // operation and should throw error when permissions are not fulfilled, // but actual op that connects WS is async. pub fn op_ws_check_permission( state: &mut OpState, - args: CheckPermissionArgs, + url: String, _zero_copy: Option, -) -> Result +) -> Result<(), AnyError> where WP: WebSocketPermissions + 'static, { state .borrow::() - .check_net_url(&url::Url::parse(&args.url)?)?; + .check_net_url(&url::Url::parse(&url)?)?; - Ok(json!({})) + Ok(()) } #[derive(Deserialize)] @@ -224,7 +218,7 @@ pub async fn op_ws_send( state: Rc>, args: SendArgs, buf: Option, -) -> Result { +) -> Result<(), AnyError> { let msg = match args.kind.as_str() { "text" => Message::Text(args.text.unwrap()), "binary" => Message::Binary(buf.ok_or_else(null_opbuf)?.to_vec()), @@ -240,7 +234,7 @@ pub async fn op_ws_send( .ok_or_else(bad_resource_id)?; let mut tx = RcRef::map(&resource, |r| &r.tx).borrow_mut().await; tx.send(msg).await?; - Ok(json!({})) + Ok(()) } #[derive(Deserialize)] @@ -255,7 +249,7 @@ pub async fn op_ws_close( state: Rc>, args: CloseArgs, _bufs: Option, -) -> Result { +) -> Result<(), AnyError> { let rid = args.rid; let msg = Message::Close(args.code.map(|c| CloseFrame { code: CloseCode::from(c), @@ -272,24 +266,18 @@ pub async fn op_ws_close( .ok_or_else(bad_resource_id)?; let mut tx = RcRef::map(&resource, |r| &r.tx).borrow_mut().await; tx.send(msg).await?; - Ok(json!({})) -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct NextEventArgs { - rid: ResourceId, + Ok(()) } pub async fn op_ws_next_event( state: Rc>, - args: NextEventArgs, + rid: ResourceId, _bufs: Option, ) -> Result { let resource = state .borrow_mut() .resource_table - .get::(args.rid) + .get::(rid) .ok_or_else(bad_resource_id)?; let mut rx = RcRef::map(&resource, |r| &r.rx).borrow_mut().await; @@ -325,7 +313,7 @@ pub async fn op_ws_next_event( Some(Ok(Message::Pong(_))) => json!({ "kind": "pong" }), Some(Err(_)) => json!({ "kind": "error" }), None => { - state.borrow_mut().resource_table.close(args.rid).unwrap(); + state.borrow_mut().resource_table.close(rid).unwrap(); json!({ "kind": "closed" }) } }; diff --git a/runtime/js/11_timers.js b/runtime/js/11_timers.js index 200c764b7d..046609f75c 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 2917ec004b..b111957132 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 f150c38b6a..e792476408 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 9081d0ef10..56fb94f26b 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 23c3d8de60..0ce8317751 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 c48d410f19..06ad3a29cf 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 d7ed5a4336..7a81ca4251 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 fd037b81f3..5ebcfddada 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 01f554b360..cd8015e94c 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 2a70986f8d..e222a91995 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 e9f683376d..da43afaac2 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 2e98a4f5ad..9b23b1ec19 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 a2fff2571c..596565bed1 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 bc166b4ad9..d965f768df 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, -) -> Result { +) -> Result { 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>, args: OpenArgs, _zero_copy: Option, -) -> Result { +) -> Result { 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, -) -> Result { +) -> Result { 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>, args: SeekArgs, _zero_copy: Option, -) -> Result { +) -> Result { 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, -) -> Result { - 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>, - args: FdatasyncArgs, + rid: ResourceId, _zero_copy: Option, -) -> Result { - 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, -) -> Result { - 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>, - args: FsyncArgs, + rid: ResourceId, _zero_copy: Option, -) -> Result { - 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, -) -> Result { +) -> Result { 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>, - args: FstatArgs, + rid: ResourceId, _zero_copy: Option, -) -> Result { +) -> Result { 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, + Ok(get_stat(metadata)) } #[allow(clippy::unnecessary_wraps)] fn op_umask( state: &mut OpState, - args: UmaskArgs, + mask: Option, _zero_copy: Option, -) -> Result { +) -> Result { 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, -) -> Result { - let d = PathBuf::from(&args.directory); +) -> Result<(), AnyError> { + let d = PathBuf::from(&directory); state.borrow::().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, -) -> Result { +) -> Result<(), AnyError> { let path = Path::new(&args.path).to_path_buf(); let mode = args.mode.unwrap_or(0o777) & 0o777; state.borrow::().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>, args: MkdirArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> 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>, args: ChmodArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> Result<(), AnyError> { let path = Path::new(&args.path).to_path_buf(); state.borrow::().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>, args: ChownArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> 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>, args: RemoveArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> 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>, args: CopyFileArgs, _zero_copy: Option, -) -> Result { +) -> 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) -> Value { +fn to_msec(maybe_time: Result) -> Option { 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, + atime: Option, + birthtime: Option, + // 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, -) -> Result { +) -> Result { let path = PathBuf::from(&args.path); let lstat = args.lstat; state.borrow::().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>, args: StatArgs, _zero_copy: Option, -) -> Result { +) -> Result { 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, -) -> Result { - let path = PathBuf::from(&args.path); +) -> Result { + let path = PathBuf::from(&path); let permissions = state.borrow::(); 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>, - args: RealpathArgs, + path: String, _zero_copy: Option, -) -> Result { - let path = PathBuf::from(&args.path); +) -> Result { + 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, -) -> Result { - let path = PathBuf::from(&args.path); +) -> Result, AnyError> { + let path = PathBuf::from(&path); state.borrow::().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>, - args: ReadDirArgs, + path: String, _zero_copy: Option, -) -> Result { - let path = PathBuf::from(&args.path); +) -> Result, AnyError> { + let path = PathBuf::from(&path); { let state = state.borrow(); state.borrow::().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, -) -> Result { +) -> 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>, args: RenameArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> 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>, args: LinkArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> 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>, args: SymlinkArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { - let path = PathBuf::from(&args.path); +) -> Result { + let path = PathBuf::from(&path); state.borrow::().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>, - args: ReadLinkArgs, + path: String, _zero_copy: Option, -) -> Result { - let path = PathBuf::from(&args.path); +) -> Result { + let path = PathBuf::from(&path); { let state = state.borrow(); state.borrow::().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, -) -> Result { +) -> 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>, args: FtruncateArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> 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>, args: TruncateArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> Result { 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>, args: MakeTempArgs, _zero_copy: Option, -) -> Result { +) -> Result { 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, -) -> Result { +) -> Result { 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>, args: MakeTempArgs, _zero_copy: Option, -) -> Result { +) -> Result { 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, -) -> Result { +) -> 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>, args: FutimeArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.utime"); let path = PathBuf::from(&args.path); @@ -1676,14 +1658,14 @@ fn op_utime_sync( state.borrow::().write.check(&path)?; filetime::set_file_times(path, atime, mtime)?; - Ok(json!({})) + Ok(()) } async fn op_utime_async( state: Rc>, args: UtimeArgs, _zero_copy: Option, -) -> Result { +) -> 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, -) -> Result { +) -> Result { let path = current_dir()?; state .borrow::() .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 fed28a3d29..a64f31a333 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, -) -> Result { +) -> Result { let (sender, receiver) = mpsc::channel::>(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>, - args: PollArgs, + rid: ResourceId, _zero_copy: Option, -) -> Result { +) -> Result, AnyError> { let resource = state .borrow() .resource_table - .get::(args.rid) + .get::(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 e5a571f811..f8ab92704c 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>, - args: ShutdownArgs, + rid: ResourceId, _zero_copy: Option, -) -> Result { +) -> 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::() { 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 7d81fcee05..224fb5570f 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>, - args: Value, + args: AcceptArgs, _buf: Option, ) -> Result { - 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>, - args: Value, + args: ReceiveArgs, zero_copy: Option, ) -> Result { - 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>, - args: Value, + args: SendArgs, zero_copy: Option, ) -> Result { 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>, - args: Value, + args: ConnectArgs, _zero_copy: Option, ) -> Result { - 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, ) -> Result { let permissions = state.borrow::(); - 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 0cc001ab48..86c5ab8a04 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 500c023aa6..3e6feacfef 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, -) -> Result { +) -> Result { let current_exe = env::current_exe().unwrap(); state .borrow::() @@ -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 { + 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, -) -> Result { +) -> Result<(), AnyError> { state.borrow::().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, -) -> Result { +) -> Result, AnyError> { state.borrow::().env.check()?; - let v = env::vars().collect::>(); - 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, -) -> Result { +) -> Result, AnyError> { state.borrow::().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, -) -> Result { +) -> Result<(), AnyError> { state.borrow::().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, -) -> Result { - std::process::exit(args.code) +) -> Result<(), AnyError> { + std::process::exit(code) } fn op_loadavg( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option, -) -> Result { +) -> Result<(f64, f64, f64), AnyError> { super::check_unstable(state, "Deno.loadavg"); state.borrow::().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, -) -> Result { +) -> Result { super::check_unstable(state, "Deno.hostname"); state.borrow::().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, -) -> Result { +) -> Result { super::check_unstable(state, "Deno.osRelease"); state.borrow::().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, -) -> Result { +) -> Result, AnyError> { super::check_unstable(state, "Deno.systemMemoryInfo"); state.borrow::().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, + speed: Option, +} + fn op_system_cpu_info( state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option, -) -> Result { +) -> Result { super::check_unstable(state, "Deno.systemCpuInfo"); state.borrow::().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 61eed6bf4e..be8c9974cc 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, -) -> Result { +) -> Result { let permissions = state.borrow::(); 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, -) -> Result { +) -> Result { let permissions = state.borrow_mut::(); 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, -) -> Result { +) -> Result { let permissions = state.borrow_mut::(); 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), AnyError> { diff --git a/runtime/ops/plugin.rs b/runtime/ops/plugin.rs index 709c5730de..0397dbca31 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, -) -> Result { - let filename = PathBuf::from(&args.filename); +) -> Result { + let filename = PathBuf::from(&filename); super::check_unstable(state, "Deno.openPlugin"); let permissions = state.borrow::(); @@ -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 d6b4dcc1ff..c2ca2c6872 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, + stdin_rid: Option, + stdout_rid: Option, + stderr_rid: Option, +} + fn op_run( state: &mut OpState, run_args: RunArgs, _zero_copy: Option, -) -> Result { +) -> Result { state.borrow::().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>, - args: RunStatusArgs, + rid: ResourceId, _zero_copy: Option, -) -> Result { - let rid = args.rid; - +) -> Result { { let s = state.borrow(); s.borrow::().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, -) -> Result { +) -> Result<(), AnyError> { super::check_unstable(state, "Deno.kill"); state.borrow::().run.check()?; kill(args.pid, args.signo)?; - Ok(json!({})) + Ok(()) } diff --git a/runtime/ops/runtime.rs b/runtime/ops/runtime.rs index 9d29671c9c..ef7445b119 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, -) -> Result { +) -> Result { let main = state.borrow::().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, -) -> Result { +) -> Result { let m = state.borrow::(); let combined = m.combined_metrics(); let unstable_checker = state.borrow::(); @@ -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 ef29ddec70..5235da6120 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)] @@ -52,46 +49,29 @@ 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, -) -> Result { +) -> Result { 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>, - args: SignalArgs, + rid: ResourceId, _zero_copy: Option, -) -> Result { +) -> Result { 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, -) -> Result { +) -> 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, -) -> Result { +) -> Result<(), AnyError> { unimplemented!(); } #[cfg(not(unix))] fn op_signal_unbind( _state: &mut OpState, - _args: Value, + _args: (), _zero_copy: Option, -) -> Result { +) -> Result<(), AnyError> { unimplemented!(); } #[cfg(not(unix))] async fn op_signal_poll( _state: Rc>, - _args: Value, + _args: (), _zero_copy: Option, -) -> Result { +) -> Result<(), AnyError> { unimplemented!(); } diff --git a/runtime/ops/timers.rs b/runtime/ops/timers.rs index c709e3173a..428d4ecea7 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, -) -> Result { +) -> Result<(), AnyError> { let global_timer = state.borrow_mut::(); 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, -) -> Result { - 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::(); global_timer.new_timeout(deadline); - Ok(json!({})) + Ok(()) } async fn op_global_timer( state: Rc>, - _args: Value, + _args: (), _zero_copy: Option, -) -> Result { +) -> Result<(), AnyError> { let maybe_timer_fut = { let mut s = state.borrow_mut(); let global_timer = s.borrow_mut::(); @@ -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, -) -> Result { +) -> 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 00f000a97a..e0cb992f01 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>, - args: AcceptTlsArgs, + rid: ResourceId, _zero_copy: Option, ) -> Result { - let rid = args.rid; - let resource = state .borrow() .resource_table diff --git a/runtime/ops/tty.rs b/runtime/ops/tty.rs index 6253cc8370..9af72b5cde 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, -) -> Result { +) -> 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, -) -> Result { - let rid = args.rid; - +) -> Result { 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, ) -> Result { 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 7918b97eac..5f63a03b7a 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 6891241dd4..d8e60171e0 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); -#[derive(Deserialize)] -struct HostUnhandledErrorArgs { - message: String, -} - pub struct WorkerThread { join_handle: JoinHandle>, 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, -) -> Result { +) -> Result { 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::() .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, -) -> Result { - let id = args.id as u32; +) -> Result<(), AnyError> { let worker_thread = state .borrow_mut::() .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>, id: u32) { /// Get message from guest worker as host async fn op_host_get_message( state: Rc>, - args: WorkerArgs, + id: WorkerId, _zero_copy: Option, ) -> Result { - let id = args.id as u32; - let worker_handle = { let s = state.borrow(); let workers_table = s.borrow::(); @@ -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, -) -> Result { +) -> 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(()) }