@astratra/payments 1.0.1 → 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/README.md CHANGED
@@ -189,6 +189,30 @@ avertissement est journalisé à la création ; ajoute `claim` et `release`.
189
189
  en production multi-instances** : chaque processus a sa propre mémoire, donc un
190
190
  rejeu qui arrive sur l'autre passe. Utilise un store partagé.
191
191
 
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
+
192
216
  Un événement **en échec n'est pas enregistré** : sa réservation est libérée et
193
217
  la relance doit pouvoir fonctionner. Un événement déclaré `unrelated` non plus.
194
218
  Un type d'événement sans handler ne prend aucune réservation.
@@ -207,6 +231,11 @@ Un type d'événement sans handler ne prend aucune réservation.
207
231
  npm test --workspace @astratra/payments
208
232
  ```
209
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
+
210
239
  Un test traverse une vraie pile Express avec CSRF et analyseur JSON, et vérifie
211
240
  que les octets signés arrivent intacts — puis que sans l'exemption, le CSRF
212
241
  répond bien 403.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/payments",
3
- "version": "1.0.1",
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
@@ -80,4 +80,91 @@ function createMemoryEventLog(options = {}) {
80
80
  };
81
81
  }
82
82
 
83
- module.exports = { createMemoryEventLog };
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)]);
144
+ },
145
+ async record(eventId, meta = {}) {
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
+ }
167
+ };
168
+ }
169
+
170
+ module.exports = { createMemoryEventLog, createPostgresEventLog, postgresEventLogSchema };
package/src/index.d.ts CHANGED
@@ -64,6 +64,29 @@ export function createMemoryEventLog(options?: {
64
64
  now?: () => number;
65
65
  }): EventLog & { seen(eventId: string | number): Promise<boolean>; size(): number };
66
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
+ };
89
+
67
90
  export interface WebhookLogger {
68
91
  info?(message: string): void;
69
92
  warn?(message: string): void;