Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call sync functions within tokio runtime #1242

Merged
merged 1 commit into from Aug 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 6 additions & 4 deletions crates/backend/src/codegen/fn.rs
Expand Up @@ -21,10 +21,12 @@ impl TryToTokens for NapiFn {

let native_call = if !self.is_async {
quote! {
let #receiver_ret_name = {
#receiver(#(#arg_names),*)
};
#ret
napi::bindgen_prelude::within_runtime_if_available(move || {
let #receiver_ret_name = {
#receiver(#(#arg_names),*)
};
#ret
})
}
} else {
let call = if self.is_ret_result {
Expand Down
10 changes: 10 additions & 0 deletions crates/napi/src/lib.rs
Expand Up @@ -162,6 +162,16 @@ pub mod bindgen_prelude {
assert_type_of, bindgen_runtime::*, check_status, check_status_or_throw, error, error::*, sys,
type_of, JsError, Property, PropertyAttributes, Result, Status, Task, ValueType,
};

// This function's signature must be kept in sync with the one in tokio_runtime.rs, otherwise napi
// will fail to compile without the `tokio_rt` feature.

/// If the feature `tokio_rt` has been enabled this will enter the runtime context and
/// then call the provided closure. Otherwise it will just call the provided closure.
#[cfg(not(all(feature = "tokio_rt", feature = "napi4")))]
pub fn within_runtime_if_available<F: FnOnce() -> T, T>(f: F) -> T {
f()
}
}

#[doc(hidden)]
Expand Down
10 changes: 10 additions & 0 deletions crates/napi/src/tokio_runtime.rs
Expand Up @@ -59,6 +59,16 @@ where
RT.0.spawn(fut);
}

// This function's signature must be kept in sync with the one in lib.rs, otherwise napi
// will fail to compile with the `tokio_rt` feature.

/// If the feature `tokio_rt` has been enabled this will enter the runtime context and
/// then call the provided closure. Otherwise it will just call the provided closure.
pub fn within_runtime_if_available<F: FnOnce() -> T, T>(f: F) -> T {
let _rt_guard = RT.0.enter();
f()
}

#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn execute_tokio_future<
Data: 'static + Send,
Expand Down
1 change: 1 addition & 0 deletions examples/napi/Cargo.toml
Expand Up @@ -25,6 +25,7 @@ napi-derive = { path = "../../crates/macro", features = ["type-def"] }
serde = "1"
serde_derive = "1"
serde_json = "1"
tokio = { version = "1.20.0", features = ["full"] }

[build-dependencies]
napi-build = { path = "../../crates/build" }
Expand Down
1 change: 1 addition & 0 deletions examples/napi/__test__/typegen.spec.ts.md
Expand Up @@ -179,6 +179,7 @@ Generated by [AVA](https://avajs.dev).
export function threadsafeFunctionThrowError(cb: (...args: any[]) => any): void␊
export function threadsafeFunctionFatalMode(cb: (...args: any[]) => any): void␊
export function threadsafeFunctionFatalModeError(cb: (...args: any[]) => any): void␊
export function useTokioWithoutAsync(): void␊
export function getBuffer(): Buffer␊
export function appendBuffer(buf: Buffer): Buffer␊
export function getEmptyBuffer(): Buffer␊
Expand Down
Binary file modified examples/napi/__test__/typegen.spec.ts.snap
Binary file not shown.
7 changes: 7 additions & 0 deletions examples/napi/__test__/values.spec.ts
Expand Up @@ -103,6 +103,7 @@ import {
receiveObjectWithClassField,
AnotherClassForEither,
receiveDifferentClass,
useTokioWithoutAsync,
} from '../'

test('export const', (t) => {
Expand Down Expand Up @@ -691,6 +692,12 @@ Napi4Test('await Promise in rust', async (t) => {
t.is(result, fx + 100)
})

Napi4Test('Run function which uses tokio internally but is not async', (t) => {
useTokioWithoutAsync()
// The prior didn't throw an exception, so it worked.
t.assert(true)
})

Napi4Test('Promise should reject raw error in rust', async (t) => {
const fxError = new Error('What is Happy Planet')
const err = await t.throwsAsync(() => asyncPlus100(Promise.reject(fxError)))
Expand Down
1 change: 1 addition & 0 deletions examples/napi/index.d.ts
Expand Up @@ -169,6 +169,7 @@ export function callThreadsafeFunction(callback: (...args: any[]) => any): void
export function threadsafeFunctionThrowError(cb: (...args: any[]) => any): void
export function threadsafeFunctionFatalMode(cb: (...args: any[]) => any): void
export function threadsafeFunctionFatalModeError(cb: (...args: any[]) => any): void
export function useTokioWithoutAsync(): void
export function getBuffer(): Buffer
export function appendBuffer(buf: Buffer): Buffer
export function getEmptyBuffer(): Buffer
Expand Down
1 change: 1 addition & 0 deletions examples/napi/src/lib.rs
Expand Up @@ -39,4 +39,5 @@ mod string;
mod symbol;
mod task;
mod threadsafe_function;
mod tokio_outside_async;
mod typed_array;
18 changes: 18 additions & 0 deletions examples/napi/src/tokio_outside_async.rs
@@ -0,0 +1,18 @@
use std::time::Duration;
use tokio::{sync::oneshot, time::Instant};

#[napi]
pub fn use_tokio_without_async() {
let (sender, receiver) = oneshot::channel();
let handle = tokio::task::spawn(async {
// If this panics, the test failed.
sender.send(true).unwrap();
});
let start = Instant::now();
while !handle.is_finished() {
if start.elapsed() > Duration::from_secs(5) {
panic!("The future never resolved.");
}
}
assert_eq!(receiver.blocking_recv(), Ok(true));
}