@ultimat3/notify 30.9.0 → 31.0.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/CLAUDE.md +21 -11
- package/README.md +49 -14
- package/package.json +10 -9
- package/src/adapter.ts +21 -0
- package/src/errors.ts +30 -9
- package/src/fanout-digest.ts +61 -37
- package/src/fanout-walk.ts +14 -0
- package/src/fanout.ts +63 -47
- package/src/index.ts +16 -24
- package/src/native-push.ts +1 -0
- package/src/preferences.ts +20 -15
- package/src/retention.ts +1 -1
- package/src/sms-channel.ts +72 -0
- package/src/sms-errors.ts +32 -0
- package/src/sms-transport.ts +109 -0
- package/src/stores.ts +48 -18
package/CLAUDE.md
CHANGED
|
@@ -47,8 +47,16 @@ manifest row. Its row is in `PRIMITIVE_FACTORIES` (`packages/core/src/registrar.
|
|
|
47
47
|
|
|
48
48
|
A job body runs **before** its checkpoint lands, so both layers are load-bearing:
|
|
49
49
|
|
|
50
|
-
1. `step.run('deliver:<channel
|
|
51
|
-
|
|
50
|
+
1. `step.run('deliver:<channel>:chunk-<n>')` — one step per `NOTIFY_CHUNK_SIZE` (500) recipients,
|
|
51
|
+
`n` the chunk's place in the audience `open` froze (never in the ALLOWED list, which a retry
|
|
52
|
+
re-reads). A retry replays a completed chunk from the step store; a chunk that failed part-way
|
|
53
|
+
re-runs whole, and layer 2 answers `sent` for whoever it already reached. Preferences are read
|
|
54
|
+
once per chunk (`PreferenceStore.allowsMany`, required since 31.0.0): 10k recipients is 20 reads
|
|
55
|
+
and 20 step rows a channel, not 20k (`fanout-chunks.test.ts`). A digest reads preferences per
|
|
56
|
+
chunk and sends per chunk (`digest-send:<channel>:chunk-<n>`, ledger-fenced the same way), but
|
|
57
|
+
its `digest:` append and `digest-drain:` steps stay ONE PER RECIPIENT: a chunked append re-runs
|
|
58
|
+
appends whose joined window may be drained by then (below), and a chunked drain widens the
|
|
59
|
+
drain seam's loss from one batch to 500.
|
|
52
60
|
2. `DeliveryLedger.claim` — an atomic claim keyed `(notifier, key, channel, coalesce(recipient, ''))`,
|
|
53
61
|
taken before the send and settled after it. A claim that already reads `sent` answers `false`, so
|
|
54
62
|
an attempt that lost its step history entirely still does not send twice. **The `coalesce` is
|
|
@@ -68,15 +76,15 @@ status = 'sending'` as `SQL_IDEMPOTENCY_SETTLE` is, and `false` is logged `notif
|
|
|
68
76
|
in `meta.retryAfterSeconds`, deferred by jobs' `rateLimitDeferralMs` with the attempt uncounted) and
|
|
69
77
|
never returns `false` for it: `false` checkpoints the step, and a
|
|
70
78
|
holder that then dies is a notification no retry is left to send (`attempt.test.ts`,
|
|
71
|
-
`
|
|
79
|
+
`deliveryLedgerConformance` in `@ultimat3/testing/conformance` (`notify-stores-conformance-postgres.live.test.ts`)).
|
|
72
80
|
|
|
73
81
|
The **one at-most-once seam** is a digest flush: `DigestStore.drain` empties the window, and a
|
|
74
82
|
process killed between the drain and its checkpoint loses that batch. It is stated in `digest.ts`
|
|
75
83
|
rather than hidden. `postgresDigestStore` makes the window itself durable and shared — the
|
|
76
84
|
partial unique index `x_notify_digests_open_idx` lets two replicas' first appends collide so ONE
|
|
77
85
|
opens the window and owns the flush; an elapsed open window is sealed and the append retried — but
|
|
78
|
-
its `drain` is still a delete, so the seam is unchanged (`
|
|
79
|
-
suite against both stores).
|
|
86
|
+
its `drain` is still a delete, so the seam is unchanged (`digestStoreConformance` in `@ultimat3/testing/conformance` (`notify-stores-conformance-postgres.live.test.ts`)
|
|
87
|
+
runs one suite against both stores).
|
|
80
88
|
|
|
81
89
|
**A digest append is ONE STEP PER RECIPIENT, and idempotent per appender** (`As of 2026-10-05`).
|
|
82
90
|
The append pass was one `step.run`, and a step that fails part-way re-runs WHOLE: recipients already
|
|
@@ -88,7 +96,7 @@ durable fence; one row per recipient, as `deliver:` already writes), and behind
|
|
|
88
96
|
opener first — so an append whose answer was lost, or a run whose step history is gone, gets back
|
|
89
97
|
the window it landed in while that window exists. Two executions of one appender at once (a lapsed
|
|
90
98
|
lease) cannot both join: the `do update` refuses an appender already in the row. Pinned by
|
|
91
|
-
`fanout-digest.test.ts` and `
|
|
99
|
+
`fanout-digest.test.ts` and `@ultimat3/testing/conformance` (`notify-stores-conformance-postgres.live.test.ts`).
|
|
92
100
|
|
|
93
101
|
**The audience is deduplicated by `id` once, as it leaves the `open` step** (`As of 2026-10-02`).
|
|
94
102
|
Every per-recipient step is named by the id, so a resolver that named one person twice failed
|
|
@@ -109,7 +117,8 @@ so an `open` checkpointed with duplicates by an earlier version is repaired on r
|
|
|
109
117
|
| `inbox.ts` · `inbox-pg.ts` | the in-app inbox, memory and Postgres |
|
|
110
118
|
| `preferences.ts` · `digest.ts` | the gate and the window, as seams |
|
|
111
119
|
| `digest-pg.ts` | the digest window in Postgres: one row per window, at most one OPEN per slot |
|
|
112
|
-
| `stores.ts` | the one installer for all four |
|
|
120
|
+
| `stores.ts` | the one installer for all four (`installNotifyStores`) and the reads behind it |
|
|
121
|
+
| `adapter.ts` | `@ultimat3/notify/adapter`: the installer + reset, the four store interfaces, `NotifyStoreMissingError` — never the `.` barrel; an app's line is `notifyStores:` in `apps/<app>/runtime.ts` |
|
|
113
122
|
| `retention.ts` | the three sweeps, read off the installed seam |
|
|
114
123
|
| `errors.ts` | this package's `X_NOTIFY_*` codes and their titles |
|
|
115
124
|
| `native-push.ts` | `nativePush()`: every device of a person, dead tokens dropped, bad tokens counted, a credential refusal ending its provider's fan-out, refusals coded |
|
|
@@ -119,6 +128,7 @@ so an `open` checkpointed with duplicates by an earlier version is repaired on r
|
|
|
119
128
|
| `push-device.ts` · `push-device-pg.ts` | the device seam, memory and Postgres (`x_push_devices`) |
|
|
120
129
|
| `push-register.ts` | `pushRegister` / `pushUnregister`, factories over `action` |
|
|
121
130
|
| `push-errors.ts` | `X_NOTIFY_PUSH_*`, registered in `errors.ts` |
|
|
131
|
+
| `sms-transport.ts` · `sms-channel.ts` · `sms-errors.ts` | the `smsTransport` port (an `ADAPTER_PORTS` row: interface + installer on `./adapter`, memory reference, E.164 check), the reference `smsChannel()`, and `X_NOTIFY_SMS_*`. A provider is the app's adapter, never shipped (axiom 8) |
|
|
122
132
|
|
|
123
133
|
One entry point, deliberately: every module runs on the server, so there is no browser half to split
|
|
124
134
|
off.
|
|
@@ -147,7 +157,7 @@ it the two would split on exactly the Unicode keys nobody writes a test for.
|
|
|
147
157
|
|
|
148
158
|
| Rule | Detail |
|
|
149
159
|
|---|---|
|
|
150
|
-
| Exports | `src/index.ts`, explicit, no `export
|
|
160
|
+
| Exports | `src/index.ts`, explicit, no `export *`: the app API only (v31): every kept export's option/result types and every error class stay; channel-name constants, env names, internal bounds and guards do not |
|
|
151
161
|
| Errors | `src/errors.ts`, subclass `UltimateError`, never a bare `Error` |
|
|
152
162
|
| Files | one responsibility each, < 200 lines, tests beside the source |
|
|
153
163
|
| Durations | one vocabulary — `@ultimat3/time`'s. `toDurationMs` is a **narrowing** of `toMs`, never a copy of it: `toMs` screens finiteness and stops, because a negative or fractional duration is real there (`toSeconds(-3000)` is a tested `-3`); a `wait` and a digest `window` are counts of whole FORWARD milliseconds, and the refusal names which declaration was wrong since one notifier holds several. `plan-bounds.test.ts` calls BOTH on the same inputs — the two disagreed once (#372), when only this side was screened, and only a test that calls both can see it come back |
|
|
@@ -155,7 +165,7 @@ it the two would split on exactly the Unicode keys nobody writes a test for.
|
|
|
155
165
|
## Retention
|
|
156
166
|
|
|
157
167
|
All three tables are swept by the boot's hourly `x.purge` job, and no store is handed to it:
|
|
158
|
-
|
|
168
|
+
the stores are an APP's `notifyStores:` line in `apps/<app>/runtime.ts`, installed after the boot that
|
|
159
169
|
installs the sweep. So `retention.ts` reads the seam **per attempt** — the same shape as
|
|
160
170
|
`purgeAuthLimits()` — and answers `0` for a memory store or none at all, which is a boot that made a
|
|
161
171
|
decision rather than a failure.
|
|
@@ -180,8 +190,8 @@ slot that never digests again — is the sweep's (`purgeNotifyDigests` → `Post
|
|
|
180
190
|
`DIGEST_PURGE_BATCH` and at most `DIGEST_PURGE_MAX_BATCHES` statements per pass.
|
|
181
191
|
|
|
182
192
|
`packages/cli/src/framework-schema.ts` applies every notify table's DDL on every boot, **whether or not that
|
|
183
|
-
boot
|
|
193
|
+
boot installs notify stores** — this file said it did not until 2026-08-27, which is a sentence that
|
|
184
194
|
outlived its fact.
|
|
185
195
|
|
|
186
|
-
Commands: `bun test packages/notify
|
|
196
|
+
Commands: `bun test ./packages/notify/`, `bun run boundaries`,
|
|
187
197
|
`bunx biome check packages/notify`.
|
package/README.md
CHANGED
|
@@ -95,25 +95,23 @@ recipients cannot collide with the framework's own key.
|
|
|
95
95
|
|
|
96
96
|
## Installing the stores
|
|
97
97
|
|
|
98
|
-
One
|
|
98
|
+
One field, `notifyStores:`, in `apps/<app>/runtime.ts`; the boot installs it. Whole-object
|
|
99
|
+
replacement, never a merge. A store's author imports the interfaces and `installNotifyStores`
|
|
100
|
+
from `@ultimat3/notify/adapter` — never the `.` barrel.
|
|
99
101
|
|
|
100
102
|
```ts
|
|
101
103
|
import type { PgExecutor } from '@ultimat3/jobs';
|
|
102
|
-
import {
|
|
103
|
-
|
|
104
|
-
postgresDigestStore,
|
|
105
|
-
postgresInboxStore,
|
|
106
|
-
setNotifyStores,
|
|
107
|
-
} from '@ultimat3/notify';
|
|
104
|
+
import type { NotifyStores } from '@ultimat3/notify';
|
|
105
|
+
import { postgresDeliveryLedger, postgresDigestStore, postgresInboxStore } from '@ultimat3/notify';
|
|
108
106
|
|
|
109
107
|
declare const executor: PgExecutor; // `@ultimat3/db`'s dbExecutor()
|
|
110
108
|
declare const idempotency: { readonly windowMs: number }; // the boot's own store
|
|
111
109
|
// The app's preference table, behind whatever taxonomy it named.
|
|
112
110
|
declare const prefs: {
|
|
113
|
-
|
|
111
|
+
allowed(recipients: string[], notifier: string, channel: string, at: Date): Promise<string[]>;
|
|
114
112
|
};
|
|
115
113
|
|
|
116
|
-
|
|
114
|
+
const notifyStores: NotifyStores = {
|
|
117
115
|
// `windowMs` is how long a settled claim is kept. NEVER SHORTER than your idempotency window —
|
|
118
116
|
// a job replayed inside that window against a purged claim claims cleanly and sends twice.
|
|
119
117
|
ledger: postgresDeliveryLedger({ executor, windowMs: idempotency.windowMs }),
|
|
@@ -122,15 +120,18 @@ setNotifyStores({
|
|
|
122
120
|
digest: postgresDigestStore({ executor }),
|
|
123
121
|
preferences: {
|
|
124
122
|
// The GATE ships; what it reads never does. Your taxonomy, your quiet hours.
|
|
125
|
-
|
|
126
|
-
|
|
123
|
+
// ONE read per chunk of ≤ NOTIFY_CHUNK_SIZE (500) recipients: answer the ids that may be reached.
|
|
124
|
+
allowsMany: ({ recipients, notifier: name, channel, ctx }) =>
|
|
125
|
+
prefs.allowed(recipients.map((r) => r.id), name, channel, ctx.now()),
|
|
127
126
|
},
|
|
128
|
-
}
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
export const runtime = { notifyStores };
|
|
129
130
|
```
|
|
130
131
|
|
|
131
132
|
| Store | Default | Why |
|
|
132
133
|
|---|---|---|
|
|
133
|
-
| `ledger` | `memoryDeliveryLedger()` | one process is
|
|
134
|
+
| `ledger` | `memoryDeliveryLedger()` in development and test; in staging and production the first claim refuses `X_NOTIFY_STORE_MISSING` | one process is deduped by a heap map; two replicas or a restart are not, so a deploy names `postgresDeliveryLedger({ executor: dbExecutor() })` |
|
|
134
135
|
| `preferences` | `allowAllPreferences()` | denying by default is a notifier that silently delivers nothing |
|
|
135
136
|
| `inbox` | **none** — `X_NOTIFY_STORE_MISSING` | a message written to nowhere is worse than a refusal |
|
|
136
137
|
| `digest` | **none** — `X_NOTIFY_STORE_MISSING` | same. `memoryDigestStore()` for one process; `postgresDigestStore({ executor })` keeps a window across a restart and gives two replicas ONE window (a partial unique index on the open one), so exactly one run owns its flush |
|
|
@@ -318,6 +319,35 @@ export const approvalRequested = notifier({
|
|
|
318
319
|
| another 4xx | `X_NOTIFY_PUSH_PROVIDER_REFUSED`, logged; the next device is tried. When no device took it, the refusal fails the delivery |
|
|
319
320
|
| 429, 5xx, timeout | rethrown after every other device was tried — the job's retry |
|
|
320
321
|
|
|
322
|
+
### SMS — the `smsTransport` port
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
import { smsChannel } from '@ultimat3/notify';
|
|
326
|
+
import type { SmsTransport } from '@ultimat3/notify/adapter';
|
|
327
|
+
|
|
328
|
+
interface LoginCode {
|
|
329
|
+
readonly code: string;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// a notifier's channel: the body is a catalog key, rendered in the recipient's locale
|
|
333
|
+
export const loginCodeSms = smsChannel<LoginCode>({
|
|
334
|
+
message: ({ event }) => ({ key: 'sms.login_code', params: { code: event.params.code } }),
|
|
335
|
+
numberOf: (recipient) => recipient.to, // the default: E.164, `+4915112345678`
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
// apps/<app>/runtime.ts — the provider is the app's adapter (Twilio, Vonage, SNS)
|
|
339
|
+
declare function twilioSms(config: { readonly from: string }): SmsTransport;
|
|
340
|
+
export const runtime = { smsTransport: twilioSms({ from: '+15550100000' }) };
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
| Rule | Detail |
|
|
344
|
+
|---|---|
|
|
345
|
+
| one port | `SmsTransport` (`send(message) → { transport, id, to, idempotencyKey }`) on `@ultimat3/notify/adapter`, installed from `smsTransport:` in `runtime.ts` (`installSmsTransport`, an `adapterSlot`). Proved by `smsTransportConformance` (`@ultimat3/testing/conformance`) |
|
|
346
|
+
| default | `memorySmsTransport()` in development/test; anywhere else the first send is `X_NOTIFY_SMS_TRANSPORT_MISSING` (terminal) — a heap that swallows a login code is not a default |
|
|
347
|
+
| the text is a catalog key | `message` answers `{ key, params }`, rendered in `recipient.locale` (else the app's fallback) by `translatorFor` — never text |
|
|
348
|
+
| E.164 or refused | `assertSmsNumber` before render or send: a local spelling is `X_NOTIFY_SMS_NUMBER_INVALID` (terminal), the number never in the cause. Every transport calls it too (the suite checks). No number is skipped and logged `notify.address_missing`, as mail |
|
|
349
|
+
| one key per delivery | `smsIdempotencyKey(notifier, key, channel, recipient)` — the same on every attempt, no number in it |
|
|
350
|
+
|
|
321
351
|
|
|
322
352
|
## The inbox
|
|
323
353
|
|
|
@@ -352,7 +382,8 @@ A job body runs before its checkpoint lands. Two layers stop a double send: the
|
|
|
352
382
|
`(notifier, key, channel, coalesce(recipient, ''))` — taken before the send, settled after. A claim
|
|
353
383
|
that already reads `sent` answers `false`. `memoryDeliveryLedger` keys and settles exactly as the
|
|
354
384
|
Postgres ledger does — a null and an empty recipient are one row, and a `settle` with no claim
|
|
355
|
-
records nothing (`
|
|
385
|
+
records nothing (`deliveryLedgerConformance` in `@ultimat3/testing/conformance` runs one suite
|
|
386
|
+
against both).
|
|
356
387
|
|
|
357
388
|
A bulk channel claims **one** row for the whole audience, with a null recipient: half a bulk POST is
|
|
358
389
|
not a state this package can represent. That null is why the key coalesces rather than naming the
|
|
@@ -372,6 +403,8 @@ without bound and every replay would re-send the whole audience.
|
|
|
372
403
|
| `X_NOTIFY_PUSH_DEVICE_GONE` | APNs 410 / FCM `UNREGISTERED`: the device row is deleted, nothing fails |
|
|
373
404
|
| `X_NOTIFY_PUSH_PROVIDER_REFUSED` | APNs or FCM refused for good: a credential, a topic or project, a payload limit |
|
|
374
405
|
| `X_NOTIFY_PUSH_MESSAGE_INVALID` | a data-only push carrying more than ids |
|
|
406
|
+
| `X_NOTIFY_SMS_TRANSPORT_MISSING` | an SMS sent outside development/test with no `smsTransport:` installed |
|
|
407
|
+
| `X_NOTIFY_SMS_NUMBER_INVALID` | an SMS number that is not E.164 |
|
|
375
408
|
|
|
376
409
|
### Error classes
|
|
377
410
|
|
|
@@ -388,6 +421,8 @@ a job boundary the class is gone and the `code` is what survives — match on th
|
|
|
388
421
|
| `NotifyPushDeviceGoneError` | `X_NOTIFY_PUSH_DEVICE_GONE` | `src/push-errors.ts` |
|
|
389
422
|
| `NotifyPushMessageInvalidError` | `X_NOTIFY_PUSH_MESSAGE_INVALID` | `src/push-errors.ts` |
|
|
390
423
|
| `NotifyPushProviderRefusedError` | `X_NOTIFY_PUSH_PROVIDER_REFUSED` | `src/push-errors.ts` |
|
|
424
|
+
| `NotifySmsNumberInvalidError` | `X_NOTIFY_SMS_NUMBER_INVALID` | `src/sms-errors.ts` |
|
|
425
|
+
| `NotifySmsTransportMissingError` | `X_NOTIFY_SMS_TRANSPORT_MISSING` | `src/sms-errors.ts` |
|
|
391
426
|
| `NotifyStoreMissingError` | `X_NOTIFY_STORE_MISSING` | `src/errors.ts` |
|
|
392
427
|
|
|
393
428
|
## Boundary
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/notify",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "31.0.0",
|
|
4
4
|
"description": "Notifications: one declaration, many channels — fan-out, preference gate, digest window, delivery ledger, in-app inbox",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
"provenance": true
|
|
25
25
|
},
|
|
26
26
|
"exports": {
|
|
27
|
-
".": "./src/index.ts"
|
|
27
|
+
".": "./src/index.ts",
|
|
28
|
+
"./adapter": "./src/adapter.ts"
|
|
28
29
|
},
|
|
29
30
|
"sideEffects": [
|
|
30
31
|
"./src/errors.ts"
|
|
@@ -45,12 +46,12 @@
|
|
|
45
46
|
"test": "bun test"
|
|
46
47
|
},
|
|
47
48
|
"dependencies": {
|
|
48
|
-
"@ultimat3/action": "
|
|
49
|
-
"@ultimat3/core": "
|
|
50
|
-
"@ultimat3/i18n": "
|
|
51
|
-
"@ultimat3/jobs": "
|
|
52
|
-
"@ultimat3/policy": "
|
|
53
|
-
"@ultimat3/schema": "
|
|
54
|
-
"@ultimat3/time": "
|
|
49
|
+
"@ultimat3/action": "31.0.0",
|
|
50
|
+
"@ultimat3/core": "31.0.0",
|
|
51
|
+
"@ultimat3/i18n": "31.0.0",
|
|
52
|
+
"@ultimat3/jobs": "31.0.0",
|
|
53
|
+
"@ultimat3/policy": "31.0.0",
|
|
54
|
+
"@ultimat3/schema": "31.0.0",
|
|
55
|
+
"@ultimat3/time": "31.0.0"
|
|
55
56
|
}
|
|
56
57
|
}
|
package/src/adapter.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// `@ultimat3/notify/adapter` — what a notifier's stores and its SMS transport are built and
|
|
2
|
+
// installed from: the port interfaces, the errors a driver raises, and the boot's installers. Never the
|
|
3
|
+
// `.` barrel: an app hands its stores over with `notifyStores:` in `apps/<app>/runtime.ts`, so the
|
|
4
|
+
// only callers here are the cli boot, `@ultimat3/testing` and a store author.
|
|
5
|
+
|
|
6
|
+
export type { DigestAppend, DigestBucket, DigestSlot, DigestStore } from './digest';
|
|
7
|
+
export { NotifyStoreMissingError } from './errors';
|
|
8
|
+
export type { InboxQuery, InboxRow, InboxStore, InboxWrite } from './inbox';
|
|
9
|
+
export type {
|
|
10
|
+
DeliveryClaim,
|
|
11
|
+
DeliveryClaimAnswer,
|
|
12
|
+
DeliveryLedger,
|
|
13
|
+
DeliveryRecord,
|
|
14
|
+
DeliveryStatus,
|
|
15
|
+
} from './ledger';
|
|
16
|
+
export type { PreferenceBatchQuery, PreferenceStore } from './preferences';
|
|
17
|
+
export { NotifySmsNumberInvalidError, NotifySmsTransportMissingError } from './sms-errors';
|
|
18
|
+
export type { SmsMessage, SmsSendResult, SmsTransport } from './sms-transport';
|
|
19
|
+
export { installSmsTransport, resetSmsTransport } from './sms-transport';
|
|
20
|
+
export type { InstalledNotifyStores, NotifyStores } from './stores';
|
|
21
|
+
export { installNotifyStores, resetNotifyStores } from './stores';
|
package/src/errors.ts
CHANGED
|
@@ -22,6 +22,8 @@ export const NOTIFY_ERROR_CODES = [
|
|
|
22
22
|
'X_NOTIFY_PUSH_DEVICE_GONE',
|
|
23
23
|
'X_NOTIFY_PUSH_PROVIDER_REFUSED',
|
|
24
24
|
'X_NOTIFY_PUSH_MESSAGE_INVALID',
|
|
25
|
+
'X_NOTIFY_SMS_TRANSPORT_MISSING',
|
|
26
|
+
'X_NOTIFY_SMS_NUMBER_INVALID',
|
|
25
27
|
] as const;
|
|
26
28
|
|
|
27
29
|
export type NotifyErrorCode = (typeof NOTIFY_ERROR_CODES)[number];
|
|
@@ -37,6 +39,8 @@ export const NOTIFY_ERROR_TITLES: Readonly<Record<NotifyErrorCode, string>> = {
|
|
|
37
39
|
X_NOTIFY_PUSH_DEVICE_GONE: 'the push provider says a device token is dead',
|
|
38
40
|
X_NOTIFY_PUSH_PROVIDER_REFUSED: 'APNs or FCM refused a push for good',
|
|
39
41
|
X_NOTIFY_PUSH_MESSAGE_INVALID: 'a data-only push carries more than an id',
|
|
42
|
+
X_NOTIFY_SMS_TRANSPORT_MISSING: 'an SMS was sent with no SmsTransport installed',
|
|
43
|
+
X_NOTIFY_SMS_NUMBER_INVALID: 'an SMS number is not E.164',
|
|
40
44
|
};
|
|
41
45
|
|
|
42
46
|
// One unconditional call, so a second package claiming one of notify's codes throws
|
|
@@ -84,6 +88,10 @@ registerErrorRetry({
|
|
|
84
88
|
// it never leaves a send.
|
|
85
89
|
X_NOTIFY_PUSH_PROVIDER_REFUSED: 'terminal',
|
|
86
90
|
X_NOTIFY_PUSH_MESSAGE_INVALID: 'terminal',
|
|
91
|
+
// SMS (`sms-errors.ts`). A transport is installed at boot or it is not, and a stored number is
|
|
92
|
+
// the same number on attempt 2: neither is the moment.
|
|
93
|
+
X_NOTIFY_SMS_TRANSPORT_MISSING: 'terminal',
|
|
94
|
+
X_NOTIFY_SMS_NUMBER_INVALID: 'terminal',
|
|
87
95
|
});
|
|
88
96
|
|
|
89
97
|
/** Refused where it is written: a notifier with no channel is a job that fans out to nobody. */
|
|
@@ -144,22 +152,35 @@ export class NotifyFanoutTooWideError extends UltimateError {
|
|
|
144
152
|
* and a digest window have no such default — there is nowhere to put the row — so they refuse.
|
|
145
153
|
*/
|
|
146
154
|
export class NotifyStoreMissingError extends UltimateError {
|
|
147
|
-
constructor(input: { notifier: string; store: 'inbox' | 'digest' }) {
|
|
148
|
-
const what =
|
|
149
|
-
input.store === 'inbox' ? 'a channel that writes the in-app inbox' : 'a digest window';
|
|
150
|
-
const install =
|
|
151
|
-
input.store === 'inbox'
|
|
152
|
-
? 'memoryInboxStore() }) at boot, or postgresInboxStore({ executor }) to share it across replicas'
|
|
153
|
-
: 'memoryDigestStore() }) at boot';
|
|
155
|
+
constructor(input: { notifier: string; store: 'inbox' | 'digest' | 'ledger' }) {
|
|
154
156
|
super({
|
|
155
157
|
code: 'X_NOTIFY_STORE_MISSING',
|
|
156
|
-
cause:
|
|
157
|
-
fix:
|
|
158
|
+
cause: STORE_MISSING_CAUSE[input.store](input.notifier),
|
|
159
|
+
fix: STORE_MISSING_FIX[input.store],
|
|
158
160
|
meta: { notifier: input.notifier, store: input.store },
|
|
159
161
|
});
|
|
160
162
|
}
|
|
161
163
|
}
|
|
162
164
|
|
|
165
|
+
const STORE_MISSING_CAUSE = {
|
|
166
|
+
inbox: (notifier: string) =>
|
|
167
|
+
`notifier "${notifier}" delivers through a channel that writes the in-app inbox and no inbox store is installed, so the rows have nowhere to go`,
|
|
168
|
+
digest: (notifier: string) =>
|
|
169
|
+
`notifier "${notifier}" delivers through a digest window and no digest store is installed, so the rows have nowhere to go`,
|
|
170
|
+
// The memory ledger is one process's heap: behind replicas or across a restart a replay sends twice.
|
|
171
|
+
ledger: (notifier: string) =>
|
|
172
|
+
`notifier "${notifier}" claimed a delivery outside development and no delivery ledger is installed; a memory ledger is one process's heap, so a replayed attempt on another replica or after a restart would send twice`,
|
|
173
|
+
} as const;
|
|
174
|
+
|
|
175
|
+
const STORE_MISSING_FIX = {
|
|
176
|
+
inbox:
|
|
177
|
+
'memoryInboxStore() # notifyStores: { inbox } in apps/<app>/runtime.ts — postgresInboxStore({ executor }) to share it across replicas',
|
|
178
|
+
digest:
|
|
179
|
+
'memoryDigestStore() # notifyStores: { digest } in apps/<app>/runtime.ts — postgresDigestStore({ executor }) to share it across replicas',
|
|
180
|
+
ledger:
|
|
181
|
+
'notifyStores: { ledger: postgresDeliveryLedger({ executor: dbExecutor() }) } # apps/<app>/runtime.ts — the x_notify_deliveries table the boot already applies',
|
|
182
|
+
} as const;
|
|
183
|
+
|
|
163
184
|
/**
|
|
164
185
|
* A digest window declared on a bulk channel. Refused where it is written: a bulk send has one
|
|
165
186
|
* payload for the whole audience and a window coalesces PER RECIPIENT, so the two have no shared
|
package/src/fanout-digest.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { attemptDelivery } from './attempt';
|
|
|
9
9
|
import type { NotifyChannel } from './channel';
|
|
10
10
|
import type { DigestSlot } from './digest';
|
|
11
11
|
import type { Walk } from './fanout-walk';
|
|
12
|
+
import { chunksOf } from './fanout-walk';
|
|
12
13
|
import type { NotifyEvent, Recipient } from './notification';
|
|
13
14
|
import type { ResolvedDelivery } from './plan';
|
|
14
15
|
import { notifyStores, requireDigest } from './stores';
|
|
@@ -34,7 +35,8 @@ export async function flushDigest<Params>(input: DigestFlush<Params>): Promise<v
|
|
|
34
35
|
});
|
|
35
36
|
|
|
36
37
|
// ONE STEP PER APPEND, and the step store is the fence: a completed append is never redone, so
|
|
37
|
-
// the same event never lands in a digest twice.
|
|
38
|
+
// the same event never lands in a digest twice. NOT chunked (`NOTIFY_CHUNK_SIZE`) for that reason:
|
|
39
|
+
// a chunk step re-runs whole. One step for the whole pass re-ran every append
|
|
38
40
|
// when any one failed, and the window a re-run append had joined may already have been drained
|
|
39
41
|
// and deleted by its owner — nothing in the store remembered it, so the event went out again in
|
|
40
42
|
// a second digest. The appender id is the store's own defence behind the step: an append whose
|
|
@@ -68,45 +70,67 @@ export async function flushDigest<Params>(input: DigestFlush<Params>): Promise<v
|
|
|
68
70
|
if (remaining > 0) await step.sleep(`digest-wait:${channel.name}`, remaining);
|
|
69
71
|
|
|
70
72
|
const byId = new Map(allowed.map((recipient) => [recipient.id, recipient]));
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
//
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
73
|
+
let index = 0;
|
|
74
|
+
for (const chunk of chunksOf(opened.owned)) {
|
|
75
|
+
// Drain stays ONE STEP PER WINDOW: a drain empties its window, and a process killed between a
|
|
76
|
+
// drain and its checkpoint loses that batch (`DigestStore.drain`'s seam). A chunked drain would
|
|
77
|
+
// widen that loss from one batch to five hundred. Its result is checkpointed, so a retry of
|
|
78
|
+
// the send below replays each batch from the step store rather than from an emptied window.
|
|
79
|
+
const drained: {
|
|
80
|
+
readonly recipient: Recipient;
|
|
81
|
+
readonly endsAt: number;
|
|
82
|
+
readonly batch: StepOutput<readonly NotifyEvent<unknown>[]>;
|
|
83
|
+
}[] = [];
|
|
84
|
+
for (const { id, endsAt } of chunk) {
|
|
85
|
+
const recipient = byId.get(id);
|
|
86
|
+
if (recipient === undefined) continue;
|
|
87
|
+
const batch = await step.run(`digest-drain:${channel.name}:${id}`, () =>
|
|
88
|
+
digest.drain(slotFor(id), endsAt),
|
|
89
|
+
);
|
|
90
|
+
if (batch.length > 0) drained.push({ recipient, endsAt, batch });
|
|
91
|
+
}
|
|
92
|
+
// Named by the chunk's place in `opened.owned`, which the append steps' checkpointed answers
|
|
93
|
+
// decide — stable across a replay.
|
|
94
|
+
const name = `digest-send:${channel.name}:chunk-${String(index)}`;
|
|
95
|
+
index += 1;
|
|
96
|
+
if (drained.length === 0) continue;
|
|
97
|
+
// ONE send step per chunk. Safe where a chunked APPEND is not: a re-run send is fenced per
|
|
98
|
+
// recipient by the ledger claim below, so a chunk that failed part-way re-sends nobody it
|
|
99
|
+
// already reached (counted `replayed`), exactly as `deliver:<channel>:chunk-<n>`.
|
|
100
|
+
const counts = await step.run(name, async (signal) => {
|
|
101
|
+
const answer = { delivered: 0, replayed: 0 };
|
|
102
|
+
for (const { recipient, endsAt, batch } of drained) {
|
|
103
|
+
const events = rehydrate(batch, plan.parseParams);
|
|
104
|
+
const newest = events[events.length - 1] ?? event;
|
|
105
|
+
const sent = await attemptDelivery(
|
|
106
|
+
{
|
|
107
|
+
ledger: notifyStores().ledger,
|
|
108
|
+
// The window, not the event: a digest is one delivery for many events, so its ledger
|
|
109
|
+
// identity is the slot plus the window it closed. Two different windows for the same
|
|
110
|
+
// recipient are two deliveries and must not dedupe into one. THIS recipient's end,
|
|
111
|
+
// never the run's maximum: two runs whose maxima coincide would share one key.
|
|
112
|
+
claim: {
|
|
113
|
+
notifier: plan.name,
|
|
114
|
+
key: `digest:${group}:${String(endsAt)}`,
|
|
115
|
+
recipient: recipient.id,
|
|
116
|
+
channel: channel.name,
|
|
117
|
+
},
|
|
93
118
|
notifier: plan.name,
|
|
94
|
-
key: `digest:${group}:${String(endsAt)}`,
|
|
95
|
-
recipient: id,
|
|
96
119
|
channel: channel.name,
|
|
120
|
+
recipients: 1,
|
|
121
|
+
ctx,
|
|
122
|
+
send: (abort) =>
|
|
123
|
+
channel.deliver({ ctx, recipient, event: newest, batch: events, signal: abort }),
|
|
97
124
|
},
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
);
|
|
108
|
-
if (sent) tally.delivered += 1;
|
|
109
|
-
else tally.replayed += 1;
|
|
125
|
+
signal,
|
|
126
|
+
);
|
|
127
|
+
if (sent) answer.delivered += 1;
|
|
128
|
+
else answer.replayed += 1;
|
|
129
|
+
}
|
|
130
|
+
return answer;
|
|
131
|
+
});
|
|
132
|
+
tally.delivered += counts.delivered;
|
|
133
|
+
tally.replayed += counts.replayed;
|
|
110
134
|
}
|
|
111
135
|
}
|
|
112
136
|
|
package/src/fanout-walk.ts
CHANGED
|
@@ -33,3 +33,17 @@ export const countSend = (tally: Tally, sent: boolean): void => {
|
|
|
33
33
|
if (sent) tally.delivered += 1;
|
|
34
34
|
else tally.replayed += 1;
|
|
35
35
|
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Recipients per preference read and per delivery step. 10k recipients was 20k+ preference round
|
|
39
|
+
* trips and 10k `x_job_steps` rows for two channels; chunked, it is 20 reads and 20 rows a channel.
|
|
40
|
+
* 500 is `DEFAULT_MAX_RECIPIENTS`: a default notifier is one chunk, exactly one read and one step.
|
|
41
|
+
*/
|
|
42
|
+
export const NOTIFY_CHUNK_SIZE = 500;
|
|
43
|
+
|
|
44
|
+
/** `items` in `NOTIFY_CHUNK_SIZE` slices, in order — for the audience, the order `open` checkpointed. */
|
|
45
|
+
export function* chunksOf<T>(items: readonly T[]): Generator<readonly T[]> {
|
|
46
|
+
for (let start = 0; start < items.length; start += NOTIFY_CHUNK_SIZE) {
|
|
47
|
+
yield items.slice(start, start + NOTIFY_CHUNK_SIZE);
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/fanout.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { isBulkChannel } from './channel';
|
|
|
13
13
|
import { NotifyFanoutTooWideError } from './errors';
|
|
14
14
|
import { flushDigest } from './fanout-digest';
|
|
15
15
|
import type { Tally, Walk } from './fanout-walk';
|
|
16
|
-
import { countSend } from './fanout-walk';
|
|
16
|
+
import { chunksOf, countSend } from './fanout-walk';
|
|
17
17
|
import type { NotifyEvent, Recipient } from './notification';
|
|
18
18
|
import type { NotifyPayload, NotifyPlan, NotifyReport, ResolvedDelivery } from './plan';
|
|
19
19
|
import { notifyStores } from './stores';
|
|
@@ -96,18 +96,20 @@ async function deliverOne<Params>(
|
|
|
96
96
|
return;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
-
const allowed = await allowedBy(walk, delivery.channel.name);
|
|
100
|
-
if (allowed.length === 0) return;
|
|
101
|
-
|
|
102
99
|
const channel = delivery.channel;
|
|
103
|
-
if (delivery.digestMs !== undefined) {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
100
|
+
if (delivery.digestMs !== undefined || isBulkChannel(channel)) {
|
|
101
|
+
const allowed: Recipient[] = [];
|
|
102
|
+
for (const chunk of chunksOf(walk.audience))
|
|
103
|
+
allowed.push(...(await allowedBy(walk, channel.name, chunk)));
|
|
104
|
+
if (allowed.length === 0) return;
|
|
105
|
+
if (delivery.digestMs !== undefined) {
|
|
106
|
+
// `notifier()` refused a digest on a bulk channel at declaration, so this narrowing cannot
|
|
107
|
+
// fail at run time — it is here because the type system cannot read that refusal.
|
|
108
|
+
if (isBulkChannel(channel)) return;
|
|
109
|
+
await flushDigest({ walk, channel: channel as NotifyChannel<Params>, delivery, allowed });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (!isBulkChannel(channel)) return;
|
|
111
113
|
const claim = {
|
|
112
114
|
notifier: walk.plan.name,
|
|
113
115
|
key: event.key,
|
|
@@ -135,56 +137,70 @@ async function deliverOne<Params>(
|
|
|
135
137
|
return;
|
|
136
138
|
}
|
|
137
139
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
140
|
+
const one = channel as NotifyChannel<Params>;
|
|
141
|
+
let index = 0;
|
|
142
|
+
for (const chunk of chunksOf(walk.audience)) {
|
|
143
|
+
// Named by the chunk's place in the audience the `open` step froze — never by who in it was
|
|
144
|
+
// ALLOWED, which is re-read on a retry: a name over the allowed list would replay a stored
|
|
145
|
+
// chunk for a different set of people. Each chunk is ONE step: a retry re-runs the chunk, and
|
|
146
|
+
// the ledger answers `sent` for every recipient it already reached (counted `replayed`).
|
|
147
|
+
const name = `deliver:${channel.name}:chunk-${String(index)}`;
|
|
148
|
+
index += 1;
|
|
149
|
+
const allowed = await allowedBy(walk, channel.name, chunk);
|
|
150
|
+
if (allowed.length === 0) continue;
|
|
151
|
+
const counts = await walk.step.run(name, async (signal) => {
|
|
152
|
+
const answer = { delivered: 0, replayed: 0 };
|
|
153
|
+
for (const recipient of allowed) {
|
|
154
|
+
const sent = await attemptDelivery(
|
|
155
|
+
{
|
|
156
|
+
ledger: notifyStores().ledger,
|
|
157
|
+
claim: {
|
|
158
|
+
notifier: walk.plan.name,
|
|
159
|
+
key: event.key,
|
|
160
|
+
recipient: recipient.id,
|
|
161
|
+
channel: channel.name,
|
|
162
|
+
},
|
|
163
|
+
notifier: walk.plan.name,
|
|
164
|
+
channel: channel.name,
|
|
165
|
+
recipients: 1,
|
|
166
|
+
ctx,
|
|
167
|
+
send: (abort) => one.deliver({ ctx, recipient, event, batch: [event], signal: abort }),
|
|
168
|
+
},
|
|
169
|
+
signal,
|
|
170
|
+
);
|
|
171
|
+
if (sent) answer.delivered += 1;
|
|
172
|
+
else answer.replayed += 1;
|
|
173
|
+
}
|
|
174
|
+
return answer;
|
|
175
|
+
});
|
|
176
|
+
tally.delivered += counts.delivered;
|
|
177
|
+
tally.replayed += counts.replayed;
|
|
163
178
|
}
|
|
164
179
|
}
|
|
165
180
|
|
|
166
181
|
/**
|
|
167
|
-
* The preference gate, per
|
|
182
|
+
* The preference gate, ONE read per chunk and channel — deliberately NOT inside a durable step. It
|
|
168
183
|
* is a read, so replaying it costs a query rather than a row, and re-asking on a retry is the more
|
|
169
184
|
* correct answer anyway: somebody who opted out during a five-minute `wait` should not receive the
|
|
170
|
-
* mail the first attempt had already decided to send.
|
|
185
|
+
* mail the first attempt had already decided to send. The answer is intersected with the chunk:
|
|
186
|
+
* an id the store invents reaches nobody.
|
|
171
187
|
*/
|
|
172
188
|
async function allowedBy<Params>(
|
|
173
189
|
walk: Walk<Params>,
|
|
174
190
|
channel: string,
|
|
191
|
+
chunk: readonly Recipient[],
|
|
175
192
|
): Promise<readonly Recipient[]> {
|
|
176
193
|
const { preferences } = notifyStores();
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
recipient,
|
|
194
|
+
const ids = new Set(
|
|
195
|
+
await preferences.allowsMany({
|
|
196
|
+
recipients: chunk,
|
|
181
197
|
notifier: walk.plan.name,
|
|
182
198
|
channel,
|
|
183
199
|
event: walk.event,
|
|
184
200
|
ctx: walk.ctx,
|
|
185
|
-
})
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
201
|
+
}),
|
|
202
|
+
);
|
|
203
|
+
const allowed = chunk.filter((recipient) => ids.has(recipient.id));
|
|
204
|
+
walk.tally.suppressed += chunk.length - allowed.length;
|
|
189
205
|
return allowed;
|
|
190
206
|
}
|
package/src/index.ts
CHANGED
|
@@ -17,11 +17,11 @@ export type {
|
|
|
17
17
|
DeliveryArgs,
|
|
18
18
|
NotifyChannel,
|
|
19
19
|
} from './channel';
|
|
20
|
-
export { bulkChannel, deliveryChannel
|
|
20
|
+
export { bulkChannel, deliveryChannel } from './channel';
|
|
21
21
|
export type { InAppChannelOptions } from './channel-in-app';
|
|
22
|
-
export {
|
|
22
|
+
export { inAppChannel } from './channel-in-app';
|
|
23
23
|
export type { MailChannelOptions, Mailer, NotifyMail } from './channel-mail';
|
|
24
|
-
export {
|
|
24
|
+
export { mailChannel } from './channel-mail';
|
|
25
25
|
export type {
|
|
26
26
|
DataPushChannelOptions,
|
|
27
27
|
DataPusher,
|
|
@@ -29,10 +29,9 @@ export type {
|
|
|
29
29
|
PushChannelOptions,
|
|
30
30
|
Pusher,
|
|
31
31
|
} from './channel-push';
|
|
32
|
-
export {
|
|
32
|
+
export { pushChannel } from './channel-push';
|
|
33
33
|
export type {
|
|
34
34
|
DigestAppend,
|
|
35
|
-
DigestBucket,
|
|
36
35
|
DigestSlot,
|
|
37
36
|
DigestStore,
|
|
38
37
|
MemoryDigestStore,
|
|
@@ -46,7 +45,6 @@ export {
|
|
|
46
45
|
} from './digest-pg';
|
|
47
46
|
export type { NotifyErrorCode } from './errors';
|
|
48
47
|
export {
|
|
49
|
-
NOTIFY_ERROR_CODES,
|
|
50
48
|
NotifyChannelDuplicateError,
|
|
51
49
|
NotifyChannelsEmptyError,
|
|
52
50
|
NotifyDeliveryFailedError,
|
|
@@ -54,12 +52,13 @@ export {
|
|
|
54
52
|
NotifyFanoutTooWideError,
|
|
55
53
|
NotifyStoreMissingError,
|
|
56
54
|
} from './errors';
|
|
55
|
+
export { NOTIFY_CHUNK_SIZE } from './fanout-walk';
|
|
57
56
|
export type { FcmOptions } from './fcm';
|
|
58
57
|
// `runFanout` is deliberately absent, for the reason `registerJob` is absent from
|
|
59
58
|
// @ultimat3/jobs: a second way to execute a fan-out would bypass the job the factory built, and
|
|
60
59
|
// with it the retry policy, the cancellation and the manifest row.
|
|
61
60
|
export type { InboxQuery, InboxRow, InboxStore, InboxWrite, MemoryInboxStore } from './inbox';
|
|
62
|
-
export {
|
|
61
|
+
export { memoryInboxStore } from './inbox';
|
|
63
62
|
export type { InboxPurgeBefore, PostgresInboxStore, PostgresInboxStoreOptions } from './inbox-pg';
|
|
64
63
|
export {
|
|
65
64
|
postgresInboxStore,
|
|
@@ -69,15 +68,11 @@ export type {
|
|
|
69
68
|
DeliveryClaim,
|
|
70
69
|
DeliveryClaimAnswer,
|
|
71
70
|
DeliveryLedger,
|
|
72
|
-
DeliveryRecord,
|
|
73
|
-
DeliveryStatus,
|
|
74
71
|
MemoryDeliveryLedger,
|
|
75
72
|
MemoryDeliveryLedgerOptions,
|
|
76
73
|
} from './ledger';
|
|
77
74
|
export {
|
|
78
75
|
DEFAULT_DELIVERY_RECLAIM_MS,
|
|
79
|
-
DELIVERY_STATUSES,
|
|
80
|
-
isDeliveryStatus,
|
|
81
76
|
memoryDeliveryLedger,
|
|
82
77
|
} from './ledger';
|
|
83
78
|
export type { PostgresDeliveryLedger, PostgresDeliveryLedgerOptions } from './ledger-pg';
|
|
@@ -87,31 +82,25 @@ export {
|
|
|
87
82
|
} from './ledger-pg';
|
|
88
83
|
export type { NativePusher, NativePushOptions } from './native-push';
|
|
89
84
|
export {
|
|
90
|
-
DEFAULT_NATIVE_PUSH_DEADLINE_MS,
|
|
91
85
|
nativePush,
|
|
92
86
|
PUSH_BAD_TOKEN_LIMIT,
|
|
93
87
|
} from './native-push';
|
|
94
|
-
export { APNS_KEY_ENV, FCM_KEY_ENV } from './native-transport';
|
|
95
88
|
export type { NotifyEvent, Recipient } from './notification';
|
|
96
|
-
export { recipientSchema } from './notification';
|
|
97
89
|
export type { NotifierDefinition } from './notifier';
|
|
98
|
-
export {
|
|
90
|
+
export { notifier } from './notifier';
|
|
99
91
|
export type {
|
|
100
92
|
ChannelDelivery,
|
|
101
93
|
DeliveryGate,
|
|
102
94
|
DigestWindow,
|
|
103
95
|
NotifyDuration,
|
|
104
96
|
NotifyPayload,
|
|
105
|
-
NotifyPlan,
|
|
106
|
-
NotifyReport,
|
|
107
97
|
RecipientArgs,
|
|
108
|
-
ResolvedDelivery,
|
|
109
98
|
} from './plan';
|
|
110
99
|
export { toDurationMs } from './plan';
|
|
111
|
-
export type { MemoryPreferenceStore,
|
|
100
|
+
export type { MemoryPreferenceStore, PreferenceBatchQuery, PreferenceStore } from './preferences';
|
|
112
101
|
export { allowAllPreferences, memoryPreferenceStore } from './preferences';
|
|
113
102
|
export type { PushDeviceRecord, PushDeviceStore, PushPlatform } from './push-device';
|
|
114
|
-
export { memoryPushDeviceStore
|
|
103
|
+
export { memoryPushDeviceStore } from './push-device';
|
|
115
104
|
export type { PostgresPushDeviceStoreOptions } from './push-device-pg';
|
|
116
105
|
export {
|
|
117
106
|
PUSH_DEVICES_TABLE,
|
|
@@ -124,15 +113,18 @@ export {
|
|
|
124
113
|
NotifyPushMessageInvalidError,
|
|
125
114
|
NotifyPushProviderRefusedError,
|
|
126
115
|
} from './push-errors';
|
|
127
|
-
export type { PushData } from './push-message';
|
|
128
|
-
export { DATA_PUSH_MAX_KEYS, DATA_PUSH_MAX_VALUE } from './push-message';
|
|
129
116
|
export type { PushRegisterOptions } from './push-register';
|
|
130
117
|
export { PUSH_DEVICES_PER_ACTOR, pushRegister, pushUnregister } from './push-register';
|
|
131
118
|
export { purgeNotifyDeliveries, purgeNotifyDigests, purgeNotifyInbox } from './retention';
|
|
119
|
+
// SMS: the reference channel over the `smsTransport` port. The port's interface and installer are
|
|
120
|
+
// on `./adapter`; a provider (Twilio, Vonage, SNS) is the app's adapter.
|
|
121
|
+
export type { NotifySmsMessage, SmsChannelOptions } from './sms-channel';
|
|
122
|
+
export { smsChannel, smsIdempotencyKey } from './sms-channel';
|
|
123
|
+
export { NotifySmsNumberInvalidError, NotifySmsTransportMissingError } from './sms-errors';
|
|
124
|
+
export type { MemorySmsTransport } from './sms-transport';
|
|
125
|
+
export { assertSmsNumber, memorySmsTransport } from './sms-transport';
|
|
132
126
|
export type { InstalledNotifyStores, NotifyStores } from './stores';
|
|
133
127
|
export {
|
|
134
128
|
notifyStores,
|
|
135
129
|
requireInbox,
|
|
136
|
-
resetNotifyStores,
|
|
137
|
-
setNotifyStores,
|
|
138
130
|
} from './stores';
|
package/src/native-push.ts
CHANGED
|
@@ -137,6 +137,7 @@ export function nativePush(options: NativePushOptions): NativePusher {
|
|
|
137
137
|
const deps = {
|
|
138
138
|
fetch: options.fetch ?? platformFetch,
|
|
139
139
|
env: options.env ?? Bun.env,
|
|
140
|
+
// Real time: a provider JWT's `iat` is judged by APNs/FCM against their own clocks.
|
|
140
141
|
clock: options.clock ?? systemClock,
|
|
141
142
|
deadlineMs: finiteCount(
|
|
142
143
|
'nativePush()',
|
package/src/preferences.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// The preference gate: one question
|
|
1
|
+
// The preference gate: one question per (chunk of recipients, notifier, channel), after the wait.
|
|
2
2
|
//
|
|
3
3
|
// `noticed` has no gate at all — it leaves opt-out to a `config.if` closure the app writes per
|
|
4
4
|
// channel, which is four teams writing the same closure four times. So the GATE ships here. What
|
|
@@ -12,8 +12,9 @@
|
|
|
12
12
|
import type { Ctx } from '@ultimat3/core';
|
|
13
13
|
import type { NotifyEvent, Recipient } from './notification';
|
|
14
14
|
|
|
15
|
-
export interface
|
|
16
|
-
|
|
15
|
+
export interface PreferenceBatchQuery<Params = unknown> {
|
|
16
|
+
/** One chunk of the audience — at most `NOTIFY_CHUNK_SIZE` (500), each id once. */
|
|
17
|
+
readonly recipients: readonly Recipient[];
|
|
17
18
|
/** The notifier's name — the app's taxonomy key, whatever its taxonomy is. */
|
|
18
19
|
readonly notifier: string;
|
|
19
20
|
readonly channel: string;
|
|
@@ -24,12 +25,14 @@ export interface PreferenceQuery<Params = unknown> {
|
|
|
24
25
|
|
|
25
26
|
export interface PreferenceStore {
|
|
26
27
|
/**
|
|
27
|
-
* `
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
28
|
+
* The ids in `query.recipients` this channel may reach — ONE read per chunk, never one per
|
|
29
|
+
* recipient: a 10k audience asked one at a time was 20k round trips for two channels. An id
|
|
30
|
+
* answered that is not in the chunk is ignored. Leaving an id out suppresses THIS channel and
|
|
31
|
+
* nothing else — the other channels of the same notifier still fire, which is why the gate is
|
|
32
|
+
* asked per channel: "email me weekly, ping me in-app immediately" is one recipient's normal
|
|
33
|
+
* answer. The one method, required (31.0.0 replaced `allows(query)`): one way to ask.
|
|
31
34
|
*/
|
|
32
|
-
|
|
35
|
+
allowsMany(query: PreferenceBatchQuery): Promise<Iterable<string>> | Iterable<string>;
|
|
33
36
|
}
|
|
34
37
|
|
|
35
38
|
/**
|
|
@@ -37,7 +40,9 @@ export interface PreferenceStore {
|
|
|
37
40
|
* the right default for a framework: silence-by-default would mean a notifier that delivers
|
|
38
41
|
* nothing until an app writes a store, and the first symptom would be a missing email.
|
|
39
42
|
*/
|
|
40
|
-
export const allowAllPreferences = (): PreferenceStore => ({
|
|
43
|
+
export const allowAllPreferences = (): PreferenceStore => ({
|
|
44
|
+
allowsMany: (query) => query.recipients.map((recipient) => recipient.id),
|
|
45
|
+
});
|
|
41
46
|
|
|
42
47
|
export interface MemoryPreferenceStore extends PreferenceStore {
|
|
43
48
|
/** Opt `recipient` out of `channel` for `notifier`. `'*'` as the notifier is every notifier. */
|
|
@@ -54,13 +59,13 @@ const optOutKey = (recipient: string, notifier: string, channel: string): string
|
|
|
54
59
|
*/
|
|
55
60
|
export function memoryPreferenceStore(): MemoryPreferenceStore {
|
|
56
61
|
const denied = new Set<string>();
|
|
62
|
+
const allows = (id: string, notifier: string, channel: string): boolean =>
|
|
63
|
+
!denied.has(optOutKey(id, notifier, channel)) && !denied.has(optOutKey(id, '*', channel));
|
|
57
64
|
return {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
!denied.has(optOutKey(id, '*', query.channel))
|
|
63
|
-
);
|
|
65
|
+
allowsMany(query) {
|
|
66
|
+
return query.recipients
|
|
67
|
+
.map((recipient) => recipient.id)
|
|
68
|
+
.filter((id) => allows(id, query.notifier, query.channel));
|
|
64
69
|
},
|
|
65
70
|
deny(input) {
|
|
66
71
|
denied.add(optOutKey(input.recipient, input.notifier, input.channel));
|
package/src/retention.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// The three sweeps over this package's tables, read off the installed seam rather than off a store
|
|
2
|
-
// somebody handed the caller.
|
|
2
|
+
// somebody handed the caller. The stores are an APP's `runtime.ts` line, installed after the boot that
|
|
3
3
|
// owns the hourly sweep, so the sweep cannot hold the stores — it can only ask, per attempt, what
|
|
4
4
|
// is installed now. Same shape and the same reason as `purgeAuthLimits()`.
|
|
5
5
|
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// SMS as a channel, over the `smsTransport` port: per recipient, its E.164 number, the message as a
|
|
2
|
+
// catalog KEY rendered in the recipient's locale, one idempotency key per delivery. The provider is
|
|
3
|
+
// the app's adapter (`smsTransport:` in `apps/<app>/runtime.ts`); this is the reference channel.
|
|
4
|
+
//
|
|
5
|
+
// smsChannel<LoginCode>({ message: ({ event }) => ({ key: 'sms.login_code', params: { code: event.params.code } }) })
|
|
6
|
+
|
|
7
|
+
import { currentLocale, translatorFor } from '@ultimat3/i18n';
|
|
8
|
+
import type { DeliveryArgs, NotifyChannel } from './channel';
|
|
9
|
+
import { deliveryChannel } from './channel';
|
|
10
|
+
import type { Recipient } from './notification';
|
|
11
|
+
import type { PushTranslate } from './push-message';
|
|
12
|
+
import type { SmsTransport } from './sms-transport';
|
|
13
|
+
import { assertSmsNumber, smsTransport } from './sms-transport';
|
|
14
|
+
|
|
15
|
+
export const SMS_CHANNEL = 'sms';
|
|
16
|
+
|
|
17
|
+
/** What one SMS says, as a catalog key and its params — never text (`t()`, house rule). */
|
|
18
|
+
export interface NotifySmsMessage {
|
|
19
|
+
readonly key: string;
|
|
20
|
+
readonly params?: Readonly<Record<string, string | number>> | undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SmsChannelOptions<Params> {
|
|
24
|
+
readonly message: (args: DeliveryArgs<Params>) => NotifySmsMessage;
|
|
25
|
+
/**
|
|
26
|
+
* Where the number comes from. Defaults to `recipient.to`. `undefined` back is a recipient with
|
|
27
|
+
* no phone — settled as sent and logged `notify.address_missing`, as `mailChannel` does.
|
|
28
|
+
*/
|
|
29
|
+
readonly numberOf?: ((recipient: Recipient) => string | undefined) | undefined;
|
|
30
|
+
readonly name?: string | undefined;
|
|
31
|
+
/** Defaults to the installed `smsTransport()`, read per delivery. A test may hand one in. */
|
|
32
|
+
readonly transport?: SmsTransport | undefined;
|
|
33
|
+
/** Defaults to `translatorFor(locale)`. The recipient's locale, else the app's fallback. */
|
|
34
|
+
readonly translate?: ((locale: string) => PushTranslate) | undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The key a provider dedupes on: the same for every attempt of one (notification, channel,
|
|
39
|
+
* recipient) — the delivery ledger's own key — and holding no number.
|
|
40
|
+
*/
|
|
41
|
+
export const smsIdempotencyKey = (
|
|
42
|
+
notifier: string,
|
|
43
|
+
eventKey: string,
|
|
44
|
+
channel: string,
|
|
45
|
+
recipient: string,
|
|
46
|
+
): string => JSON.stringify([notifier, eventKey, channel, recipient]);
|
|
47
|
+
|
|
48
|
+
export function smsChannel<Params = unknown>(
|
|
49
|
+
options: SmsChannelOptions<Params>,
|
|
50
|
+
): NotifyChannel<Params> {
|
|
51
|
+
const name = options.name ?? SMS_CHANNEL;
|
|
52
|
+
const numberOf = options.numberOf ?? ((recipient: Recipient) => recipient.to);
|
|
53
|
+
const translate = options.translate ?? ((locale: string) => translatorFor(locale));
|
|
54
|
+
return deliveryChannel<Params>(name, async (args) => {
|
|
55
|
+
const { recipient, event, ctx, signal } = args;
|
|
56
|
+
const to = numberOf(recipient);
|
|
57
|
+
if (to === undefined || to === '') {
|
|
58
|
+
ctx.logger.warn('notify.address_missing', { recipient: recipient.id, channel: name });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
// Refused before rendering or sending: a number that is wrong now is wrong on every retry.
|
|
62
|
+
assertSmsNumber(to, recipient.id);
|
|
63
|
+
const message = options.message(args);
|
|
64
|
+
const body = translate(recipient.locale ?? currentLocale())(message.key, message.params);
|
|
65
|
+
await (options.transport ?? smsTransport()).send({
|
|
66
|
+
to,
|
|
67
|
+
body,
|
|
68
|
+
idempotencyKey: smsIdempotencyKey(event.notifier, event.key, name, recipient.id),
|
|
69
|
+
signal,
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Single responsibility: the SMS seam's two refusals. Registered and classified with the rest of the
|
|
2
|
+
// package's codes in `errors.ts`. No cause ever carries a phone number or a message body: both are
|
|
3
|
+
// a person's, and a cause lands in logs, traces and the dead-letter row.
|
|
4
|
+
|
|
5
|
+
import { UltimateError } from '@ultimat3/core';
|
|
6
|
+
// Bare: the titles these codes render with, and their retry classification, are registered there.
|
|
7
|
+
import './errors';
|
|
8
|
+
|
|
9
|
+
/** No transport installed, outside development and test — where the memory one stands in. */
|
|
10
|
+
export class NotifySmsTransportMissingError extends UltimateError {
|
|
11
|
+
constructor() {
|
|
12
|
+
super({
|
|
13
|
+
code: 'X_NOTIFY_SMS_TRANSPORT_MISSING',
|
|
14
|
+
cause:
|
|
15
|
+
'an SMS was sent with no SmsTransport installed: outside development and test the memory transport would swallow the message, so the send is refused',
|
|
16
|
+
fix: 'smsTransport: yourTransport(), # in apps/<app>/runtime.ts — behavesLike(smsTransportConformance, () => yourTransport()) from @ultimat3/testing/conformance proves it',
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A number that is not E.164. The number itself stays out of the cause: `meta.recipient` names whose. */
|
|
22
|
+
export class NotifySmsNumberInvalidError extends UltimateError {
|
|
23
|
+
constructor(input: { readonly recipient: string | undefined }) {
|
|
24
|
+
super({
|
|
25
|
+
code: 'X_NOTIFY_SMS_NUMBER_INVALID',
|
|
26
|
+
cause:
|
|
27
|
+
'an SMS number is not E.164 (+, a country code, at most 15 digits in all): a local spelling is a number a provider guesses the country of',
|
|
28
|
+
fix: "smsChannel({ numberOf: (recipient) => recipient.to }) # answering E.164 ('+4915112345678'): store numbers that way",
|
|
29
|
+
...(input.recipient === undefined ? {} : { meta: { recipient: input.recipient } }),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// The `smsTransport` port: what an SMS provider adapter implements, the memory reference, and the
|
|
2
|
+
// boot's slot. Twilio, Vonage, SNS are the APP's adapters (axiom 8) — this package ships the seam,
|
|
3
|
+
// the E.164 check every transport makes, and a transport that never leaves the process.
|
|
4
|
+
|
|
5
|
+
import { isLocal } from '@ultimat3/core';
|
|
6
|
+
import { adapterSlot } from '@ultimat3/core/adapter';
|
|
7
|
+
import { NotifySmsNumberInvalidError, NotifySmsTransportMissingError } from './sms-errors';
|
|
8
|
+
|
|
9
|
+
/** One message, already rendered. The transport never sees catalog keys or a recipient row. */
|
|
10
|
+
export interface SmsMessage {
|
|
11
|
+
/** E.164: `+`, a country code, at most 15 digits in all. `assertSmsNumber` is the check. */
|
|
12
|
+
readonly to: string;
|
|
13
|
+
readonly body: string;
|
|
14
|
+
/**
|
|
15
|
+
* The same on every attempt of one delivery. A provider that dedupes reads it; one that does not
|
|
16
|
+
* still answers it back, so a caller can match a retry to its first send.
|
|
17
|
+
*/
|
|
18
|
+
readonly idempotencyKey: string;
|
|
19
|
+
/** The delivery's cancellation. Hand it to `fetch`. */
|
|
20
|
+
readonly signal?: AbortSignal | undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SmsSendResult {
|
|
24
|
+
/** The transport's own `name`. */
|
|
25
|
+
readonly transport: string;
|
|
26
|
+
/** The provider's message id. Never the number, the body or the idempotency key: it is logged. */
|
|
27
|
+
readonly id: string;
|
|
28
|
+
/** The number accepted — `message.to`. */
|
|
29
|
+
readonly to: string;
|
|
30
|
+
readonly idempotencyKey: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The port. A rejection is a failed delivery; the notifier's job decides whether it retries. */
|
|
34
|
+
export interface SmsTransport {
|
|
35
|
+
readonly name: string;
|
|
36
|
+
send(message: SmsMessage): Promise<SmsSendResult>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const E164 = /^\+[1-9]\d{1,14}$/;
|
|
40
|
+
|
|
41
|
+
/** Whether `value` is an E.164 number — what every transport and `smsChannel` refuse otherwise. */
|
|
42
|
+
export const isSmsNumber = (value: string): boolean => E164.test(value);
|
|
43
|
+
|
|
44
|
+
/** Refuses a non-E.164 number with `X_NOTIFY_SMS_NUMBER_INVALID`. Every transport calls it first. */
|
|
45
|
+
export function assertSmsNumber(value: string, recipient?: string): void {
|
|
46
|
+
if (!isSmsNumber(value)) throw new NotifySmsNumberInvalidError({ recipient });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface MemorySmsTransport extends SmsTransport {
|
|
50
|
+
/** Every accepted message, oldest first — what a test asserts on. */
|
|
51
|
+
readonly sent: readonly SmsMessage[];
|
|
52
|
+
clear(): void;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The reference transport: keeps messages in the heap and answers a fresh id per send. Never a
|
|
57
|
+
* production default — `smsTransport()` refuses outside development and test instead.
|
|
58
|
+
*/
|
|
59
|
+
export function memorySmsTransport(name = 'memory'): MemorySmsTransport {
|
|
60
|
+
const sent: SmsMessage[] = [];
|
|
61
|
+
return {
|
|
62
|
+
name,
|
|
63
|
+
sent,
|
|
64
|
+
clear: () => {
|
|
65
|
+
sent.length = 0;
|
|
66
|
+
},
|
|
67
|
+
send(message) {
|
|
68
|
+
assertSmsNumber(message.to);
|
|
69
|
+
sent.push({ to: message.to, body: message.body, idempotencyKey: message.idempotencyKey });
|
|
70
|
+
return Promise.resolve({
|
|
71
|
+
transport: name,
|
|
72
|
+
id: `sms_${crypto.randomUUID()}`,
|
|
73
|
+
to: message.to,
|
|
74
|
+
idempotencyKey: message.idempotencyKey,
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let localMemory: MemorySmsTransport | undefined;
|
|
81
|
+
|
|
82
|
+
/** The default: one memory transport per process in development and test, a refusal elsewhere. */
|
|
83
|
+
const localTransport = (): SmsTransport => ({
|
|
84
|
+
name: 'memory',
|
|
85
|
+
send(message) {
|
|
86
|
+
if (!isLocal()) return Promise.reject(new NotifySmsTransportMissingError());
|
|
87
|
+
localMemory ??= memorySmsTransport();
|
|
88
|
+
return localMemory.send(message);
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
const slot = adapterSlot<SmsTransport>(localTransport);
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The boot's installer, on `@ultimat3/notify/adapter` only: an app names `smsTransport:` in
|
|
96
|
+
* `apps/<app>/runtime.ts`. Its release removes THIS install, in any order (`adapterSlot`).
|
|
97
|
+
*/
|
|
98
|
+
export function installSmsTransport(transport: SmsTransport): () => void {
|
|
99
|
+
return slot.install(transport);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Back to the default, for a test that installed one and must hand the process back. */
|
|
103
|
+
export function resetSmsTransport(): void {
|
|
104
|
+
slot.reset();
|
|
105
|
+
localMemory = undefined;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The installed transport, read per send — a channel is declared long before a boot installs. */
|
|
109
|
+
export const smsTransport = (): SmsTransport => slot.current();
|
package/src/stores.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
// The four seams a fan-out reads, installed once per process. Same shape as `
|
|
2
|
-
// @ultimat3/jobs and for the same reason: a notifier is declared at import time, long before a
|
|
1
|
+
// The four seams a fan-out reads, installed once per process. Same shape as `installJobDriver` in
|
|
2
|
+
// @ultimat3/jobs/adapter and for the same reason: a notifier is declared at import time, long before a
|
|
3
3
|
// boot has a database, so the store cannot be a constructor argument.
|
|
4
4
|
//
|
|
5
5
|
// One installer, never four. Handing them over in one call is what makes "the ledger is Postgres
|
|
6
6
|
// but the inbox is still the memory one" a visible line of code rather than a forgotten fifth call.
|
|
7
7
|
|
|
8
|
+
import { isLocal } from '@ultimat3/core';
|
|
9
|
+
import { adapterSlot } from '@ultimat3/core/adapter';
|
|
8
10
|
import type { DigestStore } from './digest';
|
|
9
11
|
import { NotifyStoreMissingError } from './errors';
|
|
10
12
|
import type { InboxStore } from './inbox';
|
|
@@ -15,10 +17,10 @@ import { allowAllPreferences } from './preferences';
|
|
|
15
17
|
|
|
16
18
|
export interface NotifyStores {
|
|
17
19
|
/**
|
|
18
|
-
* Defaults to `memoryDeliveryLedger()
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
20
|
+
* Defaults to `memoryDeliveryLedger()` in development and test ONLY (`localDeliveryLedger`). In
|
|
21
|
+
* staging and production the default refuses its first claim with `X_NOTIFY_STORE_MISSING`: a
|
|
22
|
+
* heap map behind two replicas, or across a restart, lets a replayed attempt claim cleanly and
|
|
23
|
+
* send twice — the failure this ledger exists to prevent, and silent.
|
|
22
24
|
*/
|
|
23
25
|
readonly ledger?: DeliveryLedger | undefined;
|
|
24
26
|
/** No default: a channel that writes the inbox refuses rather than dropping the row. */
|
|
@@ -38,43 +40,71 @@ export interface InstalledNotifyStores {
|
|
|
38
40
|
readonly digest: DigestStore | undefined;
|
|
39
41
|
}
|
|
40
42
|
|
|
43
|
+
/**
|
|
44
|
+
* The default ledger: a memory one in development and test, a refusal anywhere else. Decided at
|
|
45
|
+
* the first call, never at import — the environment is read when a notification is actually sent,
|
|
46
|
+
* and one memory ledger serves the process so a local replay is still deduped.
|
|
47
|
+
*/
|
|
48
|
+
function localDeliveryLedger(): DeliveryLedger {
|
|
49
|
+
let memory: DeliveryLedger | undefined;
|
|
50
|
+
const local = (notifier: string): Promise<DeliveryLedger> => {
|
|
51
|
+
if (!isLocal())
|
|
52
|
+
return Promise.reject(new NotifyStoreMissingError({ notifier, store: 'ledger' }));
|
|
53
|
+
memory ??= memoryDeliveryLedger();
|
|
54
|
+
return Promise.resolve(memory);
|
|
55
|
+
};
|
|
56
|
+
return {
|
|
57
|
+
claim: async (claim, at) => (await local(claim.notifier)).claim(claim, at),
|
|
58
|
+
settle: async (claim, status, at, claimId) =>
|
|
59
|
+
(await local(claim.notifier)).settle(claim, status, at, claimId),
|
|
60
|
+
find: async (claim) => (await local(claim.notifier)).find(claim),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
41
64
|
const defaults = (): InstalledNotifyStores => ({
|
|
42
|
-
ledger:
|
|
65
|
+
ledger: localDeliveryLedger(),
|
|
43
66
|
inbox: undefined,
|
|
44
67
|
preferences: allowAllPreferences(),
|
|
45
68
|
digest: undefined,
|
|
46
69
|
});
|
|
47
70
|
|
|
48
|
-
let
|
|
71
|
+
let base: InstalledNotifyStores = defaults();
|
|
72
|
+
/** The installed stores: a stack over the defaults, released in any order. */
|
|
73
|
+
const slot = adapterSlot<InstalledNotifyStores>(() => base);
|
|
49
74
|
|
|
50
|
-
/**
|
|
51
|
-
*
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
75
|
+
/**
|
|
76
|
+
* The boot's installer (its release removes THIS install only, in any order — `adapterSlot`), on `@ultimat3/notify/adapter` and never the `.` barrel: an app hands its
|
|
77
|
+
* stores over with `notifyStores:` in `apps/<app>/runtime.ts`. Whole-object replacement, never a
|
|
78
|
+
* merge: two calls with different halves is the split-brain `RuntimeOverrides` exists to refuse,
|
|
79
|
+
* and a merge would hide the second call's omissions.
|
|
80
|
+
*/
|
|
81
|
+
export function installNotifyStores(stores: NotifyStores): () => void {
|
|
82
|
+
return slot.install({
|
|
83
|
+
ledger: stores.ledger ?? localDeliveryLedger(),
|
|
55
84
|
inbox: stores.inbox,
|
|
56
85
|
preferences: stores.preferences ?? allowAllPreferences(),
|
|
57
86
|
digest: stores.digest,
|
|
58
|
-
};
|
|
87
|
+
});
|
|
59
88
|
}
|
|
60
89
|
|
|
61
|
-
export const notifyStores = (): InstalledNotifyStores =>
|
|
90
|
+
export const notifyStores = (): InstalledNotifyStores => slot.current();
|
|
62
91
|
|
|
63
92
|
/** Tests only — the same escape `resetJobDriver` offers, so one suite cannot leak into the next. */
|
|
64
93
|
export function resetNotifyStores(): void {
|
|
65
|
-
|
|
94
|
+
slot.reset();
|
|
95
|
+
base = defaults();
|
|
66
96
|
}
|
|
67
97
|
|
|
68
98
|
/** The inbox, or the refusal that names the install call. Never an optional chain at the call
|
|
69
99
|
* site: a silently skipped inbox write is a notification the user never sees and nobody logs. */
|
|
70
100
|
export function requireInbox(notifier: string): InboxStore {
|
|
71
|
-
const store =
|
|
101
|
+
const store = slot.current().inbox;
|
|
72
102
|
if (store === undefined) throw new NotifyStoreMissingError({ notifier, store: 'inbox' });
|
|
73
103
|
return store;
|
|
74
104
|
}
|
|
75
105
|
|
|
76
106
|
export function requireDigest(notifier: string): DigestStore {
|
|
77
|
-
const store =
|
|
107
|
+
const store = slot.current().digest;
|
|
78
108
|
if (store === undefined) throw new NotifyStoreMissingError({ notifier, store: 'digest' });
|
|
79
109
|
return store;
|
|
80
110
|
}
|