@useherald/core 0.5.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/index.d.ts +31 -32
- package/dist/index.js +50 -13
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts +1 -1
- package/dist/memory.js +10 -1
- package/dist/memory.js.map +1 -1
- package/dist/postgres.d.ts +1 -1
- package/dist/postgres.js +33 -9
- package/dist/postgres.js.map +1 -1
- 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 +98 -0
- package/dist/testing.js.map +1 -1
- package/package.json +5 -1
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
interface SendContext {
|
|
2
|
+
/** Stable per delivery across retries. Pass to providers that dedupe. */
|
|
3
|
+
idempotencyKey: string;
|
|
4
|
+
/** 1-based attempt number. */
|
|
5
|
+
attempt: number;
|
|
6
|
+
/** The notification this delivery belongs to. */
|
|
7
|
+
notificationId: string;
|
|
8
|
+
/** This delivery (one recipient, one channel). */
|
|
9
|
+
deliveryId: string;
|
|
10
|
+
/** Aborts after `sendTimeoutMs`. Herald stops waiting then, whether or not the adapter listens. */
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
}
|
|
13
|
+
interface SendResult {
|
|
14
|
+
providerId?: string;
|
|
15
|
+
}
|
|
16
|
+
interface ErrorClass {
|
|
17
|
+
/** `false` = permanent, the delivery goes straight to `dead`. */
|
|
18
|
+
retryable: boolean;
|
|
19
|
+
/** From e.g. a Slack 429 `Retry-After`. Overrides backoff when present. */
|
|
20
|
+
retryAfterMs?: number;
|
|
21
|
+
/**
|
|
22
|
+
* The provider rate-limited the send. The retry does not use up one of the
|
|
23
|
+
* delivery's `maxAttempts`. Ignored when `retryable` is false.
|
|
24
|
+
*/
|
|
25
|
+
rateLimited?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* One delivery mechanism. `send` throws on failure; the engine asks
|
|
29
|
+
* `classifyError` whether to retry. Adapters own that classification.
|
|
30
|
+
*/
|
|
31
|
+
interface Channel<TMessage = unknown, TAddress = unknown> {
|
|
32
|
+
readonly name: string;
|
|
33
|
+
send(message: TMessage, to: TAddress, ctx: SendContext): Promise<SendResult>;
|
|
34
|
+
classifyError(err: unknown): ErrorClass;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type { Channel as C, ErrorClass as E, SendContext as S, SendResult as a };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,32 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
/** Stable per delivery across retries. Pass to providers that dedupe. */
|
|
6
|
-
idempotencyKey: string;
|
|
7
|
-
/** 1-based attempt number. */
|
|
8
|
-
attempt: number;
|
|
9
|
-
/** Aborts when the processing time budget runs out. */
|
|
10
|
-
signal?: AbortSignal;
|
|
11
|
-
}
|
|
12
|
-
interface SendResult {
|
|
13
|
-
providerId?: string;
|
|
14
|
-
}
|
|
15
|
-
interface ErrorClass {
|
|
16
|
-
/** `false` = permanent, the delivery goes straight to `dead`. */
|
|
17
|
-
retryable: boolean;
|
|
18
|
-
/** From e.g. a Slack 429 `Retry-After`. Overrides backoff when present. */
|
|
19
|
-
retryAfterMs?: number;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* One delivery mechanism. `send` throws on failure; the engine asks
|
|
23
|
-
* `classifyError` whether to retry. Adapters own that classification.
|
|
24
|
-
*/
|
|
25
|
-
interface Channel<TMessage = unknown, TAddress = unknown> {
|
|
26
|
-
readonly name: string;
|
|
27
|
-
send(message: TMessage, to: TAddress, ctx: SendContext): Promise<SendResult>;
|
|
28
|
-
classifyError(err: unknown): ErrorClass;
|
|
29
|
-
}
|
|
1
|
+
import { C as Channel } from './channel-CQnx-miD.js';
|
|
2
|
+
export { E as ErrorClass, S as SendContext, a as SendResult } from './channel-CQnx-miD.js';
|
|
3
|
+
import { T as Targets, P as ProcessOptions, a as ProcessSummary, I as InboxQuery, b as InboxPage, S as Store, R as ResolvePreferences, c as ResolveAddress, H as Hooks, L as Logger, d as RetryPolicy } from './store-C5wWRhSY.js';
|
|
4
|
+
export { C as ClaimedDelivery, D as DeliveryInfo, e as DeliveryPage, f as DeliveryQuery, g as DeliveryRecord, h as DeliveryResult, i as DeliveryStatus, j as InboxItem, k as ListedDelivery, N as NewDelivery, l as NewNotification, m as NotificationRecord, n as Priority, o as RawTarget, p as RecipientRef, q as TerminalStatus } from './store-C5wWRhSY.js';
|
|
30
5
|
|
|
31
6
|
type ChannelMap = Record<string, Channel<any, any>>;
|
|
32
7
|
/** The message type a channel expects from its templates. */
|
|
@@ -90,20 +65,44 @@ interface Herald<Ev extends Record<string, AnyEventDef>> {
|
|
|
90
65
|
notify<E extends keyof Ev & string>(event: E, payload: PayloadOf<Ev[E]>, targets: Targets<AllowedChannel<Ev[E]>>): Promise<string>;
|
|
91
66
|
/** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */
|
|
92
67
|
processPending(opts?: ProcessOptions): Promise<ProcessSummary>;
|
|
68
|
+
/**
|
|
69
|
+
* The in-app inbox. `recipientId` must come from your authenticated session,
|
|
70
|
+
* never from the client request.
|
|
71
|
+
*/
|
|
93
72
|
inbox: {
|
|
73
|
+
/** Newest first, keyset-paginated. */
|
|
94
74
|
list(q: InboxQuery): Promise<InboxPage>;
|
|
75
|
+
/** Ids belonging to another recipient are ignored. */
|
|
95
76
|
markRead(recipientId: string, ids: readonly string[]): Promise<void>;
|
|
77
|
+
/** For the bell badge. */
|
|
78
|
+
unreadCount(recipientId: string): Promise<number>;
|
|
79
|
+
/** Returns how many items were marked. */
|
|
80
|
+
markAllRead(recipientId: string): Promise<number>;
|
|
96
81
|
};
|
|
97
82
|
}
|
|
98
83
|
declare const defaultRetry: RetryPolicy;
|
|
99
84
|
/**
|
|
100
85
|
* Validates config at startup (missing templates, unregistered channels are
|
|
101
86
|
* errors here, not at send time). `notify` queues durably (and sends inline on
|
|
102
|
-
* request); `processPending` delivers
|
|
103
|
-
* a later release.
|
|
87
|
+
* request); `processPending` delivers; `inbox` reads the in-app inbox.
|
|
104
88
|
*/
|
|
105
89
|
declare function createHerald<const Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>>(config: HeraldConfig<Ch, Ev>): Herald<Ev>;
|
|
106
90
|
|
|
91
|
+
/** What an `inapp` template returns. */
|
|
92
|
+
interface InAppMessage {
|
|
93
|
+
title: string;
|
|
94
|
+
body: string;
|
|
95
|
+
/** Anything your UI needs, e.g. `{ leadId }` for a link. Stored as JSON. */
|
|
96
|
+
data?: unknown;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Delivers to the in-app inbox in your own store. The address is the
|
|
100
|
+
* recipient id (the default when no `resolveAddress` is configured).
|
|
101
|
+
* Exactly-once: the delivery's idempotency key is the inbox item key, so a
|
|
102
|
+
* retried delivery never shows twice.
|
|
103
|
+
*/
|
|
104
|
+
declare function inAppChannel(store: Store): Channel<InAppMessage, string>;
|
|
105
|
+
|
|
107
106
|
type HeraldErrorCode = "invalid_config" | "unknown_event" | "channel_not_allowed" | "invalid_targets" | "missing_template" | "not_implemented";
|
|
108
107
|
/** Every error Herald throws on its own behalf. Channel failures never surface through here. */
|
|
109
108
|
declare class HeraldError extends Error {
|
|
@@ -111,4 +110,4 @@ declare class HeraldError extends Error {
|
|
|
111
110
|
constructor(code: HeraldErrorCode, message: string);
|
|
112
111
|
}
|
|
113
112
|
|
|
114
|
-
export { type AllowedChannel,
|
|
113
|
+
export { type AllowedChannel, Channel, type ChannelMap, type EventDef, type Herald, type HeraldConfig, HeraldError, type HeraldErrorCode, Hooks, type InAppMessage, InboxPage, InboxQuery, Logger, type MessageOf, type PayloadOf, ProcessOptions, ProcessSummary, ResolveAddress, ResolvePreferences, RetryPolicy, Store, Targets, createHerald, defaultRetry, defineEvent, inAppChannel };
|
package/dist/index.js
CHANGED
|
@@ -74,6 +74,8 @@ async function notify(deps, event, payload, targets) {
|
|
|
74
74
|
// src/process.ts
|
|
75
75
|
var PROCESS_DEFAULTS = { batchSize: 50, budgetMs: 2e4, concurrency: 10 };
|
|
76
76
|
var MAX_ERROR = 1e3;
|
|
77
|
+
var RATE_LIMIT_FALLBACK_MS = 6e4;
|
|
78
|
+
var MAX_RETRY_AFTER_MS = 864e5;
|
|
77
79
|
var errorText = (err) => (err instanceof Error ? err.message : String(err)).slice(0, MAX_ERROR);
|
|
78
80
|
function backoffMs(attempt2, policy, random = Math.random) {
|
|
79
81
|
const delay = Math.min(policy.maxMs, policy.baseMs * 2 ** (attempt2 - 1));
|
|
@@ -102,6 +104,8 @@ async function attempt(deps, row) {
|
|
|
102
104
|
channel.send(message, row.address, {
|
|
103
105
|
idempotencyKey: `${n.idempotencyKey}:${row.id}`,
|
|
104
106
|
attempt: row.attempts,
|
|
107
|
+
notificationId: n.id,
|
|
108
|
+
deliveryId: row.id,
|
|
105
109
|
signal
|
|
106
110
|
}),
|
|
107
111
|
timedOut
|
|
@@ -149,6 +153,7 @@ async function deliver(deps, row) {
|
|
|
149
153
|
function failure(deps, row, channel, err, timedOut) {
|
|
150
154
|
let retryable = true;
|
|
151
155
|
let retryAfterMs;
|
|
156
|
+
let rateLimited = false;
|
|
152
157
|
let text = errorText(err);
|
|
153
158
|
if (timedOut) {
|
|
154
159
|
text = `send timed out after ${deps.sendTimeoutMs}ms: ${text}`.slice(0, MAX_ERROR);
|
|
@@ -158,6 +163,7 @@ function failure(deps, row, channel, err, timedOut) {
|
|
|
158
163
|
retryable = cls.retryable;
|
|
159
164
|
if (Number.isFinite(cls.retryAfterMs) && cls.retryAfterMs >= 0)
|
|
160
165
|
retryAfterMs = cls.retryAfterMs;
|
|
166
|
+
rateLimited = cls.retryable && cls.rateLimited === true;
|
|
161
167
|
} catch (clsErr) {
|
|
162
168
|
deps.logger?.warn("classifyError threw; treating the error as retryable", {
|
|
163
169
|
channel: row.channel,
|
|
@@ -165,9 +171,12 @@ function failure(deps, row, channel, err, timedOut) {
|
|
|
165
171
|
});
|
|
166
172
|
}
|
|
167
173
|
}
|
|
168
|
-
if (!retryable
|
|
169
|
-
|
|
170
|
-
|
|
174
|
+
if (!retryable) return { status: "dead", error: text };
|
|
175
|
+
if (!rateLimited && row.attempts >= deps.retry.maxAttempts) return { status: "dead", error: text };
|
|
176
|
+
const wait = retryAfterMs !== void 0 ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS) : rateLimited ? RATE_LIMIT_FALLBACK_MS : backoffMs(row.attempts, deps.retry, deps.random);
|
|
177
|
+
const delay = Math.max(1, wait);
|
|
178
|
+
const nextAttemptAt = new Date(deps.now().getTime() + delay);
|
|
179
|
+
return rateLimited ? { status: "retry", nextAttemptAt, error: text, refundAttempt: true } : { status: "retry", nextAttemptAt, error: text };
|
|
171
180
|
}
|
|
172
181
|
async function runHook(deps, name, call) {
|
|
173
182
|
try {
|
|
@@ -208,6 +217,11 @@ async function processPending(deps, opts = {}) {
|
|
|
208
217
|
}
|
|
209
218
|
|
|
210
219
|
// src/herald.ts
|
|
220
|
+
function who(recipientId) {
|
|
221
|
+
if (typeof recipientId !== "string" || recipientId === "")
|
|
222
|
+
throw new HeraldError("invalid_targets", "inbox: recipientId must be a non-empty string");
|
|
223
|
+
return recipientId;
|
|
224
|
+
}
|
|
211
225
|
var defaultRetry = {
|
|
212
226
|
maxAttempts: 5,
|
|
213
227
|
baseMs: 3e4,
|
|
@@ -283,9 +297,6 @@ function createHerald(config) {
|
|
|
283
297
|
leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,
|
|
284
298
|
sendTimeoutMs: config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS
|
|
285
299
|
};
|
|
286
|
-
const notImplemented = (what) => {
|
|
287
|
-
throw new HeraldError("not_implemented", `${what} is not implemented yet`);
|
|
288
|
-
};
|
|
289
300
|
return {
|
|
290
301
|
notify(event, payload, targets) {
|
|
291
302
|
return notify(
|
|
@@ -311,12 +322,10 @@ function createHerald(config) {
|
|
|
311
322
|
return processPending(engine, opts);
|
|
312
323
|
},
|
|
313
324
|
inbox: {
|
|
314
|
-
async
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
async
|
|
318
|
-
return notImplemented("inbox.markRead()");
|
|
319
|
-
}
|
|
325
|
+
list: async (q) => config.store.inboxList({ ...q, recipientId: who(q?.recipientId) }),
|
|
326
|
+
markRead: async (recipientId, ids) => config.store.inboxMarkRead(who(recipientId), ids),
|
|
327
|
+
unreadCount: async (recipientId) => config.store.inboxUnreadCount(who(recipientId)),
|
|
328
|
+
markAllRead: async (recipientId) => config.store.inboxMarkAllRead(who(recipientId))
|
|
320
329
|
}
|
|
321
330
|
};
|
|
322
331
|
}
|
|
@@ -325,10 +334,38 @@ function createHerald(config) {
|
|
|
325
334
|
function defineEvent() {
|
|
326
335
|
return (def) => def;
|
|
327
336
|
}
|
|
337
|
+
|
|
338
|
+
// src/inapp.ts
|
|
339
|
+
function inAppChannel(store) {
|
|
340
|
+
return {
|
|
341
|
+
name: "inapp",
|
|
342
|
+
async send(message, to, ctx) {
|
|
343
|
+
if (typeof to !== "string" || to === "")
|
|
344
|
+
throw new HeraldError(
|
|
345
|
+
"invalid_targets",
|
|
346
|
+
`inapp address must be the recipient id (a non-empty string), got ${typeof to}`
|
|
347
|
+
);
|
|
348
|
+
const item = await store.inboxAdd({
|
|
349
|
+
recipientId: to,
|
|
350
|
+
notificationId: ctx.notificationId,
|
|
351
|
+
title: message.title,
|
|
352
|
+
body: message.body,
|
|
353
|
+
...message.data !== void 0 && { data: message.data },
|
|
354
|
+
key: ctx.idempotencyKey
|
|
355
|
+
});
|
|
356
|
+
return { providerId: item.id };
|
|
357
|
+
},
|
|
358
|
+
// A bad address never fixes itself; anything else is a store error: retry.
|
|
359
|
+
classifyError: (err) => ({
|
|
360
|
+
retryable: !(err instanceof HeraldError && err.code === "invalid_targets")
|
|
361
|
+
})
|
|
362
|
+
};
|
|
363
|
+
}
|
|
328
364
|
export {
|
|
329
365
|
HeraldError,
|
|
330
366
|
createHerald,
|
|
331
367
|
defaultRetry,
|
|
332
|
-
defineEvent
|
|
368
|
+
defineEvent,
|
|
369
|
+
inAppChannel
|
|
333
370
|
};
|
|
334
371
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/notify.ts","../src/process.ts","../src/herald.ts","../src/events.ts"],"sourcesContent":["import { HeraldError } from \"./errors.js\";\nimport type { AnyEventDef } from \"./events.js\";\nimport type { NewDelivery, Store } from \"./store.js\";\nimport type {\n Logger,\n RawTarget,\n RecipientRef,\n ResolveAddress,\n ResolvePreferences,\n Targets,\n} from \"./types.js\";\n\nexport interface NotifyDeps {\n store: Store;\n events: Record<string, AnyEventDef>;\n resolvePreferences?: ResolvePreferences;\n resolveAddress?: ResolveAddress;\n logger?: Logger;\n /** Sends one notification's deliveries now (`targets.inline`). */\n sendInline?: (notificationId: string) => Promise<unknown>;\n}\n\nconst isRaw = (t: RecipientRef | RawTarget): t is RawTarget => \"channel\" in t;\n\n/**\n * Validate, narrow by preferences, resolve addresses, and durably queue.\n * Returns the notification id. Resolver failures propagate and nothing is\n * queued (fail closed: never notify someone who may have opted out).\n */\nexport async function notify(\n deps: NotifyDeps,\n event: string,\n payload: unknown,\n targets: Targets,\n): Promise<string> {\n const def = deps.events[event];\n if (!def) throw new HeraldError(\"unknown_event\", `unknown event \"${event}\"`);\n if (!targets.to?.length)\n throw new HeraldError(\"invalid_targets\", `notify(\"${event}\") needs at least one target in \"to\"`);\n\n const channels = [...new Set(targets.channels ?? def.channels)];\n for (const ch of channels) {\n if (!def.channels.includes(ch))\n throw new HeraldError(\"channel_not_allowed\", `event \"${event}\" does not allow channel \"${ch}\"`);\n }\n\n const raws = targets.to.filter(isRaw);\n for (const r of raws) {\n if (!channels.includes(r.channel))\n throw new HeraldError(\n \"channel_not_allowed\",\n `raw target channel \"${r.channel}\" is not in the channels requested for \"${event}\"`,\n );\n }\n\n const seen = new Set<string>();\n const recipients: RecipientRef[] = [];\n for (const t of targets.to) {\n if (isRaw(t) || seen.has(t.id)) continue;\n seen.add(t.id);\n recipients.push(t);\n }\n\n const priority = targets.priority ?? \"normal\";\n\n // Preferences: one batched call; only narrows; critical bypasses.\n let prefs: ReadonlyMap<string, readonly string[]> | undefined;\n if (deps.resolvePreferences && priority !== \"critical\" && recipients.length > 0) {\n prefs = await deps.resolvePreferences(recipients, event);\n }\n\n const pairs = recipients.flatMap((r) => {\n const allowed = prefs?.get(r.id);\n return channels\n .filter((ch) => !allowed || allowed.includes(ch))\n .map((ch) => ({ r, ch }));\n });\n\n const resolved = await Promise.all(\n pairs.map(async ({ r, ch }): Promise<NewDelivery> => {\n // No resolver configured: the recipient id is the address.\n const address = deps.resolveAddress ? await deps.resolveAddress(r, ch) : r.id;\n return address === null || address === undefined\n ? { channel: ch, address: null, recipientId: r.id, status: \"skipped\" }\n : { channel: ch, address, recipientId: r.id, status: \"pending\" };\n }),\n );\n\n const rawDeliveries: NewDelivery[] = raws.map((r) => ({\n channel: r.channel,\n address: r.address,\n status: \"pending\",\n }));\n\n const { id, created } = await deps.store.enqueue({\n event,\n payload,\n priority,\n idempotencyKey: targets.idempotencyKey ?? globalThis.crypto.randomUUID(),\n subject: targets.subject ?? null,\n deliveries: [...resolved, ...rawDeliveries],\n });\n\n deps.logger?.debug(\"notification queued\", { id, event, created });\n\n // A duplicate key was already queued (and maybe sent): never send it twice.\n if (targets.inline && created && deps.sendInline) {\n try {\n await deps.sendInline(id);\n } catch (err) {\n // Queued durably already; processPending() picks it up. Never surface to the caller.\n deps.logger?.error(\"inline send failed; left for processPending()\", {\n id,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n return id;\n}\n","import type { Channel } from \"./channel.js\";\nimport type { AnyEventDef, ChannelMap } from \"./events.js\";\nimport type { ClaimedDelivery, DeliveryResult, Store } from \"./store.js\";\nimport type {\n DeliveryInfo,\n Hooks,\n Logger,\n ProcessOptions,\n ProcessSummary,\n RetryPolicy,\n} from \"./types.js\";\n\nexport interface EngineDeps {\n store: Store;\n channels: ChannelMap;\n events: Record<string, AnyEventDef>;\n hooks?: Hooks;\n logger?: Logger;\n retry: RetryPolicy;\n now: () => Date;\n leaseMs: number;\n sendTimeoutMs: number;\n /** Injectable for deterministic jitter in tests. */\n random?: () => number;\n}\n\nexport const PROCESS_DEFAULTS = { batchSize: 50, budgetMs: 20_000, concurrency: 10 } as const;\n\nconst MAX_ERROR = 1_000;\n\nconst errorText = (err: unknown): string =>\n (err instanceof Error ? err.message : String(err)).slice(0, MAX_ERROR);\n\n/**\n * Delay before retry number `attempt + 1`. Exponential, capped, with equal\n * jitter (half fixed, half random) so it never collapses to zero.\n */\nexport function backoffMs(attempt: number, policy: RetryPolicy, random = Math.random): number {\n const delay = Math.min(policy.maxMs, policy.baseMs * 2 ** (attempt - 1));\n return policy.jitter ? delay / 2 + random() * (delay / 2) : delay;\n}\n\ntype Outcome = \"sent\" | \"retried\" | \"dead\" | \"unrecorded\";\n\n/** Render and send one claimed row. Returns the result to record plus the raw error, if any. */\nasync function attempt(\n deps: EngineDeps,\n row: ClaimedDelivery,\n): Promise<{ result: DeliveryResult; error?: unknown }> {\n const n = row.notification;\n const def = deps.events[n.event];\n if (!def) return { result: { status: \"dead\", error: `unknown event \"${n.event}\"` } };\n\n const channel = deps.channels[row.channel] as Channel | undefined;\n const template = (def.templates as Record<string, ((p: unknown) => unknown) | undefined>)[row.channel];\n if (!channel || !template)\n return { result: { status: \"dead\", error: `unknown channel \"${row.channel}\" for event \"${n.event}\"` } };\n\n let message: unknown;\n try {\n message = template(n.payload);\n } catch (error) {\n // Same payload + same code fails every time: retrying only burns budget.\n return { result: { status: \"dead\", error: `template failed: ${errorText(error)}` }, error };\n }\n\n const signal = AbortSignal.timeout(deps.sendTimeoutMs);\n // Enforce the timeout even if the adapter ignores `signal`: a hung send must not outlive its lease.\n const timedOut = new Promise<never>((_, reject) =>\n signal.addEventListener(\"abort\", () => reject(signal.reason), { once: true }),\n );\n try {\n const res = await Promise.race([\n channel.send(message, row.address, {\n idempotencyKey: `${n.idempotencyKey}:${row.id}`,\n attempt: row.attempts,\n signal,\n }),\n timedOut,\n ]);\n return { result: { status: \"sent\", ...(res?.providerId !== undefined && { providerId: res.providerId }) } };\n } catch (error) {\n return { result: failure(deps, row, channel, error, signal.aborted), error };\n }\n}\n\nasync function deliver(deps: EngineDeps, row: ClaimedDelivery): Promise<Outcome> {\n const { result, error } = await attempt(deps, row);\n\n try {\n await deps.store.recordResult(row.id, result);\n } catch (err) {\n // Row stays leased; lease expiry hands it to a later run.\n deps.logger?.error(\"recordResult failed; delivery will be retried after its lease\", {\n deliveryId: row.id,\n error: errorText(err),\n });\n return \"unrecorded\";\n }\n\n const info: DeliveryInfo = {\n notificationId: row.notification.id,\n deliveryId: row.id,\n event: row.notification.event,\n channel: row.channel,\n ...(row.recipientId !== undefined && { recipientId: row.recipientId }),\n attempt: row.attempts,\n };\n const meta = { deliveryId: row.id, channel: row.channel, attempt: row.attempts };\n\n if (result.status === \"sent\") {\n await runHook(deps, \"onSent\", () => deps.hooks?.onSent?.(info));\n return \"sent\";\n }\n const failed = { ...info, error: error ?? result.error };\n if (result.status === \"retry\") {\n const nextAttemptAt = result.nextAttemptAt;\n deps.logger?.warn(\"delivery failed, will retry\", { ...meta, error: result.error, nextAttemptAt: nextAttemptAt.toISOString() });\n await runHook(deps, \"onFailed\", () => deps.hooks?.onFailed?.({ ...failed, nextAttemptAt }));\n return \"retried\";\n }\n deps.logger?.error(\"delivery dead\", { ...meta, error: result.error });\n await runHook(deps, \"onDead\", () => deps.hooks?.onDead?.(failed));\n return \"dead\";\n}\n\nfunction failure(\n deps: EngineDeps,\n row: ClaimedDelivery,\n channel: Channel,\n err: unknown,\n timedOut: boolean,\n): DeliveryResult {\n let retryable = true;\n let retryAfterMs: number | undefined;\n let text = errorText(err);\n\n if (timedOut) {\n // The provider may or may not have accepted it; at-least-once says retry.\n text = `send timed out after ${deps.sendTimeoutMs}ms: ${text}`.slice(0, MAX_ERROR);\n } else {\n try {\n const cls = channel.classifyError(err);\n retryable = cls.retryable;\n // Ignore nonsense (NaN, negative, Infinity) and fall back to backoff.\n if (Number.isFinite(cls.retryAfterMs) && (cls.retryAfterMs as number) >= 0)\n retryAfterMs = cls.retryAfterMs;\n } catch (clsErr) {\n deps.logger?.warn(\"classifyError threw; treating the error as retryable\", {\n channel: row.channel,\n error: errorText(clsErr),\n });\n }\n }\n\n if (!retryable || row.attempts >= deps.retry.maxAttempts) return { status: \"dead\", error: text };\n\n // ponytail: a 429 still counts as an attempt (claim already incremented it), so a long\n // rate-limit storm can dead-letter rows. Upgrade: a Store result that refunds the attempt.\n // At least 1ms, so the row is due strictly after the claim snapshot of the current run.\n const delay = Math.max(1, retryAfterMs ?? backoffMs(row.attempts, deps.retry, deps.random));\n return { status: \"retry\", nextAttemptAt: new Date(deps.now().getTime() + delay), error: text };\n}\n\nasync function runHook(deps: EngineDeps, name: keyof Hooks, call: () => unknown): Promise<void> {\n try {\n await call();\n } catch (err) {\n try {\n deps.logger?.error(`${name} hook threw; delivery state is unaffected`, { error: errorText(err) });\n } catch {\n // A broken logger must not break delivery either.\n }\n }\n}\n\n/**\n * Claim due work in chunks of `concurrency`, send each chunk in parallel, and\n * stop at `batchSize` deliveries or when `budgetMs` has passed (checked before\n * each claim, so every claimed row is sent; in-flight sends are bounded by\n * `sendTimeoutMs`). Never throws for channel failures.\n */\nexport async function processPending(\n deps: EngineDeps,\n opts: ProcessOptions & { notificationId?: string } = {},\n): Promise<ProcessSummary> {\n const batchSize = opts.batchSize ?? PROCESS_DEFAULTS.batchSize;\n const concurrency = opts.concurrency ?? PROCESS_DEFAULTS.concurrency;\n // Due-ness is judged against the call's start time, so a row this call just\n // retried is never re-claimed by the same call (no tight loop on Retry-After: 0).\n const startedAt = deps.now();\n const deadline = startedAt.getTime() + (opts.budgetMs ?? PROCESS_DEFAULTS.budgetMs);\n const summary: ProcessSummary = { claimed: 0, sent: 0, retried: 0, dead: 0 };\n\n while (summary.claimed < batchSize && deps.now().getTime() < deadline) {\n const elapsed = deps.now().getTime() - startedAt.getTime();\n const rows = await deps.store.claim({\n limit: Math.min(concurrency, batchSize - summary.claimed),\n now: startedAt,\n leaseMs: deps.leaseMs + elapsed, // lease still ends leaseMs from *now*\n ...(opts.notificationId !== undefined && { notificationId: opts.notificationId }),\n });\n if (rows.length === 0) break;\n summary.claimed += rows.length;\n deps.logger?.debug(\"claimed deliveries\", { count: rows.length });\n\n const outcomes = await Promise.all(\n rows.map((r) => deliver(deps, r).catch((): Outcome => \"unrecorded\")),\n );\n for (const outcome of outcomes) {\n if (outcome !== \"unrecorded\") summary[outcome] += 1;\n }\n }\n return summary;\n}\n","import type { Channel } from \"./channel.js\";\r\nimport { HeraldError } from \"./errors.js\";\r\nimport { notify as runNotify } from \"./notify.js\";\r\nimport { processPending as runProcess, type EngineDeps } from \"./process.js\";\r\nimport type { AllowedChannel, AnyEventDef, ChannelMap, Conform, PayloadOf } from \"./events.js\";\r\nimport type { InboxPage, InboxQuery, Store } from \"./store.js\";\r\nimport type {\r\n Hooks,\r\n Logger,\r\n ProcessOptions,\r\n ProcessSummary,\r\n ResolveAddress,\r\n ResolvePreferences,\r\n RetryPolicy,\r\n Targets,\r\n} from \"./types.js\";\r\n\r\nexport interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {\r\n store: Store;\r\n channels: Ch;\r\n /** Each event must conform to the channel map: registered channels, matching message types. */\r\n events: Ev & { [E in keyof Ev]: Conform<Ev[E], Ch> };\r\n resolvePreferences?: ResolvePreferences;\r\n resolveAddress?: ResolveAddress;\r\n hooks?: Hooks;\r\n logger?: Logger;\r\n retry?: Partial<RetryPolicy>;\r\n /** Per-send timeout; aborts `ctx.signal`. Default 15_000. */\r\n sendTimeoutMs?: number;\r\n /** How long a claimed delivery stays leased. Must exceed `sendTimeoutMs`. Default 60_000. */\r\n leaseMs?: number;\r\n /** Clock override for tests. */\r\n now?: () => Date;\r\n}\r\n\r\nexport interface Herald<Ev extends Record<string, AnyEventDef>> {\r\n /** Queue a notification. Resolves with its id; channel failures never reach the caller. */\r\n notify<E extends keyof Ev & string>(\r\n event: E,\r\n payload: PayloadOf<Ev[E]>,\r\n targets: Targets<AllowedChannel<Ev[E]>>,\r\n ): Promise<string>;\r\n /** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */\r\n processPending(opts?: ProcessOptions): Promise<ProcessSummary>;\r\n inbox: {\r\n list(q: InboxQuery): Promise<InboxPage>;\r\n markRead(recipientId: string, ids: readonly string[]): Promise<void>;\r\n };\r\n}\r\n\r\nexport const defaultRetry: RetryPolicy = {\r\n maxAttempts: 5,\r\n baseMs: 30_000,\r\n maxMs: 3_600_000,\r\n jitter: true,\r\n};\r\n\r\nconst DEFAULT_SEND_TIMEOUT_MS = 15_000;\r\nconst DEFAULT_LEASE_MS = 60_000;\r\n\r\nconst fn = (v: unknown): boolean => typeof v === \"function\";\r\n\r\nconst STORE_METHODS = [\r\n \"enqueue\",\r\n \"claim\",\r\n \"recordResult\",\r\n \"listDeliveries\",\r\n \"retryDelivery\",\r\n \"cancel\",\r\n \"purge\",\r\n \"getNotification\",\r\n \"inboxAdd\",\r\n \"inboxList\",\r\n \"inboxMarkRead\",\r\n \"inboxUnreadCount\",\r\n \"inboxMarkAllRead\",\r\n] as const;\r\n\r\nfunction validate(config: HeraldConfig<ChannelMap, Record<string, AnyEventDef>>): void {\r\n const bad = (msg: string): never => {\r\n throw new HeraldError(\"invalid_config\", msg);\r\n };\r\n\r\n const { store, channels, events } = config;\r\n for (const m of STORE_METHODS) {\r\n if (!fn((store as unknown as Record<string, unknown> | undefined)?.[m]))\r\n bad(`store.${m} is not a function`);\r\n }\r\n\r\n for (const [name, ch] of Object.entries(channels ?? {})) {\r\n const c = ch as Channel | undefined;\r\n if (!c || !fn(c.send) || !fn(c.classifyError))\r\n bad(`channel \"${name}\" must implement send() and classifyError()`);\r\n }\r\n\r\n const sendTimeoutMs = config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\r\n const leaseMs = config.leaseMs ?? DEFAULT_LEASE_MS;\r\n if (!(sendTimeoutMs > 0)) bad(\"sendTimeoutMs must be a positive number\");\r\n if (!(leaseMs > sendTimeoutMs))\r\n bad(`leaseMs (${leaseMs}) must exceed sendTimeoutMs (${sendTimeoutMs}), or a lease can expire mid-send`);\r\n\r\n const r = { ...defaultRetry, ...config.retry };\r\n if (!(Number.isInteger(r.maxAttempts) && r.maxAttempts >= 1)) bad(\"retry.maxAttempts must be an integer >= 1\");\r\n if (!(Number.isFinite(r.baseMs) && r.baseMs >= 0)) bad(\"retry.baseMs must be a finite number >= 0\");\r\n if (!(Number.isFinite(r.maxMs) && r.maxMs >= r.baseMs)) bad(\"retry.maxMs must be finite and >= retry.baseMs\");\r\n\r\n const names = Object.keys(events ?? {});\r\n if (names.length === 0) bad(\"at least one event is required\");\r\n\r\n for (const [event, def] of Object.entries(events)) {\r\n if (!def.channels?.length) bad(`event \"${event}\" must allow at least one channel`);\r\n for (const ch of def.channels) {\r\n if (!(ch in channels)) bad(`event \"${event}\" allows unregistered channel \"${ch}\"`);\r\n if (!fn((def.templates as Record<string, unknown> | undefined)?.[ch]))\r\n throw new HeraldError(\"missing_template\", `event \"${event}\" has no template for channel \"${ch}\"`);\r\n }\r\n for (const ch of Object.keys(def.templates ?? {})) {\r\n if (!def.channels.includes(ch))\r\n bad(`event \"${event}\" has a template for \"${ch}\" which is not in its allowed channels`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Validates config at startup (missing templates, unregistered channels are\r\n * errors here, not at send time). `notify` queues durably (and sends inline on\r\n * request); `processPending` delivers. `inbox` throws `not_implemented` until\r\n * a later release.\r\n */\r\nexport function createHerald<\r\n const Ch extends ChannelMap,\r\n Ev extends Record<string, AnyEventDef>,\r\n>(config: HeraldConfig<Ch, Ev>): Herald<Ev> {\r\n validate(config as unknown as HeraldConfig<ChannelMap, Record<string, AnyEventDef>>);\r\n\r\n const engine: EngineDeps = {\r\n store: config.store,\r\n channels: config.channels,\r\n events: config.events as Record<string, AnyEventDef>,\r\n ...(config.hooks && { hooks: config.hooks }),\r\n ...(config.logger && { logger: config.logger }),\r\n retry: { ...defaultRetry, ...config.retry },\r\n now: config.now ?? (() => new Date()),\r\n leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,\r\n sendTimeoutMs: config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS,\r\n };\r\n\r\n const notImplemented = (what: string): never => {\r\n throw new HeraldError(\"not_implemented\", `${what} is not implemented yet`);\r\n };\r\n\r\n return {\r\n notify(event, payload, targets) {\r\n return runNotify(\r\n {\r\n store: config.store,\r\n events: config.events as Record<string, AnyEventDef>,\r\n resolvePreferences: config.resolvePreferences,\r\n resolveAddress: config.resolveAddress,\r\n logger: config.logger,\r\n // Inline gets one send-timeout of budget: notify() should not block like a worker run.\r\n sendInline: (notificationId) =>\r\n runProcess(engine, {\r\n notificationId,\r\n batchSize: Number.POSITIVE_INFINITY,\r\n budgetMs: engine.sendTimeoutMs,\r\n }),\r\n },\r\n event,\r\n payload,\r\n targets as Targets,\r\n );\r\n },\r\n processPending(opts) {\r\n return runProcess(engine, opts);\r\n },\r\n inbox: {\r\n async list() {\r\n return notImplemented(\"inbox.list()\");\r\n },\r\n async markRead() {\r\n return notImplemented(\"inbox.markRead()\");\r\n },\r\n },\r\n };\r\n}\r\n","import type { Channel } from \"./channel.js\";\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any -- `any` is how Channel<M, A> is matched regardless of its params */\r\nexport type ChannelMap = Record<string, Channel<any, any>>;\r\n\r\n/** The message type a channel expects from its templates. */\r\nexport type MessageOf<C> = C extends Channel<infer M, any> ? M : never;\r\n\r\n/**\r\n * An event: its allowed channels and one template per channel. `P` is the\r\n * payload type (type-only, via `__payload`); templates are plain functions.\r\n */\r\nexport interface EventDef<\r\n P = unknown,\r\n K extends string = string,\r\n T extends { readonly [C in K]: (payload: P) => unknown } = {\r\n readonly [C in K]: (payload: P) => unknown;\r\n },\r\n> {\r\n readonly channels: readonly K[];\r\n readonly templates: T;\r\n readonly __payload?: P;\r\n}\r\n\r\nexport type AnyEventDef = EventDef<any, string, any>;\r\nexport type PayloadOf<D> = D extends EventDef<infer P, any, any> ? P : never;\r\nexport type AllowedChannel<D> = D extends EventDef<any, infer K, any> ? K : never;\r\n\r\n/**\r\n * Curried so the payload type is explicit while channel names are inferred:\r\n * `defineEvent<{ name: string }>()({ channels: [\"slack\"], templates: { slack: (p) => ... } })`.\r\n */\r\nexport function defineEvent<P>() {\r\n return <const K extends string, T extends { [C in K]: (payload: P) => unknown }>(def: {\r\n channels: readonly K[];\r\n templates: T;\r\n }): EventDef<P, K, T> => def;\r\n}\r\n\r\n/**\r\n * What an event must look like against a concrete channel map: every allowed\r\n * channel is registered, and each template returns that channel's message type.\r\n */\r\nexport type Conform<D, Ch extends ChannelMap> =\r\n D extends EventDef<infer P, infer K, any>\r\n ? {\r\n readonly channels: readonly (K & keyof Ch)[];\r\n readonly templates: {\r\n readonly [C in K]: C extends keyof Ch ? (payload: P) => MessageOf<Ch[C]> : never;\r\n };\r\n }\r\n : never;\r\n"],"mappings":";;;;;AAsBA,IAAM,QAAQ,CAAC,MAAgD,aAAa;AAO5E,eAAsB,OACpB,MACA,OACA,SACA,SACiB;AACjB,QAAM,MAAM,KAAK,OAAO,KAAK;AAC7B,MAAI,CAAC,IAAK,OAAM,IAAI,YAAY,iBAAiB,kBAAkB,KAAK,GAAG;AAC3E,MAAI,CAAC,QAAQ,IAAI;AACf,UAAM,IAAI,YAAY,mBAAmB,WAAW,KAAK,sCAAsC;AAEjG,QAAM,WAAW,CAAC,GAAG,IAAI,IAAI,QAAQ,YAAY,IAAI,QAAQ,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AAAA,IACA,OAAO;AAAA,MACL,MAAM,OAAO;AACX,eAAO,eAAe,cAAc;AAAA,MACtC;AAAA,MACA,MAAM,WAAW;AACf,eAAO,eAAe,kBAAkB;AAAA,MAC1C;AAAA,IACF;AAAA,EACF;AACF;;;ACzJO,SAAS,cAAiB;AAC/B,SAAO,CAA0E,QAGxD;AAC3B;","names":["attempt"]}
|
|
1
|
+
{"version":3,"sources":["../src/notify.ts","../src/process.ts","../src/herald.ts","../src/events.ts","../src/inapp.ts"],"sourcesContent":["import { HeraldError } from \"./errors.js\";\nimport type { AnyEventDef } from \"./events.js\";\nimport type { NewDelivery, Store } from \"./store.js\";\nimport type {\n Logger,\n RawTarget,\n RecipientRef,\n ResolveAddress,\n ResolvePreferences,\n Targets,\n} from \"./types.js\";\n\nexport interface NotifyDeps {\n store: Store;\n events: Record<string, AnyEventDef>;\n resolvePreferences?: ResolvePreferences;\n resolveAddress?: ResolveAddress;\n logger?: Logger;\n /** Sends one notification's deliveries now (`targets.inline`). */\n sendInline?: (notificationId: string) => Promise<unknown>;\n}\n\nconst isRaw = (t: RecipientRef | RawTarget): t is RawTarget => \"channel\" in t;\n\n/**\n * Validate, narrow by preferences, resolve addresses, and durably queue.\n * Returns the notification id. Resolver failures propagate and nothing is\n * queued (fail closed: never notify someone who may have opted out).\n */\nexport async function notify(\n deps: NotifyDeps,\n event: string,\n payload: unknown,\n targets: Targets,\n): Promise<string> {\n const def = deps.events[event];\n if (!def) throw new HeraldError(\"unknown_event\", `unknown event \"${event}\"`);\n if (!targets.to?.length)\n throw new HeraldError(\"invalid_targets\", `notify(\"${event}\") needs at least one target in \"to\"`);\n\n const channels = [...new Set(targets.channels ?? def.channels)];\n for (const ch of channels) {\n if (!def.channels.includes(ch))\n throw new HeraldError(\"channel_not_allowed\", `event \"${event}\" does not allow channel \"${ch}\"`);\n }\n\n const raws = targets.to.filter(isRaw);\n for (const r of raws) {\n if (!channels.includes(r.channel))\n throw new HeraldError(\n \"channel_not_allowed\",\n `raw target channel \"${r.channel}\" is not in the channels requested for \"${event}\"`,\n );\n }\n\n const seen = new Set<string>();\n const recipients: RecipientRef[] = [];\n for (const t of targets.to) {\n if (isRaw(t) || seen.has(t.id)) continue;\n seen.add(t.id);\n recipients.push(t);\n }\n\n const priority = targets.priority ?? \"normal\";\n\n // Preferences: one batched call; only narrows; critical bypasses.\n let prefs: ReadonlyMap<string, readonly string[]> | undefined;\n if (deps.resolvePreferences && priority !== \"critical\" && recipients.length > 0) {\n prefs = await deps.resolvePreferences(recipients, event);\n }\n\n const pairs = recipients.flatMap((r) => {\n const allowed = prefs?.get(r.id);\n return channels\n .filter((ch) => !allowed || allowed.includes(ch))\n .map((ch) => ({ r, ch }));\n });\n\n const resolved = await Promise.all(\n pairs.map(async ({ r, ch }): Promise<NewDelivery> => {\n // No resolver configured: the recipient id is the address.\n const address = deps.resolveAddress ? await deps.resolveAddress(r, ch) : r.id;\n return address === null || address === undefined\n ? { channel: ch, address: null, recipientId: r.id, status: \"skipped\" }\n : { channel: ch, address, recipientId: r.id, status: \"pending\" };\n }),\n );\n\n const rawDeliveries: NewDelivery[] = raws.map((r) => ({\n channel: r.channel,\n address: r.address,\n status: \"pending\",\n }));\n\n const { id, created } = await deps.store.enqueue({\n event,\n payload,\n priority,\n idempotencyKey: targets.idempotencyKey ?? globalThis.crypto.randomUUID(),\n subject: targets.subject ?? null,\n deliveries: [...resolved, ...rawDeliveries],\n });\n\n deps.logger?.debug(\"notification queued\", { id, event, created });\n\n // A duplicate key was already queued (and maybe sent): never send it twice.\n if (targets.inline && created && deps.sendInline) {\n try {\n await deps.sendInline(id);\n } catch (err) {\n // Queued durably already; processPending() picks it up. Never surface to the caller.\n deps.logger?.error(\"inline send failed; left for processPending()\", {\n id,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n return id;\n}\n","import type { Channel } from \"./channel.js\";\nimport type { AnyEventDef, ChannelMap } from \"./events.js\";\nimport type { ClaimedDelivery, DeliveryResult, Store } from \"./store.js\";\nimport type {\n DeliveryInfo,\n Hooks,\n Logger,\n ProcessOptions,\n ProcessSummary,\n RetryPolicy,\n} from \"./types.js\";\n\nexport interface EngineDeps {\n store: Store;\n channels: ChannelMap;\n events: Record<string, AnyEventDef>;\n hooks?: Hooks;\n logger?: Logger;\n retry: RetryPolicy;\n now: () => Date;\n leaseMs: number;\n sendTimeoutMs: number;\n /** Injectable for deterministic jitter in tests. */\n random?: () => number;\n}\n\nexport const PROCESS_DEFAULTS = { batchSize: 50, budgetMs: 20_000, concurrency: 10 } as const;\n\nconst MAX_ERROR = 1_000;\n/** Rate-limited with no Retry-After. */\nconst RATE_LIMIT_FALLBACK_MS = 60_000;\n/** Longest wait a channel's `retryAfterMs` can ask for; a huge value would make an invalid Date. */\nconst MAX_RETRY_AFTER_MS = 86_400_000;\n\nconst errorText = (err: unknown): string =>\n (err instanceof Error ? err.message : String(err)).slice(0, MAX_ERROR);\n\n/**\n * Delay before retry number `attempt + 1`. Exponential, capped, with equal\n * jitter (half fixed, half random) so it never collapses to zero.\n */\nexport function backoffMs(attempt: number, policy: RetryPolicy, random = Math.random): number {\n const delay = Math.min(policy.maxMs, policy.baseMs * 2 ** (attempt - 1));\n return policy.jitter ? delay / 2 + random() * (delay / 2) : delay;\n}\n\ntype Outcome = \"sent\" | \"retried\" | \"dead\" | \"unrecorded\";\n\n/** Render and send one claimed row. Returns the result to record plus the raw error, if any. */\nasync function attempt(\n deps: EngineDeps,\n row: ClaimedDelivery,\n): Promise<{ result: DeliveryResult; error?: unknown }> {\n const n = row.notification;\n const def = deps.events[n.event];\n if (!def) return { result: { status: \"dead\", error: `unknown event \"${n.event}\"` } };\n\n const channel = deps.channels[row.channel] as Channel | undefined;\n const template = (def.templates as Record<string, ((p: unknown) => unknown) | undefined>)[row.channel];\n if (!channel || !template)\n return { result: { status: \"dead\", error: `unknown channel \"${row.channel}\" for event \"${n.event}\"` } };\n\n let message: unknown;\n try {\n message = template(n.payload);\n } catch (error) {\n // Same payload + same code fails every time: retrying only burns budget.\n return { result: { status: \"dead\", error: `template failed: ${errorText(error)}` }, error };\n }\n\n const signal = AbortSignal.timeout(deps.sendTimeoutMs);\n // Enforce the timeout even if the adapter ignores `signal`: a hung send must not outlive its lease.\n const timedOut = new Promise<never>((_, reject) =>\n signal.addEventListener(\"abort\", () => reject(signal.reason), { once: true }),\n );\n try {\n const res = await Promise.race([\n channel.send(message, row.address, {\n idempotencyKey: `${n.idempotencyKey}:${row.id}`,\n attempt: row.attempts,\n notificationId: n.id,\n deliveryId: row.id,\n signal,\n }),\n timedOut,\n ]);\n return { result: { status: \"sent\", ...(res?.providerId !== undefined && { providerId: res.providerId }) } };\n } catch (error) {\n return { result: failure(deps, row, channel, error, signal.aborted), error };\n }\n}\n\nasync function deliver(deps: EngineDeps, row: ClaimedDelivery): Promise<Outcome> {\n const { result, error } = await attempt(deps, row);\n\n try {\n await deps.store.recordResult(row.id, result);\n } catch (err) {\n // Row stays leased; lease expiry hands it to a later run.\n deps.logger?.error(\"recordResult failed; delivery will be retried after its lease\", {\n deliveryId: row.id,\n error: errorText(err),\n });\n return \"unrecorded\";\n }\n\n const info: DeliveryInfo = {\n notificationId: row.notification.id,\n deliveryId: row.id,\n event: row.notification.event,\n channel: row.channel,\n ...(row.recipientId !== undefined && { recipientId: row.recipientId }),\n attempt: row.attempts,\n };\n const meta = { deliveryId: row.id, channel: row.channel, attempt: row.attempts };\n\n if (result.status === \"sent\") {\n await runHook(deps, \"onSent\", () => deps.hooks?.onSent?.(info));\n return \"sent\";\n }\n const failed = { ...info, error: error ?? result.error };\n if (result.status === \"retry\") {\n const nextAttemptAt = result.nextAttemptAt;\n deps.logger?.warn(\"delivery failed, will retry\", { ...meta, error: result.error, nextAttemptAt: nextAttemptAt.toISOString() });\n await runHook(deps, \"onFailed\", () => deps.hooks?.onFailed?.({ ...failed, nextAttemptAt }));\n return \"retried\";\n }\n deps.logger?.error(\"delivery dead\", { ...meta, error: result.error });\n await runHook(deps, \"onDead\", () => deps.hooks?.onDead?.(failed));\n return \"dead\";\n}\n\nfunction failure(\n deps: EngineDeps,\n row: ClaimedDelivery,\n channel: Channel,\n err: unknown,\n timedOut: boolean,\n): DeliveryResult {\n let retryable = true;\n let retryAfterMs: number | undefined;\n let rateLimited = false;\n let text = errorText(err);\n\n if (timedOut) {\n // The provider may or may not have accepted it; at-least-once says retry.\n text = `send timed out after ${deps.sendTimeoutMs}ms: ${text}`.slice(0, MAX_ERROR);\n } else {\n try {\n const cls = channel.classifyError(err);\n retryable = cls.retryable;\n // Ignore nonsense (NaN, negative, Infinity) and fall back to backoff.\n if (Number.isFinite(cls.retryAfterMs) && (cls.retryAfterMs as number) >= 0)\n retryAfterMs = cls.retryAfterMs;\n rateLimited = cls.retryable && cls.rateLimited === true;\n } catch (clsErr) {\n deps.logger?.warn(\"classifyError threw; treating the error as retryable\", {\n channel: row.channel,\n error: errorText(clsErr),\n });\n }\n }\n\n if (!retryable) return { status: \"dead\", error: text };\n\n // ponytail: a rate-limited retry gives its attempt back, so a channel that rate-limits\n // forever retries forever (paced by Retry-After). Upgrade: a separate rate-limit counter.\n if (!rateLimited && row.attempts >= deps.retry.maxAttempts) return { status: \"dead\", error: text };\n\n // A refunded attempt never grows the backoff, so a rate limit without Retry-After waits a\n // fixed minute instead of hammering at baseMs.\n const wait =\n retryAfterMs !== undefined\n ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS)\n : rateLimited\n ? RATE_LIMIT_FALLBACK_MS\n : backoffMs(row.attempts, deps.retry, deps.random);\n // At least 1ms, so the row is due strictly after the claim snapshot of the current run.\n const delay = Math.max(1, wait);\n const nextAttemptAt = new Date(deps.now().getTime() + delay);\n return rateLimited\n ? { status: \"retry\", nextAttemptAt, error: text, refundAttempt: true }\n : { status: \"retry\", nextAttemptAt, error: text };\n}\n\nasync function runHook(deps: EngineDeps, name: keyof Hooks, call: () => unknown): Promise<void> {\n try {\n await call();\n } catch (err) {\n try {\n deps.logger?.error(`${name} hook threw; delivery state is unaffected`, { error: errorText(err) });\n } catch {\n // A broken logger must not break delivery either.\n }\n }\n}\n\n/**\n * Claim due work in chunks of `concurrency`, send each chunk in parallel, and\n * stop at `batchSize` deliveries or when `budgetMs` has passed (checked before\n * each claim, so every claimed row is sent; in-flight sends are bounded by\n * `sendTimeoutMs`). Never throws for channel failures.\n */\nexport async function processPending(\n deps: EngineDeps,\n opts: ProcessOptions & { notificationId?: string } = {},\n): Promise<ProcessSummary> {\n const batchSize = opts.batchSize ?? PROCESS_DEFAULTS.batchSize;\n const concurrency = opts.concurrency ?? PROCESS_DEFAULTS.concurrency;\n // Due-ness is judged against the call's start time, so a row this call just\n // retried is never re-claimed by the same call (no tight loop on Retry-After: 0).\n const startedAt = deps.now();\n const deadline = startedAt.getTime() + (opts.budgetMs ?? PROCESS_DEFAULTS.budgetMs);\n const summary: ProcessSummary = { claimed: 0, sent: 0, retried: 0, dead: 0 };\n\n while (summary.claimed < batchSize && deps.now().getTime() < deadline) {\n const elapsed = deps.now().getTime() - startedAt.getTime();\n const rows = await deps.store.claim({\n limit: Math.min(concurrency, batchSize - summary.claimed),\n now: startedAt,\n leaseMs: deps.leaseMs + elapsed, // lease still ends leaseMs from *now*\n ...(opts.notificationId !== undefined && { notificationId: opts.notificationId }),\n });\n if (rows.length === 0) break;\n summary.claimed += rows.length;\n deps.logger?.debug(\"claimed deliveries\", { count: rows.length });\n\n const outcomes = await Promise.all(\n rows.map((r) => deliver(deps, r).catch((): Outcome => \"unrecorded\")),\n );\n for (const outcome of outcomes) {\n if (outcome !== \"unrecorded\") summary[outcome] += 1;\n }\n }\n return summary;\n}\n","import type { Channel } from \"./channel.js\";\r\nimport { HeraldError } from \"./errors.js\";\r\nimport { notify as runNotify } from \"./notify.js\";\r\nimport { processPending as runProcess, type EngineDeps } from \"./process.js\";\r\nimport type { AllowedChannel, AnyEventDef, ChannelMap, Conform, PayloadOf } from \"./events.js\";\r\nimport type { InboxPage, InboxQuery, Store } from \"./store.js\";\r\nimport type {\r\n Hooks,\r\n Logger,\r\n ProcessOptions,\r\n ProcessSummary,\r\n ResolveAddress,\r\n ResolvePreferences,\r\n RetryPolicy,\r\n Targets,\r\n} from \"./types.js\";\r\n\r\nexport interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {\r\n store: Store;\r\n channels: Ch;\r\n /** Each event must conform to the channel map: registered channels, matching message types. */\r\n events: Ev & { [E in keyof Ev]: Conform<Ev[E], Ch> };\r\n resolvePreferences?: ResolvePreferences;\r\n resolveAddress?: ResolveAddress;\r\n hooks?: Hooks;\r\n logger?: Logger;\r\n retry?: Partial<RetryPolicy>;\r\n /** Per-send timeout; aborts `ctx.signal`. Default 15_000. */\r\n sendTimeoutMs?: number;\r\n /** How long a claimed delivery stays leased. Must exceed `sendTimeoutMs`. Default 60_000. */\r\n leaseMs?: number;\r\n /** Clock override for tests. */\r\n now?: () => Date;\r\n}\r\n\r\nexport interface Herald<Ev extends Record<string, AnyEventDef>> {\r\n /** Queue a notification. Resolves with its id; channel failures never reach the caller. */\r\n notify<E extends keyof Ev & string>(\r\n event: E,\r\n payload: PayloadOf<Ev[E]>,\r\n targets: Targets<AllowedChannel<Ev[E]>>,\r\n ): Promise<string>;\r\n /** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */\r\n processPending(opts?: ProcessOptions): Promise<ProcessSummary>;\r\n /**\r\n * The in-app inbox. `recipientId` must come from your authenticated session,\r\n * never from the client request.\r\n */\r\n inbox: {\r\n /** Newest first, keyset-paginated. */\r\n list(q: InboxQuery): Promise<InboxPage>;\r\n /** Ids belonging to another recipient are ignored. */\r\n markRead(recipientId: string, ids: readonly string[]): Promise<void>;\r\n /** For the bell badge. */\r\n unreadCount(recipientId: string): Promise<number>;\r\n /** Returns how many items were marked. */\r\n markAllRead(recipientId: string): Promise<number>;\r\n };\r\n}\r\n\r\n/** A missing session id (`user?.id`) must fail loudly, not read as an empty inbox. */\r\nfunction who(recipientId: unknown): string {\r\n if (typeof recipientId !== \"string\" || recipientId === \"\")\r\n throw new HeraldError(\"invalid_targets\", \"inbox: recipientId must be a non-empty string\");\r\n return recipientId;\r\n}\r\n\r\nexport const defaultRetry: RetryPolicy = {\r\n maxAttempts: 5,\r\n baseMs: 30_000,\r\n maxMs: 3_600_000,\r\n jitter: true,\r\n};\r\n\r\nconst DEFAULT_SEND_TIMEOUT_MS = 15_000;\r\nconst DEFAULT_LEASE_MS = 60_000;\r\n\r\nconst fn = (v: unknown): boolean => typeof v === \"function\";\r\n\r\nconst STORE_METHODS = [\r\n \"enqueue\",\r\n \"claim\",\r\n \"recordResult\",\r\n \"listDeliveries\",\r\n \"retryDelivery\",\r\n \"cancel\",\r\n \"purge\",\r\n \"getNotification\",\r\n \"inboxAdd\",\r\n \"inboxList\",\r\n \"inboxMarkRead\",\r\n \"inboxUnreadCount\",\r\n \"inboxMarkAllRead\",\r\n] as const;\r\n\r\nfunction validate(config: HeraldConfig<ChannelMap, Record<string, AnyEventDef>>): void {\r\n const bad = (msg: string): never => {\r\n throw new HeraldError(\"invalid_config\", msg);\r\n };\r\n\r\n const { store, channels, events } = config;\r\n for (const m of STORE_METHODS) {\r\n if (!fn((store as unknown as Record<string, unknown> | undefined)?.[m]))\r\n bad(`store.${m} is not a function`);\r\n }\r\n\r\n for (const [name, ch] of Object.entries(channels ?? {})) {\r\n const c = ch as Channel | undefined;\r\n if (!c || !fn(c.send) || !fn(c.classifyError))\r\n bad(`channel \"${name}\" must implement send() and classifyError()`);\r\n }\r\n\r\n const sendTimeoutMs = config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\r\n const leaseMs = config.leaseMs ?? DEFAULT_LEASE_MS;\r\n if (!(sendTimeoutMs > 0)) bad(\"sendTimeoutMs must be a positive number\");\r\n if (!(leaseMs > sendTimeoutMs))\r\n bad(`leaseMs (${leaseMs}) must exceed sendTimeoutMs (${sendTimeoutMs}), or a lease can expire mid-send`);\r\n\r\n const r = { ...defaultRetry, ...config.retry };\r\n if (!(Number.isInteger(r.maxAttempts) && r.maxAttempts >= 1)) bad(\"retry.maxAttempts must be an integer >= 1\");\r\n if (!(Number.isFinite(r.baseMs) && r.baseMs >= 0)) bad(\"retry.baseMs must be a finite number >= 0\");\r\n if (!(Number.isFinite(r.maxMs) && r.maxMs >= r.baseMs)) bad(\"retry.maxMs must be finite and >= retry.baseMs\");\r\n\r\n const names = Object.keys(events ?? {});\r\n if (names.length === 0) bad(\"at least one event is required\");\r\n\r\n for (const [event, def] of Object.entries(events)) {\r\n if (!def.channels?.length) bad(`event \"${event}\" must allow at least one channel`);\r\n for (const ch of def.channels) {\r\n if (!(ch in channels)) bad(`event \"${event}\" allows unregistered channel \"${ch}\"`);\r\n if (!fn((def.templates as Record<string, unknown> | undefined)?.[ch]))\r\n throw new HeraldError(\"missing_template\", `event \"${event}\" has no template for channel \"${ch}\"`);\r\n }\r\n for (const ch of Object.keys(def.templates ?? {})) {\r\n if (!def.channels.includes(ch))\r\n bad(`event \"${event}\" has a template for \"${ch}\" which is not in its allowed channels`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Validates config at startup (missing templates, unregistered channels are\r\n * errors here, not at send time). `notify` queues durably (and sends inline on\r\n * request); `processPending` delivers; `inbox` reads the in-app inbox.\r\n */\r\nexport function createHerald<\r\n const Ch extends ChannelMap,\r\n Ev extends Record<string, AnyEventDef>,\r\n>(config: HeraldConfig<Ch, Ev>): Herald<Ev> {\r\n validate(config as unknown as HeraldConfig<ChannelMap, Record<string, AnyEventDef>>);\r\n\r\n const engine: EngineDeps = {\r\n store: config.store,\r\n channels: config.channels,\r\n events: config.events as Record<string, AnyEventDef>,\r\n ...(config.hooks && { hooks: config.hooks }),\r\n ...(config.logger && { logger: config.logger }),\r\n retry: { ...defaultRetry, ...config.retry },\r\n now: config.now ?? (() => new Date()),\r\n leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,\r\n sendTimeoutMs: config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS,\r\n };\r\n\r\n return {\r\n notify(event, payload, targets) {\r\n return runNotify(\r\n {\r\n store: config.store,\r\n events: config.events as Record<string, AnyEventDef>,\r\n resolvePreferences: config.resolvePreferences,\r\n resolveAddress: config.resolveAddress,\r\n logger: config.logger,\r\n // Inline gets one send-timeout of budget: notify() should not block like a worker run.\r\n sendInline: (notificationId) =>\r\n runProcess(engine, {\r\n notificationId,\r\n batchSize: Number.POSITIVE_INFINITY,\r\n budgetMs: engine.sendTimeoutMs,\r\n }),\r\n },\r\n event,\r\n payload,\r\n targets as Targets,\r\n );\r\n },\r\n processPending(opts) {\r\n return runProcess(engine, opts);\r\n },\r\n inbox: {\r\n list: async (q) => config.store.inboxList({ ...q, recipientId: who(q?.recipientId) }),\r\n markRead: async (recipientId, ids) => config.store.inboxMarkRead(who(recipientId), ids),\r\n unreadCount: async (recipientId) => config.store.inboxUnreadCount(who(recipientId)),\r\n markAllRead: async (recipientId) => config.store.inboxMarkAllRead(who(recipientId)),\r\n },\r\n };\r\n}\r\n","import type { Channel } from \"./channel.js\";\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any -- `any` is how Channel<M, A> is matched regardless of its params */\r\nexport type ChannelMap = Record<string, Channel<any, any>>;\r\n\r\n/** The message type a channel expects from its templates. */\r\nexport type MessageOf<C> = C extends Channel<infer M, any> ? M : never;\r\n\r\n/**\r\n * An event: its allowed channels and one template per channel. `P` is the\r\n * payload type (type-only, via `__payload`); templates are plain functions.\r\n */\r\nexport interface EventDef<\r\n P = unknown,\r\n K extends string = string,\r\n T extends { readonly [C in K]: (payload: P) => unknown } = {\r\n readonly [C in K]: (payload: P) => unknown;\r\n },\r\n> {\r\n readonly channels: readonly K[];\r\n readonly templates: T;\r\n readonly __payload?: P;\r\n}\r\n\r\nexport type AnyEventDef = EventDef<any, string, any>;\r\nexport type PayloadOf<D> = D extends EventDef<infer P, any, any> ? P : never;\r\nexport type AllowedChannel<D> = D extends EventDef<any, infer K, any> ? K : never;\r\n\r\n/**\r\n * Curried so the payload type is explicit while channel names are inferred:\r\n * `defineEvent<{ name: string }>()({ channels: [\"slack\"], templates: { slack: (p) => ... } })`.\r\n */\r\nexport function defineEvent<P>() {\r\n return <const K extends string, T extends { [C in K]: (payload: P) => unknown }>(def: {\r\n channels: readonly K[];\r\n templates: T;\r\n }): EventDef<P, K, T> => def;\r\n}\r\n\r\n/**\r\n * What an event must look like against a concrete channel map: every allowed\r\n * channel is registered, and each template returns that channel's message type.\r\n */\r\nexport type Conform<D, Ch extends ChannelMap> =\r\n D extends EventDef<infer P, infer K, any>\r\n ? {\r\n readonly channels: readonly (K & keyof Ch)[];\r\n readonly templates: {\r\n readonly [C in K]: C extends keyof Ch ? (payload: P) => MessageOf<Ch[C]> : never;\r\n };\r\n }\r\n : never;\r\n","import type { Channel } from \"./channel.js\";\nimport { HeraldError } from \"./errors.js\";\nimport type { Store } from \"./store.js\";\n\n/** What an `inapp` template returns. */\nexport interface InAppMessage {\n title: string;\n body: string;\n /** Anything your UI needs, e.g. `{ leadId }` for a link. Stored as JSON. */\n data?: unknown;\n}\n\n/**\n * Delivers to the in-app inbox in your own store. The address is the\n * recipient id (the default when no `resolveAddress` is configured).\n * Exactly-once: the delivery's idempotency key is the inbox item key, so a\n * retried delivery never shows twice.\n */\nexport function inAppChannel(store: Store): Channel<InAppMessage, string> {\n return {\n name: \"inapp\",\n async send(message, to, ctx) {\n if (typeof to !== \"string\" || to === \"\")\n throw new HeraldError(\n \"invalid_targets\",\n `inapp address must be the recipient id (a non-empty string), got ${typeof to}`,\n );\n const item = await store.inboxAdd({\n recipientId: to,\n notificationId: ctx.notificationId,\n title: message.title,\n body: message.body,\n ...(message.data !== undefined && { data: message.data }),\n key: ctx.idempotencyKey,\n });\n return { providerId: item.id };\n },\n // A bad address never fixes itself; anything else is a store error: retry.\n classifyError: (err) => ({\n retryable: !(err instanceof HeraldError && err.code === \"invalid_targets\"),\n }),\n };\n}\n"],"mappings":";;;;;AAsBA,IAAM,QAAQ,CAAC,MAAgD,aAAa;AAO5E,eAAsB,OAC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C,cAAM,IAAI;AAAA,UACR;AAAA,UACA,oEAAoE,OAAO,EAAE;AAAA,QAC/E;AACF,YAAM,OAAO,MAAM,MAAM,SAAS;AAAA,QAChC,aAAa;AAAA,QACb,gBAAgB,IAAI;AAAA,QACpB,OAAO,QAAQ;AAAA,QACf,MAAM,QAAQ;AAAA,QACd,GAAI,QAAQ,SAAS,UAAa,EAAE,MAAM,QAAQ,KAAK;AAAA,QACvD,KAAK,IAAI;AAAA,MACX,CAAC;AACD,aAAO,EAAE,YAAY,KAAK,GAAG;AAAA,IAC/B;AAAA;AAAA,IAEA,eAAe,CAAC,SAAS;AAAA,MACvB,WAAW,EAAE,eAAe,eAAe,IAAI,SAAS;AAAA,IAC1D;AAAA,EACF;AACF;","names":["attempt"]}
|
package/dist/memory.d.ts
CHANGED
package/dist/memory.js
CHANGED
|
@@ -25,6 +25,7 @@ function memoryStore(options = {}) {
|
|
|
25
25
|
const byKey = /* @__PURE__ */ new Map();
|
|
26
26
|
const deliveries = /* @__PURE__ */ new Map();
|
|
27
27
|
const inbox = /* @__PURE__ */ new Map();
|
|
28
|
+
const inboxByKey = /* @__PURE__ */ new Map();
|
|
28
29
|
const out = (v) => structuredClone(v);
|
|
29
30
|
const json = (v) => v === void 0 ? null : JSON.parse(JSON.stringify(v));
|
|
30
31
|
const claimedView = (d) => {
|
|
@@ -94,6 +95,7 @@ function memoryStore(options = {}) {
|
|
|
94
95
|
d.status = "retry";
|
|
95
96
|
d.nextAttemptAt = new Date(result.nextAttemptAt);
|
|
96
97
|
d.lastError = result.error;
|
|
98
|
+
if (result.refundAttempt) d.attempts = Math.max(0, d.attempts - 1);
|
|
97
99
|
} else {
|
|
98
100
|
d.status = "dead";
|
|
99
101
|
d.nextAttemptAt = null;
|
|
@@ -166,7 +168,13 @@ function memoryStore(options = {}) {
|
|
|
166
168
|
return count;
|
|
167
169
|
},
|
|
168
170
|
async inboxAdd(item) {
|
|
169
|
-
const { data, ...rest } = item;
|
|
171
|
+
const { data, key, ...rest } = item;
|
|
172
|
+
const existing = key !== void 0 ? inbox.get(inboxByKey.get(key) ?? "") : void 0;
|
|
173
|
+
if (existing) {
|
|
174
|
+
if (existing.recipientId !== item.recipientId)
|
|
175
|
+
throw new Error(`inboxAdd: key "${key}" is already used by another recipient`);
|
|
176
|
+
return out(existing);
|
|
177
|
+
}
|
|
170
178
|
const created = {
|
|
171
179
|
...out(rest),
|
|
172
180
|
...data !== void 0 && data !== null && { data: json(data) },
|
|
@@ -176,6 +184,7 @@ function memoryStore(options = {}) {
|
|
|
176
184
|
readAt: null
|
|
177
185
|
};
|
|
178
186
|
inbox.set(created.id, created);
|
|
187
|
+
if (key !== void 0) inboxByKey.set(key, created.id);
|
|
179
188
|
return out(created);
|
|
180
189
|
},
|
|
181
190
|
async inboxList(q) {
|
package/dist/memory.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/memory.ts"],"sourcesContent":["import type {\n ClaimedDelivery,\n DeliveryPage,\n DeliveryQuery,\n DeliveryRecord,\n DeliveryResult,\n InboxItem,\n InboxPage,\n InboxQuery,\n ListedDelivery,\n NewNotification,\n NotificationRecord,\n Store,\n} from \"./store.js\";\nimport type { TerminalStatus } from \"./types.js\";\n\nexport interface MemoryStoreOptions {\n /** Clock override for tests. */\n now?: () => Date;\n}\n\nconst TERMINAL: readonly TerminalStatus[] = [\"sent\", \"dead\", \"skipped\", \"cancelled\"];\nconst DEFAULT_PAGE = 50;\n\nconst pad = (n: number) => String(n).padStart(12, \"0\");\n\n/** Newest first: (createdAt desc, id desc). */\nconst newestFirst = (a: { createdAt: Date; id: string }, b: { createdAt: Date; id: string }) =>\n b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);\n\nconst encodeCursor = (x: { createdAt: Date; id: string }) => btoa(`${x.createdAt.getTime()}|${x.id}`);\n\n/** True when `x` sorts strictly after the cursor position in newest-first order. */\nfunction afterCursor(x: { createdAt: Date; id: string }, cursor: string): boolean {\n const [ms, id] = atob(cursor).split(\"|\") as [string, string];\n const t = x.createdAt.getTime();\n const c = Number(ms);\n return t < c || (t === c && x.id < id);\n}\n\nfunction page<T extends { createdAt: Date; id: string }>(\n rows: T[],\n limit: number | undefined,\n cursor: string | undefined,\n): { items: T[]; nextCursor: string | null } {\n const size = limit ?? DEFAULT_PAGE;\n const sorted = rows.sort(newestFirst).filter((r) => !cursor || afterCursor(r, cursor));\n const items = sorted.slice(0, size);\n const last = items[items.length - 1];\n return { items, nextCursor: sorted.length > size && last ? encodeCursor(last) : null };\n}\n\n/**\n * Complete in-process Store. Reference implementation of the Store contract,\n * for tests and local development. Not durable and not shared across processes.\n * `claim` is atomic because JS is single-threaded; the contract suite still proves it.\n */\nexport function memoryStore(options: MemoryStoreOptions = {}): Store {\n const clock = options.now ?? (() => new Date());\n let seq = 0;\n const nextId = (p: string) => `${p}_${pad(++seq)}`;\n\n const notifications = new Map<string, NotificationRecord>();\n const byKey = new Map<string, string>();\n const deliveries = new Map<string, DeliveryRecord>();\n const inbox = new Map<string, InboxItem>();\n\n const out = <T>(v: T): T => structuredClone(v);\n // Stored values go through JSON, as with a SQL store's jsonb: a Date comes back as a string,\n // undefined as null. Keeps tests honest about what production returns.\n const json = (v: unknown): unknown => (v === undefined ? null : JSON.parse(JSON.stringify(v)));\n\n const claimedView = (d: DeliveryRecord): ClaimedDelivery => {\n const notification = notifications.get(d.notificationId) as NotificationRecord;\n return out({ ...d, notification });\n };\n\n return {\n async enqueue(n: NewNotification) {\n const existing = byKey.get(n.idempotencyKey);\n if (existing) return { id: existing, created: false };\n\n const createdAt = clock();\n const id = nextId(\"n\");\n notifications.set(id, {\n id,\n event: n.event,\n payload: json(n.payload),\n priority: n.priority,\n idempotencyKey: n.idempotencyKey,\n subject: n.subject,\n createdAt,\n });\n byKey.set(n.idempotencyKey, id);\n\n for (const d of n.deliveries) {\n const did = nextId(\"d\");\n deliveries.set(did, {\n id: did,\n notificationId: id,\n channel: d.channel,\n address: json(d.address),\n ...(d.recipientId !== undefined && { recipientId: d.recipientId }),\n status: d.status,\n attempts: 0,\n nextAttemptAt: null, // null = due immediately\n leaseUntil: null,\n lastError: null,\n createdAt,\n });\n }\n return { id, created: true };\n },\n\n async claim({ limit, now, leaseMs, notificationId }) {\n const due = [...deliveries.values()]\n .filter((d) => {\n if (notificationId !== undefined && d.notificationId !== notificationId) return false;\n if (d.status === \"pending\" || d.status === \"retry\")\n return d.nextAttemptAt === null || d.nextAttemptAt <= now;\n return d.status === \"sending\" && d.leaseUntil !== null && d.leaseUntil <= now;\n })\n .sort(\n (a, b) =>\n (a.nextAttemptAt?.getTime() ?? 0) - (b.nextAttemptAt?.getTime() ?? 0) ||\n a.createdAt.getTime() - b.createdAt.getTime() ||\n (a.id < b.id ? -1 : 1),\n )\n .slice(0, limit);\n\n return due.map((d) => {\n d.status = \"sending\";\n d.attempts += 1; // attempts = the number of the attempt being made\n d.leaseUntil = new Date(now.getTime() + leaseMs);\n return claimedView(d);\n });\n },\n\n async recordResult(deliveryId: string, result: DeliveryResult) {\n const d = deliveries.get(deliveryId);\n if (!d || d.status !== \"sending\") return; // e.g. cancelled while in flight\n d.leaseUntil = null;\n if (result.status === \"sent\") {\n d.status = \"sent\";\n d.nextAttemptAt = null;\n d.lastError = null;\n } else if (result.status === \"retry\") {\n d.status = \"retry\";\n d.nextAttemptAt = new Date(result.nextAttemptAt);\n d.lastError = result.error;\n } else {\n d.status = \"dead\";\n d.nextAttemptAt = null;\n d.lastError = result.error;\n }\n },\n\n async getNotification(id: string) {\n const notification = notifications.get(id);\n if (!notification) return null;\n return out({\n notification,\n deliveries: [...deliveries.values()].filter((d) => d.notificationId === id),\n });\n },\n\n async listDeliveries(q: DeliveryQuery): Promise<DeliveryPage> {\n const rows: ListedDelivery[] = [];\n for (const d of deliveries.values()) {\n const n = notifications.get(d.notificationId) as NotificationRecord;\n if (q.recipientId !== undefined && d.recipientId !== q.recipientId) continue;\n if (q.event !== undefined && n.event !== q.event) continue;\n if (q.channel !== undefined && d.channel !== q.channel) continue;\n if (q.status !== undefined && d.status !== q.status) continue;\n if (q.subject !== undefined && n.subject !== q.subject) continue;\n if (q.since && d.createdAt < q.since) continue;\n if (q.until && d.createdAt >= q.until) continue;\n rows.push({ ...d, event: n.event, subject: n.subject });\n }\n return out(page(rows, q.limit, q.cursor));\n },\n\n async retryDelivery(deliveryId: string) {\n const d = deliveries.get(deliveryId);\n if (!d || d.status !== \"dead\") return false;\n d.status = \"pending\";\n d.attempts = 0;\n d.nextAttemptAt = null;\n d.leaseUntil = null;\n return true;\n },\n\n async cancel({ subject }) {\n const ids = new Set(\n [...notifications.values()].filter((n) => n.subject === subject).map((n) => n.id),\n );\n let count = 0;\n for (const d of deliveries.values()) {\n if (!ids.has(d.notificationId)) continue;\n if (d.status !== \"pending\" && d.status !== \"retry\") continue;\n d.status = \"cancelled\";\n d.nextAttemptAt = null;\n d.leaseUntil = null;\n count += 1;\n }\n return count;\n },\n\n async purge({ olderThan, statuses }) {\n const allowed: readonly string[] = statuses ?? TERMINAL;\n let count = 0;\n for (const [id, d] of deliveries) {\n if (d.createdAt < olderThan && TERMINAL.includes(d.status as TerminalStatus) && allowed.includes(d.status)) {\n deliveries.delete(id);\n count += 1;\n }\n }\n const withDeliveries = new Set([...deliveries.values()].map((d) => d.notificationId));\n for (const [id, n] of notifications) {\n if (n.createdAt < olderThan && !withDeliveries.has(id)) {\n notifications.delete(id);\n byKey.delete(n.idempotencyKey);\n }\n }\n return count;\n },\n\n async inboxAdd(item) {\n const { data, ...rest } = item;\n const created: InboxItem = {\n ...out(rest),\n ...(data !== undefined && data !== null && { data: json(data) }), // like a NULL jsonb column\n id: nextId(\"i\"),\n createdAt: clock(),\n readAt: null,\n };\n inbox.set(created.id, created);\n return out(created);\n },\n\n async inboxList(q: InboxQuery): Promise<InboxPage> {\n const rows = [...inbox.values()].filter(\n (i) => i.recipientId === q.recipientId && (!q.unreadOnly || i.readAt === null),\n );\n return out(page(rows, q.limit, q.cursor));\n },\n\n async inboxMarkRead(recipientId, ids) {\n const now = clock();\n for (const id of ids) {\n const i = inbox.get(id);\n if (i && i.recipientId === recipientId && i.readAt === null) i.readAt = now;\n }\n },\n\n async inboxUnreadCount(recipientId) {\n return [...inbox.values()].filter((i) => i.recipientId === recipientId && i.readAt === null)\n .length;\n },\n\n async inboxMarkAllRead(recipientId) {\n const now = clock();\n let count = 0;\n for (const i of inbox.values()) {\n if (i.recipientId === recipientId && i.readAt === null) {\n i.readAt = now;\n count += 1;\n }\n }\n return count;\n },\n };\n}\n"],"mappings":";AAqBA,IAAM,WAAsC,CAAC,QAAQ,QAAQ,WAAW,WAAW;AACnF,IAAM,eAAe;AAErB,IAAM,MAAM,CAAC,MAAc,OAAO,CAAC,EAAE,SAAS,IAAI,GAAG;AAGrD,IAAM,cAAc,CAAC,GAAoC,MACvD,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ,MAAM,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK;AAEzF,IAAM,eAAe,CAAC,MAAuC,KAAK,GAAG,EAAE,UAAU,QAAQ,CAAC,IAAI,EAAE,EAAE,EAAE;AAGpG,SAAS,YAAY,GAAoC,QAAyB;AAChF,QAAM,CAAC,IAAI,EAAE,IAAI,KAAK,MAAM,EAAE,MAAM,GAAG;AACvC,QAAM,IAAI,EAAE,UAAU,QAAQ;AAC9B,QAAM,IAAI,OAAO,EAAE;AACnB,SAAO,IAAI,KAAM,MAAM,KAAK,EAAE,KAAK;AACrC;AAEA,SAAS,KACP,MACA,OACA,QAC2C;AAC3C,QAAM,OAAO,SAAS;AACtB,QAAM,SAAS,KAAK,KAAK,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,UAAU,YAAY,GAAG,MAAM,CAAC;AACrF,QAAM,QAAQ,OAAO,MAAM,GAAG,IAAI;AAClC,QAAM,OAAO,MAAM,MAAM,SAAS,CAAC;AACnC,SAAO,EAAE,OAAO,YAA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["../src/memory.ts"],"sourcesContent":["import type {\n ClaimedDelivery,\n DeliveryPage,\n DeliveryQuery,\n DeliveryRecord,\n DeliveryResult,\n InboxItem,\n InboxPage,\n InboxQuery,\n ListedDelivery,\n NewNotification,\n NotificationRecord,\n Store,\n} from \"./store.js\";\nimport type { TerminalStatus } from \"./types.js\";\n\nexport interface MemoryStoreOptions {\n /** Clock override for tests. */\n now?: () => Date;\n}\n\nconst TERMINAL: readonly TerminalStatus[] = [\"sent\", \"dead\", \"skipped\", \"cancelled\"];\nconst DEFAULT_PAGE = 50;\n\nconst pad = (n: number) => String(n).padStart(12, \"0\");\n\n/** Newest first: (createdAt desc, id desc). */\nconst newestFirst = (a: { createdAt: Date; id: string }, b: { createdAt: Date; id: string }) =>\n b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);\n\nconst encodeCursor = (x: { createdAt: Date; id: string }) => btoa(`${x.createdAt.getTime()}|${x.id}`);\n\n/** True when `x` sorts strictly after the cursor position in newest-first order. */\nfunction afterCursor(x: { createdAt: Date; id: string }, cursor: string): boolean {\n const [ms, id] = atob(cursor).split(\"|\") as [string, string];\n const t = x.createdAt.getTime();\n const c = Number(ms);\n return t < c || (t === c && x.id < id);\n}\n\nfunction page<T extends { createdAt: Date; id: string }>(\n rows: T[],\n limit: number | undefined,\n cursor: string | undefined,\n): { items: T[]; nextCursor: string | null } {\n const size = limit ?? DEFAULT_PAGE;\n const sorted = rows.sort(newestFirst).filter((r) => !cursor || afterCursor(r, cursor));\n const items = sorted.slice(0, size);\n const last = items[items.length - 1];\n return { items, nextCursor: sorted.length > size && last ? encodeCursor(last) : null };\n}\n\n/**\n * Complete in-process Store. Reference implementation of the Store contract,\n * for tests and local development. Not durable and not shared across processes.\n * `claim` is atomic because JS is single-threaded; the contract suite still proves it.\n */\nexport function memoryStore(options: MemoryStoreOptions = {}): Store {\n const clock = options.now ?? (() => new Date());\n let seq = 0;\n const nextId = (p: string) => `${p}_${pad(++seq)}`;\n\n const notifications = new Map<string, NotificationRecord>();\n const byKey = new Map<string, string>();\n const deliveries = new Map<string, DeliveryRecord>();\n const inbox = new Map<string, InboxItem>();\n const inboxByKey = new Map<string, string>();\n\n const out = <T>(v: T): T => structuredClone(v);\n // Stored values go through JSON, as with a SQL store's jsonb: a Date comes back as a string,\n // undefined as null. Keeps tests honest about what production returns.\n const json = (v: unknown): unknown => (v === undefined ? null : JSON.parse(JSON.stringify(v)));\n\n const claimedView = (d: DeliveryRecord): ClaimedDelivery => {\n const notification = notifications.get(d.notificationId) as NotificationRecord;\n return out({ ...d, notification });\n };\n\n return {\n async enqueue(n: NewNotification) {\n const existing = byKey.get(n.idempotencyKey);\n if (existing) return { id: existing, created: false };\n\n const createdAt = clock();\n const id = nextId(\"n\");\n notifications.set(id, {\n id,\n event: n.event,\n payload: json(n.payload),\n priority: n.priority,\n idempotencyKey: n.idempotencyKey,\n subject: n.subject,\n createdAt,\n });\n byKey.set(n.idempotencyKey, id);\n\n for (const d of n.deliveries) {\n const did = nextId(\"d\");\n deliveries.set(did, {\n id: did,\n notificationId: id,\n channel: d.channel,\n address: json(d.address),\n ...(d.recipientId !== undefined && { recipientId: d.recipientId }),\n status: d.status,\n attempts: 0,\n nextAttemptAt: null, // null = due immediately\n leaseUntil: null,\n lastError: null,\n createdAt,\n });\n }\n return { id, created: true };\n },\n\n async claim({ limit, now, leaseMs, notificationId }) {\n const due = [...deliveries.values()]\n .filter((d) => {\n if (notificationId !== undefined && d.notificationId !== notificationId) return false;\n if (d.status === \"pending\" || d.status === \"retry\")\n return d.nextAttemptAt === null || d.nextAttemptAt <= now;\n return d.status === \"sending\" && d.leaseUntil !== null && d.leaseUntil <= now;\n })\n .sort(\n (a, b) =>\n (a.nextAttemptAt?.getTime() ?? 0) - (b.nextAttemptAt?.getTime() ?? 0) ||\n a.createdAt.getTime() - b.createdAt.getTime() ||\n (a.id < b.id ? -1 : 1),\n )\n .slice(0, limit);\n\n return due.map((d) => {\n d.status = \"sending\";\n d.attempts += 1; // attempts = the number of the attempt being made\n d.leaseUntil = new Date(now.getTime() + leaseMs);\n return claimedView(d);\n });\n },\n\n async recordResult(deliveryId: string, result: DeliveryResult) {\n const d = deliveries.get(deliveryId);\n if (!d || d.status !== \"sending\") return; // e.g. cancelled while in flight\n d.leaseUntil = null;\n if (result.status === \"sent\") {\n d.status = \"sent\";\n d.nextAttemptAt = null;\n d.lastError = null;\n } else if (result.status === \"retry\") {\n d.status = \"retry\";\n d.nextAttemptAt = new Date(result.nextAttemptAt);\n d.lastError = result.error;\n if (result.refundAttempt) d.attempts = Math.max(0, d.attempts - 1);\n } else {\n d.status = \"dead\";\n d.nextAttemptAt = null;\n d.lastError = result.error;\n }\n },\n\n async getNotification(id: string) {\n const notification = notifications.get(id);\n if (!notification) return null;\n return out({\n notification,\n deliveries: [...deliveries.values()].filter((d) => d.notificationId === id),\n });\n },\n\n async listDeliveries(q: DeliveryQuery): Promise<DeliveryPage> {\n const rows: ListedDelivery[] = [];\n for (const d of deliveries.values()) {\n const n = notifications.get(d.notificationId) as NotificationRecord;\n if (q.recipientId !== undefined && d.recipientId !== q.recipientId) continue;\n if (q.event !== undefined && n.event !== q.event) continue;\n if (q.channel !== undefined && d.channel !== q.channel) continue;\n if (q.status !== undefined && d.status !== q.status) continue;\n if (q.subject !== undefined && n.subject !== q.subject) continue;\n if (q.since && d.createdAt < q.since) continue;\n if (q.until && d.createdAt >= q.until) continue;\n rows.push({ ...d, event: n.event, subject: n.subject });\n }\n return out(page(rows, q.limit, q.cursor));\n },\n\n async retryDelivery(deliveryId: string) {\n const d = deliveries.get(deliveryId);\n if (!d || d.status !== \"dead\") return false;\n d.status = \"pending\";\n d.attempts = 0;\n d.nextAttemptAt = null;\n d.leaseUntil = null;\n return true;\n },\n\n async cancel({ subject }) {\n const ids = new Set(\n [...notifications.values()].filter((n) => n.subject === subject).map((n) => n.id),\n );\n let count = 0;\n for (const d of deliveries.values()) {\n if (!ids.has(d.notificationId)) continue;\n if (d.status !== \"pending\" && d.status !== \"retry\") continue;\n d.status = \"cancelled\";\n d.nextAttemptAt = null;\n d.leaseUntil = null;\n count += 1;\n }\n return count;\n },\n\n async purge({ olderThan, statuses }) {\n const allowed: readonly string[] = statuses ?? TERMINAL;\n let count = 0;\n for (const [id, d] of deliveries) {\n if (d.createdAt < olderThan && TERMINAL.includes(d.status as TerminalStatus) && allowed.includes(d.status)) {\n deliveries.delete(id);\n count += 1;\n }\n }\n const withDeliveries = new Set([...deliveries.values()].map((d) => d.notificationId));\n for (const [id, n] of notifications) {\n if (n.createdAt < olderThan && !withDeliveries.has(id)) {\n notifications.delete(id);\n byKey.delete(n.idempotencyKey);\n }\n }\n return count;\n },\n\n async inboxAdd(item) {\n const { data, key, ...rest } = item;\n const existing = key !== undefined ? inbox.get(inboxByKey.get(key) ?? \"\") : undefined;\n if (existing) {\n if (existing.recipientId !== item.recipientId)\n throw new Error(`inboxAdd: key \"${key}\" is already used by another recipient`);\n return out(existing);\n }\n const created: InboxItem = {\n ...out(rest),\n ...(data !== undefined && data !== null && { data: json(data) }), // like a NULL jsonb column\n id: nextId(\"i\"),\n createdAt: clock(),\n readAt: null,\n };\n inbox.set(created.id, created);\n if (key !== undefined) inboxByKey.set(key, created.id);\n return out(created);\n },\n\n async inboxList(q: InboxQuery): Promise<InboxPage> {\n const rows = [...inbox.values()].filter(\n (i) => i.recipientId === q.recipientId && (!q.unreadOnly || i.readAt === null),\n );\n return out(page(rows, q.limit, q.cursor));\n },\n\n async inboxMarkRead(recipientId, ids) {\n const now = clock();\n for (const id of ids) {\n const i = inbox.get(id);\n if (i && i.recipientId === recipientId && i.readAt === null) i.readAt = now;\n }\n },\n\n async inboxUnreadCount(recipientId) {\n return [...inbox.values()].filter((i) => i.recipientId === recipientId && i.readAt === null)\n .length;\n },\n\n async inboxMarkAllRead(recipientId) {\n const now = clock();\n let count = 0;\n for (const i of inbox.values()) {\n if (i.recipientId === recipientId && i.readAt === null) {\n i.readAt = now;\n count += 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O;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
package/dist/postgres.d.ts
CHANGED
package/dist/postgres.js
CHANGED
|
@@ -7,7 +7,7 @@ var IDENT = /^[a-z_][a-z0-9_]*$/;
|
|
|
7
7
|
var DIGITS = /^\d{1,18}$/;
|
|
8
8
|
var DEFAULT_PAGE = 50;
|
|
9
9
|
var TERMINAL = ["sent", "dead", "skipped", "cancelled"];
|
|
10
|
-
var SCHEMA_VERSION =
|
|
10
|
+
var SCHEMA_VERSION = 2;
|
|
11
11
|
function checkSchema(schema) {
|
|
12
12
|
if (!IDENT.test(schema))
|
|
13
13
|
throw new HeraldError("invalid_config", `postgres schema "${schema}" must match ${IDENT}`);
|
|
@@ -80,6 +80,12 @@ CREATE INDEX IF NOT EXISTS herald_inbox_recipient_idx
|
|
|
80
80
|
CREATE INDEX IF NOT EXISTS herald_inbox_unread_idx
|
|
81
81
|
ON ${s}.herald_inbox (recipient_id) WHERE read_at IS NULL;
|
|
82
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
|
+
|
|
83
89
|
INSERT INTO ${s}.herald_schema_version (version) VALUES (${SCHEMA_VERSION}) ON CONFLICT DO NOTHING;
|
|
84
90
|
`.trim();
|
|
85
91
|
}
|
|
@@ -221,10 +227,12 @@ $herald$`);
|
|
|
221
227
|
if (!DIGITS.test(deliveryId)) return;
|
|
222
228
|
const next = result.status === "retry" ? iso(result.nextAttemptAt) : null;
|
|
223
229
|
const error = result.status === "sent" ? null : result.error;
|
|
230
|
+
const refund = result.status === "retry" && result.refundAttempt === true;
|
|
224
231
|
await rows(
|
|
225
|
-
`UPDATE ${D} SET status = $2, next_attempt_at = $3::timestamptz, last_error = $4, lease_until = NULL
|
|
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
|
|
226
234
|
WHERE id = $1::bigint AND status = 'sending'`,
|
|
227
|
-
[deliveryId, result.status, next, error]
|
|
235
|
+
[deliveryId, result.status, next, error, refund]
|
|
228
236
|
);
|
|
229
237
|
},
|
|
230
238
|
async getNotification(id) {
|
|
@@ -312,13 +320,29 @@ $herald$`);
|
|
|
312
320
|
);
|
|
313
321
|
},
|
|
314
322
|
async inboxAdd(item) {
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
+
]
|
|
320
338
|
);
|
|
321
|
-
return inboxItem(
|
|
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);
|
|
322
346
|
},
|
|
323
347
|
async inboxList(q) {
|
|
324
348
|
const size = q.limit ?? DEFAULT_PAGE;
|