@hamur/notifications 0.0.0-stage → 0.0.1
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/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/src/index.js +235 -0
- package/dist/src/server/index.js +282 -0
- package/dist/src/test.js +32 -0
- package/dist/types/src/build/scan.d.ts +27 -0
- package/dist/types/src/build/setup.d.ts +4 -0
- package/dist/types/src/index.d.ts +11 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +9 -0
- package/dist/types/src/server/broadcast.d.ts +6 -0
- package/dist/types/src/server/deliver.d.ts +27 -0
- package/dist/types/src/server/inbox.d.ts +23 -0
- package/dist/types/src/server/index.d.ts +17 -0
- package/dist/types/src/server/notify.d.ts +20 -0
- package/dist/types/src/server/queue.d.ts +7 -0
- package/dist/types/src/server/recipient.d.ts +2 -0
- package/dist/types/src/server/record.d.ts +3 -0
- package/dist/types/src/server/runtime.d.ts +6 -0
- package/dist/types/src/server/task.d.ts +4 -0
- package/dist/types/src/server/topic.d.ts +3 -0
- package/dist/types/src/server/webhook.d.ts +10 -0
- package/dist/types/src/test.d.ts +5 -0
- package/dist/types/src/types.d.ts +87 -0
- package/package.json +42 -4
- package/src/build/scan.ts +119 -0
- package/src/build/setup.ts +111 -0
- package/src/env.d.ts +26 -0
- package/src/index.ts +13 -0
- package/src/module.ts +11 -0
- package/src/options.ts +52 -0
- package/src/server/broadcast.ts +9 -0
- package/src/server/deliver.ts +57 -0
- package/src/server/inbox.ts +121 -0
- package/src/server/index.ts +74 -0
- package/src/server/notify.ts +127 -0
- package/src/server/queue.ts +22 -0
- package/src/server/recipient.ts +10 -0
- package/src/server/record.ts +16 -0
- package/src/server/runtime.ts +42 -0
- package/src/server/task.ts +14 -0
- package/src/server/topic.ts +18 -0
- package/src/server/webhook.ts +71 -0
- package/src/test.ts +35 -0
- package/src/types.ts +93 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { MailMessage } from "@hamur/mail"
|
|
2
|
+
import type { Logger } from "hamur/server"
|
|
3
|
+
import type { Delivery, DeliveryRecord, NotificationOptions, Recipient, WebhookTarget } from "../types.ts"
|
|
4
|
+
import type { openTopic } from "./broadcast.ts"
|
|
5
|
+
import type { Inbox } from "./inbox.ts"
|
|
6
|
+
|
|
7
|
+
/** What performing a delivery takes. */
|
|
8
|
+
export interface DeliverDeps {
|
|
9
|
+
/** The definition of a notification; rejects for an unknown name. */
|
|
10
|
+
load: (name: string) => Promise<NotificationOptions<unknown, unknown>>
|
|
11
|
+
deliverMail: (
|
|
12
|
+
message: MailMessage,
|
|
13
|
+
delivery: { id: string; site?: string; queued: boolean },
|
|
14
|
+
log: Pick<Logger, "error">,
|
|
15
|
+
) => Promise<Error | undefined>
|
|
16
|
+
storeRow: Inbox["add"]
|
|
17
|
+
/** Rejects for a recipient that can have no topic. */
|
|
18
|
+
openTopic: (to: Recipient) => Promise<ReturnType<typeof openTopic>>
|
|
19
|
+
/** `notifications.webhook`. */
|
|
20
|
+
webhook?: WebhookTarget
|
|
21
|
+
postWebhook: (target: WebhookTarget, id: string, body: string) => Promise<void>
|
|
22
|
+
/** Set in a test build. */
|
|
23
|
+
record?: (delivery: DeliveryRecord) => Promise<void>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** `webhook to Tenant::"9"`. */
|
|
27
|
+
export const shownDelivery = ({ channel, to }: Pick<Delivery, "channel" | "to">): string =>
|
|
28
|
+
`${channel} to ${to.type}::${JSON.stringify(to.id)}`
|
|
29
|
+
|
|
30
|
+
/** One delivery. It resolves to the failure of a mail that may have arrived all the same, which must not be sent again. */
|
|
31
|
+
export async function deliver(
|
|
32
|
+
deps: DeliverDeps,
|
|
33
|
+
{ id, name, channel, to, input, site, webhook = deps.webhook }: Delivery,
|
|
34
|
+
queued: boolean,
|
|
35
|
+
log: Pick<Logger, "error">,
|
|
36
|
+
): Promise<Error | undefined> {
|
|
37
|
+
const payload: unknown = await (await deps.load(name))[channel]?.(input, to)
|
|
38
|
+
if (payload === undefined) throw new TypeError(`${channel}() of the notification gave nothing to send`)
|
|
39
|
+
await deps.record?.({ name, channel, recipient: { type: to.type, id: to.id }, payload })
|
|
40
|
+
if (channel === "mail") {
|
|
41
|
+
const message = { ...(payload as Omit<MailMessage, "to">), to: to.email! }
|
|
42
|
+
return deps.deliverMail(message, { id, queued, ...(site === undefined ? {} : { site }) }, log)
|
|
43
|
+
}
|
|
44
|
+
if (channel === "database") {
|
|
45
|
+
await deps.storeRow({ id, name, to, payload })
|
|
46
|
+
return undefined
|
|
47
|
+
}
|
|
48
|
+
if (deps.record) return undefined
|
|
49
|
+
if (channel === "broadcast") {
|
|
50
|
+
const send = await deps.openTopic(to)
|
|
51
|
+
await send({ notification: name, data: payload })
|
|
52
|
+
return undefined
|
|
53
|
+
}
|
|
54
|
+
if (!webhook) throw new Error("the recipient has no webhook")
|
|
55
|
+
await deps.postWebhook(webhook, id, JSON.stringify(payload))
|
|
56
|
+
return undefined
|
|
57
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { Database, SqlFragment } from "@hamur/db"
|
|
2
|
+
import type { cursorQuery } from "@hamur/db/server"
|
|
3
|
+
import type { CursorPage } from "hamur/server"
|
|
4
|
+
import { createSqlFragment, fromBase64Url } from "hamur/server/internal"
|
|
5
|
+
import type { NotificationName, NotificationRow, Recipient } from "../types.ts"
|
|
6
|
+
import { checkRecipient } from "./recipient.ts"
|
|
7
|
+
|
|
8
|
+
type Owner = Pick<Recipient, "type" | "id">
|
|
9
|
+
|
|
10
|
+
type StoredRow = {
|
|
11
|
+
id: string
|
|
12
|
+
notification: string
|
|
13
|
+
data: string
|
|
14
|
+
read_at: string | null
|
|
15
|
+
created_at: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Inbox {
|
|
19
|
+
/** Adds the row of one delivery; a second run of the delivery leaves the first row as it is. */
|
|
20
|
+
add(delivery: { id: string; name: string; to: Owner; payload: unknown }): Promise<void>
|
|
21
|
+
list(to: Owner, options?: { unread?: boolean; limit?: number; cursor?: string }): Promise<CursorPage<NotificationRow>>
|
|
22
|
+
markRead(to: Owner, ids: readonly string[] | "all"): Promise<number>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const ORDER = [
|
|
26
|
+
["created_at", "desc"],
|
|
27
|
+
["id", "desc"],
|
|
28
|
+
] as const
|
|
29
|
+
/** D1 allows 100 bound parameters in one statement. */
|
|
30
|
+
const IDS_PER_UPDATE = 90
|
|
31
|
+
|
|
32
|
+
const isKey = (value: unknown): boolean => typeof value === "string" && !value.includes("\0")
|
|
33
|
+
|
|
34
|
+
/** postgres fails on a key its text columns cannot be compared with, and a `null` would start over. */
|
|
35
|
+
function isRowCursor(cursor: string): boolean {
|
|
36
|
+
try {
|
|
37
|
+
const key: unknown = JSON.parse(new TextDecoder().decode(fromBase64Url(cursor)))
|
|
38
|
+
return Array.isArray(key) && key.every(isKey)
|
|
39
|
+
} catch {
|
|
40
|
+
return false
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function ownedBy(to: Owner): SqlFragment {
|
|
45
|
+
checkRecipient(to)
|
|
46
|
+
const { type, id } = to
|
|
47
|
+
return createSqlFragment((dialect, first) => {
|
|
48
|
+
if (dialect === "postgres")
|
|
49
|
+
return { text: `recipient_type = $${first} AND recipient_id = $${first + 1}`, values: [type, id] }
|
|
50
|
+
if (dialect === "sqlite") return { text: "recipient_type = ? AND recipient_id = ?", values: [type, id] }
|
|
51
|
+
// the usual collations of mysql find "Ada" for "ada"; the plain comparison is for the index
|
|
52
|
+
const same = (column: string) =>
|
|
53
|
+
`${column} = ? AND CAST(CONVERT(${column} USING utf8mb4) AS BINARY) = CAST(CONVERT(? USING utf8mb4) AS BINARY)`
|
|
54
|
+
return { text: `${same("recipient_type")} AND ${same("recipient_id")}`, values: [type, type, id, id] }
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const among = (ids: string[]): SqlFragment =>
|
|
59
|
+
createSqlFragment((dialect, first) => ({
|
|
60
|
+
text: ` AND id IN (${ids.map((_, at) => (dialect === "postgres" ? `$${first + at}` : "?")).join(", ")})`,
|
|
61
|
+
values: ids,
|
|
62
|
+
}))
|
|
63
|
+
|
|
64
|
+
const raw = (text: string): SqlFragment => createSqlFragment(() => ({ text, values: [] }))
|
|
65
|
+
|
|
66
|
+
/** The rows of the app's `table`, which every statement but the insert narrows to one recipient. */
|
|
67
|
+
export function createInbox(database: () => Database, keyset: typeof cursorQuery, name: string): Inbox {
|
|
68
|
+
const table = createSqlFragment((dialect) => ({
|
|
69
|
+
text: dialect === "mysql" ? `\`${name}\`` : `"${name}"`,
|
|
70
|
+
values: [],
|
|
71
|
+
}))
|
|
72
|
+
const once = createSqlFragment((dialect) => ({
|
|
73
|
+
text: dialect === "mysql" ? "ON DUPLICATE KEY UPDATE id = id" : "ON CONFLICT (id) DO NOTHING",
|
|
74
|
+
values: [],
|
|
75
|
+
}))
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
async add({ id, name: notification, to, payload }) {
|
|
79
|
+
checkRecipient(to)
|
|
80
|
+
await database().run`INSERT INTO ${table} (id, recipient_type, recipient_id, notification, data, created_at)
|
|
81
|
+
VALUES (${id}, ${to.type}, ${to.id}, ${notification}, ${JSON.stringify(payload)}, ${new Date().toISOString()})
|
|
82
|
+
${once}`
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
async list(to, { unread = false, limit = 20, cursor } = {}) {
|
|
86
|
+
const own = ownedBy(to)
|
|
87
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
88
|
+
throw new TypeError(`listNotifications limit must be an integer from 1 to 100 (got ${JSON.stringify(limit)})`)
|
|
89
|
+
// an empty cursor gets the 400 of an unreadable one
|
|
90
|
+
const from = cursor === undefined || isRowCursor(cursor) ? cursor : ""
|
|
91
|
+
const query = keyset<StoredRow>({ cursor: from, limit }, { orderBy: ORDER })
|
|
92
|
+
const rows = await database().sql<StoredRow>`SELECT id, notification, data, read_at, created_at FROM ${table}
|
|
93
|
+
WHERE ${own} AND ${query.where}${raw(unread ? " AND read_at IS NULL" : "")}
|
|
94
|
+
ORDER BY ${query.orderBy} LIMIT ${raw(String(query.limit))}`
|
|
95
|
+
const { items, nextCursor } = query.page(rows)
|
|
96
|
+
return {
|
|
97
|
+
items: items.map((row) => ({
|
|
98
|
+
id: row.id,
|
|
99
|
+
notification: row.notification as NotificationName,
|
|
100
|
+
data: JSON.parse(row.data) as unknown,
|
|
101
|
+
readAt: row.read_at === null ? null : new Date(row.read_at),
|
|
102
|
+
createdAt: new Date(row.created_at),
|
|
103
|
+
})),
|
|
104
|
+
nextCursor,
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
async markRead(to, ids) {
|
|
109
|
+
const own = ownedBy(to)
|
|
110
|
+
const now = new Date().toISOString()
|
|
111
|
+
const mark = async (which: SqlFragment): Promise<number> =>
|
|
112
|
+
(await database().run`UPDATE ${table} SET read_at = ${now} WHERE ${own} AND read_at IS NULL${which}`).changes
|
|
113
|
+
if (ids === "all") return mark(raw(""))
|
|
114
|
+
let marked = 0
|
|
115
|
+
const possible = ids.filter(isKey)
|
|
116
|
+
for (let at = 0; at < possible.length; at += IDS_PER_UPDATE)
|
|
117
|
+
marked += await mark(among(possible.slice(at, at + IDS_PER_UPDATE)))
|
|
118
|
+
return marked
|
|
119
|
+
},
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import { queue } from "#hamur/notifications/config"
|
|
3
|
+
import { useEvent, useLogger, useSiteConfig, type CursorPage, type TaskName } from "hamur/server"
|
|
4
|
+
import { prepareEnqueue } from "hamur/server/internal"
|
|
5
|
+
import type {
|
|
6
|
+
Notification,
|
|
7
|
+
NotificationInput,
|
|
8
|
+
NotificationName,
|
|
9
|
+
NotificationOptions,
|
|
10
|
+
NotificationRow,
|
|
11
|
+
Recipient,
|
|
12
|
+
} from "../types.ts"
|
|
13
|
+
import { createNotify } from "./notify.ts"
|
|
14
|
+
import { packDelivery } from "./queue.ts"
|
|
15
|
+
import { deliverDeps, useInbox } from "./runtime.ts"
|
|
16
|
+
|
|
17
|
+
/** A string, since `TaskName` holds the task only in an app with `@hamur/notifications`. */
|
|
18
|
+
const TASK: string = "notifications:deliver"
|
|
19
|
+
const KEYS = ["input", "via", "mail", "database", "broadcast", "webhook"]
|
|
20
|
+
|
|
21
|
+
function requestSite(): string | undefined {
|
|
22
|
+
try {
|
|
23
|
+
return useSiteConfig(useEvent()).url
|
|
24
|
+
} catch {
|
|
25
|
+
return undefined
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const send = createNotify({
|
|
30
|
+
...deliverDeps,
|
|
31
|
+
queue,
|
|
32
|
+
pack: packDelivery,
|
|
33
|
+
prepare: (delivery) => prepareEnqueue(TASK as TaskName, delivery as never),
|
|
34
|
+
site: requestSite,
|
|
35
|
+
log: useLogger,
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
/** The default export of a file of `server/notifications/`; its channels are the keys among `mail`, `database`, `broadcast` and `webhook`. */
|
|
39
|
+
export function defineNotification<In, Out = In>(options: NotificationOptions<In, Out>): Notification<In> {
|
|
40
|
+
for (const key of Object.keys(options))
|
|
41
|
+
if (!KEYS.includes(key))
|
|
42
|
+
throw new TypeError(`defineNotification has no ${JSON.stringify(key)}; it takes ${KEYS.join(", ")}`)
|
|
43
|
+
if (typeof options.input?.["~standard"]?.validate !== "function")
|
|
44
|
+
throw new TypeError("defineNotification input must be a Standard Schema")
|
|
45
|
+
return options as unknown as Notification<In>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Tells each recipient through the notification's channels, one queued delivery per recipient and channel. */
|
|
49
|
+
export function notify<N extends NotificationName>(
|
|
50
|
+
to: Recipient | readonly Recipient[],
|
|
51
|
+
name: N,
|
|
52
|
+
input: NotificationInput<N>,
|
|
53
|
+
options?: { queue?: boolean },
|
|
54
|
+
): Promise<void> {
|
|
55
|
+
return send(to, name, input, options)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export { notificationTopic } from "./topic.ts"
|
|
59
|
+
|
|
60
|
+
/** A page of the notifications the database channel keeps for `to`, the newest first. */
|
|
61
|
+
export async function listNotifications(
|
|
62
|
+
to: Pick<Recipient, "type" | "id">,
|
|
63
|
+
options?: { unread?: boolean; limit?: number; cursor?: string },
|
|
64
|
+
): Promise<CursorPage<NotificationRow>> {
|
|
65
|
+
return (await useInbox("listNotifications")).list(to, options)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Marks unread notifications of `to` read, and no one else's; resolves to how many it marked. */
|
|
69
|
+
export async function markNotificationsRead(
|
|
70
|
+
to: Pick<Recipient, "type" | "id">,
|
|
71
|
+
ids: readonly string[] | "all",
|
|
72
|
+
): Promise<number> {
|
|
73
|
+
return (await useInbox("markNotificationsRead")).markRead(to, ids)
|
|
74
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { Logger } from "hamur/server"
|
|
2
|
+
import { CHANNELS, type Delivery, type Recipient } from "../types.ts"
|
|
3
|
+
import type { QueuedDelivery } from "./queue.ts"
|
|
4
|
+
import { deliver, shownDelivery, type DeliverDeps } from "./deliver.ts"
|
|
5
|
+
|
|
6
|
+
export interface NotifyDeps extends DeliverDeps {
|
|
7
|
+
/** `notifications.queue`. */
|
|
8
|
+
queue: boolean
|
|
9
|
+
pack: (delivery: Delivery) => Promise<QueuedDelivery>
|
|
10
|
+
/** Throws for a payload the queue cannot take; the function it returns queues it. */
|
|
11
|
+
prepare: (delivery: QueuedDelivery) => () => Promise<void>
|
|
12
|
+
/** The `site.url` of the current request. */
|
|
13
|
+
site: () => string | undefined
|
|
14
|
+
log: () => Pick<Logger, "warn" | "error">
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Only the fields of `Recipient`: a row of the app's own may be passed, with a password hash in it. */
|
|
18
|
+
const recipientOf = ({ type, id, email, prefs }: Recipient): Recipient => ({
|
|
19
|
+
type,
|
|
20
|
+
id,
|
|
21
|
+
...(email === undefined ? {} : { email }),
|
|
22
|
+
...(prefs === undefined ? {} : { prefs }),
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
const textOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
|
|
26
|
+
|
|
27
|
+
function uuidV7(): string {
|
|
28
|
+
const time = Date.now().toString(16).padStart(12, "0")
|
|
29
|
+
return `${time.slice(0, 8)}-${time.slice(8)}-7${crypto.randomUUID().slice(15)}`
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Every queued run, before the first is handed off: one the queue cannot take rejects the call with nothing queued. */
|
|
33
|
+
async function prepareAll(
|
|
34
|
+
deps: NotifyDeps,
|
|
35
|
+
deliveries: readonly Delivery[],
|
|
36
|
+
label: string,
|
|
37
|
+
): Promise<Array<() => Promise<void>>> {
|
|
38
|
+
const packed = await Promise.all(deliveries.map(deps.pack))
|
|
39
|
+
return packed.map((delivery) => {
|
|
40
|
+
try {
|
|
41
|
+
return deps.prepare(delivery)
|
|
42
|
+
} catch (error) {
|
|
43
|
+
throw new Error(`${label}: ${shownDelivery(delivery)}: ${textOf(error)}`, { cause: error })
|
|
44
|
+
}
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** `notify` over the definitions, the queue and the channels. */
|
|
49
|
+
export function createNotify(deps: NotifyDeps) {
|
|
50
|
+
return async function notify(
|
|
51
|
+
to: Recipient | readonly Recipient[],
|
|
52
|
+
name: string,
|
|
53
|
+
input: unknown,
|
|
54
|
+
options: { queue?: boolean } = {},
|
|
55
|
+
): Promise<void> {
|
|
56
|
+
const label = `notify(${JSON.stringify(name)})`
|
|
57
|
+
const site = deps.site()
|
|
58
|
+
const definition = await deps.load(name)
|
|
59
|
+
const result = await definition.input["~standard"].validate(input)
|
|
60
|
+
if (result.issues) {
|
|
61
|
+
const { message, path = [] } = result.issues[0]!
|
|
62
|
+
const at = path.map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".")
|
|
63
|
+
throw new Error(`${label}: the input is refused by its schema: ${message}${at ? ` at ${at}` : ""}`)
|
|
64
|
+
}
|
|
65
|
+
const log = deps.log()
|
|
66
|
+
const defined = CHANNELS.filter((channel) => definition[channel])
|
|
67
|
+
const deliveries = new Map<string, Delivery>()
|
|
68
|
+
for (const given of (Array.isArray(to) ? to : [to]) as readonly Recipient[]) {
|
|
69
|
+
const recipient = recipientOf(given)
|
|
70
|
+
for (const channel of definition.via?.(recipient, result.value) ?? defined) {
|
|
71
|
+
const delivery: Delivery = {
|
|
72
|
+
id: uuidV7(),
|
|
73
|
+
name,
|
|
74
|
+
channel,
|
|
75
|
+
to: recipient,
|
|
76
|
+
input: result.value,
|
|
77
|
+
...(channel === "webhook" && given.webhook ? { webhook: given.webhook } : {}),
|
|
78
|
+
...(channel === "mail" && site !== undefined ? { site } : {}),
|
|
79
|
+
}
|
|
80
|
+
const shown = `${recipient.type}::${JSON.stringify(recipient.id)}`
|
|
81
|
+
if (!defined.includes(channel)) {
|
|
82
|
+
log.warn(`${label}: via() names the channel ${JSON.stringify(channel)}, which the notification does not have`)
|
|
83
|
+
} else if (channel === "mail" && recipient.email === undefined) {
|
|
84
|
+
log.warn(`${label}: ${shown} has no email; the mail channel skipped it`)
|
|
85
|
+
} else if (channel === "webhook" && !given.webhook && !deps.webhook) {
|
|
86
|
+
log.warn(`${label}: ${shown} has no webhook; the webhook channel skipped it`)
|
|
87
|
+
} else if (!deliveries.has(shownDelivery(delivery))) {
|
|
88
|
+
if (channel === "broadcast") await deps.openTopic(recipient)
|
|
89
|
+
deliveries.set(shownDelivery(delivery), delivery)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const list = [...deliveries.values()]
|
|
95
|
+
// callHandler of hamur/test has no tasks, and a test reads the record right after the call
|
|
96
|
+
const queued = options.queue ?? deps.queue
|
|
97
|
+
const runs = queued && !deps.record ? await prepareAll(deps, list, label) : undefined
|
|
98
|
+
const settled = await Promise.allSettled(
|
|
99
|
+
runs
|
|
100
|
+
? runs.map((run) => run())
|
|
101
|
+
: list.map(async (delivery) => {
|
|
102
|
+
const unconfirmed = await deliver(deps, delivery, queued, log)
|
|
103
|
+
if (unconfirmed) throw unconfirmed
|
|
104
|
+
}),
|
|
105
|
+
)
|
|
106
|
+
const failures = settled.flatMap((entry, at) =>
|
|
107
|
+
entry.status === "rejected" ? [{ delivery: list[at]!, error: entry.reason as unknown }] : [],
|
|
108
|
+
)
|
|
109
|
+
if (!failures.length) return
|
|
110
|
+
const texts = failures.map(({ delivery, error }) => `${shownDelivery(delivery)}: ${textOf(error)}`)
|
|
111
|
+
throw new Error(`${label}: ${failures.length} of ${list.length} deliveries failed: ${texts.join("; ")}`, {
|
|
112
|
+
cause: failures[0]!.error,
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The run of `notifications:deliver`. A rejection makes the queue run this delivery again, and only this one. */
|
|
118
|
+
export async function runDelivery(deps: DeliverDeps, delivery: Delivery, log: Pick<Logger, "error">): Promise<void> {
|
|
119
|
+
const label = `notify(${JSON.stringify(delivery.name)}): ${shownDelivery(delivery)}`
|
|
120
|
+
let unconfirmed: Error | undefined
|
|
121
|
+
try {
|
|
122
|
+
unconfirmed = await deliver(deps, delivery, true, log)
|
|
123
|
+
} catch (error) {
|
|
124
|
+
throw new Error(`${label}: ${textOf(error)}`, { cause: error })
|
|
125
|
+
}
|
|
126
|
+
if (unconfirmed) log.error(unconfirmed, `${label}: ${unconfirmed.message}; the queue does not send it again`)
|
|
127
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { sealFor, unsealFor } from "hamur/server/internal"
|
|
2
|
+
import type { Delivery, WebhookTarget } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
const PURPOSE = "hamur-notifications"
|
|
5
|
+
|
|
6
|
+
/** The payload of `notifications:deliver`: the recipient's webhook is sealed, so a queue's record shows neither its secret nor a token in its URL. */
|
|
7
|
+
export interface QueuedDelivery extends Omit<Delivery, "webhook"> {
|
|
8
|
+
webhook?: string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function packDelivery({ webhook, ...delivery }: Delivery): Promise<QueuedDelivery> {
|
|
12
|
+
if (!webhook) return delivery
|
|
13
|
+
const { url, secret } = webhook
|
|
14
|
+
return { ...delivery, webhook: await sealFor({ url, secret }, { purpose: PURPOSE }) }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function unpackDelivery({ webhook, ...delivery }: QueuedDelivery): Promise<Delivery> {
|
|
18
|
+
if (webhook === undefined) return delivery
|
|
19
|
+
const opened = await unsealFor<WebhookTarget>(webhook, { purpose: PURPOSE })
|
|
20
|
+
if (!opened) throw new Error("the recipient's webhook was queued under another HAMUR_KEY")
|
|
21
|
+
return { ...delivery, webhook: opened }
|
|
22
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Recipient } from "../types.ts"
|
|
2
|
+
|
|
3
|
+
const isText = (value: unknown): boolean => typeof value === "string" && value !== ""
|
|
4
|
+
|
|
5
|
+
export function checkRecipient({ type, id }: Pick<Recipient, "type" | "id">): void {
|
|
6
|
+
if (!isText(type) || !isText(id))
|
|
7
|
+
throw new TypeError(
|
|
8
|
+
`A notification recipient needs type and id, both non-empty strings (got ${JSON.stringify({ type, id })})`,
|
|
9
|
+
)
|
|
10
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { appendFile, mkdir } from "node:fs/promises"
|
|
2
|
+
import { dirname } from "node:path"
|
|
3
|
+
import type { DeliveryRecord } from "../types.ts"
|
|
4
|
+
|
|
5
|
+
let last: Promise<void> = Promise.resolve()
|
|
6
|
+
|
|
7
|
+
/** Adds one line to `notifications.jsonl`, in the order of the calls. */
|
|
8
|
+
export function record(file: string, delivery: DeliveryRecord): Promise<void> {
|
|
9
|
+
const line = `${JSON.stringify(delivery)}\n`
|
|
10
|
+
const written = last.then(async () => {
|
|
11
|
+
await mkdir(dirname(file), { recursive: true })
|
|
12
|
+
await appendFile(file, line)
|
|
13
|
+
})
|
|
14
|
+
last = written.catch(() => undefined)
|
|
15
|
+
return written
|
|
16
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import {
|
|
3
|
+
loadBroadcast,
|
|
4
|
+
loadDatabase,
|
|
5
|
+
loadMail,
|
|
6
|
+
loadRecord,
|
|
7
|
+
notifications,
|
|
8
|
+
recordFile,
|
|
9
|
+
webhook,
|
|
10
|
+
} from "#hamur/notifications/config"
|
|
11
|
+
import type { DeliveryRecord, NotificationOptions } from "../types.ts"
|
|
12
|
+
import type { DeliverDeps } from "./deliver.ts"
|
|
13
|
+
import type { Inbox } from "./inbox.ts"
|
|
14
|
+
import { postWebhook } from "./webhook.ts"
|
|
15
|
+
|
|
16
|
+
/** The rows of the database channel, imported at the first use. */
|
|
17
|
+
export async function useInbox(caller: string): Promise<Inbox> {
|
|
18
|
+
if (!loadDatabase) throw new Error(`${caller} needs a notification with the database channel`)
|
|
19
|
+
return (await loadDatabase()).inbox
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** What a delivery in the call and the task `notifications:deliver` share. */
|
|
23
|
+
export const deliverDeps: DeliverDeps = {
|
|
24
|
+
async load(name) {
|
|
25
|
+
if (!Object.hasOwn(notifications, name))
|
|
26
|
+
throw new Error(
|
|
27
|
+
`Notification ${JSON.stringify(name)} not found (notifications: ${Object.keys(notifications).join(", ") || "none"})`,
|
|
28
|
+
)
|
|
29
|
+
return (await notifications[name]!()).default as NotificationOptions<unknown, unknown>
|
|
30
|
+
},
|
|
31
|
+
async deliverMail(message, delivery, log) {
|
|
32
|
+
if (!loadMail) throw new Error("the mail channel needs @hamur/mail in modules")
|
|
33
|
+
return (await loadMail()).deliverMail(message, delivery, log)
|
|
34
|
+
},
|
|
35
|
+
storeRow: async (delivery) => (await useInbox("The delivery")).add(delivery),
|
|
36
|
+
openTopic: async (to) => (await loadBroadcast!()).openTopic(to),
|
|
37
|
+
...(webhook ? { webhook } : {}),
|
|
38
|
+
postWebhook,
|
|
39
|
+
...(loadRecord
|
|
40
|
+
? { record: async (delivery: DeliveryRecord) => (await loadRecord!()).record(recordFile, delivery) }
|
|
41
|
+
: {}),
|
|
42
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineTask } from "hamur/server"
|
|
2
|
+
import { runDelivery } from "./notify.ts"
|
|
3
|
+
import { unpackDelivery, type QueuedDelivery } from "./queue.ts"
|
|
4
|
+
import { deliverDeps } from "./runtime.ts"
|
|
5
|
+
|
|
6
|
+
/** Performs one delivery that `notify` queued. */
|
|
7
|
+
export default defineTask({
|
|
8
|
+
description: "Make one delivery that notify queued",
|
|
9
|
+
async run(payload: QueuedDelivery, ctx): Promise<void> {
|
|
10
|
+
if (typeof payload?.channel !== "string")
|
|
11
|
+
throw new TypeError("notifications:deliver takes a delivery that notify queued")
|
|
12
|
+
await runDelivery(deliverDeps, await unpackDelivery(payload), ctx.log)
|
|
13
|
+
},
|
|
14
|
+
})
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Recipient } from "../types.ts"
|
|
2
|
+
import { checkRecipient } from "./recipient.ts"
|
|
3
|
+
|
|
4
|
+
/** The longest topic. */
|
|
5
|
+
const MAX_LENGTH = 256
|
|
6
|
+
|
|
7
|
+
/** The topic the broadcast channel publishes to for `to`; no two recipients share one. */
|
|
8
|
+
export function notificationTopic(to: Pick<Recipient, "type" | "id">): string {
|
|
9
|
+
checkRecipient(to)
|
|
10
|
+
const type = to.type.replaceAll("%", "%25").replaceAll(":", "%3A")
|
|
11
|
+
const topic = `hamur:notifications:${type}:${to.id}`
|
|
12
|
+
// Redis carries a topic as UTF-8, where every unpaired surrogate becomes the same character
|
|
13
|
+
if (topic.length > MAX_LENGTH || !topic.isWellFormed())
|
|
14
|
+
throw new TypeError(
|
|
15
|
+
`The topic of a notification recipient is well-formed text of at most ${MAX_LENGTH} characters (got ${JSON.stringify(topic)})`,
|
|
16
|
+
)
|
|
17
|
+
return topic
|
|
18
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { pinnedFetch, readSecret, reasonPhrase, urlProblem } from "hamur/server/internal"
|
|
2
|
+
import type { WebhookTarget } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
const TIMEOUT = 10_000
|
|
5
|
+
const PREFIX = "whsec_"
|
|
6
|
+
const encoder = new TextEncoder()
|
|
7
|
+
|
|
8
|
+
type Send = (url: string, init: RequestInit) => Promise<Response>
|
|
9
|
+
|
|
10
|
+
function keyOf(secret: string): Uint8Array<ArrayBuffer> {
|
|
11
|
+
try {
|
|
12
|
+
const bytes = secret.startsWith(PREFIX) ? atob(secret.slice(PREFIX.length)) : ""
|
|
13
|
+
if (bytes !== "") return Uint8Array.from(bytes, (char) => char.charCodeAt(0))
|
|
14
|
+
} catch {}
|
|
15
|
+
throw new Error("the webhook secret must be whsec_ followed by the base64 of the key")
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The `webhook-signature` of Standard Webhooks: HMAC-SHA256 of `<id>.<timestamp>.<body>`. */
|
|
19
|
+
export async function signWebhook(secret: string, id: string, timestamp: number, body: string): Promise<string> {
|
|
20
|
+
const key = await crypto.subtle.importKey("raw", keyOf(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
|
|
21
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(`${id}.${timestamp}.${body}`))
|
|
22
|
+
return `v1,${btoa(String.fromCharCode(...new Uint8Array(signature)))}`
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Why a request got no answer, without the URL, which may hold a token. */
|
|
26
|
+
function reasonOf(error: unknown): string {
|
|
27
|
+
const {
|
|
28
|
+
name,
|
|
29
|
+
message,
|
|
30
|
+
code = (error as { cause?: { code?: unknown } }).cause?.code,
|
|
31
|
+
} = error as {
|
|
32
|
+
name?: string
|
|
33
|
+
message?: string
|
|
34
|
+
code?: unknown
|
|
35
|
+
}
|
|
36
|
+
if (name === "TimeoutError" || name === "AbortError") return `no answer in ${TIMEOUT / 1000} s`
|
|
37
|
+
if (typeof code === "string") return `the request failed (${code})`
|
|
38
|
+
return message && !message.includes("://") ? message : "the request failed"
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One signed `POST`, through the guarded fetch. Every non-2xx answer fails, a redirect included; the body of an answer is not read. */
|
|
42
|
+
export async function postWebhook(
|
|
43
|
+
target: WebhookTarget,
|
|
44
|
+
id: string,
|
|
45
|
+
body: string,
|
|
46
|
+
{ send = pinnedFetch() ?? fetch, now = Date.now }: { send?: Send; now?: () => number } = {},
|
|
47
|
+
): Promise<void> {
|
|
48
|
+
const problem = urlProblem(target.url)
|
|
49
|
+
if (problem !== undefined) throw new Error(`the webhook URL is refused: ${problem}`)
|
|
50
|
+
const timestamp = Math.floor(now() / 1000)
|
|
51
|
+
const signature = await signWebhook(readSecret(target.secret, "the webhook channel's secret"), id, timestamp, body)
|
|
52
|
+
let response: Response
|
|
53
|
+
try {
|
|
54
|
+
response = await send(target.url, {
|
|
55
|
+
method: "POST",
|
|
56
|
+
redirect: "manual",
|
|
57
|
+
signal: AbortSignal.timeout(TIMEOUT),
|
|
58
|
+
headers: {
|
|
59
|
+
"content-type": "application/json",
|
|
60
|
+
"webhook-id": id,
|
|
61
|
+
"webhook-timestamp": String(timestamp),
|
|
62
|
+
"webhook-signature": signature,
|
|
63
|
+
},
|
|
64
|
+
body,
|
|
65
|
+
})
|
|
66
|
+
} catch (error) {
|
|
67
|
+
throw new Error(reasonOf(error))
|
|
68
|
+
}
|
|
69
|
+
await response.body?.cancel().catch(() => undefined)
|
|
70
|
+
if (!response.ok) throw new Error(`${response.status} ${reasonPhrase(response.status)}`.trim())
|
|
71
|
+
}
|
package/src/test.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { dirname, join } from "node:path"
|
|
3
|
+
import { useTestContext } from "hamur/test"
|
|
4
|
+
import { useTestLoader } from "hamur/test/internal"
|
|
5
|
+
import type { DeliveryRecord, NotificationName } from "./types.ts"
|
|
6
|
+
|
|
7
|
+
async function recordFile(): Promise<string> {
|
|
8
|
+
try {
|
|
9
|
+
return join(dirname(useTestContext().outputDir), ".hamur", "notifications.jsonl")
|
|
10
|
+
} catch {}
|
|
11
|
+
try {
|
|
12
|
+
return join((await useTestLoader()).hamur.options.buildDir, "notifications.jsonl")
|
|
13
|
+
} catch (error) {
|
|
14
|
+
throw new Error(
|
|
15
|
+
"@hamur/notifications/test: no deliveries to read; call setup() from hamur/test in this file or run the tests with the hamur/test/preload",
|
|
16
|
+
{ cause: error },
|
|
17
|
+
)
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The deliveries the test app recorded, oldest first; `name` keeps one notification's. */
|
|
22
|
+
export async function sentNotifications(options: { name?: NotificationName } = {}): Promise<DeliveryRecord[]> {
|
|
23
|
+
let text: string
|
|
24
|
+
try {
|
|
25
|
+
text = await readFile(await recordFile(), "utf8")
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if ((error as { code?: string }).code === "ENOENT") return []
|
|
28
|
+
throw error
|
|
29
|
+
}
|
|
30
|
+
const deliveries = text
|
|
31
|
+
.split("\n")
|
|
32
|
+
.filter(Boolean)
|
|
33
|
+
.map((line) => JSON.parse(line) as DeliveryRecord)
|
|
34
|
+
return options.name === undefined ? deliveries : deliveries.filter(({ name }) => name === options.name)
|
|
35
|
+
}
|