1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-24 15:19:26 -05:00

cleanup(core): use Extensions to register ops (#13224)

In examples and tests
This commit is contained in:
Aaron O'Mullan 2021-12-29 15:21:42 +01:00 committed by Bartek Iwańczuk
parent 4186f1a9db
commit e8c60f757e
No known key found for this signature in database
GPG key ID: 0C6BCDDC3B3AD750
5 changed files with 71 additions and 38 deletions

View file

@ -3,25 +3,34 @@
//! JavaScript.
use deno_core::op_sync;
use deno_core::Extension;
use deno_core::JsRuntime;
use deno_core::RuntimeOptions;
fn main() {
// Initialize a runtime instance
let mut runtime = JsRuntime::new(Default::default());
// Build a deno_core::Extension providing custom ops
let ext = Extension::builder()
.ops(vec![
// An op for summing an array of numbers
(
"op_sum",
// The op-layer automatically deserializes inputs
// and serializes the returned Result & value
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>
Ok(sum)
}),
),
])
.build();
// Register an op for summing a number array.
runtime.register_op(
"op_sum",
// The op-layer automatically deserializes inputs
// and serializes the returned Result & value
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>
Ok(sum)
}),
);
runtime.sync_ops_cache();
// Initialize a runtime instance
let mut runtime = JsRuntime::new(RuntimeOptions {
extensions: vec![ext],
..Default::default()
});
// Now we see how to invoke the op we just defined. The runtime automatically
// contains a Deno.core object with several functions for interacting with it.

View file

@ -118,11 +118,17 @@ 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::op_sync(op_listen));
runtime.register_op("accept", deno_core::op_async(op_accept));
runtime.sync_ops_cache();
runtime
let ext = deno_core::Extension::builder()
.ops(vec![
("listen", deno_core::op_sync(op_listen)),
("accept", deno_core::op_async(op_accept)),
])
.build();
JsRuntime::new(deno_core::RuntimeOptions {
extensions: vec![ext],
..Default::default()
})
}
fn op_listen(state: &mut OpState, _: (), _: ()) -> Result<ResourceId, Error> {

View file

@ -1075,6 +1075,7 @@ mod tests {
use super::*;
use crate::ops::OpCall;
use crate::serialize_op_result;
use crate::Extension;
use crate::JsRuntime;
use crate::Op;
use crate::OpPayload;
@ -1403,7 +1404,7 @@ import "/a.js";
let dispatch_count = Arc::new(AtomicUsize::new(0));
let dispatch_count_ = dispatch_count.clone();
let dispatcher = move |state, payload: OpPayload| -> Op {
let op_test = move |state, payload: OpPayload| -> Op {
dispatch_count_.fetch_add(1, Ordering::Relaxed);
let (control, _): (u8, ()) = payload.deserialize().unwrap();
assert_eq!(control, 42);
@ -1411,12 +1412,15 @@ import "/a.js";
Op::Async(OpCall::ready(resp))
};
let ext = Extension::builder()
.ops(vec![("op_test", Box::new(op_test))])
.build();
let mut runtime = JsRuntime::new(RuntimeOptions {
extensions: vec![ext],
module_loader: Some(loader),
..Default::default()
});
runtime.register_op("op_test", dispatcher);
runtime.sync_ops_cache();
runtime
.execute_script(

View file

@ -123,8 +123,6 @@ mod tests {
#[tokio::test]
async fn op_async_stack_trace() {
let mut runtime = crate::JsRuntime::new(Default::default());
async fn op_throw(
_state: Rc<RefCell<OpState>>,
msg: Option<String>,
@ -134,8 +132,15 @@ mod tests {
Err(crate::error::generic_error("foo"))
}
runtime.register_op("op_throw", op_async(op_throw));
runtime.sync_ops_cache();
let ext = crate::Extension::builder()
.ops(vec![("op_throw", op_async(op_throw))])
.build();
let mut runtime = crate::JsRuntime::new(crate::RuntimeOptions {
extensions: vec![ext],
..Default::default()
});
runtime
.execute_script(
"<init>",

View file

@ -1651,6 +1651,7 @@ pub mod tests {
futures::executor::block_on(lazy(move |cx| f(cx)));
}
#[derive(Copy, Clone)]
enum Mode {
Async,
AsyncZeroCopy(bool),
@ -1661,7 +1662,7 @@ pub mod tests {
dispatch_count: Arc<AtomicUsize>,
}
fn dispatch(rc_op_state: Rc<RefCell<OpState>>, payload: OpPayload) -> Op {
fn op_test(rc_op_state: Rc<RefCell<OpState>>, payload: OpPayload) -> Op {
let rc_op_state2 = rc_op_state.clone();
let op_state_ = rc_op_state2.borrow();
let test_state = op_state_.borrow::<TestState>();
@ -1687,16 +1688,22 @@ pub mod tests {
fn setup(mode: Mode) -> (JsRuntime, Arc<AtomicUsize>) {
let dispatch_count = Arc::new(AtomicUsize::new(0));
let mut runtime = JsRuntime::new(Default::default());
let op_state = runtime.op_state();
op_state.borrow_mut().put(TestState {
mode,
dispatch_count: dispatch_count.clone(),
let dispatch_count2 = dispatch_count.clone();
let ext = Extension::builder()
.ops(vec![("op_test", Box::new(op_test))])
.state(move |state| {
state.put(TestState {
mode,
dispatch_count: dispatch_count2.clone(),
});
Ok(())
})
.build();
let mut runtime = JsRuntime::new(RuntimeOptions {
extensions: vec![ext],
..Default::default()
});
runtime.register_op("op_test", dispatch);
runtime.sync_ops_cache();
runtime
.execute_script(
"setup.js",
@ -2029,12 +2036,14 @@ pub mod tests {
}
run_in_task(|cx| {
let ext = Extension::builder()
.ops(vec![("op_err", op_sync(op_err))])
.build();
let mut runtime = JsRuntime::new(RuntimeOptions {
extensions: vec![ext],
get_error_class_fn: Some(&get_error_class_name),
..Default::default()
});
runtime.register_op("op_err", op_sync(op_err));
runtime.sync_ops_cache();
runtime
.execute_script(
"error_builder_test.js",