@depup/elastic-apm-node 4.15.0-depup.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.
Files changed (154) hide show
  1. package/LICENSE +26 -0
  2. package/NOTICE.md +442 -0
  3. package/README.md +48 -0
  4. package/changes.json +78 -0
  5. package/index.d.ts +398 -0
  6. package/index.js +11 -0
  7. package/lib/InflightEventSet.js +53 -0
  8. package/lib/activation-method.js +119 -0
  9. package/lib/agent.js +941 -0
  10. package/lib/apm-client/apm-client.js +313 -0
  11. package/lib/apm-client/http-apm-client/CHANGELOG.md +271 -0
  12. package/lib/apm-client/http-apm-client/README.md +485 -0
  13. package/lib/apm-client/http-apm-client/central-config.js +41 -0
  14. package/lib/apm-client/http-apm-client/container-info.js +111 -0
  15. package/lib/apm-client/http-apm-client/detect-hostname.js +96 -0
  16. package/lib/apm-client/http-apm-client/index.js +1975 -0
  17. package/lib/apm-client/http-apm-client/logging.js +31 -0
  18. package/lib/apm-client/http-apm-client/ndjson.js +20 -0
  19. package/lib/apm-client/http-apm-client/truncate.js +434 -0
  20. package/lib/apm-client/noop-apm-client.js +73 -0
  21. package/lib/async-hooks-polyfill.js +58 -0
  22. package/lib/cloud-metadata/aws.js +175 -0
  23. package/lib/cloud-metadata/azure.js +123 -0
  24. package/lib/cloud-metadata/callback-coordination.js +159 -0
  25. package/lib/cloud-metadata/gcp.js +133 -0
  26. package/lib/cloud-metadata/index.js +175 -0
  27. package/lib/config/config.js +458 -0
  28. package/lib/config/normalizers.js +701 -0
  29. package/lib/config/schema.js +1007 -0
  30. package/lib/constants.js +35 -0
  31. package/lib/errors.js +303 -0
  32. package/lib/filters/sanitize-field-names.js +69 -0
  33. package/lib/http-request.js +249 -0
  34. package/lib/instrumentation/azure-functions.js +519 -0
  35. package/lib/instrumentation/context.js +56 -0
  36. package/lib/instrumentation/dropped-spans-stats.js +112 -0
  37. package/lib/instrumentation/elasticsearch-shared.js +63 -0
  38. package/lib/instrumentation/express-utils.js +91 -0
  39. package/lib/instrumentation/generic-span.js +322 -0
  40. package/lib/instrumentation/http-shared.js +424 -0
  41. package/lib/instrumentation/ids.js +39 -0
  42. package/lib/instrumentation/index.js +1127 -0
  43. package/lib/instrumentation/modules/@apollo/server.js +30 -0
  44. package/lib/instrumentation/modules/@aws-sdk/client-dynamodb.js +143 -0
  45. package/lib/instrumentation/modules/@aws-sdk/client-s3.js +230 -0
  46. package/lib/instrumentation/modules/@aws-sdk/client-sns.js +197 -0
  47. package/lib/instrumentation/modules/@aws-sdk/client-sqs.js +336 -0
  48. package/lib/instrumentation/modules/@elastic/elasticsearch.js +343 -0
  49. package/lib/instrumentation/modules/@hapi/hapi.js +221 -0
  50. package/lib/instrumentation/modules/@opentelemetry/api.js +86 -0
  51. package/lib/instrumentation/modules/@opentelemetry/sdk-metrics.js +79 -0
  52. package/lib/instrumentation/modules/@redis/client/dist/lib/client/commands-queue.js +178 -0
  53. package/lib/instrumentation/modules/@redis/client/dist/lib/client/index.js +49 -0
  54. package/lib/instrumentation/modules/@smithy/smithy-client.js +198 -0
  55. package/lib/instrumentation/modules/_lambda-handler.js +40 -0
  56. package/lib/instrumentation/modules/apollo-server-core.js +49 -0
  57. package/lib/instrumentation/modules/aws-sdk/dynamodb.js +155 -0
  58. package/lib/instrumentation/modules/aws-sdk/s3.js +184 -0
  59. package/lib/instrumentation/modules/aws-sdk/sns.js +232 -0
  60. package/lib/instrumentation/modules/aws-sdk/sqs.js +361 -0
  61. package/lib/instrumentation/modules/aws-sdk.js +76 -0
  62. package/lib/instrumentation/modules/bluebird.js +93 -0
  63. package/lib/instrumentation/modules/cassandra-driver.js +280 -0
  64. package/lib/instrumentation/modules/elasticsearch.js +191 -0
  65. package/lib/instrumentation/modules/express-graphql.js +66 -0
  66. package/lib/instrumentation/modules/express-queue.js +28 -0
  67. package/lib/instrumentation/modules/express.js +162 -0
  68. package/lib/instrumentation/modules/fastify.js +172 -0
  69. package/lib/instrumentation/modules/finalhandler.js +41 -0
  70. package/lib/instrumentation/modules/generic-pool.js +85 -0
  71. package/lib/instrumentation/modules/graphql.js +256 -0
  72. package/lib/instrumentation/modules/handlebars.js +22 -0
  73. package/lib/instrumentation/modules/http.js +112 -0
  74. package/lib/instrumentation/modules/http2.js +320 -0
  75. package/lib/instrumentation/modules/https.js +68 -0
  76. package/lib/instrumentation/modules/ioredis.js +94 -0
  77. package/lib/instrumentation/modules/jade.js +18 -0
  78. package/lib/instrumentation/modules/kafkajs.js +476 -0
  79. package/lib/instrumentation/modules/knex.js +91 -0
  80. package/lib/instrumentation/modules/koa-router.js +74 -0
  81. package/lib/instrumentation/modules/koa.js +15 -0
  82. package/lib/instrumentation/modules/memcached.js +99 -0
  83. package/lib/instrumentation/modules/mimic-response.js +45 -0
  84. package/lib/instrumentation/modules/mongodb/lib/cmap/connection_pool.js +40 -0
  85. package/lib/instrumentation/modules/mongodb-core.js +206 -0
  86. package/lib/instrumentation/modules/mongodb.js +259 -0
  87. package/lib/instrumentation/modules/mysql.js +200 -0
  88. package/lib/instrumentation/modules/mysql2.js +140 -0
  89. package/lib/instrumentation/modules/pg.js +148 -0
  90. package/lib/instrumentation/modules/pug.js +18 -0
  91. package/lib/instrumentation/modules/redis.js +176 -0
  92. package/lib/instrumentation/modules/restify.js +52 -0
  93. package/lib/instrumentation/modules/tedious.js +159 -0
  94. package/lib/instrumentation/modules/undici.js +270 -0
  95. package/lib/instrumentation/modules/ws.js +59 -0
  96. package/lib/instrumentation/noop-transaction.js +81 -0
  97. package/lib/instrumentation/run-context/AbstractRunContextManager.js +215 -0
  98. package/lib/instrumentation/run-context/AsyncHooksRunContextManager.js +106 -0
  99. package/lib/instrumentation/run-context/AsyncLocalStorageRunContextManager.js +73 -0
  100. package/lib/instrumentation/run-context/BasicRunContextManager.js +82 -0
  101. package/lib/instrumentation/run-context/RunContext.js +151 -0
  102. package/lib/instrumentation/run-context/index.js +23 -0
  103. package/lib/instrumentation/shimmer.js +123 -0
  104. package/lib/instrumentation/span-compression.js +239 -0
  105. package/lib/instrumentation/span.js +621 -0
  106. package/lib/instrumentation/template-shared.js +43 -0
  107. package/lib/instrumentation/timer.js +84 -0
  108. package/lib/instrumentation/transaction.js +571 -0
  109. package/lib/lambda.js +992 -0
  110. package/lib/load-source-map.js +100 -0
  111. package/lib/logging.js +212 -0
  112. package/lib/metrics/index.js +92 -0
  113. package/lib/metrics/platforms/generic/index.js +40 -0
  114. package/lib/metrics/platforms/generic/process-cpu.js +22 -0
  115. package/lib/metrics/platforms/generic/process-top.js +157 -0
  116. package/lib/metrics/platforms/generic/stats.js +34 -0
  117. package/lib/metrics/platforms/generic/system-cpu.js +51 -0
  118. package/lib/metrics/platforms/linux/index.js +19 -0
  119. package/lib/metrics/platforms/linux/stats.js +213 -0
  120. package/lib/metrics/queue.js +90 -0
  121. package/lib/metrics/registry.js +52 -0
  122. package/lib/metrics/reporter.js +119 -0
  123. package/lib/metrics/runtime.js +77 -0
  124. package/lib/middleware/connect.js +16 -0
  125. package/lib/opentelemetry-bridge/OTelBridgeNonRecordingSpan.js +150 -0
  126. package/lib/opentelemetry-bridge/OTelBridgeRunContext.js +124 -0
  127. package/lib/opentelemetry-bridge/OTelContextManager.js +82 -0
  128. package/lib/opentelemetry-bridge/OTelSpan.js +344 -0
  129. package/lib/opentelemetry-bridge/OTelTracer.js +201 -0
  130. package/lib/opentelemetry-bridge/OTelTracerProvider.js +25 -0
  131. package/lib/opentelemetry-bridge/README.md +244 -0
  132. package/lib/opentelemetry-bridge/index.js +15 -0
  133. package/lib/opentelemetry-bridge/oblog.js +23 -0
  134. package/lib/opentelemetry-bridge/opentelemetry-core-mini/README.md +3 -0
  135. package/lib/opentelemetry-bridge/opentelemetry-core-mini/internal/validators.js +52 -0
  136. package/lib/opentelemetry-bridge/opentelemetry-core-mini/trace/TraceState.js +109 -0
  137. package/lib/opentelemetry-bridge/otelutils.js +99 -0
  138. package/lib/opentelemetry-bridge/setup.js +76 -0
  139. package/lib/opentelemetry-metrics/ElasticApmMetricExporter.js +285 -0
  140. package/lib/opentelemetry-metrics/index.js +50 -0
  141. package/lib/parsers.js +225 -0
  142. package/lib/propwrap.js +147 -0
  143. package/lib/stacktraces.js +537 -0
  144. package/lib/symbols.js +15 -0
  145. package/lib/tracecontext/index.js +118 -0
  146. package/lib/tracecontext/traceparent.js +185 -0
  147. package/lib/tracecontext/tracestate.js +388 -0
  148. package/lib/wildcard-matcher.js +52 -0
  149. package/loader.mjs +7 -0
  150. package/package.json +299 -0
  151. package/start.d.ts +8 -0
  152. package/start.js +29 -0
  153. package/types/aws-lambda.d.ts +98 -0
  154. package/types/connect.d.ts +23 -0
package/lib/agent.js ADDED
@@ -0,0 +1,941 @@
1
+ /*
2
+ * Copyright Elasticsearch B.V. and other contributors where applicable.
3
+ * Licensed under the BSD 2-Clause License; you may not use this file except in
4
+ * compliance with the BSD 2-Clause License.
5
+ */
6
+
7
+ 'use strict';
8
+
9
+ const http = require('http');
10
+ const path = require('path');
11
+
12
+ const isError = require('core-util-is').isError;
13
+ const Filters = require('object-filter-sequence');
14
+
15
+ const { agentActivationMethodFromStartStack } = require('./activation-method');
16
+ const {
17
+ CAPTURE_ERROR_LOG_STACK_TRACES_ALWAYS,
18
+ CAPTURE_ERROR_LOG_STACK_TRACES_MESSAGES,
19
+ } = require('./constants');
20
+ const config = require('./config/config');
21
+ const connect = require('./middleware/connect');
22
+ const constants = require('./constants');
23
+ const errors = require('./errors');
24
+ const { InflightEventSet } = require('./InflightEventSet');
25
+ const { Instrumentation } = require('./instrumentation');
26
+ const { elasticApmAwsLambda } = require('./lambda');
27
+ const logging = require('./logging');
28
+ const Metrics = require('./metrics');
29
+ const parsers = require('./parsers');
30
+ const symbols = require('./symbols');
31
+ const { frameCacheStats, initStackTraceCollection } = require('./stacktraces');
32
+ const Span = require('./instrumentation/span');
33
+ const Transaction = require('./instrumentation/transaction');
34
+ const {
35
+ isOTelMetricsFeatSupported,
36
+ createOTelMeterProvider,
37
+ } = require('./opentelemetry-metrics');
38
+ const { createApmClient } = require('./apm-client/apm-client');
39
+
40
+ const IncomingMessage = http.IncomingMessage;
41
+ const ServerResponse = http.ServerResponse;
42
+
43
+ const version = require('../package').version;
44
+
45
+ // ---- Agent
46
+
47
+ module.exports = Agent;
48
+
49
+ function Agent() {
50
+ // Early configuration to ensure `agent.logger` works before `agent.start()`.
51
+ this.logger = config.configLogger();
52
+
53
+ // Get an initial pre-.start() configuration of agent defaults. This is a
54
+ // crutch for Agent APIs that depend on `agent._conf`.
55
+ this._conf = config.initialConfig(this.logger);
56
+
57
+ this._httpClient = null;
58
+ this._uncaughtExceptionListener = null;
59
+ this._inflightEvents = new InflightEventSet();
60
+ this._instrumentation = new Instrumentation(this);
61
+ this._metrics = new Metrics(this);
62
+ this._otelMeterProvider = null;
63
+ this._errorFilters = new Filters();
64
+ this._transactionFilters = new Filters();
65
+ this._spanFilters = new Filters();
66
+ this._apmClient = null;
67
+
68
+ this.lambda = elasticApmAwsLambda(this);
69
+ this.middleware = { connect: connect.bind(this) };
70
+ }
71
+
72
+ Object.defineProperty(Agent.prototype, 'currentTransaction', {
73
+ get() {
74
+ return this._instrumentation.currTransaction();
75
+ },
76
+ });
77
+
78
+ Object.defineProperty(Agent.prototype, 'currentSpan', {
79
+ get() {
80
+ return this._instrumentation.currSpan();
81
+ },
82
+ });
83
+
84
+ Object.defineProperty(Agent.prototype, 'currentTraceparent', {
85
+ get() {
86
+ const current =
87
+ this._instrumentation.currSpan() ||
88
+ this._instrumentation.currTransaction();
89
+ return current ? current.traceparent : null;
90
+ },
91
+ });
92
+
93
+ Object.defineProperty(Agent.prototype, 'currentTraceIds', {
94
+ get() {
95
+ return this._instrumentation.ids();
96
+ },
97
+ });
98
+
99
+ // Destroy this agent. This prevents any new agent processing, communication
100
+ // with APM server, and resets changed global state *as much as is possible*.
101
+ //
102
+ // In the typical uses case -- a singleton Agent running for the full process
103
+ // lifetime -- it is *not* necessary to call `agent.destroy()`. It is used
104
+ // for some testing.
105
+ //
106
+ // Limitations:
107
+ // - Patching/wrapping of functions for instrumentation *is* undone, but
108
+ // references to the wrapped versions can remain.
109
+ // - There may be in-flight tasks (in ins.addEndedSpan() and
110
+ // agent.captureError() for example) that will complete after this destroy
111
+ // completes. They should have no impact other than CPU/resource use.
112
+ Agent.prototype.destroy = async function () {
113
+ if (this._otelMeterProvider) {
114
+ // This will call `Agent#flush()`.
115
+ try {
116
+ await this._otelMeterProvider.shutdown({ timeoutMillis: 1000 });
117
+ } catch (reason) {
118
+ this.logger.warn('failed to shutdown OTel MeterProvider:', reason);
119
+ }
120
+ this._otelMeterProvider = null;
121
+ }
122
+
123
+ if (this._apmClient && this._apmClient.destroy) {
124
+ this._apmClient.destroy();
125
+ }
126
+ // So in-flight tasks in ins.addEndedSpan() and agent.captureError() do
127
+ // not use the destroyed transport.
128
+ this._apmClient = null;
129
+
130
+ // So in-flight tasks do not call user-added filters after the agent has
131
+ // been destroyed.
132
+ this._errorFilters = new Filters();
133
+ this._transactionFilters = new Filters();
134
+ this._spanFilters = new Filters();
135
+
136
+ if (this._uncaughtExceptionListener) {
137
+ process.removeListener(
138
+ 'uncaughtException',
139
+ this._uncaughtExceptionListener,
140
+ );
141
+ }
142
+ this._metrics.stop();
143
+ this._instrumentation.stop();
144
+
145
+ // Allow a new Agent instance to `.start()`. Typically this is only relevant
146
+ // for tests that may use multiple Agent instances in a single test process.
147
+ global[symbols.agentInitialized] = null;
148
+
149
+ if (
150
+ this._origStackTraceLimit &&
151
+ Error.stackTraceLimit !== this._origStackTraceLimit
152
+ ) {
153
+ Error.stackTraceLimit = this._origStackTraceLimit;
154
+ }
155
+ };
156
+
157
+ // These are metrics about the agent itself -- separate from the metrics
158
+ // gathered on behalf of the using app and sent to APM server. Currently these
159
+ // are only useful for internal debugging of the APM agent itself.
160
+ //
161
+ // **These stats are NOT a promised interface.**
162
+ Agent.prototype._getStats = function () {
163
+ const stats = {
164
+ frameCache: frameCacheStats,
165
+ };
166
+ if (
167
+ this._instrumentation._runCtxMgr &&
168
+ this._instrumentation._runCtxMgr._runContextFromAsyncId
169
+ ) {
170
+ stats.runContextFromAsyncIdSize =
171
+ this._instrumentation._runCtxMgr._runContextFromAsyncId.size;
172
+ }
173
+ if (this._apmClient && typeof this._apmClient._getStats === 'function') {
174
+ stats.apmclient = this._apmClient._getStats();
175
+ }
176
+ return stats;
177
+ };
178
+
179
+ Agent.prototype.addPatch = function (modules, handler) {
180
+ return this._instrumentation.addPatch.apply(this._instrumentation, arguments);
181
+ };
182
+
183
+ Agent.prototype.removePatch = function (modules, handler) {
184
+ return this._instrumentation.removePatch.apply(
185
+ this._instrumentation,
186
+ arguments,
187
+ );
188
+ };
189
+
190
+ Agent.prototype.clearPatches = function (modules) {
191
+ return this._instrumentation.clearPatches.apply(
192
+ this._instrumentation,
193
+ arguments,
194
+ );
195
+ };
196
+
197
+ Agent.prototype.startTransaction = function (
198
+ name,
199
+ type,
200
+ { startTime, childOf } = {},
201
+ ) {
202
+ return this._instrumentation.startTransaction.apply(
203
+ this._instrumentation,
204
+ arguments,
205
+ );
206
+ };
207
+
208
+ Agent.prototype.endTransaction = function (result, endTime) {
209
+ return this._instrumentation.endTransaction.apply(
210
+ this._instrumentation,
211
+ arguments,
212
+ );
213
+ };
214
+
215
+ Agent.prototype.setTransactionName = function (name) {
216
+ return this._instrumentation.setTransactionName.apply(
217
+ this._instrumentation,
218
+ arguments,
219
+ );
220
+ };
221
+
222
+ /**
223
+ * Sets outcome value for current transaction
224
+ *
225
+ * The setOutcome method allows users to override the default
226
+ * outcome handling in the agent and set their own value.
227
+ *
228
+ * @param {string} outcome must be one of `failure`, `success`, or `unknown`
229
+ */
230
+ Agent.prototype.setTransactionOutcome = function (outcome) {
231
+ return this._instrumentation.setTransactionOutcome.apply(
232
+ this._instrumentation,
233
+ arguments,
234
+ );
235
+ };
236
+
237
+ Agent.prototype.startSpan = function (
238
+ name,
239
+ type,
240
+ subtype,
241
+ action,
242
+ { startTime, childOf, exitSpan } = {},
243
+ ) {
244
+ return this._instrumentation.startSpan.apply(
245
+ this._instrumentation,
246
+ arguments,
247
+ );
248
+ };
249
+
250
+ /**
251
+ * Sets outcome value for current active span
252
+ *
253
+ * The setOutcome method allows users to override the default
254
+ * outcome handling in the agent and set their own value.
255
+ *
256
+ * @param {string} outcome must be one of `failure`, `success`, or `unknown`
257
+ */
258
+ Agent.prototype.setSpanOutcome = function (outcome) {
259
+ return this._instrumentation.setSpanOutcome.apply(
260
+ this._instrumentation,
261
+ arguments,
262
+ );
263
+ };
264
+
265
+ Agent.prototype._config = function (opts) {
266
+ this._conf = config.createConfig(opts, this.logger);
267
+ this.logger = this._conf.logger;
268
+ };
269
+
270
+ Agent.prototype.isStarted = function () {
271
+ return global[symbols.agentInitialized];
272
+ };
273
+
274
+ Agent.prototype.start = function (opts) {
275
+ if (this.isStarted()) {
276
+ throw new Error('Do not call .start() more than once');
277
+ }
278
+ global[symbols.agentInitialized] = true;
279
+
280
+ this._config(opts);
281
+
282
+ if (!this._conf.active) {
283
+ this.logger.debug('Elastic APM agent disabled (`active` is false)');
284
+ return this;
285
+ }
286
+
287
+ // Log preamble showing agent, environment and config relevant info
288
+ const preambleData = this._conf.loggingPreambleData;
289
+ const isPreviewVersion = version.indexOf('-') !== -1;
290
+ const startStack = {};
291
+
292
+ if (this._conf.active && this._conf.serviceName) {
293
+ this._origStackTraceLimit = Error.stackTraceLimit;
294
+ Error.stackTraceLimit = 20; // require more than default 10 for `agentActivationMethodFromStartStack()`
295
+ Error.captureStackTrace(startStack);
296
+ Error.stackTraceLimit = this._origStackTraceLimit;
297
+ this._agentActivationMethod = agentActivationMethodFromStartStack(
298
+ startStack,
299
+ this.logger,
300
+ );
301
+ preambleData.activationMethod = this._agentActivationMethod;
302
+
303
+ if (this._conf.logLevel === 'trace') {
304
+ // Attempt to load package.json from process.argv.
305
+ let pkg = null;
306
+ try {
307
+ var basedir = path.dirname(process.argv[1] || '.');
308
+ pkg = require(path.join(basedir, 'package.json'));
309
+ } catch (e) {}
310
+
311
+ // Add stack & dependencies for extra information
312
+ preambleData.dependencies = pkg
313
+ ? pkg.dependencies
314
+ : '<could not determine>';
315
+ preambleData.startTrace = startStack.stack.split(/\n */).slice(1);
316
+ }
317
+ }
318
+
319
+ this.logger.info(preambleData, 'Elastic APM Node.js Agent v%s', version);
320
+
321
+ if (!logging.isLoggerCustom(this.logger)) {
322
+ // Periodically dump the current config (delta from defaults) when logging
323
+ // at "trace"-level. This allows getting the effective config from a running
324
+ // agent by setting trace-level logging and getting 1 minute of logs.
325
+ // (Sometimes getting logs from application *start* is no possible.)
326
+ setInterval(() => {
327
+ if (this.logger.isLevelEnabled('trace')) {
328
+ try {
329
+ const currConfig = this._conf.getCurrConfig();
330
+ this.logger.trace({ currConfig }, 'currConfig');
331
+ } catch (err) {
332
+ this.logger.trace({ err }, 'error calculating currConfig');
333
+ }
334
+ }
335
+ }, 60 * 1000).unref();
336
+ }
337
+
338
+ if (isPreviewVersion) {
339
+ this.logger.warn(
340
+ 'Version %s is a pre-release and not intended for use in production environments',
341
+ version,
342
+ );
343
+ }
344
+
345
+ if (!this._conf.serverUrl) {
346
+ this.logger.error(
347
+ 'Elastic APM is incorrectly configured: Invalid serverUrl (APM will be disabled)',
348
+ );
349
+ this._conf.active = false;
350
+ return this;
351
+ }
352
+
353
+ if (!this._conf.serviceName) {
354
+ this.logger.error(
355
+ 'Elastic APM is incorrectly configured: Missing serviceName (APM will be disabled)',
356
+ );
357
+ this._conf.active = false;
358
+ return this;
359
+ }
360
+
361
+ initStackTraceCollection();
362
+ this._apmClient = createApmClient(this._conf, this);
363
+
364
+ let runContextClass;
365
+ if (this._conf.opentelemetryBridgeEnabled) {
366
+ const {
367
+ setupOTelBridge,
368
+ OTelBridgeRunContext,
369
+ } = require('./opentelemetry-bridge');
370
+ runContextClass = OTelBridgeRunContext;
371
+ setupOTelBridge(this);
372
+ }
373
+ this._instrumentation.start(runContextClass);
374
+
375
+ if (this._isMetricsEnabled()) {
376
+ this._metrics.start();
377
+ }
378
+
379
+ Error.stackTraceLimit = this._conf.stackTraceLimit;
380
+ if (this._conf.captureExceptions) this.handleUncaughtExceptions();
381
+
382
+ return this;
383
+ };
384
+
385
+ Agent.prototype._isMetricsEnabled = function () {
386
+ return this._conf.metricsInterval !== 0 && !this._conf.contextPropagationOnly;
387
+ };
388
+
389
+ /**
390
+ * Lazily create a singleton OTel MeterProvider that periodically exports
391
+ * metrics to APM server. This may return null if the MeterProvider is
392
+ * unsupported for this node version, metrics are disabled, etc.
393
+ *
394
+ * @returns {import('@opentelemetry/api').MeterProvider | null}
395
+ */
396
+ Agent.prototype._getOrCreateOTelMeterProvider = function () {
397
+ if (this._otelMeterProvider) {
398
+ return this._otelMeterProvider;
399
+ }
400
+
401
+ if (!this._isMetricsEnabled()) {
402
+ return null;
403
+ }
404
+ if (!isOTelMetricsFeatSupported) {
405
+ return null;
406
+ }
407
+
408
+ this.logger.trace('create Elastic APM MeterProvider for @opentelemetry/api');
409
+ this._otelMeterProvider = createOTelMeterProvider(this);
410
+ return this._otelMeterProvider;
411
+ };
412
+
413
+ Agent.prototype.getServiceName = function () {
414
+ return this._conf ? this._conf.serviceName : undefined;
415
+ };
416
+
417
+ Agent.prototype.getServiceVersion = function () {
418
+ return this._conf ? this._conf.serviceVersion : undefined;
419
+ };
420
+
421
+ Agent.prototype.getServiceEnvironment = function () {
422
+ return this._conf ? this._conf.environment : undefined;
423
+ };
424
+
425
+ Agent.prototype.getServiceNodeName = function () {
426
+ return this._conf ? this._conf.serviceNodeName : undefined;
427
+ };
428
+
429
+ Agent.prototype.setFramework = function ({ name, version, overwrite = true }) {
430
+ if (!this._apmClient || !this._conf) {
431
+ return;
432
+ }
433
+ const conf = {};
434
+ if (name && (overwrite || !this._conf.frameworkName))
435
+ this._conf.frameworkName = conf.frameworkName = name;
436
+ if (version && (overwrite || !this._conf.frameworkVersion))
437
+ this._conf.frameworkVersion = conf.frameworkVersion = version;
438
+ this._apmClient.config(conf);
439
+ };
440
+
441
+ Agent.prototype.setUserContext = function (context) {
442
+ var trans = this._instrumentation.currTransaction();
443
+ if (!trans) return false;
444
+ trans.setUserContext(context);
445
+ return true;
446
+ };
447
+
448
+ Agent.prototype.setCustomContext = function (context) {
449
+ var trans = this._instrumentation.currTransaction();
450
+ if (!trans) return false;
451
+ trans.setCustomContext(context);
452
+ return true;
453
+ };
454
+
455
+ Agent.prototype.setGlobalLabel = function (key, value) {
456
+ if (!this._conf.globalLabels) this._conf.globalLabels = [];
457
+ const foundPos = this._conf.globalLabels.findIndex(([name]) => key === name);
458
+ if (foundPos > -1) {
459
+ this._conf.globalLabels[foundPos][1] = value;
460
+ } else {
461
+ this._conf.globalLabels.push([key, value]);
462
+ }
463
+ if (!this._apmClient) {
464
+ this.logger.warn('cannot setGlobalLabel on inactive or unconfigured agent');
465
+ return;
466
+ }
467
+ this._apmClient.config({
468
+ globalLabels: this._conf.globalLabels.reduce((acc, [k, v]) => {
469
+ acc[k] = v;
470
+ return acc;
471
+ }, {}),
472
+ });
473
+ };
474
+
475
+ Agent.prototype.setLabel = function (key, value, stringify) {
476
+ var trans = this._instrumentation.currTransaction();
477
+ if (!trans) return false;
478
+ return trans.setLabel(key, value, stringify);
479
+ };
480
+
481
+ Agent.prototype.addLabels = function (labels, stringify) {
482
+ var trans = this._instrumentation.currTransaction();
483
+ if (!trans) return false;
484
+ return trans.addLabels(labels, stringify);
485
+ };
486
+
487
+ Agent.prototype.addFilter = function (fn) {
488
+ this.addErrorFilter(fn);
489
+ this.addTransactionFilter(fn);
490
+ this.addSpanFilter(fn);
491
+ // Note: This does *not* add to *metadata* filters, partly for backward
492
+ // compat -- the structure of metadata objects is quite different and could
493
+ // break existing filters -- and partly because that different structure
494
+ // means it makes less sense to re-use the same function to filter them.
495
+ };
496
+
497
+ Agent.prototype.addErrorFilter = function (fn) {
498
+ if (typeof fn !== 'function') {
499
+ this.logger.error("Can't add filter of type %s", typeof fn);
500
+ return;
501
+ }
502
+
503
+ this._errorFilters.push(fn);
504
+ };
505
+
506
+ Agent.prototype.addTransactionFilter = function (fn) {
507
+ if (typeof fn !== 'function') {
508
+ this.logger.error("Can't add filter of type %s", typeof fn);
509
+ return;
510
+ }
511
+
512
+ this._transactionFilters.push(fn);
513
+ };
514
+
515
+ Agent.prototype.addSpanFilter = function (fn) {
516
+ if (typeof fn !== 'function') {
517
+ this.logger.error("Can't add filter of type %s", typeof fn);
518
+ return;
519
+ }
520
+
521
+ this._spanFilters.push(fn);
522
+ };
523
+
524
+ Agent.prototype.addMetadataFilter = function (fn) {
525
+ if (typeof fn !== 'function') {
526
+ this.logger.error("Can't add filter of type %s", typeof fn);
527
+ return;
528
+ } else if (!this._apmClient) {
529
+ this.logger.error(
530
+ 'cannot add metadata filter to inactive or unconfigured agent (agent has no transport)',
531
+ );
532
+ return;
533
+ } else if (typeof this._apmClient.addMetadataFilter !== 'function') {
534
+ // Graceful failure if unexpectedly using a too-old APM client.
535
+ this.logger.error(
536
+ 'cannot add metadata filter: transport does not support addMetadataFilter',
537
+ );
538
+ return;
539
+ }
540
+
541
+ // Metadata filters are handled by the APM client, where metadata is
542
+ // processed.
543
+ this._apmClient.addMetadataFilter(fn);
544
+ };
545
+
546
+ const EMPTY_OPTS = {};
547
+
548
+ // Capture an APM server "error" event for the given `err` and send it to APM
549
+ // server.
550
+ //
551
+ // Usage:
552
+ // captureError(err, opts, cb)
553
+ // captureError(err, opts)
554
+ // captureError(err, cb)
555
+ //
556
+ // where:
557
+ // - `err` is an Error instance, or a string message, or a "parameterized string
558
+ // message" object, e.g.:
559
+ // {
560
+ // message: "this is my message template: %d %s"},
561
+ // params: [ 42, "another param" ]
562
+ // }
563
+ // - `opts` can include any of the following (all optional):
564
+ // - `opts.timestamp` - Milliseconds since the Unix epoch. Defaults to now.
565
+ // - `opts.user` - Object to add to `error.context.user`.
566
+ // - `opts.tags` - Deprecated, use `opts.labels`. Object to add to
567
+ // `error.context.labels`.
568
+ // - `opts.labels` - Object to add to `error.context.labels`.
569
+ // - `opts.custom` - Object to add to `error.context.custom`.
570
+ // - `opts.message` - If `err` is an Error instance, this string is added to
571
+ // `error.log.message` (unless it matches err.message).
572
+ // - `opts.request` - HTTP request (node `IncomingMessage` instance) to use
573
+ // for `error.context.request`. If not given, a `req` on the parent
574
+ // transaction (see `opts.parent` below) will be used.
575
+ // - `opts.response` - HTTP response (node `ServerResponse` instance) to use
576
+ // for `error.context.response`. If not given, a `res` on the parent
577
+ // transaction (see `opts.parent` below) will be used.
578
+ // - `opts.handled` - Boolean indicating if this exception was handled by
579
+ // application code. Default true. Setting to `false` also results in the
580
+ // error being flushed to APM server as soon as it is processed.
581
+ // - `opts.captureAttributes` - Boolean. Default true. Set to false to *not*
582
+ // include properties of `err` as attributes on the APM error event.
583
+ // - `opts.skipOutcome` - Boolean. Default false. Set to true to not have
584
+ // this captured error set `<currentSpan>.outcome = failure`.
585
+ // - `opts.parent` - A Transaction or Span instance to make the parent of
586
+ // this error. If not given (undefined), then the current span or
587
+ // transaction will be used. If `null` is given, then no span or transaction
588
+ // will be used.
589
+ // - `opts.exceptionType` - A string to use for `error.exception.type`. By
590
+ // default this is `err.name`. This option is only relevant if `err` is an
591
+ // Error instance.
592
+ // - `cb` is a callback `function (captureErr, apmErrorIdString)`. If provided,
593
+ // the error will be flushed to APM server as soon as it is processed, and
594
+ // `cb` will be called when that send is complete.
595
+ Agent.prototype.captureError = function (err, opts, cb) {
596
+ if (typeof opts === 'function') {
597
+ cb = opts;
598
+ opts = EMPTY_OPTS;
599
+ } else if (!opts) {
600
+ opts = EMPTY_OPTS;
601
+ }
602
+
603
+ const id = errors.generateErrorId();
604
+
605
+ if (!this.isStarted()) {
606
+ if (cb) {
607
+ cb(new Error('cannot capture error before agent is started'), id);
608
+ }
609
+ return;
610
+ }
611
+
612
+ // Avoid unneeded error/stack processing if only propagating trace-context.
613
+ if (this._conf.contextPropagationOnly) {
614
+ if (cb) {
615
+ process.nextTick(cb, null, id);
616
+ }
617
+ return;
618
+ }
619
+
620
+ const agent = this;
621
+ let callSiteLoc = null;
622
+ const errIsError = isError(err);
623
+ const handled = opts.handled !== false; // default true
624
+ const shouldCaptureAttributes = opts.captureAttributes !== false; // default true
625
+ const skipOutcome = Boolean(opts.skipOutcome);
626
+ const timestampUs = opts.timestamp
627
+ ? Math.floor(opts.timestamp * 1000)
628
+ : Date.now() * 1000;
629
+
630
+ // Determine transaction/span context to associate with this error.
631
+ let parent;
632
+ let span;
633
+ let trans;
634
+ if (opts.parent === undefined) {
635
+ parent =
636
+ this._instrumentation.currSpan() ||
637
+ this._instrumentation.currTransaction();
638
+ } else if (opts.parent === null) {
639
+ parent = null;
640
+ } else {
641
+ parent = opts.parent;
642
+ }
643
+ if (parent instanceof Transaction) {
644
+ span = null;
645
+ trans = parent;
646
+ } else if (parent instanceof Span) {
647
+ span = parent;
648
+ trans = parent.transaction;
649
+ }
650
+ const traceContext = (span || trans || {})._context;
651
+ const req =
652
+ opts.request instanceof IncomingMessage ? opts.request : trans && trans.req;
653
+ const res =
654
+ opts.response instanceof ServerResponse
655
+ ? opts.response
656
+ : trans && trans.res;
657
+
658
+ // As an added feature, for *some* cases, we capture a stacktrace at the point
659
+ // this `captureError` was called. This is added to `error.log.stacktrace`.
660
+ if (
661
+ handled &&
662
+ (agent._conf.captureErrorLogStackTraces ===
663
+ CAPTURE_ERROR_LOG_STACK_TRACES_ALWAYS ||
664
+ (!errIsError &&
665
+ agent._conf.captureErrorLogStackTraces ===
666
+ CAPTURE_ERROR_LOG_STACK_TRACES_MESSAGES))
667
+ ) {
668
+ callSiteLoc = {};
669
+ Error.captureStackTrace(callSiteLoc, Agent.prototype.captureError);
670
+ }
671
+
672
+ if (span && !skipOutcome) {
673
+ span._setOutcomeFromErrorCapture(constants.OUTCOME_FAILURE);
674
+ }
675
+
676
+ // Note this error as an "inflight" event. See Agent#flush().
677
+ const inflightEvents = this._inflightEvents;
678
+ inflightEvents.add(id);
679
+
680
+ // Move the remaining captureError processing to a later tick because:
681
+ // 1. This allows the calling code to continue processing. For example, for
682
+ // Express instrumentation this can significantly improve latency in
683
+ // the app's endpoints because the response does not proceed until the
684
+ // error handlers return.
685
+ // 2. Gathering `error.context.response` in the same tick results in data
686
+ // for a response that hasn't yet completed (no headers, unset status_code,
687
+ // etc.).
688
+ setImmediate(() => {
689
+ // Gather `error.context.*`.
690
+ const errorContext = {
691
+ user: Object.assign(
692
+ {},
693
+ req && parsers.getUserContextFromRequest(req),
694
+ trans && trans._user,
695
+ opts.user,
696
+ ),
697
+ tags: Object.assign({}, trans && trans._labels, opts.tags, opts.labels),
698
+ custom: Object.assign({}, trans && trans._custom, opts.custom),
699
+ };
700
+ if (req) {
701
+ errorContext.request = parsers.getContextFromRequest(
702
+ req,
703
+ agent._conf,
704
+ 'errors',
705
+ );
706
+ }
707
+ if (res) {
708
+ errorContext.response = parsers.getContextFromResponse(
709
+ res,
710
+ agent._conf,
711
+ true,
712
+ );
713
+ }
714
+
715
+ errors.createAPMError(
716
+ {
717
+ log: agent.logger,
718
+ id,
719
+ exception: errIsError ? err : null,
720
+ logMessage: errIsError ? null : err,
721
+ shouldCaptureAttributes,
722
+ timestampUs,
723
+ handled,
724
+ callSiteLoc,
725
+ message: opts.message,
726
+ sourceLinesAppFrames: agent._conf.sourceLinesErrorAppFrames,
727
+ sourceLinesLibraryFrames: agent._conf.sourceLinesErrorLibraryFrames,
728
+ trans,
729
+ traceContext,
730
+ errorContext,
731
+ exceptionType: opts.exceptionType,
732
+ },
733
+ function filterAndSendError(_err, apmError) {
734
+ // _err is always null from createAPMError.
735
+
736
+ apmError = agent._errorFilters.process(apmError);
737
+ if (!apmError) {
738
+ agent.logger.debug('error ignored by filter %o', { id });
739
+ inflightEvents.delete(id);
740
+ if (cb) {
741
+ cb(null, id);
742
+ }
743
+ return;
744
+ }
745
+
746
+ if (agent._apmClient) {
747
+ agent.logger.debug('Sending error to Elastic APM: %o', { id });
748
+ agent._apmClient.sendError(apmError);
749
+ inflightEvents.delete(id);
750
+ if (!handled || cb) {
751
+ // Immediately flush *unhandled* errors -- those from
752
+ // `uncaughtException` -- on the assumption that the process may
753
+ // soon crash. Also flush when a `cb` is provided.
754
+ agent.flush(function (flushErr) {
755
+ if (cb) {
756
+ cb(flushErr, id);
757
+ }
758
+ });
759
+ }
760
+ } else {
761
+ inflightEvents.delete(id);
762
+ if (cb) {
763
+ cb(new Error('cannot send error: missing transport'), id);
764
+ }
765
+ }
766
+ },
767
+ );
768
+ });
769
+ };
770
+
771
+ // The optional callback will be called with the error object after the error
772
+ // have been sent to the intake API. If no callback have been provided we will
773
+ // automatically terminate the process, so if you provide a callback you must
774
+ // remember to terminate the process manually.
775
+ Agent.prototype.handleUncaughtExceptions = function (cb) {
776
+ var agent = this;
777
+
778
+ if (this._uncaughtExceptionListener) {
779
+ process.removeListener(
780
+ 'uncaughtException',
781
+ this._uncaughtExceptionListener,
782
+ );
783
+ }
784
+
785
+ this._uncaughtExceptionListener = function (err) {
786
+ agent.logger.debug({ err }, 'Elastic APM caught unhandled exception');
787
+ // This somewhat mimics Node.js's core printing of the error to stderr, but
788
+ // is not quite the same output. Compare to:
789
+ // https://github.com/nodejs/node/blob/v20.5.0/src/node_errors.cc#L246-L266
790
+ console.error(err);
791
+
792
+ agent.captureError(err, { handled: false }, function () {
793
+ cb ? cb(err) : process.exit(1);
794
+ });
795
+ };
796
+
797
+ process.on('uncaughtException', this._uncaughtExceptionListener);
798
+ };
799
+
800
+ // Flush all ended APM events (transactions, spans, errors, metricsets) to APM
801
+ // server as soon as possible. If the optional `cb` is given, it will be called
802
+ // `cb(flushErr)` when this is complete. If no `cb` is given, then a `Promise`
803
+ // will be returned, which will either resolve with `void` or reject with
804
+ // `flushErr`.
805
+ //
806
+ // Encoding and passing event data to the agent's transport is *asynchronous*
807
+ // for some event types: spans and errors. This flush will make a *best effort*
808
+ // attempt to wait for those "inflight" events to finish processing before
809
+ // flushing data to APM server. To avoid `.flush()` hanging, this times out
810
+ // after one second.
811
+ //
812
+ // If flush is called while still waiting for inflight events in an earlier
813
+ // flush call, then the more recent flush will only wait for events that were
814
+ // newly inflight *since the last .flush()* call. I.e. the second flush does
815
+ // *not* wait for the set of events the first flush is waiting on. This makes
816
+ // the semantics of flush less than ideal (one cannot blindly call .flush() to
817
+ // flush *everything* that has come before). However it handles the common use
818
+ // case of flushing synchronously after ending a span or capturing an error:
819
+ // mySpan.end()
820
+ // await apm.flush()
821
+ // and it simplifies the implementation.
822
+ //
823
+ // # Dev Notes
824
+ //
825
+ // To support the implementation, agent code that creates an inflight event
826
+ // must do the following:
827
+ // - Take a reference to the current set of inflight events:
828
+ // const inflightEvents = agent._inflightEvents
829
+ // - Add a unique ID for the event to the set:
830
+ // inflightEvents.add(id)
831
+ // - Delete the ID from the set when sent to the transport (`.sendSpan(...)` et
832
+ // al) or when dropping the event (e.g. because of a filter):
833
+ // inflightEvents.delete(id)
834
+ Agent.prototype.flush = function (cb) {
835
+ // This 1s timeout is a subjective balance between "long enough for spans
836
+ // and errors to reasonably encode" and "short enough to not block data
837
+ // being reported to APM server".
838
+ const DEFAULT_INFLIGHT_FLUSH_TIMEOUT_MS = 1000;
839
+
840
+ // shared options for the private `._flush()` API.
841
+ const opts = { inflightTimeoutMs: DEFAULT_INFLIGHT_FLUSH_TIMEOUT_MS };
842
+
843
+ if (typeof cb !== 'function') {
844
+ return new Promise((resolve, reject) => {
845
+ this._flush(opts, (err) => {
846
+ if (err) {
847
+ reject(err);
848
+ }
849
+
850
+ resolve();
851
+ });
852
+ });
853
+ }
854
+
855
+ return this._flush(opts, cb);
856
+ };
857
+
858
+ // The internal-use `.flush()` that supports some options not exposed to the
859
+ // public API.
860
+ //
861
+ // @param {Number} opts.inflightTimeoutMs - Required. The number of ms to wait
862
+ // for inflight events (spans, errors) to finish being send to the transport
863
+ // before flushing.
864
+ // @param {Boolean} opts.lambdaEnd - Optional, default false. Set this to true
865
+ // to signal to the transport that this is the flush at the end of a Lambda
866
+ // function invocation.
867
+ // https://github.com/elastic/apm/blob/main/specs/agents/tracing-instrumentation-aws-lambda.md#data-flushing
868
+ Agent.prototype._flush = function (opts, cb) {
869
+ const lambdaEnd = !!opts.lambdaEnd;
870
+
871
+ if (!this._apmClient) {
872
+ // Log an *err* to provide a stack for the user.
873
+ const err = new Error('cannot flush agent before it is started');
874
+ this.logger.warn({ err }, err.message);
875
+ if (cb) {
876
+ process.nextTick(cb);
877
+ }
878
+ return;
879
+ }
880
+
881
+ const boundCb = cb && this._instrumentation.bindFunction(cb);
882
+
883
+ // If there are no inflight events then avoid creating additional objects.
884
+ if (this._inflightEvents.size === 0) {
885
+ this._apmClient.flush({ lambdaEnd }, boundCb);
886
+ return;
887
+ }
888
+
889
+ // Otherwise, there are inflight events to wait for. Setup a handler to
890
+ // callback when the current set of inflight events complete.
891
+ const flushingInflightEvents = this._inflightEvents;
892
+ flushingInflightEvents.setDrainHandler((drainErr) => {
893
+ // The only possible drainErr is a timeout. This is best effort, so we only
894
+ // log this and move on.
895
+ this.logger.debug(
896
+ {
897
+ numRemainingInflightEvents: flushingInflightEvents.size,
898
+ err: drainErr,
899
+ },
900
+ 'flush: drained inflight events',
901
+ );
902
+
903
+ // Then, flush the intake request to APM server.
904
+ this._apmClient.flush({ lambdaEnd }, boundCb);
905
+ }, opts.inflightTimeoutMs);
906
+
907
+ // Create a new empty set to collect subsequent inflight events.
908
+ this._inflightEvents = new InflightEventSet();
909
+ };
910
+
911
+ Agent.prototype.registerMetric = function (name, labelsOrCallback, callback) {
912
+ var labels;
913
+ if (typeof labelsOrCallback === 'function') {
914
+ callback = labelsOrCallback;
915
+ } else {
916
+ labels = labelsOrCallback;
917
+ }
918
+
919
+ if (typeof callback !== 'function') {
920
+ this.logger.error("Can't add callback of type %s", typeof callback);
921
+ return;
922
+ }
923
+
924
+ this._metrics.getOrCreateGauge(name, callback, labels);
925
+ };
926
+
927
+ /**
928
+ * Return true iff the given metric name is "disabled", according to the
929
+ * `disableMetrics` config var.
930
+ *
931
+ * @returns {boolean}
932
+ */
933
+ Agent.prototype._isMetricNameDisabled = function (name) {
934
+ const regexps = this._conf.disableMetricsRegExp;
935
+ for (var i = 0; i < regexps.length; i++) {
936
+ if (regexps[i].test(name)) {
937
+ return true;
938
+ }
939
+ }
940
+ return false;
941
+ };