@crombolo/data 0.22.0 → 0.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/cluster.ts +14 -0
- package/src/index.ts +2 -0
- package/src/repositories/content-events.ts +202 -0
- package/src/repositories/content-notifications.ts +26 -2
- package/src/repositories/documents.ts +74 -4
- package/src/repositories/webhooks.ts +69 -5
- package/src/schema/content-events.ts +52 -0
- package/src/schema/plan.ts +2 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/data",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.1",
|
|
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.24.1"
|
|
32
32
|
}
|
|
33
33
|
}
|
package/src/cluster.ts
CHANGED
|
@@ -41,6 +41,20 @@ export async function appendCacheInstruction(
|
|
|
41
41
|
await db.exec('SELECT pg_notify(?, ?)', [CACHE_INSTRUCTION_CHANNEL, instruction.kind])
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Deletes instructions older than `before`, keeping the newest, whose id a
|
|
46
|
+
* starting node reads its position from. Every node starts from there, so
|
|
47
|
+
* nothing older is ever read again.
|
|
48
|
+
*/
|
|
49
|
+
export async function pruneCacheInstructions(db: Db, before: Date): Promise<number> {
|
|
50
|
+
const rows = await db.query(
|
|
51
|
+
`DELETE FROM cache_instruction WHERE created_at < ?
|
|
52
|
+
AND id < (SELECT MAX(id) FROM cache_instruction) RETURNING id`,
|
|
53
|
+
[DbDate.toDb(before)],
|
|
54
|
+
)
|
|
55
|
+
return rows.length
|
|
56
|
+
}
|
|
57
|
+
|
|
44
58
|
/** The highest instruction id, so a fresh node ignores history. */
|
|
45
59
|
export async function latestCacheInstructionId(db: Db): Promise<number> {
|
|
46
60
|
const rows = await db.query<{ n: number | null }>('SELECT MAX(id) AS n FROM cache_instruction')
|
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,7 @@ 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-events.ts'
|
|
58
60
|
export * from './schema/content-notifications.ts'
|
|
59
61
|
export * from './schema/content-seed.ts'
|
|
60
62
|
export * from './schema/created-packages.ts'
|
|
@@ -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
|
|
|
@@ -340,6 +355,14 @@ export class DocumentRepository {
|
|
|
340
355
|
return this.#inTreeLock ? fn() : this.#db.locks.withLock(KINDS[this.kind].lock, fn)
|
|
341
356
|
}
|
|
342
357
|
|
|
358
|
+
/**
|
|
359
|
+
* Runs `fn` under the tree lock in one transaction, with a repository bound to
|
|
360
|
+
* it, so several writes commit together or not at all (story 170).
|
|
361
|
+
*/
|
|
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)))
|
|
364
|
+
}
|
|
365
|
+
|
|
343
366
|
#child(tx: Db): DocumentRepository {
|
|
344
367
|
return new DocumentRepository(tx, {
|
|
345
368
|
nodeState: this.#nodeState,
|
|
@@ -867,6 +890,7 @@ export class DocumentRepository {
|
|
|
867
890
|
const state = await assertNodeMayWrite(tx, this.#nodeState)
|
|
868
891
|
const node = await repo.nodes.byKey(input.key)
|
|
869
892
|
if (!node) return undefined
|
|
893
|
+
await repo.#assertRevision(node.id, input.expectedRevision)
|
|
870
894
|
const contentTypeNodeId = await repo.#contentTypeNodeId(node.id)
|
|
871
895
|
if (!contentTypeNodeId) return undefined
|
|
872
896
|
|
|
@@ -901,6 +925,11 @@ export class DocumentRepository {
|
|
|
901
925
|
async publish(
|
|
902
926
|
key: string,
|
|
903
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 } = {},
|
|
904
933
|
): Promise<DocumentAggregate | undefined> {
|
|
905
934
|
return this.#withTree(async () =>
|
|
906
935
|
this.#db.transaction(async (tx) => {
|
|
@@ -908,6 +937,12 @@ export class DocumentRepository {
|
|
|
908
937
|
await assertNodeMayWrite(tx, this.#nodeState)
|
|
909
938
|
const node = await repo.nodes.byKey(key)
|
|
910
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
|
+
}
|
|
911
946
|
// The bin is not a document, so the ancestor check below passes for a
|
|
912
947
|
// node trashed directly; Umbraco refuses it as FailedPublishIsTrashed.
|
|
913
948
|
if (node.trashed) throw new PublishBlockedError('The document is in the recycle bin.')
|
|
@@ -1082,11 +1117,42 @@ export class DocumentRepository {
|
|
|
1082
1117
|
}
|
|
1083
1118
|
|
|
1084
1119
|
/** Rollback appends the target version's values under a new event. History is never rewritten. */
|
|
1085
|
-
async rollback(
|
|
1086
|
-
|
|
1120
|
+
async rollback(
|
|
1121
|
+
versionId: string,
|
|
1122
|
+
options: { expectedRevision?: string } = {},
|
|
1123
|
+
): Promise<DocumentAggregate | undefined> {
|
|
1124
|
+
return this.#withTree(() => this.#rollback(versionId, options.expectedRevision))
|
|
1087
1125
|
}
|
|
1088
1126
|
|
|
1089
|
-
|
|
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> {
|
|
1090
1156
|
return this.#db.transaction(async (tx) => {
|
|
1091
1157
|
const repo = this.#child(tx)
|
|
1092
1158
|
const state = await assertNodeMayWrite(tx, this.#nodeState)
|
|
@@ -1099,6 +1165,7 @@ export class DocumentRepository {
|
|
|
1099
1165
|
if (!target) return undefined
|
|
1100
1166
|
const node = await repo.nodes.byId(Number(target.node_id))
|
|
1101
1167
|
if (!node) return undefined
|
|
1168
|
+
await repo.#assertRevision(node.id, expectedRevision)
|
|
1102
1169
|
const contentTypeNodeId = await repo.#contentTypeNodeId(node.id)
|
|
1103
1170
|
if (!contentTypeNodeId) return undefined
|
|
1104
1171
|
|
|
@@ -1783,7 +1850,9 @@ export class DocumentRepository {
|
|
|
1783
1850
|
ctn.unique_id AS content_type_key, d.published, d.edited,
|
|
1784
1851
|
head.text AS draft_name, head.version_date AS draft_date,
|
|
1785
1852
|
hv.template_id, tn.unique_id AS template_key,
|
|
1786
|
-
pub.version_date AS published_date
|
|
1853
|
+
pub.version_date AS published_date,
|
|
1854
|
+
(SELECT MAX(cvm.id) FROM content_version cvm WHERE cvm.node_id = n.id) AS head_id,
|
|
1855
|
+
(SELECT MAX(pvm.id) FROM property_value pvm WHERE pvm.node_id = n.id) AS last_value_id
|
|
1787
1856
|
FROM node n
|
|
1788
1857
|
JOIN content c ON c.node_id = n.id
|
|
1789
1858
|
JOIN content_type ct ON ct.node_id = c.content_type_id
|
|
@@ -1824,6 +1893,7 @@ export class DocumentRepository {
|
|
|
1824
1893
|
edited: fromDbBool(row.edited),
|
|
1825
1894
|
values,
|
|
1826
1895
|
variants,
|
|
1896
|
+
revision: revisionString(row.head_id as number | null, row.last_value_id as number | null),
|
|
1827
1897
|
}
|
|
1828
1898
|
}
|
|
1829
1899
|
|
|
@@ -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,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
|
@@ -24,6 +24,7 @@ import { changeReportMigration } from './change-report.ts'
|
|
|
24
24
|
import { clientIdPrefixMigration } from './client-id-prefix.ts'
|
|
25
25
|
import { contentMigration } from './content.ts'
|
|
26
26
|
import { contentEditingMigration } from './content-editing.ts'
|
|
27
|
+
import { contentEventsMigration } from './content-events.ts'
|
|
27
28
|
import { contentNotificationsMigration } from './content-notifications.ts'
|
|
28
29
|
import { createdPackagesMigration } from './created-packages.ts'
|
|
29
30
|
import { deliveryMemberTokensMigration } from './delivery-member-tokens.ts'
|
|
@@ -105,4 +106,5 @@ export const cromboloPlan = new MigrationPlan([
|
|
|
105
106
|
contentNotificationsMigration,
|
|
106
107
|
approvalSchedulesMigration,
|
|
107
108
|
mediaPermissionsMigration,
|
|
109
|
+
contentEventsMigration,
|
|
108
110
|
])
|