OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[JS API] Catch C++ error in js api async compile_model (#34771)
Alicja Miloszewska83b67f86fa5f
diff --git a/src/bindings/js/node/include/core_wrap.hpp b/src/bindings/js/node/include/core_wrap.hppindex 851d5f8c85a..667ee99407e 100644--- a/src/bindings/js/node/include/core_wrap.hpp+++ b/src/bindings/js/node/include/core_wrap.hpp@@ -1,11 +1,13 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0+//#pragma once#include <napi.h>#include <thread>+#include <variant>#include "openvino/runtime/core.hpp"@@ -77,20 +79,11 @@ protected:const Napi::Object& model,const Napi::String& device);- Napi::Value compile_model_sync(const Napi::CallbackInfo& info,- const Napi::String& model_path,- const Napi::String& device);-Napi::Value compile_model_sync(const Napi::CallbackInfo& info,const Napi::Object& model,const Napi::String& device,const std::map<std::string, ov::Any>& config);- Napi::Value compile_model_sync(const Napi::CallbackInfo& info,- const Napi::String& model_path,- const Napi::String& device,- const std::map<std::string, ov::Any>& config);-/** @brief Imports a compiled model from the previously exported one. */Napi::Value import_model(const Napi::CallbackInfo& info);@@ -108,30 +101,28 @@ private:std::mutex _mutex;};-struct TsfnContextModel {- TsfnContextModel(Napi::Env env) : deferred(Napi::Promise::Deferred::New(env)) {};- std::thread nativeThread;+struct TsfnCompileModelContext {+ TsfnCompileModelContext(Napi::Env env, ov::Core& core,+ std::variant<std::shared_ptr<ov::Model>, std::filesystem::path> model,+ const std::string& device,+ ov::AnyMap config)+ : deferred(Napi::Promise::Deferred::New(env)),+ _core{core},+ _model(std::move(model)),+ _device(device),+ _config(std::move(config)) {};- Napi::Promise::Deferred deferred;- Napi::ThreadSafeFunction tsfn;-- std::shared_ptr<ov::Model> _model;- std::string _device;- ov::CompiledModel _compiled_model;- std::map<std::string, ov::Any> _config = {};-};--struct TsfnContextPath {- TsfnContextPath(Napi::Env env) : deferred(Napi::Promise::Deferred::New(env)) {};- std::thread nativeThread;+ std::thread native_thread;Napi::Promise::Deferred deferred;Napi::ThreadSafeFunction tsfn;-- std::filesystem::path _model;++ ov::Core& _core;+ std::variant<std::shared_ptr<ov::Model>, std::filesystem::path> _model;std::string _device;+ ov::AnyMap _config;+ov::CompiledModel _compiled_model;- std::map<std::string, ov::Any> _config = {};};struct ImportModelContext {@@ -148,7 +139,5 @@ struct ImportModelContext {ov::CompiledModel _compiled_model;};-void FinalizerCallbackModel(Napi::Env env, void* finalizeData, TsfnContextModel* context);-void FinalizerCallbackPath(Napi::Env env, void* finalizeData, TsfnContextPath* context);-void compileModelThreadModel(TsfnContextModel* context);-void compileModelThreadPath(TsfnContextPath* context);+void tsfn_finalizer_callback(Napi::Env env, void* finalize_data, TsfnCompileModelContext* context);+void compile_model_thread(TsfnCompileModelContext* context);diff --git a/src/bindings/js/node/src/compiled_model.cpp b/src/bindings/js/node/src/compiled_model.cppindex 4a345bdb876..9f356d99fe3 100644--- a/src/bindings/js/node/src/compiled_model.cpp+++ b/src/bindings/js/node/src/compiled_model.cpp@@ -30,9 +30,7 @@ Napi::Function CompiledModelWrap::get_class(Napi::Env env) {Napi::Object CompiledModelWrap::wrap(Napi::Env env, ov::CompiledModel compiled_model) {const auto& prototype = env.GetInstanceData<AddonData>()->compiled_model;- if (!prototype) {- OPENVINO_THROW("Invalid pointer to CompiledModel prototype.");- }+ OPENVINO_ASSERT(prototype, "Invalid pointer to CompiledModel prototype.");auto obj = prototype.New({});const auto cm = Napi::ObjectWrap<CompiledModelWrap>::Unwrap(obj);cm->_compiled_model = compiled_model;@@ -49,8 +47,12 @@ ov::CompiledModel& CompiledModelWrap::get_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);+ try {+ return InferRequestWrap::wrap(info.Env(), _compiled_model.create_infer_request());+ } catch (std::exception& e) {+ reportError(info.Env(), e.what());+ return info.Env().Undefined();+ }}Napi::Value CompiledModelWrap::get_output(const Napi::CallbackInfo& info) {diff --git a/src/bindings/js/node/src/core_wrap.cpp b/src/bindings/js/node/src/core_wrap.cppindex 65bed7f3e00..0bcc16b1447 100644--- a/src/bindings/js/node/src/core_wrap.cpp+++ b/src/bindings/js/node/src/core_wrap.cpp@@ -172,97 +172,78 @@ Napi::Value CoreWrap::compile_model_sync_dispatch(const Napi::CallbackInfo& info}}-void FinalizerCallbackModel(Napi::Env env, void* finalizeData, TsfnContextModel* context) {- context->nativeThread.join();- delete context;-};--void FinalizerCallbackPath(Napi::Env env, void* finalizeData, TsfnContextPath* context) {- context->nativeThread.join();+void tsfn_finalizer_callback(Napi::Env env, void* finalize_data, TsfnCompileModelContext* context) {+ context->native_thread.join();delete context;};-void compileModelThreadModel(TsfnContextModel* context) {- ov::Core core;- context->_compiled_model = core.compile_model(context->_model, context->_device, context->_config);-- auto callback = [](Napi::Env env, Napi::Function, TsfnContextModel* context) {- context->deferred.Resolve(CompiledModelWrap::wrap(env, context->_compiled_model));- };-- context->tsfn.BlockingCall(context, callback);- context->tsfn.Release();-}--void compileModelThreadPath(TsfnContextPath* context) {- ov::Core core;- context->_compiled_model = core.compile_model(context->_model, context->_device, context->_config);-- auto callback = [](Napi::Env env, Napi::Function, TsfnContextPath* context) {- context->deferred.Resolve(CompiledModelWrap::wrap(env, context->_compiled_model));+void compile_model_thread(TsfnCompileModelContext* context) {+ std::exception_ptr stored_exception;+ try {+ std::visit(+ [&context](auto&& model_variant) {+ context->_compiled_model =+ context->_core.compile_model(model_variant, context->_device, context->_config);+ },+ context->_model);+ } catch (...) {+ stored_exception = std::current_exception();+ }+ auto callback = [stored_exception](Napi::Env env, Napi::Function, TsfnCompileModelContext* context) {+ try {+ if (stored_exception) {+ std::rethrow_exception(stored_exception);+ }+ context->deferred.Resolve(CompiledModelWrap::wrap(env, context->_compiled_model));+ } catch (const std::exception& e) {+ context->deferred.Reject(Napi::Error::New(env, e.what()).Value());+ }};- context->tsfn.BlockingCall(context, callback);+ const auto status = context->tsfn.BlockingCall(context, callback);+ if (status != napi_ok) {+ std::cerr << "Error: ThreadSafeFunction::BlockingCall failed in compile_model_thread function\n";+ }context->tsfn.Release();}Napi::Value CoreWrap::compile_model_async(const Napi::CallbackInfo& info) {+ std::vector<std::string> allowed_signatures;auto env = info.Env();- if (info[0].IsObject() && info[1].IsString()) {- auto context_data = new TsfnContextModel(env);- auto m = Napi::ObjectWrap<ModelWrap>::Unwrap(info[0].ToObject());- context_data->_model = m->get_model()->clone();- context_data->_device = info[1].ToString();-- if (info.Length() == 3) {- try {- context_data->_config = js_to_cpp<std::map<std::string, ov::Any>>(info, 2);- } catch (std::exception& e) {- reportError(env, e.what());- }+ try {+ std::variant<std::shared_ptr<ov::Model>, std::filesystem::path> model_variant;+ if (ov::js::validate<ModelWrap, Napi::String>(info, allowed_signatures) ||+ ov::js::validate<ModelWrap, Napi::String, Napi::Object>(info, allowed_signatures)) {+ auto m = Napi::ObjectWrap<ModelWrap>::Unwrap(info[0].ToObject());+ model_variant = m->get_model()->clone();+ } else if (ov::js::validate<Napi::String, Napi::String>(info, allowed_signatures) ||+ ov::js::validate<Napi::String, Napi::String, Napi::Object>(info, allowed_signatures)) {+ model_variant = js_to_cpp<std::filesystem::path>(info, 0);+ } else {+ OPENVINO_THROW("'compileModel'", ov::js::get_parameters_error_msg(info, allowed_signatures));}+ const std::string device = info[1].ToString();+ auto config = info.Length() == 3 ? js_to_cpp<ov::AnyMap>(info, 2) : ov::AnyMap();+ std::unique_ptr<TsfnCompileModelContext> context_data(+ new TsfnCompileModelContext(env, _core, std::move(model_variant), device, std::move(config)));context_data->tsfn = Napi::ThreadSafeFunction::New(env,Napi::Function(),"TSFN",0,1,- context_data,- FinalizerCallbackModel,+ context_data.get(),+ tsfn_finalizer_callback,(void*)nullptr);- context_data->nativeThread = std::thread(compileModelThreadModel, context_data);- return context_data->deferred.Promise();- } else if (info[0].IsString() && info[1].IsString()) {- auto context_data = new TsfnContextPath(env);- context_data->_model = js_to_cpp<std::filesystem::path>(info, 0);- context_data->_device = info[1].ToString();-- if (info.Length() == 3) {- try {- context_data->_config = js_to_cpp<std::map<std::string, ov::Any>>(info, 2);- } catch (std::exception& e) {- reportError(env, e.what());- }- }-- context_data->tsfn = Napi::ThreadSafeFunction::New(env,- Napi::Function(),- "TSFN",- 0,- 1,- context_data,- FinalizerCallbackPath,- (void*)nullptr);+ context_data->native_thread = std::thread(compile_model_thread, context_data.get());+ const auto promise = context_data->deferred.Promise();+ context_data.release(); // ownership is transferred to the TSFN finalizer callback+ return promise;- context_data->nativeThread = std::thread(compileModelThreadPath, context_data);- return context_data->deferred.Promise();- } else if (info.Length() < 2 || info.Length() > 3) {- reportError(info.Env(), "Invalid number of arguments -> " + std::to_string(info.Length()));- return Napi::Value();- } else {- reportError(info.Env(), "Error while compiling model.");- return Napi::Value();+ } catch (std::exception& e) {+ reportError(env, e.what());+ return env.Undefined();}}diff --git a/src/bindings/js/node/tests/unit/basic.test.js b/src/bindings/js/node/tests/unit/basic.test.jsindex 4a263cf19a7..58858715da4 100644--- a/src/bindings/js/node/tests/unit/basic.test.js+++ b/src/bindings/js/node/tests/unit/basic.test.js@@ -16,8 +16,7 @@ const {generateImage,} = require("../utils.js");-// Tests are skipped until CVS-180810 is fixed.-describe("ov basic tests.", { skip: true }, () => {+describe("ov basic tests.", () => {const { testModelFP32 } = testModels;let core = null;let model = null;@@ -178,6 +177,13 @@ describe("ov basic tests.", { skip: true }, () => {assert.throws(() => core.compileModelSync(model), new RegExp(expectedMsg));});++ it("compileModelSync(invalid path to model) - C++ API error", () => {+ assert.throws(+ () => core.compileModelSync("invalid_path.xml", "CPU"),+ /Could not open the file/,+ );+ });});describe("Core.compileModel()", () => {@@ -193,6 +199,7 @@ describe("ov basic tests.", { skip: true }, () => {assert.ok(promise instanceof Promise);const cm = await promise;assert.ok(cm instanceof ov.CompiledModel);+ assert.ok(cm.createInferRequest());});it("compileModel(model_path) returns Promise<CompiledModel>", async () => {@@ -200,6 +207,7 @@ describe("ov basic tests.", { skip: true }, () => {assert.ok(promise instanceof Promise);const cm = await promise;assert.ok(cm instanceof ov.CompiledModel);+ assert.ok(cm.createInferRequest());});it("compileModel(model_path, deviceName, config: {}) ", async () => {@@ -215,7 +223,7 @@ describe("ov basic tests.", { skip: true }, () => {it("compileModel(model, device, invalidconfig) throws", async () => {await assert.rejects(async () => await core.compileModel(model, "CPU", "string"),- /Argument #\d+ must be an Object./,+ /'compileModel' method called with incorrect parameters/,);});@@ -229,7 +237,21 @@ describe("ov basic tests.", { skip: true }, () => {it("compileModel(model) throws with invalid number of args", async () => {await assert.rejects(async () => await core.compileModel(model),- /Invalid number of arguments/,+ /'compileModel' method called with incorrect parameters/,+ );+ });++ it("compileModel(invalid device) - C++ API error", async () => {+ await assert.rejects(+ async () => await core.compileModel(model, "DEVICE"),+ /Device .* is not registered/,+ );+ });++ it("compileModel(invalid path to model) - C++ API error", async () => {+ await assert.rejects(+ async () => await core.compileModel("invalid_path.xml", "CPU"),+ /Could not open the file/,);});});@@ -283,7 +305,8 @@ describe("ov basic tests.", { skip: true }, () => {});});- describe("Test exportModel()/importModel()", () => {+ // Tests are skipped until CVS-180810 is fixed.+ describe("Test exportModel()/importModel()", { skip: true }, () => {let tensor = null;let userStream = null;let res1 = null;