@yaks/journal 0.0.0-stage → 0.2.36

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.
Files changed (84) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +522 -2
  3. package/_dist/backed.d.ts +9 -0
  4. package/_dist/backed.d.ts.map +1 -0
  5. package/_dist/batch.d.ts +45 -0
  6. package/_dist/batch.d.ts.map +1 -0
  7. package/_dist/feed.d.ts +108 -0
  8. package/_dist/feed.d.ts.map +1 -0
  9. package/_dist/graph.d.ts +104 -0
  10. package/_dist/graph.d.ts.map +1 -0
  11. package/_dist/kept.d.ts +63 -0
  12. package/_dist/kept.d.ts.map +1 -0
  13. package/_dist/log.d.ts +142 -0
  14. package/_dist/log.d.ts.map +1 -0
  15. package/_dist/merge.d.ts +41 -0
  16. package/_dist/merge.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +101 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/service.d.ts +68 -0
  20. package/_dist/service.d.ts.map +1 -0
  21. package/_dist/tools.d.ts +5 -0
  22. package/_dist/tools.d.ts.map +1 -0
  23. package/_dist/undo.d.ts +48 -0
  24. package/_dist/undo.d.ts.map +1 -0
  25. package/_dist/value.d.ts +6 -0
  26. package/_dist/value.d.ts.map +1 -0
  27. package/_dist/views.d.ts +25 -0
  28. package/_dist/views.d.ts.map +1 -0
  29. package/_dist/vocab.d.ts +7 -0
  30. package/_dist/vocab.d.ts.map +1 -0
  31. package/backed.js +225 -0
  32. package/backed.js.map +1 -0
  33. package/backed.ts +274 -0
  34. package/batch.js +12 -0
  35. package/batch.js.map +1 -0
  36. package/batch.ts +84 -0
  37. package/deno.json +1 -0
  38. package/feed.js +295 -0
  39. package/feed.js.map +1 -0
  40. package/feed.ts +368 -0
  41. package/graph.js +224 -0
  42. package/graph.js.map +1 -0
  43. package/graph.ts +329 -0
  44. package/held.js +25 -0
  45. package/held.js.map +1 -0
  46. package/held.ts +24 -0
  47. package/kept.js +61 -0
  48. package/kept.js.map +1 -0
  49. package/kept.ts +100 -0
  50. package/log.js +1161 -0
  51. package/log.js.map +1 -0
  52. package/log.ts +1299 -0
  53. package/merge.js +158 -0
  54. package/merge.js.map +1 -0
  55. package/merge.ts +185 -0
  56. package/mod.js +101 -0
  57. package/mod.js.map +1 -0
  58. package/mod.ts +102 -0
  59. package/names.js +206 -0
  60. package/names.js.map +1 -0
  61. package/names.ts +230 -0
  62. package/package.json +52 -4
  63. package/page.js +160 -0
  64. package/page.js.map +1 -0
  65. package/page.ts +233 -0
  66. package/service.js +118 -0
  67. package/service.js.map +1 -0
  68. package/service.ts +148 -0
  69. package/tools.js +110 -0
  70. package/tools.js.map +1 -0
  71. package/tools.ts +113 -0
  72. package/undo.js +187 -0
  73. package/undo.js.map +1 -0
  74. package/undo.ts +190 -0
  75. package/value.js +26 -0
  76. package/value.js.map +1 -0
  77. package/value.ts +35 -0
  78. package/views.js +85 -0
  79. package/views.js.map +1 -0
  80. package/views.ts +91 -0
  81. package/vocab.js +20 -0
  82. package/vocab.js.map +1 -0
  83. package/vocab.json +308 -0
  84. package/vocab.ts +22 -0
package/log.ts ADDED
@@ -0,0 +1,1299 @@
1
+ // The journal's tables: three of them, append-only, holding no entities of
2
+ // their own. A transaction here is one call to `graph.apply()`, whose bundles
3
+ // all commit or none do.
4
+ //
5
+ // journal_tx one row per committed transaction — its id is the total
6
+ // order and the cursor
7
+ // journal_change one ordered operation per component patched or removed
8
+ // journal_field one ordered after-image per property an operation wrote
9
+ //
10
+ // After-images only: what a write left, never both sides of it. The before-
11
+ // value a history read needs is rebuilt from the entity's own rows in the log
12
+ // (`before()`), a read bounded to one entity and never a table scan — which is
13
+ // what keeps the log about a third of the size of one that stores both sides. A
14
+ // property whose text the graph already keeps under a content address is
15
+ // recorded by its address ({@link Cas}), so logging every revision of every
16
+ // document costs a row rather than the document.
17
+ //
18
+ // The log is derived from what was applied, inside the caller's own
19
+ // transaction. A refused transaction leaves no trace; a committed one has a row
20
+ // unless everything it wrote is something the vocabulary keeps out of the
21
+ // journal (`journal: false`). The one thing read before the write is what an
22
+ // entity being deleted holds, so the deletion of one that held only such
23
+ // components is left out too (`journal` below).
24
+ //
25
+ // The caller supplies one function: `rows(statement)`, a @yaks/sql node in
26
+ // and its rows out. No platform API, no driver object, and no transaction of
27
+ // its own — the caller owns the transaction.
28
+
29
+ import type {
30
+ Actor,
31
+ Bundle,
32
+ Comp,
33
+ Eid,
34
+ HookContext,
35
+ Plugin,
36
+ Tx,
37
+ } from 'jsr:@yaks/graph@0.2.36'
38
+ import { comps, dead, TOMBSTONE } from '@yaks/graph/bundle'
39
+ import { writers } from '@yaks/graph/provenance'
40
+ import { minted } from '@yaks/graph/identity'
41
+ import { Refused } from '@yaks/graph/errors'
42
+ import { after } from '@yaks/fp'
43
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
44
+ import {
45
+ among,
46
+ and,
47
+ array,
48
+ as,
49
+ call,
50
+ cell,
51
+ col,
52
+ type CreateTable,
53
+ type Derived,
54
+ desc,
55
+ type Drop,
56
+ eq,
57
+ exists,
58
+ type Expr,
59
+ fn,
60
+ gt,
61
+ type Join,
62
+ join,
63
+ left,
64
+ lit,
65
+ lt,
66
+ not,
67
+ notNull,
68
+ or,
69
+ over,
70
+ type Param,
71
+ parts,
72
+ type Row,
73
+ type Select,
74
+ select,
75
+ type Stmt,
76
+ sub,
77
+ table,
78
+ val,
79
+ } from '@yaks/sql'
80
+ import type { Batch, Delta, Entry, Patch } from './batch.ts'
81
+ import { dec, enc } from './value.js'
82
+ import { heldRows, heldSql } from './held.js'
83
+ import { names, words, wordTable } from './names.js'
84
+
85
+ /** A statement, run for its rows: the whole of what the caller has to supply.
86
+ * A write goes through it too — `insert … returning id` returns a row. */
87
+ export type Rows = (s: Stmt) => Row[]
88
+
89
+ /**
90
+ * A property whose text the graph already stores once, under a content address.
91
+ * The journal then records that address and points at the graph's bytes instead
92
+ * of repeating them — the difference between a log that keeps every revision of
93
+ * every document and one that keeps a row per revision.
94
+ */
95
+ export type Cas = {
96
+ /** is this property content-addressed? */
97
+ at: (comp: string, prop: string) => boolean
98
+ /** store the text and return the id the journal records */
99
+ put: (text: string) => number
100
+ /** the table holding the content, and its key and value columns */
101
+ table: string
102
+ key: string
103
+ value: string
104
+ }
105
+
106
+ /**
107
+ * One recorded value a {@link Log.seek} found: where it sits in the log,
108
+ * the value as stored, and the content address when the property is
109
+ * content-addressed.
110
+ */
111
+ export type Hit = {
112
+ /** the row's own id — what a redaction names to rewrite it */
113
+ field: number
114
+ /** the entity the value was written about */
115
+ target: Eid | null
116
+ /** the component and property it belongs to */
117
+ comp: string
118
+ prop: string
119
+ /** the transaction it was written by, and when that committed */
120
+ seq: number
121
+ at: string
122
+ /** the value as recorded, decoded */
123
+ value: unknown
124
+ /** the content it refs, when the property is content-addressed */
125
+ content: Eid | null
126
+ }
127
+
128
+ /** How the log is bound to a store. */
129
+ export type LogOpts = {
130
+ /** the statement runner — the whole of what the caller supplies */
131
+ rows: Rows
132
+ /** the store's vocabulary: its rows record each word by the identity this
133
+ * gives it, and read back the label it gives (./names.ts) */
134
+ vocab: Vocab
135
+ /** the entity table: where an eid becomes the integer the tables store */
136
+ spine?: { table?: string; id?: string; eid?: string }
137
+ /** content-addressed properties, if the graph has any */
138
+ cas?: Cas
139
+ /** the store's read overrides (@yaks/sql `Derived`, the ones it was opened
140
+ * with): a property whose stored value reads as something else — the
141
+ * address @yaks/blob keeps in place of a body — is recorded as stored and
142
+ * read back through its `text`, so history and undo hold what a reader of
143
+ * the graph sees and what a writer writes */
144
+ derived?: Derived
145
+ /** who this log writes as: the one host (a graph opened by one process or
146
+ * thread) whose transactions it records, so history can tell one host's
147
+ * from another's. Default: a fresh id, one per log. */
148
+ host?: string
149
+ }
150
+
151
+ // The tables. Append-only, no eid of their own, never in a snapshot and never
152
+ // in a client cache: this is the record of what was applied, not part of it.
153
+ //
154
+ // `tx.id` is an integer primary key, so it is the next rowid — monotonic, which
155
+ // is what lets the total order rest on something other than a clock, and what
156
+ // every cursor in the system holds. `tx.host` names the host that wrote it
157
+ // (`LogOpts.host`).
158
+ //
159
+ // `change.component` and `field.field` name the component and the property by
160
+ // identity, or by label where a word has none or the row predates identities
161
+ // (./names.ts). `change.operation` is `upsert` (the component is present; an
162
+ // empty one is an upsert with no field rows) or `remove` (the component was
163
+ // removed, or the entity was deleted when the component is `entity`). A row in
164
+ // the entity table outlives the entity it names, so every change can keep
165
+ // pointing at one.
166
+ //
167
+ // `field.present = 1` records a written value, JSON-encoded, so a value that is
168
+ // null stays distinct from a tombstone; `present = 0` is the tombstone written
169
+ // for each property a component still held when it was removed, which keeps
170
+ // property history, before-value lookup and undo self-contained and stops a
171
+ // value leaking across a removal and a later recreation. `ref` names content-
172
+ // addressed bytes the graph already holds, and then `value` stays null.
173
+ //
174
+ // Beside them, `journal_word` holds the names `vocab` gives each word a row
175
+ // records, which reads take labels from (./names.ts `words`): written here, so
176
+ // a store holds its vocabulary's words wherever it installs this schema.
177
+ export let ddl = (vocab: Vocab, spine = 'entity'): Stmt[] => [
178
+ ...tables(spine),
179
+ ...words(vocab),
180
+ ]
181
+
182
+ let tables = (spine: string): Stmt[] => {
183
+ let id = { name: 'id', type: 'integer', pk: true }
184
+ let to = (t: string, required = false) => ({
185
+ type: 'integer',
186
+ notNull: required,
187
+ ref: { table: t, cols: ['id'] },
188
+ })
189
+ let text = (name: string, required = false) => ({
190
+ name,
191
+ type: 'text',
192
+ notNull: required,
193
+ })
194
+ let int = (name: string) => ({ name, type: 'integer', notNull: true })
195
+ let created = (name: string, cols: CreateTable['cols']): CreateTable => ({
196
+ t: 'create table',
197
+ name,
198
+ ifNot: true,
199
+ cols,
200
+ })
201
+ let index = (name: string, on: string, cols: string[], where?: Expr) => ({
202
+ t: 'create index' as const,
203
+ name,
204
+ on,
205
+ cols: cols.map((c) => col(c)),
206
+ ifNot: true,
207
+ where,
208
+ })
209
+ return [
210
+ created('journal_tx', [
211
+ id,
212
+ text('ts', true),
213
+ { name: 'actor', ...to(spine) },
214
+ { name: 'via', ...to(spine) },
215
+ text('trace'),
216
+ text('host'),
217
+ // the branch it wrote to, where it wrote to one (@yaks/sqlite `moded`)
218
+ { name: 'branch', type: 'integer' },
219
+ ]),
220
+ created('journal_change', [
221
+ id,
222
+ { name: 'tx', ...to('journal_tx', true) },
223
+ int('ordinal'),
224
+ { name: 'entity', ...to(spine, true) },
225
+ text('component', true),
226
+ text('operation', true),
227
+ ]),
228
+ created('journal_field', [
229
+ id,
230
+ { name: 'change', ...to('journal_change', true) },
231
+ int('ordinal'),
232
+ text('field', true),
233
+ int('present'),
234
+ text('value'),
235
+ { name: 'ref', ...to(spine) },
236
+ ]),
237
+ index('journal_tx_actor', 'journal_tx', ['actor']),
238
+ index('journal_tx_via', 'journal_tx', ['via']),
239
+ index('journal_change_tx', 'journal_change', ['tx', 'ordinal']),
240
+ index('journal_change_ent', 'journal_change', ['entity', 'component']),
241
+ // a component's writes, newest first by the rowid that ends each key
242
+ index('journal_change_comp', 'journal_change', ['component']),
243
+ index('journal_field_change', 'journal_field', ['change', 'ordinal']),
244
+ index('journal_field_ref', 'journal_field', ['ref'], notNull(col('ref'))),
245
+ wordTable,
246
+ // the names recorded for a `_comp` row (./names.ts `recordedAt`)
247
+ index('journal_word_row', 'journal_word', ['row']),
248
+ ]
249
+ }
250
+
251
+ /** What {@link ddl} raised, dropped, for a store that keeps no journal: its
252
+ * tables in the reverse of the order they were raised, so each goes before the
253
+ * one it refers to (SQLite drops a table still referred to by deleting its
254
+ * rows one at a time, and refuses where a reference holds one), and each
255
+ * table's indexes with it. */
256
+ export let dropDdl = (): Drop[] =>
257
+ tables('entity').flatMap((s): Drop[] =>
258
+ s.t == 'create table'
259
+ ? [{ t: 'drop', kind: 'table', name: s.name, ifExists: true }]
260
+ : []
261
+ ).reverse()
262
+
263
+ // The properties an after-image records: everything but `eid`, which is the
264
+ // row's own identity and already the change's entity.
265
+ let written = (value: Comp): [string, unknown][] =>
266
+ Object.entries(value).filter(([prop]) => prop != 'eid')
267
+
268
+ /** Which rows a transaction is written down as, beside its own row: a
269
+ * `journal_change` row per component it wrote or removed (`changes`, the
270
+ * attribution aspect), and a `journal_field` row per value (`values`, the
271
+ * journal before versions). `seq` is the id the store's history took for it,
272
+ * whose row is already there to fill in. */
273
+ export type Recording = {
274
+ seq?: number
275
+ changes?: boolean
276
+ values?: boolean
277
+ /** the branch the transaction wrote to, where it wrote to one */
278
+ branch?: number
279
+ }
280
+
281
+ /** The log bound to one store: the writer, and the questions a journal is kept
282
+ * in order to answer. */
283
+ export type Log = {
284
+ /** Deliberately erase exact entities' recorded values, keeping other
285
+ * subjects in the same transaction. Returns removed logical values. */
286
+ purge: (eids: Eid[]) => Bundle[]
287
+ /** Candidate strings still named by surviving recorded values. */
288
+ retained: (values: string[]) => string[]
289
+ /** the host this log writes as ({@link LogOpts.host}) */
290
+ host: string
291
+ /** write one transaction down inside the caller's own transaction; returns
292
+ * its seq. `as` writes it under the transaction id the store's history
293
+ * already took for it ({@link Recording.seq}); `record` says which of its
294
+ * rows to write. */
295
+ write: (
296
+ meta: {
297
+ at: string
298
+ by?: Eid | null
299
+ via?: Eid | null
300
+ note?: string | null
301
+ },
302
+ applied: Patch[],
303
+ record?: Recording,
304
+ ) => number
305
+ /** one transaction's operations, whole or cut to one entity, in applied
306
+ * order */
307
+ patches: (seq: number, target?: Eid) => Patch[]
308
+ /** the transactions that touched one entity, newest first, cut to it */
309
+ entries: (target: Eid, n?: number) => Entry[]
310
+ /** every transaction one instrument wrote, newest first, whole */
311
+ by: (via: Eid, n?: number) => Entry[]
312
+ /** the transactions after a cursor, oldest first, at most `n` when given */
313
+ since: (cursor?: number, n?: number) => Entry[]
314
+ /** one transaction as a Batch, both sides of every movement */
315
+ at: (seq: number) => Batch | undefined
316
+ /** what happened to one entity, oldest first, as Batch */
317
+ history: (target: Eid, n?: number) => Batch[]
318
+ /** one entity's components as of just before a transaction */
319
+ before: (target: Eid, seq: number) => Record<string, Comp>
320
+ /** the last transaction that touched one entity, or 0 */
321
+ latest: (target: Eid) => number
322
+ /** every recorded write of one property, oldest first */
323
+ wrote: (
324
+ comp: string,
325
+ prop: string,
326
+ ) => { target: Eid; value: unknown; seq: number }[]
327
+ /** the highest seq the log holds, or 0 */
328
+ tip: () => number
329
+ /** the changes the log holds, by the component each wrote or removed */
330
+ held: () => Record<string, number>
331
+ /** has anything touched this entity since a given transaction? */
332
+ touchedSince: (target: Eid, seq: number) => boolean
333
+ /** does the log still read its text through this content? */
334
+ holds: (ref: number) => boolean
335
+ /** every recorded value containing this text, oldest first */
336
+ seek: (text: string) => Hit[]
337
+ /** rewrite one recorded inline value in place */
338
+ scrubValue: (field: number, value: string) => void
339
+ /** point one recorded content-addressed value at different content */
340
+ scrubRef: (field: number, ref: number) => void
341
+ /** Journal metadata rows still pointing at an exact entity identity. */
342
+ refs: (target: Eid) => number
343
+ /** Repair a malformed identity in journal metadata, preserving every entry. */
344
+ retarget: (from: Eid, to: Eid) => void
345
+ }
346
+
347
+ /**
348
+ * Bind the log to a store: `log({ rows: (s) => db.query(s) })`. Its `write`
349
+ * records one transaction inside the caller's own, `history(eid)` is every
350
+ * transaction that touched an entity, oldest first, and `since(cursor)` is
351
+ * every transaction after a cursor.
352
+ */
353
+ export let log = (opts: LogOpts): Log => {
354
+ let rows = opts.rows
355
+ let spine = opts.spine?.table ?? 'entity'
356
+ let idCol = opts.spine?.id ?? 'id'
357
+ let eidCol = opts.spine?.eid ?? 'eid'
358
+ let cas = opts.cas
359
+ let derived = opts.derived ?? {}
360
+ let host = opts.host ?? crypto.randomUUID()
361
+ let named = names(opts.vocab)
362
+ let jt = (c: string) => col(c, 'jt')
363
+ let jc = (c: string) => col(c, 'jc')
364
+ let jf = (c: string) => col(c, 'jf')
365
+ // An eid bound where a column holds an entity-table id, and the lookup back
366
+ // the other way.
367
+ let idBy = (eid: Expr): Expr =>
368
+ sub(select({
369
+ cols: [col(idCol, 's')],
370
+ from: table(spine, 's'),
371
+ where: eq(col(eidCol, 's'), eid),
372
+ }))
373
+ let idOf = (eid: Eid | null | undefined): Expr => idBy(val(eid ?? null))
374
+ let eidOf = (id: Expr): Expr =>
375
+ sub(select({
376
+ cols: [col(eidCol, 's')],
377
+ from: table(spine, 's'),
378
+ where: eq(col(idCol, 's'), id),
379
+ }))
380
+ let one = (s: Stmt) => rows(s)[0]
381
+ let num = (v: unknown) => Number(v ?? 0)
382
+ let str = (v: unknown) => (v == null ? null : String(v))
383
+ let refs = (target: Eid): number => {
384
+ let tables: [string, Expr][] = [
385
+ [
386
+ 'journal_tx',
387
+ or(eq(col('actor'), idOf(target)), eq(col('via'), idOf(target))),
388
+ ],
389
+ ['journal_change', eq(col('entity'), idOf(target))],
390
+ ]
391
+ return tables.reduce((n, [name, where]) =>
392
+ n + num(
393
+ one(select({
394
+ cols: [as(fn('count', lit('*')), 'n')],
395
+ from: table(name),
396
+ where,
397
+ }))?.n,
398
+ ), 0)
399
+ }
400
+ let retarget = (from: Eid, to: Eid): void => {
401
+ if (minted(from) || !minted(to)) {
402
+ throw new Refused(
403
+ '$journal_from repairs a malformed identity into a generated eid',
404
+ )
405
+ }
406
+ if (
407
+ !one(
408
+ select({
409
+ cols: [col(idCol)],
410
+ from: table(spine),
411
+ where: eq(col(eidCol), val(to)),
412
+ }),
413
+ )
414
+ ) {
415
+ throw new Refused(`journal destination ${to} names nothing`)
416
+ }
417
+ for (
418
+ let [name, prop] of [['journal_tx', 'actor'], ['journal_tx', 'via'], [
419
+ 'journal_change',
420
+ 'entity',
421
+ ]]
422
+ ) {
423
+ rows({
424
+ t: 'update',
425
+ table: name,
426
+ set: { [prop]: idOf(to) },
427
+ where: eq(col(prop), idOf(from)),
428
+ })
429
+ }
430
+ }
431
+ // The joins from a field to its change, and from a change to its
432
+ // transaction.
433
+ let ofChange = join(
434
+ table('journal_change', 'jc'),
435
+ eq(jc('id'), jf('change')),
436
+ )
437
+ let ofTx = join(table('journal_tx', 'jt'), eq(jt('id'), jc('tx')))
438
+ // A property recorded by address reads its text back through the content
439
+ // it names.
440
+ let content: Join[] = cas
441
+ ? [left(table(cas.table, 'c'), eq(col(cas.key, 'c'), jf('ref')))]
442
+ : []
443
+ let resolved = cas ? col(cas.value, 'c') : lit(null)
444
+
445
+ // Read the changes and their present fields together. An empty upsert or a
446
+ // removal still has a change row of its own.
447
+ let changes = (where: Expr, order: Expr[]): Select =>
448
+ select({
449
+ cols: [
450
+ as(jc('id'), 'id'),
451
+ as(col(eidCol, 'e'), 'eid'),
452
+ as(jc('component'), 'component'),
453
+ as(jc('operation'), 'operation'),
454
+ as(jf('field'), 'field'),
455
+ as(jf('value'), 'value'),
456
+ as(resolved, 'text'),
457
+ ],
458
+ from: table('journal_change', 'jc'),
459
+ joins: [
460
+ join(table(spine, 'e'), eq(col(idCol, 'e'), jc('entity'))),
461
+ left(
462
+ table('journal_field', 'jf'),
463
+ and(
464
+ eq(jf('change'), jc('id')),
465
+ eq(jf('present'), lit(1)),
466
+ not(eq(jc('operation'), lit('remove'))),
467
+ ),
468
+ ),
469
+ ...content,
470
+ ],
471
+ where,
472
+ order: [...order, jc('id'), jf('ordinal')],
473
+ })
474
+
475
+ // A recorded value as the graph reads it: one the store keeps in another
476
+ // form is read back through that property's `text`, and one it cannot read
477
+ // back stays as recorded.
478
+ let read = (comp: string, prop: string, stored: unknown): unknown => {
479
+ let text = derived[`${comp}.${prop}`]?.text
480
+ if (!text || typeof stored != 'string') return stored
481
+ return one(select({ cols: [as(text(val(stored)), 'v')] }))?.v ?? stored
482
+ }
483
+
484
+ let rebuild = (found: Row[]): Patch[] => {
485
+ let out: Patch[] = []
486
+ let id: unknown, patch: Patch | undefined
487
+ for (let row of found) {
488
+ if (!patch || row.id != id) {
489
+ id = row.id
490
+ patch = {
491
+ target: String(row.eid),
492
+ comp: named.compLabel(String(row.component)),
493
+ value: row.operation == 'remove' ? null : {},
494
+ }
495
+ out.push(patch)
496
+ }
497
+ if (patch.value && row.field != null) {
498
+ let prop = named.propLabel(String(row.field))
499
+ patch.value[prop] = row.text ?? read(patch.comp, prop, dec(row.value))
500
+ }
501
+ }
502
+ return out
503
+ }
504
+
505
+ /** One transaction's operations, whole or cut to one entity, in applied
506
+ * order. */
507
+ let patches = (seq: number, target?: Eid): Patch[] =>
508
+ rebuild(rows(changes(
509
+ target == null
510
+ ? eq(jc('tx'), val(seq))
511
+ : and(eq(jc('tx'), val(seq)), eq(col(eidCol, 'e'), val(target))),
512
+ [jc('ordinal')],
513
+ )))
514
+
515
+ let entryOf = (r: Row, target?: Eid): Entry => ({
516
+ seq: num(r.id),
517
+ at: String(r.ts),
518
+ by: str(r.actor),
519
+ via: str(r.via),
520
+ note: str(r.trace),
521
+ host: str(r.host),
522
+ patches: patches(num(r.id), target),
523
+ })
524
+
525
+ /**
526
+ * Write one transaction down, inside the caller's own transaction, and
527
+ * return its seq. It is derived entirely from what was applied: nothing was
528
+ * read first, so a caller owes this function nothing but an accurate account
529
+ * of what it wrote.
530
+ */
531
+ let write = (
532
+ meta: {
533
+ at: string
534
+ by?: Eid | null
535
+ via?: Eid | null
536
+ note?: string | null
537
+ },
538
+ applied: Patch[],
539
+ record: Recording = {},
540
+ ): number => {
541
+ let said = {
542
+ ts: val(meta.at),
543
+ actor: idOf(meta.by),
544
+ via: idOf(meta.via),
545
+ trace: val(meta.note ?? null),
546
+ host: val(host),
547
+ ...record.branch == null ? {} : { branch: val(record.branch) },
548
+ }
549
+ let seq = record.seq ?? num(
550
+ one({
551
+ t: 'insert',
552
+ into: 'journal_tx',
553
+ cols: Object.keys(said),
554
+ rows: [Object.values(said)],
555
+ returning: [col('id')],
556
+ })?.id,
557
+ )
558
+ if (record.seq != null) {
559
+ rows({
560
+ t: 'update',
561
+ table: 'journal_tx',
562
+ set: said,
563
+ where: eq(col('id'), val(record.seq)),
564
+ })
565
+ }
566
+ if (record.changes === false) return seq
567
+ let values = record.values !== false
568
+ // The properties a component still holds, newest after-image per property:
569
+ // the field id is monotonic, so the highest-id row per property is the
570
+ // latest in total order — and it reads this transaction's earlier upserts,
571
+ // which are uncommitted but visible on the same connection. A property
572
+ // recorded by its label before identities and by its identity since is
573
+ // one property, whose newest row says.
574
+ let held = (target: Eid, comp: string): string[] => {
575
+ let newest = new Map<string, Row>()
576
+ for (
577
+ let r of rows(select({
578
+ cols: [col('field'), col('present'), col('id')],
579
+ from: {
580
+ t: 'from',
581
+ q: select({
582
+ cols: [
583
+ as(jf('field'), 'field'),
584
+ as(jf('present'), 'present'),
585
+ as(jf('id'), 'id'),
586
+ as(
587
+ over(fn('row_number'), [jf('field')], [desc(jf('id'))]),
588
+ 'rn',
589
+ ),
590
+ ],
591
+ from: table('journal_field', 'jf'),
592
+ joins: [ofChange],
593
+ where: and(
594
+ eq(jc('entity'), idOf(target)),
595
+ among(jc('component'), named.comps(comp).map(val)),
596
+ ),
597
+ }),
598
+ },
599
+ where: eq(col('rn'), lit(1)),
600
+ }))
601
+ ) {
602
+ let prop = named.propLabel(String(r.field))
603
+ if (num(r.id) > num(newest.get(prop)?.id)) newest.set(prop, r)
604
+ }
605
+ return [...newest].flatMap(([prop, r]) => num(r.present) ? [prop] : [])
606
+ }
607
+ // Every change is one row of a JSON array, and every field another: a
608
+ // transaction is a few statements however many components it wrote.
609
+ let changes = new Map<number, number>()
610
+ for (
611
+ let part of parts(applied.map(({ target, comp, value }, ordinal) => [
612
+ ordinal,
613
+ target,
614
+ named.comp(comp),
615
+ value == null ? 'remove' : 'upsert',
616
+ ]))
617
+ ) {
618
+ rows({
619
+ t: 'insert',
620
+ into: 'journal_change',
621
+ cols: ['tx', 'ordinal', 'entity', 'component', 'operation'],
622
+ q: select({
623
+ cols: [val(seq), cell(0), idBy(cell(1)), cell(2), cell(3)],
624
+ from: call('json_each', [val(part)]),
625
+ }),
626
+ returning: [col('id'), col('ordinal')],
627
+ }).forEach((r) => changes.set(num(r.ordinal), num(r.id)))
628
+ }
629
+ if (!values) return seq
630
+ let fields: Param[][] = []
631
+ let flush = () => {
632
+ for (let part of parts(fields.splice(0))) {
633
+ rows({
634
+ t: 'insert',
635
+ into: 'journal_field',
636
+ cols: ['change', 'ordinal', 'field', 'present', 'value', 'ref'],
637
+ q: select({
638
+ cols: [0, 1, 2, 3, 4, 5].map(cell),
639
+ from: call('json_each', [val(part)]),
640
+ }),
641
+ })
642
+ }
643
+ }
644
+ applied.forEach(({ target, comp, value }, ordinal) => {
645
+ let change = changes.get(ordinal)!
646
+ let field = (
647
+ i: number,
648
+ prop: string,
649
+ v: string | null,
650
+ ref: number | null,
651
+ ) =>
652
+ fields.push([
653
+ change,
654
+ i,
655
+ named.prop(comp, prop),
656
+ v == null && ref == null ? 0 : 1,
657
+ v,
658
+ ref,
659
+ ])
660
+ if (value == null) {
661
+ // A removal tombstones every property the component still had, so
662
+ // property history stays self-contained across a removal and a later
663
+ // recreation. What it had may be this transaction's own earlier
664
+ // after-images, so those are written first.
665
+ flush()
666
+ held(target, comp).forEach((prop, i) => field(i, prop, null, null))
667
+ return
668
+ }
669
+ // An upsert records one present after-image per property, JSON-encoded so
670
+ // a present null stays distinct from a tombstone. An empty component
671
+ // writes none — its change row alone marks its presence.
672
+ written(value).forEach(([prop, v], i) =>
673
+ cas && cas.at(comp, prop) && typeof v == 'string'
674
+ ? field(i, prop, null, cas.put(v))
675
+ : field(i, prop, enc(v) ?? 'null', null)
676
+ )
677
+ })
678
+ flush()
679
+ return seq
680
+ }
681
+
682
+ // One entity's component state as of just before `seq`, rebuilt by merging,
683
+ // property by property, that entity's own rows in the log — bounded to one
684
+ // entity, never a table scan — and whether it lay deleted then. This is where
685
+ // the before-value an after-image log does not store comes from.
686
+ type Past = { state: Record<string, Comp>; dead: boolean }
687
+ let remember = (past: Past, { comp, value }: Patch): Past => {
688
+ // A deletion empties the entity. The next component upsert revives it.
689
+ if (comp == 'entity') {
690
+ return value == null ? { state: {}, dead: true } : past
691
+ }
692
+ if (value == null) delete past.state[comp]
693
+ else {
694
+ past.state[comp] = { ...past.state[comp], ...value }
695
+ past.dead = false
696
+ }
697
+ return past
698
+ }
699
+ let past = (target: Eid, seq: number): Past =>
700
+ rebuild(rows(changes(
701
+ and(eq(jc('entity'), idOf(target)), lt(jc('tx'), val(seq))),
702
+ [jc('tx'), jc('ordinal')],
703
+ ))).reduce(remember, { state: {}, dead: false })
704
+
705
+ /** One entity's components as of just before `seq`, rebuilt from its own
706
+ * rows in the log. */
707
+ let before = (target: Eid, seq: number): Record<string, Comp> =>
708
+ past(target, seq).state
709
+
710
+ // An entry's operations as deltas: a component that was not there is
711
+ // announced by a property-less delta before its properties follow, a
712
+ // component that went is a property-less delta carrying what it held, and a
713
+ // deletion is a tombstone appearing (`after: {}`). A write that brings a
714
+ // deleted entity back is that tombstone going (`before: {}`), ahead of the
715
+ // components it gives. The before-side comes from `past()`, carried forward
716
+ // across the transaction so that a transaction touching one component twice
717
+ // reads as two movements.
718
+ let deltasOf = (e: Entry, before: typeof past): Delta[] => {
719
+ let held = new Map<Eid, Record<string, Comp>>()
720
+ let buried = new Set<Eid>()
721
+ let now = (eid: Eid) => {
722
+ let s = held.get(eid)
723
+ if (s) return s
724
+ let p = before(eid, e.seq)
725
+ if (p.dead) buried.add(eid)
726
+ let state = { ...p.state }
727
+ held.set(eid, state)
728
+ return state
729
+ }
730
+ let out: Delta[] = []
731
+ for (let { target, comp, value } of e.patches) {
732
+ let st = now(target)
733
+ if (buried.has(target) && comp != 'entity' && value != null) {
734
+ buried.delete(target)
735
+ out.push({
736
+ target,
737
+ comp: TOMBSTONE,
738
+ prop: null,
739
+ before: {},
740
+ after: null,
741
+ })
742
+ }
743
+ if (comp == 'entity' && value == null) {
744
+ buried.add(target)
745
+ for (let [name, was] of Object.entries(st)) {
746
+ out.push({
747
+ target,
748
+ comp: name,
749
+ prop: null,
750
+ before: was,
751
+ after: null,
752
+ })
753
+ }
754
+ held.set(target, {})
755
+ out.push({
756
+ target,
757
+ comp: TOMBSTONE,
758
+ prop: null,
759
+ before: null,
760
+ after: {},
761
+ })
762
+ continue
763
+ }
764
+ let was = st[comp]
765
+ if (value == null) {
766
+ if (!was) continue
767
+ out.push({ target, comp, prop: null, before: was, after: null })
768
+ delete st[comp]
769
+ continue
770
+ }
771
+ if (!was) {
772
+ out.push({ target, comp, prop: null, before: null, after: {} })
773
+ st[comp] = was = {}
774
+ }
775
+ let next: Comp = { ...was }
776
+ for (let [prop, v] of written(value)) {
777
+ out.push({
778
+ target,
779
+ comp,
780
+ prop,
781
+ before: was[prop] ?? null,
782
+ after: v ?? null,
783
+ })
784
+ if (v == null) delete next[prop]
785
+ else next[prop] = v
786
+ }
787
+ st[comp] = next
788
+ }
789
+ return out
790
+ }
791
+
792
+ let batchOf = (e: Entry, before = past): Batch => ({
793
+ seq: e.seq,
794
+ at: e.at,
795
+ by: e.by,
796
+ via: e.via,
797
+ deltas: deltasOf(e, before),
798
+ })
799
+
800
+ // Transactions: their seq, when, who and through what, and the note.
801
+ let txs = (s: Omit<Select, 't' | 'cols' | 'from'>): Select =>
802
+ select({
803
+ cols: [
804
+ as(jt('id'), 'id'),
805
+ as(jt('ts'), 'ts'),
806
+ as(eidOf(jt('actor')), 'actor'),
807
+ as(eidOf(jt('via')), 'via'),
808
+ as(jt('trace'), 'trace'),
809
+ as(jt('host'), 'host'),
810
+ ],
811
+ from: table('journal_tx', 'jt'),
812
+ ...s,
813
+ })
814
+
815
+ /** Every transaction that touched one entity, newest first, cut to that
816
+ * entity. */
817
+ let entries = (target: Eid, n = 50): Entry[] =>
818
+ rows(select({
819
+ cols: [
820
+ as(jc('tx'), 'id'),
821
+ as(jt('ts'), 'ts'),
822
+ as(eidOf(jt('actor')), 'actor'),
823
+ as(eidOf(jt('via')), 'via'),
824
+ as(jt('trace'), 'trace'),
825
+ as(jt('host'), 'host'),
826
+ ],
827
+ from: table('journal_change', 'jc'),
828
+ joins: [ofTx],
829
+ where: eq(jc('entity'), idOf(target)),
830
+ group: [jc('tx')],
831
+ order: [desc(jc('tx'))],
832
+ limit: val(n),
833
+ })).map((r) => entryOf(r, target))
834
+
835
+ /** Every transaction one instrument wrote, newest first, whole — a ledger
836
+ * wants everything a transaction did, not one entity's part of it. */
837
+ let by = (via: Eid, n = 500): Entry[] =>
838
+ rows(txs({
839
+ where: eq(jt('via'), idOf(via)),
840
+ order: [desc(jt('id'))],
841
+ limit: val(n),
842
+ })).map((r) => entryOf(r))
843
+
844
+ /** The transactions after a cursor, oldest first, at most `n` of them when a
845
+ * reader pages. The before-side is not derived here: a reader paging forward
846
+ * replays what was written, and deriving it would turn one range read into a
847
+ * walk of the log per entity. */
848
+ let since = (cursor = 0, n?: number): Entry[] =>
849
+ rows(txs({
850
+ where: gt(jt('id'), val(cursor)),
851
+ order: [jt('id')],
852
+ ...(n == null ? {} : { limit: val(n) }),
853
+ })).map((r) => entryOf(r))
854
+
855
+ /** One transaction, whole, as a Batch — both sides of every movement, which
856
+ * is what `undone()` reverses and `applied()` replays. */
857
+ let at = (seq: number): Batch | undefined => {
858
+ let found = one(txs({ where: eq(jt('id'), val(seq)) }))
859
+ if (!found) return undefined
860
+ let e = entryOf(found)
861
+ return e.patches.length ? batchOf(e) : undefined
862
+ }
863
+
864
+ /** What happened to one entity, oldest first, as Batch values carrying only
865
+ * the movements about that entity — what the `history` tool reports. */
866
+ let history = (target: Eid, n = 50): Batch[] => {
867
+ let window = entries(target, n).reverse()
868
+ if (!window.length) return []
869
+ let prior = past(target, window[0].seq)
870
+ return window.map((entry) => {
871
+ let batch = batchOf(entry, () => prior)
872
+ prior = entry.patches.reduce(remember, prior)
873
+ return batch
874
+ })
875
+ }
876
+
877
+ /** The last transaction that touched one entity, or 0 — what an undo with no
878
+ * seq reverses. */
879
+ let latest = (target: Eid): number =>
880
+ num(
881
+ one(select({
882
+ cols: [as(fn('max', jc('tx')), 'id')],
883
+ from: table('journal_change', 'jc'),
884
+ where: eq(jc('entity'), idOf(target)),
885
+ }))?.id,
886
+ )
887
+
888
+ /**
889
+ * Every recorded write of one property, oldest first: the entity it was
890
+ * about, what it wrote, and the transaction that wrote it. This is the
891
+ * question a backfill asks — what has this property ever held, on any entity
892
+ * — which no per-entity reader can answer.
893
+ */
894
+ let wrote = (
895
+ comp: string,
896
+ prop: string,
897
+ ): { target: Eid; value: unknown; seq: number }[] =>
898
+ rows(select({
899
+ cols: [
900
+ as(eidOf(jc('entity')), 'target'),
901
+ as(jf('value'), 'value'),
902
+ as(jc('tx'), 'seq'),
903
+ ],
904
+ from: table('journal_field', 'jf'),
905
+ joins: [ofChange],
906
+ where: and(
907
+ among(jc('component'), named.comps(comp).map(val)),
908
+ among(jf('field'), named.props(comp, prop).map(val)),
909
+ eq(jf('present'), lit(1)),
910
+ eq(jc('operation'), lit('upsert')),
911
+ ),
912
+ order: [jc('tx'), jf('id')],
913
+ })).flatMap((r) =>
914
+ r.target == null ? [] : [{
915
+ target: String(r.target),
916
+ value: read(comp, prop, dec(r.value)),
917
+ seq: num(r.seq),
918
+ }]
919
+ )
920
+
921
+ /** The highest seq the log holds, or 0 — the cursor a reader starts from. */
922
+ let tip = (): number =>
923
+ num(
924
+ one(
925
+ select({
926
+ cols: [as(fn('max', col('id')), 'm')],
927
+ from: table('journal_tx'),
928
+ }),
929
+ )
930
+ ?.m,
931
+ )
932
+
933
+ /** The changes the log holds per component: one pass over the index on
934
+ * `component`, reading no change row. A deletion counts under `entity`. */
935
+ let held = (): Record<string, number> => heldRows(rows(heldSql()), opts.vocab)
936
+
937
+ /** Has anything touched this entity since `seq`? The coarse "something
938
+ * changed" question an undo asks where there is no property to put a
939
+ * precondition on. */
940
+ let touchedSince = (target: Eid, seq: number): boolean =>
941
+ !!one(select({
942
+ cols: [lit(1)],
943
+ from: table('journal_change', 'jc'),
944
+ where: and(eq(jc('entity'), idOf(target)), gt(jc('tx'), val(seq))),
945
+ limit: lit(1),
946
+ }))
947
+
948
+ /**
949
+ * Every recorded value that contains this text, oldest first — the scan a
950
+ * redaction starts from. `value` is the stored JSON and `ref` the content
951
+ * address when the property is content-addressed; the caller decodes and
952
+ * decides, because whether a property holds content or structure is the
953
+ * caller's policy, not the log's.
954
+ */
955
+ let seek = (text: string): Hit[] => {
956
+ let encoded = JSON.stringify(text).slice(1, -1)
957
+ let within = (e: Expr, s: string) => gt(fn('instr', e, val(s)), lit(0))
958
+ return rows(select({
959
+ cols: [
960
+ as(jf('id'), 'id'),
961
+ as(jf('value'), 'value'),
962
+ as(jf('field'), 'field'),
963
+ as(resolved, 'text'),
964
+ as(eidOf(jc('entity')), 'target'),
965
+ as(jc('component'), 'comp'),
966
+ as(eidOf(jf('ref')), 'content'),
967
+ as(jt('id'), 'seq'),
968
+ as(jt('ts'), 'at'),
969
+ ],
970
+ from: table('journal_field', 'jf'),
971
+ joins: [ofChange, ofTx, ...content],
972
+ where: and(
973
+ eq(jf('present'), lit(1)),
974
+ cas
975
+ ? or(within(jf('value'), encoded), within(col(cas.value, 'c'), text))
976
+ : within(jf('value'), encoded),
977
+ ),
978
+ order: [jf('id')],
979
+ })).map((r) => ({
980
+ field: num(r.id),
981
+ target: str(r.target),
982
+ comp: named.compLabel(String(r.comp)),
983
+ prop: named.propLabel(String(r.field)),
984
+ seq: num(r.seq),
985
+ at: String(r.at),
986
+ value: r.text != null ? String(r.text) : dec(r.value),
987
+ content: str(r.content),
988
+ }))
989
+ }
990
+
991
+ /** Does the log still refer to this content? Content-addressed bytes outlive
992
+ * the graph row that first wrote them, and this reports whether the log is
993
+ * one of the things still holding a reference. */
994
+ let holds = (ref: number): boolean =>
995
+ !!one(select({
996
+ cols: [lit(1)],
997
+ from: table('journal_field'),
998
+ where: eq(col('ref'), val(ref)),
999
+ limit: lit(1),
1000
+ }))
1001
+
1002
+ // Rewrite one recorded value in place — the one write here that is not an
1003
+ // append. A value deliberately forgotten has to leave the log too, or it
1004
+ // survives in the very thing that keeps history; the row itself stays, so the
1005
+ // chain of changes stays navigable and reads back as whatever replaced it.
1006
+
1007
+ let scrub = (field: number, set: Record<string, Expr>) =>
1008
+ void rows({
1009
+ t: 'update',
1010
+ table: 'journal_field',
1011
+ set,
1012
+ where: eq(col('id'), val(field)),
1013
+ })
1014
+
1015
+ /** Scrub an inline value, JSON-encoded as the log stores it. */
1016
+ let scrubValue = (field: number, value: string) =>
1017
+ scrub(field, { value: val(value) })
1018
+
1019
+ /** Point a content-addressed value at clean content instead. */
1020
+ let scrubRef = (field: number, ref: number) => scrub(field, { ref: val(ref) })
1021
+
1022
+ let targets = (eids: Eid[]) =>
1023
+ select({
1024
+ cols: [col(idCol)],
1025
+ from: table(spine),
1026
+ where: among(col(eidCol), array(eids)),
1027
+ })
1028
+ let purge = (eids: Eid[]): Bundle[] => {
1029
+ let subject = among(jc('entity'), targets(eids))
1030
+ let transactions = rows(select({
1031
+ cols: [jc('tx')],
1032
+ from: table('journal_change', 'jc'),
1033
+ where: subject,
1034
+ distinct: true,
1035
+ })).map((r) => Number(r.tx))
1036
+ let removed = rebuild(rows(changes(subject, []))).flatMap((p) =>
1037
+ p.value == null ? [] : [{ entity: { eid: p.target }, [p.comp]: p.value }]
1038
+ )
1039
+ rows({
1040
+ t: 'delete',
1041
+ from: 'journal_field',
1042
+ where: among(
1043
+ col('change'),
1044
+ select({
1045
+ cols: [jc('id')],
1046
+ from: table('journal_change', 'jc'),
1047
+ where: subject,
1048
+ }),
1049
+ ),
1050
+ })
1051
+ rows({
1052
+ t: 'delete',
1053
+ from: 'journal_change',
1054
+ where: among(col('entity'), targets(eids)),
1055
+ })
1056
+ for (let prop of ['actor', 'via']) {
1057
+ rows({
1058
+ t: 'update',
1059
+ table: 'journal_tx',
1060
+ set: { [prop]: val(null) },
1061
+ where: among(col(prop), targets(eids)),
1062
+ })
1063
+ }
1064
+ rows({
1065
+ // Sequence anchors may still delimit another subject's versions or a
1066
+ // branch fork. Keep the generated clock, erase its now-unowned metadata.
1067
+ t: 'update',
1068
+ table: 'journal_tx',
1069
+ set: { actor: val(null), via: val(null), trace: val(null) },
1070
+ where: and(
1071
+ among(col('id'), array(transactions)),
1072
+ not(exists(select({
1073
+ cols: [lit(1)],
1074
+ from: table('journal_change'),
1075
+ where: eq(col('tx'), col('id', 'journal_tx')),
1076
+ }))),
1077
+ ),
1078
+ })
1079
+ return removed
1080
+ }
1081
+ let retained = (values: string[]): string[] => {
1082
+ let candidates = new Set(values), found = new Set<string>()
1083
+ let visit = (value: unknown): void => {
1084
+ if (typeof value == 'string') {
1085
+ if (candidates.has(value)) found.add(value)
1086
+ } else if (value && typeof value == 'object') {
1087
+ for (let part of Object.values(value)) visit(part)
1088
+ }
1089
+ }
1090
+ for (
1091
+ let row of rows(
1092
+ select({ cols: [col('value')], from: table('journal_field') }),
1093
+ )
1094
+ ) {
1095
+ visit(dec(row.value))
1096
+ }
1097
+ if (cas) {
1098
+ for (
1099
+ let row of rows(select({
1100
+ cols: [col(cas.value, 'c')],
1101
+ from: table('journal_field', 'jf'),
1102
+ joins: [
1103
+ join(table(cas.table, 'c'), eq(col(cas.key, 'c'), jf('ref'))),
1104
+ ],
1105
+ }))
1106
+ ) visit(row)
1107
+ }
1108
+ return [...found]
1109
+ }
1110
+
1111
+ return {
1112
+ host,
1113
+ purge,
1114
+ retained,
1115
+ write,
1116
+ patches,
1117
+ entries,
1118
+ by,
1119
+ since,
1120
+ at,
1121
+ history,
1122
+ before,
1123
+ latest,
1124
+ wrote,
1125
+ tip,
1126
+ held,
1127
+ touchedSince,
1128
+ holds,
1129
+ seek,
1130
+ scrubValue,
1131
+ scrubRef,
1132
+ refs,
1133
+ retarget,
1134
+ }
1135
+ }
1136
+
1137
+ export { dec, enc }
1138
+
1139
+ // The key a deletion rides from the `precondition` hook, which read what its
1140
+ // entity held, to the `journal` hook, which records nothing of it. Set here and
1141
+ // nowhere else: no plugin answers it as a request, so admission refuses a
1142
+ // caller who sends one.
1143
+ let UNRECORDED = '$unrecorded'
1144
+
1145
+ /**
1146
+ * The log as a plugin, so that a graph keeps a journal by listing it:
1147
+ * `graph({ storage, vocab, plugins: [journal(log({ rows }), vocab)] })`.
1148
+ *
1149
+ * Its `journal` hook records the transaction as applied — one row per
1150
+ * component the bundles patched or removed, in the order they arrived — under
1151
+ * its writer. A batch carrying more than one writer's work is recorded as one
1152
+ * transaction per writer, each holding what its entities' bundles wrote
1153
+ * (@yaks/graph `writers`), so an entity's history names who wrote it, as its
1154
+ * stamps do.
1155
+ *
1156
+ * A component the vocabulary declares `journal: false` is not recorded: a
1157
+ * process's own bookkeeping, such as the stamps or an effect run. Nor is the
1158
+ * deletion of an entity that held nothing else, so such an entity leaves no
1159
+ * trace at all. That is the one thing read before the write: on the
1160
+ * `precondition` phase, what each entity a bundle deletes holds, gathered with
1161
+ * the batch's other reads (`wants`).
1162
+ *
1163
+ * `components` narrows it to the ones named, for a store whose history is
1164
+ * about a few of its words while the rest are written often: the others are
1165
+ * left out as `journal: false` ones are.
1166
+ */
1167
+ export let journal = (
1168
+ n: Log,
1169
+ vocab: Vocab,
1170
+ opts: {
1171
+ now?: () => string
1172
+ name?: string
1173
+ record?: Recording
1174
+ components?: string[]
1175
+ } = {},
1176
+ ): Plugin => {
1177
+ let clock = opts.now ?? (() => new Date().toISOString())
1178
+ let named = opts.components && new Set(opts.components)
1179
+ let kept = (comp: string) =>
1180
+ (!named || named.has(comp)) && vocab.comp(comp)?.journal !== false
1181
+ let deleting = (bundles: Bundle[]): Eid[] => [
1182
+ ...new Set(
1183
+ bundles.filter((b) => b.$delete === true).map((b) => b.entity.eid),
1184
+ ),
1185
+ ]
1186
+ // An entity as the batch found it, holding something and nothing recorded.
1187
+ let unrecorded = (b: Bundle) => {
1188
+ let held = comps(b)
1189
+ return !dead(b) && held.length > 0 && held.every(([c]) => !kept(c))
1190
+ }
1191
+ return {
1192
+ name: opts.name ?? '@yaks/journal',
1193
+ namespace: null,
1194
+ purge: (_graph, eids) => n.purge(eids),
1195
+ retained: (_graph, values) => n.retained(values),
1196
+ admission: () => true,
1197
+ requests: ['$journal_from'],
1198
+ wants: (bundles) => {
1199
+ let eids = deleting(bundles)
1200
+ return eids.length ? [{ eids }] : []
1201
+ },
1202
+ hooks: {
1203
+ normalize: (
1204
+ bundles: Bundle[],
1205
+ _tx: Tx,
1206
+ _err: unknown,
1207
+ context?: HookContext,
1208
+ ) => {
1209
+ for (let b of bundles) {
1210
+ if (!('$journal_from' in b)) continue
1211
+ if (!context?.trusted) {
1212
+ throw new Refused(
1213
+ '$journal_from requires a trusted maintenance write',
1214
+ )
1215
+ }
1216
+ if (
1217
+ typeof b.$journal_from != 'string' || minted(b.$journal_from) ||
1218
+ !minted(b.entity.eid)
1219
+ ) {
1220
+ throw new Refused(
1221
+ '$journal_from is an exact malformed identity, on a generated destination eid',
1222
+ )
1223
+ }
1224
+ }
1225
+ return bundles
1226
+ },
1227
+ precondition: (bundles: Bundle[], tx: Tx) => {
1228
+ for (let b of bundles) {
1229
+ if (b.$prune && n.refs(b.entity.eid)) {
1230
+ throw new Refused(
1231
+ `cannot prune ${b.entity.eid}: journal history still references it; repair with $journal_from first`,
1232
+ )
1233
+ }
1234
+ }
1235
+ let eids = deleting(bundles)
1236
+ if (!eids.length) return bundles
1237
+ return after(tx.get(eids), (found) => {
1238
+ let quiet = new Set(
1239
+ found.filter(unrecorded).map((b) => b.entity.eid),
1240
+ )
1241
+ return quiet.size
1242
+ ? bundles.map((b) =>
1243
+ b.$delete === true && quiet.has(b.entity.eid)
1244
+ ? { ...b, [UNRECORDED]: true }
1245
+ : b
1246
+ )
1247
+ : bundles
1248
+ })
1249
+ },
1250
+ commit: (bundles: Bundle[]) => {
1251
+ for (let b of bundles) {
1252
+ if (typeof b.$journal_from == 'string') {
1253
+ n.retarget(b.$journal_from, b.entity.eid)
1254
+ }
1255
+ }
1256
+ return bundles
1257
+ },
1258
+ journal: (bundles: Bundle[], tx: Tx) => {
1259
+ let writer = writers(bundles)
1260
+ let by = new Map<string, { actor: Actor; applied: Patch[] }>()
1261
+ let put = (actor: Actor, patch: Patch) => {
1262
+ let key = `${actor.by ?? ''} ${actor.via ?? ''}`
1263
+ if (!by.has(key)) by.set(key, { actor, applied: [] })
1264
+ by.get(key)!.applied.push(patch)
1265
+ }
1266
+ for (let b of bundles) {
1267
+ if (b[UNRECORDED]) continue
1268
+ let target = b.entity.eid
1269
+ let actor = writer(target)
1270
+ if (dead(b)) {
1271
+ put(actor, { target, comp: 'entity', value: null })
1272
+ continue
1273
+ }
1274
+ for (let [comp, value] of comps(b)) {
1275
+ if (kept(comp)) put(actor, { target, comp, value: value ?? null })
1276
+ }
1277
+ }
1278
+ let at = clock()
1279
+ // Where the store keeps versions, the transaction its versions name
1280
+ // is the first writer's: the batch's own (@yaks/graph `writers`).
1281
+ let first = true
1282
+ for (let { actor, applied } of by.values()) {
1283
+ let seq = first && tx.clock ? tx.clock() : undefined
1284
+ first = false
1285
+ n.write(
1286
+ { at, by: actor.by ?? null, via: actor.via ?? null },
1287
+ applied,
1288
+ { ...opts.record, seq },
1289
+ )
1290
+ }
1291
+ return bundles.map((b) => {
1292
+ if (!(UNRECORDED in b)) return b
1293
+ let { [UNRECORDED]: _, ...rest } = b
1294
+ return rest as Bundle
1295
+ })
1296
+ },
1297
+ },
1298
+ }
1299
+ }