@crombolo/data 0.26.0 → 0.27.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.27.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.27.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')
@@ -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,