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

Feat: Added client destroy #679

Merged
merged 16 commits into from
Jun 29, 2023
2 changes: 1 addition & 1 deletion .github/workflows/bindings-wasm-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
- name: Install wasm-bindgen-cli
uses: jetli/wasm-bindgen-action@24ba6f9fff570246106ac3f80f35185600c3f6c9
with:
version: "0.2.86"
version: "0.2.87"

- name: Set up Node.js
uses: actions/setup-node@v2
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/bindings-wasm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ jobs:
- name: Install wasm-bindgen-cli
uses: jetli/wasm-bindgen-action@24ba6f9fff570246106ac3f80f35185600c3f6c9
with:
version: "0.2.86"
version: "0.2.87"

- name: Set Up Node.js ${{ matrix.node }} and Yarn Cache
uses: actions/setup-node@v2
Expand Down
20 changes: 10 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions bindings/nodejs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## 1.0.0-rc.2 - 2023-0x-xx

### Added

- `Client::destroy` to close an open handle;

### Changed

- Rename `Account::prepareMintNativeToken` to `prepareCreateNativeToken`, `Account::prepareIncreaseNativeTokenSupply` to `prepareMintNativeToken`, `Account::prepareDecreaseNativeTokenSupply` to `prepareMeltNativeToken`;
Expand Down
3 changes: 3 additions & 0 deletions bindings/nodejs/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/**/*.(test|spec).ts'],
verbose: false,
detectOpenHandles: true,
forceExit: true,
moduleNameMapper: {
'index.node': '<rootDir>/build/Release/index.node',
},
Expand Down
2 changes: 2 additions & 0 deletions bindings/nodejs/lib/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const {
initLogger,
callClientMethod,
createClient,
destroyClient,
listenMqtt,
callWalletMethod,
createWallet,
Expand Down Expand Up @@ -101,6 +102,7 @@ const callWalletMethodAsync = (
export {
initLogger,
createClient,
destroyClient,
createSecretManager,
createWallet,
callClientMethodAsync,
Expand Down
11 changes: 10 additions & 1 deletion bindings/nodejs/lib/client/client-method-handler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { callClientMethodAsync, createClient, listenMqtt } from '../bindings';
import {
callClientMethodAsync,
createClient,
listenMqtt,
destroyClient,
} from '../bindings';
import type { IClientOptions, __ClientMethods__ } from '../types/client';

/** The MethodHandler which sends the commands to the Rust side. */
Expand All @@ -17,6 +22,10 @@ export class ClientMethodHandler {
}
}

async destroy() {
return destroyClient(this.methodHandler);
}

async callMethod(method: __ClientMethods__): Promise<string> {
return callClientMethodAsync(
JSON.stringify(method),
Expand Down
4 changes: 4 additions & 0 deletions bindings/nodejs/lib/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export class Client {
this.methodHandler = new ClientMethodHandler(options);
}

async destroy() {
return this.methodHandler.destroy();
}

/**
* Returns the node information together with the url of the used node
* @returns { Promise<INodeInfoWrapper> }.
Expand Down
2 changes: 1 addition & 1 deletion bindings/nodejs/lib/wallet/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export class Wallet {
* Destroy the Wallet and drop its database connection.
*/
async destroy(): Promise<void> {
await this.methodHandler.destroy();
return this.methodHandler.destroy();
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down
2 changes: 1 addition & 1 deletion bindings/nodejs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"prebuild-arm64": "prebuild --runtime napi --target 6 --prepack scripts/neon-build.js --strip --arch arm64",
"rebuild": "node scripts/neon-build && tsc && node scripts/strip.js",
"install": "prebuild-install --runtime napi --tag-prefix='iota-sdk-nodejs-v' && tsc || npm run rebuild",
"test": "jest --forceExit"
Thoralf-M marked this conversation as resolved.
Show resolved Hide resolved
"test": "jest"
},
"author": "IOTA Foundation <[email protected]>",
"license": "Apache-2.0",
Expand Down
102 changes: 67 additions & 35 deletions bindings/nodejs/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,31 @@ use iota_sdk_bindings_core::{
listen_mqtt as rust_listen_mqtt, ClientMethod, Response, Result,
};
use neon::prelude::*;
use tokio::sync::RwLock;

type JsCallback = Root<JsFunction<JsObject>>;

// Wrapper so we can destroy the ClientMethodHandler
pub type ClientMethodHandlerWrapperInner = Arc<RwLock<Option<ClientMethodHandler>>>;
// Wrapper because we can't impl Finalize on ClientMethodHandlerWrapperInner
pub struct ClientMethodHandlerWrapper(pub ClientMethodHandlerWrapperInner);
pub struct ClientMethodHandler {
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved
channel: Channel,
client: Client,
}

impl Finalize for ClientMethodHandler {}
impl Finalize for ClientMethodHandlerWrapper {}

impl ClientMethodHandler {
pub fn new(channel: Channel, options: String) -> Result<Arc<Self>> {
pub fn new(channel: Channel, options: String) -> Result<Self> {
let runtime = tokio::runtime::Runtime::new().expect("error initializing client");
let client = runtime.block_on(ClientBuilder::new().from_json(&options)?.finish())?;

Ok(Arc::new(Self { channel, client }))
Ok(Self { channel, client })
}

pub(crate) fn new_with_client(channel: Channel, client: Client) -> Arc<Self> {
Arc::new(Self { channel, client })
pub(crate) fn new_with_client(channel: Channel, client: Client) -> Self {
Self { channel, client }
}

async fn call_method(&self, serialized_method: String) -> (String, bool) {
Expand All @@ -55,43 +60,66 @@ impl ClientMethodHandler {
}
}

pub fn create_client(mut cx: FunctionContext) -> JsResult<JsBox<Arc<ClientMethodHandler>>> {
pub fn create_client(mut cx: FunctionContext) -> JsResult<JsBox<ClientMethodHandlerWrapper>> {
let options = cx.argument::<JsString>(0)?;
let options = options.value(&mut cx);
let channel = cx.channel();
let method_handler = ClientMethodHandler::new(channel, options)
.or_else(|e| cx.throw_error(serde_json::to_string(&Response::Error(e)).expect("json to string error")))?;
Ok(cx.boxed(ClientMethodHandlerWrapper(Arc::new(RwLock::new(Some(method_handler))))))
}

Ok(cx.boxed(method_handler))
pub fn destroy_client(mut cx: FunctionContext) -> JsResult<JsPromise> {
let method_handler = Arc::clone(&&cx.argument::<JsBox<ClientMethodHandlerWrapper>>(0)?.0);
let channel = cx.channel();
let (deferred, promise) = cx.promise();
crate::RUNTIME.spawn(async move {
*method_handler.write().await = None;
deferred.settle_with(&channel, move |mut cx| Ok(cx.undefined()));
});
Ok(promise)
}

pub fn call_client_method(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let method = cx.argument::<JsString>(0)?;
let method = method.value(&mut cx);
let method_handler = Arc::clone(&&cx.argument::<JsBox<Arc<ClientMethodHandler>>>(1)?);
let method_handler = Arc::clone(&&cx.argument::<JsBox<ClientMethodHandlerWrapper>>(1)?.0);
let callback = cx.argument::<JsFunction>(2)?.root(&mut cx);

let (sender, receiver) = std::sync::mpsc::channel();
crate::RUNTIME.spawn(async move {
let (response, is_error) = method_handler.call_method(method).await;
method_handler.channel.send(move |mut cx| {
let cb = callback.into_inner(&mut cx);
let this = cx.undefined();

let args = [
if is_error {
cx.string(response.clone()).upcast::<JsValue>()
} else {
cx.undefined().upcast::<JsValue>()
},
cx.string(response).upcast::<JsValue>(),
];

cb.call(&mut cx, this, args)?;

Ok(())
});
if let Some(method_handler) = &*method_handler.read().await {
let (response, is_error) = method_handler.call_method(method).await;
method_handler.channel.send(move |mut cx| {
let cb = callback.into_inner(&mut cx);
let this = cx.undefined();

let args = [
if is_error {
cx.string(response.clone()).upcast::<JsValue>()
} else {
cx.undefined().upcast::<JsValue>()
},
cx.string(response).upcast::<JsValue>(),
];

cb.call(&mut cx, this, args)?;

Ok(())
});
} else {
// Notify that the client got destroyed
// Safe to unwrap because the receiver is waiting on it
sender.send(()).unwrap();
}
});

if receiver.recv().is_ok() {
return cx.throw_error(
serde_json::to_string(&Response::Panic("Client got destroyed".to_string())).expect("json to string error"),
);
}

Ok(cx.undefined())
}

Expand All @@ -106,18 +134,22 @@ pub fn listen_mqtt(mut cx: FunctionContext) -> JsResult<JsPromise> {
}

let callback = Arc::new(cx.argument::<JsFunction>(1)?.root(&mut cx));
let method_handler = Arc::clone(&&cx.argument::<JsBox<Arc<ClientMethodHandler>>>(2)?);
let method_handler = Arc::clone(&&cx.argument::<JsBox<ClientMethodHandlerWrapper>>(2)?.0);
let (deferred, promise) = cx.promise();

crate::RUNTIME.spawn(async move {
let channel0 = method_handler.channel.clone();
let channel1 = method_handler.channel.clone();
rust_listen_mqtt(&method_handler.client, topics, move |event_data| {
call_event_callback(&channel0, event_data, callback.clone())
})
.await;

deferred.settle_with(&channel1, move |mut cx| Ok(cx.undefined()));
if let Some(method_handler) = &*method_handler.read().await {
let channel0 = method_handler.channel.clone();
let channel1 = method_handler.channel.clone();
rust_listen_mqtt(&method_handler.client, topics, move |event_data| {
call_event_callback(&channel0, event_data, callback.clone())
})
.await;

deferred.settle_with(&channel1, move |mut cx| Ok(cx.undefined()));
} else {
panic!("Client got destroyed")
}
});

Ok(promise)
Expand Down
1 change: 1 addition & 0 deletions bindings/nodejs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
// Client
cx.export_function("callClientMethod", client::call_client_method)?;
cx.export_function("createClient", client::create_client)?;
cx.export_function("destroyClient", client::destroy_client)?;
// MQTT
cx.export_function("listenMqtt", client::listen_mqtt)?;

Expand Down
11 changes: 9 additions & 2 deletions bindings/nodejs/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use iota_sdk_bindings_core::{
use neon::prelude::*;
use tokio::sync::RwLock;

use crate::{client::ClientMethodHandler, secret_manager::SecretManagerMethodHandler};
use crate::{
client::{ClientMethodHandler, ClientMethodHandlerWrapper},
secret_manager::SecretManagerMethodHandler,
};

// Wrapper so we can destroy the WalletMethodHandler
pub type WalletMethodHandlerWrapperInner = Arc<RwLock<Option<WalletMethodHandler>>>;
Expand Down Expand Up @@ -187,7 +190,11 @@ pub fn get_client(mut cx: FunctionContext) -> JsResult<JsPromise> {
if let Some(method_handler) = &*method_handler.read().await {
let client_method_handler =
ClientMethodHandler::new_with_client(channel.clone(), method_handler.wallet.client().clone());
deferred.settle_with(&channel, move |mut cx| Ok(cx.boxed(client_method_handler)));
deferred.settle_with(&channel, move |mut cx| {
Ok(cx.boxed(ClientMethodHandlerWrapper(Arc::new(RwLock::new(Some(
client_method_handler,
))))))
});
} else {
deferred.settle_with(&channel, move |mut cx| {
cx.error(
Expand Down
Loading