@instana/shared-metrics 1.126.0 → 1.128.0

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/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@instana/shared-metrics",
3
- "version": "1.126.0",
3
+ "version": "1.128.0",
4
4
  "description": "Internal metrics plug-in package for Node.js monitoring with Instana",
5
5
  "author": {
6
6
  "name": "Bastian Krol",
7
7
  "email": "bastian.krol@instana.com"
8
8
  },
9
- "homepage": "https://github.com/instana/nodejs-sensor/blob/main/packages/shared-metrics/README.md",
9
+ "homepage": "https://github.com/instana/nodejs/blob/main/packages/shared-metrics/README.md",
10
10
  "main": "src/index.js",
11
11
  "files": [
12
12
  "src",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "repository": {
23
23
  "type": "git",
24
- "url": "git+https://github.com/instana/nodejs-sensor.git"
24
+ "url": "git+https://github.com/instana/nodejs.git"
25
25
  },
26
26
  "scripts": {
27
27
  "audit": "bin/prepare-audit.sh && npm audit --production; AUDIT_RESULT=$?; git checkout package-lock.json; exit $AUDIT_RESULT",
@@ -51,28 +51,28 @@
51
51
  }
52
52
  ],
53
53
  "bugs": {
54
- "url": "https://github.com/instana/nodejs-sensor/issues"
54
+ "url": "https://github.com/instana/nodejs/issues"
55
55
  },
56
56
  "license": "MIT",
57
57
  "dependencies": {
58
- "@instana/core": "1.126.0",
58
+ "@instana/core": "1.128.0",
59
59
  "detect-libc": "^1.0.3",
60
60
  "event-loop-lag": "^1.4.0",
61
- "recursive-copy": "^2.0.11",
61
+ "recursive-copy": "^2.0.13",
62
62
  "tar": "^5.0.5"
63
63
  },
64
64
  "devDependencies": {
65
- "eslint": "^7.27.0",
66
- "eslint-config-airbnb-base": "^13.1.0",
67
- "eslint-plugin-import": "^2.22.1",
65
+ "eslint": "^7.30.0",
66
+ "eslint-config-airbnb-base": "^14.2.1",
67
+ "eslint-plugin-import": "^2.23.4",
68
68
  "eslint-plugin-mocha": "^8.1.0",
69
69
  "mocha": "^7.2.0",
70
- "prettier": "^2.2.1"
70
+ "prettier": "^2.3.2"
71
71
  },
72
72
  "optionalDependencies": {
73
73
  "event-loop-stats": "1.3.0",
74
74
  "gcstats.js": "1.0.0",
75
75
  "node-gyp": "^7.1.2"
76
76
  },
77
- "gitHead": "ba48f1a9cd07fda7ff2b5bb21630e176219936e2"
77
+ "gitHead": "a08cd7c136eecdf11278b3e927da313a15ab33e8"
78
78
  }
@@ -9,6 +9,7 @@ exports.payloadPrefix = 'activeHandles';
9
9
 
10
10
  Object.defineProperty(exports, 'currentPayload', {
11
11
  get: function () {
12
+ // @ts-ignore
12
13
  return process._getActiveHandles().length;
13
14
  }
14
15
  });
@@ -9,6 +9,7 @@ exports.payloadPrefix = 'activeRequests';
9
9
 
10
10
  Object.defineProperty(exports, 'currentPayload', {
11
11
  get: function () {
12
+ // @ts-ignore
12
13
  return process._getActiveRequests().length;
13
14
  }
14
15
  });
@@ -8,14 +8,19 @@
8
8
  const path = require('path');
9
9
  const fs = require('fs');
10
10
 
11
- const applicationUnderMonitoring = require('@instana/core').util.applicationUnderMonitoring;
11
+ const { applicationUnderMonitoring } = require('@instana/core').util;
12
12
 
13
13
  let logger = require('@instana/core').logger.getLogger('metrics');
14
+
15
+ /**
16
+ * @param {import('@instana/core/src/logger').GenericLogger} _logger
17
+ */
14
18
  exports.setLogger = function setLogger(_logger) {
15
19
  logger = _logger;
16
20
  };
17
21
 
18
22
  exports.payloadPrefix = 'dependencies';
23
+ /** @type {Object.<string, *>} */
19
24
  exports.currentPayload = {};
20
25
 
21
26
  const MAX_ATTEMPTS = 20;
@@ -24,7 +29,7 @@ let attempts = 0;
24
29
 
25
30
  exports.activate = function activate() {
26
31
  attempts++;
27
- applicationUnderMonitoring.getMainPackageJsonPath((err, packageJsonPath) => {
32
+ applicationUnderMonitoring.getMainPackageJsonPathStartingAtMainModule((err, packageJsonPath) => {
28
33
  if (err) {
29
34
  return logger.warn('Failed to determine main package.json. Reason: %s %s ', err.message, err.stack);
30
35
  } else if (!packageJsonPath && attempts < MAX_ATTEMPTS) {
@@ -58,6 +63,9 @@ exports.activate = function activate() {
58
63
  });
59
64
  };
60
65
 
66
+ /**
67
+ * @param {string} dependencyDir
68
+ */
61
69
  function addDependenciesFromDir(dependencyDir) {
62
70
  fs.readdir(dependencyDir, (readDirErr, dependencies) => {
63
71
  if (readDirErr) {
@@ -92,6 +100,10 @@ function addDependenciesFromDir(dependencyDir) {
92
100
  });
93
101
  }
94
102
 
103
+ /**
104
+ * @param {*} dependency
105
+ * @param {string} packageJsonPath
106
+ */
95
107
  function addDependency(dependency, packageJsonPath) {
96
108
  fs.readFile(packageJsonPath, { encoding: 'utf8' }, (err, contents) => {
97
109
  if (err && err.code === 'ENOENT') {
@@ -5,14 +5,19 @@
5
5
 
6
6
  'use strict';
7
7
 
8
- const applicationUnderMonitoring = require('@instana/core').util.applicationUnderMonitoring;
8
+ const { applicationUnderMonitoring } = require('@instana/core').util;
9
9
 
10
10
  let logger = require('@instana/core').logger.getLogger('metrics');
11
+
12
+ /**
13
+ * @param {import('@instana/core/src/logger').GenericLogger} _logger
14
+ */
11
15
  exports.setLogger = _logger => {
12
16
  logger = _logger;
13
17
  };
14
18
 
15
19
  exports.payloadPrefix = 'description';
20
+ // @ts-ignore
16
21
  exports.currentPayload = undefined;
17
22
 
18
23
  const MAX_ATTEMPTS = 20;
@@ -21,7 +26,7 @@ let attempts = 0;
21
26
 
22
27
  exports.activate = function activate() {
23
28
  attempts++;
24
- applicationUnderMonitoring.getMainPackageJson((err, packageJson) => {
29
+ applicationUnderMonitoring.getMainPackageJsonStartingAtMainModule((err, packageJson) => {
25
30
  if (err) {
26
31
  return logger.warn('Failed to determine main package json. Reason: ', err.message, err.stack);
27
32
  } else if (!packageJson && attempts < MAX_ATTEMPTS) {
@@ -32,6 +37,7 @@ exports.activate = function activate() {
32
37
  return;
33
38
  }
34
39
 
40
+ // @ts-ignore
35
41
  exports.currentPayload = packageJson.description;
36
42
  });
37
43
  };
@@ -7,14 +7,20 @@
7
7
 
8
8
  const fs = require('fs');
9
9
 
10
- const applicationUnderMonitoring = require('@instana/core').util.applicationUnderMonitoring;
10
+ const { applicationUnderMonitoring } = require('@instana/core').util;
11
11
 
12
12
  let logger = require('@instana/core').logger.getLogger('metrics');
13
+
14
+ /**
15
+ * @param {import('@instana/core/src/logger').GenericLogger} _logger
16
+ */
13
17
  exports.setLogger = function setLogger(_logger) {
14
18
  logger = _logger;
15
19
  };
16
20
 
17
21
  exports.payloadPrefix = 'directDependencies';
22
+
23
+ /** @type {Object.<string, *>} */
18
24
  exports.currentPayload = {
19
25
  dependencies: {},
20
26
  peerDependencies: {},
@@ -27,7 +33,7 @@ let attempts = 0;
27
33
 
28
34
  exports.activate = function activate() {
29
35
  attempts++;
30
- applicationUnderMonitoring.getMainPackageJsonPath((err, packageJsonPath) => {
36
+ applicationUnderMonitoring.getMainPackageJsonPathStartingAtMainModule((err, packageJsonPath) => {
31
37
  if (err) {
32
38
  return logger.info(
33
39
  'Failed to determine main package.json for analysis of direct dependencies. Reason: %s %s ',
@@ -46,6 +52,9 @@ exports.activate = function activate() {
46
52
  });
47
53
  };
48
54
 
55
+ /**
56
+ * @param {string} packageJsonPath
57
+ */
49
58
  function addDirectDependenciesFromMainPackageJson(packageJsonPath) {
50
59
  fs.readFile(packageJsonPath, { encoding: 'utf8' }, (err, contents) => {
51
60
  if (err) {
package/src/gc.js CHANGED
@@ -16,11 +16,22 @@ const incrementalMarkingsWindow = slidingWindow.create(windowOpts);
16
16
  const processWeakCallbacksWindow = slidingWindow.create(windowOpts);
17
17
  const gcPauseWindow = slidingWindow.create(windowOpts);
18
18
 
19
+ /** @type {*} */
19
20
  let gcStats;
20
21
  let activateHasBeenCalled = false;
21
22
  let hasBeenActivated = false;
22
23
 
23
24
  exports.payloadPrefix = 'gc';
25
+
26
+ /** @type {{
27
+ * minorGcs: number
28
+ * majorGcs: number
29
+ * incrementalMarkings: number
30
+ * weakCallbackProcessing: number
31
+ * gcPause: number
32
+ * statsSupported?: boolean
33
+ * usedHeapSizeAfterGc?: number
34
+ * }} */
24
35
  exports.currentPayload = {
25
36
  minorGcs: 0,
26
37
  majorGcs: 0,
@@ -46,6 +57,7 @@ const nativeModuleLoader = require('./util/nativeModuleRetry')({
46
57
  'https://www.instana.com/docs/ecosystem/node-js/installation/#native-addons'
47
58
  });
48
59
 
60
+ /** @type {NodeJS.Timeout} */
49
61
  let senseIntervalHandle;
50
62
 
51
63
  nativeModuleLoader.once('loaded', gcStats_ => {
@@ -65,7 +77,7 @@ function actuallyActivate() {
65
77
  return;
66
78
  }
67
79
  hasBeenActivated = true;
68
- gcStats.on('stats', stats => {
80
+ gcStats.on('stats', (/** @type {*} */ stats) => {
69
81
  // gcstats exposes start and end in nanoseconds
70
82
  const pause = (stats.end - stats.start) / 1000000;
71
83
  gcPauseWindow.addPoint(pause);
@@ -5,27 +5,40 @@
5
5
 
6
6
  'use strict';
7
7
 
8
- const requireHook = require('@instana/core').util.requireHook;
8
+ const { requireHook } = require('@instana/core').util;
9
9
 
10
10
  let logger = require('@instana/core').logger.getLogger('metrics');
11
+
12
+ /**
13
+ * @param {import('@instana/core/src/logger').GenericLogger} _logger
14
+ */
11
15
  exports.setLogger = function setLogger(_logger) {
12
16
  logger = _logger;
13
17
  };
14
18
 
19
+ /** @type {number} */
15
20
  let timeBetweenHealthcheckCalls;
16
21
  const healthy = 1;
17
22
  const unhealthy = 0;
18
23
 
24
+ /** @type {*} */
19
25
  let adminPluginHealthcheck;
26
+ /** @type {NodeJS.Timeout} */
20
27
  let timeoutHandle;
21
28
 
22
29
  exports.payloadPrefix = 'healthchecks';
30
+ // @ts-ignore
23
31
  exports.currentPayload = {};
24
32
 
25
- requireHook.onModuleLoad('admin-plugin-healthcheck', function onAdminPluginHealthcheckLoaded(_adminPluginHealthcheck) {
33
+ requireHook.onModuleLoad('admin-plugin-healthcheck', function onAdminPluginHealthcheckLoaded(
34
+ /** @type {*} */ _adminPluginHealthcheck
35
+ ) {
26
36
  adminPluginHealthcheck = _adminPluginHealthcheck;
27
37
  });
28
38
 
39
+ /**
40
+ * @param {import('@instana/core/src/util/normalizeConfig').InstanaConfig} config
41
+ */
29
42
  exports.activate = function activate(config) {
30
43
  timeBetweenHealthcheckCalls = config.metrics.timeBetweenHealthcheckCalls;
31
44
 
@@ -37,8 +50,10 @@ exports.activate = function activate(config) {
37
50
  function gatherHealthcheckResults() {
38
51
  adminPluginHealthcheck
39
52
  .getHealthCheckResult()
40
- .then(function onHealthcheckResults(adminHealthcheckResults) {
53
+ .then(function onHealthcheckResults(/** @type{*} */ adminHealthcheckResults) {
54
+ /** @type {Object.<string, *>} */
41
55
  const results = {};
56
+ /** @type {Object.<string, *>} */
42
57
  const previousResults = exports.currentPayload;
43
58
 
44
59
  // eslint-disable-next-line no-restricted-syntax
@@ -55,11 +70,13 @@ function gatherHealthcheckResults() {
55
70
  }
56
71
  }
57
72
 
73
+ // @ts-ignore
58
74
  exports.currentPayload = results;
59
75
  timeoutHandle = setTimeout(gatherHealthcheckResults, timeBetweenHealthcheckCalls);
60
76
  timeoutHandle.unref();
61
77
  })
62
- .catch(function onHealthcheckResultFailure(err) {
78
+ .catch(function onHealthcheckResultFailure(/** @type {*} */ err) {
79
+ // @ts-ignore
63
80
  exports.currentPayload = {};
64
81
  logger.warn('Unexpected error while getting healthcheck results', err);
65
82
  timeoutHandle = setTimeout(gatherHealthcheckResults, timeBetweenHealthcheckCalls);
package/src/heapSpaces.js CHANGED
@@ -5,6 +5,7 @@
5
5
 
6
6
  'use strict';
7
7
 
8
+ /** @type {import('v8')} */
8
9
  let v8;
9
10
  try {
10
11
  v8 = require('v8');
@@ -14,8 +15,10 @@ try {
14
15
  }
15
16
 
16
17
  exports.payloadPrefix = 'heapSpaces';
18
+ // @ts-ignore
17
19
  exports.currentPayload = {};
18
20
 
21
+ /** @type {NodeJS.Timeout} */
19
22
  let activeIntervalHandle = null;
20
23
 
21
24
  exports.activate = function activate() {
@@ -32,6 +35,7 @@ function gatherHeapSpaceStatistics() {
32
35
 
33
36
  // We are changing the native format to a format which can be more
34
37
  // efficiently compressed and processed in the backend.
38
+ /** @type {Object.<string, *>} */
35
39
  const processedStats = {};
36
40
 
37
41
  for (let i = 0, len = rawStats.length; i < len; i++) {
@@ -44,10 +48,12 @@ function gatherHeapSpaceStatistics() {
44
48
  };
45
49
  }
46
50
 
51
+ // @ts-ignore
47
52
  exports.currentPayload = processedStats;
48
53
  }
49
54
 
50
55
  exports.deactivate = function deactivate() {
56
+ // @ts-ignore
51
57
  exports.currentPayload = {};
52
58
  if (activeIntervalHandle) {
53
59
  clearInterval(activeIntervalHandle);
package/src/http.js CHANGED
@@ -6,6 +6,7 @@
6
6
  'use strict';
7
7
 
8
8
  exports.payloadPrefix = 'http';
9
+ /** @type {Object.<string, *>} */
9
10
  exports.currentPayload = {};
10
11
 
11
12
  exports.activate = function activate() {};
@@ -14,15 +15,20 @@ exports.deactivate = function deactivate() {};
14
15
  instrumentHttpModule('http');
15
16
  instrumentHttpModule('https');
16
17
 
18
+ /**
19
+ * @param {string} httpModuleName
20
+ */
17
21
  function instrumentHttpModule(httpModuleName) {
18
22
  const coreHttpModule = require(httpModuleName);
19
23
  const originalCreateServer = coreHttpModule.createServer;
20
24
 
21
25
  coreHttpModule.createServer = function createServer() {
22
26
  const server = originalCreateServer.apply(coreHttpModule, arguments);
27
+ /** @type {*} */
23
28
  const payloadContext = {
24
29
  type: httpModuleName
25
30
  };
31
+ /** @type {string} */
26
32
  let key;
27
33
 
28
34
  server.on('listening', () => {
package/src/index.js CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  'use strict';
7
7
 
8
- exports.allMetrics = [
8
+ const allMetrics = [
9
9
  require('./activeHandles'),
10
10
  require('./activeRequests'),
11
11
  require('./args'),
@@ -25,8 +25,25 @@ exports.allMetrics = [
25
25
  require('./version')
26
26
  ];
27
27
 
28
- exports.util = require('./util');
28
+ const util = require('./util');
29
29
 
30
- exports.setLogger = function (logger) {
31
- exports.util.setLogger(logger);
30
+ /**
31
+ * @param {import('@instana/core/src/logger').GenericLogger} logger
32
+ */
33
+ const setLogger = function (logger) {
34
+ util.setLogger(logger);
35
+ };
36
+
37
+ /**
38
+ * @typedef {Object} InstanaSharedMetrics
39
+ * @property {Array.<*>} allMetrics
40
+ * @property {*} util
41
+ * @property {*} setLogger
42
+ */
43
+
44
+ /** @type {InstanaSharedMetrics} */
45
+ module.exports = {
46
+ allMetrics,
47
+ util,
48
+ setLogger
32
49
  };
package/src/keywords.js CHANGED
@@ -5,14 +5,19 @@
5
5
 
6
6
  'use strict';
7
7
 
8
- const applicationUnderMonitoring = require('@instana/core').util.applicationUnderMonitoring;
8
+ const { applicationUnderMonitoring } = require('@instana/core').util;
9
9
 
10
10
  let logger = require('@instana/core').logger.getLogger('metrics');
11
+ /**
12
+ * @param {import('@instana/core/src/logger').GenericLogger} _logger
13
+ */
11
14
  exports.setLogger = function setLogger(_logger) {
12
15
  logger = _logger;
13
16
  };
14
17
 
15
18
  exports.payloadPrefix = 'keywords';
19
+ /** @type {Array.<*>} */
20
+ // @ts-ignore
16
21
  exports.currentPayload = [];
17
22
 
18
23
  const MAX_ATTEMPTS = 20;
@@ -21,7 +26,7 @@ let attempts = 0;
21
26
 
22
27
  exports.activate = function activate() {
23
28
  attempts++;
24
- applicationUnderMonitoring.getMainPackageJson((err, packageJson) => {
29
+ applicationUnderMonitoring.getMainPackageJsonStartingAtMainModule((err, packageJson) => {
25
30
  if (err) {
26
31
  return logger.warn('Failed to determine main package json. Reason: ', err.message, err.stack);
27
32
  } else if (!packageJson && attempts < MAX_ATTEMPTS) {
@@ -33,6 +38,7 @@ exports.activate = function activate() {
33
38
  }
34
39
 
35
40
  if (packageJson.keywords) {
41
+ // @ts-ignore
36
42
  exports.currentPayload = packageJson.keywords;
37
43
  }
38
44
  });
package/src/libuv.js CHANGED
@@ -9,10 +9,10 @@ const path = require('path');
9
9
 
10
10
  const lag = require('event-loop-lag')(1000);
11
11
 
12
+ /** @type {*} */
12
13
  let eventLoopStats;
13
14
 
14
15
  exports.payloadPrefix = 'libuv';
15
- exports.currentPayload = {};
16
16
 
17
17
  const nativeModuleLoader = require('./util/nativeModuleRetry')({
18
18
  nativeModuleName: 'event-loop-stats',
package/src/memory.js CHANGED
@@ -6,8 +6,10 @@
6
6
  'use strict';
7
7
 
8
8
  exports.payloadPrefix = 'memory';
9
+ // @ts-ignore
9
10
  exports.currentPayload = {};
10
11
 
12
+ /** @type {NodeJS.Timer} */
11
13
  let activeIntervalHandle = null;
12
14
 
13
15
  exports.activate = function activate() {
@@ -17,10 +19,12 @@ exports.activate = function activate() {
17
19
  };
18
20
 
19
21
  function gatherMemoryUsageStatistics() {
22
+ // @ts-ignore
20
23
  exports.currentPayload = process.memoryUsage();
21
24
  }
22
25
 
23
26
  exports.deactivate = function deactivate() {
27
+ // @ts-ignore
24
28
  exports.currentPayload = {};
25
29
  if (activeIntervalHandle) {
26
30
  clearInterval(activeIntervalHandle);
package/src/name.js CHANGED
@@ -5,14 +5,19 @@
5
5
 
6
6
  'use strict';
7
7
 
8
- const applicationUnderMonitoring = require('@instana/core').util.applicationUnderMonitoring;
8
+ const { applicationUnderMonitoring } = require('@instana/core').util;
9
9
 
10
10
  let logger = require('@instana/core').logger.getLogger('metrics');
11
+
12
+ /**
13
+ * @param {import('@instana/core/src/logger').GenericLogger} _logger
14
+ */
11
15
  exports.setLogger = function setLogger(_logger) {
12
16
  logger = _logger;
13
17
  };
14
18
 
15
19
  exports.payloadPrefix = 'name';
20
+ // @ts-ignore
16
21
  exports.currentPayload = undefined;
17
22
 
18
23
  const MAX_ATTEMPTS = 60;
@@ -21,7 +26,7 @@ let attempts = 0;
21
26
 
22
27
  exports.activate = function activate() {
23
28
  attempts++;
24
- applicationUnderMonitoring.getMainPackageJson((err, packageJson) => {
29
+ applicationUnderMonitoring.getMainPackageJsonStartingAtMainModule((err, packageJson) => {
25
30
  if (err) {
26
31
  return logger.warn('Failed to determine main package json. Reason: ', err.message, err.stack);
27
32
  } else if (!packageJson && attempts < MAX_ATTEMPTS) {
@@ -30,6 +35,7 @@ exports.activate = function activate() {
30
35
  return;
31
36
  } else if (!packageJson) {
32
37
  if (process.mainModule) {
38
+ // @ts-ignore
33
39
  exports.currentPayload = process.mainModule.filename;
34
40
  }
35
41
  return logger.warn(
@@ -39,6 +45,7 @@ exports.activate = function activate() {
39
45
  );
40
46
  }
41
47
 
48
+ // @ts-ignore
42
49
  exports.currentPayload = packageJson.name;
43
50
  });
44
51
  };
package/src/util/index.js CHANGED
@@ -5,9 +5,13 @@
5
5
 
6
6
  'use strict';
7
7
 
8
- module.exports = exports = {
9
- nativeModuleRetry: require('./nativeModuleRetry'),
8
+ const nativeModuleRetry = require('./nativeModuleRetry');
9
+ module.exports = {
10
+ nativeModuleRetry,
11
+ /**
12
+ * @param {import('@instana/core/src/logger').GenericLogger} logger
13
+ */
10
14
  setLogger: function setLogger(logger) {
11
- exports.nativeModuleRetry.setLogger(logger);
15
+ nativeModuleRetry.setLogger(logger);
12
16
  }
13
17
  };
@@ -16,6 +16,17 @@ const tar = require('tar');
16
16
  const { fork } = require('child_process');
17
17
  const detectLibc = require('detect-libc');
18
18
 
19
+ /**
20
+ * @typedef {Object} InstanaSharedMetricsOptions
21
+ * @property {string} [nativeModuleName]
22
+ * @property {string} [nativeModulePath]
23
+ * @property {string} [nativeModuleParentPath]
24
+ * @property {string} [moduleRoot]
25
+ * @property {string} [message]
26
+ * @property {string} [loadFrom]
27
+ */
28
+
29
+ /** @type {Array.<string>} */
19
30
  const retryMechanisms = [];
20
31
  if (
21
32
  !process.env.INSTANA_COPY_PRECOMPILED_NATIVE_ADDONS ||
@@ -40,6 +51,10 @@ if (!family) {
40
51
 
41
52
  class ModuleLoadEmitter extends EventEmitter {}
42
53
 
54
+ /**
55
+ * @param {InstanaSharedMetricsOptions} opts
56
+ * @returns {ModuleLoadEmitter}
57
+ */
43
58
  function loadNativeAddOn(opts) {
44
59
  const loaderEmitter = new ModuleLoadEmitter();
45
60
  // Give clients a chance to register event listeners on the emitter that we return by attempting to load the module
@@ -49,6 +64,13 @@ function loadNativeAddOn(opts) {
49
64
  return loaderEmitter;
50
65
  }
51
66
 
67
+ /**
68
+ * @param {InstanaSharedMetricsOptions} opts
69
+ * @param {EventEmitter} loaderEmitter
70
+ * @param {number} retryIndex
71
+ * @param {boolean} skipAttempt
72
+ * @returns
73
+ */
52
74
  function loadNativeAddOnInternal(opts, loaderEmitter, retryIndex, skipAttempt) {
53
75
  try {
54
76
  const { isMainThread } = require('worker_threads');
@@ -80,6 +102,11 @@ function loadNativeAddOnInternal(opts, loaderEmitter, retryIndex, skipAttempt) {
80
102
  }
81
103
  }
82
104
 
105
+ /**
106
+ * @param {InstanaSharedMetricsOptions} opts
107
+ * @param {EventEmitter} loaderEmitter
108
+ * @param {number} retryIndex
109
+ */
83
110
  function prepareNextRetry(opts, loaderEmitter, retryIndex) {
84
111
  // The first pre-condition for all retry mechanisms is that we can find the path to the native add-on that can not be
85
112
  // required.
@@ -109,6 +136,11 @@ function prepareNextRetry(opts, loaderEmitter, retryIndex) {
109
136
  }
110
137
  }
111
138
 
139
+ /**
140
+ * @param {InstanaSharedMetricsOptions} opts
141
+ * @param {EventEmitter} loaderEmitter
142
+ * @param {number} retryIndex
143
+ */
112
144
  function copyPrecompiled(opts, loaderEmitter, retryIndex) {
113
145
  logger.debug(`Trying to copy precompiled version of ${opts.nativeModuleName} for Node.js ${process.version}.`);
114
146
 
@@ -149,15 +181,11 @@ function copyPrecompiled(opts, loaderEmitter, retryIndex) {
149
181
  cwd: os.tmpdir(),
150
182
  file: precompiledTarGzPath
151
183
  })
152
- .then(tarErr => {
153
- if (tarErr) {
154
- logger.warn(`Unpacking the precompiled build for ${opts.nativeModuleName} ${label} failed.`, tarErr);
155
- process.nextTick(loadNativeAddOnInternal.bind(null, opts, loaderEmitter, ++retryIndex, true));
156
- return;
157
- }
158
-
184
+ .then(() => {
159
185
  // See below for the reason why we append 'precompiled' to the path.
160
186
  const targetDir = path.join(opts.nativeModulePath, 'precompiled');
187
+
188
+ // @ts-ignore
161
189
  copy(
162
190
  path.join(os.tmpdir(), opts.nativeModuleName),
163
191
  targetDir,
@@ -165,6 +193,7 @@ function copyPrecompiled(opts, loaderEmitter, retryIndex) {
165
193
  overwrite: true,
166
194
  dot: true
167
195
  },
196
+ // @ts-ignore
168
197
  cpErr => {
169
198
  if (cpErr) {
170
199
  logger.warn(`Copying the precompiled build for ${opts.nativeModuleName} ${label} failed.`, cpErr);
@@ -187,15 +216,26 @@ function copyPrecompiled(opts, loaderEmitter, retryIndex) {
187
216
  process.nextTick(loadNativeAddOnInternal.bind(null, opts, loaderEmitter, ++retryIndex));
188
217
  }
189
218
  );
219
+ })
220
+ .catch(tarErr => {
221
+ logger.warn(`Unpacking the precompiled build for ${opts.nativeModuleName} ${label} failed.`, tarErr);
222
+ process.nextTick(loadNativeAddOnInternal.bind(null, opts, loaderEmitter, ++retryIndex, true));
190
223
  });
191
224
  });
192
225
  }
193
226
 
194
- // This is mainly for the scenario where @instana/collector and its dependencies has been provided by an external
195
- // mechanism (like copying a bundled version contained in the Instana agent package) without running an npm install on
196
- // the target system. Native addons are present, but might have been build for a different operating system/Node ABI,
197
- // libc familiy, ...). Thus, they need to be rebuilt.
227
+ /**
228
+ * This is mainly for the scenario where @instana/collector and its dependencies has been provided by an external
229
+ * mechanism (like copying a bundled version contained in the Instana agent package) without running an npm install on
230
+ * the target system. Native addons are present, but might have been build for a different operating system/Node ABI,
231
+ * libc familiy, ...). Thus, they need to be rebuilt.
232
+ *
233
+ * @param {InstanaSharedMetricsOptions} opts
234
+ * @param {EventEmitter} loaderEmitter
235
+ * @param {number} retryIndex
236
+ */
198
237
  function rebuildOnDemand(opts, loaderEmitter, retryIndex) {
238
+ /** @type {string} */
199
239
  let nodeGypExecutable;
200
240
  try {
201
241
  const nodeGypPath = require.resolve('node-gyp');
@@ -245,6 +285,9 @@ function rebuildOnDemand(opts, loaderEmitter, retryIndex) {
245
285
  });
246
286
  }
247
287
 
288
+ /**
289
+ * @param {InstanaSharedMetricsOptions} opts
290
+ */
248
291
  function findNativeModulePath(opts) {
249
292
  try {
250
293
  // Let's first check if there is at least a module directory in node_modules:
@@ -275,11 +318,14 @@ function findNativeModulePath(opts) {
275
318
  }
276
319
  }
277
320
 
321
+ /**
322
+ * @param {InstanaSharedMetricsOptions} opts
323
+ */
278
324
  function createNativeModulePath(opts) {
279
325
  // The module cannot be found at all in node_modules. This can happen for example if npm install --no-optional was
280
326
  // used but also if building the native add-on with node-gyp failed. We will try to reconstruct a path that makes
281
327
  // sense.
282
- if (!exports.selfNodeModulesPath) {
328
+ if (!loadNativeAddOn.selfNodeModulesPath) {
283
329
  const selfPath = path.join(__dirname, '..', '..');
284
330
  const idx = selfPath.lastIndexOf('node_modules');
285
331
  if (idx < 0) {
@@ -291,16 +337,22 @@ function createNativeModulePath(opts) {
291
337
 
292
338
  // cut off everything after module path
293
339
  const selfPathNormalized = selfPath.substring(0, idx + 'node_modules'.length + __dirname.length + 2);
294
- exports.selfNodeModulesPath = path.join(selfPathNormalized, '..', '..');
340
+ loadNativeAddOn.selfNodeModulesPath = path.join(selfPathNormalized, '..', '..');
295
341
  }
296
342
  // Find nearest ancestor node_modules directory. Since we use a scoped module (@instana/something) as the reference
297
343
  // we need to go up two directory levels.
298
- opts.nativeModuleParentPath = exports.selfNodeModulesPath;
299
- opts.nativeModulePath = path.join(exports.selfNodeModulesPath, opts.nativeModuleName);
344
+ opts.nativeModuleParentPath = loadNativeAddOn.selfNodeModulesPath;
345
+ opts.nativeModulePath = path.join(loadNativeAddOn.selfNodeModulesPath, opts.nativeModuleName);
300
346
  }
301
347
 
302
- module.exports = exports = loadNativeAddOn;
348
+ loadNativeAddOn.setLogger = setLogger;
349
+ loadNativeAddOn.selfNodeModulesPath = '';
303
350
 
304
- exports.setLogger = function setLogger(_logger) {
351
+ /**
352
+ * @param {import('@instana/core/src/logger').GenericLogger} _logger
353
+ */
354
+ function setLogger(_logger) {
305
355
  logger = _logger;
306
- };
356
+ }
357
+
358
+ module.exports = loadNativeAddOn;
package/src/version.js CHANGED
@@ -5,14 +5,18 @@
5
5
 
6
6
  'use strict';
7
7
 
8
- const applicationUnderMonitoring = require('@instana/core').util.applicationUnderMonitoring;
8
+ const { applicationUnderMonitoring } = require('@instana/core').util;
9
9
 
10
10
  let logger = require('@instana/core').logger.getLogger('metrics');
11
+ /**
12
+ * @param {import('@instana/core/src/logger').GenericLogger} _logger
13
+ */
11
14
  exports.setLogger = function setLogger(_logger) {
12
15
  logger = _logger;
13
16
  };
14
17
 
15
18
  exports.payloadPrefix = 'version';
19
+ // @ts-ignore
16
20
  exports.currentPayload = undefined;
17
21
 
18
22
  const MAX_ATTEMPTS = 20;
@@ -21,7 +25,7 @@ let attempts = 0;
21
25
 
22
26
  exports.activate = function activate() {
23
27
  attempts++;
24
- applicationUnderMonitoring.getMainPackageJson((err, packageJson) => {
28
+ applicationUnderMonitoring.getMainPackageJsonStartingAtMainModule((err, packageJson) => {
25
29
  if (err) {
26
30
  return logger.warn('Failed to determine main package json. Reason: ', err.message, err.stack);
27
31
  } else if (!packageJson && attempts < MAX_ATTEMPTS) {
@@ -32,6 +36,7 @@ exports.activate = function activate() {
32
36
  return;
33
37
  }
34
38
 
39
+ // @ts-ignore
35
40
  exports.currentPayload = packageJson.version;
36
41
  });
37
42
  };