autotel 7.1.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +25 -0
  2. package/dist/analysis.cjs +17 -0
  3. package/dist/analysis.d.cts +9 -1
  4. package/dist/analysis.d.ts +9 -1
  5. package/dist/analysis.js +17 -1
  6. package/dist/auto.cjs +2 -3
  7. package/dist/auto.js +1 -2
  8. package/dist/correlation-id.cjs +1 -1
  9. package/dist/correlation-id.js +1 -1
  10. package/dist/decorators.cjs +1 -1
  11. package/dist/decorators.d.cts +1 -1
  12. package/dist/decorators.d.ts +1 -1
  13. package/dist/decorators.js +1 -1
  14. package/dist/event.cjs +1 -1
  15. package/dist/event.js +1 -1
  16. package/dist/{functional-BhhP4Er_.cjs → functional-C925G95W.cjs} +44 -10
  17. package/dist/{functional-CJn2zY4o.d.cts → functional-CgWcRXGX.d.cts} +12 -5
  18. package/dist/{functional-Cub1ku-C.js → functional-Doi0hFm3.js} +40 -6
  19. package/dist/{functional-DXy1cHFF.d.ts → functional-RFFpQzAV.d.ts} +12 -5
  20. package/dist/functional.cjs +1 -1
  21. package/dist/functional.d.cts +1 -1
  22. package/dist/functional.d.ts +1 -1
  23. package/dist/functional.js +1 -1
  24. package/dist/http.cjs +1 -1
  25. package/dist/http.js +1 -1
  26. package/dist/index.cjs +53 -15
  27. package/dist/index.d.cts +24 -4
  28. package/dist/index.d.ts +24 -4
  29. package/dist/index.js +40 -5
  30. package/dist/{init-DrlL1eis.d.cts → init-8GSy2bza.d.cts} +1 -1
  31. package/dist/{init-DDyaLzeg.js → init-DzAdgcFM.js} +2181 -1303
  32. package/dist/{init-BgnYi2sm.d.ts → init-UnKrXhpq.d.ts} +1 -1
  33. package/dist/{init-C5aHRqi2.cjs → init-aTZKsAwy.cjs} +2324 -1294
  34. package/dist/instrumentation.cjs +2 -3
  35. package/dist/instrumentation.js +1 -2
  36. package/dist/messaging.cjs +5 -5
  37. package/dist/messaging.js +2 -2
  38. package/dist/{sampling-CM5S2Lp3.d.ts → sampling-DBng4Foa.d.ts} +20 -1
  39. package/dist/{sampling-CmRdnXUi.d.cts → sampling-Er217Mge.d.cts} +20 -1
  40. package/dist/sampling.cjs +22 -601
  41. package/dist/sampling.d.cts +2 -2
  42. package/dist/sampling.d.ts +2 -2
  43. package/dist/sampling.js +2 -585
  44. package/dist/semantic-helpers.cjs +1 -1
  45. package/dist/semantic-helpers.js +1 -1
  46. package/dist/tail-sampling-processor.cjs +2 -26
  47. package/dist/tail-sampling-processor.js +1 -25
  48. package/dist/webhook.cjs +1 -1
  49. package/dist/webhook.js +1 -1
  50. package/dist/workflow-distributed.cjs +1 -1
  51. package/dist/workflow-distributed.js +1 -1
  52. package/dist/workflow.cjs +1 -1
  53. package/dist/workflow.js +1 -1
  54. package/dist/yaml-config.cjs +4 -248
  55. package/dist/yaml-config.d.cts +2 -2
  56. package/dist/yaml-config.d.ts +2 -2
  57. package/dist/yaml-config.js +1 -242
  58. package/package.json +1 -1
package/dist/sampling.js CHANGED
@@ -1,586 +1,3 @@
1
- import { d as asStringRecord } from "./values-BenyvWKz.js";
2
- import { TraceFlags } from "@opentelemetry/api";
1
+ import { A as KeyTargetRateSampler, B as resolveSamplingPreset, C as AUTOTEL_SAMPLING_TAIL_EVALUATED, D as CompositeSampler, E as AlwaysSampler, F as debugCaptureRequested, I as extractLinksFromBatch, L as hashUnitInterval, M as RandomSampler, N as UserIdSampler, O as DeterministicSampler, P as createLinkFromHeaders, R as isForceKept, S as AUTOTEL_SAMPLING_RATE, T as AdaptiveSampler, V as samplingPresets, j as NeverSampler, k as FeatureFlagSampler, w as AUTOTEL_SAMPLING_TAIL_KEEP, x as AUTOTEL_DEBUG_BAGGAGE_KEY, z as markForceKept } from "./init-DzAdgcFM.js";
3
2
 
4
- //#region src/sampling.ts
5
- /**
6
- * Tail sampling attribute keys (autotel-internal, not OTel semconv)
7
- */
8
- const AUTOTEL_SAMPLING_TAIL_KEEP = "autotel.sampling.tail.keep";
9
- const AUTOTEL_SAMPLING_TAIL_EVALUATED = "autotel.sampling.tail.evaluated";
10
- /**
11
- * How many events each kept event stands for, expressed as "1 in N".
12
- *
13
- * A query that counts sampled spans undercounts the population. Multiplying
14
- * each kept event by this rate restores the estimate. Autotel records the
15
- * attribute only when N exceeds 1, so fully captured spans stay clean.
16
- */
17
- const AUTOTEL_SAMPLING_RATE = "autotel.sampling.rate";
18
- /**
19
- * Convert a keep probability into the "1 in N" rate reported on spans.
20
- *
21
- * Keeping 10% of traces means each survivor stands for 10, so the two numbers
22
- * are reciprocals and easy to publish the wrong way round.
23
- */
24
- function toSampleRate(probability) {
25
- return probability > 0 ? 1 / probability : 0;
26
- }
27
- /**
28
- * Map a string to a stable, evenly spread position in the unit interval.
29
- *
30
- * Two processes that hash the same key reach the same number, which is what
31
- * lets independent services agree on one trace's sampling decision.
32
- *
33
- * The spread matters as much as the stability. Real sampling keys share long
34
- * prefixes: `user_1000`, `user_1001`, `checkout-trace-0001`. A plain
35
- * multiply-and-add hash lets that shared prefix dominate the high bits, so a
36
- * whole key family lands in one narrow band and a rate of 0.1 keeps all of
37
- * them or none of them. FNV-1a followed by the murmur3 finalizer mixes the
38
- * low bits back through the word, so keys that differ in one character land
39
- * far apart.
40
- */
41
- function hashUnitInterval(value) {
42
- let hash = 2166136261;
43
- for (let i = 0; i < value.length; i++) {
44
- hash ^= value.codePointAt(i) ?? 0;
45
- hash = Math.imul(hash, 16777619);
46
- }
47
- hash ^= hash >>> 16;
48
- hash = Math.imul(hash, 2246822507);
49
- hash ^= hash >>> 13;
50
- hash = Math.imul(hash, 3266489909);
51
- hash ^= hash >>> 16;
52
- return (hash >>> 0) / 4294967296;
53
- }
54
- /**
55
- * Simple random sampler
56
- *
57
- * @example
58
- * ```typescript
59
- * new RandomSampler(0.1) // Sample 10% of requests
60
- * ```
61
- */
62
- var RandomSampler = class {
63
- rate;
64
- constructor(rate) {
65
- this.rate = rate;
66
- if (rate < 0 || rate > 1) throw new Error("Sample rate must be between 0 and 1");
67
- }
68
- shouldSample(_context) {
69
- return Math.random() < this.rate;
70
- }
71
- sampleRate() {
72
- return toSampleRate(this.rate);
73
- }
74
- };
75
- /**
76
- * Always sample (100% tracing)
77
- */
78
- var AlwaysSampler = class {
79
- shouldSample(_context) {
80
- return true;
81
- }
82
- };
83
- /**
84
- * Never sample (0% tracing)
85
- */
86
- var NeverSampler = class {
87
- shouldSample(_context) {
88
- return false;
89
- }
90
- };
91
- /**
92
- * Adaptive sampler that always traces errors and slow requests
93
- *
94
- * This is the recommended sampler for production use.
95
- * It ensures you never miss critical issues while keeping costs down.
96
- *
97
- * Strategy:
98
- * - Always trace errors (critical for debugging)
99
- * - Always trace slow requests (performance issues)
100
- * - Use baseline sample rate for successful fast requests
101
- *
102
- * **IMPORTANT - Tail Sampling Requirement:**
103
- * This sampler uses tail sampling (makes decisions AFTER execution).
104
- * You MUST use TailSamplingSpanProcessor for it to work correctly:
105
- *
106
- * - If using initInstrumentation(): TailSamplingSpanProcessor is auto-configured
107
- * - If using custom TracerProvider: You MUST manually register TailSamplingSpanProcessor
108
- *
109
- * Without TailSamplingSpanProcessor, ALL spans are exported (defeating the cost savings).
110
- *
111
- * @see TailSamplingSpanProcessor
112
- * @see README.md "Tail Sampling with Custom Providers" section
113
- *
114
- * @example
115
- * ```typescript
116
- * new AdaptiveSampler({
117
- * baselineSampleRate: 0.1, // 10% of normal requests
118
- * slowThresholdMs: 1000, // Requests > 1s are "slow"
119
- * alwaysSampleErrors: true, // Always trace errors
120
- * alwaysSampleSlow: true // Always trace slow requests
121
- * })
122
- * ```
123
- */
124
- var AdaptiveSampler = class {
125
- baselineSampleRate;
126
- slowThresholdMs;
127
- alwaysSampleErrors;
128
- alwaysSampleSlow;
129
- linksBased;
130
- linksRate;
131
- logger;
132
- samplingDecisions = /* @__PURE__ */ new WeakMap();
133
- operationResults = /* @__PURE__ */ new WeakMap();
134
- constructor(options = {}) {
135
- this.baselineSampleRate = options.baselineSampleRate ?? .1;
136
- this.slowThresholdMs = options.slowThresholdMs ?? 1e3;
137
- this.alwaysSampleErrors = options.alwaysSampleErrors ?? true;
138
- this.alwaysSampleSlow = options.alwaysSampleSlow ?? true;
139
- this.linksBased = options.linksBased ?? false;
140
- this.linksRate = options.linksRate ?? 1;
141
- this.logger = options.logger;
142
- if (this.baselineSampleRate < 0 || this.baselineSampleRate > 1) throw new Error("Baseline sample rate must be between 0 and 1");
143
- if (this.linksRate < 0 || this.linksRate > 1) throw new Error("Links rate must be between 0 and 1");
144
- }
145
- needsTailSampling() {
146
- return true;
147
- }
148
- shouldSample(context) {
149
- const baselineDecision = Math.random() < this.baselineSampleRate;
150
- this.samplingDecisions.set(context.args, baselineDecision);
151
- return true;
152
- }
153
- /**
154
- * Check if any links point to sampled spans.
155
- *
156
- * A span is considered linked to a sampled span if any of its links
157
- * have trace_flags with the sampled bit set (0x01).
158
- *
159
- * @param links - Array of span links to check
160
- * @returns true if any linked span is sampled, false otherwise
161
- */
162
- hasSampledLink(links) {
163
- if (!links || links.length === 0) return false;
164
- return links.some((link) => link.context && (link.context.traceFlags & TraceFlags.SAMPLED) !== 0);
165
- }
166
- /**
167
- * Re-evaluate sampling decision after operation completes
168
- *
169
- * This allows us to always capture errors and slow requests,
170
- * even if they weren't initially sampled.
171
- *
172
- * @param context - Sampling context
173
- * @param result - Operation result
174
- * @returns true if this operation should be kept (not discarded)
175
- */
176
- shouldKeepTrace(context, result) {
177
- const baselineDecision = this.samplingDecisions.get(context.args) ?? false;
178
- if (this.alwaysSampleErrors && !result.success) {
179
- if (!baselineDecision) this.logger?.debug({
180
- operation: context.operationName,
181
- error: result.error?.message
182
- }, "Adaptive sampling: Keeping error trace");
183
- return true;
184
- }
185
- if (this.alwaysSampleSlow && result.duration >= this.slowThresholdMs) {
186
- if (!baselineDecision) this.logger?.debug({
187
- operation: context.operationName,
188
- duration: result.duration
189
- }, "Adaptive sampling: Keeping slow trace");
190
- return true;
191
- }
192
- if (this.linksBased && context.links && this.hasSampledLink(context.links)) {
193
- const keepLinked = Math.random() < this.linksRate;
194
- if (keepLinked && !baselineDecision) this.logger?.debug({
195
- operation: context.operationName,
196
- linkCount: context.links.length
197
- }, "Adaptive sampling: Keeping trace due to sampled link");
198
- return keepLinked;
199
- }
200
- return baselineDecision;
201
- }
202
- };
203
- /**
204
- * User-based sampler for consistent tracing
205
- *
206
- * Always samples requests from specific user IDs.
207
- * Useful for debugging specific user issues or monitoring VIP users.
208
- *
209
- * @example
210
- * ```typescript
211
- * new UserIdSampler({
212
- * baselineSampleRate: 0.01, // 1% of normal users
213
- * alwaysSampleUsers: ['vip_123'], // Always trace VIP users
214
- * extractUserId: (args) => args[0]?.userId // Extract user ID from first arg
215
- * })
216
- * ```
217
- */
218
- var UserIdSampler = class {
219
- baselineSampleRate;
220
- alwaysSampleUsers;
221
- extractUserId;
222
- logger;
223
- constructor(options) {
224
- this.baselineSampleRate = options.baselineSampleRate ?? .1;
225
- this.alwaysSampleUsers = new Set(options.alwaysSampleUsers || []);
226
- this.extractUserId = options.extractUserId;
227
- this.logger = options.logger;
228
- }
229
- shouldSample(context) {
230
- const userId = this.extractUserId(context.args);
231
- if (userId && this.alwaysSampleUsers.has(userId)) {
232
- this.logger?.debug({
233
- operation: context.operationName,
234
- userId
235
- }, "Sampling user request");
236
- return true;
237
- }
238
- if (userId) return this.hashString(userId) < this.baselineSampleRate;
239
- return Math.random() < this.baselineSampleRate;
240
- }
241
- /**
242
- * Add user IDs to always-sample list
243
- */
244
- addAlwaysSampleUsers(...userIds) {
245
- for (const userId of userIds) this.alwaysSampleUsers.add(userId);
246
- }
247
- /**
248
- * Remove user IDs from always-sample list
249
- */
250
- removeAlwaysSampleUsers(...userIds) {
251
- for (const userId of userIds) this.alwaysSampleUsers.delete(userId);
252
- }
253
- /**
254
- * Simple hash function for consistent user sampling
255
- */
256
- hashString(str) {
257
- return hashUnitInterval(str);
258
- }
259
- };
260
- /**
261
- * Consistent sampler: every service reaches the same verdict for one trace.
262
- *
263
- * `RandomSampler` rolls the dice per process, so an upstream service can keep
264
- * a trace that its downstream drops, leaving a waterfall with holes in it.
265
- * Hashing a key that travels with the request removes the disagreement. Pass
266
- * the trace id, or any identifier every hop already shares.
267
- *
268
- * @example
269
- * ```typescript
270
- * new DeterministicSampler({
271
- * sampleRate: 0.1,
272
- * key: (context) => trace.getActiveSpan()?.spanContext().traceId,
273
- * })
274
- * ```
275
- */
276
- var DeterministicSampler = class {
277
- rate;
278
- key;
279
- constructor(options) {
280
- if (options.sampleRate < 0 || options.sampleRate > 1) throw new Error("Sample rate must be between 0 and 1");
281
- this.rate = options.sampleRate;
282
- this.key = options.key;
283
- }
284
- shouldSample(context) {
285
- const key = this.key(context);
286
- if (key === void 0) return Math.random() < this.rate;
287
- return hashUnitInterval(key) < this.rate;
288
- }
289
- sampleRate() {
290
- return toSampleRate(this.rate);
291
- }
292
- };
293
- /** Bucket for keys seen after the tracked map fills up. */
294
- const OVERFLOW_KEY = "__overflow__";
295
- /**
296
- * Per-key target-rate sampler for workloads with uneven traffic.
297
- *
298
- * A single rate serves a skewed workload badly: 1% floods storage with the
299
- * busiest endpoint and still loses the rare tenant whose failures you need.
300
- * This sampler counts traffic per key over a rolling window, then sets each
301
- * key its own rate so every key contributes roughly `targetPerKey` events.
302
- * Quiet keys survive intact; loud keys get thinned.
303
- *
304
- * The first window keeps everything, because no traffic history exists yet.
305
- * Rates take effect from the second window onward.
306
- *
307
- * @example
308
- * ```typescript
309
- * new KeyTargetRateSampler({
310
- * key: (context) => context.operationName,
311
- * targetPerKey: 10, // ~10 events per key per window
312
- * windowMs: 30_000,
313
- * })
314
- * ```
315
- */
316
- var KeyTargetRateSampler = class {
317
- key;
318
- targetPerKey;
319
- windowMs;
320
- maxKeys;
321
- counts = /* @__PURE__ */ new Map();
322
- rates = /* @__PURE__ */ new Map();
323
- windowStart = Date.now();
324
- constructor(options) {
325
- this.key = options.key;
326
- this.targetPerKey = options.targetPerKey ?? 10;
327
- this.windowMs = options.windowMs ?? 3e4;
328
- this.maxKeys = options.maxKeys ?? 1e3;
329
- if (this.targetPerKey <= 0) throw new Error("Target per key must be greater than 0");
330
- if (this.windowMs <= 0) throw new Error("Window must be greater than 0");
331
- }
332
- /** Turn the window's observed counts into the next window's rates. */
333
- roll(now) {
334
- if (now - this.windowStart < this.windowMs) return;
335
- const rates = /* @__PURE__ */ new Map();
336
- for (const [key, count] of this.counts) rates.set(key, Math.max(1, count / this.targetPerKey));
337
- this.rates = rates;
338
- this.counts = /* @__PURE__ */ new Map();
339
- this.windowStart = now;
340
- }
341
- /**
342
- * Resolve the key, collapsing into one bucket once the map is full.
343
- *
344
- * An unbounded key function would otherwise grow the map without limit,
345
- * which turns a sampler meant to cut cost into a memory leak.
346
- */
347
- resolveKey(context) {
348
- const key = this.key(context) ?? OVERFLOW_KEY;
349
- if (this.counts.has(key) || this.counts.size < this.maxKeys) return key;
350
- return OVERFLOW_KEY;
351
- }
352
- shouldSample(context) {
353
- this.roll(Date.now());
354
- const key = this.resolveKey(context);
355
- this.counts.set(key, (this.counts.get(key) ?? 0) + 1);
356
- const rate = this.rates.get(key) ?? 1;
357
- return rate <= 1 || Math.random() < 1 / rate;
358
- }
359
- sampleRate(context) {
360
- return this.rates.get(this.resolveKey(context)) ?? 1;
361
- }
362
- };
363
- /**
364
- * Composite sampler that combines multiple samplers
365
- *
366
- * Samples if ANY of the child samplers returns true.
367
- *
368
- * @example
369
- * ```typescript
370
- * new CompositeSampler([
371
- * new UserIdSampler({ extractUserId: (args) => args[0]?.userId }),
372
- * new AdaptiveSampler({ baselineSampleRate: 0.1 })
373
- * ])
374
- * ```
375
- */
376
- var CompositeSampler = class {
377
- samplers;
378
- constructor(samplers) {
379
- this.samplers = samplers;
380
- if (samplers.length === 0) throw new Error("CompositeSampler requires at least one child sampler");
381
- }
382
- shouldSample(context) {
383
- return this.samplers.some((sampler) => sampler.shouldSample(context));
384
- }
385
- };
386
- /**
387
- * Feature flag sampler
388
- *
389
- * Always samples requests with specific feature flags enabled.
390
- * Perfect for correlating A/B test experiments with metrics.
391
- *
392
- * @example
393
- * ```typescript
394
- * new FeatureFlagSampler({
395
- * baselineSampleRate: 0.01,
396
- * alwaysSampleFlags: ['new_checkout', 'experimental_ui'],
397
- * extractFlags: (args, metadata) => metadata?.featureFlags
398
- * })
399
- * ```
400
- */
401
- var FeatureFlagSampler = class {
402
- baselineSampleRate;
403
- alwaysSampleFlags;
404
- extractFlags;
405
- logger;
406
- constructor(options) {
407
- this.baselineSampleRate = options.baselineSampleRate ?? .1;
408
- this.alwaysSampleFlags = new Set(options.alwaysSampleFlags || []);
409
- this.extractFlags = options.extractFlags;
410
- this.logger = options.logger;
411
- }
412
- shouldSample(context) {
413
- const flags = this.extractFlags(context.args, context.metadata);
414
- if (flags && flags.some((flag) => this.alwaysSampleFlags.has(flag))) {
415
- this.logger?.debug({
416
- operation: context.operationName,
417
- flags
418
- }, "Sampling feature flag request");
419
- return true;
420
- }
421
- return Math.random() < this.baselineSampleRate;
422
- }
423
- /**
424
- * Add feature flags to always-sample list
425
- */
426
- addAlwaysSampleFlags(...flags) {
427
- for (const flag of flags) this.alwaysSampleFlags.add(flag);
428
- }
429
- /**
430
- * Remove feature flags from always-sample list
431
- */
432
- removeAlwaysSampleFlags(...flags) {
433
- for (const flag of flags) this.alwaysSampleFlags.delete(flag);
434
- }
435
- };
436
- /**
437
- * Sampling preset factories.
438
- *
439
- * For most users, the string shorthand on `init()` is simpler:
440
- * ```typescript
441
- * init({ service: 'my-app', sampling: 'production' })
442
- * ```
443
- *
444
- * Use factories when you need to customize:
445
- * ```typescript
446
- * init({ service: 'my-app', sampler: samplingPresets.production({ baselineSampleRate: 0.05 }) })
447
- * ```
448
- */
449
- const samplingPresets = {
450
- /** Capture everything — best for local development and debugging */
451
- development: () => new AlwaysSampler(),
452
- /** Only bad outcomes — zero baseline, errors always kept */
453
- errorsOnly: () => new AdaptiveSampler({
454
- baselineSampleRate: 0,
455
- alwaysSampleErrors: true
456
- }),
457
- /**
458
- * Balanced production defaults — 10% baseline + errors + slow traces.
459
- * Pass overrides to tune (uses the same option names as AdaptiveSampler).
460
- */
461
- production: (overrides) => new AdaptiveSampler({
462
- baselineSampleRate: .1,
463
- alwaysSampleErrors: true,
464
- alwaysSampleSlow: true,
465
- slowThresholdMs: 1e3,
466
- ...overrides
467
- }),
468
- /** Disable sampling entirely */
469
- off: () => new NeverSampler()
470
- };
471
- /**
472
- * Resolve a preset string to a Sampler instance.
473
- * Used internally by `init()` when `sampling` string is provided.
474
- *
475
- * @throws Error if preset is not recognized
476
- */
477
- function resolveSamplingPreset(preset) {
478
- switch (preset) {
479
- case "development": return samplingPresets.development();
480
- case "errors-only": return samplingPresets.errorsOnly();
481
- case "production": return samplingPresets.production();
482
- case "off": return samplingPresets.off();
483
- default: throw new Error(`Unknown sampling preset: "${preset}". Valid presets: development, errors-only, production, off`);
484
- }
485
- }
486
- /**
487
- * Create a Link from W3C trace context headers (e.g., from a message queue).
488
- *
489
- * This is useful for message consumers that need to link to the producer span.
490
- * The headers should contain at least a `traceparent` header in W3C format.
491
- *
492
- * @param headers - Dictionary containing traceparent/tracestate headers
493
- * @param attributes - Optional attributes for the link
494
- * @returns Link object if context could be extracted, null otherwise
495
- *
496
- * @example
497
- * ```typescript
498
- * // In a Kafka consumer
499
- * const headers = { traceparent: '00-abc123...-def456...-01' };
500
- * const link = createLinkFromHeaders(headers);
501
- * if (link) {
502
- * // Use with tracer.startActiveSpan options or ctx.addLink()
503
- * tracer.startActiveSpan('process.message', { links: [link] }, span => { ... });
504
- * }
505
- * ```
506
- */
507
- function createLinkFromHeaders(headers, attributes) {
508
- const traceparent = headers.traceparent || headers["traceparent"];
509
- if (!traceparent) return null;
510
- const spanContext = parseTraceparent(traceparent);
511
- if (!spanContext || !isValidSpanContext(spanContext)) return null;
512
- return {
513
- context: spanContext,
514
- attributes: attributes ?? {}
515
- };
516
- }
517
- /**
518
- * Extract Links from a batch of messages for fan-in scenarios.
519
- *
520
- * Useful for batch processing where multiple producer spans should be linked.
521
- * This enables tracing causality in event-driven architectures where a single
522
- * consumer processes messages from multiple producers.
523
- *
524
- * @param messages - List of message objects
525
- * @param headersKey - Key in each message containing trace headers (default: 'headers')
526
- * @returns List of Link objects for all valid trace contexts
527
- *
528
- * @example
529
- * ```typescript
530
- * // Processing a batch of SQS/Kafka messages
531
- * const messages = [
532
- * { body: '...', headers: { traceparent: '...' } },
533
- * { body: '...', headers: { traceparent: '...' } },
534
- * ];
535
- * const links = extractLinksFromBatch(messages);
536
- *
537
- * tracer.startActiveSpan('process.batch', { links }, span => {
538
- * for (const msg of messages) {
539
- * processMessage(msg);
540
- * }
541
- * });
542
- * ```
543
- */
544
- function extractLinksFromBatch(messages, headersKey = "headers") {
545
- const links = [];
546
- for (const msg of messages) {
547
- const msgHeaders = asStringRecord(msg[headersKey]);
548
- if (msgHeaders) {
549
- const link = createLinkFromHeaders(msgHeaders, { "messaging.batch.message_index": links.length });
550
- if (link) links.push(link);
551
- }
552
- }
553
- return links;
554
- }
555
- /**
556
- * Parse W3C traceparent header into SpanContext
557
- * Format: version-traceId-spanId-traceFlags (e.g., 00-abc123...-def456...-01)
558
- *
559
- * @see https://www.w3.org/TR/trace-context/#traceparent-header
560
- */
561
- function parseTraceparent(traceparent) {
562
- const match = traceparent.match(/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i);
563
- if (!match || match.length < 5) return null;
564
- const version = match[1];
565
- const traceId = match[2];
566
- const spanId = match[3];
567
- const flags = match[4];
568
- if (!version || !traceId || !spanId || !flags) return null;
569
- if (version === "ff") return null;
570
- return {
571
- traceId,
572
- spanId,
573
- traceFlags: Number.parseInt(flags, 16),
574
- isRemote: true
575
- };
576
- }
577
- /**
578
- * Check if a SpanContext is valid (has non-zero trace and span IDs)
579
- */
580
- function isValidSpanContext(spanContext) {
581
- if (!spanContext) return false;
582
- return spanContext.traceId !== "00000000000000000000000000000000" && spanContext.spanId !== "0000000000000000";
583
- }
584
-
585
- //#endregion
586
- export { AUTOTEL_SAMPLING_RATE, AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP, AdaptiveSampler, AlwaysSampler, CompositeSampler, DeterministicSampler, FeatureFlagSampler, KeyTargetRateSampler, NeverSampler, RandomSampler, UserIdSampler, createLinkFromHeaders, extractLinksFromBatch, hashUnitInterval, resolveSamplingPreset, samplingPresets };
3
+ export { AUTOTEL_DEBUG_BAGGAGE_KEY, AUTOTEL_SAMPLING_RATE, AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP, AdaptiveSampler, AlwaysSampler, CompositeSampler, DeterministicSampler, FeatureFlagSampler, KeyTargetRateSampler, NeverSampler, RandomSampler, UserIdSampler, createLinkFromHeaders, debugCaptureRequested, extractLinksFromBatch, hashUnitInterval, isForceKept, markForceKept, resolveSamplingPreset, samplingPresets };
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_values = require('./values-DApyq53y.cjs');
3
- const require_functional = require('./functional-BhhP4Er_.cjs');
3
+ const require_functional = require('./functional-C925G95W.cjs');
4
4
  const require_trace_factory_validation = require('./trace-factory-validation-Dc8epn87.cjs');
5
5
  let _opentelemetry_api = require("@opentelemetry/api");
6
6
 
@@ -1,5 +1,5 @@
1
1
  import { b as toAttributeValue, g as nonEmptyString, s as asRecord } from "./values-BenyvWKz.js";
2
- import { c as withTracing } from "./functional-Cub1ku-C.js";
2
+ import { c as withTracing } from "./functional-Doi0hFm3.js";
3
3
  import { t as assertTraceFactory } from "./trace-factory-validation-BjVAinz6.js";
4
4
  import { SpanKind } from "@opentelemetry/api";
5
5
 
@@ -1,28 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_sampling = require('./sampling.cjs');
2
+ const require_init = require('./init-aTZKsAwy.cjs');
3
3
 
4
- //#region src/tail-sampling-processor.ts
5
- var TailSamplingSpanProcessor = class {
6
- wrappedProcessor;
7
- constructor(wrappedProcessor) {
8
- this.wrappedProcessor = wrappedProcessor;
9
- }
10
- onStart(span, parentContext) {
11
- this.wrappedProcessor.onStart(span, parentContext);
12
- }
13
- onEnd(span) {
14
- const tailEvaluated = span.attributes[require_sampling.AUTOTEL_SAMPLING_TAIL_EVALUATED];
15
- const shouldKeep = span.attributes[require_sampling.AUTOTEL_SAMPLING_TAIL_KEEP];
16
- if (tailEvaluated === true && shouldKeep === false) return;
17
- this.wrappedProcessor.onEnd(span);
18
- }
19
- forceFlush() {
20
- return this.wrappedProcessor.forceFlush();
21
- }
22
- shutdown() {
23
- return this.wrappedProcessor.shutdown();
24
- }
25
- };
26
-
27
- //#endregion
28
- exports.TailSamplingSpanProcessor = TailSamplingSpanProcessor;
4
+ exports.TailSamplingSpanProcessor = require_init.TailSamplingSpanProcessor;
@@ -1,27 +1,3 @@
1
- import { AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP } from "./sampling.js";
1
+ import { b as TailSamplingSpanProcessor } from "./init-DzAdgcFM.js";
2
2
 
3
- //#region src/tail-sampling-processor.ts
4
- var TailSamplingSpanProcessor = class {
5
- wrappedProcessor;
6
- constructor(wrappedProcessor) {
7
- this.wrappedProcessor = wrappedProcessor;
8
- }
9
- onStart(span, parentContext) {
10
- this.wrappedProcessor.onStart(span, parentContext);
11
- }
12
- onEnd(span) {
13
- const tailEvaluated = span.attributes[AUTOTEL_SAMPLING_TAIL_EVALUATED];
14
- const shouldKeep = span.attributes[AUTOTEL_SAMPLING_TAIL_KEEP];
15
- if (tailEvaluated === true && shouldKeep === false) return;
16
- this.wrappedProcessor.onEnd(span);
17
- }
18
- forceFlush() {
19
- return this.wrappedProcessor.forceFlush();
20
- }
21
- shutdown() {
22
- return this.wrappedProcessor.shutdown();
23
- }
24
- };
25
-
26
- //#endregion
27
3
  export { TailSamplingSpanProcessor };
package/dist/webhook.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_structured_error = require('./structured-error--_wXpd_C.cjs');
3
- const require_functional = require('./functional-BhhP4Er_.cjs');
3
+ const require_functional = require('./functional-C925G95W.cjs');
4
4
  const require_correlated_events = require('./correlated-events-CcuknWnU.cjs');
5
5
  let _opentelemetry_api = require("@opentelemetry/api");
6
6
 
package/dist/webhook.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { r as recordStructuredError } from "./structured-error-YIuka-FE.js";
2
- import { c as withTracing } from "./functional-Cub1ku-C.js";
2
+ import { c as withTracing } from "./functional-Doi0hFm3.js";
3
3
  import { t as emitCorrelatedEvent } from "./correlated-events-DwMMbItg.js";
4
4
  import { SpanKind, trace } from "@opentelemetry/api";
5
5
 
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_values = require('./values-DApyq53y.cjs');
3
- const require_functional = require('./functional-BhhP4Er_.cjs');
3
+ const require_functional = require('./functional-C925G95W.cjs');
4
4
  const require_correlated_events = require('./correlated-events-CcuknWnU.cjs');
5
5
  const require_business_baggage = require('./business-baggage.cjs');
6
6
  let _opentelemetry_api = require("@opentelemetry/api");
@@ -1,5 +1,5 @@
1
1
  import { h as isFunction, x as toError } from "./values-BenyvWKz.js";
2
- import { c as withTracing } from "./functional-Cub1ku-C.js";
2
+ import { c as withTracing } from "./functional-Doi0hFm3.js";
3
3
  import { t as emitCorrelatedEvent } from "./correlated-events-DwMMbItg.js";
4
4
  import { createSafeBaggageSchema } from "./business-baggage.js";
5
5
  import { SpanKind, context, propagation } from "@opentelemetry/api";