@zdavison/matador 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/cli.ts +453 -0
  2. package/dist/checkpoint/context.d.ts +59 -0
  3. package/dist/checkpoint/context.d.ts.map +1 -0
  4. package/dist/checkpoint/context.js +140 -0
  5. package/dist/checkpoint/context.test.d.ts +2 -0
  6. package/dist/checkpoint/context.test.d.ts.map +1 -0
  7. package/dist/checkpoint/context.test.js +424 -0
  8. package/dist/checkpoint/index.d.ts +7 -0
  9. package/dist/checkpoint/index.d.ts.map +1 -0
  10. package/dist/checkpoint/index.js +6 -0
  11. package/dist/checkpoint/stores/memory.d.ts +29 -0
  12. package/dist/checkpoint/stores/memory.d.ts.map +1 -0
  13. package/dist/checkpoint/stores/memory.js +39 -0
  14. package/dist/checkpoint/stores/noop.d.ts +14 -0
  15. package/dist/checkpoint/stores/noop.d.ts.map +1 -0
  16. package/dist/checkpoint/stores/noop.js +18 -0
  17. package/dist/checkpoint/stores/stores.test.d.ts +2 -0
  18. package/dist/checkpoint/stores/stores.test.d.ts.map +1 -0
  19. package/dist/checkpoint/stores/stores.test.js +146 -0
  20. package/dist/checkpoint/types.d.ts +119 -0
  21. package/dist/checkpoint/types.d.ts.map +1 -0
  22. package/dist/checkpoint/types.js +1 -0
  23. package/dist/codec/codec.d.ts +29 -0
  24. package/dist/codec/codec.d.ts.map +1 -0
  25. package/dist/codec/codec.js +15 -0
  26. package/dist/codec/header-aware-codec.d.ts +36 -0
  27. package/dist/codec/header-aware-codec.d.ts.map +1 -0
  28. package/dist/codec/header-aware-codec.js +1 -0
  29. package/dist/codec/index.d.ts +6 -0
  30. package/dist/codec/index.d.ts.map +1 -0
  31. package/dist/codec/index.js +3 -0
  32. package/dist/codec/json-codec.d.ts +13 -0
  33. package/dist/codec/json-codec.d.ts.map +1 -0
  34. package/dist/codec/json-codec.js +64 -0
  35. package/dist/codec/rabbitmq-codec.d.ts +28 -0
  36. package/dist/codec/rabbitmq-codec.d.ts.map +1 -0
  37. package/dist/codec/rabbitmq-codec.js +242 -0
  38. package/dist/codec/rabbitmq-codec.test.d.ts +2 -0
  39. package/dist/codec/rabbitmq-codec.test.d.ts.map +1 -0
  40. package/dist/codec/rabbitmq-codec.test.js +433 -0
  41. package/dist/core/fanout.d.ts +59 -0
  42. package/dist/core/fanout.d.ts.map +1 -0
  43. package/dist/core/fanout.js +121 -0
  44. package/dist/core/fanout.test.d.ts +2 -0
  45. package/dist/core/fanout.test.d.ts.map +1 -0
  46. package/dist/core/fanout.test.js +1055 -0
  47. package/dist/core/index.d.ts +7 -0
  48. package/dist/core/index.d.ts.map +1 -0
  49. package/dist/core/index.js +3 -0
  50. package/dist/core/matador.d.ts +133 -0
  51. package/dist/core/matador.d.ts.map +1 -0
  52. package/dist/core/matador.js +222 -0
  53. package/dist/core/matador.test.d.ts +2 -0
  54. package/dist/core/matador.test.d.ts.map +1 -0
  55. package/dist/core/matador.test.js +446 -0
  56. package/dist/core/shutdown.d.ts +78 -0
  57. package/dist/core/shutdown.d.ts.map +1 -0
  58. package/dist/core/shutdown.js +111 -0
  59. package/dist/core/shutdown.test.d.ts +2 -0
  60. package/dist/core/shutdown.test.d.ts.map +1 -0
  61. package/dist/core/shutdown.test.js +524 -0
  62. package/dist/errors/checkpoint-errors.d.ts +30 -0
  63. package/dist/errors/checkpoint-errors.d.ts.map +1 -0
  64. package/dist/errors/checkpoint-errors.js +49 -0
  65. package/dist/errors/has-description.d.ts +18 -0
  66. package/dist/errors/has-description.d.ts.map +1 -0
  67. package/dist/errors/has-description.js +9 -0
  68. package/dist/errors/index.d.ts +6 -0
  69. package/dist/errors/index.d.ts.map +1 -0
  70. package/dist/errors/index.js +22 -0
  71. package/dist/errors/matador-errors.d.ts +183 -0
  72. package/dist/errors/matador-errors.d.ts.map +1 -0
  73. package/dist/errors/matador-errors.js +376 -0
  74. package/dist/errors/retry-errors.d.ts +67 -0
  75. package/dist/errors/retry-errors.d.ts.map +1 -0
  76. package/dist/errors/retry-errors.js +108 -0
  77. package/dist/hooks/index.d.ts +4 -0
  78. package/dist/hooks/index.d.ts.map +1 -0
  79. package/dist/hooks/index.js +2 -0
  80. package/dist/hooks/safe-hooks.d.ts +34 -0
  81. package/dist/hooks/safe-hooks.d.ts.map +1 -0
  82. package/dist/hooks/safe-hooks.js +135 -0
  83. package/dist/hooks/types.d.ts +189 -0
  84. package/dist/hooks/types.d.ts.map +1 -0
  85. package/dist/hooks/types.js +9 -0
  86. package/dist/index.cjs +3156 -0
  87. package/dist/index.cjs.map +1 -0
  88. package/dist/index.d.cts +23 -0
  89. package/dist/index.d.ts +23 -0
  90. package/dist/index.d.ts.map +1 -0
  91. package/dist/index.js +31 -0
  92. package/dist/index.js.map +1 -0
  93. package/dist/pipeline/index.d.ts +3 -0
  94. package/dist/pipeline/index.d.ts.map +1 -0
  95. package/dist/pipeline/index.js +1 -0
  96. package/dist/pipeline/pipeline.d.ts +60 -0
  97. package/dist/pipeline/pipeline.d.ts.map +1 -0
  98. package/dist/pipeline/pipeline.js +261 -0
  99. package/dist/pipeline/pipeline.test.d.ts +2 -0
  100. package/dist/pipeline/pipeline.test.d.ts.map +1 -0
  101. package/dist/pipeline/pipeline.test.js +1065 -0
  102. package/dist/retry/index.d.ts +4 -0
  103. package/dist/retry/index.d.ts.map +1 -0
  104. package/dist/retry/index.js +1 -0
  105. package/dist/retry/policy.d.ts +43 -0
  106. package/dist/retry/policy.d.ts.map +1 -0
  107. package/dist/retry/policy.js +1 -0
  108. package/dist/retry/standard-policy.d.ts +44 -0
  109. package/dist/retry/standard-policy.d.ts.map +1 -0
  110. package/dist/retry/standard-policy.js +102 -0
  111. package/dist/retry/standard-policy.test.d.ts +2 -0
  112. package/dist/retry/standard-policy.test.d.ts.map +1 -0
  113. package/dist/retry/standard-policy.test.js +190 -0
  114. package/dist/schema/index.d.ts +4 -0
  115. package/dist/schema/index.d.ts.map +1 -0
  116. package/dist/schema/index.js +2 -0
  117. package/dist/schema/registry.d.ts +63 -0
  118. package/dist/schema/registry.d.ts.map +1 -0
  119. package/dist/schema/registry.js +171 -0
  120. package/dist/schema/registry.test.d.ts +2 -0
  121. package/dist/schema/registry.test.d.ts.map +1 -0
  122. package/dist/schema/registry.test.js +278 -0
  123. package/dist/schema/types.d.ts +158 -0
  124. package/dist/schema/types.d.ts.map +1 -0
  125. package/dist/schema/types.js +74 -0
  126. package/dist/schema/types.test.d.ts +2 -0
  127. package/dist/schema/types.test.d.ts.map +1 -0
  128. package/dist/schema/types.test.js +243 -0
  129. package/dist/topology/builder.d.ts +66 -0
  130. package/dist/topology/builder.d.ts.map +1 -0
  131. package/dist/topology/builder.js +156 -0
  132. package/dist/topology/builder.test.d.ts +2 -0
  133. package/dist/topology/builder.test.d.ts.map +1 -0
  134. package/dist/topology/builder.test.js +222 -0
  135. package/dist/topology/index.d.ts +5 -0
  136. package/dist/topology/index.d.ts.map +1 -0
  137. package/dist/topology/index.js +2 -0
  138. package/dist/topology/types.d.ts +76 -0
  139. package/dist/topology/types.d.ts.map +1 -0
  140. package/dist/topology/types.js +18 -0
  141. package/dist/transport/capabilities.d.ts +66 -0
  142. package/dist/transport/capabilities.d.ts.map +1 -0
  143. package/dist/transport/capabilities.js +18 -0
  144. package/dist/transport/connection-manager.d.ts +95 -0
  145. package/dist/transport/connection-manager.d.ts.map +1 -0
  146. package/dist/transport/connection-manager.js +144 -0
  147. package/dist/transport/index.d.ts +11 -0
  148. package/dist/transport/index.d.ts.map +1 -0
  149. package/dist/transport/index.js +5 -0
  150. package/dist/transport/local/local-transport.d.ts +62 -0
  151. package/dist/transport/local/local-transport.d.ts.map +1 -0
  152. package/dist/transport/local/local-transport.js +241 -0
  153. package/dist/transport/local/local-transport.test.d.ts +2 -0
  154. package/dist/transport/local/local-transport.test.d.ts.map +1 -0
  155. package/dist/transport/local/local-transport.test.js +192 -0
  156. package/dist/transport/multi/multi-transport.d.ts +94 -0
  157. package/dist/transport/multi/multi-transport.d.ts.map +1 -0
  158. package/dist/transport/multi/multi-transport.js +184 -0
  159. package/dist/transport/multi/multi-transport.test.d.ts +2 -0
  160. package/dist/transport/multi/multi-transport.test.d.ts.map +1 -0
  161. package/dist/transport/multi/multi-transport.test.js +236 -0
  162. package/dist/transport/rabbitmq/rabbitmq-transport.d.ts +73 -0
  163. package/dist/transport/rabbitmq/rabbitmq-transport.d.ts.map +1 -0
  164. package/dist/transport/rabbitmq/rabbitmq-transport.js +518 -0
  165. package/dist/transport/transport.d.ts +152 -0
  166. package/dist/transport/transport.d.ts.map +1 -0
  167. package/dist/transport/transport.js +1 -0
  168. package/dist/types/common.d.ts +41 -0
  169. package/dist/types/common.d.ts.map +1 -0
  170. package/dist/types/common.js +12 -0
  171. package/dist/types/envelope.d.ts +82 -0
  172. package/dist/types/envelope.d.ts.map +1 -0
  173. package/dist/types/envelope.js +36 -0
  174. package/dist/types/event.d.ts +96 -0
  175. package/dist/types/event.d.ts.map +1 -0
  176. package/dist/types/event.js +26 -0
  177. package/dist/types/event.test.d.ts +2 -0
  178. package/dist/types/event.test.d.ts.map +1 -0
  179. package/dist/types/event.test.js +130 -0
  180. package/dist/types/index.d.ts +9 -0
  181. package/dist/types/index.d.ts.map +1 -0
  182. package/dist/types/index.js +4 -0
  183. package/dist/types/subscriber.d.ts +207 -0
  184. package/dist/types/subscriber.d.ts.map +1 -0
  185. package/dist/types/subscriber.js +99 -0
  186. package/examples/config.ts +126 -0
  187. package/examples/event.ts +26 -0
  188. package/examples/order-event.json +19 -0
  189. package/package.json +66 -0
  190. package/src/checkpoint/context.test.ts +510 -0
  191. package/src/checkpoint/context.ts +213 -0
  192. package/src/checkpoint/index.ts +30 -0
  193. package/src/checkpoint/stores/memory.ts +47 -0
  194. package/src/checkpoint/stores/noop.ts +22 -0
  195. package/src/checkpoint/stores/stores.test.ts +177 -0
  196. package/src/checkpoint/types.ts +147 -0
  197. package/src/codec/codec.ts +42 -0
  198. package/src/codec/header-aware-codec.ts +41 -0
  199. package/src/codec/index.ts +11 -0
  200. package/src/codec/json-codec.ts +69 -0
  201. package/src/codec/rabbitmq-codec.test.ts +516 -0
  202. package/src/codec/rabbitmq-codec.ts +336 -0
  203. package/src/core/fanout.test.ts +1351 -0
  204. package/src/core/fanout.ts +184 -0
  205. package/src/core/index.ts +12 -0
  206. package/src/core/matador.test.ts +575 -0
  207. package/src/core/matador.ts +344 -0
  208. package/src/core/shutdown.test.ts +853 -0
  209. package/src/core/shutdown.ts +165 -0
  210. package/src/errors/checkpoint-errors.ts +62 -0
  211. package/src/errors/has-description.ts +25 -0
  212. package/src/errors/index.ts +57 -0
  213. package/src/errors/matador-errors.ts +477 -0
  214. package/src/errors/retry-errors.ts +134 -0
  215. package/src/hooks/index.ts +15 -0
  216. package/src/hooks/safe-hooks.ts +223 -0
  217. package/src/hooks/types.ts +248 -0
  218. package/src/index.ts +231 -0
  219. package/src/pipeline/index.ts +2 -0
  220. package/src/pipeline/pipeline.test.ts +1317 -0
  221. package/src/pipeline/pipeline.ts +371 -0
  222. package/src/retry/index.ts +4 -0
  223. package/src/retry/policy.ts +46 -0
  224. package/src/retry/standard-policy.test.ts +282 -0
  225. package/src/retry/standard-policy.ts +156 -0
  226. package/src/schema/index.ts +16 -0
  227. package/src/schema/registry.test.ts +339 -0
  228. package/src/schema/registry.ts +226 -0
  229. package/src/schema/types.test.ts +281 -0
  230. package/src/schema/types.ts +217 -0
  231. package/src/topology/builder.test.ts +275 -0
  232. package/src/topology/builder.ts +199 -0
  233. package/src/topology/index.ts +15 -0
  234. package/src/topology/types.ts +109 -0
  235. package/src/transport/capabilities.ts +88 -0
  236. package/src/transport/connection-manager.ts +218 -0
  237. package/src/transport/index.ts +42 -0
  238. package/src/transport/local/local-transport.test.ts +262 -0
  239. package/src/transport/local/local-transport.ts +327 -0
  240. package/src/transport/multi/multi-transport.test.ts +320 -0
  241. package/src/transport/multi/multi-transport.ts +294 -0
  242. package/src/transport/rabbitmq/rabbitmq-transport.ts +753 -0
  243. package/src/transport/transport.ts +200 -0
  244. package/src/types/common.ts +53 -0
  245. package/src/types/envelope.ts +152 -0
  246. package/src/types/event.test.ts +157 -0
  247. package/src/types/event.ts +118 -0
  248. package/src/types/index.ts +52 -0
  249. package/src/types/subscriber.ts +310 -0
  250. package/test/e2e/multi-transport.e2e.test.ts +236 -0
  251. package/test/e2e/rabbitmq-transport.e2e.test.ts +327 -0
  252. package/test/e2e/transport-compliance.e2e.test.ts +505 -0
  253. package/test/integration/matador.integration.test.ts +634 -0
  254. package/tsconfig.json +29 -0
  255. package/tsconfig.tsbuildinfo +1 -0
  256. package/tsup.config.ts +13 -0
@@ -0,0 +1,510 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'bun:test';
2
+ import { DuplicateIoKeyError } from '../errors/index.js';
3
+ import type { Envelope, SubscriberDefinition } from '../types/index.js';
4
+ import { ResumableContext } from './context.js';
5
+ import { MemoryCheckpointStore } from './stores/memory.js';
6
+
7
+ function createTestEnvelope(id = 'test-envelope-id', attempts = 1): Envelope {
8
+ return {
9
+ id,
10
+ data: { userId: '123' },
11
+ docket: {
12
+ eventKey: 'test.event',
13
+ targetSubscriber: 'test-subscriber',
14
+ importance: 'should-investigate',
15
+ attempts,
16
+ createdAt: new Date().toISOString(),
17
+ },
18
+ };
19
+ }
20
+
21
+ function createTestSubscriber(name = 'test-subscriber'): SubscriberDefinition {
22
+ return {
23
+ name,
24
+ description: 'Test subscriber',
25
+ idempotent: 'resumable',
26
+ importance: 'should-investigate',
27
+ };
28
+ }
29
+
30
+ describe('ResumableContext', () => {
31
+ let store: MemoryCheckpointStore;
32
+ let envelope: Envelope;
33
+ let subscriber: SubscriberDefinition;
34
+
35
+ beforeEach(() => {
36
+ store = new MemoryCheckpointStore();
37
+ envelope = createTestEnvelope();
38
+ subscriber = createTestSubscriber();
39
+ });
40
+
41
+ describe('io()', () => {
42
+ it('should execute function and cache result on first call', async () => {
43
+ const context = new ResumableContext({
44
+ store,
45
+ envelope,
46
+ subscriber,
47
+ });
48
+
49
+ let executeCount = 0;
50
+ const result = await context.io('step-1', () => {
51
+ executeCount++;
52
+ return 'result-1';
53
+ });
54
+
55
+ expect(result).toBe('result-1');
56
+ expect(executeCount).toBe(1);
57
+ expect(store.size).toBe(1);
58
+ });
59
+
60
+ it('should return cached result on retry without re-executing', async () => {
61
+ // First execution - cache the result
62
+ const firstContext = new ResumableContext({
63
+ store,
64
+ envelope,
65
+ subscriber,
66
+ });
67
+
68
+ let executeCount = 0;
69
+ await firstContext.io('step-1', () => {
70
+ executeCount++;
71
+ return 'result-1';
72
+ });
73
+
74
+ expect(executeCount).toBe(1);
75
+
76
+ // Simulate retry - load existing checkpoint
77
+ const checkpoint = await store.get(envelope.id);
78
+ const retryContext = new ResumableContext({
79
+ store,
80
+ envelope: createTestEnvelope(envelope.id, 2),
81
+ subscriber,
82
+ existingCheckpoint: checkpoint,
83
+ });
84
+
85
+ const result = await retryContext.io<string>('step-1', () => {
86
+ executeCount++;
87
+ return 'should-not-be-used';
88
+ });
89
+
90
+ expect(result).toBe('result-1');
91
+ expect(executeCount).toBe(1); // Still 1, not re-executed
92
+ });
93
+
94
+ it('should throw DuplicateIoKeyError on duplicate key within same execution', async () => {
95
+ const context = new ResumableContext({
96
+ store,
97
+ envelope,
98
+ subscriber,
99
+ });
100
+
101
+ await context.io('same-key', () => 'first');
102
+
103
+ await expect(context.io('same-key', () => 'second')).rejects.toThrow(
104
+ DuplicateIoKeyError,
105
+ );
106
+ });
107
+
108
+ it('should handle async functions', async () => {
109
+ const context = new ResumableContext({
110
+ store,
111
+ envelope,
112
+ subscriber,
113
+ });
114
+
115
+ const result = await context.io('async-step', async () => {
116
+ await new Promise((resolve) => setTimeout(resolve, 10));
117
+ return { value: 42 };
118
+ });
119
+
120
+ expect(result).toEqual({ value: 42 });
121
+ });
122
+
123
+ it('should not cache failed operations', async () => {
124
+ const context = new ResumableContext({
125
+ store,
126
+ envelope,
127
+ subscriber,
128
+ });
129
+
130
+ // First attempt - fails
131
+ await expect(
132
+ context.io('failing-step', () => {
133
+ throw new Error('Operation failed');
134
+ }),
135
+ ).rejects.toThrow('Operation failed');
136
+
137
+ // Checkpoint should not contain the failed step
138
+ const checkpoint = await store.get(envelope.id);
139
+ expect(checkpoint?.completedSteps['failing-step']).toBeUndefined();
140
+ });
141
+
142
+ it('should persist checkpoint after each io() call', async () => {
143
+ const context = new ResumableContext({
144
+ store,
145
+ envelope,
146
+ subscriber,
147
+ });
148
+
149
+ await context.io('step-1', () => 'result-1');
150
+ let checkpoint = await store.get(envelope.id);
151
+ expect(Object.keys(checkpoint!.completedSteps)).toHaveLength(1);
152
+
153
+ await context.io('step-2', () => 'result-2');
154
+ checkpoint = await store.get(envelope.id);
155
+ expect(Object.keys(checkpoint!.completedSteps)).toHaveLength(2);
156
+ });
157
+
158
+ it('should support various JSON-serializable return types', async () => {
159
+ const context = new ResumableContext({
160
+ store,
161
+ envelope,
162
+ subscriber,
163
+ });
164
+
165
+ expect(await context.io('string', () => 'hello')).toBe('hello');
166
+ expect(await context.io('number', () => 42)).toBe(42);
167
+ expect(await context.io('boolean', () => true)).toBe(true);
168
+ expect(await context.io('null', () => null)).toBe(null);
169
+ expect(await context.io('array', () => [1, 2, 3])).toEqual([1, 2, 3]);
170
+ expect(await context.io('object', () => ({ foo: 'bar' }))).toEqual({
171
+ foo: 'bar',
172
+ });
173
+ });
174
+ });
175
+
176
+ describe('all()', () => {
177
+ it('should execute multiple operations in parallel', async () => {
178
+ const context = new ResumableContext({
179
+ store,
180
+ envelope,
181
+ subscriber,
182
+ });
183
+
184
+ const executionOrder: string[] = [];
185
+ const [a, b, c] = await context.all([
186
+ [
187
+ 'fetch-a',
188
+ () => {
189
+ executionOrder.push('a');
190
+ return 'result-a';
191
+ },
192
+ ],
193
+ [
194
+ 'fetch-b',
195
+ () => {
196
+ executionOrder.push('b');
197
+ return 'result-b';
198
+ },
199
+ ],
200
+ [
201
+ 'fetch-c',
202
+ () => {
203
+ executionOrder.push('c');
204
+ return 'result-c';
205
+ },
206
+ ],
207
+ ]);
208
+
209
+ expect(a).toBe('result-a');
210
+ expect(b).toBe('result-b');
211
+ expect(c).toBe('result-c');
212
+ expect(executionOrder).toHaveLength(3);
213
+ });
214
+
215
+ it('should cache all results on retry', async () => {
216
+ // First execution
217
+ const firstContext = new ResumableContext({
218
+ store,
219
+ envelope,
220
+ subscriber,
221
+ });
222
+
223
+ let executeCount = 0;
224
+ await firstContext.all([
225
+ [
226
+ 'fetch-a',
227
+ () => {
228
+ executeCount++;
229
+ return 'result-a';
230
+ },
231
+ ],
232
+ [
233
+ 'fetch-b',
234
+ () => {
235
+ executeCount++;
236
+ return 'result-b';
237
+ },
238
+ ],
239
+ ]);
240
+
241
+ expect(executeCount).toBe(2);
242
+
243
+ // Retry with cached checkpoint
244
+ const checkpoint = await store.get(envelope.id);
245
+ const retryContext = new ResumableContext({
246
+ store,
247
+ envelope: createTestEnvelope(envelope.id, 2),
248
+ subscriber,
249
+ existingCheckpoint: checkpoint,
250
+ });
251
+
252
+ const [a, b] = await retryContext.all([
253
+ [
254
+ 'fetch-a',
255
+ () => {
256
+ executeCount++;
257
+ return 'new-a';
258
+ },
259
+ ],
260
+ [
261
+ 'fetch-b',
262
+ () => {
263
+ executeCount++;
264
+ return 'new-b';
265
+ },
266
+ ],
267
+ ]);
268
+
269
+ expect(a).toBe('result-a'); // Cached
270
+ expect(b).toBe('result-b'); // Cached
271
+ expect(executeCount).toBe(2); // Still 2, not re-executed
272
+ });
273
+
274
+ it('should throw on duplicate key in all()', async () => {
275
+ const context = new ResumableContext({
276
+ store,
277
+ envelope,
278
+ subscriber,
279
+ });
280
+
281
+ await expect(
282
+ context.all([
283
+ ['same-key', () => 'first'],
284
+ ['same-key', () => 'second'],
285
+ ]),
286
+ ).rejects.toThrow(DuplicateIoKeyError);
287
+ });
288
+
289
+ it('should throw if all() key conflicts with previous io() key', async () => {
290
+ const context = new ResumableContext({
291
+ store,
292
+ envelope,
293
+ subscriber,
294
+ });
295
+
296
+ await context.io('used-key', () => 'first');
297
+
298
+ await expect(
299
+ context.all([
300
+ ['used-key', () => 'second'],
301
+ ['new-key', () => 'third'],
302
+ ]),
303
+ ).rejects.toThrow(DuplicateIoKeyError);
304
+ });
305
+ });
306
+
307
+ describe('attempt and isRetry', () => {
308
+ it('should report attempt number from envelope', async () => {
309
+ const context = new ResumableContext({
310
+ store,
311
+ envelope: createTestEnvelope('test', 3),
312
+ subscriber,
313
+ });
314
+
315
+ expect(context.attempt).toBe(3);
316
+ });
317
+
318
+ it('should report isRetry as false for first attempt', async () => {
319
+ const context = new ResumableContext({
320
+ store,
321
+ envelope: createTestEnvelope('test', 1),
322
+ subscriber,
323
+ });
324
+
325
+ expect(context.isRetry).toBe(false);
326
+ });
327
+
328
+ it('should report isRetry as true for subsequent attempts', async () => {
329
+ const context = new ResumableContext({
330
+ store,
331
+ envelope: createTestEnvelope('test', 2),
332
+ subscriber,
333
+ });
334
+
335
+ expect(context.isRetry).toBe(true);
336
+ });
337
+ });
338
+
339
+ describe('clear()', () => {
340
+ it('should delete checkpoint from store', async () => {
341
+ const context = new ResumableContext({
342
+ store,
343
+ envelope,
344
+ subscriber,
345
+ });
346
+
347
+ await context.io('step-1', () => 'result');
348
+ expect(store.size).toBe(1);
349
+
350
+ await context.clear();
351
+ expect(store.size).toBe(0);
352
+ });
353
+ });
354
+
355
+ describe('hooks', () => {
356
+ it('should call onCheckpointHit when using cached value', async () => {
357
+ const onCheckpointHit = vi.fn();
358
+
359
+ // First execution - populate cache
360
+ const firstContext = new ResumableContext({
361
+ store,
362
+ envelope,
363
+ subscriber,
364
+ });
365
+ await firstContext.io('cached-step', () => 'cached-result');
366
+
367
+ // Retry with hooks
368
+ const checkpoint = await store.get(envelope.id);
369
+ const retryContext = new ResumableContext({
370
+ store,
371
+ envelope: createTestEnvelope(envelope.id, 2),
372
+ subscriber,
373
+ existingCheckpoint: checkpoint,
374
+ hooks: { onCheckpointHit },
375
+ });
376
+
377
+ await retryContext.io('cached-step', () => 'new-result');
378
+
379
+ expect(onCheckpointHit).toHaveBeenCalledWith({
380
+ envelope: expect.anything(),
381
+ subscriber,
382
+ stepKey: 'cached-step',
383
+ });
384
+ });
385
+
386
+ it('should call onCheckpointMiss when executing fresh', async () => {
387
+ const onCheckpointMiss = vi.fn();
388
+
389
+ const context = new ResumableContext({
390
+ store,
391
+ envelope,
392
+ subscriber,
393
+ hooks: { onCheckpointMiss },
394
+ });
395
+
396
+ await context.io('fresh-step', () => 'result');
397
+
398
+ expect(onCheckpointMiss).toHaveBeenCalledWith({
399
+ envelope,
400
+ subscriber,
401
+ stepKey: 'fresh-step',
402
+ });
403
+ });
404
+ });
405
+
406
+ describe('real-world scenarios', () => {
407
+ it('should replay cached steps and execute new ones on retry', async () => {
408
+ const executionLog: string[] = [];
409
+ let shouldFail = true;
410
+
411
+ // First attempt - fails after step-1
412
+ const firstContext = new ResumableContext({
413
+ store,
414
+ envelope,
415
+ subscriber,
416
+ });
417
+
418
+ try {
419
+ await firstContext.io('step-0', () => {
420
+ executionLog.push('step-0');
421
+ return 'result-0';
422
+ });
423
+
424
+ await firstContext.io('step-1', () => {
425
+ executionLog.push('step-1');
426
+ return 'result-1';
427
+ });
428
+
429
+ if (shouldFail) {
430
+ shouldFail = false;
431
+ throw new Error('Simulated failure');
432
+ }
433
+
434
+ await firstContext.io('step-2', () => {
435
+ executionLog.push('step-2');
436
+ return 'result-2';
437
+ });
438
+ } catch {
439
+ // Expected failure
440
+ }
441
+
442
+ expect(executionLog).toEqual(['step-0', 'step-1']);
443
+
444
+ // Retry - step-0 and step-1 use cache, step-2 executes
445
+ executionLog.length = 0;
446
+ const checkpoint = await store.get(envelope.id);
447
+ const retryContext = new ResumableContext({
448
+ store,
449
+ envelope: createTestEnvelope(envelope.id, 2),
450
+ subscriber,
451
+ existingCheckpoint: checkpoint,
452
+ });
453
+
454
+ await retryContext.io('step-0', () => {
455
+ executionLog.push('step-0');
456
+ return 'should-not-use';
457
+ });
458
+
459
+ await retryContext.io('step-1', () => {
460
+ executionLog.push('step-1');
461
+ return 'should-not-use';
462
+ });
463
+
464
+ await retryContext.io('step-2', () => {
465
+ executionLog.push('step-2');
466
+ return 'result-2';
467
+ });
468
+
469
+ expect(executionLog).toEqual(['step-2']); // Only step-2 executed!
470
+ });
471
+
472
+ it('should handle conditional io() calls correctly', async () => {
473
+ const context = new ResumableContext({
474
+ store,
475
+ envelope: { ...envelope, data: { sendEmail: true } },
476
+ subscriber,
477
+ });
478
+
479
+ const result = await context.io('send-email', () => ({
480
+ messageId: 'msg-123',
481
+ }));
482
+
483
+ expect(result).toEqual({ messageId: 'msg-123' });
484
+ });
485
+
486
+ it('should handle dynamic loop with unique keys', async () => {
487
+ const context = new ResumableContext({
488
+ store,
489
+ envelope,
490
+ subscriber,
491
+ });
492
+
493
+ const items = [
494
+ { id: 'item-1', value: 10 },
495
+ { id: 'item-2', value: 20 },
496
+ { id: 'item-3', value: 30 },
497
+ ];
498
+
499
+ const results: number[] = [];
500
+ for (const item of items) {
501
+ const processed = await context.io(`process-${item.id}`, () => {
502
+ return item.value * 2;
503
+ });
504
+ results.push(processed);
505
+ }
506
+
507
+ expect(results).toEqual([20, 40, 60]);
508
+ });
509
+ });
510
+ });
@@ -0,0 +1,213 @@
1
+ import { DuplicateIoKeyError } from '../errors/index.js';
2
+ import type { Envelope, SubscriberDefinition } from '../types/index.js';
3
+ import type {
4
+ Checkpoint,
5
+ CheckpointHitContext,
6
+ CheckpointMissContext,
7
+ CheckpointStore,
8
+ JsonSerializable,
9
+ SubscriberContext,
10
+ } from './types.js';
11
+
12
+ /**
13
+ * Hooks for observability during context operations.
14
+ */
15
+ export interface ResumableContextHooks {
16
+ onCheckpointHit?(context: CheckpointHitContext): void | Promise<void>;
17
+ onCheckpointMiss?(context: CheckpointMissContext): void | Promise<void>;
18
+ }
19
+
20
+ /**
21
+ * Configuration for creating a ResumableContext.
22
+ */
23
+ export interface ResumableContextConfig {
24
+ readonly store: CheckpointStore;
25
+ readonly envelope: Envelope;
26
+ readonly subscriber: SubscriberDefinition;
27
+ readonly existingCheckpoint?: Checkpoint | undefined;
28
+ readonly hooks?: ResumableContextHooks | undefined;
29
+ }
30
+
31
+ /**
32
+ * Implementation of SubscriberContext that provides io() caching.
33
+ *
34
+ * On first execution, io() calls execute their lambdas and cache results.
35
+ * On retry (when existingCheckpoint is provided), cached results are returned
36
+ * without re-executing the lambda.
37
+ */
38
+ export class ResumableContext implements SubscriberContext {
39
+ private checkpoint: Checkpoint;
40
+ private readonly usedKeys = new Set<string>();
41
+ private readonly store: CheckpointStore;
42
+ private readonly envelope: Envelope;
43
+ private readonly subscriber: SubscriberDefinition;
44
+ private readonly hooks: ResumableContextHooks | undefined;
45
+
46
+ constructor(config: ResumableContextConfig) {
47
+ this.store = config.store;
48
+ this.envelope = config.envelope;
49
+ this.subscriber = config.subscriber;
50
+ this.hooks = config.hooks;
51
+
52
+ this.checkpoint = config.existingCheckpoint ?? {
53
+ envelopeId: config.envelope.id,
54
+ subscriberName: config.subscriber.name,
55
+ completedSteps: {},
56
+ };
57
+ }
58
+
59
+ get attempt(): number {
60
+ return this.envelope.docket.attempts;
61
+ }
62
+
63
+ get isRetry(): boolean {
64
+ return this.attempt > 1;
65
+ }
66
+
67
+ async io<T extends JsonSerializable>(
68
+ key: string,
69
+ fn: () => Promise<T> | T,
70
+ ): Promise<T> {
71
+ // Validate key uniqueness within this execution
72
+ if (this.usedKeys.has(key)) {
73
+ throw new DuplicateIoKeyError(key, this.subscriber.name);
74
+ }
75
+ this.usedKeys.add(key);
76
+
77
+ // Check cache first
78
+ if (key in this.checkpoint.completedSteps) {
79
+ await this.hooks?.onCheckpointHit?.({
80
+ envelope: this.envelope,
81
+ subscriber: this.subscriber,
82
+ stepKey: key,
83
+ });
84
+ return this.checkpoint.completedSteps[key] as T;
85
+ }
86
+
87
+ // Notify cache miss
88
+ await this.hooks?.onCheckpointMiss?.({
89
+ envelope: this.envelope,
90
+ subscriber: this.subscriber,
91
+ stepKey: key,
92
+ });
93
+
94
+ // Execute the function - errors propagate, no caching on failure
95
+ const result = await fn();
96
+
97
+ // Cache the result
98
+ this.checkpoint = {
99
+ ...this.checkpoint,
100
+ completedSteps: {
101
+ ...this.checkpoint.completedSteps,
102
+ [key]: result,
103
+ },
104
+ };
105
+
106
+ // Persist checkpoint immediately (incremental persistence)
107
+ await this.store.set(this.envelope.id, this.checkpoint);
108
+
109
+ return result;
110
+ }
111
+
112
+ async all<
113
+ T extends readonly [
114
+ string,
115
+ () => Promise<JsonSerializable> | JsonSerializable,
116
+ ][],
117
+ >(
118
+ ops: T,
119
+ ): Promise<{
120
+ [K in keyof T]: T[K] extends [string, () => Promise<infer R> | infer R]
121
+ ? R
122
+ : never;
123
+ }> {
124
+ // First, check for duplicates within this all() call
125
+ const keysInThisCall = new Set<string>();
126
+ for (const [key] of ops) {
127
+ if (keysInThisCall.has(key)) {
128
+ throw new DuplicateIoKeyError(key, this.subscriber.name);
129
+ }
130
+ keysInThisCall.add(key);
131
+ }
132
+
133
+ // Then validate against previously used keys
134
+ for (const [key] of ops) {
135
+ if (this.usedKeys.has(key)) {
136
+ throw new DuplicateIoKeyError(key, this.subscriber.name);
137
+ }
138
+ }
139
+
140
+ // Mark all keys as used
141
+ for (const [key] of ops) {
142
+ this.usedKeys.add(key);
143
+ }
144
+
145
+ // Execute all operations in parallel
146
+ const results = await Promise.all(
147
+ ops.map(async ([key, fn]) => {
148
+ // Check cache first
149
+ if (key in this.checkpoint.completedSteps) {
150
+ await this.hooks?.onCheckpointHit?.({
151
+ envelope: this.envelope,
152
+ subscriber: this.subscriber,
153
+ stepKey: key,
154
+ });
155
+ return this.checkpoint.completedSteps[key];
156
+ }
157
+
158
+ // Notify cache miss
159
+ await this.hooks?.onCheckpointMiss?.({
160
+ envelope: this.envelope,
161
+ subscriber: this.subscriber,
162
+ stepKey: key,
163
+ });
164
+
165
+ // Execute - errors propagate
166
+ const result = await fn();
167
+
168
+ // Cache individually (in local state, will persist after Promise.all)
169
+ this.checkpoint = {
170
+ ...this.checkpoint,
171
+ completedSteps: {
172
+ ...this.checkpoint.completedSteps,
173
+ [key]: result,
174
+ },
175
+ };
176
+
177
+ return result;
178
+ }),
179
+ );
180
+
181
+ // Persist after all parallel operations complete
182
+ await this.store.set(this.envelope.id, this.checkpoint);
183
+
184
+ return results as {
185
+ [K in keyof T]: T[K] extends [string, () => Promise<infer R> | infer R]
186
+ ? R
187
+ : never;
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Clears the checkpoint from storage.
193
+ * Called after successful completion or dead-letter.
194
+ */
195
+ async clear(): Promise<void> {
196
+ await this.store.delete(this.envelope.id);
197
+ }
198
+
199
+ /**
200
+ * Gets the current checkpoint state.
201
+ * Useful for debugging and testing.
202
+ */
203
+ getCheckpoint(): Checkpoint {
204
+ return this.checkpoint;
205
+ }
206
+
207
+ /**
208
+ * Gets the number of cached steps.
209
+ */
210
+ get cachedStepCount(): number {
211
+ return Object.keys(this.checkpoint.completedSteps).length;
212
+ }
213
+ }