@useherald/core 0.1.0 → 0.3.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/index.d.ts +7 -183
- package/dist/index.js +88 -12
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts +14 -0
- package/dist/memory.js +203 -0
- package/dist/memory.js.map +1 -0
- package/dist/store-BaqPfkS_.d.ts +252 -0
- package/dist/testing.d.ts +19 -0
- package/dist/testing.js +400 -0
- package/dist/testing.js.map +1 -0
- package/package.json +17 -1
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
type Priority = "normal" | "critical";
|
|
2
|
+
/** The app's own recipient. Herald only needs a stable id; apps carry extra fields freely. */
|
|
3
|
+
interface RecipientRef {
|
|
4
|
+
id: string;
|
|
5
|
+
}
|
|
6
|
+
/** A destination given directly, bypassing address resolution (e.g. a Slack channel id). */
|
|
7
|
+
interface RawTarget<C extends string = string> {
|
|
8
|
+
channel: C;
|
|
9
|
+
address: unknown;
|
|
10
|
+
}
|
|
11
|
+
interface Targets<C extends string = string> {
|
|
12
|
+
to: ReadonlyArray<RecipientRef | RawTarget<C>>;
|
|
13
|
+
/** Subset of the event's allowed channels. Omitted = all of them. */
|
|
14
|
+
channels?: readonly C[];
|
|
15
|
+
/** `critical` bypasses recipient preferences. */
|
|
16
|
+
priority?: Priority;
|
|
17
|
+
/** Herald generates one when omitted. */
|
|
18
|
+
idempotencyKey?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Opaque tag for what this notification is about, e.g. `"lead:42"`. Not part of
|
|
21
|
+
* the idempotency key. Lets you `cancel({ subject })` and filter `listDeliveries`.
|
|
22
|
+
*/
|
|
23
|
+
subject?: string;
|
|
24
|
+
}
|
|
25
|
+
type DeliveryStatus = "pending" | "sending" | "sent" | "retry" | "dead" | "skipped" | "cancelled";
|
|
26
|
+
/** Statuses a delivery never leaves on its own. Only these can be purged. */
|
|
27
|
+
type TerminalStatus = "sent" | "dead" | "skipped" | "cancelled";
|
|
28
|
+
/** What hooks receive after each attempt outcome. */
|
|
29
|
+
interface DeliveryInfo {
|
|
30
|
+
notificationId: string;
|
|
31
|
+
deliveryId: string;
|
|
32
|
+
event: string;
|
|
33
|
+
channel: string;
|
|
34
|
+
recipientId?: string;
|
|
35
|
+
attempt: number;
|
|
36
|
+
error?: unknown;
|
|
37
|
+
}
|
|
38
|
+
interface Hooks {
|
|
39
|
+
onSent?(info: DeliveryInfo): void | Promise<void>;
|
|
40
|
+
onFailed?(info: DeliveryInfo & {
|
|
41
|
+
nextAttemptAt: Date;
|
|
42
|
+
}): void | Promise<void>;
|
|
43
|
+
onDead?(info: DeliveryInfo): void | Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
interface Logger {
|
|
46
|
+
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
47
|
+
info(msg: string, meta?: Record<string, unknown>): void;
|
|
48
|
+
warn(msg: string, meta?: Record<string, unknown>): void;
|
|
49
|
+
error(msg: string, meta?: Record<string, unknown>): void;
|
|
50
|
+
}
|
|
51
|
+
interface RetryPolicy {
|
|
52
|
+
/** Total attempts including the first. Default 5. */
|
|
53
|
+
maxAttempts: number;
|
|
54
|
+
/** First retry delay. Doubles each attempt. Default 30_000. */
|
|
55
|
+
baseMs: number;
|
|
56
|
+
/** Delay ceiling. Default 3_600_000. */
|
|
57
|
+
maxMs: number;
|
|
58
|
+
/** Randomize delays to avoid thundering herds. Default true. */
|
|
59
|
+
jitter: boolean;
|
|
60
|
+
}
|
|
61
|
+
/** Narrows channels per recipient. Called once per `notify()` with all recipients. Never adds channels. */
|
|
62
|
+
type ResolvePreferences = (recipients: readonly RecipientRef[], event: string) => Promise<ReadonlyMap<string, readonly string[]>> | ReadonlyMap<string, readonly string[]>;
|
|
63
|
+
/** Maps a recipient to a channel address. `null` skips that delivery (recorded as `skipped`). */
|
|
64
|
+
type ResolveAddress = (recipient: RecipientRef, channel: string) => Promise<unknown | null> | unknown | null;
|
|
65
|
+
interface ProcessOptions {
|
|
66
|
+
/** Max deliveries to claim this call. Default 50. */
|
|
67
|
+
batchSize?: number;
|
|
68
|
+
/** Stop starting new sends after this many ms (fits function timeouts). Default 20_000. */
|
|
69
|
+
budgetMs?: number;
|
|
70
|
+
}
|
|
71
|
+
interface ProcessSummary {
|
|
72
|
+
claimed: number;
|
|
73
|
+
sent: number;
|
|
74
|
+
retried: number;
|
|
75
|
+
dead: number;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface NewDelivery {
|
|
79
|
+
channel: string;
|
|
80
|
+
/** Resolved address, or the raw target's address. `null` when resolution skipped it. */
|
|
81
|
+
address: unknown;
|
|
82
|
+
recipientId?: string;
|
|
83
|
+
status: "pending" | "skipped";
|
|
84
|
+
}
|
|
85
|
+
interface NewNotification {
|
|
86
|
+
event: string;
|
|
87
|
+
payload: unknown;
|
|
88
|
+
priority: Priority;
|
|
89
|
+
idempotencyKey: string;
|
|
90
|
+
/** Plain nullable indexed column, e.g. `"lead:42"`. Never part of the idempotency key. */
|
|
91
|
+
subject: string | null;
|
|
92
|
+
/** Final channels per recipient, after preferences. Retries never change them. */
|
|
93
|
+
deliveries: readonly NewDelivery[];
|
|
94
|
+
}
|
|
95
|
+
interface NotificationRecord {
|
|
96
|
+
id: string;
|
|
97
|
+
event: string;
|
|
98
|
+
payload: unknown;
|
|
99
|
+
priority: Priority;
|
|
100
|
+
idempotencyKey: string;
|
|
101
|
+
subject: string | null;
|
|
102
|
+
createdAt: Date;
|
|
103
|
+
}
|
|
104
|
+
interface DeliveryRecord {
|
|
105
|
+
id: string;
|
|
106
|
+
notificationId: string;
|
|
107
|
+
channel: string;
|
|
108
|
+
address: unknown;
|
|
109
|
+
recipientId?: string;
|
|
110
|
+
status: DeliveryStatus;
|
|
111
|
+
attempts: number;
|
|
112
|
+
nextAttemptAt: Date | null;
|
|
113
|
+
leaseUntil: Date | null;
|
|
114
|
+
lastError: string | null;
|
|
115
|
+
createdAt: Date;
|
|
116
|
+
}
|
|
117
|
+
/** A delivery leased to this worker, with the notification data needed to render it. */
|
|
118
|
+
interface ClaimedDelivery extends DeliveryRecord {
|
|
119
|
+
notification: NotificationRecord;
|
|
120
|
+
}
|
|
121
|
+
type DeliveryResult = {
|
|
122
|
+
status: "sent";
|
|
123
|
+
providerId?: string;
|
|
124
|
+
} | {
|
|
125
|
+
status: "retry";
|
|
126
|
+
nextAttemptAt: Date;
|
|
127
|
+
error: string;
|
|
128
|
+
} | {
|
|
129
|
+
status: "dead";
|
|
130
|
+
error: string;
|
|
131
|
+
};
|
|
132
|
+
interface DeliveryQuery {
|
|
133
|
+
recipientId?: string;
|
|
134
|
+
event?: string;
|
|
135
|
+
channel?: string;
|
|
136
|
+
status?: DeliveryStatus;
|
|
137
|
+
subject?: string;
|
|
138
|
+
/** Inclusive lower bound on delivery `createdAt`. */
|
|
139
|
+
since?: Date;
|
|
140
|
+
/** Exclusive upper bound on delivery `createdAt`. */
|
|
141
|
+
until?: Date;
|
|
142
|
+
limit?: number;
|
|
143
|
+
/** Opaque. Pass the previous page's `nextCursor`. Keyset on (createdAt, id), newest first. */
|
|
144
|
+
cursor?: string;
|
|
145
|
+
}
|
|
146
|
+
/** A delivery with the notification fields an admin page needs. */
|
|
147
|
+
interface ListedDelivery extends DeliveryRecord {
|
|
148
|
+
event: string;
|
|
149
|
+
subject: string | null;
|
|
150
|
+
}
|
|
151
|
+
interface DeliveryPage {
|
|
152
|
+
items: ListedDelivery[];
|
|
153
|
+
nextCursor: string | null;
|
|
154
|
+
}
|
|
155
|
+
interface InboxItem {
|
|
156
|
+
id: string;
|
|
157
|
+
recipientId: string;
|
|
158
|
+
notificationId: string;
|
|
159
|
+
title: string;
|
|
160
|
+
body: string;
|
|
161
|
+
data?: unknown;
|
|
162
|
+
createdAt: Date;
|
|
163
|
+
readAt: Date | null;
|
|
164
|
+
}
|
|
165
|
+
interface InboxQuery {
|
|
166
|
+
recipientId: string;
|
|
167
|
+
unreadOnly?: boolean;
|
|
168
|
+
limit?: number;
|
|
169
|
+
cursor?: string;
|
|
170
|
+
}
|
|
171
|
+
interface InboxPage {
|
|
172
|
+
items: InboxItem[];
|
|
173
|
+
nextCursor: string | null;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Persistence contract. Herald never sees a driver type. A store never sees
|
|
177
|
+
* templates, channels or preferences.
|
|
178
|
+
*/
|
|
179
|
+
interface Store {
|
|
180
|
+
/**
|
|
181
|
+
* Atomically insert the notification and its delivery rows. Unique on
|
|
182
|
+
* `idempotencyKey`: a repeat returns the existing id with `created: false`.
|
|
183
|
+
*/
|
|
184
|
+
enqueue(n: NewNotification): Promise<{
|
|
185
|
+
id: string;
|
|
186
|
+
created: boolean;
|
|
187
|
+
}>;
|
|
188
|
+
/**
|
|
189
|
+
* Lease up to `limit` deliveries that are due (`pending`/`retry` with
|
|
190
|
+
* `nextAttemptAt <= now`) or whose lease expired. Sets `leaseUntil = now + leaseMs`
|
|
191
|
+
* and status `sending`. Concurrent callers must never receive the same row
|
|
192
|
+
* (Postgres: `FOR UPDATE SKIP LOCKED`). Lease expiry is what makes a killed
|
|
193
|
+
* worker's rows reappear: delivery is at-least-once.
|
|
194
|
+
*/
|
|
195
|
+
claim(opts: {
|
|
196
|
+
limit: number;
|
|
197
|
+
now: Date;
|
|
198
|
+
leaseMs: number;
|
|
199
|
+
}): Promise<ClaimedDelivery[]>;
|
|
200
|
+
/**
|
|
201
|
+
* Record an attempt outcome: status, attempts, error; clears the lease.
|
|
202
|
+
* Must only apply to a row that is still `sending` (`WHERE status = 'sending'`);
|
|
203
|
+
* otherwise it is a silent no-op. This is what stops a late worker result from
|
|
204
|
+
* un-cancelling a row.
|
|
205
|
+
*/
|
|
206
|
+
recordResult(deliveryId: string, result: DeliveryResult): Promise<void>;
|
|
207
|
+
/**
|
|
208
|
+
* Admin and support visibility. Newest first, keyset-paginated on
|
|
209
|
+
* (createdAt, id), never by offset. Filters combine with AND.
|
|
210
|
+
*/
|
|
211
|
+
listDeliveries(q: DeliveryQuery): Promise<DeliveryPage>;
|
|
212
|
+
/**
|
|
213
|
+
* Re-queue a `dead` delivery: status `pending`, attempts reset to 0 (fresh
|
|
214
|
+
* retry budget), due now. Returns false if the delivery was not `dead`.
|
|
215
|
+
*/
|
|
216
|
+
retryDelivery(deliveryId: string): Promise<boolean>;
|
|
217
|
+
/**
|
|
218
|
+
* Cancel every `pending` or `retry` delivery of notifications with this
|
|
219
|
+
* subject. `sending` rows are already out the door and are left alone, as are
|
|
220
|
+
* terminal rows. Sets status `cancelled` (distinct from `skipped`).
|
|
221
|
+
* Returns the number of deliveries cancelled.
|
|
222
|
+
*/
|
|
223
|
+
cancel(q: {
|
|
224
|
+
subject: string;
|
|
225
|
+
}): Promise<number>;
|
|
226
|
+
/**
|
|
227
|
+
* Retention. Deletes deliveries created before `olderThan` whose status is
|
|
228
|
+
* terminal (default: all terminal statuses), then notifications left with no
|
|
229
|
+
* deliveries. Never deletes `pending`, `retry` or `sending` rows. Does not
|
|
230
|
+
* touch the inbox. Returns the number of deliveries deleted.
|
|
231
|
+
*/
|
|
232
|
+
purge(opts: {
|
|
233
|
+
olderThan: Date;
|
|
234
|
+
statuses?: readonly TerminalStatus[];
|
|
235
|
+
}): Promise<number>;
|
|
236
|
+
getNotification(id: string): Promise<{
|
|
237
|
+
notification: NotificationRecord;
|
|
238
|
+
deliveries: DeliveryRecord[];
|
|
239
|
+
} | null>;
|
|
240
|
+
inboxAdd(item: Omit<InboxItem, "id" | "createdAt" | "readAt">): Promise<InboxItem>;
|
|
241
|
+
inboxList(q: InboxQuery): Promise<InboxPage>;
|
|
242
|
+
inboxMarkRead(recipientId: string, ids: readonly string[]): Promise<void>;
|
|
243
|
+
/** Unread items for the bell badge. */
|
|
244
|
+
inboxUnreadCount(recipientId: string): Promise<number>;
|
|
245
|
+
/** Marks every unread item read. Returns the number of rows updated. */
|
|
246
|
+
inboxMarkAllRead(recipientId: string): Promise<number>;
|
|
247
|
+
/** Create or upgrade Herald's tables. Optional: apps may manage schema themselves. */
|
|
248
|
+
migrate?(): Promise<void>;
|
|
249
|
+
close?(): Promise<void>;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export type { ClaimedDelivery as C, DeliveryInfo as D, Hooks as H, InboxQuery as I, Logger as L, NewDelivery as N, ProcessOptions as P, ResolvePreferences as R, Store as S, Targets as T, ProcessSummary as a, InboxPage as b, ResolveAddress as c, RetryPolicy as d, DeliveryPage as e, DeliveryQuery as f, DeliveryRecord as g, DeliveryResult as h, DeliveryStatus as i, InboxItem as j, ListedDelivery as k, NewNotification as l, NotificationRecord as m, Priority as n, RawTarget as o, RecipientRef as p, TerminalStatus as q };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { S as Store } from './store-BaqPfkS_.js';
|
|
2
|
+
|
|
3
|
+
interface StoreContractOptions {
|
|
4
|
+
/** Shown in the suite title. */
|
|
5
|
+
name: string;
|
|
6
|
+
/** Fresh, empty store for every test. */
|
|
7
|
+
create: () => Promise<{
|
|
8
|
+
store: Store;
|
|
9
|
+
cleanup?: () => Promise<void>;
|
|
10
|
+
}>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The Store contract. Every adapter must pass it. Run it from your own test
|
|
14
|
+
* file: `runStoreContract({ name: "postgres", create })`. Asserts behavior, not
|
|
15
|
+
* id formats: ids are opaque.
|
|
16
|
+
*/
|
|
17
|
+
declare function runStoreContract({ name, create }: StoreContractOptions): void;
|
|
18
|
+
|
|
19
|
+
export { type StoreContractOptions, runStoreContract };
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
// src/testing/index.ts
|
|
2
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
3
|
+
var keySeq = 0;
|
|
4
|
+
async function enqueue(store, spec = {}) {
|
|
5
|
+
const deliveries = (spec.deliveries ?? [{ channel: "slack" }]).map((d, i) => ({
|
|
6
|
+
address: `addr-${i}`,
|
|
7
|
+
recipientId: `u${i}`,
|
|
8
|
+
status: "pending",
|
|
9
|
+
...d
|
|
10
|
+
}));
|
|
11
|
+
const res = await store.enqueue({
|
|
12
|
+
event: spec.event ?? "lead.created",
|
|
13
|
+
payload: { n: 1 },
|
|
14
|
+
priority: "normal",
|
|
15
|
+
idempotencyKey: spec.key ?? `k${++keySeq}`,
|
|
16
|
+
subject: spec.subject ?? null,
|
|
17
|
+
deliveries
|
|
18
|
+
});
|
|
19
|
+
const got = await store.getNotification(res.id);
|
|
20
|
+
return { id: res.id, deliveryIds: (got?.deliveries ?? []).map((d) => d.id), res };
|
|
21
|
+
}
|
|
22
|
+
var status = async (store, nid, did) => (await store.getNotification(nid))?.deliveries.find((d) => d.id === did)?.status;
|
|
23
|
+
var sorted = (ids) => [...ids].sort();
|
|
24
|
+
function runStoreContract({ name, create }) {
|
|
25
|
+
describe(`Store contract: ${name}`, () => {
|
|
26
|
+
let store;
|
|
27
|
+
let cleanup;
|
|
28
|
+
beforeEach(async () => {
|
|
29
|
+
({ store, cleanup } = await create());
|
|
30
|
+
});
|
|
31
|
+
afterEach(async () => {
|
|
32
|
+
await cleanup?.();
|
|
33
|
+
});
|
|
34
|
+
describe("enqueue", () => {
|
|
35
|
+
it("saves the notification and one delivery per row", async () => {
|
|
36
|
+
const { id, deliveryIds } = await enqueue(store, {
|
|
37
|
+
subject: "lead:1",
|
|
38
|
+
deliveries: [{ channel: "slack" }, { channel: "email" }]
|
|
39
|
+
});
|
|
40
|
+
const got = await store.getNotification(id);
|
|
41
|
+
expect(got?.notification).toMatchObject({
|
|
42
|
+
id,
|
|
43
|
+
event: "lead.created",
|
|
44
|
+
subject: "lead:1",
|
|
45
|
+
priority: "normal",
|
|
46
|
+
payload: { n: 1 }
|
|
47
|
+
});
|
|
48
|
+
expect(got?.deliveries).toHaveLength(2);
|
|
49
|
+
expect(deliveryIds).toHaveLength(2);
|
|
50
|
+
expect(got?.deliveries.every((d) => d.status === "pending" && d.attempts === 0)).toBe(true);
|
|
51
|
+
});
|
|
52
|
+
it("is idempotent on the key: same id, created=false, no new rows", async () => {
|
|
53
|
+
const a = await enqueue(store, { key: "same" });
|
|
54
|
+
const b = await enqueue(store, { key: "same", deliveries: [{ channel: "email" }] });
|
|
55
|
+
expect(a.res.created).toBe(true);
|
|
56
|
+
expect(b.res.created).toBe(false);
|
|
57
|
+
expect(b.id).toBe(a.id);
|
|
58
|
+
expect((await store.getNotification(a.id))?.deliveries).toHaveLength(1);
|
|
59
|
+
});
|
|
60
|
+
it("subject is not part of the idempotency key", async () => {
|
|
61
|
+
const a = await enqueue(store, { key: "k-subj", subject: "lead:1" });
|
|
62
|
+
const b = await enqueue(store, { key: "k-subj", subject: "lead:2" });
|
|
63
|
+
expect(b.id).toBe(a.id);
|
|
64
|
+
const c = await enqueue(store, { key: "other", subject: "lead:1" });
|
|
65
|
+
expect(c.id).not.toBe(a.id);
|
|
66
|
+
});
|
|
67
|
+
it("accepts a notification with no deliveries", async () => {
|
|
68
|
+
const { id } = await enqueue(store, { deliveries: [] });
|
|
69
|
+
expect((await store.getNotification(id))?.deliveries).toEqual([]);
|
|
70
|
+
});
|
|
71
|
+
it("stores skipped deliveries as skipped and never claims them", async () => {
|
|
72
|
+
const { deliveryIds } = await enqueue(store, {
|
|
73
|
+
deliveries: [{ channel: "email", address: null, status: "skipped" }]
|
|
74
|
+
});
|
|
75
|
+
expect(deliveryIds).toHaveLength(1);
|
|
76
|
+
expect(await store.claim({ limit: 10, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 })).toEqual([]);
|
|
77
|
+
});
|
|
78
|
+
it("getNotification returns null for an unknown id", async () => {
|
|
79
|
+
expect(await store.getNotification("does-not-exist")).toBeNull();
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
describe("claim", () => {
|
|
83
|
+
it("leases due deliveries: status sending, attempts+1, lease set, notification attached", async () => {
|
|
84
|
+
const { id, deliveryIds } = await enqueue(store);
|
|
85
|
+
const now = /* @__PURE__ */ new Date();
|
|
86
|
+
const claimed = await store.claim({ limit: 10, now, leaseMs: 5e3 });
|
|
87
|
+
expect(claimed).toHaveLength(1);
|
|
88
|
+
const c = claimed[0];
|
|
89
|
+
expect(c.id).toBe(deliveryIds[0]);
|
|
90
|
+
expect(c.status).toBe("sending");
|
|
91
|
+
expect(c.attempts).toBe(1);
|
|
92
|
+
expect(c.leaseUntil?.getTime()).toBe(now.getTime() + 5e3);
|
|
93
|
+
expect(c.notification).toMatchObject({ id, event: "lead.created", payload: { n: 1 } });
|
|
94
|
+
});
|
|
95
|
+
it("respects limit", async () => {
|
|
96
|
+
await enqueue(store, { deliveries: [{ channel: "a" }, { channel: "b" }, { channel: "c" }] });
|
|
97
|
+
expect(await store.claim({ limit: 2, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 })).toHaveLength(2);
|
|
98
|
+
expect(await store.claim({ limit: 2, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 })).toHaveLength(1);
|
|
99
|
+
});
|
|
100
|
+
it("never hands the same delivery to two concurrent callers", async () => {
|
|
101
|
+
await enqueue(store, {
|
|
102
|
+
deliveries: Array.from({ length: 10 }, (_, i) => ({ channel: `c${i}` }))
|
|
103
|
+
});
|
|
104
|
+
const now = /* @__PURE__ */ new Date();
|
|
105
|
+
const results = await Promise.all(
|
|
106
|
+
Array.from({ length: 5 }, () => store.claim({ limit: 10, now, leaseMs: 5e3 }))
|
|
107
|
+
);
|
|
108
|
+
const ids = results.flat().map((d) => d.id);
|
|
109
|
+
expect(ids).toHaveLength(10);
|
|
110
|
+
expect(new Set(ids).size).toBe(10);
|
|
111
|
+
});
|
|
112
|
+
it("does not re-claim a leased row until the lease expires, then reclaims it (crash recovery)", async () => {
|
|
113
|
+
const { deliveryIds } = await enqueue(store);
|
|
114
|
+
const t0 = /* @__PURE__ */ new Date();
|
|
115
|
+
await store.claim({ limit: 10, now: t0, leaseMs: 1e3 });
|
|
116
|
+
expect(await store.claim({ limit: 10, now: new Date(t0.getTime() + 500), leaseMs: 1e3 })).toEqual([]);
|
|
117
|
+
const again = await store.claim({ limit: 10, now: new Date(t0.getTime() + 1500), leaseMs: 1e3 });
|
|
118
|
+
expect(again.map((d) => d.id)).toEqual(deliveryIds);
|
|
119
|
+
expect(again[0].attempts).toBe(2);
|
|
120
|
+
});
|
|
121
|
+
it("claims a retry row only once nextAttemptAt has passed", async () => {
|
|
122
|
+
const { id, deliveryIds } = await enqueue(store);
|
|
123
|
+
const t0 = /* @__PURE__ */ new Date();
|
|
124
|
+
await store.claim({ limit: 10, now: t0, leaseMs: 1e3 });
|
|
125
|
+
const due = new Date(t0.getTime() + 6e4);
|
|
126
|
+
await store.recordResult(deliveryIds[0], { status: "retry", nextAttemptAt: due, error: "boom" });
|
|
127
|
+
expect(await status(store, id, deliveryIds[0])).toBe("retry");
|
|
128
|
+
expect(await store.claim({ limit: 10, now: new Date(t0.getTime() + 3e4), leaseMs: 1e3 })).toEqual([]);
|
|
129
|
+
const claimed = await store.claim({ limit: 10, now: new Date(due.getTime() + 1), leaseMs: 1e3 });
|
|
130
|
+
expect(claimed).toHaveLength(1);
|
|
131
|
+
expect(claimed[0].attempts).toBe(2);
|
|
132
|
+
});
|
|
133
|
+
it("never claims sent, dead or cancelled rows", async () => {
|
|
134
|
+
await enqueue(store, { subject: "gone" });
|
|
135
|
+
expect(await store.cancel({ subject: "gone" })).toBe(1);
|
|
136
|
+
await enqueue(store, { deliveries: [{ channel: "b" }, { channel: "c" }] });
|
|
137
|
+
const claimed = await store.claim({ limit: 10, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 });
|
|
138
|
+
expect(claimed).toHaveLength(2);
|
|
139
|
+
await store.recordResult(claimed[0].id, { status: "sent" });
|
|
140
|
+
await store.recordResult(claimed[1].id, { status: "dead", error: "x" });
|
|
141
|
+
const far = new Date(Date.now() + 1e7);
|
|
142
|
+
expect(await store.claim({ limit: 10, now: far, leaseMs: 1e3 })).toEqual([]);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
describe("recordResult", () => {
|
|
146
|
+
it("sent: status sent, lease cleared, attempts unchanged", async () => {
|
|
147
|
+
const { id, deliveryIds } = await enqueue(store);
|
|
148
|
+
await store.claim({ limit: 1, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 });
|
|
149
|
+
await store.recordResult(deliveryIds[0], { status: "sent", providerId: "p1" });
|
|
150
|
+
const d = (await store.getNotification(id)).deliveries[0];
|
|
151
|
+
expect(d).toMatchObject({ status: "sent", attempts: 1, leaseUntil: null, lastError: null });
|
|
152
|
+
});
|
|
153
|
+
it("retry: stores error and nextAttemptAt, clears lease", async () => {
|
|
154
|
+
const { id, deliveryIds } = await enqueue(store);
|
|
155
|
+
await store.claim({ limit: 1, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 });
|
|
156
|
+
const at = new Date(Date.now() + 6e4);
|
|
157
|
+
await store.recordResult(deliveryIds[0], { status: "retry", nextAttemptAt: at, error: "429" });
|
|
158
|
+
const d = (await store.getNotification(id)).deliveries[0];
|
|
159
|
+
expect(d.status).toBe("retry");
|
|
160
|
+
expect(d.lastError).toBe("429");
|
|
161
|
+
expect(d.nextAttemptAt?.getTime()).toBe(at.getTime());
|
|
162
|
+
expect(d.leaseUntil).toBeNull();
|
|
163
|
+
});
|
|
164
|
+
it("dead: status dead with the error", async () => {
|
|
165
|
+
const { id, deliveryIds } = await enqueue(store);
|
|
166
|
+
await store.claim({ limit: 1, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 });
|
|
167
|
+
await store.recordResult(deliveryIds[0], { status: "dead", error: "bad address" });
|
|
168
|
+
const d = (await store.getNotification(id)).deliveries[0];
|
|
169
|
+
expect(d).toMatchObject({ status: "dead", lastError: "bad address", leaseUntil: null });
|
|
170
|
+
});
|
|
171
|
+
it("is a no-op unless the row is still sending (a late result cannot un-cancel)", async () => {
|
|
172
|
+
const { id, deliveryIds } = await enqueue(store, { subject: "late" });
|
|
173
|
+
await store.claim({ limit: 1, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 });
|
|
174
|
+
expect(await store.cancel({ subject: "late" })).toBe(0);
|
|
175
|
+
const other = await enqueue(store, { subject: "cancel-me" });
|
|
176
|
+
expect(await store.cancel({ subject: "cancel-me" })).toBe(1);
|
|
177
|
+
await store.recordResult(other.deliveryIds[0], { status: "sent" });
|
|
178
|
+
expect(await status(store, other.id, other.deliveryIds[0])).toBe("cancelled");
|
|
179
|
+
const pending = await enqueue(store);
|
|
180
|
+
await store.recordResult(pending.deliveryIds[0], { status: "dead", error: "x" });
|
|
181
|
+
expect(await status(store, pending.id, pending.deliveryIds[0])).toBe("pending");
|
|
182
|
+
expect(await status(store, id, deliveryIds[0])).toBe("sending");
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
describe("listDeliveries", () => {
|
|
186
|
+
it("filters by recipient, event, channel, status and subject", async () => {
|
|
187
|
+
const a = await enqueue(store, {
|
|
188
|
+
event: "lead.created",
|
|
189
|
+
subject: "lead:1",
|
|
190
|
+
deliveries: [
|
|
191
|
+
{ channel: "slack", recipientId: "alice" },
|
|
192
|
+
{ channel: "email", recipientId: "bob" }
|
|
193
|
+
]
|
|
194
|
+
});
|
|
195
|
+
const b = await enqueue(store, {
|
|
196
|
+
event: "deal.won",
|
|
197
|
+
subject: "deal:9",
|
|
198
|
+
deliveries: [{ channel: "slack", recipientId: "alice" }]
|
|
199
|
+
});
|
|
200
|
+
const ids = async (q) => sorted((await store.listDeliveries(q)).items.map((d) => d.id));
|
|
201
|
+
expect(await ids({})).toEqual(sorted([...a.deliveryIds, ...b.deliveryIds]));
|
|
202
|
+
expect(await ids({ recipientId: "alice" })).toHaveLength(2);
|
|
203
|
+
expect(await ids({ event: "deal.won" })).toEqual(sorted(b.deliveryIds));
|
|
204
|
+
expect(await ids({ channel: "email" })).toHaveLength(1);
|
|
205
|
+
expect(await ids({ subject: "lead:1" })).toEqual(sorted(a.deliveryIds));
|
|
206
|
+
expect(await ids({ status: "pending" })).toHaveLength(3);
|
|
207
|
+
expect(await ids({ status: "sent" })).toEqual([]);
|
|
208
|
+
expect(await ids({ recipientId: "alice", channel: "slack", subject: "deal:9" })).toEqual(
|
|
209
|
+
sorted(b.deliveryIds)
|
|
210
|
+
);
|
|
211
|
+
});
|
|
212
|
+
it("items carry the event and subject", async () => {
|
|
213
|
+
await enqueue(store, { event: "deal.won", subject: "deal:9" });
|
|
214
|
+
const [item] = (await store.listDeliveries({})).items;
|
|
215
|
+
expect(item).toMatchObject({ event: "deal.won", subject: "deal:9" });
|
|
216
|
+
});
|
|
217
|
+
it("filters by createdAt window (since inclusive, until exclusive)", async () => {
|
|
218
|
+
await enqueue(store);
|
|
219
|
+
const future = new Date(Date.now() + 36e5);
|
|
220
|
+
const past = /* @__PURE__ */ new Date(0);
|
|
221
|
+
expect((await store.listDeliveries({ since: past })).items).toHaveLength(1);
|
|
222
|
+
expect((await store.listDeliveries({ since: future })).items).toHaveLength(0);
|
|
223
|
+
expect((await store.listDeliveries({ until: future })).items).toHaveLength(1);
|
|
224
|
+
expect((await store.listDeliveries({ until: past })).items).toHaveLength(0);
|
|
225
|
+
});
|
|
226
|
+
it("paginates newest first with no duplicates or gaps", async () => {
|
|
227
|
+
const all = [];
|
|
228
|
+
for (let i = 0; i < 7; i++) all.push(...(await enqueue(store, { subject: "p" })).deliveryIds);
|
|
229
|
+
const seen = [];
|
|
230
|
+
let cursor;
|
|
231
|
+
let pages = 0;
|
|
232
|
+
do {
|
|
233
|
+
const p = await store.listDeliveries({ subject: "p", limit: 3, cursor });
|
|
234
|
+
expect(p.items.length).toBeLessThanOrEqual(3);
|
|
235
|
+
seen.push(...p.items);
|
|
236
|
+
cursor = p.nextCursor ?? void 0;
|
|
237
|
+
pages += 1;
|
|
238
|
+
} while (cursor && pages < 10);
|
|
239
|
+
expect(pages).toBe(3);
|
|
240
|
+
expect(sorted(seen.map((d) => d.id))).toEqual(sorted(all));
|
|
241
|
+
expect(new Set(seen.map((d) => d.id)).size).toBe(7);
|
|
242
|
+
for (let i = 1; i < seen.length; i++) {
|
|
243
|
+
const prev = seen[i - 1];
|
|
244
|
+
const cur = seen[i];
|
|
245
|
+
const t = prev.createdAt.getTime() - cur.createdAt.getTime();
|
|
246
|
+
expect(t > 0 || t === 0 && prev.id > cur.id).toBe(true);
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
it("returns nextCursor null when everything fits", async () => {
|
|
250
|
+
await enqueue(store);
|
|
251
|
+
expect((await store.listDeliveries({ limit: 10 })).nextCursor).toBeNull();
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
describe("retryDelivery", () => {
|
|
255
|
+
it("revives a dead delivery as pending with attempts reset, due now", async () => {
|
|
256
|
+
const { id, deliveryIds } = await enqueue(store);
|
|
257
|
+
await store.claim({ limit: 1, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 });
|
|
258
|
+
await store.recordResult(deliveryIds[0], { status: "dead", error: "x" });
|
|
259
|
+
expect(await store.retryDelivery(deliveryIds[0])).toBe(true);
|
|
260
|
+
const d = (await store.getNotification(id)).deliveries[0];
|
|
261
|
+
expect(d).toMatchObject({ status: "pending", attempts: 0, leaseUntil: null });
|
|
262
|
+
const claimed = await store.claim({ limit: 1, now: /* @__PURE__ */ new Date(), leaseMs: 1e3 });
|
|
263
|
+
expect(claimed[0].attempts).toBe(1);
|
|
264
|
+
});
|
|
265
|
+
it("returns false for non-dead or unknown deliveries", async () => {
|
|
266
|
+
const { deliveryIds } = await enqueue(store);
|
|
267
|
+
expect(await store.retryDelivery(deliveryIds[0])).toBe(false);
|
|
268
|
+
expect(await store.retryDelivery("nope")).toBe(false);
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
describe("cancel", () => {
|
|
272
|
+
it("cancels pending and retry rows of that subject only; leaves sending and sent; returns the count", async () => {
|
|
273
|
+
const target = await enqueue(store, {
|
|
274
|
+
subject: "lead:42",
|
|
275
|
+
deliveries: [{ channel: "a" }, { channel: "b" }, { channel: "c" }]
|
|
276
|
+
});
|
|
277
|
+
const other = await enqueue(store, { subject: "lead:43" });
|
|
278
|
+
const claimed = await store.claim({ limit: 10, now: /* @__PURE__ */ new Date(), leaseMs: 6e4 });
|
|
279
|
+
const mine = claimed.filter((c) => target.deliveryIds.includes(c.id));
|
|
280
|
+
expect(mine).toHaveLength(3);
|
|
281
|
+
await store.recordResult(mine[0].id, { status: "sent" });
|
|
282
|
+
await store.recordResult(mine[1].id, {
|
|
283
|
+
status: "retry",
|
|
284
|
+
nextAttemptAt: new Date(Date.now() + 6e4),
|
|
285
|
+
error: "e"
|
|
286
|
+
});
|
|
287
|
+
const late = await enqueue(store, { subject: "lead:42" });
|
|
288
|
+
expect(await store.cancel({ subject: "lead:42" })).toBe(2);
|
|
289
|
+
const rows = (await store.getNotification(target.id)).deliveries;
|
|
290
|
+
const by = (st) => rows.filter((d) => d.status === st).length;
|
|
291
|
+
expect([by("sent"), by("cancelled"), by("sending")]).toEqual([1, 1, 1]);
|
|
292
|
+
expect(await status(store, late.id, late.deliveryIds[0])).toBe("cancelled");
|
|
293
|
+
expect(await status(store, other.id, other.deliveryIds[0])).toBe("sending");
|
|
294
|
+
expect(await store.cancel({ subject: "lead:42" })).toBe(0);
|
|
295
|
+
expect(await store.cancel({ subject: "unknown" })).toBe(0);
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
describe("purge", () => {
|
|
299
|
+
const future = () => new Date(Date.now() + 36e5);
|
|
300
|
+
const finish = (did, result) => store.recordResult(did, result === "sent" ? { status: "sent" } : { status: "dead", error: "x" });
|
|
301
|
+
it("deletes only terminal deliveries older than the cutoff and returns the count", async () => {
|
|
302
|
+
const done = await enqueue(store, { deliveries: [{ channel: "a" }, { channel: "b" }] });
|
|
303
|
+
const live = await enqueue(store, { deliveries: [{ channel: "c" }] });
|
|
304
|
+
const claimed = await store.claim({ limit: 2, now: /* @__PURE__ */ new Date(), leaseMs: 6e4 });
|
|
305
|
+
const doneIds = claimed.filter((c) => done.deliveryIds.includes(c.id)).map((c) => c.id);
|
|
306
|
+
for (const id of doneIds) await finish(id, "sent");
|
|
307
|
+
expect(await store.purge({ olderThan: /* @__PURE__ */ new Date(0) })).toBe(0);
|
|
308
|
+
const n = await store.purge({ olderThan: future() });
|
|
309
|
+
expect(n).toBe(doneIds.length);
|
|
310
|
+
expect(await store.getNotification(live.id)).not.toBeNull();
|
|
311
|
+
expect((await store.getNotification(live.id)).deliveries).toHaveLength(1);
|
|
312
|
+
});
|
|
313
|
+
it("never deletes pending, retry or sending rows", async () => {
|
|
314
|
+
const a = await enqueue(store, { deliveries: [{ channel: "a" }, { channel: "b" }, { channel: "c" }] });
|
|
315
|
+
const claimed = await store.claim({ limit: 2, now: /* @__PURE__ */ new Date(), leaseMs: 6e4 });
|
|
316
|
+
await store.recordResult(claimed[0].id, {
|
|
317
|
+
status: "retry",
|
|
318
|
+
nextAttemptAt: new Date(Date.now() + 6e4),
|
|
319
|
+
error: "e"
|
|
320
|
+
});
|
|
321
|
+
expect(await store.purge({ olderThan: future() })).toBe(0);
|
|
322
|
+
expect((await store.getNotification(a.id)).deliveries).toHaveLength(3);
|
|
323
|
+
});
|
|
324
|
+
it("narrows by statuses", async () => {
|
|
325
|
+
const a = await enqueue(store, { deliveries: [{ channel: "a" }, { channel: "b" }] });
|
|
326
|
+
const claimed = await store.claim({ limit: 2, now: /* @__PURE__ */ new Date(), leaseMs: 6e4 });
|
|
327
|
+
await finish(claimed[0].id, "sent");
|
|
328
|
+
await finish(claimed[1].id, "dead");
|
|
329
|
+
expect(await store.purge({ olderThan: future(), statuses: ["dead"] })).toBe(1);
|
|
330
|
+
const left = (await store.getNotification(a.id)).deliveries;
|
|
331
|
+
expect(left).toHaveLength(1);
|
|
332
|
+
expect(left[0].status).toBe("sent");
|
|
333
|
+
});
|
|
334
|
+
it("removes notifications left with no deliveries, keeps the rest", async () => {
|
|
335
|
+
const gone = await enqueue(store);
|
|
336
|
+
const kept = await enqueue(store);
|
|
337
|
+
const claimed = await store.claim({ limit: 10, now: /* @__PURE__ */ new Date(), leaseMs: 6e4 });
|
|
338
|
+
const goneDelivery = claimed.find((c) => c.id === gone.deliveryIds[0]);
|
|
339
|
+
await finish(goneDelivery.id, "sent");
|
|
340
|
+
await store.purge({ olderThan: future() });
|
|
341
|
+
expect(await store.getNotification(gone.id)).toBeNull();
|
|
342
|
+
expect(await store.getNotification(kept.id)).not.toBeNull();
|
|
343
|
+
});
|
|
344
|
+
it("does not touch the inbox", async () => {
|
|
345
|
+
await store.inboxAdd({ recipientId: "u1", notificationId: "n", title: "t", body: "b" });
|
|
346
|
+
await store.purge({ olderThan: future() });
|
|
347
|
+
expect((await store.inboxList({ recipientId: "u1" })).items).toHaveLength(1);
|
|
348
|
+
});
|
|
349
|
+
});
|
|
350
|
+
describe("inbox", () => {
|
|
351
|
+
const add = (recipientId, title = "t") => store.inboxAdd({ recipientId, notificationId: "n1", title, body: "b" });
|
|
352
|
+
it("adds unread items and lists newest first with a cursor", async () => {
|
|
353
|
+
for (let i = 0; i < 5; i++) await add("u1", `t${i}`);
|
|
354
|
+
await add("u2");
|
|
355
|
+
const p1 = await store.inboxList({ recipientId: "u1", limit: 2 });
|
|
356
|
+
expect(p1.items).toHaveLength(2);
|
|
357
|
+
expect(p1.nextCursor).not.toBeNull();
|
|
358
|
+
expect(p1.items.every((i) => i.readAt === null && i.recipientId === "u1")).toBe(true);
|
|
359
|
+
const seen = [...p1.items];
|
|
360
|
+
let cursor = p1.nextCursor ?? void 0;
|
|
361
|
+
let guard = 0;
|
|
362
|
+
while (cursor && guard++ < 10) {
|
|
363
|
+
const p = await store.inboxList({ recipientId: "u1", limit: 2, cursor });
|
|
364
|
+
seen.push(...p.items);
|
|
365
|
+
cursor = p.nextCursor ?? void 0;
|
|
366
|
+
}
|
|
367
|
+
expect(new Set(seen.map((i) => i.id)).size).toBe(5);
|
|
368
|
+
});
|
|
369
|
+
it("unreadOnly and unread count follow markRead", async () => {
|
|
370
|
+
const a = await add("u1");
|
|
371
|
+
await add("u1");
|
|
372
|
+
expect(await store.inboxUnreadCount("u1")).toBe(2);
|
|
373
|
+
await store.inboxMarkRead("u1", [a.id]);
|
|
374
|
+
expect(await store.inboxUnreadCount("u1")).toBe(1);
|
|
375
|
+
expect((await store.inboxList({ recipientId: "u1", unreadOnly: true })).items).toHaveLength(1);
|
|
376
|
+
const read = (await store.inboxList({ recipientId: "u1" })).items.find((i) => i.id === a.id);
|
|
377
|
+
expect(read?.readAt).not.toBeNull();
|
|
378
|
+
});
|
|
379
|
+
it("markRead ignores ids that belong to another recipient", async () => {
|
|
380
|
+
const mine = await add("u1");
|
|
381
|
+
const theirs = await add("u2");
|
|
382
|
+
await store.inboxMarkRead("u1", [mine.id, theirs.id]);
|
|
383
|
+
expect(await store.inboxUnreadCount("u1")).toBe(0);
|
|
384
|
+
expect(await store.inboxUnreadCount("u2")).toBe(1);
|
|
385
|
+
});
|
|
386
|
+
it("markAllRead returns the number updated and is scoped to the recipient", async () => {
|
|
387
|
+
await add("u1");
|
|
388
|
+
await add("u1");
|
|
389
|
+
await add("u2");
|
|
390
|
+
expect(await store.inboxMarkAllRead("u1")).toBe(2);
|
|
391
|
+
expect(await store.inboxMarkAllRead("u1")).toBe(0);
|
|
392
|
+
expect(await store.inboxUnreadCount("u2")).toBe(1);
|
|
393
|
+
});
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
export {
|
|
398
|
+
runStoreContract
|
|
399
|
+
};
|
|
400
|
+
//# sourceMappingURL=testing.js.map
|