@coherentglobal/spark-execute-sdk 0.4.9 → 0.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -7157,14 +7157,26 @@ var _require = require("@coherentglobal/wasm-runner"),
7157
7157
  var validate = require("./validate.js");
7158
7158
  var processModels = require("./models.js");
7159
7159
  var findModel = require("./findModels.js");
7160
- var registry = {};
7161
7160
  var Spark = /*#__PURE__*/function () {
7162
7161
  /**
7163
7162
  * @param {object} config
7164
7163
  */
7165
7164
  function Spark(config) {
7166
7165
  var _this$config$sparkEnd, _this$config, _this$config$sparkEnd2, _this$config$sparkEnd3, _this$config2, _this$config2$sparkEn, _ref, _this$config$sparkEnd4, _this$config3, _this$config3$sparkEn, _this$config4, _this$config4$sparkEn, _this$config$sparkEnd5, _this$config5, _this$config5$sparkEn, _this$config6;
7166
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
7167
7167
  (0, _classCallCheck2["default"])(this, Spark);
7168
+ /**
7169
+ * @private
7170
+ */
7171
+ this._registry = undefined;
7172
+
7173
+ /**
7174
+ * @private
7175
+ */
7176
+ if (options !== null && options !== void 0 && options.log) {
7177
+ this.logger = options.log;
7178
+ }
7179
+
7168
7180
  /**
7169
7181
  * @private
7170
7182
  */
@@ -7190,25 +7202,51 @@ var Spark = /*#__PURE__*/function () {
7190
7202
  * @private
7191
7203
  */
7192
7204
  this.isCompatible = utils.isWasmSupported();
7193
- /**
7194
- * @private
7195
- */
7196
- this.model = this._models((_this$config6 = this.config) === null || _this$config6 === void 0 ? void 0 : _this$config6.nodeGenModels);
7205
+
7197
7206
  /**
7198
7207
  * @private
7199
7208
  */
7200
7209
  this.priority = ["model", "onlineEndpoint"];
7201
- }
7202
7210
 
7203
- /**
7204
- *
7205
- * @param {object} nodegen
7206
- * @returns {object}
7207
- */
7211
+ /**
7212
+ * @private
7213
+ */
7214
+ this.model = this._models((_this$config6 = this.config) === null || _this$config6 === void 0 ? void 0 : _this$config6.nodeGenModels);
7215
+ }
7208
7216
  (0, _createClass2["default"])(Spark, [{
7217
+ key: "log",
7218
+ value: function log(msg) {
7219
+ this.logger && this.logger(msg);
7220
+ }
7221
+
7222
+ /**
7223
+ *
7224
+ * @param {object} nodegen
7225
+ * @returns {object}
7226
+ */
7227
+ }, {
7209
7228
  key: "_models",
7210
7229
  value: function _models(nodegen) {
7211
- var models = nodegen.map(processModels);
7230
+ this.log({
7231
+ eventType: "spark._models",
7232
+ msg: 'Parse models'
7233
+ });
7234
+ var models = [];
7235
+ for (var i = 0; i < nodegen.length; i++) {
7236
+ var startDate = Date.now();
7237
+ this.log({
7238
+ eventType: "spark._models.processModels.start",
7239
+ msg: "Start process model ".concat(i)
7240
+ });
7241
+ var model = processModels(nodegen[i], i, this.log.bind(this));
7242
+ var endDate = Date.now();
7243
+ this.log({
7244
+ eventType: "spark._models.processModels.end",
7245
+ msg: "End process model ".concat(i),
7246
+ duration: endDate - startDate
7247
+ });
7248
+ models.push(model);
7249
+ }
7212
7250
  return models;
7213
7251
  }
7214
7252
  /**
@@ -7219,13 +7257,27 @@ var Spark = /*#__PURE__*/function () {
7219
7257
  }, {
7220
7258
  key: "validateConfig",
7221
7259
  value: function validateConfig(config) {
7260
+ var start = Date.now();
7261
+ this.log({
7262
+ eventType: 'spark.validateconfig.start'
7263
+ });
7222
7264
  var _validate = validate(config),
7223
7265
  value = _validate.value,
7224
7266
  error = _validate.error;
7225
7267
  if (!error) {
7268
+ var end = Date.now();
7269
+ this.log({
7270
+ eventType: 'spark.validateconfig.startend',
7271
+ duration: end - start
7272
+ });
7226
7273
  return value;
7227
7274
  } else {
7228
7275
  var message = JSON.stringify(error.details);
7276
+ var _end = Date.now();
7277
+ this.log({
7278
+ eventType: 'spark.validateconfig.startend.error',
7279
+ duration: _end - start
7280
+ });
7229
7281
  throw new Error("ValidationError: ".concat(message));
7230
7282
  }
7231
7283
  }
@@ -7271,26 +7323,32 @@ var Spark = /*#__PURE__*/function () {
7271
7323
  while (1) {
7272
7324
  switch (_context.prev = _context.next) {
7273
7325
  case 0:
7326
+ if (!(this.model == undefined)) {
7327
+ _context.next = 2;
7328
+ break;
7329
+ }
7330
+ throw new WasmRunnerErrors.BadRequestError('Spark initialize is required. Please call initialize method');
7331
+ case 2:
7274
7332
  versionID = version_id || (input === null || input === void 0 ? void 0 : (_input$request_meta = input.request_meta) === null || _input$request_meta === void 0 ? void 0 : _input$request_meta.version_id) || (input === null || input === void 0 ? void 0 : (_input$request_meta2 = input.request_meta) === null || _input$request_meta2 === void 0 ? void 0 : _input$request_meta2.version_uuid);
7275
7333
  lookup = {
7276
- model: this.offlineModel,
7277
- onlineEndpoint: this.onlineModelEndpoint
7334
+ model: this.offlineModel.bind(this),
7335
+ onlineEndpoint: this.onlineModelEndpoint.bind(this)
7278
7336
  };
7279
- _context.next = 4;
7337
+ _context.next = 6;
7280
7338
  return lookup[this.priority[0]](input, versionID, this);
7281
- case 4:
7339
+ case 6:
7282
7340
  response = _context.sent;
7283
7341
  if (!(response instanceof Error && this.config.sparkEndpoint !== undefined)) {
7284
- _context.next = 9;
7342
+ _context.next = 11;
7285
7343
  break;
7286
7344
  }
7287
- _context.next = 8;
7345
+ _context.next = 10;
7288
7346
  return lookup[this.priority[1]](input, versionID, this);
7289
- case 8:
7347
+ case 10:
7290
7348
  response = _context.sent;
7291
- case 9:
7349
+ case 11:
7292
7350
  return _context.abrupt("return", response);
7293
- case 10:
7351
+ case 12:
7294
7352
  case "end":
7295
7353
  return _context.stop();
7296
7354
  }
@@ -7305,13 +7363,14 @@ var Spark = /*#__PURE__*/function () {
7305
7363
  }, {
7306
7364
  key: "offlineModel",
7307
7365
  value: function () {
7308
- var _offlineModel = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(input, versionID, ds) {
7366
+ var _offlineModel = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(input, versionID) {
7367
+ var _this = this;
7309
7368
  var model, modelVersionId, callback, _model2$metaData$Engi, _model2$metaData, _model2$metaData$Engi2, _model2$metaData$Engi3, _model2$metaData2, _model2$metaData2$Eng, _model2, result;
7310
7369
  return _regenerator["default"].wrap(function _callee3$(_context3) {
7311
7370
  while (1) {
7312
7371
  switch (_context3.prev = _context3.next) {
7313
7372
  case 0:
7314
- model = findModel(input.request_meta, ds.model);
7373
+ model = findModel(input.request_meta, this.model);
7315
7374
  modelVersionId = versionID || model && (model === null || model === void 0 ? void 0 : model.versionId);
7316
7375
  if (!(input !== null && input !== void 0 && input.request_meta)) {
7317
7376
  input.request_meta = {};
@@ -7320,7 +7379,7 @@ var Spark = /*#__PURE__*/function () {
7320
7379
  input.request_meta.version_id = modelVersionId;
7321
7380
  }
7322
7381
  _context3.prev = 4;
7323
- if (!(registry instanceof WasmRunner)) {
7382
+ if (this._registry === undefined) {
7324
7383
  /**
7325
7384
  * Options is the request data the the runner dispatch
7326
7385
  * receives from the wasm model
@@ -7337,12 +7396,12 @@ var Spark = /*#__PURE__*/function () {
7337
7396
  hasFolderName = options === null || options === void 0 ? void 0 : options.folder_name;
7338
7397
  hasServiceName = options === null || options === void 0 ? void 0 : options.service_name;
7339
7398
  hasVersionId = options === null || options === void 0 ? void 0 : options.version_id;
7340
- if (!(hasVersionId && !registry.isExist(hasVersionId))) {
7399
+ if (!(hasVersionId && !_this._registry.isExist(hasVersionId))) {
7341
7400
  _context2.next = 8;
7342
7401
  break;
7343
7402
  }
7344
7403
  _context2.next = 6;
7345
- return registry.append({
7404
+ return _this._registry.append({
7346
7405
  id: hasVersionId,
7347
7406
  url: model.binary,
7348
7407
  meta: {
@@ -7354,10 +7413,10 @@ var Spark = /*#__PURE__*/function () {
7354
7413
  _context2.next = 12;
7355
7414
  break;
7356
7415
  case 8:
7357
- _model = ds._getModelByMeta(hasFolderName, hasServiceName);
7416
+ _model = _this._getModelByMeta(hasFolderName, hasServiceName);
7358
7417
  hasVersionId = _model === null || _model === void 0 ? void 0 : _model.versionId;
7359
7418
  _context2.next = 12;
7360
- return registry.append({
7419
+ return _this._registry.append({
7361
7420
  id: hasVersionId,
7362
7421
  url: _model.binary,
7363
7422
  meta: {
@@ -7374,19 +7433,19 @@ var Spark = /*#__PURE__*/function () {
7374
7433
  }
7375
7434
  }, _callee2);
7376
7435
  }));
7377
- return function callback(_x6) {
7436
+ return function callback(_x5) {
7378
7437
  return _ref2.apply(this, arguments);
7379
7438
  };
7380
7439
  }();
7381
- registry = new WasmRunner("", callback);
7440
+ this._registry = new WasmRunner("", callback);
7382
7441
  }
7383
- if (registry.isExist(modelVersionId)) {
7442
+ if (this._registry.isExist(modelVersionId)) {
7384
7443
  _context3.next = 10;
7385
7444
  break;
7386
7445
  }
7387
- _model2 = findModel(input.request_meta, ds.model);
7446
+ _model2 = findModel(input.request_meta, this.model);
7388
7447
  _context3.next = 10;
7389
- return registry.append({
7448
+ return this._registry.append({
7390
7449
  id: modelVersionId,
7391
7450
  url: _model2.binary,
7392
7451
  meta: {
@@ -7396,7 +7455,7 @@ var Spark = /*#__PURE__*/function () {
7396
7455
  });
7397
7456
  case 10:
7398
7457
  _context3.next = 12;
7399
- return registry.execute(input, modelVersionId, function () {});
7458
+ return this._registry.execute(input, modelVersionId, function () {});
7400
7459
  case 12:
7401
7460
  result = _context3.sent;
7402
7461
  return _context3.abrupt("return", result);
@@ -7409,9 +7468,9 @@ var Spark = /*#__PURE__*/function () {
7409
7468
  return _context3.stop();
7410
7469
  }
7411
7470
  }
7412
- }, _callee3, null, [[4, 16]]);
7471
+ }, _callee3, this, [[4, 16]]);
7413
7472
  }));
7414
- function offlineModel(_x3, _x4, _x5) {
7473
+ function offlineModel(_x3, _x4) {
7415
7474
  return _offlineModel.apply(this, arguments);
7416
7475
  }
7417
7476
  return offlineModel;
@@ -7419,43 +7478,43 @@ var Spark = /*#__PURE__*/function () {
7419
7478
  }, {
7420
7479
  key: "onlineModelEndpoint",
7421
7480
  value: function () {
7422
- var _onlineModelEndpoint = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(input, versionID, ds) {
7481
+ var _onlineModelEndpoint = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(input, versionID) {
7423
7482
  var isPublic, token, header, options, modelUrl, response, result;
7424
7483
  return _regenerator["default"].wrap(function _callee4$(_context4) {
7425
7484
  while (1) {
7426
7485
  switch (_context4.prev = _context4.next) {
7427
7486
  case 0:
7428
- isPublic = ds.authType === "public";
7487
+ isPublic = this.authType === "public";
7429
7488
  token = "";
7430
7489
  if (isPublic) {
7431
7490
  _context4.next = 12;
7432
7491
  break;
7433
7492
  }
7434
- if (!(ds.token.constructor.name === "AsyncFunction")) {
7493
+ if (!(this.token.constructor.name === "AsyncFunction")) {
7435
7494
  _context4.next = 9;
7436
7495
  break;
7437
7496
  }
7438
7497
  _context4.next = 6;
7439
- return ds.token();
7498
+ return this.token();
7440
7499
  case 6:
7441
7500
  token = _context4.sent;
7442
7501
  _context4.next = 10;
7443
7502
  break;
7444
7503
  case 9:
7445
- if (typeof ds.token === "function") {
7446
- token = ds.token();
7504
+ if (typeof this.token === "function") {
7505
+ token = this.token();
7447
7506
  } else {
7448
- token = ds.token;
7507
+ token = this.token;
7449
7508
  }
7450
7509
  case 10:
7451
- if (!utils.isEmpty(ds.token)) {
7510
+ if (!utils.isEmpty(this.token)) {
7452
7511
  _context4.next = 12;
7453
7512
  break;
7454
7513
  }
7455
7514
  throw new WasmRunnerErrors.UnauthorizedError();
7456
7515
  case 12:
7457
7516
  _context4.prev = 12;
7458
- header = !isPublic ? utils.getAuthHeaders(token, ds.authType, ds.tenant) : {};
7517
+ header = !isPublic ? utils.getAuthHeaders(token, this.authType, this.tenant) : {};
7459
7518
  options = {
7460
7519
  method: "POST",
7461
7520
  body: JSON.stringify({
@@ -7466,7 +7525,7 @@ var Spark = /*#__PURE__*/function () {
7466
7525
  "content-type": "application/json"
7467
7526
  }), header)
7468
7527
  };
7469
- modelUrl = new URL("/".concat(ds.tenant, "/api/v3/").concat(!isPublic ? "execute" : "public"), ds.url);
7528
+ modelUrl = new URL("/".concat(this.tenant, "/api/v3/").concat(!isPublic ? "execute" : "public"), this.url);
7470
7529
  _context4.next = 18;
7471
7530
  return fetch(modelUrl, options);
7472
7531
  case 18:
@@ -7485,9 +7544,9 @@ var Spark = /*#__PURE__*/function () {
7485
7544
  return _context4.stop();
7486
7545
  }
7487
7546
  }
7488
- }, _callee4, null, [[12, 25]]);
7547
+ }, _callee4, this, [[12, 25]]);
7489
7548
  }));
7490
- function onlineModelEndpoint(_x7, _x8, _x9) {
7549
+ function onlineModelEndpoint(_x6, _x7) {
7491
7550
  return _onlineModelEndpoint.apply(this, arguments);
7492
7551
  }
7493
7552
  return onlineModelEndpoint;
@@ -7667,14 +7726,29 @@ var findModel = function findModel(requestMeta, nodegenModels) {
7667
7726
  }));
7668
7727
  }).reverse();
7669
7728
  }
7670
- } else if (requestMeta.service_id && requestMeta.version) {
7729
+ } else if (requestMeta.servicename) {
7730
+ var transactionDate = new Date();
7671
7731
  model = nodegenModels.filter(function (_ref4) {
7672
7732
  var metaData = _ref4.metaData;
7673
- return metaData.EngineInformation.ServiceGuid === requestMeta.service_id && metaData.EngineInformation.Revision === requestMeta.version;
7733
+ return metaData.EngineInformation.ServiceName === requestMeta.servicename && transactionDate >= new Date(metaData.EffectiveStartDate) && transactionDate <= new Date(metaData.EffectiveEndDate);
7674
7734
  });
7675
- } else if (requestMeta.service_id && requestMeta.transaction_date) {
7735
+ if (model.length > 1) {
7736
+ return model.sort(function (versionA, versionB) {
7737
+ return versionA.metaData.EngineInformation.Revision.replace(/\d+/g, function (n) {
7738
+ return +n + 100000;
7739
+ }).localCompare(versionB.metaData.EngineInformation.Revision.replace(/\d+/g, function (n) {
7740
+ return +n + 100000;
7741
+ }));
7742
+ }).reverse();
7743
+ }
7744
+ } else if (requestMeta.service_id && requestMeta.version) {
7676
7745
  model = nodegenModels.filter(function (_ref5) {
7677
7746
  var metaData = _ref5.metaData;
7747
+ return metaData.EngineInformation.ServiceGuid === requestMeta.service_id && metaData.EngineInformation.Revision === requestMeta.version;
7748
+ });
7749
+ } else if (requestMeta.service_id && requestMeta.transaction_date) {
7750
+ model = nodegenModels.filter(function (_ref6) {
7751
+ var metaData = _ref6.metaData;
7678
7752
  return metaData.EngineInformation.ServiceGuid === requestMeta.service_id && new Date(requestMeta.transaction_date) >= new Date(metaData.EffectiveStartDate) && new Date(requestMeta.transaction_date) <= new Date(metaData.EffectiveEndDate);
7679
7753
  });
7680
7754
  if (model.length > 1) {
@@ -7686,6 +7760,21 @@ var findModel = function findModel(requestMeta, nodegenModels) {
7686
7760
  }));
7687
7761
  }).reverse();
7688
7762
  }
7763
+ } else if (requestMeta.service_id) {
7764
+ var _transactionDate = new Date();
7765
+ model = nodegenModels.filter(function (_ref7) {
7766
+ var metaData = _ref7.metaData;
7767
+ return metaData.EngineInformation.ServiceGuid === requestMeta.service_id && _transactionDate >= new Date(metaData.EffectiveStartDate) && _transactionDate <= new Date(metaData.EffectiveEndDate);
7768
+ });
7769
+ if (model.length > 1) {
7770
+ return model.sort(function (versionA, versionB) {
7771
+ return versionA.metaData.EngineInformation.Revision.replace(/\d+/g, function (n) {
7772
+ return +n + 100000;
7773
+ }).localCompare(versionB.metaData.EngineInformation.Revision.replace(/\d+/g, function (n) {
7774
+ return +n + 100000;
7775
+ }));
7776
+ }).reverse();
7777
+ }
7689
7778
  } else if (requestMeta.service_uri && requestMeta.transaction_date) {
7690
7779
  var regex = /folders\/(.+)\/services\/(.+)/gi;
7691
7780
  var parts = regex.exec(requestMeta.service_uri);
@@ -7694,8 +7783,8 @@ var findModel = function findModel(requestMeta, nodegenModels) {
7694
7783
  folder = decodeURI(parts[1]);
7695
7784
  service = decodeURI(parts[2]);
7696
7785
  }
7697
- model = nodegenModels.filter(function (_ref6) {
7698
- var metaData = _ref6.metaData;
7786
+ model = nodegenModels.filter(function (_ref8) {
7787
+ var metaData = _ref8.metaData;
7699
7788
  return metaData.EngineInformation.ProductName === folder && metaData.EngineInformation.ServiceName === service && new Date(requestMeta.transaction_date) >= new Date(metaData.EffectiveStartDate) && new Date(requestMeta.transaction_date) <= new Date(metaData.EffectiveEndDate);
7700
7789
  });
7701
7790
  if (model.length > 1) {
@@ -7715,10 +7804,32 @@ var findModel = function findModel(requestMeta, nodegenModels) {
7715
7804
  _folder = decodeURI(_parts[1]);
7716
7805
  _service = decodeURI(_parts[2]);
7717
7806
  }
7718
- model = nodegenModels.filter(function (_ref7) {
7719
- var metaData = _ref7.metaData;
7807
+ model = nodegenModels.filter(function (_ref9) {
7808
+ var metaData = _ref9.metaData;
7720
7809
  return metaData.EngineInformation.ProductName === _folder && metaData.EngineInformation.ServiceName === _service && metaData.EngineInformation.Revision === requestMeta.version;
7721
7810
  });
7811
+ } else if (requestMeta.service_uri) {
7812
+ var _transactionDate2 = new Date();
7813
+ var _regex2 = /folders\/(.+)\/services\/(.+)/gi;
7814
+ var _parts2 = _regex2.exec(requestMeta.service_uri);
7815
+ var _folder2, _service2;
7816
+ if (_parts2) {
7817
+ _folder2 = decodeURI(_parts2[1]);
7818
+ _service2 = decodeURI(_parts2[2]);
7819
+ }
7820
+ model = nodegenModels.filter(function (_ref10) {
7821
+ var metaData = _ref10.metaData;
7822
+ return metaData.EngineInformation.ProductName === _folder2 && metaData.EngineInformation.ServiceName === _service2 && _transactionDate2 >= new Date(metaData.EffectiveStartDate) && _transactionDate2 <= new Date(metaData.EffectiveEndDate);
7823
+ });
7824
+ if (model.length > 1) {
7825
+ return model.sort(function (versionA, versionB) {
7826
+ return versionA.metaData.EngineInformation.Revision.replace(/\d+/g, function (n) {
7827
+ return +n + 100000;
7828
+ }).localCompare(versionB.metaData.EngineInformation.Revision.replace(/\d+/g, function (n) {
7829
+ return +n + 100000;
7830
+ }));
7831
+ }).reverse();
7832
+ }
7722
7833
  } else {
7723
7834
  throw new Error("Model not found. requestMeta: " + JSON.stringify(requestMeta));
7724
7835
  }
@@ -7818,13 +7929,35 @@ var path = require("path");
7818
7929
  * @param {object} nodegen
7819
7930
  * @returns
7820
7931
  */
7932
+
7821
7933
  var processModels = function processModels(nodegen, index) {
7934
+ var logFn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
7935
+ var instanceid = arguments.length > 3 ? arguments[3] : undefined;
7936
+ var startDate = Date.now();
7937
+ logFn && logFn({
7938
+ eventType: 'processModels.start',
7939
+ nodegenType: nodegen.type
7940
+ });
7822
7941
  var processedModels = _objectSpread({}, nodegen);
7942
+ var endSpreadDate = Date.now();
7943
+ logFn && logFn({
7944
+ eventType: 'processModels.spread',
7945
+ nodegenType: nodegen.type,
7946
+ duration: endSpreadDate - startDate
7947
+ });
7823
7948
  switch (nodegen.type) {
7824
7949
  case "binary":
7825
7950
  case "uint8array":
7826
7951
  case "base64":
7827
- if ((0, _typeof2["default"])(nodegen.binary) === "object") {
7952
+ if (Buffer.isBuffer(nodegen.binary)) {
7953
+ processedModels.binary = nodegen.binary;
7954
+ var _endCreateBufferDate = Date.now();
7955
+ logFn && logFn({
7956
+ eventType: 'processModels.type.buffer',
7957
+ nodegenType: nodegen.type,
7958
+ duration: _endCreateBufferDate - startDate
7959
+ });
7960
+ } else if ((0, _typeof2["default"])(nodegen.binary) === "object") {
7828
7961
  var model = {
7829
7962
  servicename: nodegen.binary.servicename,
7830
7963
  wasm: Buffer.from(nodegen.binary.wasm, "base64"),
@@ -7832,6 +7965,12 @@ var processModels = function processModels(nodegen, index) {
7832
7965
  data: Buffer.from(nodegen.binary.data, "base64"),
7833
7966
  metadata: Buffer.from(nodegen.binary.metadata, "base64")
7834
7967
  };
7968
+ var endCreateobjectDate = Date.now();
7969
+ logFn && logFn({
7970
+ eventType: 'processModels.type.object',
7971
+ nodegenType: nodegen.type,
7972
+ duration: endCreateobjectDate - startDate
7973
+ });
7835
7974
  processedModels.binary = model;
7836
7975
  } else if (typeof nodegen.binaryPath !== 'undefined') {
7837
7976
  processModels.binaryPath = nodegen.binaryPath;
@@ -7847,7 +7986,7 @@ var processModels = function processModels(nodegen, index) {
7847
7986
  fs.mkdirSync(folder);
7848
7987
  }
7849
7988
  }
7850
- var filePath = path.join(__dirname, "resolver_temp/model-".concat(nodegen.versionId || nodegen.VersionI || uuidv4(), ".binary"));
7989
+ var filePath = path.join(__dirname, "resolver_temp/".concat(instanceid, "_model_").concat(nodegen.versionId || nodegen.VersionId || uuidv4(), ".binary"));
7851
7990
  fs.writeFileSync(filePath, Buffer.from(nodegen.binary, 'base64'));
7852
7991
  processedModels.binaryPath = filePath;
7853
7992
  nodegen.binaryPath = filePath;
@@ -7856,6 +7995,12 @@ var processModels = function processModels(nodegen, index) {
7856
7995
  }
7857
7996
  } else {
7858
7997
  var _model = Buffer.from(nodegen.binary, "base64");
7998
+ var _endCreateBufferDate2 = Date.now();
7999
+ logFn && logFn({
8000
+ eventType: 'processModels.type.bufferb64',
8001
+ nodegenType: nodegen.type,
8002
+ duration: _endCreateBufferDate2 - startDate
8003
+ });
7859
8004
  processedModels.binary = _model;
7860
8005
  }
7861
8006
  }
@@ -7885,9 +8030,24 @@ var processModels = function processModels(nodegen, index) {
7885
8030
  } else {
7886
8031
  processedModels.binary = func();
7887
8032
  }
8033
+ break;
8034
+ case "url":
8035
+ processedModels.binary = nodegen.binary;
8036
+ var endCreateBufferDate = Date.now();
8037
+ logFn && logFn({
8038
+ eventType: 'processModels.type.url',
8039
+ nodegenType: nodegen.type,
8040
+ duration: endCreateBufferDate - startDate
8041
+ });
7888
8042
  default:
7889
8043
  break;
7890
8044
  }
8045
+ var endDate = Date.now();
8046
+ logFn && logFn({
8047
+ eventType: 'processModels.complete',
8048
+ nodegenType: nodegen.type,
8049
+ duration: endDate - startDate
8050
+ });
7891
8051
  return processedModels;
7892
8052
  };
7893
8053
  module.exports = processModels;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coherentglobal/spark-execute-sdk",
3
- "version": "0.4.9",
3
+ "version": "0.4.11",
4
4
  "description": "",
5
5
  "main": "src/node.js",
6
6
  "browser": "dist/browser.js",
package/src/browser.js CHANGED
@@ -5,13 +5,25 @@ const validate = require("./validate.js");
5
5
  const processModels = require("./models.js");
6
6
  const findModel = require("./findModels.js");
7
7
 
8
- let registry = {};
8
+
9
9
 
10
10
  class Spark {
11
11
  /**
12
12
  * @param {object} config
13
13
  */
14
- constructor(config) {
14
+ constructor(config, options = {}) {
15
+ /**
16
+ * @private
17
+ */
18
+ this._registry = undefined;
19
+
20
+ /**
21
+ * @private
22
+ */
23
+ if (options?.log) {
24
+ this.logger = options.log
25
+ }
26
+
15
27
  /**
16
28
  * @private
17
29
  */
@@ -40,14 +52,20 @@ class Spark {
40
52
  * @private
41
53
  */
42
54
  this.isCompatible = utils.isWasmSupported();
43
- /**
44
- * @private
45
- */
46
- this.model = this._models(this.config?.nodeGenModels);
55
+
47
56
  /**
48
57
  * @private
49
58
  */
50
59
  this.priority = ["model", "onlineEndpoint"];
60
+
61
+ /**
62
+ * @private
63
+ */
64
+ this.model = this._models(this.config?.nodeGenModels);
65
+ }
66
+
67
+ log(msg) {
68
+ this.logger && this.logger(msg)
51
69
  }
52
70
 
53
71
  /**
@@ -56,7 +74,17 @@ class Spark {
56
74
  * @returns {object}
57
75
  */
58
76
  _models(nodegen) {
59
- const models = nodegen.map(processModels);
77
+ this.log({ eventType: "spark._models", msg: 'Parse models' })
78
+ const models = [];
79
+
80
+ for (let i = 0; i < nodegen.length; i++) {
81
+ const startDate = Date.now();
82
+ this.log({ eventType: "spark._models.processModels.start", msg: `Start process model ${i}` });
83
+ const model = processModels(nodegen[i], i, this.log.bind(this));
84
+ const endDate = Date.now();
85
+ this.log({ eventType: "spark._models.processModels.end", msg: `End process model ${i}`, duration: endDate - startDate });
86
+ models.push(model)
87
+ }
60
88
 
61
89
  return models;
62
90
  }
@@ -66,11 +94,17 @@ class Spark {
66
94
  * @returns {object}
67
95
  */
68
96
  validateConfig(config) {
97
+ const start = Date.now();
98
+ this.log({ eventType: 'spark.validateconfig.start' })
69
99
  const { value, error } = validate(config);
70
100
  if (!error) {
101
+ const end = Date.now();
102
+ this.log({ eventType: 'spark.validateconfig.startend', duration: end - start })
71
103
  return value;
72
104
  } else {
73
105
  const message = JSON.stringify(error.details);
106
+ const end = Date.now();
107
+ this.log({ eventType: 'spark.validateconfig.startend.error', duration: end - start })
74
108
  throw new Error(`ValidationError: ${message}`);
75
109
  }
76
110
  }
@@ -105,13 +139,17 @@ class Spark {
105
139
  * @returns {object}
106
140
  */
107
141
  async execute(input, version_id) {
142
+ if (this.model == undefined) {
143
+ throw new WasmRunnerErrors.BadRequestError('Spark initialize is required. Please call initialize method')
144
+ }
145
+
108
146
  const versionID =
109
147
  version_id ||
110
148
  input?.request_meta?.version_id ||
111
149
  input?.request_meta?.version_uuid;
112
150
  let lookup = {
113
- model: this.offlineModel,
114
- onlineEndpoint: this.onlineModelEndpoint,
151
+ model: this.offlineModel.bind(this),
152
+ onlineEndpoint: this.onlineModelEndpoint.bind(this),
115
153
  };
116
154
 
117
155
  let response;
@@ -123,8 +161,8 @@ class Spark {
123
161
  return response;
124
162
  }
125
163
 
126
- async offlineModel(input, versionID, ds) {
127
- const model = findModel(input.request_meta, ds.model);
164
+ async offlineModel(input, versionID) {
165
+ const model = findModel(input.request_meta, this.model);
128
166
  const modelVersionId = versionID || (model && model?.versionId);
129
167
 
130
168
  if (!input?.request_meta) {
@@ -135,7 +173,7 @@ class Spark {
135
173
  }
136
174
 
137
175
  try {
138
- if (!(registry instanceof WasmRunner)) {
176
+ if (this._registry === undefined) {
139
177
  /**
140
178
  * Options is the request data the the runner dispatch
141
179
  * receives from the wasm model
@@ -147,8 +185,8 @@ class Spark {
147
185
  const hasServiceName = options?.service_name;
148
186
  let hasVersionId = options?.version_id;
149
187
 
150
- if (hasVersionId && !registry.isExist(hasVersionId)) {
151
- await registry.append({
188
+ if (hasVersionId && !this._registry.isExist(hasVersionId)) {
189
+ await this._registry.append({
152
190
  id: hasVersionId,
153
191
  url: model.binary,
154
192
  meta: {
@@ -159,9 +197,9 @@ class Spark {
159
197
  },
160
198
  });
161
199
  } else {
162
- const model = ds._getModelByMeta(hasFolderName, hasServiceName);
200
+ const model = this._getModelByMeta(hasFolderName, hasServiceName);
163
201
  hasVersionId = model?.versionId;
164
- await registry.append({
202
+ await this._registry.append({
165
203
  id: hasVersionId,
166
204
  url: model.binary,
167
205
  meta: {
@@ -174,13 +212,13 @@ class Spark {
174
212
  }
175
213
  return hasVersionId;
176
214
  };
177
- registry = new WasmRunner("", callback);
215
+ this._registry = new WasmRunner("", callback);
178
216
  }
179
217
 
180
- if (!registry.isExist(modelVersionId)) {
181
- const model = findModel(input.request_meta, ds.model);
218
+ if (!this._registry.isExist(modelVersionId)) {
219
+ const model = findModel(input.request_meta, this.model);
182
220
 
183
- await registry.append({
221
+ await this._registry.append({
184
222
  id: modelVersionId,
185
223
  url: model.binary,
186
224
  meta: {
@@ -189,35 +227,35 @@ class Spark {
189
227
  },
190
228
  });
191
229
  }
192
- const result = await registry.execute(input, modelVersionId, () => {});
230
+ const result = await this._registry.execute(input, modelVersionId, () => { });
193
231
  return result;
194
232
  } catch (err) {
195
233
  return err;
196
234
  }
197
235
  }
198
236
 
199
- async onlineModelEndpoint(input, versionID, ds) {
200
- const isPublic = ds.authType === "public";
237
+ async onlineModelEndpoint(input, versionID) {
238
+ const isPublic = this.authType === "public";
201
239
 
202
240
  let token = "";
203
241
 
204
242
  if (!isPublic) {
205
- if (ds.token.constructor.name === "AsyncFunction") {
206
- token = await ds.token();
207
- } else if (typeof ds.token === "function") {
208
- token = ds.token();
243
+ if (this.token.constructor.name === "AsyncFunction") {
244
+ token = await this.token();
245
+ } else if (typeof this.token === "function") {
246
+ token = this.token();
209
247
  } else {
210
- token = ds.token;
248
+ token = this.token;
211
249
  }
212
250
 
213
- if (utils.isEmpty(ds.token)) {
251
+ if (utils.isEmpty(this.token)) {
214
252
  throw new WasmRunnerErrors.UnauthorizedError();
215
253
  }
216
254
  }
217
255
 
218
256
  try {
219
257
  const header = !isPublic
220
- ? utils.getAuthHeaders(token, ds.authType, ds.tenant)
258
+ ? utils.getAuthHeaders(token, this.authType, this.tenant)
221
259
  : {};
222
260
 
223
261
  const options = {
@@ -230,8 +268,8 @@ class Spark {
230
268
  };
231
269
 
232
270
  const modelUrl = new URL(
233
- `/${ds.tenant}/api/v3/${!isPublic ? "execute" : "public"}`,
234
- ds.url
271
+ `/${this.tenant}/api/v3/${!isPublic ? "execute" : "public"}`,
272
+ this.url
235
273
  );
236
274
 
237
275
  const response = await fetch(modelUrl, options);
package/src/findModels.js CHANGED
@@ -17,9 +17,35 @@ const findModel = (requestMeta, nodegenModels) => {
17
17
  ({ metaData }) =>
18
18
  metaData.EngineInformation.ServiceName === requestMeta.servicename &&
19
19
  new Date(requestMeta.transaction_date) >=
20
- new Date(metaData.EffectiveStartDate) &&
20
+ new Date(metaData.EffectiveStartDate) &&
21
21
  new Date(requestMeta.transaction_date) <=
22
- new Date(metaData.EffectiveEndDate)
22
+ new Date(metaData.EffectiveEndDate)
23
+ );
24
+
25
+ if (model.length > 1) {
26
+ return model
27
+ .sort((versionA, versionB) =>
28
+ versionA.metaData.EngineInformation.Revision.replace(
29
+ /\d+/g,
30
+ (n) => +n + 100000
31
+ ).localCompare(
32
+ versionB.metaData.EngineInformation.Revision.replace(
33
+ /\d+/g,
34
+ (n) => +n + 100000
35
+ )
36
+ )
37
+ )
38
+ .reverse();
39
+ }
40
+ } else if (requestMeta.servicename) {
41
+ const transactionDate = new Date();
42
+ model = nodegenModels.filter(
43
+ ({ metaData }) =>
44
+ metaData.EngineInformation.ServiceName === requestMeta.servicename &&
45
+ transactionDate >=
46
+ new Date(metaData.EffectiveStartDate) &&
47
+ transactionDate <=
48
+ new Date(metaData.EffectiveEndDate)
23
49
  );
24
50
 
25
51
  if (model.length > 1) {
@@ -48,9 +74,35 @@ const findModel = (requestMeta, nodegenModels) => {
48
74
  ({ metaData }) =>
49
75
  metaData.EngineInformation.ServiceGuid === requestMeta.service_id &&
50
76
  new Date(requestMeta.transaction_date) >=
51
- new Date(metaData.EffectiveStartDate) &&
77
+ new Date(metaData.EffectiveStartDate) &&
52
78
  new Date(requestMeta.transaction_date) <=
53
- new Date(metaData.EffectiveEndDate)
79
+ new Date(metaData.EffectiveEndDate)
80
+ );
81
+
82
+ if (model.length > 1) {
83
+ return model
84
+ .sort((versionA, versionB) =>
85
+ versionA.metaData.EngineInformation.Revision.replace(
86
+ /\d+/g,
87
+ (n) => +n + 100000
88
+ ).localCompare(
89
+ versionB.metaData.EngineInformation.Revision.replace(
90
+ /\d+/g,
91
+ (n) => +n + 100000
92
+ )
93
+ )
94
+ )
95
+ .reverse();
96
+ }
97
+ } else if (requestMeta.service_id) {
98
+ const transactionDate = new Date();
99
+ model = nodegenModels.filter(
100
+ ({ metaData }) =>
101
+ metaData.EngineInformation.ServiceGuid === requestMeta.service_id &&
102
+ transactionDate >=
103
+ new Date(metaData.EffectiveStartDate) &&
104
+ transactionDate <=
105
+ new Date(metaData.EffectiveEndDate)
54
106
  );
55
107
 
56
108
  if (model.length > 1) {
@@ -82,9 +134,9 @@ const findModel = (requestMeta, nodegenModels) => {
82
134
  metaData.EngineInformation.ProductName === folder &&
83
135
  metaData.EngineInformation.ServiceName === service &&
84
136
  new Date(requestMeta.transaction_date) >=
85
- new Date(metaData.EffectiveStartDate) &&
137
+ new Date(metaData.EffectiveStartDate) &&
86
138
  new Date(requestMeta.transaction_date) <=
87
- new Date(metaData.EffectiveEndDate)
139
+ new Date(metaData.EffectiveEndDate)
88
140
  );
89
141
 
90
142
  if (model.length > 1) {
@@ -116,6 +168,41 @@ const findModel = (requestMeta, nodegenModels) => {
116
168
  metaData.EngineInformation.ServiceName === service &&
117
169
  metaData.EngineInformation.Revision === requestMeta.version
118
170
  );
171
+ } else if (requestMeta.service_uri) {
172
+ const transactionDate = new Date();
173
+ const regex = /folders\/(.+)\/services\/(.+)/gi;
174
+ const parts = regex.exec(requestMeta.service_uri);
175
+ let folder, service;
176
+ if (parts) {
177
+ folder = decodeURI(parts[1]);
178
+ service = decodeURI(parts[2]);
179
+ }
180
+
181
+ model = nodegenModels.filter(
182
+ ({ metaData }) =>
183
+ metaData.EngineInformation.ProductName === folder &&
184
+ metaData.EngineInformation.ServiceName === service &&
185
+ transactionDate >=
186
+ new Date(metaData.EffectiveStartDate) &&
187
+ transactionDate <=
188
+ new Date(metaData.EffectiveEndDate)
189
+ );
190
+
191
+ if (model.length > 1) {
192
+ return model
193
+ .sort((versionA, versionB) =>
194
+ versionA.metaData.EngineInformation.Revision.replace(
195
+ /\d+/g,
196
+ (n) => +n + 100000
197
+ ).localCompare(
198
+ versionB.metaData.EngineInformation.Revision.replace(
199
+ /\d+/g,
200
+ (n) => +n + 100000
201
+ )
202
+ )
203
+ )
204
+ .reverse();
205
+ }
119
206
  } else {
120
207
  throw new Error(
121
208
  "Model not found. requestMeta: " + JSON.stringify(requestMeta)
package/src/models.js CHANGED
@@ -7,14 +7,24 @@ const path = require("path");
7
7
  * @param {object} nodegen
8
8
  * @returns
9
9
  */
10
- const processModels = (nodegen, index) => {
10
+
11
+ const processModels = (nodegen, index, logFn = undefined, instanceid) => {
12
+ const startDate = Date.now();
13
+ logFn && logFn({ eventType: 'processModels.start', nodegenType: nodegen.type });
14
+
11
15
  const processedModels = { ...nodegen };
16
+ const endSpreadDate = Date.now();
17
+ logFn && logFn({ eventType: 'processModels.spread', nodegenType: nodegen.type, duration: endSpreadDate - startDate });
12
18
 
13
19
  switch (nodegen.type) {
14
20
  case "binary":
15
21
  case "uint8array":
16
22
  case "base64":
17
- if (typeof nodegen.binary === "object") {
23
+ if (Buffer.isBuffer(nodegen.binary)) {
24
+ processedModels.binary = nodegen.binary;
25
+ const endCreateBufferDate = Date.now();
26
+ logFn && logFn({ eventType: 'processModels.type.buffer', nodegenType: nodegen.type, duration: endCreateBufferDate - startDate });
27
+ } else if (typeof nodegen.binary === "object") {
18
28
  const model = {
19
29
  servicename: nodegen.binary.servicename,
20
30
  wasm: Buffer.from(nodegen.binary.wasm, "base64"),
@@ -22,6 +32,8 @@ const processModels = (nodegen, index) => {
22
32
  data: Buffer.from(nodegen.binary.data, "base64"),
23
33
  metadata: Buffer.from(nodegen.binary.metadata, "base64")
24
34
  };
35
+ const endCreateobjectDate = Date.now();
36
+ logFn && logFn({ eventType: 'processModels.type.object', nodegenType: nodegen.type, duration: endCreateobjectDate - startDate });
25
37
  processedModels.binary = model;
26
38
  } else if (typeof nodegen.binaryPath !== 'undefined') {
27
39
  processModels.binaryPath = nodegen.binaryPath
@@ -39,7 +51,7 @@ const processModels = (nodegen, index) => {
39
51
  }
40
52
  const filePath = path.join(
41
53
  __dirname,
42
- `resolver_temp/model-${nodegen.versionId || nodegen.VersionI || uuidv4()}.binary`
54
+ `resolver_temp/${instanceid}_model_${nodegen.versionId || nodegen.VersionId || uuidv4()}.binary`
43
55
  );
44
56
 
45
57
  fs.writeFileSync(filePath, Buffer.from(nodegen.binary, 'base64'));
@@ -50,6 +62,8 @@ const processModels = (nodegen, index) => {
50
62
  }
51
63
  } else {
52
64
  const model = Buffer.from(nodegen.binary, "base64");
65
+ const endCreateBufferDate = Date.now();
66
+ logFn && logFn({ eventType: 'processModels.type.bufferb64', nodegenType: nodegen.type, duration: endCreateBufferDate - startDate });
53
67
  processedModels.binary = model;
54
68
  }
55
69
  }
@@ -67,10 +81,17 @@ const processModels = (nodegen, index) => {
67
81
  } else {
68
82
  processedModels.binary = func();
69
83
  }
84
+ break;
85
+ case "url":
86
+ processedModels.binary = nodegen.binary;
87
+ const endCreateBufferDate = Date.now();
88
+ logFn && logFn({ eventType: 'processModels.type.url', nodegenType: nodegen.type, duration: endCreateBufferDate - startDate });
70
89
  default:
71
90
  break;
72
91
  }
73
92
 
93
+ const endDate = Date.now();
94
+ logFn && logFn({ eventType: 'processModels.complete', nodegenType: nodegen.type, duration: endDate - startDate })
74
95
  return processedModels;
75
96
  };
76
97
 
package/src/node.js CHANGED
@@ -13,31 +13,34 @@ const { object } = require("joi");
13
13
  const { P } = require("pino");
14
14
  const findModel = require("./findModels.js");
15
15
 
16
- let registry = [];
17
-
18
16
  class Spark {
19
17
  /**
20
18
  * @param {object} config
21
19
  */
22
- constructor(config, option = {}, apmInstance) {
23
- // REMOVE ME!!
24
- // console.log('init spark instance serialize:', option?.serialize)
20
+ constructor(config, option = undefined, apmInstance = undefined) {
21
+ /**
22
+ * @private
23
+ */
24
+ this._registry = undefined;
25
+
25
26
  if (apmInstance) {
26
- // console.log(apmInstance)
27
27
  this.apm = apmInstance
28
28
  }
29
+
30
+ /**
31
+ * @private
32
+ */
33
+ this.instanceid = option && option.instanceid ? option.instanceid : uuidv4()
34
+
29
35
  /**
30
36
  * @private
31
37
  */
32
- if (option.serialize) {
38
+ if (option && option.serialize) {
33
39
  const buffer = fs.readFileSync(option.configPath);
34
40
  const toBase = buffer.toString("utf8");
35
41
  const deserialize = serializeObject.deserialize(toBase);
36
42
  const validate = this.validateConfig(deserialize);
37
43
  this.config = validate;
38
- logger.info({
39
- message: "DESERIALIZED"
40
- });
41
44
  this.isSerializedConfig;
42
45
  } else {
43
46
  this.config = this.validateConfig(config);
@@ -88,7 +91,7 @@ class Spark {
88
91
  * @returns {object}
89
92
  */
90
93
  _models(nodegen) {
91
- const models = nodegen.map(processModels);
94
+ const models = nodegen.map((n, i) => processModels(n, i, undefined, this.instanceid));
92
95
  return models;
93
96
  }
94
97
 
@@ -105,6 +108,7 @@ class Spark {
105
108
  const message = JSON.stringify(error.details);
106
109
  logger.error({
107
110
  EventType: "ValidationError",
111
+ InstanceId: this.instanceid,
108
112
  TextMessage: message,
109
113
  });
110
114
  throw new Error(`ValidationError: ${message}`);
@@ -125,15 +129,15 @@ class Spark {
125
129
  input.request_meta.version_uuid;
126
130
 
127
131
  let lookup = {
128
- model: this.offlineModel,
129
- onlineEndpoint: this.onlineModelEndpoint,
132
+ model: this.offlineModel.bind(this),
133
+ onlineEndpoint: this.onlineModelEndpoint.bind(this),
130
134
  };
131
135
 
132
136
  let response;
133
137
 
134
- response = await lookup[this.priority[0]](input, versionID, this);
138
+ response = await lookup[this.priority[0]](input, versionID);
135
139
  if (response instanceof Error && this.config.sparkEndpoint !== undefined && false) {
136
- response = await lookup[this.priority[1]](input, versionID, this);
140
+ response = await lookup[this.priority[1]](input, versionID);
137
141
  }
138
142
 
139
143
  return response;
@@ -148,12 +152,12 @@ class Spark {
148
152
  }
149
153
  const filePath = path.join(
150
154
  __dirname,
151
- `resolver_temp/resolver-${uuidv4()}.js`
155
+ `resolver_temp/${this.instanceid}_resolver-${uuidv4()}.js`
152
156
  );
153
157
 
154
158
  const configPath = path.join(
155
159
  __dirname,
156
- `resolver_temp/model_config`
160
+ `resolver_temp/${this.instanceid}_config`
157
161
  );
158
162
 
159
163
  if (fs.existsSync(filePath)) {
@@ -173,9 +177,11 @@ class Spark {
173
177
  template = template.replace(
174
178
  "%%config_to_replace%%",
175
179
  configPath
180
+ ).replace(
181
+ "%%instanceid%%",
182
+ this.instanceid
176
183
  );
177
184
 
178
-
179
185
  fs.writeFileSync(filePath, template);
180
186
  if (!this.isSerializedConfig) {
181
187
  const config = { ...this.config }
@@ -185,7 +191,7 @@ class Spark {
185
191
  if (m.binary) {
186
192
  const filePath = path.join(
187
193
  __dirname,
188
- `resolver_temp/model-${m.versionId || m.VersionId || uuidv4()}.binary`
194
+ `resolver_temp/${this.instanceid}_model_${m.versionId || m.VersionId || uuidv4()}.binary`
189
195
  );
190
196
 
191
197
  fs.writeFileSync(filePath, Buffer.from(m.binary, 'base64'));
@@ -198,6 +204,26 @@ class Spark {
198
204
  fs.writeFileSync(configPath, Buffer.from(data))
199
205
  }
200
206
 
207
+ process.once('SIGINT', () => {
208
+ try {
209
+ fs.rmSync(path.join(
210
+ __dirname,
211
+ `resolver_temp`), { recursive: true, force: true });
212
+ } catch (err) {
213
+ // Just ignore
214
+ }
215
+ });
216
+
217
+ process.once('exit', () => {
218
+ try {
219
+ fs.rmSync(path.join(
220
+ __dirname,
221
+ `resolver_temp`), { recursive: true, force: true });
222
+ } catch (err) {
223
+ // Just ignore
224
+ }
225
+ });
226
+
201
227
  return require.resolve(filePath);
202
228
  }
203
229
 
@@ -207,7 +233,9 @@ class Spark {
207
233
  m?.metaData?.EngineInformation?.ProductName === folderName &&
208
234
  m?.metaData?.EngineInformation?.ServiceName === serviceName
209
235
  );
210
- if (!model) throw new WasmRunnerErrors.MissingModelError(serviceName);
236
+ if (!model) {
237
+ throw new WasmRunnerErrors.MissingModelError(`folder ${folderName} service ${serviceName}`);
238
+ }
211
239
  return model?.metaData?.VersionId || model?.versionId;
212
240
  }
213
241
 
@@ -216,7 +244,6 @@ class Spark {
216
244
  console.err(err)
217
245
  );
218
246
  return require.resolve("config.json");
219
- // return JSON.stringify(this.config)
220
247
  }
221
248
 
222
249
  /**
@@ -224,55 +251,61 @@ class Spark {
224
251
  */
225
252
  // async remove(versionId) {}
226
253
 
227
- async offlineModel(input, versionID, ds) {
254
+ async offlineModel(input, versionID) {
228
255
  try {
229
- const model = findModel(input.request_meta, ds.model);
256
+ const model = findModel(input.request_meta, this.model);
230
257
 
231
258
  const versionId = versionID || (model && model?.versionId);
232
259
 
233
260
  logger.info({
234
261
  EventType: "ExecuteModel",
262
+ InstanceId: this.instanceid,
235
263
  TextMessage: `Execute uuid: ${versionId}`,
236
264
  });
237
- if (!(registry instanceof WasmRunner)) {
238
- registry = new WasmRunner(undefined, ds.externalResolver, "");
265
+
266
+ if (this._registry === undefined) {
267
+ this._registry = new WasmRunner(undefined, this.externalResolver, "");
239
268
  }
240
269
 
241
- if (!registry.isExist(versionId)) {
242
- await registry.append({
270
+ if (!this._registry.isExist(versionId)) {
271
+ await this._registry.append({
243
272
  id: versionId,
244
273
  url: model?.binary || model?.binaryPath || "",
245
274
  });
246
275
  }
247
276
 
248
- let result = await registry.execute(input, versionId);
277
+ let result = await this._registry.execute(input, versionId);
249
278
 
250
279
  return result;
251
280
  } catch (err) {
252
- console.log('----ERRORR')
253
- console.log(err)
281
+ logger.error({
282
+ EventType: "ExecutionError",
283
+ InstanceId: this.instanceid,
284
+ TextMessage: err.message,
285
+ });
254
286
  return err;
255
287
  }
256
288
  }
257
289
 
258
- async onlineModelEndpoint(input, versionID, ds) {
290
+ async onlineModelEndpoint(input, versionID) {
259
291
  logger.info({
260
292
  EventType: "ExecuteOnlineModel",
293
+ InstanceId: this.instanceid,
261
294
  TextMessage: `Execute uuid: ${versionID}`,
262
295
  });
263
296
 
264
- const isPublic = ds.authType === "public";
297
+ const isPublic = this.authType === "public";
265
298
  let token = "";
266
299
  if (!isPublic) {
267
- if (ds.token.constructor.name === "AsyncFunction") {
268
- token = await ds.token();
269
- } else if (typeof ds.token === "function") {
270
- token = ds.token();
300
+ if (this.token.constructor.name === "AsyncFunction") {
301
+ token = await this.token();
302
+ } else if (typeof this.token === "function") {
303
+ token = this.token();
271
304
  } else {
272
- token = ds.token;
305
+ token = this.token;
273
306
  }
274
307
 
275
- if (utils.isEmpty(ds.token)) {
308
+ if (utils.isEmpty(this.token)) {
276
309
  throw new WasmRunnerErrors.UnauthorizedError();
277
310
  }
278
311
  }
@@ -280,7 +313,7 @@ class Spark {
280
313
  try {
281
314
  const options = {
282
315
  headers: !isPublic
283
- ? utils.getAuthHeaders(token, ds.authType, ds.tenant)
316
+ ? utils.getAuthHeaders(token, this.authType, this.tenant)
284
317
  : {},
285
318
  json: {
286
319
  request_data: {},
@@ -289,8 +322,8 @@ class Spark {
289
322
  };
290
323
 
291
324
  let modelUrl = new URL(
292
- `/${ds.tenant}/api/v3/${!isPublic ? "execute" : "public"}`,
293
- ds.url
325
+ `/${this.tenant}/api/v3/${!isPublic ? "execute" : "public"}`,
326
+ this.url
294
327
  );
295
328
 
296
329
  const result = await got.post(modelUrl, options).json();
@@ -60,7 +60,7 @@ const sparkServiceVersionOne = async (requestData, context) => {
60
60
  const options = {}
61
61
 
62
62
  if (!instance) {
63
- instance = new Spark({}, { serialize: true, configPath: "%%config_to_replace%%" })
63
+ instance = new Spark({}, { serialize: true, configPath: "%%config_to_replace%%", instanceid: "%%instanceid%%" })
64
64
  }
65
65
 
66
66
  const modelId = instance._getModelByMeta(folderName, serviceName)
@@ -3,7 +3,8 @@ declare class Spark {
3
3
  /**
4
4
  * @param {object} config
5
5
  */
6
- constructor(config: object);
6
+ constructor(config: object, options?: {});
7
+ logger: any;
7
8
  /**
8
9
  * @private
9
10
  */
@@ -28,14 +29,15 @@ declare class Spark {
28
29
  * @private
29
30
  */
30
31
  private isCompatible;
31
- /**
32
- * @private
33
- */
34
- private model;
35
32
  /**
36
33
  * @private
37
34
  */
38
35
  private priority;
36
+ /**
37
+ * @private
38
+ */
39
+ private model;
40
+ log(msg: any): void;
39
41
  /**
40
42
  *
41
43
  * @param {object} nodegen
@@ -1 +1 @@
1
- {"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.js"],"names":[],"mappings":";AASA;IACE;;OAEG;IACH,oBAFW,MAAM,EAuChB;IApCC;;OAEG;IACH,eAAyC;IAEzC;;OAEG;IACH,eAAsD;IACtD;;OAEG;IACH,iBAA0D;IAC1D;;OAEG;IACH,cAGI;IACJ;;OAEG;IACH,YAAgD;IAChD;;OAEG;IACH,qBAA2C;IAC3C;;OAEG;IACH,cAAqD;IACrD;;OAEG;IACH,iBAA2C;IAG7C;;;;OAIG;IACH,iBAHW,MAAM,GACJ,MAAM,CAMlB;IACD;;;;OAIG;IACH,uBAHW,MAAM,GACJ,MAAM,CAUlB;IACD;;;;OAIG;IACH,cAHW,MAAM,GACJ,OAAO,CAOnB;IAED,wDASC;IAED;;;;;;OAMG;IACH,eAJW,MAAM,oCAEJ,MAAM,CAmBlB;IAED,gEAuEC;IAED,uEA6CC;CACF"}
1
+ {"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.js"],"names":[],"mappings":";AASA;IACE;;OAEG;IACH,oBAFW,MAAM,gBAgDhB;IAzCG,YAAyB;IAG3B;;OAEG;IACH,eAAyC;IAEzC;;OAEG;IACH,eAAsD;IACtD;;OAEG;IACH,iBAA0D;IAC1D;;OAEG;IACH,cAGI;IACJ;;OAEG;IACH,YAAgD;IAChD;;OAEG;IACH,qBAA2C;IAE3C;;OAEG;IACH,iBAA2C;IAE3C;;MAEE;IACF,cAAqD;IAGvD,oBAEC;IAED;;;;OAIG;IACH,iBAHW,MAAM,GACJ,MAAM,CAgBlB;IACD;;;;OAIG;IACH,uBAHW,MAAM,GACJ,MAAM,CAgBlB;IACD;;;;OAIG;IACH,cAHW,MAAM,GACJ,OAAO,CAOnB;IAED,wDASC;IAED;;;;;;OAMG;IACH,eAJW,MAAM,oCAEJ,MAAM,CAuBlB;IAED,gEAuEC;IAED,uEA6CC;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"findModels.d.ts","sourceRoot":"","sources":["../src/findModels.js"],"names":[],"mappings":";AAEA,sEA+HC"}
1
+ {"version":3,"file":"findModels.d.ts","sourceRoot":"","sources":["../src/findModels.js"],"names":[],"mappings":";AAEA,sEAsNC"}
package/types/models.d.ts CHANGED
@@ -4,5 +4,5 @@ export = processModels;
4
4
  * @param {object} nodegen
5
5
  * @returns
6
6
  */
7
- declare function processModels(nodegen: object, index: any): {};
7
+ declare function processModels(nodegen: object, index: any, logFn: undefined, instanceid: any): {};
8
8
  //# sourceMappingURL=models.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../src/models.js"],"names":[],"mappings":";AAIA;;;;GAIG;AACH,wCAHW,MAAM,kBAoEhB"}
1
+ {"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../src/models.js"],"names":[],"mappings":";AAIA;;;;GAIG;AAEH,wCAJW,MAAM,qDAyFhB"}
package/types/node.d.ts CHANGED
@@ -3,9 +3,14 @@ declare class Spark {
3
3
  /**
4
4
  * @param {object} config
5
5
  */
6
- constructor(config: object, option: {} | undefined, apmInstance: any);
6
+ constructor(config: object, option?: undefined, apmInstance?: undefined);
7
+ /**
8
+ * @private
9
+ */
10
+ private _registry;
7
11
  apm: any;
8
12
  config: object;
13
+ instanceid: any;
9
14
  /**
10
15
  * @private
11
16
  */
@@ -64,7 +69,7 @@ declare class Spark {
64
69
  /**
65
70
  * Remove Model
66
71
  */
67
- offlineModel(input: any, versionID: any, ds: any): Promise<any>;
68
- onlineModelEndpoint(input: any, versionID: any, ds: any): Promise<any>;
72
+ offlineModel(input: any, versionID: any): Promise<unknown>;
73
+ onlineModelEndpoint(input: any, versionID: any): Promise<any>;
69
74
  }
70
75
  //# sourceMappingURL=node.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.js"],"names":[],"mappings":";AAiBA;IACE;;OAEG;IACH,oBAFW,MAAM,4CA8DhB;IAxDG,SAAsB;IAUtB,eAAsB;IASxB;;OAEG;IACH,eAAsD;IACtD;;OAEG;IACH,iBAA0D;IAC1D;;OAEG;IACH,cAGI;IACJ;;OAEG;IACH,YAAgD;IAChD;;OAEG;IACH,qBAA2C;IAC3C;;OAEG;IACH,cAAqD;IAErD;;OAEG;IACH,yBAAmD;IAEnD;;OAEG;IACH,iBAA2C;IAG7C;;;;OAIG;IACH,iBAHW,MAAM,GACJ,MAAM,CAKlB;IAED;;;;OAIG;IACH,uBAHW,MAAM,GACJ,MAAM,CAclB;IAED;;;;;;OAMG;IACH,eAJW,MAAM,oCAEJ,MAAM,CAqBlB;IAED,+BA4DC;IAED,wDAQC;IAED,uBAMC;IAED;;OAEG;IAGH,gEA6BC;IAED,uEA4CC;CACF"}
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.js"],"names":[],"mappings":";AAeA;IACE;;OAEG;IACH,oBAFW,MAAM,+CAmEhB;IAhEC;;OAEG;IACH,kBAA0B;IAGxB,SAAsB;IAUtB,eAAsB;IASxB,gBAA4E;IAE5E;;OAEG;IACH,eAAsD;IACtD;;OAEG;IACH,iBAA0D;IAC1D;;OAEG;IACH,cAGI;IACJ;;OAEG;IACH,YAAgD;IAChD;;OAEG;IACH,qBAA2C;IAC3C;;OAEG;IACH,cAAqD;IAErD;;OAEG;IACH,yBAAmD;IAEnD;;OAEG;IACH,iBAA2C;IAG7C;;;;OAIG;IACH,iBAHW,MAAM,GACJ,MAAM,CAKlB;IAED;;;;OAIG;IACH,uBAHW,MAAM,GACJ,MAAM,CAclB;IAED;;;;;;OAMG;IACH,eAJW,MAAM,oCAEJ,MAAM,CAqBlB;IAED,+BAkFC;IAED,wDAWC;IAED,uBAKC;IAED;;OAEG;IAGH,2DA0CC;IAED,8DA4CC;CACF"}