autotel 4.1.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 (154) hide show
  1. package/package.json +1 -2
  2. package/src/attribute-redacting-processor.test.ts +0 -763
  3. package/src/attribute-redacting-processor.ts +0 -621
  4. package/src/attributes/attachers.ts +0 -161
  5. package/src/attributes/builders.ts +0 -529
  6. package/src/attributes/domains.ts +0 -42
  7. package/src/attributes/index.ts +0 -81
  8. package/src/attributes/registry.ts +0 -323
  9. package/src/attributes/types.ts +0 -211
  10. package/src/attributes/utils.ts +0 -64
  11. package/src/attributes/validators.ts +0 -266
  12. package/src/attributes.test.ts +0 -292
  13. package/src/auto.ts +0 -67
  14. package/src/autotel-logger.test.ts +0 -548
  15. package/src/autotel-logger.ts +0 -364
  16. package/src/baggage-span-processor.test.ts +0 -202
  17. package/src/baggage-span-processor.ts +0 -100
  18. package/src/business-baggage.test.ts +0 -500
  19. package/src/business-baggage.ts +0 -669
  20. package/src/circuit-breaker.test.ts +0 -341
  21. package/src/circuit-breaker.ts +0 -184
  22. package/src/config.test.ts +0 -94
  23. package/src/config.ts +0 -172
  24. package/src/correlated-events.test.ts +0 -151
  25. package/src/correlated-events.ts +0 -47
  26. package/src/correlation-id.test.ts +0 -163
  27. package/src/correlation-id.ts +0 -206
  28. package/src/db.test.ts +0 -252
  29. package/src/db.ts +0 -447
  30. package/src/decorators.test.ts +0 -153
  31. package/src/decorators.ts +0 -188
  32. package/src/define-event.test.ts +0 -41
  33. package/src/define-event.ts +0 -58
  34. package/src/devtools.ts +0 -60
  35. package/src/drain-pipeline.test.ts +0 -68
  36. package/src/drain-pipeline.ts +0 -199
  37. package/src/drain-toolkit.test.ts +0 -113
  38. package/src/drain-toolkit.ts +0 -129
  39. package/src/enricher-toolkit.test.ts +0 -67
  40. package/src/enricher-toolkit.ts +0 -79
  41. package/src/enrichers.test.ts +0 -150
  42. package/src/enrichers.ts +0 -145
  43. package/src/env-config.test.ts +0 -323
  44. package/src/env-config.ts +0 -309
  45. package/src/error-catalog.test.ts +0 -133
  46. package/src/error-catalog.ts +0 -262
  47. package/src/event-queue.test.ts +0 -864
  48. package/src/event-queue.ts +0 -699
  49. package/src/event-subscriber.ts +0 -262
  50. package/src/event-testing.ts +0 -197
  51. package/src/event.test.ts +0 -1104
  52. package/src/event.ts +0 -988
  53. package/src/events-config.ts +0 -235
  54. package/src/exporters.ts +0 -165
  55. package/src/filtering-span-processor.test.ts +0 -281
  56. package/src/filtering-span-processor.ts +0 -111
  57. package/src/flatten-attributes.test.ts +0 -76
  58. package/src/flatten-attributes.ts +0 -80
  59. package/src/functional.strict-types.typecheck.ts +0 -53
  60. package/src/functional.test.ts +0 -1464
  61. package/src/functional.ts +0 -2539
  62. package/src/functional.types.test.ts +0 -135
  63. package/src/hook.mjs +0 -15
  64. package/src/http.test.ts +0 -485
  65. package/src/http.ts +0 -424
  66. package/src/index.ts +0 -433
  67. package/src/init-auto-redactor.test.ts +0 -53
  68. package/src/init-redactor.test.ts +0 -8
  69. package/src/init.customization.test.ts +0 -665
  70. package/src/init.integrations.test.ts +0 -399
  71. package/src/init.openllmetry.test.ts +0 -194
  72. package/src/init.protocol.test.ts +0 -215
  73. package/src/init.ts +0 -2439
  74. package/src/instrumentation.test.ts +0 -108
  75. package/src/instrumentation.ts +0 -319
  76. package/src/logger.test.ts +0 -125
  77. package/src/logger.ts +0 -341
  78. package/src/messaging-adapters.test.ts +0 -595
  79. package/src/messaging-adapters.ts +0 -583
  80. package/src/messaging-testing.test.ts +0 -573
  81. package/src/messaging-testing.ts +0 -935
  82. package/src/messaging.test.ts +0 -1646
  83. package/src/messaging.ts +0 -2245
  84. package/src/metric-helpers.ts +0 -47
  85. package/src/metric-testing.ts +0 -197
  86. package/src/metric.ts +0 -446
  87. package/src/metrics.test.ts +0 -241
  88. package/src/node-require.ts +0 -123
  89. package/src/operation-context.ts +0 -93
  90. package/src/parse-error.test.ts +0 -73
  91. package/src/parse-error.ts +0 -112
  92. package/src/posthog-logs.test.ts +0 -115
  93. package/src/posthog-logs.ts +0 -77
  94. package/src/pretty-console-exporter.test.ts +0 -545
  95. package/src/pretty-console-exporter.ts +0 -413
  96. package/src/pretty-log-formatter.test.ts +0 -123
  97. package/src/pretty-log-formatter.ts +0 -210
  98. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  99. package/src/processors/canonical-log-line-processor.ts +0 -396
  100. package/src/processors.ts +0 -152
  101. package/src/rate-limiter.test.ts +0 -199
  102. package/src/rate-limiter.ts +0 -98
  103. package/src/redact-values.test.ts +0 -90
  104. package/src/redact-values.ts +0 -34
  105. package/src/register.ts +0 -37
  106. package/src/request-logger.test.ts +0 -545
  107. package/src/request-logger.ts +0 -342
  108. package/src/sampling.test.ts +0 -1060
  109. package/src/sampling.ts +0 -737
  110. package/src/security-schema.test.ts +0 -45
  111. package/src/security-schema.ts +0 -107
  112. package/src/semantic-conventions.ts +0 -15
  113. package/src/semantic-helpers.test.ts +0 -226
  114. package/src/semantic-helpers.ts +0 -438
  115. package/src/shutdown.test.ts +0 -364
  116. package/src/shutdown.ts +0 -246
  117. package/src/span-name-normalizer.test.ts +0 -377
  118. package/src/span-name-normalizer.ts +0 -213
  119. package/src/stable-hash.ts +0 -27
  120. package/src/structured-error.test.ts +0 -191
  121. package/src/structured-error.ts +0 -157
  122. package/src/stub.integration.test.ts +0 -361
  123. package/src/tail-sampling-processor.test.ts +0 -230
  124. package/src/tail-sampling-processor.ts +0 -55
  125. package/src/test-span-collector.test.ts +0 -234
  126. package/src/test-span-collector.ts +0 -150
  127. package/src/testing.ts +0 -705
  128. package/src/trace-context.test.ts +0 -73
  129. package/src/trace-context.ts +0 -567
  130. package/src/trace-helpers.new.test.ts +0 -278
  131. package/src/trace-helpers.test.ts +0 -290
  132. package/src/trace-helpers.ts +0 -710
  133. package/src/trace-hybrid.test.ts +0 -42
  134. package/src/trace-hybrid.ts +0 -37
  135. package/src/tracer-provider.test.ts +0 -183
  136. package/src/tracer-provider.ts +0 -266
  137. package/src/track.test.ts +0 -154
  138. package/src/track.ts +0 -216
  139. package/src/validate.test.ts +0 -287
  140. package/src/validate.ts +0 -307
  141. package/src/validation-attributes.ts +0 -43
  142. package/src/validation.test.ts +0 -330
  143. package/src/validation.ts +0 -246
  144. package/src/variable-name-inference.test.ts +0 -178
  145. package/src/variable-name-inference.ts +0 -242
  146. package/src/webhook.test.ts +0 -649
  147. package/src/webhook.ts +0 -637
  148. package/src/workflow-distributed.test.ts +0 -786
  149. package/src/workflow-distributed.ts +0 -916
  150. package/src/workflow.async-safety.integration.test.ts +0 -345
  151. package/src/workflow.test.ts +0 -647
  152. package/src/workflow.ts +0 -810
  153. package/src/yaml-config.test.ts +0 -373
  154. 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
- }