@baukit/api-runtime 0.7.2 → 0.7.4
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/package.json +2 -1
- package/src/backoff.test.ts +32 -0
- package/src/backoff.ts +22 -0
- package/src/erasure.test.ts +333 -0
- package/src/erasure.ts +229 -0
- package/src/idempotency.test.ts +423 -0
- package/src/idempotency.ts +258 -0
- package/src/index.test.ts +453 -0
- package/src/index.ts +727 -0
- package/src/unverified-display-identity.test.ts +72 -0
- package/src/unverified-display-identity.ts +96 -0
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
canonicalJson,
|
|
5
|
+
classifyMutationError,
|
|
6
|
+
classifyMutationStatus,
|
|
7
|
+
createIdempotencyKeyStore,
|
|
8
|
+
sendIdempotentMutation,
|
|
9
|
+
type IdempotencyKeyStorage,
|
|
10
|
+
type MutationIntent,
|
|
11
|
+
type StoredIdempotencyKey,
|
|
12
|
+
} from './idempotency.js';
|
|
13
|
+
import { ApiError, HttpError, NetworkError } from './index.js';
|
|
14
|
+
|
|
15
|
+
const TTL_MS = 60_000;
|
|
16
|
+
const intent: MutationIntent = {
|
|
17
|
+
account: 'account-a',
|
|
18
|
+
operation: 'createNote',
|
|
19
|
+
body: { title: 'standup', tags: ['a', 'b'] },
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
function apiError(status: number, code: string): ApiError {
|
|
23
|
+
return new ApiError(
|
|
24
|
+
{ error: { code, message: 'failed', requestId: 'req-1', details: {} } },
|
|
25
|
+
status,
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function counterKeys(): () => string {
|
|
30
|
+
let next = 0;
|
|
31
|
+
return () => {
|
|
32
|
+
next += 1;
|
|
33
|
+
return `key-${String(next)}`;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function store(now: () => number = () => 0, storage?: IdempotencyKeyStorage) {
|
|
38
|
+
return createIdempotencyKeyStore({
|
|
39
|
+
ttlMs: TTL_MS,
|
|
40
|
+
now,
|
|
41
|
+
keyFactory: counterKeys(),
|
|
42
|
+
...(storage === undefined ? {} : { storage }),
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
describe('classifyMutationStatus', () => {
|
|
47
|
+
it.each([
|
|
48
|
+
[200, 'committed'],
|
|
49
|
+
[201, 'committed'],
|
|
50
|
+
[204, 'committed'],
|
|
51
|
+
[400, 'not-committed'],
|
|
52
|
+
[404, 'not-committed'],
|
|
53
|
+
[409, 'not-committed'],
|
|
54
|
+
[412, 'not-committed'],
|
|
55
|
+
[408, 'possibly-committed'],
|
|
56
|
+
[429, 'possibly-committed'],
|
|
57
|
+
[500, 'possibly-committed'],
|
|
58
|
+
[503, 'possibly-committed'],
|
|
59
|
+
[302, 'possibly-committed'],
|
|
60
|
+
] as const)('classifies %i as %s', (status, outcome) => {
|
|
61
|
+
expect(classifyMutationStatus(status)).toBe(outcome);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe('classifyMutationError', () => {
|
|
66
|
+
it('treats transport failures and unknown throws as possibly committed', () => {
|
|
67
|
+
expect(classifyMutationError(new NetworkError('offline', 'req-1', null))).toBe(
|
|
68
|
+
'possibly-committed',
|
|
69
|
+
);
|
|
70
|
+
expect(classifyMutationError(new NetworkError('aborted', 'req-1', null, true))).toBe(
|
|
71
|
+
'possibly-committed',
|
|
72
|
+
);
|
|
73
|
+
expect(classifyMutationError(new TypeError('boom'))).toBe('possibly-committed');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('classifies API and HTTP errors by status', () => {
|
|
77
|
+
expect(classifyMutationError(apiError(400, 'validation_failed'))).toBe('not-committed');
|
|
78
|
+
expect(classifyMutationError(apiError(409, 'idempotency_key_reused'))).toBe('not-committed');
|
|
79
|
+
expect(classifyMutationError(apiError(503, 'unavailable'))).toBe('possibly-committed');
|
|
80
|
+
expect(classifyMutationError(new HttpError(new Response(null, { status: 502 }), null))).toBe(
|
|
81
|
+
'possibly-committed',
|
|
82
|
+
);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('treats a key still in progress as possibly committed', () => {
|
|
86
|
+
expect(classifyMutationError(apiError(409, 'idempotency_key_in_progress'))).toBe(
|
|
87
|
+
'possibly-committed',
|
|
88
|
+
);
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
describe('createIdempotencyKeyStore', () => {
|
|
93
|
+
it('keeps one key per account, operation, and body', async () => {
|
|
94
|
+
const keys = store();
|
|
95
|
+
const first = await keys.keyFor(intent);
|
|
96
|
+
|
|
97
|
+
await expect(
|
|
98
|
+
keys.keyFor({ ...intent, body: { tags: ['a', 'b'], title: 'standup' } }),
|
|
99
|
+
).resolves.toBe(first);
|
|
100
|
+
await expect(keys.keyFor({ ...intent, account: 'account-b' })).resolves.not.toBe(first);
|
|
101
|
+
await expect(keys.keyFor({ ...intent, operation: 'createTask' })).resolves.not.toBe(first);
|
|
102
|
+
await expect(keys.keyFor({ ...intent, body: { title: 'retro' } })).resolves.not.toBe(first);
|
|
103
|
+
await expect(
|
|
104
|
+
keys.keyFor({ ...intent, body: { title: 'standup', tags: ['b', 'a'] } }),
|
|
105
|
+
).resolves.not.toBe(first);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('keeps the key while the outcome is uncertain and drops it after a definite one', async () => {
|
|
109
|
+
const keys = store();
|
|
110
|
+
const first = await keys.keyFor(intent);
|
|
111
|
+
|
|
112
|
+
await keys.settle(intent, 'possibly-committed');
|
|
113
|
+
await expect(keys.keyFor(intent)).resolves.toBe(first);
|
|
114
|
+
|
|
115
|
+
await keys.settle(intent, 'committed');
|
|
116
|
+
const second = await keys.keyFor(intent);
|
|
117
|
+
expect(second).not.toBe(first);
|
|
118
|
+
|
|
119
|
+
await keys.settle(intent, 'not-committed');
|
|
120
|
+
await expect(keys.keyFor(intent)).resolves.not.toBe(second);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('replaces a key after its time to live', async () => {
|
|
124
|
+
let now = 0;
|
|
125
|
+
const keys = store(() => now);
|
|
126
|
+
const first = await keys.keyFor(intent);
|
|
127
|
+
|
|
128
|
+
now = TTL_MS - 1;
|
|
129
|
+
await expect(keys.keyFor(intent)).resolves.toBe(first);
|
|
130
|
+
now = TTL_MS;
|
|
131
|
+
await expect(keys.keyFor(intent)).resolves.not.toBe(first);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it('reads keys back from caller storage after a restart', async () => {
|
|
135
|
+
const saved = new Map<string, StoredIdempotencyKey>();
|
|
136
|
+
const storage: IdempotencyKeyStorage = {
|
|
137
|
+
get: (slot) => Promise.resolve(saved.get(slot) ?? null),
|
|
138
|
+
set: (slot, value) => {
|
|
139
|
+
saved.set(slot, value);
|
|
140
|
+
return Promise.resolve();
|
|
141
|
+
},
|
|
142
|
+
delete: (slot) => {
|
|
143
|
+
saved.delete(slot);
|
|
144
|
+
return Promise.resolve();
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
const first = await store(() => 0, storage).keyFor(intent);
|
|
148
|
+
|
|
149
|
+
await expect(store(() => 1, storage).keyFor(intent)).resolves.toBe(first);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('rejects a time to live that is not positive', () => {
|
|
153
|
+
expect(() => createIdempotencyKeyStore({ ttlMs: 0 })).toThrow('ttlMs');
|
|
154
|
+
expect(() => createIdempotencyKeyStore({ ttlMs: Number.NaN })).toThrow('ttlMs');
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('uses random UUID keys by default', async () => {
|
|
158
|
+
const key = await createIdempotencyKeyStore({ ttlMs: TTL_MS }).keyFor(intent);
|
|
159
|
+
expect(key).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
describe('sendIdempotentMutation', () => {
|
|
164
|
+
it('resends a lost response with the same key and drops the key after success', async () => {
|
|
165
|
+
const keys = store();
|
|
166
|
+
const sent: string[] = [];
|
|
167
|
+
|
|
168
|
+
await expect(
|
|
169
|
+
sendIdempotentMutation(keys, intent, (key) => {
|
|
170
|
+
sent.push(key);
|
|
171
|
+
return Promise.reject(new NetworkError('offline', 'req-1', null));
|
|
172
|
+
}),
|
|
173
|
+
).rejects.toBeInstanceOf(NetworkError);
|
|
174
|
+
await expect(
|
|
175
|
+
sendIdempotentMutation(keys, intent, (key) => {
|
|
176
|
+
sent.push(key);
|
|
177
|
+
return Promise.resolve('created');
|
|
178
|
+
}),
|
|
179
|
+
).resolves.toBe('created');
|
|
180
|
+
await sendIdempotentMutation(keys, intent, (key) => {
|
|
181
|
+
sent.push(key);
|
|
182
|
+
return Promise.resolve('created again');
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
expect(sent).toEqual(['key-1', 'key-1', 'key-2']);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it('drops the key after a rejection that did not commit', async () => {
|
|
189
|
+
const keys = store();
|
|
190
|
+
await expect(
|
|
191
|
+
sendIdempotentMutation(keys, intent, () =>
|
|
192
|
+
Promise.reject(apiError(400, 'validation_failed')),
|
|
193
|
+
),
|
|
194
|
+
).rejects.toBeInstanceOf(ApiError);
|
|
195
|
+
|
|
196
|
+
await expect(keys.keyFor(intent)).resolves.toBe('key-2');
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
describe('canonicalJson', () => {
|
|
201
|
+
it('sorts object members at every depth and keeps array order', () => {
|
|
202
|
+
expect(canonicalJson({ b: [2, { d: 1, c: null }], a: 'x' })).toBe(
|
|
203
|
+
'{"a":"x","b":[2,{"c":null,"d":1}]}',
|
|
204
|
+
);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it('leaves out undefined members and writes undefined array items as null', () => {
|
|
208
|
+
expect(canonicalJson({ b: undefined, a: [1, undefined] })).toBe('{"a":[1,null]}');
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it('rejects non-finite numbers', () => {
|
|
212
|
+
expect(() => canonicalJson(Number.POSITIVE_INFINITY)).toThrow('non-finite');
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
describe('JSON-compatible bodies', () => {
|
|
217
|
+
interface ChoiceBody {
|
|
218
|
+
readonly text: string;
|
|
219
|
+
readonly audio?: string | null | undefined;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
interface DraftBody {
|
|
223
|
+
readonly title: string;
|
|
224
|
+
readonly choices: readonly ChoiceBody[];
|
|
225
|
+
readonly quality: 'strong' | 'weak';
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
it('accepts interface bodies without an index signature', async () => {
|
|
229
|
+
const keys = store();
|
|
230
|
+
const body: DraftBody = { title: 'intro', choices: [{ text: 'hi' }], quality: 'strong' };
|
|
231
|
+
const sent: string[] = [];
|
|
232
|
+
|
|
233
|
+
await sendIdempotentMutation(keys, { account: 'a', operation: 'createDraft', body }, (key) => {
|
|
234
|
+
sent.push(key);
|
|
235
|
+
return Promise.resolve();
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
expect(sent).toEqual(['key-1']);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it('gives a body with undefined members the key of the body without them', async () => {
|
|
242
|
+
const keys = store();
|
|
243
|
+
const sparse: DraftBody = {
|
|
244
|
+
title: 'intro',
|
|
245
|
+
choices: [{ text: 'hi', audio: undefined }],
|
|
246
|
+
quality: 'weak',
|
|
247
|
+
};
|
|
248
|
+
const dense: DraftBody = { title: 'intro', choices: [{ text: 'hi' }], quality: 'weak' };
|
|
249
|
+
|
|
250
|
+
const first = await keys.keyFor({ account: 'a', operation: 'createDraft', body: sparse });
|
|
251
|
+
|
|
252
|
+
await expect(
|
|
253
|
+
keys.keyFor({ account: 'a', operation: 'createDraft', body: dense }),
|
|
254
|
+
).resolves.toBe(first);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it('rejects bodies that JSON cannot carry unchanged', () => {
|
|
258
|
+
const keys = store();
|
|
259
|
+
// @ts-expect-error a Date is not a JSON value
|
|
260
|
+
void keys.keyFor({ account: 'a', operation: 'op', body: { at: new Date(0) } });
|
|
261
|
+
// @ts-expect-error a function is not a JSON value
|
|
262
|
+
void keys.keyFor({ account: 'a', operation: 'op', body: { run: () => 1 } });
|
|
263
|
+
// @ts-expect-error an unknown member is not known to be JSON
|
|
264
|
+
void keys.keyFor({ account: 'a', operation: 'op', body: { value: 1 as unknown } });
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
describe('product error classification', () => {
|
|
269
|
+
class ProductApiError extends Error {
|
|
270
|
+
constructor(
|
|
271
|
+
readonly status: number,
|
|
272
|
+
readonly code?: string,
|
|
273
|
+
) {
|
|
274
|
+
super('product failure');
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function classifyProductError(error: unknown) {
|
|
279
|
+
return error instanceof ProductApiError
|
|
280
|
+
? classifyMutationStatus(error.status, error.code)
|
|
281
|
+
: undefined;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
it('drops the key when the product classifier reports a definite rejection', async () => {
|
|
285
|
+
const keys = createIdempotencyKeyStore({
|
|
286
|
+
ttlMs: TTL_MS,
|
|
287
|
+
keyFactory: counterKeys(),
|
|
288
|
+
classifyError: classifyProductError,
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
await expect(
|
|
292
|
+
sendIdempotentMutation(keys, intent, () => Promise.reject(new ProductApiError(422))),
|
|
293
|
+
).rejects.toBeInstanceOf(ProductApiError);
|
|
294
|
+
|
|
295
|
+
await expect(keys.keyFor(intent)).resolves.toBe('key-2');
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
it('falls back to the Baukit classifier for errors the product does not know', () => {
|
|
299
|
+
const keys = createIdempotencyKeyStore({ ttlMs: TTL_MS, classifyError: classifyProductError });
|
|
300
|
+
|
|
301
|
+
expect(keys.classifyError(new ProductApiError(409, 'idempotency_key_in_progress'))).toBe(
|
|
302
|
+
'possibly-committed',
|
|
303
|
+
);
|
|
304
|
+
expect(keys.classifyError(new ProductApiError(404))).toBe('not-committed');
|
|
305
|
+
expect(keys.classifyError(apiError(400, 'validation_failed'))).toBe('not-committed');
|
|
306
|
+
expect(keys.classifyError(new TypeError('offline'))).toBe('possibly-committed');
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
it('keeps the key for a product error when no classifier is set', async () => {
|
|
310
|
+
const keys = store();
|
|
311
|
+
|
|
312
|
+
await expect(
|
|
313
|
+
sendIdempotentMutation(keys, intent, () => Promise.reject(new ProductApiError(422))),
|
|
314
|
+
).rejects.toBeInstanceOf(ProductApiError);
|
|
315
|
+
|
|
316
|
+
await expect(keys.keyFor(intent)).resolves.toBe('key-1');
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
it('treats the in-progress code as possibly committed', () => {
|
|
320
|
+
expect(classifyMutationStatus(409, 'idempotency_key_in_progress')).toBe('possibly-committed');
|
|
321
|
+
expect(classifyMutationStatus(409, 'idempotency_key_reused')).toBe('not-committed');
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
describe('concurrent keyFor calls', () => {
|
|
326
|
+
const droppingStorage = (): IdempotencyKeyStorage => ({
|
|
327
|
+
get: () => null,
|
|
328
|
+
set: () => undefined,
|
|
329
|
+
delete: () => undefined,
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
function gatedStorage(): IdempotencyKeyStorage & { open(): void } {
|
|
333
|
+
const saved = new Map<string, StoredIdempotencyKey>();
|
|
334
|
+
let opened: () => void = () => undefined;
|
|
335
|
+
const gate = new Promise<void>((resolve) => {
|
|
336
|
+
opened = resolve;
|
|
337
|
+
});
|
|
338
|
+
return {
|
|
339
|
+
async get(slot) {
|
|
340
|
+
await gate;
|
|
341
|
+
return saved.get(slot) ?? null;
|
|
342
|
+
},
|
|
343
|
+
async set(slot, value) {
|
|
344
|
+
await gate;
|
|
345
|
+
saved.set(slot, value);
|
|
346
|
+
},
|
|
347
|
+
delete(slot) {
|
|
348
|
+
saved.delete(slot);
|
|
349
|
+
},
|
|
350
|
+
open: () => {
|
|
351
|
+
opened();
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
it('share one key while the first lookup is still reading storage', async () => {
|
|
357
|
+
const storage = gatedStorage();
|
|
358
|
+
const keys = store(() => 0, storage);
|
|
359
|
+
|
|
360
|
+
const first = keys.keyFor(intent);
|
|
361
|
+
const second = keys.keyFor(intent);
|
|
362
|
+
storage.open();
|
|
363
|
+
|
|
364
|
+
await expect(Promise.all([first, second])).resolves.toEqual(['key-1', 'key-1']);
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
it('share one key when storage drops writes, until the intent settles', async () => {
|
|
368
|
+
const keys = store(() => 0, droppingStorage());
|
|
369
|
+
|
|
370
|
+
const first = await keys.keyFor(intent);
|
|
371
|
+
await expect(keys.keyFor(intent)).resolves.toBe(first);
|
|
372
|
+
|
|
373
|
+
await keys.settle(intent, 'committed');
|
|
374
|
+
await expect(keys.keyFor(intent)).resolves.not.toBe(first);
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
it('do not reuse a held key after its time to live', async () => {
|
|
378
|
+
let now = 0;
|
|
379
|
+
const keys = store(() => now, droppingStorage());
|
|
380
|
+
|
|
381
|
+
const first = await keys.keyFor(intent);
|
|
382
|
+
now = TTL_MS;
|
|
383
|
+
|
|
384
|
+
await expect(keys.keyFor(intent)).resolves.not.toBe(first);
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
it('recover when an earlier lookup failed', async () => {
|
|
388
|
+
let failNext = true;
|
|
389
|
+
const flaky: IdempotencyKeyStorage = {
|
|
390
|
+
...droppingStorage(),
|
|
391
|
+
get: () => {
|
|
392
|
+
if (failNext) {
|
|
393
|
+
failNext = false;
|
|
394
|
+
return Promise.reject(new Error('storage offline'));
|
|
395
|
+
}
|
|
396
|
+
return null;
|
|
397
|
+
},
|
|
398
|
+
};
|
|
399
|
+
const keys = store(() => 0, flaky);
|
|
400
|
+
|
|
401
|
+
const failed = keys.keyFor(intent);
|
|
402
|
+
const next = keys.keyFor(intent);
|
|
403
|
+
|
|
404
|
+
await expect(failed).rejects.toThrow('storage offline');
|
|
405
|
+
await expect(next).resolves.toBe('key-1');
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
it('send two in-flight mutations for one intent with one key', async () => {
|
|
409
|
+
const keys = store();
|
|
410
|
+
const sent: string[] = [];
|
|
411
|
+
const send = (key: string) => {
|
|
412
|
+
sent.push(key);
|
|
413
|
+
return Promise.resolve();
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
await Promise.all([
|
|
417
|
+
sendIdempotentMutation(keys, intent, send),
|
|
418
|
+
sendIdempotentMutation(keys, intent, send),
|
|
419
|
+
]);
|
|
420
|
+
|
|
421
|
+
expect(sent).toEqual(['key-1', 'key-1']);
|
|
422
|
+
});
|
|
423
|
+
});
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { ApiError, HttpError, type JsonValue } from './index.js';
|
|
2
|
+
|
|
3
|
+
/** The server rejected the key because its first request is still running. */
|
|
4
|
+
export const IDEMPOTENCY_KEY_IN_PROGRESS_CODE = 'idempotency_key_in_progress' as const;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* What the client knows about one mutation attempt.
|
|
8
|
+
*
|
|
9
|
+
* `possibly-committed` means the server may have applied the effect, so a retry must reuse the key.
|
|
10
|
+
*/
|
|
11
|
+
export type MutationAttemptOutcome = 'committed' | 'not-committed' | 'possibly-committed';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Accepts `Value` when it serializes to JSON unchanged, including interfaces that have no index
|
|
15
|
+
* signature. Object members may be `undefined`, which JSON omits.
|
|
16
|
+
*/
|
|
17
|
+
export type JsonCompatible<Value> = { readonly [Key in keyof Value]: JsonMember<Value[Key]> };
|
|
18
|
+
|
|
19
|
+
type JsonMember<Value> = Value extends undefined | JsonValue
|
|
20
|
+
? Value
|
|
21
|
+
: Value extends (...args: never[]) => unknown
|
|
22
|
+
? never
|
|
23
|
+
: JsonCompatible<Value>;
|
|
24
|
+
|
|
25
|
+
/** One logical write. Two intents with equal fields share a key. */
|
|
26
|
+
export interface MutationIntent<Body extends JsonCompatible<Body> = JsonValue> {
|
|
27
|
+
/** The signed-in account, so keys never cross an account switch. */
|
|
28
|
+
readonly account: string;
|
|
29
|
+
/** A stable operation name, such as `createNote`. Include the target ID when there is one. */
|
|
30
|
+
readonly operation: string;
|
|
31
|
+
/** The request body, plus the expected revision for conditional writes. */
|
|
32
|
+
readonly body: Body;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Classifies a product error, or returns `undefined` to fall back to {@link classifyMutationError}. */
|
|
36
|
+
export type MutationErrorClassifier = (error: unknown) => MutationAttemptOutcome | undefined;
|
|
37
|
+
|
|
38
|
+
/** A key kept for one intent. */
|
|
39
|
+
export interface StoredIdempotencyKey {
|
|
40
|
+
readonly key: string;
|
|
41
|
+
readonly createdAtMs: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Where an idempotency key store keeps keys.
|
|
46
|
+
*
|
|
47
|
+
* `slot` is the canonical JSON of the intent. A persistent adapter should store a digest of it,
|
|
48
|
+
* not the text, when request bodies are sensitive.
|
|
49
|
+
*/
|
|
50
|
+
export interface IdempotencyKeyStorage {
|
|
51
|
+
get(slot: string): StoredIdempotencyKey | null | Promise<StoredIdempotencyKey | null>;
|
|
52
|
+
set(slot: string, value: StoredIdempotencyKey): void | Promise<void>;
|
|
53
|
+
delete(slot: string): void | Promise<void>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Options for {@link createIdempotencyKeyStore}. */
|
|
57
|
+
export interface IdempotencyKeyStoreOptions {
|
|
58
|
+
/** How long a key is reused. Keep it below the server's replay retention. */
|
|
59
|
+
readonly ttlMs: number;
|
|
60
|
+
/** Clock seam. Defaults to `Date.now`. */
|
|
61
|
+
readonly now?: () => number;
|
|
62
|
+
/** Key factory. Defaults to `crypto.randomUUID`. */
|
|
63
|
+
readonly keyFactory?: () => string;
|
|
64
|
+
/** Key storage. Defaults to an in-memory map that a reload clears. */
|
|
65
|
+
readonly storage?: IdempotencyKeyStorage;
|
|
66
|
+
/** Classifies the product's own API errors before the Baukit defaults apply. */
|
|
67
|
+
readonly classifyError?: MutationErrorClassifier;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Keeps one key per account, operation, and body until a definite outcome or expiry. */
|
|
71
|
+
export interface IdempotencyKeyStore {
|
|
72
|
+
/**
|
|
73
|
+
* Returns the live key for the intent, or creates one. Calls for the same intent share one key
|
|
74
|
+
* from the first call until the intent settles, even when storage is slow or drops writes.
|
|
75
|
+
*/
|
|
76
|
+
keyFor<Body extends JsonCompatible<Body>>(intent: MutationIntent<Body>): Promise<string>;
|
|
77
|
+
/** Drops the key after a definite outcome and keeps it while the outcome is uncertain. */
|
|
78
|
+
settle<Body extends JsonCompatible<Body>>(
|
|
79
|
+
intent: MutationIntent<Body>,
|
|
80
|
+
outcome: MutationAttemptOutcome,
|
|
81
|
+
): Promise<void>;
|
|
82
|
+
/** Classifies a failed send with the product classifier, then {@link classifyMutationError}. */
|
|
83
|
+
classifyError(error: unknown): MutationAttemptOutcome;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const OK_MIN = 200;
|
|
87
|
+
const OK_MAX = 299;
|
|
88
|
+
const CLIENT_ERROR_MIN = 400;
|
|
89
|
+
const SERVER_ERROR_MIN = 500;
|
|
90
|
+
const REQUEST_TIMEOUT = 408;
|
|
91
|
+
const TOO_MANY_REQUESTS = 429;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Classifies a mutation response status and, when the caller has it, the error code. The code
|
|
95
|
+
* `idempotency_key_in_progress` is `possibly-committed` whatever the status.
|
|
96
|
+
*/
|
|
97
|
+
export function classifyMutationStatus(status: number, code?: string): MutationAttemptOutcome {
|
|
98
|
+
if (code === IDEMPOTENCY_KEY_IN_PROGRESS_CODE) {
|
|
99
|
+
return 'possibly-committed';
|
|
100
|
+
}
|
|
101
|
+
if (status >= OK_MIN && status <= OK_MAX) {
|
|
102
|
+
return 'committed';
|
|
103
|
+
}
|
|
104
|
+
if (status === REQUEST_TIMEOUT || status === TOO_MANY_REQUESTS || status >= SERVER_ERROR_MIN) {
|
|
105
|
+
return 'possibly-committed';
|
|
106
|
+
}
|
|
107
|
+
if (status >= CLIENT_ERROR_MIN) {
|
|
108
|
+
return 'not-committed';
|
|
109
|
+
}
|
|
110
|
+
return 'possibly-committed';
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Classifies an error thrown by an `@baukit/api-runtime` fetch.
|
|
115
|
+
*
|
|
116
|
+
* Network errors, aborts, and unknown throws are `possibly-committed`, because the request may
|
|
117
|
+
* have reached the server. So is 409 `idempotency_key_in_progress`.
|
|
118
|
+
*/
|
|
119
|
+
export function classifyMutationError(error: unknown): MutationAttemptOutcome {
|
|
120
|
+
if (error instanceof ApiError) {
|
|
121
|
+
if (error.code === IDEMPOTENCY_KEY_IN_PROGRESS_CODE) {
|
|
122
|
+
return 'possibly-committed';
|
|
123
|
+
}
|
|
124
|
+
return classifyMutationStatus(error.status);
|
|
125
|
+
}
|
|
126
|
+
if (error instanceof HttpError) {
|
|
127
|
+
return classifyMutationStatus(error.status);
|
|
128
|
+
}
|
|
129
|
+
return 'possibly-committed';
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Creates a key store. */
|
|
133
|
+
export function createIdempotencyKeyStore(
|
|
134
|
+
options: IdempotencyKeyStoreOptions,
|
|
135
|
+
): IdempotencyKeyStore {
|
|
136
|
+
if (!Number.isFinite(options.ttlMs) || options.ttlMs <= 0) {
|
|
137
|
+
throw new Error('ttlMs must be a finite positive number');
|
|
138
|
+
}
|
|
139
|
+
const now = options.now ?? Date.now;
|
|
140
|
+
const keyFactory = options.keyFactory ?? (() => globalThis.crypto.randomUUID());
|
|
141
|
+
const storage = options.storage ?? memoryStorage();
|
|
142
|
+
const classifyProductError = options.classifyError ?? (() => undefined);
|
|
143
|
+
const unsettled = new Map<string, Promise<StoredIdempotencyKey>>();
|
|
144
|
+
const isLive = (stored: StoredIdempotencyKey) => now() - stored.createdAtMs < options.ttlMs;
|
|
145
|
+
|
|
146
|
+
const loadOrCreate = async (slot: string): Promise<StoredIdempotencyKey> => {
|
|
147
|
+
const stored = await storage.get(slot);
|
|
148
|
+
if (stored !== null && isLive(stored)) {
|
|
149
|
+
return stored;
|
|
150
|
+
}
|
|
151
|
+
const fresh = { key: keyFactory(), createdAtMs: now() };
|
|
152
|
+
await storage.set(slot, fresh);
|
|
153
|
+
return fresh;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const reuseOrLoad = async (
|
|
157
|
+
slot: string,
|
|
158
|
+
earlier: Promise<StoredIdempotencyKey> | undefined,
|
|
159
|
+
): Promise<StoredIdempotencyKey> => {
|
|
160
|
+
const held = await earlier?.catch(() => undefined);
|
|
161
|
+
if (held !== undefined && isLive(held)) {
|
|
162
|
+
return held;
|
|
163
|
+
}
|
|
164
|
+
return loadOrCreate(slot);
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
async keyFor(intent) {
|
|
169
|
+
const slot = intentSlot(intent);
|
|
170
|
+
const pending = reuseOrLoad(slot, unsettled.get(slot));
|
|
171
|
+
unsettled.set(slot, pending);
|
|
172
|
+
return (await pending).key;
|
|
173
|
+
},
|
|
174
|
+
async settle(intent, outcome) {
|
|
175
|
+
const slot = intentSlot(intent);
|
|
176
|
+
unsettled.delete(slot);
|
|
177
|
+
if (outcome === 'possibly-committed') {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
await storage.delete(slot);
|
|
181
|
+
},
|
|
182
|
+
classifyError(error) {
|
|
183
|
+
return classifyProductError(error) ?? classifyMutationError(error);
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Sends one keyed mutation and settles its key.
|
|
190
|
+
*
|
|
191
|
+
* `send` receives the key to put in the `Idempotency-Key` header. A throw is classified with the
|
|
192
|
+
* store's `classifyError`, settled, and rethrown.
|
|
193
|
+
*/
|
|
194
|
+
export async function sendIdempotentMutation<Result, Body extends JsonCompatible<Body> = JsonValue>(
|
|
195
|
+
store: IdempotencyKeyStore,
|
|
196
|
+
intent: MutationIntent<Body>,
|
|
197
|
+
send: (key: string) => Promise<Result>,
|
|
198
|
+
): Promise<Result> {
|
|
199
|
+
const key = await store.keyFor(intent);
|
|
200
|
+
let result: Result;
|
|
201
|
+
try {
|
|
202
|
+
result = await send(key);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
await store.settle(intent, store.classifyError(error));
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
await store.settle(intent, 'committed');
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Serializes JSON with object members sorted by key, so equal values give equal text. Members
|
|
213
|
+
* whose value is `undefined` are left out, as `JSON.stringify` leaves them out.
|
|
214
|
+
*/
|
|
215
|
+
export function canonicalJson<Value extends JsonCompatible<Value>>(value: Value): string {
|
|
216
|
+
return canonicalText(value);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function canonicalText(value: unknown): string {
|
|
220
|
+
if (value === undefined) {
|
|
221
|
+
throw new Error('canonical JSON cannot encode undefined');
|
|
222
|
+
}
|
|
223
|
+
if (Array.isArray(value)) {
|
|
224
|
+
return `[${value.map(canonicalItem).join(',')}]`;
|
|
225
|
+
}
|
|
226
|
+
if (value !== null && typeof value === 'object') {
|
|
227
|
+
const members = Object.entries(value)
|
|
228
|
+
.filter(([, member]) => member !== undefined)
|
|
229
|
+
.sort(([left], [right]) => (left < right ? -1 : 1))
|
|
230
|
+
.map(([key, member]) => `${JSON.stringify(key)}:${canonicalText(member)}`);
|
|
231
|
+
return `{${members.join(',')}}`;
|
|
232
|
+
}
|
|
233
|
+
if (typeof value === 'number' && !Number.isFinite(value)) {
|
|
234
|
+
throw new Error('canonical JSON cannot encode a non-finite number');
|
|
235
|
+
}
|
|
236
|
+
return JSON.stringify(value);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function canonicalItem(item: unknown): string {
|
|
240
|
+
return item === undefined ? 'null' : canonicalText(item);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function intentSlot<Body extends JsonCompatible<Body>>(intent: MutationIntent<Body>): string {
|
|
244
|
+
return canonicalText([intent.account, intent.operation, intent.body]);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function memoryStorage(): IdempotencyKeyStorage {
|
|
248
|
+
const keys = new Map<string, StoredIdempotencyKey>();
|
|
249
|
+
return {
|
|
250
|
+
get: (slot) => keys.get(slot) ?? null,
|
|
251
|
+
set: (slot, value) => {
|
|
252
|
+
keys.set(slot, value);
|
|
253
|
+
},
|
|
254
|
+
delete: (slot) => {
|
|
255
|
+
keys.delete(slot);
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|