@fabrika/db 0.9.0-dev.42 → 0.9.0-dev.44
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/package.json +4 -4
- package/src/framework.ts +2 -0
- package/src/migrations-sqlite.ts +46 -0
- package/src/migrations.ts +51 -0
- package/src/notifications.ts +152 -0
- package/src/push-subscriptions.ts +287 -0
- package/src/registry.ts +6 -0
- package/src/store.ts +4 -0
- package/types/src/framework.d.ts +2 -0
- package/types/src/migrations.d.ts +2 -0
- package/types/src/notifications.d.ts +37 -0
- package/types/src/push-subscriptions.d.ts +49 -0
- package/types/src/registry.d.ts +6 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/db",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.44",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": [
|
|
6
6
|
"./src/testing.ts",
|
|
@@ -96,9 +96,9 @@
|
|
|
96
96
|
"test": "bun test"
|
|
97
97
|
},
|
|
98
98
|
"dependencies": {
|
|
99
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
100
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
101
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
99
|
+
"@fabrika/auth-core": "0.9.0-dev.44",
|
|
100
|
+
"@fabrika/platform": "0.9.0-dev.44",
|
|
101
|
+
"@fabrika/platform-node": "0.9.0-dev.44",
|
|
102
102
|
"kysely": "0.29.6",
|
|
103
103
|
"kysely-postgres-js": "5.0.1",
|
|
104
104
|
"zod": "^3.25.76"
|
package/src/framework.ts
CHANGED
|
@@ -23,7 +23,9 @@ export { type FileHolding, fileHoldingOf, type FileReference, fileReference, hol
|
|
|
23
23
|
export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables'
|
|
24
24
|
export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
|
|
25
25
|
export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes'
|
|
26
|
+
export type { NewNotification, NotificationAbout, Notifications, StoredNotification } from './notifications'
|
|
26
27
|
export type { DataAccess, DataHandles, DataSite } from './orm'
|
|
28
|
+
export type { PushBinding, PushInboxSubscription, PushRecordOutcome, PushSubscriptionKeys, PushSubscriptions } from './push-subscriptions'
|
|
27
29
|
export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry'
|
|
28
30
|
export type { RequestReceipt, RequestReceipts } from './request-receipts'
|
|
29
31
|
export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql'
|
package/src/migrations-sqlite.ts
CHANGED
|
@@ -20,6 +20,8 @@ import {
|
|
|
20
20
|
JOB_SCHEDULE_TABLE,
|
|
21
21
|
JOB_WAKES_TABLE,
|
|
22
22
|
LIST_CURSOR_KEY_TABLE,
|
|
23
|
+
NOTIFICATIONS_TABLE,
|
|
24
|
+
PUSH_SUBSCRIPTIONS_TABLE,
|
|
23
25
|
REQUEST_RECEIPTS_TABLE,
|
|
24
26
|
WEBHOOK_BINDINGS_TABLE,
|
|
25
27
|
WEBHOOK_DELIVERIES_TABLE,
|
|
@@ -205,6 +207,50 @@ CREATE TABLE ${JOB_SCHEDULE_TABLE} (
|
|
|
205
207
|
name: '0008_job_schedule_declared.sql',
|
|
206
208
|
sql: `-- The cron keys the stored generation's deploy declares, as a JSON array (see the Postgres bundle's 0014).
|
|
207
209
|
ALTER TABLE ${JOB_SCHEDULE_TABLE} ADD COLUMN declared TEXT NOT NULL DEFAULT '[]';
|
|
210
|
+
`,
|
|
211
|
+
}),
|
|
212
|
+
Object.freeze({
|
|
213
|
+
name: '0009_push_subscriptions.sql',
|
|
214
|
+
sql: `-- A browser's Web Push subscription (ADR-0088), bound to the principal who recorded it; a row whose gone_at is set is a
|
|
215
|
+
-- tombstone (see the Postgres bundle's 0015). Times are epoch milliseconds.
|
|
216
|
+
CREATE TABLE ${PUSH_SUBSCRIPTIONS_TABLE} (
|
|
217
|
+
id TEXT PRIMARY KEY,
|
|
218
|
+
principal TEXT NOT NULL,
|
|
219
|
+
endpoint TEXT NOT NULL UNIQUE,
|
|
220
|
+
p256dh TEXT,
|
|
221
|
+
auth TEXT,
|
|
222
|
+
vapid_key TEXT,
|
|
223
|
+
cursor TEXT,
|
|
224
|
+
next_attempt_at INTEGER,
|
|
225
|
+
recorded_at INTEGER NOT NULL,
|
|
226
|
+
gone_at INTEGER,
|
|
227
|
+
CONSTRAINT ${PUSH_SUBSCRIPTIONS_TABLE}_tombstone CHECK (
|
|
228
|
+
(gone_at IS NULL AND p256dh IS NOT NULL AND auth IS NOT NULL AND vapid_key IS NOT NULL)
|
|
229
|
+
OR (gone_at IS NOT NULL AND p256dh IS NULL AND auth IS NULL AND vapid_key IS NULL AND next_attempt_at IS NULL)
|
|
230
|
+
)
|
|
231
|
+
) STRICT;
|
|
232
|
+
CREATE INDEX ${PUSH_SUBSCRIPTIONS_TABLE}_principal ON ${PUSH_SUBSCRIPTIONS_TABLE} (principal, recorded_at) WHERE gone_at IS NULL;
|
|
233
|
+
CREATE INDEX ${PUSH_SUBSCRIPTIONS_TABLE}_gone_at ON ${PUSH_SUBSCRIPTIONS_TABLE} (gone_at) WHERE gone_at IS NOT NULL;
|
|
234
|
+
`,
|
|
235
|
+
}),
|
|
236
|
+
Object.freeze({
|
|
237
|
+
name: '0010_notifications.sql',
|
|
238
|
+
sql: `-- A notification for one principal (ADR-0088 §6); see the Postgres bundle's 0016. The id is a UUIDv7 as lowercase
|
|
239
|
+
-- text, so text order is the order written.
|
|
240
|
+
CREATE TABLE ${NOTIFICATIONS_TABLE} (
|
|
241
|
+
id TEXT PRIMARY KEY,
|
|
242
|
+
principal TEXT NOT NULL,
|
|
243
|
+
title TEXT NOT NULL,
|
|
244
|
+
body TEXT NOT NULL,
|
|
245
|
+
path TEXT NOT NULL,
|
|
246
|
+
action TEXT NOT NULL,
|
|
247
|
+
dimension TEXT,
|
|
248
|
+
scope_value TEXT,
|
|
249
|
+
created_at INTEGER NOT NULL,
|
|
250
|
+
CONSTRAINT ${NOTIFICATIONS_TABLE}_about CHECK ((dimension IS NULL) = (scope_value IS NULL))
|
|
251
|
+
) STRICT;
|
|
252
|
+
CREATE INDEX ${NOTIFICATIONS_TABLE}_principal ON ${NOTIFICATIONS_TABLE} (principal, id);
|
|
253
|
+
CREATE INDEX ${NOTIFICATIONS_TABLE}_created_at ON ${NOTIFICATIONS_TABLE} (created_at);
|
|
208
254
|
`,
|
|
209
255
|
}),
|
|
210
256
|
])
|
package/src/migrations.ts
CHANGED
|
@@ -19,6 +19,8 @@ export const FILES_TABLE = 'fabrika_files'
|
|
|
19
19
|
export const FILE_DELETIONS_TABLE = 'fabrika_file_deletions'
|
|
20
20
|
export const REQUEST_RECEIPTS_TABLE = 'fabrika_request_receipts'
|
|
21
21
|
export const LIST_CURSOR_KEY_TABLE = 'fabrika_list_cursor_key'
|
|
22
|
+
export const PUSH_SUBSCRIPTIONS_TABLE = 'fabrika_push_subscriptions'
|
|
23
|
+
export const NOTIFICATIONS_TABLE = 'fabrika_notifications'
|
|
22
24
|
/** The function an application's last adoption migration calls with the name of a file collection it adopted. */
|
|
23
25
|
export const FILES_RELEASE_FUNCTION = 'fabrika_files_release'
|
|
24
26
|
/**
|
|
@@ -327,6 +329,55 @@ CREATE TABLE ${JOB_SCHEDULE_TABLE} (
|
|
|
327
329
|
sql: `-- The cron keys (cron:<job>:<expression>) the stored generation's deploy declares, as a JSON array: a run of any
|
|
328
330
|
-- deploy schedules its job's next fire only under a key in it, so an old revision restores no removed job or expression.
|
|
329
331
|
ALTER TABLE ${JOB_SCHEDULE_TABLE} ADD COLUMN declared TEXT NOT NULL DEFAULT '[]';
|
|
332
|
+
`,
|
|
333
|
+
}),
|
|
334
|
+
Object.freeze({
|
|
335
|
+
name: '0015_push_subscriptions.sql',
|
|
336
|
+
sql: `-- A browser's Web Push subscription (ADR-0088), bound to the principal who recorded it: its endpoint at the push service,
|
|
337
|
+
-- its keys, the VAPID public key it was made with, the newest notification the inbox answered for it (cursor), and when
|
|
338
|
+
-- the sender may try it again. A row whose gone_at is set is a tombstone: the push service called the endpoint gone,
|
|
339
|
+
-- and only the principal and the endpoint stay, so a replacement the page posts later still finds whose it was. Times
|
|
340
|
+
-- are epoch milliseconds.
|
|
341
|
+
CREATE TABLE ${PUSH_SUBSCRIPTIONS_TABLE} (
|
|
342
|
+
id UUID PRIMARY KEY,
|
|
343
|
+
principal TEXT NOT NULL,
|
|
344
|
+
endpoint TEXT NOT NULL UNIQUE,
|
|
345
|
+
p256dh TEXT,
|
|
346
|
+
auth TEXT,
|
|
347
|
+
vapid_key TEXT,
|
|
348
|
+
cursor TEXT,
|
|
349
|
+
next_attempt_at BIGINT,
|
|
350
|
+
recorded_at BIGINT NOT NULL,
|
|
351
|
+
gone_at BIGINT,
|
|
352
|
+
CONSTRAINT ${PUSH_SUBSCRIPTIONS_TABLE}_tombstone CHECK (
|
|
353
|
+
(gone_at IS NULL AND p256dh IS NOT NULL AND auth IS NOT NULL AND vapid_key IS NOT NULL)
|
|
354
|
+
OR (gone_at IS NOT NULL AND p256dh IS NULL AND auth IS NULL AND vapid_key IS NULL AND next_attempt_at IS NULL)
|
|
355
|
+
)
|
|
356
|
+
);
|
|
357
|
+
CREATE INDEX ${PUSH_SUBSCRIPTIONS_TABLE}_principal ON ${PUSH_SUBSCRIPTIONS_TABLE} (principal, recorded_at) WHERE gone_at IS NULL;
|
|
358
|
+
CREATE INDEX ${PUSH_SUBSCRIPTIONS_TABLE}_gone_at ON ${PUSH_SUBSCRIPTIONS_TABLE} (gone_at) WHERE gone_at IS NOT NULL;
|
|
359
|
+
`,
|
|
360
|
+
}),
|
|
361
|
+
Object.freeze({
|
|
362
|
+
name: '0016_notifications.sql',
|
|
363
|
+
sql: `-- A notification for one principal (ADR-0088 §6): its text and the path a click opens, and what the recipient must
|
|
364
|
+
-- hold to read it, checked when the inbox answers: an action on an object (its dimension and key), or the action as a
|
|
365
|
+
-- global grant (dimension and scope_value null). The id is a UUIDv7, so its order is the order written, which a
|
|
366
|
+
-- subscription's cursor counts in. created_at is epoch milliseconds; a row lives seven days.
|
|
367
|
+
CREATE TABLE ${NOTIFICATIONS_TABLE} (
|
|
368
|
+
id UUID PRIMARY KEY,
|
|
369
|
+
principal TEXT NOT NULL,
|
|
370
|
+
title TEXT NOT NULL,
|
|
371
|
+
body TEXT NOT NULL,
|
|
372
|
+
path TEXT NOT NULL,
|
|
373
|
+
action TEXT NOT NULL,
|
|
374
|
+
dimension TEXT,
|
|
375
|
+
scope_value TEXT,
|
|
376
|
+
created_at BIGINT NOT NULL,
|
|
377
|
+
CONSTRAINT ${NOTIFICATIONS_TABLE}_about CHECK ((dimension IS NULL) = (scope_value IS NULL))
|
|
378
|
+
);
|
|
379
|
+
CREATE INDEX ${NOTIFICATIONS_TABLE}_principal ON ${NOTIFICATIONS_TABLE} (principal, id);
|
|
380
|
+
CREATE INDEX ${NOTIFICATIONS_TABLE}_created_at ON ${NOTIFICATIONS_TABLE} (created_at);
|
|
330
381
|
`,
|
|
331
382
|
}),
|
|
332
383
|
])
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// The framework's side of `fabrika_notifications` (`@fabrika/db/migrations`, ADR-0088 §6): a notification written for
|
|
2
|
+
// one principal, with what the recipient must hold to read it. Only `@fabrika/app` reaches it, through
|
|
3
|
+
// `frameworkTablesOf`, in the invocation's own transaction. The inbox reads a principal's rows after a subscription's
|
|
4
|
+
// cursor, oldest first; whether the caller may read each one is the framework's check, not this module's. A row lives
|
|
5
|
+
// `retentionMs`: a read never answers an older one, and every write prunes a batch of them.
|
|
6
|
+
|
|
7
|
+
import { runFixedStatement, type Session } from './database'
|
|
8
|
+
import { QueryRefusedError } from './errors'
|
|
9
|
+
import type { DialectTexts } from './job-leases'
|
|
10
|
+
import { NOTIFICATIONS_TABLE } from './migrations'
|
|
11
|
+
|
|
12
|
+
export const NOTIFICATION_LIMITS = Object.freeze({
|
|
13
|
+
/** How long a notification is kept and answered: seven days. */
|
|
14
|
+
retentionMs: 7 * 24 * 60 * 60 * 1_000,
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
/** What the recipient must hold to read a notification: an action on one object, or the action as a global grant. */
|
|
18
|
+
export type NotificationAbout =
|
|
19
|
+
| { readonly action: string; readonly dimension: string; readonly value: string }
|
|
20
|
+
| { readonly action: string; readonly dimension: null; readonly value: null }
|
|
21
|
+
|
|
22
|
+
export interface StoredNotification {
|
|
23
|
+
/** A UUIDv7: its order is the order written. */
|
|
24
|
+
readonly id: string
|
|
25
|
+
readonly title: string
|
|
26
|
+
readonly body: string
|
|
27
|
+
readonly path: string
|
|
28
|
+
readonly about: NotificationAbout
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface NewNotification extends StoredNotification {
|
|
32
|
+
readonly principal: string
|
|
33
|
+
/** Epoch milliseconds. */
|
|
34
|
+
readonly createdAt: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface Notifications {
|
|
38
|
+
/** Writes `notification`, after pruning a batch of rows past the retention. */
|
|
39
|
+
record(session: Session, notification: NewNotification): Promise<void>
|
|
40
|
+
/** `principal`'s rows written after the notification `after` (all of them for `null`), within the retention at `now`, oldest first, at most `limit`. */
|
|
41
|
+
unseen(session: Session, principal: string, after: string | null, now: number, limit: number): Promise<readonly StoredNotification[]>
|
|
42
|
+
/** How many of `principal`'s rows within the retention at `now` were written after `after`. */
|
|
43
|
+
countAfter(session: Session, principal: string, after: string | null, now: number): Promise<number>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const N = NOTIFICATIONS_TABLE
|
|
47
|
+
|
|
48
|
+
/** Rows one write prunes at most. */
|
|
49
|
+
const PRUNE_BATCH = 32
|
|
50
|
+
|
|
51
|
+
const SQL_PRUNE: DialectTexts = {
|
|
52
|
+
postgres: `delete from ${N} where id in (select id from ${N} where created_at < $1::bigint limit ${PRUNE_BATCH} for update skip locked)`,
|
|
53
|
+
sqlite: `delete from ${N} where id in (select id from ${N} where created_at < ?1 limit ${PRUNE_BATCH})`,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const SQL_INSERT: DialectTexts = {
|
|
57
|
+
postgres: `insert into ${N} (id, principal, title, body, path, action, dimension, scope_value, created_at)
|
|
58
|
+
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::bigint)`,
|
|
59
|
+
sqlite: `insert into ${N} (id, principal, title, body, path, action, dimension, scope_value, created_at)
|
|
60
|
+
values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const SQL_UNSEEN: DialectTexts = {
|
|
64
|
+
postgres: `select id::text as id, title, body, path, action, dimension, scope_value from ${N}
|
|
65
|
+
where principal = $1 and ($2::uuid is null or id > $2::uuid) and created_at >= $3::bigint order by id limit $4::int`,
|
|
66
|
+
sqlite: `select id, title, body, path, action, dimension, scope_value from ${N}
|
|
67
|
+
where principal = ?1 and (?2 is null or id > ?2) and created_at >= ?3 order by id limit ?4`,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const SQL_COUNT: DialectTexts = {
|
|
71
|
+
postgres: `select count(*)::int as unseen from ${N} where principal = $1 and ($2::uuid is null or id > $2::uuid) and created_at >= $3::bigint`,
|
|
72
|
+
sqlite: `select count(*) as unseen from ${N} where principal = ?1 and (?2 is null or id > ?2) and created_at >= ?3`,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isRow(value: unknown): value is Readonly<Record<string, unknown>> {
|
|
76
|
+
return typeof value === 'object' && value !== null
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function text(row: Readonly<Record<string, unknown>>, column: string): string {
|
|
80
|
+
const value = row[column]
|
|
81
|
+
if (typeof value !== 'string') {
|
|
82
|
+
throw new QueryRefusedError('unexpected_row', `${N}.${column} came back as ${typeof value}`)
|
|
83
|
+
}
|
|
84
|
+
return value
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function storedOf(row: unknown): StoredNotification {
|
|
88
|
+
if (!isRow(row)) {
|
|
89
|
+
throw new QueryRefusedError('unexpected_row', `${N} answered a row that is not an object`)
|
|
90
|
+
}
|
|
91
|
+
const dimension = row['dimension']
|
|
92
|
+
const value = row['scope_value']
|
|
93
|
+
const action = text(row, 'action')
|
|
94
|
+
const about: NotificationAbout | null = dimension === null && value === null
|
|
95
|
+
? { action, dimension: null, value: null }
|
|
96
|
+
: typeof dimension === 'string' && typeof value === 'string'
|
|
97
|
+
? { action, dimension, value }
|
|
98
|
+
: null
|
|
99
|
+
if (about === null) {
|
|
100
|
+
throw new QueryRefusedError('unexpected_row', `${N} answered a row whose object is half named`)
|
|
101
|
+
}
|
|
102
|
+
return { id: text(row, 'id'), title: text(row, 'title'), body: text(row, 'body'), path: text(row, 'path'), about }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function epochMs(value: number, what: string): number {
|
|
106
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
107
|
+
throw new QueryRefusedError('invalid_argument', `${what} must be epoch milliseconds`)
|
|
108
|
+
}
|
|
109
|
+
return value
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function notifications(): Notifications {
|
|
113
|
+
return Object.freeze({
|
|
114
|
+
record(session: Session, notification: NewNotification): Promise<void> {
|
|
115
|
+
const createdAt = epochMs(notification.createdAt, 'createdAt')
|
|
116
|
+
return session.transaction(async (transaction) => {
|
|
117
|
+
await runFixedStatement(transaction, SQL_PRUNE[transaction.dialect], [createdAt - NOTIFICATION_LIMITS.retentionMs])
|
|
118
|
+
const { about } = notification
|
|
119
|
+
await runFixedStatement(transaction, SQL_INSERT[transaction.dialect], [
|
|
120
|
+
notification.id,
|
|
121
|
+
notification.principal,
|
|
122
|
+
notification.title,
|
|
123
|
+
notification.body,
|
|
124
|
+
notification.path,
|
|
125
|
+
about.action,
|
|
126
|
+
about.dimension,
|
|
127
|
+
about.value,
|
|
128
|
+
createdAt,
|
|
129
|
+
])
|
|
130
|
+
})
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
async unseen(session: Session, principal: string, after: string | null, now: number, limit: number): Promise<readonly StoredNotification[]> {
|
|
134
|
+
if (!Number.isSafeInteger(limit) || limit < 1) {
|
|
135
|
+
throw new QueryRefusedError('invalid_argument', 'a limit must be a whole number of at least 1')
|
|
136
|
+
}
|
|
137
|
+
const since = epochMs(now, 'now') - NOTIFICATION_LIMITS.retentionMs
|
|
138
|
+
const rows = await runFixedStatement(session, SQL_UNSEEN[session.dialect], [principal, after, since, limit])
|
|
139
|
+
return rows.map(storedOf)
|
|
140
|
+
},
|
|
141
|
+
|
|
142
|
+
async countAfter(session: Session, principal: string, after: string | null, now: number): Promise<number> {
|
|
143
|
+
const since = epochMs(now, 'now') - NOTIFICATION_LIMITS.retentionMs
|
|
144
|
+
const [row] = await runFixedStatement(session, SQL_COUNT[session.dialect], [principal, after, since])
|
|
145
|
+
const counted = isRow(row) ? row['unseen'] : undefined
|
|
146
|
+
if (typeof counted !== 'number') {
|
|
147
|
+
throw new QueryRefusedError('unexpected_row', `${N} answered a count that is no number`)
|
|
148
|
+
}
|
|
149
|
+
return counted
|
|
150
|
+
},
|
|
151
|
+
})
|
|
152
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// The framework's side of `fabrika_push_subscriptions` (`@fabrika/db/migrations`, ADR-0088): a browser's Web Push
|
|
2
|
+
// subscription, bound to the principal who recorded it. Only `@fabrika/app`'s dispatcher reaches it, through
|
|
3
|
+
// `frameworkTablesOf`, in the invocation's own transaction. The principal always comes from the verified token, never
|
|
4
|
+
// from a request body; the caller hands it in.
|
|
5
|
+
//
|
|
6
|
+
// - A subscription is recorded only under its own principal: an endpoint whose row (or unexpired tombstone) names
|
|
7
|
+
// another principal is `taken`, never rebound.
|
|
8
|
+
// - A replacement (a key rotation, a `pushsubscriptionchange`) names the old endpoint, and is accepted only when the
|
|
9
|
+
// old endpoint's row or tombstone names the caller; the old row goes, its cursor moves to the new one.
|
|
10
|
+
// - A push service's 404 or 410 turns the row into a tombstone (`retire`): the principal and the endpoint only, kept
|
|
11
|
+
// `tombstoneRetentionMs`, which answers nothing but a replacement's question.
|
|
12
|
+
// - A principal holds at most `perPrincipal` live subscriptions: a record past it drops the oldest.
|
|
13
|
+
//
|
|
14
|
+
// On Postgres every write first takes the principal's transaction lock, so two records of one person never both see
|
|
15
|
+
// room under the bound; the endpoint's uniqueness decides between two people. Times are epoch milliseconds the caller
|
|
16
|
+
// passes, as the receipts take theirs.
|
|
17
|
+
|
|
18
|
+
import { runFixedStatement, type Session } from './database'
|
|
19
|
+
import { QueryRefusedError } from './errors'
|
|
20
|
+
import type { DialectTexts } from './job-leases'
|
|
21
|
+
import { PUSH_SUBSCRIPTIONS_TABLE } from './migrations'
|
|
22
|
+
|
|
23
|
+
export const PUSH_SUBSCRIPTION_LIMITS = Object.freeze({
|
|
24
|
+
/** Live subscriptions one principal holds; the next record drops the oldest. */
|
|
25
|
+
perPrincipal: 10,
|
|
26
|
+
/** How long a tombstone answers a replacement: 30 days. */
|
|
27
|
+
tombstoneRetentionMs: 30 * 24 * 60 * 60 * 1_000,
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
/** A subscription as the page hands it over, with the VAPID public key it was made with. */
|
|
31
|
+
export interface PushSubscriptionKeys {
|
|
32
|
+
readonly endpoint: string
|
|
33
|
+
/** The browser's P-256 key, base64url. */
|
|
34
|
+
readonly p256dh: string
|
|
35
|
+
/** The browser's authentication secret, base64url. */
|
|
36
|
+
readonly auth: string
|
|
37
|
+
/** The VAPID public key the browser subscribed with, base64url. */
|
|
38
|
+
readonly vapidKey: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Whose a browser's endpoint is, as the caller may learn it: its own live row, another principal's, or none (a tombstone included). */
|
|
42
|
+
export type PushBinding = 'mine' | 'other' | 'unknown'
|
|
43
|
+
|
|
44
|
+
/** The caller's live subscription and the newest notification the inbox answered for it, or `null` when it is not theirs. */
|
|
45
|
+
export type PushInboxSubscription = { readonly cursor: string | null } | null
|
|
46
|
+
|
|
47
|
+
/** `recorded`, or why not: the endpoint is bound to another principal, or the replaced endpoint is not the caller's. */
|
|
48
|
+
export type PushRecordOutcome = 'recorded' | 'taken' | 'not_replaceable'
|
|
49
|
+
|
|
50
|
+
export interface PushSubscriptions {
|
|
51
|
+
/** Whose `endpoint` is, for `principal`. */
|
|
52
|
+
binding(session: Session, principal: string, endpoint: string): Promise<PushBinding>
|
|
53
|
+
/**
|
|
54
|
+
* Records `subscription` for `principal` under `id` (a new row's key, a UUIDv7 made now, which is also a new row's
|
|
55
|
+
* cursor, so it reads only notifications written after it; an existing row of the caller keeps its key and cursor),
|
|
56
|
+
* replacing the endpoint `replace` when it names one, at `now`. Prunes a batch of expired tombstones first, and
|
|
57
|
+
* drops the principal's oldest live rows past the bound after. An outcome but `recorded` changes no subscription: the
|
|
58
|
+
* old row is removed only after the new one was written.
|
|
59
|
+
*/
|
|
60
|
+
record(
|
|
61
|
+
session: Session,
|
|
62
|
+
principal: string,
|
|
63
|
+
id: string,
|
|
64
|
+
subscription: PushSubscriptionKeys,
|
|
65
|
+
replace: string | null,
|
|
66
|
+
now: number,
|
|
67
|
+
): Promise<PushRecordOutcome>
|
|
68
|
+
/**
|
|
69
|
+
* What the inbox reads `endpoint` as for `principal`: the caller's live subscription and its cursor, or none. A live row
|
|
70
|
+
* of another principal is deleted here (§7): the browser it wakes is someone else's now, and stops waking for them.
|
|
71
|
+
*/
|
|
72
|
+
inbox(session: Session, principal: string, endpoint: string): Promise<PushInboxSubscription>
|
|
73
|
+
/** Moves the cursor of `principal`'s live `endpoint` forward to `cursor`, never back. */
|
|
74
|
+
advance(session: Session, principal: string, endpoint: string, cursor: string): Promise<void>
|
|
75
|
+
/** Removes `principal`'s own row (or tombstone) of `endpoint`; `false` when it has none. */
|
|
76
|
+
remove(session: Session, principal: string, endpoint: string): Promise<boolean>
|
|
77
|
+
/** The push service called `endpoint` gone: its live row becomes a tombstone at `now`. `false` when it had none. */
|
|
78
|
+
retire(session: Session, endpoint: string, now: number): Promise<boolean>
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const T = PUSH_SUBSCRIPTIONS_TABLE
|
|
82
|
+
|
|
83
|
+
/** Tombstones one write prunes at most; every record prunes, so expired ones never outgrow the live ones. */
|
|
84
|
+
const PRUNE_BATCH = 32
|
|
85
|
+
|
|
86
|
+
// Held until the transaction ends; two principals whose hashes collide only wait for each other.
|
|
87
|
+
const SQL_LOCK = `select 1 as locked from pg_advisory_xact_lock(hashtextextended('fabrika_push' || chr(10) || $1, 0))`
|
|
88
|
+
|
|
89
|
+
const SQL_PRUNE: DialectTexts = {
|
|
90
|
+
postgres: `delete from ${T} where id in (
|
|
91
|
+
select id from ${T} where gone_at < $1::bigint limit ${PRUNE_BATCH} for update skip locked
|
|
92
|
+
)`,
|
|
93
|
+
sqlite: `delete from ${T} where id in (select id from ${T} where gone_at < ?1 limit ${PRUNE_BATCH})`,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The old row is replaceable only when it, or its tombstone within the retention, is the caller's; its cursor moves on.
|
|
97
|
+
// Locked until the transaction ends, so the sender cannot retire it between this read and its delete.
|
|
98
|
+
const SQL_REPLACED: DialectTexts = {
|
|
99
|
+
postgres: `select cursor from ${T} where endpoint = $1 and principal = $2 and (gone_at is null or gone_at >= $3::bigint) for update`,
|
|
100
|
+
sqlite: `select cursor from ${T} where endpoint = ?1 and principal = ?2 and (gone_at is null or gone_at >= ?3)`,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// After the new row is written: the old one, read and locked above, goes.
|
|
104
|
+
const SQL_DROP_REPLACED: DialectTexts = {
|
|
105
|
+
postgres: `delete from ${T} where endpoint = $1 and principal = $2`,
|
|
106
|
+
sqlite: `delete from ${T} where endpoint = ?1 and principal = ?2`,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// One statement decides between two principals: a row of another principal is overwritten only when it is a tombstone
|
|
110
|
+
// past the retention. A row of the caller keeps its id and its cursor, and is live again with the new keys.
|
|
111
|
+
const SQL_UPSERT: DialectTexts = {
|
|
112
|
+
postgres: `insert into ${T} (id, principal, endpoint, p256dh, auth, vapid_key, cursor, recorded_at)
|
|
113
|
+
values ($1, $2, $3, $4, $5, $6, $7, $8::bigint)
|
|
114
|
+
on conflict (endpoint) do update set
|
|
115
|
+
principal = excluded.principal,
|
|
116
|
+
p256dh = excluded.p256dh,
|
|
117
|
+
auth = excluded.auth,
|
|
118
|
+
vapid_key = excluded.vapid_key,
|
|
119
|
+
cursor = case when ${T}.principal = excluded.principal then coalesce(${T}.cursor, excluded.cursor) else excluded.cursor end,
|
|
120
|
+
next_attempt_at = null,
|
|
121
|
+
recorded_at = excluded.recorded_at,
|
|
122
|
+
gone_at = null
|
|
123
|
+
where ${T}.principal = excluded.principal or ${T}.gone_at < $9::bigint
|
|
124
|
+
returning endpoint`,
|
|
125
|
+
sqlite: `insert into ${T} (id, principal, endpoint, p256dh, auth, vapid_key, cursor, recorded_at)
|
|
126
|
+
values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
|
|
127
|
+
on conflict (endpoint) do update set
|
|
128
|
+
principal = excluded.principal,
|
|
129
|
+
p256dh = excluded.p256dh,
|
|
130
|
+
auth = excluded.auth,
|
|
131
|
+
vapid_key = excluded.vapid_key,
|
|
132
|
+
cursor = case when ${T}.principal = excluded.principal then coalesce(${T}.cursor, excluded.cursor) else excluded.cursor end,
|
|
133
|
+
next_attempt_at = null,
|
|
134
|
+
recorded_at = excluded.recorded_at,
|
|
135
|
+
gone_at = null
|
|
136
|
+
where ${T}.principal = excluded.principal or ${T}.gone_at < ?9
|
|
137
|
+
returning endpoint`,
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const SQL_TRIM: DialectTexts = {
|
|
141
|
+
postgres: `delete from ${T} where id in (
|
|
142
|
+
select id from ${T} where principal = $1 and gone_at is null order by recorded_at desc, id desc offset ${PUSH_SUBSCRIPTION_LIMITS.perPrincipal}
|
|
143
|
+
)`,
|
|
144
|
+
sqlite: `delete from ${T} where id in (
|
|
145
|
+
select id from ${T} where principal = ?1 and gone_at is null order by recorded_at desc, id desc limit -1 offset ${PUSH_SUBSCRIPTION_LIMITS.perPrincipal}
|
|
146
|
+
)`,
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const SQL_BINDING: DialectTexts = {
|
|
150
|
+
postgres: `select principal from ${T} where endpoint = $1 and gone_at is null`,
|
|
151
|
+
sqlite: `select principal from ${T} where endpoint = ?1 and gone_at is null`,
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const SQL_INBOX: DialectTexts = {
|
|
155
|
+
postgres: `select principal, cursor from ${T} where endpoint = $1 and gone_at is null for update`,
|
|
156
|
+
sqlite: `select principal, cursor from ${T} where endpoint = ?1 and gone_at is null`,
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const SQL_DROP_OTHER: DialectTexts = {
|
|
160
|
+
postgres: `delete from ${T} where endpoint = $1 and principal <> $2 and gone_at is null`,
|
|
161
|
+
sqlite: `delete from ${T} where endpoint = ?1 and principal <> ?2 and gone_at is null`,
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const SQL_ADVANCE: DialectTexts = {
|
|
165
|
+
postgres: `update ${T} set cursor = $3 where endpoint = $1 and principal = $2 and gone_at is null and (cursor is null or cursor::uuid < $3::uuid)`,
|
|
166
|
+
sqlite: `update ${T} set cursor = ?3 where endpoint = ?1 and principal = ?2 and gone_at is null and (cursor is null or cursor < ?3)`,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const SQL_REMOVE: DialectTexts = {
|
|
170
|
+
postgres: `delete from ${T} where endpoint = $1 and principal = $2 returning endpoint`,
|
|
171
|
+
sqlite: `delete from ${T} where endpoint = ?1 and principal = ?2 returning endpoint`,
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const SQL_RETIRE: DialectTexts = {
|
|
175
|
+
postgres: `update ${T} set gone_at = $2::bigint, p256dh = null, auth = null, vapid_key = null, next_attempt_at = null
|
|
176
|
+
where endpoint = $1 and gone_at is null returning endpoint`,
|
|
177
|
+
sqlite: `update ${T} set gone_at = ?2, p256dh = null, auth = null, vapid_key = null, next_attempt_at = null
|
|
178
|
+
where endpoint = ?1 and gone_at is null returning endpoint`,
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function isRow(value: unknown): value is Readonly<Record<string, unknown>> {
|
|
182
|
+
return typeof value === 'object' && value !== null
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The text in `column` of the row, or `null`; any other value is a row this module did not write. */
|
|
186
|
+
function nullableText(row: unknown, column: string): string | null {
|
|
187
|
+
if (!isRow(row)) {
|
|
188
|
+
throw new QueryRefusedError('unexpected_row', `${T} answered a row that is not an object`)
|
|
189
|
+
}
|
|
190
|
+
const value = row[column]
|
|
191
|
+
if (value === null || typeof value === 'string') {
|
|
192
|
+
return value
|
|
193
|
+
}
|
|
194
|
+
throw new QueryRefusedError('unexpected_row', `${T}.${column} came back as ${typeof value}`)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function epochMs(value: number, what: string): number {
|
|
198
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
199
|
+
throw new QueryRefusedError('invalid_argument', `${what} must be epoch milliseconds`)
|
|
200
|
+
}
|
|
201
|
+
return value
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function pushSubscriptions(): PushSubscriptions {
|
|
205
|
+
return Object.freeze({
|
|
206
|
+
async binding(session: Session, principal: string, endpoint: string): Promise<PushBinding> {
|
|
207
|
+
const [row] = await runFixedStatement(session, SQL_BINDING[session.dialect], [endpoint])
|
|
208
|
+
if (row === undefined) {
|
|
209
|
+
return 'unknown'
|
|
210
|
+
}
|
|
211
|
+
return nullableText(row, 'principal') === principal ? 'mine' : 'other'
|
|
212
|
+
},
|
|
213
|
+
|
|
214
|
+
record(
|
|
215
|
+
session: Session,
|
|
216
|
+
principal: string,
|
|
217
|
+
id: string,
|
|
218
|
+
subscription: PushSubscriptionKeys,
|
|
219
|
+
replace: string | null,
|
|
220
|
+
now: number,
|
|
221
|
+
): Promise<PushRecordOutcome> {
|
|
222
|
+
const cutoff = epochMs(now, 'now') - PUSH_SUBSCRIPTION_LIMITS.tombstoneRetentionMs
|
|
223
|
+
return session.transaction(async (transaction) => {
|
|
224
|
+
const dialect = transaction.dialect
|
|
225
|
+
if (dialect === 'postgres') {
|
|
226
|
+
await runFixedStatement(transaction, SQL_LOCK, [principal])
|
|
227
|
+
}
|
|
228
|
+
await runFixedStatement(transaction, SQL_PRUNE[dialect], [cutoff])
|
|
229
|
+
// Nothing but the prune is written before both checks pass, so no outcome but `recorded` changes a row.
|
|
230
|
+
let cursor: string | null = null
|
|
231
|
+
const replacing = replace !== null && replace !== subscription.endpoint ? replace : null
|
|
232
|
+
if (replacing !== null) {
|
|
233
|
+
const [replaced] = await runFixedStatement(transaction, SQL_REPLACED[dialect], [replacing, principal, cutoff])
|
|
234
|
+
if (replaced === undefined) {
|
|
235
|
+
return 'not_replaceable'
|
|
236
|
+
}
|
|
237
|
+
cursor = nullableText(replaced, 'cursor')
|
|
238
|
+
}
|
|
239
|
+
const written = await runFixedStatement(transaction, SQL_UPSERT[dialect], [
|
|
240
|
+
id,
|
|
241
|
+
principal,
|
|
242
|
+
subscription.endpoint,
|
|
243
|
+
subscription.p256dh,
|
|
244
|
+
subscription.auth,
|
|
245
|
+
subscription.vapidKey,
|
|
246
|
+
// A new subscription reads only what is written after it: its id is a UUIDv7 made now. A replacement
|
|
247
|
+
// carries the old cursor, so a key rotation or a changed subscription neither replays nor skips.
|
|
248
|
+
cursor ?? id,
|
|
249
|
+
now,
|
|
250
|
+
cutoff,
|
|
251
|
+
])
|
|
252
|
+
if (written.length === 0) {
|
|
253
|
+
return 'taken'
|
|
254
|
+
}
|
|
255
|
+
if (replacing !== null) {
|
|
256
|
+
await runFixedStatement(transaction, SQL_DROP_REPLACED[dialect], [replacing, principal])
|
|
257
|
+
}
|
|
258
|
+
await runFixedStatement(transaction, SQL_TRIM[dialect], [principal])
|
|
259
|
+
return 'recorded'
|
|
260
|
+
})
|
|
261
|
+
},
|
|
262
|
+
|
|
263
|
+
async inbox(session: Session, principal: string, endpoint: string): Promise<PushInboxSubscription> {
|
|
264
|
+
const [row] = await runFixedStatement(session, SQL_INBOX[session.dialect], [endpoint])
|
|
265
|
+
if (row === undefined) {
|
|
266
|
+
return null
|
|
267
|
+
}
|
|
268
|
+
if (nullableText(row, 'principal') !== principal) {
|
|
269
|
+
await runFixedStatement(session, SQL_DROP_OTHER[session.dialect], [endpoint, principal])
|
|
270
|
+
return null
|
|
271
|
+
}
|
|
272
|
+
return { cursor: nullableText(row, 'cursor') }
|
|
273
|
+
},
|
|
274
|
+
|
|
275
|
+
async advance(session: Session, principal: string, endpoint: string, cursor: string): Promise<void> {
|
|
276
|
+
await runFixedStatement(session, SQL_ADVANCE[session.dialect], [endpoint, principal, cursor])
|
|
277
|
+
},
|
|
278
|
+
|
|
279
|
+
async remove(session: Session, principal: string, endpoint: string): Promise<boolean> {
|
|
280
|
+
return (await runFixedStatement(session, SQL_REMOVE[session.dialect], [endpoint, principal])).length > 0
|
|
281
|
+
},
|
|
282
|
+
|
|
283
|
+
async retire(session: Session, endpoint: string, now: number): Promise<boolean> {
|
|
284
|
+
return (await runFixedStatement(session, SQL_RETIRE[session.dialect], [endpoint, epochMs(now, 'now')])).length > 0
|
|
285
|
+
},
|
|
286
|
+
})
|
|
287
|
+
}
|
package/src/registry.ts
CHANGED
|
@@ -8,7 +8,9 @@ import type { Session } from './database'
|
|
|
8
8
|
import type { WebhookTables } from './framework-tables'
|
|
9
9
|
import type { JobLeases } from './job-leases'
|
|
10
10
|
import type { JobWakes } from './job-wakes'
|
|
11
|
+
import type { Notifications } from './notifications'
|
|
11
12
|
import type { DataAccess } from './orm'
|
|
13
|
+
import type { PushSubscriptions } from './push-subscriptions'
|
|
12
14
|
import type { RequestReceipts } from './request-receipts'
|
|
13
15
|
import type { DataLayerRuntime, TableContext, TableProbe } from './store'
|
|
14
16
|
import type { StoredFiles } from './stored-files'
|
|
@@ -66,6 +68,10 @@ export interface FrameworkTables {
|
|
|
66
68
|
readonly files: StoredFiles
|
|
67
69
|
/** The answers of keyed mutations, read and written in the invocation's transaction (ADR-0078). */
|
|
68
70
|
readonly receipts: RequestReceipts
|
|
71
|
+
/** The browsers' Web Push subscriptions (ADR-0088), read and written in the invocation's transaction. */
|
|
72
|
+
readonly push: PushSubscriptions
|
|
73
|
+
/** The notifications written for people (ADR-0088 §6), which the inbox answers. */
|
|
74
|
+
readonly notifications: Notifications
|
|
69
75
|
}
|
|
70
76
|
|
|
71
77
|
/** A connection of the layer and its locator. Only its holder can `release` it, which lets the layer be bound again. */
|
package/src/store.ts
CHANGED
|
@@ -115,6 +115,7 @@ import {
|
|
|
115
115
|
valueList,
|
|
116
116
|
valuesNode,
|
|
117
117
|
} from './nodes'
|
|
118
|
+
import { notifications } from './notifications'
|
|
118
119
|
import { dataAccess } from './orm'
|
|
119
120
|
import {
|
|
120
121
|
type Acknowledgement,
|
|
@@ -154,6 +155,7 @@ import {
|
|
|
154
155
|
visibleFor,
|
|
155
156
|
visibleThrough,
|
|
156
157
|
} from './policy'
|
|
158
|
+
import { pushSubscriptions } from './push-subscriptions'
|
|
157
159
|
import { frameworkSideOf, type ProvisionalBinding, register } from './registry'
|
|
158
160
|
import { requestReceipts } from './request-receipts'
|
|
159
161
|
import type { ScopeTerms, ScopeTest, ScopeUse } from './sql'
|
|
@@ -3506,6 +3508,8 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
3506
3508
|
admissions: admissions(() => runtimeOf(connection)),
|
|
3507
3509
|
files: storedFiles(() => runtimeOf(connection)),
|
|
3508
3510
|
receipts: requestReceipts(),
|
|
3511
|
+
push: pushSubscriptions(),
|
|
3512
|
+
notifications: notifications(),
|
|
3509
3513
|
}),
|
|
3510
3514
|
data: dataAccess({
|
|
3511
3515
|
models,
|
package/types/src/framework.d.ts
CHANGED
|
@@ -10,7 +10,9 @@ export { type FileHolding, fileHoldingOf, type FileReference, fileReference, hol
|
|
|
10
10
|
export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables';
|
|
11
11
|
export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases';
|
|
12
12
|
export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes';
|
|
13
|
+
export type { NewNotification, NotificationAbout, Notifications, StoredNotification } from './notifications';
|
|
13
14
|
export type { DataAccess, DataHandles, DataSite } from './orm';
|
|
15
|
+
export type { PushBinding, PushInboxSubscription, PushRecordOutcome, PushSubscriptionKeys, PushSubscriptions } from './push-subscriptions';
|
|
14
16
|
export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry';
|
|
15
17
|
export type { RequestReceipt, RequestReceipts } from './request-receipts';
|
|
16
18
|
export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql';
|
|
@@ -14,6 +14,8 @@ export declare const FILES_TABLE = "fabrika_files";
|
|
|
14
14
|
export declare const FILE_DELETIONS_TABLE = "fabrika_file_deletions";
|
|
15
15
|
export declare const REQUEST_RECEIPTS_TABLE = "fabrika_request_receipts";
|
|
16
16
|
export declare const LIST_CURSOR_KEY_TABLE = "fabrika_list_cursor_key";
|
|
17
|
+
export declare const PUSH_SUBSCRIPTIONS_TABLE = "fabrika_push_subscriptions";
|
|
18
|
+
export declare const NOTIFICATIONS_TABLE = "fabrika_notifications";
|
|
17
19
|
/** The function an application's last adoption migration calls with the name of a file collection it adopted. */
|
|
18
20
|
export declare const FILES_RELEASE_FUNCTION = "fabrika_files_release";
|
|
19
21
|
/**
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type Session } from './database';
|
|
2
|
+
export declare const NOTIFICATION_LIMITS: Readonly<{
|
|
3
|
+
/** How long a notification is kept and answered: seven days. */
|
|
4
|
+
retentionMs: number;
|
|
5
|
+
}>;
|
|
6
|
+
/** What the recipient must hold to read a notification: an action on one object, or the action as a global grant. */
|
|
7
|
+
export type NotificationAbout = {
|
|
8
|
+
readonly action: string;
|
|
9
|
+
readonly dimension: string;
|
|
10
|
+
readonly value: string;
|
|
11
|
+
} | {
|
|
12
|
+
readonly action: string;
|
|
13
|
+
readonly dimension: null;
|
|
14
|
+
readonly value: null;
|
|
15
|
+
};
|
|
16
|
+
export interface StoredNotification {
|
|
17
|
+
/** A UUIDv7: its order is the order written. */
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly title: string;
|
|
20
|
+
readonly body: string;
|
|
21
|
+
readonly path: string;
|
|
22
|
+
readonly about: NotificationAbout;
|
|
23
|
+
}
|
|
24
|
+
export interface NewNotification extends StoredNotification {
|
|
25
|
+
readonly principal: string;
|
|
26
|
+
/** Epoch milliseconds. */
|
|
27
|
+
readonly createdAt: number;
|
|
28
|
+
}
|
|
29
|
+
export interface Notifications {
|
|
30
|
+
/** Writes `notification`, after pruning a batch of rows past the retention. */
|
|
31
|
+
record(session: Session, notification: NewNotification): Promise<void>;
|
|
32
|
+
/** `principal`'s rows written after the notification `after` (all of them for `null`), within the retention at `now`, oldest first, at most `limit`. */
|
|
33
|
+
unseen(session: Session, principal: string, after: string | null, now: number, limit: number): Promise<readonly StoredNotification[]>;
|
|
34
|
+
/** How many of `principal`'s rows within the retention at `now` were written after `after`. */
|
|
35
|
+
countAfter(session: Session, principal: string, after: string | null, now: number): Promise<number>;
|
|
36
|
+
}
|
|
37
|
+
export declare function notifications(): Notifications;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type Session } from './database';
|
|
2
|
+
export declare const PUSH_SUBSCRIPTION_LIMITS: Readonly<{
|
|
3
|
+
/** Live subscriptions one principal holds; the next record drops the oldest. */
|
|
4
|
+
perPrincipal: 10;
|
|
5
|
+
/** How long a tombstone answers a replacement: 30 days. */
|
|
6
|
+
tombstoneRetentionMs: number;
|
|
7
|
+
}>;
|
|
8
|
+
/** A subscription as the page hands it over, with the VAPID public key it was made with. */
|
|
9
|
+
export interface PushSubscriptionKeys {
|
|
10
|
+
readonly endpoint: string;
|
|
11
|
+
/** The browser's P-256 key, base64url. */
|
|
12
|
+
readonly p256dh: string;
|
|
13
|
+
/** The browser's authentication secret, base64url. */
|
|
14
|
+
readonly auth: string;
|
|
15
|
+
/** The VAPID public key the browser subscribed with, base64url. */
|
|
16
|
+
readonly vapidKey: string;
|
|
17
|
+
}
|
|
18
|
+
/** Whose a browser's endpoint is, as the caller may learn it: its own live row, another principal's, or none (a tombstone included). */
|
|
19
|
+
export type PushBinding = 'mine' | 'other' | 'unknown';
|
|
20
|
+
/** The caller's live subscription and the newest notification the inbox answered for it, or `null` when it is not theirs. */
|
|
21
|
+
export type PushInboxSubscription = {
|
|
22
|
+
readonly cursor: string | null;
|
|
23
|
+
} | null;
|
|
24
|
+
/** `recorded`, or why not: the endpoint is bound to another principal, or the replaced endpoint is not the caller's. */
|
|
25
|
+
export type PushRecordOutcome = 'recorded' | 'taken' | 'not_replaceable';
|
|
26
|
+
export interface PushSubscriptions {
|
|
27
|
+
/** Whose `endpoint` is, for `principal`. */
|
|
28
|
+
binding(session: Session, principal: string, endpoint: string): Promise<PushBinding>;
|
|
29
|
+
/**
|
|
30
|
+
* Records `subscription` for `principal` under `id` (a new row's key, a UUIDv7 made now, which is also a new row's
|
|
31
|
+
* cursor, so it reads only notifications written after it; an existing row of the caller keeps its key and cursor),
|
|
32
|
+
* replacing the endpoint `replace` when it names one, at `now`. Prunes a batch of expired tombstones first, and
|
|
33
|
+
* drops the principal's oldest live rows past the bound after. An outcome but `recorded` changes no subscription: the
|
|
34
|
+
* old row is removed only after the new one was written.
|
|
35
|
+
*/
|
|
36
|
+
record(session: Session, principal: string, id: string, subscription: PushSubscriptionKeys, replace: string | null, now: number): Promise<PushRecordOutcome>;
|
|
37
|
+
/**
|
|
38
|
+
* What the inbox reads `endpoint` as for `principal`: the caller's live subscription and its cursor, or none. A live row
|
|
39
|
+
* of another principal is deleted here (§7): the browser it wakes is someone else's now, and stops waking for them.
|
|
40
|
+
*/
|
|
41
|
+
inbox(session: Session, principal: string, endpoint: string): Promise<PushInboxSubscription>;
|
|
42
|
+
/** Moves the cursor of `principal`'s live `endpoint` forward to `cursor`, never back. */
|
|
43
|
+
advance(session: Session, principal: string, endpoint: string, cursor: string): Promise<void>;
|
|
44
|
+
/** Removes `principal`'s own row (or tombstone) of `endpoint`; `false` when it has none. */
|
|
45
|
+
remove(session: Session, principal: string, endpoint: string): Promise<boolean>;
|
|
46
|
+
/** The push service called `endpoint` gone: its live row becomes a tombstone at `now`. `false` when it had none. */
|
|
47
|
+
retire(session: Session, endpoint: string, now: number): Promise<boolean>;
|
|
48
|
+
}
|
|
49
|
+
export declare function pushSubscriptions(): PushSubscriptions;
|
package/types/src/registry.d.ts
CHANGED
|
@@ -4,7 +4,9 @@ import type { Session } from './database';
|
|
|
4
4
|
import type { WebhookTables } from './framework-tables';
|
|
5
5
|
import type { JobLeases } from './job-leases';
|
|
6
6
|
import type { JobWakes } from './job-wakes';
|
|
7
|
+
import type { Notifications } from './notifications';
|
|
7
8
|
import type { DataAccess } from './orm';
|
|
9
|
+
import type { PushSubscriptions } from './push-subscriptions';
|
|
8
10
|
import type { RequestReceipts } from './request-receipts';
|
|
9
11
|
import type { DataLayerRuntime, TableContext, TableProbe } from './store';
|
|
10
12
|
import type { StoredFiles } from './stored-files';
|
|
@@ -46,6 +48,10 @@ export interface FrameworkTables {
|
|
|
46
48
|
readonly files: StoredFiles;
|
|
47
49
|
/** The answers of keyed mutations, read and written in the invocation's transaction (ADR-0078). */
|
|
48
50
|
readonly receipts: RequestReceipts;
|
|
51
|
+
/** The browsers' Web Push subscriptions (ADR-0088), read and written in the invocation's transaction. */
|
|
52
|
+
readonly push: PushSubscriptions;
|
|
53
|
+
/** The notifications written for people (ADR-0088 §6), which the inbox answers. */
|
|
54
|
+
readonly notifications: Notifications;
|
|
49
55
|
}
|
|
50
56
|
/** A connection of the layer and its locator. Only its holder can `release` it, which lets the layer be bound again. */
|
|
51
57
|
export interface ProvisionalBinding {
|