@useherald/core 0.3.0 → 0.5.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/dist/chunk-UNUPED23.js +14 -0
- package/dist/chunk-UNUPED23.js.map +1 -0
- package/dist/index.d.ts +9 -4
- package/dist/index.js +180 -12
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts +1 -1
- package/dist/memory.js +14 -4
- package/dist/memory.js.map +1 -1
- package/dist/postgres.d.ts +32 -0
- package/dist/postgres.js +369 -0
- package/dist/postgres.js.map +1 -0
- package/dist/{store-BaqPfkS_.d.ts → store-D-yCqAN7.d.ts} +11 -2
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +53 -0
- package/dist/testing.js.map +1 -1
- package/package.json +8 -1
package/dist/postgres.js
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HeraldError
|
|
3
|
+
} from "./chunk-UNUPED23.js";
|
|
4
|
+
|
|
5
|
+
// src/postgres.ts
|
|
6
|
+
var IDENT = /^[a-z_][a-z0-9_]*$/;
|
|
7
|
+
var DIGITS = /^\d{1,18}$/;
|
|
8
|
+
var DEFAULT_PAGE = 50;
|
|
9
|
+
var TERMINAL = ["sent", "dead", "skipped", "cancelled"];
|
|
10
|
+
var SCHEMA_VERSION = 1;
|
|
11
|
+
function checkSchema(schema) {
|
|
12
|
+
if (!IDENT.test(schema))
|
|
13
|
+
throw new HeraldError("invalid_config", `postgres schema "${schema}" must match ${IDENT}`);
|
|
14
|
+
return schema;
|
|
15
|
+
}
|
|
16
|
+
function postgresSchemaSql(opts = {}) {
|
|
17
|
+
const name = checkSchema(opts.schema ?? "public");
|
|
18
|
+
const s = `"${name}"`;
|
|
19
|
+
const createSchema = name === "public" ? "" : `CREATE SCHEMA IF NOT EXISTS ${s};
|
|
20
|
+
`;
|
|
21
|
+
return `
|
|
22
|
+
${createSchema}
|
|
23
|
+
CREATE TABLE IF NOT EXISTS ${s}.herald_schema_version (
|
|
24
|
+
version integer PRIMARY KEY,
|
|
25
|
+
applied_at timestamptz NOT NULL DEFAULT now()
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
CREATE TABLE IF NOT EXISTS ${s}.herald_notifications (
|
|
29
|
+
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
30
|
+
event text NOT NULL,
|
|
31
|
+
payload jsonb,
|
|
32
|
+
priority text NOT NULL CHECK (priority IN ('normal', 'critical')),
|
|
33
|
+
idempotency_key text NOT NULL UNIQUE,
|
|
34
|
+
subject text,
|
|
35
|
+
created_at timestamptz(3) NOT NULL DEFAULT now()
|
|
36
|
+
);
|
|
37
|
+
CREATE INDEX IF NOT EXISTS herald_notifications_subject_idx
|
|
38
|
+
ON ${s}.herald_notifications (subject) WHERE subject IS NOT NULL;
|
|
39
|
+
CREATE INDEX IF NOT EXISTS herald_notifications_created_idx
|
|
40
|
+
ON ${s}.herald_notifications (created_at);
|
|
41
|
+
|
|
42
|
+
CREATE TABLE IF NOT EXISTS ${s}.herald_deliveries (
|
|
43
|
+
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
44
|
+
-- NO ACTION (not RESTRICT, not CASCADE): purge deletes deliveries and their
|
|
45
|
+
-- notifications in one statement, which only works because NO ACTION is checked at statement end.
|
|
46
|
+
notification_id bigint NOT NULL REFERENCES ${s}.herald_notifications (id),
|
|
47
|
+
channel text NOT NULL,
|
|
48
|
+
address jsonb,
|
|
49
|
+
recipient_id text,
|
|
50
|
+
status text NOT NULL CHECK (status IN ('pending', 'sending', 'sent', 'retry', 'dead', 'skipped', 'cancelled')),
|
|
51
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
52
|
+
next_attempt_at timestamptz(3),
|
|
53
|
+
lease_until timestamptz(3),
|
|
54
|
+
last_error text,
|
|
55
|
+
created_at timestamptz(3) NOT NULL DEFAULT now()
|
|
56
|
+
);
|
|
57
|
+
CREATE INDEX IF NOT EXISTS herald_deliveries_due_idx
|
|
58
|
+
ON ${s}.herald_deliveries (next_attempt_at NULLS FIRST, created_at, id) WHERE status IN ('pending', 'retry');
|
|
59
|
+
CREATE INDEX IF NOT EXISTS herald_deliveries_lease_idx
|
|
60
|
+
ON ${s}.herald_deliveries (lease_until) WHERE status = 'sending';
|
|
61
|
+
CREATE INDEX IF NOT EXISTS herald_deliveries_notification_idx
|
|
62
|
+
ON ${s}.herald_deliveries (notification_id);
|
|
63
|
+
CREATE INDEX IF NOT EXISTS herald_deliveries_created_idx
|
|
64
|
+
ON ${s}.herald_deliveries (created_at DESC, id DESC);
|
|
65
|
+
CREATE INDEX IF NOT EXISTS herald_deliveries_recipient_idx
|
|
66
|
+
ON ${s}.herald_deliveries (recipient_id, created_at DESC, id DESC);
|
|
67
|
+
|
|
68
|
+
CREATE TABLE IF NOT EXISTS ${s}.herald_inbox (
|
|
69
|
+
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
70
|
+
recipient_id text NOT NULL,
|
|
71
|
+
notification_id text NOT NULL, -- no FK: purge never touches the inbox
|
|
72
|
+
title text NOT NULL,
|
|
73
|
+
body text NOT NULL,
|
|
74
|
+
data jsonb,
|
|
75
|
+
created_at timestamptz(3) NOT NULL DEFAULT now(),
|
|
76
|
+
read_at timestamptz(3)
|
|
77
|
+
);
|
|
78
|
+
CREATE INDEX IF NOT EXISTS herald_inbox_recipient_idx
|
|
79
|
+
ON ${s}.herald_inbox (recipient_id, created_at DESC, id DESC);
|
|
80
|
+
CREATE INDEX IF NOT EXISTS herald_inbox_unread_idx
|
|
81
|
+
ON ${s}.herald_inbox (recipient_id) WHERE read_at IS NULL;
|
|
82
|
+
|
|
83
|
+
INSERT INTO ${s}.herald_schema_version (version) VALUES (${SCHEMA_VERSION}) ON CONFLICT DO NOTHING;
|
|
84
|
+
`.trim();
|
|
85
|
+
}
|
|
86
|
+
var iso = (d) => d.toISOString();
|
|
87
|
+
var str = (v) => String(v);
|
|
88
|
+
var date = (v) => v instanceof Date ? v : new Date(v);
|
|
89
|
+
var dateOrNull = (v) => v === null || v === void 0 ? null : date(v);
|
|
90
|
+
var jsonParam = (v) => JSON.stringify(v ?? null);
|
|
91
|
+
function delivery(r, prefix = "") {
|
|
92
|
+
const g = (k) => r[prefix + k];
|
|
93
|
+
const recipientId = g("recipient_id");
|
|
94
|
+
return {
|
|
95
|
+
id: str(g("id")),
|
|
96
|
+
notificationId: str(g("notification_id")),
|
|
97
|
+
channel: g("channel"),
|
|
98
|
+
address: g("address") ?? null,
|
|
99
|
+
...recipientId !== null && recipientId !== void 0 && { recipientId },
|
|
100
|
+
status: g("status"),
|
|
101
|
+
attempts: Number(g("attempts")),
|
|
102
|
+
nextAttemptAt: dateOrNull(g("next_attempt_at")),
|
|
103
|
+
leaseUntil: dateOrNull(g("lease_until")),
|
|
104
|
+
lastError: g("last_error") ?? null,
|
|
105
|
+
createdAt: date(g("created_at"))
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function notification(r, prefix = "") {
|
|
109
|
+
const g = (k) => r[prefix + k];
|
|
110
|
+
return {
|
|
111
|
+
id: str(g("id")),
|
|
112
|
+
event: g("event"),
|
|
113
|
+
payload: g("payload") ?? null,
|
|
114
|
+
priority: g("priority"),
|
|
115
|
+
idempotencyKey: g("idempotency_key"),
|
|
116
|
+
subject: g("subject") ?? null,
|
|
117
|
+
createdAt: date(g("created_at"))
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function inboxItem(r) {
|
|
121
|
+
return {
|
|
122
|
+
id: str(r.id),
|
|
123
|
+
recipientId: r.recipient_id,
|
|
124
|
+
notificationId: r.notification_id,
|
|
125
|
+
title: r.title,
|
|
126
|
+
body: r.body,
|
|
127
|
+
...r.data !== null && r.data !== void 0 && { data: r.data },
|
|
128
|
+
createdAt: date(r.created_at),
|
|
129
|
+
readAt: dateOrNull(r.read_at)
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
var D_COLS = (a) => `${a}.id::text AS id, ${a}.notification_id::text AS notification_id, ${a}.channel, ${a}.address,
|
|
133
|
+
${a}.recipient_id, ${a}.status, ${a}.attempts, ${a}.next_attempt_at, ${a}.lease_until, ${a}.last_error, ${a}.created_at`;
|
|
134
|
+
var N_COLS = (a, p = "") => `${a}.id::text AS ${p}id, ${a}.event AS ${p}event, ${a}.payload AS ${p}payload, ${a}.priority AS ${p}priority,
|
|
135
|
+
${a}.idempotency_key AS ${p}idempotency_key, ${a}.subject AS ${p}subject, ${a}.created_at AS ${p}created_at`;
|
|
136
|
+
var encodeCursor = (x) => btoa(`${x.createdAt.getTime()}|${x.id}`);
|
|
137
|
+
function decodeCursor(cursor) {
|
|
138
|
+
const [ms, id] = atob(cursor).split("|");
|
|
139
|
+
if (!ms || !id || !DIGITS.test(ms) || !DIGITS.test(id)) return null;
|
|
140
|
+
return { at: new Date(Number(ms)).toISOString(), id };
|
|
141
|
+
}
|
|
142
|
+
function postgresStore(options) {
|
|
143
|
+
const { db } = options;
|
|
144
|
+
const schema = checkSchema(options.schema ?? "public");
|
|
145
|
+
const s = `"${schema}"`;
|
|
146
|
+
const N = `${s}.herald_notifications`;
|
|
147
|
+
const D = `${s}.herald_deliveries`;
|
|
148
|
+
const I = `${s}.herald_inbox`;
|
|
149
|
+
const rows = async (text, values = []) => (await db.query(text, values)).rows;
|
|
150
|
+
const count = async (text, values) => Number((await rows(text, values))[0]?.n ?? 0);
|
|
151
|
+
function pageOf(items, size) {
|
|
152
|
+
const page = items.slice(0, size);
|
|
153
|
+
const last = page[page.length - 1];
|
|
154
|
+
return { items: page, nextCursor: items.length > size && last ? encodeCursor(last) : null };
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
async migrate() {
|
|
158
|
+
await rows(`DO $herald$
|
|
159
|
+
BEGIN
|
|
160
|
+
PERFORM pg_advisory_xact_lock(hashtext('herald:${schema}'));
|
|
161
|
+
${postgresSchemaSql({ schema })}
|
|
162
|
+
END
|
|
163
|
+
$herald$`);
|
|
164
|
+
},
|
|
165
|
+
async enqueue(n) {
|
|
166
|
+
const deliveries = n.deliveries.map((d) => ({
|
|
167
|
+
channel: d.channel,
|
|
168
|
+
address: d.address ?? null,
|
|
169
|
+
recipient_id: d.recipientId ?? null,
|
|
170
|
+
status: d.status
|
|
171
|
+
}));
|
|
172
|
+
const inserted = await rows(
|
|
173
|
+
`WITH n AS (
|
|
174
|
+
INSERT INTO ${N} (event, payload, priority, idempotency_key, subject)
|
|
175
|
+
VALUES ($1, $2::jsonb, $3, $4, $5)
|
|
176
|
+
ON CONFLICT (idempotency_key) DO NOTHING
|
|
177
|
+
RETURNING id
|
|
178
|
+
), d AS (
|
|
179
|
+
INSERT INTO ${D} (notification_id, channel, address, recipient_id, status)
|
|
180
|
+
SELECT n.id, x.e->>'channel', NULLIF(x.e->'address', 'null'::jsonb), x.e->>'recipient_id', x.e->>'status'
|
|
181
|
+
FROM n, jsonb_array_elements($6::jsonb) WITH ORDINALITY AS x(e, ord)
|
|
182
|
+
ORDER BY x.ord
|
|
183
|
+
)
|
|
184
|
+
SELECT id::text AS id FROM n`,
|
|
185
|
+
[n.event, jsonParam(n.payload), n.priority, n.idempotencyKey, n.subject, JSON.stringify(deliveries)]
|
|
186
|
+
);
|
|
187
|
+
if (inserted[0]) return { id: str(inserted[0].id), created: true };
|
|
188
|
+
const existing = await rows(`SELECT id::text AS id FROM ${N} WHERE idempotency_key = $1`, [n.idempotencyKey]);
|
|
189
|
+
if (!existing[0]) throw new Error(`enqueue: idempotency key "${n.idempotencyKey}" conflicted but no row was found`);
|
|
190
|
+
return { id: str(existing[0].id), created: false };
|
|
191
|
+
},
|
|
192
|
+
async claim({ limit, now, leaseMs, notificationId }) {
|
|
193
|
+
if (notificationId !== void 0 && !DIGITS.test(notificationId)) return [];
|
|
194
|
+
const only = notificationId !== void 0 ? "AND notification_id = $4::bigint" : "";
|
|
195
|
+
const values = [iso(now), limit, iso(new Date(now.getTime() + leaseMs))];
|
|
196
|
+
if (notificationId !== void 0) values.push(notificationId);
|
|
197
|
+
const got = await rows(
|
|
198
|
+
`WITH due AS (
|
|
199
|
+
SELECT id FROM ${D}
|
|
200
|
+
WHERE status IN ('pending', 'retry') AND (next_attempt_at IS NULL OR next_attempt_at <= $1::timestamptz) ${only}
|
|
201
|
+
ORDER BY next_attempt_at NULLS FIRST, created_at, id
|
|
202
|
+
LIMIT $2 FOR UPDATE SKIP LOCKED
|
|
203
|
+
), expired AS (
|
|
204
|
+
SELECT id FROM ${D}
|
|
205
|
+
WHERE status = 'sending' AND lease_until <= $1::timestamptz ${only}
|
|
206
|
+
ORDER BY lease_until, id
|
|
207
|
+
LIMIT $2 FOR UPDATE SKIP LOCKED
|
|
208
|
+
), picked AS (
|
|
209
|
+
SELECT id FROM due UNION ALL SELECT id FROM expired LIMIT $2
|
|
210
|
+
)
|
|
211
|
+
UPDATE ${D} d
|
|
212
|
+
SET status = 'sending', attempts = d.attempts + 1, lease_until = $3::timestamptz
|
|
213
|
+
FROM picked p, ${N} n
|
|
214
|
+
WHERE d.id = p.id AND n.id = d.notification_id
|
|
215
|
+
RETURNING ${D_COLS("d")}, ${N_COLS("n", "n_")}`,
|
|
216
|
+
values
|
|
217
|
+
);
|
|
218
|
+
return got.map((r) => ({ ...delivery(r), notification: notification(r, "n_") }));
|
|
219
|
+
},
|
|
220
|
+
async recordResult(deliveryId, result) {
|
|
221
|
+
if (!DIGITS.test(deliveryId)) return;
|
|
222
|
+
const next = result.status === "retry" ? iso(result.nextAttemptAt) : null;
|
|
223
|
+
const error = result.status === "sent" ? null : result.error;
|
|
224
|
+
await rows(
|
|
225
|
+
`UPDATE ${D} SET status = $2, next_attempt_at = $3::timestamptz, last_error = $4, lease_until = NULL
|
|
226
|
+
WHERE id = $1::bigint AND status = 'sending'`,
|
|
227
|
+
[deliveryId, result.status, next, error]
|
|
228
|
+
);
|
|
229
|
+
},
|
|
230
|
+
async getNotification(id) {
|
|
231
|
+
if (!DIGITS.test(id)) return null;
|
|
232
|
+
const [n] = await rows(`SELECT ${N_COLS("n")} FROM ${N} n WHERE n.id = $1::bigint`, [id]);
|
|
233
|
+
if (!n) return null;
|
|
234
|
+
const ds = await rows(`SELECT ${D_COLS("d")} FROM ${D} d WHERE d.notification_id = $1::bigint ORDER BY d.id`, [id]);
|
|
235
|
+
return { notification: notification(n), deliveries: ds.map((r) => delivery(r)) };
|
|
236
|
+
},
|
|
237
|
+
async listDeliveries(q) {
|
|
238
|
+
const size = q.limit ?? DEFAULT_PAGE;
|
|
239
|
+
const where = [];
|
|
240
|
+
const values = [];
|
|
241
|
+
const add = (sql, v) => {
|
|
242
|
+
values.push(v);
|
|
243
|
+
where.push(sql.replace("?", `$${values.length}`));
|
|
244
|
+
};
|
|
245
|
+
if (q.recipientId !== void 0) add("d.recipient_id = ?", q.recipientId);
|
|
246
|
+
if (q.event !== void 0) add("n.event = ?", q.event);
|
|
247
|
+
if (q.channel !== void 0) add("d.channel = ?", q.channel);
|
|
248
|
+
if (q.status !== void 0) add("d.status = ?", q.status);
|
|
249
|
+
if (q.subject !== void 0) add("n.subject = ?", q.subject);
|
|
250
|
+
if (q.since) add("d.created_at >= ?::timestamptz", iso(q.since));
|
|
251
|
+
if (q.until) add("d.created_at < ?::timestamptz", iso(q.until));
|
|
252
|
+
if (q.cursor) {
|
|
253
|
+
const c = decodeCursor(q.cursor);
|
|
254
|
+
if (!c) return { items: [], nextCursor: null };
|
|
255
|
+
values.push(c.at, c.id);
|
|
256
|
+
where.push(`(d.created_at, d.id) < ($${values.length - 1}::timestamptz, $${values.length}::bigint)`);
|
|
257
|
+
}
|
|
258
|
+
values.push(size + 1);
|
|
259
|
+
const got = await rows(
|
|
260
|
+
`SELECT ${D_COLS("d")}, n.event AS n_event, n.subject AS n_subject
|
|
261
|
+
FROM ${D} d JOIN ${N} n ON n.id = d.notification_id
|
|
262
|
+
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
|
263
|
+
ORDER BY d.created_at DESC, d.id DESC
|
|
264
|
+
LIMIT $${values.length}`,
|
|
265
|
+
values
|
|
266
|
+
);
|
|
267
|
+
const items = got.map(
|
|
268
|
+
(r) => ({ ...delivery(r), event: r.n_event, subject: r.n_subject ?? null })
|
|
269
|
+
);
|
|
270
|
+
return pageOf(items, size);
|
|
271
|
+
},
|
|
272
|
+
async retryDelivery(deliveryId) {
|
|
273
|
+
if (!DIGITS.test(deliveryId)) return false;
|
|
274
|
+
return await count(
|
|
275
|
+
`WITH u AS (
|
|
276
|
+
UPDATE ${D} SET status = 'pending', attempts = 0, next_attempt_at = NULL, lease_until = NULL
|
|
277
|
+
WHERE id = $1::bigint AND status = 'dead' RETURNING 1
|
|
278
|
+
) SELECT count(*)::int AS n FROM u`,
|
|
279
|
+
[deliveryId]
|
|
280
|
+
) > 0;
|
|
281
|
+
},
|
|
282
|
+
async cancel({ subject }) {
|
|
283
|
+
return count(
|
|
284
|
+
`WITH u AS (
|
|
285
|
+
UPDATE ${D} d SET status = 'cancelled', next_attempt_at = NULL, lease_until = NULL
|
|
286
|
+
FROM ${N} n
|
|
287
|
+
WHERE n.id = d.notification_id AND n.subject = $1 AND d.status IN ('pending', 'retry')
|
|
288
|
+
RETURNING 1
|
|
289
|
+
) SELECT count(*)::int AS n FROM u`,
|
|
290
|
+
[subject]
|
|
291
|
+
);
|
|
292
|
+
},
|
|
293
|
+
async purge({ olderThan, statuses }) {
|
|
294
|
+
const allowed = (statuses ?? TERMINAL).filter((x) => TERMINAL.includes(x));
|
|
295
|
+
return count(
|
|
296
|
+
`WITH del AS (
|
|
297
|
+
DELETE FROM ${D}
|
|
298
|
+
WHERE created_at < $1::timestamptz
|
|
299
|
+
AND status IN (SELECT jsonb_array_elements_text($2::jsonb))
|
|
300
|
+
RETURNING id
|
|
301
|
+
), gone AS (
|
|
302
|
+
DELETE FROM ${N} n
|
|
303
|
+
WHERE n.created_at < $1::timestamptz
|
|
304
|
+
AND NOT EXISTS (
|
|
305
|
+
SELECT 1 FROM ${D} d
|
|
306
|
+
WHERE d.notification_id = n.id
|
|
307
|
+
AND NOT EXISTS (SELECT 1 FROM del WHERE del.id = d.id) -- anti-join, not NOT IN: scales to huge purges
|
|
308
|
+
)
|
|
309
|
+
)
|
|
310
|
+
SELECT count(*)::int AS n FROM del`,
|
|
311
|
+
[iso(olderThan), JSON.stringify(allowed)]
|
|
312
|
+
);
|
|
313
|
+
},
|
|
314
|
+
async inboxAdd(item) {
|
|
315
|
+
const [r] = await rows(
|
|
316
|
+
`INSERT INTO ${I} (recipient_id, notification_id, title, body, data)
|
|
317
|
+
VALUES ($1, $2, $3, $4, $5::jsonb)
|
|
318
|
+
RETURNING id::text AS id, recipient_id, notification_id, title, body, data, created_at, read_at`,
|
|
319
|
+
[item.recipientId, item.notificationId, item.title, item.body, item.data === void 0 ? null : jsonParam(item.data)]
|
|
320
|
+
);
|
|
321
|
+
return inboxItem(r);
|
|
322
|
+
},
|
|
323
|
+
async inboxList(q) {
|
|
324
|
+
const size = q.limit ?? DEFAULT_PAGE;
|
|
325
|
+
const values = [q.recipientId];
|
|
326
|
+
let extra = q.unreadOnly ? " AND read_at IS NULL" : "";
|
|
327
|
+
if (q.cursor) {
|
|
328
|
+
const c = decodeCursor(q.cursor);
|
|
329
|
+
if (!c) return { items: [], nextCursor: null };
|
|
330
|
+
values.push(c.at, c.id);
|
|
331
|
+
extra += ` AND (created_at, id) < ($2::timestamptz, $3::bigint)`;
|
|
332
|
+
}
|
|
333
|
+
values.push(size + 1);
|
|
334
|
+
const got = await rows(
|
|
335
|
+
`SELECT id::text AS id, recipient_id, notification_id, title, body, data, created_at, read_at
|
|
336
|
+
FROM ${I} WHERE recipient_id = $1${extra}
|
|
337
|
+
ORDER BY created_at DESC, id DESC LIMIT $${values.length}`,
|
|
338
|
+
values
|
|
339
|
+
);
|
|
340
|
+
return pageOf(got.map(inboxItem), size);
|
|
341
|
+
},
|
|
342
|
+
async inboxMarkRead(recipientId, ids) {
|
|
343
|
+
const valid = ids.filter((id) => DIGITS.test(id));
|
|
344
|
+
if (valid.length === 0) return;
|
|
345
|
+
await rows(
|
|
346
|
+
`UPDATE ${I} SET read_at = now()
|
|
347
|
+
WHERE recipient_id = $1 AND read_at IS NULL
|
|
348
|
+
AND id IN (SELECT jsonb_array_elements_text($2::jsonb)::bigint)`,
|
|
349
|
+
[recipientId, JSON.stringify(valid)]
|
|
350
|
+
);
|
|
351
|
+
},
|
|
352
|
+
async inboxUnreadCount(recipientId) {
|
|
353
|
+
return count(`SELECT count(*)::int AS n FROM ${I} WHERE recipient_id = $1 AND read_at IS NULL`, [recipientId]);
|
|
354
|
+
},
|
|
355
|
+
async inboxMarkAllRead(recipientId) {
|
|
356
|
+
return count(
|
|
357
|
+
`WITH u AS (
|
|
358
|
+
UPDATE ${I} SET read_at = now() WHERE recipient_id = $1 AND read_at IS NULL RETURNING 1
|
|
359
|
+
) SELECT count(*)::int AS n FROM u`,
|
|
360
|
+
[recipientId]
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
export {
|
|
366
|
+
postgresSchemaSql,
|
|
367
|
+
postgresStore
|
|
368
|
+
};
|
|
369
|
+
//# sourceMappingURL=postgres.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/postgres.ts"],"sourcesContent":["import { HeraldError } from \"./errors.js\";\r\nimport type {\r\n ClaimedDelivery,\r\n DeliveryPage,\r\n DeliveryRecord,\r\n InboxItem,\r\n InboxPage,\r\n ListedDelivery,\r\n NotificationRecord,\r\n Store,\r\n} from \"./store.js\";\r\nimport type { TerminalStatus } from \"./types.js\";\r\n\r\n/**\r\n * Anything with a pg-style `query`: `pg.Pool`, `pg.Client`, Neon's serverless\r\n * `Pool`, PGlite. Herald never imports a driver and never opens connections.\r\n */\r\nexport interface Queryable {\r\n query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;\r\n}\r\n\r\nexport interface PostgresStoreOptions {\r\n db: Queryable;\r\n /** Postgres schema holding Herald's tables. Default `public`. Plain identifier only. */\r\n schema?: string;\r\n}\r\n\r\nconst IDENT = /^[a-z_][a-z0-9_]*$/;\r\n/** A bigint id: at most 18 digits, so `::bigint` can never overflow (it would throw, not return \"not found\"). */\r\nconst DIGITS = /^\\d{1,18}$/;\r\nconst DEFAULT_PAGE = 50;\r\nconst TERMINAL: readonly TerminalStatus[] = [\"sent\", \"dead\", \"skipped\", \"cancelled\"];\r\nconst SCHEMA_VERSION = 1;\r\n\r\nfunction checkSchema(schema: string): string {\r\n if (!IDENT.test(schema))\r\n throw new HeraldError(\"invalid_config\", `postgres schema \"${schema}\" must match ${IDENT}`);\r\n return schema;\r\n}\r\n\r\n/**\r\n * Schema v1 as plain DDL, for apps that manage migrations themselves (Prisma,\r\n * Drizzle, SQL files). Idempotent. `store.migrate()` runs the same statements\r\n * atomically under an advisory lock.\r\n */\r\nexport function postgresSchemaSql(opts: { schema?: string } = {}): string {\r\n const name = checkSchema(opts.schema ?? \"public\");\r\n const s = `\"${name}\"`; // quoted: the regex already excludes quotes, quoting also allows reserved words\r\n // CREATE SCHEMA checks CREATE-on-database *before* IF NOT EXISTS, so it would fail for a\r\n // least-privilege role even though public exists. Only emit it for a custom schema.\r\n const createSchema = name === \"public\" ? \"\" : `CREATE SCHEMA IF NOT EXISTS ${s};\r\n`;\r\n // Timestamps are timestamptz(3): millisecond precision, exactly what a JS Date holds,\r\n // so keyset cursors and lease times round-trip without loss.\r\n return `\r\n${createSchema}\r\nCREATE TABLE IF NOT EXISTS ${s}.herald_schema_version (\r\n version integer PRIMARY KEY,\r\n applied_at timestamptz NOT NULL DEFAULT now()\r\n);\r\n\r\nCREATE TABLE IF NOT EXISTS ${s}.herald_notifications (\r\n id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\r\n event text NOT NULL,\r\n payload jsonb,\r\n priority text NOT NULL CHECK (priority IN ('normal', 'critical')),\r\n idempotency_key text NOT NULL UNIQUE,\r\n subject text,\r\n created_at timestamptz(3) NOT NULL DEFAULT now()\r\n);\r\nCREATE INDEX IF NOT EXISTS herald_notifications_subject_idx\r\n ON ${s}.herald_notifications (subject) WHERE subject IS NOT NULL;\r\nCREATE INDEX IF NOT EXISTS herald_notifications_created_idx\r\n ON ${s}.herald_notifications (created_at);\r\n\r\nCREATE TABLE IF NOT EXISTS ${s}.herald_deliveries (\r\n id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\r\n -- NO ACTION (not RESTRICT, not CASCADE): purge deletes deliveries and their\r\n -- notifications in one statement, which only works because NO ACTION is checked at statement end.\r\n notification_id bigint NOT NULL REFERENCES ${s}.herald_notifications (id),\r\n channel text NOT NULL,\r\n address jsonb,\r\n recipient_id text,\r\n status text NOT NULL CHECK (status IN ('pending', 'sending', 'sent', 'retry', 'dead', 'skipped', 'cancelled')),\r\n attempts integer NOT NULL DEFAULT 0,\r\n next_attempt_at timestamptz(3),\r\n lease_until timestamptz(3),\r\n last_error text,\r\n created_at timestamptz(3) NOT NULL DEFAULT now()\r\n);\r\nCREATE INDEX IF NOT EXISTS herald_deliveries_due_idx\r\n ON ${s}.herald_deliveries (next_attempt_at NULLS FIRST, created_at, id) WHERE status IN ('pending', 'retry');\r\nCREATE INDEX IF NOT EXISTS herald_deliveries_lease_idx\r\n ON ${s}.herald_deliveries (lease_until) WHERE status = 'sending';\r\nCREATE INDEX IF NOT EXISTS herald_deliveries_notification_idx\r\n ON ${s}.herald_deliveries (notification_id);\r\nCREATE INDEX IF NOT EXISTS herald_deliveries_created_idx\r\n ON ${s}.herald_deliveries (created_at DESC, id DESC);\r\nCREATE INDEX IF NOT EXISTS herald_deliveries_recipient_idx\r\n ON ${s}.herald_deliveries (recipient_id, created_at DESC, id DESC);\r\n\r\nCREATE TABLE IF NOT EXISTS ${s}.herald_inbox (\r\n id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\r\n recipient_id text NOT NULL,\r\n notification_id text NOT NULL, -- no FK: purge never touches the inbox\r\n title text NOT NULL,\r\n body text NOT NULL,\r\n data jsonb,\r\n created_at timestamptz(3) NOT NULL DEFAULT now(),\r\n read_at timestamptz(3)\r\n);\r\nCREATE INDEX IF NOT EXISTS herald_inbox_recipient_idx\r\n ON ${s}.herald_inbox (recipient_id, created_at DESC, id DESC);\r\nCREATE INDEX IF NOT EXISTS herald_inbox_unread_idx\r\n ON ${s}.herald_inbox (recipient_id) WHERE read_at IS NULL;\r\n\r\nINSERT INTO ${s}.herald_schema_version (version) VALUES (${SCHEMA_VERSION}) ON CONFLICT DO NOTHING;\r\n`.trim();\r\n}\r\n\r\n// ---- row mapping ------------------------------------------------------------\r\n\r\ntype Row = Record<string, unknown>;\r\n\r\nconst iso = (d: Date) => d.toISOString();\r\nconst str = (v: unknown) => String(v);\r\nconst date = (v: unknown): Date => (v instanceof Date ? v : new Date(v as string));\r\nconst dateOrNull = (v: unknown): Date | null => (v === null || v === undefined ? null : date(v));\r\n/** JSON for a jsonb parameter. `undefined` becomes SQL-side JSON null, like the memory store. */\r\nconst jsonParam = (v: unknown) => JSON.stringify(v ?? null);\r\n\r\nfunction delivery(r: Row, prefix = \"\"): DeliveryRecord {\r\n const g = (k: string) => r[prefix + k];\r\n const recipientId = g(\"recipient_id\");\r\n return {\r\n id: str(g(\"id\")),\r\n notificationId: str(g(\"notification_id\")),\r\n channel: g(\"channel\") as string,\r\n address: g(\"address\") ?? null,\r\n ...(recipientId !== null && recipientId !== undefined && { recipientId: recipientId as string }),\r\n status: g(\"status\") as DeliveryRecord[\"status\"],\r\n attempts: Number(g(\"attempts\")),\r\n nextAttemptAt: dateOrNull(g(\"next_attempt_at\")),\r\n leaseUntil: dateOrNull(g(\"lease_until\")),\r\n lastError: (g(\"last_error\") as string | null) ?? null,\r\n createdAt: date(g(\"created_at\")),\r\n };\r\n}\r\n\r\nfunction notification(r: Row, prefix = \"\"): NotificationRecord {\r\n const g = (k: string) => r[prefix + k];\r\n return {\r\n id: str(g(\"id\")),\r\n event: g(\"event\") as string,\r\n payload: g(\"payload\") ?? null,\r\n priority: g(\"priority\") as NotificationRecord[\"priority\"],\r\n idempotencyKey: g(\"idempotency_key\") as string,\r\n subject: (g(\"subject\") as string | null) ?? null,\r\n createdAt: date(g(\"created_at\")),\r\n };\r\n}\r\n\r\nfunction inboxItem(r: Row): InboxItem {\r\n return {\r\n id: str(r.id),\r\n recipientId: r.recipient_id as string,\r\n notificationId: r.notification_id as string,\r\n title: r.title as string,\r\n body: r.body as string,\r\n ...(r.data !== null && r.data !== undefined && { data: r.data }),\r\n createdAt: date(r.created_at),\r\n readAt: dateOrNull(r.read_at),\r\n };\r\n}\r\n\r\nconst D_COLS = (a: string) =>\r\n `${a}.id::text AS id, ${a}.notification_id::text AS notification_id, ${a}.channel, ${a}.address,\r\n ${a}.recipient_id, ${a}.status, ${a}.attempts, ${a}.next_attempt_at, ${a}.lease_until, ${a}.last_error, ${a}.created_at`;\r\nconst N_COLS = (a: string, p = \"\") =>\r\n `${a}.id::text AS ${p}id, ${a}.event AS ${p}event, ${a}.payload AS ${p}payload, ${a}.priority AS ${p}priority,\r\n ${a}.idempotency_key AS ${p}idempotency_key, ${a}.subject AS ${p}subject, ${a}.created_at AS ${p}created_at`;\r\n\r\n// Keyset cursor over (created_at, id), newest first. created_at is millisecond precision (timestamptz(3)).\r\nconst encodeCursor = (x: { createdAt: Date; id: string }) => btoa(`${x.createdAt.getTime()}|${x.id}`);\r\nfunction decodeCursor(cursor: string): { at: string; id: string } | null {\r\n const [ms, id] = atob(cursor).split(\"|\");\r\n if (!ms || !id || !DIGITS.test(ms) || !DIGITS.test(id)) return null;\r\n return { at: new Date(Number(ms)).toISOString(), id };\r\n}\r\n\r\n/**\r\n * Postgres Store. Every method is a single SQL statement (CTEs where needed),\r\n * so it works over pooled and serverless connections without transactions.\r\n * Call `migrate()` once (or apply `postgresSchemaSql()` yourself) before use.\r\n */\r\nexport function postgresStore(options: PostgresStoreOptions): Store {\r\n const { db } = options;\r\n const schema = checkSchema(options.schema ?? \"public\");\r\n const s = `\"${schema}\"`;\r\n const N = `${s}.herald_notifications`;\r\n const D = `${s}.herald_deliveries`;\r\n const I = `${s}.herald_inbox`;\r\n\r\n const rows = async (text: string, values: unknown[] = []) => (await db.query(text, values)).rows;\r\n const count = async (text: string, values: unknown[]) => Number((await rows(text, values))[0]?.n ?? 0);\r\n\r\n /** Keyset page: fetch limit+1 to know whether there is a next page. */\r\n function pageOf<T extends { createdAt: Date; id: string }>(items: T[], size: number) {\r\n const page = items.slice(0, size);\r\n const last = page[page.length - 1];\r\n return { items: page, nextCursor: items.length > size && last ? encodeCursor(last) : null };\r\n }\r\n\r\n return {\r\n async migrate() {\r\n // One DO block = one statement: atomic, and valid over the extended query protocol\r\n // (PGlite, Neon), where a multi-statement string is rejected.\r\n await rows(`DO $herald$\r\nBEGIN\r\n PERFORM pg_advisory_xact_lock(hashtext('herald:${schema}'));\r\n ${postgresSchemaSql({ schema })}\r\nEND\r\n$herald$`);\r\n },\r\n\r\n async enqueue(n) {\r\n const deliveries = n.deliveries.map((d) => ({\r\n channel: d.channel,\r\n address: d.address ?? null,\r\n recipient_id: d.recipientId ?? null,\r\n status: d.status,\r\n }));\r\n const inserted = await rows(\r\n `WITH n AS (\r\n INSERT INTO ${N} (event, payload, priority, idempotency_key, subject)\r\n VALUES ($1, $2::jsonb, $3, $4, $5)\r\n ON CONFLICT (idempotency_key) DO NOTHING\r\n RETURNING id\r\n ), d AS (\r\n INSERT INTO ${D} (notification_id, channel, address, recipient_id, status)\r\n SELECT n.id, x.e->>'channel', NULLIF(x.e->'address', 'null'::jsonb), x.e->>'recipient_id', x.e->>'status'\r\n FROM n, jsonb_array_elements($6::jsonb) WITH ORDINALITY AS x(e, ord)\r\n ORDER BY x.ord\r\n )\r\n SELECT id::text AS id FROM n`,\r\n [n.event, jsonParam(n.payload), n.priority, n.idempotencyKey, n.subject, JSON.stringify(deliveries)],\r\n );\r\n if (inserted[0]) return { id: str(inserted[0].id), created: true };\r\n // Duplicate key. Separate statement: under a concurrent insert, the conflicting row\r\n // is not visible in the first statement's snapshot.\r\n const existing = await rows(`SELECT id::text AS id FROM ${N} WHERE idempotency_key = $1`, [n.idempotencyKey]);\r\n if (!existing[0]) throw new Error(`enqueue: idempotency key \"${n.idempotencyKey}\" conflicted but no row was found`);\r\n return { id: str(existing[0].id), created: false };\r\n },\r\n\r\n async claim({ limit, now, leaseMs, notificationId }) {\r\n if (notificationId !== undefined && !DIGITS.test(notificationId)) return [];\r\n const only = notificationId !== undefined ? \"AND notification_id = $4::bigint\" : \"\";\r\n const values: unknown[] = [iso(now), limit, iso(new Date(now.getTime() + leaseMs))];\r\n if (notificationId !== undefined) values.push(notificationId);\r\n // Two locked subqueries, not OR/UNION in one: FOR UPDATE can't be used with UNION,\r\n // and an OR across the two partial indexes falls back to a scan.\r\n const got = await rows(\r\n `WITH due AS (\r\n SELECT id FROM ${D}\r\n WHERE status IN ('pending', 'retry') AND (next_attempt_at IS NULL OR next_attempt_at <= $1::timestamptz) ${only}\r\n ORDER BY next_attempt_at NULLS FIRST, created_at, id\r\n LIMIT $2 FOR UPDATE SKIP LOCKED\r\n ), expired AS (\r\n SELECT id FROM ${D}\r\n WHERE status = 'sending' AND lease_until <= $1::timestamptz ${only}\r\n ORDER BY lease_until, id\r\n LIMIT $2 FOR UPDATE SKIP LOCKED\r\n ), picked AS (\r\n SELECT id FROM due UNION ALL SELECT id FROM expired LIMIT $2\r\n )\r\n UPDATE ${D} d\r\n SET status = 'sending', attempts = d.attempts + 1, lease_until = $3::timestamptz\r\n FROM picked p, ${N} n\r\n WHERE d.id = p.id AND n.id = d.notification_id\r\n RETURNING ${D_COLS(\"d\")}, ${N_COLS(\"n\", \"n_\")}`,\r\n values,\r\n );\r\n return got.map((r): ClaimedDelivery => ({ ...delivery(r), notification: notification(r, \"n_\") }));\r\n },\r\n\r\n async recordResult(deliveryId, result) {\r\n if (!DIGITS.test(deliveryId)) return;\r\n const next = result.status === \"retry\" ? iso(result.nextAttemptAt) : null;\r\n const error = result.status === \"sent\" ? null : result.error;\r\n // Only a row still `sending`: a late result never un-cancels a row.\r\n await rows(\r\n `UPDATE ${D} SET status = $2, next_attempt_at = $3::timestamptz, last_error = $4, lease_until = NULL\r\n WHERE id = $1::bigint AND status = 'sending'`,\r\n [deliveryId, result.status, next, error],\r\n );\r\n },\r\n\r\n async getNotification(id) {\r\n if (!DIGITS.test(id)) return null;\r\n const [n] = await rows(`SELECT ${N_COLS(\"n\")} FROM ${N} n WHERE n.id = $1::bigint`, [id]);\r\n if (!n) return null;\r\n const ds = await rows(`SELECT ${D_COLS(\"d\")} FROM ${D} d WHERE d.notification_id = $1::bigint ORDER BY d.id`, [id]);\r\n return { notification: notification(n), deliveries: ds.map((r) => delivery(r)) };\r\n },\r\n\r\n async listDeliveries(q): Promise<DeliveryPage> {\r\n const size = q.limit ?? DEFAULT_PAGE;\r\n const where: string[] = [];\r\n const values: unknown[] = [];\r\n const add = (sql: string, v: unknown) => {\r\n values.push(v);\r\n where.push(sql.replace(\"?\", `$${values.length}`));\r\n };\r\n if (q.recipientId !== undefined) add(\"d.recipient_id = ?\", q.recipientId);\r\n if (q.event !== undefined) add(\"n.event = ?\", q.event);\r\n if (q.channel !== undefined) add(\"d.channel = ?\", q.channel);\r\n if (q.status !== undefined) add(\"d.status = ?\", q.status);\r\n if (q.subject !== undefined) add(\"n.subject = ?\", q.subject);\r\n if (q.since) add(\"d.created_at >= ?::timestamptz\", iso(q.since));\r\n if (q.until) add(\"d.created_at < ?::timestamptz\", iso(q.until));\r\n if (q.cursor) {\r\n const c = decodeCursor(q.cursor);\r\n if (!c) return { items: [], nextCursor: null };\r\n values.push(c.at, c.id);\r\n where.push(`(d.created_at, d.id) < ($${values.length - 1}::timestamptz, $${values.length}::bigint)`);\r\n }\r\n values.push(size + 1);\r\n const got = await rows(\r\n `SELECT ${D_COLS(\"d\")}, n.event AS n_event, n.subject AS n_subject\r\n FROM ${D} d JOIN ${N} n ON n.id = d.notification_id\r\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\r\n ORDER BY d.created_at DESC, d.id DESC\r\n LIMIT $${values.length}`,\r\n values,\r\n );\r\n const items = got.map(\r\n (r): ListedDelivery => ({ ...delivery(r), event: r.n_event as string, subject: (r.n_subject as string | null) ?? null }),\r\n );\r\n return pageOf(items, size);\r\n },\r\n\r\n async retryDelivery(deliveryId) {\r\n if (!DIGITS.test(deliveryId)) return false;\r\n return (\r\n (await count(\r\n `WITH u AS (\r\n UPDATE ${D} SET status = 'pending', attempts = 0, next_attempt_at = NULL, lease_until = NULL\r\n WHERE id = $1::bigint AND status = 'dead' RETURNING 1\r\n ) SELECT count(*)::int AS n FROM u`,\r\n [deliveryId],\r\n )) > 0\r\n );\r\n },\r\n\r\n async cancel({ subject }) {\r\n return count(\r\n `WITH u AS (\r\n UPDATE ${D} d SET status = 'cancelled', next_attempt_at = NULL, lease_until = NULL\r\n FROM ${N} n\r\n WHERE n.id = d.notification_id AND n.subject = $1 AND d.status IN ('pending', 'retry')\r\n RETURNING 1\r\n ) SELECT count(*)::int AS n FROM u`,\r\n [subject],\r\n );\r\n },\r\n\r\n async purge({ olderThan, statuses }) {\r\n const allowed = (statuses ?? TERMINAL).filter((x) => TERMINAL.includes(x));\r\n // A data-modifying CTE sees one snapshot: NOT EXISTS would still see the rows `del`\r\n // removes, so those ids are excluded explicitly. Notifications go only if old AND\r\n // left with no deliveries (including ones that never had any).\r\n return count(\r\n `WITH del AS (\r\n DELETE FROM ${D}\r\n WHERE created_at < $1::timestamptz\r\n AND status IN (SELECT jsonb_array_elements_text($2::jsonb))\r\n RETURNING id\r\n ), gone AS (\r\n DELETE FROM ${N} n\r\n WHERE n.created_at < $1::timestamptz\r\n AND NOT EXISTS (\r\n SELECT 1 FROM ${D} d\r\n WHERE d.notification_id = n.id\r\n AND NOT EXISTS (SELECT 1 FROM del WHERE del.id = d.id) -- anti-join, not NOT IN: scales to huge purges\r\n )\r\n )\r\n SELECT count(*)::int AS n FROM del`,\r\n [iso(olderThan), JSON.stringify(allowed)],\r\n );\r\n },\r\n\r\n async inboxAdd(item) {\r\n const [r] = await rows(\r\n `INSERT INTO ${I} (recipient_id, notification_id, title, body, data)\r\n VALUES ($1, $2, $3, $4, $5::jsonb)\r\n RETURNING id::text AS id, recipient_id, notification_id, title, body, data, created_at, read_at`,\r\n [item.recipientId, item.notificationId, item.title, item.body, item.data === undefined ? null : jsonParam(item.data)],\r\n );\r\n return inboxItem(r!);\r\n },\r\n\r\n async inboxList(q): Promise<InboxPage> {\r\n const size = q.limit ?? DEFAULT_PAGE;\r\n const values: unknown[] = [q.recipientId];\r\n let extra = q.unreadOnly ? \" AND read_at IS NULL\" : \"\";\r\n if (q.cursor) {\r\n const c = decodeCursor(q.cursor);\r\n if (!c) return { items: [], nextCursor: null };\r\n values.push(c.at, c.id);\r\n extra += ` AND (created_at, id) < ($2::timestamptz, $3::bigint)`;\r\n }\r\n values.push(size + 1);\r\n const got = await rows(\r\n `SELECT id::text AS id, recipient_id, notification_id, title, body, data, created_at, read_at\r\n FROM ${I} WHERE recipient_id = $1${extra}\r\n ORDER BY created_at DESC, id DESC LIMIT $${values.length}`,\r\n values,\r\n );\r\n return pageOf(got.map(inboxItem), size);\r\n },\r\n\r\n async inboxMarkRead(recipientId, ids) {\r\n const valid = ids.filter((id) => DIGITS.test(id));\r\n if (valid.length === 0) return;\r\n await rows(\r\n `UPDATE ${I} SET read_at = now()\r\n WHERE recipient_id = $1 AND read_at IS NULL\r\n AND id IN (SELECT jsonb_array_elements_text($2::jsonb)::bigint)`,\r\n [recipientId, JSON.stringify(valid)],\r\n );\r\n },\r\n\r\n async inboxUnreadCount(recipientId) {\r\n return count(`SELECT count(*)::int AS n FROM ${I} WHERE recipient_id = $1 AND read_at IS NULL`, [recipientId]);\r\n },\r\n\r\n async inboxMarkAllRead(recipientId) {\r\n return count(\r\n `WITH u AS (\r\n UPDATE ${I} SET read_at = now() WHERE recipient_id = $1 AND read_at IS NULL RETURNING 1\r\n ) SELECT count(*)::int AS n FROM u`,\r\n [recipientId],\r\n );\r\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A,EACF;AACF;","names":[]}
|
|
@@ -21,6 +21,11 @@ interface Targets<C extends string = string> {
|
|
|
21
21
|
* the idempotency key. Lets you `cancel({ subject })` and filter `listDeliveries`.
|
|
22
22
|
*/
|
|
23
23
|
subject?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Send this notification's deliveries before `notify()` resolves. Failures
|
|
26
|
+
* still never reach the caller: they become retries for `processPending()`.
|
|
27
|
+
*/
|
|
28
|
+
inline?: boolean;
|
|
24
29
|
}
|
|
25
30
|
type DeliveryStatus = "pending" | "sending" | "sent" | "retry" | "dead" | "skipped" | "cancelled";
|
|
26
31
|
/** Statuses a delivery never leaves on its own. Only these can be purged. */
|
|
@@ -65,8 +70,10 @@ type ResolveAddress = (recipient: RecipientRef, channel: string) => Promise<unkn
|
|
|
65
70
|
interface ProcessOptions {
|
|
66
71
|
/** Max deliveries to claim this call. Default 50. */
|
|
67
72
|
batchSize?: number;
|
|
68
|
-
/** Stop
|
|
73
|
+
/** Stop claiming new work after this many ms (fits function timeouts). Default 20_000. */
|
|
69
74
|
budgetMs?: number;
|
|
75
|
+
/** Deliveries claimed and sent in parallel at a time. Default 10. */
|
|
76
|
+
concurrency?: number;
|
|
70
77
|
}
|
|
71
78
|
interface ProcessSummary {
|
|
72
79
|
claimed: number;
|
|
@@ -190,12 +197,14 @@ interface Store {
|
|
|
190
197
|
* `nextAttemptAt <= now`) or whose lease expired. Sets `leaseUntil = now + leaseMs`
|
|
191
198
|
* and status `sending`. Concurrent callers must never receive the same row
|
|
192
199
|
* (Postgres: `FOR UPDATE SKIP LOCKED`). Lease expiry is what makes a killed
|
|
193
|
-
* worker's rows reappear: delivery is at-least-once.
|
|
200
|
+
* worker's rows reappear: delivery is at-least-once. `notificationId`, when
|
|
201
|
+
* given, restricts the claim to that notification's deliveries (inline send).
|
|
194
202
|
*/
|
|
195
203
|
claim(opts: {
|
|
196
204
|
limit: number;
|
|
197
205
|
now: Date;
|
|
198
206
|
leaseMs: number;
|
|
207
|
+
notificationId?: string;
|
|
199
208
|
}): Promise<ClaimedDelivery[]>;
|
|
200
209
|
/**
|
|
201
210
|
* Record an attempt outcome: status, attempts, error; clears the lease.
|
package/dist/testing.d.ts
CHANGED
package/dist/testing.js
CHANGED
|
@@ -75,6 +75,41 @@ function runStoreContract({ name, create }) {
|
|
|
75
75
|
expect(deliveryIds).toHaveLength(1);
|
|
76
76
|
expect(await store.claim({ limit: 10, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 })).toEqual([]);
|
|
77
77
|
});
|
|
78
|
+
it("stores payload and address as JSON: Dates become strings, undefined becomes null", async () => {
|
|
79
|
+
const at = /* @__PURE__ */ new Date("2026-01-02T03:04:05.678Z");
|
|
80
|
+
const { id } = await store.enqueue({
|
|
81
|
+
event: "e",
|
|
82
|
+
payload: { at, list: [1, "two"], nested: { ok: true } },
|
|
83
|
+
priority: "normal",
|
|
84
|
+
idempotencyKey: `json-${++keySeq}`,
|
|
85
|
+
subject: null,
|
|
86
|
+
deliveries: [{ channel: "slack", address: { at, ch: "C1" }, recipientId: "u1", status: "pending" }]
|
|
87
|
+
});
|
|
88
|
+
const got = await store.getNotification(id);
|
|
89
|
+
expect(got.notification.payload).toEqual({ at: at.toISOString(), list: [1, "two"], nested: { ok: true } });
|
|
90
|
+
expect(got.deliveries[0].address).toEqual({ at: at.toISOString(), ch: "C1" });
|
|
91
|
+
const v = await store.enqueue({
|
|
92
|
+
event: "e",
|
|
93
|
+
payload: void 0,
|
|
94
|
+
priority: "normal",
|
|
95
|
+
idempotencyKey: `json-${++keySeq}`,
|
|
96
|
+
subject: null,
|
|
97
|
+
deliveries: []
|
|
98
|
+
});
|
|
99
|
+
expect((await store.getNotification(v.id)).notification.payload).toBeNull();
|
|
100
|
+
const s = await store.enqueue({
|
|
101
|
+
event: "e",
|
|
102
|
+
payload: "just a string",
|
|
103
|
+
priority: "normal",
|
|
104
|
+
idempotencyKey: `json-${++keySeq}`,
|
|
105
|
+
subject: null,
|
|
106
|
+
deliveries: []
|
|
107
|
+
});
|
|
108
|
+
expect((await store.getNotification(s.id)).notification.payload).toBe("just a string");
|
|
109
|
+
const item = await store.inboxAdd({ recipientId: "u1", notificationId: id, title: "t", body: "b", data: { at } });
|
|
110
|
+
expect(item.data).toEqual({ at: at.toISOString() });
|
|
111
|
+
expect((await store.inboxList({ recipientId: "u1" })).items[0].data).toEqual({ at: at.toISOString() });
|
|
112
|
+
});
|
|
78
113
|
it("getNotification returns null for an unknown id", async () => {
|
|
79
114
|
expect(await store.getNotification("does-not-exist")).toBeNull();
|
|
80
115
|
});
|
|
@@ -130,6 +165,17 @@ function runStoreContract({ name, create }) {
|
|
|
130
165
|
expect(claimed).toHaveLength(1);
|
|
131
166
|
expect(claimed[0].attempts).toBe(2);
|
|
132
167
|
});
|
|
168
|
+
it("notificationId restricts the claim to that notification's due deliveries", async () => {
|
|
169
|
+
const a = await enqueue(store, { deliveries: [{ channel: "a" }, { channel: "b" }] });
|
|
170
|
+
const b = await enqueue(store);
|
|
171
|
+
const now = /* @__PURE__ */ new Date();
|
|
172
|
+
const claimed = await store.claim({ limit: 10, now, leaseMs: 1e3, notificationId: a.id });
|
|
173
|
+
expect(sorted(claimed.map((d) => d.id))).toEqual(sorted(a.deliveryIds));
|
|
174
|
+
expect(await store.claim({ limit: 10, now, leaseMs: 1e3, notificationId: a.id })).toEqual([]);
|
|
175
|
+
expect(await store.claim({ limit: 10, now, leaseMs: 1e3, notificationId: "unknown" })).toEqual([]);
|
|
176
|
+
const rest = await store.claim({ limit: 10, now, leaseMs: 1e3 });
|
|
177
|
+
expect(rest.map((d) => d.id)).toEqual(b.deliveryIds);
|
|
178
|
+
});
|
|
133
179
|
it("never claims sent, dead or cancelled rows", async () => {
|
|
134
180
|
await enqueue(store, { subject: "gone" });
|
|
135
181
|
expect(await store.cancel({ subject: "gone" })).toBe(1);
|
|
@@ -310,6 +356,13 @@ function runStoreContract({ name, create }) {
|
|
|
310
356
|
expect(await store.getNotification(live.id)).not.toBeNull();
|
|
311
357
|
expect((await store.getNotification(live.id)).deliveries).toHaveLength(1);
|
|
312
358
|
});
|
|
359
|
+
it("keeps a notification with no deliveries until it is older than the cutoff", async () => {
|
|
360
|
+
const { id } = await enqueue(store, { deliveries: [] });
|
|
361
|
+
await store.purge({ olderThan: new Date(Date.now() - 36e5) });
|
|
362
|
+
expect(await store.getNotification(id)).not.toBeNull();
|
|
363
|
+
await store.purge({ olderThan: future() });
|
|
364
|
+
expect(await store.getNotification(id)).toBeNull();
|
|
365
|
+
});
|
|
313
366
|
it("never deletes pending, retry or sending rows", async () => {
|
|
314
367
|
const a = await enqueue(store, { deliveries: [{ channel: "a" }, { channel: "b" }, { channel: "c" }] });
|
|
315
368
|
const claimed = await store.claim({ limit: 2, now: /* @__PURE__ */ new Date(), leaseMs: 6e4 });
|