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
package/src/workflow.ts DELETED
@@ -1,810 +0,0 @@
1
- /**
2
- * Workflow and Saga tracing helpers
3
- *
4
- * Provides specialized tracing for multi-step workflows and sagas with
5
- * automatic step linking, compensation tracking, and workflow correlation.
6
- *
7
- * @example Simple workflow
8
- * ```typescript
9
- * import { traceWorkflow, traceStep } from 'autotel/workflow';
10
- *
11
- * export const processOrder = traceWorkflow({
12
- * name: 'OrderFulfillment',
13
- * workflowId: (order) => order.id,
14
- * })(ctx => async (order: Order) => {
15
- * await validateOrder(order);
16
- * await chargePayment(order);
17
- * await shipOrder(order);
18
- * });
19
- * ```
20
- *
21
- * @example Saga with compensation
22
- * ```typescript
23
- * import { traceWorkflow, traceStep } from 'autotel/workflow';
24
- *
25
- * export const orderSaga = traceWorkflow({
26
- * name: 'OrderSaga',
27
- * workflowId: () => generateUUID(),
28
- * })(ctx => async (order: Order) => {
29
- *
30
- * const reserveStep = traceStep({
31
- * name: 'ReserveInventory',
32
- * compensate: async () => {
33
- * await releaseInventory(order.items);
34
- * },
35
- * })(async () => {
36
- * await inventoryService.reserve(order.items);
37
- * });
38
- * await reserveStep();
39
- *
40
- * const paymentStep = traceStep({
41
- * name: 'ProcessPayment',
42
- * linkToPrevious: true,
43
- * compensate: async () => {
44
- * await refundPayment(order.paymentId);
45
- * },
46
- * })(async () => {
47
- * await paymentService.charge(order);
48
- * });
49
- * await paymentStep();
50
- * });
51
- * ```
52
- *
53
- * @module
54
- */
55
-
56
- import { AsyncLocalStorage } from 'node:async_hooks';
57
- import type { Attributes, Link, SpanContext } from '@opentelemetry/api';
58
- import { emitCorrelatedEvent } from './correlated-events';
59
- import { trace } from './functional';
60
- import type { TraceContext } from './trace-context';
61
- import { getActiveSpan } from './trace-helpers';
62
-
63
- // ============================================================================
64
- // Types
65
- // ============================================================================
66
-
67
- /**
68
- * Workflow status
69
- */
70
- export type WorkflowStatus =
71
- | 'pending'
72
- | 'running'
73
- | 'completed'
74
- | 'failed'
75
- | 'compensating'
76
- | 'compensated'
77
- | 'compensation_failed';
78
-
79
- /**
80
- * Step status
81
- */
82
- export type StepStatus =
83
- | 'pending'
84
- | 'running'
85
- | 'completed'
86
- | 'failed'
87
- | 'skipped'
88
- | 'compensated';
89
-
90
- /**
91
- * Configuration for workflow tracing
92
- */
93
- export interface WorkflowConfig<TArgs extends unknown[] = unknown[]> {
94
- /** Workflow name (e.g., 'OrderFulfillment', 'UserOnboarding') */
95
- name: string;
96
-
97
- /**
98
- * Function to extract or generate workflow ID
99
- * Can be static string, function of args, or generator
100
- */
101
- workflowId: string | ((...args: TArgs) => string);
102
-
103
- /** Optional workflow version */
104
- version?: string;
105
-
106
- /** Additional attributes */
107
- attributes?: Attributes;
108
-
109
- /** Callback on workflow completion */
110
- onComplete?: (ctx: WorkflowContext, result: unknown) => void;
111
-
112
- /** Callback on workflow failure */
113
- onFailed?: (ctx: WorkflowContext, error: Error) => void;
114
-
115
- /** Callback on compensation start */
116
- onCompensating?: (ctx: WorkflowContext) => void;
117
- }
118
-
119
- /**
120
- * Configuration for workflow step tracing
121
- */
122
- export interface StepConfig {
123
- /** Step name */
124
- name: string;
125
-
126
- /** Optional step description */
127
- description?: string;
128
-
129
- /** Step index (auto-assigned if not provided) */
130
- index?: number;
131
-
132
- /** Link to previous step span */
133
- linkToPrevious?: boolean;
134
-
135
- /** Link to specific step(s) by name */
136
- linkTo?: string | string[];
137
-
138
- /** Additional attributes */
139
- attributes?: Attributes;
140
-
141
- /** Compensation handler for saga rollback */
142
- compensate?: (error: Error) => Promise<void> | void;
143
-
144
- /** Whether this step is idempotent */
145
- idempotent?: boolean;
146
-
147
- /** Retry configuration */
148
- retry?: {
149
- maxAttempts: number;
150
- backoffMs?: number;
151
- };
152
-
153
- /** Callback on step completion */
154
- onComplete?: (ctx: StepContext) => void;
155
-
156
- /** Callback on step failure */
157
- onFailed?: (ctx: StepContext, error: Error) => void;
158
- }
159
-
160
- /**
161
- * Step metadata stored for linking and compensation
162
- */
163
- interface StepMetadata {
164
- name: string;
165
- index: number;
166
- status: StepStatus;
167
- spanContext?: SpanContext;
168
- compensate?: (error: Error) => Promise<void> | void;
169
- startTime: number;
170
- endTime?: number;
171
- }
172
-
173
- /**
174
- * Extended trace context for workflows
175
- */
176
- export interface WorkflowContext extends TraceContext {
177
- /** Get the workflow ID */
178
- getWorkflowId(): string;
179
-
180
- /** Get workflow name */
181
- getWorkflowName(): string;
182
-
183
- /** Get current workflow status */
184
- getStatus(): WorkflowStatus;
185
-
186
- /** Mark step as completed and store for linking */
187
- completeStep(stepName: string): void;
188
-
189
- /** Get previous step's span context for linking */
190
- getPreviousStep(stepName?: string): SpanContext | null;
191
-
192
- /** Get all completed steps */
193
- getCompletedSteps(): string[];
194
-
195
- /** Register a compensation handler */
196
- registerCompensation(
197
- stepName: string,
198
- handler: (error: Error) => Promise<void> | void,
199
- ): void;
200
-
201
- /** Trigger compensation for all registered steps */
202
- compensate(error: Error): Promise<void>;
203
-
204
- /** Record compensation result */
205
- recordCompensation(stepName: string, success: boolean, error?: Error): void;
206
-
207
- /** Set workflow status */
208
- setWorkflowStatus(status: WorkflowStatus): void;
209
- }
210
-
211
- /**
212
- * Extended trace context for workflow steps
213
- */
214
- export interface StepContext extends TraceContext {
215
- /** Get step name */
216
- getStepName(): string;
217
-
218
- /** Get step index */
219
- getStepIndex(): number;
220
-
221
- /** Mark this step as completed */
222
- complete(): void;
223
-
224
- /** Skip this step */
225
- skip(reason?: string): void;
226
-
227
- /** Get workflow context */
228
- getWorkflowContext(): WorkflowContext | null;
229
- }
230
-
231
- // ============================================================================
232
- // Storage
233
- // ============================================================================
234
-
235
- // Store workflow state in a WeakMap keyed by span
236
- const workflowStates = new WeakMap<
237
- object,
238
- {
239
- workflowId: string;
240
- workflowName: string;
241
- status: WorkflowStatus;
242
- steps: Map<string, StepMetadata>;
243
- stepCounter: number;
244
- compensations: Map<string, (error: Error) => Promise<void> | void>;
245
- }
246
- >();
247
-
248
- /**
249
- * AsyncLocalStorage for workflow context (async-safe)
250
- *
251
- * This replaces the previous module-level variable which was NOT safe for
252
- * concurrent workflows. AsyncLocalStorage ensures each async execution chain
253
- * has its own isolated workflow context.
254
- */
255
- const workflowContextStorage = new AsyncLocalStorage<WorkflowContext>();
256
-
257
- // ============================================================================
258
- // Workflow Helper
259
- // ============================================================================
260
-
261
- /**
262
- * Create a traced workflow function
263
- *
264
- * Wraps business logic in a workflow span with automatic step tracking,
265
- * correlation via workflow ID, and compensation support.
266
- *
267
- * @param config - Workflow configuration
268
- * @returns Factory function that wraps your workflow logic
269
- *
270
- * @example Order fulfillment workflow
271
- * ```typescript
272
- * export const fulfillOrder = traceWorkflow({
273
- * name: 'OrderFulfillment',
274
- * workflowId: (order) => order.id,
275
- * version: '2.0',
276
- * })(ctx => async (order: Order) => {
277
- * ctx.setAttribute('order.total', order.total);
278
- *
279
- * await validateOrder(order);
280
- * await processPayment(order);
281
- * await fulfillItems(order);
282
- * await notifyCustomer(order);
283
- *
284
- * return { success: true, orderId: order.id };
285
- * });
286
- * ```
287
- */
288
- export function traceWorkflow<TArgs extends unknown[], TReturn>(
289
- config: WorkflowConfig<TArgs>,
290
- ) {
291
- const spanName = `workflow.${config.name}`;
292
-
293
- return (
294
- fnFactory: (ctx: WorkflowContext) => (...args: TArgs) => Promise<TReturn>,
295
- ): ((...args: TArgs) => Promise<TReturn>) => {
296
- return trace<TArgs, TReturn>(spanName, (baseCtx) => {
297
- return async (...args: TArgs) => {
298
- // Generate or extract workflow ID
299
- const workflowId =
300
- typeof config.workflowId === 'function'
301
- ? config.workflowId(...args)
302
- : config.workflowId;
303
-
304
- // Create workflow context
305
- const ctx = createWorkflowContext(baseCtx, config.name, workflowId);
306
-
307
- // Set workflow attributes
308
- ctx.setAttribute('workflow.name', config.name);
309
- ctx.setAttribute('workflow.id', workflowId);
310
- if (config.version) {
311
- ctx.setAttribute('workflow.version', config.version);
312
- }
313
- ctx.setAttribute('workflow.status', 'running');
314
-
315
- // Set custom attributes
316
- if (config.attributes) {
317
- for (const [key, value] of Object.entries(config.attributes)) {
318
- if (value !== undefined) {
319
- ctx.setAttribute(key, value as string | number | boolean);
320
- }
321
- }
322
- }
323
-
324
- // Run workflow in AsyncLocalStorage context for async-safety
325
- // This ensures concurrent workflows have isolated contexts
326
- return workflowContextStorage.run(ctx, async () => {
327
- try {
328
- // Execute workflow
329
- const userFn = fnFactory(ctx);
330
- const result = await userFn(...args);
331
-
332
- // Mark as completed
333
- ctx.setWorkflowStatus('completed');
334
- config.onComplete?.(ctx, result);
335
-
336
- return result;
337
- } catch (error) {
338
- // Mark as failed
339
- ctx.setWorkflowStatus('failed');
340
- config.onFailed?.(ctx, error as Error);
341
-
342
- // Check if we have compensations to run
343
- const state = getWorkflowState();
344
- if (state && state.compensations.size > 0) {
345
- ctx.setWorkflowStatus('compensating');
346
- config.onCompensating?.(ctx);
347
-
348
- try {
349
- await ctx.compensate(error as Error);
350
- ctx.setWorkflowStatus('compensated');
351
- } catch (compensationError) {
352
- ctx.setWorkflowStatus('compensation_failed');
353
- ctx.setAttribute(
354
- 'workflow.compensation.error',
355
- String(compensationError),
356
- );
357
- }
358
- }
359
-
360
- throw error;
361
- }
362
- });
363
- };
364
- });
365
- };
366
- }
367
-
368
- /**
369
- * Create a traced workflow step
370
- *
371
- * Wraps step logic with automatic linking to previous steps,
372
- * compensation registration, and status tracking.
373
- *
374
- * @param config - Step configuration
375
- * @returns Factory function that wraps your step logic
376
- *
377
- * @example Step with compensation
378
- * ```typescript
379
- * const chargePayment = traceStep({
380
- * name: 'ChargePayment',
381
- * linkToPrevious: true,
382
- * compensate: async (error) => {
383
- * await paymentService.refund(paymentId);
384
- * },
385
- * })(async (amount: number) => {
386
- * return await paymentService.charge(amount);
387
- * });
388
- * ```
389
- */
390
- export function traceStep<TArgs extends unknown[], TReturn>(
391
- config: StepConfig,
392
- ) {
393
- return (
394
- fn: (...args: TArgs) => Promise<TReturn>,
395
- ): ((...args: TArgs) => Promise<TReturn>) => {
396
- const spanName = `step.${config.name}`;
397
-
398
- return trace<TArgs, TReturn>(spanName, (baseCtx) => {
399
- return async (...args: TArgs) => {
400
- // Get workflow context from AsyncLocalStorage (async-safe)
401
- const workflowCtx = workflowContextStorage.getStore() ?? null;
402
-
403
- // Create step context
404
- const ctx = createStepContext(baseCtx, config, workflowCtx);
405
-
406
- // Set step attributes
407
- ctx.setAttribute('workflow.step.name', config.name);
408
- ctx.setAttribute('workflow.step.index', ctx.getStepIndex());
409
- ctx.setAttribute('workflow.step.status', 'running');
410
-
411
- if (config.description) {
412
- ctx.setAttribute('workflow.step.description', config.description);
413
- }
414
-
415
- if (config.idempotent) {
416
- ctx.setAttribute('workflow.step.idempotent', true);
417
- }
418
-
419
- // Set custom attributes
420
- if (config.attributes) {
421
- for (const [key, value] of Object.entries(config.attributes)) {
422
- if (value !== undefined) {
423
- ctx.setAttribute(key, value as string | number | boolean);
424
- }
425
- }
426
- }
427
-
428
- // Link to previous steps
429
- await addStepLinks(ctx, config, workflowCtx);
430
-
431
- // Register compensation if provided
432
- if (config.compensate && workflowCtx) {
433
- workflowCtx.registerCompensation(config.name, config.compensate);
434
- }
435
-
436
- // Execute with optional retry
437
- let lastError: Error | undefined;
438
- const maxAttempts = config.retry?.maxAttempts ?? 1;
439
-
440
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
441
- try {
442
- if (attempt > 1) {
443
- ctx.setAttribute('workflow.step.retry_attempt', attempt);
444
- emitCorrelatedEvent(ctx, 'step_retry', {
445
- 'workflow.step.attempt': attempt,
446
- 'workflow.step.max_attempts': maxAttempts,
447
- });
448
-
449
- // Backoff
450
- if (config.retry?.backoffMs) {
451
- await sleep(config.retry.backoffMs * attempt);
452
- }
453
- }
454
-
455
- const result = await fn(...args);
456
-
457
- // Mark as completed
458
- ctx.setAttribute('workflow.step.status', 'completed');
459
- ctx.complete();
460
- config.onComplete?.(ctx);
461
-
462
- return result;
463
- } catch (error) {
464
- lastError = error as Error;
465
-
466
- if (attempt < maxAttempts) {
467
- emitCorrelatedEvent(ctx, 'step_retry_scheduled', {
468
- 'workflow.step.error': String(error),
469
- 'workflow.step.attempt': attempt,
470
- });
471
- }
472
- }
473
- }
474
-
475
- // All attempts failed
476
- ctx.setAttribute('workflow.step.status', 'failed');
477
- ctx.setAttribute('workflow.step.error', String(lastError));
478
- config.onFailed?.(ctx, lastError!);
479
-
480
- throw lastError;
481
- };
482
- });
483
- };
484
- }
485
-
486
- // ============================================================================
487
- // Context Creation
488
- // ============================================================================
489
-
490
- /**
491
- * Create workflow-extended context
492
- */
493
- function createWorkflowContext(
494
- baseCtx: TraceContext,
495
- workflowName: string,
496
- workflowId: string,
497
- ): WorkflowContext {
498
- // Initialize state
499
- const span = getActiveSpan();
500
- const state = {
501
- workflowId,
502
- workflowName,
503
- status: 'running' as WorkflowStatus,
504
- steps: new Map<string, StepMetadata>(),
505
- stepCounter: 0,
506
- compensations: new Map<string, (error: Error) => Promise<void> | void>(),
507
- };
508
-
509
- if (span) {
510
- workflowStates.set(span, state);
511
- }
512
-
513
- return {
514
- ...baseCtx,
515
-
516
- getWorkflowId(): string {
517
- return workflowId;
518
- },
519
-
520
- getWorkflowName(): string {
521
- return workflowName;
522
- },
523
-
524
- getStatus(): WorkflowStatus {
525
- return state.status;
526
- },
527
-
528
- completeStep(stepName: string): void {
529
- let step = state.steps.get(stepName);
530
- if (!step) {
531
- // Auto-create step entry for manually managed steps
532
- // (when using registerCompensation without traceStep)
533
- step = {
534
- name: stepName,
535
- index: state.stepCounter++,
536
- status: 'pending',
537
- startTime: Date.now(),
538
- };
539
- state.steps.set(stepName, step);
540
- }
541
- step.status = 'completed';
542
- step.endTime = Date.now();
543
-
544
- // Capture span context for linking
545
- const currentSpan = getActiveSpan();
546
- if (currentSpan) {
547
- step.spanContext = currentSpan.spanContext();
548
- }
549
- },
550
-
551
- getPreviousStep(stepName?: string): SpanContext | null {
552
- if (stepName) {
553
- const step = state.steps.get(stepName);
554
- return step?.spanContext ?? null;
555
- }
556
-
557
- // Get last completed step
558
- let lastStep: StepMetadata | null = null;
559
- for (const step of state.steps.values()) {
560
- if (
561
- step.status === 'completed' &&
562
- (!lastStep || step.index > lastStep.index)
563
- ) {
564
- lastStep = step;
565
- }
566
- }
567
-
568
- return lastStep?.spanContext ?? null;
569
- },
570
-
571
- getCompletedSteps(): string[] {
572
- const completed: string[] = [];
573
- for (const [name, step] of state.steps) {
574
- if (step.status === 'completed') {
575
- completed.push(name);
576
- }
577
- }
578
- return completed.toSorted(
579
- (a, b) =>
580
- (state.steps.get(a)?.index ?? 0) - (state.steps.get(b)?.index ?? 0),
581
- );
582
- },
583
-
584
- registerCompensation(
585
- stepName: string,
586
- handler: (error: Error) => Promise<void> | void,
587
- ): void {
588
- state.compensations.set(stepName, handler);
589
- },
590
-
591
- async compensate(error: Error): Promise<void> {
592
- // Execute compensations in reverse order
593
- const compensationOrder = [...state.compensations.entries()].toReversed();
594
-
595
- for (const [stepName, handler] of compensationOrder) {
596
- const step = state.steps.get(stepName);
597
- if (step && step.status === 'completed') {
598
- try {
599
- emitCorrelatedEvent(baseCtx, 'compensation_started', {
600
- 'workflow.step.name': stepName,
601
- });
602
-
603
- await Promise.resolve(handler(error));
604
-
605
- this.recordCompensation(stepName, true);
606
- step.status = 'compensated';
607
- } catch (compensationError) {
608
- this.recordCompensation(
609
- stepName,
610
- false,
611
- compensationError as Error,
612
- );
613
- throw compensationError;
614
- }
615
- }
616
- }
617
- },
618
-
619
- recordCompensation(
620
- stepName: string,
621
- success: boolean,
622
- error?: Error,
623
- ): void {
624
- emitCorrelatedEvent(baseCtx, 'compensation_completed', {
625
- 'workflow.step.name': stepName,
626
- 'workflow.compensation.success': success,
627
- ...(error && { 'workflow.compensation.error': String(error) }),
628
- });
629
-
630
- baseCtx.setAttribute(
631
- `workflow.compensation.${stepName}`,
632
- success ? 'success' : 'failed',
633
- );
634
- },
635
-
636
- setWorkflowStatus(status: WorkflowStatus): void {
637
- state.status = status;
638
- baseCtx.setAttribute('workflow.status', status);
639
-
640
- emitCorrelatedEvent(baseCtx, 'workflow_status_changed', {
641
- 'workflow.status': status,
642
- });
643
- },
644
- };
645
- }
646
-
647
- /**
648
- * Create step-extended context
649
- */
650
- function createStepContext(
651
- baseCtx: TraceContext,
652
- config: StepConfig,
653
- workflowCtx: WorkflowContext | null,
654
- ): StepContext {
655
- // Determine step index
656
- let stepIndex = config.index ?? 0;
657
- if (workflowCtx) {
658
- const span = getActiveSpan();
659
- if (span) {
660
- const state = workflowStates.get(span);
661
- if (state) {
662
- stepIndex = config.index ?? state.stepCounter++;
663
- }
664
- }
665
- }
666
-
667
- // Register step metadata
668
- if (workflowCtx) {
669
- const wfSpan = getActiveSpan();
670
- if (wfSpan) {
671
- const state = workflowStates.get(wfSpan);
672
- if (state) {
673
- state.steps.set(config.name, {
674
- name: config.name,
675
- index: stepIndex,
676
- status: 'running',
677
- startTime: Date.now(),
678
- compensate: config.compensate,
679
- });
680
- }
681
- }
682
- }
683
-
684
- return {
685
- ...baseCtx,
686
-
687
- getStepName(): string {
688
- return config.name;
689
- },
690
-
691
- getStepIndex(): number {
692
- return stepIndex;
693
- },
694
-
695
- complete(): void {
696
- if (workflowCtx) {
697
- workflowCtx.completeStep(config.name);
698
- }
699
- },
700
-
701
- skip(reason?: string): void {
702
- baseCtx.setAttribute('workflow.step.status', 'skipped');
703
- if (reason) {
704
- baseCtx.setAttribute('workflow.step.skip_reason', reason);
705
- }
706
- emitCorrelatedEvent(baseCtx, 'step_skipped', {
707
- 'workflow.step.name': config.name,
708
- ...(reason && { 'workflow.step.skip_reason': reason }),
709
- });
710
- },
711
-
712
- getWorkflowContext(): WorkflowContext | null {
713
- return workflowCtx;
714
- },
715
- };
716
- }
717
-
718
- // ============================================================================
719
- // Helper Functions
720
- // ============================================================================
721
-
722
- /**
723
- * Get workflow state from context
724
- */
725
- function getWorkflowState() {
726
- const span = getActiveSpan();
727
- return span ? workflowStates.get(span) : null;
728
- }
729
-
730
- /**
731
- * Add links to previous steps
732
- */
733
- async function addStepLinks(
734
- ctx: StepContext,
735
- config: StepConfig,
736
- workflowCtx: WorkflowContext | null,
737
- ): Promise<void> {
738
- if (!workflowCtx) return;
739
-
740
- const links: Link[] = [];
741
-
742
- // Link to previous step
743
- if (config.linkToPrevious) {
744
- const prevSpanContext = workflowCtx.getPreviousStep();
745
- if (prevSpanContext) {
746
- links.push({
747
- context: prevSpanContext,
748
- attributes: {
749
- 'workflow.link.type': 'sequence',
750
- },
751
- });
752
- }
753
- }
754
-
755
- // Link to specific steps
756
- if (config.linkTo) {
757
- const stepNames = Array.isArray(config.linkTo)
758
- ? config.linkTo
759
- : [config.linkTo];
760
-
761
- for (const stepName of stepNames) {
762
- const spanContext = workflowCtx.getPreviousStep(stepName);
763
- if (spanContext) {
764
- links.push({
765
- context: spanContext,
766
- attributes: {
767
- 'workflow.link.type': 'dependency',
768
- 'workflow.link.step': stepName,
769
- },
770
- });
771
- }
772
- }
773
- }
774
-
775
- // Add all links
776
- if (links.length > 0) {
777
- ctx.addLinks(links);
778
- }
779
- }
780
-
781
- /**
782
- * Sleep utility for retry backoff
783
- */
784
- function sleep(ms: number): Promise<void> {
785
- return new Promise((resolve) => setTimeout(resolve, ms));
786
- }
787
-
788
- // ============================================================================
789
- // Convenience Exports
790
- // ============================================================================
791
-
792
- /**
793
- * Get current workflow context (if inside a workflow)
794
- *
795
- * Uses AsyncLocalStorage to ensure async-safety when multiple
796
- * workflows are running concurrently.
797
- */
798
- export function getCurrentWorkflowContext(): WorkflowContext | null {
799
- return workflowContextStorage.getStore() ?? null;
800
- }
801
-
802
- /**
803
- * Check if currently executing inside a workflow
804
- *
805
- * Uses AsyncLocalStorage to ensure async-safety when multiple
806
- * workflows are running concurrently.
807
- */
808
- export function isInWorkflow(): boolean {
809
- return workflowContextStorage.getStore() !== undefined;
810
- }