autotel 4.0.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +26 -1
  2. package/dist/auto.cjs +2 -2
  3. package/dist/auto.js +1 -1
  4. package/dist/correlation-id.cjs +1 -1
  5. package/dist/correlation-id.js +1 -1
  6. package/dist/decorators.cjs +1 -1
  7. package/dist/decorators.js +1 -1
  8. package/dist/{event-Dlqr4ZNL.cjs → event-BhHREDJk.cjs} +3 -3
  9. package/dist/{event-Dlqr4ZNL.cjs.map → event-BhHREDJk.cjs.map} +1 -1
  10. package/dist/{event-_58ryBjh.js → event-ByBTV9M2.js} +3 -3
  11. package/dist/{event-_58ryBjh.js.map → event-ByBTV9M2.js.map} +1 -1
  12. package/dist/event.cjs +1 -1
  13. package/dist/event.js +1 -1
  14. package/dist/{functional-BGkT8J-h.js → functional-DtI0u4vx.js} +19 -19
  15. package/dist/functional-DtI0u4vx.js.map +1 -0
  16. package/dist/{functional-C4CzoVrX.cjs → functional-zpzNLhky.cjs} +4 -4
  17. package/dist/{functional-C4CzoVrX.cjs.map → functional-zpzNLhky.cjs.map} +1 -1
  18. package/dist/functional.cjs +1 -1
  19. package/dist/functional.js +1 -1
  20. package/dist/http.cjs +1 -1
  21. package/dist/http.js +1 -1
  22. package/dist/index.cjs +5 -5
  23. package/dist/index.d.cts +1 -1
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +5 -5
  26. package/dist/{init-DJQOdVlN.d.ts → init-B7u-DjxM.d.ts} +57 -2
  27. package/dist/init-B7u-DjxM.d.ts.map +1 -0
  28. package/dist/{init-DvapOXCc.cjs → init-BX7AmFRl.cjs} +40 -21
  29. package/dist/init-BX7AmFRl.cjs.map +1 -0
  30. package/dist/{init-Ch6t7MNI.js → init-D-jnNMix.js} +39 -20
  31. package/dist/init-D-jnNMix.js.map +1 -0
  32. package/dist/{init-CNp-ee80.d.cts → init-DSrRmVnz.d.cts} +57 -2
  33. package/dist/init-DSrRmVnz.d.cts.map +1 -0
  34. package/dist/instrumentation.cjs +1 -1
  35. package/dist/instrumentation.js +1 -1
  36. package/dist/logger-D3Ej3DII.js +446 -0
  37. package/dist/logger-D3Ej3DII.js.map +1 -0
  38. package/dist/logger-thMPLpOG.cjs +487 -0
  39. package/dist/logger-thMPLpOG.cjs.map +1 -0
  40. package/dist/logger.cjs +8 -236
  41. package/dist/logger.js +2 -204
  42. package/dist/messaging.cjs +1 -1
  43. package/dist/messaging.js +1 -1
  44. package/dist/semantic-helpers.cjs +1 -1
  45. package/dist/semantic-helpers.js +1 -1
  46. package/dist/{track-3HY4NGV-.cjs → track-D59FfpL0.cjs} +2 -2
  47. package/dist/{track-3HY4NGV-.cjs.map → track-D59FfpL0.cjs.map} +1 -1
  48. package/dist/{track-nsKVy-pj.js → track-wc0HafS_.js} +6 -6
  49. package/dist/track-wc0HafS_.js.map +1 -0
  50. package/dist/webhook.cjs +1 -1
  51. package/dist/webhook.js +1 -1
  52. package/dist/workflow-distributed.cjs +1 -1
  53. package/dist/workflow-distributed.js +1 -1
  54. package/dist/workflow.cjs +1 -1
  55. package/dist/workflow.js +1 -1
  56. package/dist/{yaml-config-B3dQ82GR.cjs → yaml-config-Ck2uB0Dp.cjs} +2 -1
  57. package/dist/yaml-config-Ck2uB0Dp.cjs.map +1 -0
  58. package/dist/yaml-config.cjs +1 -1
  59. package/dist/yaml-config.d.cts +7 -1
  60. package/dist/yaml-config.d.cts.map +1 -1
  61. package/dist/yaml-config.d.ts +7 -1
  62. package/dist/yaml-config.d.ts.map +1 -1
  63. package/dist/yaml-config.js +1 -0
  64. package/dist/yaml-config.js.map +1 -1
  65. package/package.json +1 -2
  66. package/skills/autotel-core/SKILL.md +2 -0
  67. package/skills/autotel-instrumentation/SKILL.md +25 -0
  68. package/skills/debug-missing-spans/SKILL.md +3 -1
  69. package/skills/migrate-to-autotel/SKILL.md +24 -23
  70. package/skills/review-otel-patterns/SKILL.md +5 -4
  71. package/dist/functional-BGkT8J-h.js.map +0 -1
  72. package/dist/init-CNp-ee80.d.cts.map +0 -1
  73. package/dist/init-Ch6t7MNI.js.map +0 -1
  74. package/dist/init-DJQOdVlN.d.ts.map +0 -1
  75. package/dist/init-DvapOXCc.cjs.map +0 -1
  76. package/dist/logger.cjs.map +0 -1
  77. package/dist/logger.js.map +0 -1
  78. package/dist/track-nsKVy-pj.js.map +0 -1
  79. package/dist/yaml-config-B3dQ82GR.cjs.map +0 -1
  80. package/src/attribute-redacting-processor.test.ts +0 -763
  81. package/src/attribute-redacting-processor.ts +0 -621
  82. package/src/attributes/attachers.ts +0 -161
  83. package/src/attributes/builders.ts +0 -529
  84. package/src/attributes/domains.ts +0 -42
  85. package/src/attributes/index.ts +0 -81
  86. package/src/attributes/registry.ts +0 -323
  87. package/src/attributes/types.ts +0 -211
  88. package/src/attributes/utils.ts +0 -64
  89. package/src/attributes/validators.ts +0 -266
  90. package/src/attributes.test.ts +0 -292
  91. package/src/auto.ts +0 -67
  92. package/src/autotel-logger.test.ts +0 -548
  93. package/src/autotel-logger.ts +0 -364
  94. package/src/baggage-span-processor.test.ts +0 -202
  95. package/src/baggage-span-processor.ts +0 -100
  96. package/src/business-baggage.test.ts +0 -500
  97. package/src/business-baggage.ts +0 -669
  98. package/src/circuit-breaker.test.ts +0 -341
  99. package/src/circuit-breaker.ts +0 -184
  100. package/src/config.test.ts +0 -94
  101. package/src/config.ts +0 -172
  102. package/src/correlated-events.test.ts +0 -151
  103. package/src/correlated-events.ts +0 -47
  104. package/src/correlation-id.test.ts +0 -163
  105. package/src/correlation-id.ts +0 -206
  106. package/src/db.test.ts +0 -252
  107. package/src/db.ts +0 -447
  108. package/src/decorators.test.ts +0 -153
  109. package/src/decorators.ts +0 -188
  110. package/src/define-event.test.ts +0 -41
  111. package/src/define-event.ts +0 -58
  112. package/src/devtools.ts +0 -60
  113. package/src/drain-pipeline.test.ts +0 -68
  114. package/src/drain-pipeline.ts +0 -199
  115. package/src/drain-toolkit.test.ts +0 -113
  116. package/src/drain-toolkit.ts +0 -129
  117. package/src/enricher-toolkit.test.ts +0 -67
  118. package/src/enricher-toolkit.ts +0 -79
  119. package/src/enrichers.test.ts +0 -150
  120. package/src/enrichers.ts +0 -145
  121. package/src/env-config.test.ts +0 -323
  122. package/src/env-config.ts +0 -309
  123. package/src/error-catalog.test.ts +0 -133
  124. package/src/error-catalog.ts +0 -262
  125. package/src/event-queue.test.ts +0 -864
  126. package/src/event-queue.ts +0 -699
  127. package/src/event-subscriber.ts +0 -262
  128. package/src/event-testing.ts +0 -197
  129. package/src/event.test.ts +0 -1104
  130. package/src/event.ts +0 -988
  131. package/src/events-config.ts +0 -235
  132. package/src/exporters.ts +0 -165
  133. package/src/filtering-span-processor.test.ts +0 -281
  134. package/src/filtering-span-processor.ts +0 -111
  135. package/src/flatten-attributes.test.ts +0 -76
  136. package/src/flatten-attributes.ts +0 -80
  137. package/src/functional.strict-types.typecheck.ts +0 -53
  138. package/src/functional.test.ts +0 -1464
  139. package/src/functional.ts +0 -2539
  140. package/src/functional.types.test.ts +0 -135
  141. package/src/hook.mjs +0 -15
  142. package/src/http.test.ts +0 -485
  143. package/src/http.ts +0 -424
  144. package/src/index.ts +0 -433
  145. package/src/init-auto-redactor.test.ts +0 -53
  146. package/src/init-redactor.test.ts +0 -8
  147. package/src/init.customization.test.ts +0 -594
  148. package/src/init.integrations.test.ts +0 -399
  149. package/src/init.openllmetry.test.ts +0 -194
  150. package/src/init.protocol.test.ts +0 -215
  151. package/src/init.ts +0 -2312
  152. package/src/instrumentation.test.ts +0 -108
  153. package/src/instrumentation.ts +0 -319
  154. package/src/logger.test.ts +0 -125
  155. package/src/logger.ts +0 -341
  156. package/src/messaging-adapters.test.ts +0 -595
  157. package/src/messaging-adapters.ts +0 -583
  158. package/src/messaging-testing.test.ts +0 -573
  159. package/src/messaging-testing.ts +0 -935
  160. package/src/messaging.test.ts +0 -1646
  161. package/src/messaging.ts +0 -2245
  162. package/src/metric-helpers.ts +0 -47
  163. package/src/metric-testing.ts +0 -197
  164. package/src/metric.ts +0 -446
  165. package/src/metrics.test.ts +0 -241
  166. package/src/node-require.ts +0 -123
  167. package/src/operation-context.ts +0 -93
  168. package/src/parse-error.test.ts +0 -73
  169. package/src/parse-error.ts +0 -112
  170. package/src/posthog-logs.test.ts +0 -115
  171. package/src/posthog-logs.ts +0 -77
  172. package/src/pretty-console-exporter.test.ts +0 -545
  173. package/src/pretty-console-exporter.ts +0 -413
  174. package/src/pretty-log-formatter.test.ts +0 -123
  175. package/src/pretty-log-formatter.ts +0 -210
  176. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  177. package/src/processors/canonical-log-line-processor.ts +0 -396
  178. package/src/processors.ts +0 -152
  179. package/src/rate-limiter.test.ts +0 -199
  180. package/src/rate-limiter.ts +0 -98
  181. package/src/redact-values.test.ts +0 -90
  182. package/src/redact-values.ts +0 -34
  183. package/src/register.ts +0 -37
  184. package/src/request-logger.test.ts +0 -545
  185. package/src/request-logger.ts +0 -342
  186. package/src/sampling.test.ts +0 -1060
  187. package/src/sampling.ts +0 -737
  188. package/src/security-schema.test.ts +0 -45
  189. package/src/security-schema.ts +0 -107
  190. package/src/semantic-conventions.ts +0 -15
  191. package/src/semantic-helpers.test.ts +0 -226
  192. package/src/semantic-helpers.ts +0 -438
  193. package/src/shutdown.test.ts +0 -364
  194. package/src/shutdown.ts +0 -246
  195. package/src/span-name-normalizer.test.ts +0 -377
  196. package/src/span-name-normalizer.ts +0 -213
  197. package/src/stable-hash.ts +0 -27
  198. package/src/structured-error.test.ts +0 -191
  199. package/src/structured-error.ts +0 -157
  200. package/src/stub.integration.test.ts +0 -361
  201. package/src/tail-sampling-processor.test.ts +0 -230
  202. package/src/tail-sampling-processor.ts +0 -55
  203. package/src/test-span-collector.test.ts +0 -234
  204. package/src/test-span-collector.ts +0 -150
  205. package/src/testing.ts +0 -705
  206. package/src/trace-context.test.ts +0 -73
  207. package/src/trace-context.ts +0 -567
  208. package/src/trace-helpers.new.test.ts +0 -278
  209. package/src/trace-helpers.test.ts +0 -290
  210. package/src/trace-helpers.ts +0 -710
  211. package/src/trace-hybrid.test.ts +0 -42
  212. package/src/trace-hybrid.ts +0 -37
  213. package/src/tracer-provider.test.ts +0 -183
  214. package/src/tracer-provider.ts +0 -266
  215. package/src/track.test.ts +0 -154
  216. package/src/track.ts +0 -216
  217. package/src/validate.test.ts +0 -287
  218. package/src/validate.ts +0 -307
  219. package/src/validation-attributes.ts +0 -43
  220. package/src/validation.test.ts +0 -330
  221. package/src/validation.ts +0 -246
  222. package/src/variable-name-inference.test.ts +0 -178
  223. package/src/variable-name-inference.ts +0 -242
  224. package/src/webhook.test.ts +0 -649
  225. package/src/webhook.ts +0 -637
  226. package/src/workflow-distributed.test.ts +0 -786
  227. package/src/workflow-distributed.ts +0 -916
  228. package/src/workflow.async-safety.integration.test.ts +0 -345
  229. package/src/workflow.test.ts +0 -647
  230. package/src/workflow.ts +0 -810
  231. package/src/yaml-config.test.ts +0 -337
  232. package/src/yaml-config.ts +0 -342
@@ -1,649 +0,0 @@
1
- import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
- import {
3
- createParkingLot,
4
- InMemoryTraceContextStore,
5
- createCorrelationKey,
6
- toSpanContext,
7
- type StoredTraceContext,
8
- type CallbackContext,
9
- } from './webhook';
10
-
11
- // Mock the functional trace
12
- vi.mock('./functional', () => ({
13
- trace: vi.fn((options, factory) => {
14
- return (...args: unknown[]) => {
15
- const mockCtx = createMockTraceContext();
16
- const fn = factory(mockCtx);
17
- return fn(...args);
18
- };
19
- }),
20
- }));
21
-
22
- // Mock OpenTelemetry trace
23
- vi.mock('@opentelemetry/api', () => ({
24
- SpanKind: { SERVER: 1, CLIENT: 2, PRODUCER: 3, CONSUMER: 4 },
25
- SpanStatusCode: { OK: 1, ERROR: 2 },
26
- trace: {
27
- getActiveSpan: vi.fn(() => ({
28
- spanContext: () => ({
29
- traceId: '00000000000000000000000000000001',
30
- spanId: '0000000000000002',
31
- traceFlags: 1,
32
- }),
33
- addEvent: vi.fn(),
34
- })),
35
- },
36
- context: {
37
- active: vi.fn(),
38
- },
39
- }));
40
-
41
- function createMockTraceContext() {
42
- return {
43
- setAttribute: vi.fn(),
44
- setAttributes: vi.fn(),
45
- addEvent: vi.fn(),
46
- addLinks: vi.fn(),
47
- recordException: vi.fn(),
48
- setStatus: vi.fn(),
49
- getSpan: vi.fn(),
50
- getSpanContext: vi.fn(() => ({
51
- traceId: '00000000000000000000000000000001',
52
- spanId: '0000000000000002',
53
- traceFlags: 1,
54
- })),
55
- };
56
- }
57
-
58
- describe('Webhook Parking Lot', () => {
59
- let store: InMemoryTraceContextStore;
60
- let parkingLot: ReturnType<typeof createParkingLot>;
61
-
62
- beforeEach(() => {
63
- vi.clearAllMocks();
64
- store = new InMemoryTraceContextStore({ cleanupIntervalMs: 0 }); // Disable auto-cleanup for tests
65
- parkingLot = createParkingLot({
66
- store,
67
- defaultTTLMs: 60_000, // 1 minute for tests
68
- });
69
- });
70
-
71
- afterEach(() => {
72
- store.destroy();
73
- store.clear();
74
- });
75
-
76
- describe('InMemoryTraceContextStore', () => {
77
- it('should save and load context', async () => {
78
- const context: StoredTraceContext = {
79
- traceId: 'trace-123',
80
- spanId: 'span-456',
81
- traceFlags: 1,
82
- parkedAt: Date.now(),
83
- };
84
-
85
- await store.save('test-key', context);
86
- const loaded = await store.load('test-key');
87
-
88
- expect(loaded).toEqual(context);
89
- });
90
-
91
- it('should return null for non-existent key', async () => {
92
- const loaded = await store.load('non-existent');
93
- expect(loaded).toBeNull();
94
- });
95
-
96
- it('should delete context', async () => {
97
- const context: StoredTraceContext = {
98
- traceId: 'trace-123',
99
- spanId: 'span-456',
100
- traceFlags: 1,
101
- parkedAt: Date.now(),
102
- };
103
-
104
- await store.save('test-key', context);
105
- await store.delete('test-key');
106
- const loaded = await store.load('test-key');
107
-
108
- expect(loaded).toBeNull();
109
- });
110
-
111
- it('should expire contexts based on TTL', async () => {
112
- const context: StoredTraceContext = {
113
- traceId: 'trace-123',
114
- spanId: 'span-456',
115
- traceFlags: 1,
116
- parkedAt: Date.now() - 120_000, // 2 minutes ago
117
- ttlMs: 60_000, // 1 minute TTL
118
- };
119
-
120
- await store.save('test-key', context);
121
- const loaded = await store.load('test-key');
122
-
123
- expect(loaded).toBeNull(); // Should be expired
124
- });
125
-
126
- it('should not expire contexts within TTL', async () => {
127
- const context: StoredTraceContext = {
128
- traceId: 'trace-123',
129
- spanId: 'span-456',
130
- traceFlags: 1,
131
- parkedAt: Date.now() - 30_000, // 30 seconds ago
132
- ttlMs: 60_000, // 1 minute TTL
133
- };
134
-
135
- await store.save('test-key', context);
136
- const loaded = await store.load('test-key');
137
-
138
- expect(loaded).toEqual(context);
139
- });
140
-
141
- it('should track size', async () => {
142
- expect(store.size).toBe(0);
143
-
144
- await store.save('key1', {
145
- traceId: 't1',
146
- spanId: 's1',
147
- traceFlags: 1,
148
- parkedAt: Date.now(),
149
- });
150
- expect(store.size).toBe(1);
151
-
152
- await store.save('key2', {
153
- traceId: 't2',
154
- spanId: 's2',
155
- traceFlags: 1,
156
- parkedAt: Date.now(),
157
- });
158
- expect(store.size).toBe(2);
159
-
160
- await store.delete('key1');
161
- expect(store.size).toBe(1);
162
- });
163
-
164
- it('should clear all contexts', async () => {
165
- await store.save('key1', {
166
- traceId: 't1',
167
- spanId: 's1',
168
- traceFlags: 1,
169
- parkedAt: Date.now(),
170
- });
171
- await store.save('key2', {
172
- traceId: 't2',
173
- spanId: 's2',
174
- traceFlags: 1,
175
- parkedAt: Date.now(),
176
- });
177
-
178
- expect(store.size).toBe(2);
179
- store.clear();
180
- expect(store.size).toBe(0);
181
- });
182
- });
183
-
184
- describe('createParkingLot', () => {
185
- it('should create parking lot with default config', () => {
186
- const lot = createParkingLot({ store });
187
- expect(lot).toBeDefined();
188
- expect(lot.park).toBeInstanceOf(Function);
189
- expect(lot.retrieve).toBeInstanceOf(Function);
190
- expect(lot.traceCallback).toBeInstanceOf(Function);
191
- expect(lot.createLink).toBeInstanceOf(Function);
192
- expect(lot.exists).toBeInstanceOf(Function);
193
- });
194
-
195
- it('should use custom key prefix', async () => {
196
- const customStore = new InMemoryTraceContextStore({
197
- cleanupIntervalMs: 0,
198
- });
199
- const lot = createParkingLot({
200
- store: customStore,
201
- keyPrefix: 'custom:',
202
- });
203
-
204
- await lot.park('test-key');
205
-
206
- // Should be stored with custom prefix
207
- const loaded = await customStore.load('custom:test-key');
208
- expect(loaded).not.toBeNull();
209
-
210
- customStore.destroy();
211
- });
212
- });
213
-
214
- describe('park()', () => {
215
- it('should park current trace context', async () => {
216
- const key = await parkingLot.park('payment:order-123');
217
-
218
- // park() returns the unprefixed key for use with retrieve()
219
- expect(key).toBe('payment:order-123');
220
-
221
- // Store uses prefixed key internally
222
- const stored = await store.load(`parkingLot:${key}`);
223
- expect(stored).not.toBeNull();
224
- expect(stored?.traceId).toBe('00000000000000000000000000000001');
225
- expect(stored?.spanId).toBe('0000000000000002');
226
- expect(stored?.traceFlags).toBe(1);
227
- });
228
-
229
- it('should store metadata', async () => {
230
- const key = await parkingLot.park('payment:order-123', {
231
- customerId: 'cust-456',
232
- amount: '99.99',
233
- });
234
-
235
- // park() returns the unprefixed key; store uses prefixed key internally
236
- const stored = await store.load(`parkingLot:${key}`);
237
- expect(stored?.metadata).toEqual({
238
- customerId: 'cust-456',
239
- amount: '99.99',
240
- });
241
- });
242
-
243
- it('should set parkedAt timestamp', async () => {
244
- const beforePark = Date.now();
245
- const key = await parkingLot.park('test-key');
246
- const afterPark = Date.now();
247
-
248
- const stored = await store.load(`parkingLot:${key}`);
249
- expect(stored?.parkedAt).toBeGreaterThanOrEqual(beforePark);
250
- expect(stored?.parkedAt).toBeLessThanOrEqual(afterPark);
251
- });
252
-
253
- it('should set TTL from config', async () => {
254
- const key = await parkingLot.park('test-key');
255
-
256
- const stored = await store.load(`parkingLot:${key}`);
257
- expect(stored?.ttlMs).toBe(60_000); // From config
258
- });
259
- });
260
-
261
- describe('retrieve()', () => {
262
- it('should retrieve parked context', async () => {
263
- await parkingLot.park('payment:order-123', { orderId: 'order-123' });
264
-
265
- const retrieved = await parkingLot.retrieve('payment:order-123');
266
-
267
- expect(retrieved).not.toBeNull();
268
- expect(retrieved?.traceId).toBe('00000000000000000000000000000001');
269
- expect(retrieved?.metadata?.orderId).toBe('order-123');
270
- });
271
-
272
- it('should return null for non-existent key', async () => {
273
- const retrieved = await parkingLot.retrieve('non-existent');
274
- expect(retrieved).toBeNull();
275
- });
276
-
277
- it('should auto-delete after retrieval by default', async () => {
278
- await parkingLot.park('payment:order-123');
279
-
280
- // First retrieval should work
281
- const first = await parkingLot.retrieve('payment:order-123');
282
- expect(first).not.toBeNull();
283
-
284
- // Second retrieval should return null
285
- const second = await parkingLot.retrieve('payment:order-123');
286
- expect(second).toBeNull();
287
- });
288
-
289
- it('should not auto-delete when disabled', async () => {
290
- const lot = createParkingLot({
291
- store,
292
- autoDeleteOnRetrieve: false,
293
- });
294
-
295
- await lot.park('payment:order-123');
296
-
297
- // Multiple retrievals should work
298
- const first = await lot.retrieve('payment:order-123');
299
- const second = await lot.retrieve('payment:order-123');
300
-
301
- expect(first).not.toBeNull();
302
- expect(second).not.toBeNull();
303
- });
304
-
305
- it('should call onMiss callback when context not found', async () => {
306
- const onMiss = vi.fn();
307
- const lot = createParkingLot({
308
- store,
309
- onMiss,
310
- });
311
-
312
- await lot.retrieve('non-existent');
313
-
314
- expect(onMiss).toHaveBeenCalledWith('non-existent');
315
- });
316
- });
317
-
318
- describe('exists()', () => {
319
- it('should return true for existing context', async () => {
320
- await parkingLot.park('payment:order-123');
321
-
322
- const exists = await parkingLot.exists('payment:order-123');
323
- expect(exists).toBe(true);
324
- });
325
-
326
- it('should return false for non-existent context', async () => {
327
- const exists = await parkingLot.exists('non-existent');
328
- expect(exists).toBe(false);
329
- });
330
-
331
- it('should not delete context when checking existence', async () => {
332
- await parkingLot.park('payment:order-123');
333
-
334
- // Check multiple times
335
- await parkingLot.exists('payment:order-123');
336
- await parkingLot.exists('payment:order-123');
337
-
338
- // Should still exist
339
- const retrieved = await parkingLot.retrieve('payment:order-123');
340
- expect(retrieved).not.toBeNull();
341
- });
342
- });
343
-
344
- describe('createLink()', () => {
345
- it('should create span link from stored context', () => {
346
- const stored: StoredTraceContext = {
347
- traceId: 'trace-123',
348
- spanId: 'span-456',
349
- traceFlags: 1,
350
- parkedAt: Date.now(),
351
- metadata: { key: 'value' },
352
- };
353
-
354
- const link = parkingLot.createLink(stored);
355
-
356
- expect(link.context.traceId).toBe('trace-123');
357
- expect(link.context.spanId).toBe('span-456');
358
- expect(link.context.traceFlags).toBe(1);
359
- expect(link.context.isRemote).toBe(true);
360
- expect(link.attributes?.['link.type']).toBe('parking_lot');
361
- expect(link.attributes?.['parking_lot.parked_at']).toBe(stored.parkedAt);
362
- expect(link.attributes?.['parking_lot.has_metadata']).toBe(true);
363
- });
364
-
365
- it('should not include has_metadata when no metadata', () => {
366
- const stored: StoredTraceContext = {
367
- traceId: 'trace-123',
368
- spanId: 'span-456',
369
- traceFlags: 1,
370
- parkedAt: Date.now(),
371
- };
372
-
373
- const link = parkingLot.createLink(stored);
374
-
375
- expect(link.attributes?.['parking_lot.has_metadata']).toBeUndefined();
376
- });
377
- });
378
-
379
- describe('traceCallback()', () => {
380
- it('should create traced callback function', async () => {
381
- await parkingLot.park('payment:order-123');
382
-
383
- const handler = parkingLot.traceCallback({
384
- name: 'webhook.payment.completed',
385
- correlationKeyFrom: (args) =>
386
- `payment:${(args[0] as { orderId: string }).orderId}`,
387
- })((_ctx) => async (event: { orderId: string }) => {
388
- return { processed: true, orderId: event.orderId };
389
- });
390
-
391
- const result = await handler({ orderId: 'order-123' });
392
-
393
- expect(result).toEqual({ processed: true, orderId: 'order-123' });
394
- });
395
-
396
- it('should provide parked context to handler', async () => {
397
- await parkingLot.park('payment:order-123', { customerId: 'cust-456' });
398
-
399
- let capturedCtx: CallbackContext | null = null;
400
-
401
- const handler = parkingLot.traceCallback({
402
- name: 'webhook.test',
403
- correlationKeyFrom: () => 'payment:order-123',
404
- })((ctx) => async () => {
405
- capturedCtx = ctx;
406
- return {};
407
- });
408
-
409
- await handler();
410
-
411
- expect(capturedCtx).not.toBeNull();
412
- expect(capturedCtx?.parkedContext).not.toBeNull();
413
- expect(capturedCtx?.parkedContext?.metadata?.customerId).toBe('cust-456');
414
- expect(capturedCtx?.correlationKey).toBe('payment:order-123');
415
- });
416
-
417
- it('should calculate elapsed time', async () => {
418
- // Park with a timestamp in the past
419
- const parkedAt = Date.now() - 5000; // 5 seconds ago
420
- await store.save('parkingLot:payment:order-123', {
421
- traceId: 't1',
422
- spanId: 's1',
423
- traceFlags: 1,
424
- parkedAt,
425
- ttlMs: 60_000,
426
- });
427
-
428
- let capturedElapsed: number | null = null;
429
-
430
- const handler = parkingLot.traceCallback({
431
- name: 'webhook.test',
432
- correlationKeyFrom: () => 'payment:order-123',
433
- })((ctx) => async () => {
434
- capturedElapsed = ctx.elapsedMs;
435
- return {};
436
- });
437
-
438
- await handler();
439
-
440
- expect(capturedElapsed).not.toBeNull();
441
- expect(capturedElapsed).toBeGreaterThanOrEqual(5000);
442
- expect(capturedElapsed).toBeLessThan(6000); // Should be close to 5 seconds
443
- });
444
-
445
- it('should handle missing parked context gracefully', async () => {
446
- let capturedCtx: CallbackContext | null = null;
447
-
448
- const handler = parkingLot.traceCallback({
449
- name: 'webhook.test',
450
- correlationKeyFrom: () => 'non-existent',
451
- })((ctx) => async () => {
452
- capturedCtx = ctx;
453
- return {};
454
- });
455
-
456
- await handler();
457
-
458
- expect(capturedCtx?.parkedContext).toBeNull();
459
- expect(capturedCtx?.elapsedMs).toBeNull();
460
- });
461
-
462
- it('should throw when requireParkedContext is true and context missing', async () => {
463
- const handler = parkingLot.traceCallback({
464
- name: 'webhook.test',
465
- correlationKeyFrom: () => 'non-existent',
466
- requireParkedContext: true,
467
- })((_ctx) => async () => {
468
- return {};
469
- });
470
-
471
- await expect(handler()).rejects.toThrow(
472
- 'Required parked context not found for key: non-existent',
473
- );
474
- });
475
-
476
- it('should apply custom attributes', async () => {
477
- await parkingLot.park('payment:order-123');
478
-
479
- const mockCtx = createMockTraceContext();
480
- vi.mocked(
481
- await import('./functional').then((m) => m.trace),
482
- ).mockImplementationOnce((options, factory) => {
483
- return (...args: unknown[]) => {
484
- const fn = factory(mockCtx as any);
485
- return fn(...args);
486
- };
487
- });
488
-
489
- const handler = parkingLot.traceCallback({
490
- name: 'webhook.test',
491
- correlationKeyFrom: () => 'payment:order-123',
492
- attributes: {
493
- 'webhook.provider': 'stripe',
494
- 'webhook.version': 2,
495
- },
496
- })((_ctx) => async () => {
497
- return {};
498
- });
499
-
500
- await handler();
501
-
502
- // Attributes should be set (verified via mock)
503
- });
504
- });
505
-
506
- describe('Utility Functions', () => {
507
- describe('createCorrelationKey()', () => {
508
- it('should join string parts with colon', () => {
509
- const key = createCorrelationKey('payment', 'order-123', 'stripe');
510
- expect(key).toBe('payment:order-123:stripe');
511
- });
512
-
513
- it('should handle numeric parts', () => {
514
- const key = createCorrelationKey('user', 12_345, 'session');
515
- expect(key).toBe('user:12345:session');
516
- });
517
-
518
- it('should handle single part', () => {
519
- const key = createCorrelationKey('simple');
520
- expect(key).toBe('simple');
521
- });
522
- });
523
-
524
- describe('toSpanContext()', () => {
525
- it('should convert stored context to span context', () => {
526
- const stored: StoredTraceContext = {
527
- traceId: 'trace-123',
528
- spanId: 'span-456',
529
- traceFlags: 1,
530
- parkedAt: Date.now(),
531
- };
532
-
533
- const spanContext = toSpanContext(stored);
534
-
535
- expect(spanContext.traceId).toBe('trace-123');
536
- expect(spanContext.spanId).toBe('span-456');
537
- expect(spanContext.traceFlags).toBe(1);
538
- expect(spanContext.isRemote).toBe(true);
539
- });
540
- });
541
- });
542
-
543
- describe('Integration Scenarios', () => {
544
- it('should handle Stripe payment webhook flow', async () => {
545
- // 1. Initiate payment (park context)
546
- const orderId = 'order-12345';
547
- await parkingLot.park(`payment:${orderId}`, {
548
- orderId,
549
- amount: '99.99',
550
- currency: 'USD',
551
- });
552
-
553
- // 2. Simulate time passing (webhook arrives later)
554
- const parkedContext = await store.load(`parkingLot:payment:${orderId}`);
555
- expect(parkedContext).not.toBeNull();
556
-
557
- // 3. Handle webhook callback
558
- let webhookCtx: CallbackContext | null = null;
559
- const handleWebhook = parkingLot.traceCallback({
560
- name: 'stripe.webhook.payment_intent.succeeded',
561
- correlationKeyFrom: (args) => {
562
- const event = args[0] as {
563
- data: { object: { metadata: { orderId: string } } };
564
- };
565
- return `payment:${event.data.object.metadata.orderId}`;
566
- },
567
- })((ctx) => async (_event) => {
568
- webhookCtx = ctx;
569
- // Process payment...
570
- return { success: true };
571
- });
572
-
573
- const result = await handleWebhook({
574
- type: 'payment_intent.succeeded',
575
- data: {
576
- object: {
577
- metadata: { orderId },
578
- },
579
- },
580
- });
581
-
582
- expect(result).toEqual({ success: true });
583
- expect(webhookCtx?.parkedContext?.metadata?.amount).toBe('99.99');
584
- expect(webhookCtx?.correlationKey).toBe(`payment:${orderId}`);
585
- });
586
-
587
- it('should handle human approval workflow', async () => {
588
- // 1. Request approval (park context)
589
- const requestId = 'approval-req-001';
590
- await parkingLot.park(`approval:${requestId}`, {
591
- requestType: 'expense',
592
- amount: '5000',
593
- requester: 'john@example.com',
594
- });
595
-
596
- // 2. Human approves via UI (simulated)
597
-
598
- // 3. Handle approval callback
599
- const handleApproval = parkingLot.traceCallback({
600
- name: 'approval.callback',
601
- correlationKeyFrom: (args) =>
602
- `approval:${(args[0] as { requestId: string }).requestId}`,
603
- })(
604
- (ctx) => async (approval: { requestId: string; approved: boolean }) => {
605
- const metadata = ctx.parkedContext?.metadata;
606
- return {
607
- processed: true,
608
- amount: metadata?.amount,
609
- approved: approval.approved,
610
- };
611
- },
612
- );
613
-
614
- const result = await handleApproval({
615
- requestId,
616
- approved: true,
617
- });
618
-
619
- expect(result).toEqual({
620
- processed: true,
621
- amount: '5000',
622
- approved: true,
623
- });
624
- });
625
-
626
- it('should handle multiple concurrent parked contexts', async () => {
627
- // Park multiple contexts
628
- await Promise.all([
629
- parkingLot.park('order:1', { status: 'pending' }),
630
- parkingLot.park('order:2', { status: 'pending' }),
631
- parkingLot.park('order:3', { status: 'pending' }),
632
- ]);
633
-
634
- // Verify all are stored
635
- expect(await parkingLot.exists('order:1')).toBe(true);
636
- expect(await parkingLot.exists('order:2')).toBe(true);
637
- expect(await parkingLot.exists('order:3')).toBe(true);
638
-
639
- // Retrieve in different order
640
- const ctx2 = await parkingLot.retrieve('order:2');
641
- const ctx1 = await parkingLot.retrieve('order:1');
642
- const ctx3 = await parkingLot.retrieve('order:3');
643
-
644
- expect(ctx1?.metadata?.status).toBe('pending');
645
- expect(ctx2?.metadata?.status).toBe('pending');
646
- expect(ctx3?.metadata?.status).toBe('pending');
647
- });
648
- });
649
- });