@astratra/core 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Astratra
3
+ Copyright (c) 2026 Astratra contributors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -23,7 +23,10 @@ const {
23
23
  notFoundMiddleware, // gestionnaire 404 Express via apiResponse
24
24
  requestIdMiddleware, // attache req.requestId (header X-Request-Id, respecte un id entrant)
25
25
  validateMiddleware, // (validations) => exécute des validations express-validator, 400 si échec
26
- loadEnv // (schema) => lit process.env avec valeurs par défaut/requis/transform/validate
26
+ loadEnv, // (schema) => lit process.env avec valeurs par défaut/requis/transform/validate
27
+ idempotencyMiddleware, // (options) => une écriture rejouée avec la même clé ne s'exécute qu'une fois
28
+ createIdempotency, // (options) => le même moteur, hors HTTP (tâches, files, RPC)
29
+ createMemoryIdempotencyStore
27
30
  } = require('@astratra/core');
28
31
  ```
29
32
 
@@ -52,6 +55,94 @@ app.use(errorMiddleware);
52
55
  disponible, sinon `console.error`, et ne logge jamais les erreurs client
53
56
  (4xx).
54
57
 
58
+ ## Clé idempotente
59
+
60
+ Un double appui sur « Payer », une application mobile qui rejoue sa file hors
61
+ ligne, un proxy qui retente après un délai : la même écriture arrive deux fois.
62
+ Le client génère UNE clé par intention (pas par tentative) et l'envoie dans
63
+ l'en-tête `Idempotency-Key` à chaque tentative. Le serveur exécute la première ;
64
+ les suivantes reçoivent la réponse conservée, avec l'en-tête
65
+ `Idempotent-Replay: true`, sans rien refaire.
66
+
67
+ ```js
68
+ const { idempotencyMiddleware } = require('@astratra/core');
69
+
70
+ app.use('/api', authenticate); // AVANT : l'identité doit être vérifiée
71
+ app.use('/api', idempotencyMiddleware({
72
+ store, // voir « Le store » ci-dessous
73
+ ttlMs: 24 * 60 * 60 * 1000, // durée de vie d'une clé (défaut 24 h)
74
+ identify: (req) => req.user?.id ?? null // identité STABLE : le compte, jamais le jeton
75
+ }));
76
+ ```
77
+
78
+ Hors HTTP, le même moteur :
79
+
80
+ ```js
81
+ const { createIdempotency } = require('@astratra/core');
82
+ const once = createIdempotency({ store, ttlMs: 60 * 60 * 1000 });
83
+ const { replayed, result } = await once.run(
84
+ { scope: [accountId], key, payload: order },
85
+ () => charge(order)
86
+ );
87
+ ```
88
+
89
+ ### Les décisions encodées, chacune testée
90
+
91
+ | Situation | Réponse |
92
+ |---|---|
93
+ | Pas d'en-tête, ou méthode de lecture | rien ne change, la requête passe |
94
+ | Clé jamais vue | exécutée, la réponse est retenue AVANT d'être envoyée |
95
+ | Même clé, même corps, déjà terminée | réponse conservée, rien n'est refait |
96
+ | Même clé, première encore en cours (requêtes simultanées) | `409` |
97
+ | Même clé, corps différent | `422` — jamais la réponse d'une autre demande |
98
+ | Réponse hors 2xx, ou exception | clé libérée : la tentative suivante s'exécute vraiment |
99
+ | Clé expirée pas encore purgée par le store | libérée puis réclamée, pas de faux « en cours » |
100
+ | Clé invalide (hors `[A-Za-z0-9_-]{8,128}`) | `400` |
101
+ | Store indisponible | `503` par défaut ; `onStoreError: 'allow'` laisse passer sans garde |
102
+
103
+ - **La réclamation est atomique.** L'enregistrement est inséré « s'il
104
+ n'existe pas » AVANT l'exécution : c'est cette insertion qui départage deux
105
+ requêtes simultanées, jamais une lecture suivie d'une écriture.
106
+ - **L'appelant fait partie de la clé.** `identify` est obligatoire. Prenez un
107
+ identifiant VÉRIFIÉ (compte authentifié, ou jeton vérifié dans `identify`) :
108
+ un identifiant simplement décodé permet de se faire passer pour un autre et
109
+ de récupérer sa réponse. `null` place l'appel dans un espace anonyme commun,
110
+ où seuls la clé et le corps séparent les appelants.
111
+ - **Le corps est comparé sans condition**, avec un hachage insensible à
112
+ l'ordre des propriétés.
113
+ - **La réponse est stockée telle quelle** pendant `ttlMs`. Ne montez pas le
114
+ middleware sur une route qui renvoie un secret (jeton de session, code de
115
+ récupération) : il resterait en clair dans le store.
116
+
117
+ ### Le store
118
+
119
+ Trois méthodes, pour n'importe quelle base :
120
+
121
+ ```js
122
+ {
123
+ acquire(id, entry), // insertion ATOMIQUE si absent -> { acquired, record }
124
+ complete(id, token, response), // passe à « done », seulement si le jeton de réclamation correspond
125
+ release(id, token) // supprime, seulement si le jeton correspond
126
+ }
127
+ ```
128
+
129
+ MongoDB : `_id` unique + `insertOne` (erreur 11000 = déjà présent, relire),
130
+ index TTL sur `expiresAt`, `updateOne({ _id, token })`, `deleteOne({ _id, token })`.
131
+ Redis : `SET id entry NX PX ttl`. SQL : `INSERT … ON CONFLICT DO NOTHING`.
132
+ Le conditionnement par `token` n'est pas décoratif : sans lui, une tentative
133
+ lente qui libère une clé expirée efface la réclamation toute neuve d'une autre,
134
+ et les deux s'exécutent.
135
+
136
+ `createMemoryIdempotencyStore()` sert aux tests : il n'est ni persistant ni
137
+ partagé entre instances.
138
+
139
+ ### Ce que ce module ne fait pas
140
+
141
+ - Une requête dont le processus meurt en cours d'exécution laisse sa clé
142
+ « en cours » jusqu'à expiration : on préfère un `409` à un double paiement.
143
+ - Il ne protège pas les webhooks d'un prestataire de paiement : voir
144
+ `@astratra/payments`, qui les reconnaît par l'identifiant d'événement.
145
+
55
146
  ## Tests
56
147
 
57
148
  ```bash
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@astratra/core",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "Generic core utilities for Astratra SaaS packages.",
5
5
  "engines": {
6
- "node": ">=20"
6
+ "node": ">=22"
7
7
  },
8
8
  "main": "src/index.js",
9
9
  "types": "src/index.d.ts",
@@ -0,0 +1,412 @@
1
+ /**
2
+ * Idempotency keys: the same intention, sent twice, runs once.
3
+ *
4
+ * A double tap on "Pay", a mobile app replaying its offline queue, a proxy
5
+ * retrying after a timeout: each of these sends the same write again. Without
6
+ * a key, the server cannot tell a retry from a new request, and the customer
7
+ * pays twice or is registered twice. The client generates ONE key per
8
+ * intention (not per attempt) and sends it with every attempt; the server runs
9
+ * the first and hands every later attempt the stored answer of the first.
10
+ *
11
+ * Four properties make this safe, and each one was a real bug somewhere:
12
+ *
13
+ * THE CLAIM IS ATOMIC. The record is inserted "if absent" BEFORE the work
14
+ * runs, and that insertion decides who runs. A read followed by a write lets
15
+ * two simultaneous requests both see "nothing yet" and both execute.
16
+ *
17
+ * A KEY IS BOUND TO ITS PAYLOAD. The same key with a different body is a
18
+ * caller bug, and is refused (422). Serving the stored answer of another
19
+ * request in silence would tell the caller its NEW request succeeded.
20
+ * The comparison is unconditional: a stored hash compared "only when both
21
+ * sides have one" lets a body-less request collect someone's answer.
22
+ *
23
+ * ONLY SUCCESSES ARE KEPT. A stored 500 would turn a passing outage into a
24
+ * permanent refusal: the client would replay forever and receive the same
25
+ * error, and the write would never happen. Failures release the key.
26
+ *
27
+ * THE CALLER IS PART OF THE KEY. Two accounts sending the same key must
28
+ * never receive each other's answer. The identity must be STABLE across
29
+ * token refreshes: fingerprinting the access token itself made a replay sent
30
+ * after a refresh look like a new request, and it ran a second time.
31
+ *
32
+ * Storage and retention are injected; an in-memory store ships for tests.
33
+ */
34
+ const crypto = require('crypto');
35
+ const apiResponse = require('./apiResponse');
36
+
37
+ const IN_FLIGHT = 'in_flight';
38
+ const DONE = 'done';
39
+
40
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
41
+ const UNSAFE_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];
42
+ /* Long enough to be unique, short enough to be sane, and an alphabet that can
43
+ travel into a database query without being interpreted. */
44
+ const KEY_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;
45
+
46
+ const DEFAULT_MESSAGES = {
47
+ invalid_key: 'Invalid Idempotency-Key header.',
48
+ in_flight: 'A request with this idempotency key is already in progress.',
49
+ conflict: 'This idempotency key was already used for a different request.',
50
+ unavailable: 'Idempotency store unavailable; the request was not executed.'
51
+ };
52
+
53
+ class IdempotencyError extends Error {
54
+ constructor(reason, statusCode, message) {
55
+ super(message || reason);
56
+ this.name = 'IdempotencyError';
57
+ this.reason = reason;
58
+ this.statusCode = statusCode;
59
+ }
60
+ }
61
+
62
+ /*
63
+ * Key order must not matter: `{a:1,b:2}` and `{b:2,a:1}` are the same
64
+ * intention. A plain JSON.stringify hashes them differently and turns an
65
+ * honest retry (re-serialised by another client library) into a 422.
66
+ */
67
+ function stableStringify(value) {
68
+ if (value === undefined) return 'null';
69
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
70
+ if (typeof value.toJSON === 'function') return stableStringify(value.toJSON());
71
+ if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`;
72
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
73
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
74
+ }
75
+
76
+ function hashIdempotencyPayload(payload) {
77
+ return crypto.createHash('sha256').update(stableStringify(payload)).digest('hex');
78
+ }
79
+
80
+ /*
81
+ * The record id: a hash of the caller's scope plus the key. Hashing gives a
82
+ * fixed-length, separator-free id — joining raw parts with "|" lets a crafted
83
+ * part collide with another caller's id.
84
+ */
85
+ function idempotencyId(scope, key) {
86
+ return crypto.createHash('sha256').update(JSON.stringify([...scope.map(String), String(key)])).digest('hex');
87
+ }
88
+
89
+ function isValidIdempotencyKey(key, pattern = KEY_PATTERN) {
90
+ return typeof key === 'string' && pattern.test(key);
91
+ }
92
+
93
+ const timeOf = (value) => (value instanceof Date ? value.getTime() : new Date(value).getTime());
94
+
95
+ /**
96
+ * What to do with an existing record. Pure: no store, no clock of its own.
97
+ *
98
+ * expired — past its retention: not a retry any more, a new intention.
99
+ * conflict — same key, different payload.
100
+ * inFlight — the first attempt is still running: refuse rather than run twice.
101
+ * replay — done: hand back the stored answer, run nothing.
102
+ */
103
+ function decideIdempotency({ record, payloadHash, now = Date.now() }) {
104
+ if (!record) return { action: 'execute' };
105
+ if (timeOf(record.expiresAt) <= now) return { action: 'expired' };
106
+ /* Conflict BEFORE in-flight: a different payload is a caller bug whatever
107
+ the state of the first one, and saying so is more useful than "wait". */
108
+ if (record.payloadHash !== payloadHash) return { action: 'conflict' };
109
+ if (record.status !== DONE) return { action: 'inFlight' };
110
+ return { action: 'replay', response: record.response };
111
+ }
112
+
113
+ const NOOP_LOGGER = { error() {}, warn() {} };
114
+
115
+ /**
116
+ * @param {object} options
117
+ * @param {object} options.store adapter:
118
+ * acquire(id, entry) -> { acquired: boolean, record } — ATOMIC insert-if-absent;
119
+ * `record` is the existing one when not acquired.
120
+ * complete(id, token, response) — only if the record still carries `token`.
121
+ * release(id, token) — delete, only if the record still carries `token`.
122
+ * Expired records may linger (a TTL index purges on its own schedule): the
123
+ * engine detects them and releases them itself.
124
+ * @param {number} [options.ttlMs] retention; default 24h.
125
+ */
126
+ function createIdempotency(options = {}) {
127
+ const store = options.store;
128
+ for (const method of ['acquire', 'complete', 'release']) {
129
+ if (!store || typeof store[method] !== 'function') {
130
+ throw new Error(`createIdempotency requires options.store.${method}().`);
131
+ }
132
+ }
133
+ const ttlMs = options.ttlMs === undefined ? DEFAULT_TTL_MS : options.ttlMs;
134
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
135
+ throw new Error('createIdempotency: options.ttlMs must be a positive number of milliseconds.');
136
+ }
137
+ const now = options.now || (() => Date.now());
138
+ const keyPattern = options.keyPattern || KEY_PATTERN;
139
+ const messages = { ...DEFAULT_MESSAGES, ...(options.messages || {}) };
140
+ const logger = options.logger || NOOP_LOGGER;
141
+
142
+ const fail = (reason, statusCode) => new IdempotencyError(reason, statusCode, messages[reason]);
143
+
144
+ /**
145
+ * Claim the key. Returns either a replay, or a ticket that MUST be settled
146
+ * with finish(response) or abort().
147
+ */
148
+ async function begin({ scope, key, payload } = {}) {
149
+ if (!Array.isArray(scope) || scope.length === 0) {
150
+ throw new Error('idempotency.begin requires a non-empty scope (at least the caller identity).');
151
+ }
152
+ if (!isValidIdempotencyKey(key, keyPattern)) throw fail('invalid_key', 400);
153
+
154
+ const id = idempotencyId(scope, key);
155
+ const payloadHash = hashIdempotencyPayload(payload);
156
+
157
+ /* Two rounds at most: the second only happens after releasing an expired
158
+ record. Losing the race again means someone else just claimed it. */
159
+ for (let round = 0; round < 2; round += 1) {
160
+ const at = now();
161
+ const entry = {
162
+ id,
163
+ token: crypto.randomUUID(),
164
+ status: IN_FLIGHT,
165
+ payloadHash,
166
+ response: null,
167
+ createdAt: new Date(at),
168
+ expiresAt: new Date(at + ttlMs)
169
+ };
170
+
171
+ const { acquired, record } = await store.acquire(id, entry);
172
+ if (acquired) return ticket(id, entry.token);
173
+
174
+ const verdict = decideIdempotency({ record, payloadHash, now: at });
175
+ if (verdict.action === 'expired') {
176
+ /* A TTL index purges on its own schedule (MongoDB: every minute). A
177
+ lingering expired record must not block the key with "in progress"
178
+ until then. The release is conditional on ITS token, so a fresh
179
+ record claimed by a concurrent request is never deleted. */
180
+ await store.release(id, record.token);
181
+ continue;
182
+ }
183
+ if (verdict.action === 'conflict') throw fail('conflict', 422);
184
+ if (verdict.action === 'inFlight') throw fail('in_flight', 409);
185
+ return { action: 'replay', response: verdict.response };
186
+ }
187
+ throw fail('in_flight', 409);
188
+ }
189
+
190
+ function ticket(id, token) {
191
+ let settled = false;
192
+ return {
193
+ action: 'execute',
194
+ id,
195
+ async finish(response) {
196
+ if (settled) return;
197
+ settled = true;
198
+ await store.complete(id, token, response === undefined ? null : response);
199
+ },
200
+ async abort() {
201
+ if (settled) return;
202
+ settled = true;
203
+ await store.release(id, token);
204
+ }
205
+ };
206
+ }
207
+
208
+ /**
209
+ * Run `fn` once per (scope, key). Outside HTTP: jobs, queue consumers, RPC.
210
+ *
211
+ * A store failure AFTER `fn` ran is logged, not thrown: the work happened,
212
+ * and reporting it as failed would invite the caller to do it again.
213
+ */
214
+ async function run(input, fn, { remember = () => true } = {}) {
215
+ const claim = await begin(input);
216
+ if (claim.action === 'replay') return { replayed: true, result: claim.response };
217
+
218
+ let result;
219
+ try {
220
+ result = await fn();
221
+ } catch (error) {
222
+ await claim.abort().catch((e) => logger.error(`[idempotency] release failed: ${e.message}`));
223
+ throw error;
224
+ }
225
+
226
+ try {
227
+ if (remember(result)) await claim.finish(result);
228
+ else await claim.abort();
229
+ } catch (e) {
230
+ logger.error(`[idempotency] could not settle key after execution: ${e.message}`);
231
+ }
232
+ return { replayed: false, result };
233
+ }
234
+
235
+ return { begin, run, ttlMs };
236
+ }
237
+
238
+ /**
239
+ * In-process store for tests and development. Not persistent, and NOT shared
240
+ * across instances: two processes each keep their own memory, so a retry that
241
+ * reaches the other one runs again. Production needs a shared store with an
242
+ * atomic insert (a unique _id, SET NX, INSERT ... ON CONFLICT DO NOTHING).
243
+ */
244
+ function createMemoryIdempotencyStore(options = {}) {
245
+ const rows = new Map();
246
+ const now = options.now || (() => Date.now());
247
+ const clone = (value) => (value === undefined ? value : JSON.parse(JSON.stringify(value)));
248
+
249
+ /* A map that only grows is a memory leak with a long fuse: expired rows go,
250
+ the way a TTL index would remove them. */
251
+ function sweep() {
252
+ const at = now();
253
+ for (const [id, row] of rows) if (timeOf(row.expiresAt) <= at) rows.delete(id);
254
+ }
255
+
256
+ return {
257
+ async acquire(id, entry) {
258
+ sweep();
259
+ /* No await between the check and the set: in one process, this is the
260
+ atomic insert-if-absent. */
261
+ if (rows.has(id)) return { acquired: false, record: clone(rows.get(id)) };
262
+ rows.set(id, clone(entry));
263
+ return { acquired: true, record: clone(entry) };
264
+ },
265
+ async complete(id, token, response) {
266
+ const row = rows.get(id);
267
+ if (!row || row.token !== token) return false;
268
+ row.status = DONE;
269
+ row.response = clone(response);
270
+ return true;
271
+ },
272
+ async release(id, token) {
273
+ const row = rows.get(id);
274
+ if (!row || row.token !== token) return false;
275
+ rows.delete(id);
276
+ return true;
277
+ },
278
+ get(id) {
279
+ return clone(rows.get(id)) || null;
280
+ },
281
+ size: () => rows.size
282
+ };
283
+ }
284
+
285
+ const defaultRespond = (res, { status, message }) => apiResponse(res, status, message, null, false);
286
+ const isSuccess = (statusCode) => Number.isInteger(statusCode) && statusCode >= 200 && statusCode < 300;
287
+
288
+ function headerOf(req, name) {
289
+ const headers = req.headers || {};
290
+ const value = headers[name] !== undefined ? headers[name] : headers[name.toLowerCase()];
291
+ return Array.isArray(value) ? value[0] : value;
292
+ }
293
+
294
+ function setHeader(res, name, value) {
295
+ if (typeof res.setHeader === 'function') res.setHeader(name, value);
296
+ else if (typeof res.set === 'function') res.set(name, value);
297
+ }
298
+
299
+ /**
300
+ * The Express side.
301
+ *
302
+ * WITHOUT the header, nothing happens: idempotency is offered to clients that
303
+ * ask for it, never imposed, so it can be deployed before any client uses it.
304
+ *
305
+ * @param {object} options everything createIdempotency takes, plus:
306
+ * @param {Function} options.identify REQUIRED. (req) => a STABLE caller id
307
+ * (the account id, not the token). Mount the middleware AFTER authentication
308
+ * or verify the credential yourself inside `identify`: an unverified id lets
309
+ * anyone claim someone else's identity and collect their stored answer.
310
+ * Returning null puts the call in a shared anonymous namespace, where only
311
+ * the key and the payload separate callers.
312
+ * @param {'deny'|'allow'} [options.onStoreError] default 'deny' (503). 'allow'
313
+ * runs the request unguarded when the store is down: availability over the
314
+ * risk of a duplicate. Choose it knowingly — on a payment route it is the
315
+ * duplicate you were trying to prevent.
316
+ */
317
+ function idempotencyMiddleware(options = {}) {
318
+ const identify = options.identify;
319
+ if (typeof identify !== 'function') {
320
+ throw new Error('idempotencyMiddleware requires options.identify(req) — a stable caller id.');
321
+ }
322
+ const engine = options.engine || createIdempotency(options);
323
+ const header = (options.header || 'idempotency-key').toLowerCase();
324
+ const methods = new Set((options.methods || UNSAFE_METHODS).map((m) => m.toUpperCase()));
325
+ const replayHeader = options.replayHeader || 'Idempotent-Replay';
326
+ const remember = options.remember || isSuccess;
327
+ const onStoreError = options.onStoreError || 'deny';
328
+ const respond = options.respond || defaultRespond;
329
+ const messages = { ...DEFAULT_MESSAGES, ...(options.messages || {}) };
330
+ const logger = options.logger || NOOP_LOGGER;
331
+
332
+ return async function idempotency(req, res, next) {
333
+ const key = headerOf(req, header);
334
+ if (!key || !methods.has(String(req.method || '').toUpperCase())) return next();
335
+
336
+ let identity;
337
+ try {
338
+ identity = await identify(req);
339
+ } catch (error) {
340
+ return next(error);
341
+ }
342
+
343
+ const path = String(req.originalUrl || req.url || '').split('?')[0];
344
+ const scope = [identity === undefined || identity === null ? 'anonymous' : `id:${identity}`, req.method.toUpperCase(), path];
345
+
346
+ let claim;
347
+ try {
348
+ claim = await engine.begin({ scope, key, payload: req.body });
349
+ } catch (error) {
350
+ if (error instanceof IdempotencyError) {
351
+ return respond(res, { status: error.statusCode, reason: error.reason, message: error.message });
352
+ }
353
+ logger.error(`[idempotency] store unavailable: ${error.message}`);
354
+ if (onStoreError === 'allow') return next();
355
+ return respond(res, { status: 503, reason: 'unavailable', message: messages.unavailable });
356
+ }
357
+
358
+ if (claim.action === 'replay') {
359
+ /* Tells the client (and its logs) that nothing was redone — the way to
360
+ tell a replay from a double write when reading an incident. */
361
+ setHeader(res, replayHeader, 'true');
362
+ const stored = claim.response || { statusCode: 200, body: null };
363
+ return res.status(stored.statusCode).json(stored.body);
364
+ }
365
+
366
+ captureResponse(res, (response) => {
367
+ const settle = remember(response.statusCode) ? claim.finish(response) : claim.abort();
368
+ return settle.catch((e) => logger.error(`[idempotency] could not settle key: ${e.message}`));
369
+ });
370
+ return next();
371
+ };
372
+ }
373
+
374
+ /*
375
+ * Record the answer BEFORE it leaves. Sending first and saving afterwards lets
376
+ * a client that retries the instant it gets the answer find the key still "in
377
+ * progress" and receive a 409 for a request that succeeded.
378
+ *
379
+ * Responses that never go through res.json (res.send, res.end, a stream) are
380
+ * settled on 'finish' with an empty body: the work happened, and a replay must
381
+ * not run it again, even if it cannot hand back the original body.
382
+ */
383
+ function captureResponse(res, onResponse) {
384
+ let captured = false;
385
+ const originalJson = res.json;
386
+
387
+ res.json = function idempotentJson(body) {
388
+ if (captured) return originalJson.call(res, body);
389
+ captured = true;
390
+ Promise.resolve(onResponse({ statusCode: res.statusCode, body })).then(() => originalJson.call(res, body));
391
+ return res;
392
+ };
393
+
394
+ if (typeof res.once === 'function') {
395
+ res.once('finish', () => {
396
+ if (captured) return;
397
+ captured = true;
398
+ onResponse({ statusCode: res.statusCode, body: null });
399
+ });
400
+ }
401
+ }
402
+
403
+ module.exports = {
404
+ createIdempotency,
405
+ createMemoryIdempotencyStore,
406
+ idempotencyMiddleware,
407
+ decideIdempotency,
408
+ hashIdempotencyPayload,
409
+ isValidIdempotencyKey,
410
+ IdempotencyError,
411
+ IDEMPOTENCY_TTL_MS: DEFAULT_TTL_MS
412
+ };
package/src/index.d.ts CHANGED
@@ -91,3 +91,104 @@ export type LoadedEnv<TSchema extends EnvSchema> = {
91
91
  };
92
92
 
93
93
  export function loadEnv<TSchema extends EnvSchema = EnvSchema>(schema?: TSchema): LoadedEnv<TSchema>;
94
+
95
+ /* ────────────────────────── Idempotency ────────────────────────── */
96
+
97
+ export type IdempotencyStatus = 'in_flight' | 'done';
98
+
99
+ export interface StoredIdempotentResponse {
100
+ statusCode: number;
101
+ body: unknown;
102
+ }
103
+
104
+ export interface IdempotencyRecord<R = unknown> {
105
+ id: string;
106
+ /** Unique per claim: completes and releases only apply to the claim that holds it. */
107
+ token: string;
108
+ status: IdempotencyStatus;
109
+ payloadHash: string;
110
+ response: R | null;
111
+ createdAt: Date | string;
112
+ /** Stores with a TTL index can expire on this field. */
113
+ expiresAt: Date | string;
114
+ }
115
+
116
+ export interface IdempotencyStore<R = unknown> {
117
+ /** ATOMIC insert-if-absent. `record` is the existing one when not acquired. */
118
+ acquire(id: string, entry: IdempotencyRecord<R>): Promise<{ acquired: boolean; record: IdempotencyRecord<R> }>;
119
+ /** Marks done, only if the record still carries `token`. */
120
+ complete(id: string, token: string, response: R | null): Promise<unknown>;
121
+ /** Deletes, only if the record still carries `token`. */
122
+ release(id: string, token: string): Promise<unknown>;
123
+ }
124
+
125
+ export function createMemoryIdempotencyStore<R = unknown>(options?: { now?: () => number }): IdempotencyStore<R> & {
126
+ get(id: string): IdempotencyRecord<R> | null;
127
+ size(): number;
128
+ };
129
+
130
+ export type IdempotencyReason = 'invalid_key' | 'in_flight' | 'conflict' | 'unavailable';
131
+
132
+ export class IdempotencyError extends Error {
133
+ reason: IdempotencyReason;
134
+ statusCode: number;
135
+ constructor(reason: IdempotencyReason, statusCode: number, message?: string);
136
+ }
137
+
138
+ export interface IdempotencyInput {
139
+ /** At least the caller identity; the middleware adds method and path. */
140
+ scope: Array<string | number>;
141
+ key: string;
142
+ payload?: unknown;
143
+ }
144
+
145
+ export type IdempotencyClaim<R = unknown> =
146
+ | { action: 'replay'; response: R | null }
147
+ | { action: 'execute'; id: string; finish(response: R): Promise<void>; abort(): Promise<void> };
148
+
149
+ export interface IdempotencyOptions<R = unknown> {
150
+ store: IdempotencyStore<R>;
151
+ /** Retention of a key, in ms. Default 24h. */
152
+ ttlMs?: number;
153
+ now?: () => number;
154
+ keyPattern?: RegExp;
155
+ messages?: Partial<Record<IdempotencyReason, string>>;
156
+ logger?: { error(message: string): void; warn?(message: string): void };
157
+ }
158
+
159
+ export interface Idempotency<R = unknown> {
160
+ begin(input: IdempotencyInput): Promise<IdempotencyClaim<R>>;
161
+ run<T extends R>(
162
+ input: IdempotencyInput,
163
+ fn: () => T | Promise<T>,
164
+ options?: { remember?: (result: T) => boolean }
165
+ ): Promise<{ replayed: boolean; result: T }>;
166
+ ttlMs: number;
167
+ }
168
+
169
+ export function createIdempotency<R = unknown>(options: IdempotencyOptions<R>): Idempotency<R>;
170
+
171
+ export interface IdempotencyMiddlewareOptions extends IdempotencyOptions<StoredIdempotentResponse> {
172
+ /** REQUIRED: a STABLE, VERIFIED caller id (the account, not the token). null = shared anonymous namespace. */
173
+ identify(req: RequestLike): string | number | null | undefined | Promise<string | number | null | undefined>;
174
+ engine?: Idempotency<StoredIdempotentResponse>;
175
+ header?: string;
176
+ methods?: string[];
177
+ replayHeader?: string;
178
+ remember?: (statusCode: number) => boolean;
179
+ /** Default 'deny' (503): no unguarded execution while the store is down. */
180
+ onStoreError?: 'deny' | 'allow';
181
+ respond?: (res: ResponseLike, payload: { status: number; reason: IdempotencyReason; message: string }) => unknown;
182
+ }
183
+
184
+ export function idempotencyMiddleware(options: IdempotencyMiddlewareOptions): RequestHandler;
185
+
186
+ export function decideIdempotency(input: {
187
+ record: IdempotencyRecord | null;
188
+ payloadHash: string;
189
+ now?: number;
190
+ }): { action: 'execute' | 'expired' | 'conflict' | 'inFlight' } | { action: 'replay'; response: unknown };
191
+
192
+ export function hashIdempotencyPayload(payload: unknown): string;
193
+ export function isValidIdempotencyKey(key: unknown, pattern?: RegExp): boolean;
194
+ export const IDEMPOTENCY_TTL_MS: number;
package/src/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ const idempotency = require('./idempotency');
2
+
1
3
  module.exports = {
2
4
  apiResponse: require('./apiResponse'),
3
5
  asyncHandler: require('./asyncHandler'),
@@ -7,5 +9,6 @@ module.exports = {
7
9
  notFoundMiddleware: require('./notFoundMiddleware'),
8
10
  requestIdMiddleware: require('./requestIdMiddleware'),
9
11
  validateMiddleware: require('./validateMiddleware'),
10
- loadEnv: require('./loadEnv')
12
+ loadEnv: require('./loadEnv'),
13
+ ...idempotency
11
14
  };