@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/backed.ts ADDED
@@ -0,0 +1,274 @@
1
+ // The journal read as entities. Its vocabulary declares two computed
2
+ // components (vocab.json): `_tx`, a committed transaction, and `_change`, one
3
+ // component a transaction wrote or removed. No table holds them. These are
4
+ // their backings (@yaks/sql `Backing`): the journal's own rows, renamed to the
5
+ // components' properties, which a store reads as it reads a component table —
6
+ // so an entity's history is `._change.target=T-5`, a session's writes are
7
+ // `._tx.via=S-7`, and nothing is copied, nor journaled, to answer either.
8
+ //
9
+ // A reference column already holds what a component table holds, the
10
+ // referent's integer id: `target`, `by` and `via` point into the entity table,
11
+ // and `tx` at a transaction's own id. `comp` is the `_comp` entity describing
12
+ // the component (@yaks/vocab), the entity whose eid is the component's
13
+ // identity, which is what the row recorded (./names.ts); a graph that does not
14
+ // describe its vocabulary, or no longer describes a component the journal
15
+ // names, has none to point at. A row recorded by label before identities
16
+ // points at the `_comp` row that label has now.
17
+ //
18
+ // `component` is the component's label, and a change's `value` its after-image
19
+ // keyed by its properties' labels, as the vocabulary reads the identities the
20
+ // rows recorded: a reader reads history in the words it reads the graph in,
21
+ // and a renamed word's history under its new label. The value is the
22
+ // properties the change wrote as one object, read from its field rows; a
23
+ // removal has none. A property the store keeps in another form, the address
24
+ // @yaks/blob keeps in place of a body, reads back through the store's `text`
25
+ // (@yaks/sql `Derived`), so a change says the text a reader of the graph read;
26
+ // where that text is no longer kept, it says what was recorded.
27
+
28
+ import {
29
+ among,
30
+ and,
31
+ as,
32
+ col,
33
+ type Derived,
34
+ desc,
35
+ eq,
36
+ exists,
37
+ type Expr,
38
+ fn,
39
+ join,
40
+ left,
41
+ lit,
42
+ type Select,
43
+ select,
44
+ sub,
45
+ table,
46
+ when,
47
+ } from '@yaks/sql/core'
48
+ import type { Backings, Held } from 'jsr:@yaks/sql@0.2.36'
49
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
50
+ import { type Names, names } from './names.js'
51
+
52
+ let jc = (c: string) => col(c, 'jc')
53
+ let jf = (c: string) => col(c, 'jf')
54
+ let cc = (c: string) => col(c, 'cc')
55
+
56
+ // The address a field row `f` recorded: its value, or, as the journal once
57
+ // recorded content, the eid of the entity holding it (`ref`).
58
+ let addressOf = (f: (c: string) => Expr) =>
59
+ fn(
60
+ 'coalesce',
61
+ fn('json_extract', f('value'), lit('$')),
62
+ sub(select({
63
+ cols: [col('eid', 'jr')],
64
+ from: table('entity', 'jr'),
65
+ where: eq(col('id', 'jr'), f('ref')),
66
+ })),
67
+ )
68
+ let address = addressOf(jf)
69
+
70
+ // Any of the names a row may hold for a word (./names.ts).
71
+ let any = (names: string[]) => names.map((n) => lit(n))
72
+
73
+ // One field's value as JSON: through its property's `text` where the store
74
+ // keeps it in another form, and as recorded otherwise.
75
+ let fieldOf = (derived: Derived, named: Names): Expr => {
76
+ let recorded = fn('json', jf('value'))
77
+ let texts = Object.entries(derived).flatMap(([key, d]) =>
78
+ d.text ? [[key.split('.'), d.text] as const] : []
79
+ )
80
+ return texts.length
81
+ ? when(
82
+ texts.map(([[comp, prop], text]) => [
83
+ and(
84
+ among(jc('component'), any(named.comps(comp))),
85
+ among(jf('field'), any(named.props(comp, prop))),
86
+ ),
87
+ fn('coalesce', fn('json_quote', text(address)), recorded),
88
+ ]),
89
+ recorded,
90
+ )
91
+ : recorded
92
+ }
93
+
94
+ // The `_comp` a change's component names, where the graph has one: its
95
+ // column, and the join that reads it. The join also says the names a row may
96
+ // have recorded for that `_comp` (`recordedAt`), which the first term implies:
97
+ // so `._change.comp=<_comp>` seeks the index on `component` from the `_comp`
98
+ // row, and does not walk the journal back to front testing each change, which
99
+ // for a component written rarely is the whole journal.
100
+ let described = (vocab: Vocab, named: Names) =>
101
+ vocab.comp('_comp')
102
+ ? {
103
+ comp: cc('id'),
104
+ joins: [
105
+ left(
106
+ table('entity', 'cc'),
107
+ and(
108
+ eq(cc('eid'), named.rowOf(jc('component'))),
109
+ among(jc('component'), named.recordedAt(cc('eid'))),
110
+ ),
111
+ ),
112
+ ],
113
+ }
114
+ : { comp: lit(null), joins: [] }
115
+
116
+ // One change's present after-images as one object, keyed by label. The field
117
+ // rows are read in the order they were written, through their (change,
118
+ // ordinal) index.
119
+ let valueOf = (derived: Derived, named: Names) =>
120
+ when([[
121
+ eq(jc('operation'), lit('upsert')),
122
+ sub(select({
123
+ cols: [fn(
124
+ 'json_group_object',
125
+ named.propLabelOf(jf('field')),
126
+ fieldOf(derived, named),
127
+ )],
128
+ from: table('journal_field', 'jf'),
129
+ where: and(eq(jf('change'), jc('id')), eq(jf('present'), lit(1))),
130
+ })),
131
+ ]])
132
+
133
+ // What each record tells of, by the record's own id (`id` for a change, `tx`
134
+ // for a transaction): every change's entity and component, by label. A scoped
135
+ // read sees a change when it may see that component of that entity, and a
136
+ // transaction when it may see one of its changes.
137
+ let tells = (id: string, named: Names) =>
138
+ select({
139
+ cols: [
140
+ as(jc(id), 'entity'),
141
+ as(jc('entity'), 'about'),
142
+ as(named.compLabelOf(jc('component')), 'component'),
143
+ ],
144
+ from: table('journal_change', 'jc'),
145
+ })
146
+
147
+ // Component `comp` as the journal last told each entity held it (@yaks/sql
148
+ // `Backing.held`), which is how a scoped read judges a deleted entity: an
149
+ // entity whose newest change to it wrote it, and each property's newest
150
+ // after-image, null where that is the tombstone a removal wrote. A reference
151
+ // is read back to the referent's integer id, as the component's table keeps
152
+ // it. Start with the owner, then seek its latest change: starting with changes
153
+ // let a scoped get walk their history or build a bloom filter over the journal
154
+ // before testing two owners. This single-table relation also folds into a
155
+ // LEFT JOIN without materializing every owner's history.
156
+ let heldIn = (named: Names) => (comp: string, props: Held[]): Select => {
157
+ let jn = (c: string) => col(c, 'jn')
158
+ let jl = (c: string) => col(c, 'jl')
159
+ let owner = col('id', '__held')
160
+ let ours = (c: (c: string) => Expr) =>
161
+ and(eq(c('entity'), owner), among(c('component'), any(named.comps(comp))))
162
+ let newest = ({ name, ref }: Held) =>
163
+ sub(select({
164
+ cols: [when([[
165
+ eq(jl('present'), lit(1)),
166
+ ref
167
+ ? sub(select({
168
+ cols: [col('id', 'jr')],
169
+ from: table('entity', 'jr'),
170
+ where: eq(
171
+ col('eid', 'jr'),
172
+ fn('json_extract', jl('value'), lit('$')),
173
+ ),
174
+ }))
175
+ : addressOf(jl),
176
+ ]])],
177
+ from: table('journal_field', 'jl'),
178
+ joins: [join(table('journal_change', 'jn'), eq(jn('id'), jl('change')))],
179
+ where: and(ours(jn), among(jl('field'), any(named.props(comp, name)))),
180
+ order: [desc(jl('id'))],
181
+ limit: lit(1),
182
+ }))
183
+ return select({
184
+ cols: [
185
+ as(owner, 'entity'),
186
+ ...props.map((p) => as(newest(p), p.as)),
187
+ ],
188
+ from: table('entity', '__held'),
189
+ where: exists(select({
190
+ cols: [lit(1)],
191
+ from: table('journal_change', 'jc'),
192
+ where: and(
193
+ eq(jc('operation'), lit('upsert')),
194
+ eq(
195
+ jc('id'),
196
+ sub(select({
197
+ cols: [fn('max', jn('id'))],
198
+ from: table('journal_change', 'jn'),
199
+ where: ours(jn),
200
+ })),
201
+ ),
202
+ ),
203
+ })),
204
+ })
205
+ }
206
+
207
+ /** The rows `_tx` and `_change` are read from: the journal's tables, a value
208
+ * the store keeps in another form read through `derived`, the store's read
209
+ * overrides. `_change` also tells what each entity last held (`held`). One
210
+ * registry per vocabulary and overrides, so every store given them compiles
211
+ * its reads once (@yaks/sql `Backing`). */
212
+ export let backed = (vocab: Vocab, derived: Derived = NONE): Backings => {
213
+ let byDerived = registries.get(vocab)
214
+ if (!byDerived) registries.set(vocab, byDerived = new WeakMap())
215
+ let got = byDerived.get(derived)
216
+ if (!got) byDerived.set(derived, got = registry(vocab, derived))
217
+ return got
218
+ }
219
+ let NONE: Derived = {}
220
+ let registries = new WeakMap<Vocab, WeakMap<Derived, Backings>>()
221
+
222
+ let registry = (vocab: Vocab, derived: Derived): Backings => {
223
+ let named = names(vocab)
224
+ let { comp, joins } = described(vocab, named)
225
+ let value = valueOf(derived, named)
226
+ return {
227
+ _tx: {
228
+ about: tells('tx', named),
229
+ rows: select({
230
+ cols: [
231
+ as(col('id'), 'entity'),
232
+ as(col('id'), 'seq'),
233
+ as(col('ts'), 'at'),
234
+ as(col('actor'), 'by'),
235
+ as(col('via'), 'via'),
236
+ as(col('host'), 'host'),
237
+ as(col('trace'), 'note'),
238
+ ],
239
+ from: table('journal_tx'),
240
+ }),
241
+ },
242
+ _change: {
243
+ about: tells('id', named),
244
+ held: heldIn(named),
245
+ rows: select({
246
+ cols: [
247
+ as(jc('id'), 'entity'),
248
+ as(jc('tx'), 'tx'),
249
+ as(jc('entity'), 'target'),
250
+ as(comp, 'comp'),
251
+ as(named.compLabelOf(jc('component')), 'component'),
252
+ as(value, 'value'),
253
+ ],
254
+ from: table('journal_change', 'jc'),
255
+ joins,
256
+ }),
257
+ // `component` is a label read from what a row recorded, which no index
258
+ // holds: compared row by row, `._change.component=step` walked the
259
+ // box's whole journal, past 10 s (T-5375). The names that may read as
260
+ // it seek the index on `component`, and each row found is then tested.
261
+ select: {
262
+ component: (labels) =>
263
+ select({
264
+ cols: [jc('id')],
265
+ from: table('journal_change', 'jc'),
266
+ where: and(
267
+ among(jc('component'), named.labeled(labels)),
268
+ among(named.compLabelOf(jc('component')), labels),
269
+ ),
270
+ }),
271
+ },
272
+ },
273
+ }
274
+ }
package/batch.js ADDED
@@ -0,0 +1,12 @@
1
+ // The types the journal returns. A transaction — one call to `graph.apply()`,
2
+ // whose bundles all commit or none do — is the unit the log is kept in: one
3
+ // committed write, who wrote it, and every movement it made. A delta is one of
4
+ // those movements: a property that changed, or a whole component that appeared
5
+ // or went.
6
+ //
7
+ // These are the shapes the log derives, not the shapes it stores: the tables
8
+ // keep after-images only (`./log.ts`), and the before-side of every movement is
9
+ // rebuilt at read time from the entity's own rows in the log. They live in
10
+ // their own file so `./undo.ts` can walk a transaction in either direction
11
+ // without knowing where the rows came from.
12
+ //# sourceMappingURL=batch.js.map
package/batch.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch.js","sources":["./batch.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,4EAA4E;AAC5E,+EAA+E;AAC/E,+EAA+E;AAC/E,WAAW;AACX,EAAE;AACF,6EAA6E;AAC7E,gFAAgF;AAChF,2EAA2E;AAC3E,2EAA2E;AAC3E,4CAA4C"}
package/batch.ts ADDED
@@ -0,0 +1,84 @@
1
+ // The types the journal returns. A transaction — one call to `graph.apply()`,
2
+ // whose bundles all commit or none do — is the unit the log is kept in: one
3
+ // committed write, who wrote it, and every movement it made. A delta is one of
4
+ // those movements: a property that changed, or a whole component that appeared
5
+ // or went.
6
+ //
7
+ // These are the shapes the log derives, not the shapes it stores: the tables
8
+ // keep after-images only (`./log.ts`), and the before-side of every movement is
9
+ // rebuilt at read time from the entity's own rows in the log. They live in
10
+ // their own file so `./undo.ts` can walk a transaction in either direction
11
+ // without knowing where the rows came from.
12
+
13
+ import type { Comp, Eid } from 'jsr:@yaks/graph@0.2.36'
14
+
15
+ /**
16
+ * One thing that moved. A delta with a `prop` names the property that moved and
17
+ * carries the value on each side of the write; a delta with no property is
18
+ * about the component as a whole — `after` set means the component appeared,
19
+ * `before` set means it went, and either way the set side holds the properties
20
+ * it had. A `tombstone` delta is about the entity itself: `after` set means it
21
+ * was deleted, `before` set means a write brought it back.
22
+ */
23
+ export type Delta = {
24
+ /** the entity that changed */
25
+ target: Eid
26
+ /** the component that changed */
27
+ comp: string
28
+ /** the property that moved, or `null` for the whole component */
29
+ prop: string | null
30
+ /** what it held before (`null` for nothing) */
31
+ before: unknown
32
+ /** what it holds after (`null` for nothing) */
33
+ after: unknown
34
+ }
35
+
36
+ /** One committed transaction: where it sits in the log, who wrote it, and what
37
+ * moved. */
38
+ export type Batch = {
39
+ /** its place in the total order — the cursor a feed pages by */
40
+ seq: number
41
+ /** when it committed, ISO-8601 */
42
+ at: string
43
+ /** the identity it was written for, from the transaction's `$actor` */
44
+ by: Eid | null
45
+ /** the instrument it was written through */
46
+ via: Eid | null
47
+ /** what moved, in the order it moved */
48
+ deltas: Delta[]
49
+ }
50
+
51
+ /**
52
+ * One recorded operation: a component patched to `value`, or removed when
53
+ * `value` is null. This is the unit the tables store directly, and the unit a
54
+ * client that applies component patches can replay — a transaction is a list of
55
+ * these, in the order they were applied.
56
+ */
57
+ export type Patch = {
58
+ /** the entity the operation was about */
59
+ target: Eid
60
+ /** the component it patched, or `entity` for the entity row itself */
61
+ comp: string
62
+ /** the properties it wrote, or `null` for a removal */
63
+ value: Comp | null
64
+ }
65
+
66
+ /** One committed transaction as the tables hold it: who wrote it, the note the
67
+ * writer left beside it, and what it did. */
68
+ export type Entry = {
69
+ /** its place in the total order — the cursor a feed pages by */
70
+ seq: number
71
+ /** when it committed, ISO-8601 */
72
+ at: string
73
+ /** the identity it resolved to, or null when nobody was named */
74
+ by: Eid | null
75
+ /** the instrument it was written through */
76
+ via: Eid | null
77
+ /** whatever the writer wrote down beside the transaction, verbatim */
78
+ note: string | null
79
+ /** the host that wrote it (@yaks/journal `LogOpts.host`), or null for a
80
+ * transaction recorded before hosts were */
81
+ host: string | null
82
+ /** what it did, in the order it did it */
83
+ patches: Patch[]
84
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"compilerOptions":{"lib":["dom","esnext"]},"publish":{"exclude":["**/*_test.ts","./testing.ts"]},"name":"@yaks/journal","version":"0.2.36","license":"Apache-2.0","description":"Records every committed graph transaction, and who wrote it, inside that same transaction: entity history and undo, and a short-lived feed that carries every commit to the other processes on the store.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./graph":"./graph.ts","./tools":"./tools.ts","./service":"./service.ts","./views":"./views.ts","./kept":"./kept.ts"},"imports":{"@yaks/journal":"./mod.ts","@yaks/journal/vocab":"./vocab.ts","@yaks/journal/graph":"./graph.ts","@yaks/journal/tools":"./tools.ts","@yaks/journal/service":"./service.ts","@yaks/journal/views":"./views.ts","@yaks/journal/kept":"./kept.ts"}}
package/feed.js ADDED
@@ -0,0 +1,295 @@
1
+ // The feed: every commit, for the other hosts that opened the same store.
2
+ //
3
+ // A graph's `effect` phase shows it only its own commits. Anything else that
4
+ // opened the same store — a `yak` command beside `yak serve`, a worker serving
5
+ // the effects role — commits where this graph cannot see. So each commit
6
+ // writes one row to `journal_feed`, inside its own transaction: the host that
7
+ // made it and what it wrote, the names of the components and properties of
8
+ // each entity and no values. A follower pages through the rows from a cursor,
9
+ // keeps the ones another host wrote, and reads their values where the graph
10
+ // keeps them (`filled`); what this host wrote, its own graph already saw.
11
+ //
12
+ // The feed is plumbing, not history. The journal keeps what the vocabulary
13
+ // says is history and leaves out what it declares `journal: false`; the feed
14
+ // carries every commit, so a lease another process renews reaches a
15
+ // subscription here the way a task's new title does. A row is kept for
16
+ // {@link KEEP} and then pruned by a later write, so the table holds minutes of
17
+ // commits and does not grow with them.
18
+ //
19
+ // Nothing here arms a timer. The follower is a value that answers "what is new
20
+ // since last time"; the loop that asks it lives where a process keeps its
21
+ // timers (./graph.ts `feed`).
22
+ import { after, isPromise } from "@yaks/fp";
23
+ import { composed, comps, dead } from "@yaks/graph/bundle";
24
+ import { as, col, desc, eq, ge, gt, iff, lit, lt, select, sub, table, val } from "@yaks/sql";
25
+ let FEED = 'journal_feed';
26
+ /** How long a commit stays in the feed, in ms: far longer than a follower
27
+ * that is still running ever falls behind. */ export let KEEP = 10 * 60_000;
28
+ /** The feed's table, which a writing host adds with the rest of its composed
29
+ * schema (./graph.ts `schema`). Its id is the cursor. */ export let feedDdl = ()=>[
30
+ {
31
+ t: 'create table',
32
+ name: FEED,
33
+ ifNot: true,
34
+ cols: [
35
+ {
36
+ name: 'id',
37
+ type: 'integer',
38
+ pk: true
39
+ },
40
+ {
41
+ name: 'at',
42
+ type: 'integer',
43
+ notNull: true
44
+ },
45
+ {
46
+ name: 'host',
47
+ type: 'text',
48
+ notNull: true
49
+ },
50
+ {
51
+ name: 'applied',
52
+ type: 'text',
53
+ notNull: true
54
+ }
55
+ ]
56
+ }
57
+ ];
58
+ /**
59
+ * A commit as the feed keeps it: one {@link Wrote} per entity.
60
+ *
61
+ * ```ts
62
+ * import { assertEquals } from '@std/assert'
63
+ *
64
+ * assertEquals(
65
+ * wrote([
66
+ * { entity: { eid: 'p1' }, page: { title: 'Hi' }, $was: {} },
67
+ * { entity: { eid: 'p1' }, updated: { by: 'ada' }, pin: null },
68
+ * { entity: { eid: 'n1' }, $delete: true },
69
+ * ]),
70
+ * [
71
+ * { entity: { eid: 'p1' }, page: ['title'], updated: ['by'], pin: null },
72
+ * { entity: { eid: 'n1' }, $delete: true },
73
+ * ],
74
+ * )
75
+ * ```
76
+ */ export let wrote = (bundles)=>composed(bundles).map((b)=>dead(b) ? {
77
+ entity: b.entity,
78
+ $delete: true
79
+ } : {
80
+ entity: b.entity,
81
+ ...Object.fromEntries(comps(b).map(([k, v])=>[
82
+ k,
83
+ v == null ? null : Object.keys(v)
84
+ ]))
85
+ });
86
+ /**
87
+ * The commits a follower heard, each entity's bundle holding what the graph
88
+ * holds now of what the commit wrote, in one read for all of them. A
89
+ * component the entity no longer holds, or an entity since deleted, reads as
90
+ * removed, and a property it no longer holds as `null`: the later commit that
91
+ * removed it is heard too, so the patches still end where the graph is.
92
+ *
93
+ * ```ts
94
+ * import { assertEquals } from '@std/assert'
95
+ *
96
+ * let now = [{ entity: { eid: 'p1' }, page: { title: 'Hi', text: 'x' } }]
97
+ * assertEquals(
98
+ * filled([[
99
+ * { entity: { eid: 'p1' }, page: ['title', 'lede'], pin: ['at'] },
100
+ * { entity: { eid: 'n1' }, $delete: true },
101
+ * ]], () => now),
102
+ * [[
103
+ * { entity: { eid: 'p1' }, page: { title: 'Hi', lede: null }, pin: null },
104
+ * { entity: { eid: 'n1' }, $delete: true },
105
+ * ]],
106
+ * )
107
+ * ```
108
+ */ export let filled = (txs, read)=>{
109
+ let eids = new Set();
110
+ let names = new Set();
111
+ for (let w of txs.flat()){
112
+ if (w.$delete) continue;
113
+ eids.add(w.entity.eid);
114
+ for (let [k, v] of Object.entries(w))if (Array.isArray(v)) names.add(k);
115
+ }
116
+ let fill = (now)=>{
117
+ let held = new Map(now.filter((b)=>!dead(b)).map((b)=>[
118
+ b.entity.eid,
119
+ b
120
+ ]));
121
+ return txs.map((tx)=>tx.map((w)=>{
122
+ if (w.$delete) return {
123
+ entity: w.entity,
124
+ $delete: true
125
+ };
126
+ let b = held.get(w.entity.eid);
127
+ let out = {
128
+ entity: w.entity
129
+ };
130
+ for (let [k, props] of Object.entries(w)){
131
+ if (k == 'entity') continue;
132
+ let comp = b?.[k];
133
+ out[k] = Array.isArray(props) && comp ? Object.fromEntries(props.map((p)=>[
134
+ p,
135
+ comp[p] ?? null
136
+ ])) : null;
137
+ }
138
+ return out;
139
+ }));
140
+ };
141
+ return eids.size ? after(read([
142
+ ...eids
143
+ ], [
144
+ ...names
145
+ ]), fill) : fill([]);
146
+ };
147
+ // A row a feed before {@link wrote} kept holds the values themselves, which a
148
+ // host still running it writes while a restart reaches it: its names are what
149
+ // a follower reads.
150
+ let named = (w)=>Object.fromEntries(Object.entries(w).map(([k, v])=>[
151
+ k,
152
+ k != 'entity' && v && typeof v == 'object' && !Array.isArray(v) ? Object.keys(v) : v
153
+ ]));
154
+ /** Bind the feed to a store: `feedOf({ rows: (s) => db.query(s) })`. */ export let feedOf = (o)=>{
155
+ let { rows } = o;
156
+ let read = o.read ?? rows;
157
+ let host = o.host ?? crypto.randomUUID();
158
+ let keep = o.keep ?? KEEP;
159
+ let now = o.now ?? Date.now;
160
+ let write = (wrote)=>{
161
+ let at = now();
162
+ rows({
163
+ t: 'insert',
164
+ into: FEED,
165
+ cols: [
166
+ 'at',
167
+ 'host',
168
+ 'applied'
169
+ ],
170
+ rows: [
171
+ [
172
+ val(at),
173
+ val(host),
174
+ val(JSON.stringify(wrote))
175
+ ]
176
+ ]
177
+ });
178
+ // Pruned after the insert, so the newest row always stands: the next id
179
+ // is always past every cursor, and a follower never mistakes a fresh row
180
+ // for one it read.
181
+ rows({
182
+ t: 'delete',
183
+ from: FEED,
184
+ where: lt(col('id'), sub(select({
185
+ cols: [
186
+ col('id')
187
+ ],
188
+ from: table(FEED),
189
+ where: ge(col('at'), val(at - keep)),
190
+ order: [
191
+ col('id')
192
+ ],
193
+ limit: lit(1)
194
+ })))
195
+ });
196
+ };
197
+ let tip = ()=>after(read(select({
198
+ cols: [
199
+ col('id')
200
+ ],
201
+ from: table(FEED),
202
+ order: [
203
+ desc(col('id'))
204
+ ],
205
+ limit: lit(1)
206
+ })), (rows)=>Number(rows[0]?.id ?? 0));
207
+ let since = (cursor, n)=>after(read(select({
208
+ cols: [
209
+ col('id'),
210
+ as(iff(eq(col('host'), val(host)), lit(null), col('applied')), 'out')
211
+ ],
212
+ from: table(FEED),
213
+ where: gt(col('id'), val(cursor)),
214
+ order: [
215
+ col('id')
216
+ ],
217
+ limit: val(n)
218
+ })), (rows)=>rows.map((r)=>({
219
+ seq: Number(r.id),
220
+ ...r.out == null ? {} : {
221
+ wrote: JSON.parse(String(r.out)).map(named)
222
+ }
223
+ })));
224
+ return {
225
+ host,
226
+ write,
227
+ tip,
228
+ since
229
+ };
230
+ };
231
+ /** The plugin that writes each commit into the feed, as the last thing inside
232
+ * its transaction. */ export let feeder = (f)=>({
233
+ name: '@yaks/journal/feed',
234
+ hooks: {
235
+ commit: (bundles)=>{
236
+ let said = wrote(bundles);
237
+ if (said.length) f.write(said);
238
+ return bundles;
239
+ }
240
+ }
241
+ });
242
+ /**
243
+ * A follower of a feed: each call answers the commits made since the last call
244
+ * by any host but the feed's own, oldest first. The cursor moves past this
245
+ * host's own commits without reading them, and past another's only once it is
246
+ * read: a read that fails ends the call with what came before it, and the next
247
+ * call starts again at the one that failed, throwing if it still fails.
248
+ */ export let follow = (f, opts = {})=>{
249
+ let cursor = opts.from;
250
+ let initial = cursor === undefined ? f.tip() : undefined;
251
+ // Capture the tip when following starts, even if no poll asks for it yet.
252
+ // A failed opening read belongs to that poll, rather than an unhandled task.
253
+ if (isPromise(initial)) void initial.catch(()=>{});
254
+ let page = opts.page ?? 100;
255
+ return ()=>{
256
+ let out = [];
257
+ let accept = (seen)=>{
258
+ let first = seen[0]?.seq;
259
+ if (first > cursor + 1) opts.missed?.(first - cursor - 1);
260
+ for (let { seq, wrote } of seen){
261
+ if (wrote) out.push({
262
+ seq,
263
+ wrote
264
+ });
265
+ cursor = seq;
266
+ }
267
+ return seen.length < page;
268
+ };
269
+ let pages = ()=>{
270
+ for(;;){
271
+ let seen = f.since(cursor, page);
272
+ if (isPromise(seen)) {
273
+ return seen.then((rows)=>accept(rows) ? out : pages());
274
+ }
275
+ if (accept(seen)) return out;
276
+ }
277
+ };
278
+ let failed = (err)=>{
279
+ if (out.length) return out;
280
+ throw err;
281
+ };
282
+ try {
283
+ let start = initial;
284
+ initial = undefined;
285
+ let result = cursor === undefined ? after(start ?? f.tip(), (tip)=>{
286
+ cursor = tip;
287
+ return pages();
288
+ }) : pages();
289
+ return isPromise(result) ? result.catch(failed) : result;
290
+ } catch (err) {
291
+ return failed(err);
292
+ }
293
+ };
294
+ };
295
+ //# sourceMappingURL=feed.js.map
package/feed.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feed.js","sources":["./feed.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,yEAAyE;AACzE,8EAA8E;AAC9E,2EAA2E;AAC3E,8EAA8E;AAC9E,4EAA4E;AAC5E,0EAA0E;AAC1E,EAAE;AACF,2EAA2E;AAC3E,6EAA6E;AAC7E,oEAAoE;AACpE,uEAAuE;AACvE,+EAA+E;AAC/E,uCAAuC;AACvC,EAAE;AACF,+EAA+E;AAC/E,0EAA0E;AAC1E,8BAA8B;AAE9B,SAAS,KAAK,EAAE,SAAS,wBAA6B;AAEtD,SAAS,QAAQ,EAAE,KAAK,EAAE,IAAI,kCAAuC;AACrE,SACE,EAAE,EACF,GAAG,EACH,IAAI,EACJ,EAAE,EACF,EAAE,EACF,EAAE,EACF,GAAG,EACH,GAAG,EACH,EAAE,EAEF,MAAM,EAEN,GAAG,EACH,KAAK,EACL,GAAG,yBACwB;AAG7B,IAAI,OAAO;AAEX;4CAC4C,GAC5C,OAAO,IAAI,OAAO,KAAK,OAAM;AAE7B;uDACuD,GACvD,OAAO,IAAI,UAAU,IAAc;IAAC;MAClC,GAAG;MACH,MAAM;MACN,OAAO;MACP,MAAM;QACJ;UAAE,MAAM;UAAM,MAAM;UAAW,IAAI;QAAK;QACxC;UAAE,MAAM;UAAM,MAAM;UAAW,SAAS;QAAK;QAC7C;UAAE,MAAM;UAAQ,MAAM;UAAQ,SAAS;QAAK;QAC5C;UAAE,MAAM;UAAW,MAAM;UAAQ,SAAS;QAAK;OAChD;IACH;GAAE,CAAA;AAcF;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,IAAI,QAAQ,CAAC,UAClB,SAAS,SAAS,GAAG,CAAC,CAAC,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