@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/rules.ts ADDED
@@ -0,0 +1,234 @@
1
+ // Declared rules, evaluated over the map. A rule is a query (@yaks/graph's
2
+ // join.ts parses it into a plan of patterns, one per entity), and @yaks/sqlite
3
+ // answers one by compiling the plan into a statement. This is the same answer
4
+ // worked out in memory: each pattern's filter is an ordinary query that
5
+ // @yaks/match answers over the store's own indexes, and what is left is the
6
+ // join, every pattern's entity and the values its variables took, kept where
7
+ // the variables agree.
8
+ //
9
+ // The store folds the batch in before asking (./store.ts `bindings`), so what
10
+ // this file is handed is the graph as the batch would leave it, the entities
11
+ // the batch is about, and what it removed. The first is the source a filter
12
+ // reads; the second is the anchor, since a rule is about a batch and not the
13
+ // whole graph: at least one of its patterns binds an entity the batch wrote,
14
+ // so a gated rule does not fire on every entity that ever failed its gate. The
15
+ // third answers `-comp`, the one clause no row can answer.
16
+ //
17
+ // The anchor is also the plan. An anchored pattern is read from the batch
18
+ // alone, and each pattern after it is found through what the ones before it
19
+ // bound: its entity by id, or its property through the store's keyed index.
20
+ // A keystroke's batch is one entity, so a rule over it reads a handful of
21
+ // bundles, however large the page's graph.
22
+
23
+ import type { Bind, Binding, Eid, Match, Pattern } from 'jsr:@yaks/graph@0.2.36'
24
+ import { collected } from '@yaks/graph/declared'
25
+ import {
26
+ type Bundle,
27
+ filter,
28
+ type Index,
29
+ keyOf,
30
+ matcher,
31
+ type MatchOpts,
32
+ } from '@yaks/match'
33
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
34
+ import { Unknown } from '@yaks/vocab/runtime'
35
+ import { Refused } from '@yaks/graph/errors'
36
+
37
+ // Where a variable is filled from: an `id` (a pattern's entity, or a
38
+ // reference) or a plain `value`, and how to read it off a bundle. A slot on one
39
+ // stored property of the bundle itself names it, so a join can look the value
40
+ // up in the keyed index instead of reading every candidate.
41
+ type Slot = {
42
+ kind: 'id' | 'value'
43
+ read: (b: Bundle, x: Index) => unknown
44
+ at?: [comp: string, prop: string]
45
+ }
46
+
47
+ // One property, as a read of a bundle: its computed rule where the vocabulary
48
+ // derives it, else what the bundle holds.
49
+ let reader = (comp: string, prop: string, opts: MatchOpts) => {
50
+ let computed = opts.computed?.[`${comp}.${prop}`]
51
+ return (b: Bundle | undefined, x: Index): unknown =>
52
+ !b
53
+ ? null
54
+ : computed
55
+ ? computed(b, x)
56
+ : (b[comp] as Record<string, unknown> | undefined)?.[prop] ?? null
57
+ }
58
+
59
+ // A bound property, followed through the references before its leaf. A path
60
+ // ending `entity.eid` reads the eid of the entity it reaches, a plain value.
61
+ let slot = (v: Vocab, bind: Bind, opts: MatchOpts): Slot => {
62
+ let path = bind.path.join('.')
63
+ let hops = v.aim(path)
64
+ let leaf = hops[hops.length - 1]
65
+ if (!leaf?.prop) {
66
+ throw new Unknown(path, `$${bind.name} names no property: .${path}`)
67
+ }
68
+ let spine = leaf.comp == 'entity' && leaf.prop == 'eid'
69
+ let prop = spine ? undefined : v.prop(leaf.comp, leaf.prop)
70
+ if (!prop && !spine) {
71
+ throw new Unknown(path, `no property ${path} for $${bind.name}`)
72
+ }
73
+ let reads = hops.map((h) => reader(h.comp, h.prop, opts))
74
+ let kind: Slot['kind'] = prop?.category == 'ref' ? 'id' : 'value'
75
+ if (hops.length == 1) {
76
+ let at: Slot['at'] = !prop || prop.computed
77
+ ? undefined
78
+ : [leaf.comp, leaf.prop]
79
+ return { kind, read: reads[0], at }
80
+ }
81
+ return {
82
+ kind,
83
+ read: (b, x) => {
84
+ let at: Bundle | undefined = b
85
+ for (let r of reads.slice(0, -1)) {
86
+ let eid = r(at, x)
87
+ at = typeof eid == 'string' ? x.of(eid) : undefined
88
+ }
89
+ return reads[reads.length - 1](at, x)
90
+ },
91
+ }
92
+ }
93
+
94
+ let eidOf = (b: Bundle) => b.entity.eid
95
+
96
+ // One pattern, compiled once per evaluation: the entities it selects, the test
97
+ // for one candidate, and its variables' slots. A bound property implies its
98
+ // component is worn, and a gate that it is not, as the SQL a pattern compiles
99
+ // to joins the one and left-joins the other.
100
+ let compiled = (p: Pattern, v: Vocab, opts: MatchOpts) => {
101
+ let select = matcher(p.filter, v, opts)
102
+ let test = filter(p.filter, v, opts)
103
+ let worn = p.binds.map((b) => v.aim(b.path.join('.'))[0].comp)
104
+ let fits = (b: Bundle) =>
105
+ worn.every((c) => b[c] != null) && p.gates.every((c) => b[c] == null)
106
+ let slots: [string, Slot][] = p.binds.map((b) => [b.name, slot(v, b, opts)])
107
+ if (p.entity) slots.unshift([p.entity, { kind: 'id', read: eidOf }])
108
+ return {
109
+ entity: p.entity,
110
+ slots,
111
+ all: (x: Index) => select(x).filter(fits),
112
+ one: (b: Bundle | undefined, x: Index): b is Bundle =>
113
+ !!b && test(b, x) && fits(b),
114
+ }
115
+ }
116
+
117
+ type Compiled = ReturnType<typeof compiled>
118
+ type Vars = Record<string, unknown>
119
+
120
+ // A candidate's variables joined to the ones already bound, or null where one
121
+ // disagrees. A variable is the same value in every slot, and nothing equals an
122
+ // absent one, as in SQL; values compare as a keyed index files them.
123
+ let joined = (slots: [string, Slot][], b: Bundle, x: Index, vars: Vars) => {
124
+ let out = vars
125
+ for (let [name, s] of slots) {
126
+ let value = s.read(b, x)
127
+ if (name in out) {
128
+ if (value == null || keyOf(value) !== keyOf(out[name])) return null
129
+ continue
130
+ }
131
+ if (out === vars) out = { ...vars }
132
+ out[name] = value
133
+ }
134
+ return out
135
+ }
136
+
137
+ // One flat level of a match: its patterns joined, anchored to the batch when
138
+ // `anchor` is given.
139
+ let level = (
140
+ plan: Match,
141
+ x: Index,
142
+ anchor: ReadonlySet<Eid> | undefined,
143
+ v: Vocab,
144
+ opts: MatchOpts,
145
+ ): Binding[] => {
146
+ let pats = plan.patterns.map((p) => p.makes ? null : compiled(p, v, opts))
147
+ // An id and a value are not comparable, so a variable that is an entity in
148
+ // one place and a plain value in another is refused rather than coerced:
149
+ // the query is the caller's.
150
+ let kinds = new Map<string, Slot['kind']>()
151
+ for (let [name, s] of pats.flatMap((p) => p?.slots ?? [])) {
152
+ if ((kinds.get(name) ?? s.kind) != s.kind) {
153
+ throw new Refused(
154
+ `$${name} is an entity in one place and a plain value in another; ` +
155
+ `end the entity's path in .entity.eid to compare its eid as a value`,
156
+ )
157
+ }
158
+ kinds.set(name, s.kind)
159
+ }
160
+ let live = pats.flatMap((p, i) => p ? [i] : [])
161
+ if (anchor && !live.length) return []
162
+ let out: Binding[] = []
163
+ let seen = new Set<string>()
164
+ let entities: (Eid | null)[] = plan.patterns.map(() => null)
165
+ // What a pattern could bind, given what the patterns before it bound.
166
+ let found = (p: Compiled, vars: Vars): Iterable<Bundle | undefined> => {
167
+ let eid = p.entity && vars[p.entity]
168
+ if (eid != null) return [x.of(String(eid))]
169
+ for (let [name, s] of p.slots) {
170
+ let key = s.at && keyOf(vars[name])
171
+ if (key !== undefined && s.at && x.keyed) {
172
+ return x.keyed(s.at[0], s.at[1], key).values()
173
+ }
174
+ }
175
+ return p.all(x)
176
+ }
177
+ let walk = (
178
+ order: number[],
179
+ at: number,
180
+ vars: Vars,
181
+ first?: Iterable<Eid>,
182
+ ) => {
183
+ if (at == order.length) {
184
+ let row = {
185
+ entities: [...entities],
186
+ vars: Object.fromEntries(plan.vars.map((n) => [n, vars[n] ?? null])),
187
+ }
188
+ let key = JSON.stringify(row)
189
+ if (seen.has(key)) return
190
+ seen.add(key)
191
+ out.push(row)
192
+ return
193
+ }
194
+ let i = order[at]
195
+ let p = pats[i]!
196
+ let from = first ? [...first].map((eid) => x.of(eid)) : found(p, vars)
197
+ for (let b of from) {
198
+ if (!p.one(b, x)) continue
199
+ let next = joined(p.slots, b, x, vars)
200
+ if (!next) continue
201
+ entities[i] = b.entity.eid
202
+ walk(order, at + 1, next)
203
+ }
204
+ entities[i] = null
205
+ }
206
+ // Anchored, each pattern in turn is the one read from the batch and the rest
207
+ // are found through it; a row two turns both find is kept once.
208
+ let orders = anchor
209
+ ? live.map((k) => [k, ...live.filter((i) => i != k)])
210
+ : [live]
211
+ for (let order of orders) walk(order, 0, {}, anchor)
212
+ return out
213
+ }
214
+
215
+ /**
216
+ * Evaluate declared rules' matches over a source (@yaks/graph `Tx.bindings`):
217
+ * each match's bindings, with its collections attached. `anchor` is the set of
218
+ * entities the batch is about, which every outer binding must touch; left out,
219
+ * the match is asked outright, as a template's invocation asks it.
220
+ */
221
+ export let bindings = (
222
+ matches: Match[],
223
+ x: Index,
224
+ anchor: ReadonlySet<Eid> | undefined,
225
+ v: Vocab,
226
+ opts: MatchOpts = {},
227
+ ): Binding[][] =>
228
+ matches.map((m) =>
229
+ collected(
230
+ m,
231
+ (plan, anchored) =>
232
+ level(plan, x, anchored ? anchor : undefined, v, opts),
233
+ )
234
+ )