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. //! JavaScript.
use deno_core::op_sync; use deno_core::op_sync;
use deno_core::Extension;
use deno_core::JsRuntime; use deno_core::JsRuntime;
use deno_core::RuntimeOptions;
fn main() { fn main() {
// Initialize a runtime instance // Build a deno_core::Extension providing custom ops
let mut runtime = JsRuntime::new(Default::default()); 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. // Initialize a runtime instance
runtime.register_op( let mut runtime = JsRuntime::new(RuntimeOptions {
"op_sum", extensions: vec![ext],
// The op-layer automatically deserializes inputs ..Default::default()
// 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();
// Now we see how to invoke the op we just defined. The runtime automatically // 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. // 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 { fn create_js_runtime() -> JsRuntime {
let mut runtime = JsRuntime::new(Default::default()); let ext = deno_core::Extension::builder()
runtime.register_op("listen", deno_core::op_sync(op_listen)); .ops(vec![
runtime.register_op("accept", deno_core::op_async(op_accept)); ("listen", deno_core::op_sync(op_listen)),
runtime.sync_ops_cache(); ("accept", deno_core::op_async(op_accept)),
runtime ])
.build();
JsRuntime::new(deno_core::RuntimeOptions {
extensions: vec![ext],
..Default::default()
})
} }
fn op_listen(state: &mut OpState, _: (), _: ()) -> Result<ResourceId, Error> { fn op_listen(state: &mut OpState, _: (), _: ()) -> Result<ResourceId, Error> {

View file

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

View file

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

View file

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