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