@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/feed.ts ADDED
@@ -0,0 +1,368 @@
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
+
23
+ import { after, isPromise } from '@yaks/fp'
24
+ import type { Bundle, Plugin } from 'jsr:@yaks/graph@0.2.36'
25
+ import { composed, comps, dead } from '@yaks/graph/bundle'
26
+ import {
27
+ as,
28
+ col,
29
+ desc,
30
+ eq,
31
+ ge,
32
+ gt,
33
+ iff,
34
+ lit,
35
+ lt,
36
+ type Row,
37
+ select,
38
+ type Stmt,
39
+ sub,
40
+ table,
41
+ val,
42
+ } from '@yaks/sql'
43
+ import type { Rows } from './log.ts'
44
+
45
+ let FEED = 'journal_feed'
46
+
47
+ /** How long a commit stays in the feed, in ms: far longer than a follower
48
+ * that is still running ever falls behind. */
49
+ export let KEEP = 10 * 60_000
50
+
51
+ /** The feed's table, which a writing host adds with the rest of its composed
52
+ * schema (./graph.ts `schema`). Its id is the cursor. */
53
+ export let feedDdl = (): Stmt[] => [{
54
+ t: 'create table',
55
+ name: FEED,
56
+ ifNot: true,
57
+ cols: [
58
+ { name: 'id', type: 'integer', pk: true },
59
+ { name: 'at', type: 'integer', notNull: true },
60
+ { name: 'host', type: 'text', notNull: true },
61
+ { name: 'applied', type: 'text', notNull: true },
62
+ ],
63
+ }]
64
+
65
+ /**
66
+ * What a commit wrote to one entity, as the feed keeps it: the properties it
67
+ * wrote of each component, `null` for a component it removed, or `$delete`
68
+ * where the entity went. The values stay where the graph keeps them, and a
69
+ * follower reads them there ({@link filled}).
70
+ */
71
+ export type Wrote = {
72
+ entity: Bundle['entity']
73
+ $delete?: true
74
+ [comp: string]: string[] | null | true | Bundle['entity'] | undefined
75
+ }
76
+
77
+ /**
78
+ * A commit as the feed keeps it: one {@link Wrote} per entity.
79
+ *
80
+ * ```ts
81
+ * import { assertEquals } from '@std/assert'
82
+ *
83
+ * assertEquals(
84
+ * wrote([
85
+ * { entity: { eid: 'p1' }, page: { title: 'Hi' }, $was: {} },
86
+ * { entity: { eid: 'p1' }, updated: { by: 'ada' }, pin: null },
87
+ * { entity: { eid: 'n1' }, $delete: true },
88
+ * ]),
89
+ * [
90
+ * { entity: { eid: 'p1' }, page: ['title'], updated: ['by'], pin: null },
91
+ * { entity: { eid: 'n1' }, $delete: true },
92
+ * ],
93
+ * )
94
+ * ```
95
+ */
96
+ export let wrote = (bundles: Bundle[]): Wrote[] =>
97
+ composed(bundles).map((b): Wrote =>
98
+ dead(b) ? { entity: b.entity, $delete: true } : {
99
+ entity: b.entity,
100
+ ...Object.fromEntries(
101
+ comps(b).map(([k, v]) => [k, v == null ? null : Object.keys(v)]),
102
+ ),
103
+ }
104
+ )
105
+
106
+ /** Reads entities as they stand, carrying the components named (@yaks/graph
107
+ * `Storage.get`). */
108
+ export type Read = (
109
+ eids: string[],
110
+ comps: string[],
111
+ ) => Bundle[] | Promise<Bundle[]>
112
+
113
+ /**
114
+ * The commits a follower heard, each entity's bundle holding what the graph
115
+ * holds now of what the commit wrote, in one read for all of them. A
116
+ * component the entity no longer holds, or an entity since deleted, reads as
117
+ * removed, and a property it no longer holds as `null`: the later commit that
118
+ * removed it is heard too, so the patches still end where the graph is.
119
+ *
120
+ * ```ts
121
+ * import { assertEquals } from '@std/assert'
122
+ *
123
+ * let now = [{ entity: { eid: 'p1' }, page: { title: 'Hi', text: 'x' } }]
124
+ * assertEquals(
125
+ * filled([[
126
+ * { entity: { eid: 'p1' }, page: ['title', 'lede'], pin: ['at'] },
127
+ * { entity: { eid: 'n1' }, $delete: true },
128
+ * ]], () => now),
129
+ * [[
130
+ * { entity: { eid: 'p1' }, page: { title: 'Hi', lede: null }, pin: null },
131
+ * { entity: { eid: 'n1' }, $delete: true },
132
+ * ]],
133
+ * )
134
+ * ```
135
+ */
136
+ export let filled = (
137
+ txs: Wrote[][],
138
+ read: Read,
139
+ ): Bundle[][] | Promise<Bundle[][]> => {
140
+ let eids = new Set<string>()
141
+ let names = new Set<string>()
142
+ for (let w of txs.flat()) {
143
+ if (w.$delete) continue
144
+ eids.add(w.entity.eid)
145
+ for (let [k, v] of Object.entries(w)) if (Array.isArray(v)) names.add(k)
146
+ }
147
+ let fill = (now: Bundle[]) => {
148
+ let held = new Map(
149
+ now.filter((b) => !dead(b)).map((b) => [b.entity.eid, b]),
150
+ )
151
+ return txs.map((tx) =>
152
+ tx.map((w): Bundle => {
153
+ if (w.$delete) return { entity: w.entity, $delete: true }
154
+ let b = held.get(w.entity.eid)
155
+ let out: Bundle = { entity: w.entity }
156
+ for (let [k, props] of Object.entries(w)) {
157
+ if (k == 'entity') continue
158
+ let comp = b?.[k] as Record<string, unknown> | null | undefined
159
+ out[k] = Array.isArray(props) && comp
160
+ ? Object.fromEntries(props.map((p) => [p, comp[p] ?? null]))
161
+ : null
162
+ }
163
+ return out
164
+ })
165
+ )
166
+ }
167
+ return eids.size ? after(read([...eids], [...names]), fill) : fill([])
168
+ }
169
+
170
+ /** One commit another host made: its place in the feed, and what it wrote
171
+ * ({@link wrote}). */
172
+ export type Heard = { seq: number; wrote: Wrote[] }
173
+
174
+ // A row a feed before {@link wrote} kept holds the values themselves, which a
175
+ // host still running it writes while a restart reaches it: its names are what
176
+ // a follower reads.
177
+ let named = (w: Wrote): Wrote =>
178
+ Object.fromEntries(
179
+ Object.entries(w).map(([k, v]) => [
180
+ k,
181
+ k != 'entity' && v && typeof v == 'object' && !Array.isArray(v)
182
+ ? Object.keys(v)
183
+ : v,
184
+ ]),
185
+ ) as Wrote
186
+
187
+ /** The feed bound to one store, as one host. */
188
+ export type FeedRows = Row[] | Promise<Row[]>
189
+ type Answer<T, V> = T extends Promise<unknown> ? Promise<V> : V
190
+ type Page = { seq: number; wrote?: Wrote[] }[]
191
+
192
+ export type Feed<T extends FeedRows = FeedRows> = {
193
+ /** who this feed writes as: the one host (a graph opened by one process or
194
+ * thread) whose commits it records, so a follower can skip its own */
195
+ host: string
196
+ /** write one commit down inside the caller's own transaction, and prune
197
+ * what has been kept long enough */
198
+ write: (wrote: Wrote[]) => void
199
+ /** the newest commit's seq, or 0 */
200
+ tip: () => Answer<T, number>
201
+ /** the commits after a cursor, oldest first, at most `n`; one this host
202
+ * made comes without what it wrote */
203
+ since: (cursor: number, n: number) => Answer<T, Page>
204
+ }
205
+
206
+ /** How a feed is bound to a store. */
207
+ export type FeedOpts<T extends FeedRows = Row[]> = {
208
+ /** the statement runner, over the graph's own transaction */
209
+ rows: Rows
210
+ /** committed reads, where another connection answers them; writes stay on
211
+ * `rows`, inside the committing transaction */
212
+ read?: (statement: Stmt) => T
213
+ /** the host it writes as (default: a fresh id) */
214
+ host?: string
215
+ /** how long a commit is kept, in ms (default {@link KEEP}) */
216
+ keep?: number
217
+ /** the clock, in ms (default `Date.now`) */
218
+ now?: () => number
219
+ }
220
+
221
+ /** Bind the feed to a store: `feedOf({ rows: (s) => db.query(s) })`. */
222
+ export let feedOf = <T extends FeedRows = Row[]>(o: FeedOpts<T>): Feed<T> => {
223
+ let { rows } = o
224
+ let read = o.read ?? rows
225
+ let host = o.host ?? crypto.randomUUID()
226
+ let keep = o.keep ?? KEEP
227
+ let now = o.now ?? Date.now
228
+ let write = (wrote: Wrote[]) => {
229
+ let at = now()
230
+ rows({
231
+ t: 'insert',
232
+ into: FEED,
233
+ cols: ['at', 'host', 'applied'],
234
+ rows: [[val(at), val(host), val(JSON.stringify(wrote))]],
235
+ })
236
+ // Pruned after the insert, so the newest row always stands: the next id
237
+ // is always past every cursor, and a follower never mistakes a fresh row
238
+ // for one it read.
239
+ rows({
240
+ t: 'delete',
241
+ from: FEED,
242
+ where: lt(
243
+ col('id'),
244
+ sub(select({
245
+ cols: [col('id')],
246
+ from: table(FEED),
247
+ where: ge(col('at'), val(at - keep)),
248
+ order: [col('id')],
249
+ limit: lit(1),
250
+ })),
251
+ ),
252
+ })
253
+ }
254
+ let tip = () =>
255
+ after(
256
+ read(select({
257
+ cols: [col('id')],
258
+ from: table(FEED),
259
+ order: [desc(col('id'))],
260
+ limit: lit(1),
261
+ })),
262
+ (rows) => Number(rows[0]?.id ?? 0),
263
+ )
264
+ let since = (cursor: number, n: number) =>
265
+ after(
266
+ read(select({
267
+ cols: [
268
+ col('id'),
269
+ as(iff(eq(col('host'), val(host)), lit(null), col('applied')), 'out'),
270
+ ],
271
+ from: table(FEED),
272
+ where: gt(col('id'), val(cursor)),
273
+ order: [col('id')],
274
+ limit: val(n),
275
+ })),
276
+ (rows) =>
277
+ rows.map((r) => ({
278
+ seq: Number(r.id),
279
+ ...r.out == null
280
+ ? {}
281
+ : { wrote: (JSON.parse(String(r.out)) as Wrote[]).map(named) },
282
+ })),
283
+ )
284
+ return { host, write, tip, since } as Feed<T>
285
+ }
286
+
287
+ /** The plugin that writes each commit into the feed, as the last thing inside
288
+ * its transaction. */
289
+ export let feeder = (f: Feed): Plugin => ({
290
+ name: '@yaks/journal/feed',
291
+ hooks: {
292
+ commit: (bundles: Bundle[]) => {
293
+ let said = wrote(bundles)
294
+ if (said.length) f.write(said)
295
+ return bundles
296
+ },
297
+ },
298
+ })
299
+
300
+ /** How a follower reads. */
301
+ export type FollowOpts = {
302
+ /** the seq to start after (default: the feed's tip when the follower is
303
+ * made, so it reports only what commits from then on) */
304
+ from?: number
305
+ /** the most commits one page reads, so a burst of writes elsewhere is
306
+ * worked through a page at a time (default 100) */
307
+ page?: number
308
+ /** told how many commits were pruned before this follower read them: it
309
+ * was away longer than they are kept */
310
+ missed?: (n: number) => void
311
+ }
312
+
313
+ /**
314
+ * A follower of a feed: each call answers the commits made since the last call
315
+ * by any host but the feed's own, oldest first. The cursor moves past this
316
+ * host's own commits without reading them, and past another's only once it is
317
+ * read: a read that fails ends the call with what came before it, and the next
318
+ * call starts again at the one that failed, throwing if it still fails.
319
+ */
320
+ export let follow = <T extends FeedRows>(
321
+ f: Feed<T>,
322
+ opts: FollowOpts = {},
323
+ ): () => Answer<T, Heard[]> => {
324
+ let cursor = opts.from
325
+ let initial = cursor === undefined ? f.tip() : undefined
326
+ // Capture the tip when following starts, even if no poll asks for it yet.
327
+ // A failed opening read belongs to that poll, rather than an unhandled task.
328
+ if (isPromise(initial)) void initial.catch(() => {})
329
+ let page = opts.page ?? 100
330
+ return (() => {
331
+ let out: Heard[] = []
332
+ let accept = (seen: Page) => {
333
+ let first = seen[0]?.seq
334
+ if (first > cursor! + 1) opts.missed?.(first - cursor! - 1)
335
+ for (let { seq, wrote } of seen) {
336
+ if (wrote) out.push({ seq, wrote })
337
+ cursor = seq
338
+ }
339
+ return seen.length < page
340
+ }
341
+ let pages = (): Heard[] | Promise<Heard[]> => {
342
+ for (;;) {
343
+ let seen = f.since(cursor!, page)
344
+ if (isPromise(seen)) {
345
+ return seen.then((rows) => accept(rows) ? out : pages())
346
+ }
347
+ if (accept(seen)) return out
348
+ }
349
+ }
350
+ let failed = (err: unknown) => {
351
+ if (out.length) return out
352
+ throw err
353
+ }
354
+ try {
355
+ let start = initial
356
+ initial = undefined
357
+ let result = cursor === undefined
358
+ ? after(start ?? f.tip(), (tip) => {
359
+ cursor = tip
360
+ return pages()
361
+ })
362
+ : pages()
363
+ return isPromise(result) ? result.catch(failed) : result
364
+ } catch (err) {
365
+ return failed(err)
366
+ }
367
+ }) as () => Answer<T, Heard[]>
368
+ }
package/graph.js ADDED
@@ -0,0 +1,224 @@
1
+ // `@yaks/journal/graph` — what a server composed from a config file imports to
2
+ // switch the journal on. Its schema is the journal's append-only tables and
3
+ // the feed's short-lived one, which a writing host adds to its store; its
4
+ // plugins write a row per component every transaction touched that the
5
+ // vocabulary keeps as history, and a row per commit to the feed.
6
+ //
7
+ // `logFor` and `feedFor` are here rather than inside `plugins` because
8
+ // `@yaks/journal/tools` reads the same tables this plugin writes, and the feed
9
+ // below follows its own: one host, one log and one feed, bound in one place.
10
+ // Both write as the same host, which is what lets the feed leave out what this
11
+ // host wrote itself.
12
+ import { as, col, fn, NOW, select, statements, table } from "@yaks/sql";
13
+ import { ddl, journal, log } from "./mod.js";
14
+ import { feedDdl, feeder, feedOf, filled, follow } from "./feed.js";
15
+ let logs = new WeakMap();
16
+ let feeds = new WeakMap();
17
+ let rowsOf = (host)=>{
18
+ let sql = statements(host.storage);
19
+ return (s)=>sql.query(s);
20
+ };
21
+ /** The log bound to a host: the three tables, read and written over that
22
+ * host's storage transaction, as that host. The same host gets the same log. */ export let logFor = (host)=>{
23
+ let found = logs.get(host);
24
+ if (!found) {
25
+ logs.set(host, found = log({
26
+ rows: rowsOf(host),
27
+ vocab: host.vocab,
28
+ derived: host.derived
29
+ }));
30
+ }
31
+ return found;
32
+ };
33
+ /** The feed bound to a host, written as the host its log writes as. The same
34
+ * host gets the same feed. */ export let feedFor = (host)=>{
35
+ let found = feeds.get(host);
36
+ if (!found) {
37
+ let rows = rowsOf(host);
38
+ let read = host.reader?.statements;
39
+ feeds.set(host, found = feedOf({
40
+ rows,
41
+ read: read && ((s)=>read.query(s)),
42
+ host: logFor(host).host
43
+ }));
44
+ }
45
+ return found;
46
+ };
47
+ /** The journal's tables and the feed's, and the words of the host's
48
+ * vocabulary (./names.ts), which a writing host adds with the rest of its
49
+ * composed schema; a store an older journal made gains the columns it
50
+ * predates there (@yaks/sqlite `grow`). */ export let schema = (host)=>[
51
+ ...ddl(host.vocab),
52
+ ...feedDdl()
53
+ ];
54
+ export let aspects = (options = {})=>'attribution' in options || 'versions' in options ? {
55
+ attribution: options.attribution !== false,
56
+ versions: options.versions !== false,
57
+ values: false
58
+ } : {
59
+ attribution: true,
60
+ versions: false,
61
+ values: true
62
+ };
63
+ /** What a store keeps versions with, where `versions` is on: the statement
64
+ * that takes a transaction's id, as a `journal_tx` row whose writer the
65
+ * journal fills in as it records the transaction, and the newest one's. */ export let history = (options)=>aspects(options).versions ? {
66
+ clock: {
67
+ t: 'insert',
68
+ into: 'journal_tx',
69
+ cols: [
70
+ 'ts'
71
+ ],
72
+ rows: [
73
+ [
74
+ NOW
75
+ ]
76
+ ],
77
+ returning: [
78
+ col('id')
79
+ ]
80
+ },
81
+ tip: select({
82
+ cols: [
83
+ as(fn('max', col('id')), 'id')
84
+ ],
85
+ from: table('journal_tx')
86
+ })
87
+ } : undefined;
88
+ /** A store keeping versions requires the journal from then on: a writer
89
+ * without it would change live rows and keep nothing they replaced. */ export let required = (options)=>aspects(options).versions;
90
+ /** Bind the hooks over the tables the installer prepared: the journal,
91
+ * recording what the host's vocabulary keeps as history, as its aspects say,
92
+ * and the feed, carrying every commit to the other hosts. */ export let plugins = (host, options)=>{
93
+ let a = aspects(options);
94
+ // A branch's commits are recorded as its own, and reach no other host: the
95
+ // feed carries main's.
96
+ let mode = host.storage.statements?.mode;
97
+ let record = {
98
+ changes: a.attribution,
99
+ values: a.values,
100
+ ...mode && 'branch' in mode ? {
101
+ branch: mode.branch
102
+ } : {}
103
+ };
104
+ let components = Array.isArray(options?.components) ? options.components.map(String) : undefined;
105
+ return [
106
+ journal(logFor(host), host.vocab, {
107
+ record,
108
+ components
109
+ }),
110
+ ...mode || options?.feed === false ? [] : [
111
+ feeder(feedFor(host))
112
+ ]
113
+ ];
114
+ };
115
+ /** How often a host looks for what other hosts committed, in ms, unless the
116
+ * config says (`{"use": "@yaks/journal", "with": {"every": 50}}`). */ export let EVERY = 200;
117
+ /** How many times news the consumer failed on is offered again before it is
118
+ * reported and passed over, so news that can never be taken does not hold
119
+ * back everything after it; the consumer is then told it missed some. */ export let TRIES = 5;
120
+ /**
121
+ * The commits other hosts made to this store, handed to `each` as bundles of
122
+ * what each wrote, its values read from the graph as they stand (./feed.ts
123
+ * `filled`), oldest first, from the moment `each` is given until the
124
+ * returned function is called or the host stops. What a subscription registry
125
+ * or a cache is fed so it also sees writes its own graph did not make: a `yak`
126
+ * command's beside `yak serve`, or a worker's serving the effects role.
127
+ * Whatever goes wrong on the way is the host's to report.
128
+ *
129
+ * The feed is read every `every` ms however long the consumer takes, so a
130
+ * slow consumer is handed more at once rather than left behind what the store
131
+ * keeps (./feed.ts `KEEP`). What still never reaches it (a process asleep past
132
+ * that, news passed over) comes with `missed`, and the consumer reads again
133
+ * what it holds: it ends up correct on its own.
134
+ *
135
+ * A look reads through the host's reader, and the consumer may take its time:
136
+ * stopping cancels the next look, and the host's release (`defer`) waits out
137
+ * the one under way, so no read outlives the plugins into a closed reader.
138
+ * A host whose options say `feed: false` is offered none.
139
+ */ export let feed = (host, options = {})=>options.feed === false ? undefined : (each)=>{
140
+ let every = options.every ?? EVERY;
141
+ let timer = options.timer ?? later;
142
+ let told = (error)=>host.report ? void host.report(error) : console.error('@yaks/journal feed —', error);
143
+ let missed = false;
144
+ let next = follow(feedFor(host), {
145
+ missed: (n)=>{
146
+ missed = true;
147
+ told(new Error(`the feed pruned ${n} commits before they were read`));
148
+ }
149
+ });
150
+ let heard = [];
151
+ let tries = 0;
152
+ let taking;
153
+ let cancel = ()=>{};
154
+ let stopped = false;
155
+ // One call at a time, so the consumer is never handed a transaction out of
156
+ // order. News it fails on (a store busy for a moment) is offered again at
157
+ // the next look, ahead of everything heard after it.
158
+ let take = async ()=>{
159
+ while((heard.length || missed) && !stopped){
160
+ let [said, was] = [
161
+ heard,
162
+ missed
163
+ ];
164
+ heard = [];
165
+ missed = false;
166
+ try {
167
+ let applied = await filled(said, (e, c)=>host.reader?.storage ? host.reader.storage.get(e, c) : host.storage.get(e, c));
168
+ await each({
169
+ applied,
170
+ missed: was
171
+ });
172
+ tries = 0;
173
+ } catch (err) {
174
+ if (++tries < TRIES) {
175
+ heard = [
176
+ ...said,
177
+ ...heard
178
+ ];
179
+ missed ||= was;
180
+ break;
181
+ }
182
+ tries = 0;
183
+ missed = true;
184
+ told(new Error('the feed passed over what it heard', {
185
+ cause: err
186
+ }));
187
+ }
188
+ }
189
+ };
190
+ // A read that fails is tried again at the next look, since the cursor moves
191
+ // only past what was read.
192
+ let looking;
193
+ let look = ()=>looking = looked();
194
+ let looked = async ()=>{
195
+ try {
196
+ heard.push(...(await next()).map((h)=>h.wrote));
197
+ } catch (err) {
198
+ told(err);
199
+ }
200
+ let started = !taking && (heard.length || missed) ? taking = take().finally(()=>taking = undefined) : undefined;
201
+ if (!stopped) cancel = timer(look, every);
202
+ return started;
203
+ };
204
+ let stop = ()=>{
205
+ stopped = true;
206
+ cancel();
207
+ };
208
+ host.defer?.(async ()=>{
209
+ stop();
210
+ await looking;
211
+ await taking;
212
+ });
213
+ if (host.stopping.aborted) return stop;
214
+ host.stopping.addEventListener('abort', stop, {
215
+ once: true
216
+ });
217
+ cancel = timer(look, every);
218
+ return stop;
219
+ };
220
+ let later = (fn, ms)=>{
221
+ let id = setTimeout(fn, ms);
222
+ return ()=>clearTimeout(id);
223
+ };
224
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,4EAA4E;AAC5E,0EAA0E;AAC1E,uEAAuE;AACvE,iEAAiE;AACjE,EAAE;AACF,uEAAuE;AACvE,+EAA+E;AAC/E,6EAA6E;AAC7E,+EAA+E;AAC/E,qBAAqB;AAGrB,SACE,EAAE,EACF,GAAG,EAEH,EAAE,EAEF,GAAG,EAEH,MAAM,EAEN,UAAU,EAEV,KAAK,yBACsB;AAE7B,SACE,GAAG,EACH,OAAO,EAEP,GAAG,mBAGY;AACjB,SAEE,OAAO,EACP,MAAM,EACN,MAAM,EACN,MAAM,EACN,MAAM,oBAGU;AAElB,IAAI,OAAO,IAAI;AACf,IAAI,QAAQ,IAAI;AAiBhB,IAAI,SAAS,CAAC;EACZ,IAAI,MAAM,WAAW,KAAK,OAAO;EACjC,OAAO,CAAC,IAAY,IAAI,KAAK,CAAC;AAChC;AAEA;8EAC8E,GAC9E,OAAO,IAAI,SAAS,CAAC;EACnB,IAAI,QAAQ,KAAK,GAAG,CAAC;EACrB,IAAI,CAAC,OAAO;IACV,KAAK,GAAG,CACN,MACA,QAAQ,IAAI;MACV,MAAM,OAAO;MACb,OAAO,KAAK,KAAK;MACjB,SAAS,KAAK,OAAO;IACvB;EAEJ;EACA,OA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