diff options
author | Aaron O'Mullan <aaron.omullan@gmail.com> | 2021-04-12 21:55:05 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-12 15:55:05 -0400 |
commit | 46b1c653c0c433932908b7610f60b409af134c76 (patch) | |
tree | 00d8b59c8c4e9b90538d548ebd828d2b3f94d4fd /core/examples | |
parent | a20504642d083172f297543f9788b128e9c2e0bc (diff) |
refactor(deno): remove concept of bin & json ops (#10145)
Diffstat (limited to 'core/examples')
-rw-r--r-- | core/examples/hello_world.rs | 12 | ||||
-rw-r--r-- | core/examples/http_bench_bin_ops.js | 71 | ||||
-rw-r--r-- | core/examples/http_bench_bin_ops.rs | 228 | ||||
-rw-r--r-- | core/examples/http_bench_json_ops.js | 12 | ||||
-rw-r--r-- | core/examples/http_bench_json_ops.rs | 10 |
5 files changed, 17 insertions, 316 deletions
diff --git a/core/examples/hello_world.rs b/core/examples/hello_world.rs index 11fc5ff0e..154c05d97 100644 --- a/core/examples/hello_world.rs +++ b/core/examples/hello_world.rs @@ -2,7 +2,7 @@ //! This example shows you how to define ops in Rust and then call them from //! JavaScript. -use deno_core::json_op_sync; +use deno_core::op_sync; use deno_core::JsRuntime; use std::io::Write; @@ -26,7 +26,7 @@ fn main() { // The op_fn callback takes a state object OpState, // a structured arg of type `T` and an optional ZeroCopyBuf, // a mutable reference to a JavaScript ArrayBuffer - json_op_sync(|_state, msg: Option<String>, zero_copy| { + op_sync(|_state, msg: Option<String>, zero_copy| { let mut out = std::io::stdout(); // Write msg to stdout @@ -46,10 +46,10 @@ fn main() { // Register the JSON op for summing a number array. runtime.register_op( "op_sum", - // The json_op_sync function automatically deserializes + // The op_sync function automatically deserializes // the first ZeroCopyBuf and serializes the return value // to reduce boilerplate - json_op_sync(|_state, nums: Vec<f64>, _| { + op_sync(|_state, nums: Vec<f64>, _| { // Sum inputs let sum = nums.iter().fold(0.0, |a, v| a + v); // return as a Result<f64, AnyError> @@ -91,11 +91,11 @@ const arr = [1, 2, 3]; print("The sum of"); print(arr); print("is"); -print(Deno.core.jsonOpSync('op_sum', arr)); +print(Deno.core.opSync('op_sum', arr)); // And incorrect usage try { - print(Deno.core.jsonOpSync('op_sum', 0)); + print(Deno.core.opSync('op_sum', 0)); } catch(e) { print('Exception:'); print(e); diff --git a/core/examples/http_bench_bin_ops.js b/core/examples/http_bench_bin_ops.js deleted file mode 100644 index c3128dbb2..000000000 --- a/core/examples/http_bench_bin_ops.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -// This is not a real HTTP server. We read blindly one time into 'requestBuf', -// then write this fixed 'responseBuf'. The point of this benchmark is to -// exercise the event loop in a simple yet semi-realistic way. -const requestBuf = new Uint8Array(64 * 1024); -const responseBuf = new Uint8Array( - "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" - .split("") - .map((c) => c.charCodeAt(0)), -); - -/** Listens on 0.0.0.0:4500, returns rid. */ -function listen() { - return Deno.core.binOpSync("listen", 0); -} - -/** Accepts a connection, returns rid. */ -function accept(rid) { - return Deno.core.binOpAsync("accept", rid); -} - -/** - * Reads a packet from the rid, presumably an http request. data is ignored. - * Returns bytes read. - */ -function read(rid, data) { - return Deno.core.binOpAsync("read", rid, data); -} - -/** Writes a fixed HTTP response to the socket rid. Returns bytes written. */ -function write(rid, data) { - return Deno.core.binOpAsync("write", rid, data); -} - -function close(rid) { - Deno.core.binOpSync("close", rid); -} - -async function serve(rid) { - try { - while (true) { - await read(rid, requestBuf); - await write(rid, responseBuf); - } - } catch (e) { - if ( - !e.message.includes("Broken pipe") && - !e.message.includes("Connection reset by peer") - ) { - throw e; - } - } - close(rid); -} - -async function main() { - Deno.core.ops(); - Deno.core.registerErrorClass("Error", Error); - - const listenerRid = listen(); - Deno.core.print( - `http_bench_bin_ops listening on http://127.0.0.1:4544/\n`, - ); - - while (true) { - const rid = await accept(listenerRid); - serve(rid); - } -} - -main(); diff --git a/core/examples/http_bench_bin_ops.rs b/core/examples/http_bench_bin_ops.rs deleted file mode 100644 index 0ba7b6706..000000000 --- a/core/examples/http_bench_bin_ops.rs +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -use deno_core::error::bad_resource_id; -use deno_core::error::null_opbuf; -use deno_core::error::AnyError; -use deno_core::AsyncRefCell; -use deno_core::CancelHandle; -use deno_core::CancelTryFuture; -use deno_core::JsRuntime; -use deno_core::OpState; -use deno_core::RcRef; -use deno_core::Resource; -use deno_core::ResourceId; -use deno_core::ZeroCopyBuf; -use std::cell::RefCell; -use std::convert::TryFrom; -use std::env; -use std::io::Error; -use std::net::SocketAddr; -use std::rc::Rc; -use tokio::io::AsyncReadExt; -use tokio::io::AsyncWriteExt; - -struct Logger; - -impl log::Log for Logger { - fn enabled(&self, metadata: &log::Metadata) -> bool { - metadata.level() <= log::max_level() - } - - fn log(&self, record: &log::Record) { - if self.enabled(record.metadata()) { - println!("{} - {}", record.level(), record.args()); - } - } - - fn flush(&self) {} -} - -// Note: a `tokio::net::TcpListener` doesn't need to be wrapped in a cell, -// because it only supports one op (`accept`) which does not require a mutable -// reference to the listener. -struct TcpListener { - inner: tokio::net::TcpListener, - cancel: CancelHandle, -} - -impl TcpListener { - async fn accept(self: Rc<Self>) -> Result<TcpStream, Error> { - let cancel = RcRef::map(&self, |r| &r.cancel); - let stream = self.inner.accept().try_or_cancel(cancel).await?.0.into(); - Ok(stream) - } -} - -impl Resource for TcpListener { - fn close(self: Rc<Self>) { - self.cancel.cancel(); - } -} - -impl TryFrom<std::net::TcpListener> for TcpListener { - type Error = Error; - fn try_from( - std_listener: std::net::TcpListener, - ) -> Result<Self, Self::Error> { - tokio::net::TcpListener::try_from(std_listener).map(|tokio_listener| Self { - inner: tokio_listener, - cancel: Default::default(), - }) - } -} - -struct TcpStream { - rd: AsyncRefCell<tokio::net::tcp::OwnedReadHalf>, - wr: AsyncRefCell<tokio::net::tcp::OwnedWriteHalf>, - // When a `TcpStream` resource is closed, all pending 'read' ops are - // canceled, while 'write' ops are allowed to complete. Therefore only - // 'read' futures are attached to this cancel handle. - cancel: CancelHandle, -} - -impl TcpStream { - async fn read(self: Rc<Self>, buf: &mut [u8]) -> Result<usize, Error> { - let mut rd = RcRef::map(&self, |r| &r.rd).borrow_mut().await; - let cancel = RcRef::map(self, |r| &r.cancel); - rd.read(buf).try_or_cancel(cancel).await - } - - async fn write(self: Rc<Self>, buf: &[u8]) -> Result<usize, Error> { - let mut wr = RcRef::map(self, |r| &r.wr).borrow_mut().await; - wr.write(buf).await - } -} - -impl Resource for TcpStream { - fn close(self: Rc<Self>) { - self.cancel.cancel() - } -} - -impl From<tokio::net::TcpStream> for TcpStream { - fn from(s: tokio::net::TcpStream) -> Self { - let (rd, wr) = s.into_split(); - Self { - rd: rd.into(), - wr: wr.into(), - cancel: Default::default(), - } - } -} - -fn create_js_runtime() -> JsRuntime { - let mut runtime = JsRuntime::new(Default::default()); - runtime.register_op("listen", deno_core::bin_op_sync(op_listen)); - runtime.register_op("close", deno_core::bin_op_sync(op_close)); - runtime.register_op("accept", deno_core::bin_op_async(op_accept)); - runtime.register_op("read", deno_core::bin_op_async(op_read)); - runtime.register_op("write", deno_core::bin_op_async(op_write)); - runtime -} - -fn op_listen( - state: &mut OpState, - _rid: ResourceId, - _bufs: Option<ZeroCopyBuf>, -) -> Result<u32, AnyError> { - log::debug!("listen"); - let addr = "127.0.0.1:4544".parse::<SocketAddr>().unwrap(); - let std_listener = std::net::TcpListener::bind(&addr)?; - std_listener.set_nonblocking(true)?; - let listener = TcpListener::try_from(std_listener)?; - let rid = state.resource_table.add(listener); - Ok(rid) -} - -fn op_close( - state: &mut OpState, - rid: ResourceId, - _bufs: Option<ZeroCopyBuf>, -) -> Result<u32, AnyError> { - log::debug!("close rid={}", rid); - state - .resource_table - .close(rid) - .map(|_| 0) - .ok_or_else(bad_resource_id) -} - -async fn op_accept( - state: Rc<RefCell<OpState>>, - rid: ResourceId, - _bufs: Option<ZeroCopyBuf>, -) -> Result<u32, AnyError> { - log::debug!("accept rid={}", rid); - - let listener = state - .borrow() - .resource_table - .get::<TcpListener>(rid) - .ok_or_else(bad_resource_id)?; - let stream = listener.accept().await?; - let rid = state.borrow_mut().resource_table.add(stream); - Ok(rid) -} - -async fn op_read( - state: Rc<RefCell<OpState>>, - rid: ResourceId, - buf: Option<ZeroCopyBuf>, -) -> Result<u32, AnyError> { - let mut buf = buf.ok_or_else(null_opbuf)?; - log::debug!("read rid={}", rid); - - let stream = state - .borrow() - .resource_table - .get::<TcpStream>(rid) - .ok_or_else(bad_resource_id)?; - let nread = stream.read(&mut buf).await?; - Ok(nread as u32) -} - -async fn op_write( - state: Rc<RefCell<OpState>>, - rid: ResourceId, - buf: Option<ZeroCopyBuf>, -) -> Result<u32, AnyError> { - let buf = buf.ok_or_else(null_opbuf)?; - log::debug!("write rid={}", rid); - - let stream = state - .borrow() - .resource_table - .get::<TcpStream>(rid) - .ok_or_else(bad_resource_id)?; - let nwritten = stream.write(&buf).await?; - Ok(nwritten as u32) -} - -fn main() { - log::set_logger(&Logger).unwrap(); - log::set_max_level( - env::args() - .find(|a| a == "-D") - .map(|_| log::LevelFilter::Debug) - .unwrap_or(log::LevelFilter::Warn), - ); - - // NOTE: `--help` arg will display V8 help and exit - deno_core::v8_set_flags(env::args().collect()); - - let mut js_runtime = create_js_runtime(); - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .unwrap(); - - let future = async move { - js_runtime - .execute( - "http_bench_bin_ops.js", - include_str!("http_bench_bin_ops.js"), - ) - .unwrap(); - js_runtime.run_event_loop().await - }; - runtime.block_on(future).unwrap(); -} diff --git a/core/examples/http_bench_json_ops.js b/core/examples/http_bench_json_ops.js index f8ac05353..687be7ec1 100644 --- a/core/examples/http_bench_json_ops.js +++ b/core/examples/http_bench_json_ops.js @@ -11,12 +11,12 @@ const responseBuf = new Uint8Array( /** Listens on 0.0.0.0:4500, returns rid. */ function listen() { - return Deno.core.jsonOpSync("listen"); + return Deno.core.opSync("listen"); } /** Accepts a connection, returns rid. */ function accept(serverRid) { - return Deno.core.jsonOpAsync("accept", serverRid); + return Deno.core.opAsync("accept", serverRid); } /** @@ -24,16 +24,16 @@ function accept(serverRid) { * Returns bytes read. */ function read(rid, data) { - return Deno.core.jsonOpAsync("read", rid, data); + return Deno.core.opAsync("read", rid, data); } /** Writes a fixed HTTP response to the socket rid. Returns bytes written. */ function write(rid, data) { - return Deno.core.jsonOpAsync("write", rid, data); + return Deno.core.opAsync("write", rid, data); } function close(rid) { - Deno.core.jsonOpSync("close", rid); + Deno.core.opSync("close", rid); } async function serve(rid) { @@ -58,7 +58,7 @@ async function main() { Deno.core.registerErrorClass("Error", Error); const listenerRid = listen(); - Deno.core.print(`http_bench_json_ops listening on http://127.0.0.1:4544/\n`); + Deno.core.print(`http_bench_ops listening on http://127.0.0.1:4544/\n`); while (true) { const rid = await accept(listenerRid); diff --git a/core/examples/http_bench_json_ops.rs b/core/examples/http_bench_json_ops.rs index cb3c64945..e1b435e4c 100644 --- a/core/examples/http_bench_json_ops.rs +++ b/core/examples/http_bench_json_ops.rs @@ -111,11 +111,11 @@ impl From<tokio::net::TcpStream> for TcpStream { fn create_js_runtime() -> JsRuntime { let mut runtime = JsRuntime::new(Default::default()); - runtime.register_op("listen", deno_core::json_op_sync(op_listen)); - runtime.register_op("close", deno_core::json_op_sync(op_close)); - runtime.register_op("accept", deno_core::json_op_async(op_accept)); - runtime.register_op("read", deno_core::json_op_async(op_read)); - runtime.register_op("write", deno_core::json_op_async(op_write)); + runtime.register_op("listen", deno_core::op_sync(op_listen)); + runtime.register_op("close", deno_core::op_sync(op_close)); + runtime.register_op("accept", deno_core::op_async(op_accept)); + runtime.register_op("read", deno_core::op_async(op_read)); + runtime.register_op("write", deno_core::op_async(op_write)); runtime } |