@yaks/api 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 (152) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +956 -2
  3. package/_dist/actor.d.ts +59 -0
  4. package/_dist/actor.d.ts.map +1 -0
  5. package/_dist/address.d.ts +33 -0
  6. package/_dist/address.d.ts.map +1 -0
  7. package/_dist/asset.d.ts +15 -0
  8. package/_dist/asset.d.ts.map +1 -0
  9. package/_dist/batches.d.ts +4 -0
  10. package/_dist/batches.d.ts.map +1 -0
  11. package/_dist/body.d.ts +7 -0
  12. package/_dist/body.d.ts.map +1 -0
  13. package/_dist/deno.d.ts +38 -0
  14. package/_dist/deno.d.ts.map +1 -0
  15. package/_dist/doors.d.ts +134 -0
  16. package/_dist/doors.d.ts.map +1 -0
  17. package/_dist/graph.d.ts +17 -0
  18. package/_dist/graph.d.ts.map +1 -0
  19. package/_dist/headers.d.ts +5 -0
  20. package/_dist/headers.d.ts.map +1 -0
  21. package/_dist/log.d.ts +253 -0
  22. package/_dist/log.d.ts.map +1 -0
  23. package/_dist/mod.d.ts +71 -0
  24. package/_dist/mod.d.ts.map +1 -0
  25. package/_dist/publish.d.ts +7 -0
  26. package/_dist/publish.d.ts.map +1 -0
  27. package/_dist/reached.d.ts +145 -0
  28. package/_dist/reached.d.ts.map +1 -0
  29. package/_dist/receipts.d.ts +153 -0
  30. package/_dist/receipts.d.ts.map +1 -0
  31. package/_dist/refuse.d.ts +51 -0
  32. package/_dist/refuse.d.ts.map +1 -0
  33. package/_dist/relay.d.ts +3 -0
  34. package/_dist/relay.d.ts.map +1 -0
  35. package/_dist/request.d.ts +79 -0
  36. package/_dist/request.d.ts.map +1 -0
  37. package/_dist/requests.d.ts +7 -0
  38. package/_dist/requests.d.ts.map +1 -0
  39. package/_dist/route.d.ts +71 -0
  40. package/_dist/route.d.ts.map +1 -0
  41. package/_dist/routed.d.ts +33 -0
  42. package/_dist/routed.d.ts.map +1 -0
  43. package/_dist/routes.d.ts +46 -0
  44. package/_dist/routes.d.ts.map +1 -0
  45. package/_dist/save.d.ts +6 -0
  46. package/_dist/save.d.ts.map +1 -0
  47. package/_dist/socket.d.ts +73 -0
  48. package/_dist/socket.d.ts.map +1 -0
  49. package/_dist/subs.d.ts +134 -0
  50. package/_dist/subs.d.ts.map +1 -0
  51. package/_dist/timing.d.ts +8 -0
  52. package/_dist/timing.d.ts.map +1 -0
  53. package/_dist/tools.d.ts +80 -0
  54. package/_dist/tools.d.ts.map +1 -0
  55. package/_dist/vocab.d.ts +6 -0
  56. package/_dist/vocab.d.ts.map +1 -0
  57. package/access.js +32 -0
  58. package/access.js.map +1 -0
  59. package/access.ts +42 -0
  60. package/actor.js +75 -0
  61. package/actor.js.map +1 -0
  62. package/actor.ts +106 -0
  63. package/address.js +42 -0
  64. package/address.js.map +1 -0
  65. package/address.ts +49 -0
  66. package/admission.js +71 -0
  67. package/admission.js.map +1 -0
  68. package/admission.ts +64 -0
  69. package/asset.js +37 -0
  70. package/asset.js.map +1 -0
  71. package/asset.ts +47 -0
  72. package/batches.js +92 -0
  73. package/batches.js.map +1 -0
  74. package/batches.ts +96 -0
  75. package/body.js +51 -0
  76. package/body.js.map +1 -0
  77. package/body.ts +82 -0
  78. package/deno.js +88 -0
  79. package/deno.js.map +1 -0
  80. package/deno.json +1 -0
  81. package/deno.ts +150 -0
  82. package/doors.js +435 -0
  83. package/doors.js.map +1 -0
  84. package/doors.ts +570 -0
  85. package/graph.js +12 -0
  86. package/graph.js.map +1 -0
  87. package/graph.ts +23 -0
  88. package/headers.js +5 -0
  89. package/headers.js.map +1 -0
  90. package/headers.ts +9 -0
  91. package/interest.js +224 -0
  92. package/interest.js.map +1 -0
  93. package/interest.ts +264 -0
  94. package/log.js +1011 -0
  95. package/log.js.map +1 -0
  96. package/log.ts +1035 -0
  97. package/mod.js +69 -0
  98. package/mod.js.map +1 -0
  99. package/mod.ts +142 -0
  100. package/package.json +75 -4
  101. package/peer_query.js +164 -0
  102. package/peer_query.js.map +1 -0
  103. package/peer_query.ts +158 -0
  104. package/publish.js +7 -0
  105. package/publish.js.map +1 -0
  106. package/publish.ts +16 -0
  107. package/reached.js +456 -0
  108. package/reached.js.map +1 -0
  109. package/reached.ts +549 -0
  110. package/receipts.js +543 -0
  111. package/receipts.js.map +1 -0
  112. package/receipts.ts +749 -0
  113. package/refuse.js +120 -0
  114. package/refuse.js.map +1 -0
  115. package/refuse.ts +179 -0
  116. package/relay.js +249 -0
  117. package/relay.js.map +1 -0
  118. package/relay.ts +284 -0
  119. package/request.js +218 -0
  120. package/request.js.map +1 -0
  121. package/request.ts +235 -0
  122. package/requests.js +250 -0
  123. package/requests.js.map +1 -0
  124. package/requests.ts +257 -0
  125. package/route.js +139 -0
  126. package/route.js.map +1 -0
  127. package/route.ts +228 -0
  128. package/routed.js +25 -0
  129. package/routed.js.map +1 -0
  130. package/routed.ts +53 -0
  131. package/routes.js +154 -0
  132. package/routes.js.map +1 -0
  133. package/routes.ts +201 -0
  134. package/save.js +341 -0
  135. package/save.js.map +1 -0
  136. package/save.ts +393 -0
  137. package/socket.js +398 -0
  138. package/socket.js.map +1 -0
  139. package/socket.ts +496 -0
  140. package/subs.js +2295 -0
  141. package/subs.js.map +1 -0
  142. package/subs.ts +2979 -0
  143. package/timing.js +17 -0
  144. package/timing.js.map +1 -0
  145. package/timing.ts +26 -0
  146. package/tools.js +251 -0
  147. package/tools.js.map +1 -0
  148. package/tools.ts +315 -0
  149. package/vocab.js +18 -0
  150. package/vocab.js.map +1 -0
  151. package/vocab.json +93 -0
  152. package/vocab.ts +18 -0
package/subs.ts ADDED
@@ -0,0 +1,2979 @@
1
+ // Subscriptions: a saved query whose result is pushed again whenever a
2
+ // committed transaction changes it.
3
+ //
4
+ // The registry registers a hook on the graph's own `effect` phase, so every
5
+ // commit is seen — the ones that arrived through `POST /apply` and the ones
6
+ // the application wrote straight to the graph. A commit is handled in two
7
+ // steps: read the changed entities once, whole, then test them against each
8
+ // subscription.
9
+ //
10
+ // The writer does not wait for that. The hook starts the pass and returns, so a
11
+ // tool call's bookkeeping rows are answered at their commit, however many tabs
12
+ // are open and however long their windows take to read. Commits that arrive
13
+ // while a pass is still reading join the next one, so a busy writer costs the
14
+ // subscribers one more pass, not one per commit.
15
+ //
16
+ // Two modes, chosen when the subscription opens:
17
+ //
18
+ // Routed the query asks only about each entity itself, so it joins
19
+ // the registry's network (@yaks/match `net`), which every
20
+ // subscription of that kind shares. A changed entity moves
21
+ // through the network once, into the subscriptions it matches
22
+ // and out of the ones it left — the query is never run again,
23
+ // however large the set is, and a commit costs what it
24
+ // changed, not how many subscriptions are open.
25
+ // Refresh the query follows a reference, walks, counts, orders or
26
+ // limits, so its result can change when an entity the query
27
+ // never named does. A dependency with a reference back to the
28
+ // answer refreshes that entity alone. An unlocated dependency
29
+ // or a window refreshes the whole query (./interest.ts).
30
+ //
31
+ // The membership Set is what makes "this entity no longer matches" as cheap
32
+ // as "this entity now matches": a client cannot work out that something left
33
+ // its set — it never sees the row that stopped matching — so the server is
34
+ // what remembers who is in.
35
+
36
+ import type {
37
+ Bundle,
38
+ Eid,
39
+ Graph,
40
+ News,
41
+ Query,
42
+ ReadOpts,
43
+ Reads,
44
+ Taken,
45
+ } from '@yaks/graph'
46
+ import { type Asker, asker, asking } from '@yaks/graph/asker'
47
+ import { namesBetween } from '@yaks/graph'
48
+ import { after, groupBy, isPromise, over } from '@yaks/fp'
49
+ import { during, link, parent, peek, scope, unlink } from '@yaks/trace'
50
+ import type { TransientFrame } from '@yaks/graph'
51
+ import { coalesced, composed, dead, formed } from '@yaks/graph/bundle'
52
+ import { transient } from '@yaks/graph/read'
53
+ import type {
54
+ Agg,
55
+ Coverage,
56
+ Projected,
57
+ Projection,
58
+ ReadView,
59
+ Reduced,
60
+ } from '@yaks/graph'
61
+ import {
62
+ aggregate,
63
+ flat,
64
+ named,
65
+ only,
66
+ project,
67
+ projection,
68
+ reduced,
69
+ } from '@yaks/graph/read'
70
+ import { comps } from '@yaks/graph/bundle'
71
+ import { Refused } from '@yaks/graph/errors'
72
+ import { matcher, net, rows as matchRows } from '@yaks/match'
73
+ import {
74
+ type And,
75
+ bare,
76
+ drifts,
77
+ line,
78
+ parse,
79
+ whole as said,
80
+ windowOf,
81
+ } from '@yaks/query'
82
+ import { paceOf, saveOf, syncOf } from '@yaks/vocab'
83
+ import { published } from './publish.js'
84
+ import { cares, type Interest, interest, refers } from './interest.js'
85
+ import { peerPlan, peerTargets } from './peer_query.js'
86
+ import { fault, type Refusal, refusal } from './refuse.js'
87
+ import { type Relay, relay as relaying, type Timer } from './relay.js'
88
+ import { type PeerWriter, saving } from './save.js'
89
+
90
+ /** Which revision of the store a frame's rows were read at: one number, or,
91
+ * from a door over several stores, each store's under its name (@yaks/reach).
92
+ * A store's revision only moves forward, across restarts too, so of two
93
+ * frames about one row the one with the higher revision is the newer. */
94
+ export type Revision = number | Record<string, number>
95
+
96
+ /**
97
+ * One push to one subscriber. `bundles` are whole entities that are now in
98
+ * the set — for the raw feed (`subscribe: true`), the committed transaction
99
+ * as it was applied, one bundle per entity, exactly as its writer's `/apply`
100
+ * response read. `gone` names the entities that left the set, whether they
101
+ * were deleted or merely stopped matching. `refused` replaces both when the
102
+ * subscription could not be opened.
103
+ */
104
+ export type Frame = {
105
+ /** Peer values held by this connection need to be sent again after wake. */
106
+ resay?: true
107
+ /** the token a socket subscriber echoes after applying this frame */
108
+ ack?: string
109
+ /** a whole answer replacing the subscriber's previous membership and order */
110
+ reset?: boolean
111
+ transient?: TransientFrame[]
112
+ transientReset?: Eid[]
113
+ /** the subscription this frame answers */
114
+ id: string
115
+ /** the store's revision when the frame left: its rows are no newer */
116
+ revision?: Revision
117
+ /** the revision of the subscription's previous frame, absent on its first:
118
+ * a subscriber that last heard another has missed one */
119
+ since?: Revision
120
+ /** the entities now in the set (whole), or the composed transaction for a
121
+ * raw feed */
122
+ bundles?: Bundle[]
123
+ /** what each of `bundles` covers, where a `.fields` projection narrowed it:
124
+ * a property covered and left out is absent, one not covered was not read */
125
+ coverage?: Record<Eid, Coverage>
126
+ /** the entities a `.fields` projection's paths reach from the set, each
127
+ * narrowed to what was read off it: carried along, never in the set */
128
+ peers?: Bundle[]
129
+ /** what each of `peers` covers */
130
+ peerCoverage?: Record<Eid, Coverage>
131
+ /** entities no path reaches any more */
132
+ peerGone?: Eid[]
133
+ /** entities that left the set — deleted, or no longer matching */
134
+ gone?: Eid[]
135
+ /**
136
+ * `sync: peers` components being relayed: a cursor, a caret, a presence
137
+ * dot. Components declaring `save` also retain a stored snapshot. A value cleared by its writer — or by
138
+ * that writer's connection closing, or by its own duration running out —
139
+ * arrives as the component set to `null`.
140
+ */
141
+ relay?: Bundle[]
142
+ /** why the subscription was refused, when it was */
143
+ refused?: Refusal
144
+ } & Partial<Reduced>
145
+
146
+ // Whether a frame says what the store holds: rows, members leaving, or a
147
+ // reduction. One carrying only relayed or transient values says what peers
148
+ // are doing, which no revision of the store orders.
149
+ let says = (f: Frame) =>
150
+ !!(f.bundles || f.gone || f.peers || f.peerGone) ||
151
+ 'count' in f || 'tally' in f || 'distinct' in f
152
+
153
+ /** Where a subscriber's frames go. One sink per client — the socket layer
154
+ * makes one per connection, and the registry keys subscriptions by it. */
155
+ export type Sink = (frame: Frame) => void
156
+
157
+ /** What a subscriber asks for: a query string, or `true` for the raw feed of
158
+ * every committed transaction. */
159
+ export type Ask = string | true
160
+
161
+ /** Saved watches recovered together after their owner lost its memory, each
162
+ * with its opener: the read it asks as and the writer its socket holds. */
163
+ export type Opening = {
164
+ sink: Sink
165
+ id: string
166
+ query: Ask
167
+ opts?: ReadOpts
168
+ writer?: PeerWriter
169
+ }
170
+
171
+ /** The subscription registry: what the socket layer talks to, and what an
172
+ * application can drive directly. */
173
+ export type Subs = {
174
+ /** Vocabulary for decoding binary relay properties at the JSON door. */
175
+ vocab?: import('@yaks/vocab').Vocab
176
+ /** Runtime activity target, shared with the graph even through read overlays. */
177
+ activity?: object
178
+ /** Read bundles using the graph's query and read-option contract, with held
179
+ * peer values unless `durable: true` selects storage alone. */
180
+ read: Graph['read']
181
+ /** Observe changes to held peer values after registry work has released.
182
+ * Observers may read the registry or write the graph. */
183
+ observe: (fn: (bundles: Bundle[]) => void | Promise<unknown>) => () => void
184
+ /** Answer one query from storage and the peer values held right now. */
185
+ snapshot: Reads<Bundle[] | Reduced | Promise<Bundle[] | Reduced>>
186
+ /** open (or replace) a subscription and send its current set, as `opts`
187
+ * reads; `writer` is who opened it, for a registry that vouches its opener
188
+ * onward ({@link import('./reached.ts').reached}) */
189
+ open: (
190
+ sink: Sink,
191
+ id: string,
192
+ query: Ask,
193
+ opts?: ReadOpts,
194
+ writer?: PeerWriter,
195
+ ) => void | Promise<void>
196
+ /** Reopen saved watches. A cold peer-only recovery may register proven
197
+ * static durable interests without repeating the page's held snapshot. */
198
+ restore: (openings: Opening[], deferStatic?: boolean) => void | Promise<void>
199
+ /** Answer deferred static watches on an explicit read/handshake. */
200
+ resume?: () => void | Promise<void>
201
+ /** Stop observation and cancel registry reads; admitted saves keep running. */
202
+ stop: () => void
203
+ /** close one subscription */
204
+ close: (sink: Sink, id: string) => void | Promise<void>
205
+ /** close every subscription a sink holds — a client went away */
206
+ drop: (sink: Sink) => void | Promise<void>
207
+ /** a transaction committed: push what changed to whoever is watching */
208
+ commit: (applied: Bundle[]) => void | Promise<void>
209
+ /** what other hosts committed, as a feed hands it: pushed as one pass, and
210
+ * every answer read again first when the feed missed some */
211
+ hear: (news: News) => void | Promise<void>
212
+ /** Reconcile query answers when the store's revision changed outside this
213
+ * registry. The host decides when to check; opening also checks before
214
+ * reusing a retained answer. */
215
+ check: () => void | Promise<void>
216
+ /**
217
+ * `sync: peers` components from one sink: forwarded to everyone else
218
+ * watching those entities, and held under this sink until it closes
219
+ * (relay.ts). Components declaring `save` also keep snapshots through apply.
220
+ * Queries that read peer
221
+ * components update their membership against the value now held.
222
+ */
223
+ relay: (
224
+ sink: Sink,
225
+ bundles: Bundle[],
226
+ writer?: PeerWriter,
227
+ ) => void | Promise<void>
228
+ /** Socket inputs share one short fan-out batch across writers. Held values
229
+ * and ownership change immediately; the returned promise follows delivery. */
230
+ enqueue?: (
231
+ sink: Sink,
232
+ bundles: Bundle[],
233
+ writer?: PeerWriter,
234
+ ) => void | Promise<void>
235
+ /** The vocabulary's cadence for a peer component, if it declares one. */
236
+ pace?: (comp: string) => number | null
237
+ /** The query deciding when a peer component is saved. */
238
+ save?: (comp: string) => string | null
239
+ /** The registry's clock, as {@link subscriptions} was given it: the time a
240
+ * socket serving it reads (relay pace, clock replies) and how it sets its
241
+ * timers (frame queues). Unset, the runtime's. */
242
+ now?: () => number
243
+ timer?: Timer
244
+ /** The keys one sink's relayed values are held under — small enough to
245
+ * store somewhere that outlives this process's memory. */
246
+ relaying: (sink: Sink) => string[]
247
+ /** Take those keys back after such a loss, so a close still clears them. */
248
+ relayed: (sink: Sink, keys: string[]) => void | Promise<void>
249
+ }
250
+
251
+ /** What a socket asks of a registry (./socket.ts `attach`): to open, close
252
+ * and drop subscriptions and take relayed values. A {@link Subs} is one, and
253
+ * so is a registry over graphs it can only ask (./reached.ts). */
254
+ export type Listening =
255
+ & Pick<Subs, 'open' | 'close' | 'drop' | 'relay'>
256
+ & Partial<Pick<Subs, 'activity' | 'vocab' | 'enqueue' | 'pace' | 'now'>>
257
+
258
+ /** A listener that can resume the interests of a hibernating socket. */
259
+ export type RecoverableListening =
260
+ & Listening
261
+ & Pick<
262
+ Subs,
263
+ 'restore' | 'resume' | 'relaying' | 'relayed' | 'timer' | 'save'
264
+ >
265
+
266
+ type Joint<T> = {
267
+ value: T | Promise<T>
268
+ /** Aborted once every owner let go: an owner arriving after must start the
269
+ * work again. */
270
+ cancelled: AbortSignal
271
+ /** Make the signal's owner one of the work's owners. */
272
+ share: (signal?: AbortSignal) => void
273
+ }
274
+
275
+ type Sub = {
276
+ /** the revision of the last frame sent ({@link Frame.since}) */
277
+ said?: number
278
+ loading?: boolean
279
+ dirty?: boolean
280
+ abort?: AbortController
281
+ id: string
282
+ sink: Sink
283
+ /** the raw feed of committed transactions, rather than a query */
284
+ raw: boolean
285
+ /** Interests stand, but the page's retained snapshot was not reread here.
286
+ * Its first relevant durable change owes a complete scoped reset. */
287
+ deferred?: boolean
288
+ /** the query string (empty for a raw feed) */
289
+ query: string
290
+ ast?: And
291
+ window?: boolean
292
+ view?: ReadView
293
+ opts?: ReadOpts
294
+ /** who opened it, whom its reads after a commit answer too */
295
+ asker?: Asker
296
+ send: (frame: Frame) => void | Promise<void>
297
+ /** the entities currently in the set */
298
+ members: Set<Eid>
299
+ fields: Map<Eid, Set<string>>
300
+ /** the entities each member's sent row references */
301
+ targets: Map<Eid, Eid[]>
302
+ /** true when the registry's network decides membership, false when this
303
+ * subscription runs its query again instead */
304
+ routed: boolean
305
+ network?: ReturnType<typeof net<Sub>>
306
+ policy?: Interest | null
307
+ policyDependencies?: readonly string[]
308
+ policyRefs?: boolean
309
+ /** the query reads a component held by peers rather than storage */
310
+ peer: boolean
311
+ /** the durable rows that may match a query reading peers */
312
+ durable?: And | null
313
+ candidates?: Bundle[] | Promise<Bundle[]>
314
+ /** one reference through which this query reads a peer value */
315
+ ref?: { comp: string; prop: string; far: Set<string> }
316
+ /** the components its rows carry, or `null` for every one (@yaks/graph
317
+ * `named`) */
318
+ want?: Set<string> | null
319
+ /** its `.fields` projection, when it asks for one */
320
+ plan?: Projection | null
321
+ /** a pushed bundle cut the way the first answer was */
322
+ cut: (b: Bundle) => Bundle
323
+ /** the entities its projection's paths reach from the set */
324
+ riders: Set<Eid>
325
+ /** the reduction an aggregate query asks for, and its last answer */
326
+ agg?: Agg
327
+ answer?: string
328
+ /** what a refresh or an aggregate is read from, or `null` when every
329
+ * commit can move it */
330
+ reads?: Interest | null
331
+ /** the answer this subscription shares with every other asking the same */
332
+ shared?: Shared
333
+ /** closed, and standing only to keep its shared answer current */
334
+ kept?: boolean
335
+ }
336
+
337
+ // A routed answer held in memory: the rows a client subscribed all along
338
+ // holds, kept current by the network from what each commit moved, never by
339
+ // asking again. Subscriptions asking the same query with the same options
340
+ // share one, and the last to close leaves it standing, so a page that lets go
341
+ // of a watch and asks for it again (a map walked back across, a reload) is
342
+ // answered from memory. Answers hold at most HELD rows; closed ones KEPT rows
343
+ // between them, and KEEP answers however few rows each holds (an empty answer
344
+ // still holds its subscription), the longest unasked let go first. The
345
+ // answers read for openings until the next commit hold OPENED rows between
346
+ // them: a page's whole set of watches on a large app store (peterson/ancestry's
347
+ // 22 listings and their neighbours, about 40,000 rows).
348
+ type Shared = { key: string; rows: Map<Eid, Bundle>; users: Set<Sub> }
349
+ const HELD = 512, KEPT = 8192, KEEP = 256, OPENED = 32_768
350
+
351
+ // Membership and projection use storage's vocabulary; delivery uses the caller's.
352
+ // A subscriber's line is its own whole query (@yaks/query `whole`).
353
+ let queryOf = (sub: Sub, q = sub.query): Taken => {
354
+ if (!sub.ast) return said(q)
355
+ if (q == sub.query) return sub.ast
356
+ return {
357
+ ...sub.ast,
358
+ clauses: [
359
+ ...sub.ast.clauses,
360
+ ...parse(q.slice(sub.query.length)).clauses,
361
+ ],
362
+ }
363
+ }
364
+
365
+ // What one commit did to one routed subscription: the entities now in its set,
366
+ // the ones among them that were not in it before, and the ones that left it.
367
+ type Moved = { bundles: Bundle[]; joined: Eid[]; gone: Eid[] }
368
+
369
+ // A query's answer as a subscription holds it: the entities in its set, and
370
+ // the ones its projection's paths reach from them.
371
+ type Answer = Projected | Promise<Projected>
372
+
373
+ let answered = (found: Bundle[]): Projected => ({
374
+ found,
375
+ reached: [],
376
+ covers: new Map(),
377
+ })
378
+
379
+ let whole = (b: Bundle) => b
380
+
381
+ // Work several owners share, cancelled only once every owner has let go:
382
+ // one owner cancelling ends no answer another still waits on. An owner
383
+ // without a signal never lets go.
384
+ let jointly = <T>(
385
+ work: (signal: AbortSignal) => T | Promise<T>,
386
+ ): Joint<T> => {
387
+ let joint = new AbortController()
388
+ let owners = 0, held = false
389
+ let offs: (() => void)[] = []
390
+ let value = work(joint.signal)
391
+ let settled = !isPromise(value)
392
+ let settle = () => {
393
+ settled = true
394
+ for (let off of offs.splice(0)) off()
395
+ }
396
+ if (isPromise(value)) value.then(settle, settle)
397
+ return {
398
+ value,
399
+ cancelled: joint.signal,
400
+ share: (signal) => {
401
+ if (settled || signal?.aborted) return
402
+ if (!signal) return void (held = true)
403
+ owners++
404
+ let leave = () => {
405
+ if (!--owners && !held) joint.abort(signal.reason)
406
+ }
407
+ signal.addEventListener('abort', leave, { once: true })
408
+ offs.push(() => signal.removeEventListener('abort', leave))
409
+ },
410
+ }
411
+ }
412
+
413
+ let covering = (
414
+ bundles: Bundle[],
415
+ of: (eid: Eid) => Coverage,
416
+ ): Record<Eid, Coverage> =>
417
+ Object.fromEntries(bundles.map((b) => [b.entity.eid, of(b.entity.eid)]))
418
+
419
+ // What one commit did to each entity it touched: the components its patches
420
+ // named, and the ones it wears now, or `null` once it is deleted.
421
+ type Touch = Map<Eid, {
422
+ named: Set<string>
423
+ props: Set<string>
424
+ worn: Set<string> | null
425
+ bundle?: Bundle
426
+ born: boolean
427
+ }>
428
+
429
+ // Whether a subscription holds the members of an answer each entity alone
430
+ // decides (./interest.ts `alone`), so that deleting an entity outside them
431
+ // cannot move it. An aggregate holds only its value, a deferred watch nothing
432
+ // yet, and a peer or view answer is read from more than storage.
433
+ let keeps = (sub: Sub) =>
434
+ !!sub.reads?.alone && !sub.agg && !sub.deferred && !sub.peer && !sub.view
435
+
436
+ // A write matters when it changes what the query tests or sends. A whole-row
437
+ // projection also observes every component of an entity already in its set.
438
+ // A deletion matters unless the subscription keeps its members and the entity
439
+ // is not one of them.
440
+ let notices = (sub: Sub, b: Bundle): boolean => {
441
+ if (b.$delete) return !keeps(sub) || sub.members.has(b.entity.eid)
442
+ if (
443
+ !sub.reads || sub.reads.unseen || (sub.deferred && sub.want === null)
444
+ ) return true
445
+ if (sub.want === null && sub.members.has(b.entity.eid)) return true
446
+ let i = sub.reads
447
+ if (b.created && !i.own.length) return true
448
+ return Object.keys(b).some((c) =>
449
+ c != 'entity' &&
450
+ (i.near.has(c) || i.far.has(c) || i.via.has(c))
451
+ )
452
+ }
453
+
454
+ // `get` is only for deciding changed entities' membership and filling their
455
+ // frames. Read the union of what open queries test and project, unless one
456
+ // query needs the entire row or a peer cache must retain it.
457
+ let components = (subs: Sub[]): string[] | undefined => {
458
+ let names = new Set<string>()
459
+ for (let s of subs) {
460
+ if (s.peer || !s.reads || s.want === null) return undefined
461
+ for (let c of s.reads.near) names.add(c)
462
+ for (let c of s.reads.far) names.add(c)
463
+ for (let c of s.reads.via.keys()) names.add(c)
464
+ for (let c of s.want ?? []) names.add(c)
465
+ }
466
+ names.delete('entity')
467
+ return [...names]
468
+ }
469
+
470
+ let touches = (applied: Bundle[], now: Bundle[]): Touch => {
471
+ let out: Touch = new Map()
472
+ for (let b of now) {
473
+ out.set(b.entity.eid, {
474
+ named: new Set(),
475
+ props: new Set(),
476
+ worn: new Set(Object.keys(b)),
477
+ bundle: b,
478
+ born: false,
479
+ })
480
+ }
481
+ for (let b of applied) {
482
+ let t = out.get(b.entity.eid) ?? {
483
+ named: new Set<string>(),
484
+ props: new Set<string>(),
485
+ worn: null,
486
+ born: false,
487
+ }
488
+ out.set(b.entity.eid, t)
489
+ if (b.$delete) t.worn = null
490
+ if (b.created) t.born = true
491
+ for (let k of Object.keys(b)) {
492
+ if (k == 'entity' || k[0] == '$') continue
493
+ t.named.add(k)
494
+ let patch = b[k]
495
+ if (patch && typeof patch == 'object') {
496
+ for (let prop of Object.keys(patch)) t.props.add(k + '.' + prop)
497
+ }
498
+ }
499
+ }
500
+ return out
501
+ }
502
+
503
+ // The answer's entities a write can have moved. `null` means that the query
504
+ // must run whole: a far dependency has no owner, or a reference moved/deleted
505
+ // and the old owner cannot be read after the commit.
506
+ let affected = (
507
+ sub: Sub,
508
+ touch: Touch,
509
+ relevant: Set<Eid>,
510
+ ): Set<Eid> | null | undefined => {
511
+ let i = sub.reads
512
+ if (!i || i.unseen) return null
513
+ let ids = new Set<Eid>()
514
+ for (let [eid, t] of touch) {
515
+ if (!relevant.has(eid)) continue
516
+ if (!t.worn) return null
517
+ if ([...i.far].some((c) => t.named.has(c) || t.worn!.has(c))) {
518
+ return null
519
+ }
520
+ if (
521
+ sub.members.has(eid) ||
522
+ refers(i, t.bundle) && (
523
+ (t.born && !i.own.length) ||
524
+ (cares(i, t.named, t.worn) &&
525
+ i.fixed.every(({ comp, prop, value }) =>
526
+ (t.bundle?.[comp] as Record<string, unknown> | undefined)
527
+ ?.[prop] === value
528
+ ))
529
+ )
530
+ ) ids.add(eid)
531
+ for (let [comp, prop] of i.via) {
532
+ if (!t.named.has(comp) && !t.worn.has(comp)) continue
533
+ let owner = (t.bundle?.[comp] as Record<string, unknown> | undefined)
534
+ ?.[prop]
535
+ if (typeof owner != 'string') return null
536
+ if (t.props.has(comp + '.' + prop) && !t.born) return null
537
+ ids.add(owner)
538
+ }
539
+ }
540
+ return ids.size ? i.whole ? null : ids : undefined
541
+ }
542
+
543
+ /**
544
+ * A subscription registry over a graph. It registers an `effect` hook on that
545
+ * graph, so every transaction that commits — through this API or not —
546
+ * reaches whoever is watching. Build one per graph;
547
+ * {@link https://jsr.io/@yaks/api | api()} makes one when you do not pass
548
+ * your own.
549
+ *
550
+ * ```ts ignore
551
+ * let subs = subscriptions(graph)
552
+ * subs.open(sink, 'cheap', '.book&.book.price<20')
553
+ * ```
554
+ */
555
+ export let subscriptions = (graph: Graph, opts: {
556
+ /** The composed graph when `graph` is only its read overlay. */
557
+ activity?: object
558
+ /** A store token that changes for commits through other graph instances. */
559
+ revision?: () => unknown
560
+ /** A host may budget and page reads of a subscription's stored rows. */
561
+ readWindow?: (
562
+ query: Taken,
563
+ read: (query: Taken) => Bundle[] | Promise<Bundle[]>,
564
+ signal?: AbortSignal,
565
+ ) => Bundle[] | Promise<Bundle[]>
566
+ /** Give other requests a turn between inherited snapshot reads. */
567
+ yieldRecovery?: () => Promise<void>
568
+ /** A query may depend on entities outside its result (for example a computed
569
+ * session status depends on transcript entries). Returning true refreshes
570
+ * that subscription after this commit. It does not subscribe to those rows. */
571
+ invalidate?: (query: string, applied: Bundle[]) => boolean
572
+ /** How every timer of the registry is set: a `durable: "5s"` relayed
573
+ * value's expiry, a pending save's retry, a relay batch's flush and the
574
+ * frame queue of a socket serving it (default: setTimeout). */
575
+ timer?: Timer
576
+ /** The registry's time: what pending save queries and the relay pace of a
577
+ * socket serving it read (default: Date.now). */
578
+ now?: () => number
579
+ /** How many closed answers stand at once for a page to ask again (default
580
+ * 256). */
581
+ keep?: number
582
+ /** Told of every subscription the registry refuses and closes, with its
583
+ * query: the caller's own refusals too, which `fault` leaves unreported,
584
+ * for a host that knows whose query it was to judge. */
585
+ refused?: (error: unknown, query: string) => void
586
+ } = {}): Subs => {
587
+ let base = graph
588
+ let ending = new AbortController()
589
+ let readingOpts = (opts?: ReadOpts): ReadOpts => {
590
+ ending.signal.throwIfAborted()
591
+ return {
592
+ ...opts,
593
+ signal: opts?.signal
594
+ ? AbortSignal.any([ending.signal, opts.signal])
595
+ : ending.signal,
596
+ }
597
+ }
598
+ graph = {
599
+ ...base,
600
+ get vocab() {
601
+ return base.vocab
602
+ },
603
+ read: (q, opts) => base.read(q, readingOpts(opts)),
604
+ rows: (q, opts) => base.rows(q, readingOpts(opts)),
605
+ get: (ids, comps, opts) => base.get(ids, comps, readingOpts(opts)),
606
+ }
607
+ // The store's revision as this registry knows it (Frame `revision`): it
608
+ // moves on with every commit the registry hears, and with every change it
609
+ // learns of only from the store's token. It starts at the time, so a
610
+ // registry made again after a restart starts past every frame the one
611
+ // before it sent.
612
+ let now = opts.now ?? Date.now
613
+ let rev = now()
614
+ let advance = () => {
615
+ rev = Math.max(rev + 1, now())
616
+ opened.clear()
617
+ aims.clear()
618
+ }
619
+ let revision = opts.revision?.()
620
+ let knownRevision = after(revision, (value) => {
621
+ revision = value
622
+ })
623
+ if (isPromise(knownRevision)) {
624
+ knownRevision = knownRevision.catch((error) => {
625
+ revision = undefined
626
+ fault(error, 'store revision')
627
+ })
628
+ }
629
+ let held = new Map<Sink, Map<string, Sub>>()
630
+ let all = () =>
631
+ [...held.values()].flatMap((m) => [...m.values()].filter((s) => !s.loading))
632
+ let durableNet = net<Sub>(graph.vocab)
633
+ let peerNet = net<Sub>(graph.vocab)
634
+ // Keep storage rows only while a peer value makes their entity relevant.
635
+ // A missing row is cached too: a peer-only entity must not hit storage on
636
+ // every movement.
637
+ let peerRows = new Map<Eid, Bundle | null>()
638
+ // A reference's durable answer changes only with a commit that writes its
639
+ // component, or writes an entity among its rows. Keep its full rows across
640
+ // peer movements and other commits, including empty answers, with a fixed
641
+ // bound for spaces that hold many peer values at once.
642
+ let backlinks = new Map<
643
+ string,
644
+ { comp: string; peer: Eid; rows: Bundle[] }
645
+ >()
646
+ const BACKLINK_LIMIT = 512
647
+ let linkKey = (comp: string, prop: string, peer: Eid) =>
648
+ JSON.stringify([comp, prop, peer])
649
+ let linked = (
650
+ ref: { comp: string; prop: string },
651
+ targets: Eid[],
652
+ ): Bundle[] | Promise<Bundle[]> => {
653
+ let answers = new Map<Eid, Bundle[]>()
654
+ for (let peer of targets) {
655
+ let rows = backlinks.get(linkKey(ref.comp, ref.prop, peer))?.rows
656
+ if (rows) answers.set(peer, rows)
657
+ }
658
+ let missing = targets.filter((peer) => !answers.has(peer))
659
+ let fresh = missing.length
660
+ ? after(
661
+ graph.read(
662
+ line`.${ref.comp}.${ref.prop}=${missing}`,
663
+ { durable: true, native: true },
664
+ ),
665
+ (refs) =>
666
+ refs.length
667
+ ? graph.get(refs.map((b) => b.entity.eid), undefined, {
668
+ native: true,
669
+ })
670
+ : [],
671
+ )
672
+ : []
673
+ return after(fresh, (rows) => {
674
+ for (let peer of missing) {
675
+ let key = linkKey(ref.comp, ref.prop, peer)
676
+ let matching = rows.filter((b) =>
677
+ (b[ref.comp] as Record<string, unknown> | undefined)
678
+ ?.[ref.prop] == peer
679
+ )
680
+ answers.set(peer, matching)
681
+ backlinks.set(key, { comp: ref.comp, peer, rows: matching })
682
+ }
683
+ while (backlinks.size > BACKLINK_LIMIT) {
684
+ backlinks.delete(backlinks.keys().next().value!)
685
+ }
686
+ let held = peers.referencing(ref.comp, ref.prop, targets)
687
+ return [...targets.flatMap((peer) => answers.get(peer) ?? []), ...held]
688
+ })
689
+ }
690
+ let scopedNets = new Map<string, ReturnType<typeof net<Sub>>>()
691
+ let network = (sub: Sub) => {
692
+ if (sub.network) return sub.network
693
+ if (
694
+ sub.opts?.person === undefined &&
695
+ !graph.scope(sub.opts).visibility
696
+ ) return sub.network = sub.peer ? peerNet : durableNet
697
+ let key = JSON.stringify([sub.peer, sub.opts ?? null])
698
+ let found = scopedNets.get(key)
699
+ if (!found) scopedNets.set(key, found = net<Sub>(graph.vocab))
700
+ return sub.network = found
701
+ }
702
+ let dropNetwork = (sub: Sub) => {
703
+ let routing = network(sub)
704
+ routing.drop(sub)
705
+ sub.routed = false
706
+ if (
707
+ [...all(), ...kept.values()].some((s) =>
708
+ s.routed && s.network === routing
709
+ )
710
+ ) return
711
+ for (let [key, found] of scopedNets) {
712
+ if (found === routing) scopedNets.delete(key)
713
+ }
714
+ }
715
+ let routable = (sub: Sub) =>
716
+ !!sub.reads?.alone && !sub.reads.unseen && !sub.reads.far.size &&
717
+ !sub.reads.via.size && !sub.plan?.reaches.length && sub.opts?.now == null
718
+ let peerComp = (name: string) => syncOf(graph.vocab, name) == 'peers'
719
+ let references = (sub: Sub) => {
720
+ let vocab = sub.view?.vocab ?? graph.vocab
721
+ return [...sub.want ?? vocab.all].some((name) =>
722
+ vocab.props(name).some((prop) =>
723
+ vocab.prop(name, prop)?.category == 'ref'
724
+ )
725
+ )
726
+ }
727
+ // Whether an answer can show a reference to `eid`: one its sent rows hold,
728
+ // or any while its rows are still being read or are read from more than
729
+ // its members (a view, a projection's peers, relayed values).
730
+ let shows = (sub: Sub, eid: Eid) =>
731
+ sub.loading || !!sub.view || !!sub.plan?.reaches.length || sub.peer ||
732
+ [...sub.targets.values()].some((to) => to.includes(eid))
733
+ // Reference values depend on their targets' visibility, even when the
734
+ // unchanged referring entity remains in a routed or retained answer. A
735
+ // deleted target can only hide the references to it, so it moves only an
736
+ // answer that shows one; a write to what the policy reads may also reveal
737
+ // a reference the answer hides.
738
+ let policyMoved = (sub: Sub, applied: Bundle[]) =>
739
+ !!sub.policyDependencies?.length &&
740
+ applied.some((b) =>
741
+ dead(b) || sub.policyDependencies!.some((name) => name in b)
742
+ ) || sub.policyRefs && sub.policy !== undefined &&
743
+ (!sub.policy ||
744
+ applied.some((b) =>
745
+ dead(b)
746
+ ? shows(sub, b.entity.eid)
747
+ : comps(b).some(([name]) =>
748
+ sub.policy!.near.has(name) || sub.policy!.far.has(name) ||
749
+ sub.policy!.via.has(name)
750
+ )
751
+ ))
752
+ // Policies read dependencies without changing what the caller selected or
753
+ // requiring their private components on otherwise public members.
754
+ let dependencies = (reads: Interest | null, readOpts?: ReadOpts) => {
755
+ let visibility = graph.scope(readOpts).visibility
756
+ let policies = [
757
+ visibility?.entity,
758
+ ...Object.values(visibility?.components ?? {}),
759
+ ].filter((q): q is Query => q !== undefined)
760
+ if (!reads || !policies.length) return reads
761
+ let policy = interest(
762
+ {
763
+ kind: 'and',
764
+ clauses: policies.map((q) => typeof q == 'string' ? parse(q) : q),
765
+ },
766
+ graph.vocab,
767
+ graph.worn,
768
+ )
769
+ if (!policy) return null
770
+ let via = new Map(reads.via), far = new Set([...reads.far, ...policy.far])
771
+ for (let [comp, prop] of policy.via) {
772
+ if (via.has(comp) && via.get(comp) != prop) {
773
+ via.delete(comp)
774
+ far.add(comp)
775
+ } else if (!far.has(comp)) via.set(comp, prop)
776
+ }
777
+ return {
778
+ ...reads,
779
+ near: new Set([...reads.near, ...policy.near]),
780
+ far,
781
+ via,
782
+ whole: reads.whole || policy.whole,
783
+ alone: reads.alone && policy.alone,
784
+ unseen: reads.unseen || policy.unseen,
785
+ }
786
+ }
787
+ let pendingWork: Promise<void> | undefined
788
+ let observers = new Set<(bundles: Bundle[]) => void | Promise<unknown>>()
789
+ let observed: Bundle[] = []
790
+ let observing = false
791
+ let notify = (bundles: Bundle[]) => {
792
+ if (!observers.size || !bundles.length) return
793
+ observed.push(...bundles)
794
+ if (observing) return
795
+ observing = true
796
+ let released = () => {
797
+ // Registry work never awaits an observer: it may read this registry or
798
+ // write through a graph hook that queues more registry work.
799
+ if (pendingWork) return void pendingWork.then(released)
800
+ observing = false
801
+ let changes = coalesced(observed)
802
+ observed = []
803
+ for (let fn of observers) {
804
+ try {
805
+ let out = fn(changes)
806
+ if (isPromise(out)) out.catch((err) => fault(err, 'peer observer'))
807
+ } catch (err) {
808
+ fault(err, 'peer observer')
809
+ }
810
+ }
811
+ }
812
+ queueMicrotask(released)
813
+ }
814
+
815
+ let ordered = <T>(fn: () => T | Promise<T>): T | Promise<T> => {
816
+ let out = pendingWork ? pendingWork.then(fn) : fn()
817
+ if (isPromise(out)) {
818
+ let done = out.then(() => {}, () => {})
819
+ pendingWork = done
820
+ done.then(() => {
821
+ if (pendingWork === done) pendingWork = undefined
822
+ })
823
+ }
824
+ return out
825
+ }
826
+ // Saved peer edits belong to the writer, beyond subscription observation.
827
+ let saves = saving<Sink>(base, (fn, ms) =>
828
+ (opts.timer ?? ((fn, ms) => {
829
+ let t = setTimeout(fn, ms)
830
+ return () => clearTimeout(t)
831
+ }))(() => {
832
+ let out = ordered(fn)
833
+ if (isPromise(out)) out.catch((err) => fault(err, 'peer saving'))
834
+ }, ms), (sink, err) => {
835
+ fault(err, 'peer saving')
836
+ sink({ id: '', refused: refusal(err) })
837
+ }, opts.now)
838
+ let saved = (bundles: Bundle[]) =>
839
+ bundles.some((b) =>
840
+ comps(b).some(([comp]) => saveOf(graph.vocab, comp) != null)
841
+ )
842
+ let relays = new Map<Sink, { bundles: Bundle[]; done: Promise<void> }>()
843
+ let shared = new Map<string, Shared>()
844
+ let opened = new Map<string, { joint: Joint<Projected>; rows: number }>()
845
+ let aims = new Map<string, Query | Promise<Query>>()
846
+ // Moving peer predicates can ask the same stored question. Keep that
847
+ // answer across watches, including empty answers, until a commit moves it.
848
+ let durableCandidates = new Map<string, {
849
+ sub: Sub
850
+ rows: Bundle[] | Promise<Bundle[]>
851
+ }>()
852
+ // The closed subscriptions keeping a shared answer, longest unasked first.
853
+ let kept = new Map<string, Sub>()
854
+ let keyOf = (sub: Sub) => JSON.stringify([sub.query, sub.opts ?? null])
855
+ let unshare = (share: Shared) => {
856
+ if (shared.get(share.key) === share) shared.delete(share.key)
857
+ for (let s of share.users) {
858
+ s.shared = undefined
859
+ if (!s.kept) continue
860
+ kept.delete(share.key)
861
+ dropNetwork(s)
862
+ }
863
+ share.users.clear()
864
+ }
865
+ // A routed subscription that reads only what each entity holds, now and
866
+ // later alike, takes up the answer others asking the same share, or starts
867
+ // one for them when its own is small enough to hold.
868
+ let join = (sub: Sub, ast: And, bundles: Bundle[]) => {
869
+ if (
870
+ sub.view || sub.peer || sub.agg || sub.plan || sub.reads?.via.size ||
871
+ moving(ast)
872
+ ) return
873
+ let share = shared.get(keyOf(sub))
874
+ if (!share) {
875
+ if (bundles.length > HELD) return
876
+ share = {
877
+ key: keyOf(sub),
878
+ rows: new Map(bundles.map((b) => [b.entity.eid, b])),
879
+ users: new Set(),
880
+ }
881
+ shared.set(share.key, share)
882
+ }
883
+ for (let k of share.users) {
884
+ if (!k.kept) continue
885
+ share.users.delete(k)
886
+ kept.delete(share.key)
887
+ dropNetwork(k)
888
+ }
889
+ share.users.add(sub)
890
+ sub.shared = share
891
+ }
892
+ // A subscription let go of, by its sink closing it or by a new one under
893
+ // its id: the network lets go of it too, unless it is the last keeping a
894
+ // shared answer, which it keeps current while the answer stays kept.
895
+ let forget = (sub: Sub | undefined, keep = true) => {
896
+ if (!sub) return
897
+ sub.abort?.abort()
898
+ sub.abort = undefined
899
+ if (!sub.routed) return
900
+ let share = sub.shared
901
+ share?.users.delete(sub)
902
+ if (share && !share.users.size) {
903
+ if (!keep) return unshare(share)
904
+ sub.kept = true
905
+ share.users.add(sub)
906
+ kept.set(share.key, sub)
907
+ let rows = 0, answers = 0
908
+ for (let k of [...kept.values()].reverse()) {
909
+ rows += k.shared!.rows.size
910
+ answers++
911
+ if (rows > KEPT || answers > (opts.keep ?? KEEP)) unshare(k.shared!)
912
+ }
913
+ return
914
+ }
915
+ dropNetwork(sub)
916
+ }
917
+
918
+ // A subscription whose query is refused is closed, not kept: a query the
919
+ // graph cannot answer would otherwise throw on every commit for the life of
920
+ // the socket.
921
+ let cut = (sub: Sub, err: unknown) => {
922
+ if (held.get(sub.sink)?.get(sub.id) !== sub) return
923
+ held.get(sub.sink)?.delete(sub.id)
924
+ forget(sub, false)
925
+ fault(err, 'subscription')
926
+ try {
927
+ opts.refused?.(err, sub.query)
928
+ } catch (why) {
929
+ fault(why, 'subscription refused')
930
+ }
931
+ sub.sink({ id: sub.id, refused: refusal(err) })
932
+ }
933
+
934
+ let delivery = (
935
+ sink: Sink,
936
+ id: string,
937
+ readOpts?: ReadOpts,
938
+ raw = false,
939
+ ): Sub['send'] => {
940
+ let owner = () => held.get(sink)?.get(id)
941
+ let sub: Sub | undefined
942
+ let sendPublished: Sink = (frame) => {
943
+ sub ??= owner()
944
+ if (sub && owner() !== sub) return
945
+ let out: Frame = { ...frame }
946
+ if (says(frame)) {
947
+ out.revision = rev
948
+ if (sub?.said !== undefined) out.since = sub.said
949
+ if (sub) sub.said = rev
950
+ }
951
+ for (let key of ['bundles', 'peers', 'relay'] as const) {
952
+ if (frame[key]) out[key] = published(graph.vocab, frame[key])
953
+ }
954
+ for (let key of ['coverage', 'peerCoverage'] as const) {
955
+ if (!frame[key]) continue
956
+ out[key] = Object.fromEntries(
957
+ Object.entries(frame[key]).map(([eid, coverage]) => [
958
+ eid,
959
+ coverage === true ? true : Object.fromEntries(
960
+ Object.entries(coverage).filter(([comp]) =>
961
+ syncOf(graph.vocab, comp) != 'none'
962
+ ),
963
+ ),
964
+ ]),
965
+ )
966
+ }
967
+ if (frame.transient) {
968
+ out.transient = frame.transient.filter((f) =>
969
+ syncOf(graph.vocab, f.component) != 'none'
970
+ )
971
+ }
972
+ return sink(out)
973
+ }
974
+ if (!graph.rewrites(readOpts)) return sendPublished
975
+ let seen = new Set<Eid>()
976
+ let riders = new Set<Eid>()
977
+ let patchOpts = { ...readOpts, patch: true }
978
+ let waiting: Promise<void> | undefined
979
+ // A stored subscription's own rows were read under this reader's scopes,
980
+ // by its query or by the routing that screens a commit's rows for its
981
+ // network (`routeAll`), so a scope's hooks pass them as screened, and the
982
+ // coverage naming those same entities with them. What peers relay, what
983
+ // a raw feed carries and what a view assembles were not.
984
+ let screened = (key: 'bundles' | 'peers' | 'relay') =>
985
+ key == 'bundles' && !raw && !!sub && !sub.view && !sub.peer
986
+ let send = (frame: Frame) => {
987
+ let rewritten: Frame = { ...frame }
988
+ return after(
989
+ over(['bundles', 'peers', 'relay'] as const, (key) => {
990
+ let bundles = frame[key]
991
+ if (!bundles) return
992
+ return after(
993
+ graph.answer(
994
+ published(graph.vocab, bundles),
995
+ key == 'relay' || raw && key == 'bundles' ? patchOpts : readOpts,
996
+ screened(key),
997
+ ),
998
+ (out) => {
999
+ rewritten[key] = raw && key == 'bundles'
1000
+ ? out.filter((b) => !dead(b) || seen.has(b.entity.eid))
1001
+ : out
1002
+ },
1003
+ )
1004
+ }),
1005
+ () =>
1006
+ after(
1007
+ over(['coverage', 'peerCoverage'] as const, (key) => {
1008
+ let coverage = frame[key]
1009
+ if (!coverage) return
1010
+ let whole = Object.keys(coverage).filter((eid) =>
1011
+ coverage[eid] === true
1012
+ )
1013
+ let got = whole.length
1014
+ ? graph.get(whole, undefined, readOpts)
1015
+ : []
1016
+ return after(got, (held) => {
1017
+ let rows: Bundle[] = Object.entries(coverage).flatMap(
1018
+ ([eid, scope]) => {
1019
+ if (scope === true) {
1020
+ return held.filter((b) => b.entity.eid == eid)
1021
+ }
1022
+ return [{
1023
+ entity: { eid },
1024
+ ...Object.fromEntries(
1025
+ Object.entries(scope).map((
1026
+ [comp, props],
1027
+ ) => [
1028
+ comp,
1029
+ props === true
1030
+ ? {}
1031
+ : Object.fromEntries(props.map((p) => [p, null])),
1032
+ ]),
1033
+ ),
1034
+ }]
1035
+ },
1036
+ )
1037
+ return after(
1038
+ graph.answer(
1039
+ published(graph.vocab, rows),
1040
+ readOpts,
1041
+ key == 'coverage' && screened('bundles'),
1042
+ ),
1043
+ (out) => {
1044
+ rewritten[key] = Object.fromEntries(
1045
+ out.map((
1046
+ row,
1047
+ ) => [
1048
+ row.entity.eid,
1049
+ Object.fromEntries(
1050
+ comps(row).map(([name, props]) => {
1051
+ let original = coverage[row.entity.eid]
1052
+ let fields = props && typeof props == 'object'
1053
+ ? Object.keys(props)
1054
+ : []
1055
+ return [
1056
+ name,
1057
+ original === true || original[name] === true ||
1058
+ !fields.length
1059
+ ? true
1060
+ : fields,
1061
+ ]
1062
+ }),
1063
+ ),
1064
+ ]),
1065
+ )
1066
+ },
1067
+ )
1068
+ })
1069
+ }),
1070
+ () => {
1071
+ for (
1072
+ let b of [...rewritten.bundles ?? [], ...rewritten.relay ?? []]
1073
+ ) seen.add(b.entity.eid)
1074
+ for (let b of rewritten.peers ?? []) riders.add(b.entity.eid)
1075
+ if (frame.gone) {
1076
+ rewritten.gone = frame.gone.filter((eid) => seen.has(eid))
1077
+ }
1078
+ if (frame.peerGone) {
1079
+ rewritten.peerGone = frame.peerGone.filter((eid) =>
1080
+ riders.has(eid)
1081
+ )
1082
+ }
1083
+ if (frame.transientReset) {
1084
+ rewritten.transientReset = frame.transientReset.filter((eid) =>
1085
+ seen.has(eid)
1086
+ )
1087
+ }
1088
+ for (let eid of rewritten.gone ?? []) seen.delete(eid)
1089
+ for (let eid of rewritten.peerGone ?? []) riders.delete(eid)
1090
+ if (!frame.transient?.length) return sendPublished(rewritten)
1091
+ let rows: Bundle[] = frame.transient.map((f) => ({
1092
+ entity: { eid: f.entity },
1093
+ [f.component]: { [f.property]: null },
1094
+ }))
1095
+ return after(graph.answer(rows, patchOpts), (visible) => {
1096
+ rewritten.transient = frame.transient!.filter((f) =>
1097
+ visible.some((b) =>
1098
+ b.entity.eid == f.entity && b[f.component] &&
1099
+ f.property in (b[f.component] as Record<string, unknown>)
1100
+ )
1101
+ )
1102
+ return sendPublished(rewritten)
1103
+ })
1104
+ },
1105
+ ),
1106
+ )
1107
+ }
1108
+ return (frame) => {
1109
+ sub ??= owner()
1110
+ let fail = (err: unknown) => {
1111
+ if (sub) cut(sub, err)
1112
+ }
1113
+ try {
1114
+ let out = waiting ? waiting.then(() => send(frame)) : send(frame)
1115
+ if (isPromise(out)) {
1116
+ let pending = out.catch(fail)
1117
+ waiting = pending
1118
+ pending.then(() => {
1119
+ if (waiting === pending) waiting = undefined
1120
+ })
1121
+ return pending
1122
+ }
1123
+ } catch (err) {
1124
+ fail(err)
1125
+ }
1126
+ }
1127
+ }
1128
+
1129
+ let attempt = (sub: Sub, fn: () => void | Promise<void>) => {
1130
+ if (!sub.kept && held.get(sub.sink)?.get(sub.id) !== sub) return
1131
+ try {
1132
+ let out = fn()
1133
+ return isPromise(out) ? out.catch((err) => cut(sub, err)) : out
1134
+ } catch (err) {
1135
+ cut(sub, err)
1136
+ }
1137
+ }
1138
+
1139
+ const rememberFields = (sub: Sub, bundles: Bundle[]) => {
1140
+ let vocab = sub.view?.vocab ?? graph.vocab
1141
+ for (const b of bundles) {
1142
+ let to = comps(b).flatMap(([comp, value]) =>
1143
+ Object.entries(value ?? {}).flatMap(([prop, v]) =>
1144
+ vocab.prop(comp, prop)?.category != 'ref'
1145
+ ? []
1146
+ : [v].flat().filter((e): e is Eid => typeof e == 'string')
1147
+ )
1148
+ )
1149
+ if (to.length) sub.targets.set(b.entity.eid, to)
1150
+ else sub.targets.delete(b.entity.eid)
1151
+ sub.fields.set(
1152
+ b.entity.eid,
1153
+ new Set(
1154
+ Object.entries(b).flatMap(([comp, value]) =>
1155
+ value && typeof value == 'object'
1156
+ ? Object.keys(value).map((prop) => comp + '.' + prop)
1157
+ : []
1158
+ ),
1159
+ ),
1160
+ )
1161
+ }
1162
+ }
1163
+ const visible = (sub: Sub, f: TransientFrame) =>
1164
+ sub.members.has(f.entity) &&
1165
+ sub.fields.get(f.entity)?.has(f.component + '.' + f.property)
1166
+
1167
+ let reading = (sub: Sub, signal = sub.abort?.signal) => ({
1168
+ ...sub.opts,
1169
+ signal,
1170
+ })
1171
+
1172
+ // What a subscription's query answers now. A projection whose paths reach
1173
+ // other entities is read as its rows (@yaks/graph `project`), which tell the
1174
+ // entities it selects from the ones they reach; any other query is the
1175
+ // graph's read, the same answer `/query` gives.
1176
+ // Under the subscription's own signal, or one it shares with others.
1177
+ let ask = (sub: Sub, q: string, signal?: AbortSignal): Answer =>
1178
+ asking(sub.asker, () => asked(sub, q, signal))
1179
+ let asked = (sub: Sub, q: string, signal?: AbortSignal): Answer =>
1180
+ sub.view
1181
+ ? viewed(sub.view, reading(sub, signal))
1182
+ : sub.plan?.reaches.length
1183
+ ? project(graph, sub.plan, {
1184
+ ...reading(sub, signal),
1185
+ durable: true,
1186
+ native: true,
1187
+ })
1188
+ : after(windowRows(sub, q, signal), answered)
1189
+ let windowRows = (sub: Sub, q: string, signal?: AbortSignal) => {
1190
+ let query = queryOf(sub, q)
1191
+ let optsForRead = {
1192
+ ...reading(sub, signal),
1193
+ durable: true,
1194
+ native: !!sub.ast || graph.rewrites(sub.opts) || sub.opts?.native,
1195
+ }
1196
+ let read = (query: Taken) => graph.read(query, optsForRead)
1197
+ return opts.readWindow
1198
+ ? opts.readWindow(query, read, optsForRead.signal)
1199
+ : read(query)
1200
+ }
1201
+
1202
+ // The bundles a frame carries, and what each covers where a projection
1203
+ // narrowed them, so a replica clears only a property the projection named.
1204
+ // A projection that reaches sends its riders whole each time, and names the
1205
+ // ones no path reaches any more.
1206
+ let framed = (
1207
+ sub: Sub,
1208
+ bundles: Bundle[],
1209
+ { reached, covers }: Projected = answered([]),
1210
+ initial = false,
1211
+ ): Partial<Frame> => {
1212
+ // Current held values outrun saved snapshots. New replicas initialize
1213
+ // from the saved value; subsequent updates carry the live one when held.
1214
+ if (!initial && !sub.view) {
1215
+ let latest = (b: Bundle) => {
1216
+ let out = { ...b }
1217
+ let held = peers.values([b.entity.eid])[0]
1218
+ for (let [comp, patch] of held ? comps(held) : []) {
1219
+ if (saveOf(graph.vocab, comp) != null) out[comp] = patch
1220
+ }
1221
+ return out
1222
+ }
1223
+ bundles = bundles.map((b) => sub.cut(latest(b)))
1224
+ reached = reached.map((b) => {
1225
+ let out = latest(b), coverage = covers.get(b.entity.eid)
1226
+ if (!coverage) return b
1227
+ return {
1228
+ entity: out.entity,
1229
+ ...Object.fromEntries(
1230
+ Object.entries(coverage).flatMap(([comp, props]) => {
1231
+ let value = out[comp] as Record<string, unknown> | undefined
1232
+ return value
1233
+ ? [[
1234
+ comp,
1235
+ Object.fromEntries(
1236
+ props.filter((p) => p in value).map((p) => [p, value[p]]),
1237
+ ),
1238
+ ]]
1239
+ : []
1240
+ }),
1241
+ ),
1242
+ }
1243
+ })
1244
+ }
1245
+ let p = sub.plan
1246
+ if (!p) {
1247
+ // A component-selected answer knows whole components, not the entity.
1248
+ // Include absent requested components so snapshots clear stale values.
1249
+ if (sub.want == null) return { bundles }
1250
+ let scope: Coverage = Object.fromEntries(
1251
+ [...sub.want].map((comp) => [comp, true]),
1252
+ )
1253
+ return { bundles, coverage: covering(bundles, () => scope) }
1254
+ }
1255
+ let own = { bundles, coverage: covering(bundles, () => p.own) }
1256
+ if (!p.reaches.length) return own
1257
+ let now = new Set(reached.map((b) => b.entity.eid))
1258
+ let peerGone = [...sub.riders].filter((eid) => !now.has(eid))
1259
+ sub.riders = now
1260
+ return {
1261
+ ...own,
1262
+ peers: reached,
1263
+ peerCoverage: covering(reached, (eid) => covers.get(eid)!),
1264
+ ...peerGone.length ? { peerGone } : {},
1265
+ }
1266
+ }
1267
+
1268
+ // A path no component declares (`.kind`) may be anything: it drifts.
1269
+ let moving = (ast: And): boolean =>
1270
+ drifts(ast, (c) => {
1271
+ let leaf = graph.vocab.aim(c.path.join('.'), bare(c)).at(-1)
1272
+ return leaf && graph.vocab.prop(leaf.comp, leaf.prop)?.scalar
1273
+ })
1274
+
1275
+ let windowed = (ast: And) => {
1276
+ let { limit, after } = windowOf(ast)
1277
+ return limit != null || after != null
1278
+ }
1279
+
1280
+ let parallel = <T>(items: T[], run: (item: T) => void | Promise<void>) => {
1281
+ let work = items.map(run).filter(isPromise)
1282
+ if (work.length) return Promise.all(work).then(() => {})
1283
+ }
1284
+
1285
+ // What an opening read, shared by every opening of the same query under the
1286
+ // same options while the store and its words stand as they were: the
1287
+ // sockets of one reader restoring the same watches on a wake, and the
1288
+ // pages that open them one message at a time, read each answer once.
1289
+ // A commit lets them all go (`advance`), and an answer joined while its read
1290
+ // is still running is cancelled only once every opening joined has let go.
1291
+ // Settled answers are kept up to OPENED rows between them. A registry that
1292
+ // learns of commits from the store's token may not have heard of one yet,
1293
+ // so it keeps none past its read.
1294
+ let opening = (sub: Sub, read: (signal: AbortSignal) => Answer): Answer => {
1295
+ let key = keyOf(sub)
1296
+ let held = opened.get(key)
1297
+ if (held && !held.joint.cancelled.aborted) {
1298
+ opened.delete(key)
1299
+ opened.set(key, held)
1300
+ } else {
1301
+ let joint = jointly(read)
1302
+ let entry = held = { joint, rows: 0 }
1303
+ opened.set(key, entry)
1304
+ let release = () => {
1305
+ if (opened.get(key) === entry) opened.delete(key)
1306
+ }
1307
+ let keep = (answer: Projected) => {
1308
+ if (opts.revision) return release()
1309
+ entry.rows = answer.found.length + answer.reached.length
1310
+ let rows = 0
1311
+ for (let o of opened.values()) rows += o.rows
1312
+ // Past the bound, the latest asked before this one go first: openings
1313
+ // that come round in the same order again (each socket's page asking
1314
+ // its watches in turn) find the earlier answers still here, and the
1315
+ // one just read is kept for the openings asking it next.
1316
+ for (let [k, o] of [...opened].reverse()) {
1317
+ if (rows <= OPENED) break
1318
+ if (o === entry) continue
1319
+ opened.delete(k)
1320
+ rows -= o.rows
1321
+ }
1322
+ }
1323
+ if (isPromise(joint.value)) joint.value.then(keep, release)
1324
+ else keep(joint.value)
1325
+ }
1326
+ held.joint.share(sub.abort?.signal)
1327
+ return held.joint.value
1328
+ }
1329
+
1330
+ // The query an opening asks once the graph has said what its words name
1331
+ // (an `.after` anchor, a reader's rewrites), the same for every opening of
1332
+ // it under the same options until a commit (`advance`), as `opening` keeps
1333
+ // its answer.
1334
+ let aimed = (sub: Sub, ask: () => Query | Promise<Query>) => {
1335
+ if (opts.revision) return ask()
1336
+ let key = keyOf(sub)
1337
+ let held = aims.get(key)
1338
+ if (!held) {
1339
+ if (aims.size >= KEEP) aims.delete(aims.keys().next().value!)
1340
+ aims.set(key, held = ask())
1341
+ if (isPromise(held)) held.catch(() => aims.delete(key))
1342
+ }
1343
+ return held
1344
+ }
1345
+
1346
+ // Only completed answers are shared: pending work still belongs to the
1347
+ // opening that may cancel it.
1348
+ let cache = <T>(
1349
+ map: Map<string, T | Promise<T>> | undefined,
1350
+ key: string,
1351
+ value: T | Promise<T>,
1352
+ ) => {
1353
+ if (!map) return
1354
+ if (isPromise(value)) value.then((v) => map.set(key, v), () => {})
1355
+ else map.set(key, value)
1356
+ }
1357
+
1358
+ // A slow opening owns only its own read; a replaced or closed opening owes
1359
+ // no answer. One a commit crossed still answers with what it read, and is
1360
+ // then read again in turn, as a live answer a commit invalidates is: an
1361
+ // answer the box's commits move faster than it can be read would otherwise
1362
+ // be read again for as long as they keep coming, and its page never hears it.
1363
+ let initial = <T>(
1364
+ sub: Sub,
1365
+ value: T,
1366
+ use: (value: T) => void | Promise<void>,
1367
+ ): void | Promise<void> => {
1368
+ if (held.get(sub.sink)?.get(sub.id) !== sub) return
1369
+ let crossed = sub.dirty
1370
+ sub.dirty = false
1371
+ sub.loading = false
1372
+ let sent = use(value)
1373
+ if (crossed && isPromise(sent)) sent.then(() => caughtUp(sub), () => {})
1374
+ else if (crossed) caughtUp(sub)
1375
+ return sent
1376
+ }
1377
+
1378
+ // Not awaited by the opening: it is ordered work, and an opening may be
1379
+ // part of ordered work itself (`resync`).
1380
+ let caughtUp = (sub: Sub) => {
1381
+ let out = ordered(() => attempt(sub, () => reread(sub, ask)))
1382
+ if (isPromise(out)) out.catch((err) => fault(err, 'subscription catch-up'))
1383
+ }
1384
+
1385
+ let open = (
1386
+ sink: Sink,
1387
+ id: string,
1388
+ query: Ask,
1389
+ readOpts?: ReadOpts,
1390
+ answers?: Map<string, Reduced | Promise<Reduced>>,
1391
+ deferStatic = false,
1392
+ reset = false,
1393
+ ): void | Promise<void> => {
1394
+ flush()
1395
+ let mine = held.get(sink) ?? new Map<string, Sub>()
1396
+ held.set(sink, mine)
1397
+ let line = query === true ? '' : query
1398
+ let options = readOpts
1399
+ let abort = new AbortController()
1400
+ readOpts = { ...readOpts, signal: abort.signal }
1401
+ let visibility = graph.scope(readOpts).visibility
1402
+ let sub: Sub = {
1403
+ abort,
1404
+ policyDependencies: visibility?.dependencies,
1405
+ loading: query !== true,
1406
+ policy: visibility?.entity === undefined ? undefined : interest(
1407
+ typeof visibility.entity == 'string'
1408
+ ? parse(visibility.entity)
1409
+ : visibility.entity,
1410
+ graph.vocab,
1411
+ graph.worn,
1412
+ ),
1413
+ id,
1414
+ sink,
1415
+ raw: query === true,
1416
+ query: line,
1417
+ opts: options,
1418
+ asker: asker(),
1419
+ send: delivery(sink, id, readOpts, query === true),
1420
+ members: new Set(),
1421
+ fields: new Map(),
1422
+ targets: new Map(),
1423
+ routed: false,
1424
+ peer: false,
1425
+ cut: whole,
1426
+ riders: new Set(),
1427
+ }
1428
+ let deliver = sub.send
1429
+ sub.send = (frame) =>
1430
+ held.get(sink)?.get(id) === sub ? deliver(frame) : undefined
1431
+ forget(mine.get(id))
1432
+ mine.set(id, sub)
1433
+ // a raw feed carries whole transactions, not a membership set
1434
+ if (sub.raw) return
1435
+ return attempt(sub, () => {
1436
+ // Parsed here, before the network is asked, so a query that cannot be
1437
+ // parsed is refused rather than quietly demoted to a subscription that
1438
+ // runs it again on every commit forever.
1439
+ return after(graph.view(line, readOpts), (view) => {
1440
+ if (view) {
1441
+ sub.view = view
1442
+ sub.ast = view.original
1443
+ sub.window = windowed(view.original)
1444
+ sub.reads = dependencies(
1445
+ interest(view.original, view.vocab, graph.worn),
1446
+ readOpts,
1447
+ )
1448
+ sub.peer = view.dependencies?.some(peerComp) ?? false
1449
+ sub.agg = aggregate(view.original)
1450
+ sub.want = named(view.vocab, view.original)
1451
+ sub.plan = projection(view.vocab, view.original)
1452
+ sub.cut = sub.plan?.cut ?? only(sub.want)
1453
+ sub.policyRefs = references(sub)
1454
+ // The view already speaks the caller's words.
1455
+ let deliver = delivery(sink, id, { ...readOpts, native: true })
1456
+ sub.send = (frame) =>
1457
+ held.get(sink)?.get(id) === sub ? deliver(frame) : undefined
1458
+ if (sub.agg) return tell(sub, true, answers)
1459
+ let loaded = opening(
1460
+ sub,
1461
+ (signal) => viewed(view, { ...readOpts, signal }),
1462
+ )
1463
+ return after(loaded, (answer) =>
1464
+ initial(sub, answer, (answer) => {
1465
+ for (let b of answer.found) sub.members.add(b.entity.eid)
1466
+ rememberFields(sub, answer.found)
1467
+ return sub.send({
1468
+ id,
1469
+ ...framed(sub, answer.found, answer, true),
1470
+ ...reset ? { reset: true } : {},
1471
+ })
1472
+ }))
1473
+ }
1474
+ let parsed = parse(line)
1475
+ return after(
1476
+ graph.rewrites(readOpts) ||
1477
+ parsed.clauses.some((c) => c.kind == 'after')
1478
+ ? aimed(sub, () => graph.ask(line, readOpts))
1479
+ : line,
1480
+ (q) => {
1481
+ let ast = typeof q == 'string' ? parsed : q
1482
+ if (typeof q != 'string') sub.ast = ast
1483
+ sub.window = windowed(ast)
1484
+ sub.reads = dependencies(
1485
+ interest(ast, graph.vocab, graph.worn),
1486
+ readOpts,
1487
+ )
1488
+ let plan = peerPlan(ast, graph.vocab)
1489
+ sub.peer = plan.peers
1490
+ sub.durable = plan.durable
1491
+ sub.ref = plan.ref
1492
+ sub.agg = aggregate(ast)
1493
+ sub.want = named(graph.vocab, ast, q !== line)
1494
+ sub.plan = projection(graph.vocab, ast)
1495
+ sub.cut = sub.plan?.cut ?? only(sub.want)
1496
+ sub.policyRefs = references(sub)
1497
+ if (
1498
+ deferStatic && !sub.peer && sub.reads && !sub.reads.unseen &&
1499
+ sub.opts?.now == null && !sub.agg &&
1500
+ !moving(ast) &&
1501
+ [...sub.reads.near, ...sub.reads.far, ...sub.reads.via.keys()]
1502
+ .every((c) => syncOf(graph.vocab, c) != 'peers')
1503
+ ) {
1504
+ sub.deferred = true
1505
+ sub.loading = false
1506
+ return
1507
+ }
1508
+ if (sub.agg) return tell(sub, true, answers)
1509
+ if (sub.peer && sub.plan?.reaches.length) {
1510
+ throw new Refused(
1511
+ 'a projection through a reference is not read over relayed values',
1512
+ )
1513
+ }
1514
+ let share = shared.get(keyOf(sub))
1515
+ let loaded = share
1516
+ ? answered([...share.rows.values()])
1517
+ : sub.peer
1518
+ ? after(read(sub), answered)
1519
+ : opening(sub, (signal) => ask(sub, line, signal))
1520
+ return after(loaded, (answer) =>
1521
+ initial(sub, answer, (answer) => {
1522
+ let bundles = answer.found
1523
+ for (let b of bundles) sub.members.add(b.entity.eid)
1524
+ // A query over a computed component is never routed: the entities it
1525
+ // selects move without a bundle that names them (./interest.ts). Nor
1526
+ // is a projection that reaches: what it reaches moves without the
1527
+ // entities it selects moving.
1528
+ if (
1529
+ held.get(sink)?.get(id) === sub && routable(sub)
1530
+ ) {
1531
+ sub.routed = network(sub).add(sub, ast, sub.members)
1532
+ if (sub.routed) join(sub, ast, bundles)
1533
+ }
1534
+ rememberFields(sub, bundles)
1535
+ const snapshots = live.snapshots().filter((f) =>
1536
+ visible(sub, f)
1537
+ )
1538
+ // The relayed values other connections already hold for this set, so
1539
+ // a subscriber that arrives late still sees the cursors that were
1540
+ // there before it.
1541
+ let now = peers.snapshot(sink, (eid) => sub.members.has(eid))
1542
+ return sub.send({
1543
+ id,
1544
+ ...framed(sub, bundles, answer, true),
1545
+ ...reset ? { reset: true } : {},
1546
+ transientReset: bundles.map((b) => b.entity.eid),
1547
+ ...snapshots.length ? { transient: snapshots } : {},
1548
+ ...now.length ? { relay: now } : {},
1549
+ })
1550
+ }))
1551
+ },
1552
+ )
1553
+ })
1554
+ })
1555
+ }
1556
+
1557
+ // An aggregate's answer, sent when it is new: always on open, and after a
1558
+ // commit only when the value moved. A count or a tally is a question about
1559
+ // the whole set, so it is asked again after every commit.
1560
+ let tell = (
1561
+ sub: Sub,
1562
+ first = false,
1563
+ answers?: Map<string, Reduced | Promise<Reduced>>,
1564
+ ): void | Promise<void> => {
1565
+ let key = sub.opts ? JSON.stringify([sub.query, sub.opts]) : sub.query
1566
+ let value = answers?.get(key)
1567
+ if (!value) {
1568
+ value = sub.view
1569
+ ? after(
1570
+ viewValues(sub.view, reading(sub)),
1571
+ (bundles) =>
1572
+ reduced(
1573
+ sub.agg!,
1574
+ matchRows(sub.view!.original, sub.view!.vocab, sub.opts)(bundles),
1575
+ ),
1576
+ )
1577
+ : after(
1578
+ sub.peer
1579
+ ? after(
1580
+ source(sub),
1581
+ (bundles) =>
1582
+ matchRows(queryOf(sub), graph.vocab, sub.opts)(bundles),
1583
+ )
1584
+ : graph.rows(queryOf(sub), {
1585
+ ...reading(sub),
1586
+ durable: true,
1587
+ native: !!sub.ast || graph.rewrites(sub.opts) || sub.opts?.native,
1588
+ }),
1589
+ (rows) => reduced(sub.agg!, rows),
1590
+ )
1591
+ cache(answers, key, value)
1592
+ }
1593
+ let send = (value: Reduced) => {
1594
+ let answer = JSON.stringify(value)
1595
+ if (!first && answer == sub.answer) {
1596
+ return
1597
+ }
1598
+ sub.answer = answer
1599
+ return sub.send({ id: sub.id, ...value })
1600
+ }
1601
+ return after(
1602
+ value,
1603
+ (value) => first ? initial(sub, value, send) : send(value),
1604
+ )
1605
+ }
1606
+
1607
+ // What a commit did to one routed subscription, sent cut to what the query
1608
+ // names.
1609
+ let send = (sub: Sub, moved?: Moved) => {
1610
+ if (!moved) return
1611
+ let { bundles, joined, gone } = moved
1612
+ let share = sub.shared
1613
+ if (share) {
1614
+ for (let b of bundles) share.rows.set(b.entity.eid, b)
1615
+ for (let eid of gone) share.rows.delete(eid)
1616
+ if (share.rows.size > HELD) unshare(share)
1617
+ }
1618
+ if (sub.kept) return
1619
+ rememberFields(sub, bundles)
1620
+ for (const eid of gone) {
1621
+ sub.fields.delete(eid)
1622
+ sub.targets.delete(eid)
1623
+ }
1624
+ if (bundles.length || gone.length) {
1625
+ return sub.send({
1626
+ id: sub.id,
1627
+ ...framed(sub, bundles),
1628
+ gone,
1629
+ ...hail(sub, joined),
1630
+ })
1631
+ }
1632
+ }
1633
+
1634
+ // What the peers are already saying about entities that just joined a set,
1635
+ // as a subscription that opens is told it: a writer relays a value when it
1636
+ // changes, so one relayed before its entity joined would otherwise not be
1637
+ // heard again until it moved.
1638
+ let hail = (sub: Sub, joined: Eid[]): { relay?: Bundle[] } => {
1639
+ if (!joined.length || sub.view) return {}
1640
+ let fresh = new Set(joined)
1641
+ let now = peers.snapshot(sub.sink, (eid) => fresh.has(eid))
1642
+ return now.length ? { relay: now } : {}
1643
+ }
1644
+
1645
+ // A refresh runs against the affected entities where it can locate them.
1646
+ // A limit, order or unlocated dependency still needs the whole answer, and
1647
+ // so does a projection that reaches: what it reaches is the whole answer's.
1648
+ let push = (
1649
+ sub: Sub,
1650
+ scope?: Set<Eid>,
1651
+ load: (sub: Sub, q: string) => Answer = ask,
1652
+ prepared?: Bundle[] | Promise<Bundle[]>,
1653
+ joinsOnly = false,
1654
+ ) => {
1655
+ if (sub.agg) return tell(sub)
1656
+ if (sub.plan?.reaches.length) scope = undefined
1657
+ let query = scope
1658
+ ? sub.query + '&.entity.eid=' + [...scope].join(',')
1659
+ : sub.query
1660
+ let loaded = sub.view
1661
+ ? viewed(sub.view, reading(sub))
1662
+ : sub.peer
1663
+ ? after(read(sub, scope, prepared), answered)
1664
+ : load(sub, query)
1665
+ return after(loaded, (answer) => {
1666
+ let set = answer.found
1667
+ let ids = new Set(set.map((b) => b.entity.eid))
1668
+ let gone = [...(scope ?? sub.members)].filter((e) =>
1669
+ sub.members.has(e) && !ids.has(e)
1670
+ )
1671
+ // An entity can join without being touched: a hop or a computed
1672
+ // property moved it from the far side.
1673
+ let joined = [...ids].filter((e) => !sub.members.has(e))
1674
+ if (scope) {
1675
+ for (let e of gone) sub.members.delete(e)
1676
+ for (let e of ids) sub.members.add(e)
1677
+ } else sub.members = ids
1678
+ if (sub.routed) network(sub).add(sub, queryOf(sub), sub.members)
1679
+ // A far peer movement changes membership, not stored answer rows.
1680
+ // Existing members need no second copy of their unchanged row.
1681
+ let changed = joinsOnly
1682
+ ? set.filter((b) => joined.includes(b.entity.eid))
1683
+ : set
1684
+ rememberFields(sub, changed)
1685
+ for (let e of gone) {
1686
+ sub.fields.delete(e)
1687
+ sub.targets.delete(e)
1688
+ }
1689
+ let frame = framed(sub, changed, answer)
1690
+ if (changed.length || gone.length || frame.peerGone) {
1691
+ return sub.send({
1692
+ id: sub.id,
1693
+ ...frame,
1694
+ ...sub.window && !scope && !joinsOnly ? { reset: true } : {},
1695
+ gone,
1696
+ ...hail(sub, joined),
1697
+ })
1698
+ }
1699
+ })
1700
+ }
1701
+
1702
+ // One pass over the transactions that committed since the last: each one
1703
+ // to the raw feeds, then all of them at once to the queries.
1704
+ let fanout = (txs: Bundle[][]) => {
1705
+ let target = opts.activity ?? base
1706
+ let c = peek(target)
1707
+ if (!c) return commitNow(txs)
1708
+ // Refreshes can run after the writer has already answered. The box host
1709
+ // treats a missing/completed parent as an independent request; a Store
1710
+ // still recording that write keeps this pass in its existing tree.
1711
+ return scope(undefined, () =>
1712
+ during(
1713
+ c.begin({
1714
+ kind: 'request',
1715
+ name: 'ws refresh',
1716
+ package: '@yaks/api',
1717
+ parent: parent(target, txs[0]),
1718
+ }),
1719
+ () =>
1720
+ during(
1721
+ c.begin({
1722
+ kind: 'fanout',
1723
+ name: 'subscriptions',
1724
+ package: '@yaks/api',
1725
+ }),
1726
+ () => commitNow(txs),
1727
+ 'ok',
1728
+ () => ({
1729
+ transactions: txs.length,
1730
+ bundles: txs.reduce((n, b) => n + b.length, 0),
1731
+ subscriptions: all().length,
1732
+ }),
1733
+ ),
1734
+ ))
1735
+ }
1736
+
1737
+ // A live answer asked again whole, and what moved sent: the set as it now
1738
+ // stands, what left it and what joined.
1739
+ let reread = (
1740
+ s: Sub,
1741
+ load: (s: Sub, q: string) => Answer,
1742
+ ): void | Promise<void> => {
1743
+ // An answer asked again whole is no longer one kept current.
1744
+ if (s.shared) unshare(s.shared)
1745
+ if (s.kept) return
1746
+ let reset = s.deferred
1747
+ if (s.agg) return tell(s)
1748
+ let loaded = s.view
1749
+ ? viewed(s.view, reading(s))
1750
+ : s.peer
1751
+ ? after(read(s), answered)
1752
+ : load(s, s.query)
1753
+ return after(loaded, (answer) => {
1754
+ s.deferred = false
1755
+ let set = answer.found
1756
+ let ids = new Set(set.map((b) => b.entity.eid))
1757
+ let gone = [...s.members].filter((id) => !ids.has(id))
1758
+ let joined = [...ids].filter((id) => !s.members.has(id))
1759
+ s.members = ids
1760
+ for (let e of gone) s.targets.delete(e)
1761
+ if (
1762
+ reset && routable(s)
1763
+ ) s.routed = network(s).add(s, queryOf(s), ids)
1764
+ else if (s.routed) network(s).add(s, queryOf(s), ids)
1765
+ if (s.routed) join(s, s.ast ?? parse(s.query), set)
1766
+ rememberFields(s, set)
1767
+ return s.send({
1768
+ id: s.id,
1769
+ ...framed(s, set, answer),
1770
+ ...reset || s.window ? { reset: true } : {},
1771
+ gone,
1772
+ ...hail(s, joined),
1773
+ })
1774
+ })
1775
+ }
1776
+
1777
+ let commitNow = (txs: Bundle[][]) => {
1778
+ if (ending.signal.aborted) return
1779
+ flush()
1780
+ let applied = txs.flat()
1781
+ let wrote = new Set(applied.map((b) => b.entity.eid))
1782
+ let named = new Set(applied.flatMap((b) => Object.keys(b)))
1783
+ for (let [key, link] of backlinks) {
1784
+ if (
1785
+ named.has(link.comp) || link.rows.some((b) => wrote.has(b.entity.eid))
1786
+ ) backlinks.delete(key)
1787
+ }
1788
+ for (let [key, held] of durableCandidates) {
1789
+ if (
1790
+ opts.invalidate || policyMoved(held.sub, applied) ||
1791
+ applied.some((b) => notices(held.sub, b))
1792
+ ) durableCandidates.delete(key)
1793
+ }
1794
+ let subs = all()
1795
+ // A raw feed sends each transaction to a client, and this hook is handed
1796
+ // what the phases passed to each other — one patch each, with the `$`
1797
+ // keys still on them. So it is composed here, the same way `apply()`
1798
+ // composes what it returns: a subscriber receives exactly what the writer
1799
+ // did.
1800
+ let raw = subs.filter((s) => s.raw)
1801
+ for (let tx of raw.length ? txs : []) {
1802
+ let bundles = composed(tx)
1803
+ for (let s of raw) s.send({ id: s.id, bundles })
1804
+ }
1805
+ let queries = [...subs.filter((s) => !s.raw), ...kept.values()]
1806
+ let invalidated = new Set(
1807
+ queries.filter((s) =>
1808
+ s.deferred && applied.some((b) => notices(s, b)) ||
1809
+ policyMoved(s, applied) ||
1810
+ opts.invalidate?.(s.query, applied) ||
1811
+ s.view && applied.some((b) =>
1812
+ b.$delete ||
1813
+ !s.view!.dependencies || comps(b).some(([comp]) =>
1814
+ s.view!.dependencies!.includes(comp)
1815
+ )
1816
+ )
1817
+ ),
1818
+ )
1819
+ for (let s of invalidated) {
1820
+ if (!s.policyDependencies?.length) continue
1821
+ let visibility = graph.scope(s.opts).visibility
1822
+ let query = visibility?.entity
1823
+ s.policy = query === undefined ? undefined : interest(
1824
+ typeof query == 'string' ? parse(query) : query,
1825
+ graph.vocab,
1826
+ graph.worn,
1827
+ )
1828
+ s.reads = dependencies(
1829
+ interest(parse(s.query), graph.vocab, graph.worn),
1830
+ s.opts,
1831
+ )
1832
+ }
1833
+ let noticedBy = new Map(queries.map((s) => [
1834
+ s,
1835
+ new Set(applied.filter((b) => notices(s, b)).map((b) => b.entity.eid)),
1836
+ ]))
1837
+ let relevant = new Set(
1838
+ queries.filter((s) => invalidated.has(s) || noticedBy.get(s)!.size),
1839
+ )
1840
+ for (let s of relevant) if (s.peer) s.candidates = undefined
1841
+ let touched = [
1842
+ ...new Set(
1843
+ applied.filter((b) =>
1844
+ peerRows.has(b.entity.eid) || invalidated.size ||
1845
+ [...noticedBy.values()].some((ids) => ids.has(b.entity.eid))
1846
+ ).map((b) => b.entity.eid),
1847
+ ),
1848
+ ]
1849
+ if (!relevant.size && !touched.length) return
1850
+ // One read for every subscription asking the same thing in this pass,
1851
+ // owned by all of them: a socket that drops mid-pass cancels no answer
1852
+ // another page is waiting on.
1853
+ let reads = new Map<string, Joint<Projected>>()
1854
+ let load = (s: Sub, q: string) => {
1855
+ let key = s.opts ? JSON.stringify([q, s.opts]) : q
1856
+ let got = reads.get(key)
1857
+ if (!got || got.cancelled.aborted) {
1858
+ reads.set(key, got = jointly((signal) => ask(s, q, signal)))
1859
+ }
1860
+ got.share(s.abort?.signal)
1861
+ return got.value
1862
+ }
1863
+ let names = touched.some((eid) => peerRows.has(eid))
1864
+ ? undefined
1865
+ : components(queries)
1866
+ return after(graph.get(touched, names, { native: true }), (now) => {
1867
+ let changed = new Map(now.map((b) => [b.entity.eid, b]))
1868
+ for (let eid of touched) {
1869
+ if (peerRows.has(eid)) {
1870
+ let row = changed.get(eid)
1871
+ peerRows.set(eid, row ? stored(row) : null)
1872
+ }
1873
+ }
1874
+ if (!queries.length) return
1875
+ let touch = touches(applied, now)
1876
+ return after(routeAll(now, touched, false), (durable) =>
1877
+ after(
1878
+ routeAll(
1879
+ overlay(now.map(stored), peers.values(touched)),
1880
+ touched,
1881
+ true,
1882
+ ),
1883
+ (peer) => {
1884
+ let routing = new Map([...durable, ...peer])
1885
+ return after(
1886
+ over(queries, (s) =>
1887
+ attempt(s, () => {
1888
+ if (!relevant.has(s)) return
1889
+ if (invalidated.has(s)) return reread(s, load)
1890
+ if (s.routed && !s.reads?.via.size) {
1891
+ let moved = routing.get(s)
1892
+ if (moved) {
1893
+ let joined = new Set(moved.joined)
1894
+ moved.bundles = moved.bundles.filter((b) =>
1895
+ joined.has(b.entity.eid) ||
1896
+ noticedBy.get(s)!.has(b.entity.eid)
1897
+ )
1898
+ }
1899
+ return send(s, moved)
1900
+ }
1901
+ // An ordered window can change only at the named local rows.
1902
+ // Re-select its existing members plus those rows, not every old
1903
+ // entry. A missing replacement (delete/filter exit) falls back to
1904
+ // the full query, since an unseen row may fill the window then.
1905
+ let ast = s.ast ?? parse(s.query)
1906
+ let limit = ast.clauses.find((c) => c.kind == 'limit')
1907
+ if (
1908
+ limit?.kind == 'limit' && !s.peer && !s.view && !s.agg &&
1909
+ s.reads && !s.reads.unseen && !s.reads.far.size &&
1910
+ !s.reads.via.size && s.reads.own.length &&
1911
+ !ast.clauses.some((c) => c.kind == 'after') &&
1912
+ (s.members.size < limit.n ||
1913
+ ![...noticedBy.get(s)!].some((id) => s.members.has(id)))
1914
+ ) {
1915
+ let local = affected(
1916
+ { ...s, reads: { ...s.reads, whole: false } },
1917
+ touch,
1918
+ noticedBy.get(s)!,
1919
+ )
1920
+ if (local === undefined) return
1921
+ if (local) {
1922
+ if (
1923
+ s.members.size < limit.n &&
1924
+ local.size == 1 &&
1925
+ [...s.members].every((id) => local.has(id)) &&
1926
+ !s.plan?.reaches.length
1927
+ ) {
1928
+ // Commit facts can answer the whole window when only
1929
+ // one entity can belong to it. Otherwise the Store
1930
+ // must put affected and unchanged rows in query order.
1931
+ return after(
1932
+ graph.answer(
1933
+ now.filter((b) => local.has(b.entity.eid)),
1934
+ { ...s.opts, native: true },
1935
+ ),
1936
+ (rows) =>
1937
+ push(s, undefined, () =>
1938
+ answered(
1939
+ matcher(queryOf(s), graph.vocab, s.opts)(rows)
1940
+ .map(s.cut),
1941
+ )),
1942
+ )
1943
+ }
1944
+ let candidates = [...new Set([...s.members, ...local])]
1945
+ if (
1946
+ candidates.some((id) => !/^[a-zA-Z0-9_-]+$/.test(id))
1947
+ ) return push(s, undefined, load)
1948
+ let q = s.query + '&.entity.eid=' + candidates.join(',')
1949
+ let loaded = load(s, q)
1950
+ return after(loaded, (answer) => {
1951
+ return push(s, undefined, () =>
1952
+ s.members.size >= limit.n &&
1953
+ answer.found.length < limit.n
1954
+ ? load(s, s.query)
1955
+ : answer)
1956
+ })
1957
+ }
1958
+ }
1959
+ let scope = affected(s, touch, noticedBy.get(s)!)
1960
+ if (scope === undefined) {
1961
+ return
1962
+ }
1963
+ return push(s, scope ?? undefined, load)
1964
+ })),
1965
+ () => undefined,
1966
+ )
1967
+ },
1968
+ ))
1969
+ })
1970
+ }
1971
+ // A commit that finds earlier work still running waits for it, beside every
1972
+ // commit that arrives meanwhile: when their turn comes they are one pass.
1973
+ let waiting: { txs: Bundle[][]; done: Promise<void> } | undefined
1974
+ let commits = (txs: Bundle[][]): void | Promise<void> => {
1975
+ if (ending.signal.aborted || !txs.length) return
1976
+ advance()
1977
+ let applied = txs.flat()
1978
+ for (let mine of held.values()) {
1979
+ for (let sub of mine.values()) {
1980
+ if (
1981
+ sub.loading && (!sub.reads || policyMoved(sub, applied) ||
1982
+ applied.some((b) => notices(sub, b)) ||
1983
+ opts.invalidate?.(sub.query, applied))
1984
+ ) sub.dirty = true
1985
+ }
1986
+ }
1987
+ flushPeers()
1988
+ if (waiting) {
1989
+ waiting.txs.push(...txs)
1990
+ return waiting.done
1991
+ }
1992
+ if (!pendingWork) return ordered(() => fanout(txs))
1993
+ let next = { txs: [...txs], done: Promise.resolve() }
1994
+ waiting = next
1995
+ next.done = ordered(() => {
1996
+ waiting = undefined
1997
+ return fanout(next.txs)
1998
+ }) as Promise<void>
1999
+ return next.done
2000
+ }
2001
+ let commit = (applied: Bundle[]) => commits([applied])
2002
+ // What other hosts committed comes as one pass. When some of it never
2003
+ // arrived, every answer is read again first: the patches that did arrive
2004
+ // cannot say what the missing ones moved.
2005
+ let hear = ({ applied, missed }: News): void | Promise<void> => {
2006
+ let reset = missed ? (flushPeers(), ordered(resync)) : undefined
2007
+ let pass = commits(applied)
2008
+ return isPromise(reset) || isPromise(pass)
2009
+ ? Promise.all([reset, pass]).then(() => {})
2010
+ : undefined
2011
+ }
2012
+
2013
+ // Each caller context routes only mandatory-policy-filtered canonical rows.
2014
+ // Its network and shared answers never contain another person's aspects.
2015
+ let routeAll = (
2016
+ rows: Bundle[],
2017
+ touched: Eid[],
2018
+ peer: boolean,
2019
+ joinsOnly = false,
2020
+ ): Map<Sub, Moved> | Promise<Map<Sub, Moved>> => {
2021
+ let groups = new Map<ReturnType<typeof net<Sub>>, ReadOpts | undefined>()
2022
+ for (let sub of [...all(), ...kept.values()]) {
2023
+ if (sub.routed && sub.peer === peer) groups.set(network(sub), sub.opts)
2024
+ }
2025
+ let out = new Map<Sub, Moved>()
2026
+ return after(
2027
+ over([...groups], ([routing, readOpts]) =>
2028
+ after(
2029
+ graph.answer(rows, { ...readOpts, native: true }),
2030
+ (visible) => {
2031
+ for (
2032
+ let [sub, moved] of route(visible, touched, routing, joinsOnly)
2033
+ ) {
2034
+ out.set(sub, moved)
2035
+ }
2036
+ },
2037
+ )),
2038
+ () => out,
2039
+ )
2040
+ }
2041
+
2042
+ // The entities a transaction changed, read whole, each moved through the
2043
+ // network once: what joined and what left every routed subscription.
2044
+ let route = (
2045
+ now: Bundle[],
2046
+ touched: Eid[],
2047
+ routing: ReturnType<typeof net<Sub>>,
2048
+ joinsOnly = false,
2049
+ ): Map<Sub, Moved> => {
2050
+ let out = new Map<Sub, Moved>()
2051
+ let of = (s: Sub) => {
2052
+ let m = out.get(s)
2053
+ if (!m) out.set(s, m = { bundles: [], joined: [], gone: [] })
2054
+ return m
2055
+ }
2056
+ let seen = new Set<Eid>()
2057
+ for (let b of now) {
2058
+ let eid = b.entity.eid
2059
+ seen.add(eid)
2060
+ let { into, out: left } = routing.move(b)
2061
+ for (let s of left) {
2062
+ s.members.delete(eid)
2063
+ of(s).gone.push(eid)
2064
+ }
2065
+ for (let s of into) {
2066
+ let joined = !s.members.has(eid)
2067
+ if (joined) of(s).joined.push(eid)
2068
+ s.members.add(eid)
2069
+ // Peer relays change routing but not stored data. Existing members
2070
+ // already heard the patch from cast(); only new members need a
2071
+ // full stored bundle and the held relay from hail().
2072
+ if (joined || !joinsOnly) {
2073
+ of(s).bundles.push(s.cut(s.peer ? stored(b) : b))
2074
+ }
2075
+ }
2076
+ }
2077
+ // An entity storage no longer holds at all has left every set too.
2078
+ for (let eid of touched) {
2079
+ if (seen.has(eid)) continue
2080
+ for (let s of routing.forget(eid)) {
2081
+ s.members.delete(eid)
2082
+ of(s).gone.push(eid)
2083
+ }
2084
+ }
2085
+ return out
2086
+ }
2087
+
2088
+ // Deliver a relay patch to the old members before that patch changes a
2089
+ // peer-aware query's membership. A raw feed receives every patch.
2090
+ let cast = (bundles: Bundle[], except?: Sink) => {
2091
+ for (let [sink, mine] of held) {
2092
+ if (sink === except) continue
2093
+ for (let sub of mine.values()) {
2094
+ // Views refresh after the canonical movement; their whole answer
2095
+ // includes the reconstructed relay value in the caller's vocabulary.
2096
+ if (sub.view) continue
2097
+ let seen = sub.raw
2098
+ ? bundles
2099
+ : bundles.filter((b) => sub.members.has(b.entity.eid))
2100
+ if (seen.length) sub.send({ id: sub.id, relay: seen })
2101
+ }
2102
+ }
2103
+ }
2104
+ let peers: Relay<Sink> = relaying(
2105
+ graph.vocab,
2106
+ (b) => {
2107
+ flushPeers()
2108
+ let out = ordered(() => peerChange(b))
2109
+ if (isPromise(out)) out.catch((err) => fault(err, 'peer expiry'))
2110
+ },
2111
+ opts.timer,
2112
+ )
2113
+
2114
+ // A peer query is answered from durable candidates and the relay's current
2115
+ // values together. The query plan keeps unrelated durable rows out of this
2116
+ // read, even when an OR has both stored and peer branches.
2117
+ let overlay = (rows: Bundle[], values: Bundle[]): Bundle[] => {
2118
+ let out = new Map(rows.map((b) => [b.entity.eid, b]))
2119
+ for (let peer of values) {
2120
+ let was = out.get(peer.entity.eid) ?? { entity: peer.entity }
2121
+ out.set(peer.entity.eid, { ...was, ...peer })
2122
+ }
2123
+ return [...out.values()]
2124
+ }
2125
+ let stored = (b: Bundle): Bundle => {
2126
+ let out: Bundle = { entity: b.entity }
2127
+ for (let [name, patch] of comps(b)) {
2128
+ if (!peerComp(name)) out[name] = patch
2129
+ }
2130
+ return out
2131
+ }
2132
+ let durableRows = (ids: Eid[]): Bundle[] | Promise<Bundle[]> => {
2133
+ let missing = ids.filter((eid) => !peerRows.has(eid))
2134
+ let collect = () => ids.flatMap((eid) => peerRows.get(eid) ?? [])
2135
+ if (!missing.length) return collect()
2136
+ return after(graph.get(missing, undefined, { native: true }), (rows) => {
2137
+ let found = new Map(rows.map((b) => [b.entity.eid, stored(b)]))
2138
+ for (let eid of missing) peerRows.set(eid, found.get(eid) ?? null)
2139
+ return collect()
2140
+ })
2141
+ }
2142
+ let candidatesOf = (sub: Sub): Bundle[] | Promise<Bundle[]> => {
2143
+ let targets = peerTargets(sub.ast ?? parse(sub.query))
2144
+ if (!sub.durable) {
2145
+ return targets.length
2146
+ ? after(
2147
+ graph.get(targets, undefined, { ...reading(sub), native: true }),
2148
+ (roots) => roots.map(stored),
2149
+ )
2150
+ : []
2151
+ }
2152
+ let read = () =>
2153
+ after(
2154
+ graph.read(sub.durable!, {
2155
+ ...reading(sub),
2156
+ durable: true,
2157
+ native: !!sub.ast || graph.rewrites(sub.opts) || sub.opts?.native,
2158
+ }),
2159
+ (rows) => {
2160
+ return targets.length
2161
+ ? after(
2162
+ graph.get(targets, undefined, { ...reading(sub), native: true }),
2163
+ (roots) => [...rows, ...roots].map(stored),
2164
+ )
2165
+ : rows.map(stored)
2166
+ },
2167
+ )
2168
+ if (sub.opts?.now != null || moving(sub.durable)) return read()
2169
+ let key = JSON.stringify([sub.durable, sub.opts ?? null, targets])
2170
+ let found = durableCandidates.get(key)
2171
+ if (
2172
+ found && (!isPromise(found.rows) ||
2173
+ found.sub.abort === sub.abort)
2174
+ ) return found.rows
2175
+ if (found) return read()
2176
+ let held: { sub: Sub; rows: Bundle[] | Promise<Bundle[]> } = {
2177
+ sub: {
2178
+ ...sub,
2179
+ reads: dependencies(
2180
+ interest(sub.durable, graph.vocab, graph.worn),
2181
+ sub.opts,
2182
+ ),
2183
+ members: new Set(),
2184
+ want: null,
2185
+ },
2186
+ rows: [],
2187
+ }
2188
+ durableCandidates.set(key, held)
2189
+ let release = () => {
2190
+ if (durableCandidates.get(key) === held) durableCandidates.delete(key)
2191
+ }
2192
+ try {
2193
+ held.rows = after(read(), (rows) => {
2194
+ held.sub.members = new Set(rows.map((b) => b.entity.eid))
2195
+ if (rows.length > HELD) release()
2196
+ let n = 0
2197
+ for (let [key, entry] of [...durableCandidates].reverse()) {
2198
+ n += entry.sub.members.size
2199
+ if (n > KEPT) durableCandidates.delete(key)
2200
+ }
2201
+ return rows
2202
+ })
2203
+ if (isPromise(held.rows)) {
2204
+ held.rows = held.rows.catch((err) => {
2205
+ release()
2206
+ throw err
2207
+ })
2208
+ }
2209
+ } catch (err) {
2210
+ release()
2211
+ throw err
2212
+ }
2213
+ while (durableCandidates.size > HELD) {
2214
+ durableCandidates.delete(durableCandidates.keys().next().value!)
2215
+ }
2216
+ return held.rows
2217
+ }
2218
+ let gathered = (
2219
+ sub: Sub,
2220
+ scope?: Set<Eid>,
2221
+ scoped?: Bundle[] | Promise<Bundle[]>,
2222
+ ): Bundle[] | Promise<Bundle[]> => {
2223
+ let targets = peerTargets(sub.ast ?? parse(sub.query))
2224
+ let candidates = scope
2225
+ ? after(
2226
+ scoped ?? after(
2227
+ graph.get([...scope], undefined, { native: true }),
2228
+ (rows) => rows.map(stored),
2229
+ ),
2230
+ (rows) =>
2231
+ targets.length
2232
+ ? after(
2233
+ graph.get(targets, undefined, { ...reading(sub), native: true }),
2234
+ (roots) => [...rows, ...roots].map(stored),
2235
+ )
2236
+ : rows,
2237
+ )
2238
+ : sub.candidates ??
2239
+ (sub.candidates = candidatesOf(sub))
2240
+ if (scope) {
2241
+ return after(candidates, (rows) => {
2242
+ let ids = new Set(scope)
2243
+ if (sub.ref) {
2244
+ for (let row of overlay(rows, peers.values(scope))) {
2245
+ let eid = (row[sub.ref.comp] as Record<string, unknown> | undefined)
2246
+ ?.[sub.ref.prop]
2247
+ if (typeof eid == 'string') ids.add(eid)
2248
+ }
2249
+ }
2250
+ let values = peers.values(ids)
2251
+ return after(
2252
+ durableRows(values.map((b) => b.entity.eid)),
2253
+ (held) => overlay([...rows, ...held], values),
2254
+ )
2255
+ })
2256
+ }
2257
+ let values = peers.values()
2258
+ let ids = [...new Set(values.map((b) => b.entity.eid))]
2259
+ let refs = sub.ref && !scope && ids.length ? linked(sub.ref, ids) : []
2260
+ return after(
2261
+ candidates,
2262
+ (rows) =>
2263
+ after(
2264
+ refs,
2265
+ (linked) =>
2266
+ after(durableRows(ids), (held) =>
2267
+ overlay([...rows, ...linked, ...held], values)),
2268
+ ),
2269
+ )
2270
+ }
2271
+ let source = (
2272
+ sub: Sub,
2273
+ scope?: Set<Eid>,
2274
+ scoped?: Bundle[] | Promise<Bundle[]>,
2275
+ ) =>
2276
+ after(
2277
+ gathered(sub, scope, scoped),
2278
+ (rows) => graph.answer(rows, { ...reading(sub), native: true }),
2279
+ )
2280
+ let read = (
2281
+ sub: Sub,
2282
+ scope?: Set<Eid>,
2283
+ prepared?: Bundle[] | Promise<Bundle[]>,
2284
+ ): Bundle[] | Promise<Bundle[]> => {
2285
+ if (sub.view) return after(viewed(sub.view, reading(sub)), flat)
2286
+ if (!sub.peer) {
2287
+ return graph.read(queryOf(sub), {
2288
+ ...reading(sub),
2289
+ durable: true,
2290
+ native: !!sub.ast || graph.rewrites(sub.opts) || sub.opts?.native,
2291
+ })
2292
+ }
2293
+ return after(
2294
+ after(
2295
+ prepared ?? gathered(sub, scope),
2296
+ (rows) => graph.answer(rows, { ...reading(sub), native: true }),
2297
+ ),
2298
+ (bundles) => {
2299
+ let chosen = matcher(queryOf(sub), graph.vocab, sub.opts)(bundles)
2300
+ return chosen.filter((b) => !scope || scope.has(b.entity.eid))
2301
+ .map((b) => sub.cut(stored(b)))
2302
+ },
2303
+ )
2304
+ }
2305
+
2306
+ let snapshot = (
2307
+ line: Taken,
2308
+ readOpts: ReadOpts = {},
2309
+ nested = false,
2310
+ reduce = true,
2311
+ ): Bundle[] | Reduced | Promise<Bundle[] | Reduced> => {
2312
+ let ast = typeof line == 'string' ? parse(line) : line
2313
+ let op = reduce ? aggregate(ast) : null
2314
+ if (readOpts.durable) {
2315
+ return op
2316
+ ? after(graph.rows(line, readOpts), (rows) => reduced(op, rows))
2317
+ : graph.read(line, readOpts)
2318
+ }
2319
+ let plan = peerPlan(ast, graph.vocab)
2320
+ let p = op ? null : projection(graph.vocab, ast)
2321
+ let cut = p?.cut ??
2322
+ only(named(graph.vocab, line, nested || !!readOpts.native))
2323
+ if (!plan.peers) {
2324
+ if (op) {
2325
+ return after(
2326
+ graph.rows(ast, {
2327
+ ...readOpts,
2328
+ durable: true,
2329
+ native: nested || readOpts.native || graph.rewrites(readOpts),
2330
+ }),
2331
+ (rows) => reduced(op, rows),
2332
+ )
2333
+ }
2334
+ // A projection answers what is stored, the entities it reaches too.
2335
+ if (p) {
2336
+ return graph.read(ast, {
2337
+ ...readOpts,
2338
+ durable: true,
2339
+ native: nested || readOpts.native || graph.rewrites(readOpts),
2340
+ })
2341
+ }
2342
+ return after(
2343
+ graph.read(ast, {
2344
+ ...readOpts,
2345
+ durable: true,
2346
+ native: nested || readOpts.native || graph.rewrites(readOpts),
2347
+ }),
2348
+ (rows) =>
2349
+ rows.map((row) =>
2350
+ cut(overlay([row], peers.values([row.entity.eid]))[0])
2351
+ ),
2352
+ )
2353
+ }
2354
+ if (p?.reaches.length) {
2355
+ throw new Refused(
2356
+ 'a projection through a reference is not read over relayed values',
2357
+ )
2358
+ }
2359
+ let sub: Sub = {
2360
+ id: '',
2361
+ sink: () => {},
2362
+ send: () => {},
2363
+ raw: false,
2364
+ query: typeof line == 'string' ? line : '',
2365
+ ast: typeof line == 'string' ? undefined : line,
2366
+ opts: { ...readOpts, native: nested || readOpts.native },
2367
+ members: new Set(),
2368
+ fields: new Map(),
2369
+ targets: new Map(),
2370
+ routed: false,
2371
+ peer: true,
2372
+ durable: plan.durable,
2373
+ ref: plan.ref,
2374
+ cut,
2375
+ riders: new Set(),
2376
+ }
2377
+ return after(
2378
+ source(sub),
2379
+ (bundles) =>
2380
+ op
2381
+ ? reduced(op, matchRows(line, graph.vocab, readOpts)(bundles))
2382
+ : matcher(line, graph.vocab, readOpts)(bundles).map(cut),
2383
+ )
2384
+ }
2385
+
2386
+ // A durable watch kept by the page may still carry relays for its rows.
2387
+ // Recover only the touched owners' membership, never its retained catalog.
2388
+ let recoverMembership = (bundles: Bundle[]): void | Promise<void> => {
2389
+ let deferred = all().filter((s) => s.deferred)
2390
+ if (!deferred.length || !bundles.length) return
2391
+ let ids = [...new Set(bundles.map((b) => b.entity.eid))]
2392
+ return after(
2393
+ graph.get(ids, undefined, { native: true }),
2394
+ (rows) =>
2395
+ after(
2396
+ over(deferred, (s) => {
2397
+ let i = s.reads!
2398
+ let candidates = rows.filter((row) => i.own.every((c) => c in row))
2399
+ if (!candidates.length) return
2400
+ if (
2401
+ i.whole || i.far.size || i.via.size || s.plan?.reaches.length
2402
+ ) return open(s.sink, s.id, s.query, s.opts)
2403
+ for (
2404
+ let row of matcher(queryOf(s), graph.vocab, s.opts)(candidates)
2405
+ ) s.members.add(row.entity.eid)
2406
+ }),
2407
+ () => {},
2408
+ ),
2409
+ )
2410
+ }
2411
+ let peerChange = (
2412
+ bundles: Bundle[],
2413
+ except?: Sink,
2414
+ casted = false,
2415
+ ): void | Promise<void> => {
2416
+ if (ending.signal.aborted || !bundles.length) return
2417
+ for (let mine of held.values()) {
2418
+ for (let sub of mine.values()) {
2419
+ if (sub.loading && (!sub.reads || sub.peer)) sub.dirty = true
2420
+ }
2421
+ }
2422
+ if (!casted) {
2423
+ return after(recoverMembership(bundles), () => {
2424
+ cast(bundles, except)
2425
+ return peerChange(bundles, except, true)
2426
+ })
2427
+ }
2428
+ notify(bundles)
2429
+ // Old members hear the patch that moved a row out; new members receive
2430
+ // its full held value in the membership frame below.
2431
+
2432
+ let touched = [...new Set(bundles.map((b) => b.entity.eid))]
2433
+ let values = peers.values(touched)
2434
+ let active = new Set(values.map((b) => b.entity.eid))
2435
+ let release = () => {
2436
+ for (let eid of touched) {
2437
+ if (active.has(eid)) continue
2438
+ peerRows.delete(eid)
2439
+ for (let [key, value] of backlinks) {
2440
+ if (value.peer == eid) backlinks.delete(key)
2441
+ }
2442
+ }
2443
+ }
2444
+ if (!all().some((s) => s.peer)) {
2445
+ release()
2446
+ return
2447
+ }
2448
+ // Every watch that follows the same reference sees the same rows for
2449
+ // this movement. The cross-movement cache avoids SQL; this batch map
2450
+ // avoids rebuilding the combined answer for every watch.
2451
+ let batchLinks = new Map<string, Bundle[] | Promise<Bundle[]>>()
2452
+ let batchSources = new Map<string, Bundle[] | Promise<Bundle[]>>()
2453
+ return after(durableRows(touched), (rows) => {
2454
+ return after(
2455
+ routeAll(overlay(rows, values), touched, true, true),
2456
+ (routing) => {
2457
+ release()
2458
+ return after(
2459
+ over(
2460
+ all().filter((s) => s.peer),
2461
+ (s) =>
2462
+ attempt(
2463
+ s,
2464
+ () => {
2465
+ if (s.view) return push(s)
2466
+ if (s.routed) return send(s, routing.get(s))
2467
+ if (!s.ref || s.window) return push(s)
2468
+ let roots = new Set(
2469
+ bundles.filter((b) => s.ref!.comp in b)
2470
+ .map((b) => b.entity.eid),
2471
+ )
2472
+ let moved = bundles.filter((b) =>
2473
+ Object.keys(b).some((c) => s.ref!.far.has(c))
2474
+ )
2475
+ if (!moved.length && !roots.size) return
2476
+ let ids = [...new Set(moved.map((b) => b.entity.eid))]
2477
+ let key = JSON.stringify([s.ref.comp, s.ref.prop, ids])
2478
+ let found = batchLinks.get(key)
2479
+ if (!found) {
2480
+ found = ids.length ? linked(s.ref, ids) : []
2481
+ batchLinks.set(key, found)
2482
+ }
2483
+ return after(
2484
+ found,
2485
+ (refs) => {
2486
+ let scope = new Set([
2487
+ ...roots,
2488
+ ...refs.map((b) => b.entity.eid),
2489
+ ])
2490
+ if (!scope.size) return
2491
+ let own = rows.filter((b) => roots.has(b.entity.eid))
2492
+ let sourceKey = JSON.stringify([key, [...roots]])
2493
+ let prepared = batchSources.get(sourceKey)
2494
+ if (!prepared) {
2495
+ prepared = source(s, scope, [...refs, ...own])
2496
+ batchSources.set(sourceKey, prepared)
2497
+ }
2498
+ return push(s, scope, undefined, prepared, true)
2499
+ },
2500
+ )
2501
+ },
2502
+ ),
2503
+ ),
2504
+ () => undefined,
2505
+ )
2506
+ },
2507
+ )
2508
+ })
2509
+ }
2510
+
2511
+ const live = transient(base)
2512
+ const pending = new Map<Sink, Map<string, TransientFrame[]>>()
2513
+ let scheduled = false
2514
+ const flush = () => {
2515
+ scheduled = false
2516
+ const batch = [...pending]
2517
+ pending.clear()
2518
+ for (const [sink, ids] of batch) {
2519
+ for (const [id, frames] of ids) {
2520
+ held.get(sink)?.get(id)?.send({ id, transient: frames })
2521
+ }
2522
+ }
2523
+ }
2524
+ let stopLive = live.subscribe((frame) => {
2525
+ if (syncOf(graph.vocab, frame.component) == 'none') return
2526
+ for (const mine of held.values()) {
2527
+ for (const sub of mine.values()) {
2528
+ if (!sub.raw && !visible(sub, frame)) continue
2529
+ let ids = pending.get(sub.sink)
2530
+ if (!ids) pending.set(sub.sink, ids = new Map())
2531
+ const frames = ids.get(sub.id) ?? []
2532
+ frames.push(frame)
2533
+ ids.set(sub.id, frames)
2534
+ }
2535
+ }
2536
+ if (!scheduled) {
2537
+ scheduled = true
2538
+ queueMicrotask(flush)
2539
+ }
2540
+ })
2541
+
2542
+ // The writer is answered at its commit, and the pass it starts goes on
2543
+ // without it. A pass that fails is said here, where nobody waits on it.
2544
+ graph.use({
2545
+ name: '@yaks/api',
2546
+ // This hook follows its registry's reading. A namespace view supplies
2547
+ // that namespace at registration.
2548
+ namespace: null,
2549
+ hooks: {
2550
+ effect: (bundles, _tx, _err, context) => {
2551
+ if (ending.signal.aborted) return bundles
2552
+ let target = opts.activity ?? base
2553
+ if (context?.parent && peek(target)) {
2554
+ link(target, bundles, context.parent)
2555
+ }
2556
+ let pass = commit(bundles)
2557
+ if (isPromise(pass)) {
2558
+ pass.finally(() => unlink(target, bundles)).catch(() => {})
2559
+ } else unlink(target, bundles)
2560
+ if (isPromise(pass)) pass.catch((err) => fault(err, 'subscriptions'))
2561
+ return bundles
2562
+ },
2563
+ },
2564
+ })
2565
+
2566
+ let batch: {
2567
+ writes: Map<string, { sink: Sink; row: Bundle }>
2568
+ done: Promise<void>
2569
+ resolve: () => void
2570
+ reject: (err: unknown) => void
2571
+ cancel: () => void
2572
+ } | undefined
2573
+ let flushPeers = () => {
2574
+ let next = batch
2575
+ if (!next) return
2576
+ batch = undefined
2577
+ next.cancel()
2578
+ let run = () => {
2579
+ let writes = new Map<Sink, Bundle[]>()
2580
+ for (let { sink, row } of next.writes.values()) {
2581
+ let rows = writes.get(sink) ?? []
2582
+ rows.push(row)
2583
+ writes.set(sink, rows)
2584
+ }
2585
+ let bundles = coalesced([...next.writes.values()].map((w) => w.row))
2586
+ return after(recoverMembership(bundles), () => {
2587
+ for (let [sink, rows] of writes) cast(coalesced(rows), sink)
2588
+ return peerChange(bundles, undefined, true)
2589
+ })
2590
+ }
2591
+ try {
2592
+ let out = ordered(run)
2593
+ if (isPromise(out)) out.then(next.resolve, next.reject)
2594
+ else next.resolve()
2595
+ } catch (err) {
2596
+ next.reject(err)
2597
+ }
2598
+ }
2599
+ let enqueue = (sink: Sink, bundles: Bundle[], writer?: PeerWriter) => {
2600
+ bundles = formed(bundles)
2601
+ let stage = (accepted: Bundle[]) => {
2602
+ if (ending.signal.aborted) return
2603
+ let rows = peers.write(sink, accepted)
2604
+ if (!rows.length) return
2605
+ if (!batch) {
2606
+ let resolve!: () => void, reject!: (err: unknown) => void
2607
+ let done = new Promise<void>((yes, no) => {
2608
+ resolve = yes
2609
+ reject = no
2610
+ })
2611
+ let cancel = (opts.timer ?? ((fn, ms) => {
2612
+ let t = setTimeout(fn, ms)
2613
+ return () => clearTimeout(t)
2614
+ }))(flushPeers, 16)
2615
+ batch = { writes: new Map(), done, resolve, reject, cancel }
2616
+ }
2617
+ for (let row of rows) {
2618
+ for (let [comp, patch] of comps(row)) {
2619
+ let key = JSON.stringify([row.entity.eid, comp])
2620
+ let was = batch.writes.get(key)?.row[comp]
2621
+ let previous = was && typeof was == 'object' ? was : {}
2622
+ batch.writes.set(key, {
2623
+ sink,
2624
+ row: {
2625
+ entity: row.entity,
2626
+ [comp]: patch == null ? null : { ...previous, ...patch },
2627
+ },
2628
+ })
2629
+ }
2630
+ }
2631
+ return batch.done
2632
+ }
2633
+ // The fan-out promise must not lock the registry while its batch is
2634
+ // gathering more inputs. Flush orders delivery after storage work.
2635
+ let delivery: void | Promise<void>
2636
+ let out = ordered(() =>
2637
+ after(
2638
+ saves.write(
2639
+ sink,
2640
+ bundles,
2641
+ writer,
2642
+ peers.values(bundles.map((b) => b.entity.eid)),
2643
+ ),
2644
+ (accepted) => {
2645
+ delivery = stage(accepted)
2646
+ },
2647
+ )
2648
+ )
2649
+ return after(out, () => delivery)
2650
+ }
2651
+ // Views supply canonical candidates first; peer values are overlaid before
2652
+ // reconstructing and selecting the caller's components.
2653
+ let viewValues = (view: ReadView, readOpts: ReadOpts = {}) =>
2654
+ after(
2655
+ graph.read(view.query, { ...readOpts, native: true, durable: true }),
2656
+ (rows) =>
2657
+ after(view.expand ? view.expand(rows) : rows, (expanded) => {
2658
+ // Canonical live reads strip even positions reconstructed from an
2659
+ // unmoved saved source. A durable caller component keeps its saved
2660
+ // baseline; held values replace that baseline under active holders.
2661
+ let baseline = view.saved || readOpts.durable
2662
+ ? expanded
2663
+ : expanded.map(stored)
2664
+ return view.answer(overlay(baseline, peers.values()))
2665
+ }),
2666
+ )
2667
+ let viewed = (view: ReadView, readOpts: ReadOpts = {}): Answer =>
2668
+ after(viewValues(view, readOpts), (bundles) => {
2669
+ let p = projection(view.vocab, view.original)
2670
+ if (p) return p.fold(matchRows(p.query, view.vocab, readOpts)(bundles))
2671
+ return answered(
2672
+ matcher(view.original, view.vocab, readOpts)(bundles)
2673
+ .map(only(named(view.vocab, view.original))),
2674
+ )
2675
+ })
2676
+ let answering = (query: Taken, readOpts: ReadOpts = {}, reduce = true) => {
2677
+ if (readOpts.durable) return snapshot(query, readOpts, false, reduce)
2678
+ return after(graph.view(query, readOpts), (view) => {
2679
+ if (view) {
2680
+ let op = reduce ? aggregate(view.original) : null
2681
+ return op
2682
+ ? after(
2683
+ viewValues(view, readOpts),
2684
+ (bundles) =>
2685
+ reduced(
2686
+ op,
2687
+ matchRows(view.original, view.vocab, readOpts)(bundles),
2688
+ ),
2689
+ )
2690
+ : after(viewed(view, readOpts), flat)
2691
+ }
2692
+ return after(
2693
+ graph.ask(query, readOpts),
2694
+ (q) =>
2695
+ after(
2696
+ snapshot(q as Taken, readOpts, q !== query, reduce),
2697
+ (out) => Array.isArray(out) ? graph.answer(out, readOpts) : out,
2698
+ ),
2699
+ )
2700
+ })
2701
+ }
2702
+
2703
+ // A commit feed gives precise patches; a revision proves whether anything
2704
+ // changed even when no feed is installed. Such a change has no write set,
2705
+ // and neither have commits a feed missed, so every query gets an
2706
+ // authoritative reset and retained answers let go.
2707
+ let check = (): void | Promise<void> => {
2708
+ if (ending.signal.aborted || !opts.revision) return
2709
+ return after(knownRevision, () =>
2710
+ after(opts.revision!(), (next) => {
2711
+ if (Object.is(next, revision)) return
2712
+ revision = next
2713
+ return resync()
2714
+ }))
2715
+ }
2716
+ let resync = (): void | Promise<void> => {
2717
+ if (ending.signal.aborted) return
2718
+ advance()
2719
+ for (let mine of held.values()) {
2720
+ for (let sub of mine.values()) if (sub.loading) sub.dirty = true
2721
+ }
2722
+ for (let share of shared.values()) unshare(share)
2723
+ peerRows.clear()
2724
+ backlinks.clear()
2725
+ durableCandidates.clear()
2726
+ let answers = new Map<string, Reduced | Promise<Reduced>>()
2727
+ return after(
2728
+ parallel(
2729
+ all().filter((s) => !s.raw),
2730
+ (s) => open(s.sink, s.id, s.query, s.opts, answers, false, true),
2731
+ ),
2732
+ () => {},
2733
+ )
2734
+ }
2735
+
2736
+ let stopVocabulary = base.onVocabulary?.((previous) => {
2737
+ let out = ordered(() => {
2738
+ let watched = [...held.values()].flatMap((mine) => [...mine.values()])
2739
+ let queries = watched.filter((s) => !s.raw)
2740
+ for (let sub of queries) {
2741
+ let mine = held.get(sub.sink)!
2742
+ mine.delete(sub.id)
2743
+ forget(sub, false)
2744
+ }
2745
+ for (let share of shared.values()) unshare(share)
2746
+ scopedNets.clear()
2747
+ durableNet = net<Sub>(graph.vocab)
2748
+ peerNet = net<Sub>(graph.vocab)
2749
+ peerRows.clear()
2750
+ backlinks.clear()
2751
+ durableCandidates.clear()
2752
+ advance()
2753
+ let names = namesBetween(previous, graph.vocab)
2754
+ return parallel(queries, (sub) => {
2755
+ let mine = held.get(sub.sink)!
2756
+ mine.set(sub.id, sub)
2757
+ try {
2758
+ let query = names.query(sub.query)
2759
+ return open(
2760
+ sub.sink,
2761
+ sub.id,
2762
+ query,
2763
+ names.opts(sub.opts),
2764
+ undefined,
2765
+ false,
2766
+ true,
2767
+ )
2768
+ } catch (error) {
2769
+ cut(sub, error)
2770
+ }
2771
+ })
2772
+ })
2773
+ if (isPromise(out)) {
2774
+ out.catch((error) => fault(error, 'subscription vocabulary'))
2775
+ }
2776
+ })
2777
+
2778
+ let checking = () => {
2779
+ let out = check()
2780
+ if (isPromise(out)) out.catch((err) => fault(err, 'subscription revision'))
2781
+ }
2782
+
2783
+ let reopen = (sub: Sub) => {
2784
+ if (sub.deferred && held.get(sub.sink)?.get(sub.id) === sub) {
2785
+ return open(sub.sink, sub.id, sub.query, sub.opts)
2786
+ }
2787
+ }
2788
+ let resuming: Promise<void> | undefined
2789
+ let resume = () => {
2790
+ if (resuming) return resuming
2791
+ let deferred = all().filter((sub) => sub.deferred)
2792
+ let turn = opts.yieldRecovery
2793
+ if (!turn || !deferred.length) return parallel(deferred, (s) => reopen(s))
2794
+ return resuming = (async () => {
2795
+ // Restore equal queries under the same reader together, so each
2796
+ // after the first is answered from the one it read (`opening`).
2797
+ let groups = groupBy(deferred, keyOf)
2798
+ for (let group of groups.values()) {
2799
+ for (let sub of group) {
2800
+ await turn()
2801
+ await reopen(sub)
2802
+ }
2803
+ }
2804
+ })().finally(() => resuming = undefined)
2805
+ }
2806
+
2807
+ return {
2808
+ stop: () => {
2809
+ if (ending.signal.aborted) return
2810
+ ending.abort(new Refused('subscription registry stopped'))
2811
+ let subs = [...held.values()].flatMap((mine) => [...mine.values()])
2812
+ held.clear()
2813
+ for (let sub of subs) forget(sub, false)
2814
+ for (let share of shared.values()) unshare(share)
2815
+ stopVocabulary?.()
2816
+ stopLive()
2817
+ peers.close()
2818
+ pending.clear()
2819
+ observers.clear()
2820
+ batch?.cancel()
2821
+ batch?.resolve()
2822
+ batch = undefined
2823
+ },
2824
+ get vocab() {
2825
+ return graph.vocab
2826
+ },
2827
+ activity: opts.activity ?? base,
2828
+ // A host can read while its own graph apply is saving a relay. This read
2829
+ // takes the currently admitted held values without entering ordered work.
2830
+ read: (query, readOpts) =>
2831
+ after(
2832
+ answering(query as Taken, readOpts, false),
2833
+ (out) => out as Bundle[],
2834
+ ),
2835
+ observe: (fn) => {
2836
+ observers.add(fn)
2837
+ return () => void observers.delete(fn)
2838
+ },
2839
+ snapshot: (query, readOpts) => {
2840
+ flushPeers()
2841
+ checking()
2842
+ return after(
2843
+ answering(query as Taken, readOpts),
2844
+ (out) => Array.isArray(out) ? published(graph.vocab, out) : out,
2845
+ )
2846
+ },
2847
+ enqueue,
2848
+ open: (sink, id, query, readOpts) => {
2849
+ ending.signal.throwIfAborted()
2850
+ flushPeers()
2851
+ checking()
2852
+ return open(sink, id, query, readOpts)
2853
+ },
2854
+ restore: (openings, deferStatic = false) => {
2855
+ ending.signal.throwIfAborted()
2856
+ flushPeers()
2857
+ checking()
2858
+ let answers = new Map<string, Reduced | Promise<Reduced>>()
2859
+ return parallel(
2860
+ openings,
2861
+ ({ sink, id, query, opts }) =>
2862
+ open(sink, id, query, opts, answers, deferStatic),
2863
+ )
2864
+ },
2865
+ resume,
2866
+ close: (sink, id) => {
2867
+ flushPeers()
2868
+ pending.get(sink)?.delete(id)
2869
+ let sub = held.get(sink)?.get(id)
2870
+ held.get(sink)?.delete(id)
2871
+ forget(sub)
2872
+ },
2873
+ drop: (sink) => {
2874
+ flushPeers()
2875
+ pending.delete(sink)
2876
+ let mine = held.get(sink)
2877
+ held.delete(sink)
2878
+ for (let sub of mine?.values() ?? []) forget(sub)
2879
+ if (ending.signal.aborted) return saves.drop(sink)
2880
+ return ordered(() => {
2881
+ // Connection-lifetime values leave with their writer. Timed values
2882
+ // remain available for another writer until their own expiry.
2883
+ return after(saves.drop(sink), () => {
2884
+ let off = peers.drop(sink)
2885
+ if (off.length) return peerChange(off)
2886
+ })
2887
+ })
2888
+ },
2889
+ commit,
2890
+ hear,
2891
+ check: () => {
2892
+ flushPeers()
2893
+ return ordered(check)
2894
+ },
2895
+ relay: (sink, bundles, writer) => {
2896
+ bundles = formed(bundles)
2897
+ flushPeers()
2898
+ // Admit before queueing, so even a patch superseded while waiting still
2899
+ // gets the same refusal as one sent without a backlog.
2900
+ if (saved(bundles)) {
2901
+ return ordered(() =>
2902
+ after(
2903
+ saves.write(
2904
+ sink,
2905
+ bundles,
2906
+ writer,
2907
+ peers.values(bundles.map((b) => b.entity.eid)),
2908
+ ),
2909
+ (accepted) => {
2910
+ if (ending.signal.aborted) return
2911
+ let out = peers.write(sink, accepted)
2912
+ return peerChange(out, sink)
2913
+ },
2914
+ )
2915
+ )
2916
+ }
2917
+ return after(
2918
+ saves.write(
2919
+ sink,
2920
+ bundles,
2921
+ writer,
2922
+ peers.values(bundles.map((b) => b.entity.eid)),
2923
+ ),
2924
+ (accepted) => {
2925
+ if (ending.signal.aborted) return
2926
+ let waiting = relays.get(sink)
2927
+ if (waiting) {
2928
+ waiting.bundles = coalesced([...waiting.bundles, ...accepted])
2929
+ return waiting.done
2930
+ }
2931
+ let run = (rows: Bundle[]) =>
2932
+ ending.signal.aborted
2933
+ ? undefined
2934
+ : peerChange(peers.write(sink, rows), sink)
2935
+ if (!pendingWork) return ordered(() => run(accepted))
2936
+ let next = { bundles: accepted, done: Promise.resolve() }
2937
+ relays.set(sink, next)
2938
+ next.done = ordered(() => {
2939
+ relays.delete(sink)
2940
+ return run(next.bundles)
2941
+ }) as Promise<void>
2942
+ return next.done
2943
+ },
2944
+ )
2945
+ },
2946
+ relaying: (sink) => peers.holds(sink),
2947
+ relayed: (sink, keys) =>
2948
+ ordered(() => {
2949
+ let before = new Set(peers.holds(sink))
2950
+ peers.adopt(sink, keys)
2951
+ let restored = peers.holds(sink).filter((key) => {
2952
+ let comp = key.slice(key.indexOf(' ') + 1)
2953
+ return !before.has(key) && saveOf(graph.vocab, comp) != null
2954
+ })
2955
+ if (!restored.length) return
2956
+ let ids = [...new Set(restored.map((k) => k.slice(0, k.indexOf(' '))))]
2957
+ return after(
2958
+ graph.get(ids, undefined, { native: true, durable: true }),
2959
+ (rows) => {
2960
+ let held = new Set(restored)
2961
+ let values = rows.flatMap((row) => {
2962
+ let value: Bundle = { entity: row.entity }
2963
+ for (let [comp, patch] of comps(row)) {
2964
+ if (held.has(row.entity.eid + ' ' + comp) && patch != null) {
2965
+ value[comp] = patch
2966
+ }
2967
+ }
2968
+ return comps(value).length ? [value] : []
2969
+ })
2970
+ return peerChange(peers.write(sink, values), sink)
2971
+ },
2972
+ )
2973
+ }),
2974
+ pace: (comp) => peerComp(comp) ? paceOf(graph.vocab, comp) : null,
2975
+ save: (comp) => saveOf(graph.vocab, comp),
2976
+ now: opts.now,
2977
+ timer: opts.timer,
2978
+ }
2979
+ }