@cslug/notification 0.2.0 → 0.4.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/README.md +5 -2
- package/docs/README.md +46 -3
- package/docs/api.md +16 -0
- package/migrations/00000000_000400_cslug_notifications.sql +27 -0
- package/package.json +13 -5
- package/src/fake.ts +73 -0
- package/src/index.ts +15 -4
- package/src/notification.ts +64 -0
- package/src/notifier.ts +153 -0
- package/src/provider.ts +86 -0
package/README.md
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
# @cslug/notification
|
|
2
2
|
|
|
3
|
-
Notifications over mail, database, WhatsApp and
|
|
3
|
+
Notifications over mail, database, WhatsApp, SMS and custom channels: each message built in the recipient's
|
|
4
|
+
locale, one job per delivery, delivery records, and a fake for tests. List `NotificationProvider` in
|
|
5
|
+
`bootstrap/providers.ts` (after `MailProvider` for the mail channel).
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
8
|
+
[guide 14](../../guides/14-mail-and-notifications.md#notifications).
|
package/docs/README.md
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
# @cslug/notification
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
List `NotificationProvider` in `bootstrap/providers.ts` and inject `Notifier`. The guide is
|
|
4
|
+
[guide 14](../../../guides/14-mail-and-notifications.md#notifications).
|
|
4
5
|
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
## Notifications
|
|
7
|
+
|
|
8
|
+
A `Notification` lists its channels per recipient in `via(to)` and builds one message per channel in
|
|
9
|
+
`to<Channel>(to)`: `toMail` returns a `Mailable`, `toDatabase`, `toWhatsapp`, `toSms` and custom channels return a
|
|
10
|
+
JSON value. `static notificationName` names the type stored with deliveries (default: the class name).
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
await notifier.send(traveller, new CheckinDueNotification(booking, 'mid_trip'))
|
|
14
|
+
await notifier.sendMany(travellers, new CrisisNotice(notice))
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Recipients
|
|
18
|
+
|
|
19
|
+
Any object. Its routes are read from `id`, `email`, `whatsapp` (else `phone`), `phone`, `locale` and `name`;
|
|
20
|
+
`recipient(row, (row) => ({ … }))` sets them explicitly (for example, WhatsApp only with consent).
|
|
21
|
+
|
|
22
|
+
## Delivery
|
|
23
|
+
|
|
24
|
+
When `send()` runs, every message is built in the recipient's locale (`withLocale`). Then, per channel:
|
|
25
|
+
|
|
26
|
+
- `mail`: handed to the Mailer, `mailer.to(email).locale(locale).queue(mailable)`, so it is rendered now and sent
|
|
27
|
+
by the Mailer's job `cslug.mail` (`notification.queued: false` sends it instead).
|
|
28
|
+
- `database`: a `cslug_notifications` row (`recipient_id`, `type`, `data`, `read_at`) in the current transaction.
|
|
29
|
+
- other channels: one job `cslug.notification` per delivery on `notification.queue` (default `default`), so a
|
|
30
|
+
failure retries that channel only. Inside a transaction the job waits for COMMIT. Without @cslug/queue (or with
|
|
31
|
+
`queued: false`) it runs after COMMIT in the process.
|
|
32
|
+
|
|
33
|
+
With @cslug/database, every delivery is recorded in `cslug_notification_deliveries` (`channel`, `status`: `queued`,
|
|
34
|
+
`sent`, `manual`, `failed` with `error`, and the message); `cslug migrate` creates both tables.
|
|
35
|
+
|
|
36
|
+
## Channels
|
|
37
|
+
|
|
38
|
+
- `whatsapp` and `sms`: driver `log` (default, logs `notification.logged`) or `manual` (config
|
|
39
|
+
`notification.whatsapp.driver`): the delivery is recorded with status `manual` for staff to send.
|
|
40
|
+
- Custom: implement `Channel` (`send(to, message, delivery)`; `manual = true` to only record) and register it in a
|
|
41
|
+
provider's `boot()`: `this.app.resolve(Notifier).extend('slack', SlackChannel)`. A class is built by the
|
|
42
|
+
container, so it can `@inject` what it needs. `extend` also replaces a built-in channel.
|
|
43
|
+
|
|
44
|
+
## Tests
|
|
45
|
+
|
|
46
|
+
`testApp({ fakes: ['notify'] })` → `t.notify`: messages are built for every channel (so `toMail` and the others run)
|
|
47
|
+
and recorded, never delivered. `assertSentTo(to, Cls, { channel?, where? })`, `assertNotSentTo(to, Cls)`,
|
|
48
|
+
`assertNothingSent()`, `sentTo(to, Cls?, channel?)`, `sent`. A recipient matches by the same object, the same `id`,
|
|
49
|
+
else the same email.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# @cslug/notification: API
|
|
2
|
+
|
|
3
|
+
| | |
|
|
4
|
+
|---|---|
|
|
5
|
+
| `Notification` | `via(to)` → channel names; `to<Channel>(to)` → message; `type`; `messageFor(channel, to)`; `static notificationName` |
|
|
6
|
+
| `Notifier` | Injectable. `send(to, notification)`, `sendMany(recipients, notification)`, `extend(name, channel)`, `channel(name)`, `run(delivery)` (what the job calls) |
|
|
7
|
+
| `Recipient` | `{ id?, email?, whatsapp?, phone?, locale?, name? }` |
|
|
8
|
+
| `recipient(value, fn)` | `value` with explicit routes |
|
|
9
|
+
| `routeOf(value)` | The routes of a recipient object |
|
|
10
|
+
| `Channel` | `send(to, message, delivery)`; `manual?` |
|
|
11
|
+
| `LogChannel`, `ManualChannel` | The `log` and `manual` drivers |
|
|
12
|
+
| `Delivery` | `{ id, recipientId?, type, channel, to, message }` (the job payload) |
|
|
13
|
+
| `NotificationStore` | `notify`, `record`, `mark`: set by the provider with @cslug/database |
|
|
14
|
+
| `NotificationProvider` | Config `notification`: `queued` (true), `queue` (`default`), `whatsapp.driver` / `sms.driver` (`log`, `manual`). Registers the migrations and the job `cslug.notification` when database and queue are installed |
|
|
15
|
+
| `NOTIFICATION_MIGRATIONS` | The migration folder (`cslug_notifications`, `cslug_notification_deliveries`) |
|
|
16
|
+
| `NotificationFake`, `installNotificationFake(app)` | `fakes: ['notify']`: `assertSentTo`, `assertNotSentTo`, `assertNothingSent`, `sentTo`, `sent` |
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
-- up
|
|
2
|
+
create table cslug_notifications (
|
|
3
|
+
id uuid primary key,
|
|
4
|
+
recipient_id text,
|
|
5
|
+
type text not null,
|
|
6
|
+
data jsonb not null,
|
|
7
|
+
read_at timestamptz,
|
|
8
|
+
created_at timestamptz not null default now()
|
|
9
|
+
);
|
|
10
|
+
create index cslug_notifications_recipient_idx on cslug_notifications (recipient_id, created_at desc);
|
|
11
|
+
|
|
12
|
+
create table cslug_notification_deliveries (
|
|
13
|
+
id uuid primary key,
|
|
14
|
+
recipient_id text,
|
|
15
|
+
type text not null,
|
|
16
|
+
channel text not null,
|
|
17
|
+
status text not null,
|
|
18
|
+
message jsonb,
|
|
19
|
+
error text,
|
|
20
|
+
created_at timestamptz not null default now(),
|
|
21
|
+
updated_at timestamptz not null default now()
|
|
22
|
+
);
|
|
23
|
+
create index cslug_notification_deliveries_status_idx on cslug_notification_deliveries (status, created_at);
|
|
24
|
+
|
|
25
|
+
-- down
|
|
26
|
+
drop table cslug_notification_deliveries;
|
|
27
|
+
drop table cslug_notifications;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/notification",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Notifications over mail, database, WhatsApp and SMS channels.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
},
|
|
21
21
|
"files": [
|
|
22
22
|
"src",
|
|
23
|
+
"migrations",
|
|
23
24
|
"docs",
|
|
24
25
|
"stubs",
|
|
25
26
|
"README.md"
|
|
@@ -28,10 +29,10 @@
|
|
|
28
29
|
"bun": ">=1.3.14"
|
|
29
30
|
},
|
|
30
31
|
"peerDependencies": {
|
|
31
|
-
"@cslug/core": "0.
|
|
32
|
-
"@cslug/mail": "0.
|
|
33
|
-
"@cslug/queue": "0.
|
|
34
|
-
"@cslug/database": "0.
|
|
32
|
+
"@cslug/core": "0.4.0",
|
|
33
|
+
"@cslug/mail": "0.4.0",
|
|
34
|
+
"@cslug/queue": "0.4.0",
|
|
35
|
+
"@cslug/database": "0.4.0"
|
|
35
36
|
},
|
|
36
37
|
"peerDependenciesMeta": {
|
|
37
38
|
"@cslug/mail": {
|
|
@@ -43,5 +44,12 @@
|
|
|
43
44
|
"@cslug/database": {
|
|
44
45
|
"optional": true
|
|
45
46
|
}
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@cslug/testing": "workspace:*",
|
|
50
|
+
"@cslug/database": "workspace:*",
|
|
51
|
+
"@cslug/queue": "workspace:*",
|
|
52
|
+
"@cslug/redis": "workspace:*",
|
|
53
|
+
"@cslug/mail": "workspace:*"
|
|
46
54
|
}
|
|
47
55
|
}
|
package/src/fake.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { type Application, Logger } from '@cslug/core'
|
|
2
|
+
import { type Notification, type Recipient, routeOf } from './notification'
|
|
3
|
+
import { type Delivery, Notifier } from './notifier'
|
|
4
|
+
|
|
5
|
+
/** A delivery the fake recorded: the recipient object, its routes, the notification and the built message. */
|
|
6
|
+
export type SentNotification<N extends Notification = Notification> = Delivery & { recipient: object; notification: N }
|
|
7
|
+
|
|
8
|
+
type NotificationClass<N extends Notification> = abstract new (...args: never[]) => N
|
|
9
|
+
|
|
10
|
+
const same = (a: Recipient, b: Recipient) => (a.id !== undefined ? a.id === b.id : !!a.email && a.email === b.email)
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Notifications in tests (`testApp({ fakes: ['notify'] })` → `t.notify`): messages are built for every channel (so
|
|
14
|
+
* `toMail` and friends run) and recorded, never delivered.
|
|
15
|
+
*/
|
|
16
|
+
export class NotificationFake extends Notifier {
|
|
17
|
+
readonly sent: SentNotification[] = []
|
|
18
|
+
private current?: { recipient: object; notification: Notification }
|
|
19
|
+
|
|
20
|
+
constructor(app: Application) {
|
|
21
|
+
super(app, {}, Logger.null())
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
override async send(to: object, notification: Notification): Promise<void> {
|
|
25
|
+
this.current = { recipient: to, notification }
|
|
26
|
+
await super.send(to, notification)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
protected override async deliver(delivery: Delivery): Promise<void> {
|
|
30
|
+
if (this.current) this.sent.push({ ...delivery, ...this.current })
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What was sent to `to` (same object, same `id`, else same email), optionally of one class or on one channel. */
|
|
34
|
+
sentTo<N extends Notification>(to: object, cls?: NotificationClass<N>, channel?: string): SentNotification<N>[] {
|
|
35
|
+
const route = routeOf(to)
|
|
36
|
+
return this.sent.filter(
|
|
37
|
+
(s) =>
|
|
38
|
+
(s.recipient === to || same(route, s.to)) &&
|
|
39
|
+
(!cls || s.notification instanceof cls) &&
|
|
40
|
+
(!channel || s.channel === channel),
|
|
41
|
+
) as SentNotification<N>[]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
assertSentTo<N extends Notification>(
|
|
45
|
+
to: object,
|
|
46
|
+
cls: NotificationClass<N>,
|
|
47
|
+
options: { channel?: string; where?: (sent: SentNotification<N>) => boolean } = {},
|
|
48
|
+
): void {
|
|
49
|
+
const found = this.sentTo(to, cls, options.channel)
|
|
50
|
+
if (!found.some((s) => !options.where || options.where(s)))
|
|
51
|
+
throw new Error(
|
|
52
|
+
`Expected ${cls.name}${options.channel ? ` via ${options.channel}` : ''} to ${JSON.stringify(routeOf(to))}; sent: ${this.describe()}`,
|
|
53
|
+
)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
assertNotSentTo<N extends Notification>(to: object, cls: NotificationClass<N>): void {
|
|
57
|
+
if (this.sentTo(to, cls).length) throw new Error(`Expected no ${cls.name} to ${JSON.stringify(routeOf(to))}`)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
assertNothingSent(): void {
|
|
61
|
+
if (this.sent.length) throw new Error(`Expected no notification; sent: ${this.describe()}`)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private describe(): string {
|
|
65
|
+
return this.sent.map((s) => `${s.type} via ${s.channel} to ${JSON.stringify(s.to)}`).join(', ') || 'none'
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function installNotificationFake(app: Application): NotificationFake {
|
|
70
|
+
const fake = new NotificationFake(app)
|
|
71
|
+
app.swap(Notifier, fake)
|
|
72
|
+
return fake
|
|
73
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @cslug/notification:
|
|
3
|
-
*
|
|
4
|
-
* Not implemented yet. See docs/packages.md and docs/implementation-plan.md.
|
|
2
|
+
* @cslug/notification: notifications over mail, database, WhatsApp, SMS and custom channels, one job per
|
|
3
|
+
* delivery, delivery records, and a fake for tests.
|
|
5
4
|
*/
|
|
6
|
-
export {}
|
|
5
|
+
export { installNotificationFake, NotificationFake, type SentNotification } from './fake'
|
|
6
|
+
export { Notification, type Recipient, recipient, routeOf } from './notification'
|
|
7
|
+
export {
|
|
8
|
+
type Channel,
|
|
9
|
+
type Delivery,
|
|
10
|
+
type DeliveryStatus,
|
|
11
|
+
LogChannel,
|
|
12
|
+
ManualChannel,
|
|
13
|
+
type NotificationConfig,
|
|
14
|
+
type NotificationStore,
|
|
15
|
+
Notifier,
|
|
16
|
+
} from './notifier'
|
|
17
|
+
export { NOTIFICATION_MIGRATIONS, NotificationProvider } from './provider'
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Where a notification goes. Read from the recipient object (`email`, `whatsapp` or else `phone`, `phone`,
|
|
5
|
+
* `locale`, `name`, `id`); `recipient(row, fn)` sets them explicitly.
|
|
6
|
+
*/
|
|
7
|
+
export type Recipient = {
|
|
8
|
+
id?: string
|
|
9
|
+
email?: string
|
|
10
|
+
whatsapp?: string
|
|
11
|
+
phone?: string
|
|
12
|
+
locale?: string
|
|
13
|
+
name?: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const ROUTES = Symbol('cslug.notification.routes')
|
|
17
|
+
type Routed = { [ROUTES]: Recipient }
|
|
18
|
+
|
|
19
|
+
/** `notifier.send(recipient(traveller, (t) => ({ whatsapp: t.whatsappOptIn ? t.phone : undefined })), n)` */
|
|
20
|
+
export function recipient<T extends object>(value: T, routes: (value: T) => Partial<Recipient>): T & Routed {
|
|
21
|
+
return { ...value, [ROUTES]: { ...routeOf(value), ...routes(value) } }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const str = (v: unknown) => (typeof v === 'string' && v ? v : undefined)
|
|
25
|
+
|
|
26
|
+
/** The routes of any recipient object. */
|
|
27
|
+
export function routeOf(value: object): Recipient {
|
|
28
|
+
if (ROUTES in value) return (value as Routed)[ROUTES]
|
|
29
|
+
const v = value as Record<string, unknown>
|
|
30
|
+
const id = v.id === undefined || v.id === null ? undefined : String(v.id)
|
|
31
|
+
const route: Recipient = {
|
|
32
|
+
id,
|
|
33
|
+
email: str(v.email),
|
|
34
|
+
whatsapp: str(v.whatsapp) ?? str(v.phone),
|
|
35
|
+
phone: str(v.phone),
|
|
36
|
+
locale: str(v.locale),
|
|
37
|
+
name: str(v.name),
|
|
38
|
+
}
|
|
39
|
+
return Object.fromEntries(Object.entries(route).filter(([, x]) => x !== undefined)) as Recipient
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A notification: `via(to)` lists channels; `to<Channel>(to)` builds each message (`toMail` a Mailable,
|
|
44
|
+
* `toDatabase` / `toWhatsapp` / `toSms` / custom channels a JSON value). Messages are built when it is sent, in the
|
|
45
|
+
* recipient's locale; channels then deliver them, each as its own job.
|
|
46
|
+
*/
|
|
47
|
+
export abstract class Notification {
|
|
48
|
+
abstract via(to: Recipient): string[]
|
|
49
|
+
|
|
50
|
+
/** The type stored with deliveries (`static notificationName`, else the class name). */
|
|
51
|
+
get type(): string {
|
|
52
|
+
const cls = this.constructor as { notificationName?: string; name: string }
|
|
53
|
+
return cls.notificationName ?? cls.name
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The message for one channel (`toWhatsapp` for `whatsapp`). */
|
|
57
|
+
messageFor(channel: string, to: Recipient): unknown {
|
|
58
|
+
const method = `to${channel[0]?.toUpperCase()}${channel.slice(1)}`
|
|
59
|
+
const build: unknown = Reflect.get(this, method)
|
|
60
|
+
if (typeof build !== 'function')
|
|
61
|
+
throw new CslugError('notification.no_message', `${this.type} sends via "${channel}" but has no ${method}()`)
|
|
62
|
+
return build.call(this, to)
|
|
63
|
+
}
|
|
64
|
+
}
|
package/src/notifier.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Application,
|
|
3
|
+
afterCommit,
|
|
4
|
+
type Class,
|
|
5
|
+
CslugError,
|
|
6
|
+
currentLocale,
|
|
7
|
+
type Logger,
|
|
8
|
+
withLocale,
|
|
9
|
+
} from '@cslug/core'
|
|
10
|
+
import { type Notification, type Recipient, routeOf } from './notification'
|
|
11
|
+
|
|
12
|
+
/** Delivers one message. A `manual` channel only records it, for staff to send (status `manual`). */
|
|
13
|
+
export interface Channel {
|
|
14
|
+
readonly manual?: boolean
|
|
15
|
+
send(to: Recipient, message: unknown, delivery: Delivery): Promise<void>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** One notification on one channel (a `cslug_notification_deliveries` row; the queued job's payload). */
|
|
19
|
+
export type Delivery = {
|
|
20
|
+
id: string
|
|
21
|
+
recipientId?: string
|
|
22
|
+
type: string
|
|
23
|
+
channel: string
|
|
24
|
+
to: Recipient
|
|
25
|
+
message: unknown
|
|
26
|
+
}
|
|
27
|
+
export type DeliveryStatus = 'queued' | 'sent' | 'manual' | 'failed'
|
|
28
|
+
|
|
29
|
+
/** Where deliveries and `database` notifications are stored; set by `NotificationProvider` with @cslug/database. */
|
|
30
|
+
export interface NotificationStore {
|
|
31
|
+
notify(delivery: Delivery): Promise<void>
|
|
32
|
+
record(delivery: Delivery, status: DeliveryStatus): Promise<void>
|
|
33
|
+
mark(id: string, status: DeliveryStatus, error?: string): Promise<void>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** `config/notification.ts`. */
|
|
37
|
+
export type NotificationConfig = {
|
|
38
|
+
/** Queue the deliveries (default true, when @cslug/queue is installed). */
|
|
39
|
+
queued?: boolean
|
|
40
|
+
queue?: string
|
|
41
|
+
/** Drivers of the built-in channels: `log` (default) or `manual`. */
|
|
42
|
+
whatsapp?: { driver?: 'log' | 'manual' }
|
|
43
|
+
sms?: { driver?: 'log' | 'manual' }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Writes each message to the log (development, and the default driver of `whatsapp` and `sms`). */
|
|
47
|
+
export class LogChannel implements Channel {
|
|
48
|
+
constructor(
|
|
49
|
+
private readonly name: string,
|
|
50
|
+
private readonly log: Logger,
|
|
51
|
+
) {}
|
|
52
|
+
async send(to: Recipient, message: unknown) {
|
|
53
|
+
this.log.info('notification.logged', { channel: this.name, to, message })
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Leaves the message for staff to send by hand (status `manual` in `cslug_notification_deliveries`). */
|
|
58
|
+
export class ManualChannel implements Channel {
|
|
59
|
+
readonly manual = true
|
|
60
|
+
async send() {}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Sends notifications: `notifier.send(traveller, new CheckinDueNotification(booking, 'mid_trip'))`. Each channel's
|
|
65
|
+
* message is built now, in the recipient's locale; `mail` goes to the Mailer (queued), `database` is written in the
|
|
66
|
+
* current transaction, other channels are delivered by a job each (`cslug.notification`) after COMMIT.
|
|
67
|
+
*/
|
|
68
|
+
export class Notifier {
|
|
69
|
+
private readonly channels = new Map<string, Channel | Class<Channel>>()
|
|
70
|
+
/** Set by `NotificationProvider` with @cslug/queue: queues one delivery. */
|
|
71
|
+
enqueue?: (delivery: Delivery) => Promise<unknown>
|
|
72
|
+
store?: NotificationStore
|
|
73
|
+
|
|
74
|
+
constructor(
|
|
75
|
+
protected readonly app: Application,
|
|
76
|
+
protected readonly config: NotificationConfig,
|
|
77
|
+
protected readonly log: Logger,
|
|
78
|
+
) {}
|
|
79
|
+
|
|
80
|
+
/** Add a channel: an instance, or a class built by the container (`@inject`). */
|
|
81
|
+
extend(name: string, channel: Channel | Class<Channel>): this {
|
|
82
|
+
this.channels.set(name, channel)
|
|
83
|
+
return this
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
channel(name: string): Channel {
|
|
87
|
+
const channel = this.channels.get(name)
|
|
88
|
+
if (!channel) throw new CslugError('notification.unknown_channel', `No notification channel "${name}"`)
|
|
89
|
+
return typeof channel === 'function' ? this.app.resolve(channel) : channel
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async send(to: object, notification: Notification): Promise<void> {
|
|
93
|
+
const route = routeOf(to)
|
|
94
|
+
for (const channel of notification.via(route)) {
|
|
95
|
+
const message = await withLocale(route.locale ?? currentLocale(), async () =>
|
|
96
|
+
notification.messageFor(channel, route),
|
|
97
|
+
)
|
|
98
|
+
await this.deliver({
|
|
99
|
+
id: Bun.randomUUIDv7(),
|
|
100
|
+
recipientId: route.id,
|
|
101
|
+
type: notification.type,
|
|
102
|
+
channel,
|
|
103
|
+
to: route,
|
|
104
|
+
message,
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async sendMany(recipients: Iterable<object>, notification: Notification): Promise<void> {
|
|
110
|
+
for (const to of recipients) await this.send(to, notification)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
protected async deliver(delivery: Delivery): Promise<void> {
|
|
114
|
+
const queued = this.config.queued !== false
|
|
115
|
+
if (delivery.channel === 'mail') return this.mail(delivery, queued)
|
|
116
|
+
if (delivery.channel === 'database') {
|
|
117
|
+
if (!this.store) throw new CslugError('notification.no_database', 'The database channel needs @cslug/database')
|
|
118
|
+
await this.store.notify(delivery)
|
|
119
|
+
return this.store.record(delivery, 'sent')
|
|
120
|
+
}
|
|
121
|
+
this.channel(delivery.channel) // fail now on an unknown channel, not in the worker
|
|
122
|
+
await this.store?.record(delivery, 'queued')
|
|
123
|
+
if (queued && this.enqueue) await this.enqueue(delivery)
|
|
124
|
+
else afterCommit(() => this.run(delivery).catch(() => {})) // run() has logged and recorded the failure
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private async mail(delivery: Delivery, queued: boolean): Promise<void> {
|
|
128
|
+
const { Mailable, Mailer } = await import('@cslug/mail').catch(() => {
|
|
129
|
+
throw new CslugError('notification.no_mail', 'The mail channel needs @cslug/mail')
|
|
130
|
+
})
|
|
131
|
+
if (!(delivery.message instanceof Mailable))
|
|
132
|
+
throw new CslugError('notification.no_message', `${delivery.type}.toMail() must return a Mailable`)
|
|
133
|
+
if (!delivery.to.email)
|
|
134
|
+
throw new CslugError('notification.no_route', `${delivery.type}: the recipient has no email`)
|
|
135
|
+
const pending = this.app.resolve(Mailer).to(delivery.to.email).locale(delivery.to.locale)
|
|
136
|
+
await (queued ? pending.queue(delivery.message) : pending.send(delivery.message))
|
|
137
|
+
await this.store?.record({ ...delivery, message: null }, queued ? 'queued' : 'sent') // the mail job reports itself
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Deliver on a channel (the job, or after COMMIT without a queue) and record the outcome. */
|
|
141
|
+
async run(delivery: Delivery): Promise<void> {
|
|
142
|
+
try {
|
|
143
|
+
const channel = this.channel(delivery.channel)
|
|
144
|
+
await channel.send(delivery.to, delivery.message, delivery)
|
|
145
|
+
await this.store?.mark(delivery.id, channel.manual ? 'manual' : 'sent')
|
|
146
|
+
this.log.info('notification.sent', { id: delivery.id, channel: delivery.channel, type: delivery.type })
|
|
147
|
+
} catch (error) {
|
|
148
|
+
await this.store?.mark(delivery.id, 'failed', error instanceof Error ? error.message : String(error))
|
|
149
|
+
this.log.error('notification.failed', { id: delivery.id, channel: delivery.channel, error })
|
|
150
|
+
throw error
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { type Application, Logger, resolve, ServiceProvider } from '@cslug/core'
|
|
3
|
+
import {
|
|
4
|
+
type Delivery,
|
|
5
|
+
LogChannel,
|
|
6
|
+
ManualChannel,
|
|
7
|
+
type NotificationConfig,
|
|
8
|
+
type NotificationStore,
|
|
9
|
+
Notifier,
|
|
10
|
+
} from './notifier'
|
|
11
|
+
|
|
12
|
+
/** The `cslug_notifications` and `cslug_notification_deliveries` migrations (registered with @cslug/database). */
|
|
13
|
+
export const NOTIFICATION_MIGRATIONS = join(import.meta.dir, '../migrations')
|
|
14
|
+
|
|
15
|
+
type QueueModule = typeof import('@cslug/queue')
|
|
16
|
+
let deliveryJob: Parameters<InstanceType<QueueModule['Queue']>['dispatch']>[0] | undefined
|
|
17
|
+
|
|
18
|
+
/** The job (`cslug.notification`) that delivers one queued message; defined once, when the queue is installed. */
|
|
19
|
+
function notificationJob(q: QueueModule) {
|
|
20
|
+
if (!deliveryJob) {
|
|
21
|
+
class NotificationJob extends q.Job<Delivery> {
|
|
22
|
+
static jobName = 'cslug.notification'
|
|
23
|
+
async handle(delivery: Delivery) {
|
|
24
|
+
await resolve(Notifier).run(delivery)
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
q.registerJob(NotificationJob)
|
|
28
|
+
deliveryJob = NotificationJob as never
|
|
29
|
+
}
|
|
30
|
+
return deliveryJob as NonNullable<typeof deliveryJob>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Rows in the ambient transaction, through @cslug/database. */
|
|
34
|
+
async function databaseStore(app: Application): Promise<NotificationStore | undefined> {
|
|
35
|
+
const db = await import('@cslug/database').catch(() => undefined)
|
|
36
|
+
if (!db || !app.has(db.Database)) return undefined
|
|
37
|
+
db.addMigrations(NOTIFICATION_MIGRATIONS)
|
|
38
|
+
const { sql } = db
|
|
39
|
+
const exec = (query: Parameters<InstanceType<typeof db.Database>['exec']>[0]) => app.resolve(db.Database).exec(query)
|
|
40
|
+
return {
|
|
41
|
+
notify: (d) =>
|
|
42
|
+
exec(sql`insert into cslug_notifications (id, recipient_id, type, data)
|
|
43
|
+
values (${d.id}, ${d.recipientId ?? null}, ${d.type}, ${sql.json(d.message ?? null)})`).then(() => {}),
|
|
44
|
+
record: (d, status) =>
|
|
45
|
+
exec(sql`insert into cslug_notification_deliveries (id, recipient_id, type, channel, status, message)
|
|
46
|
+
values (${d.id}, ${d.recipientId ?? null}, ${d.type}, ${d.channel}, ${status}, ${sql.json(d.message ?? null)})`).then(
|
|
47
|
+
() => {},
|
|
48
|
+
),
|
|
49
|
+
mark: (id, status, error) =>
|
|
50
|
+
exec(sql`update cslug_notification_deliveries set status = ${status}, error = ${error ?? null}, updated_at = now()
|
|
51
|
+
where id = ${id}`).then(() => {}),
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Binds `Notifier` with the `mail` and `database` channels and `whatsapp` / `sms` (driver `log` or `manual`,
|
|
57
|
+
* config `notification`). With @cslug/database: the tables and delivery records; with @cslug/queue: one job per
|
|
58
|
+
* delivery on `notification.queue`.
|
|
59
|
+
*/
|
|
60
|
+
export class NotificationProvider extends ServiceProvider {
|
|
61
|
+
register() {
|
|
62
|
+
this.app.singleton(Notifier, (c) => {
|
|
63
|
+
const config = this.app.config<NotificationConfig | undefined>('notification') ?? {}
|
|
64
|
+
const log = c.resolve(Logger)
|
|
65
|
+
const notifier = new Notifier(this.app, config, log)
|
|
66
|
+
for (const name of ['whatsapp', 'sms'] as const)
|
|
67
|
+
notifier.extend(name, config[name]?.driver === 'manual' ? new ManualChannel() : new LogChannel(name, log))
|
|
68
|
+
return notifier
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async boot() {
|
|
73
|
+
const notifier = this.app.resolve(Notifier)
|
|
74
|
+
notifier.store = await databaseStore(this.app)
|
|
75
|
+
const q = await import('@cslug/queue').catch(() => undefined)
|
|
76
|
+
if (!q || !this.app.has(q.Queue)) return
|
|
77
|
+
const job = notificationJob(q)
|
|
78
|
+
const queue = this.app.config<string | undefined>('notification.queue') ?? 'default'
|
|
79
|
+
notifier.enqueue = async (delivery) => {
|
|
80
|
+
await this.app
|
|
81
|
+
.resolve(q.Queue)
|
|
82
|
+
.dispatch(job, delivery as never)
|
|
83
|
+
.onQueue(queue)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|