@astratra/payments 1.0.0 → 1.1.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
@@ -74,6 +74,10 @@ que ton application est seule à connaître ses propres middlewares.
74
74
  ```js
75
75
  const { createWebhookHandler, createMemoryEventLog } = require('@astratra/payments');
76
76
 
77
+ // Développement seulement. En production, un store partagé qui fournit
78
+ // claim / release / record (voir « Les rejeux »).
79
+ const eventLog = createMemoryEventLog();
80
+
77
81
  const webhook = createWebhookHandler({
78
82
  // À toi, parce que c'est propre au prestataire. DOIT lever si la signature
79
83
  // ne correspond pas.
@@ -84,7 +88,7 @@ const webhook = createWebhookHandler({
84
88
  // interface sans redémarrage. Se marie avec @astratra/credentials.
85
89
  secret: () => vault.get('STRIPE_WEBHOOK_SECRET'),
86
90
 
87
- eventLog, // protection contre les rejeux
91
+ eventLog, // protection contre les rejeux : claim / release / record (voir « Les rejeux »)
88
92
 
89
93
  events: {
90
94
  'checkout.session.completed': async (event, { sideEffect, unrelated }) => {
@@ -114,9 +118,9 @@ Le code HTTP n'est pas décoratif : le prestataire le lit comme une consigne.
114
118
  | traité | 200 | terminé |
115
119
  | type d'événement inconnu | 200 | acquitté, pas une erreur |
116
120
  | `unrelated(...)` | 200 | « reçu, pas mon circuit » |
117
- | déjà traité | 200 | rejeu reconnu |
121
+ | déjà traité, ou en cours de traitement par une autre livraison | 200 (`duplicate`) | rejeu reconnu, réservé avant le traitement |
118
122
  | signature invalide | **400** | relancer ne changerait rien |
119
- | le gestionnaire a levé | **500** | là, une relance peut aider |
123
+ | le gestionnaire a levé | **500** | réservation libérée : là, une relance peut aider |
120
124
 
121
125
  Le 400 sur signature invalide est délibéré. Un 500 ferait relancer un message
122
126
  que le prestataire a mal signé, ou que tu ne sais pas vérifier — indéfiniment.
@@ -149,17 +153,69 @@ Les prestataires renvoient les événements, volontairement : ils ne peuvent pas
149
153
  distinguer une réponse perdue d'une réponse lente. Sans mémoire, la seconde
150
154
  livraison reconfirme la commande, renvoie le reçu, recrédite le compte.
151
155
 
156
+ Et ils renvoient **en même temps** : une relance peut arriver pendant que la
157
+ première livraison tourne encore. « Déjà vu ? » puis « je m'en souviens » laisse
158
+ une fenêtre où les deux livraisons répondent non, et la commande est confirmée
159
+ deux fois. L'événement est donc **réservé de façon atomique avant le
160
+ traitement** :
161
+
152
162
  ```
153
- seen(eventId) -> boolean
154
- record(eventId, meta) -> void
163
+ claim(eventId, meta) -> boolean vrai : réservé maintenant, à traiter.
164
+ faux : déjà traité ou en cours → 200 « duplicate ».
165
+ release(eventId) -> void le handler a échoué : réservation libérée,
166
+ la relance du prestataire pourra passer.
167
+ record(eventId, meta) -> void traité : la réservation devient définitive.
168
+ seen(eventId) -> boolean traité (une réservation en cours ne compte pas).
169
+ ```
170
+
171
+ En SQL, `claim` tient en une instruction sur une clé unique :
172
+
173
+ ```sql
174
+ INSERT INTO webhook_events (id, status, claimed_at) VALUES ($1, 'pending', now())
175
+ ON CONFLICT (id) DO UPDATE SET claimed_at = now()
176
+ WHERE webhook_events.status = 'pending'
177
+ AND webhook_events.claimed_at < now() - interval '15 minutes'
178
+ RETURNING id; -- une ligne renvoyée = réservé
155
179
  ```
156
180
 
181
+ Une réservation **doit expirer** : un processus qui plante en plein traitement ne
182
+ la libère jamais (`createMemoryEventLog({ claimTtlMs })`, 15 min par défaut).
183
+
184
+ Un ancien journal `{ seen, record }` est encore accepté, mais **il n'est pas
185
+ atomique** : deux livraisons simultanées passent toutes les deux. Un
186
+ avertissement est journalisé à la création ; ajoute `claim` et `release`.
187
+
157
188
  `createMemoryEventLog()` sert aux tests et au développement. **Il n'est pas sûr
158
189
  en production multi-instances** : chaque processus a sa propre mémoire, donc un
159
190
  rejeu qui arrive sur l'autre passe. Utilise un store partagé.
160
191
 
161
- Un événement **en échec n'est pas enregistré** : la relance doit pouvoir
162
- fonctionner. Un événement déclaré `unrelated` non plus.
192
+ ### Le journal PostgreSQL (1.1.0)
193
+
194
+ `createPostgresEventLog(pool, { table, claimTtlMs })` tient le même contrat dans
195
+ une table partagée par toutes les instances : `claim` est l'instruction
196
+ `INSERT … ON CONFLICT` ci-dessus, une réservation inachevée expire après
197
+ `claimTtlMs` (15 min par défaut), `release` ne libère qu'une réservation en
198
+ cours, jamais un événement déjà traité.
199
+
200
+ ```js
201
+ const { Pool } = require('pg');
202
+ const { createPostgresEventLog, postgresEventLogSchema } = require('@astratra/payments');
203
+
204
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
205
+ await pool.query(postgresEventLogSchema({ table: 'webhook_events' })); // une fois (migration)
206
+ const eventLog = createPostgresEventLog(pool, { table: 'webhook_events' });
207
+
208
+ // De temps en temps : les événements traités de plus de 90 jours ne reviendront plus.
209
+ await eventLog.prune(90 * 24 * 3600_000);
210
+ ```
211
+
212
+ Le paquet ne dépend pas de `pg` : `pool` est n'importe quel objet avec
213
+ `query(texte, paramètres)`. Le nom de table (éventuellement `schéma.table`) est
214
+ vérifié et cité ; les identifiants d'événements passent toujours en paramètres.
215
+
216
+ Un événement **en échec n'est pas enregistré** : sa réservation est libérée et
217
+ la relance doit pouvoir fonctionner. Un événement déclaré `unrelated` non plus.
218
+ Un type d'événement sans handler ne prend aucune réservation.
163
219
 
164
220
  ## Ce que ce package ne fait pas
165
221
 
@@ -175,6 +231,11 @@ fonctionner. Un événement déclaré `unrelated` non plus.
175
231
  npm test --workspace @astratra/payments
176
232
  ```
177
233
 
234
+ Les tests du journal PostgreSQL tournent sur une vraie base quand
235
+ `PAYMENTS_TEST_DATABASE_URL` désigne une base dont le nom finit par `_test`
236
+ (sinon ils sont sautés) : le même contrat que le journal en mémoire, plus deux
237
+ instances sur une même table et la purge.
238
+
178
239
  Un test traverse une vraie pile Express avec CSRF et analyseur JSON, et vérifie
179
240
  que les octets signés arrivent intacts — puis que sans l'exemption, le CSRF
180
241
  répond bien 403.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/payments",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "The payment webhook pipeline done once: raw-body signature checks, replay protection, and the answers that stop a provider retrying for days.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -24,7 +24,8 @@
24
24
  "payments",
25
25
  "webhook",
26
26
  "stripe",
27
- "idempotency"
27
+ "idempotency",
28
+ "postgresql"
28
29
  ],
29
30
  "license": "MIT",
30
31
  "publishConfig": {
@@ -33,6 +34,7 @@
33
34
  "devDependencies": {
34
35
  "express": "^4.18.3",
35
36
  "jest": "30.4.2",
37
+ "pg": "^8.13.1",
36
38
  "supertest": "^7.0.0"
37
39
  }
38
40
  }
package/src/eventLog.js CHANGED
@@ -6,12 +6,28 @@
6
6
  * record, the second delivery re-confirms an order, re-sends a receipt, or
7
7
  * re-credits an account.
8
8
  *
9
- * Two methods, so any store fits — a table, a Redis key, a collection:
9
+ * And they resend CONCURRENTLY: a retry can land while the first delivery is
10
+ * still running. "Have I seen it?" then "remember it" leaves a window where both
11
+ * deliveries answer no. The event must be reserved atomically BEFORE it is
12
+ * handled:
10
13
  *
11
- * seen(eventId) -> boolean
12
- * record(eventId, meta) -> void
14
+ * claim(eventId, meta) -> boolean true: reserved now, handle it.
15
+ * false: already handled or being handled.
16
+ * release(eventId) -> void the handler failed: free the claim so the
17
+ * provider's retry can work.
18
+ * record(eventId, meta) -> void handled: the claim becomes permanent.
19
+ * seen(eventId) -> boolean handled (a claim in progress is not).
20
+ *
21
+ * In SQL, claim is one statement on a unique key:
22
+ * INSERT INTO webhook_events (id, status, claimed_at) VALUES ($1, 'pending', now())
23
+ * ON CONFLICT (id) DO UPDATE SET claimed_at = now()
24
+ * WHERE webhook_events.status = 'pending' AND webhook_events.claimed_at < now() - interval '15 minutes'
25
+ * RETURNING id; -- a row back means claimed
26
+ * A claim must expire: a process that crashes mid-handler never releases it.
13
27
  */
14
28
 
29
+ const DEFAULT_CLAIM_TTL_MS = 15 * 60 * 1000;
30
+
15
31
  /**
16
32
  * In-process log for tests and local development. Not persistent, and NOT safe
17
33
  * across several instances: two processes each keep their own memory, so a
@@ -19,24 +35,136 @@
19
35
  */
20
36
  function createMemoryEventLog(options = {}) {
21
37
  const limit = options.limit || 10_000;
22
- const seen = new Map();
38
+ const claimTtlMs = options.claimTtlMs || DEFAULT_CLAIM_TTL_MS;
39
+ const now = options.now || Date.now;
40
+ const entries = new Map();
41
+
42
+ function trim() {
43
+ /* A log that only grows is a memory leak with a long fuse. Oldest out
44
+ first — a replay older than the last ten thousand events is not a
45
+ scenario worth holding memory for. */
46
+ while (entries.size > limit) {
47
+ const oldest = entries.keys().next().value;
48
+ entries.delete(oldest);
49
+ }
50
+ }
23
51
 
24
52
  return {
53
+ /* Synchronous between the read and the write: within one process, no
54
+ other delivery can slip in between. */
55
+ async claim(eventId, meta = {}) {
56
+ const key = String(eventId);
57
+ const entry = entries.get(key);
58
+ if (entry && (entry.handled || now() - entry.claimedAt < claimTtlMs)) return false;
59
+ entries.delete(key);
60
+ entries.set(key, { handled: false, claimedAt: now(), ...meta });
61
+ trim();
62
+ return true;
63
+ },
64
+ async release(eventId) {
65
+ const key = String(eventId);
66
+ const entry = entries.get(key);
67
+ if (entry && !entry.handled) entries.delete(key);
68
+ },
25
69
  async seen(eventId) {
26
- return seen.has(String(eventId));
70
+ const entry = entries.get(String(eventId));
71
+ return Boolean(entry && entry.handled);
72
+ },
73
+ async record(eventId, meta = {}) {
74
+ const key = String(eventId);
75
+ const previous = entries.get(key) || {};
76
+ entries.set(key, { ...previous, ...meta, handled: true, at: new Date(now()) });
77
+ trim();
78
+ },
79
+ size: () => entries.size
80
+ };
81
+ }
82
+
83
+ /* ───────────── PostgreSQL: the log shared by every instance ───────────── */
84
+
85
+ const IDENTIFIER = /^[a-z_][a-z0-9_]{0,62}$/i;
86
+
87
+ function quoteTable(table) {
88
+ const parts = String(table).split('.');
89
+ if (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part))) {
90
+ throw new TypeError(`Invalid table name: ${JSON.stringify(table)} (letters, digits and _ only, optionally schema.table).`);
91
+ }
92
+ return parts.map((part) => `"${part}"`).join('.');
93
+ }
94
+
95
+ /**
96
+ * The table behind createPostgresEventLog. Run it once (migration or startup);
97
+ * it is idempotent.
98
+ */
99
+ function postgresEventLogSchema(options = {}) {
100
+ const table = quoteTable(options.table || 'webhook_events');
101
+ return `CREATE TABLE IF NOT EXISTS ${table} (
102
+ id text PRIMARY KEY,
103
+ status text NOT NULL CHECK (status IN ('pending', 'handled')),
104
+ claimed_at timestamptz NOT NULL,
105
+ handled_at timestamptz,
106
+ meta jsonb NOT NULL DEFAULT '{}'::jsonb
107
+ )`;
108
+ }
109
+
110
+ /**
111
+ * Event log in PostgreSQL, shared by every instance of the service: a retry
112
+ * reaching another process is still refused. Same contract as the memory log;
113
+ * claim is a single INSERT … ON CONFLICT on the primary key, so two concurrent
114
+ * deliveries cannot both win, and an unfinished claim expires after claimTtlMs.
115
+ *
116
+ * `pool` is anything with query(text, params) (a pg Pool or client): the
117
+ * package does not depend on pg. Create the table with postgresEventLogSchema().
118
+ */
119
+ function createPostgresEventLog(pool, options = {}) {
120
+ if (!pool || typeof pool.query !== 'function') {
121
+ throw new TypeError('createPostgresEventLog needs a pool with query(text, params) (for example a pg Pool).');
122
+ }
123
+ const table = quoteTable(options.table || 'webhook_events');
124
+ const claimTtlMs = options.claimTtlMs || DEFAULT_CLAIM_TTL_MS;
125
+ const now = options.now || Date.now;
126
+ const at = () => new Date(now());
127
+ const json = (meta) => JSON.stringify(meta && typeof meta === 'object' ? meta : {});
128
+
129
+ return {
130
+ async claim(eventId, meta = {}) {
131
+ const time = at();
132
+ const { rows } = await pool.query(
133
+ `INSERT INTO ${table} (id, status, claimed_at, meta) VALUES ($1, 'pending', $2, $3::jsonb)
134
+ ON CONFLICT (id) DO UPDATE SET claimed_at = EXCLUDED.claimed_at, meta = EXCLUDED.meta
135
+ WHERE ${table}.status = 'pending' AND ${table}.claimed_at <= $4
136
+ RETURNING id`,
137
+ [String(eventId), time, json(meta), new Date(time.getTime() - claimTtlMs)]
138
+ );
139
+ return rows.length === 1;
140
+ },
141
+ /* Only a pending claim is freed: a handled event stays handled. */
142
+ async release(eventId) {
143
+ await pool.query(`DELETE FROM ${table} WHERE id = $1 AND status = 'pending'`, [String(eventId)]);
27
144
  },
28
145
  async record(eventId, meta = {}) {
29
- seen.set(String(eventId), { at: new Date(), ...meta });
30
- /* A log that only grows is a memory leak with a long fuse. Oldest out
31
- first — a replay older than the last ten thousand events is not a
32
- scenario worth holding memory for. */
33
- if (seen.size > limit) {
34
- const oldest = seen.keys().next().value;
35
- seen.delete(oldest);
36
- }
37
- },
38
- size: () => seen.size
146
+ const time = at();
147
+ await pool.query(
148
+ `INSERT INTO ${table} (id, status, claimed_at, handled_at, meta) VALUES ($1, 'handled', $2, $2, $3::jsonb)
149
+ ON CONFLICT (id) DO UPDATE SET status = 'handled', handled_at = EXCLUDED.handled_at,
150
+ meta = ${table}.meta || EXCLUDED.meta`,
151
+ [String(eventId), time, json(meta)]
152
+ );
153
+ },
154
+ async seen(eventId) {
155
+ const { rows } = await pool.query(`SELECT 1 FROM ${table} WHERE id = $1 AND status = 'handled'`, [String(eventId)]);
156
+ return rows.length === 1;
157
+ },
158
+ /** Deletes handled events older than `olderThanMs` (a provider does not resend months-old events). */
159
+ async prune(olderThanMs) {
160
+ if (!Number.isFinite(olderThanMs) || olderThanMs <= 0) throw new TypeError('prune(olderThanMs) needs a positive duration in milliseconds.');
161
+ const { rowCount } = await pool.query(
162
+ `DELETE FROM ${table} WHERE status = 'handled' AND handled_at < $1`,
163
+ [new Date(now() - olderThanMs)]
164
+ );
165
+ return rowCount ?? 0;
166
+ }
39
167
  };
40
168
  }
41
169
 
42
- module.exports = { createMemoryEventLog };
170
+ module.exports = { createMemoryEventLog, createPostgresEventLog, postgresEventLogSchema };
package/src/index.d.ts CHANGED
@@ -33,12 +33,59 @@ export function unrelated(reason?: string): Outcome;
33
33
  /** Already acted on. */
34
34
  export function duplicate(reason?: string): Outcome;
35
35
 
36
+ /**
37
+ * Atomic replay protection: the event is reserved before it is handled, so two
38
+ * concurrent deliveries of one event cannot both be handled.
39
+ */
36
40
  export interface EventLog {
41
+ /** true: reserved now, handle it. false: already handled or being handled. A claim must expire. */
42
+ claim(eventId: string | number, meta?: Record<string, unknown>): Promise<boolean> | boolean;
43
+ /** The handler failed or the event was not ours: free the claim (never undoes a recorded event). */
44
+ release(eventId: string | number): Promise<void> | void;
45
+ /** Handled: the claim becomes permanent. */
46
+ record(eventId: string | number, meta?: Record<string, unknown>): Promise<void> | void;
47
+ /** Handled (a claim in progress is not). */
48
+ seen?(eventId: string | number): Promise<boolean> | boolean;
49
+ }
50
+
51
+ /**
52
+ * @deprecated Not atomic: two concurrent deliveries of one event can both be
53
+ * handled. Still accepted, with a warning; add claim() and release().
54
+ */
55
+ export interface LegacyEventLog {
37
56
  seen(eventId: string | number): Promise<boolean> | boolean;
38
57
  record(eventId: string | number, meta?: Record<string, unknown>): Promise<void> | void;
39
58
  }
40
59
 
41
- export function createMemoryEventLog(options?: { limit?: number }): EventLog & { size(): number };
60
+ export function createMemoryEventLog(options?: {
61
+ limit?: number;
62
+ /** How long an unfinished claim blocks retries (a crashed process never releases it). Default 15 min. */
63
+ claimTtlMs?: number;
64
+ now?: () => number;
65
+ }): EventLog & { seen(eventId: string | number): Promise<boolean>; size(): number };
66
+
67
+ /** Anything with query(text, params): a pg Pool, a pg client. */
68
+ export interface QueryablePool {
69
+ query(text: string, params?: unknown[]): Promise<{ rows: unknown[]; rowCount?: number | null }>;
70
+ }
71
+
72
+ /** The CREATE TABLE IF NOT EXISTS behind createPostgresEventLog (default table: webhook_events). */
73
+ export function postgresEventLogSchema(options?: { table?: string }): string;
74
+
75
+ /**
76
+ * Event log in PostgreSQL, shared by every instance: same contract as the memory log, claim is
77
+ * one INSERT … ON CONFLICT on the primary key, an unfinished claim expires after claimTtlMs.
78
+ */
79
+ export function createPostgresEventLog(pool: QueryablePool, options?: {
80
+ table?: string;
81
+ /** How long an unfinished claim blocks retries. Default 15 min. */
82
+ claimTtlMs?: number;
83
+ now?: () => number;
84
+ }): EventLog & {
85
+ seen(eventId: string | number): Promise<boolean>;
86
+ /** Deletes handled events older than olderThanMs; returns how many. */
87
+ prune(olderThanMs: number): Promise<number>;
88
+ };
42
89
 
43
90
  export interface WebhookLogger {
44
91
  info?(message: string): void;
@@ -75,7 +122,7 @@ export function createWebhookHandler<Event = Record<string, unknown>>(options: {
75
122
  /** A value, or a function read on every call so the secret can rotate without a restart. */
76
123
  secret?: unknown | (() => unknown | Promise<unknown>);
77
124
  events: Record<string, EventHandler<Event>>;
78
- eventLog?: EventLog;
125
+ eventLog?: EventLog | LegacyEventLog;
79
126
  eventId?: (event: Event) => string | undefined;
80
127
  logger?: WebhookLogger;
81
128
  }): WebhookHandler;
package/src/webhook.js CHANGED
@@ -43,7 +43,10 @@ const resolve = async (value) => (typeof value === 'function' ? value() : value)
43
43
  * interface without a restart.
44
44
  * @param {Record<string, Function>} options.events event type -> handler.
45
45
  * An event type absent from this map is acknowledged, never rejected.
46
- * @param {object} [options.eventLog] { seen, record } — replay protection.
46
+ * @param {object} [options.eventLog] { claim, release, record } — replay
47
+ * protection, atomic: the event is reserved before it is handled. A legacy
48
+ * { seen, record } log still works but leaves a window where two concurrent
49
+ * deliveries both get through.
47
50
  * @param {Function} [options.eventId] (event) => string. Defaults to `event.id`.
48
51
  * @param {object} [options.logger]
49
52
  */
@@ -59,8 +62,18 @@ function createWebhookHandler(options = {}) {
59
62
  }
60
63
 
61
64
  const eventLog = options.eventLog || null;
62
- const eventIdOf = options.eventId || ((event) => event && event.id);
63
65
  const logger = options.logger || NOOP_LOGGER;
66
+ const atomic = Boolean(eventLog && typeof eventLog.claim === 'function');
67
+ if (eventLog && !atomic) {
68
+ if (typeof eventLog.seen !== 'function' || typeof eventLog.record !== 'function') {
69
+ throw new Error('createWebhookHandler: options.eventLog needs claim() and release() (or the legacy seen() and record()).');
70
+ }
71
+ logger.warn('[payments] eventLog has no claim(): replay protection is not atomic, two concurrent deliveries of one event can both be handled. Add claim() and release().');
72
+ }
73
+ if (atomic && typeof eventLog.release !== 'function') {
74
+ throw new Error('createWebhookHandler: an eventLog with claim() also needs release(), or a failed event could never be retried.');
75
+ }
76
+ const eventIdOf = options.eventId || ((event) => event && event.id);
64
77
 
65
78
  /**
66
79
  * Run something that must NOT be able to fail the webhook.
@@ -101,11 +114,6 @@ function createWebhookHandler(options = {}) {
101
114
 
102
115
  const id = eventIdOf(event);
103
116
 
104
- if (eventLog && id && (await eventLog.seen(id))) {
105
- logger.info(`[payments] ${event.type} ${id} already handled — acknowledged again`);
106
- return { status: 200, body: { received: true, status: DUPLICATE } };
107
- }
108
-
109
117
  const handler = events[event.type];
110
118
  if (!handler) {
111
119
  /* Not an error. One endpoint receives everything the account emits, and
@@ -114,6 +122,17 @@ function createWebhookHandler(options = {}) {
114
122
  return { status: 200, body: { received: true, status: IGNORED, type: event.type } };
115
123
  }
116
124
 
125
+ /* Reserve BEFORE handling: a retry arriving while this delivery runs must
126
+ be turned away, not handled a second time. */
127
+ const claimed = eventLog && id
128
+ ? (atomic ? await eventLog.claim(id, { type: event.type }) : !(await eventLog.seen(id)))
129
+ : true;
130
+ if (!claimed) {
131
+ logger.info(`[payments] ${event.type} ${id} already handled — acknowledged again`);
132
+ return { status: 200, body: { received: true, status: DUPLICATE } };
133
+ }
134
+ const release = () => (atomic && id ? sideEffect('event log release', () => eventLog.release(id)) : null);
135
+
117
136
  let outcome;
118
137
  try {
119
138
  outcome = await handler(event, { sideEffect, handled, unrelated, duplicate, logger });
@@ -121,6 +140,7 @@ function createWebhookHandler(options = {}) {
121
140
  /* A genuine failure: the provider SHOULD retry, so 500 is right here.
122
141
  This is the one case where retrying can help. */
123
142
  logger.error(`[payments] ${event.type} failed: ${error.message}`);
143
+ await release();
124
144
  return { status: 500, body: { received: false, reason: 'handler-failed' } };
125
145
  }
126
146
 
@@ -128,6 +148,9 @@ function createWebhookHandler(options = {}) {
128
148
 
129
149
  if (eventLog && id && result.status === HANDLED) {
130
150
  await sideEffect('event log', () => eventLog.record(id, { type: event.type }));
151
+ } else {
152
+ /* Not ours, or already acted on elsewhere: nothing to remember. */
153
+ await release();
131
154
  }
132
155
 
133
156
  if (result.status === UNRELATED) {