@venturekit/notify 0.0.0-dev.20260507015349

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.
Files changed (75) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +304 -0
  3. package/dist/admin/index.d.ts +88 -0
  4. package/dist/admin/index.d.ts.map +1 -0
  5. package/dist/admin/index.js +105 -0
  6. package/dist/admin/index.js.map +1 -0
  7. package/dist/bounce-handler.d.ts +65 -0
  8. package/dist/bounce-handler.d.ts.map +1 -0
  9. package/dist/bounce-handler.js +171 -0
  10. package/dist/bounce-handler.js.map +1 -0
  11. package/dist/client.d.ts +113 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +213 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/dispatcher.d.ts +95 -0
  16. package/dist/dispatcher.d.ts.map +1 -0
  17. package/dist/dispatcher.js +251 -0
  18. package/dist/dispatcher.js.map +1 -0
  19. package/dist/index.d.ts +60 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +66 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/providers/email-noop.d.ts +30 -0
  24. package/dist/providers/email-noop.d.ts.map +1 -0
  25. package/dist/providers/email-noop.js +39 -0
  26. package/dist/providers/email-noop.js.map +1 -0
  27. package/dist/providers/email-ses.d.ts +39 -0
  28. package/dist/providers/email-ses.d.ts.map +1 -0
  29. package/dist/providers/email-ses.js +114 -0
  30. package/dist/providers/email-ses.js.map +1 -0
  31. package/dist/providers/index.d.ts +20 -0
  32. package/dist/providers/index.d.ts.map +1 -0
  33. package/dist/providers/index.js +20 -0
  34. package/dist/providers/index.js.map +1 -0
  35. package/dist/providers/push-noop.d.ts +12 -0
  36. package/dist/providers/push-noop.d.ts.map +1 -0
  37. package/dist/providers/push-noop.js +30 -0
  38. package/dist/providers/push-noop.js.map +1 -0
  39. package/dist/providers/sms-noop.d.ts +21 -0
  40. package/dist/providers/sms-noop.d.ts.map +1 -0
  41. package/dist/providers/sms-noop.js +42 -0
  42. package/dist/providers/sms-noop.js.map +1 -0
  43. package/dist/providers/types.d.ts +95 -0
  44. package/dist/providers/types.d.ts.map +1 -0
  45. package/dist/providers/types.js +40 -0
  46. package/dist/providers/types.js.map +1 -0
  47. package/dist/providers/whatsapp-meta.d.ts +63 -0
  48. package/dist/providers/whatsapp-meta.d.ts.map +1 -0
  49. package/dist/providers/whatsapp-meta.js +160 -0
  50. package/dist/providers/whatsapp-meta.js.map +1 -0
  51. package/dist/store/index.d.ts +6 -0
  52. package/dist/store/index.d.ts.map +1 -0
  53. package/dist/store/index.js +5 -0
  54. package/dist/store/index.js.map +1 -0
  55. package/dist/store/postgres.d.ts +36 -0
  56. package/dist/store/postgres.d.ts.map +1 -0
  57. package/dist/store/postgres.js +354 -0
  58. package/dist/store/postgres.js.map +1 -0
  59. package/dist/store/types.d.ts +139 -0
  60. package/dist/store/types.d.ts.map +1 -0
  61. package/dist/store/types.js +14 -0
  62. package/dist/store/types.js.map +1 -0
  63. package/dist/templates/registry.d.ts +55 -0
  64. package/dist/templates/registry.d.ts.map +1 -0
  65. package/dist/templates/registry.js +94 -0
  66. package/dist/templates/registry.js.map +1 -0
  67. package/dist/types.d.ts +214 -0
  68. package/dist/types.d.ts.map +1 -0
  69. package/dist/types.js +12 -0
  70. package/dist/types.js.map +1 -0
  71. package/migrations/vk_notify_001_init.sql +109 -0
  72. package/package.json +109 -0
  73. package/runtime/bounce-handler-stub.ts +35 -0
  74. package/runtime/dispatcher-stub.ts +63 -0
  75. package/runtime/tsconfig.json +19 -0
package/dist/client.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * @venturekit/notify — runtime client
3
+ *
4
+ * The runtime API consumers use:
5
+ * - `notify.enqueue({ recipientUserId, channel, templateKey, payload })`
6
+ * writes a row to the outbox.
7
+ * - `notify.registerTemplate({...})` adds a render function.
8
+ * - `notify.registerProvider(provider)` swaps in a custom provider
9
+ * for a given channel (e.g. wire MailHog locally, Twilio for SMS).
10
+ *
11
+ * The client never sends synchronously — the dispatcher cron picks rows
12
+ * up. Synchronous send is technically possible (skip the outbox by
13
+ * calling provider.send directly) but Phase 1 deliberately doesn't
14
+ * expose that path: the outbox is what makes retries, audit logging,
15
+ * and bounce-suppression work, so bypassing it loses too much value.
16
+ *
17
+ * For a project that genuinely doesn't need an outbox (small marketing
18
+ * site, dev preview), set `NotifyIntent.tracking = 'none'`. The infra
19
+ * package wires a memory-backed store in that mode and the dispatcher
20
+ * is provisioned but does nothing — the next-tick re-pickup window
21
+ * collapses to "synchronous-ish" because each call ends up dispatching
22
+ * within seconds.
23
+ */
24
+ import { createTemplateRegistry, } from './templates/registry.js';
25
+ /**
26
+ * Create a notify client. Most projects construct one at module scope:
27
+ *
28
+ * ```ts
29
+ * // src/lib/notify.ts
30
+ * import { createNotifyClient, createPostgresNotifyStore,
31
+ * createSesEmailProvider, createMetaWhatsAppProvider,
32
+ * createSecretsTokenResolver } from '@venturekit/notify';
33
+ *
34
+ * export const notify = createNotifyClient({
35
+ * store: createPostgresNotifyStore(),
36
+ * defaultFrom: process.env.VENTURE_NOTIFY_FROM,
37
+ * providers: [
38
+ * createSesEmailProvider({
39
+ * region: process.env.AWS_REGION!,
40
+ * configurationSetName: process.env.VENTURE_NOTIFY_CONFIG_SET,
41
+ * }),
42
+ * createMetaWhatsAppProvider({
43
+ * phoneNumberId: process.env.VENTURE_NOTIFY_WHATSAPP_PHONE_ID!,
44
+ * tokenResolver: createSecretsTokenResolver({
45
+ * secretArn: process.env.VENTURE_NOTIFY_WHATSAPP_TOKEN_SECRET!,
46
+ * }),
47
+ * }),
48
+ * ],
49
+ * });
50
+ * ```
51
+ */
52
+ export function createNotifyClient(options) {
53
+ const templates = options.templates ?? createTemplateRegistry();
54
+ const providers = new Map();
55
+ for (const p of options.providers ?? [])
56
+ providers.set(p.channel, p);
57
+ const client = {
58
+ store: options.store,
59
+ templates,
60
+ providers,
61
+ defaultFrom: options.defaultFrom,
62
+ addressResolver: options.addressResolver,
63
+ registerTemplate(template) {
64
+ templates.register(template);
65
+ },
66
+ registerTemplates(list) {
67
+ templates.registerAll(list);
68
+ },
69
+ registerProvider(provider) {
70
+ providers.set(provider.channel, provider);
71
+ },
72
+ async enqueue(input) {
73
+ // Pre-flight checks before persisting:
74
+ //
75
+ // 1. The (templateKey, channel) must be registered. We catch this
76
+ // at enqueue time so the calling code gets a synchronous error
77
+ // on first call rather than a row stuck in 'failed' that's
78
+ // only visible to whoever monitors the outbox dashboard.
79
+ if (!templates.has(input.templateKey, input.channel)) {
80
+ // Persist the row anyway so the failure is auditable, but
81
+ // mark it 'failed' immediately. This way the operator can
82
+ // grep CloudWatch for `[notify] template missing` and find
83
+ // the matching row in the outbox.
84
+ const row = await options.store.createNotification({
85
+ recipientUserId: input.recipientUserId ?? null,
86
+ address: input.address ?? null,
87
+ channel: input.channel,
88
+ templateKey: input.templateKey,
89
+ payload: input.payload,
90
+ scheduledForISO: input.scheduledForISO,
91
+ relatedKind: input.relatedKind,
92
+ relatedId: input.relatedId,
93
+ });
94
+ await options.store.updateStatus({
95
+ id: row.id,
96
+ status: 'failed',
97
+ error: `Template '${input.templateKey}' (${input.channel}) is not registered`,
98
+ });
99
+ return { id: row.id, channel: input.channel, suppressed: true,
100
+ suppressionReason: 'no-channel-provider' };
101
+ }
102
+ // 2. The channel needs a provider. Same audit-trail logic as
103
+ // above — failed rows surface in the admin UI.
104
+ if (!providers.has(input.channel)) {
105
+ const row = await options.store.createNotification({
106
+ recipientUserId: input.recipientUserId ?? null,
107
+ address: input.address ?? null,
108
+ channel: input.channel,
109
+ templateKey: input.templateKey,
110
+ payload: input.payload,
111
+ scheduledForISO: input.scheduledForISO,
112
+ relatedKind: input.relatedKind,
113
+ relatedId: input.relatedId,
114
+ });
115
+ await options.store.updateStatus({
116
+ id: row.id,
117
+ status: 'failed',
118
+ error: `No provider registered for channel '${input.channel}'`,
119
+ });
120
+ return { id: row.id, channel: input.channel, suppressed: true,
121
+ suppressionReason: 'no-channel-provider' };
122
+ }
123
+ // 3. Either recipient or address must be set. Validate at
124
+ // enqueue time — a missing address is a programmer error,
125
+ // not a runtime concern.
126
+ if (!input.recipientUserId && !input.address) {
127
+ throw new Error('notify.enqueue: at least one of `recipientUserId` or `address` is required');
128
+ }
129
+ // 4. Preferences gate: only checked when we have a userId AND
130
+ // the template declares a category. Bypass gating for
131
+ // templates without a category so transactional sends (e.g.
132
+ // password reset) can never be opted out of.
133
+ const tpl = templates.get(input.templateKey, input.channel);
134
+ if (input.recipientUserId && tpl.category) {
135
+ const optedIn = await options.store.isOptedIn(input.recipientUserId, input.channel, tpl.category);
136
+ if (!optedIn) {
137
+ // Persist a 'cancelled' row so the audit trail records the
138
+ // suppression — useful for compliance reviews.
139
+ const row = await options.store.createNotification({
140
+ recipientUserId: input.recipientUserId,
141
+ address: input.address ?? null,
142
+ channel: input.channel,
143
+ templateKey: input.templateKey,
144
+ payload: input.payload,
145
+ scheduledForISO: input.scheduledForISO,
146
+ relatedKind: input.relatedKind,
147
+ relatedId: input.relatedId,
148
+ });
149
+ await options.store.updateStatus({
150
+ id: row.id,
151
+ status: 'cancelled',
152
+ error: `User opted out of channel '${input.channel}' for category '${tpl.category}'`,
153
+ });
154
+ return {
155
+ id: row.id,
156
+ channel: input.channel,
157
+ suppressed: true,
158
+ suppressionReason: 'opted-out',
159
+ };
160
+ }
161
+ }
162
+ // 5. Address-level suppression check. Only meaningful when we
163
+ // already have an address; the resolver path runs again in
164
+ // the dispatcher and re-checks suppression there, so user-id
165
+ // callers don't get a false-positive at enqueue.
166
+ if (input.address) {
167
+ const suppressed = await options.store.isAddressSuppressed(input.channel, input.address);
168
+ if (suppressed) {
169
+ const row = await options.store.createNotification({
170
+ recipientUserId: input.recipientUserId ?? null,
171
+ address: input.address,
172
+ channel: input.channel,
173
+ templateKey: input.templateKey,
174
+ payload: input.payload,
175
+ scheduledForISO: input.scheduledForISO,
176
+ relatedKind: input.relatedKind,
177
+ relatedId: input.relatedId,
178
+ });
179
+ await options.store.updateStatus({
180
+ id: row.id,
181
+ status: 'cancelled',
182
+ error: `Address '${input.address}' is suppressed (prior bounce / complaint)`,
183
+ });
184
+ return {
185
+ id: row.id,
186
+ channel: input.channel,
187
+ suppressed: true,
188
+ suppressionReason: 'address-suppressed',
189
+ };
190
+ }
191
+ }
192
+ // Happy path: persist, return.
193
+ const row = await options.store.createNotification({
194
+ recipientUserId: input.recipientUserId ?? null,
195
+ address: input.address ?? null,
196
+ channel: input.channel,
197
+ templateKey: input.templateKey,
198
+ payload: input.payload,
199
+ scheduledForISO: input.scheduledForISO,
200
+ relatedKind: input.relatedKind,
201
+ relatedId: input.relatedId,
202
+ });
203
+ return { id: row.id, channel: input.channel, suppressed: false };
204
+ },
205
+ };
206
+ return client;
207
+ }
208
+ // Note: a `createTestNotifyClient` helper backed by an in-memory store
209
+ // is intentionally omitted in Phase 1 — see `src/store/memory.ts` once
210
+ // it lands. Tests today should call `createNotifyClient()` directly
211
+ // with a hand-rolled `NotifyStore` mock; the surface area is small
212
+ // enough that mocking is cheaper than a shared helper.
213
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EACL,sBAAsB,GAEvB,MAAM,yBAAyB,CAAC;AA6EjC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAkC;IAElC,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,sBAAsB,EAAE,CAAC;IAChE,MAAM,SAAS,GAAG,IAAI,GAAG,EAAiC,CAAC;IAC3D,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,SAAS,IAAI,EAAE;QAAE,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAErE,MAAM,MAAM,GAAiB;QAC3B,KA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I,IAAI;gBAC9C,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,IAAI;gBAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,WAAW,EAAE,KAAK,CAAC,WAAW;gBAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,WAAW,EAAE,KAAK,CAAC,WAAW;gBAC9B,SAAS,EAAE,KAAK,CAAC,SAAS;aAC3B,CAAC,CAAC;YACH,OAAO,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;QACnE,CAAC;KACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,uEAAuE;AACvE,uEAAuE;AACvE,oEAAoE;AACpE,mEAAmE;AACnE,uDAAuD"}
@@ -0,0 +1,95 @@
1
+ /**
2
+ * @venturekit/notify — outbox dispatcher
3
+ *
4
+ * Drains pending rows from the outbox and calls each row's provider.
5
+ * Designed to run on a cron schedule (1 invocation per minute by
6
+ * default — `NotifyIntent.dispatchRateMinutes`). Two execution modes:
7
+ *
8
+ * 1. **Cron Lambda (production)** — `dispatchHandler` is exported as
9
+ * a `taskHandler`-compatible function. The infra package wires
10
+ * this as the EventBridge target Lambda for the auto-provisioned
11
+ * cron rule.
12
+ * 2. **Programmatic (tests / one-off CLI)** — `dispatchOnce(client,
13
+ * options)` runs a single sweep and returns the per-row outcome
14
+ * list. No timers, no recursion.
15
+ *
16
+ * The dispatcher is **at-least-once**: a row whose provider call
17
+ * succeeds but whose status update fails (because the DB connection
18
+ * dropped between SES accepting the SendEmail and Postgres committing
19
+ * the UPDATE) will be re-claimed on the next tick and re-sent. The
20
+ * SES `Notify-Id` tag (and Meta `biz_opaque_callback_data`) carry the
21
+ * outbox row id so duplicate detection at the provider level is
22
+ * possible — but Phase 1 doesn't ship server-side dedup. Templates
23
+ * should be designed with idempotency in mind (recipients of a
24
+ * duplicate password-reset email aren't surprised; transactional
25
+ * receipts may want a `notif_id` line in the body to make duplicates
26
+ * obvious).
27
+ *
28
+ * Throughput targets at default settings:
29
+ * - 50 rows / cron tick × 60 ticks / hour = 3000 rows / hour / dispatcher
30
+ * - One Lambda runs at a time; CloudWatch shows < 5 s typical duration
31
+ * - SES accepts ~14 / second sandbox, 200 / second production —
32
+ * dispatcher is bottlenecked on Lambda timeout, not SES quota.
33
+ */
34
+ import type { NotifyClient } from './client.js';
35
+ import type { NotifyChannel } from './types.js';
36
+ /** Result of dispatching a single row. */
37
+ export interface DispatchOutcome {
38
+ id: string;
39
+ channel: NotifyChannel;
40
+ status: 'sent' | 'failed' | 'pending' | 'cancelled';
41
+ /** Set when `status === 'sent'`. */
42
+ providerMessageId?: string;
43
+ /** Set when `status !== 'sent'`. */
44
+ error?: string;
45
+ durationMs: number;
46
+ }
47
+ /** Aggregate result of one dispatcher invocation. */
48
+ export interface DispatchSummary {
49
+ /** Total rows claimed in this sweep. */
50
+ claimed: number;
51
+ /** Rows that ended `'sent'`. */
52
+ sent: number;
53
+ /** Rows that ended `'failed'` (hard errors, exhausted retries). */
54
+ failed: number;
55
+ /** Rows left `'pending'` for retry on next tick. */
56
+ retried: number;
57
+ /** Rows transitioned to `'cancelled'` (e.g. address suppression
58
+ * detected after enqueue). */
59
+ cancelled: number;
60
+ /** Per-row detail. Useful for tests and observability. */
61
+ outcomes: DispatchOutcome[];
62
+ }
63
+ /** Construction options for {@link dispatchOnce}. */
64
+ export interface DispatchOnceOptions {
65
+ /** Max rows to claim. Defaults to 50. */
66
+ batchSize?: number;
67
+ /**
68
+ * Hard cap on dispatch attempts before a `'pending'` row is given up
69
+ * on as `'failed'`. Defaults to 5. Soft cap; we still consult the
70
+ * row's `attempts` counter to make the decision.
71
+ */
72
+ maxAttempts?: number;
73
+ /**
74
+ * Override `Date.now` for tests — primarily so retry/scheduling
75
+ * logic can be exercised without sleeping.
76
+ */
77
+ now?: () => number;
78
+ }
79
+ /**
80
+ * Run a single dispatch sweep. Returns a {@link DispatchSummary}.
81
+ * Never throws — all per-row failures are recorded in the outcome
82
+ * list and reflected in the outbox row's status.
83
+ */
84
+ export declare function dispatchOnce(client: NotifyClient, options?: DispatchOnceOptions): Promise<DispatchSummary>;
85
+ /**
86
+ * Build a Lambda-compatible cron handler. The infra package wires
87
+ * this via a synth-time stub file — consumers usually don't import
88
+ * `dispatchHandler` directly.
89
+ *
90
+ * The handler accepts no input (EventBridge cron events have no
91
+ * meaningful payload) and returns the {@link DispatchSummary}, which
92
+ * lands in CloudWatch and feeds a future dashboard.
93
+ */
94
+ export declare function makeDispatchHandler(getClient: () => NotifyClient | Promise<NotifyClient>, options?: DispatchOnceOptions): (event: unknown) => Promise<DispatchSummary>;
95
+ //# sourceMappingURL=dispatcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dispatcher.d.ts","sourceRoot":"","sources":["../src/dispatcher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAGhD,OAAO,KAAK,EAAmB,aAAa,EAAmB,MAAM,YAAY,CAAC;AAElF,0CAA0C;AAC1C,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,aAAa,CAAC;IACvB,MAAM,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,WAAW,CAAC;IACpD,oCAAoC;IACpC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,oCAAoC;IACpC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,qDAAqD;AACrD,MAAM,WAAW,eAAe;IAC9B,wCAAwC;IACxC,OAAO,EAAE,MAAM,CAAC;IAChB,gCAAgC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,mEAAmE;IACnE,MAAM,EAAE,MAAM,CAAC;IACf,oDAAoD;IACpD,OAAO,EAAE,MAAM,CAAC;IAChB;mCAC+B;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,QAAQ,EAAE,eAAe,EAAE,CAAC;CAC7B;AAED,qDAAqD;AACrD,MAAM,WAAW,mBAAmB;IAClC,yCAAyC;IACzC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,YAAY,EACpB,OAAO,GAAE,mBAAwB,GAChC,OAAO,CAAC,eAAe,CAAC,CA4M1B;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,EACrD,OAAO,GAAE,mBAAwB,GAChC,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,eAAe,CAAC,CAK9C"}
@@ -0,0 +1,251 @@
1
+ /**
2
+ * @venturekit/notify — outbox dispatcher
3
+ *
4
+ * Drains pending rows from the outbox and calls each row's provider.
5
+ * Designed to run on a cron schedule (1 invocation per minute by
6
+ * default — `NotifyIntent.dispatchRateMinutes`). Two execution modes:
7
+ *
8
+ * 1. **Cron Lambda (production)** — `dispatchHandler` is exported as
9
+ * a `taskHandler`-compatible function. The infra package wires
10
+ * this as the EventBridge target Lambda for the auto-provisioned
11
+ * cron rule.
12
+ * 2. **Programmatic (tests / one-off CLI)** — `dispatchOnce(client,
13
+ * options)` runs a single sweep and returns the per-row outcome
14
+ * list. No timers, no recursion.
15
+ *
16
+ * The dispatcher is **at-least-once**: a row whose provider call
17
+ * succeeds but whose status update fails (because the DB connection
18
+ * dropped between SES accepting the SendEmail and Postgres committing
19
+ * the UPDATE) will be re-claimed on the next tick and re-sent. The
20
+ * SES `Notify-Id` tag (and Meta `biz_opaque_callback_data`) carry the
21
+ * outbox row id so duplicate detection at the provider level is
22
+ * possible — but Phase 1 doesn't ship server-side dedup. Templates
23
+ * should be designed with idempotency in mind (recipients of a
24
+ * duplicate password-reset email aren't surprised; transactional
25
+ * receipts may want a `notif_id` line in the body to make duplicates
26
+ * obvious).
27
+ *
28
+ * Throughput targets at default settings:
29
+ * - 50 rows / cron tick × 60 ticks / hour = 3000 rows / hour / dispatcher
30
+ * - One Lambda runs at a time; CloudWatch shows < 5 s typical duration
31
+ * - SES accepts ~14 / second sandbox, 200 / second production —
32
+ * dispatcher is bottlenecked on Lambda timeout, not SES quota.
33
+ */
34
+ import { ProviderHardError } from './providers/types.js';
35
+ /**
36
+ * Run a single dispatch sweep. Returns a {@link DispatchSummary}.
37
+ * Never throws — all per-row failures are recorded in the outcome
38
+ * list and reflected in the outbox row's status.
39
+ */
40
+ export async function dispatchOnce(client, options = {}) {
41
+ const batchSize = options.batchSize ?? 50;
42
+ const maxAttempts = options.maxAttempts ?? 5;
43
+ const summary = {
44
+ claimed: 0,
45
+ sent: 0,
46
+ failed: 0,
47
+ retried: 0,
48
+ cancelled: 0,
49
+ outcomes: [],
50
+ };
51
+ const claimed = await client.store.claimPending(batchSize);
52
+ summary.claimed = claimed.length;
53
+ // Process sequentially — SES sandbox quotas, WhatsApp rate limits,
54
+ // and our own DB write throughput don't benefit from parallelism at
55
+ // these batch sizes. Switching to `Promise.all` later is a one-line
56
+ // change if needed.
57
+ for (const row of claimed) {
58
+ const startedAt = (options.now ?? Date.now)();
59
+ try {
60
+ const outcome = await dispatchOne(client, row);
61
+ outcome.durationMs = (options.now ?? Date.now)() - startedAt;
62
+ summary.outcomes.push(outcome);
63
+ switch (outcome.status) {
64
+ case 'sent':
65
+ summary.sent++;
66
+ break;
67
+ case 'failed':
68
+ summary.failed++;
69
+ break;
70
+ case 'pending':
71
+ summary.retried++;
72
+ break;
73
+ case 'cancelled':
74
+ summary.cancelled++;
75
+ break;
76
+ }
77
+ }
78
+ catch (err) {
79
+ // Last-resort safety net — `dispatchOne` is supposed to catch
80
+ // all errors itself; this only fires on unexpected programming
81
+ // bugs (missing await, etc.). Still mark the row failed so
82
+ // it's not silently retried forever.
83
+ const message = err instanceof Error ? err.message : String(err);
84
+ await client.store.updateStatus({
85
+ id: row.id,
86
+ status: 'failed',
87
+ error: `dispatchOne crashed: ${message}`,
88
+ });
89
+ summary.failed++;
90
+ summary.outcomes.push({
91
+ id: row.id,
92
+ channel: row.channel,
93
+ status: 'failed',
94
+ error: message,
95
+ durationMs: (options.now ?? Date.now)() - startedAt,
96
+ });
97
+ }
98
+ }
99
+ return summary;
100
+ // ── helpers ────────────────────────────────────────────────────────
101
+ async function dispatchOne(client, row) {
102
+ const provider = client.providers.get(row.channel);
103
+ if (!provider) {
104
+ await client.store.updateStatus({
105
+ id: row.id,
106
+ status: 'failed',
107
+ error: `No provider registered for channel '${row.channel}'`,
108
+ });
109
+ return {
110
+ id: row.id,
111
+ channel: row.channel,
112
+ status: 'failed',
113
+ error: 'no-channel-provider',
114
+ durationMs: 0,
115
+ };
116
+ }
117
+ // Resolve address: explicit `row.address` wins; otherwise the
118
+ // resolver maps userId -> address. Both paths re-check
119
+ // suppression so a hard bounce that arrived between enqueue and
120
+ // dispatch is caught.
121
+ let address = row.address;
122
+ if (!address && row.recipientUserId && client.addressResolver) {
123
+ try {
124
+ address = await client.addressResolver(row.recipientUserId, row.channel);
125
+ }
126
+ catch (err) {
127
+ const msg = err instanceof Error ? err.message : String(err);
128
+ // Resolver failures are transient — bad DB connection, etc. —
129
+ // so bounce the row back to 'pending' for the next tick.
130
+ await client.store.updateStatus({
131
+ id: row.id,
132
+ status: 'pending',
133
+ error: `address resolver failed: ${msg}`,
134
+ });
135
+ return {
136
+ id: row.id,
137
+ channel: row.channel,
138
+ status: 'pending',
139
+ error: msg,
140
+ durationMs: 0,
141
+ };
142
+ }
143
+ }
144
+ if (!address) {
145
+ await client.store.updateStatus({
146
+ id: row.id,
147
+ status: 'failed',
148
+ error: 'No address available for recipient on this channel',
149
+ });
150
+ return {
151
+ id: row.id,
152
+ channel: row.channel,
153
+ status: 'failed',
154
+ error: 'no-address',
155
+ durationMs: 0,
156
+ };
157
+ }
158
+ if (await client.store.isAddressSuppressed(row.channel, address)) {
159
+ await client.store.updateStatus({
160
+ id: row.id,
161
+ status: 'cancelled',
162
+ error: `Address '${address}' is suppressed (prior bounce / complaint)`,
163
+ });
164
+ return {
165
+ id: row.id,
166
+ channel: row.channel,
167
+ status: 'cancelled',
168
+ error: 'address-suppressed',
169
+ durationMs: 0,
170
+ };
171
+ }
172
+ // Render. A render failure is a permanent error — the template
173
+ // is broken, retries won't help.
174
+ let message;
175
+ try {
176
+ message = client.templates.render(row.templateKey, row.channel, row.payload);
177
+ }
178
+ catch (err) {
179
+ const msg = err instanceof Error ? err.message : String(err);
180
+ await client.store.updateStatus({
181
+ id: row.id,
182
+ status: 'failed',
183
+ error: `template render failed: ${msg}`,
184
+ });
185
+ return {
186
+ id: row.id,
187
+ channel: row.channel,
188
+ status: 'failed',
189
+ error: msg,
190
+ durationMs: 0,
191
+ };
192
+ }
193
+ // Send.
194
+ const sendRequest = {
195
+ to: address,
196
+ from: client.defaultFrom ?? 'system',
197
+ message,
198
+ notificationId: row.id,
199
+ };
200
+ try {
201
+ const result = await provider.send(sendRequest);
202
+ await client.store.updateStatus({
203
+ id: row.id,
204
+ status: 'sent',
205
+ providerMessageId: result.providerMessageId,
206
+ error: null,
207
+ });
208
+ return {
209
+ id: row.id,
210
+ channel: row.channel,
211
+ status: 'sent',
212
+ providerMessageId: result.providerMessageId,
213
+ durationMs: 0,
214
+ };
215
+ }
216
+ catch (err) {
217
+ const msg = err instanceof Error ? err.message : String(err);
218
+ const isHard = err instanceof ProviderHardError;
219
+ const exhausted = row.attempts >= maxAttempts;
220
+ const finalStatus = isHard || exhausted ? 'failed' : 'pending';
221
+ await client.store.updateStatus({
222
+ id: row.id,
223
+ status: finalStatus,
224
+ error: msg,
225
+ });
226
+ return {
227
+ id: row.id,
228
+ channel: row.channel,
229
+ status: finalStatus,
230
+ error: msg,
231
+ durationMs: 0,
232
+ };
233
+ }
234
+ }
235
+ }
236
+ /**
237
+ * Build a Lambda-compatible cron handler. The infra package wires
238
+ * this via a synth-time stub file — consumers usually don't import
239
+ * `dispatchHandler` directly.
240
+ *
241
+ * The handler accepts no input (EventBridge cron events have no
242
+ * meaningful payload) and returns the {@link DispatchSummary}, which
243
+ * lands in CloudWatch and feeds a future dashboard.
244
+ */
245
+ export function makeDispatchHandler(getClient, options = {}) {
246
+ return async () => {
247
+ const client = await getClient();
248
+ return dispatchOnce(client, options);
249
+ };
250
+ }
251
+ //# sourceMappingURL=dispatcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dispatcher.js","sourceRoot":"","sources":["../src/dispatcher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAIH,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAiDzD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,MAAoB,EACpB,UAA+B,EAAE;IAEjC,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,EAAE,CAAC;IAC1C,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,CAAC,CAAC;IAE7C,MAAM,OAAO,GAAoB;QAC/B,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,CAAC;QACP,MAAM,EAAE,CAAC;QACT,OAAO,EAAE,CAAC;QACV,SAAS,EAAE,CAAC;QACZ,QAAQ,EAAE,EAAE;KACb,CAAC;IAEF,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IAC3D,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAEjC,mEAAmE;IACnE,oEAAoE;IACpE,oEAAoE;IACpE,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
+ *
4
+ * Transactional notifications for VentureKit applications. The shape:
5
+ *
6
+ * ```ts
7
+ * import {
8
+ * createNotifyClient, createPostgresNotifyStore,
9
+ * createSesEmailProvider, createMetaWhatsAppProvider,
10
+ * createSecretsTokenResolver,
11
+ * } from '@venturekit/notify';
12
+ *
13
+ * export const notify = createNotifyClient({
14
+ * store: createPostgresNotifyStore(),
15
+ * defaultFrom: process.env.VENTURE_NOTIFY_FROM,
16
+ * providers: [
17
+ * createSesEmailProvider({ region: process.env.AWS_REGION! }),
18
+ * createMetaWhatsAppProvider({
19
+ * phoneNumberId: process.env.VENTURE_NOTIFY_WHATSAPP_PHONE_ID!,
20
+ * tokenResolver: createSecretsTokenResolver({
21
+ * secretArn: process.env.VENTURE_NOTIFY_WHATSAPP_TOKEN_SECRET!,
22
+ * }),
23
+ * }),
24
+ * ],
25
+ * addressResolver: async (userId, channel) => {
26
+ * const user = await usersRepo.findById(userId);
27
+ * if (channel === 'email') return user?.email ?? null;
28
+ * if (channel === 'whatsapp') return user?.whatsappNumber ?? null;
29
+ * return null;
30
+ * },
31
+ * });
32
+ *
33
+ * notify.registerTemplate({
34
+ * key: 'application_registered',
35
+ * channel: 'email',
36
+ * category: 'transactional_application',
37
+ * render: ({ groupName }) => ({
38
+ * subject: `Inscription confirmée: ${groupName}`,
39
+ * text: `Votre inscription au groupe ${groupName} est confirmée.`,
40
+ * html: `<p>Votre inscription au groupe <b>${groupName}</b> est confirmée.</p>`,
41
+ * }),
42
+ * });
43
+ *
44
+ * await notify.enqueue({
45
+ * recipientUserId: 'usr_123',
46
+ * channel: 'email',
47
+ * templateKey: 'application_registered',
48
+ * payload: { groupName: 'Île-de-France #4' },
49
+ * });
50
+ * ```
51
+ */
52
+ export type { NotifyChannel, NotificationStatus, NotifyAddress, NotificationRow, NotificationPreferenceRow, NotificationEventLogRow, EnqueueInput, EnqueueResult, RenderedMessage, NotifyTemplate, } from './types.js';
53
+ export { createNotifyClient, type NotifyClient, type CreateNotifyClientOptions, type AddressResolver, } from './client.js';
54
+ export { createTemplateRegistry, TemplateNotFoundError, type TemplateRegistry, } from './templates/registry.js';
55
+ export { createPostgresNotifyStore, type CreatePostgresNotifyStoreOptions, type NotifyStore, type CreateNotificationInput, type UpdateNotificationStatusInput, type ListForUserOptions, type AdminListOptions, } from './store/index.js';
56
+ export { ProviderHardError, ProviderSendError, type NotifyProvider, type ProviderSendRequest, type ProviderSendResult, createSesEmailProvider, type SesEmailProviderConfig, __resetSesClientForTests, createMetaWhatsAppProvider, createSecretsTokenResolver, type MetaWhatsAppProviderConfig, createSmsNoopProvider, createPushNoopProvider, createEmailNoopProvider, type EmailNoopOptions, } from './providers/index.js';
57
+ export { dispatchOnce, makeDispatchHandler, type DispatchOutcome, type DispatchSummary, type DispatchOnceOptions, } from './dispatcher.js';
58
+ export { makeBounceHandler, type BounceHandlerOutcome, } from './bounce-handler.js';
59
+ export { adminListNotifications, adminGetNotification, adminSendNotification, adminRetryNotification, adminCancelNotification, adminClearSuppression, listUserPreferences, upsertUserPreference, listNotificationsForUser, type AdminListResult, type AdminSendInput, } from './admin/index.js';
60
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AAGH,YAAY,EACV,aAAa,EACb,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,yBAAyB,EACzB,uBAAuB,EACvB,YAAY,EACZ,aAAa,EACb,eAAe,EACf,cAAc,GACf,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,kBAAkB,EAClB,KAAK,YAAY,EACjB,KAAK,yBAAyB,EAC9B,KAAK,eAAe,GACrB,MAAM,aAAa,CAAC;AAGrB,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACrB,KAAK,gBAAgB,GACtB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EAC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