1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-11 16:42:21 -05:00

refactor: convert ops to use serde_v8 (#10009)

This commit rewrites most of the ops to use "serde_v8" instead
of "json" serialization.
This commit is contained in:
Aaron O'Mullan 2021-04-05 18:40:24 +02:00 committed by GitHub
parent 284e6c3039
commit 2aed322dd5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
49 changed files with 840 additions and 980 deletions

View file

@ -37,7 +37,7 @@
arrayBufferView.byteOffset, arrayBufferView.byteOffset,
arrayBufferView.byteLength, arrayBufferView.byteLength,
); );
core.jsonOpSync("op_crypto_get_random_values", {}, ui8); core.jsonOpSync("op_crypto_get_random_values", null, ui8);
return arrayBufferView; return arrayBufferView;
} }

View file

@ -4,8 +4,6 @@
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::JsRuntime; use deno_core::JsRuntime;
use deno_core::OpState; use deno_core::OpState;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
@ -29,9 +27,9 @@ pub fn init(isolate: &mut JsRuntime) {
pub fn op_crypto_get_random_values( pub fn op_crypto_get_random_values(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let mut zero_copy = zero_copy.ok_or_else(null_opbuf)?; let mut zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let maybe_seeded_rng = state.try_borrow_mut::<StdRng>(); let maybe_seeded_rng = state.try_borrow_mut::<StdRng>();
if let Some(seeded_rng) = maybe_seeded_rng { if let Some(seeded_rng) = maybe_seeded_rng {
@ -41,7 +39,7 @@ pub fn op_crypto_get_random_values(
rng.fill(&mut *zero_copy); rng.fill(&mut *zero_copy);
} }
Ok(json!({})) Ok(())
} }
pub fn get_declaration() -> PathBuf { pub fn get_declaration() -> PathBuf {

View file

@ -884,29 +884,29 @@
if (body != null) { if (body != null) {
zeroCopy = new Uint8Array(body.buffer, body.byteOffset, body.byteLength); 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<string,string[]>, url: string, responseRid: number}>} * @returns {Promise<{status: number, statusText: string, headers: Record<string,string[]>, url: string, responseRid: number}>}
*/ */
function opFetchSend(args) { function opFetchSend(rid) {
return core.jsonOpAsync("op_fetch_send", args); return core.jsonOpAsync("op_fetch_send", rid);
} }
/** /**
* @param {{rid: number}} args * @param {number} rid
* @param {Uint8Array} body * @param {Uint8Array} body
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
function opFetchRequestWrite(args, body) { function opFetchRequestWrite(rid, body) {
const zeroCopy = new Uint8Array( const zeroCopy = new Uint8Array(
body.buffer, body.buffer,
body.byteOffset, body.byteOffset,
body.byteLength, 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]; const NULL_BODY_STATUS = [101, 204, 205, 304];
@ -1276,7 +1276,7 @@
*/ */
async write(chunk, controller) { async write(chunk, controller) {
try { try {
await opFetchRequestWrite({ rid: requestBodyRid }, chunk); await opFetchRequestWrite(requestBodyRid, chunk);
} catch (err) { } catch (err) {
controller.error(err); controller.error(err);
} }
@ -1288,7 +1288,7 @@
body.pipeTo(writer); body.pipeTo(writer);
} }
return await opFetchSend({ rid: requestRid }); return await opFetchSend(requestRid);
} }
/** /**
@ -1400,9 +1400,9 @@
async pull(controller) { async pull(controller) {
try { try {
const chunk = new Uint8Array(16 * 1024 + 256); const chunk = new Uint8Array(16 * 1024 + 256);
const { read } = await core.jsonOpAsync( const read = await core.jsonOpAsync(
"op_fetch_response_read", "op_fetch_response_read",
{ rid }, rid,
chunk, chunk,
); );
if (read != 0) { if (read != 0) {

View file

@ -10,8 +10,6 @@ use deno_core::error::AnyError;
use deno_core::futures::Future; use deno_core::futures::Future;
use deno_core::futures::Stream; use deno_core::futures::Stream;
use deno_core::futures::StreamExt; 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::url::Url;
use deno_core::AsyncRefCell; use deno_core::AsyncRefCell;
use deno_core::CancelFuture; use deno_core::CancelFuture;
@ -34,6 +32,7 @@ use reqwest::Client;
use reqwest::Method; use reqwest::Method;
use reqwest::Response; use reqwest::Response;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use std::convert::From; use std::convert::From;
@ -121,11 +120,18 @@ pub struct FetchArgs {
has_body: bool, has_body: bool,
} }
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FetchReturn {
request_rid: ResourceId,
request_body_rid: Option<ResourceId>,
}
pub fn op_fetch<FP>( pub fn op_fetch<FP>(
state: &mut OpState, state: &mut OpState,
args: FetchArgs, args: FetchArgs,
data: Option<ZeroCopyBuf>, data: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> ) -> Result<FetchReturn, AnyError>
where where
FP: FetchPermissions + 'static, FP: FetchPermissions + 'static,
{ {
@ -164,7 +170,7 @@ where
let mut request = client.request(method, url); 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 { match data {
None => { None => {
// If no body is passed, we return a writer for streaming the body. // If no body is passed, we return a writer for streaming the body.
@ -201,27 +207,31 @@ where
.resource_table .resource_table
.add(FetchRequestResource(Box::pin(fut))); .add(FetchRequestResource(Box::pin(fut)));
Ok(json!({ Ok(FetchReturn {
"requestRid": request_rid, request_rid,
"requestBodyRid": maybe_request_body_rid request_body_rid,
})) })
} }
#[derive(Deserialize)] #[derive(Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct FetchSendArgs { pub struct FetchResponse {
rid: ResourceId, status: u16,
status_text: String,
headers: Vec<(String, String)>,
url: String,
response_rid: ResourceId,
} }
pub async fn op_fetch_send( pub async fn op_fetch_send(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: FetchSendArgs, rid: ResourceId,
_data: Option<ZeroCopyBuf>, _data: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<FetchResponse, AnyError> {
let request = state let request = state
.borrow_mut() .borrow_mut()
.resource_table .resource_table
.take::<FetchRequestResource>(args.rid) .take::<FetchRequestResource>(rid)
.ok_or_else(bad_resource_id)?; .ok_or_else(bad_resource_id)?;
let request = Rc::try_unwrap(request) let request = Rc::try_unwrap(request)
@ -266,27 +276,20 @@ pub async fn op_fetch_send(
cancel: CancelHandle::default(), cancel: CancelHandle::default(),
}); });
Ok(json!({ Ok(FetchResponse {
"status": status.as_u16(), status: status.as_u16(),
"statusText": status.canonical_reason().unwrap_or(""), status_text: status.canonical_reason().unwrap_or("").to_string(),
"headers": res_headers, headers: res_headers,
"url": url, url,
"responseRid": rid, response_rid: rid,
})) })
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FetchRequestWriteArgs {
rid: ResourceId,
} }
pub async fn op_fetch_request_write( pub async fn op_fetch_request_write(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: FetchRequestWriteArgs, rid: ResourceId,
data: Option<ZeroCopyBuf>, data: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let rid = args.rid;
let data = data.ok_or_else(null_opbuf)?; let data = data.ok_or_else(null_opbuf)?;
let buf = Vec::from(&*data); let buf = Vec::from(&*data);
@ -299,21 +302,14 @@ pub async fn op_fetch_request_write(
let cancel = RcRef::map(resource, |r| &r.cancel); let cancel = RcRef::map(resource, |r| &r.cancel);
body.send(Ok(buf)).or_cancel(cancel).await??; body.send(Ok(buf)).or_cancel(cancel).await??;
Ok(json!({})) Ok(())
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FetchResponseReadArgs {
rid: ResourceId,
} }
pub async fn op_fetch_response_read( pub async fn op_fetch_response_read(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: FetchResponseReadArgs, rid: ResourceId,
data: Option<ZeroCopyBuf>, data: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<usize, AnyError> {
let rid = args.rid;
let data = data.ok_or_else(null_opbuf)?; let data = data.ok_or_else(null_opbuf)?;
let resource = state let resource = state
@ -325,7 +321,7 @@ pub async fn op_fetch_response_read(
let cancel = RcRef::map(resource, |r| &r.cancel); let cancel = RcRef::map(resource, |r| &r.cancel);
let mut buf = data.clone(); let mut buf = data.clone();
let read = reader.read(&mut buf).try_or_cancel(cancel).await?; let read = reader.read(&mut buf).try_or_cancel(cancel).await?;
Ok(json!({ "read": read })) Ok(read)
} }
struct FetchRequestResource( struct FetchRequestResource(
@ -391,7 +387,7 @@ pub fn op_create_http_client<FP>(
state: &mut OpState, state: &mut OpState,
args: CreateHttpClientOptions, args: CreateHttpClientOptions,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> ) -> Result<ResourceId, AnyError>
where where
FP: FetchPermissions + 'static, FP: FetchPermissions + 'static,
{ {
@ -411,7 +407,7 @@ where
.unwrap(); .unwrap();
let rid = state.resource_table.add(HttpClientResource::new(client)); let rid = state.resource_table.add(HttpClientResource::new(client));
Ok(json!(rid)) Ok(rid)
} }
fn get_cert_data( fn get_cert_data(

View file

@ -4,8 +4,6 @@ use deno_core::error::generic_error;
use deno_core::error::type_error; use deno_core::error::type_error;
use deno_core::error::uri_error; use deno_core::error::uri_error;
use deno_core::error::AnyError; 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::form_urlencoded;
use deno_core::url::quirks; use deno_core::url::quirks;
use deno_core::url::Url; use deno_core::url::Url;
@ -34,13 +32,28 @@ pub struct UrlParseArgs {
set_username: Option<String>, set_username: Option<String>,
} }
#[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 /// Parse `UrlParseArgs::href` with an optional `UrlParseArgs::base_href`, or an
/// optional part to "set" after parsing. Return `UrlParts`. /// optional part to "set" after parsing. Return `UrlParts`.
pub fn op_url_parse( pub fn op_url_parse(
_state: &mut deno_core::OpState, _state: &mut deno_core::OpState,
args: UrlParseArgs, args: UrlParseArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<UrlParts, AnyError> {
let base_url = args let base_url = args
.base_href .base_href
.as_ref() .as_ref()
@ -75,20 +88,6 @@ pub fn op_url_parse(
.map_err(|_| uri_error("Invalid username"))?; .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:` // TODO(nayeemrmn): Panic that occurs in rust-url for the `non-spec:`
// url-constructor wpt tests: https://github.com/servo/rust-url/issues/670. // url-constructor wpt tests: https://github.com/servo/rust-url/issues/670.
let username = catch_unwind(|| quirks::username(&url)).map_err(|_| { let username = catch_unwind(|| quirks::username(&url)).map_err(|_| {
@ -102,41 +101,42 @@ pub fn op_url_parse(
.unwrap_or_default() .unwrap_or_default()
)) ))
})?; })?;
Ok(json!(UrlParts { Ok(UrlParts {
href: quirks::href(&url), href: quirks::href(&url).to_string(),
hash: quirks::hash(&url), hash: quirks::hash(&url).to_string(),
host: quirks::host(&url), host: quirks::host(&url).to_string(),
hostname: quirks::hostname(&url), hostname: quirks::hostname(&url).to_string(),
origin: &quirks::origin(&url), origin: quirks::origin(&url),
password: quirks::password(&url), password: quirks::password(&url).to_string(),
pathname: quirks::pathname(&url), pathname: quirks::pathname(&url).to_string(),
port: quirks::port(&url), port: quirks::port(&url).to_string(),
protocol: quirks::protocol(&url), protocol: quirks::protocol(&url).to_string(),
search: quirks::search(&url), search: quirks::search(&url).to_string(),
username, username: username.to_string(),
})) })
} }
pub fn op_url_parse_search_params( pub fn op_url_parse_search_params(
_state: &mut deno_core::OpState, _state: &mut deno_core::OpState,
args: String, args: String,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Vec<(String, String)>, AnyError> {
let search_params: Vec<_> = form_urlencoded::parse(args.as_bytes()) let search_params: Vec<_> = form_urlencoded::parse(args.as_bytes())
.into_iter() .into_iter()
.map(|(k, v)| (k.as_ref().to_owned(), v.as_ref().to_owned()))
.collect(); .collect();
Ok(json!(search_params)) Ok(search_params)
} }
pub fn op_url_stringify_search_params( pub fn op_url_stringify_search_params(
_state: &mut deno_core::OpState, _state: &mut deno_core::OpState,
args: Vec<(String, String)>, args: Vec<(String, String)>,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<String, AnyError> {
let search = form_urlencoded::Serializer::new(String::new()) let search = form_urlencoded::Serializer::new(String::new())
.extend_pairs(args) .extend_pairs(args)
.finish(); .finish();
Ok(json!(search)) Ok(search)
} }
/// Load and execute the javascript code. /// Load and execute the javascript code.

View file

@ -2,15 +2,13 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
use serde::Deserialize; use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use super::error::WebGpuError; use super::error::WebGpuResult;
pub(crate) struct WebGpuBindGroupLayout( pub(crate) struct WebGpuBindGroupLayout(
pub(crate) wgpu_core::id::BindGroupLayoutId, pub(crate) wgpu_core::id::BindGroupLayoutId,
@ -83,7 +81,7 @@ pub fn op_webgpu_create_bind_group_layout(
state: &mut OpState, state: &mut OpState,
args: CreateBindGroupLayoutArgs, args: CreateBindGroupLayoutArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -207,10 +205,7 @@ pub fn op_webgpu_create_bind_group_layout(
.resource_table .resource_table
.add(WebGpuBindGroupLayout(bind_group_layout)); .add(WebGpuBindGroupLayout(bind_group_layout));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -225,7 +220,7 @@ pub fn op_webgpu_create_pipeline_layout(
state: &mut OpState, state: &mut OpState,
args: CreatePipelineLayoutArgs, args: CreatePipelineLayoutArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -259,10 +254,7 @@ pub fn op_webgpu_create_pipeline_layout(
.resource_table .resource_table
.add(super::pipeline::WebGpuPipelineLayout(pipeline_layout)); .add(super::pipeline::WebGpuPipelineLayout(pipeline_layout));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -288,7 +280,7 @@ pub fn op_webgpu_create_bind_group(
state: &mut OpState, state: &mut OpState,
args: CreateBindGroupArgs, args: CreateBindGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -356,8 +348,5 @@ pub fn op_webgpu_create_bind_group(
let rid = state.resource_table.add(WebGpuBindGroup(bind_group)); let rid = state.resource_table.add(WebGpuBindGroup(bind_group));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }

View file

@ -4,8 +4,6 @@ use deno_core::error::bad_resource_id;
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::futures::channel::oneshot; 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::OpState;
use deno_core::Resource; use deno_core::Resource;
use deno_core::ResourceId; use deno_core::ResourceId;
@ -17,7 +15,7 @@ use std::rc::Rc;
use std::time::Duration; use std::time::Duration;
use super::error::DomExceptionOperationError; use super::error::DomExceptionOperationError;
use super::error::WebGpuError; use super::error::WebGpuResult;
pub(crate) struct WebGpuBuffer(pub(crate) wgpu_core::id::BufferId); pub(crate) struct WebGpuBuffer(pub(crate) wgpu_core::id::BufferId);
impl Resource for WebGpuBuffer { impl Resource for WebGpuBuffer {
@ -47,7 +45,7 @@ pub fn op_webgpu_create_buffer(
state: &mut OpState, state: &mut OpState,
args: CreateBufferArgs, args: CreateBufferArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -70,10 +68,7 @@ pub fn op_webgpu_create_buffer(
let rid = state.resource_table.add(WebGpuBuffer(buffer)); let rid = state.resource_table.add(WebGpuBuffer(buffer));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -90,7 +85,7 @@ pub async fn op_webgpu_buffer_get_map_async(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: BufferGetMapAsyncArgs, args: BufferGetMapAsyncArgs,
_bufs: Option<ZeroCopyBuf>, _bufs: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let (sender, receiver) = oneshot::channel::<Result<(), AnyError>>(); let (sender, receiver) = oneshot::channel::<Result<(), AnyError>>();
let device; let device;
@ -164,7 +159,7 @@ pub async fn op_webgpu_buffer_get_map_async(
tokio::try_join!(device_poll_fut, receiver_fut)?; tokio::try_join!(device_poll_fut, receiver_fut)?;
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -179,7 +174,7 @@ pub fn op_webgpu_buffer_get_mapped_range(
state: &mut OpState, state: &mut OpState,
args: BufferGetMappedRangeArgs, args: BufferGetMappedRangeArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let mut zero_copy = zero_copy.ok_or_else(null_opbuf)?; let mut zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let buffer_resource = state let buffer_resource = state
@ -204,9 +199,7 @@ pub fn op_webgpu_buffer_get_mapped_range(
.resource_table .resource_table
.add(WebGpuBufferMapped(slice_pointer, args.size as usize)); .add(WebGpuBufferMapped(slice_pointer, args.size as usize));
Ok(json!({ Ok(WebGpuResult::rid(rid))
"rid": rid,
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -220,7 +213,7 @@ pub fn op_webgpu_buffer_unmap(
state: &mut OpState, state: &mut OpState,
args: BufferUnmapArgs, args: BufferUnmapArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let mapped_resource = state let mapped_resource = state
.resource_table .resource_table
.take::<WebGpuBufferMapped>(args.mapped_rid) .take::<WebGpuBufferMapped>(args.mapped_rid)
@ -242,5 +235,5 @@ pub fn op_webgpu_buffer_unmap(
let maybe_err = gfx_select!(buffer => instance.buffer_unmap(buffer)).err(); 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))
} }

View file

@ -3,8 +3,6 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
@ -13,7 +11,7 @@ use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use super::error::WebGpuError; use super::error::WebGpuResult;
use super::texture::serialize_texture_format; use super::texture::serialize_texture_format;
struct WebGpuRenderBundleEncoder( struct WebGpuRenderBundleEncoder(
@ -46,7 +44,7 @@ pub fn op_webgpu_create_render_bundle_encoder(
state: &mut OpState, state: &mut OpState,
args: CreateRenderBundleEncoderArgs, args: CreateRenderBundleEncoderArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let device_resource = state let device_resource = state
.resource_table .resource_table
.get::<super::WebGpuDevice>(args.device_rid) .get::<super::WebGpuDevice>(args.device_rid)
@ -85,10 +83,7 @@ pub fn op_webgpu_create_render_bundle_encoder(
render_bundle_encoder, render_bundle_encoder,
))); )));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from),
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -102,7 +97,7 @@ pub fn op_webgpu_render_bundle_encoder_finish(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderFinishArgs, args: RenderBundleEncoderFinishArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state let render_bundle_encoder_resource = state
.resource_table .resource_table
.take::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid) .take::<WebGpuRenderBundleEncoder>(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)); let rid = state.resource_table.add(WebGpuRenderBundle(render_bundle));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -145,7 +137,7 @@ pub fn op_webgpu_render_bundle_encoder_set_bind_group(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderSetBindGroupArgs, args: RenderBundleEncoderSetBindGroupArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let bind_group_resource = state 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)] #[derive(Deserialize)]
@ -202,7 +194,7 @@ pub fn op_webgpu_render_bundle_encoder_push_debug_group(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderPushDebugGroupArgs, args: RenderBundleEncoderPushDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state let render_bundle_encoder_resource = state
.resource_table .resource_table
.get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid) .get::<WebGpuRenderBundleEncoder>(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)] #[derive(Deserialize)]
@ -229,7 +221,7 @@ pub fn op_webgpu_render_bundle_encoder_pop_debug_group(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderPopDebugGroupArgs, args: RenderBundleEncoderPopDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state let render_bundle_encoder_resource = state
.resource_table .resource_table
.get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid) .get::<WebGpuRenderBundleEncoder>(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)] #[derive(Deserialize)]
@ -255,7 +247,7 @@ pub fn op_webgpu_render_bundle_encoder_insert_debug_marker(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderInsertDebugMarkerArgs, args: RenderBundleEncoderInsertDebugMarkerArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state let render_bundle_encoder_resource = state
.resource_table .resource_table
.get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid) .get::<WebGpuRenderBundleEncoder>(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)] #[derive(Deserialize)]
@ -283,7 +275,7 @@ pub fn op_webgpu_render_bundle_encoder_set_pipeline(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderSetPipelineArgs, args: RenderBundleEncoderSetPipelineArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pipeline_resource = state let render_pipeline_resource = state
.resource_table .resource_table
.get::<super::pipeline::WebGpuRenderPipeline>(args.pipeline) .get::<super::pipeline::WebGpuRenderPipeline>(args.pipeline)
@ -298,7 +290,7 @@ pub fn op_webgpu_render_bundle_encoder_set_pipeline(
render_pipeline_resource.0, render_pipeline_resource.0,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -315,7 +307,7 @@ pub fn op_webgpu_render_bundle_encoder_set_index_buffer(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderSetIndexBufferArgs, args: RenderBundleEncoderSetIndexBufferArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state let buffer_resource = state
.resource_table .resource_table
.get::<super::buffer::WebGpuBuffer>(args.buffer) .get::<super::buffer::WebGpuBuffer>(args.buffer)
@ -335,7 +327,7 @@ pub fn op_webgpu_render_bundle_encoder_set_index_buffer(
std::num::NonZeroU64::new(args.size), std::num::NonZeroU64::new(args.size),
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -352,7 +344,7 @@ pub fn op_webgpu_render_bundle_encoder_set_vertex_buffer(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderSetVertexBufferArgs, args: RenderBundleEncoderSetVertexBufferArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state let buffer_resource = state
.resource_table .resource_table
.get::<super::buffer::WebGpuBuffer>(args.buffer) .get::<super::buffer::WebGpuBuffer>(args.buffer)
@ -370,7 +362,7 @@ pub fn op_webgpu_render_bundle_encoder_set_vertex_buffer(
std::num::NonZeroU64::new(args.size), std::num::NonZeroU64::new(args.size),
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -387,7 +379,7 @@ pub fn op_webgpu_render_bundle_encoder_draw(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderDrawArgs, args: RenderBundleEncoderDrawArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state let render_bundle_encoder_resource = state
.resource_table .resource_table
.get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid) .get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid)
@ -401,7 +393,7 @@ pub fn op_webgpu_render_bundle_encoder_draw(
args.first_instance, args.first_instance,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -419,7 +411,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indexed(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderDrawIndexedArgs, args: RenderBundleEncoderDrawIndexedArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state let render_bundle_encoder_resource = state
.resource_table .resource_table
.get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid) .get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid)
@ -434,7 +426,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indexed(
args.first_instance, args.first_instance,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -449,7 +441,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indirect(
state: &mut OpState, state: &mut OpState,
args: RenderBundleEncoderDrawIndirectArgs, args: RenderBundleEncoderDrawIndirectArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state let buffer_resource = state
.resource_table .resource_table
.get::<super::buffer::WebGpuBuffer>(args.indirect_buffer) .get::<super::buffer::WebGpuBuffer>(args.indirect_buffer)
@ -465,5 +457,5 @@ pub fn op_webgpu_render_bundle_encoder_draw_indirect(
args.indirect_offset, args.indirect_offset,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }

View file

@ -2,8 +2,6 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
@ -11,7 +9,7 @@ use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use super::error::WebGpuError; use super::error::WebGpuResult;
pub(crate) struct WebGpuCommandEncoder( pub(crate) struct WebGpuCommandEncoder(
pub(crate) wgpu_core::id::CommandEncoderId, pub(crate) wgpu_core::id::CommandEncoderId,
@ -51,7 +49,7 @@ pub fn op_webgpu_create_command_encoder(
state: &mut OpState, state: &mut OpState,
args: CreateCommandEncoderArgs, args: CreateCommandEncoderArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -73,10 +71,7 @@ pub fn op_webgpu_create_command_encoder(
.resource_table .resource_table
.add(WebGpuCommandEncoder(command_encoder)); .add(WebGpuCommandEncoder(command_encoder));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from),
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -117,7 +112,7 @@ pub fn op_webgpu_command_encoder_begin_render_pass(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderBeginRenderPassArgs, args: CommandEncoderBeginRenderPassArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
.get::<WebGpuCommandEncoder>(args.command_encoder_rid) .get::<WebGpuCommandEncoder>(args.command_encoder_rid)
@ -236,9 +231,7 @@ pub fn op_webgpu_command_encoder_begin_render_pass(
render_pass, render_pass,
))); )));
Ok(json!({ Ok(WebGpuResult::rid(rid))
"rid": rid,
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -252,7 +245,7 @@ pub fn op_webgpu_command_encoder_begin_compute_pass(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderBeginComputePassArgs, args: CommandEncoderBeginComputePassArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
.get::<WebGpuCommandEncoder>(args.command_encoder_rid) .get::<WebGpuCommandEncoder>(args.command_encoder_rid)
@ -273,9 +266,7 @@ pub fn op_webgpu_command_encoder_begin_compute_pass(
compute_pass, compute_pass,
))); )));
Ok(json!({ Ok(WebGpuResult::rid(rid))
"rid": rid,
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -293,7 +284,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_buffer(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderCopyBufferToBufferArgs, args: CommandEncoderCopyBufferToBufferArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
@ -320,7 +311,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_buffer(
args.size args.size
)).err(); )).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -362,7 +353,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_texture(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderCopyBufferToTextureArgs, args: CommandEncoderCopyBufferToTextureArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
@ -409,7 +400,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_texture(
} }
)).err(); )).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -425,7 +416,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_buffer(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderCopyTextureToBufferArgs, args: CommandEncoderCopyTextureToBufferArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
@ -471,7 +462,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_buffer(
} }
)).err(); )).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -487,7 +478,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_texture(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderCopyTextureToTextureArgs, args: CommandEncoderCopyTextureToTextureArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
@ -537,7 +528,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_texture(
} }
)).err(); )).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -551,7 +542,7 @@ pub fn op_webgpu_command_encoder_push_debug_group(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderPushDebugGroupArgs, args: CommandEncoderPushDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .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)) .command_encoder_push_debug_group(command_encoder, &args.group_label))
.err(); .err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -576,7 +567,7 @@ pub fn op_webgpu_command_encoder_pop_debug_group(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderPopDebugGroupArgs, args: CommandEncoderPopDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .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(); 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)] #[derive(Deserialize)]
@ -600,7 +591,7 @@ pub fn op_webgpu_command_encoder_insert_debug_marker(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderInsertDebugMarkerArgs, args: CommandEncoderInsertDebugMarkerArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
@ -613,7 +604,7 @@ pub fn op_webgpu_command_encoder_insert_debug_marker(
&args.marker_label &args.marker_label
)).err(); )).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -628,7 +619,7 @@ pub fn op_webgpu_command_encoder_write_timestamp(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderWriteTimestampArgs, args: CommandEncoderWriteTimestampArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
@ -648,7 +639,7 @@ pub fn op_webgpu_command_encoder_write_timestamp(
)) ))
.err(); .err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -666,7 +657,7 @@ pub fn op_webgpu_command_encoder_resolve_query_set(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderResolveQuerySetArgs, args: CommandEncoderResolveQuerySetArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
@ -693,7 +684,7 @@ pub fn op_webgpu_command_encoder_resolve_query_set(
)) ))
.err(); .err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -707,7 +698,7 @@ pub fn op_webgpu_command_encoder_finish(
state: &mut OpState, state: &mut OpState,
args: CommandEncoderFinishArgs, args: CommandEncoderFinishArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
.take::<WebGpuCommandEncoder>(args.command_encoder_rid) .take::<WebGpuCommandEncoder>(args.command_encoder_rid)
@ -728,8 +719,5 @@ pub fn op_webgpu_command_encoder_finish(
.resource_table .resource_table
.add(WebGpuCommandBuffer(command_buffer)); .add(WebGpuCommandBuffer(command_buffer));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }

View file

@ -3,8 +3,6 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
@ -12,7 +10,7 @@ use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use super::error::WebGpuError; use super::error::WebGpuResult;
pub(crate) struct WebGpuComputePass( pub(crate) struct WebGpuComputePass(
pub(crate) RefCell<wgpu_core::command::ComputePass>, pub(crate) RefCell<wgpu_core::command::ComputePass>,
@ -34,7 +32,7 @@ pub fn op_webgpu_compute_pass_set_pipeline(
state: &mut OpState, state: &mut OpState,
args: ComputePassSetPipelineArgs, args: ComputePassSetPipelineArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let compute_pipeline_resource = state let compute_pipeline_resource = state
.resource_table .resource_table
.get::<super::pipeline::WebGpuComputePipeline>(args.pipeline) .get::<super::pipeline::WebGpuComputePipeline>(args.pipeline)
@ -49,7 +47,7 @@ pub fn op_webgpu_compute_pass_set_pipeline(
compute_pipeline_resource.0, compute_pipeline_resource.0,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -65,7 +63,7 @@ pub fn op_webgpu_compute_pass_dispatch(
state: &mut OpState, state: &mut OpState,
args: ComputePassDispatchArgs, args: ComputePassDispatchArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state let compute_pass_resource = state
.resource_table .resource_table
.get::<WebGpuComputePass>(args.compute_pass_rid) .get::<WebGpuComputePass>(args.compute_pass_rid)
@ -78,7 +76,7 @@ pub fn op_webgpu_compute_pass_dispatch(
args.z, args.z,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -93,7 +91,7 @@ pub fn op_webgpu_compute_pass_dispatch_indirect(
state: &mut OpState, state: &mut OpState,
args: ComputePassDispatchIndirectArgs, args: ComputePassDispatchIndirectArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state let buffer_resource = state
.resource_table .resource_table
.get::<super::buffer::WebGpuBuffer>(args.indirect_buffer) .get::<super::buffer::WebGpuBuffer>(args.indirect_buffer)
@ -109,7 +107,7 @@ pub fn op_webgpu_compute_pass_dispatch_indirect(
args.indirect_offset, args.indirect_offset,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -124,7 +122,7 @@ pub fn op_webgpu_compute_pass_begin_pipeline_statistics_query(
state: &mut OpState, state: &mut OpState,
args: ComputePassBeginPipelineStatisticsQueryArgs, args: ComputePassBeginPipelineStatisticsQueryArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state let compute_pass_resource = state
.resource_table .resource_table
.get::<WebGpuComputePass>(args.compute_pass_rid) .get::<WebGpuComputePass>(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)] #[derive(Deserialize)]
@ -155,7 +153,7 @@ pub fn op_webgpu_compute_pass_end_pipeline_statistics_query(
state: &mut OpState, state: &mut OpState,
args: ComputePassEndPipelineStatisticsQueryArgs, args: ComputePassEndPipelineStatisticsQueryArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state let compute_pass_resource = state
.resource_table .resource_table
.get::<WebGpuComputePass>(args.compute_pass_rid) .get::<WebGpuComputePass>(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)] #[derive(Deserialize)]
@ -182,7 +180,7 @@ pub fn op_webgpu_compute_pass_write_timestamp(
state: &mut OpState, state: &mut OpState,
args: ComputePassWriteTimestampArgs, args: ComputePassWriteTimestampArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state let compute_pass_resource = state
.resource_table .resource_table
.get::<WebGpuComputePass>(args.compute_pass_rid) .get::<WebGpuComputePass>(args.compute_pass_rid)
@ -200,7 +198,7 @@ pub fn op_webgpu_compute_pass_write_timestamp(
); );
} }
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -214,7 +212,7 @@ pub fn op_webgpu_compute_pass_end_pass(
state: &mut OpState, state: &mut OpState,
args: ComputePassEndPassArgs, args: ComputePassEndPassArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
.get::<super::command_encoder::WebGpuCommandEncoder>( .get::<super::command_encoder::WebGpuCommandEncoder>(
@ -236,7 +234,7 @@ pub fn op_webgpu_compute_pass_end_pass(
)) ))
.err(); .err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -254,7 +252,7 @@ pub fn op_webgpu_compute_pass_set_bind_group(
state: &mut OpState, state: &mut OpState,
args: ComputePassSetBindGroupArgs, args: ComputePassSetBindGroupArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let bind_group_resource = state let bind_group_resource = state
.resource_table .resource_table
.get::<super::binding::WebGpuBindGroup>(args.bind_group) .get::<super::binding::WebGpuBindGroup>(args.bind_group)
@ -283,7 +281,7 @@ pub fn op_webgpu_compute_pass_set_bind_group(
); );
} }
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -297,7 +295,7 @@ pub fn op_webgpu_compute_pass_push_debug_group(
state: &mut OpState, state: &mut OpState,
args: ComputePassPushDebugGroupArgs, args: ComputePassPushDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state let compute_pass_resource = state
.resource_table .resource_table
.get::<WebGpuComputePass>(args.compute_pass_rid) .get::<WebGpuComputePass>(args.compute_pass_rid)
@ -312,7 +310,7 @@ pub fn op_webgpu_compute_pass_push_debug_group(
); );
} }
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -325,7 +323,7 @@ pub fn op_webgpu_compute_pass_pop_debug_group(
state: &mut OpState, state: &mut OpState,
args: ComputePassPopDebugGroupArgs, args: ComputePassPopDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state let compute_pass_resource = state
.resource_table .resource_table
.get::<WebGpuComputePass>(args.compute_pass_rid) .get::<WebGpuComputePass>(args.compute_pass_rid)
@ -335,7 +333,7 @@ pub fn op_webgpu_compute_pass_pop_debug_group(
&mut compute_pass_resource.0.borrow_mut(), &mut compute_pass_resource.0.borrow_mut(),
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -349,7 +347,7 @@ pub fn op_webgpu_compute_pass_insert_debug_marker(
state: &mut OpState, state: &mut OpState,
args: ComputePassInsertDebugMarkerArgs, args: ComputePassInsertDebugMarkerArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state let compute_pass_resource = state
.resource_table .resource_table
.get::<WebGpuComputePass>(args.compute_pass_rid) .get::<WebGpuComputePass>(args.compute_pass_rid)
@ -364,5 +362,5 @@ pub fn op_webgpu_compute_pass_insert_debug_marker(
); );
} }
Ok(json!({})) Ok(WebGpuResult::empty())
} }

View file

@ -1,6 +1,8 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::ResourceId;
use serde::Serialize; use serde::Serialize;
use std::convert::From;
use std::fmt; use std::fmt;
use wgpu_core::binding_model::CreateBindGroupError; use wgpu_core::binding_model::CreateBindGroupError;
use wgpu_core::binding_model::CreateBindGroupLayoutError; use wgpu_core::binding_model::CreateBindGroupLayoutError;
@ -27,6 +29,45 @@ use wgpu_core::resource::CreateSamplerError;
use wgpu_core::resource::CreateTextureError; use wgpu_core::resource::CreateTextureError;
use wgpu_core::resource::CreateTextureViewError; use wgpu_core::resource::CreateTextureViewError;
#[derive(Serialize)]
pub struct WebGpuResult {
pub rid: Option<ResourceId>,
pub err: Option<WebGpuError>,
}
impl WebGpuResult {
pub fn rid(rid: ResourceId) -> Self {
Self {
rid: Some(rid),
err: None,
}
}
pub fn rid_err<T: Into<WebGpuError>>(
rid: ResourceId,
err: Option<T>,
) -> Self {
Self {
rid: Some(rid),
err: err.map(|e| e.into()),
}
}
pub fn maybe_err<T: Into<WebGpuError>>(err: Option<T>) -> Self {
Self {
rid: None,
err: err.map(|e| e.into()),
}
}
pub fn empty() -> Self {
Self {
rid: None,
err: None,
}
}
}
#[derive(Serialize)] #[derive(Serialize)]
#[serde(tag = "type", content = "value")] #[serde(tag = "type", content = "value")]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]

View file

@ -4,13 +4,12 @@
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::error::{bad_resource_id, not_supported}; 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::OpState;
use deno_core::Resource; use deno_core::Resource;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use std::path::PathBuf; use std::path::PathBuf;
@ -19,7 +18,7 @@ pub use wgpu_core;
pub use wgpu_types; pub use wgpu_types;
use error::DomExceptionOperationError; use error::DomExceptionOperationError;
use error::WebGpuError; use error::WebGpuResult;
#[macro_use] #[macro_use]
mod macros { mod macros {
@ -113,8 +112,8 @@ pub fn get_declaration() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_webgpu.d.ts") PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_webgpu.d.ts")
} }
fn deserialize_features(features: &wgpu_types::Features) -> Vec<&str> { fn deserialize_features(features: &wgpu_types::Features) -> Vec<&'static str> {
let mut return_features: Vec<&str> = vec![]; let mut return_features: Vec<&'static str> = vec![];
if features.contains(wgpu_types::Features::DEPTH_CLAMPING) { if features.contains(wgpu_types::Features::DEPTH_CLAMPING) {
return_features.push("depth-clamping"); return_features.push("depth-clamping");
@ -191,11 +190,27 @@ pub struct RequestAdapterArgs {
power_preference: Option<String>, power_preference: Option<String>,
} }
#[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<String>,
limits: wgpu_types::Limits,
features: Vec<&'static str>,
}
pub async fn op_webgpu_request_adapter( pub async fn op_webgpu_request_adapter(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: RequestAdapterArgs, args: RequestAdapterArgs,
_bufs: Option<ZeroCopyBuf>, _bufs: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<GpuAdapterDeviceOrErr, AnyError> {
let mut state = state.borrow_mut(); let mut state = state.borrow_mut();
check_unstable(&state, "navigator.gpu.requestAdapter"); check_unstable(&state, "navigator.gpu.requestAdapter");
let instance = if let Some(instance) = state.try_borrow::<Instance>() { let instance = if let Some(instance) = state.try_borrow::<Instance>() {
@ -231,9 +246,9 @@ pub async fn op_webgpu_request_adapter(
let adapter = match res { let adapter = match res {
Ok(adapter) => adapter, Ok(adapter) => adapter,
Err(err) => { Err(err) => {
return Ok(json!({ return Ok(GpuAdapterDeviceOrErr::Error {
"err": err.to_string() err: err.to_string(),
})) })
} }
}; };
let name = gfx_select!(adapter => instance.adapter_get_info(adapter))?.name; 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 = let adapter_limits =
gfx_select!(adapter => instance.adapter_limits(adapter))?; 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)); let rid = state.resource_table.add(WebGpuAdapter(adapter));
Ok(json!({ Ok(GpuAdapterDeviceOrErr::Features(GpuAdapterDevice {
"rid": rid, rid,
"name": name, name: Some(name),
"features": features, features,
"limits": limits limits: adapter_limits,
})) }))
} }
@ -300,7 +303,7 @@ pub async fn op_webgpu_request_device(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: RequestDeviceArgs, args: RequestDeviceArgs,
_bufs: Option<ZeroCopyBuf>, _bufs: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<GpuAdapterDevice, AnyError> {
let mut state = state.borrow_mut(); let mut state = state.borrow_mut();
let adapter_resource = state let adapter_resource = state
.resource_table .resource_table
@ -437,25 +440,15 @@ pub async fn op_webgpu_request_device(
gfx_select!(device => instance.device_features(device))?; gfx_select!(device => instance.device_features(device))?;
let features = deserialize_features(&device_features); let features = deserialize_features(&device_features);
let limits = gfx_select!(device => instance.device_limits(device))?; 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)); let rid = state.resource_table.add(WebGpuDevice(device));
Ok(json!({ Ok(GpuAdapterDevice {
"rid": rid, rid,
"features": features, name: None,
"limits": json_limits, features,
})) limits,
})
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -473,7 +466,7 @@ pub fn op_webgpu_create_query_set(
state: &mut OpState, state: &mut OpState,
args: CreateQuerySetArgs, args: CreateQuerySetArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let device_resource = state let device_resource = state
.resource_table .resource_table
.get::<WebGpuDevice>(args.device_rid) .get::<WebGpuDevice>(args.device_rid)
@ -544,8 +537,5 @@ pub fn op_webgpu_create_query_set(
let rid = state.resource_table.add(WebGpuQuerySet(query_set)); let rid = state.resource_table.add(WebGpuQuerySet(query_set));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from),
}))
} }

View file

@ -2,15 +2,14 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow; use std::borrow::Cow;
use super::error::WebGpuError; use super::error::{WebGpuError, WebGpuResult};
pub(crate) struct WebGpuPipelineLayout( pub(crate) struct WebGpuPipelineLayout(
pub(crate) wgpu_core::id::PipelineLayoutId, pub(crate) wgpu_core::id::PipelineLayoutId,
@ -163,7 +162,7 @@ pub fn op_webgpu_create_compute_pipeline(
state: &mut OpState, state: &mut OpState,
args: CreateComputePipelineArgs, args: CreateComputePipelineArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -213,10 +212,7 @@ pub fn op_webgpu_create_compute_pipeline(
.resource_table .resource_table
.add(WebGpuComputePipeline(compute_pipeline)); .add(WebGpuComputePipeline(compute_pipeline));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from),
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -226,11 +222,19 @@ pub struct ComputePipelineGetBindGroupLayoutArgs {
index: u32, index: u32,
} }
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PipelineLayout {
rid: ResourceId,
label: String,
err: Option<WebGpuError>,
}
pub fn op_webgpu_compute_pipeline_get_bind_group_layout( pub fn op_webgpu_compute_pipeline_get_bind_group_layout(
state: &mut OpState, state: &mut OpState,
args: ComputePipelineGetBindGroupLayoutArgs, args: ComputePipelineGetBindGroupLayoutArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<PipelineLayout, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let compute_pipeline_resource = state let compute_pipeline_resource = state
.resource_table .resource_table
@ -246,11 +250,11 @@ pub fn op_webgpu_compute_pipeline_get_bind_group_layout(
.resource_table .resource_table
.add(super::binding::WebGpuBindGroupLayout(bind_group_layout)); .add(super::binding::WebGpuBindGroupLayout(bind_group_layout));
Ok(json!({ Ok(PipelineLayout {
"rid": rid, rid,
"label": label, label,
"err": maybe_err.map(WebGpuError::from) err: maybe_err.map(WebGpuError::from),
})) })
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -367,7 +371,7 @@ pub fn op_webgpu_create_render_pipeline(
state: &mut OpState, state: &mut OpState,
args: CreateRenderPipelineArgs, args: CreateRenderPipelineArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -601,10 +605,7 @@ pub fn op_webgpu_create_render_pipeline(
.resource_table .resource_table
.add(WebGpuRenderPipeline(render_pipeline)); .add(WebGpuRenderPipeline(render_pipeline));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -618,7 +619,7 @@ pub fn op_webgpu_render_pipeline_get_bind_group_layout(
state: &mut OpState, state: &mut OpState,
args: RenderPipelineGetBindGroupLayoutArgs, args: RenderPipelineGetBindGroupLayoutArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<PipelineLayout, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let render_pipeline_resource = state let render_pipeline_resource = state
.resource_table .resource_table
@ -634,9 +635,9 @@ pub fn op_webgpu_render_pipeline_get_bind_group_layout(
.resource_table .resource_table
.add(super::binding::WebGpuBindGroupLayout(bind_group_layout)); .add(super::binding::WebGpuBindGroupLayout(bind_group_layout));
Ok(json!({ Ok(PipelineLayout {
"rid": rid, rid,
"label": label, label,
"err": maybe_err.map(WebGpuError::from), err: maybe_err.map(WebGpuError::from),
})) })
} }

View file

@ -3,14 +3,12 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::OpState; use deno_core::OpState;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use serde::Deserialize; use serde::Deserialize;
use super::error::WebGpuError; use super::error::WebGpuResult;
type WebGpuQueue = super::WebGpuDevice; type WebGpuQueue = super::WebGpuDevice;
@ -25,7 +23,7 @@ pub fn op_webgpu_queue_submit(
state: &mut OpState, state: &mut OpState,
args: QueueSubmitArgs, args: QueueSubmitArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let queue_resource = state let queue_resource = state
.resource_table .resource_table
@ -46,7 +44,7 @@ pub fn op_webgpu_queue_submit(
let maybe_err = let maybe_err =
gfx_select!(queue => instance.queue_submit(queue, &ids)).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)] #[derive(Deserialize)]
@ -71,7 +69,7 @@ pub fn op_webgpu_write_buffer(
state: &mut OpState, state: &mut OpState,
args: QueueWriteBufferArgs, args: QueueWriteBufferArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let buffer_resource = state let buffer_resource = state
@ -97,7 +95,7 @@ pub fn op_webgpu_write_buffer(
)) ))
.err(); .err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -113,7 +111,7 @@ pub fn op_webgpu_write_texture(
state: &mut OpState, state: &mut OpState,
args: QueueWriteTextureArgs, args: QueueWriteTextureArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let texture_resource = state let texture_resource = state
@ -157,5 +155,5 @@ pub fn op_webgpu_write_texture(
)) ))
.err(); .err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) })) Ok(WebGpuResult::maybe_err(maybe_err))
} }

View file

@ -3,8 +3,6 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
@ -12,7 +10,7 @@ use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use super::error::WebGpuError; use super::error::WebGpuResult;
pub(crate) struct WebGpuRenderPass( pub(crate) struct WebGpuRenderPass(
pub(crate) RefCell<wgpu_core::command::RenderPass>, pub(crate) RefCell<wgpu_core::command::RenderPass>,
@ -39,7 +37,7 @@ pub fn op_webgpu_render_pass_set_viewport(
state: &mut OpState, state: &mut OpState,
args: RenderPassSetViewportArgs, args: RenderPassSetViewportArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -55,7 +53,7 @@ pub fn op_webgpu_render_pass_set_viewport(
args.max_depth, args.max_depth,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -72,7 +70,7 @@ pub fn op_webgpu_render_pass_set_scissor_rect(
state: &mut OpState, state: &mut OpState,
args: RenderPassSetScissorRectArgs, args: RenderPassSetScissorRectArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -86,7 +84,7 @@ pub fn op_webgpu_render_pass_set_scissor_rect(
args.height, args.height,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -109,7 +107,7 @@ pub fn op_webgpu_render_pass_set_blend_color(
state: &mut OpState, state: &mut OpState,
args: RenderPassSetBlendColorArgs, args: RenderPassSetBlendColorArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -125,7 +123,7 @@ pub fn op_webgpu_render_pass_set_blend_color(
}, },
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -139,7 +137,7 @@ pub fn op_webgpu_render_pass_set_stencil_reference(
state: &mut OpState, state: &mut OpState,
args: RenderPassSetStencilReferenceArgs, args: RenderPassSetStencilReferenceArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -150,7 +148,7 @@ pub fn op_webgpu_render_pass_set_stencil_reference(
args.reference, args.reference,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -165,7 +163,7 @@ pub fn op_webgpu_render_pass_begin_pipeline_statistics_query(
state: &mut OpState, state: &mut OpState,
args: RenderPassBeginPipelineStatisticsQueryArgs, args: RenderPassBeginPipelineStatisticsQueryArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(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)] #[derive(Deserialize)]
@ -196,7 +194,7 @@ pub fn op_webgpu_render_pass_end_pipeline_statistics_query(
state: &mut OpState, state: &mut OpState,
args: RenderPassEndPipelineStatisticsQueryArgs, args: RenderPassEndPipelineStatisticsQueryArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(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)] #[derive(Deserialize)]
@ -223,7 +221,7 @@ pub fn op_webgpu_render_pass_write_timestamp(
state: &mut OpState, state: &mut OpState,
args: RenderPassWriteTimestampArgs, args: RenderPassWriteTimestampArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -241,7 +239,7 @@ pub fn op_webgpu_render_pass_write_timestamp(
); );
} }
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -255,7 +253,7 @@ pub fn op_webgpu_render_pass_execute_bundles(
state: &mut OpState, state: &mut OpState,
args: RenderPassExecuteBundlesArgs, args: RenderPassExecuteBundlesArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let mut render_bundle_ids = vec![]; let mut render_bundle_ids = vec![];
for rid in &args.bundles { for rid in &args.bundles {
@ -279,7 +277,7 @@ pub fn op_webgpu_render_pass_execute_bundles(
); );
} }
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -293,7 +291,7 @@ pub fn op_webgpu_render_pass_end_pass(
state: &mut OpState, state: &mut OpState,
args: RenderPassEndPassArgs, args: RenderPassEndPassArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state let command_encoder_resource = state
.resource_table .resource_table
.get::<super::command_encoder::WebGpuCommandEncoder>( .get::<super::command_encoder::WebGpuCommandEncoder>(
@ -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(); 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)] #[derive(Deserialize)]
@ -328,7 +326,7 @@ pub fn op_webgpu_render_pass_set_bind_group(
state: &mut OpState, state: &mut OpState,
args: RenderPassSetBindGroupArgs, args: RenderPassSetBindGroupArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let bind_group_resource = state let bind_group_resource = state
.resource_table .resource_table
@ -370,7 +368,7 @@ pub fn op_webgpu_render_pass_set_bind_group(
} }
}; };
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -384,7 +382,7 @@ pub fn op_webgpu_render_pass_push_debug_group(
state: &mut OpState, state: &mut OpState,
args: RenderPassPushDebugGroupArgs, args: RenderPassPushDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -399,7 +397,7 @@ pub fn op_webgpu_render_pass_push_debug_group(
); );
} }
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -412,7 +410,7 @@ pub fn op_webgpu_render_pass_pop_debug_group(
state: &mut OpState, state: &mut OpState,
args: RenderPassPopDebugGroupArgs, args: RenderPassPopDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -422,7 +420,7 @@ pub fn op_webgpu_render_pass_pop_debug_group(
&mut render_pass_resource.0.borrow_mut(), &mut render_pass_resource.0.borrow_mut(),
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -436,7 +434,7 @@ pub fn op_webgpu_render_pass_insert_debug_marker(
state: &mut OpState, state: &mut OpState,
args: RenderPassInsertDebugMarkerArgs, args: RenderPassInsertDebugMarkerArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -451,7 +449,7 @@ pub fn op_webgpu_render_pass_insert_debug_marker(
); );
} }
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -465,7 +463,7 @@ pub fn op_webgpu_render_pass_set_pipeline(
state: &mut OpState, state: &mut OpState,
args: RenderPassSetPipelineArgs, args: RenderPassSetPipelineArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pipeline_resource = state let render_pipeline_resource = state
.resource_table .resource_table
.get::<super::pipeline::WebGpuRenderPipeline>(args.pipeline) .get::<super::pipeline::WebGpuRenderPipeline>(args.pipeline)
@ -480,7 +478,7 @@ pub fn op_webgpu_render_pass_set_pipeline(
render_pipeline_resource.0, render_pipeline_resource.0,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -497,7 +495,7 @@ pub fn op_webgpu_render_pass_set_index_buffer(
state: &mut OpState, state: &mut OpState,
args: RenderPassSetIndexBufferArgs, args: RenderPassSetIndexBufferArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state let buffer_resource = state
.resource_table .resource_table
.get::<super::buffer::WebGpuBuffer>(args.buffer) .get::<super::buffer::WebGpuBuffer>(args.buffer)
@ -514,7 +512,7 @@ pub fn op_webgpu_render_pass_set_index_buffer(
std::num::NonZeroU64::new(args.size), std::num::NonZeroU64::new(args.size),
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -531,7 +529,7 @@ pub fn op_webgpu_render_pass_set_vertex_buffer(
state: &mut OpState, state: &mut OpState,
args: RenderPassSetVertexBufferArgs, args: RenderPassSetVertexBufferArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state let buffer_resource = state
.resource_table .resource_table
.get::<super::buffer::WebGpuBuffer>(args.buffer) .get::<super::buffer::WebGpuBuffer>(args.buffer)
@ -549,7 +547,7 @@ pub fn op_webgpu_render_pass_set_vertex_buffer(
std::num::NonZeroU64::new(args.size), std::num::NonZeroU64::new(args.size),
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -566,7 +564,7 @@ pub fn op_webgpu_render_pass_draw(
state: &mut OpState, state: &mut OpState,
args: RenderPassDrawArgs, args: RenderPassDrawArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -580,7 +578,7 @@ pub fn op_webgpu_render_pass_draw(
args.first_instance, args.first_instance,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -598,7 +596,7 @@ pub fn op_webgpu_render_pass_draw_indexed(
state: &mut OpState, state: &mut OpState,
args: RenderPassDrawIndexedArgs, args: RenderPassDrawIndexedArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state let render_pass_resource = state
.resource_table .resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid) .get::<WebGpuRenderPass>(args.render_pass_rid)
@ -613,7 +611,7 @@ pub fn op_webgpu_render_pass_draw_indexed(
args.first_instance, args.first_instance,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -628,7 +626,7 @@ pub fn op_webgpu_render_pass_draw_indirect(
state: &mut OpState, state: &mut OpState,
args: RenderPassDrawIndirectArgs, args: RenderPassDrawIndirectArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state let buffer_resource = state
.resource_table .resource_table
.get::<super::buffer::WebGpuBuffer>(args.indirect_buffer) .get::<super::buffer::WebGpuBuffer>(args.indirect_buffer)
@ -644,7 +642,7 @@ pub fn op_webgpu_render_pass_draw_indirect(
args.indirect_offset, args.indirect_offset,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -659,7 +657,7 @@ pub fn op_webgpu_render_pass_draw_indexed_indirect(
state: &mut OpState, state: &mut OpState,
args: RenderPassDrawIndexedIndirectArgs, args: RenderPassDrawIndexedIndirectArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state let buffer_resource = state
.resource_table .resource_table
.get::<super::buffer::WebGpuBuffer>(args.indirect_buffer) .get::<super::buffer::WebGpuBuffer>(args.indirect_buffer)
@ -675,5 +673,5 @@ pub fn op_webgpu_render_pass_draw_indexed_indirect(
args.indirect_offset, args.indirect_offset,
); );
Ok(json!({})) Ok(WebGpuResult::empty())
} }

View file

@ -2,15 +2,13 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
use serde::Deserialize; use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use super::error::WebGpuError; use super::error::WebGpuResult;
pub(crate) struct WebGpuSampler(pub(crate) wgpu_core::id::SamplerId); pub(crate) struct WebGpuSampler(pub(crate) wgpu_core::id::SamplerId);
impl Resource for WebGpuSampler { impl Resource for WebGpuSampler {
@ -83,7 +81,7 @@ pub fn op_webgpu_create_sampler(
state: &mut OpState, state: &mut OpState,
args: CreateSamplerArgs, args: CreateSamplerArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -123,8 +121,5 @@ pub fn op_webgpu_create_sampler(
let rid = state.resource_table.add(WebGpuSampler(sampler)); let rid = state.resource_table.add(WebGpuSampler(sampler));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }

View file

@ -3,15 +3,13 @@
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
use serde::Deserialize; use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use super::error::WebGpuError; use super::error::WebGpuResult;
pub(crate) struct WebGpuShaderModule(pub(crate) wgpu_core::id::ShaderModuleId); pub(crate) struct WebGpuShaderModule(pub(crate) wgpu_core::id::ShaderModuleId);
impl Resource for WebGpuShaderModule { impl Resource for WebGpuShaderModule {
@ -33,7 +31,7 @@ pub fn op_webgpu_create_shader_module(
state: &mut OpState, state: &mut OpState,
args: CreateShaderModuleArgs, args: CreateShaderModuleArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -77,8 +75,5 @@ pub fn op_webgpu_create_shader_module(
let rid = state.resource_table.add(WebGpuShaderModule(shader_module)); let rid = state.resource_table.add(WebGpuShaderModule(shader_module));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }

View file

@ -2,15 +2,13 @@
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::error::{bad_resource_id, not_supported}; 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::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource}; use deno_core::{OpState, Resource};
use serde::Deserialize; use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use super::error::WebGpuError; use super::error::WebGpuResult;
pub(crate) struct WebGpuTexture(pub(crate) wgpu_core::id::TextureId); pub(crate) struct WebGpuTexture(pub(crate) wgpu_core::id::TextureId);
impl Resource for WebGpuTexture { impl Resource for WebGpuTexture {
fn name(&self) -> Cow<str> { fn name(&self) -> Cow<str> {
@ -148,7 +146,7 @@ pub fn op_webgpu_create_texture(
state: &mut OpState, state: &mut OpState,
args: CreateTextureArgs, args: CreateTextureArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let device_resource = state let device_resource = state
.resource_table .resource_table
@ -186,10 +184,7 @@ pub fn op_webgpu_create_texture(
let rid = state.resource_table.add(WebGpuTexture(texture)); let rid = state.resource_table.add(WebGpuTexture(texture));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -210,7 +205,7 @@ pub fn op_webgpu_create_texture_view(
state: &mut OpState, state: &mut OpState,
args: CreateTextureViewArgs, args: CreateTextureViewArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>(); let instance = state.borrow::<super::Instance>();
let texture_resource = state let texture_resource = state
.resource_table .resource_table
@ -250,8 +245,5 @@ pub fn op_webgpu_create_texture_view(
let rid = state.resource_table.add(WebGpuTextureView(texture_view)); let rid = state.resource_table.add(WebGpuTextureView(texture_view));
Ok(json!({ Ok(WebGpuResult::rid_err(rid, maybe_err))
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
} }

View file

@ -99,9 +99,7 @@
this.#url = wsURL.href; this.#url = wsURL.href;
core.jsonOpSync("op_ws_check_permission", { core.jsonOpSync("op_ws_check_permission", this.#url);
url: this.#url,
});
if (protocols && typeof protocols === "string") { if (protocols && typeof protocols === "string") {
protocols = [protocols]; protocols = [protocols];
@ -311,7 +309,7 @@
while (this.#readyState === OPEN) { while (this.#readyState === OPEN) {
const message = await core.jsonOpAsync( const message = await core.jsonOpAsync(
"op_ws_next_event", "op_ws_next_event",
{ rid: this.#rid }, this.#rid,
); );
switch (message.kind) { switch (message.kind) {

View file

@ -82,28 +82,22 @@ impl Resource for WsStreamResource {
impl 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 // This op is needed because creating a WS instance in JavaScript is a sync
// operation and should throw error when permissions are not fulfilled, // operation and should throw error when permissions are not fulfilled,
// but actual op that connects WS is async. // but actual op that connects WS is async.
pub fn op_ws_check_permission<WP>( pub fn op_ws_check_permission<WP>(
state: &mut OpState, state: &mut OpState,
args: CheckPermissionArgs, url: String,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> ) -> Result<(), AnyError>
where where
WP: WebSocketPermissions + 'static, WP: WebSocketPermissions + 'static,
{ {
state state
.borrow::<WP>() .borrow::<WP>()
.check_net_url(&url::Url::parse(&args.url)?)?; .check_net_url(&url::Url::parse(&url)?)?;
Ok(json!({})) Ok(())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -224,7 +218,7 @@ pub async fn op_ws_send(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: SendArgs, args: SendArgs,
buf: Option<ZeroCopyBuf>, buf: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let msg = match args.kind.as_str() { let msg = match args.kind.as_str() {
"text" => Message::Text(args.text.unwrap()), "text" => Message::Text(args.text.unwrap()),
"binary" => Message::Binary(buf.ok_or_else(null_opbuf)?.to_vec()), "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)?; .ok_or_else(bad_resource_id)?;
let mut tx = RcRef::map(&resource, |r| &r.tx).borrow_mut().await; let mut tx = RcRef::map(&resource, |r| &r.tx).borrow_mut().await;
tx.send(msg).await?; tx.send(msg).await?;
Ok(json!({})) Ok(())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -255,7 +249,7 @@ pub async fn op_ws_close(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: CloseArgs, args: CloseArgs,
_bufs: Option<ZeroCopyBuf>, _bufs: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let rid = args.rid; let rid = args.rid;
let msg = Message::Close(args.code.map(|c| CloseFrame { let msg = Message::Close(args.code.map(|c| CloseFrame {
code: CloseCode::from(c), code: CloseCode::from(c),
@ -272,24 +266,18 @@ pub async fn op_ws_close(
.ok_or_else(bad_resource_id)?; .ok_or_else(bad_resource_id)?;
let mut tx = RcRef::map(&resource, |r| &r.tx).borrow_mut().await; let mut tx = RcRef::map(&resource, |r| &r.tx).borrow_mut().await;
tx.send(msg).await?; tx.send(msg).await?;
Ok(json!({})) Ok(())
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NextEventArgs {
rid: ResourceId,
} }
pub async fn op_ws_next_event( pub async fn op_ws_next_event(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: NextEventArgs, rid: ResourceId,
_bufs: Option<ZeroCopyBuf>, _bufs: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let resource = state let resource = state
.borrow_mut() .borrow_mut()
.resource_table .resource_table
.get::<WsStreamResource>(args.rid) .get::<WsStreamResource>(rid)
.ok_or_else(bad_resource_id)?; .ok_or_else(bad_resource_id)?;
let mut rx = RcRef::map(&resource, |r| &r.rx).borrow_mut().await; 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(Ok(Message::Pong(_))) => json!({ "kind": "pong" }),
Some(Err(_)) => json!({ "kind": "error" }), Some(Err(_)) => json!({ "kind": "error" }),
None => { None => {
state.borrow_mut().resource_table.close(args.rid).unwrap(); state.borrow_mut().resource_table.close(rid).unwrap();
json!({ "kind": "closed" }) json!({ "kind": "closed" })
} }
}; };

View file

@ -10,7 +10,7 @@
} }
function opStartGlobalTimer(timeout) { function opStartGlobalTimer(timeout) {
return core.jsonOpSync("op_global_timer_start", { timeout }); return core.jsonOpSync("op_global_timer_start", timeout);
} }
async function opWaitGlobalTimer() { async function opWaitGlobalTimer() {
@ -22,7 +22,7 @@
} }
function sleepSync(millis = 0) { 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. // Derived from https://github.com/vadimg/js_bintrees. MIT Licensed.

View file

@ -28,15 +28,15 @@
} }
function hostTerminateWorker(id) { function hostTerminateWorker(id) {
core.jsonOpSync("op_host_terminate_worker", { id }); core.jsonOpSync("op_host_terminate_worker", id);
} }
function hostPostMessage(id, data) { function hostPostMessage(id, data) {
core.jsonOpSync("op_host_post_message", { id }, data); core.jsonOpSync("op_host_post_message", id, data);
} }
function hostGetMessage(id) { function hostGetMessage(id) {
return core.jsonOpAsync("op_host_get_message", { id }); return core.jsonOpAsync("op_host_get_message", id);
} }
const encoder = new TextEncoder(); const encoder = new TextEncoder();
@ -197,7 +197,7 @@
} }
} }
const { id } = createWorker( const id = createWorker(
specifier, specifier,
hasSourceCode, hasSourceCode,
sourceCode, sourceCode,
@ -270,7 +270,7 @@
} else { } else {
core.jsonOpSync( core.jsonOpSync(
"op_host_unhandled_error", "op_host_unhandled_error",
{ message: event.error.message }, event.error.message,
); );
} }
} }
@ -289,7 +289,7 @@
} else { } else {
core.jsonOpSync( core.jsonOpSync(
"op_host_unhandled_error", "op_host_unhandled_error",
{ message: event.error.message }, event.error.message,
); );
} }
} }

View file

@ -58,7 +58,7 @@
} }
function chdir(directory) { function chdir(directory) {
core.jsonOpSync("op_chdir", { directory }); core.jsonOpSync("op_chdir", directory);
} }
function makeTempDirSync(options = {}) { function makeTempDirSync(options = {}) {
@ -101,14 +101,8 @@
await core.jsonOpAsync("op_mkdir_async", mkdirArgs(path, options)); await core.jsonOpAsync("op_mkdir_async", mkdirArgs(path, options));
} }
function res(response) {
return response.entries;
}
function readDirSync(path) { function readDirSync(path) {
return res( return core.jsonOpSync("op_read_dir_sync", pathFromURL(path))[
core.jsonOpSync("op_read_dir_sync", { path: pathFromURL(path) }),
)[
Symbol.iterator Symbol.iterator
](); ]();
} }
@ -116,11 +110,8 @@
function readDir(path) { function readDir(path) {
const array = core.jsonOpAsync( const array = core.jsonOpAsync(
"op_read_dir_async", "op_read_dir_async",
{ path: pathFromURL(path) }, pathFromURL(path),
) );
.then(
res,
);
return { return {
async *[Symbol.asyncIterator]() { async *[Symbol.asyncIterator]() {
yield* await array; yield* await array;
@ -129,19 +120,19 @@
} }
function readLinkSync(path) { 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) { 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) { function realPathSync(path) {
return core.jsonOpSync("op_realpath_sync", { path }); return core.jsonOpSync("op_realpath_sync", path);
} }
function realPath(path) { function realPath(path) {
return core.jsonOpAsync("op_realpath_async", { path }); return core.jsonOpAsync("op_realpath_async", path);
} }
function removeSync( function removeSync(
@ -198,11 +189,11 @@
} }
function fstatSync(rid) { function fstatSync(rid) {
return parseFileInfo(core.jsonOpSync("op_fstat_sync", { rid })); return parseFileInfo(core.jsonOpSync("op_fstat_sync", rid));
} }
async function fstat(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) { async function lstat(path) {
@ -262,7 +253,7 @@
} }
function umask(mask) { function umask(mask) {
return core.jsonOpSync("op_umask", { mask }); return core.jsonOpSync("op_umask", mask);
} }
function linkSync(oldpath, newpath) { function linkSync(oldpath, newpath) {
@ -359,19 +350,19 @@
} }
function fdatasyncSync(rid) { function fdatasyncSync(rid) {
core.jsonOpSync("op_fdatasync_sync", { rid }); core.jsonOpSync("op_fdatasync_sync", rid);
} }
async function fdatasync(rid) { async function fdatasync(rid) {
await core.jsonOpAsync("op_fdatasync_async", { rid }); await core.jsonOpAsync("op_fdatasync_async", rid);
} }
function fsyncSync(rid) { function fsyncSync(rid) {
core.jsonOpSync("op_fsync_sync", { rid }); core.jsonOpSync("op_fsync_sync", rid);
} }
async function fsync(rid) { async function fsync(rid) {
await core.jsonOpAsync("op_fsync_async", { rid }); await core.jsonOpAsync("op_fsync_async", rid);
} }
window.__bootstrap.fs = { window.__bootstrap.fs = {

View file

@ -7,7 +7,7 @@
const { read, write } = window.__bootstrap.io; const { read, write } = window.__bootstrap.io;
function shutdown(rid) { function shutdown(rid) {
return core.jsonOpAsync("op_shutdown", { rid }); return core.jsonOpAsync("op_shutdown", rid);
} }
function opAccept(rid, transport) { function opAccept(rid, transport) {

View file

@ -21,7 +21,12 @@
} }
function systemCpuInfo() { 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 // This is an internal only method used by the test harness to override the
@ -44,7 +49,7 @@
return; return;
} }
core.jsonOpSync("op_exit", { code }); core.jsonOpSync("op_exit", code);
throw new Error("Code not reachable"); throw new Error("Code not reachable");
} }
@ -53,11 +58,11 @@
} }
function getEnv(key) { function getEnv(key) {
return core.jsonOpSync("op_get_env", { key })[0]; return core.jsonOpSync("op_get_env", key) ?? undefined;
} }
function deleteEnv(key) { function deleteEnv(key) {
core.jsonOpSync("op_delete_env", { key }); core.jsonOpSync("op_delete_env", key);
} }
const env = { const env = {

View file

@ -19,9 +19,10 @@
async next() { async next() {
try { try {
return await core.jsonOpAsync("op_fs_events_poll", { const value = await core.jsonOpAsync("op_fs_events_poll", this.rid);
rid: this.rid, return value
}); ? { value, done: false }
: { value: undefined, done: true };
} catch (error) { } catch (error) {
if (error instanceof errors.BadResource) { if (error instanceof errors.BadResource) {
return { value: undefined, done: true }; return { value: undefined, done: true };

View file

@ -31,7 +31,7 @@
* @returns {Deno.PermissionState} * @returns {Deno.PermissionState}
*/ */
function opQuery(desc) { 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} * @returns {Deno.PermissionState}
*/ */
function opRevoke(desc) { 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} * @returns {Deno.PermissionState}
*/ */
function opRequest(desc) { function opRequest(desc) {
return core.jsonOpSync("op_request_permission", desc).state; return core.jsonOpSync("op_request_permission", desc);
} }
class PermissionStatus extends EventTarget { class PermissionStatus extends EventTarget {

View file

@ -5,7 +5,7 @@
const core = window.Deno.core; const core = window.Deno.core;
function openPlugin(filename) { function openPlugin(filename) {
return core.jsonOpSync("op_open_plugin", { filename }); return core.jsonOpSync("op_open_plugin", filename);
} }
window.__bootstrap.plugins = { window.__bootstrap.plugins = {

View file

@ -12,7 +12,7 @@
} }
function opRunStatus(rid) { function opRunStatus(rid) {
return core.jsonOpAsync("op_run_status", { rid }); return core.jsonOpAsync("op_run_status", rid);
} }
function opRun(request) { function opRun(request) {

View file

@ -7,15 +7,15 @@
const { errors } = window.__bootstrap.errors; const { errors } = window.__bootstrap.errors;
function bindSignal(signo) { function bindSignal(signo) {
return core.jsonOpSync("op_signal_bind", { signo }); return core.jsonOpSync("op_signal_bind", signo);
} }
function pollSignal(rid) { function pollSignal(rid) {
return core.jsonOpAsync("op_signal_poll", { rid }); return core.jsonOpAsync("op_signal_poll", rid);
} }
function unbindSignal(rid) { function unbindSignal(rid) {
core.jsonOpSync("op_signal_unbind", { rid }); core.jsonOpSync("op_signal_unbind", rid);
} }
// From `kill -l` // From `kill -l`
@ -209,21 +209,21 @@
#rid = 0; #rid = 0;
constructor(signo) { constructor(signo) {
this.#rid = bindSignal(signo).rid; this.#rid = bindSignal(signo);
this.#loop(); this.#loop();
} }
#pollSignal = async () => { #pollSignal = async () => {
let res; let done;
try { try {
res = await pollSignal(this.#rid); done = await pollSignal(this.#rid);
} catch (error) { } catch (error) {
if (error instanceof errors.BadResource) { if (error instanceof errors.BadResource) {
return true; return true;
} }
throw error; throw error;
} }
return res.done; return done;
}; };
#loop = async () => { #loop = async () => {

View file

@ -12,7 +12,7 @@
} }
function opAcceptTLS(rid) { function opAcceptTLS(rid) {
return core.jsonOpAsync("op_accept_tls", { rid }); return core.jsonOpAsync("op_accept_tls", rid);
} }
function opListenTls(args) { function opListenTls(args) {

View file

@ -5,11 +5,11 @@
const core = window.Deno.core; const core = window.Deno.core;
function consoleSize(rid) { function consoleSize(rid) {
return core.jsonOpSync("op_console_size", { rid }); return core.jsonOpSync("op_console_size", rid);
} }
function isatty(rid) { function isatty(rid) {
return core.jsonOpSync("op_isatty", { rid }); return core.jsonOpSync("op_isatty", rid);
} }
const DEFAULT_SET_RAW_OPTIONS = { const DEFAULT_SET_RAW_OPTIONS = {

View file

@ -129,7 +129,7 @@ delete Object.prototype.__proto__;
} }
function opPostMessage(data) { function opPostMessage(data) {
core.jsonOpSync("op_worker_post_message", {}, data); core.jsonOpSync("op_worker_post_message", null, data);
} }
function opCloseWorker() { function opCloseWorker() {

File diff suppressed because it is too large Load diff

View file

@ -3,8 +3,6 @@
use crate::permissions::Permissions; use crate::permissions::Permissions;
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::AsyncRefCell; use deno_core::AsyncRefCell;
use deno_core::CancelFuture; use deno_core::CancelFuture;
use deno_core::CancelHandle; use deno_core::CancelHandle;
@ -93,7 +91,7 @@ fn op_fs_events_open(
state: &mut OpState, state: &mut OpState,
args: OpenArgs, args: OpenArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<ResourceId, AnyError> {
let (sender, receiver) = mpsc::channel::<Result<FsEvent, AnyError>>(16); let (sender, receiver) = mpsc::channel::<Result<FsEvent, AnyError>>(16);
let sender = std::sync::Mutex::new(sender); let sender = std::sync::Mutex::new(sender);
let mut watcher: RecommendedWatcher = let mut watcher: RecommendedWatcher =
@ -122,30 +120,25 @@ fn op_fs_events_open(
cancel: Default::default(), cancel: Default::default(),
}; };
let rid = state.resource_table.add(resource); let rid = state.resource_table.add(resource);
Ok(json!(rid)) Ok(rid)
}
#[derive(Deserialize)]
pub struct PollArgs {
rid: ResourceId,
} }
async fn op_fs_events_poll( async fn op_fs_events_poll(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: PollArgs, rid: ResourceId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Option<FsEvent>, AnyError> {
let resource = state let resource = state
.borrow() .borrow()
.resource_table .resource_table
.get::<FsEventsResource>(args.rid) .get::<FsEventsResource>(rid)
.ok_or_else(bad_resource_id)?; .ok_or_else(bad_resource_id)?;
let mut receiver = RcRef::map(&resource, |r| &r.receiver).borrow_mut().await; let mut receiver = RcRef::map(&resource, |r| &r.receiver).borrow_mut().await;
let cancel = RcRef::map(resource, |r| &r.cancel); let cancel = RcRef::map(resource, |r| &r.cancel);
let maybe_result = receiver.recv().or_cancel(cancel).await?; let maybe_result = receiver.recv().or_cancel(cancel).await?;
match maybe_result { match maybe_result {
Some(Ok(value)) => Ok(json!({ "value": value, "done": false })), Some(Ok(value)) => Ok(Some(value)),
Some(Err(err)) => Err(err), Some(Err(err)) => Err(err),
None => Ok(json!({ "done": true })), None => Ok(None),
} }
} }

View file

@ -4,8 +4,6 @@ use deno_core::error::null_opbuf;
use deno_core::error::resource_unavailable; use deno_core::error::resource_unavailable;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::error::{bad_resource_id, not_supported}; 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::AsyncMutFuture;
use deno_core::AsyncRefCell; use deno_core::AsyncRefCell;
use deno_core::CancelHandle; use deno_core::CancelHandle;
@ -16,7 +14,6 @@ use deno_core::RcRef;
use deno_core::Resource; use deno_core::Resource;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use std::io::Read; use std::io::Read;
@ -610,20 +607,15 @@ async fn op_write_async(
Ok(nwritten as u32) Ok(nwritten as u32)
} }
#[derive(Deserialize)]
struct ShutdownArgs {
rid: ResourceId,
}
async fn op_shutdown( async fn op_shutdown(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: ShutdownArgs, rid: ResourceId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let resource = state let resource = state
.borrow() .borrow()
.resource_table .resource_table
.get_any(args.rid) .get_any(rid)
.ok_or_else(bad_resource_id)?; .ok_or_else(bad_resource_id)?;
if let Some(s) = resource.downcast_rc::<ChildStdinResource>() { if let Some(s) = resource.downcast_rc::<ChildStdinResource>() {
s.shutdown().await?; s.shutdown().await?;
@ -638,5 +630,5 @@ async fn op_shutdown(
} else { } else {
return Err(not_supported()); return Err(not_supported());
} }
Ok(json!({})) Ok(())
} }

View file

@ -9,7 +9,6 @@ use deno_core::error::generic_error;
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::error::type_error; use deno_core::error::type_error;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::serde_json::Value; use deno_core::serde_json::Value;
use deno_core::AsyncRefCell; use deno_core::AsyncRefCell;
@ -109,10 +108,9 @@ async fn accept_tcp(
async fn op_accept( async fn op_accept(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: AcceptArgs,
_buf: Option<ZeroCopyBuf>, _buf: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let args: AcceptArgs = serde_json::from_value(args)?;
match args.transport.as_str() { match args.transport.as_str() {
"tcp" => accept_tcp(state, args, _buf).await, "tcp" => accept_tcp(state, args, _buf).await,
#[cfg(unix)] #[cfg(unix)]
@ -163,10 +161,9 @@ async fn receive_udp(
async fn op_datagram_receive( async fn op_datagram_receive(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: ReceiveArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let args: ReceiveArgs = serde_json::from_value(args)?;
match args.transport.as_str() { match args.transport.as_str() {
"udp" => receive_udp(state, args, zero_copy).await, "udp" => receive_udp(state, args, zero_copy).await,
#[cfg(unix)] #[cfg(unix)]
@ -188,13 +185,13 @@ struct SendArgs {
async fn op_datagram_send( async fn op_datagram_send(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: SendArgs,
zero_copy: Option<ZeroCopyBuf>, zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let zero_copy = zero_copy.ok_or_else(null_opbuf)?; let zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let zero_copy = zero_copy.clone(); let zero_copy = zero_copy.clone();
match serde_json::from_value(args)? { match args {
SendArgs { SendArgs {
rid, rid,
transport, transport,
@ -257,10 +254,10 @@ struct ConnectArgs {
async fn op_connect( async fn op_connect(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: ConnectArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
match serde_json::from_value(args)? { match args {
ConnectArgs { ConnectArgs {
transport, transport,
transport_args: ArgsEnum::Ip(args), transport_args: ArgsEnum::Ip(args),
@ -421,11 +418,11 @@ fn listen_udp(
fn op_listen( fn op_listen(
state: &mut OpState, state: &mut OpState,
args: Value, args: ListenArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let permissions = state.borrow::<Permissions>(); let permissions = state.borrow::<Permissions>();
match serde_json::from_value(args)? { match args {
ListenArgs { ListenArgs {
transport, transport,
transport_args: ArgsEnum::Ip(args), transport_args: ArgsEnum::Ip(args),

View file

@ -17,6 +17,7 @@ use deno_core::RcRef;
use deno_core::Resource; use deno_core::Resource;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use std::fs::remove_file; 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)] #[derive(Deserialize)]
pub struct UnixListenArgs { pub struct UnixListenArgs {
pub path: String, pub path: String,

View file

@ -1,13 +1,12 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::permissions::Permissions; use crate::permissions::Permissions;
use deno_core::error::{type_error, AnyError}; use deno_core::error::{custom_error, type_error, AnyError};
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::url::Url; use deno_core::url::Url;
use deno_core::OpState; use deno_core::OpState;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
@ -27,9 +26,9 @@ pub fn init(rt: &mut deno_core::JsRuntime) {
fn op_exec_path( fn op_exec_path(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<String, AnyError> {
let current_exe = env::current_exe().unwrap(); let current_exe = env::current_exe().unwrap();
state state
.borrow::<Permissions>() .borrow::<Permissions>()
@ -39,7 +38,16 @@ fn op_exec_path(
// we might get `./` and `../` bits in `exec_path` // we might get `./` and `../` bits in `exec_path`
let exe_url = Url::from_file_path(current_exe).unwrap(); let exe_url = Url::from_file_path(current_exe).unwrap();
let path = exe_url.to_file_path().unwrap(); let path = exe_url.to_file_path().unwrap();
Ok(json!(path))
into_string(path.into_os_string())
}
// TODO(@AaronO): share this code with fs' into_string()
fn into_string(s: std::ffi::OsString) -> Result<String, AnyError> {
s.into_string().map_err(|s| {
let message = format!("File name or path {:?} is not valid UTF-8", s);
custom_error("InvalidData", message)
})
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -52,7 +60,7 @@ fn op_set_env(
state: &mut OpState, state: &mut OpState,
args: SetEnv, args: SetEnv,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
let invalid_key = let invalid_key =
args.key.is_empty() || args.key.contains(&['=', '\0'] as &[char]); 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.")); return Err(type_error("Key or value contains invalid characters."));
} }
env::set_var(args.key, args.value); env::set_var(args.key, args.value);
Ok(json!({})) Ok(())
} }
fn op_env( fn op_env(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<HashMap<String, String>, AnyError> {
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
let v = env::vars().collect::<HashMap<String, String>>(); Ok(env::vars().collect())
Ok(json!(v))
}
#[derive(Deserialize)]
pub struct GetEnv {
key: String,
} }
fn op_get_env( fn op_get_env(
state: &mut OpState, state: &mut OpState,
args: GetEnv, key: String,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Option<String>, AnyError> {
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
if args.key.is_empty() || args.key.contains(&['=', '\0'] as &[char]) { if key.is_empty() || key.contains(&['=', '\0'] as &[char]) {
return Err(type_error("Key contains invalid characters.")); return Err(type_error("Key contains invalid characters."));
} }
let r = match env::var(args.key) { let r = match env::var(key) {
Err(env::VarError::NotPresent) => json!([]), Err(env::VarError::NotPresent) => None,
v => json!([v?]), v => Some(v?),
}; };
Ok(r) Ok(r)
} }
#[derive(Deserialize)]
pub struct DeleteEnv {
key: String,
}
fn op_delete_env( fn op_delete_env(
state: &mut OpState, state: &mut OpState,
args: DeleteEnv, key: String,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
if args.key.is_empty() || args.key.contains(&['=', '\0'] as &[char]) { if key.is_empty() || key.contains(&['=', '\0'] as &[char]) {
return Err(type_error("Key contains invalid characters.")); return Err(type_error("Key contains invalid characters."));
} }
env::remove_var(args.key); env::remove_var(key);
Ok(json!({})) Ok(())
}
#[derive(Deserialize)]
pub struct Exit {
code: i32,
} }
fn op_exit( fn op_exit(
_state: &mut OpState, _state: &mut OpState,
args: Exit, code: i32,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
std::process::exit(args.code) std::process::exit(code)
} }
fn op_loadavg( fn op_loadavg(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(f64, f64, f64), AnyError> {
super::check_unstable(state, "Deno.loadavg"); super::check_unstable(state, "Deno.loadavg");
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
match sys_info::loadavg() { match sys_info::loadavg() {
Ok(loadavg) => Ok(json!([loadavg.one, loadavg.five, loadavg.fifteen])), Ok(loadavg) => Ok((loadavg.one, loadavg.five, loadavg.fifteen)),
Err(_) => Ok(json!([0f64, 0f64, 0f64])), Err(_) => Ok((0.0, 0.0, 0.0)),
} }
} }
fn op_hostname( fn op_hostname(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<String, AnyError> {
super::check_unstable(state, "Deno.hostname"); super::check_unstable(state, "Deno.hostname");
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
let hostname = sys_info::hostname().unwrap_or_else(|_| "".to_string()); let hostname = sys_info::hostname().unwrap_or_else(|_| "".to_string());
Ok(json!(hostname)) Ok(hostname)
} }
fn op_os_release( fn op_os_release(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<String, AnyError> {
super::check_unstable(state, "Deno.osRelease"); super::check_unstable(state, "Deno.osRelease");
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
let release = sys_info::os_release().unwrap_or_else(|_| "".to_string()); 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( fn op_system_memory_info(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Option<MemInfo>, AnyError> {
super::check_unstable(state, "Deno.systemMemoryInfo"); super::check_unstable(state, "Deno.systemMemoryInfo");
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
match sys_info::mem_info() { match sys_info::mem_info() {
Ok(info) => Ok(json!({ Ok(info) => Ok(Some(MemInfo {
"total": info.total, total: info.total,
"free": info.free, free: info.free,
"available": info.avail, available: info.avail,
"buffers": info.buffers, buffers: info.buffers,
"cached": info.cached, cached: info.cached,
"swapTotal": info.swap_total, swap_total: info.swap_total,
"swapFree": info.swap_free swap_free: info.swap_free,
})), })),
Err(_) => Ok(json!({})), Err(_) => Ok(None),
} }
} }
#[derive(Serialize)]
struct CpuInfo {
cores: Option<u32>,
speed: Option<u64>,
}
fn op_system_cpu_info( fn op_system_cpu_info(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<CpuInfo, AnyError> {
super::check_unstable(state, "Deno.systemCpuInfo"); super::check_unstable(state, "Deno.systemCpuInfo");
state.borrow::<Permissions>().env.check()?; state.borrow::<Permissions>().env.check()?;
let cores = sys_info::cpu_num().ok(); let cores = sys_info::cpu_num().ok();
let speed = sys_info::cpu_speed().ok(); let speed = sys_info::cpu_speed().ok();
Ok(json!({ Ok(CpuInfo { cores, speed })
"cores": cores,
"speed": speed
}))
} }

View file

@ -4,8 +4,6 @@ use crate::permissions::Permissions;
use deno_core::error::custom_error; use deno_core::error::custom_error;
use deno_core::error::uri_error; use deno_core::error::uri_error;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::url; use deno_core::url;
use deno_core::OpState; use deno_core::OpState;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
@ -29,7 +27,7 @@ pub fn op_query_permission(
state: &mut OpState, state: &mut OpState,
args: PermissionArgs, args: PermissionArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<String, AnyError> {
let permissions = state.borrow::<Permissions>(); let permissions = state.borrow::<Permissions>();
let path = args.path.as_deref(); let path = args.path.as_deref();
let perm = match args.name.as_ref() { 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( pub fn op_revoke_permission(
state: &mut OpState, state: &mut OpState,
args: PermissionArgs, args: PermissionArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<String, AnyError> {
let permissions = state.borrow_mut::<Permissions>(); let permissions = state.borrow_mut::<Permissions>();
let path = args.path.as_deref(); let path = args.path.as_deref();
let perm = match args.name.as_ref() { 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( pub fn op_request_permission(
state: &mut OpState, state: &mut OpState,
args: PermissionArgs, args: PermissionArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<String, AnyError> {
let permissions = state.borrow_mut::<Permissions>(); let permissions = state.borrow_mut::<Permissions>();
let path = args.path.as_deref(); let path = args.path.as_deref();
let perm = match args.name.as_ref() { let perm = match args.name.as_ref() {
@ -115,7 +113,7 @@ pub fn op_request_permission(
)) ))
} }
}; };
Ok(json!({ "state": perm.to_string() })) Ok(perm.to_string())
} }
fn parse_host(host_str: &str) -> Result<(String, Option<u16>), AnyError> { fn parse_host(host_str: &str) -> Result<(String, Option<u16>), AnyError> {

View file

@ -4,8 +4,6 @@ use crate::permissions::Permissions;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::futures::prelude::*; use deno_core::futures::prelude::*;
use deno_core::plugin_api; use deno_core::plugin_api;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::JsRuntime; use deno_core::JsRuntime;
use deno_core::Op; use deno_core::Op;
use deno_core::OpAsyncFuture; use deno_core::OpAsyncFuture;
@ -13,10 +11,10 @@ use deno_core::OpFn;
use deno_core::OpId; use deno_core::OpId;
use deno_core::OpState; use deno_core::OpState;
use deno_core::Resource; use deno_core::Resource;
use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use dlopen::symbor::Library; use dlopen::symbor::Library;
use log::debug; use log::debug;
use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::path::PathBuf; use std::path::PathBuf;
use std::pin::Pin; 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); 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( pub fn op_open_plugin(
state: &mut OpState, state: &mut OpState,
args: OpenPluginArgs, filename: String,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<ResourceId, AnyError> {
let filename = PathBuf::from(&args.filename); let filename = PathBuf::from(&filename);
super::check_unstable(state, "Deno.openPlugin"); super::check_unstable(state, "Deno.openPlugin");
let permissions = state.borrow::<Permissions>(); let permissions = state.borrow::<Permissions>();
@ -67,7 +59,7 @@ pub fn op_open_plugin(
let mut interface = PluginInterface::new(state, &plugin_lib); let mut interface = PluginInterface::new(state, &plugin_lib);
deno_plugin_init(&mut interface); deno_plugin_init(&mut interface);
Ok(json!(rid)) Ok(rid)
} }
struct PluginResource { struct PluginResource {

View file

@ -8,8 +8,6 @@ use crate::permissions::Permissions;
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
use deno_core::error::type_error; use deno_core::error::type_error;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::AsyncMutFuture; use deno_core::AsyncMutFuture;
use deno_core::AsyncRefCell; use deno_core::AsyncRefCell;
use deno_core::OpState; use deno_core::OpState;
@ -18,6 +16,7 @@ use deno_core::Resource;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
@ -81,11 +80,22 @@ impl ChildResource {
} }
} }
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
// TODO(@AaronO): maybe find a more descriptive name or a convention for return structs
struct RunInfo {
rid: ResourceId,
pid: Option<u32>,
stdin_rid: Option<ResourceId>,
stdout_rid: Option<ResourceId>,
stderr_rid: Option<ResourceId>,
}
fn op_run( fn op_run(
state: &mut OpState, state: &mut OpState,
run_args: RunArgs, run_args: RunArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<RunInfo, AnyError> {
state.borrow::<Permissions>().run.check()?; state.borrow::<Permissions>().run.check()?;
let args = run_args.cmd; let args = run_args.cmd;
@ -166,28 +176,28 @@ fn op_run(
}; };
let child_rid = state.resource_table.add(child_resource); let child_rid = state.resource_table.add(child_resource);
Ok(json!({ Ok(RunInfo {
"rid": child_rid, rid: child_rid,
"pid": pid, pid,
"stdinRid": stdin_rid, stdin_rid,
"stdoutRid": stdout_rid, stdout_rid,
"stderrRid": stderr_rid, stderr_rid,
})) })
} }
#[derive(Deserialize)] #[derive(Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct RunStatusArgs { struct RunStatus {
rid: ResourceId, got_signal: bool,
exit_code: i32,
exit_signal: i32,
} }
async fn op_run_status( async fn op_run_status(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: RunStatusArgs, rid: ResourceId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<RunStatus, AnyError> {
let rid = args.rid;
{ {
let s = state.borrow(); let s = state.borrow();
s.borrow::<Permissions>().run.check()?; s.borrow::<Permissions>().run.check()?;
@ -212,11 +222,11 @@ async fn op_run_status(
.expect("Should have either an exit code or a signal."); .expect("Should have either an exit code or a signal.");
let got_signal = signal.is_some(); let got_signal = signal.is_some();
Ok(json!({ Ok(RunStatus {
"gotSignal": got_signal, got_signal,
"exitCode": code.unwrap_or(-1), exit_code: code.unwrap_or(-1),
"exitSignal": signal.unwrap_or(-1), exit_signal: signal.unwrap_or(-1),
})) })
} }
#[cfg(unix)] #[cfg(unix)]
@ -280,10 +290,10 @@ fn op_kill(
state: &mut OpState, state: &mut OpState,
args: KillArgs, args: KillArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
super::check_unstable(state, "Deno.kill"); super::check_unstable(state, "Deno.kill");
state.borrow::<Permissions>().run.check()?; state.borrow::<Permissions>().run.check()?;
kill(args.pid, args.signo)?; kill(args.pid, args.signo)?;
Ok(json!({})) Ok(())
} }

View file

@ -1,10 +1,10 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::metrics::OpMetrics;
use crate::metrics::RuntimeMetrics; use crate::metrics::RuntimeMetrics;
use crate::ops::UnstableChecker; use crate::ops::UnstableChecker;
use crate::permissions::Permissions; use crate::permissions::Permissions;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::serde_json::Value; use deno_core::serde_json::Value;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
@ -23,9 +23,9 @@ pub fn init(rt: &mut deno_core::JsRuntime, main_module: ModuleSpecifier) {
fn op_main_module( fn op_main_module(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<String, AnyError> {
let main = state.borrow::<ModuleSpecifier>().to_string(); let main = state.borrow::<ModuleSpecifier>().to_string();
let main_url = deno_core::resolve_url_or_path(&main)?; let main_url = deno_core::resolve_url_or_path(&main)?;
if main_url.scheme() == "file" { if main_url.scheme() == "file" {
@ -35,15 +35,21 @@ fn op_main_module(
.read .read
.check_blind(&main_path, "main_module")?; .check_blind(&main_path, "main_module")?;
} }
Ok(json!(&main)) Ok(main)
}
#[derive(serde::Serialize)]
struct MetricsReturn {
combined: OpMetrics,
ops: Value,
} }
#[allow(clippy::unnecessary_wraps)] #[allow(clippy::unnecessary_wraps)]
fn op_metrics( fn op_metrics(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<MetricsReturn, AnyError> {
let m = state.borrow::<RuntimeMetrics>(); let m = state.borrow::<RuntimeMetrics>();
let combined = m.combined_metrics(); let combined = m.combined_metrics();
let unstable_checker = state.borrow::<UnstableChecker>(); let unstable_checker = state.borrow::<UnstableChecker>();
@ -52,10 +58,13 @@ fn op_metrics(
} else { } else {
None 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)] #[cfg(windows)]
{ {
// Adopted from rustup: // Adopted from rustup:
@ -77,7 +86,7 @@ pub fn ppid() -> Value {
// and contains our parent's pid // and contains our parent's pid
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if snapshot == INVALID_HANDLE_VALUE { if snapshot == INVALID_HANDLE_VALUE {
return serde_json::to_value(-1).unwrap(); return -1;
} }
let mut entry: PROCESSENTRY32 = mem::zeroed(); let mut entry: PROCESSENTRY32 = mem::zeroed();
@ -87,7 +96,7 @@ pub fn ppid() -> Value {
let success = Process32First(snapshot, &mut entry); let success = Process32First(snapshot, &mut entry);
if success == 0 { if success == 0 {
CloseHandle(snapshot); CloseHandle(snapshot);
return serde_json::to_value(-1).unwrap(); return -1;
} }
let this_pid = GetCurrentProcessId(); let this_pid = GetCurrentProcessId();
@ -95,7 +104,7 @@ pub fn ppid() -> Value {
let success = Process32Next(snapshot, &mut entry); let success = Process32Next(snapshot, &mut entry);
if success == 0 { if success == 0 {
CloseHandle(snapshot); CloseHandle(snapshot);
return serde_json::to_value(-1).unwrap(); return -1;
} }
} }
CloseHandle(snapshot); CloseHandle(snapshot);
@ -104,12 +113,12 @@ pub fn ppid() -> Value {
// wherein the parent process already exited and the OS // wherein the parent process already exited and the OS
// reassigned its ID. // reassigned its ID.
let parent_id = entry.th32ParentProcessID; let parent_id = entry.th32ParentProcessID;
serde_json::to_value(parent_id).unwrap() parent_id.into()
} }
} }
#[cfg(not(windows))] #[cfg(not(windows))]
{ {
use std::os::unix::process::parent_id; use std::os::unix::process::parent_id;
serde_json::to_value(parent_id()).unwrap() parent_id().into()
} }
} }

View file

@ -1,6 +1,5 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::Value;
use deno_core::OpState; use deno_core::OpState;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use std::cell::RefCell; use std::cell::RefCell;
@ -9,8 +8,6 @@ use std::rc::Rc;
#[cfg(unix)] #[cfg(unix)]
use deno_core::error::bad_resource_id; use deno_core::error::bad_resource_id;
#[cfg(unix)] #[cfg(unix)]
use deno_core::serde_json::json;
#[cfg(unix)]
use deno_core::AsyncRefCell; use deno_core::AsyncRefCell;
#[cfg(unix)] #[cfg(unix)]
use deno_core::CancelFuture; use deno_core::CancelFuture;
@ -21,7 +18,7 @@ use deno_core::RcRef;
#[cfg(unix)] #[cfg(unix)]
use deno_core::Resource; use deno_core::Resource;
#[cfg(unix)] #[cfg(unix)]
use serde::Deserialize; use deno_core::ResourceId;
#[cfg(unix)] #[cfg(unix)]
use std::borrow::Cow; use std::borrow::Cow;
#[cfg(unix)] #[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)] #[cfg(unix)]
#[allow(clippy::unnecessary_wraps)] #[allow(clippy::unnecessary_wraps)]
fn op_signal_bind( fn op_signal_bind(
state: &mut OpState, state: &mut OpState,
args: BindSignalArgs, signo: i32,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<ResourceId, AnyError> {
super::check_unstable(state, "Deno.signal"); super::check_unstable(state, "Deno.signal");
let resource = SignalStreamResource { let resource = SignalStreamResource {
signal: AsyncRefCell::new( signal: AsyncRefCell::new(signal(SignalKind::from_raw(signo)).expect("")),
signal(SignalKind::from_raw(args.signo)).expect(""),
),
cancel: Default::default(), cancel: Default::default(),
}; };
let rid = state.resource_table.add(resource); let rid = state.resource_table.add(resource);
Ok(json!({ Ok(rid)
"rid": rid,
}))
} }
#[cfg(unix)] #[cfg(unix)]
async fn op_signal_poll( async fn op_signal_poll(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: SignalArgs, rid: ResourceId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<bool, AnyError> {
super::check_unstable2(&state, "Deno.signal"); super::check_unstable2(&state, "Deno.signal");
let rid = args.rid;
let resource = state let resource = state
.borrow_mut() .borrow_mut()
@ -102,49 +82,48 @@ async fn op_signal_poll(
let mut signal = RcRef::map(&resource, |r| &r.signal).borrow_mut().await; let mut signal = RcRef::map(&resource, |r| &r.signal).borrow_mut().await;
match signal.recv().or_cancel(cancel).await { match signal.recv().or_cancel(cancel).await {
Ok(result) => Ok(json!({ "done": result.is_none() })), Ok(result) => Ok(result.is_none()),
Err(_) => Ok(json!({ "done": true })), Err(_) => Ok(true),
} }
} }
#[cfg(unix)] #[cfg(unix)]
pub fn op_signal_unbind( pub fn op_signal_unbind(
state: &mut OpState, state: &mut OpState,
args: SignalArgs, rid: ResourceId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
super::check_unstable(state, "Deno.signal"); super::check_unstable(state, "Deno.signal");
let rid = args.rid;
state state
.resource_table .resource_table
.close(rid) .close(rid)
.ok_or_else(bad_resource_id)?; .ok_or_else(bad_resource_id)?;
Ok(json!({})) Ok(())
} }
#[cfg(not(unix))] #[cfg(not(unix))]
pub fn op_signal_bind( pub fn op_signal_bind(
_state: &mut OpState, _state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
unimplemented!(); unimplemented!();
} }
#[cfg(not(unix))] #[cfg(not(unix))]
fn op_signal_unbind( fn op_signal_unbind(
_state: &mut OpState, _state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
unimplemented!(); unimplemented!();
} }
#[cfg(not(unix))] #[cfg(not(unix))]
async fn op_signal_poll( async fn op_signal_poll(
_state: Rc<RefCell<OpState>>, _state: Rc<RefCell<OpState>>,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
unimplemented!(); unimplemented!();
} }

View file

@ -14,11 +14,8 @@ use deno_core::futures;
use deno_core::futures::channel::oneshot; use deno_core::futures::channel::oneshot;
use deno_core::futures::FutureExt; use deno_core::futures::FutureExt;
use deno_core::futures::TryFutureExt; use deno_core::futures::TryFutureExt;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::OpState; use deno_core::OpState;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use serde::Deserialize;
use std::cell::RefCell; use std::cell::RefCell;
use std::future::Future; use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
@ -82,17 +79,12 @@ pub fn init(rt: &mut deno_core::JsRuntime) {
#[allow(clippy::unnecessary_wraps)] #[allow(clippy::unnecessary_wraps)]
fn op_global_timer_stop( fn op_global_timer_stop(
state: &mut OpState, state: &mut OpState,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let global_timer = state.borrow_mut::<GlobalTimer>(); let global_timer = state.borrow_mut::<GlobalTimer>();
global_timer.cancel(); global_timer.cancel();
Ok(json!({})) Ok(())
}
#[derive(Deserialize)]
pub struct GlobalTimerArgs {
timeout: u64,
} }
// Set up a timer that will be later awaited by JS promise. // Set up a timer that will be later awaited by JS promise.
@ -105,22 +97,20 @@ pub struct GlobalTimerArgs {
#[allow(clippy::unnecessary_wraps)] #[allow(clippy::unnecessary_wraps)]
fn op_global_timer_start( fn op_global_timer_start(
state: &mut OpState, state: &mut OpState,
args: GlobalTimerArgs, timeout: u64,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let val = args.timeout; let deadline = Instant::now() + Duration::from_millis(timeout);
let deadline = Instant::now() + Duration::from_millis(val);
let global_timer = state.borrow_mut::<GlobalTimer>(); let global_timer = state.borrow_mut::<GlobalTimer>();
global_timer.new_timeout(deadline); global_timer.new_timeout(deadline);
Ok(json!({})) Ok(())
} }
async fn op_global_timer( async fn op_global_timer(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
_args: Value, _args: (),
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let maybe_timer_fut = { let maybe_timer_fut = {
let mut s = state.borrow_mut(); let mut s = state.borrow_mut();
let global_timer = s.borrow_mut::<GlobalTimer>(); let global_timer = s.borrow_mut::<GlobalTimer>();
@ -129,7 +119,7 @@ async fn op_global_timer(
if let Some(timer_fut) = maybe_timer_fut { if let Some(timer_fut) = maybe_timer_fut {
let _ = timer_fut.await; let _ = timer_fut.await;
} }
Ok(json!({})) Ok(())
} }
// Returns a milliseconds and nanoseconds subsec // Returns a milliseconds and nanoseconds subsec
@ -159,18 +149,13 @@ fn op_now(
Ok(result) Ok(result)
} }
#[derive(Deserialize)]
pub struct SleepArgs {
millis: u64,
}
#[allow(clippy::unnecessary_wraps)] #[allow(clippy::unnecessary_wraps)]
fn op_sleep_sync( fn op_sleep_sync(
state: &mut OpState, state: &mut OpState,
args: SleepArgs, millis: u64,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
super::check_unstable(state, "Deno.sleepSync"); super::check_unstable(state, "Deno.sleepSync");
sleep(Duration::from_millis(args.millis)); sleep(Duration::from_millis(millis));
Ok(json!({})) Ok(())
} }

View file

@ -348,18 +348,11 @@ fn op_listen_tls(
})) }))
} }
#[derive(Deserialize)]
pub struct AcceptTlsArgs {
rid: ResourceId,
}
async fn op_accept_tls( async fn op_accept_tls(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: AcceptTlsArgs, rid: ResourceId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let rid = args.rid;
let resource = state let resource = state
.borrow() .borrow()
.resource_table .resource_table

View file

@ -5,8 +5,6 @@ use deno_core::error::bad_resource_id;
use deno_core::error::not_supported; use deno_core::error::not_supported;
use deno_core::error::resource_unavailable; use deno_core::error::resource_unavailable;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::OpState; use deno_core::OpState;
use deno_core::RcRef; use deno_core::RcRef;
use deno_core::ResourceId; use deno_core::ResourceId;
@ -68,7 +66,7 @@ fn op_set_raw(
state: &mut OpState, state: &mut OpState,
args: SetRawArgs, args: SetRawArgs,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
super::check_unstable(state, "Deno.setRaw"); super::check_unstable(state, "Deno.setRaw");
let rid = args.rid; let rid = args.rid;
@ -147,7 +145,7 @@ fn op_set_raw(
return Err(Error::last_os_error().into()); return Err(Error::last_os_error().into());
} }
Ok(json!({})) Ok(())
} }
#[cfg(unix)] #[cfg(unix)]
{ {
@ -210,22 +208,15 @@ fn op_set_raw(
} }
} }
Ok(json!({})) Ok(())
} }
} }
#[derive(Deserialize)]
pub struct IsattyArgs {
rid: ResourceId,
}
fn op_isatty( fn op_isatty(
state: &mut OpState, state: &mut OpState,
args: IsattyArgs, rid: ResourceId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<bool, AnyError> {
let rid = args.rid;
let isatty: bool = StdFileResource::with(state, rid, move |r| match r { let isatty: bool = StdFileResource::with(state, rid, move |r| match r {
Ok(std_file) => { Ok(std_file) => {
#[cfg(windows)] #[cfg(windows)]
@ -246,12 +237,7 @@ fn op_isatty(
} }
_ => Ok(false), _ => Ok(false),
})?; })?;
Ok(json!(isatty)) Ok(isatty)
}
#[derive(Deserialize)]
pub struct ConsoleSizeArgs {
rid: ResourceId,
} }
#[derive(Serialize)] #[derive(Serialize)]
@ -262,13 +248,11 @@ struct ConsoleSize {
fn op_console_size( fn op_console_size(
state: &mut OpState, state: &mut OpState,
args: ConsoleSizeArgs, rid: ResourceId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<ConsoleSize, AnyError> { ) -> Result<ConsoleSize, AnyError> {
super::check_unstable(state, "Deno.consoleSize"); super::check_unstable(state, "Deno.consoleSize");
let rid = args.rid;
let size = StdFileResource::with(state, rid, move |r| match r { let size = StdFileResource::with(state, rid, move |r| match r {
Ok(std_file) => { Ok(std_file) => {
#[cfg(windows)] #[cfg(windows)]

View file

@ -4,7 +4,6 @@ use crate::web_worker::WebWorkerHandle;
use crate::web_worker::WorkerEvent; use crate::web_worker::WorkerEvent;
use deno_core::error::null_opbuf; use deno_core::error::null_opbuf;
use deno_core::futures::channel::mpsc; use deno_core::futures::channel::mpsc;
use deno_core::serde_json::{json, Value};
pub fn init( pub fn init(
rt: &mut deno_core::JsRuntime, rt: &mut deno_core::JsRuntime,
@ -16,14 +15,14 @@ pub fn init(
super::reg_json_sync( super::reg_json_sync(
rt, rt,
"op_worker_post_message", "op_worker_post_message",
move |_state, _args: Value, buf| { move |_state, _args: (), buf| {
let buf = buf.ok_or_else(null_opbuf)?; let buf = buf.ok_or_else(null_opbuf)?;
let msg_buf: Box<[u8]> = (*buf).into(); let msg_buf: Box<[u8]> = (*buf).into();
sender_ sender_
.clone() .clone()
.try_send(WorkerEvent::Message(msg_buf)) .try_send(WorkerEvent::Message(msg_buf))
.expect("Failed to post message to host"); .expect("Failed to post message to host");
Ok(json!({})) Ok(())
}, },
); );
@ -31,12 +30,12 @@ pub fn init(
super::reg_json_sync( super::reg_json_sync(
rt, rt,
"op_worker_close", "op_worker_close",
move |_state, _args: Value, _bufs| { move |_state, _args: (), _bufs| {
// Notify parent that we're finished // Notify parent that we're finished
sender.clone().close_channel(); sender.clone().close_channel();
// Terminate execution of current worker // Terminate execution of current worker
handle.terminate(); handle.terminate();
Ok(json!({})) Ok(())
}, },
); );
} }

View file

@ -57,11 +57,6 @@ pub type CreateWebWorkerCb =
#[derive(Clone)] #[derive(Clone)]
pub struct CreateWebWorkerCbHolder(Arc<CreateWebWorkerCb>); pub struct CreateWebWorkerCbHolder(Arc<CreateWebWorkerCb>);
#[derive(Deserialize)]
struct HostUnhandledErrorArgs {
message: String,
}
pub struct WorkerThread { pub struct WorkerThread {
join_handle: JoinHandle<Result<(), AnyError>>, join_handle: JoinHandle<Result<(), AnyError>>,
worker_handle: WebWorkerHandle, worker_handle: WebWorkerHandle,
@ -95,12 +90,12 @@ pub fn init(
super::reg_json_sync( super::reg_json_sync(
rt, rt,
"op_host_unhandled_error", "op_host_unhandled_error",
move |_state, args: HostUnhandledErrorArgs, _zero_copy| { move |_state, message: String, _zero_copy| {
if let Some(mut sender) = sender.clone() { if let Some(mut sender) = sender.clone() {
sender 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"); .expect("Failed to propagate error event to parent worker");
Ok(json!(true)) Ok(true)
} else { } else {
Err(generic_error("Cannot be called from main worker.")) Err(generic_error("Cannot be called from main worker."))
} }
@ -370,7 +365,7 @@ fn op_create_worker(
state: &mut OpState, state: &mut OpState,
args: CreateWorkerArgs, args: CreateWorkerArgs,
_data: Option<ZeroCopyBuf>, _data: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<WorkerId, AnyError> {
let specifier = args.specifier.clone(); let specifier = args.specifier.clone();
let maybe_source_code = if args.has_source_code { let maybe_source_code = if args.has_source_code {
Some(args.source_code.clone()) Some(args.source_code.clone())
@ -445,21 +440,15 @@ fn op_create_worker(
.borrow_mut::<WorkersTable>() .borrow_mut::<WorkersTable>()
.insert(worker_id, worker_thread); .insert(worker_id, worker_thread);
Ok(json!({ "id": worker_id })) Ok(worker_id)
}
#[derive(Deserialize)]
pub struct WorkerArgs {
id: i32,
} }
#[allow(clippy::unnecessary_wraps)] #[allow(clippy::unnecessary_wraps)]
fn op_host_terminate_worker( fn op_host_terminate_worker(
state: &mut OpState, state: &mut OpState,
args: WorkerArgs, id: WorkerId,
_data: Option<ZeroCopyBuf>, _data: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let id = args.id as u32;
let worker_thread = state let worker_thread = state
.borrow_mut::<WorkersTable>() .borrow_mut::<WorkersTable>()
.remove(&id) .remove(&id)
@ -470,7 +459,7 @@ fn op_host_terminate_worker(
.join() .join()
.expect("Panic in worker thread") .expect("Panic in worker thread")
.expect("Panic in worker event loop"); .expect("Panic in worker event loop");
Ok(json!({})) Ok(())
} }
fn serialize_worker_event(event: WorkerEvent) -> Value { fn serialize_worker_event(event: WorkerEvent) -> Value {
@ -532,11 +521,9 @@ fn try_remove_and_close(state: Rc<RefCell<OpState>>, id: u32) {
/// Get message from guest worker as host /// Get message from guest worker as host
async fn op_host_get_message( async fn op_host_get_message(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: WorkerArgs, id: WorkerId,
_zero_copy: Option<ZeroCopyBuf>, _zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let id = args.id as u32;
let worker_handle = { let worker_handle = {
let s = state.borrow(); let s = state.borrow();
let workers_table = s.borrow::<WorkersTable>(); let workers_table = s.borrow::<WorkersTable>();
@ -566,11 +553,10 @@ async fn op_host_get_message(
/// Post message to guest worker as host /// Post message to guest worker as host
fn op_host_post_message( fn op_host_post_message(
state: &mut OpState, state: &mut OpState,
args: WorkerArgs, id: WorkerId,
data: Option<ZeroCopyBuf>, data: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> { ) -> Result<(), AnyError> {
let data = data.ok_or_else(null_opbuf)?; let data = data.ok_or_else(null_opbuf)?;
let id = args.id as u32;
let msg = Vec::from(&*data).into_boxed_slice(); let msg = Vec::from(&*data).into_boxed_slice();
debug!("post message to worker {}", id); debug!("post message to worker {}", id);
@ -579,5 +565,5 @@ fn op_host_post_message(
.get(&id) .get(&id)
.expect("No worker handle found"); .expect("No worker handle found");
worker_thread.worker_handle.post_message(msg)?; worker_thread.worker_handle.post_message(msg)?;
Ok(json!({})) Ok(())
} }