@crombolo/data 0.24.1 → 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 +98 -18
- package/src/database.ts +61 -1
- package/src/index.ts +1 -0
- package/src/migrations.ts +4 -0
- package/src/repositories/documents.ts +3 -0
- package/src/schema/content-checkpoint.ts +35 -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.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,89 @@ 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],
|
|
38
96
|
)
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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)
|
|
42
104
|
}
|
|
43
105
|
|
|
44
106
|
/**
|
|
@@ -63,7 +125,7 @@ export async function latestCacheInstructionId(db: Db): Promise<number> {
|
|
|
63
125
|
|
|
64
126
|
export async function cacheInstructionsAfter(db: Db, afterId: number): Promise<CacheInstruction[]> {
|
|
65
127
|
const rows = await db.query(
|
|
66
|
-
'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',
|
|
67
129
|
[afterId],
|
|
68
130
|
)
|
|
69
131
|
return rows.map((row) => ({
|
|
@@ -71,6 +133,8 @@ export async function cacheInstructionsAfter(db: Db, afterId: number): Promise<C
|
|
|
71
133
|
kind: String(row.kind) as CacheInstructionKind,
|
|
72
134
|
payload: row.payload ? (JSON.parse(String(row.payload)) as Record<string, unknown>) : {},
|
|
73
135
|
createdBy: (row.created_by as string | null) ?? null,
|
|
136
|
+
checkpoint:
|
|
137
|
+
row.checkpoint === null || row.checkpoint === undefined ? null : Number(row.checkpoint),
|
|
74
138
|
}))
|
|
75
139
|
}
|
|
76
140
|
|
|
@@ -82,6 +146,8 @@ export interface ServerIdentity {
|
|
|
82
146
|
role?: string
|
|
83
147
|
/** The Crombolo release this node runs; `version` is the schema set's. */
|
|
84
148
|
cromboloVersion?: string
|
|
149
|
+
/** The content checkpoint its published cache serves, and when it was built (story 174). */
|
|
150
|
+
served?: { checkpoint: number; at: Date }
|
|
85
151
|
}
|
|
86
152
|
|
|
87
153
|
/** Records this node in `server`; called at boot and on each poll. */
|
|
@@ -93,15 +159,20 @@ export async function touchServer(db: Db, identity: ServerIdentity): Promise<voi
|
|
|
93
159
|
'SELECT node_id FROM server WHERE node_id = ?',
|
|
94
160
|
[identity.nodeId],
|
|
95
161
|
)
|
|
162
|
+
const served = identity.served?.checkpoint ?? null
|
|
163
|
+
const servedAt = identity.served ? DbDate.toDb(identity.served.at) : null
|
|
96
164
|
if (existing[0]) {
|
|
97
165
|
await db.exec(
|
|
98
|
-
|
|
99
|
-
|
|
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],
|
|
100
170
|
)
|
|
101
171
|
} else {
|
|
102
172
|
await db.exec(
|
|
103
|
-
|
|
104
|
-
|
|
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],
|
|
105
176
|
)
|
|
106
177
|
}
|
|
107
178
|
}
|
|
@@ -115,12 +186,16 @@ export interface LiveNode {
|
|
|
115
186
|
/** Null for a row written before node releases were recorded. */
|
|
116
187
|
cromboloVersion: string | null
|
|
117
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
|
|
118
192
|
}
|
|
119
193
|
|
|
120
194
|
/** The nodes that have polled within `seenWithinMs`: the cluster as it stands. */
|
|
121
195
|
export async function liveNodes(db: Db, options: { seenWithinMs: number }): Promise<LiveNode[]> {
|
|
122
196
|
const rows = await db.query(
|
|
123
|
-
|
|
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`,
|
|
124
199
|
[DbDate.toDb(new Date(Date.now() - options.seenWithinMs))],
|
|
125
200
|
)
|
|
126
201
|
return rows.map((row) => ({
|
|
@@ -130,5 +205,10 @@ export async function liveNodes(db: Db, options: { seenWithinMs: number }): Prom
|
|
|
130
205
|
revision: (row.revision as string | null) ?? null,
|
|
131
206
|
cromboloVersion: (row.crombolo_version as string | null) ?? null,
|
|
132
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,
|
|
133
213
|
}))
|
|
134
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
|
@@ -56,6 +56,7 @@ export * from './schema/bundles-rename.ts'
|
|
|
56
56
|
export * from './schema/change-report.ts'
|
|
57
57
|
export * from './schema/client-id-prefix.ts'
|
|
58
58
|
export * from './schema/content.ts'
|
|
59
|
+
export * from './schema/content-checkpoint.ts'
|
|
59
60
|
export * from './schema/content-events.ts'
|
|
60
61
|
export * from './schema/content-notifications.ts'
|
|
61
62
|
export * from './schema/content-seed.ts'
|
package/src/migrations.ts
CHANGED
|
@@ -1291,6 +1291,9 @@ export class DocumentRepository {
|
|
|
1291
1291
|
await tx.exec('DELETE FROM content WHERE node_id = ?', [row])
|
|
1292
1292
|
await tx.exec('DELETE FROM node WHERE id = ?', [row])
|
|
1293
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)
|
|
1294
1297
|
return true
|
|
1295
1298
|
})
|
|
1296
1299
|
}
|
|
@@ -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
|
+
}
|
package/src/schema/plan.ts
CHANGED
|
@@ -23,6 +23,7 @@ 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'
|
|
27
28
|
import { contentEventsMigration } from './content-events.ts'
|
|
28
29
|
import { contentNotificationsMigration } from './content-notifications.ts'
|
|
@@ -107,4 +108,5 @@ export const cromboloPlan = new MigrationPlan([
|
|
|
107
108
|
approvalSchedulesMigration,
|
|
108
109
|
mediaPermissionsMigration,
|
|
109
110
|
contentEventsMigration,
|
|
111
|
+
contentCheckpointMigration,
|
|
110
112
|
])
|