autotel 4.1.0 → 4.2.1

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 (253) hide show
  1. package/dist/auto.cjs +5 -3
  2. package/dist/auto.cjs.map +1 -1
  3. package/dist/auto.js +3 -3
  4. package/dist/auto.js.map +1 -1
  5. package/dist/chunk-C_NdSu1c.cjs +34 -0
  6. package/dist/correlation-id.cjs +1 -1
  7. package/dist/correlation-id.d.cts.map +1 -1
  8. package/dist/correlation-id.d.ts.map +1 -1
  9. package/dist/correlation-id.js +1 -1
  10. package/dist/decorators.cjs +1 -1
  11. package/dist/decorators.js +1 -1
  12. package/dist/{event-ByBTV9M2.js → event-531asIM6.js} +4 -4
  13. package/dist/{event-ByBTV9M2.js.map → event-531asIM6.js.map} +1 -1
  14. package/dist/{event-BhHREDJk.cjs → event-CcZYwp50.cjs} +4 -4
  15. package/dist/{event-BhHREDJk.cjs.map → event-CcZYwp50.cjs.map} +1 -1
  16. package/dist/event.cjs +1 -1
  17. package/dist/event.js +1 -1
  18. package/dist/{functional-zpzNLhky.cjs → functional-C8B0Qa7o.cjs} +10 -7
  19. package/dist/functional-C8B0Qa7o.cjs.map +1 -0
  20. package/dist/{functional-DtI0u4vx.js → functional-r-AUIRy_.js} +9 -9
  21. package/dist/functional-r-AUIRy_.js.map +1 -0
  22. package/dist/functional.cjs +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 +15 -13
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts.map +1 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +14 -14
  31. package/dist/index.js.map +1 -1
  32. package/dist/{init-D-jnNMix.js → init-BS2JVkrL.js} +2 -2
  33. package/dist/{init-D-jnNMix.js.map → init-BS2JVkrL.js.map} +1 -1
  34. package/dist/{init-BX7AmFRl.cjs → init-BXiuPK6j.cjs} +3 -3
  35. package/dist/{init-BX7AmFRl.cjs.map → init-BXiuPK6j.cjs.map} +1 -1
  36. package/dist/instrumentation.cjs +2 -2
  37. package/dist/instrumentation.js +2 -2
  38. package/dist/logger.cjs +236 -8
  39. package/dist/logger.cjs.map +1 -0
  40. package/dist/messaging.cjs +1 -1
  41. package/dist/messaging.js +1 -1
  42. package/dist/{node-require-DF5QBX6z.cjs → node-require-CZ_PU448.cjs} +6 -4
  43. package/dist/node-require-CZ_PU448.cjs.map +1 -0
  44. package/dist/{node-require-Db1oDpLj.js → node-require-vROmTeJ8.js} +5 -5
  45. package/dist/node-require-vROmTeJ8.js.map +1 -0
  46. package/dist/{operation-context-C-2hmmtP.js → operation-context-CKBoA4Qy.js} +3 -3
  47. package/dist/operation-context-CKBoA4Qy.js.map +1 -0
  48. package/dist/{operation-context-n4_obUwq.cjs → operation-context-D6LDf4W_.cjs} +3 -1
  49. package/dist/operation-context-D6LDf4W_.cjs.map +1 -0
  50. package/dist/register.cjs +3 -1
  51. package/dist/register.cjs.map +1 -1
  52. package/dist/register.js +2 -2
  53. package/dist/register.js.map +1 -1
  54. package/dist/semantic-helpers.cjs +1 -1
  55. package/dist/semantic-helpers.js +1 -1
  56. package/dist/{stable-hash-Cg5cT34Q.js → stable-hash-ChFBIhNt.js} +3 -3
  57. package/dist/stable-hash-ChFBIhNt.js.map +1 -0
  58. package/dist/{stable-hash-BNTMrmdB.cjs → stable-hash-brKISGf1.cjs} +4 -2
  59. package/dist/stable-hash-brKISGf1.cjs.map +1 -0
  60. package/dist/trace-context-Cijqoi6e.d.cts.map +1 -1
  61. package/dist/trace-context-Cijqoi6e.d.ts.map +1 -1
  62. package/dist/trace-helpers.cjs +1 -1
  63. package/dist/trace-helpers.js +1 -1
  64. package/dist/{track-wc0HafS_.js → track-COUuU48p.js} +5 -5
  65. package/dist/track-COUuU48p.js.map +1 -0
  66. package/dist/{track-D59FfpL0.cjs → track-Cb3Q4QmS.cjs} +4 -2
  67. package/dist/track-Cb3Q4QmS.cjs.map +1 -0
  68. package/dist/validate.cjs +1 -1
  69. package/dist/validate.js +1 -1
  70. package/dist/webhook.cjs +1 -1
  71. package/dist/webhook.js +1 -1
  72. package/dist/workflow-distributed.cjs +1 -1
  73. package/dist/workflow-distributed.js +1 -1
  74. package/dist/workflow.cjs +3 -1
  75. package/dist/workflow.cjs.map +1 -1
  76. package/dist/workflow.d.cts.map +1 -1
  77. package/dist/workflow.d.ts.map +1 -1
  78. package/dist/workflow.js +3 -3
  79. package/dist/workflow.js.map +1 -1
  80. package/dist/yaml-config.cjs +233 -4
  81. package/dist/yaml-config.cjs.map +1 -0
  82. package/dist/yaml-config.d.cts.map +1 -1
  83. package/dist/yaml-config.d.ts.map +1 -1
  84. package/dist/yaml-config.js +8 -7
  85. package/dist/yaml-config.js.map +1 -1
  86. package/package.json +1 -2
  87. package/dist/functional-DtI0u4vx.js.map +0 -1
  88. package/dist/functional-zpzNLhky.cjs.map +0 -1
  89. package/dist/logger-thMPLpOG.cjs +0 -487
  90. package/dist/logger-thMPLpOG.cjs.map +0 -1
  91. package/dist/node-require-DF5QBX6z.cjs.map +0 -1
  92. package/dist/node-require-Db1oDpLj.js.map +0 -1
  93. package/dist/operation-context-C-2hmmtP.js.map +0 -1
  94. package/dist/operation-context-n4_obUwq.cjs.map +0 -1
  95. package/dist/stable-hash-BNTMrmdB.cjs.map +0 -1
  96. package/dist/stable-hash-Cg5cT34Q.js.map +0 -1
  97. package/dist/track-D59FfpL0.cjs.map +0 -1
  98. package/dist/track-wc0HafS_.js.map +0 -1
  99. package/dist/yaml-config-Ck2uB0Dp.cjs +0 -273
  100. package/dist/yaml-config-Ck2uB0Dp.cjs.map +0 -1
  101. package/src/attribute-redacting-processor.test.ts +0 -763
  102. package/src/attribute-redacting-processor.ts +0 -621
  103. package/src/attributes/attachers.ts +0 -161
  104. package/src/attributes/builders.ts +0 -529
  105. package/src/attributes/domains.ts +0 -42
  106. package/src/attributes/index.ts +0 -81
  107. package/src/attributes/registry.ts +0 -323
  108. package/src/attributes/types.ts +0 -211
  109. package/src/attributes/utils.ts +0 -64
  110. package/src/attributes/validators.ts +0 -266
  111. package/src/attributes.test.ts +0 -292
  112. package/src/auto.ts +0 -67
  113. package/src/autotel-logger.test.ts +0 -548
  114. package/src/autotel-logger.ts +0 -364
  115. package/src/baggage-span-processor.test.ts +0 -202
  116. package/src/baggage-span-processor.ts +0 -100
  117. package/src/business-baggage.test.ts +0 -500
  118. package/src/business-baggage.ts +0 -669
  119. package/src/circuit-breaker.test.ts +0 -341
  120. package/src/circuit-breaker.ts +0 -184
  121. package/src/config.test.ts +0 -94
  122. package/src/config.ts +0 -172
  123. package/src/correlated-events.test.ts +0 -151
  124. package/src/correlated-events.ts +0 -47
  125. package/src/correlation-id.test.ts +0 -163
  126. package/src/correlation-id.ts +0 -206
  127. package/src/db.test.ts +0 -252
  128. package/src/db.ts +0 -447
  129. package/src/decorators.test.ts +0 -153
  130. package/src/decorators.ts +0 -188
  131. package/src/define-event.test.ts +0 -41
  132. package/src/define-event.ts +0 -58
  133. package/src/devtools.ts +0 -60
  134. package/src/drain-pipeline.test.ts +0 -68
  135. package/src/drain-pipeline.ts +0 -199
  136. package/src/drain-toolkit.test.ts +0 -113
  137. package/src/drain-toolkit.ts +0 -129
  138. package/src/enricher-toolkit.test.ts +0 -67
  139. package/src/enricher-toolkit.ts +0 -79
  140. package/src/enrichers.test.ts +0 -150
  141. package/src/enrichers.ts +0 -145
  142. package/src/env-config.test.ts +0 -323
  143. package/src/env-config.ts +0 -309
  144. package/src/error-catalog.test.ts +0 -133
  145. package/src/error-catalog.ts +0 -262
  146. package/src/event-queue.test.ts +0 -864
  147. package/src/event-queue.ts +0 -699
  148. package/src/event-subscriber.ts +0 -262
  149. package/src/event-testing.ts +0 -197
  150. package/src/event.test.ts +0 -1104
  151. package/src/event.ts +0 -988
  152. package/src/events-config.ts +0 -235
  153. package/src/exporters.ts +0 -165
  154. package/src/filtering-span-processor.test.ts +0 -281
  155. package/src/filtering-span-processor.ts +0 -111
  156. package/src/flatten-attributes.test.ts +0 -76
  157. package/src/flatten-attributes.ts +0 -80
  158. package/src/functional.strict-types.typecheck.ts +0 -53
  159. package/src/functional.test.ts +0 -1464
  160. package/src/functional.ts +0 -2539
  161. package/src/functional.types.test.ts +0 -135
  162. package/src/hook.mjs +0 -15
  163. package/src/http.test.ts +0 -485
  164. package/src/http.ts +0 -424
  165. package/src/index.ts +0 -433
  166. package/src/init-auto-redactor.test.ts +0 -53
  167. package/src/init-redactor.test.ts +0 -8
  168. package/src/init.customization.test.ts +0 -665
  169. package/src/init.integrations.test.ts +0 -399
  170. package/src/init.openllmetry.test.ts +0 -194
  171. package/src/init.protocol.test.ts +0 -215
  172. package/src/init.ts +0 -2439
  173. package/src/instrumentation.test.ts +0 -108
  174. package/src/instrumentation.ts +0 -319
  175. package/src/logger.test.ts +0 -125
  176. package/src/logger.ts +0 -341
  177. package/src/messaging-adapters.test.ts +0 -595
  178. package/src/messaging-adapters.ts +0 -583
  179. package/src/messaging-testing.test.ts +0 -573
  180. package/src/messaging-testing.ts +0 -935
  181. package/src/messaging.test.ts +0 -1646
  182. package/src/messaging.ts +0 -2245
  183. package/src/metric-helpers.ts +0 -47
  184. package/src/metric-testing.ts +0 -197
  185. package/src/metric.ts +0 -446
  186. package/src/metrics.test.ts +0 -241
  187. package/src/node-require.ts +0 -123
  188. package/src/operation-context.ts +0 -93
  189. package/src/parse-error.test.ts +0 -73
  190. package/src/parse-error.ts +0 -112
  191. package/src/posthog-logs.test.ts +0 -115
  192. package/src/posthog-logs.ts +0 -77
  193. package/src/pretty-console-exporter.test.ts +0 -545
  194. package/src/pretty-console-exporter.ts +0 -413
  195. package/src/pretty-log-formatter.test.ts +0 -123
  196. package/src/pretty-log-formatter.ts +0 -210
  197. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  198. package/src/processors/canonical-log-line-processor.ts +0 -396
  199. package/src/processors.ts +0 -152
  200. package/src/rate-limiter.test.ts +0 -199
  201. package/src/rate-limiter.ts +0 -98
  202. package/src/redact-values.test.ts +0 -90
  203. package/src/redact-values.ts +0 -34
  204. package/src/register.ts +0 -37
  205. package/src/request-logger.test.ts +0 -545
  206. package/src/request-logger.ts +0 -342
  207. package/src/sampling.test.ts +0 -1060
  208. package/src/sampling.ts +0 -737
  209. package/src/security-schema.test.ts +0 -45
  210. package/src/security-schema.ts +0 -107
  211. package/src/semantic-conventions.ts +0 -15
  212. package/src/semantic-helpers.test.ts +0 -226
  213. package/src/semantic-helpers.ts +0 -438
  214. package/src/shutdown.test.ts +0 -364
  215. package/src/shutdown.ts +0 -246
  216. package/src/span-name-normalizer.test.ts +0 -377
  217. package/src/span-name-normalizer.ts +0 -213
  218. package/src/stable-hash.ts +0 -27
  219. package/src/structured-error.test.ts +0 -191
  220. package/src/structured-error.ts +0 -157
  221. package/src/stub.integration.test.ts +0 -361
  222. package/src/tail-sampling-processor.test.ts +0 -230
  223. package/src/tail-sampling-processor.ts +0 -55
  224. package/src/test-span-collector.test.ts +0 -234
  225. package/src/test-span-collector.ts +0 -150
  226. package/src/testing.ts +0 -705
  227. package/src/trace-context.test.ts +0 -73
  228. package/src/trace-context.ts +0 -567
  229. package/src/trace-helpers.new.test.ts +0 -278
  230. package/src/trace-helpers.test.ts +0 -290
  231. package/src/trace-helpers.ts +0 -710
  232. package/src/trace-hybrid.test.ts +0 -42
  233. package/src/trace-hybrid.ts +0 -37
  234. package/src/tracer-provider.test.ts +0 -183
  235. package/src/tracer-provider.ts +0 -266
  236. package/src/track.test.ts +0 -154
  237. package/src/track.ts +0 -216
  238. package/src/validate.test.ts +0 -287
  239. package/src/validate.ts +0 -307
  240. package/src/validation-attributes.ts +0 -43
  241. package/src/validation.test.ts +0 -330
  242. package/src/validation.ts +0 -246
  243. package/src/variable-name-inference.test.ts +0 -178
  244. package/src/variable-name-inference.ts +0 -242
  245. package/src/webhook.test.ts +0 -649
  246. package/src/webhook.ts +0 -637
  247. package/src/workflow-distributed.test.ts +0 -786
  248. package/src/workflow-distributed.ts +0 -916
  249. package/src/workflow.async-safety.integration.test.ts +0 -345
  250. package/src/workflow.test.ts +0 -647
  251. package/src/workflow.ts +0 -810
  252. package/src/yaml-config.test.ts +0 -373
  253. package/src/yaml-config.ts +0 -351
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
- }