autotel-plugins 0.19.25 → 0.19.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5,58 +5,66 @@ var traceHelpers = require('autotel/trace-helpers');
5
5
  var api = require('@opentelemetry/api');
6
6
 
7
7
  // src/common/constants.ts
8
- var SEMATTRS_DB_SYSTEM = "db.system";
9
- var SEMATTRS_DB_SYSTEM_NAME = "db.system.name";
10
- var SEMATTRS_DB_OPERATION = "db.operation";
11
- var SEMATTRS_DB_STATEMENT = "db.statement";
12
- var SEMATTRS_DB_NAME = "db.name";
13
- var SEMATTRS_DB_NAMESPACE = "db.namespace";
14
- var SEMATTRS_DB_COLLECTION_NAME = "db.collection.name";
15
- var SEMATTRS_DB_OPERATION_NAME = "db.operation.name";
16
- var SEMATTRS_DB_QUERY_TEXT = "db.query.text";
17
- var SEMATTRS_DB_QUERY_SUMMARY = "db.query.summary";
18
- var SEMATTRS_NET_PEER_NAME = "net.peer.name";
19
- var SEMATTRS_NET_PEER_PORT = "net.peer.port";
20
- var SEMATTRS_MESSAGING_SYSTEM = "messaging.system";
21
- var SEMATTRS_MESSAGING_DESTINATION_NAME = "messaging.destination.name";
22
- var SEMATTRS_MESSAGING_OPERATION = "messaging.operation";
23
- var SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer.group";
24
- var SEMATTRS_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition";
25
- var SEMATTRS_MESSAGING_KAFKA_OFFSET = "messaging.kafka.offset";
26
- var SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message.key";
27
- var SEMATTRS_LINKED_TRACE_ID_COUNT = "linked_trace_id_count";
28
- var SEMATTRS_LINKED_TRACE_ID_HASH = "linked_trace_id_hash";
29
- var CORRELATION_ID_HEADER = "x-correlation-id";
30
- var SEMATTRS_GCP_BIGQUERY_JOB_ID = "gcp.bigquery.job.id";
31
- var SEMATTRS_GCP_BIGQUERY_JOB_LOCATION = "gcp.bigquery.job.location";
32
- var SEMATTRS_GCP_BIGQUERY_PROJECT_ID = "gcp.bigquery.project.id";
33
- var SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE = "gcp.bigquery.destination.table";
34
- var SEMATTRS_GCP_BIGQUERY_SOURCE_TABLES = "gcp.bigquery.source.tables";
35
- var SEMATTRS_GCP_BIGQUERY_STATEMENT_TYPE = "gcp.bigquery.statement_type";
36
- var SEMATTRS_GCP_BIGQUERY_QUERY_HASH = "gcp.bigquery.query.hash";
37
- var SEMATTRS_GCP_BIGQUERY_ROWS_AFFECTED = "gcp.bigquery.rows.affected";
38
- var SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED = "gcp.bigquery.rows.returned";
39
- var SEMATTRS_GCP_BIGQUERY_SCHEMA_FIELDS = "gcp.bigquery.schema.fields";
40
- var SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY = "messaging.rabbitmq.destination.routing_key";
41
- var SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_EXCHANGE = "messaging.rabbitmq.destination.exchange";
42
- var SEMATTRS_MESSAGING_RABBITMQ_ACK_RESULT = "messaging.rabbitmq.ack_result";
43
- var SEMATTRS_MESSAGING_RABBITMQ_REQUEUE = "messaging.rabbitmq.requeue";
44
- var SEMATTRS_MESSAGING_MESSAGE_ID = "messaging.message.id";
45
- var SEMATTRS_MESSAGING_MESSAGE_CONVERSATION_ID = "messaging.message.conversation_id";
46
- var SEMATTRS_MESSAGING_CONSUMER_ID = "messaging.consumer.id";
47
- var SEMATTRS_MESSAGING_OPERATION_NAME = "messaging.operation.name";
48
- var SEMATTRS_MESSAGING_BATCH_MESSAGE_COUNT = "messaging.batch.message_count";
49
- var SEMATTRS_MESSAGING_KAFKA_BATCH_FIRST_OFFSET = "messaging.kafka.batch.first_offset";
50
- var SEMATTRS_MESSAGING_KAFKA_BATCH_LAST_OFFSET = "messaging.kafka.batch.last_offset";
51
- var SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_PROCESSED = "messaging.kafka.batch.messages_processed";
52
- var SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_FAILED = "messaging.kafka.batch.messages_failed";
53
- var SEMATTRS_MESSAGING_KAFKA_BATCH_PROCESSING_TIME_MS = "messaging.kafka.batch.processing_time_ms";
54
- var DEFAULT_TRACER_NAME = "autotel-plugins/bigquery";
55
- var DEFAULT_DB_SYSTEM_NAME = "gcp.bigquery";
56
- var INSTRUMENTED_FLAG = "__autotelBigQueryInstrumented";
57
- var PROTOTYPE_INSTRUMENTED_FLAG = "__autotelBigQueryPrototypeInstrumented";
58
- var CONFIG_STORAGE_KEY = "__autotelBigQueryConfig";
59
- var TRACER_STORAGE_KEY = "__autotelBigQueryTracer";
8
+ var SEMATTRS_DB_SYSTEM = 'db.system';
9
+ var SEMATTRS_DB_SYSTEM_NAME = 'db.system.name';
10
+ var SEMATTRS_DB_OPERATION = 'db.operation';
11
+ var SEMATTRS_DB_STATEMENT = 'db.statement';
12
+ var SEMATTRS_DB_NAME = 'db.name';
13
+ var SEMATTRS_DB_NAMESPACE = 'db.namespace';
14
+ var SEMATTRS_DB_COLLECTION_NAME = 'db.collection.name';
15
+ var SEMATTRS_DB_OPERATION_NAME = 'db.operation.name';
16
+ var SEMATTRS_DB_QUERY_TEXT = 'db.query.text';
17
+ var SEMATTRS_DB_QUERY_SUMMARY = 'db.query.summary';
18
+ var SEMATTRS_NET_PEER_NAME = 'net.peer.name';
19
+ var SEMATTRS_NET_PEER_PORT = 'net.peer.port';
20
+ var SEMATTRS_MESSAGING_SYSTEM = 'messaging.system';
21
+ var SEMATTRS_MESSAGING_DESTINATION_NAME = 'messaging.destination.name';
22
+ var SEMATTRS_MESSAGING_OPERATION = 'messaging.operation';
23
+ var SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = 'messaging.kafka.consumer.group';
24
+ var SEMATTRS_MESSAGING_KAFKA_PARTITION = 'messaging.kafka.partition';
25
+ var SEMATTRS_MESSAGING_KAFKA_OFFSET = 'messaging.kafka.offset';
26
+ var SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = 'messaging.kafka.message.key';
27
+ var SEMATTRS_LINKED_TRACE_ID_COUNT = 'linked_trace_id_count';
28
+ var SEMATTRS_LINKED_TRACE_ID_HASH = 'linked_trace_id_hash';
29
+ var CORRELATION_ID_HEADER = 'x-correlation-id';
30
+ var SEMATTRS_GCP_BIGQUERY_JOB_ID = 'gcp.bigquery.job.id';
31
+ var SEMATTRS_GCP_BIGQUERY_JOB_LOCATION = 'gcp.bigquery.job.location';
32
+ var SEMATTRS_GCP_BIGQUERY_PROJECT_ID = 'gcp.bigquery.project.id';
33
+ var SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE = 'gcp.bigquery.destination.table';
34
+ var SEMATTRS_GCP_BIGQUERY_SOURCE_TABLES = 'gcp.bigquery.source.tables';
35
+ var SEMATTRS_GCP_BIGQUERY_STATEMENT_TYPE = 'gcp.bigquery.statement_type';
36
+ var SEMATTRS_GCP_BIGQUERY_QUERY_HASH = 'gcp.bigquery.query.hash';
37
+ var SEMATTRS_GCP_BIGQUERY_ROWS_AFFECTED = 'gcp.bigquery.rows.affected';
38
+ var SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED = 'gcp.bigquery.rows.returned';
39
+ var SEMATTRS_GCP_BIGQUERY_SCHEMA_FIELDS = 'gcp.bigquery.schema.fields';
40
+ var SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY =
41
+ 'messaging.rabbitmq.destination.routing_key';
42
+ var SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_EXCHANGE =
43
+ 'messaging.rabbitmq.destination.exchange';
44
+ var SEMATTRS_MESSAGING_RABBITMQ_ACK_RESULT = 'messaging.rabbitmq.ack_result';
45
+ var SEMATTRS_MESSAGING_RABBITMQ_REQUEUE = 'messaging.rabbitmq.requeue';
46
+ var SEMATTRS_MESSAGING_MESSAGE_ID = 'messaging.message.id';
47
+ var SEMATTRS_MESSAGING_MESSAGE_CONVERSATION_ID =
48
+ 'messaging.message.conversation_id';
49
+ var SEMATTRS_MESSAGING_CONSUMER_ID = 'messaging.consumer.id';
50
+ var SEMATTRS_MESSAGING_OPERATION_NAME = 'messaging.operation.name';
51
+ var SEMATTRS_MESSAGING_BATCH_MESSAGE_COUNT = 'messaging.batch.message_count';
52
+ var SEMATTRS_MESSAGING_KAFKA_BATCH_FIRST_OFFSET =
53
+ 'messaging.kafka.batch.first_offset';
54
+ var SEMATTRS_MESSAGING_KAFKA_BATCH_LAST_OFFSET =
55
+ 'messaging.kafka.batch.last_offset';
56
+ var SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_PROCESSED =
57
+ 'messaging.kafka.batch.messages_processed';
58
+ var SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_FAILED =
59
+ 'messaging.kafka.batch.messages_failed';
60
+ var SEMATTRS_MESSAGING_KAFKA_BATCH_PROCESSING_TIME_MS =
61
+ 'messaging.kafka.batch.processing_time_ms';
62
+ var DEFAULT_TRACER_NAME = 'autotel-plugins/bigquery';
63
+ var DEFAULT_DB_SYSTEM_NAME = 'gcp.bigquery';
64
+ var INSTRUMENTED_FLAG = '__autotelBigQueryInstrumented';
65
+ var PROTOTYPE_INSTRUMENTED_FLAG = '__autotelBigQueryPrototypeInstrumented';
66
+ var CONFIG_STORAGE_KEY = '__autotelBigQueryConfig';
67
+ var TRACER_STORAGE_KEY = '__autotelBigQueryTracer';
60
68
  function getInstanceConfig(instance) {
61
69
  if (instance?.[CONFIG_STORAGE_KEY]) {
62
70
  return instance[CONFIG_STORAGE_KEY];
@@ -104,13 +112,13 @@ function extractOperationType(query) {
104
112
  function createQuerySummary(query) {
105
113
  const operation = extractOperationType(query);
106
114
  if (!operation) {
107
- return "UNKNOWN";
115
+ return 'UNKNOWN';
108
116
  }
109
117
  const patterns = {
110
118
  SELECT: /FROM\s+(?<table>[\w.]+)/iu,
111
119
  INSERT: /INTO\s+(?<table>[\w.]+)/iu,
112
120
  UPDATE: /UPDATE\s+(?<table>[\w.]+)/iu,
113
- DELETE: /FROM\s+(?<table>[\w.]+)/iu
121
+ DELETE: /FROM\s+(?<table>[\w.]+)/iu,
114
122
  };
115
123
  const pattern = patterns[operation];
116
124
  if (pattern) {
@@ -125,9 +133,9 @@ function createQuerySummary(query) {
125
133
  function sanitizeQuery(query) {
126
134
  let sanitized = query.replaceAll(/'(?:[^'\\]|\\.)*'/gu, "'?'");
127
135
  sanitized = sanitized.replaceAll(/"(?:[^"\\]|\\.)*"/gu, '"?"');
128
- sanitized = sanitized.replaceAll(/\b\d+\.?\d*\b/gu, "?");
129
- sanitized = sanitized.replaceAll(/\b(?:true|false)\b/giu, "?");
130
- sanitized = sanitized.replaceAll(/\bNULL\b/giu, "?");
136
+ sanitized = sanitized.replaceAll(/\b\d+\.?\d*\b/gu, '?');
137
+ sanitized = sanitized.replaceAll(/\b(?:true|false)\b/giu, '?');
138
+ sanitized = sanitized.replaceAll(/\bNULL\b/giu, '?');
131
139
  return sanitized;
132
140
  }
133
141
  function truncateText(text, maxLength) {
@@ -156,7 +164,7 @@ function extractTableReference(obj) {
156
164
  return {
157
165
  projectId: obj.dataset?.parent?.projectId || obj.parent?.projectId,
158
166
  datasetId: obj.dataset?.id || obj.parent?.datasetId,
159
- tableId: obj.id
167
+ tableId: obj.id,
160
168
  };
161
169
  }
162
170
  if (obj.metadata?.tableReference) {
@@ -171,55 +179,63 @@ function createSpan(tracer, operationName, target, projectId, config = {}) {
171
179
  const spanName = target ? `${operationName} ${target}` : operationName;
172
180
  const attributes = {
173
181
  [SEMATTRS_DB_SYSTEM_NAME]: DEFAULT_DB_SYSTEM_NAME,
174
- [SEMATTRS_DB_OPERATION_NAME]: operationName
182
+ [SEMATTRS_DB_OPERATION_NAME]: operationName,
175
183
  };
176
184
  if (projectId || config.projectId) {
177
- attributes[SEMATTRS_GCP_BIGQUERY_PROJECT_ID] = projectId || config.projectId;
185
+ attributes[SEMATTRS_GCP_BIGQUERY_PROJECT_ID] =
186
+ projectId || config.projectId;
178
187
  }
179
188
  if (config.location) {
180
189
  attributes[SEMATTRS_GCP_BIGQUERY_JOB_LOCATION] = config.location;
181
190
  }
182
- return tracer.startSpan(spanName, { kind: autotel.SpanKind.CLIENT, attributes });
191
+ return tracer.startSpan(spanName, {
192
+ kind: autotel.SpanKind.CLIENT,
193
+ attributes,
194
+ });
183
195
  }
184
196
  function instrumentQueryMethod(BigQuery) {
185
197
  const originalQuery = BigQuery.prototype.query;
186
- if (typeof originalQuery !== "function") {
198
+ if (typeof originalQuery !== 'function') {
187
199
  return;
188
200
  }
189
- BigQuery.prototype.query = function instrumentedQuery(query, options, callback) {
201
+ BigQuery.prototype.query = function instrumentedQuery(
202
+ query,
203
+ options,
204
+ callback,
205
+ ) {
190
206
  const config = getInstanceConfig(this);
191
207
  const tracer = getInstanceTracer(this);
192
208
  if (!config || !tracer) {
193
209
  return originalQuery.call(this, query, options, callback);
194
210
  }
195
- const queryText = typeof query === "string" ? query : query.query;
211
+ const queryText = typeof query === 'string' ? query : query.query;
196
212
  const projectId = extractProjectId(this);
197
213
  const location = extractLocation(this, options);
198
- const operation = queryText ? extractOperationType(queryText) : "QUERY";
199
- const summary = queryText ? createQuerySummary(queryText) : "QUERY";
214
+ const operation = queryText ? extractOperationType(queryText) : 'QUERY';
215
+ const summary = queryText ? createQuerySummary(queryText) : 'QUERY';
200
216
  const span = createSpan(
201
217
  tracer,
202
- operation || "QUERY",
218
+ operation || 'QUERY',
203
219
  summary,
204
220
  projectId,
205
- config
221
+ config,
206
222
  );
207
223
  if (location) {
208
224
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
209
225
  }
210
226
  span.setAttribute(SEMATTRS_DB_QUERY_SUMMARY, summary);
211
- if (config.captureQueryText !== "never" && queryText) {
212
- if (config.captureQueryText === "raw") {
227
+ if (config.captureQueryText !== 'never' && queryText) {
228
+ if (config.captureQueryText === 'raw') {
213
229
  const truncated = truncateText(
214
230
  queryText,
215
- config.maxQueryTextLength || 1e3
231
+ config.maxQueryTextLength || 1e3,
216
232
  );
217
233
  span.setAttribute(SEMATTRS_DB_QUERY_TEXT, truncated);
218
- } else if (config.captureQueryText === "sanitized") {
234
+ } else if (config.captureQueryText === 'sanitized') {
219
235
  const sanitized = sanitizeQuery(queryText);
220
236
  const truncated = truncateText(
221
237
  sanitized,
222
- config.maxQueryTextLength || 1e3
238
+ config.maxQueryTextLength || 1e3,
223
239
  );
224
240
  span.setAttribute(SEMATTRS_DB_QUERY_TEXT, truncated);
225
241
  }
@@ -230,16 +246,18 @@ function instrumentQueryMethod(BigQuery) {
230
246
  if (options?.destination) {
231
247
  const dest = extractTableReference(options.destination);
232
248
  if (dest.tableId) {
233
- const destTable = dest.datasetId ? `${dest.datasetId}.${dest.tableId}` : dest.tableId;
249
+ const destTable = dest.datasetId
250
+ ? `${dest.datasetId}.${dest.tableId}`
251
+ : dest.tableId;
234
252
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE, destTable);
235
253
  }
236
254
  }
237
- if (typeof callback === "function") {
255
+ if (typeof callback === 'function') {
238
256
  const wrappedCallback = (err, ...args) => {
239
257
  if (err) {
240
258
  traceHelpers.finalizeSpan(
241
259
  span,
242
- err instanceof Error ? err : new Error(String(err))
260
+ err instanceof Error ? err : new Error(String(err)),
243
261
  );
244
262
  } else {
245
263
  const [rows, response] = args;
@@ -249,7 +267,7 @@ function instrumentQueryMethod(BigQuery) {
249
267
  if (response?.jobReference?.jobId) {
250
268
  span.setAttribute(
251
269
  SEMATTRS_GCP_BIGQUERY_JOB_ID,
252
- response.jobReference.jobId
270
+ response.jobReference.jobId,
253
271
  );
254
272
  }
255
273
  traceHelpers.finalizeSpan(span);
@@ -261,32 +279,34 @@ function instrumentQueryMethod(BigQuery) {
261
279
  return traceHelpers.runWithSpan(span, () => {
262
280
  try {
263
281
  const result = originalQuery.call(this, query, options);
264
- return Promise.resolve(result).then(([rows, response]) => {
265
- if (Array.isArray(rows)) {
266
- span.setAttribute(
267
- SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED,
268
- rows.length
269
- );
270
- }
271
- if (response?.jobReference?.jobId) {
272
- span.setAttribute(
273
- SEMATTRS_GCP_BIGQUERY_JOB_ID,
274
- response.jobReference.jobId
282
+ return Promise.resolve(result)
283
+ .then(([rows, response]) => {
284
+ if (Array.isArray(rows)) {
285
+ span.setAttribute(
286
+ SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED,
287
+ rows.length,
288
+ );
289
+ }
290
+ if (response?.jobReference?.jobId) {
291
+ span.setAttribute(
292
+ SEMATTRS_GCP_BIGQUERY_JOB_ID,
293
+ response.jobReference.jobId,
294
+ );
295
+ }
296
+ traceHelpers.finalizeSpan(span);
297
+ return [rows, response];
298
+ })
299
+ .catch((error) => {
300
+ traceHelpers.finalizeSpan(
301
+ span,
302
+ error instanceof Error ? error : new Error(String(error)),
275
303
  );
276
- }
277
- traceHelpers.finalizeSpan(span);
278
- return [rows, response];
279
- }).catch((error) => {
280
- traceHelpers.finalizeSpan(
281
- span,
282
- error instanceof Error ? error : new Error(String(error))
283
- );
284
- throw error;
285
- });
304
+ throw error;
305
+ });
286
306
  } catch (error) {
287
307
  traceHelpers.finalizeSpan(
288
308
  span,
289
- error instanceof Error ? error : new Error(String(error))
309
+ error instanceof Error ? error : new Error(String(error)),
290
310
  );
291
311
  throw error;
292
312
  }
@@ -295,43 +315,45 @@ function instrumentQueryMethod(BigQuery) {
295
315
  }
296
316
  function instrumentCreateQueryJob(BigQuery) {
297
317
  const originalCreateQueryJob = BigQuery.prototype.createQueryJob;
298
- if (typeof originalCreateQueryJob !== "function") {
318
+ if (typeof originalCreateQueryJob !== 'function') {
299
319
  return;
300
320
  }
301
- BigQuery.prototype.createQueryJob = function instrumentedCreateQueryJob(options) {
321
+ BigQuery.prototype.createQueryJob = function instrumentedCreateQueryJob(
322
+ options,
323
+ ) {
302
324
  const config = getInstanceConfig(this);
303
325
  const tracer = getInstanceTracer(this);
304
326
  if (!config || !tracer) {
305
327
  return originalCreateQueryJob.call(this, options);
306
328
  }
307
- const queryText = typeof options === "string" ? options : options.query;
329
+ const queryText = typeof options === 'string' ? options : options.query;
308
330
  const projectId = extractProjectId(this);
309
331
  const location = extractLocation(this, options);
310
- const operation = queryText ? extractOperationType(queryText) : "QUERY";
311
- const summary = queryText ? createQuerySummary(queryText) : "QUERY";
332
+ const operation = queryText ? extractOperationType(queryText) : 'QUERY';
333
+ const summary = queryText ? createQuerySummary(queryText) : 'QUERY';
312
334
  const span = createSpan(
313
335
  tracer,
314
- `${operation || "QUERY"}_JOB`,
336
+ `${operation || 'QUERY'}_JOB`,
315
337
  summary,
316
338
  projectId,
317
- config
339
+ config,
318
340
  );
319
341
  if (location) {
320
342
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
321
343
  }
322
344
  span.setAttribute(SEMATTRS_DB_QUERY_SUMMARY, summary);
323
- if (config.captureQueryText !== "never" && queryText) {
324
- if (config.captureQueryText === "raw") {
345
+ if (config.captureQueryText !== 'never' && queryText) {
346
+ if (config.captureQueryText === 'raw') {
325
347
  const truncated = truncateText(
326
348
  queryText,
327
- config.maxQueryTextLength || 1e3
349
+ config.maxQueryTextLength || 1e3,
328
350
  );
329
351
  span.setAttribute(SEMATTRS_DB_QUERY_TEXT, truncated);
330
- } else if (config.captureQueryText === "sanitized") {
352
+ } else if (config.captureQueryText === 'sanitized') {
331
353
  const sanitized = sanitizeQuery(queryText);
332
354
  const truncated = truncateText(
333
355
  sanitized,
334
- config.maxQueryTextLength || 1e3
356
+ config.maxQueryTextLength || 1e3,
335
357
  );
336
358
  span.setAttribute(SEMATTRS_DB_QUERY_TEXT, truncated);
337
359
  }
@@ -342,35 +364,39 @@ function instrumentCreateQueryJob(BigQuery) {
342
364
  if (options?.destination) {
343
365
  const dest = extractTableReference(options.destination);
344
366
  if (dest.tableId) {
345
- const destTable = dest.datasetId ? `${dest.datasetId}.${dest.tableId}` : dest.tableId;
367
+ const destTable = dest.datasetId
368
+ ? `${dest.datasetId}.${dest.tableId}`
369
+ : dest.tableId;
346
370
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE, destTable);
347
371
  }
348
372
  }
349
373
  return traceHelpers.runWithSpan(span, () => {
350
374
  try {
351
375
  const result = originalCreateQueryJob.call(this, options);
352
- return Promise.resolve(result).then(([job, response]) => {
353
- if (job?.id) {
354
- span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, job.id);
355
- } else if (response?.jobReference?.jobId) {
356
- span.setAttribute(
357
- SEMATTRS_GCP_BIGQUERY_JOB_ID,
358
- response.jobReference.jobId
376
+ return Promise.resolve(result)
377
+ .then(([job, response]) => {
378
+ if (job?.id) {
379
+ span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, job.id);
380
+ } else if (response?.jobReference?.jobId) {
381
+ span.setAttribute(
382
+ SEMATTRS_GCP_BIGQUERY_JOB_ID,
383
+ response.jobReference.jobId,
384
+ );
385
+ }
386
+ traceHelpers.finalizeSpan(span);
387
+ return [job, response];
388
+ })
389
+ .catch((error) => {
390
+ traceHelpers.finalizeSpan(
391
+ span,
392
+ error instanceof Error ? error : new Error(String(error)),
359
393
  );
360
- }
361
- traceHelpers.finalizeSpan(span);
362
- return [job, response];
363
- }).catch((error) => {
364
- traceHelpers.finalizeSpan(
365
- span,
366
- error instanceof Error ? error : new Error(String(error))
367
- );
368
- throw error;
369
- });
394
+ throw error;
395
+ });
370
396
  } catch (error) {
371
397
  traceHelpers.finalizeSpan(
372
398
  span,
373
- error instanceof Error ? error : new Error(String(error))
399
+ error instanceof Error ? error : new Error(String(error)),
374
400
  );
375
401
  throw error;
376
402
  }
@@ -379,7 +405,7 @@ function instrumentCreateQueryJob(BigQuery) {
379
405
  }
380
406
  function instrumentTableInsert(Table) {
381
407
  const originalInsert = Table.prototype.insert;
382
- if (typeof originalInsert !== "function") {
408
+ if (typeof originalInsert !== 'function') {
383
409
  return;
384
410
  }
385
411
  Table.prototype.insert = function instrumentedInsert(rows, options) {
@@ -392,10 +418,14 @@ function instrumentTableInsert(Table) {
392
418
  const projectId = extractProjectId(this.dataset?.parent || this.parent);
393
419
  const location = extractLocation(
394
420
  this.dataset?.parent || this.parent,
395
- options
421
+ options,
396
422
  );
397
- const target = tableRef.tableId ? tableRef.datasetId ? `${tableRef.datasetId}.${tableRef.tableId}` : tableRef.tableId : void 0;
398
- const span = createSpan(tracer, "INSERT", target, projectId, config);
423
+ const target = tableRef.tableId
424
+ ? tableRef.datasetId
425
+ ? `${tableRef.datasetId}.${tableRef.tableId}`
426
+ : tableRef.tableId
427
+ : void 0;
428
+ const span = createSpan(tracer, 'INSERT', target, projectId, config);
399
429
  if (location) {
400
430
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
401
431
  }
@@ -410,26 +440,28 @@ function instrumentTableInsert(Table) {
410
440
  return traceHelpers.runWithSpan(span, () => {
411
441
  try {
412
442
  const result = originalInsert.call(this, rows, options);
413
- return Promise.resolve(result).then((response) => {
414
- if (response?.insertErrors?.length > 0) {
415
- span.setAttribute(
416
- "gcp.bigquery.insert.errors",
417
- response.insertErrors.length
443
+ return Promise.resolve(result)
444
+ .then((response) => {
445
+ if (response?.insertErrors?.length > 0) {
446
+ span.setAttribute(
447
+ 'gcp.bigquery.insert.errors',
448
+ response.insertErrors.length,
449
+ );
450
+ }
451
+ traceHelpers.finalizeSpan(span);
452
+ return response;
453
+ })
454
+ .catch((error) => {
455
+ traceHelpers.finalizeSpan(
456
+ span,
457
+ error instanceof Error ? error : new Error(String(error)),
418
458
  );
419
- }
420
- traceHelpers.finalizeSpan(span);
421
- return response;
422
- }).catch((error) => {
423
- traceHelpers.finalizeSpan(
424
- span,
425
- error instanceof Error ? error : new Error(String(error))
426
- );
427
- throw error;
428
- });
459
+ throw error;
460
+ });
429
461
  } catch (error) {
430
462
  traceHelpers.finalizeSpan(
431
463
  span,
432
- error instanceof Error ? error : new Error(String(error))
464
+ error instanceof Error ? error : new Error(String(error)),
433
465
  );
434
466
  throw error;
435
467
  }
@@ -438,7 +470,7 @@ function instrumentTableInsert(Table) {
438
470
  }
439
471
  function instrumentTableGetRows(Table) {
440
472
  const originalGetRows = Table.prototype.getRows;
441
- if (typeof originalGetRows !== "function") {
473
+ if (typeof originalGetRows !== 'function') {
442
474
  return;
443
475
  }
444
476
  Table.prototype.getRows = function instrumentedGetRows(options) {
@@ -451,10 +483,14 @@ function instrumentTableGetRows(Table) {
451
483
  const projectId = extractProjectId(this.dataset?.parent || this.parent);
452
484
  const location = extractLocation(
453
485
  this.dataset?.parent || this.parent,
454
- options
486
+ options,
455
487
  );
456
- const target = tableRef.tableId ? tableRef.datasetId ? `${tableRef.datasetId}.${tableRef.tableId}` : tableRef.tableId : void 0;
457
- const span = createSpan(tracer, "SELECT", target, projectId, config);
488
+ const target = tableRef.tableId
489
+ ? tableRef.datasetId
490
+ ? `${tableRef.datasetId}.${tableRef.tableId}`
491
+ : tableRef.tableId
492
+ : void 0;
493
+ const span = createSpan(tracer, 'SELECT', target, projectId, config);
458
494
  if (location) {
459
495
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
460
496
  }
@@ -467,26 +503,28 @@ function instrumentTableGetRows(Table) {
467
503
  return traceHelpers.runWithSpan(span, () => {
468
504
  try {
469
505
  const result = originalGetRows.call(this, options);
470
- return Promise.resolve(result).then(([rows, nextQuery, apiResponse]) => {
471
- if (Array.isArray(rows)) {
472
- span.setAttribute(
473
- SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED,
474
- rows.length
506
+ return Promise.resolve(result)
507
+ .then(([rows, nextQuery, apiResponse]) => {
508
+ if (Array.isArray(rows)) {
509
+ span.setAttribute(
510
+ SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED,
511
+ rows.length,
512
+ );
513
+ }
514
+ traceHelpers.finalizeSpan(span);
515
+ return [rows, nextQuery, apiResponse];
516
+ })
517
+ .catch((error) => {
518
+ traceHelpers.finalizeSpan(
519
+ span,
520
+ error instanceof Error ? error : new Error(String(error)),
475
521
  );
476
- }
477
- traceHelpers.finalizeSpan(span);
478
- return [rows, nextQuery, apiResponse];
479
- }).catch((error) => {
480
- traceHelpers.finalizeSpan(
481
- span,
482
- error instanceof Error ? error : new Error(String(error))
483
- );
484
- throw error;
485
- });
522
+ throw error;
523
+ });
486
524
  } catch (error) {
487
525
  traceHelpers.finalizeSpan(
488
526
  span,
489
- error instanceof Error ? error : new Error(String(error))
527
+ error instanceof Error ? error : new Error(String(error)),
490
528
  );
491
529
  throw error;
492
530
  }
@@ -495,10 +533,13 @@ function instrumentTableGetRows(Table) {
495
533
  }
496
534
  function instrumentTableCreateLoadJob(Table) {
497
535
  const originalCreateLoadJob = Table.prototype.createLoadJob;
498
- if (typeof originalCreateLoadJob !== "function") {
536
+ if (typeof originalCreateLoadJob !== 'function') {
499
537
  return;
500
538
  }
501
- Table.prototype.createLoadJob = function instrumentedCreateLoadJob(source, metadata) {
539
+ Table.prototype.createLoadJob = function instrumentedCreateLoadJob(
540
+ source,
541
+ metadata,
542
+ ) {
502
543
  const config = getInstanceConfig(this);
503
544
  const tracer = getInstanceTracer(this);
504
545
  if (!config || !tracer) {
@@ -508,10 +549,14 @@ function instrumentTableCreateLoadJob(Table) {
508
549
  const projectId = extractProjectId(this.dataset?.parent || this.parent);
509
550
  const location = extractLocation(
510
551
  this.dataset?.parent || this.parent,
511
- metadata
552
+ metadata,
512
553
  );
513
- const target = tableRef.tableId ? tableRef.datasetId ? `${tableRef.datasetId}.${tableRef.tableId}` : tableRef.tableId : void 0;
514
- const span = createSpan(tracer, "LOAD", target, projectId, config);
554
+ const target = tableRef.tableId
555
+ ? tableRef.datasetId
556
+ ? `${tableRef.datasetId}.${tableRef.tableId}`
557
+ : tableRef.tableId
558
+ : void 0;
559
+ const span = createSpan(tracer, 'LOAD', target, projectId, config);
515
560
  if (location) {
516
561
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
517
562
  }
@@ -522,28 +567,30 @@ function instrumentTableCreateLoadJob(Table) {
522
567
  span.setAttribute(SEMATTRS_DB_COLLECTION_NAME, tableRef.tableId);
523
568
  }
524
569
  if (metadata?.sourceFormat) {
525
- span.setAttribute("gcp.bigquery.source.format", metadata.sourceFormat);
570
+ span.setAttribute('gcp.bigquery.source.format', metadata.sourceFormat);
526
571
  }
527
572
  return traceHelpers.runWithSpan(span, () => {
528
573
  try {
529
574
  const result = originalCreateLoadJob.call(this, source, metadata);
530
- return Promise.resolve(result).then(([job, response]) => {
531
- if (job?.id) {
532
- span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, job.id);
533
- }
534
- traceHelpers.finalizeSpan(span);
535
- return [job, response];
536
- }).catch((error) => {
537
- traceHelpers.finalizeSpan(
538
- span,
539
- error instanceof Error ? error : new Error(String(error))
540
- );
541
- throw error;
542
- });
575
+ return Promise.resolve(result)
576
+ .then(([job, response]) => {
577
+ if (job?.id) {
578
+ span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, job.id);
579
+ }
580
+ traceHelpers.finalizeSpan(span);
581
+ return [job, response];
582
+ })
583
+ .catch((error) => {
584
+ traceHelpers.finalizeSpan(
585
+ span,
586
+ error instanceof Error ? error : new Error(String(error)),
587
+ );
588
+ throw error;
589
+ });
543
590
  } catch (error) {
544
591
  traceHelpers.finalizeSpan(
545
592
  span,
546
- error instanceof Error ? error : new Error(String(error))
593
+ error instanceof Error ? error : new Error(String(error)),
547
594
  );
548
595
  throw error;
549
596
  }
@@ -552,10 +599,13 @@ function instrumentTableCreateLoadJob(Table) {
552
599
  }
553
600
  function instrumentTableCreateCopyJob(Table) {
554
601
  const originalCreateCopyJob = Table.prototype.createCopyJob;
555
- if (typeof originalCreateCopyJob !== "function") {
602
+ if (typeof originalCreateCopyJob !== 'function') {
556
603
  return;
557
604
  }
558
- Table.prototype.createCopyJob = function instrumentedCreateCopyJob(destination, metadata) {
605
+ Table.prototype.createCopyJob = function instrumentedCreateCopyJob(
606
+ destination,
607
+ metadata,
608
+ ) {
559
609
  const config = getInstanceConfig(this);
560
610
  const tracer = getInstanceTracer(this);
561
611
  if (!config || !tracer) {
@@ -565,16 +615,24 @@ function instrumentTableCreateCopyJob(Table) {
565
615
  const projectId = extractProjectId(this.dataset?.parent || this.parent);
566
616
  const location = extractLocation(
567
617
  this.dataset?.parent || this.parent,
568
- metadata
618
+ metadata,
569
619
  );
570
- const source = sourceRef.tableId ? sourceRef.datasetId ? `${sourceRef.datasetId}.${sourceRef.tableId}` : sourceRef.tableId : "unknown";
571
- const span = createSpan(tracer, "COPY", source, projectId, config);
620
+ const source = sourceRef.tableId
621
+ ? sourceRef.datasetId
622
+ ? `${sourceRef.datasetId}.${sourceRef.tableId}`
623
+ : sourceRef.tableId
624
+ : 'unknown';
625
+ const span = createSpan(tracer, 'COPY', source, projectId, config);
572
626
  if (location) {
573
627
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
574
628
  }
575
629
  if (destination) {
576
630
  const destRef = extractTableReference(destination);
577
- const destTable = destRef.tableId ? destRef.datasetId ? `${destRef.datasetId}.${destRef.tableId}` : destRef.tableId : void 0;
631
+ const destTable = destRef.tableId
632
+ ? destRef.datasetId
633
+ ? `${destRef.datasetId}.${destRef.tableId}`
634
+ : destRef.tableId
635
+ : void 0;
578
636
  if (destTable) {
579
637
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE, destTable);
580
638
  }
@@ -582,23 +640,25 @@ function instrumentTableCreateCopyJob(Table) {
582
640
  return traceHelpers.runWithSpan(span, () => {
583
641
  try {
584
642
  const result = originalCreateCopyJob.call(this, destination, metadata);
585
- return Promise.resolve(result).then(([job, response]) => {
586
- if (job?.id) {
587
- span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, job.id);
588
- }
589
- traceHelpers.finalizeSpan(span);
590
- return [job, response];
591
- }).catch((error) => {
592
- traceHelpers.finalizeSpan(
593
- span,
594
- error instanceof Error ? error : new Error(String(error))
595
- );
596
- throw error;
597
- });
643
+ return Promise.resolve(result)
644
+ .then(([job, response]) => {
645
+ if (job?.id) {
646
+ span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, job.id);
647
+ }
648
+ traceHelpers.finalizeSpan(span);
649
+ return [job, response];
650
+ })
651
+ .catch((error) => {
652
+ traceHelpers.finalizeSpan(
653
+ span,
654
+ error instanceof Error ? error : new Error(String(error)),
655
+ );
656
+ throw error;
657
+ });
598
658
  } catch (error) {
599
659
  traceHelpers.finalizeSpan(
600
660
  span,
601
- error instanceof Error ? error : new Error(String(error))
661
+ error instanceof Error ? error : new Error(String(error)),
602
662
  );
603
663
  throw error;
604
664
  }
@@ -607,10 +667,13 @@ function instrumentTableCreateCopyJob(Table) {
607
667
  }
608
668
  function instrumentTableCreateExtractJob(Table) {
609
669
  const originalCreateExtractJob = Table.prototype.createExtractJob;
610
- if (typeof originalCreateExtractJob !== "function") {
670
+ if (typeof originalCreateExtractJob !== 'function') {
611
671
  return;
612
672
  }
613
- Table.prototype.createExtractJob = function instrumentedCreateExtractJob(destination, metadata) {
673
+ Table.prototype.createExtractJob = function instrumentedCreateExtractJob(
674
+ destination,
675
+ metadata,
676
+ ) {
614
677
  const config = getInstanceConfig(this);
615
678
  const tracer = getInstanceTracer(this);
616
679
  if (!config || !tracer) {
@@ -620,10 +683,14 @@ function instrumentTableCreateExtractJob(Table) {
620
683
  const projectId = extractProjectId(this.dataset?.parent || this.parent);
621
684
  const location = extractLocation(
622
685
  this.dataset?.parent || this.parent,
623
- metadata
686
+ metadata,
624
687
  );
625
- const source = sourceRef.tableId ? sourceRef.datasetId ? `${sourceRef.datasetId}.${sourceRef.tableId}` : sourceRef.tableId : "unknown";
626
- const span = createSpan(tracer, "EXTRACT", source, projectId, config);
688
+ const source = sourceRef.tableId
689
+ ? sourceRef.datasetId
690
+ ? `${sourceRef.datasetId}.${sourceRef.tableId}`
691
+ : sourceRef.tableId
692
+ : 'unknown';
693
+ const span = createSpan(tracer, 'EXTRACT', source, projectId, config);
627
694
  if (location) {
628
695
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
629
696
  }
@@ -633,39 +700,41 @@ function instrumentTableCreateExtractJob(Table) {
633
700
  if (sourceRef.tableId) {
634
701
  span.setAttribute(SEMATTRS_DB_COLLECTION_NAME, sourceRef.tableId);
635
702
  }
636
- if (typeof destination === "string") {
637
- span.setAttribute("gcp.bigquery.destination.uri", destination);
703
+ if (typeof destination === 'string') {
704
+ span.setAttribute('gcp.bigquery.destination.uri', destination);
638
705
  } else if (Array.isArray(destination) && destination.length > 0) {
639
- span.setAttribute("gcp.bigquery.destination.uri", destination[0]);
706
+ span.setAttribute('gcp.bigquery.destination.uri', destination[0]);
640
707
  }
641
708
  const format = metadata?.destinationFormat || metadata?.format;
642
709
  if (format) {
643
- span.setAttribute("gcp.bigquery.destination.format", format);
710
+ span.setAttribute('gcp.bigquery.destination.format', format);
644
711
  }
645
712
  return traceHelpers.runWithSpan(span, () => {
646
713
  try {
647
714
  const result = originalCreateExtractJob.call(
648
715
  this,
649
716
  destination,
650
- metadata
717
+ metadata,
651
718
  );
652
- return Promise.resolve(result).then(([job, response]) => {
653
- if (job?.id) {
654
- span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, job.id);
655
- }
656
- traceHelpers.finalizeSpan(span);
657
- return [job, response];
658
- }).catch((error) => {
659
- traceHelpers.finalizeSpan(
660
- span,
661
- error instanceof Error ? error : new Error(String(error))
662
- );
663
- throw error;
664
- });
719
+ return Promise.resolve(result)
720
+ .then(([job, response]) => {
721
+ if (job?.id) {
722
+ span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, job.id);
723
+ }
724
+ traceHelpers.finalizeSpan(span);
725
+ return [job, response];
726
+ })
727
+ .catch((error) => {
728
+ traceHelpers.finalizeSpan(
729
+ span,
730
+ error instanceof Error ? error : new Error(String(error)),
731
+ );
732
+ throw error;
733
+ });
665
734
  } catch (error) {
666
735
  traceHelpers.finalizeSpan(
667
736
  span,
668
- error instanceof Error ? error : new Error(String(error))
737
+ error instanceof Error ? error : new Error(String(error)),
669
738
  );
670
739
  throw error;
671
740
  }
@@ -674,10 +743,12 @@ function instrumentTableCreateExtractJob(Table) {
674
743
  }
675
744
  function instrumentJobGetQueryResults(Job) {
676
745
  const originalGetQueryResults = Job.prototype.getQueryResults;
677
- if (typeof originalGetQueryResults !== "function") {
746
+ if (typeof originalGetQueryResults !== 'function') {
678
747
  return;
679
748
  }
680
- Job.prototype.getQueryResults = function instrumentedGetQueryResults(options) {
749
+ Job.prototype.getQueryResults = function instrumentedGetQueryResults(
750
+ options,
751
+ ) {
681
752
  const config = getInstanceConfig(this);
682
753
  const tracer = getInstanceTracer(this);
683
754
  if (!config || !tracer) {
@@ -688,10 +759,10 @@ function instrumentJobGetQueryResults(Job) {
688
759
  const location = this.location || options?.location;
689
760
  const span = createSpan(
690
761
  tracer,
691
- "GET_QUERY_RESULTS",
762
+ 'GET_QUERY_RESULTS',
692
763
  void 0,
693
764
  projectId,
694
- config
765
+ config,
695
766
  );
696
767
  if (jobId) {
697
768
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_ID, jobId);
@@ -702,26 +773,28 @@ function instrumentJobGetQueryResults(Job) {
702
773
  return traceHelpers.runWithSpan(span, () => {
703
774
  try {
704
775
  const result = originalGetQueryResults.call(this, options);
705
- return Promise.resolve(result).then(([rows, nextQuery, apiResponse]) => {
706
- if (Array.isArray(rows)) {
707
- span.setAttribute(
708
- SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED,
709
- rows.length
776
+ return Promise.resolve(result)
777
+ .then(([rows, nextQuery, apiResponse]) => {
778
+ if (Array.isArray(rows)) {
779
+ span.setAttribute(
780
+ SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED,
781
+ rows.length,
782
+ );
783
+ }
784
+ traceHelpers.finalizeSpan(span);
785
+ return [rows, nextQuery, apiResponse];
786
+ })
787
+ .catch((error) => {
788
+ traceHelpers.finalizeSpan(
789
+ span,
790
+ error instanceof Error ? error : new Error(String(error)),
710
791
  );
711
- }
712
- traceHelpers.finalizeSpan(span);
713
- return [rows, nextQuery, apiResponse];
714
- }).catch((error) => {
715
- traceHelpers.finalizeSpan(
716
- span,
717
- error instanceof Error ? error : new Error(String(error))
718
- );
719
- throw error;
720
- });
792
+ throw error;
793
+ });
721
794
  } catch (error) {
722
795
  traceHelpers.finalizeSpan(
723
796
  span,
724
- error instanceof Error ? error : new Error(String(error))
797
+ error instanceof Error ? error : new Error(String(error)),
725
798
  );
726
799
  throw error;
727
800
  }
@@ -730,7 +803,7 @@ function instrumentJobGetQueryResults(Job) {
730
803
  }
731
804
  function instrumentDatasetCreate(Dataset) {
732
805
  const originalCreate = Dataset.prototype.create;
733
- if (typeof originalCreate !== "function") {
806
+ if (typeof originalCreate !== 'function') {
734
807
  return;
735
808
  }
736
809
  Dataset.prototype.create = function instrumentedCreate(options) {
@@ -744,10 +817,10 @@ function instrumentDatasetCreate(Dataset) {
744
817
  const location = extractLocation(this.parent, options);
745
818
  const span = createSpan(
746
819
  tracer,
747
- "CREATE_DATASET",
820
+ 'CREATE_DATASET',
748
821
  datasetId,
749
822
  projectId,
750
- config
823
+ config,
751
824
  );
752
825
  if (location) {
753
826
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
@@ -758,20 +831,22 @@ function instrumentDatasetCreate(Dataset) {
758
831
  return traceHelpers.runWithSpan(span, () => {
759
832
  try {
760
833
  const result = originalCreate.call(this, options);
761
- return Promise.resolve(result).then((response) => {
762
- traceHelpers.finalizeSpan(span);
763
- return response;
764
- }).catch((error) => {
765
- traceHelpers.finalizeSpan(
766
- span,
767
- error instanceof Error ? error : new Error(String(error))
768
- );
769
- throw error;
770
- });
834
+ return Promise.resolve(result)
835
+ .then((response) => {
836
+ traceHelpers.finalizeSpan(span);
837
+ return response;
838
+ })
839
+ .catch((error) => {
840
+ traceHelpers.finalizeSpan(
841
+ span,
842
+ error instanceof Error ? error : new Error(String(error)),
843
+ );
844
+ throw error;
845
+ });
771
846
  } catch (error) {
772
847
  traceHelpers.finalizeSpan(
773
848
  span,
774
- error instanceof Error ? error : new Error(String(error))
849
+ error instanceof Error ? error : new Error(String(error)),
775
850
  );
776
851
  throw error;
777
852
  }
@@ -780,7 +855,7 @@ function instrumentDatasetCreate(Dataset) {
780
855
  }
781
856
  function instrumentDatasetDelete(Dataset) {
782
857
  const originalDelete = Dataset.prototype.delete;
783
- if (typeof originalDelete !== "function") {
858
+ if (typeof originalDelete !== 'function') {
784
859
  return;
785
860
  }
786
861
  Dataset.prototype.delete = function instrumentedDelete(options) {
@@ -793,10 +868,10 @@ function instrumentDatasetDelete(Dataset) {
793
868
  const projectId = extractProjectId(this.parent);
794
869
  const span = createSpan(
795
870
  tracer,
796
- "DELETE_DATASET",
871
+ 'DELETE_DATASET',
797
872
  datasetId,
798
873
  projectId,
799
- config
874
+ config,
800
875
  );
801
876
  if (datasetId) {
802
877
  span.setAttribute(SEMATTRS_DB_NAMESPACE, datasetId);
@@ -804,20 +879,22 @@ function instrumentDatasetDelete(Dataset) {
804
879
  return traceHelpers.runWithSpan(span, () => {
805
880
  try {
806
881
  const result = originalDelete.call(this, options);
807
- return Promise.resolve(result).then((response) => {
808
- traceHelpers.finalizeSpan(span);
809
- return response;
810
- }).catch((error) => {
811
- traceHelpers.finalizeSpan(
812
- span,
813
- error instanceof Error ? error : new Error(String(error))
814
- );
815
- throw error;
816
- });
882
+ return Promise.resolve(result)
883
+ .then((response) => {
884
+ traceHelpers.finalizeSpan(span);
885
+ return response;
886
+ })
887
+ .catch((error) => {
888
+ traceHelpers.finalizeSpan(
889
+ span,
890
+ error instanceof Error ? error : new Error(String(error)),
891
+ );
892
+ throw error;
893
+ });
817
894
  } catch (error) {
818
895
  traceHelpers.finalizeSpan(
819
896
  span,
820
- error instanceof Error ? error : new Error(String(error))
897
+ error instanceof Error ? error : new Error(String(error)),
821
898
  );
822
899
  throw error;
823
900
  }
@@ -826,10 +903,14 @@ function instrumentDatasetDelete(Dataset) {
826
903
  }
827
904
  function instrumentBigQueryCreateDataset(BigQuery) {
828
905
  const originalCreateDataset = BigQuery.prototype.createDataset;
829
- if (typeof originalCreateDataset !== "function") {
906
+ if (typeof originalCreateDataset !== 'function') {
830
907
  return;
831
908
  }
832
- BigQuery.prototype.createDataset = function instrumentedCreateDataset(id, options, callback) {
909
+ BigQuery.prototype.createDataset = function instrumentedCreateDataset(
910
+ id,
911
+ options,
912
+ callback,
913
+ ) {
833
914
  const config = getInstanceConfig(this);
834
915
  const tracer = getInstanceTracer(this);
835
916
  if (!config || !tracer || !config.instrumentAdminOps) {
@@ -840,10 +921,10 @@ function instrumentBigQueryCreateDataset(BigQuery) {
840
921
  const location = extractLocation(this, options);
841
922
  const span = createSpan(
842
923
  tracer,
843
- "CREATE_DATASET",
924
+ 'CREATE_DATASET',
844
925
  datasetId,
845
926
  projectId,
846
- config
927
+ config,
847
928
  );
848
929
  if (location) {
849
930
  span.setAttribute(SEMATTRS_GCP_BIGQUERY_JOB_LOCATION, location);
@@ -851,12 +932,12 @@ function instrumentBigQueryCreateDataset(BigQuery) {
851
932
  if (datasetId) {
852
933
  span.setAttribute(SEMATTRS_DB_NAMESPACE, datasetId);
853
934
  }
854
- if (typeof callback === "function") {
935
+ if (typeof callback === 'function') {
855
936
  const wrappedCallback = (err, ...args) => {
856
937
  if (err) {
857
938
  traceHelpers.finalizeSpan(
858
939
  span,
859
- err instanceof Error ? err : new Error(String(err))
940
+ err instanceof Error ? err : new Error(String(err)),
860
941
  );
861
942
  } else {
862
943
  traceHelpers.finalizeSpan(span);
@@ -868,20 +949,22 @@ function instrumentBigQueryCreateDataset(BigQuery) {
868
949
  return traceHelpers.runWithSpan(span, () => {
869
950
  try {
870
951
  const result = originalCreateDataset.call(this, id, options);
871
- return Promise.resolve(result).then((response) => {
872
- traceHelpers.finalizeSpan(span);
873
- return response;
874
- }).catch((error) => {
875
- traceHelpers.finalizeSpan(
876
- span,
877
- error instanceof Error ? error : new Error(String(error))
878
- );
879
- throw error;
880
- });
952
+ return Promise.resolve(result)
953
+ .then((response) => {
954
+ traceHelpers.finalizeSpan(span);
955
+ return response;
956
+ })
957
+ .catch((error) => {
958
+ traceHelpers.finalizeSpan(
959
+ span,
960
+ error instanceof Error ? error : new Error(String(error)),
961
+ );
962
+ throw error;
963
+ });
881
964
  } catch (error) {
882
965
  traceHelpers.finalizeSpan(
883
966
  span,
884
- error instanceof Error ? error : new Error(String(error))
967
+ error instanceof Error ? error : new Error(String(error)),
885
968
  );
886
969
  throw error;
887
970
  }
@@ -890,7 +973,7 @@ function instrumentBigQueryCreateDataset(BigQuery) {
890
973
  }
891
974
  function instrumentTableCreate(Table) {
892
975
  const originalCreate = Table.prototype.create;
893
- if (typeof originalCreate !== "function") {
976
+ if (typeof originalCreate !== 'function') {
894
977
  return;
895
978
  }
896
979
  Table.prototype.create = function instrumentedCreate(options) {
@@ -901,8 +984,12 @@ function instrumentTableCreate(Table) {
901
984
  }
902
985
  const tableRef = extractTableReference(this);
903
986
  const projectId = extractProjectId(this.dataset?.parent || this.parent);
904
- const target = tableRef.tableId ? tableRef.datasetId ? `${tableRef.datasetId}.${tableRef.tableId}` : tableRef.tableId : void 0;
905
- const span = createSpan(tracer, "CREATE_TABLE", target, projectId, config);
987
+ const target = tableRef.tableId
988
+ ? tableRef.datasetId
989
+ ? `${tableRef.datasetId}.${tableRef.tableId}`
990
+ : tableRef.tableId
991
+ : void 0;
992
+ const span = createSpan(tracer, 'CREATE_TABLE', target, projectId, config);
906
993
  if (tableRef.datasetId) {
907
994
  span.setAttribute(SEMATTRS_DB_NAMESPACE, tableRef.datasetId);
908
995
  }
@@ -912,20 +999,22 @@ function instrumentTableCreate(Table) {
912
999
  return traceHelpers.runWithSpan(span, () => {
913
1000
  try {
914
1001
  const result = originalCreate.call(this, options);
915
- return Promise.resolve(result).then((response) => {
916
- traceHelpers.finalizeSpan(span);
917
- return response;
918
- }).catch((error) => {
919
- traceHelpers.finalizeSpan(
920
- span,
921
- error instanceof Error ? error : new Error(String(error))
922
- );
923
- throw error;
924
- });
1002
+ return Promise.resolve(result)
1003
+ .then((response) => {
1004
+ traceHelpers.finalizeSpan(span);
1005
+ return response;
1006
+ })
1007
+ .catch((error) => {
1008
+ traceHelpers.finalizeSpan(
1009
+ span,
1010
+ error instanceof Error ? error : new Error(String(error)),
1011
+ );
1012
+ throw error;
1013
+ });
925
1014
  } catch (error) {
926
1015
  traceHelpers.finalizeSpan(
927
1016
  span,
928
- error instanceof Error ? error : new Error(String(error))
1017
+ error instanceof Error ? error : new Error(String(error)),
929
1018
  );
930
1019
  throw error;
931
1020
  }
@@ -934,7 +1023,7 @@ function instrumentTableCreate(Table) {
934
1023
  }
935
1024
  function instrumentTableDelete(Table) {
936
1025
  const originalDelete = Table.prototype.delete;
937
- if (typeof originalDelete !== "function") {
1026
+ if (typeof originalDelete !== 'function') {
938
1027
  return;
939
1028
  }
940
1029
  Table.prototype.delete = function instrumentedDelete(options) {
@@ -945,8 +1034,12 @@ function instrumentTableDelete(Table) {
945
1034
  }
946
1035
  const tableRef = extractTableReference(this);
947
1036
  const projectId = extractProjectId(this.dataset?.parent || this.parent);
948
- const target = tableRef.tableId ? tableRef.datasetId ? `${tableRef.datasetId}.${tableRef.tableId}` : tableRef.tableId : void 0;
949
- const span = createSpan(tracer, "DELETE_TABLE", target, projectId, config);
1037
+ const target = tableRef.tableId
1038
+ ? tableRef.datasetId
1039
+ ? `${tableRef.datasetId}.${tableRef.tableId}`
1040
+ : tableRef.tableId
1041
+ : void 0;
1042
+ const span = createSpan(tracer, 'DELETE_TABLE', target, projectId, config);
950
1043
  if (tableRef.datasetId) {
951
1044
  span.setAttribute(SEMATTRS_DB_NAMESPACE, tableRef.datasetId);
952
1045
  }
@@ -956,20 +1049,22 @@ function instrumentTableDelete(Table) {
956
1049
  return traceHelpers.runWithSpan(span, () => {
957
1050
  try {
958
1051
  const result = originalDelete.call(this, options);
959
- return Promise.resolve(result).then((response) => {
960
- traceHelpers.finalizeSpan(span);
961
- return response;
962
- }).catch((error) => {
963
- traceHelpers.finalizeSpan(
964
- span,
965
- error instanceof Error ? error : new Error(String(error))
966
- );
967
- throw error;
968
- });
1052
+ return Promise.resolve(result)
1053
+ .then((response) => {
1054
+ traceHelpers.finalizeSpan(span);
1055
+ return response;
1056
+ })
1057
+ .catch((error) => {
1058
+ traceHelpers.finalizeSpan(
1059
+ span,
1060
+ error instanceof Error ? error : new Error(String(error)),
1061
+ );
1062
+ throw error;
1063
+ });
969
1064
  } catch (error) {
970
1065
  traceHelpers.finalizeSpan(
971
1066
  span,
972
- error instanceof Error ? error : new Error(String(error))
1067
+ error instanceof Error ? error : new Error(String(error)),
973
1068
  );
974
1069
  throw error;
975
1070
  }
@@ -985,15 +1080,15 @@ function instrumentBigQuery(bigquery, config) {
985
1080
  return bigquery;
986
1081
  }
987
1082
  const finalConfig = {
988
- projectId: config?.projectId || "",
989
- location: config?.location || "",
1083
+ projectId: config?.projectId || '',
1084
+ location: config?.location || '',
990
1085
  tracerName: config?.tracerName || DEFAULT_TRACER_NAME,
991
- captureQueryText: config?.captureQueryText || "summary",
1086
+ captureQueryText: config?.captureQueryText || 'summary',
992
1087
  maxQueryTextLength: config?.maxQueryTextLength || 1e3,
993
1088
  includeQueryHash: config?.includeQueryHash ?? true,
994
1089
  instrumentAdminOps: config?.instrumentAdminOps ?? false,
995
1090
  instrumentBqmlOps: config?.instrumentBqmlOps ?? false,
996
- instrumentRoutineOps: config?.instrumentRoutineOps ?? false
1091
+ instrumentRoutineOps: config?.instrumentRoutineOps ?? false,
997
1092
  };
998
1093
  const tracer = autotel.otelTrace.getTracer(finalConfig.tracerName);
999
1094
  bq[CONFIG_STORAGE_KEY] = finalConfig;
@@ -1005,18 +1100,17 @@ function instrumentBigQuery(bigquery, config) {
1005
1100
  instrumentBigQueryCreateDataset(BigQuery);
1006
1101
  if (bq.dataset) {
1007
1102
  try {
1008
- const tempDataset = bq.dataset("__temp__");
1103
+ const tempDataset = bq.dataset('__temp__');
1009
1104
  const Dataset = tempDataset.constructor;
1010
1105
  instrumentDatasetCreate(Dataset);
1011
1106
  instrumentDatasetDelete(Dataset);
1012
1107
  tempDataset.dataset = null;
1013
- } catch {
1014
- }
1108
+ } catch {}
1015
1109
  }
1016
1110
  if (bq.dataset) {
1017
1111
  try {
1018
- const tempDataset = bq.dataset("__temp__");
1019
- const tempTable = tempDataset.table("__temp__");
1112
+ const tempDataset = bq.dataset('__temp__');
1113
+ const tempTable = tempDataset.table('__temp__');
1020
1114
  const Table = tempTable.constructor;
1021
1115
  instrumentTableInsert(Table);
1022
1116
  instrumentTableGetRows(Table);
@@ -1027,17 +1121,15 @@ function instrumentBigQuery(bigquery, config) {
1027
1121
  instrumentTableDelete(Table);
1028
1122
  tempTable.table = null;
1029
1123
  tempDataset.dataset = null;
1030
- } catch {
1031
- }
1124
+ } catch {}
1032
1125
  }
1033
1126
  if (bq.job) {
1034
1127
  try {
1035
- const tempJob = bq.job("__temp__");
1128
+ const tempJob = bq.job('__temp__');
1036
1129
  const Job = tempJob.constructor;
1037
1130
  instrumentJobGetQueryResults(Job);
1038
1131
  tempJob.job = null;
1039
- } catch {
1040
- }
1132
+ } catch {}
1041
1133
  }
1042
1134
  BigQuery[PROTOTYPE_INSTRUMENTED_FLAG] = true;
1043
1135
  }
@@ -1063,7 +1155,7 @@ function normalizeHeaders(headers) {
1063
1155
  if (value === void 0) {
1064
1156
  continue;
1065
1157
  }
1066
- normalized[key] = Buffer.isBuffer(value) ? value.toString("utf8") : value;
1158
+ normalized[key] = Buffer.isBuffer(value) ? value.toString('utf8') : value;
1067
1159
  }
1068
1160
  return normalized;
1069
1161
  }
@@ -1079,19 +1171,23 @@ var caseInsensitiveGetter = {
1079
1171
  },
1080
1172
  keys(carrier) {
1081
1173
  return Object.keys(carrier);
1082
- }
1174
+ },
1083
1175
  };
1084
1176
  function extractTraceContext(headers) {
1085
- return autotel.propagation.extract(autotel.ROOT_CONTEXT, headers, caseInsensitiveGetter);
1177
+ return autotel.propagation.extract(
1178
+ autotel.ROOT_CONTEXT,
1179
+ headers,
1180
+ caseInsensitiveGetter,
1181
+ );
1086
1182
  }
1087
1183
  var headerSetter = {
1088
1184
  set(carrier, key, value) {
1089
1185
  carrier[key] = value;
1090
- }
1186
+ },
1091
1187
  };
1092
1188
  function deriveCorrelationId() {
1093
1189
  const activeBaggage = autotel.propagation.getActiveBaggage();
1094
- const baggageCorrelationId = activeBaggage?.getEntry("correlation-id");
1190
+ const baggageCorrelationId = activeBaggage?.getEntry('correlation-id');
1095
1191
  if (baggageCorrelationId?.value) {
1096
1192
  return baggageCorrelationId.value;
1097
1193
  }
@@ -1100,7 +1196,7 @@ function deriveCorrelationId() {
1100
1196
  const spanContext = activeSpan.spanContext();
1101
1197
  return spanContext.traceId.slice(0, 16);
1102
1198
  }
1103
- return "";
1199
+ return '';
1104
1200
  }
1105
1201
  function extractCorrelationId(headers) {
1106
1202
  const lowerKey = CORRELATION_ID_HEADER.toLowerCase();
@@ -1123,21 +1219,26 @@ function injectTraceHeaders(base = {}, options = {}) {
1123
1219
  }
1124
1220
  return carrier;
1125
1221
  }
1126
- var DEFAULT_TRACER_NAME2 = "autotel-plugins/kafka";
1222
+ var DEFAULT_TRACER_NAME2 = 'autotel-plugins/kafka';
1127
1223
  function isValidSpanContext(spanContext) {
1128
- return !!(spanContext && spanContext.traceId && spanContext.spanId && autotel.otelTrace.isSpanContextValid(spanContext));
1224
+ return !!(
1225
+ spanContext &&
1226
+ spanContext.traceId &&
1227
+ spanContext.spanId &&
1228
+ autotel.otelTrace.isSpanContextValid(spanContext)
1229
+ );
1129
1230
  }
1130
1231
  async function withProcessingSpan(descriptor, fn) {
1131
1232
  const {
1132
1233
  name,
1133
1234
  headers,
1134
- contextMode = "inherit",
1235
+ contextMode = 'inherit',
1135
1236
  links = [],
1136
1237
  topic,
1137
1238
  consumerGroup,
1138
1239
  partition,
1139
1240
  offset,
1140
- key
1241
+ key,
1141
1242
  } = descriptor;
1142
1243
  const tracer = autotel.otelTrace.getTracer(DEFAULT_TRACER_NAME2);
1143
1244
  const normalizedHeaders = normalizeHeaders(headers);
@@ -1146,22 +1247,22 @@ async function withProcessingSpan(descriptor, fn) {
1146
1247
  const { parentContext, spanLinks } = resolveContextAndLinks(
1147
1248
  contextMode,
1148
1249
  extractedSpanContext,
1149
- links
1250
+ links,
1150
1251
  );
1151
1252
  const span = tracer.startSpan(
1152
1253
  name,
1153
1254
  {
1154
1255
  kind: autotel.SpanKind.CONSUMER,
1155
- links: spanLinks
1256
+ links: spanLinks,
1156
1257
  },
1157
- parentContext
1258
+ parentContext,
1158
1259
  );
1159
1260
  setMessagingAttributes(span, {
1160
1261
  topic,
1161
1262
  consumerGroup,
1162
1263
  partition,
1163
1264
  offset,
1164
- key
1265
+ key,
1165
1266
  });
1166
1267
  const spanContext = autotel.otelTrace.setSpan(autotel.context.active(), span);
1167
1268
  try {
@@ -1182,14 +1283,18 @@ async function withProcessingSpan(descriptor, fn) {
1182
1283
  throw error;
1183
1284
  }
1184
1285
  }
1185
- function resolveContextAndLinks(contextMode, extractedSpanContext, additionalLinks) {
1286
+ function resolveContextAndLinks(
1287
+ contextMode,
1288
+ extractedSpanContext,
1289
+ additionalLinks,
1290
+ ) {
1186
1291
  const activeSpan = autotel.otelTrace.getActiveSpan();
1187
1292
  const activeContext = autotel.context.active();
1188
1293
  const hasActiveSpan = activeSpan !== void 0;
1189
1294
  const hasValidExtracted = isValidSpanContext(extractedSpanContext);
1190
1295
  const spanLinks = [...additionalLinks];
1191
1296
  switch (contextMode) {
1192
- case "inherit": {
1297
+ case 'inherit': {
1193
1298
  if (hasActiveSpan) {
1194
1299
  if (hasValidExtracted) {
1195
1300
  const activeSpanContext = activeSpan.spanContext();
@@ -1202,20 +1307,20 @@ function resolveContextAndLinks(contextMode, extractedSpanContext, additionalLin
1202
1307
  if (hasValidExtracted) {
1203
1308
  const extractedParentCtx = autotel.otelTrace.setSpanContext(
1204
1309
  activeContext,
1205
- extractedSpanContext
1310
+ extractedSpanContext,
1206
1311
  );
1207
1312
  return { parentContext: extractedParentCtx, spanLinks };
1208
1313
  }
1209
1314
  return { parentContext: activeContext, spanLinks };
1210
1315
  }
1211
1316
  }
1212
- case "link": {
1317
+ case 'link': {
1213
1318
  if (hasValidExtracted) {
1214
1319
  spanLinks.push({ context: extractedSpanContext });
1215
1320
  }
1216
1321
  return { parentContext: activeContext, spanLinks };
1217
1322
  }
1218
- case "none": {
1323
+ case 'none': {
1219
1324
  return { parentContext: activeContext, spanLinks };
1220
1325
  }
1221
1326
  default: {
@@ -1227,7 +1332,7 @@ function resolveContextAndLinks(contextMode, extractedSpanContext, additionalLin
1227
1332
  function setMessagingAttributes(span, attrs) {
1228
1333
  const { topic, consumerGroup, partition, offset, key } = attrs;
1229
1334
  if (topic) {
1230
- span.setAttribute(SEMATTRS_MESSAGING_SYSTEM, "kafka");
1335
+ span.setAttribute(SEMATTRS_MESSAGING_SYSTEM, 'kafka');
1231
1336
  span.setAttribute(SEMATTRS_MESSAGING_DESTINATION_NAME, topic);
1232
1337
  }
1233
1338
  if (consumerGroup) {
@@ -1243,16 +1348,16 @@ function setMessagingAttributes(span, attrs) {
1243
1348
  span.setAttribute(SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY, key);
1244
1349
  }
1245
1350
  }
1246
- var DEFAULT_TRACER_NAME3 = "autotel-plugins/kafka";
1351
+ var DEFAULT_TRACER_NAME3 = 'autotel-plugins/kafka';
1247
1352
  async function withProducerSpan(descriptor, fn) {
1248
- const { name, topic, messageKey, system = "kafka" } = descriptor;
1353
+ const { name, topic, messageKey, system = 'kafka' } = descriptor;
1249
1354
  const tracer = autotel.otelTrace.getTracer(DEFAULT_TRACER_NAME3);
1250
1355
  const span = tracer.startSpan(name, {
1251
- kind: autotel.SpanKind.PRODUCER
1356
+ kind: autotel.SpanKind.PRODUCER,
1252
1357
  });
1253
1358
  span.setAttribute(SEMATTRS_MESSAGING_SYSTEM, system);
1254
1359
  span.setAttribute(SEMATTRS_MESSAGING_DESTINATION_NAME, topic);
1255
- span.setAttribute(SEMATTRS_MESSAGING_OPERATION, "publish");
1360
+ span.setAttribute(SEMATTRS_MESSAGING_OPERATION, 'publish');
1256
1361
  if (messageKey !== void 0) {
1257
1362
  span.setAttribute(SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY, messageKey);
1258
1363
  }
@@ -1277,31 +1382,39 @@ async function withProducerSpan(descriptor, fn) {
1277
1382
  }
1278
1383
  var DEFAULT_MAX_LINKS = 128;
1279
1384
  function isValidSpanContext2(spanContext) {
1280
- return !!(spanContext && spanContext.traceId && spanContext.spanId && autotel.otelTrace.isSpanContextValid(spanContext));
1385
+ return !!(
1386
+ spanContext &&
1387
+ spanContext.traceId &&
1388
+ spanContext.spanId &&
1389
+ autotel.otelTrace.isSpanContextValid(spanContext)
1390
+ );
1281
1391
  }
1282
1392
  async function hashTraceIds(traceIds) {
1283
- const input = traceIds.join("|");
1393
+ const input = traceIds.join('|');
1284
1394
  try {
1285
1395
  const encoder = new TextEncoder();
1286
1396
  const data = encoder.encode(input);
1287
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1397
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
1288
1398
  const hashArray = new Uint8Array(hashBuffer);
1289
- return [...hashArray].map((byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 16);
1399
+ return [...hashArray]
1400
+ .map((byte) => byte.toString(16).padStart(2, '0'))
1401
+ .join('')
1402
+ .slice(0, 16);
1290
1403
  } catch {
1291
1404
  let hash = 5381;
1292
1405
  for (let i = 0; i < input.length; i++) {
1293
- hash = hash * 33 ^ input.charCodeAt(i);
1406
+ hash = (hash * 33) ^ input.charCodeAt(i);
1294
1407
  }
1295
- return (hash >>> 0).toString(16).padStart(16, "0");
1408
+ return (hash >>> 0).toString(16).padStart(16, '0');
1296
1409
  }
1297
1410
  }
1298
1411
  function hashTraceIdsSync(traceIds) {
1299
- const input = traceIds.join("|");
1412
+ const input = traceIds.join('|');
1300
1413
  let hash = 5381;
1301
1414
  for (let i = 0; i < input.length; i++) {
1302
- hash = hash * 33 ^ input.charCodeAt(i);
1415
+ hash = (hash * 33) ^ input.charCodeAt(i);
1303
1416
  }
1304
- return (hash >>> 0).toString(16).padStart(16, "0");
1417
+ return (hash >>> 0).toString(16).padStart(16, '0');
1305
1418
  }
1306
1419
  function extractBatchLineage(items, options = {}) {
1307
1420
  const { includeTraceIds = false, maxLinks = DEFAULT_MAX_LINKS } = options;
@@ -1311,23 +1424,29 @@ function extractBatchLineage(items, options = {}) {
1311
1424
  const normalizedHeaders = normalizeHeaders(item.headers);
1312
1425
  const extractedCtx = extractTraceContext(normalizedHeaders);
1313
1426
  const spanContext = autotel.otelTrace.getSpanContext(extractedCtx);
1314
- if (isValidSpanContext2(spanContext) && !seenTraceIds.has(spanContext.traceId)) {
1427
+ if (
1428
+ isValidSpanContext2(spanContext) &&
1429
+ !seenTraceIds.has(spanContext.traceId)
1430
+ ) {
1315
1431
  seenTraceIds.add(spanContext.traceId);
1316
1432
  extractedContexts.push({
1317
1433
  traceId: spanContext.traceId,
1318
- spanContext
1434
+ spanContext,
1319
1435
  });
1320
1436
  }
1321
1437
  }
1322
1438
  extractedContexts.sort((a, b) => a.traceId.localeCompare(b.traceId));
1323
1439
  const traceIds = extractedContexts.map((ec) => ec.traceId);
1324
- const links = extractedContexts.slice(0, maxLinks).map((ec) => ({ context: ec.spanContext }));
1325
- const hash = traceIds.length > 0 ? hashTraceIdsSync(traceIds) : "0000000000000000";
1440
+ const links = extractedContexts
1441
+ .slice(0, maxLinks)
1442
+ .map((ec) => ({ context: ec.spanContext }));
1443
+ const hash =
1444
+ traceIds.length > 0 ? hashTraceIdsSync(traceIds) : '0000000000000000';
1326
1445
  return {
1327
1446
  linked_trace_id_count: traceIds.length,
1328
1447
  linked_trace_id_hash: hash,
1329
1448
  links,
1330
- ...includeTraceIds && { trace_ids: traceIds }
1449
+ ...(includeTraceIds && { trace_ids: traceIds }),
1331
1450
  };
1332
1451
  }
1333
1452
  async function extractBatchLineageAsync(items, options = {}) {
@@ -1338,28 +1457,34 @@ async function extractBatchLineageAsync(items, options = {}) {
1338
1457
  const normalizedHeaders = normalizeHeaders(item.headers);
1339
1458
  const extractedCtx = extractTraceContext(normalizedHeaders);
1340
1459
  const spanContext = autotel.otelTrace.getSpanContext(extractedCtx);
1341
- if (isValidSpanContext2(spanContext) && !seenTraceIds.has(spanContext.traceId)) {
1460
+ if (
1461
+ isValidSpanContext2(spanContext) &&
1462
+ !seenTraceIds.has(spanContext.traceId)
1463
+ ) {
1342
1464
  seenTraceIds.add(spanContext.traceId);
1343
1465
  extractedContexts.push({
1344
1466
  traceId: spanContext.traceId,
1345
- spanContext
1467
+ spanContext,
1346
1468
  });
1347
1469
  }
1348
1470
  }
1349
1471
  extractedContexts.sort((a, b) => a.traceId.localeCompare(b.traceId));
1350
1472
  const traceIds = extractedContexts.map((ec) => ec.traceId);
1351
- const links = extractedContexts.slice(0, maxLinks).map((ec) => ({ context: ec.spanContext }));
1352
- const hash = traceIds.length > 0 ? await hashTraceIds(traceIds) : "0000000000000000";
1473
+ const links = extractedContexts
1474
+ .slice(0, maxLinks)
1475
+ .map((ec) => ({ context: ec.spanContext }));
1476
+ const hash =
1477
+ traceIds.length > 0 ? await hashTraceIds(traceIds) : '0000000000000000';
1353
1478
  return {
1354
1479
  linked_trace_id_count: traceIds.length,
1355
1480
  linked_trace_id_hash: hash,
1356
1481
  links,
1357
- ...includeTraceIds && { trace_ids: traceIds }
1482
+ ...(includeTraceIds && { trace_ids: traceIds }),
1358
1483
  };
1359
1484
  }
1360
- var DEFAULT_TRACER_NAME4 = "autotel-plugins/kafka";
1485
+ var DEFAULT_TRACER_NAME4 = 'autotel-plugins/kafka';
1361
1486
  function withBatchConsumer(config, handler) {
1362
- const { name, consumerGroup, perMessageSpans = "none", onProgress } = config;
1487
+ const { name, consumerGroup, perMessageSpans = 'none', onProgress } = config;
1363
1488
  const tracer = autotel.otelTrace.getTracer(DEFAULT_TRACER_NAME4);
1364
1489
  return async (payload) => {
1365
1490
  const { batch } = payload;
@@ -1368,7 +1493,7 @@ function withBatchConsumer(config, handler) {
1368
1493
  let failed = 0;
1369
1494
  let skipped = 0;
1370
1495
  const batchSpan = tracer.startSpan(name, {
1371
- kind: autotel.SpanKind.CONSUMER
1496
+ kind: autotel.SpanKind.CONSUMER,
1372
1497
  });
1373
1498
  setBatchAttributes(batchSpan, {
1374
1499
  topic: batch.topic,
@@ -1376,31 +1501,34 @@ function withBatchConsumer(config, handler) {
1376
1501
  consumerGroup,
1377
1502
  messageCount: batch.messages.length,
1378
1503
  firstOffset: batch.firstOffset() ?? void 0,
1379
- lastOffset: batch.lastOffset()
1504
+ lastOffset: batch.lastOffset(),
1380
1505
  });
1381
- const spanContext = autotel.otelTrace.setSpan(autotel.context.active(), batchSpan);
1506
+ const spanContext = autotel.otelTrace.setSpan(
1507
+ autotel.context.active(),
1508
+ batchSpan,
1509
+ );
1382
1510
  const {
1383
1511
  wrappedPayload,
1384
1512
  endOpenMessageSpans,
1385
- endRemainingMessageSpansOnSuccess
1513
+ endRemainingMessageSpansOnSuccess,
1386
1514
  } = createWrappedPayload(
1387
1515
  payload,
1388
1516
  perMessageSpans,
1389
1517
  tracer,
1390
1518
  spanContext,
1391
1519
  (type) => {
1392
- if (type === "processed") processed++;
1393
- else if (type === "failed") failed++;
1520
+ if (type === 'processed') processed++;
1521
+ else if (type === 'failed') failed++;
1394
1522
  else skipped++;
1395
1523
  if (onProgress) {
1396
1524
  onProgress({
1397
1525
  processed,
1398
1526
  failed,
1399
1527
  skipped,
1400
- batchProcessingTimeMs: Date.now() - startTime
1528
+ batchProcessingTimeMs: Date.now() - startTime,
1401
1529
  });
1402
1530
  }
1403
- }
1531
+ },
1404
1532
  );
1405
1533
  try {
1406
1534
  await autotel.context.with(spanContext, async () => {
@@ -1410,47 +1538,47 @@ function withBatchConsumer(config, handler) {
1410
1538
  const processingTime = Date.now() - startTime;
1411
1539
  batchSpan.setAttribute(
1412
1540
  SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_PROCESSED,
1413
- processed
1541
+ processed,
1414
1542
  );
1415
1543
  batchSpan.setAttribute(
1416
1544
  SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_FAILED,
1417
- failed
1545
+ failed,
1418
1546
  );
1419
1547
  batchSpan.setAttribute(
1420
1548
  SEMATTRS_MESSAGING_KAFKA_BATCH_PROCESSING_TIME_MS,
1421
- processingTime
1549
+ processingTime,
1422
1550
  );
1423
1551
  batchSpan.setStatus({ code: autotel.SpanStatusCode.OK });
1424
1552
  batchSpan.end();
1425
1553
  } catch (error) {
1426
1554
  endOpenMessageSpans?.(error);
1427
1555
  const firstMessage = batch.messages[0];
1428
- if (perMessageSpans === "errors" && firstMessage !== void 0) {
1556
+ if (perMessageSpans === 'errors' && firstMessage !== void 0) {
1429
1557
  createMessageErrorSpan(
1430
1558
  name,
1431
1559
  {
1432
1560
  offset: firstMessage.offset,
1433
1561
  key: firstMessage.key ?? void 0,
1434
- headers: firstMessage.headers
1562
+ headers: firstMessage.headers,
1435
1563
  },
1436
1564
  error instanceof Error ? error : new Error(String(error)),
1437
1565
  batch.topic,
1438
- batch.partition
1566
+ batch.partition,
1439
1567
  );
1440
1568
  }
1441
1569
  const processingTime = Date.now() - startTime;
1442
1570
  batchSpan.setAttribute(
1443
1571
  SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_PROCESSED,
1444
- processed
1572
+ processed,
1445
1573
  );
1446
1574
  batchSpan.setAttribute(
1447
1575
  SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_FAILED,
1448
- failed + 1
1576
+ failed + 1,
1449
1577
  // Count the batch error
1450
1578
  );
1451
1579
  batchSpan.setAttribute(
1452
1580
  SEMATTRS_MESSAGING_KAFKA_BATCH_PROCESSING_TIME_MS,
1453
- processingTime
1581
+ processingTime,
1454
1582
  );
1455
1583
  batchSpan.setStatus({ code: autotel.SpanStatusCode.ERROR });
1456
1584
  if (error instanceof Error) {
@@ -1464,77 +1592,86 @@ function withBatchConsumer(config, handler) {
1464
1592
  };
1465
1593
  }
1466
1594
  function setBatchAttributes(span, attrs) {
1467
- span.setAttribute(SEMATTRS_MESSAGING_SYSTEM, "kafka");
1595
+ span.setAttribute(SEMATTRS_MESSAGING_SYSTEM, 'kafka');
1468
1596
  span.setAttribute(SEMATTRS_MESSAGING_DESTINATION_NAME, attrs.topic);
1469
1597
  span.setAttribute(SEMATTRS_MESSAGING_KAFKA_PARTITION, attrs.partition);
1470
1598
  span.setAttribute(SEMATTRS_MESSAGING_BATCH_MESSAGE_COUNT, attrs.messageCount);
1471
1599
  if (attrs.consumerGroup) {
1472
1600
  span.setAttribute(
1473
1601
  SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,
1474
- attrs.consumerGroup
1602
+ attrs.consumerGroup,
1475
1603
  );
1476
1604
  }
1477
1605
  if (attrs.firstOffset) {
1478
1606
  span.setAttribute(
1479
1607
  SEMATTRS_MESSAGING_KAFKA_BATCH_FIRST_OFFSET,
1480
- attrs.firstOffset
1608
+ attrs.firstOffset,
1481
1609
  );
1482
1610
  }
1483
1611
  span.setAttribute(
1484
1612
  SEMATTRS_MESSAGING_KAFKA_BATCH_LAST_OFFSET,
1485
- attrs.lastOffset
1613
+ attrs.lastOffset,
1486
1614
  );
1487
1615
  }
1488
- function createWrappedPayload(original, perMessageSpans, tracer, parentContext, onMetric) {
1489
- if (perMessageSpans === "none") {
1616
+ function createWrappedPayload(
1617
+ original,
1618
+ perMessageSpans,
1619
+ tracer,
1620
+ parentContext,
1621
+ onMetric,
1622
+ ) {
1623
+ if (perMessageSpans === 'none') {
1490
1624
  return {
1491
1625
  wrappedPayload: {
1492
1626
  ...original,
1493
1627
  resolveOffset: (offset) => {
1494
- onMetric("processed");
1628
+ onMetric('processed');
1495
1629
  original.resolveOffset(offset);
1496
- }
1497
- }
1630
+ },
1631
+ },
1498
1632
  };
1499
1633
  }
1500
1634
  const messageSpans = /* @__PURE__ */ new Map();
1501
- if (perMessageSpans === "all") {
1635
+ if (perMessageSpans === 'all') {
1502
1636
  for (const message of original.batch.messages) {
1503
1637
  const normalizedHeaders = normalizeHeaders(message.headers);
1504
1638
  const extractedCtx = extractTraceContext(normalizedHeaders);
1505
1639
  const spanContext = autotel.otelTrace.getSpanContext(extractedCtx);
1506
- const parentCtx = spanContext && autotel.otelTrace.isSpanContextValid(spanContext) ? extractedCtx : parentContext;
1640
+ const parentCtx =
1641
+ spanContext && autotel.otelTrace.isSpanContextValid(spanContext)
1642
+ ? extractedCtx
1643
+ : parentContext;
1507
1644
  const span = tracer.startSpan(
1508
1645
  `${original.batch.topic}.${original.batch.partition}.${message.offset}`,
1509
1646
  {
1510
- kind: autotel.SpanKind.CONSUMER
1647
+ kind: autotel.SpanKind.CONSUMER,
1511
1648
  },
1512
- parentCtx
1649
+ parentCtx,
1513
1650
  );
1514
1651
  span.setAttributes({
1515
- [SEMATTRS_MESSAGING_SYSTEM]: "kafka",
1652
+ [SEMATTRS_MESSAGING_SYSTEM]: 'kafka',
1516
1653
  [SEMATTRS_MESSAGING_DESTINATION_NAME]: original.batch.topic,
1517
1654
  [SEMATTRS_MESSAGING_KAFKA_PARTITION]: original.batch.partition,
1518
1655
  [SEMATTRS_MESSAGING_KAFKA_OFFSET]: message.offset,
1519
- ...message.key && {
1520
- [SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY]: message.key.toString()
1521
- }
1656
+ ...(message.key && {
1657
+ [SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY]: message.key.toString(),
1658
+ }),
1522
1659
  });
1523
1660
  messageSpans.set(message.offset, span);
1524
1661
  }
1525
1662
  }
1526
1663
  const wrappedMessages = original.batch.messages.map((message) => ({
1527
- ...message
1664
+ ...message,
1528
1665
  }));
1529
1666
  const wrappedBatch = {
1530
1667
  ...original.batch,
1531
- messages: wrappedMessages
1668
+ messages: wrappedMessages,
1532
1669
  };
1533
1670
  const wrappedPayload = {
1534
1671
  ...original,
1535
1672
  batch: wrappedBatch,
1536
1673
  resolveOffset: (offset) => {
1537
- onMetric("processed");
1674
+ onMetric('processed');
1538
1675
  const span = messageSpans.get(offset);
1539
1676
  if (span) {
1540
1677
  span.setStatus({ code: autotel.SpanStatusCode.OK });
@@ -1542,31 +1679,37 @@ function createWrappedPayload(original, perMessageSpans, tracer, parentContext,
1542
1679
  messageSpans.delete(offset);
1543
1680
  }
1544
1681
  original.resolveOffset(offset);
1545
- }
1682
+ },
1546
1683
  };
1547
- const endOpenMessageSpans = perMessageSpans === "all" ? (error) => {
1548
- for (const [, span] of messageSpans) {
1549
- span.setStatus({ code: autotel.SpanStatusCode.ERROR });
1550
- if (error instanceof Error) {
1551
- span.recordException(error);
1552
- } else {
1553
- span.recordException(new Error(String(error)));
1554
- }
1555
- span.end();
1556
- }
1557
- messageSpans.clear();
1558
- } : void 0;
1559
- const endRemainingMessageSpansOnSuccess = perMessageSpans === "all" ? () => {
1560
- for (const [, span] of messageSpans) {
1561
- span.setStatus({ code: autotel.SpanStatusCode.OK });
1562
- span.end();
1563
- }
1564
- messageSpans.clear();
1565
- } : void 0;
1684
+ const endOpenMessageSpans =
1685
+ perMessageSpans === 'all'
1686
+ ? (error) => {
1687
+ for (const [, span] of messageSpans) {
1688
+ span.setStatus({ code: autotel.SpanStatusCode.ERROR });
1689
+ if (error instanceof Error) {
1690
+ span.recordException(error);
1691
+ } else {
1692
+ span.recordException(new Error(String(error)));
1693
+ }
1694
+ span.end();
1695
+ }
1696
+ messageSpans.clear();
1697
+ }
1698
+ : void 0;
1699
+ const endRemainingMessageSpansOnSuccess =
1700
+ perMessageSpans === 'all'
1701
+ ? () => {
1702
+ for (const [, span] of messageSpans) {
1703
+ span.setStatus({ code: autotel.SpanStatusCode.OK });
1704
+ span.end();
1705
+ }
1706
+ messageSpans.clear();
1707
+ }
1708
+ : void 0;
1566
1709
  return {
1567
1710
  wrappedPayload,
1568
1711
  endOpenMessageSpans,
1569
- endRemainingMessageSpansOnSuccess
1712
+ endRemainingMessageSpansOnSuccess,
1570
1713
  };
1571
1714
  }
1572
1715
  function createMessageErrorSpan(name, message, error, topic, partition) {
@@ -1576,24 +1719,24 @@ function createMessageErrorSpan(name, message, error, topic, partition) {
1576
1719
  const span = tracer.startSpan(
1577
1720
  `${name}.error`,
1578
1721
  {
1579
- kind: autotel.SpanKind.CONSUMER
1722
+ kind: autotel.SpanKind.CONSUMER,
1580
1723
  },
1581
- extractedCtx
1724
+ extractedCtx,
1582
1725
  );
1583
1726
  span.setAttributes({
1584
- [SEMATTRS_MESSAGING_SYSTEM]: "kafka",
1727
+ [SEMATTRS_MESSAGING_SYSTEM]: 'kafka',
1585
1728
  [SEMATTRS_MESSAGING_DESTINATION_NAME]: topic,
1586
1729
  [SEMATTRS_MESSAGING_KAFKA_PARTITION]: partition,
1587
1730
  [SEMATTRS_MESSAGING_KAFKA_OFFSET]: message.offset,
1588
- ...message.key && {
1589
- [SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY]: message.key.toString()
1590
- }
1731
+ ...(message.key && {
1732
+ [SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY]: message.key.toString(),
1733
+ }),
1591
1734
  });
1592
1735
  span.setStatus({ code: autotel.SpanStatusCode.ERROR });
1593
1736
  span.recordException(error);
1594
1737
  span.end();
1595
1738
  }
1596
- var DEFAULT_TRACER_NAME5 = "autotel-plugins/kafka";
1739
+ var DEFAULT_TRACER_NAME5 = 'autotel-plugins/kafka';
1597
1740
  function createStreamProcessor(config) {
1598
1741
  const { name } = config;
1599
1742
  const tracer = autotel.otelTrace.getTracer(DEFAULT_TRACER_NAME5);
@@ -1605,27 +1748,39 @@ function createStreamProcessor(config) {
1605
1748
  const processorSpan = tracer.startSpan(
1606
1749
  name,
1607
1750
  {
1608
- kind: autotel.SpanKind.CONSUMER
1751
+ kind: autotel.SpanKind.CONSUMER,
1609
1752
  },
1610
- inputSpanContext && autotel.otelTrace.isSpanContextValid(inputSpanContext) ? extractedCtx : void 0
1753
+ inputSpanContext &&
1754
+ autotel.otelTrace.isSpanContextValid(inputSpanContext)
1755
+ ? extractedCtx
1756
+ : void 0,
1757
+ );
1758
+ processorSpan.setAttribute(SEMATTRS_MESSAGING_SYSTEM, 'kafka');
1759
+ processorSpan.setAttribute(SEMATTRS_MESSAGING_OPERATION, 'process');
1760
+ const processorContext = autotel.otelTrace.setSpan(
1761
+ autotel.context.active(),
1762
+ processorSpan,
1611
1763
  );
1612
- processorSpan.setAttribute(SEMATTRS_MESSAGING_SYSTEM, "kafka");
1613
- processorSpan.setAttribute(SEMATTRS_MESSAGING_OPERATION, "process");
1614
- const processorContext = autotel.otelTrace.setSpan(autotel.context.active(), processorSpan);
1615
1764
  const ctx = {
1616
1765
  span: processorSpan,
1617
1766
  inputContext: inputSpanContext,
1618
1767
  async stage(stageName, fn) {
1619
1768
  return autotel.context.with(processorContext, async () => {
1620
1769
  const stageSpan = tracer.startSpan(`${name}.${stageName}`, {
1621
- kind: autotel.SpanKind.INTERNAL
1770
+ kind: autotel.SpanKind.INTERNAL,
1622
1771
  });
1623
- stageSpan.setAttribute("stream.stage", stageName);
1624
- const stageContext = autotel.otelTrace.setSpan(autotel.context.active(), stageSpan);
1772
+ stageSpan.setAttribute('stream.stage', stageName);
1773
+ const stageContext = autotel.otelTrace.setSpan(
1774
+ autotel.context.active(),
1775
+ stageSpan,
1776
+ );
1625
1777
  try {
1626
- const result = await autotel.context.with(stageContext, async () => {
1627
- return await fn();
1628
- });
1778
+ const result = await autotel.context.with(
1779
+ stageContext,
1780
+ async () => {
1781
+ return await fn();
1782
+ },
1783
+ );
1629
1784
  stageSpan.setStatus({ code: autotel.SpanStatusCode.OK });
1630
1785
  stageSpan.end();
1631
1786
  return result;
@@ -1642,33 +1797,44 @@ function createStreamProcessor(config) {
1642
1797
  });
1643
1798
  },
1644
1799
  async produce(topic, _payload, options) {
1645
- const { linkToInput = false, headers: extraHeaders = {} } = options ?? {};
1800
+ const { linkToInput = false, headers: extraHeaders = {} } =
1801
+ options ?? {};
1646
1802
  const links = [];
1647
- if (linkToInput && inputSpanContext && autotel.otelTrace.isSpanContextValid(inputSpanContext)) {
1803
+ if (
1804
+ linkToInput &&
1805
+ inputSpanContext &&
1806
+ autotel.otelTrace.isSpanContextValid(inputSpanContext)
1807
+ ) {
1648
1808
  links.push({ context: inputSpanContext });
1649
1809
  }
1650
1810
  const produceSpan = tracer.startSpan(`${name}.produce`, {
1651
1811
  kind: autotel.SpanKind.PRODUCER,
1652
- links
1812
+ links,
1653
1813
  });
1654
- produceSpan.setAttribute(SEMATTRS_MESSAGING_SYSTEM, "kafka");
1814
+ produceSpan.setAttribute(SEMATTRS_MESSAGING_SYSTEM, 'kafka');
1655
1815
  produceSpan.setAttribute(SEMATTRS_MESSAGING_DESTINATION_NAME, topic);
1656
- produceSpan.setAttribute(SEMATTRS_MESSAGING_OPERATION, "publish");
1657
- const produceContext = autotel.otelTrace.setSpan(autotel.context.active(), produceSpan);
1816
+ produceSpan.setAttribute(SEMATTRS_MESSAGING_OPERATION, 'publish');
1817
+ const produceContext = autotel.otelTrace.setSpan(
1818
+ autotel.context.active(),
1819
+ produceSpan,
1820
+ );
1658
1821
  return autotel.context.with(produceContext, () => {
1659
1822
  const headers = injectTraceHeaders(extraHeaders, {
1660
- includeCorrelationIdHeader: true
1823
+ includeCorrelationIdHeader: true,
1661
1824
  });
1662
1825
  produceSpan.setStatus({ code: autotel.SpanStatusCode.OK });
1663
1826
  produceSpan.end();
1664
1827
  return headers;
1665
1828
  });
1666
- }
1829
+ },
1667
1830
  };
1668
1831
  try {
1669
- const result = await autotel.context.with(processorContext, async () => {
1670
- return await callback(ctx);
1671
- });
1832
+ const result = await autotel.context.with(
1833
+ processorContext,
1834
+ async () => {
1835
+ return await callback(ctx);
1836
+ },
1837
+ );
1672
1838
  processorSpan.setStatus({ code: autotel.SpanStatusCode.OK });
1673
1839
  processorSpan.end();
1674
1840
  return result;
@@ -1682,7 +1848,7 @@ function createStreamProcessor(config) {
1682
1848
  processorSpan.end();
1683
1849
  throw error;
1684
1850
  }
1685
- }
1851
+ },
1686
1852
  };
1687
1853
  }
1688
1854
  var ConsumerMetrics = class {
@@ -1697,61 +1863,69 @@ var ConsumerMetrics = class {
1697
1863
  lagPollInterval;
1698
1864
  isRunning = false;
1699
1865
  constructor(config) {
1700
- if (config.enableLag && config.lagStrategy === "polling" && !config.lagPollIntervalMs) {
1701
- throw new Error("Lag polling requires lagPollIntervalMs");
1702
- }
1703
- if (config.enableLag && (config.lagStrategy === "polling" || config.lagStrategy === "hybrid")) {
1866
+ if (
1867
+ config.enableLag &&
1868
+ config.lagStrategy === 'polling' &&
1869
+ !config.lagPollIntervalMs
1870
+ ) {
1871
+ throw new Error('Lag polling requires lagPollIntervalMs');
1872
+ }
1873
+ if (
1874
+ config.enableLag &&
1875
+ (config.lagStrategy === 'polling' || config.lagStrategy === 'hybrid')
1876
+ ) {
1704
1877
  if (!config.admin) {
1705
1878
  throw new Error(
1706
- `Lag strategy '${config.lagStrategy}' requires admin client`
1879
+ `Lag strategy '${config.lagStrategy}' requires admin client`,
1707
1880
  );
1708
1881
  }
1709
1882
  if (!config.groupId) {
1710
- throw new Error("Lag tracking requires groupId");
1883
+ throw new Error('Lag tracking requires groupId');
1711
1884
  }
1712
1885
  if (!config.topics || config.topics.length === 0) {
1713
- throw new Error("Lag tracking requires topics");
1886
+ throw new Error('Lag tracking requires topics');
1714
1887
  }
1715
1888
  }
1716
1889
  this.config = {
1717
1890
  ...config,
1718
- metricsPrefix: config.metricsPrefix ?? "kafka.consumer",
1891
+ metricsPrefix: config.metricsPrefix ?? 'kafka.consumer',
1719
1892
  enableLag: config.enableLag ?? false,
1720
- lagStrategy: config.lagStrategy ?? "hybrid",
1721
- lagPollIntervalMs: config.lagPollIntervalMs ?? 3e4
1893
+ lagStrategy: config.lagStrategy ?? 'hybrid',
1894
+ lagPollIntervalMs: config.lagPollIntervalMs ?? 3e4,
1722
1895
  };
1723
- this.meter = api.metrics.getMeter("autotel-plugins/kafka");
1896
+ this.meter = api.metrics.getMeter('autotel-plugins/kafka');
1724
1897
  const prefix = this.config.metricsPrefix;
1725
1898
  this.messagesProcessed = this.meter.createCounter(
1726
1899
  `${prefix}.messages_processed`,
1727
1900
  {
1728
- description: "Total number of messages processed"
1729
- }
1901
+ description: 'Total number of messages processed',
1902
+ },
1730
1903
  );
1731
1904
  this.processingDuration = this.meter.createHistogram(
1732
1905
  `${prefix}.processing_duration`,
1733
1906
  {
1734
- description: "Message processing duration in milliseconds",
1735
- unit: "ms"
1736
- }
1907
+ description: 'Message processing duration in milliseconds',
1908
+ unit: 'ms',
1909
+ },
1737
1910
  );
1738
1911
  this.batchSize = this.meter.createHistogram(`${prefix}.batch_size`, {
1739
- description: "Number of messages in each batch"
1912
+ description: 'Number of messages in each batch',
1740
1913
  });
1741
1914
  this.rebalances = this.meter.createCounter(`${prefix}.rebalances`, {
1742
- description: "Number of consumer group rebalances"
1915
+ description: 'Number of consumer group rebalances',
1743
1916
  });
1744
1917
  this.lag = this.meter.createObservableGauge(`${prefix}.lag`, {
1745
- description: "Consumer lag per topic-partition"
1918
+ description: 'Consumer lag per topic-partition',
1746
1919
  });
1747
1920
  if (this.config.enableLag) {
1748
1921
  this.lag.addCallback((observableResult) => {
1749
1922
  for (const [, state] of this.partitionStates.entries()) {
1750
1923
  if (state.highWatermark) {
1751
- const lagValue = BigInt(state.highWatermark) - BigInt(state.currentOffset);
1924
+ const lagValue =
1925
+ BigInt(state.highWatermark) - BigInt(state.currentOffset);
1752
1926
  observableResult.observe(Number(lagValue), {
1753
1927
  topic: state.topic,
1754
- partition: state.partition
1928
+ partition: state.partition,
1755
1929
  });
1756
1930
  }
1757
1931
  }
@@ -1765,18 +1939,21 @@ var ConsumerMetrics = class {
1765
1939
  if (this.isRunning) return;
1766
1940
  this.isRunning = true;
1767
1941
  const { consumer } = this.config;
1768
- consumer.on("consumer.rebalancing", () => {
1769
- this.rebalances.add(1, { event: "rebalancing" });
1942
+ consumer.on('consumer.rebalancing', () => {
1943
+ this.rebalances.add(1, { event: 'rebalancing' });
1770
1944
  });
1771
- consumer.on("consumer.group_join", () => {
1772
- this.rebalances.add(1, { event: "group_join" });
1945
+ consumer.on('consumer.group_join', () => {
1946
+ this.rebalances.add(1, { event: 'group_join' });
1773
1947
  });
1774
- if (this.config.enableLag && (this.config.lagStrategy === "polling" || this.config.lagStrategy === "hybrid")) {
1948
+ if (
1949
+ this.config.enableLag &&
1950
+ (this.config.lagStrategy === 'polling' ||
1951
+ this.config.lagStrategy === 'hybrid')
1952
+ ) {
1775
1953
  await this.pollLag();
1776
1954
  this.lagPollInterval = setInterval(
1777
- () => this.pollLag().catch(() => {
1778
- }),
1779
- this.config.lagPollIntervalMs
1955
+ () => this.pollLag().catch(() => {}),
1956
+ this.config.lagPollIntervalMs,
1780
1957
  );
1781
1958
  }
1782
1959
  }
@@ -1829,7 +2006,7 @@ var ConsumerMetrics = class {
1829
2006
  topic,
1830
2007
  partition,
1831
2008
  currentOffset: offset,
1832
- highWatermark: highWatermark ?? existing?.highWatermark
2009
+ highWatermark: highWatermark ?? existing?.highWatermark,
1833
2010
  });
1834
2011
  }
1835
2012
  /**
@@ -1841,15 +2018,15 @@ var ConsumerMetrics = class {
1841
2018
  try {
1842
2019
  const committedOffsets = await admin.fetchOffsets({
1843
2020
  groupId,
1844
- topics
2021
+ topics,
1845
2022
  });
1846
2023
  for (const topicOffsets of committedOffsets) {
1847
2024
  const topicHighWatermarks = await admin.fetchTopicOffsets(
1848
- topicOffsets.topic
2025
+ topicOffsets.topic,
1849
2026
  );
1850
2027
  for (const partition of topicOffsets.partitions) {
1851
2028
  const hwm = topicHighWatermarks.find(
1852
- (p) => p.partition === partition.partition
2029
+ (p) => p.partition === partition.partition,
1853
2030
  );
1854
2031
  if (hwm) {
1855
2032
  const key = `${topicOffsets.topic}-${partition.partition}`;
@@ -1857,34 +2034,33 @@ var ConsumerMetrics = class {
1857
2034
  topic: topicOffsets.topic,
1858
2035
  partition: partition.partition,
1859
2036
  currentOffset: partition.offset,
1860
- highWatermark: hwm.high
2037
+ highWatermark: hwm.high,
1861
2038
  });
1862
2039
  }
1863
2040
  }
1864
2041
  }
1865
- } catch {
1866
- }
2042
+ } catch {}
1867
2043
  }
1868
2044
  };
1869
- var DEFAULT_TRACER_NAME6 = "autotel-plugins/kafka";
2045
+ var DEFAULT_TRACER_NAME6 = 'autotel-plugins/kafka';
1870
2046
  var REBALANCE_EVENTS = [
1871
- "consumer.group_join",
1872
- "consumer.rebalancing",
1873
- "consumer.stop"
2047
+ 'consumer.group_join',
2048
+ 'consumer.rebalancing',
2049
+ 'consumer.stop',
1874
2050
  ];
1875
2051
  var ERROR_EVENTS = [
1876
- "consumer.crash",
1877
- "consumer.disconnect",
1878
- "consumer.network.request_timeout"
2052
+ 'consumer.crash',
2053
+ 'consumer.disconnect',
2054
+ 'consumer.network.request_timeout',
1879
2055
  ];
1880
- var HEARTBEAT_EVENTS = ["consumer.heartbeat"];
2056
+ var HEARTBEAT_EVENTS = ['consumer.heartbeat'];
1881
2057
  function instrumentConsumerEvents(consumer, config = {}) {
1882
2058
  const {
1883
- mode = "events",
2059
+ mode = 'events',
1884
2060
  traceRebalances = true,
1885
2061
  traceErrors = true,
1886
2062
  traceHeartbeats = false,
1887
- lifecycleSpan
2063
+ lifecycleSpan,
1888
2064
  } = config;
1889
2065
  const tracer = autotel.otelTrace.getTracer(DEFAULT_TRACER_NAME6);
1890
2066
  const listeners = [];
@@ -1895,7 +2071,7 @@ function instrumentConsumerEvents(consumer, config = {}) {
1895
2071
  if (traceRebalances) {
1896
2072
  for (const event of REBALANCE_EVENTS) {
1897
2073
  addListener(event, (payload) => {
1898
- if (mode === "spans") {
2074
+ if (mode === 'spans') {
1899
2075
  createEventSpan(tracer, event, payload);
1900
2076
  } else if (lifecycleSpan) {
1901
2077
  lifecycleSpan.addEvent(event, extractEventAttributes(payload));
@@ -1906,14 +2082,14 @@ function instrumentConsumerEvents(consumer, config = {}) {
1906
2082
  if (traceErrors) {
1907
2083
  for (const event of ERROR_EVENTS) {
1908
2084
  addListener(event, (payload) => {
1909
- if (mode === "spans") {
2085
+ if (mode === 'spans') {
1910
2086
  createErrorSpan(tracer, event, payload);
1911
2087
  } else if (lifecycleSpan) {
1912
2088
  lifecycleSpan.addEvent(event, {
1913
2089
  ...extractEventAttributes(payload),
1914
- "event.severity": "error"
2090
+ 'event.severity': 'error',
1915
2091
  });
1916
- if (event === "consumer.crash" && isErrorPayload(payload)) {
2092
+ if (event === 'consumer.crash' && isErrorPayload(payload)) {
1917
2093
  lifecycleSpan.recordException(payload.error);
1918
2094
  }
1919
2095
  }
@@ -1923,7 +2099,7 @@ function instrumentConsumerEvents(consumer, config = {}) {
1923
2099
  if (traceHeartbeats) {
1924
2100
  for (const event of HEARTBEAT_EVENTS) {
1925
2101
  addListener(event, (payload) => {
1926
- if (mode === "spans") {
2102
+ if (mode === 'spans') {
1927
2103
  createEventSpan(tracer, event, payload);
1928
2104
  } else if (lifecycleSpan) {
1929
2105
  lifecycleSpan.addEvent(event, extractEventAttributes(payload));
@@ -1942,7 +2118,7 @@ function instrumentConsumerEvents(consumer, config = {}) {
1942
2118
  }
1943
2119
  function createEventSpan(tracer, eventName, payload) {
1944
2120
  const span = tracer.startSpan(`kafka.consumer.${eventName}`, {
1945
- kind: autotel.SpanKind.INTERNAL
2121
+ kind: autotel.SpanKind.INTERNAL,
1946
2122
  });
1947
2123
  const attributes = extractEventAttributes(payload);
1948
2124
  for (const [key, value] of Object.entries(attributes)) {
@@ -1953,7 +2129,7 @@ function createEventSpan(tracer, eventName, payload) {
1953
2129
  }
1954
2130
  function createErrorSpan(tracer, eventName, payload) {
1955
2131
  const span = tracer.startSpan(`kafka.consumer.${eventName}`, {
1956
- kind: autotel.SpanKind.INTERNAL
2132
+ kind: autotel.SpanKind.INTERNAL,
1957
2133
  });
1958
2134
  const attributes = extractEventAttributes(payload);
1959
2135
  for (const [key, value] of Object.entries(attributes)) {
@@ -1967,35 +2143,41 @@ function createErrorSpan(tracer, eventName, payload) {
1967
2143
  }
1968
2144
  function extractEventAttributes(payload) {
1969
2145
  const attributes = {};
1970
- if (!payload || typeof payload !== "object") {
2146
+ if (!payload || typeof payload !== 'object') {
1971
2147
  return attributes;
1972
2148
  }
1973
2149
  const p = payload;
1974
- if (typeof p.groupId === "string") {
1975
- attributes["messaging.kafka.consumer.group"] = p.groupId;
2150
+ if (typeof p.groupId === 'string') {
2151
+ attributes['messaging.kafka.consumer.group'] = p.groupId;
1976
2152
  }
1977
- if (typeof p.memberId === "string") {
1978
- attributes["messaging.kafka.consumer.member_id"] = p.memberId;
2153
+ if (typeof p.memberId === 'string') {
2154
+ attributes['messaging.kafka.consumer.member_id'] = p.memberId;
1979
2155
  }
1980
- if (typeof p.leaderId === "string") {
1981
- attributes["messaging.kafka.consumer.leader_id"] = p.leaderId;
2156
+ if (typeof p.leaderId === 'string') {
2157
+ attributes['messaging.kafka.consumer.leader_id'] = p.leaderId;
1982
2158
  }
1983
- if (typeof p.duration === "number") {
1984
- attributes["event.duration_ms"] = p.duration;
2159
+ if (typeof p.duration === 'number') {
2160
+ attributes['event.duration_ms'] = p.duration;
1985
2161
  }
1986
- if (typeof p.isLeader === "boolean") {
1987
- attributes["messaging.kafka.consumer.is_leader"] = p.isLeader;
2162
+ if (typeof p.isLeader === 'boolean') {
2163
+ attributes['messaging.kafka.consumer.is_leader'] = p.isLeader;
1988
2164
  }
1989
2165
  if (Array.isArray(p.memberAssignment)) {
1990
- attributes["messaging.kafka.consumer.assignment_count"] = p.memberAssignment.length;
2166
+ attributes['messaging.kafka.consumer.assignment_count'] =
2167
+ p.memberAssignment.length;
1991
2168
  }
1992
- if (typeof p.type === "string") {
1993
- attributes["event.type"] = p.type;
2169
+ if (typeof p.type === 'string') {
2170
+ attributes['event.type'] = p.type;
1994
2171
  }
1995
2172
  return attributes;
1996
2173
  }
1997
2174
  function isErrorPayload(payload) {
1998
- return payload !== null && typeof payload === "object" && "error" in payload && payload.error instanceof Error;
2175
+ return (
2176
+ payload !== null &&
2177
+ typeof payload === 'object' &&
2178
+ 'error' in payload &&
2179
+ payload.error instanceof Error
2180
+ );
1999
2181
  }
2000
2182
  function normalizeHeaders2(headers) {
2001
2183
  if (!headers) {
@@ -2009,23 +2191,24 @@ function normalizeHeaders2(headers) {
2009
2191
  }
2010
2192
  if (Buffer.isBuffer(value)) {
2011
2193
  try {
2012
- const decoded = value.toString("utf8");
2013
- normalized[key] = Buffer.from(decoded, "utf8").equals(value) ? decoded : `base64:${value.toString("base64")}`;
2194
+ const decoded = value.toString('utf8');
2195
+ normalized[key] = Buffer.from(decoded, 'utf8').equals(value)
2196
+ ? decoded
2197
+ : `base64:${value.toString('base64')}`;
2014
2198
  } catch {
2015
- normalized[key] = `base64:${value.toString("base64")}`;
2199
+ normalized[key] = `base64:${value.toString('base64')}`;
2016
2200
  }
2017
- } else if (typeof value === "string") {
2201
+ } else if (typeof value === 'string') {
2018
2202
  normalized[key] = value;
2019
- } else if (typeof value === "number" || typeof value === "boolean") {
2203
+ } else if (typeof value === 'number' || typeof value === 'boolean') {
2020
2204
  normalized[key] = String(value);
2021
- } else if (typeof value === "object") {
2205
+ } else if (typeof value === 'object') {
2022
2206
  try {
2023
2207
  const json = JSON.stringify(value);
2024
2208
  if (json.length <= MAX_OBJECT_SIZE) {
2025
2209
  normalized[key] = json;
2026
2210
  }
2027
- } catch {
2028
- }
2211
+ } catch {}
2029
2212
  }
2030
2213
  }
2031
2214
  return normalized;
@@ -2042,19 +2225,23 @@ var caseInsensitiveGetter2 = {
2042
2225
  },
2043
2226
  keys(carrier) {
2044
2227
  return Object.keys(carrier);
2045
- }
2228
+ },
2046
2229
  };
2047
2230
  function extractTraceContext2(headers) {
2048
- return autotel.propagation.extract(autotel.ROOT_CONTEXT, headers, caseInsensitiveGetter2);
2231
+ return autotel.propagation.extract(
2232
+ autotel.ROOT_CONTEXT,
2233
+ headers,
2234
+ caseInsensitiveGetter2,
2235
+ );
2049
2236
  }
2050
2237
  var headerSetter2 = {
2051
2238
  set(carrier, key, value) {
2052
2239
  carrier[key] = value;
2053
- }
2240
+ },
2054
2241
  };
2055
2242
  function deriveCorrelationId2() {
2056
2243
  const activeBaggage = autotel.propagation.getActiveBaggage();
2057
- const baggageCorrelationId = activeBaggage?.getEntry("correlation-id");
2244
+ const baggageCorrelationId = activeBaggage?.getEntry('correlation-id');
2058
2245
  if (baggageCorrelationId?.value) {
2059
2246
  return baggageCorrelationId.value;
2060
2247
  }
@@ -2063,7 +2250,7 @@ function deriveCorrelationId2() {
2063
2250
  const spanContext = activeSpan.spanContext();
2064
2251
  return spanContext.traceId.slice(0, 16);
2065
2252
  }
2066
- return "";
2253
+ return '';
2067
2254
  }
2068
2255
  function extractCorrelationId2(headers, amqpCorrelationId) {
2069
2256
  if (amqpCorrelationId) {
@@ -2089,13 +2276,18 @@ function injectTraceHeaders2(base = {}, options = {}) {
2089
2276
  }
2090
2277
  return carrier;
2091
2278
  }
2092
- var DEFAULT_TRACER_NAME7 = "autotel-plugins/rabbitmq";
2279
+ var DEFAULT_TRACER_NAME7 = 'autotel-plugins/rabbitmq';
2093
2280
  function isValidSpanContext3(spanContext) {
2094
- return !!(spanContext && spanContext.traceId && spanContext.spanId && autotel.otelTrace.isSpanContextValid(spanContext));
2281
+ return !!(
2282
+ spanContext &&
2283
+ spanContext.traceId &&
2284
+ spanContext.spanId &&
2285
+ autotel.otelTrace.isSpanContextValid(spanContext)
2286
+ );
2095
2287
  }
2096
2288
  function validateDeferredConfig(descriptor) {
2097
2289
  if (descriptor.deferSpanEnd && !descriptor.ackTimeoutMs) {
2098
- throw new Error("deferSpanEnd requires ackTimeoutMs to be set");
2290
+ throw new Error('deferSpanEnd requires ackTimeoutMs to be set');
2099
2291
  }
2100
2292
  }
2101
2293
  async function withConsumeSpan(descriptor, fn) {
@@ -2103,7 +2295,7 @@ async function withConsumeSpan(descriptor, fn) {
2103
2295
  const {
2104
2296
  name,
2105
2297
  headers,
2106
- contextMode = "inherit",
2298
+ contextMode = 'inherit',
2107
2299
  links = [],
2108
2300
  queue,
2109
2301
  exchange,
@@ -2112,7 +2304,7 @@ async function withConsumeSpan(descriptor, fn) {
2112
2304
  correlationId,
2113
2305
  consumerTag,
2114
2306
  deferSpanEnd = false,
2115
- ackTimeoutMs
2307
+ ackTimeoutMs,
2116
2308
  } = descriptor;
2117
2309
  const tracer = autotel.otelTrace.getTracer(DEFAULT_TRACER_NAME7);
2118
2310
  const normalizedHeaders = normalizeHeaders2(headers);
@@ -2121,15 +2313,15 @@ async function withConsumeSpan(descriptor, fn) {
2121
2313
  const { parentContext, spanLinks } = resolveContextAndLinks2(
2122
2314
  contextMode,
2123
2315
  extractedSpanContext,
2124
- links
2316
+ links,
2125
2317
  );
2126
2318
  const span = tracer.startSpan(
2127
2319
  name,
2128
2320
  {
2129
2321
  kind: autotel.SpanKind.CONSUMER,
2130
- links: spanLinks
2322
+ links: spanLinks,
2131
2323
  },
2132
- parentContext
2324
+ parentContext,
2133
2325
  );
2134
2326
  setMessagingAttributes2(span, {
2135
2327
  queue,
@@ -2137,16 +2329,11 @@ async function withConsumeSpan(descriptor, fn) {
2137
2329
  routingKey,
2138
2330
  messageId,
2139
2331
  correlationId,
2140
- consumerTag
2332
+ consumerTag,
2141
2333
  });
2142
2334
  const spanContext = autotel.otelTrace.setSpan(autotel.context.active(), span);
2143
2335
  if (deferSpanEnd) {
2144
- return executeDeferredMode(
2145
- span,
2146
- spanContext,
2147
- fn,
2148
- ackTimeoutMs
2149
- );
2336
+ return executeDeferredMode(span, spanContext, fn, ackTimeoutMs);
2150
2337
  }
2151
2338
  return executeImmediateMode(span, spanContext, fn);
2152
2339
  }
@@ -2185,25 +2372,28 @@ async function executeDeferredMode(span, spanContext, fn, ackTimeoutMs) {
2185
2372
  span.setAttribute(SEMATTRS_MESSAGING_RABBITMQ_REQUEUE, requeue);
2186
2373
  }
2187
2374
  span.setStatus({
2188
- code: status === "ok" ? autotel.SpanStatusCode.OK : autotel.SpanStatusCode.ERROR
2375
+ code:
2376
+ status === 'ok'
2377
+ ? autotel.SpanStatusCode.OK
2378
+ : autotel.SpanStatusCode.ERROR,
2189
2379
  });
2190
2380
  span.end();
2191
2381
  };
2192
2382
  const controls = {
2193
2383
  ack() {
2194
- endSpan("ok", "ack");
2384
+ endSpan('ok', 'ack');
2195
2385
  },
2196
2386
  nack(options) {
2197
- endSpan("ok", "nack", options?.requeue ?? true);
2387
+ endSpan('ok', 'nack', options?.requeue ?? true);
2198
2388
  },
2199
2389
  reject(options) {
2200
- endSpan("ok", "reject", options?.requeue ?? false);
2201
- }
2390
+ endSpan('ok', 'reject', options?.requeue ?? false);
2391
+ },
2202
2392
  };
2203
2393
  timeoutRef.id = setTimeout(() => {
2204
2394
  if (!spanEnded) {
2205
- span.setAttribute("messaging.rabbitmq.ack_timeout", true);
2206
- endSpan("error");
2395
+ span.setAttribute('messaging.rabbitmq.ack_timeout', true);
2396
+ endSpan('error');
2207
2397
  }
2208
2398
  }, ackTimeoutMs);
2209
2399
  try {
@@ -2211,7 +2401,7 @@ async function executeDeferredMode(span, spanContext, fn, ackTimeoutMs) {
2211
2401
  return await fn(span, controls);
2212
2402
  });
2213
2403
  if (!spanEnded) {
2214
- endSpan("ok");
2404
+ endSpan('ok');
2215
2405
  }
2216
2406
  return result;
2217
2407
  } catch (error) {
@@ -2221,33 +2411,37 @@ async function executeDeferredMode(span, spanContext, fn, ackTimeoutMs) {
2221
2411
  } else {
2222
2412
  span.recordException(new Error(String(error)));
2223
2413
  }
2224
- endSpan("error");
2414
+ endSpan('error');
2225
2415
  }
2226
2416
  throw error;
2227
2417
  }
2228
2418
  }
2229
- function resolveContextAndLinks2(contextMode, extractedSpanContext, additionalLinks) {
2419
+ function resolveContextAndLinks2(
2420
+ contextMode,
2421
+ extractedSpanContext,
2422
+ additionalLinks,
2423
+ ) {
2230
2424
  const activeContext = autotel.context.active();
2231
2425
  const hasValidExtracted = isValidSpanContext3(extractedSpanContext);
2232
2426
  const spanLinks = [...additionalLinks];
2233
2427
  switch (contextMode) {
2234
- case "inherit": {
2428
+ case 'inherit': {
2235
2429
  if (hasValidExtracted) {
2236
2430
  const extractedParentCtx = autotel.otelTrace.setSpanContext(
2237
2431
  activeContext,
2238
- extractedSpanContext
2432
+ extractedSpanContext,
2239
2433
  );
2240
2434
  return { parentContext: extractedParentCtx, spanLinks };
2241
2435
  }
2242
2436
  return { parentContext: activeContext, spanLinks };
2243
2437
  }
2244
- case "link": {
2438
+ case 'link': {
2245
2439
  if (hasValidExtracted) {
2246
2440
  spanLinks.push({ context: extractedSpanContext });
2247
2441
  }
2248
2442
  return { parentContext: activeContext, spanLinks };
2249
2443
  }
2250
- case "none": {
2444
+ case 'none': {
2251
2445
  return { parentContext: activeContext, spanLinks };
2252
2446
  }
2253
2447
  default: {
@@ -2257,22 +2451,23 @@ function resolveContextAndLinks2(contextMode, extractedSpanContext, additionalLi
2257
2451
  }
2258
2452
  }
2259
2453
  function setMessagingAttributes2(span, attrs) {
2260
- const { queue, exchange, routingKey, messageId, correlationId, consumerTag } = attrs;
2261
- span.setAttribute(SEMATTRS_MESSAGING_SYSTEM, "rabbitmq");
2262
- span.setAttribute(SEMATTRS_MESSAGING_OPERATION_NAME, "receive");
2454
+ const { queue, exchange, routingKey, messageId, correlationId, consumerTag } =
2455
+ attrs;
2456
+ span.setAttribute(SEMATTRS_MESSAGING_SYSTEM, 'rabbitmq');
2457
+ span.setAttribute(SEMATTRS_MESSAGING_OPERATION_NAME, 'receive');
2263
2458
  if (queue) {
2264
2459
  span.setAttribute(SEMATTRS_MESSAGING_DESTINATION_NAME, queue);
2265
2460
  }
2266
2461
  if (exchange) {
2267
2462
  span.setAttribute(
2268
2463
  SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_EXCHANGE,
2269
- exchange
2464
+ exchange,
2270
2465
  );
2271
2466
  }
2272
2467
  if (routingKey) {
2273
2468
  span.setAttribute(
2274
2469
  SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY,
2275
- routingKey
2470
+ routingKey,
2276
2471
  );
2277
2472
  }
2278
2473
  if (messageId) {
@@ -2281,33 +2476,33 @@ function setMessagingAttributes2(span, attrs) {
2281
2476
  if (correlationId) {
2282
2477
  span.setAttribute(
2283
2478
  SEMATTRS_MESSAGING_MESSAGE_CONVERSATION_ID,
2284
- correlationId
2479
+ correlationId,
2285
2480
  );
2286
2481
  }
2287
2482
  if (consumerTag) {
2288
2483
  span.setAttribute(SEMATTRS_MESSAGING_CONSUMER_ID, consumerTag);
2289
2484
  }
2290
2485
  }
2291
- var DEFAULT_TRACER_NAME8 = "autotel-plugins/rabbitmq";
2486
+ var DEFAULT_TRACER_NAME8 = 'autotel-plugins/rabbitmq';
2292
2487
  async function withPublishSpan(descriptor, fn) {
2293
2488
  const {
2294
2489
  name,
2295
- exchange = "amq.default",
2490
+ exchange = 'amq.default',
2296
2491
  routingKey,
2297
2492
  messageId,
2298
2493
  correlationId,
2299
- system = "rabbitmq"
2494
+ system = 'rabbitmq',
2300
2495
  } = descriptor;
2301
2496
  const tracer = autotel.otelTrace.getTracer(DEFAULT_TRACER_NAME8);
2302
2497
  const span = tracer.startSpan(name, {
2303
- kind: autotel.SpanKind.PRODUCER
2498
+ kind: autotel.SpanKind.PRODUCER,
2304
2499
  });
2305
2500
  span.setAttribute(SEMATTRS_MESSAGING_SYSTEM, system);
2306
2501
  span.setAttribute(SEMATTRS_MESSAGING_DESTINATION_NAME, exchange);
2307
- span.setAttribute(SEMATTRS_MESSAGING_OPERATION_NAME, "publish");
2502
+ span.setAttribute(SEMATTRS_MESSAGING_OPERATION_NAME, 'publish');
2308
2503
  span.setAttribute(
2309
2504
  SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY,
2310
- routingKey
2505
+ routingKey,
2311
2506
  );
2312
2507
  if (messageId) {
2313
2508
  span.setAttribute(SEMATTRS_MESSAGING_MESSAGE_ID, messageId);
@@ -2315,7 +2510,7 @@ async function withPublishSpan(descriptor, fn) {
2315
2510
  if (correlationId) {
2316
2511
  span.setAttribute(
2317
2512
  SEMATTRS_MESSAGING_MESSAGE_CONVERSATION_ID,
2318
- correlationId
2513
+ correlationId,
2319
2514
  );
2320
2515
  }
2321
2516
  const spanContext = autotel.otelTrace.setSpan(autotel.context.active(), span);
@@ -2339,15 +2534,20 @@ async function withPublishSpan(descriptor, fn) {
2339
2534
  }
2340
2535
  var DEFAULT_MAX_LINKS2 = 128;
2341
2536
  function isValidSpanContext4(spanContext) {
2342
- return !!(spanContext && spanContext.traceId && spanContext.spanId && autotel.otelTrace.isSpanContextValid(spanContext));
2537
+ return !!(
2538
+ spanContext &&
2539
+ spanContext.traceId &&
2540
+ spanContext.spanId &&
2541
+ autotel.otelTrace.isSpanContextValid(spanContext)
2542
+ );
2343
2543
  }
2344
2544
  function hashTraceIdsSync2(traceIds) {
2345
- const input = traceIds.join("|");
2545
+ const input = traceIds.join('|');
2346
2546
  let hash = 5381;
2347
2547
  for (let i = 0; i < input.length; i++) {
2348
- hash = hash * 33 ^ input.charCodeAt(i);
2548
+ hash = (hash * 33) ^ input.charCodeAt(i);
2349
2549
  }
2350
- return (hash >>> 0).toString(16).padStart(16, "0");
2550
+ return (hash >>> 0).toString(16).padStart(16, '0');
2351
2551
  }
2352
2552
  function extractBatchLineage2(items, options = {}) {
2353
2553
  const { includeTraceIds = false, maxLinks = DEFAULT_MAX_LINKS2 } = options;
@@ -2357,23 +2557,29 @@ function extractBatchLineage2(items, options = {}) {
2357
2557
  const normalizedHeaders = normalizeHeaders2(item.headers);
2358
2558
  const extractedCtx = extractTraceContext2(normalizedHeaders);
2359
2559
  const spanContext = autotel.otelTrace.getSpanContext(extractedCtx);
2360
- if (isValidSpanContext4(spanContext) && !seenTraceIds.has(spanContext.traceId)) {
2560
+ if (
2561
+ isValidSpanContext4(spanContext) &&
2562
+ !seenTraceIds.has(spanContext.traceId)
2563
+ ) {
2361
2564
  seenTraceIds.add(spanContext.traceId);
2362
2565
  extractedContexts.push({
2363
2566
  traceId: spanContext.traceId,
2364
- spanContext
2567
+ spanContext,
2365
2568
  });
2366
2569
  }
2367
2570
  }
2368
2571
  extractedContexts.sort((a, b) => a.traceId.localeCompare(b.traceId));
2369
2572
  const traceIds = extractedContexts.map((ec) => ec.traceId);
2370
- const links = extractedContexts.slice(0, maxLinks).map((ec) => ({ context: ec.spanContext }));
2371
- const hash = traceIds.length > 0 ? hashTraceIdsSync2(traceIds) : "0000000000000000";
2573
+ const links = extractedContexts
2574
+ .slice(0, maxLinks)
2575
+ .map((ec) => ({ context: ec.spanContext }));
2576
+ const hash =
2577
+ traceIds.length > 0 ? hashTraceIdsSync2(traceIds) : '0000000000000000';
2372
2578
  return {
2373
2579
  linked_trace_id_count: traceIds.length,
2374
2580
  linked_trace_id_hash: hash,
2375
2581
  links,
2376
- ...includeTraceIds && { trace_ids: traceIds }
2582
+ ...(includeTraceIds && { trace_ids: traceIds }),
2377
2583
  };
2378
2584
  }
2379
2585
 
@@ -2398,38 +2604,58 @@ exports.SEMATTRS_DB_QUERY_TEXT = SEMATTRS_DB_QUERY_TEXT;
2398
2604
  exports.SEMATTRS_DB_STATEMENT = SEMATTRS_DB_STATEMENT;
2399
2605
  exports.SEMATTRS_DB_SYSTEM = SEMATTRS_DB_SYSTEM;
2400
2606
  exports.SEMATTRS_DB_SYSTEM_NAME = SEMATTRS_DB_SYSTEM_NAME;
2401
- exports.SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE = SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE;
2607
+ exports.SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE =
2608
+ SEMATTRS_GCP_BIGQUERY_DESTINATION_TABLE;
2402
2609
  exports.SEMATTRS_GCP_BIGQUERY_JOB_ID = SEMATTRS_GCP_BIGQUERY_JOB_ID;
2403
2610
  exports.SEMATTRS_GCP_BIGQUERY_JOB_LOCATION = SEMATTRS_GCP_BIGQUERY_JOB_LOCATION;
2404
2611
  exports.SEMATTRS_GCP_BIGQUERY_PROJECT_ID = SEMATTRS_GCP_BIGQUERY_PROJECT_ID;
2405
2612
  exports.SEMATTRS_GCP_BIGQUERY_QUERY_HASH = SEMATTRS_GCP_BIGQUERY_QUERY_HASH;
2406
- exports.SEMATTRS_GCP_BIGQUERY_ROWS_AFFECTED = SEMATTRS_GCP_BIGQUERY_ROWS_AFFECTED;
2407
- exports.SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED = SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED;
2408
- exports.SEMATTRS_GCP_BIGQUERY_SCHEMA_FIELDS = SEMATTRS_GCP_BIGQUERY_SCHEMA_FIELDS;
2409
- exports.SEMATTRS_GCP_BIGQUERY_SOURCE_TABLES = SEMATTRS_GCP_BIGQUERY_SOURCE_TABLES;
2410
- exports.SEMATTRS_GCP_BIGQUERY_STATEMENT_TYPE = SEMATTRS_GCP_BIGQUERY_STATEMENT_TYPE;
2613
+ exports.SEMATTRS_GCP_BIGQUERY_ROWS_AFFECTED =
2614
+ SEMATTRS_GCP_BIGQUERY_ROWS_AFFECTED;
2615
+ exports.SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED =
2616
+ SEMATTRS_GCP_BIGQUERY_ROWS_RETURNED;
2617
+ exports.SEMATTRS_GCP_BIGQUERY_SCHEMA_FIELDS =
2618
+ SEMATTRS_GCP_BIGQUERY_SCHEMA_FIELDS;
2619
+ exports.SEMATTRS_GCP_BIGQUERY_SOURCE_TABLES =
2620
+ SEMATTRS_GCP_BIGQUERY_SOURCE_TABLES;
2621
+ exports.SEMATTRS_GCP_BIGQUERY_STATEMENT_TYPE =
2622
+ SEMATTRS_GCP_BIGQUERY_STATEMENT_TYPE;
2411
2623
  exports.SEMATTRS_LINKED_TRACE_ID_COUNT = SEMATTRS_LINKED_TRACE_ID_COUNT;
2412
2624
  exports.SEMATTRS_LINKED_TRACE_ID_HASH = SEMATTRS_LINKED_TRACE_ID_HASH;
2413
- exports.SEMATTRS_MESSAGING_BATCH_MESSAGE_COUNT = SEMATTRS_MESSAGING_BATCH_MESSAGE_COUNT;
2625
+ exports.SEMATTRS_MESSAGING_BATCH_MESSAGE_COUNT =
2626
+ SEMATTRS_MESSAGING_BATCH_MESSAGE_COUNT;
2414
2627
  exports.SEMATTRS_MESSAGING_CONSUMER_ID = SEMATTRS_MESSAGING_CONSUMER_ID;
2415
- exports.SEMATTRS_MESSAGING_DESTINATION_NAME = SEMATTRS_MESSAGING_DESTINATION_NAME;
2416
- exports.SEMATTRS_MESSAGING_KAFKA_BATCH_FIRST_OFFSET = SEMATTRS_MESSAGING_KAFKA_BATCH_FIRST_OFFSET;
2417
- exports.SEMATTRS_MESSAGING_KAFKA_BATCH_LAST_OFFSET = SEMATTRS_MESSAGING_KAFKA_BATCH_LAST_OFFSET;
2418
- exports.SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_FAILED = SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_FAILED;
2419
- exports.SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_PROCESSED = SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_PROCESSED;
2420
- exports.SEMATTRS_MESSAGING_KAFKA_BATCH_PROCESSING_TIME_MS = SEMATTRS_MESSAGING_KAFKA_BATCH_PROCESSING_TIME_MS;
2421
- exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP;
2422
- exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY;
2628
+ exports.SEMATTRS_MESSAGING_DESTINATION_NAME =
2629
+ SEMATTRS_MESSAGING_DESTINATION_NAME;
2630
+ exports.SEMATTRS_MESSAGING_KAFKA_BATCH_FIRST_OFFSET =
2631
+ SEMATTRS_MESSAGING_KAFKA_BATCH_FIRST_OFFSET;
2632
+ exports.SEMATTRS_MESSAGING_KAFKA_BATCH_LAST_OFFSET =
2633
+ SEMATTRS_MESSAGING_KAFKA_BATCH_LAST_OFFSET;
2634
+ exports.SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_FAILED =
2635
+ SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_FAILED;
2636
+ exports.SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_PROCESSED =
2637
+ SEMATTRS_MESSAGING_KAFKA_BATCH_MESSAGES_PROCESSED;
2638
+ exports.SEMATTRS_MESSAGING_KAFKA_BATCH_PROCESSING_TIME_MS =
2639
+ SEMATTRS_MESSAGING_KAFKA_BATCH_PROCESSING_TIME_MS;
2640
+ exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP =
2641
+ SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP;
2642
+ exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY =
2643
+ SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY;
2423
2644
  exports.SEMATTRS_MESSAGING_KAFKA_OFFSET = SEMATTRS_MESSAGING_KAFKA_OFFSET;
2424
2645
  exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = SEMATTRS_MESSAGING_KAFKA_PARTITION;
2425
- exports.SEMATTRS_MESSAGING_MESSAGE_CONVERSATION_ID = SEMATTRS_MESSAGING_MESSAGE_CONVERSATION_ID;
2646
+ exports.SEMATTRS_MESSAGING_MESSAGE_CONVERSATION_ID =
2647
+ SEMATTRS_MESSAGING_MESSAGE_CONVERSATION_ID;
2426
2648
  exports.SEMATTRS_MESSAGING_MESSAGE_ID = SEMATTRS_MESSAGING_MESSAGE_ID;
2427
2649
  exports.SEMATTRS_MESSAGING_OPERATION = SEMATTRS_MESSAGING_OPERATION;
2428
2650
  exports.SEMATTRS_MESSAGING_OPERATION_NAME = SEMATTRS_MESSAGING_OPERATION_NAME;
2429
- exports.SEMATTRS_MESSAGING_RABBITMQ_ACK_RESULT = SEMATTRS_MESSAGING_RABBITMQ_ACK_RESULT;
2430
- exports.SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_EXCHANGE = SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_EXCHANGE;
2431
- exports.SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY = SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY;
2432
- exports.SEMATTRS_MESSAGING_RABBITMQ_REQUEUE = SEMATTRS_MESSAGING_RABBITMQ_REQUEUE;
2651
+ exports.SEMATTRS_MESSAGING_RABBITMQ_ACK_RESULT =
2652
+ SEMATTRS_MESSAGING_RABBITMQ_ACK_RESULT;
2653
+ exports.SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_EXCHANGE =
2654
+ SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_EXCHANGE;
2655
+ exports.SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY =
2656
+ SEMATTRS_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY;
2657
+ exports.SEMATTRS_MESSAGING_RABBITMQ_REQUEUE =
2658
+ SEMATTRS_MESSAGING_RABBITMQ_REQUEUE;
2433
2659
  exports.SEMATTRS_MESSAGING_SYSTEM = SEMATTRS_MESSAGING_SYSTEM;
2434
2660
  exports.SEMATTRS_NET_PEER_NAME = SEMATTRS_NET_PEER_NAME;
2435
2661
  exports.SEMATTRS_NET_PEER_PORT = SEMATTRS_NET_PEER_PORT;
@@ -2457,4 +2683,4 @@ exports.withProcessingSpan = withProcessingSpan;
2457
2683
  exports.withProducerSpan = withProducerSpan;
2458
2684
  exports.withPublishSpan = withPublishSpan;
2459
2685
  //# sourceMappingURL=index.cjs.map
2460
- //# sourceMappingURL=index.cjs.map
2686
+ //# sourceMappingURL=index.cjs.map