Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[OV JS] Add AsyncInferQueue (#30092)

Alicja Miloszewska1ddabf4812a0
diff --git a/src/bindings/js/node/CMakeLists.txt b/src/bindings/js/node/CMakeLists.txt
index ce90fe5f490..2431210f417 100644
--- a/src/bindings/js/node/CMakeLists.txt
+++ b/src/bindings/js/node/CMakeLists.txt
@@ -48,6 +48,7 @@ FetchContent_MakeAvailable(node-addon-api)
add_library(${PROJECT_NAME} SHARED
${CMAKE_CURRENT_SOURCE_DIR}/src/node_output.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/async_reader.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/async_infer_queue.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/preprocess/preprocess.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/preprocess/pre_post_process_wrap.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/preprocess/preprocess_steps.cpp
diff --git a/src/bindings/js/node/include/addon.hpp b/src/bindings/js/node/include/addon.hpp
index 5056e11e7b0..619cc38b357 100644
--- a/src/bindings/js/node/include/addon.hpp
+++ b/src/bindings/js/node/include/addon.hpp
@@ -9,6 +9,7 @@ typedef Napi::Function (*Prototype)(Napi::Env);
/** @brief A structure with data that will be associated with the instance of the ov.js node-addon. */
struct AddonData {
+ Napi::FunctionReference async_infer_queue;
Napi::FunctionReference compiled_model;
Napi::FunctionReference core;
Napi::FunctionReference const_output;
diff --git a/src/bindings/js/node/include/async_infer_queue.hpp b/src/bindings/js/node/include/async_infer_queue.hpp
new file mode 100644
index 00000000000..095cacadd5d
--- /dev/null
+++ b/src/bindings/js/node/include/async_infer_queue.hpp
@@ -0,0 +1,48 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+#include <napi.h>
+
+#include <condition_variable>
+#include <mutex>
+#include <queue>
+#include <string>
+#include <vector>
+
+#include "openvino/runtime/infer_request.hpp"
+
+class AsyncInferQueue : public Napi::ObjectWrap<AsyncInferQueue> {
+public:
+ AsyncInferQueue(const Napi::CallbackInfo& info);
+ static Napi::Function get_class(Napi::Env env);
+
+ void release(const Napi::CallbackInfo& info);
+ void set_custom_callbacks(const Napi::CallbackInfo& info);
+ /**
+ * @param info[0] Napi::Object containing data for inference.
+ * @param info[1] Napi::Object containing user data that will be passed to the callback. [Optional]
+ */
+ Napi::Value start_async(const Napi::CallbackInfo& info);
+
+private:
+ int check_idle_request_id();
+ void start_async_impl(const size_t handle,
+ Napi::Object infer_data,
+ Napi::Object user_data,
+ Napi::Promise::Deferred deferred);
+ void set_tsfn(Napi::Env env, Napi::Function callback);
+ void release();
+
+ // AsyncInferQueue is the owner of all requests. When AsyncInferQueue is destroyed,
+ // all of requests are destroyed as well.
+ std::vector<ov::InferRequest> m_requests;
+ std::vector<Napi::ObjectReference> m_user_inputs; // to prevent garbage collection
+ std::vector<std::pair<Napi::ObjectReference, Napi::Promise::Deferred>> m_user_ids;
+
+ std::queue<size_t> m_idle_handles;
+ std::queue<std::tuple<Napi::ObjectReference, Napi::ObjectReference, Napi::Promise::Deferred>> m_awaiting_requests;
+
+ std::mutex m_mutex;
+ Napi::ThreadSafeFunction m_tsfn;
+};
diff --git a/src/bindings/js/node/include/compiled_model.hpp b/src/bindings/js/node/include/compiled_model.hpp
index 858546dd470..3d1baa1e87b 100644
--- a/src/bindings/js/node/include/compiled_model.hpp
+++ b/src/bindings/js/node/include/compiled_model.hpp
@@ -33,6 +33,9 @@ public:
* object on node-addon side. */
void set_compiled_model(const ov::CompiledModel& compiled_model);
+ /** @brief Gets a _compiled_model property of a CompiledModelWrap object. */
+ ov::CompiledModel& get_compiled_model();
+
/** @return A Javascript InferRequest */
Napi::Value create_infer_request(const Napi::CallbackInfo& info);
@@ -91,7 +94,7 @@ private:
/** @brief Gets node of a compiled model specified in CallbackInfo. */
Napi::Value get_node(const Napi::CallbackInfo& info,
const ov::Output<const ov::Node>& (ov::CompiledModel::*func)() const,
- const ov::Output<const ov::Node>& (ov::CompiledModel::*func_tname)(const std::string&)const,
+ const ov::Output<const ov::Node>& (ov::CompiledModel::*func_tname)(const std::string&) const,
const ov::Output<const ov::Node>& (ov::CompiledModel::*func_idx)(size_t) const);
ov::CompiledModel _compiled_model;
diff --git a/src/bindings/js/node/include/helper.hpp b/src/bindings/js/node/include/helper.hpp
index 6801f031555..04d408aa7d2 100644
--- a/src/bindings/js/node/include/helper.hpp
+++ b/src/bindings/js/node/include/helper.hpp
@@ -176,3 +176,5 @@ bool is_napi_value_int(const Napi::Env& env, const Napi::Value& num);
ov::AnyMap to_anyMap(const Napi::Env&, const Napi::Value&);
std::string buffer_to_string(const Napi::Value& value);
+
+uint32_t get_optimal_number_of_requests(const ov::CompiledModel& actual);
diff --git a/src/bindings/js/node/include/type_validation.hpp b/src/bindings/js/node/include/type_validation.hpp
index 765a9e4920f..9d9f4715a73 100644
--- a/src/bindings/js/node/include/type_validation.hpp
+++ b/src/bindings/js/node/include/type_validation.hpp
@@ -5,6 +5,7 @@
#include <napi.h>
#include "node/include/addon.hpp"
+#include "node/include/compiled_model.hpp"
#include "node/include/model_wrap.hpp"
#include "node/include/node_output.hpp"
#include "node/include/partial_shape_wrap.hpp"
@@ -27,6 +28,9 @@ const char* get_attr_type() {
OPENVINO_THROW("get_attr_type is not implemented for passed type!");
};
+template <>
+const char* get_attr_type<Napi::Value>();
+
template <>
const char* get_attr_type<Napi::String>();
@@ -36,6 +40,9 @@ const char* get_attr_type<Napi::Object>();
template <>
const char* get_attr_type<Napi::Boolean>();
+template <>
+const char* get_attr_type<Napi::Function>();
+
template <>
const char* get_attr_type<Napi::Buffer<uint8_t>>();
@@ -45,6 +52,9 @@ const char* get_attr_type<int>();
template <>
const char* get_attr_type<ModelWrap>();
+template <>
+const char* get_attr_type<CompiledModelWrap>();
+
template <>
const char* get_attr_type<TensorWrap>();
@@ -59,6 +69,9 @@ bool validate_value(const Napi::Env& env, const Napi::Value& arg) {
OPENVINO_THROW("Validation for this type is not implemented!");
};
+template <>
+bool validate_value<Napi::Value>(const Napi::Env& env, const Napi::Value& value);
+
template <>
bool validate_value<Napi::String>(const Napi::Env& env, const Napi::Value& value);
@@ -68,6 +81,9 @@ bool validate_value<Napi::Object>(const Napi::Env& env, const Napi::Value& value
template <>
bool validate_value<Napi::Boolean>(const Napi::Env& env, const Napi::Value& value);
+template <>
+bool validate_value<Napi::Function>(const Napi::Env& env, const Napi::Value& value);
+
template <>
bool validate_value<Napi::Buffer<uint8_t>>(const Napi::Env& env, const Napi::Value& value);
@@ -77,6 +93,9 @@ bool validate_value<int>(const Napi::Env& env, const Napi::Value& value);
template <>
bool validate_value<ModelWrap>(const Napi::Env& env, const Napi::Value& value);
+template <>
+bool validate_value<CompiledModelWrap>(const Napi::Env& env, const Napi::Value& value);
+
/** @brief Checks if Napi::Value is a Tensor.*/
template <>
bool validate_value<TensorWrap>(const Napi::Env& env, const Napi::Value& value);
diff --git a/src/bindings/js/node/lib/addon.ts b/src/bindings/js/node/lib/addon.ts
index 0a8c4bcfe29..761c6718dc0 100644
--- a/src/bindings/js/node/lib/addon.ts
+++ b/src/bindings/js/node/lib/addon.ts
@@ -655,6 +655,54 @@ interface PartialShape {
getDimensions(): Dimension[];
}
+/**
+ * Callback function type for AsyncInferQueue operations.
+ * @param inferRequest The {@link InferRequest} object from the queue's pool.
+ * It allows to access input and output tensors.
+ * @param userData User data that was passed to the startAsync method. If data was not
+ * passed, it will be undefined.
+ * @param error Optional error that occurred during inference, if any.
+ */
+type AsyncInferQueueCallback = (
+ error: null | Error,
+ inferRequest: InferRequest,
+ userData: object,
+) => void;
+
+interface AsyncInferQueue {
+ /**
+ * Creates AsyncInferQueue.
+ * @param compiledModel The compiledModel that will be used
+ * to create InferRequests in the pool.
+ * @param jobs Number of InferRequest objects in the pool. If not provided,
+ * jobs number will be set automatically to the optimal number.
+ */
+ new (compiledModel: CompiledModel, jobs?: number): AsyncInferQueue;
+ /**
+ * Sets unified callback on all InferRequests from queue's pool.
+ * The callback that was previously set will be replaced.
+ * @param callback - Any function that matches callback's requirements.
+ */
+ setCallback(callback: AsyncInferQueueCallback): void;
+ /**
+ * It starts asynchronous inference for the specified input data.
+ * @param inputData An object with the key-value pairs where the key is the
+ * input name and value is a tensor or an array with tensors.
+ * @param userData User data that will be passed to the callback.
+ * @returns A Promise that can be used to track the callback completion.
+ */
+ startAsync(
+ inputData: { [inputName: string]: Tensor } | Tensor[],
+ userData?: object,
+ ): Promise<object>;
+ /**
+ * Releases resources associated with this AsyncInferQueue instance.
+ * Call this method after all `startAsync` requests have completed
+ * and the AsyncInferQueue is no longer needed.
+ */
+ release(): void;
+}
+
declare enum element {
u8,
u32,
@@ -683,6 +731,7 @@ export interface NodeAddon {
InferRequest: InferRequest;
Output: Output;
PartialShape: PartialShape;
+ AsyncInferQueue: AsyncInferQueue;
preprocess: {
resizeAlgorithm: typeof resizeAlgorithm;
diff --git a/src/bindings/js/node/src/addon.cpp b/src/bindings/js/node/src/addon.cpp
index 97921b7127b..8be3dbd6837 100644
--- a/src/bindings/js/node/src/addon.cpp
+++ b/src/bindings/js/node/src/addon.cpp
@@ -5,6 +5,7 @@
#include <napi.h>
+#include "node/include/async_infer_queue.hpp"
#include "node/include/compiled_model.hpp"
#include "node/include/core_wrap.hpp"
#include "node/include/element_type.hpp"
@@ -67,6 +68,7 @@ Napi::Object init_module(Napi::Env env, Napi::Object exports) {
init_class(env, exports, "Output", &Output<ov::Node>::get_class, addon_data->output);
init_class(env, exports, "ConstOutput", &Output<const ov::Node>::get_class, addon_data->const_output);
init_class(env, exports, "PartialShape", &PartialShapeWrap::get_class, addon_data->partial_shape);
+ init_class(env, exports, "AsyncInferQueue", &AsyncInferQueue::get_class, addon_data->async_infer_queue);
init_function(env, exports, "saveModelSync", save_model_sync);
diff --git a/src/bindings/js/node/src/async_infer_queue.cpp b/src/bindings/js/node/src/async_infer_queue.cpp
new file mode 100644
index 00000000000..e600812fc59
--- /dev/null
+++ b/src/bindings/js/node/src/async_infer_queue.cpp
@@ -0,0 +1,198 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "node/include/async_infer_queue.hpp"
+
+#include <condition_variable>
+#include <mutex>
+#include <queue>
+#include <string>
+#include <vector>
+
+namespace {
+constexpr const char* UNDEFINED_USER_DATA = "UNDEFINED";
+}
+
+#include "node/include/addon.hpp"
+#include "node/include/compiled_model.hpp"
+#include "node/include/errors.hpp"
+#include "node/include/helper.hpp"
+#include "node/include/infer_request.hpp"
+#include "node/include/node_output.hpp"
+#include "node/include/tensor.hpp"
+#include "node/include/type_validation.hpp"
+
+AsyncInferQueue::AsyncInferQueue(const Napi::CallbackInfo& info) : Napi::ObjectWrap<AsyncInferQueue>(info) {
+ const auto env = info.Env();
+ std::vector<std::string> allowed_signatures;
+
+ try {
+ const auto are_arguments_valid = ov::js::validate<CompiledModelWrap>(info, allowed_signatures) ||
+ ov::js::validate<CompiledModelWrap, int>(info, allowed_signatures);
+ OPENVINO_ASSERT(are_arguments_valid,
+ "'AsyncInferQueue' constructor",
+ ov::js::get_parameters_error_msg(info, allowed_signatures));
+
+ auto& compiled = Napi::ObjectWrap<CompiledModelWrap>::Unwrap(info[0].ToObject())->get_compiled_model();
+ size_t jobs =
+ info.Length() == 1 ? get_optimal_number_of_requests(compiled) : info[1].As<Napi::Number>().Int32Value();
+ m_tsfn = nullptr;
+
+ m_requests.reserve(jobs);
+ m_user_ids.reserve(jobs);
+ m_user_inputs.reserve(jobs);
+
+ for (size_t handle = 0; handle < jobs; handle++) {
+ m_requests.emplace_back(compiled.create_infer_request());
+ m_user_ids.push_back(std::make_pair(Napi::Reference<Napi::Object>::New(Napi::Object::New(env), 1),
+ Napi::Promise::Deferred::New(env)));
+ m_user_inputs.push_back(Napi::Reference<Napi::Object>::New(Napi::Object::New(env), 1));
+ m_idle_handles.push(handle);
+ }
+
+ } catch (const ov::Exception& e) {
+ reportError(env, e.what());
+ }
+}
+
+void AsyncInferQueue::release() {
+ if (m_tsfn) {
+ const auto status = m_tsfn.Release();
+ OPENVINO_ASSERT(status == napi_ok, "Failed to release AsyncInferQueue resources.");
+ m_tsfn = nullptr;
+ }
+}
+
+void AsyncInferQueue::release(const Napi::CallbackInfo& info) {
+ try {
+ release();
+ } catch (const ov::Exception& e) {
+ reportError(info.Env(), e.what());
+ }
+}
+
+Napi::Function AsyncInferQueue::get_class(Napi::Env env) {
+ return DefineClass(env,
+ "AsyncInferQueue",
+ {
+ InstanceMethod("setCallback", &AsyncInferQueue::set_custom_callbacks),
+ InstanceMethod("startAsync", &AsyncInferQueue::start_async),
+ InstanceMethod("release", &AsyncInferQueue::release),
+ });
+}
+
+int AsyncInferQueue::check_idle_request_id() {
+ std::unique_lock<std::mutex> lock(m_mutex);
+ if (m_idle_handles.empty()) {
+ return -1;
+ }
+ auto idle_handle = static_cast<int>(m_idle_handles.front());
+ m_idle_handles.pop();
+ return idle_handle;
+}
+
+void AsyncInferQueue::set_tsfn(Napi::Env env, Napi::Function callback) {
+ release(); // release previous ThreadSafeFunction if it exists
+ m_tsfn = Napi::ThreadSafeFunction::New(env, callback, "AsyncInferQueueCallback", 0, 1);
+}
+
+void AsyncInferQueue::set_custom_callbacks(const Napi::CallbackInfo& info) {
+ std::vector<std::string> allowed_signatures;
+ try {
+ OPENVINO_ASSERT(ov::js::validate<Napi::Function>(info, allowed_signatures),
+ "'setCallback'",
+ ov::js::get_parameters_error_msg(info, allowed_signatures));
+
+ set_tsfn(info.Env(), info[0].As<Napi::Function>());
+ for (size_t handle = 0; handle < m_requests.size(); handle++) {
+ m_requests[handle].set_callback([this, handle](std::exception_ptr exception_ptr) {
+ try {
+ if (exception_ptr) {
+ std::rethrow_exception(exception_ptr);
+ }
+ auto ov_callback = [this, handle](Napi::Env env, Napi::Function user_callback) {
+ Napi::Object js_ir = InferRequestWrap::wrap(env, m_requests[handle]);
+ const auto promise = m_user_ids[handle].second;
+ try {
+ auto user_data =
+ m_user_ids[handle].first.Value().ToString().Utf8Value() == UNDEFINED_USER_DATA
+ ? env.Undefined()
+ : m_user_ids[handle].first.Value();
+ user_callback.Call({env.Null(), js_ir, user_data}); // CVS-170804
+ promise.Resolve(user_data);
+ // returns before the promise's .then() is completed
+ } catch (Napi::Error& e) {
+ promise.Reject(Napi::Error::New(env, e.Message()).Value());
+ }
+ // Start async inference on the next request or add idle handle to queue
+ if (std::lock_guard<std::mutex> lock(m_mutex); m_awaiting_requests.size() > 0) {
+ const auto& [infer_data, user_data, promise] = m_awaiting_requests.front();
+ start_async_impl(handle, infer_data.Value(), user_data.Value(), promise);
+ m_awaiting_requests.pop();
+ } else {
+ m_idle_handles.push(handle);
+ }
+ };
+ // The ov_callback will execute when the main event loop will be free
+ napi_status status = m_tsfn.BlockingCall(ov_callback);
+ OPENVINO_ASSERT(status == napi_ok, "Failed to call user callback.");
+ } catch (const std::exception& e) {
+ OPENVINO_THROW(e.what());
+ }
+ });
+ }
+ } catch (std::exception& e) {
+ reportError(info.Env(), e.what());
+ }
+}
+
+void AsyncInferQueue::start_async_impl(const size_t handle,
+ Napi::Object infer_data,
+ Napi::Object user_data,
+ Napi::Promise::Deferred deferred) {
+ m_user_inputs[handle] = Napi::Persistent(infer_data); // keep reference to inputs so they are not garbage collected
+ m_user_ids[handle] = std::make_pair(Napi::Persistent(user_data), deferred);
+
+ // CVS-166764
+ const auto& keys = infer_data.GetPropertyNames();
+ for (uint32_t i = 0; i < keys.Length(); ++i) {
+ auto input_name = static_cast<Napi::Value>(keys[i]).ToString().Utf8Value();
+ auto value = infer_data.Get(input_name);
+ auto tensor = value_to_tensor(value, m_requests[handle], input_name);
+
+ m_requests[handle].set_tensor(input_name, tensor);
+ }
+
+ OPENVINO_ASSERT(m_tsfn != nullptr, "Callback has to be set before starting inference. Use 'setCallback' method.");
+ m_requests[handle].start_async(); // returns immediately, main event loop is free
+}
+
+Napi::Value AsyncInferQueue::start_async(const Napi::CallbackInfo& info) {
+ std::vector<std::string> allowed_signatures;
+
+ try {
+ const auto are_arguments_valid = ov::js::validate<Napi::Object>(info, allowed_signatures) ||
+ ov::js::validate<Napi::Object, Napi::Value>(info, allowed_signatures);
+ OPENVINO_ASSERT(are_arguments_valid,
+ "'startAsync'",
+ ov::js::get_parameters_error_msg(info, allowed_signatures));
+
+ const auto handle = check_idle_request_id();
+ // WA for "Error: Invalid argument" when Napi::Object is undefined.
+ auto user_data =
+ info.Length() > 1 ? info[1].ToObject() : Napi::String::New(info.Env(), UNDEFINED_USER_DATA).ToObject();
+ Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(info.Env());
+ if (handle == -1) {
+ std::lock_guard<std::mutex> lock(m_mutex);
+ m_awaiting_requests.push(
+ std::make_tuple(Napi::Persistent(info[0].ToObject()), Napi::Persistent(user_data), deferred));
+ } else {
+ start_async_impl(handle, info[0].ToObject(), user_data, deferred);
+ }
+ return deferred.Promise();
+
+ } catch (std::exception& err) {
+ reportError(info.Env(), err.what());
+ return info.Env().Undefined();
+ }
+}
diff --git a/src/bindings/js/node/src/compiled_model.cpp b/src/bindings/js/node/src/compiled_model.cpp
index 15dcc635066..42cd093211d 100644
--- a/src/bindings/js/node/src/compiled_model.cpp
+++ b/src/bindings/js/node/src/compiled_model.cpp
@@ -42,6 +42,11 @@ void CompiledModelWrap::set_compiled_model(const ov::CompiledModel& compiled_mod
_compiled_model = compiled_model;
}
+ov::CompiledModel& CompiledModelWrap::get_compiled_model() {
+ OPENVINO_ASSERT(_compiled_model, "CompiledModelWrap::get_compiled_model() failed.");
+ return _compiled_model;
+}
+
Napi::Value CompiledModelWrap::create_infer_request(const Napi::CallbackInfo& info) {
ov::InferRequest infer_request = _compiled_model.create_infer_request();
return InferRequestWrap::wrap(info.Env(), infer_request);
diff --git a/src/bindings/js/node/src/helper.cpp b/src/bindings/js/node/src/helper.cpp
index f9dd8bbf283..5a3a085230b 100644
--- a/src/bindings/js/node/src/helper.cpp
+++ b/src/bindings/js/node/src/helper.cpp
@@ -591,3 +591,19 @@ std::string buffer_to_string(const Napi::Value& value) {
return std::string(reinterpret_cast<char*>(model_data.Data()), model_data.Length());
}
+
+uint32_t get_optimal_number_of_requests(const ov::CompiledModel& actual) {
+ try {
+ const auto supported_properties = actual.get_property(ov::supported_properties);
+ const auto has_optimal_num_of_requests =
+ std::find(supported_properties.begin(), supported_properties.end(), ov::optimal_number_of_infer_requests) !=
+ supported_properties.end();
+ OPENVINO_ASSERT(has_optimal_num_of_requests,
+ "Can't load network: ",
+ ov::optimal_number_of_infer_requests.name(),
+ " is not supported! Please specify number of infer requests directly!");
+ return actual.get_property(ov::optimal_number_of_infer_requests);
+ } catch (const std::exception& ex) {
+ OPENVINO_THROW("Can't load network: ", ex.what(), ". Please specify number of infer requests directly!");
+ }
+}
diff --git a/src/bindings/js/node/src/infer_request.cpp b/src/bindings/js/node/src/infer_request.cpp
index 0b5629adac6..80c5f53fd28 100644
--- a/src/bindings/js/node/src/infer_request.cpp
+++ b/src/bindings/js/node/src/infer_request.cpp
@@ -41,7 +41,6 @@ void InferRequestWrap::set_infer_request(const ov::InferRequest& infer_request)
}
Napi::Object InferRequestWrap::wrap(Napi::Env env, ov::InferRequest infer_request) {
- Napi::HandleScope scope(env);
const auto& prototype = env.GetInstanceData<AddonData>()->infer_request;
if (!prototype) {
OPENVINO_THROW("Invalid pointer to InferRequest prototype.");
diff --git a/src/bindings/js/node/src/type_validation.cpp b/src/bindings/js/node/src/type_validation.cpp
index 65a92771f8d..76a9e8f272c 100644
--- a/src/bindings/js/node/src/type_validation.cpp
+++ b/src/bindings/js/node/src/type_validation.cpp
@@ -22,10 +22,12 @@ static const char UNKNOWN_STR[] = "unknown";
namespace BindingTypename {
static const char INT[] = "Integer";
static const char MODEL[] = "Model";
+static const char COMPILED_MODEL[] = "CompiledModel";
static const char TENSOR[] = "Tensor";
static const char OUTPUT[] = "Output<ov::Node>";
static const char PARTIALSHAPE[] = "PartialShape";
static const char BUFFER[] = "Buffer";
+static const char VALUE[] = "value";
} // namespace BindingTypename
namespace NapiArg {
const char* get_type_name(napi_valuetype type) {
@@ -77,6 +79,11 @@ std::string get_current_signature(const Napi::CallbackInfo& info) {
return std::string("(" + ov::util::join(signature_attributes) + ")");
};
+template <>
+const char* get_attr_type<Napi::Value>() {
+ return BindingTypename::VALUE;
+}
+
template <>
const char* get_attr_type<Napi::String>() {
return NapiArg::get_type_name(napi_string);
@@ -92,6 +99,11 @@ const char* get_attr_type<Napi::Boolean>() {
return NapiArg::get_type_name(napi_boolean);
}
+template <>
+const char* get_attr_type<Napi::Function>() {
+ return NapiArg::get_type_name(napi_function);
+}
+
template <>
const char* get_attr_type<Napi::Buffer<uint8_t>>() {
return BindingTypename::BUFFER;
@@ -106,6 +118,10 @@ template <>
const char* get_attr_type<ModelWrap>() {
return BindingTypename::MODEL;
}
+template <>
+const char* get_attr_type<CompiledModelWrap>() {
+ return BindingTypename::COMPILED_MODEL;
+}
template <>
const char* get_attr_type<TensorWrap>() {
@@ -122,6 +138,11 @@ const char* get_attr_type<PartialShapeWrap>() {
return BindingTypename::PARTIALSHAPE;
}
+template <>
+bool validate_value<Napi::Value>(const Napi::Env& env, const Napi::Value& value) {
+ return true;
+}
+
template <>
bool validate_value<Napi::String>(const Napi::Env& env, const Napi::Value& value) {
return napi_string == value.Type();
@@ -137,6 +158,11 @@ bool validate_value<Napi::Boolean>(const Napi::Env& env, const Napi::Value& valu
return napi_boolean == value.Type();
}
+template <>
+bool validate_value<Napi::Function>(const Napi::Env& env, const Napi::Value& value) {
+ return napi_function == value.Type();
+}
+
template <>
bool validate_value<Napi::Buffer<uint8_t>>(const Napi::Env& env, const Napi::Value& value) {
return value.IsBuffer();
@@ -161,6 +187,13 @@ bool validate_value<ModelWrap>(const Napi::Env& env, const Napi::Value& value) {
return value.ToObject().InstanceOf(prototype.Value().As<Napi::Function>());
}
+template <>
+bool validate_value<CompiledModelWrap>(const Napi::Env& env, const Napi::Value& value) {
+ const auto& prototype = env.GetInstanceData<AddonData>()->compiled_model;
+
+ return value.ToObject().InstanceOf(prototype.Value().As<Napi::Function>());
+}
+
template <>
bool validate_value<TensorWrap>(const Napi::Env& env, const Napi::Value& value) {
const auto& prototype = env.GetInstanceData<AddonData>()->tensor;
diff --git a/src/bindings/js/node/tests/unit/async_infer_queue.test.js b/src/bindings/js/node/tests/unit/async_infer_queue.test.js
new file mode 100644
index 00000000000..95130703221
--- /dev/null
+++ b/src/bindings/js/node/tests/unit/async_infer_queue.test.js
@@ -0,0 +1,220 @@
+// -*- coding: utf-8 -*-
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+const assert = require("assert");
+const { addon: ov } = require("../..");
+const { describe, it, before } = require("node:test");
+const { testModels, generateImage } = require("../utils.js");
+
+describe("Tests for AsyncInferQueue.", () => {
+ const jobs = 8;
+ const numRequest = 4;
+ let core = null;
+ let compiledModel = null;
+ const { reluModel } = testModels;
+
+ before(async () => {
+ core = new ov.Core();
+ const model = await core.readModel(reluModel.xml);
+ compiledModel = core.compileModelSync(model, "CPU");
+ });
+
+ function basicUserCallback(err, request, jobId) {
+ if (err) {
+ console.error(`Job ${jobId} failed: ${err}`);
+ } else {
+ assert.strictEqual(request instanceof ov.InferRequest, true);
+ }
+ }
+
+ it("Test AsyncInferQueue constructor with invalid arguments", async () => {
+ assert.throws(() => {
+ new ov.AsyncInferQueue(); // No arguments
+ }, /'AsyncInferQueue' constructor method called with incorrect parameters./);
+
+ assert.throws(() => {
+ // Invalid numRequest type
+ new ov.AsyncInferQueue(compiledModel, "invalid");
+ }, /'AsyncInferQueue' constructor method called with incorrect parameters./);
+ });
+
+ it("Test AsyncInferQueue constructor with default ctor", () => {
+ assert.doesNotThrow(() => {
+ new ov.AsyncInferQueue(compiledModel);
+ });
+ });
+
+ it("Test main event loop non-blocking inference", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+ const jobsDone = Array.from({ length: jobs }, () => ({ finished: false }));
+
+ function callback(err, request, jobId) {
+ if (err) {
+ console.error(`Job ${jobId} failed: ${err}`);
+ } else {
+ jobsDone[jobId].finished = true;
+ assert.ok(request instanceof ov.InferRequest);
+ }
+ }
+
+ inferQueue.setCallback(callback);
+
+ for (let i = 0; i < jobs; i++) {
+ const img = generateImage();
+ // Start the inference request in non-blocking mode.
+ // The results will be available in the callback function.
+ await inferQueue.startAsync({ data: img }, i);
+ }
+
+ assert.strictEqual(jobsDone.filter((job) => job.finished).length, jobs);
+ inferQueue.release();
+ });
+
+ it("Test startAsync fails without callback", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+
+ const img = generateImage();
+ await assert.rejects(async () => {
+ await inferQueue.startAsync({ data: img }, "user_data");
+ }, /Callback has to be set before starting inference./);
+ });
+
+ it("Test startAsync without user data", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+ function basicUserCallback(err, request, userData) {
+ if (err) {
+ console.error(`Job failed: ${err}`);
+ } else {
+ assert.ok(request instanceof ov.InferRequest);
+ assert.strictEqual(userData, undefined);
+ }
+ }
+ inferQueue.setCallback(basicUserCallback);
+ await inferQueue.startAsync({ data: generateImage() });
+ inferQueue.release();
+ });
+
+ it("test Promise.all()", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+ const jobsDone = Array.from({ length: jobs }, () => ({ finished: false }));
+
+ function callback(err, request, jobId) {
+ if (err) {
+ console.error(`Job ${jobId} failed: ${err}`);
+ } else {
+ jobsDone[jobId].finished = true;
+ const inferenceResult = request.getOutputTensor().data;
+ const inputAt0 = jobId * (jobId % 2 === 0 ? 1 : -1);
+ const resultAt0 = inputAt0 > 0 ? inputAt0 : 0; // relu function
+ assert.strictEqual(inferenceResult[0], resultAt0);
+ const input = request.getInputTensor().data;
+ assert.strictEqual(input[0], inputAt0);
+ }
+ }
+
+ inferQueue.setCallback(callback);
+
+ const promises = [];
+ for (let i = 0; i < jobs; i++) {
+ const img = generateImage();
+ img[0] = i * (i % 2 === 0 ? 1 : -1);
+ const promise = inferQueue.startAsync({ data: img }, i);
+ promises.push(promise);
+ }
+
+ await Promise.all(promises);
+ assert.strictEqual(jobsDone.filter((job) => job.finished).length, jobs);
+ inferQueue.release();
+ });
+
+ it("Test AsyncInferQueue no freeze", async () => {
+ try {
+ new ov.AsyncInferQueue(compiledModel, numRequest);
+ } catch (err) {
+ assert.fail(`Unexpected error thrown: ${err.message}`);
+ }
+ });
+
+ it("Test double set_callback", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+ inferQueue.setCallback(() => {});
+ inferQueue.setCallback(() => {});
+ inferQueue.release();
+ });
+
+ it("Test repeated AsyncInferQueue.release()", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+ inferQueue.setCallback(basicUserCallback);
+ inferQueue.release();
+ assert.doesNotThrow(() => {
+ inferQueue.release();
+ }, "Release should do nothing on second call.");
+ });
+
+ it("Test call startAsync after release()", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+ inferQueue.setCallback(basicUserCallback);
+ inferQueue.release();
+ await assert.rejects(async () => {
+ await inferQueue.startAsync({ data: generateImage() }, "user_data");
+ }, /Callback has to be set before starting inference./);
+ });
+
+ it("Test setCallback throws and list possible signatures", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+ assert.throws(() => {
+ inferQueue.setCallback();
+ }, /'setCallback' method called with incorrect parameters./);
+ inferQueue.release();
+ });
+
+ it("Test startAsync throws and list possible signatures", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+ inferQueue.setCallback(basicUserCallback);
+ assert.throws(() => {
+ inferQueue.startAsync({ data: generateImage() }, "user_data", "extra_param");
+ }, /'startAsync' method called with incorrect parameters./);
+ inferQueue.release();
+ });
+
+ it("Test possibility to catch error in callback", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+
+ function callback(err, request, jobId) {
+ if (err) {
+ console.error(`Job ${jobId} failed: ${err}`);
+ } else {
+ assert.ok(request instanceof ov.InferRequest);
+ assert.throws(() => {
+ // eslint-disable-next-line no-undef
+ jobsDone[jobId].finished = true;
+ }, /ReferenceError: jobsDone is not defined/);
+ }
+ }
+ inferQueue.setCallback(callback);
+ await inferQueue.startAsync({ data: generateImage() }, "data");
+ inferQueue.release();
+ });
+
+ it("Test error in callback and rejected promise", async () => {
+ const inferQueue = new ov.AsyncInferQueue(compiledModel, numRequest);
+
+ function callback(err, request, jobId) {
+ if (err) {
+ console.error(`Job ${jobId} failed: ${err}`);
+ } else {
+ assert.ok(request instanceof ov.InferRequest);
+ // eslint-disable-next-line no-undef
+ jobsDone[jobId].finished = true; // throws ReferenceError
+ }
+ }
+
+ inferQueue.setCallback(callback);
+ await inferQueue.startAsync({ data: generateImage() }, "data").catch((err) => {
+ assert(err instanceof Error);
+ assert.strictEqual(err.message, "jobsDone is not defined");
+ });
+ inferQueue.release();
+ });
+});
diff --git a/src/bindings/js/node/tests/unit/test_models/relu_model.xml b/src/bindings/js/node/tests/unit/test_models/relu_model.xml
new file mode 100644
index 00000000000..c0132b9fe61
--- /dev/null
+++ b/src/bindings/js/node/tests/unit/test_models/relu_model.xml
@@ -0,0 +1,49 @@
+<?xml version="1.0"?>
+<net name="test_model" version="11">
+ <layers>
+ <layer id="0" name="data" type="Parameter" version="opset1">
+ <data shape="1,3,32,32" element_type="f32" />
+ <output>
+ <port id="0" precision="FP32" names="data">
+ <dim>1</dim>
+ <dim>3</dim>
+ <dim>32</dim>
+ <dim>32</dim>
+ </port>
+ </output>
+ </layer>
+ <layer id="1" name="relu" type="ReLU" version="opset1">
+ <input>
+ <port id="0" precision="FP32">
+ <dim>1</dim>
+ <dim>3</dim>
+ <dim>32</dim>
+ <dim>32</dim>
+ </port>
+ </input>
+ <output>
+ <port id="1" precision="FP32">
+ <dim>1</dim>
+ <dim>3</dim>
+ <dim>32</dim>
+ <dim>32</dim>
+ </port>
+ </output>
+ </layer>
+ <layer id="2" name="Result_3" type="Result" version="opset1">
+ <input>
+ <port id="0" precision="FP32">
+ <dim>1</dim>
+ <dim>3</dim>
+ <dim>32</dim>
+ <dim>32</dim>
+ </port>
+ </input>
+ </layer>
+ </layers>
+ <edges>
+ <edge from-layer="0" from-port="0" to-layer="1" to-port="0" />
+ <edge from-layer="1" from-port="1" to-layer="2" to-port="0" />
+ </edges>
+ <rt_info />
+</net>
diff --git a/src/bindings/js/node/tests/utils.js b/src/bindings/js/node/tests/utils.js
index a5b49588073..ff5545f159e 100644
--- a/src/bindings/js/node/tests/utils.js
+++ b/src/bindings/js/node/tests/utils.js
@@ -39,6 +39,9 @@ const testModels = {
addModelWithVar: {
xml: getModelPath("add_model_with_var.xml"),
},
+ reluModel: {
+ xml: getModelPath("relu_model.xml"),
+ },
};
module.exports = {