autotel 2.26.3 → 3.0.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.
- package/README.md +29 -19
- package/dist/attributes.d.cts +3 -3
- package/dist/attributes.d.ts +3 -3
- package/dist/business-baggage.d.cts +1 -1
- package/dist/business-baggage.d.ts +1 -1
- package/dist/{chunk-YN7USLHW.js → chunk-3QMFLJHJ.js} +11 -10
- package/dist/chunk-3QMFLJHJ.js.map +1 -0
- package/dist/{chunk-BJ2XPN77.js → chunk-4DAG3RFS.js} +4 -4
- package/dist/{chunk-BJ2XPN77.js.map → chunk-4DAG3RFS.js.map} +1 -1
- package/dist/chunk-4P6ZOARG.cjs +33 -0
- package/dist/chunk-4P6ZOARG.cjs.map +1 -0
- package/dist/{chunk-U54FTVFH.js → chunk-7HNQYHK4.js} +3 -3
- package/dist/{chunk-U54FTVFH.js.map → chunk-7HNQYHK4.js.map} +1 -1
- package/dist/chunk-CJ4PD2TZ.cjs +1207 -0
- package/dist/chunk-CJ4PD2TZ.cjs.map +1 -0
- package/dist/{chunk-HPUGKUMZ.js → chunk-DAAJLUTO.js} +13 -640
- package/dist/chunk-DAAJLUTO.js.map +1 -0
- package/dist/{chunk-B3ZHLLMP.js → chunk-DSMSIVTG.js} +2 -2
- package/dist/chunk-DSMSIVTG.js.map +1 -0
- package/dist/{chunk-6YGUN7IY.cjs → chunk-DWOBIBLY.cjs} +18 -17
- package/dist/chunk-DWOBIBLY.cjs.map +1 -0
- package/dist/{chunk-QC5MNKVF.js → chunk-IUDXKLS4.js} +13 -12
- package/dist/chunk-IUDXKLS4.js.map +1 -0
- package/dist/{chunk-OBWXM4NN.cjs → chunk-KHGA4OST.cjs} +15 -14
- package/dist/chunk-KHGA4OST.cjs.map +1 -0
- package/dist/chunk-KIL5CUN6.js +31 -0
- package/dist/chunk-KIL5CUN6.js.map +1 -0
- package/dist/{chunk-YEVCD6DR.cjs → chunk-L7JDUDJD.cjs} +7 -7
- package/dist/{chunk-YEVCD6DR.cjs.map → chunk-L7JDUDJD.cjs.map} +1 -1
- package/dist/{chunk-UTZR7P7E.cjs → chunk-MOK3E54E.cjs} +29 -659
- package/dist/chunk-MOK3E54E.cjs.map +1 -0
- package/dist/{chunk-GML3FBOT.cjs → chunk-NCSMD3TK.cjs} +2 -2
- package/dist/chunk-NCSMD3TK.cjs.map +1 -0
- package/dist/chunk-QG3U5ONP.js +1183 -0
- package/dist/chunk-QG3U5ONP.js.map +1 -0
- package/dist/chunk-SEO6NAQT.js +14 -0
- package/dist/chunk-SEO6NAQT.js.map +1 -0
- package/dist/chunk-VQTCQKHQ.cjs +17 -0
- package/dist/chunk-VQTCQKHQ.cjs.map +1 -0
- package/dist/{chunk-WZOKY3PW.cjs → chunk-ZSABTI3C.cjs} +8 -8
- package/dist/{chunk-WZOKY3PW.cjs.map → chunk-ZSABTI3C.cjs.map} +1 -1
- package/dist/correlation-id.cjs +22 -10
- package/dist/correlation-id.js +14 -2
- package/dist/decorators.cjs +5 -6
- package/dist/decorators.cjs.map +1 -1
- package/dist/decorators.d.cts +1 -1
- package/dist/decorators.d.ts +1 -1
- package/dist/decorators.js +4 -5
- package/dist/decorators.js.map +1 -1
- package/dist/event.cjs +6 -7
- package/dist/event.js +3 -4
- package/dist/functional.cjs +11 -12
- package/dist/functional.d.cts +1 -1
- package/dist/functional.d.ts +1 -1
- package/dist/functional.js +4 -5
- package/dist/http.cjs +13 -2
- package/dist/http.cjs.map +1 -1
- package/dist/http.js +12 -1
- package/dist/http.js.map +1 -1
- package/dist/index.cjs +134 -243
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +23 -8
- package/dist/index.d.ts +23 -8
- package/dist/index.js +52 -176
- package/dist/index.js.map +1 -1
- package/dist/messaging-adapters.d.cts +1 -1
- package/dist/messaging-adapters.d.ts +1 -1
- package/dist/messaging-testing.d.cts +1 -1
- package/dist/messaging-testing.d.ts +1 -1
- package/dist/messaging.cjs +9 -9
- package/dist/messaging.d.cts +1 -1
- package/dist/messaging.d.ts +1 -1
- package/dist/messaging.js +6 -6
- package/dist/semantic-helpers.cjs +9 -10
- package/dist/semantic-helpers.d.cts +1 -1
- package/dist/semantic-helpers.d.ts +1 -1
- package/dist/semantic-helpers.js +5 -6
- package/dist/{trace-context-t5X1AP-e.d.ts → trace-context-DbGKd1Rn.d.cts} +18 -5
- package/dist/{trace-context-t5X1AP-e.d.cts → trace-context-DbGKd1Rn.d.ts} +18 -5
- package/dist/trace-helpers.cjs +13 -13
- package/dist/trace-helpers.d.cts +2 -2
- package/dist/trace-helpers.d.ts +2 -2
- package/dist/trace-helpers.js +1 -1
- package/dist/{utils-CbUkl8r1.d.cts → utils-BahBCFtJ.d.cts} +1 -1
- package/dist/{utils-Buel3cj0.d.ts → utils-CLKwaUlG.d.ts} +1 -1
- package/dist/webhook.cjs +19 -10
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.d.cts +1 -1
- package/dist/webhook.d.ts +1 -1
- package/dist/webhook.js +18 -9
- package/dist/webhook.js.map +1 -1
- package/dist/workflow-distributed.cjs +23 -19
- package/dist/workflow-distributed.cjs.map +1 -1
- package/dist/workflow-distributed.d.cts +1 -1
- package/dist/workflow-distributed.d.ts +1 -1
- package/dist/workflow-distributed.js +21 -17
- package/dist/workflow-distributed.js.map +1 -1
- package/dist/workflow.cjs +10 -10
- package/dist/workflow.d.cts +1 -1
- package/dist/workflow.d.ts +1 -1
- package/dist/workflow.js +6 -6
- package/package.json +1 -1
- package/skills/autotel-core/SKILL.md +2 -0
- package/skills/autotel-events/SKILL.md +2 -0
- package/skills/autotel-frameworks/SKILL.md +2 -0
- package/skills/autotel-instrumentation/SKILL.md +2 -0
- package/skills/autotel-request-logging/SKILL.md +2 -0
- package/skills/autotel-structured-errors/SKILL.md +2 -0
- package/src/correlated-events.test.ts +151 -0
- package/src/correlated-events.ts +47 -0
- package/src/functional.ts +2 -0
- package/src/gen-ai-events.ts +14 -5
- package/src/index.ts +20 -4
- package/src/messaging.ts +10 -9
- package/src/request-logger.ts +4 -3
- package/src/structured-error.test.ts +83 -1
- package/src/structured-error.ts +9 -2
- package/src/trace-context.ts +39 -11
- package/src/trace-helpers.ts +2 -2
- package/src/trace-hybrid.test.ts +42 -0
- package/src/trace-hybrid.ts +37 -0
- package/src/webhook.ts +16 -7
- package/src/workflow-distributed.ts +18 -13
- package/src/workflow.ts +7 -6
- package/dist/chunk-6YGUN7IY.cjs.map +0 -1
- package/dist/chunk-B3ZHLLMP.js.map +0 -1
- package/dist/chunk-BBBWDIYQ.js +0 -211
- package/dist/chunk-BBBWDIYQ.js.map +0 -1
- package/dist/chunk-D5LMF53P.cjs +0 -150
- package/dist/chunk-D5LMF53P.cjs.map +0 -1
- package/dist/chunk-GML3FBOT.cjs.map +0 -1
- package/dist/chunk-HPUGKUMZ.js.map +0 -1
- package/dist/chunk-HZ3FYBJG.cjs +0 -217
- package/dist/chunk-HZ3FYBJG.cjs.map +0 -1
- package/dist/chunk-JSNUWSBH.cjs +0 -62
- package/dist/chunk-JSNUWSBH.cjs.map +0 -1
- package/dist/chunk-OBWXM4NN.cjs.map +0 -1
- package/dist/chunk-QC5MNKVF.js.map +0 -1
- package/dist/chunk-S4OFEXLA.js +0 -53
- package/dist/chunk-S4OFEXLA.js.map +0 -1
- package/dist/chunk-UTZR7P7E.cjs.map +0 -1
- package/dist/chunk-WD4RP6IV.js +0 -146
- package/dist/chunk-WD4RP6IV.js.map +0 -1
- package/dist/chunk-YN7USLHW.js.map +0 -1
package/dist/webhook.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webhook.ts"],"names":["otelTrace"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+PO,IAAM,4BAAN,MAA6D;AAAA,EAIlE,WAAA,CACU,OAAA,GAGJ,EAAC,EACL;AAJQ,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAMR,IAAA,MAAM,SAAA,GAAY,QAAQ,iBAAA,IAAqB,GAAA;A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A,UACvB,QAAQ,aAAA,CAAc,MAAA;AAAA,UACtB,YAAY,aAAA,CAAc,UAAA;AAAA,UAC1B,QAAA,EAAU;AAAA,SACZ;AAAA,QACA,UAAA,EAAY;AAAA,UACV,WAAA,EAAa,aAAA;AAAA,UACb,yBAAyB,aAAA,CAAc,QAAA;AAAA,UACvC,GAAI,cAAc,QAAA,IAAY;AAAA,YAC5B,0BAAA,EAA4B;AAAA;AAC9B;AACF,OACF;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,OAAO,cAAA,EAA0C;AACrD,MAAA,MAAM,OAAA,GAAU,UAAU,cAAc,CAAA;AACxC,MAAA,MAAM,OAAA,GAAU,MAAM,KAAA,CAAM,IAAA,CAAK,OAAO,CAAA;AACxC,MAAA,OAAO,OAAA,KAAY,IAAA;AAAA,IACrB;AAAA,GACF;AAEA,EAAA,OAAO,UAAA;AACT;AAkBO,SAAS,wBAAwB,KAAA,EAAoC;AAC1E,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,MAAM,CAAA,CAAE,KAAK,GAAG,CAAA;AACnC;AAQO,SAAS,cAAc,aAAA,EAAgD;AAC5E,EAAA,OAAO;AAAA,IACL,SAAS,aAAA,CAAc,OAAA;AAAA,IACvB,QAAQ,aAAA,CAAc,MAAA;AAAA,IACtB,YAAY,aAAA,CAAc,UAAA;AAAA,IAC1B,QAAA,EAAU;AAAA,GACZ;AACF","file":"webhook.js","sourcesContent":["/**\n * Webhook and callback tracing with the \"Parking Lot\" pattern\n *\n * When initiating async operations that return hours/days later (webhooks,\n * payment callbacks, human approvals), you can't keep a span open. This module\n * provides utilities to \"park\" trace context and retrieve it when callbacks arrive.\n *\n * @example Stripe payment webhook\n * ```typescript\n * import { createParkingLot, InMemoryTraceContextStore } from 'autotel/webhook';\n *\n * const parkingLot = createParkingLot({\n * store: new InMemoryTraceContextStore(),\n * defaultTTLMs: 24 * 60 * 60 * 1000, // 24 hours\n * });\n *\n * // When initiating payment\n * export const initiatePayment = trace(ctx => async (orderId: string) => {\n * await parkingLot.park(`payment:${orderId}`, { orderId });\n * await stripeClient.createPaymentIntent({ metadata: { orderId } });\n * });\n *\n * // When Stripe webhook arrives (hours later)\n * export const handleStripeWebhook = parkingLot.traceCallback({\n * name: 'stripe.webhook.payment_intent.succeeded',\n * correlationKeyFrom: (event) => `payment:${event.data.object.metadata.orderId}`,\n * })(ctx => async (event: Stripe.Event) => {\n * // ctx.parkedContext contains the original trace context\n * // ctx.elapsedMs shows time since payment was initiated\n * await fulfillOrder(event.data.object);\n * });\n * ```\n *\n * @module\n */\n\nimport { SpanKind, trace as otelTrace } from '@opentelemetry/api';\nimport type { SpanContext, Link } from '@opentelemetry/api';\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Stored trace context for parking lot pattern\n */\nexport interface StoredTraceContext {\n /** Trace ID from the original span */\n traceId: string;\n\n /** Span ID from the original span */\n spanId: string;\n\n /** Trace flags (sampling decision) */\n traceFlags: number;\n\n /** When the context was parked */\n parkedAt: number;\n\n /** Optional TTL in milliseconds */\n ttlMs?: number;\n\n /** User-provided metadata */\n metadata?: Record<string, string>;\n}\n\n/**\n * Interface for trace context storage backends\n *\n * Implement this interface to use different storage backends (Redis, DynamoDB, etc.)\n */\nexport interface TraceContextStore {\n /**\n * Save trace context with a correlation key\n *\n * @param key - Unique correlation key (e.g., \"payment:order-123\")\n * @param context - The trace context to store\n */\n save(key: string, context: StoredTraceContext): Promise<void>;\n\n /**\n * Load trace context by correlation key\n *\n * @param key - The correlation key used when parking\n * @returns The stored context, or null if not found/expired\n */\n load(key: string): Promise<StoredTraceContext | null>;\n\n /**\n * Delete trace context by correlation key\n *\n * @param key - The correlation key to delete\n */\n delete(key: string): Promise<void>;\n}\n\n/**\n * Configuration for creating a parking lot\n */\nexport interface ParkingLotConfig {\n /** Storage backend for parked contexts */\n store: TraceContextStore;\n\n /** Default TTL in milliseconds (default: 24 hours) */\n defaultTTLMs?: number;\n\n /** Prefix for all correlation keys (default: \"parkingLot:\") */\n keyPrefix?: string;\n\n /** Whether to auto-delete after retrieval (default: true) */\n autoDeleteOnRetrieve?: boolean;\n\n /** Callback when context expires or is not found */\n onMiss?: (correlationKey: string) => void;\n}\n\n/**\n * Configuration for traceCallback wrapper\n */\nexport interface CallbackConfig {\n /** Span name for the callback handler */\n name: string;\n\n /**\n * Extract correlation key from callback arguments\n *\n * @example\n * ```typescript\n * correlationKeyFrom: (event) => `payment:${event.data.orderId}`\n * ```\n */\n correlationKeyFrom: (args: unknown[]) => string;\n\n /** Additional span attributes */\n attributes?: Record<string, string | number | boolean>;\n\n /** Whether to fail if parked context is not found (default: false) */\n requireParkedContext?: boolean;\n}\n\n/**\n * Extended context for callback handlers\n */\nexport interface CallbackContext extends TraceContext {\n /** The retrieved parked context, if found */\n parkedContext: StoredTraceContext | null;\n\n /** Time elapsed since context was parked (ms), or null if not found */\n elapsedMs: number | null;\n\n /** The correlation key used for retrieval */\n correlationKey: string;\n}\n\n/**\n * The parking lot instance\n */\nexport interface ParkingLot {\n /**\n * Park current trace context before initiating async operation\n *\n * Call this before sending a webhook, initiating a payment, or starting\n * any operation that will complete via callback.\n *\n * @param correlationKey - Unique key to retrieve context later (e.g., \"payment:order-123\")\n * @param metadata - Optional metadata to store with the context\n * @returns The correlation key (with prefix applied)\n *\n * @example\n * ```typescript\n * await parkingLot.park(`payment:${orderId}`, {\n * customerId: customer.id,\n * amount: payment.amount.toString(),\n * });\n * ```\n */\n park(\n correlationKey: string,\n metadata?: Record<string, string>,\n ): Promise<string>;\n\n /**\n * Retrieve parked context when callback arrives\n *\n * @param correlationKey - The key used when parking\n * @returns The stored context, or null if not found/expired\n */\n retrieve(correlationKey: string): Promise<StoredTraceContext | null>;\n\n /**\n * Wrap a callback handler with automatic context retrieval and linking\n *\n * Creates a traced function that:\n * 1. Extracts correlation key from arguments\n * 2. Retrieves parked context from storage\n * 3. Creates a span link to the original trace\n * 4. Provides elapsed time since parking\n *\n * @param config - Callback configuration\n * @returns Factory function for the callback handler\n *\n * @example\n * ```typescript\n * export const handleWebhook = parkingLot.traceCallback({\n * name: 'webhook.payment.completed',\n * correlationKeyFrom: (args) => `payment:${args[0].orderId}`,\n * })(ctx => async (event) => {\n * console.log(`Payment completed after ${ctx.elapsedMs}ms`);\n * await processPayment(event);\n * });\n * ```\n */\n traceCallback<TArgs extends unknown[], TReturn>(\n config: CallbackConfig,\n ): (\n fnFactory: (ctx: CallbackContext) => (...args: TArgs) => Promise<TReturn>,\n ) => (...args: TArgs) => Promise<TReturn>;\n\n /**\n * Manually create a span link from stored context\n *\n * Useful when you need more control over span creation.\n *\n * @param storedContext - The stored trace context\n * @returns A span link that can be added to a span\n */\n createLink(storedContext: StoredTraceContext): Link;\n\n /**\n * Check if a parked context exists (without retrieving/deleting it)\n *\n * @param correlationKey - The key to check\n * @returns True if context exists and hasn't expired\n */\n exists(correlationKey: string): Promise<boolean>;\n}\n\n// ============================================================================\n// In-Memory Store (for testing and development)\n// ============================================================================\n\n/**\n * In-memory trace context store\n *\n * Useful for testing and development. For production, use a persistent\n * store like Redis or DynamoDB.\n *\n * @example\n * ```typescript\n * const store = new InMemoryTraceContextStore();\n * const parkingLot = createParkingLot({ store });\n * ```\n */\nexport class InMemoryTraceContextStore implements TraceContextStore {\n private store = new Map<string, StoredTraceContext>();\n private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n\n constructor(\n private options: {\n /** Cleanup interval in ms (default: 60000) */\n cleanupIntervalMs?: number;\n } = {},\n ) {\n // Start periodic cleanup of expired entries\n const cleanupMs = options.cleanupIntervalMs ?? 60_000;\n if (cleanupMs > 0) {\n this.cleanupInterval = setInterval(() => this.cleanup(), cleanupMs);\n // Don't prevent process exit\n if (this.cleanupInterval.unref) {\n this.cleanupInterval.unref();\n }\n }\n }\n\n async save(key: string, context: StoredTraceContext): Promise<void> {\n this.store.set(key, context);\n }\n\n async load(key: string): Promise<StoredTraceContext | null> {\n const context = this.store.get(key);\n if (!context) {\n return null;\n }\n\n // Check TTL expiration\n if (context.ttlMs) {\n const age = Date.now() - context.parkedAt;\n if (age > context.ttlMs) {\n this.store.delete(key);\n return null;\n }\n }\n\n return context;\n }\n\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n /**\n * Get number of stored contexts (for testing)\n */\n get size(): number {\n return this.store.size;\n }\n\n /**\n * Clear all stored contexts (for testing)\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Stop the cleanup interval\n */\n destroy(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n }\n\n private cleanup(): void {\n const now = Date.now();\n for (const [key, context] of this.store.entries()) {\n if (context.ttlMs) {\n const age = now - context.parkedAt;\n if (age > context.ttlMs) {\n this.store.delete(key);\n }\n }\n }\n }\n}\n\n// ============================================================================\n// Parking Lot Factory\n// ============================================================================\n\n/**\n * Create a parking lot for trace context storage and retrieval\n *\n * @param config - Parking lot configuration\n * @returns A parking lot instance\n *\n * @example Basic usage\n * ```typescript\n * const parkingLot = createParkingLot({\n * store: new InMemoryTraceContextStore(),\n * defaultTTLMs: 24 * 60 * 60 * 1000, // 24 hours\n * });\n * ```\n *\n * @example With Redis store\n * ```typescript\n * class RedisTraceContextStore implements TraceContextStore {\n * constructor(private redis: Redis) {}\n *\n * async save(key: string, context: StoredTraceContext) {\n * const ttlSeconds = context.ttlMs ? Math.ceil(context.ttlMs / 1000) : 86400;\n * await this.redis.setex(key, ttlSeconds, JSON.stringify(context));\n * }\n *\n * async load(key: string) {\n * const data = await this.redis.get(key);\n * return data ? JSON.parse(data) : null;\n * }\n *\n * async delete(key: string) {\n * await this.redis.del(key);\n * }\n * }\n *\n * const parkingLot = createParkingLot({\n * store: new RedisTraceContextStore(redis),\n * });\n * ```\n */\nexport function createParkingLot(config: ParkingLotConfig): ParkingLot {\n const {\n store,\n defaultTTLMs = 24 * 60 * 60 * 1000, // 24 hours\n keyPrefix = 'parkingLot:',\n autoDeleteOnRetrieve = true,\n onMiss,\n } = config;\n\n /**\n * Get current span context from active context\n */\n function getCurrentSpanContext(): SpanContext | null {\n const activeSpan = otelTrace.getActiveSpan();\n if (!activeSpan) {\n return null;\n }\n return activeSpan.spanContext();\n }\n\n /**\n * Apply key prefix\n */\n function prefixKey(key: string): string {\n return `${keyPrefix}${key}`;\n }\n\n const parkingLot: ParkingLot = {\n async park(\n correlationKey: string,\n metadata?: Record<string, string>,\n ): Promise<string> {\n const spanContext = getCurrentSpanContext();\n const fullKey = prefixKey(correlationKey);\n\n const storedContext: StoredTraceContext = {\n traceId: spanContext?.traceId ?? '',\n spanId: spanContext?.spanId ?? '',\n traceFlags: spanContext?.traceFlags ?? 0,\n parkedAt: Date.now(),\n ttlMs: defaultTTLMs,\n metadata,\n };\n\n await store.save(fullKey, storedContext);\n\n // Add event to current span\n const activeSpan = otelTrace.getActiveSpan();\n if (activeSpan) {\n activeSpan.addEvent('trace_context_parked', {\n 'parking_lot.correlation_key': correlationKey,\n 'parking_lot.ttl_ms': defaultTTLMs,\n ...(metadata &&\n Object.fromEntries(\n Object.entries(metadata).map(([k, v]) => [\n `parking_lot.metadata.${k}`,\n v,\n ]),\n )),\n });\n }\n\n // Return the unprefixed key so callers can use the same key for retrieve()\n return correlationKey;\n },\n\n async retrieve(correlationKey: string): Promise<StoredTraceContext | null> {\n const fullKey = prefixKey(correlationKey);\n const storedContext = await store.load(fullKey);\n\n if (!storedContext) {\n onMiss?.(correlationKey);\n return null;\n }\n\n if (autoDeleteOnRetrieve) {\n await store.delete(fullKey);\n }\n\n return storedContext;\n },\n\n traceCallback<TArgs extends unknown[], TReturn>(\n callbackConfig: CallbackConfig,\n ): (\n fnFactory: (ctx: CallbackContext) => (...args: TArgs) => Promise<TReturn>,\n ) => (...args: TArgs) => Promise<TReturn> {\n return (\n fnFactory: (\n ctx: CallbackContext,\n ) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>(\n {\n name: callbackConfig.name,\n spanKind: SpanKind.SERVER,\n },\n (baseCtx) => {\n return async (...args: TArgs) => {\n // Extract correlation key from arguments\n const correlationKey = callbackConfig.correlationKeyFrom(args);\n\n // Retrieve parked context\n const parkedContext = await parkingLot.retrieve(correlationKey);\n\n // Calculate elapsed time\n const elapsedMs = parkedContext\n ? Date.now() - parkedContext.parkedAt\n : null;\n\n // Set span attributes\n baseCtx.setAttribute(\n 'parking_lot.correlation_key',\n correlationKey,\n );\n\n if (parkedContext) {\n baseCtx.setAttribute('parking_lot.elapsed_ms', elapsedMs!);\n baseCtx.setAttribute(\n 'parking_lot.original_trace_id',\n parkedContext.traceId,\n );\n baseCtx.setAttribute(\n 'parking_lot.original_span_id',\n parkedContext.spanId,\n );\n\n // Add metadata as attributes\n if (parkedContext.metadata) {\n for (const [key, value] of Object.entries(\n parkedContext.metadata,\n )) {\n baseCtx.setAttribute(`parking_lot.metadata.${key}`, value);\n }\n }\n\n // Create span link to original trace\n const link = parkingLot.createLink(parkedContext);\n baseCtx.addLinks([link]);\n\n // Add event\n baseCtx.addEvent('parked_context_retrieved', {\n 'parking_lot.correlation_key': correlationKey,\n 'parking_lot.elapsed_ms': elapsedMs!,\n 'parking_lot.original_trace_id': parkedContext.traceId,\n });\n } else {\n baseCtx.setAttribute('parking_lot.context_found', false);\n\n if (callbackConfig.requireParkedContext) {\n const error = new Error(\n `Required parked context not found for key: ${correlationKey}`,\n );\n baseCtx.recordException(error);\n throw error;\n }\n }\n\n // Apply custom attributes\n if (callbackConfig.attributes) {\n for (const [key, value] of Object.entries(\n callbackConfig.attributes,\n )) {\n baseCtx.setAttribute(key, value);\n }\n }\n\n // Create extended context\n const callbackCtx: CallbackContext = {\n ...baseCtx,\n parkedContext,\n elapsedMs,\n correlationKey,\n };\n\n // Execute user's function\n const userFn = fnFactory(callbackCtx);\n return userFn(...args);\n };\n },\n );\n };\n },\n\n createLink(storedContext: StoredTraceContext): Link {\n return {\n context: {\n traceId: storedContext.traceId,\n spanId: storedContext.spanId,\n traceFlags: storedContext.traceFlags,\n isRemote: true,\n },\n attributes: {\n 'link.type': 'parking_lot',\n 'parking_lot.parked_at': storedContext.parkedAt,\n ...(storedContext.metadata && {\n 'parking_lot.has_metadata': true,\n }),\n },\n };\n },\n\n async exists(correlationKey: string): Promise<boolean> {\n const fullKey = prefixKey(correlationKey);\n const context = await store.load(fullKey);\n return context !== null;\n },\n };\n\n return parkingLot;\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Create a correlation key from multiple parts\n *\n * @param parts - Key parts to join\n * @returns A correlation key string\n *\n * @example\n * ```typescript\n * const key = createCorrelationKey('payment', orderId, 'stripe');\n * // Returns: \"payment:order-123:stripe\"\n * ```\n */\nexport function createCorrelationKey(...parts: (string | number)[]): string {\n return parts.map(String).join(':');\n}\n\n/**\n * Extract span context from stored context for manual linking\n *\n * @param storedContext - The stored trace context\n * @returns SpanContext compatible object\n */\nexport function toSpanContext(storedContext: StoredTraceContext): SpanContext {\n return {\n traceId: storedContext.traceId,\n spanId: storedContext.spanId,\n traceFlags: storedContext.traceFlags,\n isRemote: true,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/webhook.ts"],"names":["otelTrace"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiQO,IAAM,4BAAN,MAA6D;AAAA,EAIlE,WAAA,CACU,OAAA,GAGJ,EAAC,EACL;AAJQ,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAMR,IAAA,MAAM,SAAA,GAAY,QAAQ,iBAAA,IAAqB,GAAA;AAC/C,IAAA,IAAI,YAAY,CAAA,EAAG;AACjB,MAAA,IAAA,CAAK,kBAAkB,WAAA,CAAY,MAAM,IAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AAElE,MAAA,IAAI,IAAA,CAAK,gBAAgB,KAAA,EAAO;AAC9B,QAAA,IAAA,CAAK,gBAAgB,KAAA,EAAM;AAAA,MAC7B;AAAA,IACF;AAAA,EACF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S;AAAA,UACP,SAAS,aAAA,CAAc,OAAA;AAAA,UACvB,QAAQ,aAAA,CAAc,MAAA;AAAA,UACtB,YAAY,aAAA,CAAc,UAAA;AAAA,UAC1B,QAAA,EAAU;AAAA,SACZ;AAAA,QACA,UAAA,EAAY;AAAA,UACV,WAAA,EAAa,aAAA;AAAA,UACb,yBAAyB,aAAA,CAAc,QAAA;AAAA,UACvC,GAAI,cAAc,QAAA,IAAY;AAAA,YAC5B,0BAAA,EAA4B;AAAA;AAC9B;AACF,OACF;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,OAAO,cAAA,EAA0C;AACrD,MAAA,MAAM,OAAA,GAAU,UAAU,cAAc,CAAA;AACxC,MAAA,MAAM,OAAA,GAAU,MAAM,KAAA,CAAM,IAAA,CAAK,OAAO,CAAA;AACxC,MAAA,OAAO,OAAA,KAAY,IAAA;AAAA,IACrB;AAAA,GACF;AAEA,EAAA,OAAO,UAAA;AACT;AAkBO,SAAS,wBAAwB,KAAA,EAAoC;AAC1E,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,MAAM,CAAA,CAAE,KAAK,GAAG,CAAA;AACnC;AAQO,SAAS,cAAc,aAAA,EAAgD;AAC5E,EAAA,OAAO;AAAA,IACL,SAAS,aAAA,CAAc,OAAA;AAAA,IACvB,QAAQ,aAAA,CAAc,MAAA;AAAA,IACtB,YAAY,aAAA,CAAc,UAAA;AAAA,IAC1B,QAAA,EAAU;AAAA,GACZ;AACF","file":"webhook.js","sourcesContent":["/**\n * Webhook and callback tracing with the \"Parking Lot\" pattern\n *\n * When initiating async operations that return hours/days later (webhooks,\n * payment callbacks, human approvals), you can't keep a span open. This module\n * provides utilities to \"park\" trace context and retrieve it when callbacks arrive.\n *\n * @example Stripe payment webhook\n * ```typescript\n * import { createParkingLot, InMemoryTraceContextStore } from 'autotel/webhook';\n *\n * const parkingLot = createParkingLot({\n * store: new InMemoryTraceContextStore(),\n * defaultTTLMs: 24 * 60 * 60 * 1000, // 24 hours\n * });\n *\n * // When initiating payment\n * export const initiatePayment = trace(ctx => async (orderId: string) => {\n * await parkingLot.park(`payment:${orderId}`, { orderId });\n * await stripeClient.createPaymentIntent({ metadata: { orderId } });\n * });\n *\n * // When Stripe webhook arrives (hours later)\n * export const handleStripeWebhook = parkingLot.traceCallback({\n * name: 'stripe.webhook.payment_intent.succeeded',\n * correlationKeyFrom: (event) => `payment:${event.data.object.metadata.orderId}`,\n * })(ctx => async (event: Stripe.Event) => {\n * // ctx.parkedContext contains the original trace context\n * // ctx.elapsedMs shows time since payment was initiated\n * await fulfillOrder(event.data.object);\n * });\n * ```\n *\n * @module\n */\n\nimport { SpanKind, trace as otelTrace } from '@opentelemetry/api';\nimport type { SpanContext, Link } from '@opentelemetry/api';\nimport { emitCorrelatedEvent } from './correlated-events';\nimport { trace } from './functional';\nimport type { AttributeValue, TraceContext } from './trace-context';\nimport { recordStructuredError } from './structured-error';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Stored trace context for parking lot pattern\n */\nexport interface StoredTraceContext {\n /** Trace ID from the original span */\n traceId: string;\n\n /** Span ID from the original span */\n spanId: string;\n\n /** Trace flags (sampling decision) */\n traceFlags: number;\n\n /** When the context was parked */\n parkedAt: number;\n\n /** Optional TTL in milliseconds */\n ttlMs?: number;\n\n /** User-provided metadata */\n metadata?: Record<string, string>;\n}\n\n/**\n * Interface for trace context storage backends\n *\n * Implement this interface to use different storage backends (Redis, DynamoDB, etc.)\n */\nexport interface TraceContextStore {\n /**\n * Save trace context with a correlation key\n *\n * @param key - Unique correlation key (e.g., \"payment:order-123\")\n * @param context - The trace context to store\n */\n save(key: string, context: StoredTraceContext): Promise<void>;\n\n /**\n * Load trace context by correlation key\n *\n * @param key - The correlation key used when parking\n * @returns The stored context, or null if not found/expired\n */\n load(key: string): Promise<StoredTraceContext | null>;\n\n /**\n * Delete trace context by correlation key\n *\n * @param key - The correlation key to delete\n */\n delete(key: string): Promise<void>;\n}\n\n/**\n * Configuration for creating a parking lot\n */\nexport interface ParkingLotConfig {\n /** Storage backend for parked contexts */\n store: TraceContextStore;\n\n /** Default TTL in milliseconds (default: 24 hours) */\n defaultTTLMs?: number;\n\n /** Prefix for all correlation keys (default: \"parkingLot:\") */\n keyPrefix?: string;\n\n /** Whether to auto-delete after retrieval (default: true) */\n autoDeleteOnRetrieve?: boolean;\n\n /** Callback when context expires or is not found */\n onMiss?: (correlationKey: string) => void;\n}\n\n/**\n * Configuration for traceCallback wrapper\n */\nexport interface CallbackConfig {\n /** Span name for the callback handler */\n name: string;\n\n /**\n * Extract correlation key from callback arguments\n *\n * @example\n * ```typescript\n * correlationKeyFrom: (event) => `payment:${event.data.orderId}`\n * ```\n */\n correlationKeyFrom: (args: unknown[]) => string;\n\n /** Additional span attributes */\n attributes?: Record<string, string | number | boolean>;\n\n /** Whether to fail if parked context is not found (default: false) */\n requireParkedContext?: boolean;\n}\n\n/**\n * Extended context for callback handlers\n */\nexport interface CallbackContext extends TraceContext {\n /** The retrieved parked context, if found */\n parkedContext: StoredTraceContext | null;\n\n /** Time elapsed since context was parked (ms), or null if not found */\n elapsedMs: number | null;\n\n /** The correlation key used for retrieval */\n correlationKey: string;\n}\n\n/**\n * The parking lot instance\n */\nexport interface ParkingLot {\n /**\n * Park current trace context before initiating async operation\n *\n * Call this before sending a webhook, initiating a payment, or starting\n * any operation that will complete via callback.\n *\n * @param correlationKey - Unique key to retrieve context later (e.g., \"payment:order-123\")\n * @param metadata - Optional metadata to store with the context\n * @returns The correlation key (with prefix applied)\n *\n * @example\n * ```typescript\n * await parkingLot.park(`payment:${orderId}`, {\n * customerId: customer.id,\n * amount: payment.amount.toString(),\n * });\n * ```\n */\n park(\n correlationKey: string,\n metadata?: Record<string, string>,\n ): Promise<string>;\n\n /**\n * Retrieve parked context when callback arrives\n *\n * @param correlationKey - The key used when parking\n * @returns The stored context, or null if not found/expired\n */\n retrieve(correlationKey: string): Promise<StoredTraceContext | null>;\n\n /**\n * Wrap a callback handler with automatic context retrieval and linking\n *\n * Creates a traced function that:\n * 1. Extracts correlation key from arguments\n * 2. Retrieves parked context from storage\n * 3. Creates a span link to the original trace\n * 4. Provides elapsed time since parking\n *\n * @param config - Callback configuration\n * @returns Factory function for the callback handler\n *\n * @example\n * ```typescript\n * export const handleWebhook = parkingLot.traceCallback({\n * name: 'webhook.payment.completed',\n * correlationKeyFrom: (args) => `payment:${args[0].orderId}`,\n * })(ctx => async (event) => {\n * console.log(`Payment completed after ${ctx.elapsedMs}ms`);\n * await processPayment(event);\n * });\n * ```\n */\n traceCallback<TArgs extends unknown[], TReturn>(\n config: CallbackConfig,\n ): (\n fnFactory: (ctx: CallbackContext) => (...args: TArgs) => Promise<TReturn>,\n ) => (...args: TArgs) => Promise<TReturn>;\n\n /**\n * Manually create a span link from stored context\n *\n * Useful when you need more control over span creation.\n *\n * @param storedContext - The stored trace context\n * @returns A span link that can be added to a span\n */\n createLink(storedContext: StoredTraceContext): Link;\n\n /**\n * Check if a parked context exists (without retrieving/deleting it)\n *\n * @param correlationKey - The key to check\n * @returns True if context exists and hasn't expired\n */\n exists(correlationKey: string): Promise<boolean>;\n}\n\n// ============================================================================\n// In-Memory Store (for testing and development)\n// ============================================================================\n\n/**\n * In-memory trace context store\n *\n * Useful for testing and development. For production, use a persistent\n * store like Redis or DynamoDB.\n *\n * @example\n * ```typescript\n * const store = new InMemoryTraceContextStore();\n * const parkingLot = createParkingLot({ store });\n * ```\n */\nexport class InMemoryTraceContextStore implements TraceContextStore {\n private store = new Map<string, StoredTraceContext>();\n private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n\n constructor(\n private options: {\n /** Cleanup interval in ms (default: 60000) */\n cleanupIntervalMs?: number;\n } = {},\n ) {\n // Start periodic cleanup of expired entries\n const cleanupMs = options.cleanupIntervalMs ?? 60_000;\n if (cleanupMs > 0) {\n this.cleanupInterval = setInterval(() => this.cleanup(), cleanupMs);\n // Don't prevent process exit\n if (this.cleanupInterval.unref) {\n this.cleanupInterval.unref();\n }\n }\n }\n\n async save(key: string, context: StoredTraceContext): Promise<void> {\n this.store.set(key, context);\n }\n\n async load(key: string): Promise<StoredTraceContext | null> {\n const context = this.store.get(key);\n if (!context) {\n return null;\n }\n\n // Check TTL expiration\n if (context.ttlMs) {\n const age = Date.now() - context.parkedAt;\n if (age > context.ttlMs) {\n this.store.delete(key);\n return null;\n }\n }\n\n return context;\n }\n\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n /**\n * Get number of stored contexts (for testing)\n */\n get size(): number {\n return this.store.size;\n }\n\n /**\n * Clear all stored contexts (for testing)\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Stop the cleanup interval\n */\n destroy(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n }\n\n private cleanup(): void {\n const now = Date.now();\n for (const [key, context] of this.store.entries()) {\n if (context.ttlMs) {\n const age = now - context.parkedAt;\n if (age > context.ttlMs) {\n this.store.delete(key);\n }\n }\n }\n }\n}\n\n// ============================================================================\n// Parking Lot Factory\n// ============================================================================\n\n/**\n * Create a parking lot for trace context storage and retrieval\n *\n * @param config - Parking lot configuration\n * @returns A parking lot instance\n *\n * @example Basic usage\n * ```typescript\n * const parkingLot = createParkingLot({\n * store: new InMemoryTraceContextStore(),\n * defaultTTLMs: 24 * 60 * 60 * 1000, // 24 hours\n * });\n * ```\n *\n * @example With Redis store\n * ```typescript\n * class RedisTraceContextStore implements TraceContextStore {\n * constructor(private redis: Redis) {}\n *\n * async save(key: string, context: StoredTraceContext) {\n * const ttlSeconds = context.ttlMs ? Math.ceil(context.ttlMs / 1000) : 86400;\n * await this.redis.setex(key, ttlSeconds, JSON.stringify(context));\n * }\n *\n * async load(key: string) {\n * const data = await this.redis.get(key);\n * return data ? JSON.parse(data) : null;\n * }\n *\n * async delete(key: string) {\n * await this.redis.del(key);\n * }\n * }\n *\n * const parkingLot = createParkingLot({\n * store: new RedisTraceContextStore(redis),\n * });\n * ```\n */\nexport function createParkingLot(config: ParkingLotConfig): ParkingLot {\n const {\n store,\n defaultTTLMs = 24 * 60 * 60 * 1000, // 24 hours\n keyPrefix = 'parkingLot:',\n autoDeleteOnRetrieve = true,\n onMiss,\n } = config;\n\n /**\n * Get current span context from active context\n */\n function getCurrentSpanContext(): SpanContext | null {\n const activeSpan = otelTrace.getActiveSpan();\n if (!activeSpan) {\n return null;\n }\n return activeSpan.spanContext();\n }\n\n /**\n * Apply key prefix\n */\n function prefixKey(key: string): string {\n return `${keyPrefix}${key}`;\n }\n\n const parkingLot: ParkingLot = {\n async park(\n correlationKey: string,\n metadata?: Record<string, string>,\n ): Promise<string> {\n const spanContext = getCurrentSpanContext();\n const fullKey = prefixKey(correlationKey);\n\n const storedContext: StoredTraceContext = {\n traceId: spanContext?.traceId ?? '',\n spanId: spanContext?.spanId ?? '',\n traceFlags: spanContext?.traceFlags ?? 0,\n parkedAt: Date.now(),\n ttlMs: defaultTTLMs,\n metadata,\n };\n\n await store.save(fullKey, storedContext);\n\n const activeSpan = otelTrace.getActiveSpan();\n if (activeSpan) {\n const parkAttrs: Record<string, AttributeValue> = {\n 'parking_lot.correlation_key': correlationKey,\n 'parking_lot.ttl_ms': defaultTTLMs,\n ...(metadata &&\n Object.fromEntries(\n Object.entries(metadata).map(([k, v]) => [\n `parking_lot.metadata.${k}`,\n v,\n ]),\n )),\n };\n emitCorrelatedEvent(\n {\n setAttribute: (k, v) => activeSpan.setAttribute(k, v),\n setAttributes: (a) => activeSpan.setAttributes(a),\n addEvent: (n, a) => activeSpan.addEvent(n, a),\n },\n 'trace_context_parked',\n parkAttrs,\n );\n }\n\n // Return the unprefixed key so callers can use the same key for retrieve()\n return correlationKey;\n },\n\n async retrieve(correlationKey: string): Promise<StoredTraceContext | null> {\n const fullKey = prefixKey(correlationKey);\n const storedContext = await store.load(fullKey);\n\n if (!storedContext) {\n onMiss?.(correlationKey);\n return null;\n }\n\n if (autoDeleteOnRetrieve) {\n await store.delete(fullKey);\n }\n\n return storedContext;\n },\n\n traceCallback<TArgs extends unknown[], TReturn>(\n callbackConfig: CallbackConfig,\n ): (\n fnFactory: (ctx: CallbackContext) => (...args: TArgs) => Promise<TReturn>,\n ) => (...args: TArgs) => Promise<TReturn> {\n return (\n fnFactory: (\n ctx: CallbackContext,\n ) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>(\n {\n name: callbackConfig.name,\n spanKind: SpanKind.SERVER,\n },\n (baseCtx) => {\n return async (...args: TArgs) => {\n // Extract correlation key from arguments\n const correlationKey = callbackConfig.correlationKeyFrom(args);\n\n // Retrieve parked context\n const parkedContext = await parkingLot.retrieve(correlationKey);\n\n // Calculate elapsed time\n const elapsedMs = parkedContext\n ? Date.now() - parkedContext.parkedAt\n : null;\n\n // Set span attributes\n baseCtx.setAttribute(\n 'parking_lot.correlation_key',\n correlationKey,\n );\n\n if (parkedContext) {\n baseCtx.setAttribute('parking_lot.elapsed_ms', elapsedMs!);\n baseCtx.setAttribute(\n 'parking_lot.original_trace_id',\n parkedContext.traceId,\n );\n baseCtx.setAttribute(\n 'parking_lot.original_span_id',\n parkedContext.spanId,\n );\n\n // Add metadata as attributes\n if (parkedContext.metadata) {\n for (const [key, value] of Object.entries(\n parkedContext.metadata,\n )) {\n baseCtx.setAttribute(`parking_lot.metadata.${key}`, value);\n }\n }\n\n // Create span link to original trace\n const link = parkingLot.createLink(parkedContext);\n baseCtx.addLinks([link]);\n\n emitCorrelatedEvent(baseCtx, 'parked_context_retrieved', {\n 'parking_lot.correlation_key': correlationKey,\n 'parking_lot.elapsed_ms': elapsedMs!,\n 'parking_lot.original_trace_id': parkedContext.traceId,\n });\n } else {\n baseCtx.setAttribute('parking_lot.context_found', false);\n\n if (callbackConfig.requireParkedContext) {\n const error = new Error(\n `Required parked context not found for key: ${correlationKey}`,\n );\n recordStructuredError(baseCtx, error);\n throw error;\n }\n }\n\n // Apply custom attributes\n if (callbackConfig.attributes) {\n for (const [key, value] of Object.entries(\n callbackConfig.attributes,\n )) {\n baseCtx.setAttribute(key, value);\n }\n }\n\n // Create extended context\n const callbackCtx: CallbackContext = {\n ...baseCtx,\n parkedContext,\n elapsedMs,\n correlationKey,\n };\n\n // Execute user's function\n const userFn = fnFactory(callbackCtx);\n return userFn(...args);\n };\n },\n );\n };\n },\n\n createLink(storedContext: StoredTraceContext): Link {\n return {\n context: {\n traceId: storedContext.traceId,\n spanId: storedContext.spanId,\n traceFlags: storedContext.traceFlags,\n isRemote: true,\n },\n attributes: {\n 'link.type': 'parking_lot',\n 'parking_lot.parked_at': storedContext.parkedAt,\n ...(storedContext.metadata && {\n 'parking_lot.has_metadata': true,\n }),\n },\n };\n },\n\n async exists(correlationKey: string): Promise<boolean> {\n const fullKey = prefixKey(correlationKey);\n const context = await store.load(fullKey);\n return context !== null;\n },\n };\n\n return parkingLot;\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Create a correlation key from multiple parts\n *\n * @param parts - Key parts to join\n * @returns A correlation key string\n *\n * @example\n * ```typescript\n * const key = createCorrelationKey('payment', orderId, 'stripe');\n * // Returns: \"payment:order-123:stripe\"\n * ```\n */\nexport function createCorrelationKey(...parts: (string | number)[]): string {\n return parts.map(String).join(':');\n}\n\n/**\n * Extract span context from stored context for manual linking\n *\n * @param storedContext - The stored trace context\n * @returns SpanContext compatible object\n */\nexport function toSpanContext(storedContext: StoredTraceContext): SpanContext {\n return {\n traceId: storedContext.traceId,\n spanId: storedContext.spanId,\n traceFlags: storedContext.traceFlags,\n isRemote: true,\n };\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var chunk4P6ZOARG_cjs = require('./chunk-4P6ZOARG.cjs');
|
|
3
4
|
var chunkINJD3G4K_cjs = require('./chunk-INJD3G4K.cjs');
|
|
4
|
-
var
|
|
5
|
-
require('./chunk-
|
|
6
|
-
require('./chunk-
|
|
7
|
-
require('./chunk-
|
|
8
|
-
require('./chunk-HZ3FYBJG.cjs');
|
|
5
|
+
var chunkMOK3E54E_cjs = require('./chunk-MOK3E54E.cjs');
|
|
6
|
+
require('./chunk-NCSMD3TK.cjs');
|
|
7
|
+
require('./chunk-VQTCQKHQ.cjs');
|
|
8
|
+
require('./chunk-CJ4PD2TZ.cjs');
|
|
9
9
|
require('./chunk-563EL6O6.cjs');
|
|
10
10
|
require('./chunk-OC6X2VIN.cjs');
|
|
11
11
|
require('./chunk-CEAQK2QY.cjs');
|
|
@@ -59,7 +59,7 @@ var WorkflowBaggage = chunkINJD3G4K_cjs.createSafeBaggageSchema(workflowBaggageF
|
|
|
59
59
|
function traceDistributedWorkflow(config) {
|
|
60
60
|
const spanName = `workflow.${config.name}`;
|
|
61
61
|
return (fnFactory) => {
|
|
62
|
-
return
|
|
62
|
+
return chunkMOK3E54E_cjs.trace(
|
|
63
63
|
{ name: spanName, spanKind: api.SpanKind.INTERNAL },
|
|
64
64
|
(baseCtx) => {
|
|
65
65
|
return async (...args) => {
|
|
@@ -123,14 +123,14 @@ function traceDistributedWorkflow(config) {
|
|
|
123
123
|
baggageValues.stepName = stepName;
|
|
124
124
|
baggageValues.stepIndex = stepIndex;
|
|
125
125
|
WorkflowBaggage.set(baseCtx, baggageValues);
|
|
126
|
-
|
|
126
|
+
chunk4P6ZOARG_cjs.emitCorrelatedEvent(baseCtx, "workflow.step_progress", {
|
|
127
127
|
"workflow.step.name": stepName,
|
|
128
128
|
"workflow.step.index": stepIndex
|
|
129
129
|
});
|
|
130
130
|
}
|
|
131
131
|
};
|
|
132
132
|
config.onStart?.(workflowCtx);
|
|
133
|
-
|
|
133
|
+
chunk4P6ZOARG_cjs.emitCorrelatedEvent(baseCtx, "workflow.started", {
|
|
134
134
|
"workflow.id": workflowId,
|
|
135
135
|
"workflow.name": config.name
|
|
136
136
|
});
|
|
@@ -138,13 +138,13 @@ function traceDistributedWorkflow(config) {
|
|
|
138
138
|
const userFn = fnFactory(workflowCtx);
|
|
139
139
|
const result = await userFn(...args);
|
|
140
140
|
config.onComplete?.(workflowCtx, result);
|
|
141
|
-
|
|
141
|
+
chunk4P6ZOARG_cjs.emitCorrelatedEvent(baseCtx, "workflow.completed", {
|
|
142
142
|
"workflow.id": workflowId
|
|
143
143
|
});
|
|
144
144
|
return result;
|
|
145
145
|
} catch (error) {
|
|
146
146
|
config.onError?.(workflowCtx, error);
|
|
147
|
-
|
|
147
|
+
chunk4P6ZOARG_cjs.emitCorrelatedEvent(baseCtx, "workflow.failed", {
|
|
148
148
|
"workflow.id": workflowId,
|
|
149
149
|
"workflow.error": error.message
|
|
150
150
|
});
|
|
@@ -158,7 +158,7 @@ function traceDistributedWorkflow(config) {
|
|
|
158
158
|
function traceDistributedStep(config) {
|
|
159
159
|
const spanName = `workflow.step.${config.name}`;
|
|
160
160
|
return (fnFactory) => {
|
|
161
|
-
return
|
|
161
|
+
return chunkMOK3E54E_cjs.trace(
|
|
162
162
|
{ name: spanName, spanKind: api.SpanKind.INTERNAL },
|
|
163
163
|
(baseCtx) => {
|
|
164
164
|
return async (...args) => {
|
|
@@ -244,16 +244,20 @@ function traceDistributedStep(config) {
|
|
|
244
244
|
requiresCompensation(data) {
|
|
245
245
|
compensationData = data;
|
|
246
246
|
baseCtx.setAttribute("workflow.step.requires_compensation", true);
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
247
|
+
chunk4P6ZOARG_cjs.emitCorrelatedEvent(
|
|
248
|
+
baseCtx,
|
|
249
|
+
"workflow.step.compensation_registered",
|
|
250
|
+
{
|
|
251
|
+
"workflow.step.name": config.name,
|
|
252
|
+
...data && {
|
|
253
|
+
"workflow.step.compensation_data": JSON.stringify(data)
|
|
254
|
+
}
|
|
251
255
|
}
|
|
252
|
-
|
|
256
|
+
);
|
|
253
257
|
}
|
|
254
258
|
};
|
|
255
259
|
config.onStart?.(stepCtx);
|
|
256
|
-
|
|
260
|
+
chunk4P6ZOARG_cjs.emitCorrelatedEvent(baseCtx, "workflow.step.started", {
|
|
257
261
|
"workflow.step.name": config.name,
|
|
258
262
|
...baggageValues && { "workflow.id": baggageValues.workflowId }
|
|
259
263
|
});
|
|
@@ -261,13 +265,13 @@ function traceDistributedStep(config) {
|
|
|
261
265
|
const userFn = fnFactory(stepCtx);
|
|
262
266
|
const result = await userFn(...args);
|
|
263
267
|
config.onComplete?.(stepCtx, result);
|
|
264
|
-
|
|
268
|
+
chunk4P6ZOARG_cjs.emitCorrelatedEvent(baseCtx, "workflow.step.completed", {
|
|
265
269
|
"workflow.step.name": config.name
|
|
266
270
|
});
|
|
267
271
|
return result;
|
|
268
272
|
} catch (error) {
|
|
269
273
|
config.onError?.(stepCtx, error);
|
|
270
|
-
|
|
274
|
+
chunk4P6ZOARG_cjs.emitCorrelatedEvent(baseCtx, "workflow.step.failed", {
|
|
271
275
|
"workflow.step.name": config.name,
|
|
272
276
|
"workflow.step.error": error.message,
|
|
273
277
|
...compensationData && {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/workflow-distributed.ts"],"names":["createSafeBaggageSchema","trace","SpanKind","context","propagation"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAM,qBAAA,GAAwB;AAAA;AAAA,EAE5B,YAAY,EAAE,IAAA,EAAM,UAAmB,SAAA,EAAW,GAAA,EAAK,UAAU,IAAA,EAAK;AAAA;AAAA,EAGtE,cAAc,EAAE,IAAA,EAAM,UAAmB,SAAA,EAAW,EAAA,EAAI,UAAU,IAAA,EAAK;AAAA;AAAA,EAGvE,eAAA,EAAiB,EAAE,IAAA,EAAM,QAAA,EAAmB,WAAW,EAAA,EAAG;AAAA;AAAA,EAG1D,QAAA,EAAU,EAAE,IAAA,EAAM,QAAA,EAAmB,WAAW,EAAA,EAAG;AAAA;AAAA,EAGnD,SAAA,EAAW,EAAE,IAAA,EAAM,QAAA,EAAkB;AAAA;AAAA,EAGrC,UAAA,EAAY,EAAE,IAAA,EAAM,QAAA,EAAkB;AAAA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O,SAAA,GAAY,YAAA;AACnB,QAAA;AAAA,MACF;AAAA;AACF,EACF;AAEA,EAAA,OAAO,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,MAAA,GAAS,IAAI,MAAA,GAAS,IAAA;AACnD","file":"workflow-distributed.cjs","sourcesContent":["/**\n * Distributed workflow tracing with cross-service correlation\n *\n * Enables tracking workflows that span multiple microservices by propagating\n * workflow identity (workflowId, stepName, stepIndex) via baggage in message headers.\n *\n * Unlike local workflow.ts (which uses AsyncLocalStorage), distributed workflows\n * propagate context across network boundaries using W3C baggage.\n *\n * @example Order fulfillment saga across services\n * ```typescript\n * // Service A: Order Service\n * import { traceDistributedWorkflow, WorkflowBaggage } from 'autotel/workflow-distributed';\n * import { traceProducer } from 'autotel/messaging';\n *\n * export const createOrder = traceDistributedWorkflow({\n * name: 'OrderFulfillment',\n * workflowIdFrom: (order) => order.id,\n * version: '1.0.0',\n * })(ctx => async (order: Order) => {\n * // Workflow baggage is auto-set\n * await publishToInventory(order);\n * });\n *\n * const publishToInventory = traceProducer({\n * system: 'kafka',\n * destination: 'inventory-requests',\n * propagateBaggage: true, // Includes workflow.* baggage\n * })(ctx => async (order) => {\n * await producer.send({ topic: 'inventory-requests', value: order });\n * });\n *\n * // Service B: Inventory Service\n * import { traceDistributedStep, WorkflowBaggage } from 'autotel/workflow-distributed';\n *\n * export const processInventory = traceDistributedStep({\n * name: 'ReserveInventory',\n * extractBaggage: true, // Extracts workflow.* from headers\n * })(ctx => async (message) => {\n * const workflow = WorkflowBaggage.get(ctx);\n * // workflow.workflowId === order.id (propagated from Service A)\n * console.log(`Processing step for workflow ${workflow.workflowId}`);\n * await reserveItems(message.items);\n * });\n * ```\n *\n * @module\n */\n\nimport { context, propagation, SpanKind } from '@opentelemetry/api';\nimport { createSafeBaggageSchema } from './business-baggage';\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\n\n// ============================================================================\n// Workflow Baggage Schema\n// ============================================================================\n\n/**\n * Workflow baggage field definitions\n */\nconst workflowBaggageFields = {\n /** Unique identifier for the workflow instance */\n workflowId: { type: 'string' as const, maxLength: 128, required: true },\n\n /** Name/type of the workflow (e.g., \"OrderFulfillment\") */\n workflowName: { type: 'string' as const, maxLength: 64, required: true },\n\n /** Version of the workflow definition */\n workflowVersion: { type: 'string' as const, maxLength: 32 },\n\n /** Current step name */\n stepName: { type: 'string' as const, maxLength: 64 },\n\n /** Current step index (0-based) */\n stepIndex: { type: 'number' as const },\n\n /** Total number of steps (if known) */\n totalSteps: { type: 'number' as const },\n\n /** Parent workflow ID (for sub-workflows) */\n parentWorkflowId: { type: 'string' as const, maxLength: 128 },\n\n /** Correlation ID for external systems */\n correlationId: { type: 'string' as const, maxLength: 128 },\n\n /** Workflow priority */\n priority: {\n type: 'enum' as const,\n values: ['low', 'normal', 'high', 'critical'] as const,\n },\n\n /** Initiating user/system */\n initiatedBy: { type: 'string' as const, maxLength: 64 },\n\n /** Workflow start timestamp (ISO) */\n startedAt: { type: 'string' as const, maxLength: 30 },\n} as const;\n\n/**\n * Pre-built baggage schema for distributed workflows\n *\n * Use this to read/write workflow context that propagates across services.\n *\n * @example Setting workflow baggage\n * ```typescript\n * WorkflowBaggage.set(ctx, {\n * workflowId: 'order-12345',\n * workflowName: 'OrderFulfillment',\n * stepName: 'ReserveInventory',\n * stepIndex: 1,\n * });\n * ```\n *\n * @example Reading workflow baggage in downstream service\n * ```typescript\n * const { workflowId, workflowName, stepIndex } = WorkflowBaggage.get(ctx);\n * console.log(`Processing ${workflowName} step ${stepIndex}`);\n * ```\n */\nexport const WorkflowBaggage = createSafeBaggageSchema(workflowBaggageFields, {\n prefix: 'workflow',\n hashHighCardinality: false, // Workflow IDs should be traceable\n redactPII: false, // Workflow fields are internal identifiers\n});\n\n/**\n * Type for workflow baggage values\n */\nexport type WorkflowBaggageValues = {\n workflowId: string;\n workflowName: string;\n workflowVersion?: string;\n stepName?: string;\n stepIndex?: number;\n totalSteps?: number;\n parentWorkflowId?: string;\n correlationId?: string;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n initiatedBy?: string;\n startedAt?: string;\n};\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Configuration for distributed workflow tracing\n */\nexport interface DistributedWorkflowConfig {\n /** Workflow name/type (e.g., \"OrderFulfillment\", \"UserOnboarding\") */\n name: string;\n\n /**\n * Extract workflow ID from function arguments\n *\n * Receives all arguments passed to the workflow function, allowing\n * multi-parameter handlers to derive workflow IDs from any argument.\n *\n * @example Single argument\n * ```typescript\n * workflowIdFrom: (order) => order.id\n * ```\n *\n * @example Multiple arguments (payload + metadata)\n * ```typescript\n * workflowIdFrom: (payload, metadata) => metadata.correlationId ?? payload.id\n * ```\n */\n workflowIdFrom: (...args: unknown[]) => string;\n\n /** Workflow version (e.g., \"1.0.0\", \"2023-01-15\") */\n version?: string;\n\n /** Total number of steps if known */\n totalSteps?: number;\n\n /** Parent workflow ID (for sub-workflows) */\n parentWorkflowId?: string;\n\n /** Correlation ID for external systems */\n correlationId?: string;\n\n /** Workflow priority */\n priority?: 'low' | 'normal' | 'high' | 'critical';\n\n /** User/system that initiated the workflow */\n initiatedBy?: string;\n\n /** Additional span attributes */\n attributes?: Record<string, string | number | boolean>;\n\n /** Callback on workflow start */\n onStart?: (ctx: DistributedWorkflowContext) => void;\n\n /** Callback on workflow completion */\n onComplete?: (ctx: DistributedWorkflowContext, result: unknown) => void;\n\n /** Callback on workflow error */\n onError?: (ctx: DistributedWorkflowContext, error: Error) => void;\n}\n\n/**\n * Configuration for distributed workflow step\n */\nexport interface DistributedStepConfig {\n /** Step name (e.g., \"ReserveInventory\", \"ChargePayment\") */\n name: string;\n\n /**\n * Extract baggage from incoming message/request\n *\n * If true, reads workflow baggage from current context (assumes already extracted).\n * If function, extracts from arguments.\n *\n * @default true\n */\n extractBaggage?:\n | boolean\n | ((args: unknown[]) => WorkflowBaggageValues | null);\n\n /** Override step index (otherwise uses baggage or auto-increments) */\n stepIndex?: number;\n\n /** Additional span attributes */\n attributes?: Record<string, string | number | boolean>;\n\n /** Whether this step is idempotent (safe to retry) */\n idempotent?: boolean;\n\n /** Whether this step is a compensation/rollback step */\n isCompensation?: boolean;\n\n /** Callback on step start */\n onStart?: (ctx: DistributedStepContext) => void;\n\n /** Callback on step completion */\n onComplete?: (ctx: DistributedStepContext, result: unknown) => void;\n\n /** Callback on step error */\n onError?: (ctx: DistributedStepContext, error: Error) => void;\n}\n\n/**\n * Extended context for distributed workflow root\n */\nexport interface DistributedWorkflowContext extends TraceContext {\n /** The workflow ID */\n workflowId: string;\n\n /** The workflow name */\n workflowName: string;\n\n /** The workflow version */\n workflowVersion?: string;\n\n /** Get workflow baggage for propagation to other services */\n getWorkflowBaggage(): WorkflowBaggageValues;\n\n /** Set additional workflow baggage fields */\n setWorkflowBaggage(values: Partial<WorkflowBaggageValues>): void;\n\n /** Get headers with workflow baggage for outgoing requests */\n getWorkflowHeaders(): Record<string, string>;\n\n /** Record workflow step completion (for progress tracking) */\n recordStepProgress(stepName: string, stepIndex: number): void;\n}\n\n/**\n * Extended context for distributed workflow step\n */\nexport interface DistributedStepContext extends TraceContext {\n /** The workflow ID (from baggage) */\n workflowId: string | null;\n\n /** The workflow name (from baggage) */\n workflowName: string | null;\n\n /** The current step name */\n stepName: string;\n\n /** The current step index */\n stepIndex: number | null;\n\n /** Whether this step is a compensation */\n isCompensation: boolean;\n\n /** Get the full workflow baggage */\n getWorkflowBaggage(): WorkflowBaggageValues | null;\n\n /** Update workflow baggage (e.g., increment step index) */\n updateWorkflowBaggage(values: Partial<WorkflowBaggageValues>): void;\n\n /** Get headers with updated workflow baggage for downstream calls */\n getWorkflowHeaders(): Record<string, string>;\n\n /** Mark step as requiring compensation on failure */\n requiresCompensation(compensationData?: Record<string, unknown>): void;\n}\n\n// ============================================================================\n// Distributed Workflow Tracer\n// ============================================================================\n\n/**\n * Create a traced distributed workflow function\n *\n * Wraps a function as the entry point for a distributed workflow. Automatically:\n * - Generates or extracts workflow ID\n * - Sets workflow baggage for downstream propagation\n * - Creates root span with workflow attributes\n *\n * @param config - Workflow configuration\n * @returns Factory function for the workflow handler\n *\n * @example Basic usage\n * ```typescript\n * export const createOrder = traceDistributedWorkflow({\n * name: 'OrderFulfillment',\n * workflowIdFrom: (order) => order.id,\n * version: '1.0.0',\n * })(ctx => async (order: Order) => {\n * ctx.recordStepProgress('ValidateOrder', 0);\n * await validateOrder(order);\n *\n * ctx.recordStepProgress('ReserveInventory', 1);\n * await publishToInventoryService(order);\n *\n * return { workflowId: ctx.workflowId, status: 'started' };\n * });\n * ```\n */\nexport function traceDistributedWorkflow<TArgs extends unknown[], TReturn>(\n config: DistributedWorkflowConfig,\n) {\n const spanName = `workflow.${config.name}`;\n\n return (\n fnFactory: (\n ctx: DistributedWorkflowContext,\n ) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>(\n { name: spanName, spanKind: SpanKind.INTERNAL },\n (baseCtx) => {\n return async (...args: TArgs) => {\n // Extract workflow ID from arguments (spread to allow multi-arg access)\n const workflowId = config.workflowIdFrom(...args);\n const startedAt = new Date().toISOString();\n\n // Initialize workflow baggage\n const baggageValues: WorkflowBaggageValues = {\n workflowId,\n workflowName: config.name,\n workflowVersion: config.version,\n stepIndex: 0,\n totalSteps: config.totalSteps,\n parentWorkflowId: config.parentWorkflowId,\n correlationId: config.correlationId,\n priority: config.priority,\n initiatedBy: config.initiatedBy,\n startedAt,\n };\n\n // Set baggage\n WorkflowBaggage.set(baseCtx, baggageValues);\n\n // Set span attributes\n baseCtx.setAttribute('workflow.id', workflowId);\n baseCtx.setAttribute('workflow.name', config.name);\n if (config.version) {\n baseCtx.setAttribute('workflow.version', config.version);\n }\n if (config.totalSteps) {\n baseCtx.setAttribute('workflow.total_steps', config.totalSteps);\n }\n if (config.parentWorkflowId) {\n baseCtx.setAttribute('workflow.parent_id', config.parentWorkflowId);\n }\n if (config.priority) {\n baseCtx.setAttribute('workflow.priority', config.priority);\n }\n if (config.initiatedBy) {\n baseCtx.setAttribute('workflow.initiated_by', config.initiatedBy);\n }\n baseCtx.setAttribute('workflow.started_at', startedAt);\n\n // Apply custom attributes\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n baseCtx.setAttribute(key, value);\n }\n }\n\n // Create extended context\n const workflowCtx: DistributedWorkflowContext = {\n ...baseCtx,\n workflowId,\n workflowName: config.name,\n workflowVersion: config.version,\n\n getWorkflowBaggage(): WorkflowBaggageValues {\n return { ...baggageValues };\n },\n\n setWorkflowBaggage(values: Partial<WorkflowBaggageValues>): void {\n Object.assign(baggageValues, values);\n WorkflowBaggage.set(baseCtx, baggageValues);\n },\n\n getWorkflowHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n const ctx = context.active();\n propagation.inject(ctx, headers);\n return headers;\n },\n\n recordStepProgress(stepName: string, stepIndex: number): void {\n baggageValues.stepName = stepName;\n baggageValues.stepIndex = stepIndex;\n WorkflowBaggage.set(baseCtx, baggageValues);\n\n baseCtx.addEvent('workflow.step_progress', {\n 'workflow.step.name': stepName,\n 'workflow.step.index': stepIndex,\n });\n },\n };\n\n // Call onStart callback\n config.onStart?.(workflowCtx);\n\n // Add start event\n baseCtx.addEvent('workflow.started', {\n 'workflow.id': workflowId,\n 'workflow.name': config.name,\n });\n\n try {\n const userFn = fnFactory(workflowCtx);\n const result = await userFn(...args);\n\n // Call onComplete callback\n config.onComplete?.(workflowCtx, result);\n\n // Add completion event\n baseCtx.addEvent('workflow.completed', {\n 'workflow.id': workflowId,\n });\n\n return result;\n } catch (error) {\n // Call onError callback\n config.onError?.(workflowCtx, error as Error);\n\n // Add error event\n baseCtx.addEvent('workflow.failed', {\n 'workflow.id': workflowId,\n 'workflow.error': (error as Error).message,\n });\n\n throw error;\n }\n };\n },\n );\n };\n}\n\n// ============================================================================\n// Distributed Step Tracer\n// ============================================================================\n\n/**\n * Create a traced distributed workflow step\n *\n * Use in downstream services to trace steps that are part of a distributed workflow.\n * Automatically extracts workflow baggage from the current context.\n *\n * @param config - Step configuration\n * @returns Factory function for the step handler\n *\n * @example Consumer in downstream service\n * ```typescript\n * export const processInventory = traceConsumer({\n * system: 'kafka',\n * destination: 'inventory-requests',\n * extractBaggage: true, // Extracts workflow.* from headers\n * })(ctx => {\n * // Wrap inner logic with traceDistributedStep\n * return traceDistributedStep({\n * name: 'ReserveInventory',\n * })(stepCtx => async (message) => {\n * console.log(`Processing workflow ${stepCtx.workflowId}`);\n * await reserveItems(message.items);\n * })(message);\n * });\n * ```\n *\n * @example Standalone step handler\n * ```typescript\n * export const reserveInventory = traceDistributedStep({\n * name: 'ReserveInventory',\n * idempotent: true,\n * })(ctx => async (request: InventoryRequest) => {\n * if (ctx.workflowId) {\n * console.log(`Part of workflow ${ctx.workflowId}, step ${ctx.stepIndex}`);\n * }\n * return await inventoryService.reserve(request.items);\n * });\n * ```\n */\nexport function traceDistributedStep<TArgs extends unknown[], TReturn>(\n config: DistributedStepConfig,\n) {\n const spanName = `workflow.step.${config.name}`;\n\n return (\n fnFactory: (\n ctx: DistributedStepContext,\n ) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>(\n { name: spanName, spanKind: SpanKind.INTERNAL },\n (baseCtx) => {\n return async (...args: TArgs) => {\n // Extract workflow baggage\n let baggageValues: WorkflowBaggageValues | null = null;\n\n const extractBaggage = config.extractBaggage ?? true;\n if (typeof extractBaggage === 'function') {\n baggageValues = extractBaggage(args);\n } else if (extractBaggage) {\n // Read from current context\n const extracted = WorkflowBaggage.get(baseCtx);\n if (extracted.workflowId && extracted.workflowName) {\n baggageValues = extracted as WorkflowBaggageValues;\n }\n }\n\n // Determine step index\n // If explicit stepIndex provided in config, use it\n // Otherwise, auto-increment from baggage if available\n let stepIndex: number | null;\n if (config.stepIndex !== undefined) {\n stepIndex = config.stepIndex;\n } else if (baggageValues?.stepIndex === undefined) {\n stepIndex = null;\n } else {\n // Auto-increment from previous step\n stepIndex = baggageValues.stepIndex + 1;\n }\n\n // Update baggage with current step\n if (baggageValues) {\n baggageValues.stepName = config.name;\n if (stepIndex !== null) {\n baggageValues.stepIndex = stepIndex;\n }\n WorkflowBaggage.set(baseCtx, baggageValues);\n }\n\n // Set span attributes\n baseCtx.setAttribute('workflow.step.name', config.name);\n if (stepIndex !== null) {\n baseCtx.setAttribute('workflow.step.index', stepIndex);\n }\n if (config.idempotent !== undefined) {\n baseCtx.setAttribute('workflow.step.idempotent', config.idempotent);\n }\n if (config.isCompensation) {\n baseCtx.setAttribute('workflow.step.is_compensation', true);\n }\n\n // Add workflow context attributes if available\n if (baggageValues) {\n baseCtx.setAttribute('workflow.id', baggageValues.workflowId);\n baseCtx.setAttribute('workflow.name', baggageValues.workflowName);\n if (baggageValues.workflowVersion) {\n baseCtx.setAttribute(\n 'workflow.version',\n baggageValues.workflowVersion,\n );\n }\n if (baggageValues.totalSteps) {\n baseCtx.setAttribute(\n 'workflow.total_steps',\n baggageValues.totalSteps,\n );\n }\n }\n\n // Apply custom attributes\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n baseCtx.setAttribute(key, value);\n }\n }\n\n // Compensation data storage\n let compensationData: Record<string, unknown> | undefined;\n\n // Create extended context\n const stepCtx: DistributedStepContext = {\n ...baseCtx,\n workflowId: baggageValues?.workflowId ?? null,\n workflowName: baggageValues?.workflowName ?? null,\n stepName: config.name,\n stepIndex,\n isCompensation: config.isCompensation ?? false,\n\n getWorkflowBaggage(): WorkflowBaggageValues | null {\n return baggageValues ? { ...baggageValues } : null;\n },\n\n updateWorkflowBaggage(\n values: Partial<WorkflowBaggageValues>,\n ): void {\n if (baggageValues) {\n Object.assign(baggageValues, values);\n WorkflowBaggage.set(baseCtx, baggageValues);\n }\n },\n\n getWorkflowHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n const ctx = context.active();\n propagation.inject(ctx, headers);\n return headers;\n },\n\n requiresCompensation(data?: Record<string, unknown>): void {\n compensationData = data;\n baseCtx.setAttribute('workflow.step.requires_compensation', true);\n baseCtx.addEvent('workflow.step.compensation_registered', {\n 'workflow.step.name': config.name,\n ...(data && {\n 'workflow.step.compensation_data': JSON.stringify(data),\n }),\n });\n },\n };\n\n // Call onStart callback\n config.onStart?.(stepCtx);\n\n // Add start event\n baseCtx.addEvent('workflow.step.started', {\n 'workflow.step.name': config.name,\n ...(baggageValues && { 'workflow.id': baggageValues.workflowId }),\n });\n\n try {\n const userFn = fnFactory(stepCtx);\n const result = await userFn(...args);\n\n // Call onComplete callback\n config.onComplete?.(stepCtx, result);\n\n // Add completion event\n baseCtx.addEvent('workflow.step.completed', {\n 'workflow.step.name': config.name,\n });\n\n return result;\n } catch (error) {\n // Call onError callback\n config.onError?.(stepCtx, error as Error);\n\n // Add error event with compensation info if registered\n baseCtx.addEvent('workflow.step.failed', {\n 'workflow.step.name': config.name,\n 'workflow.step.error': (error as Error).message,\n ...(compensationData && {\n 'workflow.step.requires_compensation': true,\n }),\n });\n\n throw error;\n }\n };\n },\n );\n };\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Generate a unique workflow ID\n *\n * @param prefix - Optional prefix for the ID\n * @returns A unique workflow ID\n *\n * @example\n * ```typescript\n * const workflowId = generateWorkflowId('order'); // \"order-abc123def456\"\n * ```\n */\nexport function generateWorkflowId(prefix?: string): string {\n const random = Math.random().toString(36).slice(2, 15);\n const timestamp = Date.now().toString(36);\n const id = `${timestamp}-${random}`;\n return prefix ? `${prefix}-${id}` : id;\n}\n\n/**\n * Check if the current context is part of a distributed workflow\n *\n * @param ctx - The trace context\n * @returns True if workflow baggage is present\n */\nexport function isInDistributedWorkflow(ctx: TraceContext): boolean {\n const baggage = WorkflowBaggage.get(ctx);\n return !!(baggage.workflowId && baggage.workflowName);\n}\n\n/**\n * Get workflow progress information\n *\n * @param ctx - The trace context\n * @returns Progress info or null if not in a workflow\n */\nexport function getWorkflowProgress(ctx: TraceContext): {\n workflowId: string;\n workflowName: string;\n currentStep: string | null;\n currentStepIndex: number | null;\n totalSteps: number | null;\n percentComplete: number | null;\n} | null {\n const baggage = WorkflowBaggage.get(ctx);\n if (!baggage.workflowId || !baggage.workflowName) {\n return null;\n }\n\n const percentComplete =\n baggage.totalSteps && baggage.stepIndex !== undefined\n ? Math.round(((baggage.stepIndex + 1) / baggage.totalSteps) * 100)\n : null;\n\n return {\n workflowId: baggage.workflowId,\n workflowName: baggage.workflowName,\n currentStep: baggage.stepName ?? null,\n currentStepIndex: baggage.stepIndex ?? null,\n totalSteps: baggage.totalSteps ?? null,\n percentComplete,\n };\n}\n\n/**\n * Create workflow correlation headers for manual propagation\n *\n * Use when you need to manually add workflow context to outgoing requests.\n *\n * @param values - Workflow baggage values\n * @returns Headers object with workflow baggage\n *\n * @example\n * ```typescript\n * const headers = createWorkflowHeaders({\n * workflowId: 'order-123',\n * workflowName: 'OrderFulfillment',\n * stepIndex: 2,\n * });\n *\n * await fetch('/api/inventory', { headers });\n * ```\n */\nexport function createWorkflowHeaders(\n values: Partial<WorkflowBaggageValues>,\n): Record<string, string> {\n const headers: Record<string, string> = {};\n\n // Build baggage string\n const baggageEntries: string[] = [];\n\n if (values.workflowId) {\n baggageEntries.push(\n `workflow.workflowId=${encodeURIComponent(values.workflowId)}`,\n );\n }\n if (values.workflowName) {\n baggageEntries.push(\n `workflow.workflowName=${encodeURIComponent(values.workflowName)}`,\n );\n }\n if (values.workflowVersion) {\n baggageEntries.push(\n `workflow.workflowVersion=${encodeURIComponent(values.workflowVersion)}`,\n );\n }\n if (values.stepName) {\n baggageEntries.push(\n `workflow.stepName=${encodeURIComponent(values.stepName)}`,\n );\n }\n if (values.stepIndex !== undefined) {\n baggageEntries.push(`workflow.stepIndex=${values.stepIndex}`);\n }\n if (values.totalSteps !== undefined) {\n baggageEntries.push(`workflow.totalSteps=${values.totalSteps}`);\n }\n if (values.priority) {\n baggageEntries.push(`workflow.priority=${values.priority}`);\n }\n if (values.correlationId) {\n baggageEntries.push(\n `workflow.correlationId=${encodeURIComponent(values.correlationId)}`,\n );\n }\n if (values.parentWorkflowId) {\n baggageEntries.push(\n `workflow.parentWorkflowId=${encodeURIComponent(values.parentWorkflowId)}`,\n );\n }\n if (values.initiatedBy) {\n baggageEntries.push(\n `workflow.initiatedBy=${encodeURIComponent(values.initiatedBy)}`,\n );\n }\n if (values.startedAt) {\n baggageEntries.push(\n `workflow.startedAt=${encodeURIComponent(values.startedAt)}`,\n );\n }\n\n if (baggageEntries.length > 0) {\n headers['baggage'] = baggageEntries.join(',');\n }\n\n return headers;\n}\n\n/**\n * Parse workflow context from baggage header\n *\n * @param baggageHeader - The baggage header value\n * @returns Parsed workflow values or null\n */\nexport function parseWorkflowFromBaggage(\n baggageHeader: string,\n): Partial<WorkflowBaggageValues> | null {\n if (!baggageHeader) {\n return null;\n }\n\n const values: Partial<WorkflowBaggageValues> = {};\n const entries = baggageHeader.split(',');\n\n for (const entry of entries) {\n const [key, value] = entry.trim().split('=');\n if (!key || !value) continue;\n\n const decodedValue = decodeURIComponent(value);\n\n switch (key) {\n case 'workflow.workflowId': {\n values.workflowId = decodedValue;\n break;\n }\n case 'workflow.workflowName': {\n values.workflowName = decodedValue;\n break;\n }\n case 'workflow.workflowVersion': {\n values.workflowVersion = decodedValue;\n break;\n }\n case 'workflow.stepName': {\n values.stepName = decodedValue;\n break;\n }\n case 'workflow.stepIndex': {\n values.stepIndex = Number.parseInt(decodedValue, 10);\n break;\n }\n case 'workflow.totalSteps': {\n values.totalSteps = Number.parseInt(decodedValue, 10);\n break;\n }\n case 'workflow.priority': {\n values.priority = decodedValue as WorkflowBaggageValues['priority'];\n break;\n }\n case 'workflow.correlationId': {\n values.correlationId = decodedValue;\n break;\n }\n case 'workflow.parentWorkflowId': {\n values.parentWorkflowId = decodedValue;\n break;\n }\n case 'workflow.initiatedBy': {\n values.initiatedBy = decodedValue;\n break;\n }\n case 'workflow.startedAt': {\n values.startedAt = decodedValue;\n break;\n }\n }\n }\n\n return Object.keys(values).length > 0 ? values : null;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/workflow-distributed.ts"],"names":["createSafeBaggageSchema","trace","SpanKind","context","propagation","emitCorrelatedEvent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA8DA,IAAM,qBAAA,GAAwB;AAAA;AAAA,EAE5B,YAAY,EAAE,IAAA,EAAM,UAAmB,SAAA,EAAW,GAAA,EAAK,UAAU,IAAA,EAAK;AAAA;AAAA,EAGtE,cAAc,EAAE,IAAA,EAAM,UAAmB,SAAA,EAAW,EAAA,EAAI,UAAU,IAAA,EAAK;AAAA;AAAA,EAGvE,eAAA,EAAiB,EAAE,IAAA,EAAM,QAAA,EAAmB,WAAW,EAAA,EAAG;AAAA;AAAA,EAG1D,QAAA,EAAU,EAAE,IAAA,EAAM,QAAA,EAAmB,WAAW,EAAA,EAAG;AAAA;AAAA,EAGnD,SAAA,EAAW,EAAE,IAAA,EAAM,QAAA,EAAkB;AAAA;AAAA,EAGrC,UAAA,EAAY,EAAE,IAAA,EAAM,QAAA,EAAkB;AAAA;AAAA,EAGtC,gBAAA,EAAkB,EAAE,IAAA,EAAM,QAAA,EAAmB,WAAW,GAAA,EAAI;AAAA;AAAA,EAG5D,aAAA,EAAe,EAAE,IAAA,EAAM,QAAA,EAAmB,WAAW,GAAA,EAAI;AAAA;AAAA,EAGzD,QAAA,EAAU;AAAA,IACR,IAAA,EAAM,MAAA;AAAA,IACN,MAAA,EAAQ,CAAC,KAAA,EAAO,QAAA,EAAU,QAAQ,UAAU;AAAA,GAC9C;AAAA;AAAA,EAGA,WAAA,EAAa,EAAE,IAAA,EAAM,QAAA,EAAmB,WAAW,EAAA,EAAG;AAAA;AAAA,EAGtD,SAAA,EAAW,EAAE,IAAA,EAAM,QAAA,EAAmB,WAAW,EAAA;AACnD,CAAA;AAuBO,IAAM,eAAA,GAAkBA,0CAAwB,qBAAA,EAAuB;AAAA,EAC5E,MAAA,EAAQ,UAAA;AAAA,EACR,mBAAA,EAAq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A,EAAsB;AACzB,QAAA,MAAA,CAAO,SAAA,GAAY,MAAA,CAAO,QAAA,CAAS,YAAA,EAAc,EAAE,CAAA;AACnD,QAAA;AAAA,MACF;AAAA,MACA,KAAK,qBAAA,EAAuB;AAC1B,QAAA,MAAA,CAAO,UAAA,GAAa,MAAA,CAAO,QAAA,CAAS,YAAA,EAAc,EAAE,CAAA;AACpD,QAAA;AAAA,MACF;AAAA,MACA,KAAK,mBAAA,EAAqB;AACxB,QAAA,MAAA,CAAO,QAAA,GAAW,YAAA;AAClB,QAAA;AAAA,MACF;AAAA,MACA,KAAK,wBAAA,EAA0B;AAC7B,QAAA,MAAA,CAAO,aAAA,GAAgB,YAAA;AACvB,QAAA;AAAA,MACF;AAAA,MACA,KAAK,2BAAA,EAA6B;AAChC,QAAA,MAAA,CAAO,gBAAA,GAAmB,YAAA;AAC1B,QAAA;AAAA,MACF;AAAA,MACA,KAAK,sBAAA,EAAwB;AAC3B,QAAA,MAAA,CAAO,WAAA,GAAc,YAAA;AACrB,QAAA;AAAA,MACF;AAAA,MACA,KAAK,oBAAA,EAAsB;AACzB,QAAA,MAAA,CAAO,SAAA,GAAY,YAAA;AACnB,QAAA;AAAA,MACF;AAAA;AACF,EACF;AAEA,EAAA,OAAO,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,MAAA,GAAS,IAAI,MAAA,GAAS,IAAA;AACnD","file":"workflow-distributed.cjs","sourcesContent":["/**\n * Distributed workflow tracing with cross-service correlation\n *\n * Enables tracking workflows that span multiple microservices by propagating\n * workflow identity (workflowId, stepName, stepIndex) via baggage in message headers.\n *\n * Unlike local workflow.ts (which uses AsyncLocalStorage), distributed workflows\n * propagate context across network boundaries using W3C baggage.\n *\n * @example Order fulfillment saga across services\n * ```typescript\n * // Service A: Order Service\n * import { traceDistributedWorkflow, WorkflowBaggage } from 'autotel/workflow-distributed';\n * import { traceProducer } from 'autotel/messaging';\n *\n * export const createOrder = traceDistributedWorkflow({\n * name: 'OrderFulfillment',\n * workflowIdFrom: (order) => order.id,\n * version: '1.0.0',\n * })(ctx => async (order: Order) => {\n * // Workflow baggage is auto-set\n * await publishToInventory(order);\n * });\n *\n * const publishToInventory = traceProducer({\n * system: 'kafka',\n * destination: 'inventory-requests',\n * propagateBaggage: true, // Includes workflow.* baggage\n * })(ctx => async (order) => {\n * await producer.send({ topic: 'inventory-requests', value: order });\n * });\n *\n * // Service B: Inventory Service\n * import { traceDistributedStep, WorkflowBaggage } from 'autotel/workflow-distributed';\n *\n * export const processInventory = traceDistributedStep({\n * name: 'ReserveInventory',\n * extractBaggage: true, // Extracts workflow.* from headers\n * })(ctx => async (message) => {\n * const workflow = WorkflowBaggage.get(ctx);\n * // workflow.workflowId === order.id (propagated from Service A)\n * console.log(`Processing step for workflow ${workflow.workflowId}`);\n * await reserveItems(message.items);\n * });\n * ```\n *\n * @module\n */\n\nimport { context, propagation, SpanKind } from '@opentelemetry/api';\nimport { createSafeBaggageSchema } from './business-baggage';\nimport { emitCorrelatedEvent } from './correlated-events';\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\n\n// ============================================================================\n// Workflow Baggage Schema\n// ============================================================================\n\n/**\n * Workflow baggage field definitions\n */\nconst workflowBaggageFields = {\n /** Unique identifier for the workflow instance */\n workflowId: { type: 'string' as const, maxLength: 128, required: true },\n\n /** Name/type of the workflow (e.g., \"OrderFulfillment\") */\n workflowName: { type: 'string' as const, maxLength: 64, required: true },\n\n /** Version of the workflow definition */\n workflowVersion: { type: 'string' as const, maxLength: 32 },\n\n /** Current step name */\n stepName: { type: 'string' as const, maxLength: 64 },\n\n /** Current step index (0-based) */\n stepIndex: { type: 'number' as const },\n\n /** Total number of steps (if known) */\n totalSteps: { type: 'number' as const },\n\n /** Parent workflow ID (for sub-workflows) */\n parentWorkflowId: { type: 'string' as const, maxLength: 128 },\n\n /** Correlation ID for external systems */\n correlationId: { type: 'string' as const, maxLength: 128 },\n\n /** Workflow priority */\n priority: {\n type: 'enum' as const,\n values: ['low', 'normal', 'high', 'critical'] as const,\n },\n\n /** Initiating user/system */\n initiatedBy: { type: 'string' as const, maxLength: 64 },\n\n /** Workflow start timestamp (ISO) */\n startedAt: { type: 'string' as const, maxLength: 30 },\n} as const;\n\n/**\n * Pre-built baggage schema for distributed workflows\n *\n * Use this to read/write workflow context that propagates across services.\n *\n * @example Setting workflow baggage\n * ```typescript\n * WorkflowBaggage.set(ctx, {\n * workflowId: 'order-12345',\n * workflowName: 'OrderFulfillment',\n * stepName: 'ReserveInventory',\n * stepIndex: 1,\n * });\n * ```\n *\n * @example Reading workflow baggage in downstream service\n * ```typescript\n * const { workflowId, workflowName, stepIndex } = WorkflowBaggage.get(ctx);\n * console.log(`Processing ${workflowName} step ${stepIndex}`);\n * ```\n */\nexport const WorkflowBaggage = createSafeBaggageSchema(workflowBaggageFields, {\n prefix: 'workflow',\n hashHighCardinality: false, // Workflow IDs should be traceable\n redactPII: false, // Workflow fields are internal identifiers\n});\n\n/**\n * Type for workflow baggage values\n */\nexport type WorkflowBaggageValues = {\n workflowId: string;\n workflowName: string;\n workflowVersion?: string;\n stepName?: string;\n stepIndex?: number;\n totalSteps?: number;\n parentWorkflowId?: string;\n correlationId?: string;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n initiatedBy?: string;\n startedAt?: string;\n};\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Configuration for distributed workflow tracing\n */\nexport interface DistributedWorkflowConfig {\n /** Workflow name/type (e.g., \"OrderFulfillment\", \"UserOnboarding\") */\n name: string;\n\n /**\n * Extract workflow ID from function arguments\n *\n * Receives all arguments passed to the workflow function, allowing\n * multi-parameter handlers to derive workflow IDs from any argument.\n *\n * @example Single argument\n * ```typescript\n * workflowIdFrom: (order) => order.id\n * ```\n *\n * @example Multiple arguments (payload + metadata)\n * ```typescript\n * workflowIdFrom: (payload, metadata) => metadata.correlationId ?? payload.id\n * ```\n */\n workflowIdFrom: (...args: unknown[]) => string;\n\n /** Workflow version (e.g., \"1.0.0\", \"2023-01-15\") */\n version?: string;\n\n /** Total number of steps if known */\n totalSteps?: number;\n\n /** Parent workflow ID (for sub-workflows) */\n parentWorkflowId?: string;\n\n /** Correlation ID for external systems */\n correlationId?: string;\n\n /** Workflow priority */\n priority?: 'low' | 'normal' | 'high' | 'critical';\n\n /** User/system that initiated the workflow */\n initiatedBy?: string;\n\n /** Additional span attributes */\n attributes?: Record<string, string | number | boolean>;\n\n /** Callback on workflow start */\n onStart?: (ctx: DistributedWorkflowContext) => void;\n\n /** Callback on workflow completion */\n onComplete?: (ctx: DistributedWorkflowContext, result: unknown) => void;\n\n /** Callback on workflow error */\n onError?: (ctx: DistributedWorkflowContext, error: Error) => void;\n}\n\n/**\n * Configuration for distributed workflow step\n */\nexport interface DistributedStepConfig {\n /** Step name (e.g., \"ReserveInventory\", \"ChargePayment\") */\n name: string;\n\n /**\n * Extract baggage from incoming message/request\n *\n * If true, reads workflow baggage from current context (assumes already extracted).\n * If function, extracts from arguments.\n *\n * @default true\n */\n extractBaggage?:\n | boolean\n | ((args: unknown[]) => WorkflowBaggageValues | null);\n\n /** Override step index (otherwise uses baggage or auto-increments) */\n stepIndex?: number;\n\n /** Additional span attributes */\n attributes?: Record<string, string | number | boolean>;\n\n /** Whether this step is idempotent (safe to retry) */\n idempotent?: boolean;\n\n /** Whether this step is a compensation/rollback step */\n isCompensation?: boolean;\n\n /** Callback on step start */\n onStart?: (ctx: DistributedStepContext) => void;\n\n /** Callback on step completion */\n onComplete?: (ctx: DistributedStepContext, result: unknown) => void;\n\n /** Callback on step error */\n onError?: (ctx: DistributedStepContext, error: Error) => void;\n}\n\n/**\n * Extended context for distributed workflow root\n */\nexport interface DistributedWorkflowContext extends TraceContext {\n /** The workflow ID */\n workflowId: string;\n\n /** The workflow name */\n workflowName: string;\n\n /** The workflow version */\n workflowVersion?: string;\n\n /** Get workflow baggage for propagation to other services */\n getWorkflowBaggage(): WorkflowBaggageValues;\n\n /** Set additional workflow baggage fields */\n setWorkflowBaggage(values: Partial<WorkflowBaggageValues>): void;\n\n /** Get headers with workflow baggage for outgoing requests */\n getWorkflowHeaders(): Record<string, string>;\n\n /** Record workflow step completion (for progress tracking) */\n recordStepProgress(stepName: string, stepIndex: number): void;\n}\n\n/**\n * Extended context for distributed workflow step\n */\nexport interface DistributedStepContext extends TraceContext {\n /** The workflow ID (from baggage) */\n workflowId: string | null;\n\n /** The workflow name (from baggage) */\n workflowName: string | null;\n\n /** The current step name */\n stepName: string;\n\n /** The current step index */\n stepIndex: number | null;\n\n /** Whether this step is a compensation */\n isCompensation: boolean;\n\n /** Get the full workflow baggage */\n getWorkflowBaggage(): WorkflowBaggageValues | null;\n\n /** Update workflow baggage (e.g., increment step index) */\n updateWorkflowBaggage(values: Partial<WorkflowBaggageValues>): void;\n\n /** Get headers with updated workflow baggage for downstream calls */\n getWorkflowHeaders(): Record<string, string>;\n\n /** Mark step as requiring compensation on failure */\n requiresCompensation(compensationData?: Record<string, unknown>): void;\n}\n\n// ============================================================================\n// Distributed Workflow Tracer\n// ============================================================================\n\n/**\n * Create a traced distributed workflow function\n *\n * Wraps a function as the entry point for a distributed workflow. Automatically:\n * - Generates or extracts workflow ID\n * - Sets workflow baggage for downstream propagation\n * - Creates root span with workflow attributes\n *\n * @param config - Workflow configuration\n * @returns Factory function for the workflow handler\n *\n * @example Basic usage\n * ```typescript\n * export const createOrder = traceDistributedWorkflow({\n * name: 'OrderFulfillment',\n * workflowIdFrom: (order) => order.id,\n * version: '1.0.0',\n * })(ctx => async (order: Order) => {\n * ctx.recordStepProgress('ValidateOrder', 0);\n * await validateOrder(order);\n *\n * ctx.recordStepProgress('ReserveInventory', 1);\n * await publishToInventoryService(order);\n *\n * return { workflowId: ctx.workflowId, status: 'started' };\n * });\n * ```\n */\nexport function traceDistributedWorkflow<TArgs extends unknown[], TReturn>(\n config: DistributedWorkflowConfig,\n) {\n const spanName = `workflow.${config.name}`;\n\n return (\n fnFactory: (\n ctx: DistributedWorkflowContext,\n ) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>(\n { name: spanName, spanKind: SpanKind.INTERNAL },\n (baseCtx) => {\n return async (...args: TArgs) => {\n // Extract workflow ID from arguments (spread to allow multi-arg access)\n const workflowId = config.workflowIdFrom(...args);\n const startedAt = new Date().toISOString();\n\n // Initialize workflow baggage\n const baggageValues: WorkflowBaggageValues = {\n workflowId,\n workflowName: config.name,\n workflowVersion: config.version,\n stepIndex: 0,\n totalSteps: config.totalSteps,\n parentWorkflowId: config.parentWorkflowId,\n correlationId: config.correlationId,\n priority: config.priority,\n initiatedBy: config.initiatedBy,\n startedAt,\n };\n\n // Set baggage\n WorkflowBaggage.set(baseCtx, baggageValues);\n\n // Set span attributes\n baseCtx.setAttribute('workflow.id', workflowId);\n baseCtx.setAttribute('workflow.name', config.name);\n if (config.version) {\n baseCtx.setAttribute('workflow.version', config.version);\n }\n if (config.totalSteps) {\n baseCtx.setAttribute('workflow.total_steps', config.totalSteps);\n }\n if (config.parentWorkflowId) {\n baseCtx.setAttribute('workflow.parent_id', config.parentWorkflowId);\n }\n if (config.priority) {\n baseCtx.setAttribute('workflow.priority', config.priority);\n }\n if (config.initiatedBy) {\n baseCtx.setAttribute('workflow.initiated_by', config.initiatedBy);\n }\n baseCtx.setAttribute('workflow.started_at', startedAt);\n\n // Apply custom attributes\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n baseCtx.setAttribute(key, value);\n }\n }\n\n // Create extended context\n const workflowCtx: DistributedWorkflowContext = {\n ...baseCtx,\n workflowId,\n workflowName: config.name,\n workflowVersion: config.version,\n\n getWorkflowBaggage(): WorkflowBaggageValues {\n return { ...baggageValues };\n },\n\n setWorkflowBaggage(values: Partial<WorkflowBaggageValues>): void {\n Object.assign(baggageValues, values);\n WorkflowBaggage.set(baseCtx, baggageValues);\n },\n\n getWorkflowHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n const ctx = context.active();\n propagation.inject(ctx, headers);\n return headers;\n },\n\n recordStepProgress(stepName: string, stepIndex: number): void {\n baggageValues.stepName = stepName;\n baggageValues.stepIndex = stepIndex;\n WorkflowBaggage.set(baseCtx, baggageValues);\n\n emitCorrelatedEvent(baseCtx, 'workflow.step_progress', {\n 'workflow.step.name': stepName,\n 'workflow.step.index': stepIndex,\n });\n },\n };\n\n // Call onStart callback\n config.onStart?.(workflowCtx);\n\n // Add start event\n emitCorrelatedEvent(baseCtx, 'workflow.started', {\n 'workflow.id': workflowId,\n 'workflow.name': config.name,\n });\n\n try {\n const userFn = fnFactory(workflowCtx);\n const result = await userFn(...args);\n\n // Call onComplete callback\n config.onComplete?.(workflowCtx, result);\n\n // Add completion event\n emitCorrelatedEvent(baseCtx, 'workflow.completed', {\n 'workflow.id': workflowId,\n });\n\n return result;\n } catch (error) {\n // Call onError callback\n config.onError?.(workflowCtx, error as Error);\n\n // Add error event\n emitCorrelatedEvent(baseCtx, 'workflow.failed', {\n 'workflow.id': workflowId,\n 'workflow.error': (error as Error).message,\n });\n\n throw error;\n }\n };\n },\n );\n };\n}\n\n// ============================================================================\n// Distributed Step Tracer\n// ============================================================================\n\n/**\n * Create a traced distributed workflow step\n *\n * Use in downstream services to trace steps that are part of a distributed workflow.\n * Automatically extracts workflow baggage from the current context.\n *\n * @param config - Step configuration\n * @returns Factory function for the step handler\n *\n * @example Consumer in downstream service\n * ```typescript\n * export const processInventory = traceConsumer({\n * system: 'kafka',\n * destination: 'inventory-requests',\n * extractBaggage: true, // Extracts workflow.* from headers\n * })(ctx => {\n * // Wrap inner logic with traceDistributedStep\n * return traceDistributedStep({\n * name: 'ReserveInventory',\n * })(stepCtx => async (message) => {\n * console.log(`Processing workflow ${stepCtx.workflowId}`);\n * await reserveItems(message.items);\n * })(message);\n * });\n * ```\n *\n * @example Standalone step handler\n * ```typescript\n * export const reserveInventory = traceDistributedStep({\n * name: 'ReserveInventory',\n * idempotent: true,\n * })(ctx => async (request: InventoryRequest) => {\n * if (ctx.workflowId) {\n * console.log(`Part of workflow ${ctx.workflowId}, step ${ctx.stepIndex}`);\n * }\n * return await inventoryService.reserve(request.items);\n * });\n * ```\n */\nexport function traceDistributedStep<TArgs extends unknown[], TReturn>(\n config: DistributedStepConfig,\n) {\n const spanName = `workflow.step.${config.name}`;\n\n return (\n fnFactory: (\n ctx: DistributedStepContext,\n ) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>(\n { name: spanName, spanKind: SpanKind.INTERNAL },\n (baseCtx) => {\n return async (...args: TArgs) => {\n // Extract workflow baggage\n let baggageValues: WorkflowBaggageValues | null = null;\n\n const extractBaggage = config.extractBaggage ?? true;\n if (typeof extractBaggage === 'function') {\n baggageValues = extractBaggage(args);\n } else if (extractBaggage) {\n // Read from current context\n const extracted = WorkflowBaggage.get(baseCtx);\n if (extracted.workflowId && extracted.workflowName) {\n baggageValues = extracted as WorkflowBaggageValues;\n }\n }\n\n // Determine step index\n // If explicit stepIndex provided in config, use it\n // Otherwise, auto-increment from baggage if available\n let stepIndex: number | null;\n if (config.stepIndex !== undefined) {\n stepIndex = config.stepIndex;\n } else if (baggageValues?.stepIndex === undefined) {\n stepIndex = null;\n } else {\n // Auto-increment from previous step\n stepIndex = baggageValues.stepIndex + 1;\n }\n\n // Update baggage with current step\n if (baggageValues) {\n baggageValues.stepName = config.name;\n if (stepIndex !== null) {\n baggageValues.stepIndex = stepIndex;\n }\n WorkflowBaggage.set(baseCtx, baggageValues);\n }\n\n // Set span attributes\n baseCtx.setAttribute('workflow.step.name', config.name);\n if (stepIndex !== null) {\n baseCtx.setAttribute('workflow.step.index', stepIndex);\n }\n if (config.idempotent !== undefined) {\n baseCtx.setAttribute('workflow.step.idempotent', config.idempotent);\n }\n if (config.isCompensation) {\n baseCtx.setAttribute('workflow.step.is_compensation', true);\n }\n\n // Add workflow context attributes if available\n if (baggageValues) {\n baseCtx.setAttribute('workflow.id', baggageValues.workflowId);\n baseCtx.setAttribute('workflow.name', baggageValues.workflowName);\n if (baggageValues.workflowVersion) {\n baseCtx.setAttribute(\n 'workflow.version',\n baggageValues.workflowVersion,\n );\n }\n if (baggageValues.totalSteps) {\n baseCtx.setAttribute(\n 'workflow.total_steps',\n baggageValues.totalSteps,\n );\n }\n }\n\n // Apply custom attributes\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n baseCtx.setAttribute(key, value);\n }\n }\n\n // Compensation data storage\n let compensationData: Record<string, unknown> | undefined;\n\n // Create extended context\n const stepCtx: DistributedStepContext = {\n ...baseCtx,\n workflowId: baggageValues?.workflowId ?? null,\n workflowName: baggageValues?.workflowName ?? null,\n stepName: config.name,\n stepIndex,\n isCompensation: config.isCompensation ?? false,\n\n getWorkflowBaggage(): WorkflowBaggageValues | null {\n return baggageValues ? { ...baggageValues } : null;\n },\n\n updateWorkflowBaggage(\n values: Partial<WorkflowBaggageValues>,\n ): void {\n if (baggageValues) {\n Object.assign(baggageValues, values);\n WorkflowBaggage.set(baseCtx, baggageValues);\n }\n },\n\n getWorkflowHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n const ctx = context.active();\n propagation.inject(ctx, headers);\n return headers;\n },\n\n requiresCompensation(data?: Record<string, unknown>): void {\n compensationData = data;\n baseCtx.setAttribute('workflow.step.requires_compensation', true);\n emitCorrelatedEvent(\n baseCtx,\n 'workflow.step.compensation_registered',\n {\n 'workflow.step.name': config.name,\n ...(data && {\n 'workflow.step.compensation_data': JSON.stringify(data),\n }),\n },\n );\n },\n };\n\n // Call onStart callback\n config.onStart?.(stepCtx);\n\n // Add start event\n emitCorrelatedEvent(baseCtx, 'workflow.step.started', {\n 'workflow.step.name': config.name,\n ...(baggageValues && { 'workflow.id': baggageValues.workflowId }),\n });\n\n try {\n const userFn = fnFactory(stepCtx);\n const result = await userFn(...args);\n\n // Call onComplete callback\n config.onComplete?.(stepCtx, result);\n\n // Add completion event\n emitCorrelatedEvent(baseCtx, 'workflow.step.completed', {\n 'workflow.step.name': config.name,\n });\n\n return result;\n } catch (error) {\n // Call onError callback\n config.onError?.(stepCtx, error as Error);\n\n // Add error event with compensation info if registered\n emitCorrelatedEvent(baseCtx, 'workflow.step.failed', {\n 'workflow.step.name': config.name,\n 'workflow.step.error': (error as Error).message,\n ...(compensationData && {\n 'workflow.step.requires_compensation': true,\n }),\n });\n\n throw error;\n }\n };\n },\n );\n };\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Generate a unique workflow ID\n *\n * @param prefix - Optional prefix for the ID\n * @returns A unique workflow ID\n *\n * @example\n * ```typescript\n * const workflowId = generateWorkflowId('order'); // \"order-abc123def456\"\n * ```\n */\nexport function generateWorkflowId(prefix?: string): string {\n const random = Math.random().toString(36).slice(2, 15);\n const timestamp = Date.now().toString(36);\n const id = `${timestamp}-${random}`;\n return prefix ? `${prefix}-${id}` : id;\n}\n\n/**\n * Check if the current context is part of a distributed workflow\n *\n * @param ctx - The trace context\n * @returns True if workflow baggage is present\n */\nexport function isInDistributedWorkflow(ctx: TraceContext): boolean {\n const baggage = WorkflowBaggage.get(ctx);\n return !!(baggage.workflowId && baggage.workflowName);\n}\n\n/**\n * Get workflow progress information\n *\n * @param ctx - The trace context\n * @returns Progress info or null if not in a workflow\n */\nexport function getWorkflowProgress(ctx: TraceContext): {\n workflowId: string;\n workflowName: string;\n currentStep: string | null;\n currentStepIndex: number | null;\n totalSteps: number | null;\n percentComplete: number | null;\n} | null {\n const baggage = WorkflowBaggage.get(ctx);\n if (!baggage.workflowId || !baggage.workflowName) {\n return null;\n }\n\n const percentComplete =\n baggage.totalSteps && baggage.stepIndex !== undefined\n ? Math.round(((baggage.stepIndex + 1) / baggage.totalSteps) * 100)\n : null;\n\n return {\n workflowId: baggage.workflowId,\n workflowName: baggage.workflowName,\n currentStep: baggage.stepName ?? null,\n currentStepIndex: baggage.stepIndex ?? null,\n totalSteps: baggage.totalSteps ?? null,\n percentComplete,\n };\n}\n\n/**\n * Create workflow correlation headers for manual propagation\n *\n * Use when you need to manually add workflow context to outgoing requests.\n *\n * @param values - Workflow baggage values\n * @returns Headers object with workflow baggage\n *\n * @example\n * ```typescript\n * const headers = createWorkflowHeaders({\n * workflowId: 'order-123',\n * workflowName: 'OrderFulfillment',\n * stepIndex: 2,\n * });\n *\n * await fetch('/api/inventory', { headers });\n * ```\n */\nexport function createWorkflowHeaders(\n values: Partial<WorkflowBaggageValues>,\n): Record<string, string> {\n const headers: Record<string, string> = {};\n\n // Build baggage string\n const baggageEntries: string[] = [];\n\n if (values.workflowId) {\n baggageEntries.push(\n `workflow.workflowId=${encodeURIComponent(values.workflowId)}`,\n );\n }\n if (values.workflowName) {\n baggageEntries.push(\n `workflow.workflowName=${encodeURIComponent(values.workflowName)}`,\n );\n }\n if (values.workflowVersion) {\n baggageEntries.push(\n `workflow.workflowVersion=${encodeURIComponent(values.workflowVersion)}`,\n );\n }\n if (values.stepName) {\n baggageEntries.push(\n `workflow.stepName=${encodeURIComponent(values.stepName)}`,\n );\n }\n if (values.stepIndex !== undefined) {\n baggageEntries.push(`workflow.stepIndex=${values.stepIndex}`);\n }\n if (values.totalSteps !== undefined) {\n baggageEntries.push(`workflow.totalSteps=${values.totalSteps}`);\n }\n if (values.priority) {\n baggageEntries.push(`workflow.priority=${values.priority}`);\n }\n if (values.correlationId) {\n baggageEntries.push(\n `workflow.correlationId=${encodeURIComponent(values.correlationId)}`,\n );\n }\n if (values.parentWorkflowId) {\n baggageEntries.push(\n `workflow.parentWorkflowId=${encodeURIComponent(values.parentWorkflowId)}`,\n );\n }\n if (values.initiatedBy) {\n baggageEntries.push(\n `workflow.initiatedBy=${encodeURIComponent(values.initiatedBy)}`,\n );\n }\n if (values.startedAt) {\n baggageEntries.push(\n `workflow.startedAt=${encodeURIComponent(values.startedAt)}`,\n );\n }\n\n if (baggageEntries.length > 0) {\n headers['baggage'] = baggageEntries.join(',');\n }\n\n return headers;\n}\n\n/**\n * Parse workflow context from baggage header\n *\n * @param baggageHeader - The baggage header value\n * @returns Parsed workflow values or null\n */\nexport function parseWorkflowFromBaggage(\n baggageHeader: string,\n): Partial<WorkflowBaggageValues> | null {\n if (!baggageHeader) {\n return null;\n }\n\n const values: Partial<WorkflowBaggageValues> = {};\n const entries = baggageHeader.split(',');\n\n for (const entry of entries) {\n const [key, value] = entry.trim().split('=');\n if (!key || !value) continue;\n\n const decodedValue = decodeURIComponent(value);\n\n switch (key) {\n case 'workflow.workflowId': {\n values.workflowId = decodedValue;\n break;\n }\n case 'workflow.workflowName': {\n values.workflowName = decodedValue;\n break;\n }\n case 'workflow.workflowVersion': {\n values.workflowVersion = decodedValue;\n break;\n }\n case 'workflow.stepName': {\n values.stepName = decodedValue;\n break;\n }\n case 'workflow.stepIndex': {\n values.stepIndex = Number.parseInt(decodedValue, 10);\n break;\n }\n case 'workflow.totalSteps': {\n values.totalSteps = Number.parseInt(decodedValue, 10);\n break;\n }\n case 'workflow.priority': {\n values.priority = decodedValue as WorkflowBaggageValues['priority'];\n break;\n }\n case 'workflow.correlationId': {\n values.correlationId = decodedValue;\n break;\n }\n case 'workflow.parentWorkflowId': {\n values.parentWorkflowId = decodedValue;\n break;\n }\n case 'workflow.initiatedBy': {\n values.initiatedBy = decodedValue;\n break;\n }\n case 'workflow.startedAt': {\n values.startedAt = decodedValue;\n break;\n }\n }\n }\n\n return Object.keys(values).length > 0 ? values : null;\n}\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { emitCorrelatedEvent } from './chunk-KIL5CUN6.js';
|
|
1
2
|
import { createSafeBaggageSchema } from './chunk-4IFSYQVX.js';
|
|
2
|
-
import { trace } from './chunk-
|
|
3
|
-
import './chunk-
|
|
4
|
-
import './chunk-
|
|
5
|
-
import './chunk-
|
|
6
|
-
import './chunk-BBBWDIYQ.js';
|
|
3
|
+
import { trace } from './chunk-DAAJLUTO.js';
|
|
4
|
+
import './chunk-DSMSIVTG.js';
|
|
5
|
+
import './chunk-SEO6NAQT.js';
|
|
6
|
+
import './chunk-QG3U5ONP.js';
|
|
7
7
|
import './chunk-W35FVJBC.js';
|
|
8
8
|
import './chunk-3SDILILG.js';
|
|
9
9
|
import './chunk-A4E5AQFK.js';
|
|
@@ -121,14 +121,14 @@ function traceDistributedWorkflow(config) {
|
|
|
121
121
|
baggageValues.stepName = stepName;
|
|
122
122
|
baggageValues.stepIndex = stepIndex;
|
|
123
123
|
WorkflowBaggage.set(baseCtx, baggageValues);
|
|
124
|
-
baseCtx
|
|
124
|
+
emitCorrelatedEvent(baseCtx, "workflow.step_progress", {
|
|
125
125
|
"workflow.step.name": stepName,
|
|
126
126
|
"workflow.step.index": stepIndex
|
|
127
127
|
});
|
|
128
128
|
}
|
|
129
129
|
};
|
|
130
130
|
config.onStart?.(workflowCtx);
|
|
131
|
-
baseCtx
|
|
131
|
+
emitCorrelatedEvent(baseCtx, "workflow.started", {
|
|
132
132
|
"workflow.id": workflowId,
|
|
133
133
|
"workflow.name": config.name
|
|
134
134
|
});
|
|
@@ -136,13 +136,13 @@ function traceDistributedWorkflow(config) {
|
|
|
136
136
|
const userFn = fnFactory(workflowCtx);
|
|
137
137
|
const result = await userFn(...args);
|
|
138
138
|
config.onComplete?.(workflowCtx, result);
|
|
139
|
-
baseCtx
|
|
139
|
+
emitCorrelatedEvent(baseCtx, "workflow.completed", {
|
|
140
140
|
"workflow.id": workflowId
|
|
141
141
|
});
|
|
142
142
|
return result;
|
|
143
143
|
} catch (error) {
|
|
144
144
|
config.onError?.(workflowCtx, error);
|
|
145
|
-
baseCtx
|
|
145
|
+
emitCorrelatedEvent(baseCtx, "workflow.failed", {
|
|
146
146
|
"workflow.id": workflowId,
|
|
147
147
|
"workflow.error": error.message
|
|
148
148
|
});
|
|
@@ -242,16 +242,20 @@ function traceDistributedStep(config) {
|
|
|
242
242
|
requiresCompensation(data) {
|
|
243
243
|
compensationData = data;
|
|
244
244
|
baseCtx.setAttribute("workflow.step.requires_compensation", true);
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
245
|
+
emitCorrelatedEvent(
|
|
246
|
+
baseCtx,
|
|
247
|
+
"workflow.step.compensation_registered",
|
|
248
|
+
{
|
|
249
|
+
"workflow.step.name": config.name,
|
|
250
|
+
...data && {
|
|
251
|
+
"workflow.step.compensation_data": JSON.stringify(data)
|
|
252
|
+
}
|
|
249
253
|
}
|
|
250
|
-
|
|
254
|
+
);
|
|
251
255
|
}
|
|
252
256
|
};
|
|
253
257
|
config.onStart?.(stepCtx);
|
|
254
|
-
baseCtx
|
|
258
|
+
emitCorrelatedEvent(baseCtx, "workflow.step.started", {
|
|
255
259
|
"workflow.step.name": config.name,
|
|
256
260
|
...baggageValues && { "workflow.id": baggageValues.workflowId }
|
|
257
261
|
});
|
|
@@ -259,13 +263,13 @@ function traceDistributedStep(config) {
|
|
|
259
263
|
const userFn = fnFactory(stepCtx);
|
|
260
264
|
const result = await userFn(...args);
|
|
261
265
|
config.onComplete?.(stepCtx, result);
|
|
262
|
-
baseCtx
|
|
266
|
+
emitCorrelatedEvent(baseCtx, "workflow.step.completed", {
|
|
263
267
|
"workflow.step.name": config.name
|
|
264
268
|
});
|
|
265
269
|
return result;
|
|
266
270
|
} catch (error) {
|
|
267
271
|
config.onError?.(stepCtx, error);
|
|
268
|
-
baseCtx
|
|
272
|
+
emitCorrelatedEvent(baseCtx, "workflow.step.failed", {
|
|
269
273
|
"workflow.step.name": config.name,
|
|
270
274
|
"workflow.step.error": error.message,
|
|
271
275
|
...compensationData && {
|