@useherald/core 0.4.0 → 0.6.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/channel-CQnx-miD.d.ts +37 -0
- package/dist/chunk-UNUPED23.js +14 -0
- package/dist/chunk-UNUPED23.js.map +1 -0
- package/dist/index.d.ts +31 -32
- package/dist/index.js +53 -22
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts +1 -1
- package/dist/memory.js +21 -3
- package/dist/memory.js.map +1 -1
- package/dist/postgres.d.ts +32 -0
- package/dist/postgres.js +393 -0
- package/dist/postgres.js.map +1 -0
- package/dist/slack.d.ts +33 -0
- package/dist/slack.js +86 -0
- package/dist/slack.js.map +1 -0
- package/dist/{store-D-yCqAN7.d.ts → store-C5wWRhSY.d.ts} +12 -1
- package/dist/testing.d.ts +26 -2
- package/dist/testing.js +140 -0
- package/dist/testing.js.map +1 -1
- package/package.json +12 -1
package/dist/postgres.js
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
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 = 2;
|
|
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
|
+
-- v2: idempotent inbox writes (a retried in-app delivery never shows twice).
|
|
84
|
+
-- ADD COLUMN without a default is metadata-only: instant on any table size.
|
|
85
|
+
ALTER TABLE ${s}.herald_inbox ADD COLUMN IF NOT EXISTS idempotency_key text;
|
|
86
|
+
CREATE UNIQUE INDEX IF NOT EXISTS herald_inbox_key_idx
|
|
87
|
+
ON ${s}.herald_inbox (idempotency_key);
|
|
88
|
+
|
|
89
|
+
INSERT INTO ${s}.herald_schema_version (version) VALUES (${SCHEMA_VERSION}) ON CONFLICT DO NOTHING;
|
|
90
|
+
`.trim();
|
|
91
|
+
}
|
|
92
|
+
var iso = (d) => d.toISOString();
|
|
93
|
+
var str = (v) => String(v);
|
|
94
|
+
var date = (v) => v instanceof Date ? v : new Date(v);
|
|
95
|
+
var dateOrNull = (v) => v === null || v === void 0 ? null : date(v);
|
|
96
|
+
var jsonParam = (v) => JSON.stringify(v ?? null);
|
|
97
|
+
function delivery(r, prefix = "") {
|
|
98
|
+
const g = (k) => r[prefix + k];
|
|
99
|
+
const recipientId = g("recipient_id");
|
|
100
|
+
return {
|
|
101
|
+
id: str(g("id")),
|
|
102
|
+
notificationId: str(g("notification_id")),
|
|
103
|
+
channel: g("channel"),
|
|
104
|
+
address: g("address") ?? null,
|
|
105
|
+
...recipientId !== null && recipientId !== void 0 && { recipientId },
|
|
106
|
+
status: g("status"),
|
|
107
|
+
attempts: Number(g("attempts")),
|
|
108
|
+
nextAttemptAt: dateOrNull(g("next_attempt_at")),
|
|
109
|
+
leaseUntil: dateOrNull(g("lease_until")),
|
|
110
|
+
lastError: g("last_error") ?? null,
|
|
111
|
+
createdAt: date(g("created_at"))
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function notification(r, prefix = "") {
|
|
115
|
+
const g = (k) => r[prefix + k];
|
|
116
|
+
return {
|
|
117
|
+
id: str(g("id")),
|
|
118
|
+
event: g("event"),
|
|
119
|
+
payload: g("payload") ?? null,
|
|
120
|
+
priority: g("priority"),
|
|
121
|
+
idempotencyKey: g("idempotency_key"),
|
|
122
|
+
subject: g("subject") ?? null,
|
|
123
|
+
createdAt: date(g("created_at"))
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function inboxItem(r) {
|
|
127
|
+
return {
|
|
128
|
+
id: str(r.id),
|
|
129
|
+
recipientId: r.recipient_id,
|
|
130
|
+
notificationId: r.notification_id,
|
|
131
|
+
title: r.title,
|
|
132
|
+
body: r.body,
|
|
133
|
+
...r.data !== null && r.data !== void 0 && { data: r.data },
|
|
134
|
+
createdAt: date(r.created_at),
|
|
135
|
+
readAt: dateOrNull(r.read_at)
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
var D_COLS = (a) => `${a}.id::text AS id, ${a}.notification_id::text AS notification_id, ${a}.channel, ${a}.address,
|
|
139
|
+
${a}.recipient_id, ${a}.status, ${a}.attempts, ${a}.next_attempt_at, ${a}.lease_until, ${a}.last_error, ${a}.created_at`;
|
|
140
|
+
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,
|
|
141
|
+
${a}.idempotency_key AS ${p}idempotency_key, ${a}.subject AS ${p}subject, ${a}.created_at AS ${p}created_at`;
|
|
142
|
+
var encodeCursor = (x) => btoa(`${x.createdAt.getTime()}|${x.id}`);
|
|
143
|
+
function decodeCursor(cursor) {
|
|
144
|
+
const [ms, id] = atob(cursor).split("|");
|
|
145
|
+
if (!ms || !id || !DIGITS.test(ms) || !DIGITS.test(id)) return null;
|
|
146
|
+
return { at: new Date(Number(ms)).toISOString(), id };
|
|
147
|
+
}
|
|
148
|
+
function postgresStore(options) {
|
|
149
|
+
const { db } = options;
|
|
150
|
+
const schema = checkSchema(options.schema ?? "public");
|
|
151
|
+
const s = `"${schema}"`;
|
|
152
|
+
const N = `${s}.herald_notifications`;
|
|
153
|
+
const D = `${s}.herald_deliveries`;
|
|
154
|
+
const I = `${s}.herald_inbox`;
|
|
155
|
+
const rows = async (text, values = []) => (await db.query(text, values)).rows;
|
|
156
|
+
const count = async (text, values) => Number((await rows(text, values))[0]?.n ?? 0);
|
|
157
|
+
function pageOf(items, size) {
|
|
158
|
+
const page = items.slice(0, size);
|
|
159
|
+
const last = page[page.length - 1];
|
|
160
|
+
return { items: page, nextCursor: items.length > size && last ? encodeCursor(last) : null };
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
async migrate() {
|
|
164
|
+
await rows(`DO $herald$
|
|
165
|
+
BEGIN
|
|
166
|
+
PERFORM pg_advisory_xact_lock(hashtext('herald:${schema}'));
|
|
167
|
+
${postgresSchemaSql({ schema })}
|
|
168
|
+
END
|
|
169
|
+
$herald$`);
|
|
170
|
+
},
|
|
171
|
+
async enqueue(n) {
|
|
172
|
+
const deliveries = n.deliveries.map((d) => ({
|
|
173
|
+
channel: d.channel,
|
|
174
|
+
address: d.address ?? null,
|
|
175
|
+
recipient_id: d.recipientId ?? null,
|
|
176
|
+
status: d.status
|
|
177
|
+
}));
|
|
178
|
+
const inserted = await rows(
|
|
179
|
+
`WITH n AS (
|
|
180
|
+
INSERT INTO ${N} (event, payload, priority, idempotency_key, subject)
|
|
181
|
+
VALUES ($1, $2::jsonb, $3, $4, $5)
|
|
182
|
+
ON CONFLICT (idempotency_key) DO NOTHING
|
|
183
|
+
RETURNING id
|
|
184
|
+
), d AS (
|
|
185
|
+
INSERT INTO ${D} (notification_id, channel, address, recipient_id, status)
|
|
186
|
+
SELECT n.id, x.e->>'channel', NULLIF(x.e->'address', 'null'::jsonb), x.e->>'recipient_id', x.e->>'status'
|
|
187
|
+
FROM n, jsonb_array_elements($6::jsonb) WITH ORDINALITY AS x(e, ord)
|
|
188
|
+
ORDER BY x.ord
|
|
189
|
+
)
|
|
190
|
+
SELECT id::text AS id FROM n`,
|
|
191
|
+
[n.event, jsonParam(n.payload), n.priority, n.idempotencyKey, n.subject, JSON.stringify(deliveries)]
|
|
192
|
+
);
|
|
193
|
+
if (inserted[0]) return { id: str(inserted[0].id), created: true };
|
|
194
|
+
const existing = await rows(`SELECT id::text AS id FROM ${N} WHERE idempotency_key = $1`, [n.idempotencyKey]);
|
|
195
|
+
if (!existing[0]) throw new Error(`enqueue: idempotency key "${n.idempotencyKey}" conflicted but no row was found`);
|
|
196
|
+
return { id: str(existing[0].id), created: false };
|
|
197
|
+
},
|
|
198
|
+
async claim({ limit, now, leaseMs, notificationId }) {
|
|
199
|
+
if (notificationId !== void 0 && !DIGITS.test(notificationId)) return [];
|
|
200
|
+
const only = notificationId !== void 0 ? "AND notification_id = $4::bigint" : "";
|
|
201
|
+
const values = [iso(now), limit, iso(new Date(now.getTime() + leaseMs))];
|
|
202
|
+
if (notificationId !== void 0) values.push(notificationId);
|
|
203
|
+
const got = await rows(
|
|
204
|
+
`WITH due AS (
|
|
205
|
+
SELECT id FROM ${D}
|
|
206
|
+
WHERE status IN ('pending', 'retry') AND (next_attempt_at IS NULL OR next_attempt_at <= $1::timestamptz) ${only}
|
|
207
|
+
ORDER BY next_attempt_at NULLS FIRST, created_at, id
|
|
208
|
+
LIMIT $2 FOR UPDATE SKIP LOCKED
|
|
209
|
+
), expired AS (
|
|
210
|
+
SELECT id FROM ${D}
|
|
211
|
+
WHERE status = 'sending' AND lease_until <= $1::timestamptz ${only}
|
|
212
|
+
ORDER BY lease_until, id
|
|
213
|
+
LIMIT $2 FOR UPDATE SKIP LOCKED
|
|
214
|
+
), picked AS (
|
|
215
|
+
SELECT id FROM due UNION ALL SELECT id FROM expired LIMIT $2
|
|
216
|
+
)
|
|
217
|
+
UPDATE ${D} d
|
|
218
|
+
SET status = 'sending', attempts = d.attempts + 1, lease_until = $3::timestamptz
|
|
219
|
+
FROM picked p, ${N} n
|
|
220
|
+
WHERE d.id = p.id AND n.id = d.notification_id
|
|
221
|
+
RETURNING ${D_COLS("d")}, ${N_COLS("n", "n_")}`,
|
|
222
|
+
values
|
|
223
|
+
);
|
|
224
|
+
return got.map((r) => ({ ...delivery(r), notification: notification(r, "n_") }));
|
|
225
|
+
},
|
|
226
|
+
async recordResult(deliveryId, result) {
|
|
227
|
+
if (!DIGITS.test(deliveryId)) return;
|
|
228
|
+
const next = result.status === "retry" ? iso(result.nextAttemptAt) : null;
|
|
229
|
+
const error = result.status === "sent" ? null : result.error;
|
|
230
|
+
const refund = result.status === "retry" && result.refundAttempt === true;
|
|
231
|
+
await rows(
|
|
232
|
+
`UPDATE ${D} SET status = $2, next_attempt_at = $3::timestamptz, last_error = $4, lease_until = NULL,
|
|
233
|
+
attempts = CASE WHEN $5::boolean THEN GREATEST(attempts - 1, 0) ELSE attempts END
|
|
234
|
+
WHERE id = $1::bigint AND status = 'sending'`,
|
|
235
|
+
[deliveryId, result.status, next, error, refund]
|
|
236
|
+
);
|
|
237
|
+
},
|
|
238
|
+
async getNotification(id) {
|
|
239
|
+
if (!DIGITS.test(id)) return null;
|
|
240
|
+
const [n] = await rows(`SELECT ${N_COLS("n")} FROM ${N} n WHERE n.id = $1::bigint`, [id]);
|
|
241
|
+
if (!n) return null;
|
|
242
|
+
const ds = await rows(`SELECT ${D_COLS("d")} FROM ${D} d WHERE d.notification_id = $1::bigint ORDER BY d.id`, [id]);
|
|
243
|
+
return { notification: notification(n), deliveries: ds.map((r) => delivery(r)) };
|
|
244
|
+
},
|
|
245
|
+
async listDeliveries(q) {
|
|
246
|
+
const size = q.limit ?? DEFAULT_PAGE;
|
|
247
|
+
const where = [];
|
|
248
|
+
const values = [];
|
|
249
|
+
const add = (sql, v) => {
|
|
250
|
+
values.push(v);
|
|
251
|
+
where.push(sql.replace("?", `$${values.length}`));
|
|
252
|
+
};
|
|
253
|
+
if (q.recipientId !== void 0) add("d.recipient_id = ?", q.recipientId);
|
|
254
|
+
if (q.event !== void 0) add("n.event = ?", q.event);
|
|
255
|
+
if (q.channel !== void 0) add("d.channel = ?", q.channel);
|
|
256
|
+
if (q.status !== void 0) add("d.status = ?", q.status);
|
|
257
|
+
if (q.subject !== void 0) add("n.subject = ?", q.subject);
|
|
258
|
+
if (q.since) add("d.created_at >= ?::timestamptz", iso(q.since));
|
|
259
|
+
if (q.until) add("d.created_at < ?::timestamptz", iso(q.until));
|
|
260
|
+
if (q.cursor) {
|
|
261
|
+
const c = decodeCursor(q.cursor);
|
|
262
|
+
if (!c) return { items: [], nextCursor: null };
|
|
263
|
+
values.push(c.at, c.id);
|
|
264
|
+
where.push(`(d.created_at, d.id) < ($${values.length - 1}::timestamptz, $${values.length}::bigint)`);
|
|
265
|
+
}
|
|
266
|
+
values.push(size + 1);
|
|
267
|
+
const got = await rows(
|
|
268
|
+
`SELECT ${D_COLS("d")}, n.event AS n_event, n.subject AS n_subject
|
|
269
|
+
FROM ${D} d JOIN ${N} n ON n.id = d.notification_id
|
|
270
|
+
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
|
271
|
+
ORDER BY d.created_at DESC, d.id DESC
|
|
272
|
+
LIMIT $${values.length}`,
|
|
273
|
+
values
|
|
274
|
+
);
|
|
275
|
+
const items = got.map(
|
|
276
|
+
(r) => ({ ...delivery(r), event: r.n_event, subject: r.n_subject ?? null })
|
|
277
|
+
);
|
|
278
|
+
return pageOf(items, size);
|
|
279
|
+
},
|
|
280
|
+
async retryDelivery(deliveryId) {
|
|
281
|
+
if (!DIGITS.test(deliveryId)) return false;
|
|
282
|
+
return await count(
|
|
283
|
+
`WITH u AS (
|
|
284
|
+
UPDATE ${D} SET status = 'pending', attempts = 0, next_attempt_at = NULL, lease_until = NULL
|
|
285
|
+
WHERE id = $1::bigint AND status = 'dead' RETURNING 1
|
|
286
|
+
) SELECT count(*)::int AS n FROM u`,
|
|
287
|
+
[deliveryId]
|
|
288
|
+
) > 0;
|
|
289
|
+
},
|
|
290
|
+
async cancel({ subject }) {
|
|
291
|
+
return count(
|
|
292
|
+
`WITH u AS (
|
|
293
|
+
UPDATE ${D} d SET status = 'cancelled', next_attempt_at = NULL, lease_until = NULL
|
|
294
|
+
FROM ${N} n
|
|
295
|
+
WHERE n.id = d.notification_id AND n.subject = $1 AND d.status IN ('pending', 'retry')
|
|
296
|
+
RETURNING 1
|
|
297
|
+
) SELECT count(*)::int AS n FROM u`,
|
|
298
|
+
[subject]
|
|
299
|
+
);
|
|
300
|
+
},
|
|
301
|
+
async purge({ olderThan, statuses }) {
|
|
302
|
+
const allowed = (statuses ?? TERMINAL).filter((x) => TERMINAL.includes(x));
|
|
303
|
+
return count(
|
|
304
|
+
`WITH del AS (
|
|
305
|
+
DELETE FROM ${D}
|
|
306
|
+
WHERE created_at < $1::timestamptz
|
|
307
|
+
AND status IN (SELECT jsonb_array_elements_text($2::jsonb))
|
|
308
|
+
RETURNING id
|
|
309
|
+
), gone AS (
|
|
310
|
+
DELETE FROM ${N} n
|
|
311
|
+
WHERE n.created_at < $1::timestamptz
|
|
312
|
+
AND NOT EXISTS (
|
|
313
|
+
SELECT 1 FROM ${D} d
|
|
314
|
+
WHERE d.notification_id = n.id
|
|
315
|
+
AND NOT EXISTS (SELECT 1 FROM del WHERE del.id = d.id) -- anti-join, not NOT IN: scales to huge purges
|
|
316
|
+
)
|
|
317
|
+
)
|
|
318
|
+
SELECT count(*)::int AS n FROM del`,
|
|
319
|
+
[iso(olderThan), JSON.stringify(allowed)]
|
|
320
|
+
);
|
|
321
|
+
},
|
|
322
|
+
async inboxAdd(item) {
|
|
323
|
+
const cols = "id::text AS id, recipient_id, notification_id, title, body, data, created_at, read_at";
|
|
324
|
+
const inserted = await rows(
|
|
325
|
+
`INSERT INTO ${I} (recipient_id, notification_id, title, body, data, idempotency_key)
|
|
326
|
+
VALUES ($1, $2, $3, $4, $5::jsonb, $6)
|
|
327
|
+
ON CONFLICT (idempotency_key) DO NOTHING
|
|
328
|
+
RETURNING ${cols}`,
|
|
329
|
+
[
|
|
330
|
+
item.recipientId,
|
|
331
|
+
item.notificationId,
|
|
332
|
+
item.title,
|
|
333
|
+
item.body,
|
|
334
|
+
item.data === void 0 ? null : jsonParam(item.data),
|
|
335
|
+
item.key ?? null
|
|
336
|
+
// NULL keys never conflict
|
|
337
|
+
]
|
|
338
|
+
);
|
|
339
|
+
if (inserted[0]) return inboxItem(inserted[0]);
|
|
340
|
+
const [existing] = await rows(`SELECT ${cols} FROM ${I} WHERE idempotency_key = $1 AND recipient_id = $2`, [
|
|
341
|
+
item.key,
|
|
342
|
+
item.recipientId
|
|
343
|
+
]);
|
|
344
|
+
if (!existing) throw new Error(`inboxAdd: key "${item.key}" is already used by another recipient`);
|
|
345
|
+
return inboxItem(existing);
|
|
346
|
+
},
|
|
347
|
+
async inboxList(q) {
|
|
348
|
+
const size = q.limit ?? DEFAULT_PAGE;
|
|
349
|
+
const values = [q.recipientId];
|
|
350
|
+
let extra = q.unreadOnly ? " AND read_at IS NULL" : "";
|
|
351
|
+
if (q.cursor) {
|
|
352
|
+
const c = decodeCursor(q.cursor);
|
|
353
|
+
if (!c) return { items: [], nextCursor: null };
|
|
354
|
+
values.push(c.at, c.id);
|
|
355
|
+
extra += ` AND (created_at, id) < ($2::timestamptz, $3::bigint)`;
|
|
356
|
+
}
|
|
357
|
+
values.push(size + 1);
|
|
358
|
+
const got = await rows(
|
|
359
|
+
`SELECT id::text AS id, recipient_id, notification_id, title, body, data, created_at, read_at
|
|
360
|
+
FROM ${I} WHERE recipient_id = $1${extra}
|
|
361
|
+
ORDER BY created_at DESC, id DESC LIMIT $${values.length}`,
|
|
362
|
+
values
|
|
363
|
+
);
|
|
364
|
+
return pageOf(got.map(inboxItem), size);
|
|
365
|
+
},
|
|
366
|
+
async inboxMarkRead(recipientId, ids) {
|
|
367
|
+
const valid = ids.filter((id) => DIGITS.test(id));
|
|
368
|
+
if (valid.length === 0) return;
|
|
369
|
+
await rows(
|
|
370
|
+
`UPDATE ${I} SET read_at = now()
|
|
371
|
+
WHERE recipient_id = $1 AND read_at IS NULL
|
|
372
|
+
AND id IN (SELECT jsonb_array_elements_text($2::jsonb)::bigint)`,
|
|
373
|
+
[recipientId, JSON.stringify(valid)]
|
|
374
|
+
);
|
|
375
|
+
},
|
|
376
|
+
async inboxUnreadCount(recipientId) {
|
|
377
|
+
return count(`SELECT count(*)::int AS n FROM ${I} WHERE recipient_id = $1 AND read_at IS NULL`, [recipientId]);
|
|
378
|
+
},
|
|
379
|
+
async inboxMarkAllRead(recipientId) {
|
|
380
|
+
return count(
|
|
381
|
+
`WITH u AS (
|
|
382
|
+
UPDATE ${I} SET read_at = now() WHERE recipient_id = $1 AND read_at IS NULL RETURNING 1
|
|
383
|
+
) SELECT count(*)::int AS n FROM u`,
|
|
384
|
+
[recipientId]
|
|
385
|
+
);
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
export {
|
|
390
|
+
postgresSchemaSql,
|
|
391
|
+
postgresStore
|
|
392
|
+
};
|
|
393
|
+
//# 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 = 2;\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\n-- v2: idempotent inbox writes (a retried in-app delivery never shows twice).\r\n-- ADD COLUMN without a default is metadata-only: instant on any table size.\r\nALTER TABLE ${s}.herald_inbox ADD COLUMN IF NOT EXISTS idempotency_key text;\r\nCREATE UNIQUE INDEX IF NOT EXISTS herald_inbox_key_idx\r\n ON ${s}.herald_inbox (idempotency_key);\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 const refund = result.status === \"retry\" && result.refundAttempt === true;\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 attempts = CASE WHEN $5::boolean THEN GREATEST(attempts - 1, 0) ELSE attempts END\r\n WHERE id = $1::bigint AND status = 'sending'`,\r\n [deliveryId, result.status, next, error, refund],\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 cols = \"id::text AS id, recipient_id, notification_id, title, body, data, created_at, read_at\";\r\n const inserted = await rows(\r\n `INSERT INTO ${I} (recipient_id, notification_id, title, body, data, idempotency_key)\r\n VALUES ($1, $2, $3, $4, $5::jsonb, $6)\r\n ON CONFLICT (idempotency_key) DO NOTHING\r\n RETURNING ${cols}`,\r\n [\r\n item.recipientId,\r\n item.notificationId,\r\n item.title,\r\n item.body,\r\n item.data === undefined ? null : jsonParam(item.data),\r\n item.key ?? null, // NULL keys never conflict\r\n ],\r\n );\r\n if (inserted[0]) return inboxItem(inserted[0]);\r\n // Key already used. Separate statement for the same snapshot reason as enqueue.\r\n // Scoped to the recipient: never hand back someone else's item.\r\n const [existing] = await rows(`SELECT ${cols} FROM ${I} WHERE idempotency_key = $1 AND recipient_id = $2`, [\r\n item.key,\r\n item.recipientId,\r\n ]);\r\n if (!existing) throw new Error(`inboxAdd: key \"${item.key}\" is already used by another recipient`);\r\n return inboxItem(existing);\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\n },\r\n };\r\n}\r\n"],"mappings":";;;;;AA2BA,IAAM,QAAQ;AAEd,IAAM,SAAS;AACf,IAAM,eAAe;AACrB,IAAM,WAAsC,CAAC,QAAQ,QAAQ,WAAW,WAAW;AACnF,IAAM,iBAAiB;AAEvB,SAAS,YAAY,QAAwB;AAC3C,MAAI,CAAC,MAAM,KAAK,MAAM;AACpB,UAAM,IAAI,YAAY,kBAAkB,oBAAoB,MAAM,gBAAgB,KAAK,EAAE;AAC3F,SAAO;AACT;AAOO,SAAS,kBAAkB,OAA4B,CAAC,GAAW;AACxE,QAAM,OAAO,YAAY,KAAK,UAAU,QAAQ;AAChD,QAAM,IAAI,IAAI,IAAI;AAGlB,QAAM,eAAe,SAAS,WAAW,KAAK,+BAA+B,CAAC;AAAA;AAI9E,SAAO;AAAA,EACP,YAAY;AAAA,6BACe,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,6BAKD,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,OAUvB,CAAC;AAAA;AAAA,OAED,CAAC;AAAA;AAAA,6BAEqB,CAAC;AAAA;AAAA;AAAA;AAAA,+CAIiB,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,OAYzC,CAAC;AAAA;AAAA,OAED,CAAC;AAAA;AAAA,OA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AE,MAAM;AAC/B,YAAI,CAAC,EAAG,QAAO,EAAE,OAAO,CAAC,GAAG,YAAY,KAAK;AAC7C,eAAO,KAAK,EAAE,IAAI,EAAE,EAAE;AACtB,iBAAS;AAAA,MACX;AACA,aAAO,KAAK,OAAO,CAAC;AACpB,YAAM,MAAM,MAAM;AAAA,QAChB;AAAA,gBACQ,CAAC,2BAA2B,KAAK;AAAA,oDACG,OAAO,MAAM;AAAA,QACzD;AAAA,MACF;AACA,aAAO,OAAO,IAAI,IAAI,SAAS,GAAG,IAAI;AAAA,IACxC;AAAA,IAEA,MAAM,cAAc,aAAa,KAAK;AACpC,YAAM,QAAQ,IAAI,OAAO,CAAC,OAAO,OAAO,KAAK,EAAE,CAAC;AAChD,UAAI,MAAM,WAAW,EAAG;AACxB,YAAM;AAAA,QACJ,UAAU,CAAC;AAAA;AAAA;AAAA,QAGX,CAAC,aAAa,KAAK,UAAU,KAAK,CAAC;AAAA,MACrC;AAAA,IACF;AAAA,IAEA,MAAM,iBAAiB,aAAa;AAClC,aAAO,MAAM,kCAAkC,CAAC,gDAAgD,CAAC,WAAW,CAAC;AAAA,IAC/G;AAAA,IAEA,MAAM,iBAAiB,aAAa;AAClC,aAAO;AAAA,QACL;AAAA,oBACY,CAAC;AAAA;AAAA,QAEb,CAAC,WAAW;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/slack.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { C as Channel } from './channel-CQnx-miD.js';
|
|
2
|
+
|
|
3
|
+
/** What a `slack` template returns. */
|
|
4
|
+
interface SlackMessage {
|
|
5
|
+
/** Required: shown in notifications, and the fallback when `blocks` are given. */
|
|
6
|
+
text: string;
|
|
7
|
+
/** Block Kit blocks, passed through to Slack as is. */
|
|
8
|
+
blocks?: unknown[];
|
|
9
|
+
/** Post as a reply in this thread (the parent message's `ts`). */
|
|
10
|
+
threadTs?: string;
|
|
11
|
+
}
|
|
12
|
+
interface SlackChannelOptions {
|
|
13
|
+
/** Bot token (`xoxb-…`) with the `chat:write` scope. */
|
|
14
|
+
token: string;
|
|
15
|
+
/** Defaults to the global `fetch`. Pass one for tests or older runtimes. */
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
}
|
|
18
|
+
/** A failed `chat.postMessage`. `code` is Slack's error code, or `http_<status>` / `invalid_response`. */
|
|
19
|
+
declare class SlackError extends Error {
|
|
20
|
+
readonly code: string;
|
|
21
|
+
readonly status: number;
|
|
22
|
+
readonly retryAfterMs: number | undefined;
|
|
23
|
+
constructor(code: string, status: number, retryAfterMs?: number, detail?: string);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Posts to Slack via `chat.postMessage`. The address is a Slack conversation
|
|
27
|
+
* id: a channel (`C…`) or a user (`U…`, posted to the bot's DM with them).
|
|
28
|
+
* Slack has no idempotency key, so under at-least-once a crash after Slack
|
|
29
|
+
* accepted a post can post it twice.
|
|
30
|
+
*/
|
|
31
|
+
declare function slackChannel(options: SlackChannelOptions): Channel<SlackMessage, string>;
|
|
32
|
+
|
|
33
|
+
export { type SlackChannelOptions, SlackError, type SlackMessage, slackChannel };
|
package/dist/slack.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HeraldError
|
|
3
|
+
} from "./chunk-UNUPED23.js";
|
|
4
|
+
|
|
5
|
+
// src/slack.ts
|
|
6
|
+
var SlackError = class extends Error {
|
|
7
|
+
code;
|
|
8
|
+
status;
|
|
9
|
+
retryAfterMs;
|
|
10
|
+
constructor(code, status, retryAfterMs, detail) {
|
|
11
|
+
super(`slack chat.postMessage failed: ${code} (HTTP ${status})${detail ? `: ${detail}` : ""}`);
|
|
12
|
+
this.name = "SlackError";
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.retryAfterMs = retryAfterMs;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
var URL = "https://slack.com/api/chat.postMessage";
|
|
19
|
+
var RATE_LIMITED = /* @__PURE__ */ new Set(["ratelimited", "rate_limited"]);
|
|
20
|
+
var TRANSIENT = /* @__PURE__ */ new Set([
|
|
21
|
+
"internal_error",
|
|
22
|
+
"fatal_error",
|
|
23
|
+
"service_unavailable",
|
|
24
|
+
"request_timeout",
|
|
25
|
+
"team_added_to_org",
|
|
26
|
+
"org_login_required",
|
|
27
|
+
"invalid_response"
|
|
28
|
+
]);
|
|
29
|
+
function retryAfter(header) {
|
|
30
|
+
if (header === null || header.trim() === "") return void 0;
|
|
31
|
+
const seconds = Number(header);
|
|
32
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : void 0;
|
|
33
|
+
}
|
|
34
|
+
function slackChannel(options) {
|
|
35
|
+
if (typeof options?.token !== "string" || options.token === "")
|
|
36
|
+
throw new HeraldError("invalid_config", "slackChannel: token must be a non-empty string");
|
|
37
|
+
const { token } = options;
|
|
38
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
39
|
+
return {
|
|
40
|
+
name: "slack",
|
|
41
|
+
async send(message, to, ctx) {
|
|
42
|
+
if (typeof to !== "string" || to === "")
|
|
43
|
+
throw new HeraldError(
|
|
44
|
+
"invalid_targets",
|
|
45
|
+
`slack address must be a Slack conversation id (a non-empty string), got ${typeof to}`
|
|
46
|
+
);
|
|
47
|
+
const res = await doFetch(URL, {
|
|
48
|
+
method: "POST",
|
|
49
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json; charset=utf-8" },
|
|
50
|
+
body: JSON.stringify({
|
|
51
|
+
channel: to,
|
|
52
|
+
text: message.text,
|
|
53
|
+
...message.blocks !== void 0 && { blocks: message.blocks },
|
|
54
|
+
...message.threadTs !== void 0 && { thread_ts: message.threadTs }
|
|
55
|
+
}),
|
|
56
|
+
...ctx.signal && { signal: ctx.signal }
|
|
57
|
+
});
|
|
58
|
+
const wait = retryAfter(res.headers.get("retry-after"));
|
|
59
|
+
const body = await res.json().catch(() => null);
|
|
60
|
+
if (res.status === 429) throw new SlackError("ratelimited", 429, wait);
|
|
61
|
+
if (body?.ok === true) {
|
|
62
|
+
const { channel, ts } = body;
|
|
63
|
+
return typeof channel === "string" && typeof ts === "string" ? { providerId: `${channel}:${ts}` } : {};
|
|
64
|
+
}
|
|
65
|
+
const code = typeof body?.error === "string" ? body.error : body === null && res.ok ? "invalid_response" : `http_${res.status}`;
|
|
66
|
+
const why = body?.response_metadata?.messages;
|
|
67
|
+
throw new SlackError(code, res.status, wait, Array.isArray(why) ? why.join("; ") : void 0);
|
|
68
|
+
},
|
|
69
|
+
classifyError(err) {
|
|
70
|
+
if (err instanceof HeraldError && err.code === "invalid_targets") return { retryable: false };
|
|
71
|
+
if (!(err instanceof SlackError)) return { retryable: true };
|
|
72
|
+
const rateLimited = err.status === 429 || RATE_LIMITED.has(err.code);
|
|
73
|
+
const retryable = rateLimited || err.status >= 500 || TRANSIENT.has(err.code);
|
|
74
|
+
return {
|
|
75
|
+
retryable,
|
|
76
|
+
...retryable && err.retryAfterMs !== void 0 && { retryAfterMs: err.retryAfterMs },
|
|
77
|
+
...rateLimited && { rateLimited: true }
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
export {
|
|
83
|
+
SlackError,
|
|
84
|
+
slackChannel
|
|
85
|
+
};
|
|
86
|
+
//# sourceMappingURL=slack.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/slack.ts"],"sourcesContent":["import type { Channel, ErrorClass } from \"./channel.js\";\nimport { HeraldError } from \"./errors.js\";\n\n/** What a `slack` template returns. */\nexport interface SlackMessage {\n /** Required: shown in notifications, and the fallback when `blocks` are given. */\n text: string;\n /** Block Kit blocks, passed through to Slack as is. */\n blocks?: unknown[];\n /** Post as a reply in this thread (the parent message's `ts`). */\n threadTs?: string;\n}\n\nexport interface SlackChannelOptions {\n /** Bot token (`xoxb-…`) with the `chat:write` scope. */\n token: string;\n /** Defaults to the global `fetch`. Pass one for tests or older runtimes. */\n fetch?: typeof fetch;\n}\n\n/** A failed `chat.postMessage`. `code` is Slack's error code, or `http_<status>` / `invalid_response`. */\nexport class SlackError extends Error {\n readonly code: string;\n readonly status: number;\n readonly retryAfterMs: number | undefined;\n\n constructor(code: string, status: number, retryAfterMs?: number, detail?: string) {\n super(`slack chat.postMessage failed: ${code} (HTTP ${status})${detail ? `: ${detail}` : \"\"}`);\n this.name = \"SlackError\";\n this.code = code;\n this.status = status;\n this.retryAfterMs = retryAfterMs;\n }\n}\n\nconst URL = \"https://slack.com/api/chat.postMessage\";\nconst RATE_LIMITED = new Set([\"ratelimited\", \"rate_limited\"]);\n// Slack's docs call these transient. Every other code (bad token, bot not in channel,\n// missing scope, invalid blocks) needs a fix, not a retry: dead now, `retryDelivery` later.\nconst TRANSIENT = new Set([\n \"internal_error\",\n \"fatal_error\",\n \"service_unavailable\",\n \"request_timeout\",\n \"team_added_to_org\",\n \"org_login_required\",\n \"invalid_response\",\n]);\n\n/** `Retry-After` is in seconds. Missing or junk → undefined (the engine's backoff applies). */\nfunction retryAfter(header: string | null): number | undefined {\n if (header === null || header.trim() === \"\") return undefined;\n const seconds = Number(header);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : undefined;\n}\n\n/**\n * Posts to Slack via `chat.postMessage`. The address is a Slack conversation\n * id: a channel (`C…`) or a user (`U…`, posted to the bot's DM with them).\n * Slack has no idempotency key, so under at-least-once a crash after Slack\n * accepted a post can post it twice.\n */\nexport function slackChannel(options: SlackChannelOptions): Channel<SlackMessage, string> {\n if (typeof options?.token !== \"string\" || options.token === \"\")\n throw new HeraldError(\"invalid_config\", \"slackChannel: token must be a non-empty string\");\n const { token } = options;\n const doFetch = options.fetch ?? globalThis.fetch;\n\n return {\n name: \"slack\",\n async send(message, to, ctx) {\n if (typeof to !== \"string\" || to === \"\")\n throw new HeraldError(\n \"invalid_targets\",\n `slack address must be a Slack conversation id (a non-empty string), got ${typeof to}`,\n );\n const res = await doFetch(URL, {\n method: \"POST\",\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json; charset=utf-8\" },\n body: JSON.stringify({\n channel: to,\n text: message.text,\n ...(message.blocks !== undefined && { blocks: message.blocks }),\n ...(message.threadTs !== undefined && { thread_ts: message.threadTs }),\n }),\n ...(ctx.signal && { signal: ctx.signal }),\n });\n const wait = retryAfter(res.headers.get(\"retry-after\"));\n // Not JSON (e.g. a proxy's HTML error page) → null, classified below.\n const body = (await res.json().catch(() => null)) as {\n ok?: unknown;\n error?: unknown;\n channel?: unknown;\n ts?: unknown;\n response_metadata?: { messages?: unknown };\n } | null;\n if (res.status === 429) throw new SlackError(\"ratelimited\", 429, wait);\n if (body?.ok === true) {\n const { channel, ts } = body;\n return typeof channel === \"string\" && typeof ts === \"string\" ? { providerId: `${channel}:${ts}` } : {};\n }\n // A 2xx that isn't Slack JSON is odd but transient; a non-JSON 4xx (a proxy's 403 page) is\n // classified by its status like any other HTTP error.\n const code =\n typeof body?.error === \"string\"\n ? body.error\n : body === null && res.ok\n ? \"invalid_response\"\n : `http_${res.status}`;\n // Slack explains e.g. which block is invalid here; it ends up in `lastError`.\n const why = body?.response_metadata?.messages;\n throw new SlackError(code, res.status, wait, Array.isArray(why) ? why.join(\"; \") : undefined);\n },\n classifyError(err): ErrorClass {\n if (err instanceof HeraldError && err.code === \"invalid_targets\") return { retryable: false };\n // Network errors, aborts, anything unexpected: transient.\n if (!(err instanceof SlackError)) return { retryable: true };\n const rateLimited = err.status === 429 || RATE_LIMITED.has(err.code);\n const retryable = rateLimited || err.status >= 500 || TRANSIENT.has(err.code);\n return {\n retryable,\n ...(retryable && err.retryAfterMs !== undefined && { retryAfterMs: err.retryAfterMs }),\n ...(rateLimited && { rateLimited: true }),\n };\n },\n };\n}\n"],"mappings":";;;;;AAqBO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAAc,QAAgB,cAAuB,QAAiB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133
|
nextAttemptAt: Date;
|
|
134
134
|
error: string;
|
|
135
|
+
/** Rate-limited: give back the attempt `claim` counted (attempts - 1, never below 0). */
|
|
136
|
+
refundAttempt?: boolean;
|
|
135
137
|
} | {
|
|
136
138
|
status: "dead";
|
|
137
139
|
error: string;
|
|
@@ -246,7 +248,16 @@ interface Store {
|
|
|
246
248
|
notification: NotificationRecord;
|
|
247
249
|
deliveries: DeliveryRecord[];
|
|
248
250
|
} | null>;
|
|
249
|
-
|
|
251
|
+
/**
|
|
252
|
+
* Add an inbox item. With `key`, idempotent: if an item with that key exists,
|
|
253
|
+
* for the same recipient, return it and create nothing (the in-app channel
|
|
254
|
+
* passes the delivery's idempotency key, so a retried delivery never shows
|
|
255
|
+
* twice). A key already used by another recipient is an error: it must never
|
|
256
|
+
* hand back someone else's item.
|
|
257
|
+
*/
|
|
258
|
+
inboxAdd(item: Omit<InboxItem, "id" | "createdAt" | "readAt"> & {
|
|
259
|
+
key?: string;
|
|
260
|
+
}): Promise<InboxItem>;
|
|
250
261
|
inboxList(q: InboxQuery): Promise<InboxPage>;
|
|
251
262
|
inboxMarkRead(recipientId: string, ids: readonly string[]): Promise<void>;
|
|
252
263
|
/** Unread items for the bell badge. */
|