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.byteLength,
);
core.jsonOpSync("op_crypto_get_random_values", {}, ui8);
core.jsonOpSync("op_crypto_get_random_values", null, ui8);
return arrayBufferView;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,8 +4,6 @@ use deno_core::error::bad_resource_id;
use deno_core::error::null_opbuf;
use deno_core::error::AnyError;
use deno_core::futures::channel::oneshot;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::OpState;
use deno_core::Resource;
use deno_core::ResourceId;
@ -17,7 +15,7 @@ use std::rc::Rc;
use std::time::Duration;
use super::error::DomExceptionOperationError;
use super::error::WebGpuError;
use super::error::WebGpuResult;
pub(crate) struct WebGpuBuffer(pub(crate) wgpu_core::id::BufferId);
impl Resource for WebGpuBuffer {
@ -47,7 +45,7 @@ pub fn op_webgpu_create_buffer(
state: &mut OpState,
args: CreateBufferArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let device_resource = state
.resource_table
@ -70,10 +68,7 @@ pub fn op_webgpu_create_buffer(
let rid = state.resource_table.add(WebGpuBuffer(buffer));
Ok(json!({
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
Ok(WebGpuResult::rid_err(rid, maybe_err))
}
#[derive(Deserialize)]
@ -90,7 +85,7 @@ pub async fn op_webgpu_buffer_get_map_async(
state: Rc<RefCell<OpState>>,
args: BufferGetMapAsyncArgs,
_bufs: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let (sender, receiver) = oneshot::channel::<Result<(), AnyError>>();
let device;
@ -164,7 +159,7 @@ pub async fn op_webgpu_buffer_get_map_async(
tokio::try_join!(device_poll_fut, receiver_fut)?;
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -179,7 +174,7 @@ pub fn op_webgpu_buffer_get_mapped_range(
state: &mut OpState,
args: BufferGetMappedRangeArgs,
zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let mut zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let instance = state.borrow::<super::Instance>();
let buffer_resource = state
@ -204,9 +199,7 @@ pub fn op_webgpu_buffer_get_mapped_range(
.resource_table
.add(WebGpuBufferMapped(slice_pointer, args.size as usize));
Ok(json!({
"rid": rid,
}))
Ok(WebGpuResult::rid(rid))
}
#[derive(Deserialize)]
@ -220,7 +213,7 @@ pub fn op_webgpu_buffer_unmap(
state: &mut OpState,
args: BufferUnmapArgs,
zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let mapped_resource = state
.resource_table
.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();
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::null_opbuf;
use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId;
use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource};
@ -13,7 +11,7 @@ use std::borrow::Cow;
use std::cell::RefCell;
use std::rc::Rc;
use super::error::WebGpuError;
use super::error::WebGpuResult;
use super::texture::serialize_texture_format;
struct WebGpuRenderBundleEncoder(
@ -46,7 +44,7 @@ pub fn op_webgpu_create_render_bundle_encoder(
state: &mut OpState,
args: CreateRenderBundleEncoderArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let device_resource = state
.resource_table
.get::<super::WebGpuDevice>(args.device_rid)
@ -85,10 +83,7 @@ pub fn op_webgpu_create_render_bundle_encoder(
render_bundle_encoder,
)));
Ok(json!({
"rid": rid,
"err": maybe_err.map(WebGpuError::from),
}))
Ok(WebGpuResult::rid_err(rid, maybe_err))
}
#[derive(Deserialize)]
@ -102,7 +97,7 @@ pub fn op_webgpu_render_bundle_encoder_finish(
state: &mut OpState,
args: RenderBundleEncoderFinishArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state
.resource_table
.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));
Ok(json!({
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
Ok(WebGpuResult::rid_err(rid, maybe_err))
}
#[derive(Deserialize)]
@ -145,7 +137,7 @@ pub fn op_webgpu_render_bundle_encoder_set_bind_group(
state: &mut OpState,
args: RenderBundleEncoderSetBindGroupArgs,
zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let zero_copy = zero_copy.ok_or_else(null_opbuf)?;
let bind_group_resource = state
@ -188,7 +180,7 @@ pub fn op_webgpu_render_bundle_encoder_set_bind_group(
}
};
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -202,7 +194,7 @@ pub fn op_webgpu_render_bundle_encoder_push_debug_group(
state: &mut OpState,
args: RenderBundleEncoderPushDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state
.resource_table
.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)]
@ -229,7 +221,7 @@ pub fn op_webgpu_render_bundle_encoder_pop_debug_group(
state: &mut OpState,
args: RenderBundleEncoderPopDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state
.resource_table
.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)]
@ -255,7 +247,7 @@ pub fn op_webgpu_render_bundle_encoder_insert_debug_marker(
state: &mut OpState,
args: RenderBundleEncoderInsertDebugMarkerArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state
.resource_table
.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)]
@ -283,7 +275,7 @@ pub fn op_webgpu_render_bundle_encoder_set_pipeline(
state: &mut OpState,
args: RenderBundleEncoderSetPipelineArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let render_pipeline_resource = state
.resource_table
.get::<super::pipeline::WebGpuRenderPipeline>(args.pipeline)
@ -298,7 +290,7 @@ pub fn op_webgpu_render_bundle_encoder_set_pipeline(
render_pipeline_resource.0,
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -315,7 +307,7 @@ pub fn op_webgpu_render_bundle_encoder_set_index_buffer(
state: &mut OpState,
args: RenderBundleEncoderSetIndexBufferArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state
.resource_table
.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),
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -352,7 +344,7 @@ pub fn op_webgpu_render_bundle_encoder_set_vertex_buffer(
state: &mut OpState,
args: RenderBundleEncoderSetVertexBufferArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state
.resource_table
.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),
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -387,7 +379,7 @@ pub fn op_webgpu_render_bundle_encoder_draw(
state: &mut OpState,
args: RenderBundleEncoderDrawArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state
.resource_table
.get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid)
@ -401,7 +393,7 @@ pub fn op_webgpu_render_bundle_encoder_draw(
args.first_instance,
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -419,7 +411,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indexed(
state: &mut OpState,
args: RenderBundleEncoderDrawIndexedArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let render_bundle_encoder_resource = state
.resource_table
.get::<WebGpuRenderBundleEncoder>(args.render_bundle_encoder_rid)
@ -434,7 +426,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indexed(
args.first_instance,
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -449,7 +441,7 @@ pub fn op_webgpu_render_bundle_encoder_draw_indirect(
state: &mut OpState,
args: RenderBundleEncoderDrawIndirectArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state
.resource_table
.get::<super::buffer::WebGpuBuffer>(args.indirect_buffer)
@ -465,5 +457,5 @@ pub fn op_webgpu_render_bundle_encoder_draw_indirect(
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::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId;
use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource};
@ -11,7 +9,7 @@ use serde::Deserialize;
use std::borrow::Cow;
use std::cell::RefCell;
use super::error::WebGpuError;
use super::error::WebGpuResult;
pub(crate) struct WebGpuCommandEncoder(
pub(crate) wgpu_core::id::CommandEncoderId,
@ -51,7 +49,7 @@ pub fn op_webgpu_create_command_encoder(
state: &mut OpState,
args: CreateCommandEncoderArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let device_resource = state
.resource_table
@ -73,10 +71,7 @@ pub fn op_webgpu_create_command_encoder(
.resource_table
.add(WebGpuCommandEncoder(command_encoder));
Ok(json!({
"rid": rid,
"err": maybe_err.map(WebGpuError::from),
}))
Ok(WebGpuResult::rid_err(rid, maybe_err))
}
#[derive(Deserialize)]
@ -117,7 +112,7 @@ pub fn op_webgpu_command_encoder_begin_render_pass(
state: &mut OpState,
args: CommandEncoderBeginRenderPassArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state
.resource_table
.get::<WebGpuCommandEncoder>(args.command_encoder_rid)
@ -236,9 +231,7 @@ pub fn op_webgpu_command_encoder_begin_render_pass(
render_pass,
)));
Ok(json!({
"rid": rid,
}))
Ok(WebGpuResult::rid(rid))
}
#[derive(Deserialize)]
@ -252,7 +245,7 @@ pub fn op_webgpu_command_encoder_begin_compute_pass(
state: &mut OpState,
args: CommandEncoderBeginComputePassArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state
.resource_table
.get::<WebGpuCommandEncoder>(args.command_encoder_rid)
@ -273,9 +266,7 @@ pub fn op_webgpu_command_encoder_begin_compute_pass(
compute_pass,
)));
Ok(json!({
"rid": rid,
}))
Ok(WebGpuResult::rid(rid))
}
#[derive(Deserialize)]
@ -293,7 +284,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_buffer(
state: &mut OpState,
args: CommandEncoderCopyBufferToBufferArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -320,7 +311,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_buffer(
args.size
)).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -362,7 +353,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_texture(
state: &mut OpState,
args: CommandEncoderCopyBufferToTextureArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -409,7 +400,7 @@ pub fn op_webgpu_command_encoder_copy_buffer_to_texture(
}
)).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -425,7 +416,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_buffer(
state: &mut OpState,
args: CommandEncoderCopyTextureToBufferArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -471,7 +462,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_buffer(
}
)).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -487,7 +478,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_texture(
state: &mut OpState,
args: CommandEncoderCopyTextureToTextureArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -537,7 +528,7 @@ pub fn op_webgpu_command_encoder_copy_texture_to_texture(
}
)).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -551,7 +542,7 @@ pub fn op_webgpu_command_encoder_push_debug_group(
state: &mut OpState,
args: CommandEncoderPushDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -563,7 +554,7 @@ pub fn op_webgpu_command_encoder_push_debug_group(
.command_encoder_push_debug_group(command_encoder, &args.group_label))
.err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -576,7 +567,7 @@ pub fn op_webgpu_command_encoder_pop_debug_group(
state: &mut OpState,
args: CommandEncoderPopDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -586,7 +577,7 @@ pub fn op_webgpu_command_encoder_pop_debug_group(
let maybe_err = gfx_select!(command_encoder => instance.command_encoder_pop_debug_group(command_encoder)).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -600,7 +591,7 @@ pub fn op_webgpu_command_encoder_insert_debug_marker(
state: &mut OpState,
args: CommandEncoderInsertDebugMarkerArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -613,7 +604,7 @@ pub fn op_webgpu_command_encoder_insert_debug_marker(
&args.marker_label
)).err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -628,7 +619,7 @@ pub fn op_webgpu_command_encoder_write_timestamp(
state: &mut OpState,
args: CommandEncoderWriteTimestampArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -648,7 +639,7 @@ pub fn op_webgpu_command_encoder_write_timestamp(
))
.err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -666,7 +657,7 @@ pub fn op_webgpu_command_encoder_resolve_query_set(
state: &mut OpState,
args: CommandEncoderResolveQuerySetArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let instance = state.borrow::<super::Instance>();
let command_encoder_resource = state
.resource_table
@ -693,7 +684,7 @@ pub fn op_webgpu_command_encoder_resolve_query_set(
))
.err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -707,7 +698,7 @@ pub fn op_webgpu_command_encoder_finish(
state: &mut OpState,
args: CommandEncoderFinishArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state
.resource_table
.take::<WebGpuCommandEncoder>(args.command_encoder_rid)
@ -728,8 +719,5 @@ pub fn op_webgpu_command_encoder_finish(
.resource_table
.add(WebGpuCommandBuffer(command_buffer));
Ok(json!({
"rid": rid,
"err": maybe_err.map(WebGpuError::from)
}))
Ok(WebGpuResult::rid_err(rid, maybe_err))
}

View File

@ -3,8 +3,6 @@
use deno_core::error::bad_resource_id;
use deno_core::error::null_opbuf;
use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ResourceId;
use deno_core::ZeroCopyBuf;
use deno_core::{OpState, Resource};
@ -12,7 +10,7 @@ use serde::Deserialize;
use std::borrow::Cow;
use std::cell::RefCell;
use super::error::WebGpuError;
use super::error::WebGpuResult;
pub(crate) struct WebGpuComputePass(
pub(crate) RefCell<wgpu_core::command::ComputePass>,
@ -34,7 +32,7 @@ pub fn op_webgpu_compute_pass_set_pipeline(
state: &mut OpState,
args: ComputePassSetPipelineArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let compute_pipeline_resource = state
.resource_table
.get::<super::pipeline::WebGpuComputePipeline>(args.pipeline)
@ -49,7 +47,7 @@ pub fn op_webgpu_compute_pass_set_pipeline(
compute_pipeline_resource.0,
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -65,7 +63,7 @@ pub fn op_webgpu_compute_pass_dispatch(
state: &mut OpState,
args: ComputePassDispatchArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state
.resource_table
.get::<WebGpuComputePass>(args.compute_pass_rid)
@ -78,7 +76,7 @@ pub fn op_webgpu_compute_pass_dispatch(
args.z,
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -93,7 +91,7 @@ pub fn op_webgpu_compute_pass_dispatch_indirect(
state: &mut OpState,
args: ComputePassDispatchIndirectArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let buffer_resource = state
.resource_table
.get::<super::buffer::WebGpuBuffer>(args.indirect_buffer)
@ -109,7 +107,7 @@ pub fn op_webgpu_compute_pass_dispatch_indirect(
args.indirect_offset,
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -124,7 +122,7 @@ pub fn op_webgpu_compute_pass_begin_pipeline_statistics_query(
state: &mut OpState,
args: ComputePassBeginPipelineStatisticsQueryArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state
.resource_table
.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)]
@ -155,7 +153,7 @@ pub fn op_webgpu_compute_pass_end_pipeline_statistics_query(
state: &mut OpState,
args: ComputePassEndPipelineStatisticsQueryArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state
.resource_table
.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)]
@ -182,7 +180,7 @@ pub fn op_webgpu_compute_pass_write_timestamp(
state: &mut OpState,
args: ComputePassWriteTimestampArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state
.resource_table
.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)]
@ -214,7 +212,7 @@ pub fn op_webgpu_compute_pass_end_pass(
state: &mut OpState,
args: ComputePassEndPassArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let command_encoder_resource = state
.resource_table
.get::<super::command_encoder::WebGpuCommandEncoder>(
@ -236,7 +234,7 @@ pub fn op_webgpu_compute_pass_end_pass(
))
.err();
Ok(json!({ "err": maybe_err.map(WebGpuError::from) }))
Ok(WebGpuResult::maybe_err(maybe_err))
}
#[derive(Deserialize)]
@ -254,7 +252,7 @@ pub fn op_webgpu_compute_pass_set_bind_group(
state: &mut OpState,
args: ComputePassSetBindGroupArgs,
zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let bind_group_resource = state
.resource_table
.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)]
@ -297,7 +295,7 @@ pub fn op_webgpu_compute_pass_push_debug_group(
state: &mut OpState,
args: ComputePassPushDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state
.resource_table
.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)]
@ -325,7 +323,7 @@ pub fn op_webgpu_compute_pass_pop_debug_group(
state: &mut OpState,
args: ComputePassPopDebugGroupArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state
.resource_table
.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(),
);
Ok(json!({}))
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
@ -349,7 +347,7 @@ pub fn op_webgpu_compute_pass_insert_debug_marker(
state: &mut OpState,
args: ComputePassInsertDebugMarkerArgs,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<Value, AnyError> {
) -> Result<WebGpuResult, AnyError> {
let compute_pass_resource = state
.resource_table
.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.
use deno_core::error::AnyError;
use deno_core::ResourceId;
use serde::Serialize;
use std::convert::From;
use std::fmt;
use wgpu_core::binding_model::CreateBindGroupError;
use wgpu_core::binding_model::CreateBindGroupLayoutError;
@ -27,6 +29,45 @@ use wgpu_core::resource::CreateSamplerError;
use wgpu_core::resource::CreateTextureError;
use wgpu_core::resource::CreateTextureViewError;
#[derive(Serialize)]
pub struct WebGpuResult {
pub rid: Option<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)]
#[serde(tag = "type", content = "value")]
#[serde(rename_all = "kebab-case")]

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -31,7 +31,7 @@
* @returns {Deno.PermissionState}
*/
function opQuery(desc) {
return core.jsonOpSync("op_query_permission", desc).state;
return core.jsonOpSync("op_query_permission", desc);
}
/**
@ -39,7 +39,7 @@
* @returns {Deno.PermissionState}
*/
function opRevoke(desc) {
return core.jsonOpSync("op_revoke_permission", desc).state;
return core.jsonOpSync("op_revoke_permission", desc);
}
/**
@ -47,7 +47,7 @@
* @returns {Deno.PermissionState}
*/
function opRequest(desc) {
return core.jsonOpSync("op_request_permission", desc).state;
return core.jsonOpSync("op_request_permission", desc);
}
class PermissionStatus extends EventTarget {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

@ -17,6 +17,7 @@ use deno_core::RcRef;
use deno_core::Resource;
use deno_core::ZeroCopyBuf;
use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow;
use std::cell::RefCell;
use std::fs::remove_file;
@ -56,6 +57,12 @@ impl Resource for UnixDatagramResource {
}
}
#[derive(Serialize)]
pub struct UnixAddr {
pub path: String,
pub transport: String,
}
#[derive(Deserialize)]
pub struct UnixListenArgs {
pub path: String,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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