@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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baukit/api-runtime",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "Shared client-side behavior for product APIs: environment selection, auth and request-ID headers, trace propagation, normalized errors, and safe retries.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Patrick Koss",
|
|
@@ -45,6 +45,7 @@
|
|
|
45
45
|
},
|
|
46
46
|
"files": [
|
|
47
47
|
"dist",
|
|
48
|
+
"src",
|
|
48
49
|
"README.md",
|
|
49
50
|
"LICENSE"
|
|
50
51
|
],
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { fullJitterBackoffMs } from './backoff.js';
|
|
4
|
+
|
|
5
|
+
const policy = { baseDelayMs: 100, maxDelayMs: 1_000 };
|
|
6
|
+
|
|
7
|
+
describe('fullJitterBackoffMs', () => {
|
|
8
|
+
it('doubles the ceiling per retry and caps it', () => {
|
|
9
|
+
const top = { ...policy, random: () => 1 };
|
|
10
|
+
|
|
11
|
+
expect([0, 1, 2, 3, 4, 10].map((index) => fullJitterBackoffMs(index, top))).toEqual([
|
|
12
|
+
100, 200, 400, 800, 1_000, 1_000,
|
|
13
|
+
]);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('scales the ceiling by the random sample', () => {
|
|
17
|
+
expect(fullJitterBackoffMs(2, { ...policy, random: () => 0.25 })).toBe(100);
|
|
18
|
+
expect(fullJitterBackoffMs(2, { ...policy, random: () => 0 })).toBe(0);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('clamps samples outside zero to one', () => {
|
|
22
|
+
expect(fullJitterBackoffMs(0, { ...policy, random: () => 2 })).toBe(100);
|
|
23
|
+
expect(fullJitterBackoffMs(0, { ...policy, random: () => -1 })).toBe(0);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('defaults to Math.random within the ceiling', () => {
|
|
27
|
+
const delay = fullJitterBackoffMs(1, policy);
|
|
28
|
+
|
|
29
|
+
expect(delay).toBeGreaterThanOrEqual(0);
|
|
30
|
+
expect(delay).toBeLessThanOrEqual(200);
|
|
31
|
+
});
|
|
32
|
+
});
|
package/src/backoff.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Exponential backoff with full jitter. The retry index counts from 0. */
|
|
2
|
+
export interface BackoffPolicy {
|
|
3
|
+
/** Ceiling for the first retry, doubled for each later one. */
|
|
4
|
+
readonly baseDelayMs: number;
|
|
5
|
+
/** The ceiling never grows past this. */
|
|
6
|
+
readonly maxDelayMs: number;
|
|
7
|
+
/** Random source in `[0, 1]`. Values outside are clamped. Defaults to `Math.random`. */
|
|
8
|
+
readonly random?: () => number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const EXPONENT_BASE = 2;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Returns a delay between 0 and `min(maxDelayMs, baseDelayMs * 2 ** retryIndex)`.
|
|
15
|
+
*
|
|
16
|
+
* Full jitter spreads clients that failed together, so they do not retry together.
|
|
17
|
+
*/
|
|
18
|
+
export function fullJitterBackoffMs(retryIndex: number, policy: BackoffPolicy): number {
|
|
19
|
+
const ceiling = Math.min(policy.maxDelayMs, policy.baseDelayMs * EXPONENT_BASE ** retryIndex);
|
|
20
|
+
const sample = (policy.random ?? Math.random)();
|
|
21
|
+
return ceiling * Math.max(0, Math.min(1, sample));
|
|
22
|
+
}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import receiptVectors from '../../../../fixtures/erasure/receipts-v1.json' with { type: 'json' };
|
|
4
|
+
|
|
5
|
+
import { ApiError, createApiRuntime, MockFetch } from './index.js';
|
|
6
|
+
import { type IdempotencyKeyStorage, type StoredIdempotencyKey } from './idempotency.js';
|
|
7
|
+
import { AmbiguousProfileErasureError, createProfileErasureClient } from './erasure.js';
|
|
8
|
+
|
|
9
|
+
const operationId = 'c6417b1e-4092-4ab8-8dce-e16222c160f3';
|
|
10
|
+
const key = 'b7e64cbd-4521-4515-b4c7-3ffb1c7a72b7';
|
|
11
|
+
const completedAt = '2026-10-03T12:00:00Z';
|
|
12
|
+
const pending = { status: 'pending', operationId };
|
|
13
|
+
const completed = { status: 'completed', operationId, completedAt };
|
|
14
|
+
|
|
15
|
+
function storage(): IdempotencyKeyStorage & {
|
|
16
|
+
readonly entries: ReadonlyMap<string, StoredIdempotencyKey>;
|
|
17
|
+
} {
|
|
18
|
+
const persisted = new Map<string, StoredIdempotencyKey>();
|
|
19
|
+
return {
|
|
20
|
+
entries: persisted,
|
|
21
|
+
get: (slot) => persisted.get(slot) ?? null,
|
|
22
|
+
set: (slot, value) => {
|
|
23
|
+
persisted.set(slot, value);
|
|
24
|
+
},
|
|
25
|
+
delete: (slot) => {
|
|
26
|
+
persisted.delete(slot);
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function setup(persisted = storage(), account = 'subject-a') {
|
|
32
|
+
const transport = new MockFetch();
|
|
33
|
+
const runtime = createApiRuntime({
|
|
34
|
+
baseUrl: 'https://api.example.test',
|
|
35
|
+
environment: 'test',
|
|
36
|
+
fetch: transport.fetch,
|
|
37
|
+
retry: false,
|
|
38
|
+
});
|
|
39
|
+
const client = createProfileErasureClient({
|
|
40
|
+
fetch: runtime.fetch,
|
|
41
|
+
account,
|
|
42
|
+
storage: persisted,
|
|
43
|
+
keyFactory: () => key,
|
|
44
|
+
});
|
|
45
|
+
return { client, transport };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function errorBody(code: string) {
|
|
49
|
+
return { error: { code, message: 'Request rejected', requestId: 'request-1', details: {} } };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
afterEach(() => {
|
|
53
|
+
vi.useRealTimers();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('profile erasure transport', () => {
|
|
57
|
+
it.each(receiptVectors.cases)('matches the shared $name contract', async (vector) => {
|
|
58
|
+
const persisted = storage();
|
|
59
|
+
const { client, transport } = setup(persisted);
|
|
60
|
+
transport.enqueueJson(vector.receipt, { status: vector.httpStatus });
|
|
61
|
+
if (vector.clientOutcome === 'failed') {
|
|
62
|
+
await expect(client.erase()).rejects.toMatchObject({
|
|
63
|
+
name: 'ProfileErasureOperationFailedError',
|
|
64
|
+
code: 'erasure_operation_failed',
|
|
65
|
+
operationId: vector.receipt.operationId,
|
|
66
|
+
});
|
|
67
|
+
expect(persisted.entries.size).toBe(1);
|
|
68
|
+
transport.enqueueJson(completed, { status: 200 });
|
|
69
|
+
await expect(client.erase()).resolves.toEqual(completed);
|
|
70
|
+
expect(transport.request(1).headers.get('Idempotency-Key')).toBe(key);
|
|
71
|
+
} else {
|
|
72
|
+
await expect(client.erase()).resolves.toEqual(vector.receipt);
|
|
73
|
+
}
|
|
74
|
+
expect(persisted.entries.size).toBe(0);
|
|
75
|
+
});
|
|
76
|
+
it.each([
|
|
77
|
+
[200, completed],
|
|
78
|
+
[202, pending],
|
|
79
|
+
] as const)('parses a %i receipt and sends a persisted key', async (status, body) => {
|
|
80
|
+
const persisted = storage();
|
|
81
|
+
const set = vi.spyOn(persisted, 'set');
|
|
82
|
+
const { client, transport } = setup(persisted);
|
|
83
|
+
transport.enqueue((request) => {
|
|
84
|
+
expect(set).toHaveBeenCalledOnce();
|
|
85
|
+
expect(request.headers.get('Idempotency-Key')).toBe(key);
|
|
86
|
+
return Response.json(body, { status });
|
|
87
|
+
});
|
|
88
|
+
await expect(client.erase()).resolves.toEqual(body);
|
|
89
|
+
expect(persisted.entries.size).toBe(0);
|
|
90
|
+
transport.assertRequest(0, { method: 'DELETE', url: 'https://api.example.test/me' });
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('replays the persisted key in a new client after a dropped response', async () => {
|
|
94
|
+
const persisted = storage();
|
|
95
|
+
const first = setup(persisted);
|
|
96
|
+
first.transport.enqueue(new TypeError('Connection dropped after commit'));
|
|
97
|
+
await expect(first.client.erase()).rejects.toBeInstanceOf(AmbiguousProfileErasureError);
|
|
98
|
+
|
|
99
|
+
expect(persisted.entries.size).toBe(1);
|
|
100
|
+
const second = setup(persisted);
|
|
101
|
+
second.transport.enqueueJson(pending, { status: 202 });
|
|
102
|
+
await expect(second.client.erase()).resolves.toEqual(pending);
|
|
103
|
+
expect(persisted.entries.size).toBe(0);
|
|
104
|
+
expect(second.transport.request(0).headers.get('Idempotency-Key')).toBe(
|
|
105
|
+
first.transport.request(0).headers.get('Idempotency-Key'),
|
|
106
|
+
);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it.each([
|
|
110
|
+
[200, completed],
|
|
111
|
+
[202, pending],
|
|
112
|
+
] as const)('preserves the committed %i receipt if key removal fails', async (status, body) => {
|
|
113
|
+
const persisted = storage();
|
|
114
|
+
vi.spyOn(persisted, 'delete').mockRejectedValue(new Error('Storage unavailable'));
|
|
115
|
+
const { client, transport } = setup(persisted);
|
|
116
|
+
transport.enqueueJson(body, { status });
|
|
117
|
+
await expect(client.erase()).rejects.toMatchObject({
|
|
118
|
+
name: 'ProfileErasureKeyCleanupError',
|
|
119
|
+
receipt: body,
|
|
120
|
+
});
|
|
121
|
+
expect(persisted.entries.size).toBe(1);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('reports 409 as a definite rejection and releases its key', async () => {
|
|
125
|
+
const persisted = storage();
|
|
126
|
+
const remove = vi.spyOn(persisted, 'delete');
|
|
127
|
+
const { client, transport } = setup(persisted);
|
|
128
|
+
transport.enqueueJson(errorBody('erasure_idempotency_conflict'), { status: 409 });
|
|
129
|
+
await expect(client.erase()).rejects.toMatchObject({
|
|
130
|
+
status: 409,
|
|
131
|
+
code: 'erasure_idempotency_conflict',
|
|
132
|
+
});
|
|
133
|
+
expect(remove).toHaveBeenCalledOnce();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('accepts a 401 profile_erased as committed with identity deletion still unconfirmed', async () => {
|
|
137
|
+
const persisted = storage();
|
|
138
|
+
const { client, transport } = setup(persisted);
|
|
139
|
+
transport.enqueueJson(errorBody('profile_erased'), { status: 401 });
|
|
140
|
+
await expect(client.erase()).resolves.toEqual({ status: 'pending', operationId: null });
|
|
141
|
+
expect(persisted.entries.size).toBe(0);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('retains the original key if a later retry is unauthorized after a lost response', async () => {
|
|
145
|
+
const persisted = storage();
|
|
146
|
+
const remove = vi.spyOn(persisted, 'delete');
|
|
147
|
+
const first = setup(persisted);
|
|
148
|
+
first.transport.enqueue(new TypeError('Response lost after commit'));
|
|
149
|
+
await expect(first.client.erase()).rejects.toBeInstanceOf(AmbiguousProfileErasureError);
|
|
150
|
+
const second = setup(persisted);
|
|
151
|
+
second.transport.enqueueJson(errorBody('unauthorized'), { status: 401 });
|
|
152
|
+
await expect(second.client.erase()).rejects.toMatchObject({ status: 401 });
|
|
153
|
+
expect(remove).not.toHaveBeenCalled();
|
|
154
|
+
const third = setup(persisted);
|
|
155
|
+
third.transport.enqueueJson(pending, { status: 202 });
|
|
156
|
+
await expect(third.client.erase()).resolves.toEqual(pending);
|
|
157
|
+
expect(third.transport.request(0).headers.get('Idempotency-Key')).toBe(
|
|
158
|
+
first.transport.request(0).headers.get('Idempotency-Key'),
|
|
159
|
+
);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('also handles a raw fetch that returns the fence response', async () => {
|
|
163
|
+
const fetch = vi.fn(() =>
|
|
164
|
+
Promise.resolve(Response.json(errorBody('profile_erased'), { status: 401 })),
|
|
165
|
+
);
|
|
166
|
+
const client = createProfileErasureClient({
|
|
167
|
+
fetch,
|
|
168
|
+
account: 'account',
|
|
169
|
+
storage: storage(),
|
|
170
|
+
keyFactory: () => key,
|
|
171
|
+
});
|
|
172
|
+
await expect(client.erase()).resolves.toEqual({ status: 'pending', operationId: null });
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('keeps an ordinary 401 as a rejection', async () => {
|
|
176
|
+
const { client, transport } = setup();
|
|
177
|
+
transport.enqueueJson(errorBody('unauthorized'), { status: 401 });
|
|
178
|
+
await expect(client.erase()).rejects.toBeInstanceOf(ApiError);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it.each([
|
|
182
|
+
[200, pending],
|
|
183
|
+
[202, completed],
|
|
184
|
+
[200, { ...completed, completedAt: 'bad' }],
|
|
185
|
+
[200, { ...completed, operationId: 'not-a-uuid' }],
|
|
186
|
+
[200, { status: 'completed', operationId }],
|
|
187
|
+
[202, { ...pending, status: 'failed' }],
|
|
188
|
+
[204, null],
|
|
189
|
+
[200, null],
|
|
190
|
+
])('keeps malformed %i replies ambiguous', async (status, body) => {
|
|
191
|
+
const persisted = storage();
|
|
192
|
+
const remove = vi.spyOn(persisted, 'delete');
|
|
193
|
+
const { client, transport } = setup(persisted);
|
|
194
|
+
transport.enqueue(
|
|
195
|
+
status === 204 ? new Response(null, { status }) : Response.json(body, { status }),
|
|
196
|
+
);
|
|
197
|
+
await expect(client.erase()).rejects.toMatchObject({
|
|
198
|
+
code: 'product_profile_erasure_ambiguous',
|
|
199
|
+
});
|
|
200
|
+
expect(remove).not.toHaveBeenCalled();
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it('does not send if durable key storage fails', async () => {
|
|
204
|
+
const persisted = storage();
|
|
205
|
+
vi.spyOn(persisted, 'set').mockRejectedValue(new Error('Disk full'));
|
|
206
|
+
const { client, transport } = setup(persisted);
|
|
207
|
+
await expect(client.erase()).rejects.toThrow('Disk full');
|
|
208
|
+
expect(transport.requests).toHaveLength(0);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it('separates key storage slots by account', async () => {
|
|
212
|
+
const persisted = storage();
|
|
213
|
+
const set = vi.spyOn(persisted, 'set');
|
|
214
|
+
const first = setup(persisted, 'subject-a');
|
|
215
|
+
const second = setup(persisted, 'subject-b');
|
|
216
|
+
first.transport.enqueueJson(pending, { status: 202 });
|
|
217
|
+
second.transport.enqueueJson(pending, { status: 202 });
|
|
218
|
+
await first.client.erase();
|
|
219
|
+
await second.client.erase();
|
|
220
|
+
expect(set).toHaveBeenCalledTimes(2);
|
|
221
|
+
expect(set.mock.calls[0]?.[0]).not.toBe(set.mock.calls[1]?.[0]);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it('rejects an invalid key before sending', async () => {
|
|
225
|
+
const fetch = vi.fn();
|
|
226
|
+
const client = createProfileErasureClient({
|
|
227
|
+
fetch,
|
|
228
|
+
account: 'account',
|
|
229
|
+
storage: storage(),
|
|
230
|
+
keyFactory: () => 'short',
|
|
231
|
+
});
|
|
232
|
+
await expect(client.erase()).rejects.toThrow('Invalid erasure idempotency key.');
|
|
233
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
describe('profile erasure polling', () => {
|
|
238
|
+
it.each(['completed', 'failed'] as const)(
|
|
239
|
+
'polls to %s with capped exponential backoff',
|
|
240
|
+
async (status) => {
|
|
241
|
+
vi.useFakeTimers();
|
|
242
|
+
const { client, transport } = setup();
|
|
243
|
+
for (let index = 0; index < 4; index += 1) transport.enqueueJson(pending);
|
|
244
|
+
const terminal = status === 'completed' ? completed : { status, operationId };
|
|
245
|
+
transport.enqueueJson(terminal);
|
|
246
|
+
const polling = client.poll(operationId, { initialDelayMs: 100, maxDelayMs: 250 });
|
|
247
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
248
|
+
expect(transport.requests).toHaveLength(1);
|
|
249
|
+
for (const [index, delay] of [100, 200, 250, 250].entries()) {
|
|
250
|
+
await vi.advanceTimersByTimeAsync(delay - 1);
|
|
251
|
+
expect(transport.requests).toHaveLength(index + 1);
|
|
252
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
253
|
+
expect(transport.requests).toHaveLength(index + 2);
|
|
254
|
+
}
|
|
255
|
+
await expect(polling).resolves.toEqual(terminal);
|
|
256
|
+
transport.assertRequest(4, {
|
|
257
|
+
method: 'GET',
|
|
258
|
+
url: `https://api.example.test/me/erasures/${operationId}`,
|
|
259
|
+
});
|
|
260
|
+
expect(vi.getTimerCount()).toBe(0);
|
|
261
|
+
},
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
it('returns pending at the polling limit', async () => {
|
|
265
|
+
vi.useFakeTimers();
|
|
266
|
+
const { client, transport } = setup();
|
|
267
|
+
transport.enqueueJson(pending).enqueueJson(pending);
|
|
268
|
+
const polling = client.poll(operationId, { maxAttempts: 2 });
|
|
269
|
+
await vi.runAllTimersAsync();
|
|
270
|
+
await expect(polling).resolves.toEqual(pending);
|
|
271
|
+
expect(transport.requests).toHaveLength(2);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
it('aborts a backoff delay without sending another request', async () => {
|
|
275
|
+
vi.useFakeTimers();
|
|
276
|
+
const { client, transport } = setup();
|
|
277
|
+
transport.enqueueJson(pending);
|
|
278
|
+
const controller = new AbortController();
|
|
279
|
+
const polling = client.poll(operationId, { signal: controller.signal });
|
|
280
|
+
const rejected = expect(polling).rejects.toMatchObject({ name: 'AbortError' });
|
|
281
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
282
|
+
controller.abort();
|
|
283
|
+
await rejected;
|
|
284
|
+
expect(transport.requests).toHaveLength(1);
|
|
285
|
+
expect(vi.getTimerCount()).toBe(0);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it('aborts before sending and forwards the signal to in-flight reads', async () => {
|
|
289
|
+
const { client, transport } = setup();
|
|
290
|
+
const controller = new AbortController();
|
|
291
|
+
transport.enqueue((request) => {
|
|
292
|
+
expect(request.signal.aborted).toBe(false);
|
|
293
|
+
controller.abort();
|
|
294
|
+
return Response.json(pending);
|
|
295
|
+
});
|
|
296
|
+
await expect(client.poll(operationId, { signal: controller.signal })).rejects.toMatchObject({
|
|
297
|
+
aborted: true,
|
|
298
|
+
});
|
|
299
|
+
await expect(client.poll(operationId, { signal: controller.signal })).rejects.toMatchObject({
|
|
300
|
+
name: 'AbortError',
|
|
301
|
+
});
|
|
302
|
+
expect(transport.requests).toHaveLength(1);
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it('keeps profile_erased during polling pending rather than guessing that the IdP finished', async () => {
|
|
306
|
+
const { client, transport } = setup();
|
|
307
|
+
transport.enqueueJson(errorBody('profile_erased'), { status: 401 });
|
|
308
|
+
await expect(client.poll(operationId, { maxAttempts: 1 })).resolves.toEqual(pending);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
it('rejects a foreign operation receipt', async () => {
|
|
312
|
+
const { client, transport } = setup();
|
|
313
|
+
transport.enqueueJson({ ...completed, operationId: key });
|
|
314
|
+
await expect(client.poll(operationId)).rejects.toThrow('Erasure operation ID mismatch.');
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
it('preserves 404 and ordinary 401 errors', async () => {
|
|
318
|
+
const { client, transport } = setup();
|
|
319
|
+
transport.enqueueJson(errorBody('not_found'), { status: 404 });
|
|
320
|
+
transport.enqueueJson(errorBody('unauthorized'), { status: 401 });
|
|
321
|
+
await expect(client.poll(operationId)).rejects.toMatchObject({ status: 404 });
|
|
322
|
+
await expect(client.poll(operationId)).rejects.toMatchObject({ status: 401 });
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
it.each([{ maxAttempts: 0 }, { initialDelayMs: -1 }, { maxDelayMs: Number.NaN }])(
|
|
326
|
+
'rejects invalid polling settings %j',
|
|
327
|
+
async (polling) => {
|
|
328
|
+
const { client, transport } = setup();
|
|
329
|
+
await expect(client.poll(operationId, polling)).rejects.toBeInstanceOf(RangeError);
|
|
330
|
+
expect(transport.requests).toHaveLength(0);
|
|
331
|
+
},
|
|
332
|
+
);
|
|
333
|
+
});
|
package/src/erasure.ts
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { ApiError, normalizeResponseError, type FetchImplementation } from './index.js';
|
|
2
|
+
import {
|
|
3
|
+
classifyMutationError,
|
|
4
|
+
createIdempotencyKeyStore,
|
|
5
|
+
type IdempotencyKeyStorage,
|
|
6
|
+
} from './idempotency.js';
|
|
7
|
+
|
|
8
|
+
export type ProfileErasureReceipt =
|
|
9
|
+
| { readonly status: 'completed'; readonly operationId: string; readonly completedAt: string }
|
|
10
|
+
| { readonly status: 'pending'; readonly operationId: string | null };
|
|
11
|
+
|
|
12
|
+
export type ProfileErasureOperation =
|
|
13
|
+
| { readonly status: 'pending' | 'failed'; readonly operationId: string }
|
|
14
|
+
| { readonly status: 'completed'; readonly operationId: string; readonly completedAt?: string };
|
|
15
|
+
|
|
16
|
+
export interface ProfileErasureClientOptions {
|
|
17
|
+
readonly fetch: FetchImplementation;
|
|
18
|
+
readonly account: string;
|
|
19
|
+
/** Durable storage, separate from tokens so a lost response survives a reload. */
|
|
20
|
+
readonly storage: IdempotencyKeyStorage;
|
|
21
|
+
readonly keyFactory?: () => string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ProfileErasurePollingOptions {
|
|
25
|
+
readonly signal?: AbortSignal;
|
|
26
|
+
/** Total status reads. Defaults to 8. A still-pending operation is returned at the limit. */
|
|
27
|
+
readonly maxAttempts?: number;
|
|
28
|
+
readonly initialDelayMs?: number;
|
|
29
|
+
readonly maxDelayMs?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ProfileErasureClient {
|
|
33
|
+
erase(signal?: AbortSignal): Promise<ProfileErasureReceipt>;
|
|
34
|
+
poll(
|
|
35
|
+
operationId: string,
|
|
36
|
+
options?: ProfileErasurePollingOptions,
|
|
37
|
+
): Promise<ProfileErasureOperation>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A committed receipt whose durable key could not be removed from this device. */
|
|
41
|
+
export class ProfileErasureKeyCleanupError extends Error {
|
|
42
|
+
public override readonly name = 'ProfileErasureKeyCleanupError';
|
|
43
|
+
|
|
44
|
+
public constructor(
|
|
45
|
+
public readonly receipt: ProfileErasureReceipt,
|
|
46
|
+
cause: unknown,
|
|
47
|
+
) {
|
|
48
|
+
super('The committed erasure key could not be removed.', { cause });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Compatible with the ambiguous error contract in @baukit/data-contracts. */
|
|
53
|
+
export class AmbiguousProfileErasureError extends Error {
|
|
54
|
+
public override readonly name = 'AmbiguousProfileErasureError';
|
|
55
|
+
public readonly code = 'product_profile_erasure_ambiguous' as const;
|
|
56
|
+
|
|
57
|
+
public constructor(cause: unknown) {
|
|
58
|
+
super('The server erasure outcome is unknown.', { cause });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Product rows are erased, but the retained identity deletion job needs operator repair. */
|
|
63
|
+
export class ProfileErasureOperationFailedError extends Error {
|
|
64
|
+
public override readonly name = 'ProfileErasureOperationFailedError';
|
|
65
|
+
public readonly code = 'erasure_operation_failed' as const;
|
|
66
|
+
|
|
67
|
+
public constructor(public readonly operationId: string) {
|
|
68
|
+
super('Identity deletion failed. Contact support with the erasure operation ID.');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
73
|
+
const TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;
|
|
74
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7e]{16,128}$/u;
|
|
75
|
+
const INITIAL_DELAY_MS = 500;
|
|
76
|
+
const MAX_DELAY_MS = 5_000;
|
|
77
|
+
const MAX_ATTEMPTS = 8;
|
|
78
|
+
|
|
79
|
+
/** Creates a client for DELETE /me and its fenced-subject status endpoint. */
|
|
80
|
+
export function createProfileErasureClient(
|
|
81
|
+
options: ProfileErasureClientOptions,
|
|
82
|
+
): ProfileErasureClient {
|
|
83
|
+
if (options.account.trim() === '') throw new TypeError('An erasure account is required.');
|
|
84
|
+
const keys = createIdempotencyKeyStore({
|
|
85
|
+
// An uncertain erasure must keep its key, even if the user returns much later.
|
|
86
|
+
ttlMs: Number.MAX_SAFE_INTEGER,
|
|
87
|
+
storage: options.storage,
|
|
88
|
+
...(options.keyFactory === undefined ? {} : { keyFactory: options.keyFactory }),
|
|
89
|
+
});
|
|
90
|
+
const intent = { account: options.account, operation: 'profile.erase', body: null };
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
async erase(signal) {
|
|
94
|
+
signal?.throwIfAborted();
|
|
95
|
+
const key = await keys.keyFor(intent);
|
|
96
|
+
if (!IDEMPOTENCY_KEY_PATTERN.test(key))
|
|
97
|
+
throw new TypeError('Invalid erasure idempotency key.');
|
|
98
|
+
signal?.throwIfAborted();
|
|
99
|
+
let receipt: ProfileErasureReceipt;
|
|
100
|
+
try {
|
|
101
|
+
const response = await options.fetch('/me', {
|
|
102
|
+
method: 'DELETE',
|
|
103
|
+
headers: { 'Idempotency-Key': key },
|
|
104
|
+
...(signal === undefined ? {} : { signal }),
|
|
105
|
+
});
|
|
106
|
+
if (!response.ok) throw await normalizeResponseError(response);
|
|
107
|
+
const value: unknown = await response.json();
|
|
108
|
+
receipt = parseReceipt(value, response.status);
|
|
109
|
+
} catch (cause) {
|
|
110
|
+
if (cause instanceof ProfileErasureOperationFailedError) throw cause;
|
|
111
|
+
if (isErasedFence(cause)) {
|
|
112
|
+
receipt = { status: 'pending', operationId: null };
|
|
113
|
+
} else if (classifyMutationError(cause) === 'not-committed') {
|
|
114
|
+
if (cause instanceof ApiError && cause.code === 'erasure_idempotency_conflict') {
|
|
115
|
+
await keys.settle(intent, 'not-committed');
|
|
116
|
+
}
|
|
117
|
+
throw cause;
|
|
118
|
+
} else throw new AmbiguousProfileErasureError(cause);
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
await keys.settle(intent, 'committed');
|
|
122
|
+
} catch (cause) {
|
|
123
|
+
throw new ProfileErasureKeyCleanupError(receipt, cause);
|
|
124
|
+
}
|
|
125
|
+
return receipt;
|
|
126
|
+
},
|
|
127
|
+
async poll(operationId, polling = {}) {
|
|
128
|
+
if (!UUID_PATTERN.test(operationId)) throw new TypeError('Invalid erasure operation ID.');
|
|
129
|
+
const maxAttempts = positiveInteger(polling.maxAttempts ?? MAX_ATTEMPTS, 'maxAttempts');
|
|
130
|
+
let delayMs = positiveInteger(polling.initialDelayMs ?? INITIAL_DELAY_MS, 'initialDelayMs');
|
|
131
|
+
const maxDelayMs = positiveInteger(polling.maxDelayMs ?? MAX_DELAY_MS, 'maxDelayMs');
|
|
132
|
+
delayMs = Math.min(delayMs, maxDelayMs);
|
|
133
|
+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
134
|
+
polling.signal?.throwIfAborted();
|
|
135
|
+
const operation = await readOperation(options.fetch, operationId, polling.signal);
|
|
136
|
+
if (operation.status !== 'pending' || attempt === maxAttempts - 1) return operation;
|
|
137
|
+
await waitForPoll(delayMs, polling.signal);
|
|
138
|
+
delayMs = Math.min(delayMs * 2, maxDelayMs);
|
|
139
|
+
}
|
|
140
|
+
throw new RangeError('Invalid erasure polling limit.');
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function isErasedFence(cause: unknown): boolean {
|
|
146
|
+
return cause instanceof ApiError && cause.status === 401 && cause.code === 'profile_erased';
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function readOperation(
|
|
150
|
+
fetch: FetchImplementation,
|
|
151
|
+
operationId: string,
|
|
152
|
+
signal: AbortSignal | undefined,
|
|
153
|
+
): Promise<ProfileErasureOperation> {
|
|
154
|
+
try {
|
|
155
|
+
const response = await fetch(`/me/erasures/${encodeURIComponent(operationId)}`, {
|
|
156
|
+
method: 'GET',
|
|
157
|
+
...(signal === undefined ? {} : { signal }),
|
|
158
|
+
});
|
|
159
|
+
signal?.throwIfAborted();
|
|
160
|
+
if (!response.ok) throw await normalizeResponseError(response);
|
|
161
|
+
const value: unknown = await response.json();
|
|
162
|
+
const operation = parseOperation(value);
|
|
163
|
+
if (operation.operationId !== operationId)
|
|
164
|
+
throw new TypeError('Erasure operation ID mismatch.');
|
|
165
|
+
return operation;
|
|
166
|
+
} catch (cause) {
|
|
167
|
+
if (isErasedFence(cause)) return { status: 'pending', operationId };
|
|
168
|
+
throw cause;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function parseReceipt(value: unknown, status: number): ProfileErasureReceipt {
|
|
173
|
+
const operation = parseOperation(value);
|
|
174
|
+
if (status === 202 && operation.status === 'pending') {
|
|
175
|
+
return { status: 'pending', operationId: operation.operationId };
|
|
176
|
+
}
|
|
177
|
+
if (status === 200 && operation.status === 'completed' && operation.completedAt !== undefined) {
|
|
178
|
+
return { ...operation, completedAt: operation.completedAt };
|
|
179
|
+
}
|
|
180
|
+
if (status === 200 && operation.status === 'failed') {
|
|
181
|
+
throw new ProfileErasureOperationFailedError(operation.operationId);
|
|
182
|
+
}
|
|
183
|
+
throw new TypeError('Invalid erasure receipt.');
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function parseOperation(value: unknown): ProfileErasureOperation {
|
|
187
|
+
if (typeof value !== 'object' || value === null)
|
|
188
|
+
throw new TypeError('Invalid erasure operation.');
|
|
189
|
+
const operationId: unknown = Reflect.get(value, 'operationId');
|
|
190
|
+
const status: unknown = Reflect.get(value, 'status');
|
|
191
|
+
const completedAt: unknown = Reflect.get(value, 'completedAt');
|
|
192
|
+
if (typeof operationId !== 'string' || !UUID_PATTERN.test(operationId)) {
|
|
193
|
+
throw new TypeError('Invalid erasure operation ID.');
|
|
194
|
+
}
|
|
195
|
+
if (status === 'pending' || status === 'failed') return { operationId, status };
|
|
196
|
+
if (status !== 'completed') throw new TypeError('Invalid erasure operation status.');
|
|
197
|
+
if (completedAt === undefined) return { operationId, status };
|
|
198
|
+
if (
|
|
199
|
+
typeof completedAt !== 'string' ||
|
|
200
|
+
!TIMESTAMP_PATTERN.test(completedAt) ||
|
|
201
|
+
!Number.isFinite(Date.parse(completedAt))
|
|
202
|
+
) {
|
|
203
|
+
throw new TypeError('Invalid erasure completion time.');
|
|
204
|
+
}
|
|
205
|
+
return { operationId, status, completedAt };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function positiveInteger(value: number, name: string): number {
|
|
209
|
+
if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError(`${name} must be positive.`);
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function waitForPoll(delayMs: number, signal: AbortSignal | undefined): Promise<void> {
|
|
214
|
+
signal?.throwIfAborted();
|
|
215
|
+
return new Promise((resolve, reject) => {
|
|
216
|
+
const onAbort = (): void => {
|
|
217
|
+
globalThis.clearTimeout(timer);
|
|
218
|
+
const reason: unknown = signal?.reason;
|
|
219
|
+
reject(
|
|
220
|
+
reason instanceof Error ? reason : new Error('Erasure polling aborted.', { cause: reason }),
|
|
221
|
+
);
|
|
222
|
+
};
|
|
223
|
+
const timer = globalThis.setTimeout(() => {
|
|
224
|
+
signal?.removeEventListener('abort', onAbort);
|
|
225
|
+
resolve();
|
|
226
|
+
}, delayMs);
|
|
227
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
228
|
+
});
|
|
229
|
+
}
|