@yaks/ram 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.
package/store.ts ADDED
@@ -0,0 +1,1139 @@
1
+ import {
2
+ preserving,
3
+ type Trash,
4
+ trashLimit,
5
+ trashOrder,
6
+ type TrashPage,
7
+ } from '@yaks/graph/trash'
8
+ // A graph in a Map. This is @yaks/graph's `Storage` with nothing underneath it
9
+ // — one record per entity, keyed by eid, held in a plain Map — so a graph can
10
+ // run in a page, in a worker, or in a test with no database to install, no
11
+ // driver to bind, and no promise to await.
12
+ //
13
+ // Reads go through @yaks/match: the same query string @yaks/sql compiles into a
14
+ // SQL statement is evaluated here as a predicate over the bundles the map
15
+ // holds. This file hands the matcher its rows the way a database hands a plan
16
+ // its tables: by id, by the component an entity wears, and by the value a
17
+ // property holds, so a query that names a component or asks for a value reads
18
+ // those entities and no others.
19
+ //
20
+ // Writes follow the patch rules every adapter implements — omitted properties
21
+ // untouched, a null property cleared, a null component dropped, a tombstoned
22
+ // entity taking no patch until `revive` brings it back under the identity it
23
+ // kept — and identity belongs to storage: `patch` creates a
24
+ // record for every eid the write touches or points at, numbers each new one in
25
+ // the order it was first touched, and returns what it created.
26
+ //
27
+ // A record is the bundle a read answers with, and it is never mutated in place:
28
+ // a patch builds the next one and puts it in the map, and a patch that changes
29
+ // nothing keeps the one it found. So a read copies nothing, and rolling back is
30
+ // cheap — an undo log of one reference per entity a transaction touched,
31
+ // replayed backwards, restores the map and its indexes exactly as they were
32
+ // without copying anything the write did not touch.
33
+ //
34
+ // The same log is how declared rules see a batch before it is written: the
35
+ // batch is patched in, the rules are asked (./rules.ts), and the log is
36
+ // rewound, so a rule reads the graph as the batch would leave it through the
37
+ // same indexes every read uses, and nothing it saw outlives the question.
38
+
39
+ import type {
40
+ Binding,
41
+ Bundle,
42
+ Comp,
43
+ Doom,
44
+ Eid,
45
+ Entity,
46
+ Graves,
47
+ Match,
48
+ ReadOpts,
49
+ Row,
50
+ } from 'jsr:@yaks/graph@0.2.36'
51
+ import { isPromise, same } from '@yaks/fp'
52
+ import {
53
+ comps,
54
+ dead,
55
+ reserved as metadata,
56
+ TOMBSTONE,
57
+ tombstoned,
58
+ } from '@yaks/graph/bundle'
59
+ import { only } from '@yaks/graph/read'
60
+ import {
61
+ clash,
62
+ type Pair,
63
+ renumbering,
64
+ type Series,
65
+ seriesOf,
66
+ stating,
67
+ } from '@yaks/graph/storage'
68
+ import {
69
+ type Computed,
70
+ type Index,
71
+ index,
72
+ keyOf,
73
+ matcher,
74
+ type Query,
75
+ rows as answer,
76
+ statusOf,
77
+ } from '@yaks/match'
78
+ import { extendsVocab, relabelsVocab, type Vocab } from '@yaks/vocab'
79
+ import { bindings } from './rules.js'
80
+ import { records } from './records.js'
81
+
82
+ export type { Query }
83
+
84
+ // What a rollback puts the numbering back to.
85
+ type Counted = { highs: Map<string, number> }
86
+
87
+ /** Passed to every read of a store: the moment relative time phrases in a query
88
+ * (`.released=today`) resolve against. A per-call `opts` overrides it. */
89
+ export type RamOpts = {
90
+ /** the reference moment for time phrases (default: the read's own `now`) */
91
+ now?: number
92
+ /** never assign a number, and take the `num` a patch states unchecked.
93
+ * This is what a store mirroring another graph needs — a client applying the
94
+ * bundles a server returned is being told the identity, not choosing it. An
95
+ * entity it has not been told a number for has none: a number it guessed
96
+ * could be another entity's. Off by default: a store that mirrors nothing
97
+ * owns its own numbering, and gives a stated number only where no other
98
+ * entity holds it. Such a store also keeps the computed values it is sent,
99
+ * as the graph it mirrors derived them. */
100
+ adopt?: boolean
101
+ /** Give new entities a human-readable number. Opt-IN, with the same option
102
+ * name @yaks/sqlite uses: left out, an entity has its eid and nothing else.
103
+ * A table of letters (component → letter), or `true` for the prefixes the
104
+ * vocabulary declares, numbers each entity in the series of the components
105
+ * it is given, once, on the write that first gives it one. */
106
+ number?: boolean | Series
107
+ /** `comp.prop` → the value for one bundle, for each property the vocabulary
108
+ * declares computed and never stores: what `.task.status=open` is answered
109
+ * with here, the way @yaks/sql answers it with a `derived` expression. A
110
+ * package that declares one ships the rule (@yaks/task `compute`). Left out,
111
+ * a query on a computed property is refused, naming it. */
112
+ computed?: Computed
113
+ }
114
+
115
+ /**
116
+ * A transaction over the map: @yaks/graph's `Tx`, implemented synchronously.
117
+ * The store commits when the body returns and rolls back when it throws, so a
118
+ * rejected write leaves the map exactly as it found it.
119
+ */
120
+ export type Tx = {
121
+ /** a query → whole bundles, or only `comps` when named */
122
+ read: (query: Query, opts?: ReadOpts, comps?: string[]) => Bundle[]
123
+ /** lookup by id, not search: these entities as they stand, carrying the
124
+ * components `comps` names or every one. A deleted one carries `tombstone`;
125
+ * an unknown one is simply absent. */
126
+ get: (eids: Eid[], comps?: string[], opts?: ReadOpts) => Bundle[]
127
+ /** what declared rules are evaluated through: every match run against this
128
+ * graph with `bundles` folded in, as though it had been written, and nothing
129
+ * of it left behind */
130
+ bindings: (matches: Match[], bundles: Bundle[]) => Binding[][]
131
+ /** The deletion closure and references to clear, from the stored index. */
132
+ doom: (eids: Eid[]) => Doom | null
133
+ /** apply these patches → the entities they created, each with its `num` */
134
+ patch: (bundles: Bundle[]) => Entity[]
135
+ /** Evict live payloads, not identities. A later patch keeps the same number.
136
+ * A tombstone stays; eviction is never deletion. */
137
+ evict: (eids: Eid[]) => void
138
+ /** remove these entities: their components go, their identity is tombstoned */
139
+ remove: (entities: Entity[]) => void
140
+ /** erase these entities, a writer's own bookkeeping: components and
141
+ * identity go, with no tombstone */
142
+ discard: (entities: Entity[]) => void
143
+ /** Erase identities the graph has checked as empty and unreferenced. */
144
+ prune: (eids: Eid[]) => void
145
+ /** bring these tombstoned entities back, with their identity and no
146
+ * components */
147
+ revive: (eids: Eid[]) => void
148
+ }
149
+
150
+ /**
151
+ * A bound store: @yaks/graph's `Storage`, implemented synchronously. It has
152
+ * the same five members a database adapter has, so it satisfies `Storage`
153
+ * wherever one is wanted — and a caller using a `Store` directly never awaits
154
+ * a row.
155
+ */
156
+ export type Store = {
157
+ /** Destructive transactions retained for recovery. */
158
+ trash: (eids?: Eid[], page?: TrashPage) => Trash[]
159
+ /** Purge one retained transaction after a person explicitly chooses it. */
160
+ purgeTrash: (id: string | string[]) => void
161
+
162
+ /** Adopt an additive vocabulary without replacing rows or their indexes. */
163
+ extend: (next: Vocab) => boolean
164
+ /** Read a renamed vocabulary over the same records. */
165
+ reload: (next: Vocab) => boolean
166
+ /** Whether a value this store reads for the property means its entity
167
+ * wears the component. */
168
+ worn: (comp: string, prop: string) => boolean
169
+ /** nothing to create — installing a map is a no-op */
170
+ install: () => void
171
+ /** a query → its entities, with `comps` only where named */
172
+ read: (query: Query, opts?: ReadOpts, comps?: string[]) => Bundle[]
173
+ /** a query → one raw `{ eid }` row per match, or an aggregate's rows */
174
+ rows: (query: Query, opts?: ReadOpts) => Row[]
175
+ /** these entities as they stand, carrying the components `comps` names or
176
+ * every one */
177
+ get: (eids: Eid[], comps?: string[], opts?: ReadOpts) => Bundle[]
178
+ /** tombstones laid before `before` that nothing refers to, oldest first,
179
+ * resuming at `after` */
180
+ buried: (
181
+ before: string,
182
+ page: { after?: string; limit: number; referenced?: boolean },
183
+ ) => Graves
184
+ /** run `body` in a transaction: commit on return, roll back on throw */
185
+ tx: <R>(body: (tx: Tx) => R) => R
186
+ }
187
+
188
+ // A deleted entity keeps its identity and a tombstone, and nothing else, until
189
+ // `revive` brings it back.
190
+ let buried = (b: Bundle | undefined): boolean => b?.[TOMBSTONE] != null
191
+ let NONE: ReadonlyMap<Eid, Bundle> = new Map()
192
+ let file = <K>(
193
+ byKey: Map<K, Map<Eid, Bundle>>,
194
+ key: K,
195
+ eid: Eid,
196
+ b: Bundle,
197
+ ) => {
198
+ let at = byKey.get(key)
199
+ if (!at) byKey.set(key, at = new Map())
200
+ at.set(eid, b)
201
+ }
202
+ let unfile = <K>(byKey: Map<K, Map<Eid, Bundle>>, key: K, eid: Eid) => {
203
+ let at = byKey.get(key)
204
+ if (at?.delete(eid) && !at.size) byKey.delete(key)
205
+ }
206
+ // The band a value files under in a number index: the whole number at or below
207
+ // it, read the way a number comparison reads it (@yaks/match), so every value a
208
+ // range selects is in one of the bands the range spans.
209
+ let bandOf = (v: unknown): number | undefined => {
210
+ if (v == null) return undefined
211
+ let n = Math.floor(Number(v))
212
+ return Number.isNaN(n) ? undefined : n
213
+ }
214
+ // One property of a record, or undefined.
215
+ let valueOf = (b: Bundle | undefined, comp: string, prop: string): unknown =>
216
+ (b?.[comp] as Comp | undefined)?.[prop]
217
+
218
+ // A vocabulary snapshot never changes: resolve its status-bearing components once,
219
+ // rather than inspect every component of every row each time it is gathered.
220
+ let ladders = new WeakMap<Vocab, string[]>()
221
+ let statusesOf = (vocab: Vocab): string[] => {
222
+ let held = ladders.get(vocab)
223
+ if (!held) {
224
+ ladders.set(
225
+ vocab,
226
+ held = vocab.all.filter((n) => vocab.comp(n)?.ladder),
227
+ )
228
+ }
229
+ return held
230
+ }
231
+ let binariesOf = (vocab: Vocab) =>
232
+ vocab.all.flatMap((comp) => {
233
+ let props = vocab.props(comp).filter((p) =>
234
+ vocab.prop(comp, p)?.scalar == 'binary'
235
+ )
236
+ return props.length ? [{ comp, props }] : []
237
+ })
238
+ let uniqueIn = (vocab: Vocab) =>
239
+ vocab.all.some((name) => vocab.indexes(name).some((i) => i.unique))
240
+
241
+ /**
242
+ * A store over a Map of bundles, bound to a vocabulary once. It is the storage
243
+ * a client graph and a fast test run on:
244
+ *
245
+ * ```ts
246
+ * import { graph } from '@yaks/graph'
247
+ * import { loadVocab } from '@yaks/vocab'
248
+ * import { docDoc } from '@yaks/doc'
249
+ * import { ram } from '@yaks/ram'
250
+ *
251
+ * let vocab = loadVocab([docDoc])
252
+ * let g = graph({ storage: ram(vocab), vocab })
253
+ * g.apply([{ entity: { eid: 'b1' }, doc: { title: 'Dune' } }])
254
+ * g.read('.kind=doc')
255
+ * ```
256
+ */
257
+ export let ram = (vocab: Vocab, base: RamOpts = {}): Store => {
258
+ let rows = records(() => vocab)
259
+ // Compact identity reservations survive payload eviction. They are not query rows.
260
+ let cold = new Map<Eid, Entity>()
261
+ // What a query reads instead of every row: the entities wearing each
262
+ // component, and — for each property a query has asked for by value — the
263
+ // entities by the key their value files under (@yaks/match `keyOf`), or for
264
+ // each number a query has asked for a range of, by band (`bandOf`).
265
+ let worn = new Map<string, Map<Eid, Bundle>>()
266
+ let filed = new Map<
267
+ string,
268
+ [string, string, Map<string, Map<Eid, Bundle>>]
269
+ >()
270
+ let banded = new Map<
271
+ string,
272
+ [string, string, Map<number, Map<Eid, Bundle>>]
273
+ >()
274
+ // The same declared uniqueness that SQLite enforces on its indexes, each
275
+ // component's taken from the vocabulary when a row first wears it. A
276
+ // transaction's rollback travels through `put`, restoring these as well.
277
+ type Unique = {
278
+ comp: string
279
+ index: ReturnType<Vocab['indexes']>[number]
280
+ held: Map<string, Eid>
281
+ }
282
+ let uniques = new Map<string, Unique[]>()
283
+ let uniqueOf = (comp: string): Unique[] => {
284
+ let key = vocab.stored(comp)
285
+ let got = uniques.get(key)
286
+ if (!got) {
287
+ uniques.set(
288
+ key,
289
+ got = !vocab.comp(comp) ? [] : vocab.indexes(comp)
290
+ .filter((i) => i.unique)
291
+ .map((index) => ({ comp, index, held: new Map() })),
292
+ )
293
+ }
294
+ return got
295
+ }
296
+ let hasUnique = uniqueIn(vocab)
297
+ let uniqueKey = (
298
+ b: Bundle | undefined,
299
+ comp: string,
300
+ props: string[],
301
+ present: string[] = [],
302
+ ): string | undefined => {
303
+ if (!b?.[comp] || present.some((p) => valueOf(b, comp, p) == null)) {
304
+ return undefined
305
+ }
306
+ let values = props.map((p) => keyOf(valueOf(b, comp, p)))
307
+ return values.some((v) => v === undefined)
308
+ ? undefined
309
+ : JSON.stringify(values)
310
+ }
311
+ // Each series' last number, by letter.
312
+ let highs = new Map<string, number>()
313
+ // The entities each number was given to, any letter, a tombstone's and an
314
+ // evicted payload's included. Never pruned: an entry is checked against the
315
+ // entity's own pair when asked (`holders`), so one given away since says
316
+ // nothing.
317
+ let given = new Map<number, Set<Eid>>()
318
+ let pairOf = (eid: Eid): Pair | null | undefined => {
319
+ let e = rows.get(eid)?.entity ?? cold.get(eid)
320
+ return !e ? undefined : e.num == null ? null : {
321
+ num: e.num,
322
+ prefix: e.prefix ?? null,
323
+ }
324
+ }
325
+ let holders = (num: number): ({ eid: Eid } & Pair)[] =>
326
+ [...given.get(num) ?? []].flatMap((eid) => {
327
+ let pair = pairOf(eid)
328
+ return pair?.num === num ? [{ eid, ...pair }] : []
329
+ })
330
+ // When each tombstone was laid, keyed by the record itself, so a rollback
331
+ // that puts an earlier record back takes the time with it.
332
+ let laid = new WeakMap<Bundle, string>()
333
+ // The undo log: for each entity a transaction is about to change, the record
334
+ // it held first. Replayed backwards, it is the rollback.
335
+ let log: [Eid, Bundle | undefined, Entity | undefined][] = []
336
+ let trash = new Map<string, Trash>()
337
+ let trashLog: [string, Trash | undefined][] = []
338
+ let depth = 0
339
+ let save = (eid: Eid) => log.push([eid, rows.get(eid), cold.get(eid)])
340
+ // Back to where the log stood at `mark`, and the numbering with it.
341
+ let rewind = (mark: number, minted: Counted) => {
342
+ while (log.length > mark) {
343
+ let [eid, rec, identity] = log.pop()!
344
+ if (identity) cold.set(eid, identity)
345
+ else cold.delete(eid)
346
+ put(eid, rec)
347
+ }
348
+ highs = minted.highs
349
+ }
350
+ let counted = (): Counted => ({ highs: new Map(highs) })
351
+
352
+ // One entity's record replaced, or dropped, and every index moved with it.
353
+ // Every write goes through here, a rollback's included, so an index never
354
+ // disagrees with the rows.
355
+ let put = (eid: Eid, b: Bundle | undefined) => {
356
+ let was = rows.get(eid)
357
+ let checks: Unique[] = []
358
+ // Components are immutable; their unique keys stay held by the same eid
359
+ // when another component changes. Row-bearing indexes still move below.
360
+ if (hasUnique) {
361
+ for (let comp in was) {
362
+ if (was[comp] !== b?.[comp]) checks.push(...uniqueOf(comp))
363
+ }
364
+ for (let comp in b) {
365
+ if (!was || !(comp in was)) checks.push(...uniqueOf(comp))
366
+ }
367
+ }
368
+ for (let { comp, index, held } of checks) {
369
+ let key = uniqueKey(b, comp, index.props, index.present)
370
+ if (key !== undefined && held.has(key) && held.get(key) != eid) {
371
+ throw new Error(
372
+ `unique constraint failed: ${comp}.${index.props.join(', ')}`,
373
+ )
374
+ }
375
+ }
376
+ if (b) {
377
+ let at = laid.get(b)
378
+ b = rows.set(eid, b)
379
+ if (at != null) laid.set(b, at)
380
+ } else rows.delete(eid)
381
+ let num = b?.entity.num
382
+ if (num != null) given.set(num, (given.get(num) ?? new Set()).add(eid))
383
+ for (let { comp, index, held } of checks) {
384
+ let from = uniqueKey(was, comp, index.props, index.present)
385
+ let to = uniqueKey(b, comp, index.props, index.present)
386
+ if (from !== undefined && from != to) held.delete(from)
387
+ if (to !== undefined) held.set(to, eid)
388
+ }
389
+ if (was) {
390
+ for (let name in was) {
391
+ if (name != 'entity' && !(b && name in b)) {
392
+ worn.get(vocab.stored(name))?.delete(eid)
393
+ }
394
+ }
395
+ }
396
+ if (b) {
397
+ for (let name in b) {
398
+ if (name == 'entity') continue
399
+ let key = vocab.stored(name)
400
+ let at = worn.get(key)
401
+ if (!at) worn.set(key, at = new Map())
402
+ at.set(eid, b)
403
+ }
404
+ }
405
+ for (let [comp, prop, byKey] of filed.values()) {
406
+ let from = keyOf(valueOf(was, comp, prop))
407
+ let to = keyOf(valueOf(b, comp, prop))
408
+ if (from !== undefined && from !== to) unfile(byKey, from, eid)
409
+ if (to !== undefined) file(byKey, to, eid, b!)
410
+ }
411
+ for (let [comp, prop, byBand] of banded.values()) {
412
+ let from = bandOf(valueOf(was, comp, prop))
413
+ let to = bandOf(valueOf(b, comp, prop))
414
+ if (from !== undefined && from !== to) unfile(byBand, from, eid)
415
+ if (to !== undefined) file(byBand, to, eid, b!)
416
+ }
417
+ }
418
+
419
+ let holdersOf = (comp: string) => worn.get(vocab.stored(comp)) ?? NONE
420
+ let keyFor = (comp: string, prop: string) =>
421
+ `${vocab.stored(comp)}.${vocab.stored(comp, prop)}`
422
+
423
+ // The keyed index over one property: filed from the component index the
424
+ // first time a query asks for it, and kept by `put` from then on.
425
+ let keys = (comp: string, prop: string): Map<string, Map<Eid, Bundle>> => {
426
+ let at = keyFor(comp, prop)
427
+ let held = filed.get(at)
428
+ if (held) return held[2]
429
+ let byKey = new Map<string, Map<Eid, Bundle>>()
430
+ filed.set(at, [comp, prop, byKey])
431
+ for (let [eid, b] of holdersOf(comp)) {
432
+ let key = keyOf(valueOf(b, comp, prop))
433
+ if (key !== undefined) file(byKey, key, eid, b)
434
+ }
435
+ return byKey
436
+ }
437
+
438
+ // The number index over one property, filed the same way the first time a
439
+ // query asks for a range of it.
440
+ let bands = (comp: string, prop: string): Map<number, Map<Eid, Bundle>> => {
441
+ let at = keyFor(comp, prop)
442
+ let held = banded.get(at)
443
+ if (held) return held[2]
444
+ let byBand = new Map<number, Map<Eid, Bundle>>()
445
+ banded.set(at, [comp, prop, byBand])
446
+ for (let [eid, b] of holdersOf(comp)) {
447
+ let band = bandOf(valueOf(b, comp, prop))
448
+ if (band !== undefined) file(byBand, band, eid, b)
449
+ }
450
+ return byBand
451
+ }
452
+
453
+ // The bands a range spans: counted off one by one when there are fewer of
454
+ // them than bands filed, else picked out of the ones filed.
455
+ let ranged = (comp: string, prop: string, lo: number, hi: number) => {
456
+ let byBand = bands(comp, prop)
457
+ let a = Math.floor(lo)
458
+ let z = Math.floor(hi)
459
+ let out: ReadonlyMap<Eid, Bundle>[] = []
460
+ if (z - a < byBand.size) {
461
+ for (let k = a; k <= z; k++) {
462
+ let at = byBand.get(k)
463
+ if (at) out.push(at)
464
+ }
465
+ } else {
466
+ for (let [k, at] of byBand) if (k >= a && k <= z) out.push(at)
467
+ }
468
+ return out
469
+ }
470
+
471
+ // What one read sees: every row, by id, by component and by value, and what
472
+ // a batch under evaluation removed. A fresh view per read, so what a run
473
+ // keeps against it (a walk's closure) never outlives the rows it was worked
474
+ // out from.
475
+ let view = (gone?: Index['gone']): Index => {
476
+ let list: Bundle[] | undefined
477
+ return {
478
+ get list() {
479
+ return list ??= [...rows.values()]
480
+ },
481
+ of: (eid) => rows.get(eid),
482
+ wearing: holdersOf,
483
+ keyed: (comp, prop, key) => keys(comp, prop).get(key) ?? NONE,
484
+ ranged,
485
+ gone,
486
+ }
487
+ }
488
+
489
+ // Resolve storage policy once per component, not on every moving cell.
490
+ // Existing components keep their policy when the vocabulary grows.
491
+ let cells = new Map<string, { refs: Set<string>; kept: Set<string> }>()
492
+ let cellsOf = (comp: string) => {
493
+ let held = cells.get(comp)
494
+ if (!held) {
495
+ let refs = new Set<string>()
496
+ let kept = new Set<string>()
497
+ for (let name of vocab.props(comp)) {
498
+ let prop = vocab.prop(comp, name)!
499
+ if (prop.category == 'ref') refs.add(name)
500
+ if (!prop.computed || base.adopt) kept.add(name)
501
+ }
502
+ cells.set(comp, held = { refs, kept })
503
+ }
504
+ return held
505
+ }
506
+ let isRef = (comp: string, prop: string) => cellsOf(comp).refs.has(prop)
507
+
508
+ // The properties of a patch this vocabulary stores. A component whose patch
509
+ // names none is still a component: its presence is the fact. A store that
510
+ // mirrors another graph keeps the computed values that graph sent, since it
511
+ // holds no rule to derive them.
512
+ // Bytes cross the storage boundary by value, just as a database BLOB does.
513
+ // Keep the ordinary immutable-bundle path allocation-free.
514
+ let binary = binariesOf(vocab)
515
+ let detached = (b: Bundle): Bundle => {
516
+ let out = b
517
+ for (let { comp, props } of binary) {
518
+ let held = b[comp] as Comp | undefined
519
+ if (!held) continue
520
+ for (let prop of props) {
521
+ let value = held[prop]
522
+ if (value instanceof Uint8Array) {
523
+ if (out === b) out = { ...b }
524
+ if (out[comp] === held) out[comp] = { ...held }
525
+ ;(out[comp] as Comp)[prop] = value.slice()
526
+ }
527
+ }
528
+ }
529
+ return out
530
+ }
531
+
532
+ // Reads carry the computed values a server would send, without storing
533
+ // them. Compute against the whole index before cutting requested components.
534
+ let statuses = statusesOf(vocab)
535
+ let derived = Object.entries(base.computed ?? {}).map(([path, read]) =>
536
+ [...path.split('.'), read] as [string, string, Computed[string]]
537
+ )
538
+ let computed = (b: Bundle, among: Index, names?: string[]): Bundle => {
539
+ let out = b
540
+ for (let name of statuses) {
541
+ if (names && !names.includes(name)) continue
542
+ let value = b[name] as Comp | undefined
543
+ if (!value) continue
544
+ out = { ...out, [name]: { ...value, status: statusOf(vocab, name, b) } }
545
+ }
546
+ for (let [name, prop, read] of derived) {
547
+ if (names && !names.includes(name)) continue
548
+ if (!b[name]) continue
549
+ let value = read(b, among)
550
+ let comp = { ...out[name] as Comp }
551
+ if (value == null) delete comp[prop]
552
+ else comp[prop] = value
553
+ out = { ...out, [name]: comp }
554
+ }
555
+ return out
556
+ }
557
+
558
+ // Remove hidden relations before the matcher can inspect a value or follow
559
+ // a reference. Every index for this read is built from this visible dataset.
560
+ // A deleted entity is judged by its history (@yaks/sql `ghostly`), and
561
+ // this store keeps none, so no scope sees it here.
562
+ let visible = (opts: ReadOpts): Index | Bundle[] => {
563
+ let scope = opts.visibility
564
+ if (!scope) return view()
565
+ let source = view()
566
+ let screen = { now: opts.now ?? base.now, exactIds: true }
567
+ let allowed = scope.entity
568
+ ? matcher(scope.entity, vocab, screen)(source)
569
+ : source.list
570
+ let components = Object.entries(scope.components ?? {}).map(([name, q]) =>
571
+ [
572
+ name,
573
+ new Set(matcher(q, vocab, screen)(source).map((b) => b.entity.eid)),
574
+ ] as const
575
+ )
576
+ let present = new Set(allowed.map((b) => b.entity.eid))
577
+ return index(allowed.map((b) => {
578
+ let out = { ...b }
579
+ for (let [name, owners] of components) {
580
+ if (!owners.has(b.entity.eid)) delete out[name]
581
+ }
582
+ for (let [name, value] of comps(out)) {
583
+ if (!value) continue
584
+ for (let prop of vocab.props(name)) {
585
+ if (
586
+ isRef(name, prop) && typeof value[prop] == 'string' &&
587
+ !present.has(value[prop] as string)
588
+ ) {
589
+ let comp = { ...out[name] as Comp }
590
+ delete comp[prop]
591
+ out[name] = comp
592
+ }
593
+ }
594
+ }
595
+ // Archetype metadata describes stored components, not this caller's view.
596
+ let { archetype: _, ...entity } = b.entity as Entity
597
+ out.entity = entity
598
+ return out
599
+ }))
600
+ }
601
+
602
+ let read = (
603
+ query: Query,
604
+ opts: ReadOpts = {},
605
+ comps?: string[],
606
+ ): Bundle[] => {
607
+ let among = visible(opts) as Index
608
+ let found = matcher(query, vocab, {
609
+ now: opts.now ?? base.now,
610
+ storageOrder: opts.storageOrder,
611
+ unordered: opts.unordered,
612
+ eids: opts.eids,
613
+ graves: opts.graves,
614
+ computed: base.computed,
615
+ })(among)
616
+ let gathered = statuses.length || derived.length
617
+ ? found.map((b) => computed(b, among, comps))
618
+ : found
619
+ return (comps ? gathered.map(only(new Set(comps))) : gathered).map(detached)
620
+ }
621
+
622
+ // The raw-rows path: one `{ eid }` per match, or an aggregate's rows in the
623
+ // shape @yaks/sql returns, so a caller reads the same shape from either
624
+ // storage.
625
+ let raw = (query: Query, opts: ReadOpts = {}): Row[] =>
626
+ answer(query, vocab, {
627
+ now: opts.now ?? base.now,
628
+ storageOrder: opts.storageOrder,
629
+ unordered: opts.unordered,
630
+ eids: opts.eids,
631
+ graves: opts.graves,
632
+ computed: base.computed,
633
+ })(visible(opts)).map((row) => {
634
+ if (!Object.values(row).some((v) => v instanceof Uint8Array)) return row
635
+ return Object.fromEntries(
636
+ Object.entries(row).map(([key, value]) => [
637
+ key,
638
+ value instanceof Uint8Array ? value.slice() : value,
639
+ ]),
640
+ )
641
+ })
642
+
643
+ // The series an entity is numbered in, where this store numbers by series
644
+ // (@yaks/id `seriesOf`).
645
+ let series = base.number
646
+ ? seriesOf(vocab, base.number === true ? undefined : base.number)
647
+ : undefined
648
+ // The next number in a series, past the last it gave, stepping over one an
649
+ // entity holds in it.
650
+ let nextIn = (prefix: string): number => {
651
+ let n = (highs.get(prefix) ?? 0) + 1
652
+ while (holders(n).some((h) => clash(h, { prefix, num: n }))) n++
653
+ highs.set(prefix, n)
654
+ return n
655
+ }
656
+ // The number an identity gets when no bundle states one: the next this
657
+ // store has to give, in the series its components pick where it numbers by
658
+ // series, or none in a store mirroring another graph, which waits to be
659
+ // told.
660
+ let numbered = (held: string[]): Partial<Pair> => {
661
+ if (base.adopt || !series) return {}
662
+ let prefix = series(held)
663
+ return prefix ? { num: nextIn(prefix), prefix } : {}
664
+ }
665
+
666
+ let patch = (bundles: Bundle[]): Entity[] => {
667
+ let born: Entity[] = []
668
+ // New identities need no component indexes until their payload is ready.
669
+ let reserved = new Map<Eid, Bundle>()
670
+ let keep = (eid: Eid, b: Bundle) =>
671
+ reserved.has(eid) ? reserved.set(eid, b) : put(eid, b)
672
+ // The pair each bundle states for its entity: one to take, or `null` for
673
+ // none. A mirror is told it, whatever its vocabulary says; any other store
674
+ // takes one where its vocabulary declares numbers (@yaks/id), and checks
675
+ // it first, against every pair its entities hold.
676
+ let stated = new Map<Eid, Pair | null>()
677
+ let told = base.adopt || !!vocab.prop('entity', 'num')
678
+ for (let b of told ? bundles : []) {
679
+ if (buried(rows.get(b.entity.eid))) continue
680
+ let pair = stating(b.entity, pairOf(b.entity.eid))
681
+ if (pair !== undefined) stated.set(b.entity.eid, pair)
682
+ }
683
+ if (!base.adopt && stated.size) {
684
+ let held = new Map<number, ({ eid: Eid } & Pair)[]>()
685
+ for (let pair of stated.values()) {
686
+ if (pair) held.set(pair.num, holders(pair.num))
687
+ }
688
+ renumbering(stated, pairOf, held)
689
+ }
690
+ // A stated pair, as an identity carries it; the next number this store
691
+ // gives stays past every one it holds.
692
+ let take = (eid: Eid): Partial<Pair> => {
693
+ let pair = stated.get(eid)
694
+ if (pair == null) return {}
695
+ if (pair.prefix) {
696
+ highs.set(pair.prefix, Math.max(highs.get(pair.prefix) ?? 0, pair.num))
697
+ }
698
+ return pair.prefix ? pair : { num: pair.num }
699
+ }
700
+ let unnumbered = ({ num: _, prefix: __, ...entity }: Entity): Entity =>
701
+ entity
702
+ // Only a numbered store needs to plan which components determine the
703
+ // series of a new identity. Reference-only identities wait for a bundle.
704
+ let giving = new Map<Eid, string[]>()
705
+ if (series && !base.adopt) {
706
+ for (let b of bundles) {
707
+ for (let name in b) {
708
+ if (metadata(name) || b[name] == null) continue
709
+ let eid = b.entity.eid
710
+ let held = giving.get(eid)
711
+ if (held) held.push(name)
712
+ else giving.set(eid, [name])
713
+ }
714
+ }
715
+ }
716
+ // An eid a reference only names gets a record to hold the pointer and no
717
+ // number, until a bundle of its own arrives (@yaks/sqlite `patch`): one
718
+ // giving it a component, or one stating its number.
719
+ // Create a record for every eid this write touches or points at, so that a
720
+ // reference may name a target created by the same write, in any order.
721
+ let birth = (eid: Eid) => {
722
+ let rec = reserved.get(eid) ?? rows.get(eid)
723
+ let told = stated.has(eid)
724
+ if (rec) {
725
+ let was = pairOf(eid) ?? null
726
+ let now = stated.get(eid) ?? null
727
+ if (
728
+ told &&
729
+ (was?.num !== now?.num || (was?.prefix ?? null) !== now?.prefix)
730
+ ) {
731
+ // A pair stated for an entity holding another: changed, or cleared
732
+ // by `null`.
733
+ save(eid)
734
+ let entity = { ...unnumbered(rec.entity), ...take(eid) }
735
+ keep(eid, { ...rec, entity })
736
+ } else if (
737
+ // A record numbered nothing so far is numbered when a bundle of its
738
+ // own gives the first component in its series.
739
+ !told && !base.adopt && giving.has(eid) && !!series &&
740
+ !buried(rec) && rec.entity.num == null &&
741
+ !!series(giving.get(eid) ?? [])
742
+ ) {
743
+ let entity = {
744
+ ...rec.entity,
745
+ ...numbered([
746
+ ...comps(rec).map(([name]) => name),
747
+ ...giving.get(eid) ?? [],
748
+ ]),
749
+ }
750
+ if (entity.num == null) return
751
+ save(eid)
752
+ keep(eid, { ...rec, entity })
753
+ born.push(entity)
754
+ }
755
+ return
756
+ }
757
+ save(eid)
758
+ let identity = cold.get(eid)
759
+ cold.delete(eid)
760
+ let entity = identity
761
+ ? told ? { ...unnumbered(identity), ...take(eid) } : identity
762
+ : {
763
+ eid,
764
+ ...told
765
+ ? take(eid)
766
+ : giving.has(eid)
767
+ ? numbered(giving.get(eid) ?? [])
768
+ : {},
769
+ }
770
+ reserved.set(eid, { entity })
771
+ if (!identity) born.push(entity)
772
+ }
773
+ for (let b of bundles) {
774
+ if (buried(rows.get(b.entity.eid))) continue
775
+ birth(b.entity.eid)
776
+ for (let [name, comp] of comps(b)) {
777
+ for (let prop in comp) {
778
+ let val = comp[prop]
779
+ if (val != null && isRef(name, prop)) birth(String(val))
780
+ }
781
+ }
782
+ }
783
+ for (let b of bundles) {
784
+ let eid = b.entity.eid
785
+ let rec = reserved.get(eid) ?? rows.get(eid)
786
+ let was = rec
787
+ let patches = comps(b)
788
+ let archetype = b.entity.archetype
789
+ if (
790
+ rec && archetype !== undefined && archetype !== rec.entity.archetype
791
+ ) {
792
+ let entity = { ...rec.entity, archetype }
793
+ rec = { ...rec, entity }
794
+ }
795
+ if (!rec) continue
796
+ let held = buried(rec) ? rec : merged(rec, patches)
797
+ if (reserved.delete(eid)) {
798
+ put(eid, held)
799
+ continue
800
+ }
801
+ if (held == was) continue
802
+ save(eid)
803
+ put(eid, held)
804
+ }
805
+ for (let [eid, rec] of reserved) put(eid, rec)
806
+ return born
807
+ }
808
+
809
+ // The record a patch leaves. A null component drops the row; anything else
810
+ // merges in, so an omitted property keeps what it held and a null one clears
811
+ // it. A patch that changes nothing leaves the very record it found: an
812
+ // unchanged write is no write.
813
+ let merged = (rec: Bundle, patches: [string, Comp | null][]): Bundle => {
814
+ let held = rec
815
+ let own = () => held == rec ? held = { ...rec } : held
816
+ for (let [name, comp] of patches) {
817
+ let was = held[name] as Comp | undefined
818
+ if (comp == null) {
819
+ if (was !== undefined) delete own()[name]
820
+ continue
821
+ }
822
+ let next = was ?? {}
823
+ let kept = cellsOf(name).kept
824
+ for (let p in comp) {
825
+ if (!kept.has(p)) continue
826
+ let value = comp[p]
827
+ if (
828
+ value == null
829
+ ? !Object.hasOwn(next, p)
830
+ : Object.hasOwn(next, p) && same(next[p], value)
831
+ ) continue
832
+ if (next === was) next = { ...was }
833
+ if (value == null) delete next[p]
834
+ else {
835
+ // Bytes retain the storage boundary's by-value ownership.
836
+ next[p] = value instanceof Uint8Array &&
837
+ vocab.prop(name, p)?.scalar == 'binary'
838
+ ? value.slice()
839
+ : value
840
+ }
841
+ }
842
+ if (next !== was) own()[name] = next
843
+ }
844
+ return held
845
+ }
846
+
847
+ // The records themselves. A record is never mutated once stored, so the one a
848
+ // read hands back is safe to keep, and costs no copy; a record cut to the
849
+ // named components is a copy only when it carries others.
850
+ let get = (eids: Eid[], names?: string[], opts: ReadOpts = {}): Bundle[] => {
851
+ let cut = only(names ? new Set(names) : null)
852
+ let out: Bundle[] = []
853
+ // Plain committed gets need neither a matcher view nor its closures.
854
+ let among = opts.visibility || statuses.length || derived.length
855
+ ? visible(opts) as Index
856
+ : undefined
857
+ let scoped = opts.visibility
858
+ ? new Map(among!.list.map((b) => [b.entity.eid, b as Bundle]))
859
+ : rows
860
+ for (let eid of eids) {
861
+ let rec = scoped.get(eid)
862
+ if (rec) {
863
+ out.push(detached(cut(among ? computed(rec, among, names) : rec)))
864
+ }
865
+ }
866
+ return out
867
+ }
868
+
869
+ // The batch folded in, the matches asked, the log rewound. What the batch
870
+ // took a component off is its own list, since a removed component leaves
871
+ // nothing in a row to ask about; one written again later in the batch is
872
+ // not gone. A deleted entity is removed, and matches nothing.
873
+ let ask = (matches: Match[], bundles: Bundle[]): Binding[][] => {
874
+ if (!matches.length) return []
875
+ let mark = log.length
876
+ let minted = counted()
877
+ try {
878
+ tx.remove(bundles.filter(dead).map((b) => b.entity))
879
+ patch(bundles.filter((b) => !dead(b)))
880
+ let gone = new Map<string, Set<Eid>>()
881
+ for (let b of bundles) {
882
+ for (let [name, c] of comps(b)) {
883
+ let at = gone.get(name) ?? new Set()
884
+ if (c == null) gone.set(name, at.add(b.entity.eid))
885
+ else at.delete(b.entity.eid)
886
+ }
887
+ }
888
+ let anchor = bundles.length
889
+ ? new Set(bundles.map((b) => b.entity.eid))
890
+ : undefined
891
+ return bindings(
892
+ matches,
893
+ view((comp) => gone.get(comp)),
894
+ anchor,
895
+ vocab,
896
+ { now: base.now, computed: base.computed },
897
+ )
898
+ } finally {
899
+ rewind(mark, minted)
900
+ }
901
+ }
902
+
903
+ // Resolve deletion through the same reference indexes queries use.
904
+ let doom = (eids: Eid[]): Doom | null => {
905
+ let cascade = vocab.deaths('cascade')
906
+ let soft = [...vocab.deaths('release'), ...vocab.deaths('detach')]
907
+ if ([...cascade, ...soft].some(([c, p]) => base.computed?.[`${c}.${p}`])) {
908
+ return null
909
+ }
910
+ let owners = (targets: Eid[], props: [string, string][]): Bundle[] => {
911
+ let found = new Map<Eid, Bundle>()
912
+ for (let [comp, prop] of props) {
913
+ if (!worn.has(vocab.stored(comp))) continue
914
+ let held = keys(comp, prop)
915
+ for (let target of targets) {
916
+ for (let [eid, b] of held.get(keyOf(target)!) ?? NONE) {
917
+ found.set(eid, b)
918
+ }
919
+ }
920
+ }
921
+ return [...found.values()].sort((a, b) =>
922
+ (a.entity.num ?? 0) - (b.entity.num ?? 0)
923
+ )
924
+ }
925
+ let gone = eids.map((eid) => ({ eid, depth: 0 }))
926
+ let dead = new Set(eids)
927
+ let front = eids
928
+ for (let depth = 1; front.length; depth++) {
929
+ let next: Eid[] = []
930
+ for (let b of owners(front, cascade)) {
931
+ let eid = b.entity.eid
932
+ if (dead.has(eid)) continue
933
+ dead.add(eid)
934
+ gone.push({ eid, depth })
935
+ next.push(eid)
936
+ }
937
+ front = next
938
+ }
939
+ let targets = [...dead]
940
+ let loose: Doom['loose'] = []
941
+ for (let b of owners(targets, soft)) {
942
+ let eid = b.entity.eid
943
+ if (dead.has(eid)) continue
944
+ for (let [comp, prop] of soft) {
945
+ let target = valueOf(b, comp, prop)
946
+ if (target != null && dead.has(String(target))) {
947
+ loose.push({ eid, comp, prop })
948
+ }
949
+ }
950
+ }
951
+ return { gone, loose }
952
+ }
953
+
954
+ let tx: Tx = {
955
+ read,
956
+ doom,
957
+ get,
958
+ bindings: ask,
959
+ patch,
960
+ evict: (eids) => {
961
+ for (let eid of eids) {
962
+ let rec = rows.get(eid)
963
+ if (!rec || buried(rec)) continue
964
+ save(eid)
965
+ let { num, prefix } = rec.entity
966
+ cold.set(eid, { eid, num, ...prefix == null ? {} : { prefix } })
967
+ put(eid, undefined)
968
+ }
969
+ },
970
+ remove: (entities) => {
971
+ for (let { eid } of entities) {
972
+ let entity = rows.get(eid)?.entity ?? cold.get(eid)
973
+ if (!entity) continue
974
+ save(eid)
975
+ cold.delete(eid)
976
+ let grave = tombstoned(entity)
977
+ laid.set(grave, new Date().toISOString())
978
+ put(eid, grave)
979
+ }
980
+ },
981
+ discard: (entities) => {
982
+ for (let { eid } of entities) {
983
+ save(eid)
984
+ cold.delete(eid)
985
+ put(eid, undefined)
986
+ }
987
+ },
988
+ prune: (eids) => {
989
+ let retained = new Set(
990
+ [...trash.values()].flatMap((r) => r.bundles.map((b) => b.entity.eid)),
991
+ )
992
+ for (let eid of eids) {
993
+ if (retained.has(eid)) continue
994
+ save(eid)
995
+ cold.delete(eid)
996
+ put(eid, undefined)
997
+ }
998
+ },
999
+ revive: (eids) => {
1000
+ for (let eid of eids) {
1001
+ let rec = rows.get(eid)
1002
+ if (!rec || !buried(rec)) continue
1003
+ save(eid)
1004
+ put(eid, { entity: rec.entity })
1005
+ }
1006
+ },
1007
+ }
1008
+
1009
+ // Tombstones laid before `before` that no stored reference names, oldest
1010
+ // first. The cursor is the last grave's time and eid, which still marks
1011
+ // the place once that grave is pruned.
1012
+ let graves = (
1013
+ before: string,
1014
+ page: { after?: string; limit: number; referenced?: boolean },
1015
+ ): Graves => {
1016
+ let refs = vocab.refProps().filter(([c, p]) => !vocab.prop(c, p)?.computed)
1017
+ let named = (eid: Eid) =>
1018
+ [...trash.values()].some((r) =>
1019
+ r.bundles.some((b) => b.entity.eid == eid)
1020
+ ) ||
1021
+ refs.some(([c, p]) =>
1022
+ worn.has(vocab.stored(c)) && !!keys(c, p).get(keyOf(eid)!)?.size
1023
+ )
1024
+ let mark = (at: string, eid: Eid) => JSON.stringify([at, eid])
1025
+ let found = [...rows].flatMap(([eid, b]) => {
1026
+ let at = laid.get(b)
1027
+ return at != null && at < before ? [mark(at, eid)] : []
1028
+ }).sort().filter((m) => page.after == null || m > page.after)
1029
+ let seen = found.slice(0, page.limit)
1030
+ let eids = seen.map((m) => JSON.parse(m)[1] as Eid).filter((e) =>
1031
+ page.referenced || !named(e)
1032
+ )
1033
+ return seen.length < page.limit ? { eids } : { eids, next: seen.at(-1) }
1034
+ }
1035
+
1036
+ return {
1037
+ extend: (next) => {
1038
+ if (next === vocab) return true
1039
+ if (depth || !extendsVocab(vocab, next)) return false
1040
+ for (let name of next.all) {
1041
+ if (vocab.comp(name)) continue
1042
+ cells.delete(name)
1043
+ uniques.delete(next.stored(name))
1044
+ }
1045
+ vocab = next
1046
+ hasUnique = uniqueIn(vocab)
1047
+ binary = binariesOf(vocab)
1048
+ statuses = statusesOf(vocab)
1049
+ return true
1050
+ },
1051
+ reload: (next) => {
1052
+ if (next === vocab) return true
1053
+ if (depth || !relabelsVocab(vocab, next)) return false
1054
+ let before = [...rows].map(([eid, b]) => [eid, laid.get(b)] as const)
1055
+ vocab = next
1056
+ hasUnique = uniqueIn(vocab)
1057
+ binary = binariesOf(vocab)
1058
+ statuses = statusesOf(vocab)
1059
+ rows.relabel()
1060
+ for (let index of [worn, filed, banded, uniques, cells]) index.clear()
1061
+ for (let [eid, at] of before) {
1062
+ let row = rows.get(eid)!
1063
+ if (at != null) laid.set(row, at)
1064
+ rows.delete(eid)
1065
+ put(eid, row)
1066
+ }
1067
+ return true
1068
+ },
1069
+ // A computed override may read another component, even when its named
1070
+ // component is absent, so only a stored property's value says it is worn.
1071
+ worn: (comp, prop) =>
1072
+ !!vocab.prop(comp, prop) && !vocab.prop(comp, prop)?.computed &&
1073
+ !base.computed?.[`${comp}.${prop}`],
1074
+ install: () => {},
1075
+ read,
1076
+ rows: raw,
1077
+ get,
1078
+ buried: graves,
1079
+ purgeTrash: (id) => {
1080
+ for (let [key, entry] of trash) {
1081
+ let bundles = typeof id == 'string'
1082
+ ? key == id ? [] : entry.bundles
1083
+ : entry.bundles.filter((b) => !id.includes(b.entity.eid))
1084
+ if (bundles.length == entry.bundles.length) continue
1085
+ if (depth) trashLog.push([key, entry])
1086
+ if (bundles.length) trash.set(key, { ...entry, bundles })
1087
+ else trash.delete(key)
1088
+ }
1089
+ },
1090
+ trash: (eids, page = {}) => {
1091
+ let cursor = page.before ??
1092
+ (page.after ? trash.get(page.after) : undefined)
1093
+ if (page.after && !cursor) return []
1094
+ return structuredClone(
1095
+ [...trash.values()].filter((r) =>
1096
+ (!eids || r.bundles.some((b) => eids.includes(b.entity.eid))) &&
1097
+ (!page.id || r.id == page.id) &&
1098
+ (!cursor || trashOrder(r, cursor) > 0)
1099
+ ).sort(trashOrder).slice(0, trashLimit(page)),
1100
+ )
1101
+ },
1102
+ tx: (body) => {
1103
+ // A nested transaction is a savepoint: it rolls back to where it opened,
1104
+ // and its entries stay in the log for the outer one to undo in its turn.
1105
+ let trashMark = trashLog.length
1106
+ let mark = log.length
1107
+ let minted = counted()
1108
+ depth++
1109
+ let undo = (e: unknown): never => {
1110
+ while (trashLog.length > trashMark) {
1111
+ let [id, entry] = trashLog.pop()!
1112
+ if (entry) trash.set(id, entry)
1113
+ else trash.delete(id)
1114
+ }
1115
+ rewind(mark, minted)
1116
+ depth--
1117
+ throw e
1118
+ }
1119
+ let done = <R>(out: R): R => {
1120
+ if (--depth == 0) log.length = trashLog.length = 0
1121
+ return out
1122
+ }
1123
+ try {
1124
+ let out = body(preserving(tx, vocab, (id, at, bundles) => {
1125
+ let before = trash.get(id)
1126
+ trashLog.push([id, before])
1127
+ trash.set(id, {
1128
+ id,
1129
+ at,
1130
+ bundles: [...before?.bundles ?? [], ...bundles],
1131
+ })
1132
+ }))
1133
+ return (isPromise(out) ? out.then(done, undo) : done(out)) as typeof out
1134
+ } catch (e) {
1135
+ return undo(e)
1136
+ }
1137
+ },
1138
+ }
1139
+ }