autotel 4.0.0 → 4.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 (232) hide show
  1. package/README.md +26 -1
  2. package/dist/auto.cjs +2 -2
  3. package/dist/auto.js +1 -1
  4. package/dist/correlation-id.cjs +1 -1
  5. package/dist/correlation-id.js +1 -1
  6. package/dist/decorators.cjs +1 -1
  7. package/dist/decorators.js +1 -1
  8. package/dist/{event-Dlqr4ZNL.cjs → event-BhHREDJk.cjs} +3 -3
  9. package/dist/{event-Dlqr4ZNL.cjs.map → event-BhHREDJk.cjs.map} +1 -1
  10. package/dist/{event-_58ryBjh.js → event-ByBTV9M2.js} +3 -3
  11. package/dist/{event-_58ryBjh.js.map → event-ByBTV9M2.js.map} +1 -1
  12. package/dist/event.cjs +1 -1
  13. package/dist/event.js +1 -1
  14. package/dist/{functional-BGkT8J-h.js → functional-DtI0u4vx.js} +19 -19
  15. package/dist/functional-DtI0u4vx.js.map +1 -0
  16. package/dist/{functional-C4CzoVrX.cjs → functional-zpzNLhky.cjs} +4 -4
  17. package/dist/{functional-C4CzoVrX.cjs.map → functional-zpzNLhky.cjs.map} +1 -1
  18. package/dist/functional.cjs +1 -1
  19. package/dist/functional.js +1 -1
  20. package/dist/http.cjs +1 -1
  21. package/dist/http.js +1 -1
  22. package/dist/index.cjs +5 -5
  23. package/dist/index.d.cts +1 -1
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +5 -5
  26. package/dist/{init-DJQOdVlN.d.ts → init-B7u-DjxM.d.ts} +57 -2
  27. package/dist/init-B7u-DjxM.d.ts.map +1 -0
  28. package/dist/{init-DvapOXCc.cjs → init-BX7AmFRl.cjs} +40 -21
  29. package/dist/init-BX7AmFRl.cjs.map +1 -0
  30. package/dist/{init-Ch6t7MNI.js → init-D-jnNMix.js} +39 -20
  31. package/dist/init-D-jnNMix.js.map +1 -0
  32. package/dist/{init-CNp-ee80.d.cts → init-DSrRmVnz.d.cts} +57 -2
  33. package/dist/init-DSrRmVnz.d.cts.map +1 -0
  34. package/dist/instrumentation.cjs +1 -1
  35. package/dist/instrumentation.js +1 -1
  36. package/dist/logger-D3Ej3DII.js +446 -0
  37. package/dist/logger-D3Ej3DII.js.map +1 -0
  38. package/dist/logger-thMPLpOG.cjs +487 -0
  39. package/dist/logger-thMPLpOG.cjs.map +1 -0
  40. package/dist/logger.cjs +8 -236
  41. package/dist/logger.js +2 -204
  42. package/dist/messaging.cjs +1 -1
  43. package/dist/messaging.js +1 -1
  44. package/dist/semantic-helpers.cjs +1 -1
  45. package/dist/semantic-helpers.js +1 -1
  46. package/dist/{track-3HY4NGV-.cjs → track-D59FfpL0.cjs} +2 -2
  47. package/dist/{track-3HY4NGV-.cjs.map → track-D59FfpL0.cjs.map} +1 -1
  48. package/dist/{track-nsKVy-pj.js → track-wc0HafS_.js} +6 -6
  49. package/dist/track-wc0HafS_.js.map +1 -0
  50. package/dist/webhook.cjs +1 -1
  51. package/dist/webhook.js +1 -1
  52. package/dist/workflow-distributed.cjs +1 -1
  53. package/dist/workflow-distributed.js +1 -1
  54. package/dist/workflow.cjs +1 -1
  55. package/dist/workflow.js +1 -1
  56. package/dist/{yaml-config-B3dQ82GR.cjs → yaml-config-Ck2uB0Dp.cjs} +2 -1
  57. package/dist/yaml-config-Ck2uB0Dp.cjs.map +1 -0
  58. package/dist/yaml-config.cjs +1 -1
  59. package/dist/yaml-config.d.cts +7 -1
  60. package/dist/yaml-config.d.cts.map +1 -1
  61. package/dist/yaml-config.d.ts +7 -1
  62. package/dist/yaml-config.d.ts.map +1 -1
  63. package/dist/yaml-config.js +1 -0
  64. package/dist/yaml-config.js.map +1 -1
  65. package/package.json +1 -2
  66. package/skills/autotel-core/SKILL.md +2 -0
  67. package/skills/autotel-instrumentation/SKILL.md +25 -0
  68. package/skills/debug-missing-spans/SKILL.md +3 -1
  69. package/skills/migrate-to-autotel/SKILL.md +24 -23
  70. package/skills/review-otel-patterns/SKILL.md +5 -4
  71. package/dist/functional-BGkT8J-h.js.map +0 -1
  72. package/dist/init-CNp-ee80.d.cts.map +0 -1
  73. package/dist/init-Ch6t7MNI.js.map +0 -1
  74. package/dist/init-DJQOdVlN.d.ts.map +0 -1
  75. package/dist/init-DvapOXCc.cjs.map +0 -1
  76. package/dist/logger.cjs.map +0 -1
  77. package/dist/logger.js.map +0 -1
  78. package/dist/track-nsKVy-pj.js.map +0 -1
  79. package/dist/yaml-config-B3dQ82GR.cjs.map +0 -1
  80. package/src/attribute-redacting-processor.test.ts +0 -763
  81. package/src/attribute-redacting-processor.ts +0 -621
  82. package/src/attributes/attachers.ts +0 -161
  83. package/src/attributes/builders.ts +0 -529
  84. package/src/attributes/domains.ts +0 -42
  85. package/src/attributes/index.ts +0 -81
  86. package/src/attributes/registry.ts +0 -323
  87. package/src/attributes/types.ts +0 -211
  88. package/src/attributes/utils.ts +0 -64
  89. package/src/attributes/validators.ts +0 -266
  90. package/src/attributes.test.ts +0 -292
  91. package/src/auto.ts +0 -67
  92. package/src/autotel-logger.test.ts +0 -548
  93. package/src/autotel-logger.ts +0 -364
  94. package/src/baggage-span-processor.test.ts +0 -202
  95. package/src/baggage-span-processor.ts +0 -100
  96. package/src/business-baggage.test.ts +0 -500
  97. package/src/business-baggage.ts +0 -669
  98. package/src/circuit-breaker.test.ts +0 -341
  99. package/src/circuit-breaker.ts +0 -184
  100. package/src/config.test.ts +0 -94
  101. package/src/config.ts +0 -172
  102. package/src/correlated-events.test.ts +0 -151
  103. package/src/correlated-events.ts +0 -47
  104. package/src/correlation-id.test.ts +0 -163
  105. package/src/correlation-id.ts +0 -206
  106. package/src/db.test.ts +0 -252
  107. package/src/db.ts +0 -447
  108. package/src/decorators.test.ts +0 -153
  109. package/src/decorators.ts +0 -188
  110. package/src/define-event.test.ts +0 -41
  111. package/src/define-event.ts +0 -58
  112. package/src/devtools.ts +0 -60
  113. package/src/drain-pipeline.test.ts +0 -68
  114. package/src/drain-pipeline.ts +0 -199
  115. package/src/drain-toolkit.test.ts +0 -113
  116. package/src/drain-toolkit.ts +0 -129
  117. package/src/enricher-toolkit.test.ts +0 -67
  118. package/src/enricher-toolkit.ts +0 -79
  119. package/src/enrichers.test.ts +0 -150
  120. package/src/enrichers.ts +0 -145
  121. package/src/env-config.test.ts +0 -323
  122. package/src/env-config.ts +0 -309
  123. package/src/error-catalog.test.ts +0 -133
  124. package/src/error-catalog.ts +0 -262
  125. package/src/event-queue.test.ts +0 -864
  126. package/src/event-queue.ts +0 -699
  127. package/src/event-subscriber.ts +0 -262
  128. package/src/event-testing.ts +0 -197
  129. package/src/event.test.ts +0 -1104
  130. package/src/event.ts +0 -988
  131. package/src/events-config.ts +0 -235
  132. package/src/exporters.ts +0 -165
  133. package/src/filtering-span-processor.test.ts +0 -281
  134. package/src/filtering-span-processor.ts +0 -111
  135. package/src/flatten-attributes.test.ts +0 -76
  136. package/src/flatten-attributes.ts +0 -80
  137. package/src/functional.strict-types.typecheck.ts +0 -53
  138. package/src/functional.test.ts +0 -1464
  139. package/src/functional.ts +0 -2539
  140. package/src/functional.types.test.ts +0 -135
  141. package/src/hook.mjs +0 -15
  142. package/src/http.test.ts +0 -485
  143. package/src/http.ts +0 -424
  144. package/src/index.ts +0 -433
  145. package/src/init-auto-redactor.test.ts +0 -53
  146. package/src/init-redactor.test.ts +0 -8
  147. package/src/init.customization.test.ts +0 -594
  148. package/src/init.integrations.test.ts +0 -399
  149. package/src/init.openllmetry.test.ts +0 -194
  150. package/src/init.protocol.test.ts +0 -215
  151. package/src/init.ts +0 -2312
  152. package/src/instrumentation.test.ts +0 -108
  153. package/src/instrumentation.ts +0 -319
  154. package/src/logger.test.ts +0 -125
  155. package/src/logger.ts +0 -341
  156. package/src/messaging-adapters.test.ts +0 -595
  157. package/src/messaging-adapters.ts +0 -583
  158. package/src/messaging-testing.test.ts +0 -573
  159. package/src/messaging-testing.ts +0 -935
  160. package/src/messaging.test.ts +0 -1646
  161. package/src/messaging.ts +0 -2245
  162. package/src/metric-helpers.ts +0 -47
  163. package/src/metric-testing.ts +0 -197
  164. package/src/metric.ts +0 -446
  165. package/src/metrics.test.ts +0 -241
  166. package/src/node-require.ts +0 -123
  167. package/src/operation-context.ts +0 -93
  168. package/src/parse-error.test.ts +0 -73
  169. package/src/parse-error.ts +0 -112
  170. package/src/posthog-logs.test.ts +0 -115
  171. package/src/posthog-logs.ts +0 -77
  172. package/src/pretty-console-exporter.test.ts +0 -545
  173. package/src/pretty-console-exporter.ts +0 -413
  174. package/src/pretty-log-formatter.test.ts +0 -123
  175. package/src/pretty-log-formatter.ts +0 -210
  176. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  177. package/src/processors/canonical-log-line-processor.ts +0 -396
  178. package/src/processors.ts +0 -152
  179. package/src/rate-limiter.test.ts +0 -199
  180. package/src/rate-limiter.ts +0 -98
  181. package/src/redact-values.test.ts +0 -90
  182. package/src/redact-values.ts +0 -34
  183. package/src/register.ts +0 -37
  184. package/src/request-logger.test.ts +0 -545
  185. package/src/request-logger.ts +0 -342
  186. package/src/sampling.test.ts +0 -1060
  187. package/src/sampling.ts +0 -737
  188. package/src/security-schema.test.ts +0 -45
  189. package/src/security-schema.ts +0 -107
  190. package/src/semantic-conventions.ts +0 -15
  191. package/src/semantic-helpers.test.ts +0 -226
  192. package/src/semantic-helpers.ts +0 -438
  193. package/src/shutdown.test.ts +0 -364
  194. package/src/shutdown.ts +0 -246
  195. package/src/span-name-normalizer.test.ts +0 -377
  196. package/src/span-name-normalizer.ts +0 -213
  197. package/src/stable-hash.ts +0 -27
  198. package/src/structured-error.test.ts +0 -191
  199. package/src/structured-error.ts +0 -157
  200. package/src/stub.integration.test.ts +0 -361
  201. package/src/tail-sampling-processor.test.ts +0 -230
  202. package/src/tail-sampling-processor.ts +0 -55
  203. package/src/test-span-collector.test.ts +0 -234
  204. package/src/test-span-collector.ts +0 -150
  205. package/src/testing.ts +0 -705
  206. package/src/trace-context.test.ts +0 -73
  207. package/src/trace-context.ts +0 -567
  208. package/src/trace-helpers.new.test.ts +0 -278
  209. package/src/trace-helpers.test.ts +0 -290
  210. package/src/trace-helpers.ts +0 -710
  211. package/src/trace-hybrid.test.ts +0 -42
  212. package/src/trace-hybrid.ts +0 -37
  213. package/src/tracer-provider.test.ts +0 -183
  214. package/src/tracer-provider.ts +0 -266
  215. package/src/track.test.ts +0 -154
  216. package/src/track.ts +0 -216
  217. package/src/validate.test.ts +0 -287
  218. package/src/validate.ts +0 -307
  219. package/src/validation-attributes.ts +0 -43
  220. package/src/validation.test.ts +0 -330
  221. package/src/validation.ts +0 -246
  222. package/src/variable-name-inference.test.ts +0 -178
  223. package/src/variable-name-inference.ts +0 -242
  224. package/src/webhook.test.ts +0 -649
  225. package/src/webhook.ts +0 -637
  226. package/src/workflow-distributed.test.ts +0 -786
  227. package/src/workflow-distributed.ts +0 -916
  228. package/src/workflow.async-safety.integration.test.ts +0 -345
  229. package/src/workflow.test.ts +0 -647
  230. package/src/workflow.ts +0 -810
  231. package/src/yaml-config.test.ts +0 -337
  232. package/src/yaml-config.ts +0 -342
@@ -1,583 +0,0 @@
1
- /**
2
- * Pre-built adapter configurations for common messaging systems.
3
- *
4
- * These adapters provide ready-to-use hook configurations for systems
5
- * not explicitly supported by the core messaging module. Use them with
6
- * traceProducer/traceConsumer to get system-specific attributes.
7
- *
8
- * @example NATS consumer
9
- * ```typescript
10
- * import { traceConsumer } from 'autotel/messaging';
11
- * import { natsAdapter } from 'autotel/messaging/adapters';
12
- *
13
- * const processMessage = traceConsumer({
14
- * system: 'nats',
15
- * destination: 'orders',
16
- * ...natsAdapter.consumer,
17
- * })(ctx => async (msg) => {
18
- * // msg.subject, msg.info.stream are now captured as span attributes
19
- * await handleOrder(msg.data);
20
- * });
21
- * ```
22
- *
23
- * @example Datadog context propagation
24
- * ```typescript
25
- * import { traceConsumer } from 'autotel/messaging';
26
- * import { datadogContextExtractor } from 'autotel/messaging/adapters';
27
- *
28
- * const processMessage = traceConsumer({
29
- * system: 'kafka',
30
- * destination: 'events',
31
- * customContextExtractor: datadogContextExtractor,
32
- * })(ctx => async (msg) => {
33
- * // Parent span from Datadog trace headers is linked
34
- * });
35
- * ```
36
- *
37
- * @module
38
- */
39
-
40
- import type { AttributeValue, SpanContext } from '@opentelemetry/api';
41
- import { TraceFlags } from '@opentelemetry/api';
42
- import type { ProducerContext, ConsumerContext } from './messaging';
43
-
44
- // ============================================================================
45
- // Adapter Types
46
- // ============================================================================
47
-
48
- /**
49
- * Producer adapter configuration
50
- */
51
- export interface ProducerAdapter {
52
- /**
53
- * Hook to add system-specific attributes to producer spans
54
- */
55
- customAttributes?: (
56
- ctx: ProducerContext,
57
- args: unknown[],
58
- ) => Record<string, AttributeValue>;
59
-
60
- /**
61
- * Hook to inject custom headers beyond W3C traceparent
62
- */
63
- customHeaders?: (ctx: ProducerContext) => Record<string, string>;
64
- }
65
-
66
- /**
67
- * Consumer adapter configuration
68
- */
69
- export interface ConsumerAdapter {
70
- /**
71
- * Extract headers from the message for trace context propagation
72
- */
73
- headersFrom?: (msg: unknown) => Record<string, string> | undefined;
74
-
75
- /**
76
- * Hook to add system-specific attributes to consumer spans
77
- */
78
- customAttributes?: (
79
- ctx: ConsumerContext,
80
- msg: unknown,
81
- ) => Record<string, AttributeValue>;
82
-
83
- /**
84
- * Hook to extract parent span context from non-W3C header formats
85
- */
86
- customContextExtractor?: (
87
- headers: Record<string, string>,
88
- ) => SpanContext | null;
89
- }
90
-
91
- /**
92
- * Combined producer and consumer adapter
93
- */
94
- export interface MessagingAdapter {
95
- producer?: ProducerAdapter;
96
- consumer?: ConsumerAdapter;
97
- }
98
-
99
- // ============================================================================
100
- // NATS JetStream Adapter
101
- // ============================================================================
102
-
103
- /**
104
- * NATS JetStream message type (for reference)
105
- *
106
- * @internal Not exported - users bring their own NATS types
107
- */
108
- interface NatsJetStreamMsg {
109
- subject: string;
110
- reply?: string;
111
- data: Uint8Array;
112
- headers?: {
113
- /** Convert headers to plain object (some NATS implementations) */
114
- toJSON?: () => Record<string, string> | unknown;
115
- /** Get a header value by key (Headers-like interface) */
116
- get?: (key: string) => string | undefined;
117
- /** Iterate over header entries */
118
- entries?: () => Iterable<[string, string]>;
119
- };
120
- info?: {
121
- stream: string;
122
- consumer: string;
123
- redeliveryCount?: number;
124
- pending?: number;
125
- timestampNanos?: bigint;
126
- };
127
- }
128
-
129
- /**
130
- * NATS JetStream adapter
131
- *
132
- * Captures NATS-specific attributes following NATS observability conventions.
133
- *
134
- * @example Producer
135
- * ```typescript
136
- * const publishOrder = traceProducer({
137
- * system: 'nats',
138
- * destination: 'orders.created',
139
- * ...natsAdapter.producer,
140
- * })(ctx => async (subject, payload, opts) => {
141
- * const headers = ctx.getTraceHeaders();
142
- * await nc.publish(subject, payload, { headers });
143
- * });
144
- * ```
145
- *
146
- * @example Consumer
147
- * ```typescript
148
- * const processOrder = traceConsumer({
149
- * system: 'nats',
150
- * destination: 'orders.created',
151
- * consumerGroup: 'order-processor',
152
- * ...natsAdapter.consumer,
153
- * })(ctx => async (msg: JsMsg) => {
154
- * await handleOrder(msg.data);
155
- * msg.ack();
156
- * });
157
- * ```
158
- */
159
- export const natsAdapter: MessagingAdapter = {
160
- producer: {
161
- customAttributes: (_ctx, args) => {
162
- const msg = args[0] as
163
- | { subject?: string; replyTo?: string; stream?: string }
164
- | undefined;
165
- const attrs: Record<string, AttributeValue> = {};
166
-
167
- if (msg?.subject) attrs['nats.subject'] = msg.subject;
168
- if (msg?.replyTo) attrs['nats.reply_to'] = msg.replyTo;
169
- if (msg?.stream) attrs['nats.stream'] = msg.stream;
170
-
171
- return attrs;
172
- },
173
- },
174
- consumer: {
175
- headersFrom: (msg) => {
176
- const natsMsg = msg as NatsJetStreamMsg;
177
- const headers = natsMsg.headers;
178
-
179
- if (!headers) return;
180
-
181
- // Try toJSON() first (some NATS implementations)
182
- if (typeof headers.toJSON === 'function') {
183
- const json = headers.toJSON();
184
- if (json && typeof json === 'object') {
185
- return json as Record<string, string>;
186
- }
187
- }
188
-
189
- // Fallback: use .get() for common trace headers
190
- // This handles Headers-like objects that only expose .get()
191
- if (typeof headers.get === 'function') {
192
- const result: Record<string, string> = {};
193
- const traceHeaders = [
194
- 'traceparent',
195
- 'tracestate',
196
- 'baggage',
197
- 'x-b3-traceid',
198
- 'x-b3-spanid',
199
- 'x-b3-sampled',
200
- 'b3',
201
- ];
202
- for (const key of traceHeaders) {
203
- const value = headers.get(key);
204
- if (value) {
205
- result[key] = value;
206
- }
207
- }
208
- if (Object.keys(result).length > 0) {
209
- return result;
210
- }
211
- }
212
-
213
- // Fallback: try to iterate if it's iterable (e.g., entries())
214
- if (typeof headers.entries === 'function') {
215
- const result: Record<string, string> = {};
216
- for (const [key, value] of headers.entries()) {
217
- if (typeof key === 'string' && typeof value === 'string') {
218
- result[key] = value;
219
- }
220
- }
221
- if (Object.keys(result).length > 0) {
222
- return result;
223
- }
224
- }
225
-
226
- return;
227
- },
228
- customAttributes: (_ctx, msg) => {
229
- const natsMsg = msg as NatsJetStreamMsg;
230
- const attrs: Record<string, AttributeValue> = {};
231
-
232
- if (natsMsg.subject) attrs['nats.subject'] = natsMsg.subject;
233
- if (natsMsg.reply) attrs['nats.reply_to'] = natsMsg.reply;
234
- if (natsMsg.info?.stream) attrs['nats.stream'] = natsMsg.info.stream;
235
- if (natsMsg.info?.consumer)
236
- attrs['nats.consumer'] = natsMsg.info.consumer;
237
- if (natsMsg.info?.redeliveryCount !== undefined) {
238
- attrs['nats.delivered_count'] = natsMsg.info.redeliveryCount;
239
- }
240
- if (natsMsg.info?.pending !== undefined) {
241
- attrs['nats.pending'] = natsMsg.info.pending;
242
- }
243
-
244
- return attrs;
245
- },
246
- },
247
- };
248
-
249
- // ============================================================================
250
- // Temporal Adapter
251
- // ============================================================================
252
-
253
- /**
254
- * Temporal activity/workflow info type (for reference)
255
- *
256
- * @internal Not exported - users bring their own Temporal types
257
- */
258
- interface TemporalActivityInfo {
259
- workflowId?: string;
260
- runId?: string;
261
- activityId?: string;
262
- taskQueue?: string;
263
- attempt?: number;
264
- workflowType?: string;
265
- activityType?: string;
266
- startToCloseTimeout?: string;
267
- scheduleToCloseTimeout?: string;
268
- }
269
-
270
- /**
271
- * Temporal adapter
272
- *
273
- * Captures Temporal-specific attributes for workflow activities.
274
- * Use this when instrumenting Temporal activity handlers.
275
- *
276
- * @example Activity handler
277
- * ```typescript
278
- * const processOrder = traceConsumer({
279
- * system: 'temporal',
280
- * destination: 'order-activities',
281
- * ...temporalAdapter.consumer,
282
- * })(ctx => async (info: ActivityInfo, input: OrderInput) => {
283
- * // Temporal attributes are captured automatically
284
- * return processOrderLogic(input);
285
- * });
286
- * ```
287
- *
288
- * @example Workflow signal/query
289
- * ```typescript
290
- * const sendSignal = traceProducer({
291
- * system: 'temporal',
292
- * destination: 'order-signals',
293
- * ...temporalAdapter.producer,
294
- * })(ctx => async (workflowId, signalName, payload) => {
295
- * await client.workflow.signal(workflowId, signalName, payload);
296
- * });
297
- * ```
298
- */
299
- export const temporalAdapter: MessagingAdapter = {
300
- producer: {
301
- customAttributes: (_ctx, args) => {
302
- const info = args[0] as TemporalActivityInfo | undefined;
303
- const attrs: Record<string, AttributeValue> = {};
304
-
305
- if (info?.workflowId) attrs['temporal.workflow_id'] = info.workflowId;
306
- if (info?.runId) attrs['temporal.run_id'] = info.runId;
307
- if (info?.taskQueue) attrs['temporal.task_queue'] = info.taskQueue;
308
- if (info?.workflowType)
309
- attrs['temporal.workflow_type'] = info.workflowType;
310
-
311
- return attrs;
312
- },
313
- },
314
- consumer: {
315
- customAttributes: (_ctx, msg) => {
316
- const info = msg as TemporalActivityInfo;
317
- const attrs: Record<string, AttributeValue> = {};
318
-
319
- if (info.workflowId) attrs['temporal.workflow_id'] = info.workflowId;
320
- if (info.runId) attrs['temporal.run_id'] = info.runId;
321
- if (info.activityId) attrs['temporal.activity_id'] = info.activityId;
322
- if (info.taskQueue) attrs['temporal.task_queue'] = info.taskQueue;
323
- if (info.attempt !== undefined) attrs['temporal.attempt'] = info.attempt;
324
- if (info.activityType)
325
- attrs['temporal.activity_type'] = info.activityType;
326
-
327
- return attrs;
328
- },
329
- },
330
- };
331
-
332
- // ============================================================================
333
- // Cloudflare Queues Adapter
334
- // ============================================================================
335
-
336
- /**
337
- * Cloudflare Queue message type (for reference)
338
- *
339
- * @internal Not exported - users bring their own Cloudflare types
340
- */
341
- interface CloudflareQueueMessage {
342
- id: string;
343
- timestamp: Date;
344
- body: unknown;
345
- attempts: number;
346
- }
347
-
348
- /**
349
- * Cloudflare Queues adapter
350
- *
351
- * Captures Cloudflare Queue-specific attributes.
352
- *
353
- * @example Queue consumer
354
- * ```typescript
355
- * export default {
356
- * async queue(batch: MessageBatch, env: Env) {
357
- * for (const msg of batch.messages) {
358
- * await processMessage(msg);
359
- * }
360
- * },
361
- * };
362
- *
363
- * const processMessage = traceConsumer({
364
- * system: 'cloudflare_queues',
365
- * destination: 'my-queue',
366
- * ...cloudflareQueuesAdapter.consumer,
367
- * })(ctx => async (msg: Message) => {
368
- * await handleMessage(msg.body);
369
- * msg.ack();
370
- * });
371
- * ```
372
- */
373
- export const cloudflareQueuesAdapter: MessagingAdapter = {
374
- consumer: {
375
- customAttributes: (_ctx, msg) => {
376
- const cfMsg = msg as CloudflareQueueMessage;
377
- const attrs: Record<string, AttributeValue> = {};
378
-
379
- if (cfMsg.id) attrs['cloudflare.queue.message_id'] = cfMsg.id;
380
- if (cfMsg.timestamp) {
381
- attrs['cloudflare.queue.timestamp_ms'] = cfMsg.timestamp.getTime();
382
- }
383
- if (cfMsg.attempts !== undefined) {
384
- attrs['cloudflare.queue.attempts'] = cfMsg.attempts;
385
- }
386
-
387
- return attrs;
388
- },
389
- },
390
- };
391
-
392
- // ============================================================================
393
- // Context Extractors for Non-W3C Formats
394
- // ============================================================================
395
-
396
- /**
397
- * Datadog trace context extractor
398
- *
399
- * Extracts parent span context from Datadog-format trace headers.
400
- * Converts Datadog's decimal IDs to OpenTelemetry's hex format.
401
- *
402
- * Note: Datadog sends trace/span IDs as decimal strings, not hex.
403
- * This extractor converts decimal -> hex before formatting for OTel.
404
- *
405
- * @example
406
- * ```typescript
407
- * const processMessage = traceConsumer({
408
- * system: 'kafka',
409
- * destination: 'events',
410
- * customContextExtractor: datadogContextExtractor,
411
- * })(ctx => async (msg) => {
412
- * // Links to parent Datadog span automatically
413
- * });
414
- * ```
415
- */
416
- export function datadogContextExtractor(
417
- headers: Record<string, string>,
418
- ): SpanContext | null {
419
- const traceIdDecimal = headers['x-datadog-trace-id'];
420
- const spanIdDecimal = headers['x-datadog-parent-id'];
421
- const samplingPriority = headers['x-datadog-sampling-priority'];
422
-
423
- if (!traceIdDecimal || !spanIdDecimal) return null;
424
-
425
- // Datadog sends IDs as decimal strings - convert to hex
426
- // Use BigInt for 64-bit values that exceed Number.MAX_SAFE_INTEGER
427
- let otelTraceId: string;
428
- let otelSpanId: string;
429
-
430
- try {
431
- // Convert decimal to hex and pad to OTel format
432
- // OTel trace IDs are 32 hex chars (128-bit), Datadog uses 64-bit
433
- otelTraceId = BigInt(traceIdDecimal).toString(16).padStart(32, '0');
434
- // OTel span IDs are 16 hex chars (64-bit)
435
- otelSpanId = BigInt(spanIdDecimal).toString(16).padStart(16, '0');
436
- } catch {
437
- // Invalid decimal string
438
- return null;
439
- }
440
-
441
- // Sampling priority > 0 means sampled
442
- const sampled = samplingPriority
443
- ? Number.parseInt(samplingPriority, 10) > 0
444
- : true;
445
-
446
- return {
447
- traceId: otelTraceId,
448
- spanId: otelSpanId,
449
- traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
450
- isRemote: true,
451
- };
452
- }
453
-
454
- /**
455
- * B3 (Zipkin) trace context extractor
456
- *
457
- * Extracts parent span context from B3 format headers.
458
- * Supports both single-header (b3) and multi-header formats.
459
- *
460
- * @see https://github.com/openzipkin/b3-propagation
461
- *
462
- * @example Single-header format
463
- * ```typescript
464
- * // Header: b3: 80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-1
465
- * const processMessage = traceConsumer({
466
- * system: 'rabbitmq',
467
- * destination: 'events',
468
- * customContextExtractor: b3ContextExtractor,
469
- * })(ctx => async (msg) => {
470
- * // Links to parent Zipkin span
471
- * });
472
- * ```
473
- *
474
- * @example Multi-header format
475
- * ```typescript
476
- * // Headers: X-B3-TraceId, X-B3-SpanId, X-B3-Sampled
477
- * ```
478
- */
479
- export function b3ContextExtractor(
480
- headers: Record<string, string>,
481
- ): SpanContext | null {
482
- // Try single-header format first: {TraceId}-{SpanId}-{SamplingState}-{ParentSpanId}
483
- const b3Single = headers['b3'] || headers['B3'];
484
- if (b3Single) {
485
- // Handle "0" (not sampled, no trace) case
486
- if (b3Single === '0') return null;
487
-
488
- const parts = b3Single.split('-');
489
- const traceId = parts[0];
490
- const spanId = parts[1];
491
- const sampledFlag = parts[2];
492
-
493
- if (traceId && spanId) {
494
- const sampled = sampledFlag !== '0' && sampledFlag !== 'd';
495
-
496
- return {
497
- traceId: traceId.padStart(32, '0'),
498
- spanId: spanId.padStart(16, '0'),
499
- traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
500
- isRemote: true,
501
- };
502
- }
503
- }
504
-
505
- // Fall back to multi-header format
506
- const traceId =
507
- headers['x-b3-traceid'] ||
508
- headers['X-B3-TraceId'] ||
509
- headers['X-B3-Traceid'];
510
- const spanId =
511
- headers['x-b3-spanid'] || headers['X-B3-SpanId'] || headers['X-B3-Spanid'];
512
- const sampledHeader =
513
- headers['x-b3-sampled'] ||
514
- headers['X-B3-Sampled'] ||
515
- headers['x-b3-flags'] ||
516
- headers['X-B3-Flags'];
517
-
518
- if (!traceId || !spanId) return null;
519
-
520
- // x-b3-sampled: "1" or "true" = sampled, "0" or "false" = not sampled
521
- // x-b3-flags: "1" = debug (implies sampled)
522
- const sampled =
523
- sampledHeader === '1' ||
524
- sampledHeader === 'true' ||
525
- sampledHeader === undefined; // Default to sampled if not specified
526
-
527
- return {
528
- traceId: traceId.padStart(32, '0'),
529
- spanId: spanId.padStart(16, '0'),
530
- traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
531
- isRemote: true,
532
- };
533
- }
534
-
535
- /**
536
- * AWS X-Ray trace context extractor
537
- *
538
- * Extracts parent span context from AWS X-Ray trace header.
539
- * Format: Root=1-{timestamp}-{random};Parent={parent-id};Sampled={0|1}
540
- *
541
- * @example
542
- * ```typescript
543
- * const processMessage = traceConsumer({
544
- * system: 'sqs',
545
- * destination: 'my-queue',
546
- * customContextExtractor: xrayContextExtractor,
547
- * })(ctx => async (msg) => {
548
- * // Links to parent X-Ray trace
549
- * });
550
- * ```
551
- */
552
- export function xrayContextExtractor(
553
- headers: Record<string, string>,
554
- ): SpanContext | null {
555
- const xrayHeader = headers['x-amzn-trace-id'] || headers['X-Amzn-Trace-Id'];
556
-
557
- if (!xrayHeader) return null;
558
-
559
- // Parse: Root=1-{8-char-timestamp}-{24-char-random};Parent={16-char-parent};Sampled=1
560
- const rootMatch = xrayHeader.match(/Root=1-([a-f0-9]{8})-([a-f0-9]{24})/i);
561
- const parentMatch = xrayHeader.match(/Parent=([a-f0-9]{16})/i);
562
- const sampledMatch = xrayHeader.match(/Sampled=([01])/);
563
-
564
- if (!rootMatch || !parentMatch) return null;
565
-
566
- // X-Ray trace ID format: 1-{timestamp}-{random} -> OTel: {timestamp}{random}
567
- const timestamp = rootMatch[1];
568
- const random = rootMatch[2];
569
- const parentId = parentMatch[1];
570
-
571
- if (!timestamp || !random || !parentId) return null;
572
-
573
- const traceId = `${timestamp}${random}`;
574
- const spanId = parentId;
575
- const sampled = sampledMatch ? sampledMatch[1] === '1' : true;
576
-
577
- return {
578
- traceId,
579
- spanId,
580
- traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
581
- isRemote: true,
582
- };
583
- }