@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/index.d.ts ADDED
@@ -0,0 +1,398 @@
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
+ /// <reference types="node" />
8
+
9
+ // Note: We avoid import of any external `@types/...` to avoid TypeScript users
10
+ // needing to manually install them. The only exception is the prerequisite to
11
+ // `npm install -D @types/node`.
12
+ import type { IncomingMessage, ServerResponse } from 'http';
13
+ import { Connect } from './types/connect';
14
+ import { AwsLambda } from './types/aws-lambda';
15
+
16
+ declare namespace apm {
17
+ // Agent API
18
+ // https://www.elastic.co/guide/en/apm/agent/nodejs/current/agent-api.html
19
+ export interface Agent {
20
+ // Configuration
21
+ start (options?: AgentConfigOptions): Agent;
22
+ isStarted (): boolean;
23
+ getServiceName (): string | undefined;
24
+ getServiceVersion (): string | undefined;
25
+ getServiceEnvironment (): string;
26
+ getServiceNodeName (): string | undefined;
27
+ setFramework (options: {
28
+ name?: string;
29
+ version?: string;
30
+ overwrite?: boolean;
31
+ }): void;
32
+ addPatch (modules: string | Array<string>, handler: string | PatchHandler): void;
33
+ removePatch (modules: string | Array<string>, handler: string | PatchHandler): void;
34
+ clearPatches (modules: string | Array<string>): void;
35
+
36
+ // Data collection hooks
37
+ middleware: { connect (): Connect.ErrorHandleFunction };
38
+ lambda (handler: AwsLambda.Handler): AwsLambda.Handler;
39
+ lambda (type: string, handler: AwsLambda.Handler): AwsLambda.Handler;
40
+ handleUncaughtExceptions (
41
+ fn?: (err: Error) => void
42
+ ): void;
43
+
44
+ // Errors
45
+ captureError (
46
+ err: Error | string | ParameterizedMessageObject,
47
+ callback?: CaptureErrorCallback
48
+ ): void;
49
+ captureError (
50
+ err: Error | string | ParameterizedMessageObject,
51
+ options?: CaptureErrorOptions,
52
+ callback?: CaptureErrorCallback
53
+ ): void;
54
+
55
+ // Distributed Tracing
56
+ currentTraceparent: string | null;
57
+ currentTraceIds: {
58
+ 'trace.id'?: string;
59
+ 'transaction.id'?: string;
60
+ 'span.id'?: string;
61
+ }
62
+
63
+ // Transactions
64
+ startTransaction(
65
+ name?: string | null,
66
+ options?: TransactionOptions
67
+ ): Transaction;
68
+ startTransaction(
69
+ name: string | null,
70
+ type: string | null,
71
+ options?: TransactionOptions
72
+ ): Transaction;
73
+ setTransactionName (name: string): void;
74
+ endTransaction (result?: string | number, endTime?: number): void;
75
+ currentTransaction: Transaction | null;
76
+
77
+ // Spans
78
+ startSpan(
79
+ name?: string | null,
80
+ options?: SpanOptions
81
+ ): Span | null;
82
+ startSpan(
83
+ name: string | null,
84
+ type: string | null,
85
+ options?: SpanOptions
86
+ ): Span | null;
87
+ startSpan(
88
+ name: string | null,
89
+ type: string | null,
90
+ subtype: string | null,
91
+ options?: SpanOptions
92
+ ): Span | null;
93
+ startSpan(
94
+ name: string | null,
95
+ type: string | null,
96
+ subtype: string | null,
97
+ action: string | null,
98
+ options?: SpanOptions
99
+ ): Span | null;
100
+ currentSpan: Span | null;
101
+
102
+ // Context
103
+ setGlobalLabel (name: string, value: LabelValue): void;
104
+ setLabel (name: string, value: LabelValue, stringify?: boolean): boolean;
105
+ addLabels (labels: Labels, stringify?: boolean): boolean;
106
+ setUserContext (user: UserObject): void;
107
+ setCustomContext (custom: object): void;
108
+
109
+ // Transport
110
+ addFilter (fn: FilterFn): void;
111
+ addErrorFilter (fn: FilterFn): void;
112
+ addSpanFilter (fn: FilterFn): void;
113
+ addTransactionFilter (fn: FilterFn): void;
114
+ addMetadataFilter (fn: FilterFn): void;
115
+ flush (): Promise<void>;
116
+ flush (callback?: Function): void;
117
+ destroy (): Promise<void>;
118
+
119
+ // Utils
120
+ logger: Logger;
121
+
122
+ // Custom metrics
123
+ registerMetric(name: string, callback: Function): void;
124
+ registerMetric(name: string, labels: Labels, callback: Function): void;
125
+
126
+ setTransactionOutcome(outcome: Outcome): void;
127
+ setSpanOutcome(outcome: Outcome): void;
128
+ }
129
+
130
+ type Outcome = 'unknown' | 'success' | 'failure';
131
+
132
+ // Transaction API
133
+ // https://www.elastic.co/guide/en/apm/agent/nodejs/current/transaction-api.html
134
+ export interface Transaction {
135
+ // The following properties and methods are currently not documented as their API isn't considered official:
136
+ // - timestamp, ended, id, traceId, parentId, sampled, duration()
137
+ // - setUserContext(), setCustomContext(), toJSON(), setDefaultName(), setDefaultNameFromRequest()
138
+
139
+ name: string;
140
+ type: string | null;
141
+ traceparent: string;
142
+ outcome: Outcome;
143
+ result: string | number;
144
+ ids: {
145
+ 'trace.id': string;
146
+ 'transaction.id': string;
147
+ }
148
+
149
+ setType (type?: string | null): void;
150
+ setLabel (name: string, value: LabelValue, stringify?: boolean): boolean;
151
+ addLabels (labels: Labels, stringify?: boolean): boolean;
152
+ setOutcome(outcome: Outcome): void;
153
+ addLink (link: Link): void;
154
+ addLinks (links: Link[]): void;
155
+
156
+ startSpan(
157
+ name?: string | null,
158
+ options?: SpanOptions
159
+ ): Span | null;
160
+ startSpan(
161
+ name: string | null,
162
+ type: string | null,
163
+ options?: SpanOptions
164
+ ): Span | null;
165
+ startSpan(
166
+ name: string | null,
167
+ type: string | null,
168
+ subtype: string | null,
169
+ options?: SpanOptions
170
+ ): Span | null;
171
+ startSpan(
172
+ name: string | null,
173
+ type: string | null,
174
+ subtype: string | null,
175
+ action: string | null,
176
+ options?: SpanOptions
177
+ ): Span | null;
178
+ ensureParentId (): string;
179
+ end (result?: string | number | null, endTime?: number): void;
180
+ }
181
+
182
+ // Span API
183
+ // https://www.elastic.co/guide/en/apm/agent/nodejs/current/span-api.html
184
+ export interface Span {
185
+ // The following properties and methods are currently not documented as their API isn't considered official:
186
+ // - timestamp, ended, id, traceId, parentId, sampled, duration()
187
+ // - customStackTrace(), setDbContext()
188
+
189
+ transaction: Transaction;
190
+ name: string;
191
+ type: string | null;
192
+ subtype: string | null;
193
+ action: string | null;
194
+ traceparent: string;
195
+ outcome: Outcome;
196
+ ids: {
197
+ 'trace.id': string;
198
+ 'span.id': string;
199
+ }
200
+
201
+ setType (type?: string | null, subtype?: string | null, action?: string | null): void;
202
+ setLabel (name: string, value: LabelValue, stringify?: boolean): boolean;
203
+ addLabels (labels: Labels, stringify?: boolean): boolean;
204
+ setOutcome(outcome: Outcome): void;
205
+ setServiceTarget(type?: string | null, name?: string | null): void;
206
+ addLink (link: Link): void;
207
+ addLinks (links: Link[]): void;
208
+ end (endTime?: number): void;
209
+ }
210
+
211
+ // https://www.elastic.co/guide/en/apm/agent/nodejs/current/configuration.html
212
+ export interface AgentConfigOptions {
213
+ abortedErrorThreshold?: string; // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
214
+ active?: boolean;
215
+ addPatch?: KeyValueConfig;
216
+ apiKey?: string;
217
+ apiRequestSize?: string; // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
218
+ apiRequestTime?: string; // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
219
+ breakdownMetrics?: boolean;
220
+ captureBody?: CaptureBody;
221
+ captureErrorLogStackTraces?: CaptureErrorLogStackTraces;
222
+ captureExceptions?: boolean;
223
+ captureHeaders?: boolean;
224
+ /**
225
+ * @deprecated Use `spanStackTraceMinDuration`.
226
+ */
227
+ captureSpanStackTraces?: boolean;
228
+ centralConfig?: boolean;
229
+ cloudProvider?: string;
230
+ configFile?: string;
231
+ containerId?: string;
232
+ contextManager?: string;
233
+ contextPropagationOnly?: boolean;
234
+ disableInstrumentations?: string | string[];
235
+ disableSend?: boolean;
236
+ elasticsearchCaptureBodyUrls?: Array<string>;
237
+ environment?: string;
238
+ /**
239
+ * @deprecated Use `longFieldMaxLength`
240
+ */
241
+ errorMessageMaxLength?: string;
242
+ errorOnAbortedRequests?: boolean;
243
+ exitSpanMinDuration?: string;
244
+ frameworkName?: string;
245
+ frameworkVersion?: string;
246
+ globalLabels?: KeyValueConfig;
247
+ hostname?: string;
248
+ ignoreMessageQueues?: Array<string>;
249
+ ignoreUrls?: Array<string | RegExp>;
250
+ ignoreUserAgents?: Array<string | RegExp>;
251
+ instrument?: boolean;
252
+ instrumentIncomingHTTPRequests?: boolean;
253
+ kubernetesNamespace?: string;
254
+ kubernetesNodeName?: string;
255
+ kubernetesPodName?: string;
256
+ kubernetesPodUID?: string;
257
+ logLevel?: LogLevel;
258
+ logger?: Logger; // Notably this Logger interface matches the Pino Logger.
259
+ longFieldMaxLength?: number;
260
+ maxQueueSize?: number;
261
+ metricsInterval?: string; // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
262
+ metricsLimit?: number;
263
+ opentelemetryBridgeEnabled?: boolean;
264
+ payloadLogFile?: string;
265
+ sanitizeFieldNames?: Array<string>;
266
+ secretToken?: string;
267
+ serverCaCertFile?: string;
268
+ serverTimeout?: string; // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
269
+ serverUrl?: string;
270
+ serviceName?: string;
271
+ serviceNodeName?: string;
272
+ serviceVersion?: string;
273
+ sourceLinesErrorAppFrames?: number;
274
+ sourceLinesErrorLibraryFrames?: number;
275
+ sourceLinesSpanAppFrames?: number;
276
+ sourceLinesSpanLibraryFrames?: number;
277
+ spanCompressionEnabled?: boolean;
278
+ spanCompressionExactMatchMaxDuration?: string;
279
+ spanCompressionSameKindMaxDuration?: string;
280
+ /**
281
+ * @deprecated Use `spanStackTraceMinDuration`.
282
+ */
283
+ spanFramesMinDuration?: string;
284
+ spanStackTraceMinDuration?: string;
285
+ stackTraceLimit?: number;
286
+ traceContinuationStrategy?: TraceContinuationStrategy;
287
+ transactionIgnoreUrls?: Array<string>;
288
+ transactionMaxSpans?: number;
289
+ transactionSampleRate?: number;
290
+ useElasticTraceparentHeader?: boolean;
291
+ usePathAsTransactionName?: boolean;
292
+ verifyServerCert?: boolean;
293
+ }
294
+
295
+ interface CaptureErrorOptions {
296
+ request?: IncomingMessage;
297
+ response?: ServerResponse;
298
+ timestamp?: number;
299
+ handled?: boolean;
300
+ user?: UserObject;
301
+ labels?: Labels;
302
+ tags?: Labels;
303
+ custom?: object;
304
+ message?: string;
305
+ captureAttributes?: boolean;
306
+ skipOutcome?: boolean;
307
+ /**
308
+ * A Transaction or Span instance to make the parent of this error. If not
309
+ * given (undefined), then the current span or transaction will be used. If
310
+ * `null` is given, then no span or transaction will be used.
311
+ */
312
+ parent?: Transaction | Span | null;
313
+ }
314
+
315
+ interface Labels {
316
+ [key: string]: LabelValue;
317
+ }
318
+
319
+ interface UserObject {
320
+ id?: string | number;
321
+ username?: string;
322
+ email?: string;
323
+ }
324
+
325
+ interface ParameterizedMessageObject {
326
+ message: string;
327
+ params: Array<any>;
328
+ }
329
+
330
+ interface Logger {
331
+ // Defining overloaded methods rather than a separate `interface LogFn`
332
+ // as @types/pino does, because the IDE completion shows these as *methods*
333
+ // rather than as properties, which is slightly nicer.
334
+ fatal (msg: string, ...args: any[]): void;
335
+ fatal (obj: {}, msg?: string, ...args: any[]): void;
336
+ error (msg: string, ...args: any[]): void;
337
+ error (obj: {}, msg?: string, ...args: any[]): void;
338
+ warn (msg: string, ...args: any[]): void;
339
+ warn (obj: {}, msg?: string, ...args: any[]): void;
340
+ info (msg: string, ...args: any[]): void;
341
+ info (obj: {}, msg?: string, ...args: any[]): void;
342
+ debug (msg: string, ...args: any[]): void;
343
+ debug (obj: {}, msg?: string, ...args: any[]): void;
344
+ trace (msg: string, ...args: any[]): void;
345
+ trace (obj: {}, msg?: string, ...args: any[]): void;
346
+ // Allow a passed in Logger that has other properties, as a Pino logger
347
+ // does. Discussion:
348
+ // https://github.com/elastic/apm-agent-nodejs/pull/926/files#r266239656
349
+ [propName: string]: any;
350
+ }
351
+
352
+ // Link and `links` are intended to be compatible with OTel's
353
+ // equivalent APIs in "opentelemetry-js-api/src/trace/link.ts". Currently
354
+ // span link attributes are not supported.
355
+ export interface Link {
356
+ /** A W3C trace-context 'traceparent' string, Transaction, Span, or OTel SpanContext. */
357
+ context: Transaction | Span | {traceId: string, spanId: string} | string;
358
+ }
359
+
360
+ export interface TransactionOptions {
361
+ startTime?: number;
362
+ // `childOf` is a W3C trace-context 'traceparent' string. Passing a
363
+ // Transaction or Span is deprecated.
364
+ childOf?: Transaction | Span | string;
365
+ tracestate?: string; // A W3C trace-context 'tracestate' string.
366
+ links?: Link[];
367
+ }
368
+
369
+ export interface SpanOptions {
370
+ startTime?: number;
371
+ childOf?: Transaction | Span | string;
372
+ exitSpan?: boolean;
373
+ links?: Link[];
374
+ }
375
+
376
+ type CaptureBody = 'off' | 'errors' | 'transactions' | 'all';
377
+ type CaptureErrorLogStackTraces = 'never' | 'messages' | 'always';
378
+ type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'warning' | 'error' | 'fatal' | 'critical' | 'off';
379
+ type TraceContinuationStrategy = 'continue' | 'restart' | 'restart_external';
380
+
381
+ type CaptureErrorCallback = (err: Error | null, id: string) => void;
382
+ type FilterFn = (payload: Payload) => Payload | boolean | void;
383
+ type LabelValue = string | number | boolean | null | undefined;
384
+ type KeyValueConfig = string | Labels | Array<Array<LabelValue>>
385
+
386
+ type Payload = { [propName: string]: any }
387
+
388
+ type PatchHandler = (exports: any, agent: Agent, options: PatchOptions) => any;
389
+
390
+ interface PatchOptions {
391
+ name: string;
392
+ version: string | undefined;
393
+ enabled: boolean;
394
+ }
395
+ }
396
+
397
+ declare const apm: apm.Agent;
398
+ export = apm;
package/index.js ADDED
@@ -0,0 +1,11 @@
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
+ var Agent = require('./lib/agent');
10
+
11
+ module.exports = new Agent();
@@ -0,0 +1,53 @@
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
+ // A `Set` object used to track inflight APM events: ended spans and errors
10
+ // that are currently being processed, but have not yet been sent to the Agent
11
+ // transport.
12
+ //
13
+ // `setDrainHandler` allows setting a function to be called when the inflight
14
+ // events have drained. Agent#flush() uses this to ensure that a flush waits
15
+ // for inflight events to be processed, so they are sent to APM Server before
16
+ // calling back.
17
+ class InflightEventSet extends Set {
18
+ // Set a `fn` to be called *once* when the set size next goes to zero.
19
+ // If the optional `timeoutMs` is given, then `fn(err)` will be called if
20
+ // the set hasn't yet drained.
21
+ setDrainHandler(fn, timeoutMs) {
22
+ this._drainHandler = fn;
23
+ if (timeoutMs) {
24
+ this._drainTimeout = setTimeout(() => {
25
+ this._drain(new Error('inflight event set drain timeout'));
26
+ }, timeoutMs).unref();
27
+ }
28
+ }
29
+
30
+ // Call the drain handler, if there is one.
31
+ _drain(err) {
32
+ if (this._drainHandler) {
33
+ if (this._drainTimeout) {
34
+ clearTimeout(this._drainTimeout);
35
+ this._drainTimeout = null;
36
+ }
37
+ this._drainHandler(err);
38
+ // Remove the handler so it is only called once.
39
+ this._drainHandler = null;
40
+ }
41
+ }
42
+
43
+ delete(key) {
44
+ super.delete(key);
45
+ if (this.size === 0) {
46
+ this._drain();
47
+ }
48
+ }
49
+ }
50
+
51
+ module.exports = {
52
+ InflightEventSet,
53
+ };
@@ -0,0 +1,119 @@
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 path = require('path');
10
+
11
+ const errorStackParser = require('error-stack-parser');
12
+ const semver = require('semver');
13
+
14
+ var { isLambdaExecutionEnvironment } = require('./lambda');
15
+
16
+ const CONTAINS_R_ELASTIC_APM_NODE_START =
17
+ /(-r\s+|--require\s*=?\s*).*elastic-apm-node\/start/;
18
+
19
+ /**
20
+ * Determine the 'service.agent.activation_method' metadata value from an Error
21
+ * stack collected at `Agent.start()` time. Spec:
22
+ * https://github.com/elastic/apm/blob/main/specs/agents/metadata.md#activation-method
23
+ *
24
+ * @param {Error} startStack - An Error object with a captured stack trace.
25
+ * The `stackTraceLimit` for the stack should be at least 15 -- higher
26
+ * that the default of 10.
27
+ * @returns {string} one of the following values:
28
+ * - "unknown"
29
+ * - "require":
30
+ * require('elastic-apm-node').start(...)
31
+ * require('elastic-apm-node/start')
32
+ * - "import":
33
+ * import 'elastic-apm-node/start.js'
34
+ * import apm from 'elastic-apm-node'; apm.start()
35
+ * - "aws-lambda-layer": `NODE_OPTIONS` using Agent installed at /opt/nodejs/node_modules/elastic-apm-node
36
+ * - "k8s-attach": `NODE_OPTIONS` using Agent, and `ELASTIC_APM_ACTIVATION_METHOD=K8S_ATTACH` (or `K8S` for bwcompat to earlier apm-k8s-attacher versions) in env
37
+ * - "env-attach": Fallback for any other usage of NODE_OPTIONS='-r elastic-apm-node/start'
38
+ * - "preload": For usage of `node -r elastic-apm-node/start` without `NODE_OPTIONS`.
39
+ */
40
+ function agentActivationMethodFromStartStack(startStack, log) {
41
+ /* @param {require('stackframe').StackFrame[]} frames */
42
+ let frames;
43
+ try {
44
+ frames = errorStackParser.parse(startStack);
45
+ } catch (parseErr) {
46
+ log.trace(
47
+ parseErr,
48
+ 'could not determine metadata.service.agent.activation_method',
49
+ );
50
+ return 'unknown';
51
+ }
52
+ if (frames.length < 2) {
53
+ return 'unknown';
54
+ }
55
+
56
+ // frames[0].fileName = "$topDir/lib/agent.js"
57
+ // at Agent.start (/Users/trentm/tmp/asdf/node_modules/elastic-apm-node/lib/agent.js:241:11)
58
+ const topDir = path.dirname(path.dirname(frames[0].fileName));
59
+
60
+ // If this was a preload (i.e. using `-r elastic-apm-node/start`), then
61
+ // there will be a frame with `functionName` equal to:
62
+ // - node >=12: 'loadPreloadModules'
63
+ // - node <12: 'preloadModules'
64
+ const functionName = semver.gte(process.version, '12.0.0', {
65
+ includePrerelease: true,
66
+ })
67
+ ? 'loadPreloadModules'
68
+ : 'preloadModules';
69
+ let isPreload = false;
70
+ for (let i = frames.length - 1; i >= 2; i--) {
71
+ if (frames[i].functionName === functionName) {
72
+ isPreload = true;
73
+ break;
74
+ }
75
+ }
76
+ if (isPreload) {
77
+ if (
78
+ isLambdaExecutionEnvironment &&
79
+ topDir === '/opt/nodejs/node_modules/elastic-apm-node'
80
+ ) {
81
+ // This path is defined by https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path
82
+ // and created by "dev-utils/make-distribution.sh".
83
+ return 'aws-lambda-layer';
84
+ } else if (
85
+ process.env.ELASTIC_APM_ACTIVATION_METHOD === 'K8S_ATTACH' ||
86
+ process.env.ELASTIC_APM_ACTIVATION_METHOD === 'K8S'
87
+ ) {
88
+ // apm-k8s-attacher v0.1.0 started setting value to K8S.
89
+ // v0.4.0 will start using 'K8S_ATTACH'.
90
+ return 'k8s-attach';
91
+ } else if (
92
+ process.env.NODE_OPTIONS &&
93
+ CONTAINS_R_ELASTIC_APM_NODE_START.test(process.env.NODE_OPTIONS)
94
+ ) {
95
+ return 'env-attach';
96
+ } else {
97
+ return 'preload';
98
+ }
99
+ }
100
+
101
+ // To tell if elastic-apm-node was `import`d or `require`d we look for a
102
+ // frame with `functionName` equal to 'ModuleJob.run'. This has consistently
103
+ // been the name of this method back to at least Node v8.
104
+ const esmImportFunctionName = 'ModuleJob.run';
105
+ if (esmImportFunctionName) {
106
+ for (let i = frames.length - 1; i >= 2; i--) {
107
+ if (frames[i].functionName === esmImportFunctionName) {
108
+ return 'import';
109
+ }
110
+ }
111
+ }
112
+
113
+ // Otherwise this was a manual `require(...)` of the agent in user code.
114
+ return 'require';
115
+ }
116
+
117
+ module.exports = {
118
+ agentActivationMethodFromStartStack,
119
+ };