@useherald/core 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-UNUPED23.js +14 -0
- package/dist/chunk-UNUPED23.js.map +1 -0
- package/dist/index.d.ts +9 -4
- package/dist/index.js +180 -12
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts +1 -1
- package/dist/memory.js +14 -4
- package/dist/memory.js.map +1 -1
- package/dist/postgres.d.ts +32 -0
- package/dist/postgres.js +369 -0
- package/dist/postgres.js.map +1 -0
- package/dist/{store-BaqPfkS_.d.ts → store-D-yCqAN7.d.ts} +11 -2
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +53 -0
- package/dist/testing.js.map +1 -1
- package/package.json +8 -1
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var HeraldError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "HeraldError";
|
|
7
|
+
this.code = code;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export {
|
|
12
|
+
HeraldError
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=chunk-UNUPED23.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["export type HeraldErrorCode =\r\n | \"invalid_config\"\r\n | \"unknown_event\"\r\n | \"channel_not_allowed\"\r\n | \"invalid_targets\"\r\n | \"missing_template\"\r\n | \"not_implemented\";\r\n\r\n/** Every error Herald throws on its own behalf. Channel failures never surface through here. */\r\nexport class HeraldError extends Error {\r\n readonly code: HeraldErrorCode;\r\n\r\n constructor(code: HeraldErrorCode, message: string) {\r\n super(message);\r\n this.name = \"HeraldError\";\r\n this.code = code;\r\n }\r\n}\r\n"],"mappings":";AASO,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EAET,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
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-
|
|
2
|
-
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-
|
|
1
|
+
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-D-yCqAN7.js';
|
|
2
|
+
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-D-yCqAN7.js';
|
|
3
3
|
|
|
4
4
|
interface SendContext {
|
|
5
5
|
/** Stable per delivery across retries. Pass to providers that dedupe. */
|
|
@@ -78,6 +78,10 @@ interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEvent
|
|
|
78
78
|
hooks?: Hooks;
|
|
79
79
|
logger?: Logger;
|
|
80
80
|
retry?: Partial<RetryPolicy>;
|
|
81
|
+
/** Per-send timeout; aborts `ctx.signal`. Default 15_000. */
|
|
82
|
+
sendTimeoutMs?: number;
|
|
83
|
+
/** How long a claimed delivery stays leased. Must exceed `sendTimeoutMs`. Default 60_000. */
|
|
84
|
+
leaseMs?: number;
|
|
81
85
|
/** Clock override for tests. */
|
|
82
86
|
now?: () => Date;
|
|
83
87
|
}
|
|
@@ -94,8 +98,9 @@ interface Herald<Ev extends Record<string, AnyEventDef>> {
|
|
|
94
98
|
declare const defaultRetry: RetryPolicy;
|
|
95
99
|
/**
|
|
96
100
|
* Validates config at startup (missing templates, unregistered channels are
|
|
97
|
-
* errors here, not at send time). `notify` queues durably
|
|
98
|
-
* `
|
|
101
|
+
* errors here, not at send time). `notify` queues durably (and sends inline on
|
|
102
|
+
* request); `processPending` delivers. `inbox` throws `not_implemented` until
|
|
103
|
+
* a later release.
|
|
99
104
|
*/
|
|
100
105
|
declare function createHerald<const Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>>(config: HeraldConfig<Ch, Ev>): Herald<Ev>;
|
|
101
106
|
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
constructor(code, message) {
|
|
5
|
-
super(message);
|
|
6
|
-
this.name = "HeraldError";
|
|
7
|
-
this.code = code;
|
|
8
|
-
}
|
|
9
|
-
};
|
|
1
|
+
import {
|
|
2
|
+
HeraldError
|
|
3
|
+
} from "./chunk-UNUPED23.js";
|
|
10
4
|
|
|
11
5
|
// src/notify.ts
|
|
12
6
|
var isRaw = (t) => "channel" in t;
|
|
@@ -64,9 +58,155 @@ async function notify(deps, event, payload, targets) {
|
|
|
64
58
|
deliveries: [...resolved, ...rawDeliveries]
|
|
65
59
|
});
|
|
66
60
|
deps.logger?.debug("notification queued", { id, event, created });
|
|
61
|
+
if (targets.inline && created && deps.sendInline) {
|
|
62
|
+
try {
|
|
63
|
+
await deps.sendInline(id);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
deps.logger?.error("inline send failed; left for processPending()", {
|
|
66
|
+
id,
|
|
67
|
+
error: err instanceof Error ? err.message : String(err)
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
67
71
|
return id;
|
|
68
72
|
}
|
|
69
73
|
|
|
74
|
+
// src/process.ts
|
|
75
|
+
var PROCESS_DEFAULTS = { batchSize: 50, budgetMs: 2e4, concurrency: 10 };
|
|
76
|
+
var MAX_ERROR = 1e3;
|
|
77
|
+
var errorText = (err) => (err instanceof Error ? err.message : String(err)).slice(0, MAX_ERROR);
|
|
78
|
+
function backoffMs(attempt2, policy, random = Math.random) {
|
|
79
|
+
const delay = Math.min(policy.maxMs, policy.baseMs * 2 ** (attempt2 - 1));
|
|
80
|
+
return policy.jitter ? delay / 2 + random() * (delay / 2) : delay;
|
|
81
|
+
}
|
|
82
|
+
async function attempt(deps, row) {
|
|
83
|
+
const n = row.notification;
|
|
84
|
+
const def = deps.events[n.event];
|
|
85
|
+
if (!def) return { result: { status: "dead", error: `unknown event "${n.event}"` } };
|
|
86
|
+
const channel = deps.channels[row.channel];
|
|
87
|
+
const template = def.templates[row.channel];
|
|
88
|
+
if (!channel || !template)
|
|
89
|
+
return { result: { status: "dead", error: `unknown channel "${row.channel}" for event "${n.event}"` } };
|
|
90
|
+
let message;
|
|
91
|
+
try {
|
|
92
|
+
message = template(n.payload);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
return { result: { status: "dead", error: `template failed: ${errorText(error)}` }, error };
|
|
95
|
+
}
|
|
96
|
+
const signal = AbortSignal.timeout(deps.sendTimeoutMs);
|
|
97
|
+
const timedOut = new Promise(
|
|
98
|
+
(_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true })
|
|
99
|
+
);
|
|
100
|
+
try {
|
|
101
|
+
const res = await Promise.race([
|
|
102
|
+
channel.send(message, row.address, {
|
|
103
|
+
idempotencyKey: `${n.idempotencyKey}:${row.id}`,
|
|
104
|
+
attempt: row.attempts,
|
|
105
|
+
signal
|
|
106
|
+
}),
|
|
107
|
+
timedOut
|
|
108
|
+
]);
|
|
109
|
+
return { result: { status: "sent", ...res?.providerId !== void 0 && { providerId: res.providerId } } };
|
|
110
|
+
} catch (error) {
|
|
111
|
+
return { result: failure(deps, row, channel, error, signal.aborted), error };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async function deliver(deps, row) {
|
|
115
|
+
const { result, error } = await attempt(deps, row);
|
|
116
|
+
try {
|
|
117
|
+
await deps.store.recordResult(row.id, result);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
deps.logger?.error("recordResult failed; delivery will be retried after its lease", {
|
|
120
|
+
deliveryId: row.id,
|
|
121
|
+
error: errorText(err)
|
|
122
|
+
});
|
|
123
|
+
return "unrecorded";
|
|
124
|
+
}
|
|
125
|
+
const info = {
|
|
126
|
+
notificationId: row.notification.id,
|
|
127
|
+
deliveryId: row.id,
|
|
128
|
+
event: row.notification.event,
|
|
129
|
+
channel: row.channel,
|
|
130
|
+
...row.recipientId !== void 0 && { recipientId: row.recipientId },
|
|
131
|
+
attempt: row.attempts
|
|
132
|
+
};
|
|
133
|
+
const meta = { deliveryId: row.id, channel: row.channel, attempt: row.attempts };
|
|
134
|
+
if (result.status === "sent") {
|
|
135
|
+
await runHook(deps, "onSent", () => deps.hooks?.onSent?.(info));
|
|
136
|
+
return "sent";
|
|
137
|
+
}
|
|
138
|
+
const failed = { ...info, error: error ?? result.error };
|
|
139
|
+
if (result.status === "retry") {
|
|
140
|
+
const nextAttemptAt = result.nextAttemptAt;
|
|
141
|
+
deps.logger?.warn("delivery failed, will retry", { ...meta, error: result.error, nextAttemptAt: nextAttemptAt.toISOString() });
|
|
142
|
+
await runHook(deps, "onFailed", () => deps.hooks?.onFailed?.({ ...failed, nextAttemptAt }));
|
|
143
|
+
return "retried";
|
|
144
|
+
}
|
|
145
|
+
deps.logger?.error("delivery dead", { ...meta, error: result.error });
|
|
146
|
+
await runHook(deps, "onDead", () => deps.hooks?.onDead?.(failed));
|
|
147
|
+
return "dead";
|
|
148
|
+
}
|
|
149
|
+
function failure(deps, row, channel, err, timedOut) {
|
|
150
|
+
let retryable = true;
|
|
151
|
+
let retryAfterMs;
|
|
152
|
+
let text = errorText(err);
|
|
153
|
+
if (timedOut) {
|
|
154
|
+
text = `send timed out after ${deps.sendTimeoutMs}ms: ${text}`.slice(0, MAX_ERROR);
|
|
155
|
+
} else {
|
|
156
|
+
try {
|
|
157
|
+
const cls = channel.classifyError(err);
|
|
158
|
+
retryable = cls.retryable;
|
|
159
|
+
if (Number.isFinite(cls.retryAfterMs) && cls.retryAfterMs >= 0)
|
|
160
|
+
retryAfterMs = cls.retryAfterMs;
|
|
161
|
+
} catch (clsErr) {
|
|
162
|
+
deps.logger?.warn("classifyError threw; treating the error as retryable", {
|
|
163
|
+
channel: row.channel,
|
|
164
|
+
error: errorText(clsErr)
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (!retryable || row.attempts >= deps.retry.maxAttempts) return { status: "dead", error: text };
|
|
169
|
+
const delay = Math.max(1, retryAfterMs ?? backoffMs(row.attempts, deps.retry, deps.random));
|
|
170
|
+
return { status: "retry", nextAttemptAt: new Date(deps.now().getTime() + delay), error: text };
|
|
171
|
+
}
|
|
172
|
+
async function runHook(deps, name, call) {
|
|
173
|
+
try {
|
|
174
|
+
await call();
|
|
175
|
+
} catch (err) {
|
|
176
|
+
try {
|
|
177
|
+
deps.logger?.error(`${name} hook threw; delivery state is unaffected`, { error: errorText(err) });
|
|
178
|
+
} catch {
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async function processPending(deps, opts = {}) {
|
|
183
|
+
const batchSize = opts.batchSize ?? PROCESS_DEFAULTS.batchSize;
|
|
184
|
+
const concurrency = opts.concurrency ?? PROCESS_DEFAULTS.concurrency;
|
|
185
|
+
const startedAt = deps.now();
|
|
186
|
+
const deadline = startedAt.getTime() + (opts.budgetMs ?? PROCESS_DEFAULTS.budgetMs);
|
|
187
|
+
const summary = { claimed: 0, sent: 0, retried: 0, dead: 0 };
|
|
188
|
+
while (summary.claimed < batchSize && deps.now().getTime() < deadline) {
|
|
189
|
+
const elapsed = deps.now().getTime() - startedAt.getTime();
|
|
190
|
+
const rows = await deps.store.claim({
|
|
191
|
+
limit: Math.min(concurrency, batchSize - summary.claimed),
|
|
192
|
+
now: startedAt,
|
|
193
|
+
leaseMs: deps.leaseMs + elapsed,
|
|
194
|
+
// lease still ends leaseMs from *now*
|
|
195
|
+
...opts.notificationId !== void 0 && { notificationId: opts.notificationId }
|
|
196
|
+
});
|
|
197
|
+
if (rows.length === 0) break;
|
|
198
|
+
summary.claimed += rows.length;
|
|
199
|
+
deps.logger?.debug("claimed deliveries", { count: rows.length });
|
|
200
|
+
const outcomes = await Promise.all(
|
|
201
|
+
rows.map((r) => deliver(deps, r).catch(() => "unrecorded"))
|
|
202
|
+
);
|
|
203
|
+
for (const outcome of outcomes) {
|
|
204
|
+
if (outcome !== "unrecorded") summary[outcome] += 1;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return summary;
|
|
208
|
+
}
|
|
209
|
+
|
|
70
210
|
// src/herald.ts
|
|
71
211
|
var defaultRetry = {
|
|
72
212
|
maxAttempts: 5,
|
|
@@ -74,6 +214,8 @@ var defaultRetry = {
|
|
|
74
214
|
maxMs: 36e5,
|
|
75
215
|
jitter: true
|
|
76
216
|
};
|
|
217
|
+
var DEFAULT_SEND_TIMEOUT_MS = 15e3;
|
|
218
|
+
var DEFAULT_LEASE_MS = 6e4;
|
|
77
219
|
var fn = (v) => typeof v === "function";
|
|
78
220
|
var STORE_METHODS = [
|
|
79
221
|
"enqueue",
|
|
@@ -104,6 +246,15 @@ function validate(config) {
|
|
|
104
246
|
if (!c || !fn(c.send) || !fn(c.classifyError))
|
|
105
247
|
bad(`channel "${name}" must implement send() and classifyError()`);
|
|
106
248
|
}
|
|
249
|
+
const sendTimeoutMs = config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
|
|
250
|
+
const leaseMs = config.leaseMs ?? DEFAULT_LEASE_MS;
|
|
251
|
+
if (!(sendTimeoutMs > 0)) bad("sendTimeoutMs must be a positive number");
|
|
252
|
+
if (!(leaseMs > sendTimeoutMs))
|
|
253
|
+
bad(`leaseMs (${leaseMs}) must exceed sendTimeoutMs (${sendTimeoutMs}), or a lease can expire mid-send`);
|
|
254
|
+
const r = { ...defaultRetry, ...config.retry };
|
|
255
|
+
if (!(Number.isInteger(r.maxAttempts) && r.maxAttempts >= 1)) bad("retry.maxAttempts must be an integer >= 1");
|
|
256
|
+
if (!(Number.isFinite(r.baseMs) && r.baseMs >= 0)) bad("retry.baseMs must be a finite number >= 0");
|
|
257
|
+
if (!(Number.isFinite(r.maxMs) && r.maxMs >= r.baseMs)) bad("retry.maxMs must be finite and >= retry.baseMs");
|
|
107
258
|
const names = Object.keys(events ?? {});
|
|
108
259
|
if (names.length === 0) bad("at least one event is required");
|
|
109
260
|
for (const [event, def] of Object.entries(events)) {
|
|
@@ -121,6 +272,17 @@ function validate(config) {
|
|
|
121
272
|
}
|
|
122
273
|
function createHerald(config) {
|
|
123
274
|
validate(config);
|
|
275
|
+
const engine = {
|
|
276
|
+
store: config.store,
|
|
277
|
+
channels: config.channels,
|
|
278
|
+
events: config.events,
|
|
279
|
+
...config.hooks && { hooks: config.hooks },
|
|
280
|
+
...config.logger && { logger: config.logger },
|
|
281
|
+
retry: { ...defaultRetry, ...config.retry },
|
|
282
|
+
now: config.now ?? (() => /* @__PURE__ */ new Date()),
|
|
283
|
+
leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,
|
|
284
|
+
sendTimeoutMs: config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS
|
|
285
|
+
};
|
|
124
286
|
const notImplemented = (what) => {
|
|
125
287
|
throw new HeraldError("not_implemented", `${what} is not implemented yet`);
|
|
126
288
|
};
|
|
@@ -132,15 +294,21 @@ function createHerald(config) {
|
|
|
132
294
|
events: config.events,
|
|
133
295
|
resolvePreferences: config.resolvePreferences,
|
|
134
296
|
resolveAddress: config.resolveAddress,
|
|
135
|
-
logger: config.logger
|
|
297
|
+
logger: config.logger,
|
|
298
|
+
// Inline gets one send-timeout of budget: notify() should not block like a worker run.
|
|
299
|
+
sendInline: (notificationId) => processPending(engine, {
|
|
300
|
+
notificationId,
|
|
301
|
+
batchSize: Number.POSITIVE_INFINITY,
|
|
302
|
+
budgetMs: engine.sendTimeoutMs
|
|
303
|
+
})
|
|
136
304
|
},
|
|
137
305
|
event,
|
|
138
306
|
payload,
|
|
139
307
|
targets
|
|
140
308
|
);
|
|
141
309
|
},
|
|
142
|
-
|
|
143
|
-
return
|
|
310
|
+
processPending(opts) {
|
|
311
|
+
return processPending(engine, opts);
|
|
144
312
|
},
|
|
145
313
|
inbox: {
|
|
146
314
|
async list() {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/notify.ts","../src/herald.ts","../src/events.ts"],"sourcesContent":["export type HeraldErrorCode =\r\n | \"invalid_config\"\r\n | \"unknown_event\"\r\n | \"channel_not_allowed\"\r\n | \"invalid_targets\"\r\n | \"missing_template\"\r\n | \"not_implemented\";\r\n\r\n/** Every error Herald throws on its own behalf. Channel failures never surface through here. */\r\nexport class HeraldError extends Error {\r\n readonly code: HeraldErrorCode;\r\n\r\n constructor(code: HeraldErrorCode, message: string) {\r\n super(message);\r\n this.name = \"HeraldError\";\r\n this.code = code;\r\n }\r\n}\r\n","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}\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 return id;\n}\n","import type { Channel } from \"./channel.js\";\r\nimport { HeraldError } from \"./errors.js\";\r\nimport { notify as runNotify } from \"./notify.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 /** 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 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 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; `processPending` and\r\n * `inbox` are typed but throw `not_implemented` until later releases.\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 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 },\r\n event,\r\n payload,\r\n targets as Targets,\r\n );\r\n },\r\n async processPending() {\r\n return notImplemented(\"processPending()\");\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":";AASO,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EAET,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;;;ACGA,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,CAAC;AAC9D,aAAW,MAAM,UAAU;AACzB,QAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,YAAM,IAAI,YAAY,uBAAuB,UAAU,KAAK,6BAA6B,EAAE,GAAG;AAAA,EAClG;AAEA,QAAM,OAAO,QAAQ,GAAG,OAAO,KAAK;AACpC,aAAW,KAAK,MAAM;AACpB,QAAI,CAAC,SAAS,SAAS,EAAE,OAAO;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,QACA,uBAA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KAAK,mCAAmC;AACjF,eAAW,MAAM,IAAI,UAAU;AAC7B,UAAI,EAAE,MAAM,UAAW,KAAI,UAAU,KAAK,kCAAkC,EAAE,GAAG;AACjF,UAAI,CAAC,GAAI,IAAI,YAAoD,EAAE,CAAC;AAClE,cAAM,IAAI,YAAY,oBAAoB,UAAU,KAAK,kCAAkC,EAAE,GAAG;AAAA,IACpG;AACA,eAAW,MAAM,OAAO,KAAK,IAAI,aAAa,CAAC,CAAC,GAAG;AACjD,UAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,YAAI,UAAU,KAAK,yBAAyB,EAAE,wCAAwC;AAAA,IAC1F;AAAA,EACF;AACF;AAOO,SAAS,aAGd,QAA0C;AAC1C,WAAS,MAA0E;AAEnF,QAAM,iBAAiB,CAAC,SAAwB;AAC9C,UAAM,IAAI,YAAY,mBAAmB,GAAG,IAAI,yBAAyB;AAAA,EAC3E;AAEA,SAAO;AAAA,IACL,OAAO,OAAO,SAAS,SAAS;AAC9B,aAAO;AAAA,QACL;AAAA,UACE,OAAO,OAAO;AAAA,UACd,QAAQ,OAAO;AAAA,UACf,oBAAoB,OAAO;AAAA,UAC3B,gBAAgB,OAAO;AAAA,UACvB,QAAQ,OAAO;AAAA,QACjB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,IACA,MAAM,iBAAiB;AACrB,aAAO,eAAe,kBAAkB;AAAA,IAC1C;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;;;AClHO,SAAS,cAAiB;AAC/B,SAAO,CAA0E,QAGxD;AAC3B;","names":[]}
|
|
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,CAAC;AAC9D,aAAW,MAAM,UAAU;AACzB,QAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,YAAM,IAAI,YAAY,uBAAuB,UAAU,KAAK,6BAA6B,EAAE,GAAG;AAAA,EAClG;AAEA,QAAM,OAAO,QAAQ,GAAG,OAAO,KAAK;AACpC,aAAW,KAAK,MAAM;AACpB,QAAI,CAAC,SAAS,SAAS,EAAE,OAAO;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,QACA,uBAAuB,EAAE,OAAO,2CAA2C,KAAK;AAAA,MAClF;AAAA,EACJ;AAEA,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,aAA6B,CAAC;AACpC,aAAW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O,MAAM;AAAA,IAC1C,GAAI,OAAO,UAAU,EAAE,QAAQ,OAAO,OAAO;AAAA,IAC7C,OAAO,EAAE,GAAG,cAAc,GAAG,OAAO,MAAM;AAAA,IAC1C,KAAK,OAAO,QAAQ,MAAM,oBAAI,KAAK;AAAA,IACnC,SAAS,OAAO,WAAW;AAAA,IAC3B,eAAe,OAAO,iBAAiB;AAAA,EACzC;AAEA,QAAM,iBAAiB,CAAC,SAAwB;AAC9C,UAAM,IAAI,YAAY,mBAAmB,GAAG,IAAI,yBAAyB;AAAA,EAC3E;AAEA,SAAO;AAAA,IACL,OAAO,OAAO,SAAS,SAAS;AAC9B,aAAO;AAAA,QACL;AAAA,UACE,OAAO,OAAO;AAAA,UACd,QAAQ,OAAO;AAAA,UACf,oBAAoB,OAAO;AAAA,UAC3B,gBAAgB,OAAO;AAAA,UACvB,QAAQ,OAAO;AAAA;AAAA,UAEf,YAAY,CAAC,mBACX,eAAW,QAAQ;AAAA,YACjB;AAAA,YACA,WAAW,OAAO;AAAA,YAClB,UAAU,OAAO;AAAA,UACnB,CAAC;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,IACA,eAAe,MAAM;AACnB,aAAO,eAAW,QAAQ,IAAI;AAAA,IAChC;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"]}
|
package/dist/memory.d.ts
CHANGED
package/dist/memory.js
CHANGED
|
@@ -26,6 +26,7 @@ function memoryStore(options = {}) {
|
|
|
26
26
|
const deliveries = /* @__PURE__ */ new Map();
|
|
27
27
|
const inbox = /* @__PURE__ */ new Map();
|
|
28
28
|
const out = (v) => structuredClone(v);
|
|
29
|
+
const json = (v) => v === void 0 ? null : JSON.parse(JSON.stringify(v));
|
|
29
30
|
const claimedView = (d) => {
|
|
30
31
|
const notification = notifications.get(d.notificationId);
|
|
31
32
|
return out({ ...d, notification });
|
|
@@ -39,7 +40,7 @@ function memoryStore(options = {}) {
|
|
|
39
40
|
notifications.set(id, {
|
|
40
41
|
id,
|
|
41
42
|
event: n.event,
|
|
42
|
-
payload:
|
|
43
|
+
payload: json(n.payload),
|
|
43
44
|
priority: n.priority,
|
|
44
45
|
idempotencyKey: n.idempotencyKey,
|
|
45
46
|
subject: n.subject,
|
|
@@ -52,7 +53,7 @@ function memoryStore(options = {}) {
|
|
|
52
53
|
id: did,
|
|
53
54
|
notificationId: id,
|
|
54
55
|
channel: d.channel,
|
|
55
|
-
address:
|
|
56
|
+
address: json(d.address),
|
|
56
57
|
...d.recipientId !== void 0 && { recipientId: d.recipientId },
|
|
57
58
|
status: d.status,
|
|
58
59
|
attempts: 0,
|
|
@@ -65,8 +66,9 @@ function memoryStore(options = {}) {
|
|
|
65
66
|
}
|
|
66
67
|
return { id, created: true };
|
|
67
68
|
},
|
|
68
|
-
async claim({ limit, now, leaseMs }) {
|
|
69
|
+
async claim({ limit, now, leaseMs, notificationId }) {
|
|
69
70
|
const due = [...deliveries.values()].filter((d) => {
|
|
71
|
+
if (notificationId !== void 0 && d.notificationId !== notificationId) return false;
|
|
70
72
|
if (d.status === "pending" || d.status === "retry")
|
|
71
73
|
return d.nextAttemptAt === null || d.nextAttemptAt <= now;
|
|
72
74
|
return d.status === "sending" && d.leaseUntil !== null && d.leaseUntil <= now;
|
|
@@ -164,7 +166,15 @@ function memoryStore(options = {}) {
|
|
|
164
166
|
return count;
|
|
165
167
|
},
|
|
166
168
|
async inboxAdd(item) {
|
|
167
|
-
const
|
|
169
|
+
const { data, ...rest } = item;
|
|
170
|
+
const created = {
|
|
171
|
+
...out(rest),
|
|
172
|
+
...data !== void 0 && data !== null && { data: json(data) },
|
|
173
|
+
// like a NULL jsonb column
|
|
174
|
+
id: nextId("i"),
|
|
175
|
+
createdAt: clock(),
|
|
176
|
+
readAt: null
|
|
177
|
+
};
|
|
168
178
|
inbox.set(created.id, created);
|
|
169
179
|
return out(created);
|
|
170
180
|
},
|
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\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: out(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: out(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 }) {\n const due = [...deliveries.values()]\n .filter((d) => {\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 created: InboxItem = { ...out(item), id: nextId(\"i\"), createdAt: clock(), readAt: null };\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,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AC,MAAM,EAAE,gBAAgB,eAAe,EAAE,WAAW,IAAI,EACxF;AAAA,IACL;AAAA,IAEA,MAAM,iBAAiB,aAAa;AAClC,YAAM,MAAM,MAAM;AAClB,UAAI,QAAQ;AACZ,iBAAW,KAAK,MAAM,OAAO,GAAG;AAC9B,YAAI,EAAE,gBAAgB,eAAe,EAAE,WAAW,MAAM;AACtD,YAAE,SAAS;AACX,mBAAS;AAAA,QACX;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
|
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,YAAY,OAAO,SAAS,QAAQ,OAAO,aAAa,IAAI,IAAI,KAAK;AACvF;AAOO,SAAS,YAAY,UAA8B,CAAC,GAAU;AACnE,QAAM,QAAQ,QAAQ,QAAQ,MAAM,oBAAI,KAAK;AAC7C,MAAI,MAAM;AACV,QAAM,SAAS,CAAC,MAAc,GAAG,CAAC,I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AW,MAAM;AAAA,QACjB,QAAQ;AAAA,MACV;AACA,YAAM,IAAI,QAAQ,IAAI,OAAO;AAC7B,aAAO,IAAI,OAAO;AAAA,IACpB;AAAA,IAEA,MAAM,UAAU,GAAmC;AACjD,YAAM,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE;AAAA,QAC/B,CAAC,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,EAAE,cAAc,EAAE,WAAW;AAAA,MAC3E;AACA,aAAO,IAAI,KAAK,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC;AAAA,IAC1C;AAAA,IAEA,MAAM,cAAc,aAAa,KAAK;AACpC,YAAM,MAAM,MAAM;AAClB,iBAAW,MAAM,KAAK;AACpB,cAAM,IAAI,MAAM,IAAI,EAAE;AACtB,YAAI,KAAK,EAAE,gBAAgB,eAAe,EAAE,WAAW,KAAM,GAAE,SAAS;AAAA,MAC1E;AAAA,IACF;AAAA,IAEA,MAAM,iBAAiB,aAAa;AAClC,aAAO,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,gBAAgB,eAAe,EAAE,WAAW,IAAI,EACxF;AAAA,IACL;AAAA,IAEA,MAAM,iBAAiB,aAAa;AAClC,YAAM,MAAM,MAAM;AAClB,UAAI,QAAQ;AACZ,iBAAW,KAAK,MAAM,OAAO,GAAG;AAC9B,YAAI,EAAE,gBAAgB,eAAe,EAAE,WAAW,MAAM;AACtD,YAAE,SAAS;AACX,mBAAS;AAAA,QACX;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { S as Store } from './store-D-yCqAN7.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Anything with a pg-style `query`: `pg.Pool`, `pg.Client`, Neon's serverless
|
|
5
|
+
* `Pool`, PGlite. Herald never imports a driver and never opens connections.
|
|
6
|
+
*/
|
|
7
|
+
interface Queryable {
|
|
8
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
9
|
+
rows: Record<string, unknown>[];
|
|
10
|
+
}>;
|
|
11
|
+
}
|
|
12
|
+
interface PostgresStoreOptions {
|
|
13
|
+
db: Queryable;
|
|
14
|
+
/** Postgres schema holding Herald's tables. Default `public`. Plain identifier only. */
|
|
15
|
+
schema?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Schema v1 as plain DDL, for apps that manage migrations themselves (Prisma,
|
|
19
|
+
* Drizzle, SQL files). Idempotent. `store.migrate()` runs the same statements
|
|
20
|
+
* atomically under an advisory lock.
|
|
21
|
+
*/
|
|
22
|
+
declare function postgresSchemaSql(opts?: {
|
|
23
|
+
schema?: string;
|
|
24
|
+
}): string;
|
|
25
|
+
/**
|
|
26
|
+
* Postgres Store. Every method is a single SQL statement (CTEs where needed),
|
|
27
|
+
* so it works over pooled and serverless connections without transactions.
|
|
28
|
+
* Call `migrate()` once (or apply `postgresSchemaSql()` yourself) before use.
|
|
29
|
+
*/
|
|
30
|
+
declare function postgresStore(options: PostgresStoreOptions): Store;
|
|
31
|
+
|
|
32
|
+
export { type PostgresStoreOptions, type Queryable, postgresSchemaSql, postgresStore };
|