@crombolo/data 0.26.0 → 0.28.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/data",
3
- "version": "0.26.0",
3
+ "version": "0.28.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.26.0"
31
+ "@crombolo/core": "0.28.0"
32
32
  }
33
33
  }
package/src/audit.ts CHANGED
@@ -75,8 +75,48 @@ export interface AuditFilter {
75
75
  /** Matched anywhere in the item's name or key, or the user's name. */
76
76
  text?: string
77
77
  ascending?: boolean
78
+ /**
79
+ * A person by e-mail, login or key: their account's entries, or, for a login
80
+ * with no account, the entries that name it (a failed sign-in).
81
+ */
82
+ user?: string
83
+ }
84
+
85
+ /** Where a page of entries starts: newest first below `before`, or oldest first above `after`. */
86
+ export interface AuditCursor {
87
+ before?: number
88
+ after?: number
89
+ limit: number
90
+ }
91
+
92
+ export interface AuditPage {
93
+ items: AuditEntry[]
94
+ /** The cursor for the next page; null when a newest-first read has reached the end. */
95
+ next: number | null
96
+ /** The `after` cursor names an entry retention has already deleted, so some were missed. */
97
+ truncated: boolean
98
+ }
99
+
100
+ /** An entry as every reader gets it: the dashboard, the command line and a remote. */
101
+ export function auditRecord(entry: AuditEntry) {
102
+ return {
103
+ id: entry.id,
104
+ occurredAt: entry.occurredAt.toISOString(),
105
+ category: entry.category,
106
+ action: entry.action,
107
+ source: entry.source,
108
+ user: entry.userKey || entry.userName ? { key: entry.userKey, name: entry.userName } : null,
109
+ item: entry.entityType
110
+ ? { type: entry.entityType, key: entry.entityKey, name: entry.entityName }
111
+ : null,
112
+ ipAddress: entry.ipAddress,
113
+ forwardedFor: entry.forwardedFor,
114
+ detail: entry.detail,
115
+ }
78
116
  }
79
117
 
118
+ export type AuditRecord = ReturnType<typeof auditRecord>
119
+
80
120
  /** What a key names, for an entry to carry once the thing itself has gone. */
81
121
  export interface AuditSubject {
82
122
  entityType: string
@@ -162,14 +202,12 @@ export class AuditLog {
162
202
  }
163
203
  }
164
204
 
165
- async query(
166
- filter: AuditFilter = {},
167
- page: { skip: number; take: number } = { skip: 0, take: 100 },
168
- ): Promise<{ total: number; items: AuditEntry[] }> {
205
+ /** The conditions a filter comes to, or undefined when it can match nothing. */
206
+ async #where(filter: AuditFilter): Promise<{ where: string[]; params: unknown[] } | undefined> {
169
207
  const where: string[] = []
170
208
  const params: unknown[] = []
171
209
  if (filter.userKey !== undefined) {
172
- if (!UUID.test(filter.userKey)) return { total: 0, items: [] }
210
+ if (!UUID.test(filter.userKey)) return undefined
173
211
  where.push('user_key = ?')
174
212
  params.push(normaliseUuid(filter.userKey))
175
213
  }
@@ -201,6 +239,36 @@ export class AuditLog {
201
239
  )
202
240
  params.push(like, like, like)
203
241
  }
242
+ if (filter.user !== undefined) {
243
+ const who = filter.user.trim()
244
+ const accounts = await this.#db.query<{ key: string }>(
245
+ UUID.test(who)
246
+ ? 'SELECT key FROM user_account WHERE key = ?'
247
+ : 'SELECT key FROM user_account WHERE LOWER(email) = LOWER(?) OR LOWER(login) = LOWER(?) OR LOWER(user_name) = LOWER(?)',
248
+ UUID.test(who) ? [normaliseUuid(who)] : [who, who, who],
249
+ )
250
+ const account = accounts[0]
251
+ if (account) {
252
+ where.push('user_key = ?')
253
+ params.push(normaliseUuid(String(account.key)))
254
+ } else if (UUID.test(who)) {
255
+ where.push('user_key = ?')
256
+ params.push(normaliseUuid(who))
257
+ } else {
258
+ where.push('user_key IS NULL AND LOWER(user_name) = LOWER(?)')
259
+ params.push(who)
260
+ }
261
+ }
262
+ return { where, params }
263
+ }
264
+
265
+ async query(
266
+ filter: AuditFilter = {},
267
+ page: { skip: number; take: number } = { skip: 0, take: 100 },
268
+ ): Promise<{ total: number; items: AuditEntry[] }> {
269
+ const conditions = await this.#where(filter)
270
+ if (!conditions) return { total: 0, items: [] }
271
+ const { where, params } = conditions
204
272
  const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''
205
273
  const counted = await this.#db.query<{ total: number }>(
206
274
  `SELECT COUNT(*) AS total FROM audit_entry ${clause}`,
@@ -214,6 +282,57 @@ export class AuditLog {
214
282
  return { total: Number(counted[0]?.total ?? 0), items: rows.map(toEntry) }
215
283
  }
216
284
 
285
+ /**
286
+ * A page by id (story 156): newest first below `before`, or oldest first
287
+ * above `after`, for a reader that resumes where it stopped. Id order is
288
+ * write order, since every entry is stamped as it is written.
289
+ */
290
+ async page(filter: AuditFilter, cursor: AuditCursor): Promise<AuditPage> {
291
+ const ascending = cursor.after !== undefined
292
+ const conditions = await this.#where(filter)
293
+ if (!conditions)
294
+ return { items: [], next: ascending ? (cursor.after ?? null) : null, truncated: false }
295
+ const { where, params } = conditions
296
+ if (cursor.after !== undefined) {
297
+ where.push('id > ?')
298
+ params.push(cursor.after)
299
+ }
300
+ if (cursor.before !== undefined) {
301
+ where.push('id < ?')
302
+ params.push(cursor.before)
303
+ }
304
+ const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''
305
+ const order = ascending ? 'ASC' : 'DESC'
306
+ const rows = await this.#db.query(
307
+ `SELECT * FROM audit_entry ${clause} ORDER BY id ${order} LIMIT ?`,
308
+ [...params, cursor.limit],
309
+ )
310
+ const items = rows.map(toEntry)
311
+ const last = items.at(-1)?.id
312
+ const next = ascending
313
+ ? (last ?? cursor.after ?? null)
314
+ : items.length === cursor.limit && last !== undefined
315
+ ? last
316
+ : null
317
+ return { items, next, truncated: ascending && (await this.#pruned(cursor.after as number)) }
318
+ }
319
+
320
+ /** Whether the entry a cursor names has gone while older ones are kept no longer. */
321
+ async #pruned(after: number): Promise<boolean> {
322
+ if (after <= 0) return false
323
+ const rows = await this.#db.query<{ oldest: number | null; there: number }>(
324
+ 'SELECT MIN(id) AS oldest, SUM(CASE WHEN id = ? THEN 1 ELSE 0 END) AS there FROM audit_entry',
325
+ [after],
326
+ )
327
+ const oldest = rows[0]?.oldest
328
+ return (
329
+ Number(rows[0]?.there ?? 0) === 0 &&
330
+ oldest !== null &&
331
+ oldest !== undefined &&
332
+ Number(oldest) > after
333
+ )
334
+ }
335
+
217
336
  /** Everyone the log names, by the name they had most recently. */
218
337
  async users(): Promise<Array<{ key: string; name: string }>> {
219
338
  const rows = await this.#db.query<{ user_key: string; user_name: string | null }>(
package/src/database.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /** Driver-agnostic database handle. */
2
2
 
3
3
  import { Database as BunSqlite } from 'bun:sqlite'
4
+ import { existsSync } from 'node:fs'
4
5
  import { ambient, ambientFor } from './ambient.ts'
5
6
  import { type Dialect, type DialectName, dialectFor } from './dialect.ts'
6
7
  import { createLockManager, DEFAULT_LOCK_TIMEOUT_MS, type LockManager } from './locks.ts'
@@ -32,6 +33,12 @@ export interface ConnectOptions {
32
33
  url?: string
33
34
  /** How long a write waits for a content lock; defaults to `CROMBOLO_LOCK_TIMEOUT_SECONDS`, else 15s. */
34
35
  lockTimeoutMs?: number
36
+ /**
37
+ * A connection that cannot write (story 156): SQLite opened read-only, an
38
+ * existing file only; on Postgres every statement in a read-only transaction,
39
+ * and no extension created.
40
+ */
41
+ readOnly?: boolean
35
42
  }
36
43
 
37
44
  export function resolveLockTimeoutMs(options: ConnectOptions = {}): number {
@@ -161,17 +168,30 @@ class PostgresDb implements Db {
161
168
  #sql: SqlTag
162
169
  #inTransaction: boolean
163
170
 
164
- constructor(sql: SqlTag, locks?: LockManager, inTransaction = false, lockTimeoutMs?: number) {
171
+ #readOnly: boolean
172
+
173
+ constructor(
174
+ sql: SqlTag,
175
+ locks?: LockManager,
176
+ inTransaction = false,
177
+ lockTimeoutMs?: number,
178
+ readOnly = false,
179
+ ) {
165
180
  this.#sql = sql
166
181
  this.locks = locks ?? createLockManager(this, { timeoutMs: lockTimeoutMs })
167
182
  this.#inTransaction = inTransaction
183
+ this.#readOnly = readOnly
168
184
  }
169
185
 
170
186
  async query<T = Record<string, unknown>>(sql: string, params: unknown[] = []): Promise<T[]> {
187
+ if (this.#readOnly && !this.#inTransaction)
188
+ return this.transaction((tx) => tx.query<T>(sql, params))
171
189
  return (await this.#sql.unsafe(this.dialect.render(sql), params)) as T[]
172
190
  }
173
191
 
174
192
  async exec(sql: string, params: unknown[] = []): Promise<void> {
193
+ if (this.#readOnly && !this.#inTransaction)
194
+ return this.transaction((tx) => tx.exec(sql, params))
175
195
  await this.#sql.unsafe(this.dialect.render(sql), params)
176
196
  }
177
197
 
@@ -183,6 +203,7 @@ class PostgresDb implements Db {
183
203
  async transaction<T>(fn: (tx: Db) => Promise<T>): Promise<T> {
184
204
  if (this.#inTransaction) return fn(this)
185
205
  return this.#sql.begin(async (sql) => {
206
+ if (this.#readOnly) await sql.unsafe('SET TRANSACTION READ ONLY')
186
207
  const tx = new PostgresDb(sql, this.locks, true)
187
208
  const store = { owner: this, tx: tx as unknown }
188
209
  try {
@@ -225,10 +246,24 @@ export async function connect(options: ConnectOptions = {}): Promise<Db> {
225
246
  // A modest pool: many short-lived connections exhaust Postgres' client limit,
226
247
  // and a single process does not need more.
227
248
  const sql = new SQL({ url, max: options.poolSize ?? 5 }) as unknown as SqlTag
228
- const db = new PostgresDb(sql, undefined, false, resolveLockTimeoutMs(options))
229
- await db.exec('CREATE EXTENSION IF NOT EXISTS citext')
249
+ const db = new PostgresDb(
250
+ sql,
251
+ undefined,
252
+ false,
253
+ resolveLockTimeoutMs(options),
254
+ options.readOnly === true,
255
+ )
256
+ if (!options.readOnly) await db.exec('CREATE EXTENSION IF NOT EXISTS citext')
230
257
  return db
231
258
  }
259
+ if (options.readOnly) {
260
+ const file = options.file
261
+ if (!file || file === ':memory:' || !existsSync(file))
262
+ throw new Error(`There is no database at ${file ?? '(none configured)'}.`)
263
+ const sqlite = new BunSqlite(file, { readonly: true })
264
+ sqlite.exec('PRAGMA busy_timeout = 5000')
265
+ return new SqliteDb(sqlite, undefined, false, undefined, resolveLockTimeoutMs(options))
266
+ }
232
267
  const sqlite = new BunSqlite(options.file ?? ':memory:', { create: true })
233
268
  sqlite.exec('PRAGMA journal_mode = WAL')
234
269
  sqlite.exec('PRAGMA foreign_keys = ON')
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-applied.ts'
17
18
  export * from './repositories/content-events.ts'
18
19
  export * from './repositories/content-notifications.ts'
19
20
  export * from './repositories/content-types.ts'
@@ -56,6 +57,7 @@ export * from './schema/bundles-rename.ts'
56
57
  export * from './schema/change-report.ts'
57
58
  export * from './schema/client-id-prefix.ts'
58
59
  export * from './schema/content.ts'
60
+ export * from './schema/content-applied.ts'
59
61
  export * from './schema/content-checkpoint.ts'
60
62
  export * from './schema/content-events.ts'
61
63
  export * from './schema/content-notifications.ts'
@@ -0,0 +1,87 @@
1
+ /**
2
+ * What an import last applied to each node (story 163): the base a later import
3
+ * compares the bundle and the site against. Written inside the import's
4
+ * transaction, with the state it replaced, so a revert can put it back.
5
+ */
6
+ import { normaliseUuid } from '@crombolo/core'
7
+ import type { Db } from '../database.ts'
8
+ import { DbDate } from '../dialect.ts'
9
+
10
+ /** One node as an import left it. Values are keyed `alias|culture|segment`, names by culture. */
11
+ export interface AppliedState {
12
+ values: Record<string, unknown>
13
+ names: Record<string, string>
14
+ parent: string | null
15
+ /** The order the bundle gave it among its siblings. */
16
+ bundleSortOrder: number
17
+ /** The order it had here once the import was done. */
18
+ sortOrder: number
19
+ }
20
+
21
+ export const appliedValueKey = (alias: string, culture: string | null, segment: string | null) =>
22
+ `${alias}|${culture ?? ''}|${segment ?? ''}`
23
+
24
+ const parse = (text: unknown): AppliedState | null =>
25
+ text === null || text === undefined ? null : (JSON.parse(String(text)) as AppliedState)
26
+
27
+ export class ContentAppliedRepository {
28
+ #db: Db
29
+
30
+ constructor(db: Db) {
31
+ this.#db = db
32
+ }
33
+
34
+ async byKeys(keys: readonly string[]): Promise<Map<string, AppliedState>> {
35
+ const out = new Map<string, AppliedState>()
36
+ for (let i = 0; i < keys.length; i += 500) {
37
+ const chunk = keys.slice(i, i + 500).map(normaliseUuid)
38
+ if (chunk.length === 0) continue
39
+ const rows = await this.#db.query<{ node_key: string; state: string }>(
40
+ `SELECT node_key, state FROM content_applied WHERE node_key IN (${chunk.map(() => '?').join(', ')})`,
41
+ chunk,
42
+ )
43
+ for (const row of rows) {
44
+ const state = parse(row.state)
45
+ if (state) out.set(normaliseUuid(String(row.node_key)), state)
46
+ }
47
+ }
48
+ return out
49
+ }
50
+
51
+ /** Records what a run applied to a node, keeping what it replaced. */
52
+ async record(key: string, runId: string, state: AppliedState): Promise<void> {
53
+ const nodeKey = normaliseUuid(key)
54
+ const rows = await this.#db.query<{ run_id: string; state: string }>(
55
+ 'SELECT run_id, state FROM content_applied WHERE node_key = ?',
56
+ [nodeKey],
57
+ )
58
+ const was = rows[0]
59
+ const now = DbDate.toDb(new Date())
60
+ if (!was) {
61
+ await this.#db.exec(
62
+ `INSERT INTO content_applied (node_key, run_id, state, applied_at, previous_run_id, previous_state)
63
+ VALUES (?, ?, ?, ?, NULL, NULL)`,
64
+ [nodeKey, runId, JSON.stringify(state), now],
65
+ )
66
+ return
67
+ }
68
+ await this.#db.exec(
69
+ `UPDATE content_applied SET run_id = ?, state = ?, applied_at = ?, previous_run_id = ?, previous_state = ?
70
+ WHERE node_key = ?`,
71
+ [runId, JSON.stringify(state), now, String(was.run_id), String(was.state), nodeKey],
72
+ )
73
+ }
74
+
75
+ /** Undoes what a run recorded: the state before it, or no record where it made the first. */
76
+ async revert(runId: string): Promise<void> {
77
+ await this.#db.exec('DELETE FROM content_applied WHERE run_id = ? AND previous_state IS NULL', [
78
+ runId,
79
+ ])
80
+ await this.#db.exec(
81
+ `UPDATE content_applied SET run_id = previous_run_id, state = previous_state,
82
+ previous_run_id = NULL, previous_state = NULL
83
+ WHERE run_id = ?`,
84
+ [runId],
85
+ )
86
+ }
87
+ }
@@ -227,6 +227,40 @@ export class ContentTypeRepository {
227
227
  return { total: Number(totals[0]?.n ?? 0) - hidden, items }
228
228
  }
229
229
 
230
+ /**
231
+ * Why an item of type `typeKey` may not sit under `parentKey` (null: the top
232
+ * level), as its parent's type allows children; nothing when it may.
233
+ */
234
+ async placementRefusal(typeKey: string, parentKey: string | null): Promise<string | undefined> {
235
+ const types = await this.#db.query<{ id: number; text: string | null; allow_at_root: unknown }>(
236
+ `SELECT n.id, n.text, ct.allow_at_root FROM node n JOIN content_type ct ON ct.node_id = n.id
237
+ WHERE n.unique_id = ?`,
238
+ [normaliseUuid(typeKey)],
239
+ )
240
+ const type = types[0]
241
+ if (!type) return undefined
242
+ const typeName = String(type.text ?? typeKey)
243
+ if (parentKey === null)
244
+ return fromDbBool(type.allow_at_root)
245
+ ? undefined
246
+ : `"${typeName}" isn't allowed at the top level.`
247
+ const parents = await this.#db.query<{ text: string | null; content_type_id: number }>(
248
+ `SELECT n.text, c.content_type_id FROM node n JOIN content c ON c.node_id = n.id
249
+ WHERE n.unique_id = ?`,
250
+ [normaliseUuid(parentKey)],
251
+ )
252
+ const parent = parents[0]
253
+ if (!parent) return undefined
254
+ const allowed = await this.#db.query<{ n: number }>(
255
+ `SELECT COUNT(*) AS n FROM content_type_allowed_child
256
+ WHERE content_type_id = ? AND allowed_content_type_id = ?`,
257
+ [parent.content_type_id, type.id],
258
+ )
259
+ return Number(allowed[0]?.n ?? 0) > 0
260
+ ? undefined
261
+ : `"${typeName}" isn't allowed under "${parent.text ?? parentKey}".`
262
+ }
263
+
230
264
  async allowedChildren(
231
265
  key: string,
232
266
  skip: number,
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Migration 049 — what an import last applied to each node (story 163).
3
+ *
4
+ * `content_applied` holds, per node, the values, names, order and parent the
5
+ * last import that wrote it left there. A later import compares three ways —
6
+ * the bundle, the site and this — so a change made only in the bundle is
7
+ * taken, one made only here is kept, and only a change made in both is a
8
+ * decision for a person. The state before the run is kept beside it, so a
9
+ * revert puts the record back as well as the content.
10
+ */
11
+ import type { Db } from '../database.ts'
12
+ import type { Migration } from '../migrations.ts'
13
+ import { STATE_DROP_ASSISTANT } from './drop-assistant.ts'
14
+
15
+ export const STATE_CONTENT_APPLIED = '{5d1f8a3c-0049-4e72-b6a9-3c8e1f4d2b49}'
16
+
17
+ export const contentAppliedMigration: Migration = {
18
+ from: STATE_DROP_ASSISTANT,
19
+ to: STATE_CONTENT_APPLIED,
20
+ name: 'AddContentApplied',
21
+ kind: 'expand',
22
+ release: '0.28.0',
23
+ async up(db: Db) {
24
+ const t = db.dialect.types
25
+ await db.exec(
26
+ `CREATE TABLE content_applied (
27
+ node_key ${t.uuid} PRIMARY KEY,
28
+ run_id ${t.varchar(64)} NOT NULL,
29
+ state ${t.text} NOT NULL,
30
+ applied_at ${t.timestamp} NOT NULL,
31
+ previous_run_id ${t.varchar(64)},
32
+ previous_state ${t.text}
33
+ )`,
34
+ )
35
+ },
36
+ }
@@ -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 { contentAppliedMigration } from './content-applied.ts'
26
27
  import { contentCheckpointMigration } from './content-checkpoint.ts'
27
28
  import { contentEditingMigration } from './content-editing.ts'
28
29
  import { contentEventsMigration } from './content-events.ts'
@@ -111,4 +112,5 @@ export const cromboloPlan = new MigrationPlan([
111
112
  contentEventsMigration,
112
113
  contentCheckpointMigration,
113
114
  dropAssistantMigration,
115
+ contentAppliedMigration,
114
116
  ])