@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/page.ts ADDED
@@ -0,0 +1,233 @@
1
+ /**
2
+ * What history keeps, as the browsing app draws it: its share of the file
3
+ * and what it kept per change and per day, day by day; the changes the
4
+ * journal holds for each component, beside what that component keeps in its
5
+ * own table and its versions; and every table in the file, largest first.
6
+ * Everything comes from the `kept` rows the duty writes once a day
7
+ * (./service.ts), the changes per component among them, so opening the page
8
+ * reads a month of rows and counts nothing. A component is drawn by name and
9
+ * opens its page, where its recent writes are.
10
+ *
11
+ * @module
12
+ */
13
+ /* @ts-types="npm:@types/react@19.3.0" */ import { createElement as h, Fragment, type JSX, type ReactNode } from 'react'
14
+ import {
15
+ compEid,
16
+ mention,
17
+ type Props,
18
+ useNamed,
19
+ type View,
20
+ } from '@yaks/inspect'
21
+ import { Head, Loading, Meter, Section, Table } from '@yaks/ui'
22
+ import { size } from '@yaks/file'
23
+ import {
24
+ changes,
25
+ historic,
26
+ history,
27
+ type Kept,
28
+ keptOf,
29
+ perChange,
30
+ perDay,
31
+ versioned,
32
+ } from './kept.js'
33
+
34
+ let { Body, Cell, Heading, Row } = Table
35
+ let COMPONENTS = 30
36
+ let TABLES = 40
37
+
38
+ let count = (n: number) => Math.round(n).toLocaleString('en-US')
39
+ let share = (part: number, whole: number) =>
40
+ whole ? `${Math.round((part / whole) * 100)}%` : ''
41
+
42
+ type Answer = Props['got'][string] | undefined
43
+
44
+ let waiting = (got: Answer, what: string) =>
45
+ got?.error
46
+ ? h(Section.Sub, { role: 'alert' }, got.error)
47
+ : !got?.ready
48
+ ? h(Loading, {}, `Loading ${what}…`)
49
+ : null
50
+
51
+ // A table of rows under headings: the first column a name, the second a bar.
52
+ let Ranked = (
53
+ { title, sub, heads, rows }: {
54
+ title: string
55
+ sub: string
56
+ heads: string[]
57
+ rows: {
58
+ key: string
59
+ name: ReactNode
60
+ bar: number
61
+ cells: string[]
62
+ }[]
63
+ },
64
+ ) =>
65
+ h(
66
+ Section,
67
+ {},
68
+ h(Section.Title, {}, title, ' ', h(Section.Count, {}, String(rows.length))),
69
+ h(Section.Sub, {}, sub),
70
+ h(
71
+ Table,
72
+ { cols: [null, null, ...heads.map(() => 'num')] },
73
+ h(
74
+ Table.Head,
75
+ {},
76
+ h(
77
+ Row,
78
+ {},
79
+ h(Heading, {}, ''),
80
+ h(Heading, {}, ''),
81
+ ...heads.map((k) => h(Heading, { key: k, mod: 'num' }, k)),
82
+ ),
83
+ ),
84
+ h(
85
+ Body,
86
+ {},
87
+ rows.map((r) =>
88
+ h(
89
+ Row,
90
+ { key: r.key },
91
+ h(Cell, {}, r.name),
92
+ h(Cell, {}, h(Meter, { value: r.bar, width: 10 })),
93
+ ...r.cells.map((s, i) => h(Cell, { key: i, mod: 'num' }, s)),
94
+ )
95
+ ),
96
+ ),
97
+ ),
98
+ )
99
+
100
+ // Each day, newest first, beside the day before it.
101
+ let Days = ({ days }: { days: Kept[] }) =>
102
+ h(Ranked, {
103
+ title: 'Day by day',
104
+ sub:
105
+ 'The file and what history kept in it each day, the changes the journal held, and what history kept per change written since the day before.',
106
+ heads: ['file', 'history', 'changes', 'per change'],
107
+ rows: days.map((k, i) => {
108
+ let before = days[i + 1]
109
+ let each = before && perChange(before, k)
110
+ return {
111
+ key: k.day,
112
+ name: k.day,
113
+ bar: k.bytes ? history(k) / k.bytes : 0,
114
+ cells: [
115
+ size(k.bytes),
116
+ `${size(history(k))} (${share(history(k), k.bytes)})`,
117
+ count(changes(k)),
118
+ each == null ? '' : size(each),
119
+ ],
120
+ }
121
+ }),
122
+ })
123
+
124
+ // The changes the journal held for each component, beside what the
125
+ // component keeps in its table and its versions.
126
+ let Components = ({ io, k }: { io: Props['io']; k: Kept }) => {
127
+ let rows = io.vocab.all.map((c) => ({
128
+ c,
129
+ eid: compEid(io.vocab, c),
130
+ n: k.changes?.[c] ?? 0,
131
+ })).filter((r) => r.n || k.tables[`${r.c}$versions`])
132
+ .toSorted((a, b) => b.n - a.n).slice(0, COMPONENTS)
133
+ useNamed(io, rows.map((r) => r.eid))
134
+ let most = rows[0]?.n || 1
135
+ return h(Ranked, {
136
+ title: 'By component',
137
+ sub:
138
+ 'The changes the journal held for each component, and what the component keeps in its own table and in its versions. A component marked as keeping no history has none.',
139
+ heads: ['changes', 'table', 'versions'],
140
+ rows: rows.map(({ c, eid, n }) => ({
141
+ key: c,
142
+ name: mention(io, eid),
143
+ bar: n / most,
144
+ cells: [
145
+ count(n),
146
+ size(k.tables[c]?.[0]),
147
+ k.tables[`${c}$versions`] ? size(k.tables[`${c}$versions`][0]) : '',
148
+ ],
149
+ })),
150
+ })
151
+ }
152
+
153
+ // Every table, largest first, with its growth a day.
154
+ let Tables = ({ k, before }: { k: Kept; before?: Kept }) => {
155
+ let rows = Object.entries(k.tables).toSorted(([, a], [, b]) => b[0] - a[0])
156
+ .slice(0, TABLES)
157
+ let most = rows[0]?.[1][0] || 1
158
+ let grew = (t: string) => {
159
+ let d = before && perDay(before, k, (m) => m.tables[t]?.[0] ?? 0)
160
+ return d == null ? '' : `${d > 0 ? '+' : ''}${size(d)}`
161
+ }
162
+ return h(Ranked, {
163
+ title: 'Tables',
164
+ sub:
165
+ 'Every table in the file with its indexes, largest first. History’s are the journal’s and each component’s versions.',
166
+ heads: ['bytes', 'rows', 'a day', ''],
167
+ rows: rows.map(([t, [bytes, n]]) => ({
168
+ key: t,
169
+ name: versioned(t) ? `${versioned(t)} versions` : t,
170
+ bar: bytes / most,
171
+ cells: [size(bytes), count(n), grew(t), historic(t) ? 'history' : ''],
172
+ })),
173
+ })
174
+ }
175
+
176
+ /** The page: history's share of the file, day by day, by component and by
177
+ * table. */
178
+ export let Page = ({ io, got }: Props): JSX.Element => {
179
+ let days = (got.days?.rows ?? []).map(keptOf).filter((k): k is Kept => !!k)
180
+ let [k, before] = days
181
+ let each = before && perChange(before, k)
182
+ let daily = before && perDay(before, k, history)
183
+ return h(
184
+ 'article',
185
+ {},
186
+ h(
187
+ Head,
188
+ {},
189
+ h(Head.Title, {}, 'What history keeps'),
190
+ h(
191
+ Head.Sub,
192
+ {},
193
+ 'The journal records who wrote what and the values each write left; versions keep every version of a row. Measured once a day from the file’s pages, each table with its indexes.',
194
+ ),
195
+ k
196
+ ? h(
197
+ Head.Facts,
198
+ {},
199
+ `${size(history(k))} of the file’s ${size(k.bytes)} (${
200
+ share(history(k), k.bytes)
201
+ })`,
202
+ ...daily == null ? [] : [`${size(daily)} more a day`],
203
+ ...each == null ? [] : [`${size(each)} kept per change`],
204
+ `${count(changes(k))} changes held`,
205
+ `measured ${io.when(k.at)}`,
206
+ )
207
+ : null,
208
+ ),
209
+ waiting(got.days, 'the measurements') ?? (!k
210
+ ? h(
211
+ Section.Sub,
212
+ {},
213
+ 'Not measured yet: the duty measures the file once a day.',
214
+ )
215
+ : h(
216
+ Fragment,
217
+ {},
218
+ h(Days, { days: days.slice(0, 14) }),
219
+ h(Components, { io, k }),
220
+ h(Tables, { k, before }),
221
+ )),
222
+ )
223
+ }
224
+
225
+ /** The views this package draws in the browsing app. */
226
+ export let inspectViews: View[] = [
227
+ {
228
+ view: 'History.Page',
229
+ match: true,
230
+ asks: () => ({ days: '.kept * .order=-kept.day .limit=31' }),
231
+ Render: Page,
232
+ },
233
+ ]
package/service.js ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * What the file keeps, as a duty: the module a server imports at
3
+ * `@yaks/journal/service`. Once a UTC day it measures the store's file (its
4
+ * storage's `measure`) and keeps the day's `kept` row, which the History page
5
+ * reads (./page.ts), so looking costs nothing. The row names the file it
6
+ * measured, so a page about the disk finds the store's file and its free
7
+ * pages, and holds the changes the journal holds per component, counted from
8
+ * its log, so the page never counts them. A store that keeps no file of
9
+ * pages measures nothing.
10
+ *
11
+ * @module
12
+ */ import { identityEid } from "@yaks/graph/identity";
13
+ import { sleep } from "@yaks/fp";
14
+ import { onDisk } from "@yaks/file/local";
15
+ import { CHANGES } from "./kept.js";
16
+ import { logFor } from "./graph.js";
17
+ import { heldRows, heldSql } from "./held.js";
18
+ /** How long a pass waits for the next, in milliseconds: an hour. */ export let EVERY = 60 * 60 * 1000;
19
+ /** The row a day's measurement is kept in. */ export let keptEid = (day)=>identityEid('kept', [
20
+ day
21
+ ]);
22
+ /**
23
+ * Whether a day is still to be measured: it has no row, its row does not
24
+ * name the file the store keeps, or it measured a journal without counting
25
+ * its changes.
26
+ *
27
+ * ```ts
28
+ * import { owed } from './service.ts'
29
+ * import { equal } from '@yaks/testing'
30
+ *
31
+ * equal(owed(undefined), true)
32
+ * equal(owed({}), false)
33
+ * equal(owed({}, '/a/yak.db'), true)
34
+ * equal(owed({ file: 'f' }, '/a/yak.db'), false)
35
+ * equal(owed({ tables: { journal_change: [1, 1] } }), true)
36
+ * equal(owed({ tables: { journal_change: [1, 1] }, changes: {} }), false)
37
+ * ```
38
+ */ export let owed = (kept, path)=>!kept || !!path && !kept.file || !!kept.tables && CHANGES in kept.tables && !kept.changes;
39
+ /**
40
+ * What a day's measurement writes: the file measured, where the store keeps
41
+ * one (@yaks/file's bundle for it), and the day's row naming it, with the
42
+ * changes the journal holds per component where it keeps one.
43
+ *
44
+ * ```ts
45
+ * import { keptEid, measured } from './service.ts'
46
+ * import { equal } from '@yaks/testing'
47
+ *
48
+ * let m = { bytes: 300, free: 0, tables: {} }
49
+ * let file = { entity: { eid: 'f' }, file: { path: 'a/yak.db', root: 'v' } }
50
+ * equal(measured('2026-10-21', 'T', m, [file]), [file, {
51
+ * entity: { eid: keptEid('2026-10-21') },
52
+ * kept: { day: '2026-10-21', at: 'T', ...m, file: 'f' },
53
+ * }])
54
+ * equal(measured('2026-10-21', 'T', m, [])[0].kept, { day: '2026-10-21', at: 'T', ...m })
55
+ * equal(measured('2026-10-21', 'T', m, [], { doc: 2 })[0].kept, { day: '2026-10-21', at: 'T', ...m, changes: { doc: 2 } })
56
+ * ```
57
+ */ export let measured = (day, at, m, file, changes)=>[
58
+ ...file,
59
+ {
60
+ entity: {
61
+ eid: keptEid(day)
62
+ },
63
+ kept: {
64
+ day,
65
+ at,
66
+ ...m,
67
+ ...file[0] ? {
68
+ file: file[0].entity.eid
69
+ } : {},
70
+ ...changes ? {
71
+ changes
72
+ } : {}
73
+ }
74
+ }
75
+ ];
76
+ /** One pass: measure the file, unless the day `now` falls in has been. A
77
+ * file that keeps a journal has its changes counted by `held` (its log's). */ export let pass = async (g, now = Date.now(), signal, held)=>{
78
+ if (!g.storage.measure) return;
79
+ let day = new Date(now).toISOString().slice(0, 10);
80
+ let [had] = await g.get([
81
+ keptEid(day)
82
+ ], [
83
+ 'kept'
84
+ ]);
85
+ let path = g.storage.file;
86
+ if (!owed(had?.kept, path)) return;
87
+ let m = await g.storage.measure(signal);
88
+ if (!m) return;
89
+ let file = path ? await onDisk(g, path) : [];
90
+ let changes = m.tables[CHANGES] ? await held?.() : undefined;
91
+ await g.apply(measured(day, new Date().toISOString(), m, file, changes), {
92
+ trusted: true
93
+ });
94
+ };
95
+ /** Measure, then look again every `every`, until the signal aborts. An
96
+ * already aborted signal is one pass. */ export let service = async (host, options = {}, signal = AbortSignal.abort())=>{
97
+ // The log the journal writes through on this host, where it keeps one.
98
+ let bound = host.storage?.statements ? host : undefined;
99
+ let read = host.reader?.statements?.query;
100
+ let held = read ? async ()=>heldRows(await read(heldSql()), host.graph.vocab) : bound && (()=>logFor(bound).held());
101
+ for(;;){
102
+ try {
103
+ await pass(host.graph, Date.now(), signal.aborted ? undefined : signal, held);
104
+ } catch (e) {
105
+ // A pass that failed is told, and the next one measures again.
106
+ ;
107
+ (host.report ?? console.error)(e, {
108
+ tags: {
109
+ step: 'journal measure'
110
+ }
111
+ });
112
+ }
113
+ if (signal.aborted) return;
114
+ await sleep(options.every ?? EVERY, signal);
115
+ if (signal.aborted) return;
116
+ }
117
+ };
118
+ //# sourceMappingURL=service.js.map
package/service.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.js","sources":["./service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;CAWC,GAED,SAAS,WAAW,oCAAyC;AAC7D,SAAS,KAAK,wBAA6B;AAC3C,SAAS,MAAM,gCAAqC;AACpD,SAAS,OAAO,oBAAmB;AACnC,SAAqB,MAAM,qBAAoB;AAC/C,SAAS,QAAQ,EAAE,OAAO,oBAAmB;AAE7C,kEAAkE,GAClE,OAAO,IAAI,QAAQ,KAAK,KAAK,KAAI;AAEjC,4CAA4C,GAC5C,OAAO,IAAI,UAAU,CAAC,MAAqB,YAAY,QAAQ;IAAC;GAAI,EAAC;AAKrE;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,IAAI,OAAO,CAAC,MAAY,OAC7B,CAAC,QAAS,CAAC,CAAC,QAAQ,CAAC,KAAK,IAAI,IAC7B,CAAC,CAAC,KAAK,MAAM,IAAI,WAAW,KAAK,MAAM,IAAI,CAAC,KAAK,OAAO,CAAC;AAE5D;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,IAAI,WA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SAAS,MAAM,KAAK,YAAY,KAAK,KAAK,CAAC,KAAK,IAC5D,SAAS,CAAC,IAAM,OAAO,OAAO,IAAI,EAAE;EACxC,OAAS;IACP,IAAI;MACF,MAAM,KACJ,KAAK,KAAK,EACV,KAAK,GAAG,IACR,OAAO,OAAO,GAAG,YAAY,QAC7B;IAEJ,EAAE,OAAO,GAAG;MACV,+DAA+D;;MAC9D,CAAC,KAAK,MAAM,IAAI,QAAQ,KAAK,EAAE,GAAG;QAAE,MAAM;UAAE,MAAM;QAAkB;MAAE;IACzE;IACA,IAAI,OAAO,OAAO,EAAE;IACpB,MAAM,MAAM,QAAQ,KAAK,IAAI,OAAO;IACpC,IAAI,OAAO,OAAO,EAAE;EACtB;AACF,EAAC"}
package/service.ts ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * What the file keeps, as a duty: the module a server imports at
3
+ * `@yaks/journal/service`. Once a UTC day it measures the store's file (its
4
+ * storage's `measure`) and keeps the day's `kept` row, which the History page
5
+ * reads (./page.ts), so looking costs nothing. The row names the file it
6
+ * measured, so a page about the disk finds the store's file and its free
7
+ * pages, and holds the changes the journal holds per component, counted from
8
+ * its log, so the page never counts them. A store that keeps no file of
9
+ * pages measures nothing.
10
+ *
11
+ * @module
12
+ */
13
+ import type { Bundle, Eid, Graph, Measure } from 'jsr:@yaks/graph@0.2.36'
14
+ import { identityEid } from '@yaks/graph/identity'
15
+ import { sleep } from '@yaks/fp'
16
+ import { onDisk } from '@yaks/file/local'
17
+ import { CHANGES } from './kept.js'
18
+ import { type Bound, logFor } from './graph.js'
19
+ import { heldRows, heldSql } from './held.js'
20
+
21
+ /** How long a pass waits for the next, in milliseconds: an hour. */
22
+ export let EVERY = 60 * 60 * 1000
23
+
24
+ /** The row a day's measurement is kept in. */
25
+ export let keptEid = (day: string): Eid => identityEid('kept', [day])
26
+
27
+ /** What a day's row says of itself, as far as {@link owed} asks. */
28
+ export type Had = { file?: unknown; tables?: object; changes?: unknown }
29
+
30
+ /**
31
+ * Whether a day is still to be measured: it has no row, its row does not
32
+ * name the file the store keeps, or it measured a journal without counting
33
+ * its changes.
34
+ *
35
+ * ```ts
36
+ * import { owed } from './service.ts'
37
+ * import { equal } from '@yaks/testing'
38
+ *
39
+ * equal(owed(undefined), true)
40
+ * equal(owed({}), false)
41
+ * equal(owed({}, '/a/yak.db'), true)
42
+ * equal(owed({ file: 'f' }, '/a/yak.db'), false)
43
+ * equal(owed({ tables: { journal_change: [1, 1] } }), true)
44
+ * equal(owed({ tables: { journal_change: [1, 1] }, changes: {} }), false)
45
+ * ```
46
+ */
47
+ export let owed = (kept?: Had, path?: string): boolean =>
48
+ !kept || (!!path && !kept.file) ||
49
+ (!!kept.tables && CHANGES in kept.tables && !kept.changes)
50
+
51
+ /**
52
+ * What a day's measurement writes: the file measured, where the store keeps
53
+ * one (@yaks/file's bundle for it), and the day's row naming it, with the
54
+ * changes the journal holds per component where it keeps one.
55
+ *
56
+ * ```ts
57
+ * import { keptEid, measured } from './service.ts'
58
+ * import { equal } from '@yaks/testing'
59
+ *
60
+ * let m = { bytes: 300, free: 0, tables: {} }
61
+ * let file = { entity: { eid: 'f' }, file: { path: 'a/yak.db', root: 'v' } }
62
+ * equal(measured('2026-10-21', 'T', m, [file]), [file, {
63
+ * entity: { eid: keptEid('2026-10-21') },
64
+ * kept: { day: '2026-10-21', at: 'T', ...m, file: 'f' },
65
+ * }])
66
+ * equal(measured('2026-10-21', 'T', m, [])[0].kept, { day: '2026-10-21', at: 'T', ...m })
67
+ * equal(measured('2026-10-21', 'T', m, [], { doc: 2 })[0].kept, { day: '2026-10-21', at: 'T', ...m, changes: { doc: 2 } })
68
+ * ```
69
+ */
70
+ export let measured = (
71
+ day: string,
72
+ at: string,
73
+ m: Measure,
74
+ file: Bundle[],
75
+ changes?: Record<string, number>,
76
+ ): Bundle[] => [
77
+ ...file,
78
+ {
79
+ entity: { eid: keptEid(day) },
80
+ kept: {
81
+ day,
82
+ at,
83
+ ...m,
84
+ ...file[0] ? { file: file[0].entity.eid } : {},
85
+ ...changes ? { changes } : {},
86
+ },
87
+ },
88
+ ]
89
+
90
+ /** One pass: measure the file, unless the day `now` falls in has been. A
91
+ * file that keeps a journal has its changes counted by `held` (its log's). */
92
+ export let pass = async (
93
+ g: Graph,
94
+ now: number = Date.now(),
95
+ signal?: AbortSignal,
96
+ held?: () => Record<string, number> | Promise<Record<string, number>>,
97
+ ): Promise<void> => {
98
+ if (!g.storage.measure) return
99
+ let day = new Date(now).toISOString().slice(0, 10)
100
+ let [had] = await g.get([keptEid(day)], ['kept'])
101
+ let path = g.storage.file
102
+ if (!owed(had?.kept as Had | undefined, path)) return
103
+ let m = await g.storage.measure(signal)
104
+ if (!m) return
105
+ let file = path ? await onDisk(g, path) : []
106
+ let changes = m.tables[CHANGES] ? await held?.() : undefined
107
+ await g.apply(
108
+ measured(day, new Date().toISOString(), m, file, changes),
109
+ { trusted: true },
110
+ )
111
+ }
112
+
113
+ /** Measure, then look again every `every`, until the signal aborts. An
114
+ * already aborted signal is one pass. */
115
+ export let service = async (
116
+ host: Partial<Bound> & {
117
+ graph: Graph
118
+ report?: (
119
+ error: unknown,
120
+ context?: { tags?: Record<string, string> },
121
+ ) => unknown
122
+ },
123
+ options: { every?: number } = {},
124
+ signal: AbortSignal = AbortSignal.abort(),
125
+ ): Promise<void> => {
126
+ // The log the journal writes through on this host, where it keeps one.
127
+ let bound = host.storage?.statements ? host as Bound : undefined
128
+ let read = host.reader?.statements?.query
129
+ let held = read
130
+ ? async () => heldRows(await read(heldSql()), host.graph.vocab)
131
+ : bound && (() => logFor(bound).held())
132
+ for (;;) {
133
+ try {
134
+ await pass(
135
+ host.graph,
136
+ Date.now(),
137
+ signal.aborted ? undefined : signal,
138
+ held,
139
+ )
140
+ } catch (e) {
141
+ // A pass that failed is told, and the next one measures again.
142
+ ;(host.report ?? console.error)(e, { tags: { step: 'journal measure' } })
143
+ }
144
+ if (signal.aborted) return
145
+ await sleep(options.every ?? EVERY, signal)
146
+ if (signal.aborted) return
147
+ }
148
+ }
package/tools.js ADDED
@@ -0,0 +1,110 @@
1
+ // `@yaks/journal/tools` — what an agent may ask the log: the function behind
2
+ // the `history` declaration in ./vocab.json, because the log answers one
3
+ // question people actually ask: what happened to this, and who did it. And
4
+ // the graph's branches, which its versions make possible (D-395): made,
5
+ // listed, merged, trashed and restored here, read and written through the graph's own
6
+ // tools. A merge with a conflict left writes nothing and answers the
7
+ // conflicts, each side by side, for a person to pick (./merge.ts).
8
+ //
9
+ // The answer is bundles, and each bundle is the transaction: `applied()`
10
+ // rebuilds what a write committed out of the log's own record, so a history row
11
+ // has the same shape as the write that produced it — the components it patched,
12
+ // or `$delete` if it deleted the entity. Which transaction it was — its place in
13
+ // the log, when it committed, whom it acted for and through what — is carried on
14
+ // `_tx`, this package's own word for a committed transaction, so a row reads as
15
+ // the moment it was and draws as one (./views.ts).
16
+ //
17
+ // There is no `undo` tool here and no feed. Undo is `undo(g, j)` in ./undo.ts —
18
+ // a write, and one a server has to decide it offers — and a feed is a cursor a
19
+ // consumer holds, not a question anybody types.
20
+ import { argsOf } from "@yaks/graph/call";
21
+ import { Refused } from "@yaks/graph/errors";
22
+ import { applied } from "./undo.js";
23
+ import { merge } from "./merge.js";
24
+ import { actorOf } from "@yaks/graph/provenance";
25
+ import { logFor } from "./graph.js";
26
+ // Which transaction it was: where it sits in the log, when it committed, whom
27
+ // it acted for and through what.
28
+ let stamp = (b)=>({
29
+ seq: b.seq,
30
+ at: b.at,
31
+ ...b.by ? {
32
+ by: b.by
33
+ } : {},
34
+ ...b.via ? {
35
+ via: b.via
36
+ } : {}
37
+ });
38
+ // One committed transaction as the patch it applied to one entity, stamped. The
39
+ // log is cut to that entity first, so a transaction that also moved something
40
+ // else reports only this entity's part of it.
41
+ let said = (b)=>applied(b).map((patch)=>({
42
+ ...patch,
43
+ _tx: stamp(b)
44
+ }));
45
+ // The graph's branches, or the reason it has none.
46
+ let branches = (graph)=>{
47
+ if (!graph.branches) {
48
+ throw new Refused('this graph keeps no branches: list @yaks/journal with versions on');
49
+ }
50
+ return graph.branches;
51
+ };
52
+ // A branch tool's answer: what it says about the branches, as data.
53
+ let told = (call, value)=>[
54
+ {
55
+ entity: {
56
+ eid: '$said'
57
+ },
58
+ output: {
59
+ source: call.entity.eid,
60
+ value
61
+ }
62
+ }
63
+ ];
64
+ // The branch `id`, or the refusal that names it.
65
+ let known = async (all, id, trash = false)=>{
66
+ let b = (await all.list(trash)).find((b)=>b.id == id);
67
+ if (!b) throw new Refused(`no branch ${id}`);
68
+ return b;
69
+ };
70
+ /** The functions behind the tools ./vocab.json declares — read over this
71
+ * host's storage, which is why this export is a factory. */ export let runs = (host)=>{
72
+ let j = logFor(host);
73
+ return {
74
+ history: (call)=>{
75
+ let args = argsOf(call);
76
+ let asked = String(args.entity ?? '').trim();
77
+ if (!asked) throw new Refused('history needs an entity');
78
+ if (host.reader?.tool) return host.reader.tool('history', call);
79
+ let n = args.limit == null ? undefined : Number(args.limit);
80
+ // Newest first: a history is read back from where the entity got to.
81
+ return j.history(asked, n).reverse().flatMap(said);
82
+ },
83
+ branch_new: async (call, graph)=>told(call, await branches(graph).make()),
84
+ branch_list: async (call, graph)=>told(call, await branches(graph).list(!!argsOf(call).trash)),
85
+ branch_delete: async (call, graph)=>{
86
+ let id = Number(argsOf(call).id);
87
+ let all = branches(graph);
88
+ let gone = await known(all, id);
89
+ await all.drop(id);
90
+ return told(call, (await all.list(true)).find((b)=>b.id == gone.id));
91
+ },
92
+ branch_restore: async (call, graph)=>{
93
+ let id = Number(argsOf(call).id);
94
+ let all = branches(graph);
95
+ await known(all, id, true);
96
+ await all.restore(id);
97
+ return told(call, await known(all, id));
98
+ },
99
+ branch_merge: async (call, graph)=>{
100
+ let args = argsOf(call);
101
+ let id = Number(args.id);
102
+ await known(branches(graph), id);
103
+ let picks = args.pick ?? [];
104
+ return told(call, await merge(graph)(id, picks, actorOf([
105
+ call
106
+ ])));
107
+ }
108
+ };
109
+ };
110
+ //# sourceMappingUR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