1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-30 16:40:57 -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 GitHub
parent b33bbf6af5
commit 92e8a29269
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 71 additions and 38 deletions

View file

@ -3,14 +3,16 @@
//! 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![
// Register an op for summing a number array. // An op for summing an array of numbers
runtime.register_op( (
"op_sum", "op_sum",
// The op-layer automatically deserializes inputs // The op-layer automatically deserializes inputs
// and serializes the returned Result & value // and serializes the returned Result & value
@ -20,8 +22,15 @@ fn main() {
// return as a Result<f64, AnyError> // return as a Result<f64, AnyError>
Ok(sum) Ok(sum)
}), }),
); ),
runtime.sync_ops_cache(); ])
.build();
// 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 // 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,15 +1688,21 @@ 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))])
.state(move |state| {
state.put(TestState {
mode, mode,
dispatch_count: dispatch_count.clone(), 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(
@ -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",