@crombolo/data 0.23.0 → 0.25.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/package.json +2 -2
- package/src/cluster.ts +112 -18
- package/src/database.ts +61 -1
- package/src/index.ts +3 -0
- package/src/migrations.ts +4 -0
- package/src/repositories/content-events.ts +202 -0
- package/src/repositories/content-notifications.ts +26 -2
- package/src/repositories/documents.ts +71 -6
- package/src/repositories/webhooks.ts +69 -5
- package/src/schema/content-checkpoint.ts +35 -0
- package/src/schema/content-events.ts +52 -0
- package/src/schema/plan.ts +4 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/data",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"description": "SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -28,6 +28,6 @@
|
|
|
28
28
|
"access": "public"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@crombolo/core": "0.
|
|
31
|
+
"@crombolo/core": "0.25.0"
|
|
32
32
|
}
|
|
33
33
|
}
|
package/src/cluster.ts
CHANGED
|
@@ -18,27 +18,103 @@ export interface CacheInstruction {
|
|
|
18
18
|
kind: CacheInstructionKind
|
|
19
19
|
payload: Record<string, unknown>
|
|
20
20
|
createdBy: string | null
|
|
21
|
+
/** The content checkpoint it moved to (story 174); null for a views instruction. */
|
|
22
|
+
checkpoint: number | null
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
/** Where Postgres says an instruction was written, so nodes poll now rather than on their timer. */
|
|
24
26
|
export const CACHE_INSTRUCTION_CHANNEL = 'crombolo_cache_instruction'
|
|
25
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Tells the other nodes what changed. A `content` or `schema` instruction moves
|
|
30
|
+
* the content checkpoint (story 174): called on the change's own transaction,
|
|
31
|
+
* the checkpoint row stays locked until that commits, so no change can commit
|
|
32
|
+
* later with a smaller number. Called outside one, it takes its own, after the
|
|
33
|
+
* change it announces — never before it. Answers the checkpoint, or null for a
|
|
34
|
+
* views instruction, which is not published content.
|
|
35
|
+
*/
|
|
26
36
|
export async function appendCacheInstruction(
|
|
27
37
|
db: Db,
|
|
28
38
|
instruction: { kind: CacheInstructionKind; payload?: Record<string, unknown>; by?: string },
|
|
29
|
-
): Promise<
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
39
|
+
): Promise<number | null> {
|
|
40
|
+
return db.transaction(async (tx) => {
|
|
41
|
+
const checkpoint = instruction.kind === 'components' ? null : await advanceCheckpoint(tx)
|
|
42
|
+
await tx.exec(
|
|
43
|
+
'INSERT INTO cache_instruction (kind, payload, created_at, created_by, checkpoint) VALUES (?, ?, ?, ?, ?)',
|
|
44
|
+
[
|
|
45
|
+
instruction.kind,
|
|
46
|
+
JSON.stringify(instruction.payload ?? {}),
|
|
47
|
+
DbDate.toDb(new Date()),
|
|
48
|
+
instruction.by ?? null,
|
|
49
|
+
checkpoint,
|
|
50
|
+
],
|
|
51
|
+
)
|
|
52
|
+
// Delivered at commit, so a write that rolls back wakes nobody.
|
|
53
|
+
if (tx.dialect.name === 'postgres')
|
|
54
|
+
await tx.exec('SELECT pg_notify(?, ?)', [CACHE_INSTRUCTION_CHANNEL, instruction.kind])
|
|
55
|
+
return checkpoint
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Moves the checkpoint on by one, holding its row until `tx` commits. An upsert,
|
|
61
|
+
* so a row lost to a truncate is started again rather than silently not counted.
|
|
62
|
+
*/
|
|
63
|
+
async function advanceCheckpoint(tx: Db): Promise<number> {
|
|
64
|
+
const rows = await tx.query<{ n: unknown }>(
|
|
65
|
+
`INSERT INTO content_checkpoint (id, n) VALUES (1, 1)
|
|
66
|
+
ON CONFLICT (id) DO UPDATE SET n = content_checkpoint.n + 1 RETURNING n`,
|
|
67
|
+
)
|
|
68
|
+
return Number(rows[0]?.n ?? 0)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Waits until `db` has committed at least `checkpoint`, looking every
|
|
73
|
+
* `everyMs`, and answers whether it got there before `timeoutMs` ran out. For a
|
|
74
|
+
* reader that may lag — a replica (story 121) — to catch up to the change it
|
|
75
|
+
* was told of, or for its caller to fall back to the primary.
|
|
76
|
+
*/
|
|
77
|
+
export async function waitForCheckpoint(
|
|
78
|
+
db: Db,
|
|
79
|
+
checkpoint: number,
|
|
80
|
+
timeoutMs: number,
|
|
81
|
+
everyMs = 100,
|
|
82
|
+
): Promise<boolean> {
|
|
83
|
+
const deadline = Date.now() + timeoutMs
|
|
84
|
+
for (;;) {
|
|
85
|
+
if ((await latestCheckpoint(db)) >= checkpoint) return true
|
|
86
|
+
if (Date.now() >= deadline) return false
|
|
87
|
+
await Bun.sleep(Math.min(everyMs, Math.max(0, deadline - Date.now())))
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** When the first change after `checkpoint` was recorded: how long a node serving it has been behind. */
|
|
92
|
+
export async function changedSince(db: Db, checkpoint: number): Promise<Date | undefined> {
|
|
93
|
+
const rows = await db.query<{ at: unknown }>(
|
|
94
|
+
'SELECT MIN(created_at) AS at FROM cache_instruction WHERE checkpoint > ?',
|
|
95
|
+
[checkpoint],
|
|
96
|
+
)
|
|
97
|
+
return DbDate.fromDb(rows[0]?.at) ?? undefined
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The latest committed checkpoint: every change numbered at or below it has committed. */
|
|
101
|
+
export async function latestCheckpoint(db: Db): Promise<number> {
|
|
102
|
+
const rows = await db.query<{ n: unknown }>('SELECT n FROM content_checkpoint WHERE id = 1')
|
|
103
|
+
return Number(rows[0]?.n ?? 0)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Deletes instructions older than `before`, keeping the newest, whose id a
|
|
108
|
+
* starting node reads its position from. Every node starts from there, so
|
|
109
|
+
* nothing older is ever read again.
|
|
110
|
+
*/
|
|
111
|
+
export async function pruneCacheInstructions(db: Db, before: Date): Promise<number> {
|
|
112
|
+
const rows = await db.query(
|
|
113
|
+
`DELETE FROM cache_instruction WHERE created_at < ?
|
|
114
|
+
AND id < (SELECT MAX(id) FROM cache_instruction) RETURNING id`,
|
|
115
|
+
[DbDate.toDb(before)],
|
|
38
116
|
)
|
|
39
|
-
|
|
40
|
-
if (db.dialect.name === 'postgres')
|
|
41
|
-
await db.exec('SELECT pg_notify(?, ?)', [CACHE_INSTRUCTION_CHANNEL, instruction.kind])
|
|
117
|
+
return rows.length
|
|
42
118
|
}
|
|
43
119
|
|
|
44
120
|
/** The highest instruction id, so a fresh node ignores history. */
|
|
@@ -49,7 +125,7 @@ export async function latestCacheInstructionId(db: Db): Promise<number> {
|
|
|
49
125
|
|
|
50
126
|
export async function cacheInstructionsAfter(db: Db, afterId: number): Promise<CacheInstruction[]> {
|
|
51
127
|
const rows = await db.query(
|
|
52
|
-
'SELECT id, kind, payload, created_by FROM cache_instruction WHERE id > ? ORDER BY id',
|
|
128
|
+
'SELECT id, kind, payload, created_by, checkpoint FROM cache_instruction WHERE id > ? ORDER BY id',
|
|
53
129
|
[afterId],
|
|
54
130
|
)
|
|
55
131
|
return rows.map((row) => ({
|
|
@@ -57,6 +133,8 @@ export async function cacheInstructionsAfter(db: Db, afterId: number): Promise<C
|
|
|
57
133
|
kind: String(row.kind) as CacheInstructionKind,
|
|
58
134
|
payload: row.payload ? (JSON.parse(String(row.payload)) as Record<string, unknown>) : {},
|
|
59
135
|
createdBy: (row.created_by as string | null) ?? null,
|
|
136
|
+
checkpoint:
|
|
137
|
+
row.checkpoint === null || row.checkpoint === undefined ? null : Number(row.checkpoint),
|
|
60
138
|
}))
|
|
61
139
|
}
|
|
62
140
|
|
|
@@ -68,6 +146,8 @@ export interface ServerIdentity {
|
|
|
68
146
|
role?: string
|
|
69
147
|
/** The Crombolo release this node runs; `version` is the schema set's. */
|
|
70
148
|
cromboloVersion?: string
|
|
149
|
+
/** The content checkpoint its published cache serves, and when it was built (story 174). */
|
|
150
|
+
served?: { checkpoint: number; at: Date }
|
|
71
151
|
}
|
|
72
152
|
|
|
73
153
|
/** Records this node in `server`; called at boot and on each poll. */
|
|
@@ -79,15 +159,20 @@ export async function touchServer(db: Db, identity: ServerIdentity): Promise<voi
|
|
|
79
159
|
'SELECT node_id FROM server WHERE node_id = ?',
|
|
80
160
|
[identity.nodeId],
|
|
81
161
|
)
|
|
162
|
+
const served = identity.served?.checkpoint ?? null
|
|
163
|
+
const servedAt = identity.served ? DbDate.toDb(identity.served.at) : null
|
|
82
164
|
if (existing[0]) {
|
|
83
165
|
await db.exec(
|
|
84
|
-
|
|
85
|
-
|
|
166
|
+
`UPDATE server SET version = ?, revision = ?, role = ?, crombolo_version = ?, last_seen = ?,
|
|
167
|
+
served_checkpoint = COALESCE(?, served_checkpoint), served_at = COALESCE(?, served_at)
|
|
168
|
+
WHERE node_id = ?`,
|
|
169
|
+
[identity.version, identity.revision, role, crombolo, now, served, servedAt, identity.nodeId],
|
|
86
170
|
)
|
|
87
171
|
} else {
|
|
88
172
|
await db.exec(
|
|
89
|
-
|
|
90
|
-
|
|
173
|
+
`INSERT INTO server (node_id, version, revision, role, crombolo_version, last_seen,
|
|
174
|
+
served_checkpoint, served_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
175
|
+
[identity.nodeId, identity.version, identity.revision, role, crombolo, now, served, servedAt],
|
|
91
176
|
)
|
|
92
177
|
}
|
|
93
178
|
}
|
|
@@ -101,12 +186,16 @@ export interface LiveNode {
|
|
|
101
186
|
/** Null for a row written before node releases were recorded. */
|
|
102
187
|
cromboloVersion: string | null
|
|
103
188
|
lastSeen: Date
|
|
189
|
+
/** The checkpoint it last reported serving, and when that snapshot was built; null before. */
|
|
190
|
+
servedCheckpoint: number | null
|
|
191
|
+
servedAt: Date | null
|
|
104
192
|
}
|
|
105
193
|
|
|
106
194
|
/** The nodes that have polled within `seenWithinMs`: the cluster as it stands. */
|
|
107
195
|
export async function liveNodes(db: Db, options: { seenWithinMs: number }): Promise<LiveNode[]> {
|
|
108
196
|
const rows = await db.query(
|
|
109
|
-
|
|
197
|
+
`SELECT node_id, role, version, revision, crombolo_version, last_seen, served_checkpoint, served_at
|
|
198
|
+
FROM server WHERE last_seen >= ? ORDER BY node_id`,
|
|
110
199
|
[DbDate.toDb(new Date(Date.now() - options.seenWithinMs))],
|
|
111
200
|
)
|
|
112
201
|
return rows.map((row) => ({
|
|
@@ -116,5 +205,10 @@ export async function liveNodes(db: Db, options: { seenWithinMs: number }): Prom
|
|
|
116
205
|
revision: (row.revision as string | null) ?? null,
|
|
117
206
|
cromboloVersion: (row.crombolo_version as string | null) ?? null,
|
|
118
207
|
lastSeen: DbDate.fromDb(row.last_seen) as Date,
|
|
208
|
+
servedCheckpoint:
|
|
209
|
+
row.served_checkpoint === null || row.served_checkpoint === undefined
|
|
210
|
+
? null
|
|
211
|
+
: Number(row.served_checkpoint),
|
|
212
|
+
servedAt: DbDate.fromDb(row.served_at) ?? null,
|
|
119
213
|
}))
|
|
120
214
|
}
|
package/src/database.ts
CHANGED
|
@@ -11,6 +11,12 @@ export interface Db {
|
|
|
11
11
|
query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>
|
|
12
12
|
exec(sql: string, params?: unknown[]): Promise<void>
|
|
13
13
|
transaction<T>(fn: (tx: Db) => Promise<T>): Promise<T>
|
|
14
|
+
/**
|
|
15
|
+
* Runs `fn` against one consistent, read-only view of committed data (story
|
|
16
|
+
* 174): it sees every transaction that committed before it began and nothing
|
|
17
|
+
* after, and never another chain's uncommitted writes. It holds no write lock.
|
|
18
|
+
*/
|
|
19
|
+
readSnapshot<T>(fn: (reader: Db) => Promise<T>): Promise<T>
|
|
14
20
|
close(): Promise<void>
|
|
15
21
|
/** Postgres only: calls `onNotify` for each `NOTIFY` on `channel`; resolves to the way to stop. */
|
|
16
22
|
listen?(channel: string, onNotify: (payload: string) => void): Promise<() => Promise<void>>
|
|
@@ -46,6 +52,9 @@ class SqliteDb implements Db {
|
|
|
46
52
|
#db: BunSqlite
|
|
47
53
|
#inTransaction: boolean
|
|
48
54
|
#gate: { tail: Promise<void> }
|
|
55
|
+
/** The database file, for a read-only connection beside this one; absent in memory. */
|
|
56
|
+
#file: string | undefined
|
|
57
|
+
#reader: { db: BunSqlite; gate: { tail: Promise<void> } } | undefined
|
|
49
58
|
|
|
50
59
|
constructor(
|
|
51
60
|
db: BunSqlite,
|
|
@@ -53,11 +62,13 @@ class SqliteDb implements Db {
|
|
|
53
62
|
inTransaction = false,
|
|
54
63
|
gate: { tail: Promise<void> } = { tail: Promise.resolve() },
|
|
55
64
|
lockTimeoutMs?: number,
|
|
65
|
+
file?: string,
|
|
56
66
|
) {
|
|
57
67
|
this.#db = db
|
|
58
68
|
this.locks = locks ?? createLockManager(this, { timeoutMs: lockTimeoutMs })
|
|
59
69
|
this.#inTransaction = inTransaction
|
|
60
70
|
this.#gate = gate
|
|
71
|
+
this.#file = file
|
|
61
72
|
}
|
|
62
73
|
|
|
63
74
|
async query<T = Record<string, unknown>>(sql: string, params: unknown[] = []): Promise<T[]> {
|
|
@@ -96,7 +107,40 @@ class SqliteDb implements Db {
|
|
|
96
107
|
}
|
|
97
108
|
}
|
|
98
109
|
|
|
110
|
+
/**
|
|
111
|
+
* On a file, a read-only connection of its own in one read transaction: WAL
|
|
112
|
+
* gives it a snapshot as of its first read, writers carry on, and nothing this
|
|
113
|
+
* connection has not committed is visible. In memory there is no second
|
|
114
|
+
* connection to open, so it reads inside a transaction on this one, which at
|
|
115
|
+
* least keeps other chains' writes out until it ends.
|
|
116
|
+
*/
|
|
117
|
+
async readSnapshot<T>(fn: (reader: Db) => Promise<T>): Promise<T> {
|
|
118
|
+
if (this.#inTransaction || !this.#file || this.#file === ':memory:') return this.transaction(fn)
|
|
119
|
+
this.#reader ??= {
|
|
120
|
+
db: new BunSqlite(this.#file, { readonly: true }),
|
|
121
|
+
gate: { tail: Promise.resolve() },
|
|
122
|
+
}
|
|
123
|
+
const reader = this.#reader
|
|
124
|
+
const previous = reader.gate.tail
|
|
125
|
+
let release!: () => void
|
|
126
|
+
reader.gate.tail = new Promise<void>((resolve) => {
|
|
127
|
+
release = resolve
|
|
128
|
+
})
|
|
129
|
+
await previous
|
|
130
|
+
try {
|
|
131
|
+
reader.db.exec('BEGIN')
|
|
132
|
+
try {
|
|
133
|
+
return await fn(new SqliteDb(reader.db, this.locks, true, reader.gate))
|
|
134
|
+
} finally {
|
|
135
|
+
reader.db.exec('COMMIT')
|
|
136
|
+
}
|
|
137
|
+
} finally {
|
|
138
|
+
release()
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
99
142
|
async close(): Promise<void> {
|
|
143
|
+
this.#reader?.db.close()
|
|
100
144
|
this.#db.close()
|
|
101
145
|
}
|
|
102
146
|
}
|
|
@@ -149,6 +193,15 @@ class PostgresDb implements Db {
|
|
|
149
193
|
})
|
|
150
194
|
}
|
|
151
195
|
|
|
196
|
+
/** A `REPEATABLE READ, READ ONLY` transaction: one snapshot for every statement in it. */
|
|
197
|
+
async readSnapshot<T>(fn: (reader: Db) => Promise<T>): Promise<T> {
|
|
198
|
+
if (this.#inTransaction) return fn(this)
|
|
199
|
+
return this.#sql.begin(async (sql) => {
|
|
200
|
+
await sql.unsafe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY')
|
|
201
|
+
return fn(new PostgresDb(sql, this.locks, true))
|
|
202
|
+
})
|
|
203
|
+
}
|
|
204
|
+
|
|
152
205
|
async close(): Promise<void> {
|
|
153
206
|
await this.#sql.close()
|
|
154
207
|
}
|
|
@@ -180,5 +233,12 @@ export async function connect(options: ConnectOptions = {}): Promise<Db> {
|
|
|
180
233
|
sqlite.exec('PRAGMA journal_mode = WAL')
|
|
181
234
|
sqlite.exec('PRAGMA foreign_keys = ON')
|
|
182
235
|
sqlite.exec('PRAGMA busy_timeout = 5000')
|
|
183
|
-
return new SqliteDb(
|
|
236
|
+
return new SqliteDb(
|
|
237
|
+
sqlite,
|
|
238
|
+
undefined,
|
|
239
|
+
false,
|
|
240
|
+
undefined,
|
|
241
|
+
resolveLockTimeoutMs(options),
|
|
242
|
+
options.file,
|
|
243
|
+
)
|
|
184
244
|
}
|
package/src/index.ts
CHANGED
|
@@ -14,6 +14,7 @@ export * from './pending.ts'
|
|
|
14
14
|
export * from './relations.ts'
|
|
15
15
|
export * from './repositories/approvals.ts'
|
|
16
16
|
export * from './repositories/bundles.ts'
|
|
17
|
+
export * from './repositories/content-events.ts'
|
|
17
18
|
export * from './repositories/content-notifications.ts'
|
|
18
19
|
export * from './repositories/content-types.ts'
|
|
19
20
|
export * from './repositories/data-types.ts'
|
|
@@ -55,6 +56,8 @@ export * from './schema/bundles-rename.ts'
|
|
|
55
56
|
export * from './schema/change-report.ts'
|
|
56
57
|
export * from './schema/client-id-prefix.ts'
|
|
57
58
|
export * from './schema/content.ts'
|
|
59
|
+
export * from './schema/content-checkpoint.ts'
|
|
60
|
+
export * from './schema/content-events.ts'
|
|
58
61
|
export * from './schema/content-notifications.ts'
|
|
59
62
|
export * from './schema/content-seed.ts'
|
|
60
63
|
export * from './schema/created-packages.ts'
|
package/src/migrations.ts
CHANGED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The content event outbox (story 171): what a change announces, recorded with
|
|
3
|
+
* the change and dispatched after it. Claimed one event at a time, so two nodes
|
|
4
|
+
* never dispatch the same one at once; a claim left behind by a node that died
|
|
5
|
+
* is released after a while.
|
|
6
|
+
*/
|
|
7
|
+
import type { Db } from '../database.ts'
|
|
8
|
+
import { DbDate } from '../dialect.ts'
|
|
9
|
+
|
|
10
|
+
export type ContentEventState = 'pending' | 'running' | 'dispatched' | 'failed'
|
|
11
|
+
|
|
12
|
+
export interface NewContentEvent {
|
|
13
|
+
kind: string
|
|
14
|
+
entityType: string
|
|
15
|
+
entityKey: string | null
|
|
16
|
+
/** What was true when the change committed; versioned by its own `v`. */
|
|
17
|
+
facts: Record<string, unknown>
|
|
18
|
+
actor: Record<string, unknown>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ContentEvent extends NewContentEvent {
|
|
22
|
+
id: string
|
|
23
|
+
occurredAt: Date
|
|
24
|
+
state: ContentEventState
|
|
25
|
+
attempts: number
|
|
26
|
+
lastError: string | null
|
|
27
|
+
runAfter: Date
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** How many items sit in each state, and when the oldest waiting one was queued. */
|
|
31
|
+
export interface QueueCounts {
|
|
32
|
+
pending: number
|
|
33
|
+
running: number
|
|
34
|
+
failed: number
|
|
35
|
+
oldestPending: Date | null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const COLUMNS =
|
|
39
|
+
'id, kind, entity_type, entity_key, facts, actor, occurred_at, state, attempts, last_error, run_after'
|
|
40
|
+
|
|
41
|
+
const json = (value: unknown): Record<string, unknown> => {
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(String(value ?? '{}')) as unknown
|
|
44
|
+
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {}
|
|
45
|
+
} catch {
|
|
46
|
+
return {}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function hydrate(row: Record<string, unknown>): ContentEvent {
|
|
51
|
+
return {
|
|
52
|
+
id: String(row.id),
|
|
53
|
+
kind: String(row.kind),
|
|
54
|
+
entityType: String(row.entity_type),
|
|
55
|
+
entityKey:
|
|
56
|
+
row.entity_key === null || row.entity_key === undefined ? null : String(row.entity_key),
|
|
57
|
+
facts: json(row.facts),
|
|
58
|
+
actor: json(row.actor),
|
|
59
|
+
occurredAt: DbDate.fromDb(row.occurred_at) ?? new Date(0),
|
|
60
|
+
state: String(row.state) as ContentEventState,
|
|
61
|
+
attempts: Number(row.attempts),
|
|
62
|
+
lastError: (row.last_error as string | null) ?? null,
|
|
63
|
+
runAfter: DbDate.fromDb(row.run_after) ?? new Date(0),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Counts by state for a queue table, and its oldest pending item's date. */
|
|
68
|
+
export async function queueCounts(
|
|
69
|
+
db: Db,
|
|
70
|
+
table: 'content_event' | 'webhook_delivery' | 'content_notification',
|
|
71
|
+
): Promise<QueueCounts> {
|
|
72
|
+
const rows = await db.query<{ state: string; n: number; oldest: unknown }>(
|
|
73
|
+
`SELECT state, COUNT(*) AS n, MIN(create_date) AS oldest FROM ${table} GROUP BY state`,
|
|
74
|
+
)
|
|
75
|
+
const of = (state: string) => rows.find((row) => row.state === state)
|
|
76
|
+
return {
|
|
77
|
+
pending: Number(of('pending')?.n ?? 0),
|
|
78
|
+
running: Number(of('running')?.n ?? 0),
|
|
79
|
+
failed: Number(of('failed')?.n ?? 0),
|
|
80
|
+
oldestPending: DbDate.fromDb(of('pending')?.oldest) ?? null,
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export class ContentEventRepository {
|
|
85
|
+
#db: Db
|
|
86
|
+
|
|
87
|
+
constructor(db: Db) {
|
|
88
|
+
this.#db = db
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Records an event; called inside the change's transaction, so it commits with it. */
|
|
92
|
+
async record(event: NewContentEvent, now = new Date()): Promise<string> {
|
|
93
|
+
const id = crypto.randomUUID()
|
|
94
|
+
const at = DbDate.toDb(now)
|
|
95
|
+
await this.#db.exec(
|
|
96
|
+
`INSERT INTO content_event (${COLUMNS}, create_date, update_date)
|
|
97
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 0, NULL, ?, ?, ?)`,
|
|
98
|
+
[
|
|
99
|
+
id,
|
|
100
|
+
event.kind,
|
|
101
|
+
event.entityType,
|
|
102
|
+
event.entityKey,
|
|
103
|
+
JSON.stringify(event.facts),
|
|
104
|
+
JSON.stringify(event.actor),
|
|
105
|
+
at,
|
|
106
|
+
at,
|
|
107
|
+
at,
|
|
108
|
+
at,
|
|
109
|
+
],
|
|
110
|
+
)
|
|
111
|
+
return id
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async due(now = new Date(), limit = 50): Promise<string[]> {
|
|
115
|
+
const rows = await this.#db.query<{ id: string }>(
|
|
116
|
+
`SELECT id FROM content_event WHERE state = 'pending' AND run_after <= ?
|
|
117
|
+
ORDER BY occurred_at, create_date LIMIT ?`,
|
|
118
|
+
[DbDate.toDb(now), limit],
|
|
119
|
+
)
|
|
120
|
+
return rows.map((row) => String(row.id))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Takes an event, or finds another node already has. */
|
|
124
|
+
async claim(id: string): Promise<ContentEvent | undefined> {
|
|
125
|
+
const rows = await this.#db.query(
|
|
126
|
+
`UPDATE content_event SET state = 'running', attempts = attempts + 1, update_date = ?
|
|
127
|
+
WHERE id = ? AND state = 'pending' RETURNING ${COLUMNS}`,
|
|
128
|
+
[DbDate.toDb(new Date()), id],
|
|
129
|
+
)
|
|
130
|
+
return rows[0] ? hydrate(rows[0]) : undefined
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async dispatched(id: string): Promise<void> {
|
|
134
|
+
await this.#db.exec(
|
|
135
|
+
`UPDATE content_event SET state = 'dispatched', last_error = NULL, update_date = ? WHERE id = ?`,
|
|
136
|
+
[DbDate.toDb(new Date()), id],
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** `retryAt` puts it back in the queue; without one it has failed until someone retries it. */
|
|
141
|
+
async fail(id: string, error: string, retryAt?: Date): Promise<void> {
|
|
142
|
+
await this.#db.exec(
|
|
143
|
+
'UPDATE content_event SET state = ?, last_error = ?, run_after = ?, update_date = ? WHERE id = ?',
|
|
144
|
+
[
|
|
145
|
+
retryAt ? 'pending' : 'failed',
|
|
146
|
+
error.slice(0, 2000),
|
|
147
|
+
DbDate.toDb(retryAt ?? new Date()),
|
|
148
|
+
DbDate.toDb(new Date()),
|
|
149
|
+
id,
|
|
150
|
+
],
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Claims older than `olderThan` belong to a node that died: they go back in the queue. */
|
|
155
|
+
async releaseStale(olderThan: Date): Promise<number> {
|
|
156
|
+
const rows = await this.#db.query(
|
|
157
|
+
`UPDATE content_event SET state = 'pending', update_date = ?
|
|
158
|
+
WHERE state = 'running' AND update_date < ? RETURNING id`,
|
|
159
|
+
[DbDate.toDb(new Date()), DbDate.toDb(olderThan)],
|
|
160
|
+
)
|
|
161
|
+
return rows.length
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Puts failed events back, all or one; answers how many. */
|
|
165
|
+
async retry(id?: string): Promise<number> {
|
|
166
|
+
const now = DbDate.toDb(new Date())
|
|
167
|
+
const rows = await this.#db.query(
|
|
168
|
+
`UPDATE content_event SET state = 'pending', attempts = 0, run_after = ?, update_date = ?
|
|
169
|
+
WHERE state = 'failed'${id ? ' AND id = ?' : ''} RETURNING id`,
|
|
170
|
+
id ? [now, now, id] : [now, now],
|
|
171
|
+
)
|
|
172
|
+
return rows.length
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async prune(before: Date): Promise<number> {
|
|
176
|
+
const rows = await this.#db.query(
|
|
177
|
+
`DELETE FROM content_event WHERE state = 'dispatched' AND update_date < ? RETURNING id`,
|
|
178
|
+
[DbDate.toDb(before)],
|
|
179
|
+
)
|
|
180
|
+
return rows.length
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async byId(id: string): Promise<ContentEvent | undefined> {
|
|
184
|
+
const rows = await this.#db.query(`SELECT ${COLUMNS} FROM content_event WHERE id = ?`, [id])
|
|
185
|
+
return rows[0] ? hydrate(rows[0]) : undefined
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async failed(limit = 100): Promise<ContentEvent[]> {
|
|
189
|
+
const rows = await this.#db.query(
|
|
190
|
+
`SELECT ${COLUMNS} FROM content_event WHERE state = 'failed' ORDER BY occurred_at DESC LIMIT ?`,
|
|
191
|
+
[limit],
|
|
192
|
+
)
|
|
193
|
+
return rows.map(hydrate)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async all(): Promise<ContentEvent[]> {
|
|
197
|
+
const rows = await this.#db.query(
|
|
198
|
+
`SELECT ${COLUMNS} FROM content_event ORDER BY occurred_at, create_date`,
|
|
199
|
+
)
|
|
200
|
+
return rows.map(hydrate)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -35,6 +35,8 @@ export interface NewContentNotification {
|
|
|
35
35
|
detail: string | null
|
|
36
36
|
occurredAt: Date
|
|
37
37
|
runAfter: Date
|
|
38
|
+
/** The content event it was dispatched from (story 171): one row per event, person and action. */
|
|
39
|
+
eventId?: string
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
const COLUMNS = `id, recipient_user_key, action_id, node_key, node_name, actor_user_key, actor_name,
|
|
@@ -74,8 +76,9 @@ export class ContentNotificationRepository {
|
|
|
74
76
|
await tx.exec(
|
|
75
77
|
`INSERT INTO content_notification (id, recipient_user_key, action_id, node_key, node_name,
|
|
76
78
|
actor_user_key, actor_name, detail, occurred_at, state, attempts, last_error, run_after,
|
|
77
|
-
create_date, update_date)
|
|
78
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, NULL, ?, ?, ?)
|
|
79
|
+
create_date, update_date, event_id)
|
|
80
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, NULL, ?, ?, ?, ?)
|
|
81
|
+
ON CONFLICT DO NOTHING`,
|
|
79
82
|
[
|
|
80
83
|
crypto.randomUUID(),
|
|
81
84
|
row.recipientUserKey,
|
|
@@ -89,6 +92,7 @@ export class ContentNotificationRepository {
|
|
|
89
92
|
DbDate.toDb(row.runAfter),
|
|
90
93
|
now,
|
|
91
94
|
now,
|
|
95
|
+
row.eventId ?? null,
|
|
92
96
|
],
|
|
93
97
|
)
|
|
94
98
|
})
|
|
@@ -162,6 +166,26 @@ export class ContentNotificationRepository {
|
|
|
162
166
|
return rows.length
|
|
163
167
|
}
|
|
164
168
|
|
|
169
|
+
/** Puts failed notifications back, all or one; answers how many. */
|
|
170
|
+
async retry(id?: string): Promise<number> {
|
|
171
|
+
const now = DbDate.toDb(new Date())
|
|
172
|
+
const rows = await this.#db.query(
|
|
173
|
+
`UPDATE content_notification SET state = 'pending', attempts = 0, run_after = ?, update_date = ?
|
|
174
|
+
WHERE state = 'failed'${id ? ' AND id = ?' : ''} RETURNING id`,
|
|
175
|
+
id ? [now, now, id] : [now, now],
|
|
176
|
+
)
|
|
177
|
+
return rows.length
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async failed(limit = 100): Promise<ContentNotification[]> {
|
|
181
|
+
const rows = await this.#db.query(
|
|
182
|
+
`SELECT ${COLUMNS} FROM content_notification WHERE state = 'failed'
|
|
183
|
+
ORDER BY occurred_at DESC LIMIT ?`,
|
|
184
|
+
[limit],
|
|
185
|
+
)
|
|
186
|
+
return rows.map(hydrate)
|
|
187
|
+
}
|
|
188
|
+
|
|
165
189
|
async prune(before: Date): Promise<number> {
|
|
166
190
|
const rows = await this.#db.query(
|
|
167
191
|
`DELETE FROM content_notification WHERE state IN ('done', 'skipped') AND update_date < ? RETURNING id`,
|
|
@@ -110,6 +110,8 @@ export interface SaveDocumentInput {
|
|
|
110
110
|
values: DocumentValue[]
|
|
111
111
|
variants: Array<{ culture: string | null; segment: string | null; name: string }>
|
|
112
112
|
userId?: number
|
|
113
|
+
/** The revision the values were based on; a different one refuses the save (story 172). */
|
|
114
|
+
expectedRevision?: string
|
|
113
115
|
}
|
|
114
116
|
|
|
115
117
|
/** A published document plus the values of its published version. */
|
|
@@ -221,6 +223,19 @@ export class PublishBlockedError extends Error {}
|
|
|
221
223
|
/** The parent named for a new item is gone, or in the recycle bin. */
|
|
222
224
|
export class InvalidParentError extends Error {}
|
|
223
225
|
|
|
226
|
+
/** The draft changed after the revision a write was based on (story 172). */
|
|
227
|
+
export class StaleRevisionError extends Error {
|
|
228
|
+
constructor(
|
|
229
|
+
readonly expected: string,
|
|
230
|
+
readonly actual: string,
|
|
231
|
+
) {
|
|
232
|
+
super('The page changed after this copy of it was read.')
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const revisionString = (head: unknown, value: unknown): string =>
|
|
237
|
+
`${Number(head ?? 0)}.${Number(value ?? 0)}`
|
|
238
|
+
|
|
224
239
|
const isEmpty = (value: unknown) =>
|
|
225
240
|
value === null || value === undefined || (typeof value === 'string' && value.trim() === '')
|
|
226
241
|
|
|
@@ -344,8 +359,8 @@ export class DocumentRepository {
|
|
|
344
359
|
* Runs `fn` under the tree lock in one transaction, with a repository bound to
|
|
345
360
|
* it, so several writes commit together or not at all (story 170).
|
|
346
361
|
*/
|
|
347
|
-
async atomically<T>(fn: (repo: DocumentRepository) => Promise<T>): Promise<T> {
|
|
348
|
-
return this.#withTree(() => this.#db.transaction((tx) => fn(this.#child(tx))))
|
|
362
|
+
async atomically<T>(fn: (repo: DocumentRepository, tx: Db) => Promise<T>): Promise<T> {
|
|
363
|
+
return this.#withTree(() => this.#db.transaction((tx) => fn(this.#child(tx), tx)))
|
|
349
364
|
}
|
|
350
365
|
|
|
351
366
|
#child(tx: Db): DocumentRepository {
|
|
@@ -875,6 +890,7 @@ export class DocumentRepository {
|
|
|
875
890
|
const state = await assertNodeMayWrite(tx, this.#nodeState)
|
|
876
891
|
const node = await repo.nodes.byKey(input.key)
|
|
877
892
|
if (!node) return undefined
|
|
893
|
+
await repo.#assertRevision(node.id, input.expectedRevision)
|
|
878
894
|
const contentTypeNodeId = await repo.#contentTypeNodeId(node.id)
|
|
879
895
|
if (!contentTypeNodeId) return undefined
|
|
880
896
|
|
|
@@ -909,6 +925,11 @@ export class DocumentRepository {
|
|
|
909
925
|
async publish(
|
|
910
926
|
key: string,
|
|
911
927
|
cultures: readonly string[] | null,
|
|
928
|
+
/**
|
|
929
|
+
* `expectedHead` is the event an approval was given for: a publish of
|
|
930
|
+
* anything later is refused, while an upgrade's value rewrite is not.
|
|
931
|
+
*/
|
|
932
|
+
options: { expectedRevision?: string; expectedHead?: number } = {},
|
|
912
933
|
): Promise<DocumentAggregate | undefined> {
|
|
913
934
|
return this.#withTree(async () =>
|
|
914
935
|
this.#db.transaction(async (tx) => {
|
|
@@ -916,6 +937,12 @@ export class DocumentRepository {
|
|
|
916
937
|
await assertNodeMayWrite(tx, this.#nodeState)
|
|
917
938
|
const node = await repo.nodes.byKey(key)
|
|
918
939
|
if (!node) return undefined
|
|
940
|
+
await repo.#assertRevision(node.id, options.expectedRevision)
|
|
941
|
+
if (options.expectedHead !== undefined) {
|
|
942
|
+
const head = (await repo.#headEvent(node.id))?.id
|
|
943
|
+
if (head !== options.expectedHead)
|
|
944
|
+
throw new StaleRevisionError(String(options.expectedHead), String(head))
|
|
945
|
+
}
|
|
919
946
|
// The bin is not a document, so the ancestor check below passes for a
|
|
920
947
|
// node trashed directly; Umbraco refuses it as FailedPublishIsTrashed.
|
|
921
948
|
if (node.trashed) throw new PublishBlockedError('The document is in the recycle bin.')
|
|
@@ -1090,11 +1117,42 @@ export class DocumentRepository {
|
|
|
1090
1117
|
}
|
|
1091
1118
|
|
|
1092
1119
|
/** Rollback appends the target version's values under a new event. History is never rewritten. */
|
|
1093
|
-
async rollback(
|
|
1094
|
-
|
|
1120
|
+
async rollback(
|
|
1121
|
+
versionId: string,
|
|
1122
|
+
options: { expectedRevision?: string } = {},
|
|
1123
|
+
): Promise<DocumentAggregate | undefined> {
|
|
1124
|
+
return this.#withTree(() => this.#rollback(versionId, options.expectedRevision))
|
|
1095
1125
|
}
|
|
1096
1126
|
|
|
1097
|
-
|
|
1127
|
+
/**
|
|
1128
|
+
* Which state of the draft a node is in (story 172): its latest event and its
|
|
1129
|
+
* latest value row. The second moves when an upgrade rewrites values under the
|
|
1130
|
+
* same event, which an editor's copy must not silently undo.
|
|
1131
|
+
*/
|
|
1132
|
+
async revisionOf(key: string): Promise<string | undefined> {
|
|
1133
|
+
const node = await this.#nodes.byKey(key)
|
|
1134
|
+
return node ? this.#revision(node.id) : undefined
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
async #revision(nodeId: number): Promise<string> {
|
|
1138
|
+
const rows = await this.#db.query<{ head: number | null; value: number | null }>(
|
|
1139
|
+
`SELECT (SELECT MAX(id) FROM content_version WHERE node_id = ?) AS head,
|
|
1140
|
+
(SELECT MAX(id) FROM property_value WHERE node_id = ?) AS value`,
|
|
1141
|
+
[nodeId, nodeId],
|
|
1142
|
+
)
|
|
1143
|
+
return revisionString(rows[0]?.head, rows[0]?.value)
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
async #assertRevision(nodeId: number, expected: string | undefined): Promise<void> {
|
|
1147
|
+
if (expected === undefined) return
|
|
1148
|
+
const actual = await this.#revision(nodeId)
|
|
1149
|
+
if (actual !== expected) throw new StaleRevisionError(expected, actual)
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
async #rollback(
|
|
1153
|
+
versionId: string,
|
|
1154
|
+
expectedRevision?: string,
|
|
1155
|
+
): Promise<DocumentAggregate | undefined> {
|
|
1098
1156
|
return this.#db.transaction(async (tx) => {
|
|
1099
1157
|
const repo = this.#child(tx)
|
|
1100
1158
|
const state = await assertNodeMayWrite(tx, this.#nodeState)
|
|
@@ -1107,6 +1165,7 @@ export class DocumentRepository {
|
|
|
1107
1165
|
if (!target) return undefined
|
|
1108
1166
|
const node = await repo.nodes.byId(Number(target.node_id))
|
|
1109
1167
|
if (!node) return undefined
|
|
1168
|
+
await repo.#assertRevision(node.id, expectedRevision)
|
|
1110
1169
|
const contentTypeNodeId = await repo.#contentTypeNodeId(node.id)
|
|
1111
1170
|
if (!contentTypeNodeId) return undefined
|
|
1112
1171
|
|
|
@@ -1232,6 +1291,9 @@ export class DocumentRepository {
|
|
|
1232
1291
|
await tx.exec('DELETE FROM content WHERE node_id = ?', [row])
|
|
1233
1292
|
await tx.exec('DELETE FROM node WHERE id = ?', [row])
|
|
1234
1293
|
}
|
|
1294
|
+
// A page deleted from the bin was never served, but an item deleted
|
|
1295
|
+
// directly may have been: every node is told (story 174).
|
|
1296
|
+
await this.#child(tx).#instructContent(node.key)
|
|
1235
1297
|
return true
|
|
1236
1298
|
})
|
|
1237
1299
|
}
|
|
@@ -1791,7 +1853,9 @@ export class DocumentRepository {
|
|
|
1791
1853
|
ctn.unique_id AS content_type_key, d.published, d.edited,
|
|
1792
1854
|
head.text AS draft_name, head.version_date AS draft_date,
|
|
1793
1855
|
hv.template_id, tn.unique_id AS template_key,
|
|
1794
|
-
pub.version_date AS published_date
|
|
1856
|
+
pub.version_date AS published_date,
|
|
1857
|
+
(SELECT MAX(cvm.id) FROM content_version cvm WHERE cvm.node_id = n.id) AS head_id,
|
|
1858
|
+
(SELECT MAX(pvm.id) FROM property_value pvm WHERE pvm.node_id = n.id) AS last_value_id
|
|
1795
1859
|
FROM node n
|
|
1796
1860
|
JOIN content c ON c.node_id = n.id
|
|
1797
1861
|
JOIN content_type ct ON ct.node_id = c.content_type_id
|
|
@@ -1832,6 +1896,7 @@ export class DocumentRepository {
|
|
|
1832
1896
|
edited: fromDbBool(row.edited),
|
|
1833
1897
|
values,
|
|
1834
1898
|
variants,
|
|
1899
|
+
revision: revisionString(row.head_id as number | null, row.last_value_id as number | null),
|
|
1835
1900
|
}
|
|
1836
1901
|
}
|
|
1837
1902
|
|
|
@@ -104,6 +104,8 @@ export interface WebhookDelivery {
|
|
|
104
104
|
lastError: string | null
|
|
105
105
|
runAfter: Date
|
|
106
106
|
createDate: Date
|
|
107
|
+
/** The content event it was dispatched from (story 171); null for one raised before. */
|
|
108
|
+
eventId: string | null
|
|
107
109
|
}
|
|
108
110
|
|
|
109
111
|
export interface WebhookLogEntry {
|
|
@@ -124,7 +126,7 @@ export interface WebhookLogEntry {
|
|
|
124
126
|
}
|
|
125
127
|
|
|
126
128
|
const DELIVERY_COLUMNS =
|
|
127
|
-
'id, subscriber, event_alias, payload, state, attempts, last_error, run_after, create_date'
|
|
129
|
+
'id, subscriber, event_alias, payload, state, attempts, last_error, run_after, create_date, event_id'
|
|
128
130
|
|
|
129
131
|
const hydrateDelivery = (row: Record<string, unknown>): WebhookDelivery => {
|
|
130
132
|
let payload: unknown = null
|
|
@@ -143,6 +145,7 @@ const hydrateDelivery = (row: Record<string, unknown>): WebhookDelivery => {
|
|
|
143
145
|
lastError: (row.last_error as string | null) ?? null,
|
|
144
146
|
runAfter: DbDate.fromDb(row.run_after) ?? new Date(0),
|
|
145
147
|
createDate: DbDate.fromDb(row.create_date) ?? new Date(0),
|
|
148
|
+
eventId: row.event_id === null || row.event_id === undefined ? null : String(row.event_id),
|
|
146
149
|
}
|
|
147
150
|
}
|
|
148
151
|
|
|
@@ -155,16 +158,26 @@ export class WebhookDeliveryRepository {
|
|
|
155
158
|
this.#db = db
|
|
156
159
|
}
|
|
157
160
|
|
|
161
|
+
/**
|
|
162
|
+
* Queues deliveries. One per event and subscriber: a dispatcher repeating a
|
|
163
|
+
* step after a crash queues nothing twice. Answers the ids actually queued.
|
|
164
|
+
*/
|
|
158
165
|
async enqueue(
|
|
159
|
-
deliveries: ReadonlyArray<{
|
|
166
|
+
deliveries: ReadonlyArray<{
|
|
167
|
+
subscriber: string
|
|
168
|
+
eventAlias: string
|
|
169
|
+
payload: unknown
|
|
170
|
+
eventId?: string
|
|
171
|
+
}>,
|
|
160
172
|
now = new Date(),
|
|
161
173
|
): Promise<string[]> {
|
|
162
174
|
const ids: string[] = []
|
|
163
175
|
for (const delivery of deliveries) {
|
|
164
176
|
const id = randomUUID()
|
|
165
|
-
await this.#db.
|
|
177
|
+
const rows = await this.#db.query(
|
|
166
178
|
`INSERT INTO webhook_delivery (${DELIVERY_COLUMNS}, update_date)
|
|
167
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
179
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
180
|
+
ON CONFLICT DO NOTHING RETURNING id`,
|
|
168
181
|
[
|
|
169
182
|
id,
|
|
170
183
|
delivery.subscriber,
|
|
@@ -175,14 +188,65 @@ export class WebhookDeliveryRepository {
|
|
|
175
188
|
null,
|
|
176
189
|
DbDate.toDb(now),
|
|
177
190
|
DbDate.toDb(now),
|
|
191
|
+
delivery.eventId ?? null,
|
|
178
192
|
DbDate.toDb(now),
|
|
179
193
|
],
|
|
180
194
|
)
|
|
181
|
-
ids.push(id)
|
|
195
|
+
if (rows.length > 0) ids.push(id)
|
|
182
196
|
}
|
|
183
197
|
return ids
|
|
184
198
|
}
|
|
185
199
|
|
|
200
|
+
/** Claims older than `olderThan` belong to a node that died: they go back in the queue. */
|
|
201
|
+
async releaseStale(olderThan: Date): Promise<number> {
|
|
202
|
+
const rows = await this.#db.query(
|
|
203
|
+
`UPDATE webhook_delivery SET state = 'pending', update_date = ?
|
|
204
|
+
WHERE state = 'running' AND update_date < ? RETURNING id`,
|
|
205
|
+
[DbDate.toDb(new Date()), DbDate.toDb(olderThan)],
|
|
206
|
+
)
|
|
207
|
+
return rows.length
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Puts failed deliveries back, all or one; answers how many. */
|
|
211
|
+
async retry(id?: string): Promise<number> {
|
|
212
|
+
const now = DbDate.toDb(new Date())
|
|
213
|
+
const rows = await this.#db.query(
|
|
214
|
+
`UPDATE webhook_delivery SET state = 'pending', attempts = 0, run_after = ?, update_date = ?
|
|
215
|
+
WHERE state = 'failed'${id ? ' AND id = ?' : ''} RETURNING id`,
|
|
216
|
+
id ? [now, now, id] : [now, now],
|
|
217
|
+
)
|
|
218
|
+
return rows.length
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Delivered rows and log entries older than `before` go; failed ones stay until retried. */
|
|
222
|
+
async prune(before: Date): Promise<number> {
|
|
223
|
+
const done = await this.#db.query(
|
|
224
|
+
`DELETE FROM webhook_delivery WHERE state = 'done' AND update_date < ? RETURNING id`,
|
|
225
|
+
[DbDate.toDb(before)],
|
|
226
|
+
)
|
|
227
|
+
const logged = await this.#db.query(
|
|
228
|
+
'DELETE FROM webhook_log WHERE log_date < ? RETURNING key',
|
|
229
|
+
[DbDate.toDb(before)],
|
|
230
|
+
)
|
|
231
|
+
return done.length + logged.length
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async failed(limit = 100): Promise<WebhookDelivery[]> {
|
|
235
|
+
const rows = await this.#db.query(
|
|
236
|
+
`SELECT ${DELIVERY_COLUMNS} FROM webhook_delivery WHERE state = 'failed'
|
|
237
|
+
ORDER BY update_date DESC LIMIT ?`,
|
|
238
|
+
[limit],
|
|
239
|
+
)
|
|
240
|
+
return rows.map(hydrateDelivery)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async all(): Promise<WebhookDelivery[]> {
|
|
244
|
+
const rows = await this.#db.query(
|
|
245
|
+
`SELECT ${DELIVERY_COLUMNS} FROM webhook_delivery ORDER BY create_date`,
|
|
246
|
+
)
|
|
247
|
+
return rows.map(hydrateDelivery)
|
|
248
|
+
}
|
|
249
|
+
|
|
186
250
|
async due(now = new Date(), limit = 25): Promise<WebhookDelivery[]> {
|
|
187
251
|
const rows = await this.#db.query(
|
|
188
252
|
`SELECT ${DELIVERY_COLUMNS} FROM webhook_delivery WHERE state = ? AND run_after <= ?
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration 047 — the content checkpoint (story 174).
|
|
3
|
+
*
|
|
4
|
+
* One row, `content_checkpoint`, counts the committed changes to anything the
|
|
5
|
+
* published cache reads. Every such change increments it inside its own
|
|
6
|
+
* transaction, which holds the row until it commits, so the count's order is
|
|
7
|
+
* the commit order on both dialects. Cache instructions carry the number, and
|
|
8
|
+
* each node records the one it serves.
|
|
9
|
+
*/
|
|
10
|
+
import type { Db } from '../database.ts'
|
|
11
|
+
import type { Migration } from '../migrations.ts'
|
|
12
|
+
import { STATE_CONTENT_EVENTS } from './content-events.ts'
|
|
13
|
+
|
|
14
|
+
export const STATE_CONTENT_CHECKPOINT = '{6b2e8f14-0047-4d93-a5c1-9e3f7b2d4c47}'
|
|
15
|
+
|
|
16
|
+
export const contentCheckpointMigration: Migration = {
|
|
17
|
+
from: STATE_CONTENT_EVENTS,
|
|
18
|
+
to: STATE_CONTENT_CHECKPOINT,
|
|
19
|
+
name: 'AddContentCheckpoint',
|
|
20
|
+
kind: 'expand',
|
|
21
|
+
release: '0.25.0',
|
|
22
|
+
async up(db: Db) {
|
|
23
|
+
const t = db.dialect.types
|
|
24
|
+
await db.exec(
|
|
25
|
+
`CREATE TABLE content_checkpoint (
|
|
26
|
+
id ${t.integer} PRIMARY KEY,
|
|
27
|
+
n ${t.bigint} NOT NULL
|
|
28
|
+
)`,
|
|
29
|
+
)
|
|
30
|
+
await db.exec('INSERT INTO content_checkpoint (id, n) VALUES (1, 0)')
|
|
31
|
+
await db.exec(`ALTER TABLE cache_instruction ADD COLUMN checkpoint ${t.bigint}`)
|
|
32
|
+
await db.exec(`ALTER TABLE server ADD COLUMN served_checkpoint ${t.bigint}`)
|
|
33
|
+
await db.exec(`ALTER TABLE server ADD COLUMN served_at ${t.timestamp}`)
|
|
34
|
+
},
|
|
35
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration 046 — the content event outbox (story 171).
|
|
3
|
+
*
|
|
4
|
+
* `content_event` holds what a change announces, written in the change's own
|
|
5
|
+
* transaction: the facts as they were when it committed, and who made it. A
|
|
6
|
+
* dispatcher turns each into webhook deliveries and content notifications. The
|
|
7
|
+
* unique keys on those let it repeat a step after a crash without queueing
|
|
8
|
+
* anything twice.
|
|
9
|
+
*/
|
|
10
|
+
import type { Db } from '../database.ts'
|
|
11
|
+
import type { Migration } from '../migrations.ts'
|
|
12
|
+
import { STATE_MEDIA_PERMISSIONS } from './media-permissions.ts'
|
|
13
|
+
|
|
14
|
+
export const STATE_CONTENT_EVENTS = '{3e9b7d25-0046-4a1c-8f63-2d5c9e1b7a46}'
|
|
15
|
+
|
|
16
|
+
export const contentEventsMigration: Migration = {
|
|
17
|
+
from: STATE_MEDIA_PERMISSIONS,
|
|
18
|
+
to: STATE_CONTENT_EVENTS,
|
|
19
|
+
name: 'AddContentEvents',
|
|
20
|
+
kind: 'expand',
|
|
21
|
+
release: '0.24.1',
|
|
22
|
+
async up(db: Db) {
|
|
23
|
+
const t = db.dialect.types
|
|
24
|
+
await db.exec(
|
|
25
|
+
`CREATE TABLE content_event (
|
|
26
|
+
id ${t.varchar(64)} PRIMARY KEY,
|
|
27
|
+
kind ${t.varchar(32)} NOT NULL,
|
|
28
|
+
entity_type ${t.varchar(32)} NOT NULL,
|
|
29
|
+
entity_key ${t.uuid},
|
|
30
|
+
facts ${t.text} NOT NULL,
|
|
31
|
+
actor ${t.text} NOT NULL,
|
|
32
|
+
occurred_at ${t.timestamp} NOT NULL,
|
|
33
|
+
state ${t.varchar(16)} NOT NULL,
|
|
34
|
+
attempts ${t.integer} NOT NULL,
|
|
35
|
+
last_error ${t.text},
|
|
36
|
+
run_after ${t.timestamp} NOT NULL,
|
|
37
|
+
create_date ${t.timestamp} NOT NULL,
|
|
38
|
+
update_date ${t.timestamp} NOT NULL
|
|
39
|
+
)`,
|
|
40
|
+
)
|
|
41
|
+
await db.exec('CREATE INDEX ix_content_event_due ON content_event (state, run_after)')
|
|
42
|
+
await db.exec(`ALTER TABLE webhook_delivery ADD COLUMN event_id ${t.varchar(64)}`)
|
|
43
|
+
await db.exec(
|
|
44
|
+
'CREATE UNIQUE INDEX ux_webhook_delivery_event ON webhook_delivery (event_id, subscriber)',
|
|
45
|
+
)
|
|
46
|
+
await db.exec(`ALTER TABLE content_notification ADD COLUMN event_id ${t.varchar(64)}`)
|
|
47
|
+
await db.exec(
|
|
48
|
+
`CREATE UNIQUE INDEX ux_content_notification_event
|
|
49
|
+
ON content_notification (event_id, recipient_user_key, action_id)`,
|
|
50
|
+
)
|
|
51
|
+
},
|
|
52
|
+
}
|
package/src/schema/plan.ts
CHANGED
|
@@ -23,7 +23,9 @@ import { bundlesRenameMigration } from './bundles-rename.ts'
|
|
|
23
23
|
import { changeReportMigration } from './change-report.ts'
|
|
24
24
|
import { clientIdPrefixMigration } from './client-id-prefix.ts'
|
|
25
25
|
import { contentMigration } from './content.ts'
|
|
26
|
+
import { contentCheckpointMigration } from './content-checkpoint.ts'
|
|
26
27
|
import { contentEditingMigration } from './content-editing.ts'
|
|
28
|
+
import { contentEventsMigration } from './content-events.ts'
|
|
27
29
|
import { contentNotificationsMigration } from './content-notifications.ts'
|
|
28
30
|
import { createdPackagesMigration } from './created-packages.ts'
|
|
29
31
|
import { deliveryMemberTokensMigration } from './delivery-member-tokens.ts'
|
|
@@ -105,4 +107,6 @@ export const cromboloPlan = new MigrationPlan([
|
|
|
105
107
|
contentNotificationsMigration,
|
|
106
108
|
approvalSchedulesMigration,
|
|
107
109
|
mediaPermissionsMigration,
|
|
110
|
+
contentEventsMigration,
|
|
111
|
+
contentCheckpointMigration,
|
|
108
112
|
])
|