@yaks/sync 0.0.0-stage → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +729 -2
- package/_dist/coverage.d.ts +7 -0
- package/_dist/coverage.d.ts.map +1 -0
- package/_dist/inbound.d.ts +43 -0
- package/_dist/inbound.d.ts.map +1 -0
- package/_dist/mark.d.ts +29 -0
- package/_dist/mark.d.ts.map +1 -0
- package/_dist/mod.d.ts +78 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/outbound.d.ts +55 -0
- package/_dist/outbound.d.ts.map +1 -0
- package/_dist/outbox.d.ts +48 -0
- package/_dist/outbox.d.ts.map +1 -0
- package/_dist/pace.d.ts +9 -0
- package/_dist/pace.d.ts.map +1 -0
- package/_dist/port.d.ts +31 -0
- package/_dist/port.d.ts.map +1 -0
- package/_dist/revision.d.ts +60 -0
- package/_dist/revision.d.ts.map +1 -0
- package/_dist/saying.d.ts +12 -0
- package/_dist/saying.d.ts.map +1 -0
- package/_dist/socket.d.ts +151 -0
- package/_dist/socket.d.ts.map +1 -0
- package/_dist/sync.d.ts +97 -0
- package/_dist/sync.d.ts.map +1 -0
- package/_dist/tier.d.ts +62 -0
- package/_dist/tier.d.ts.map +1 -0
- package/clock.js +43 -0
- package/clock.js.map +1 -0
- package/clock.ts +56 -0
- package/coverage.js +13 -0
- package/coverage.js.map +1 -0
- package/coverage.ts +26 -0
- package/deno.json +1 -0
- package/inbound.js +217 -0
- package/inbound.js.map +1 -0
- package/inbound.ts +251 -0
- package/mark.js +87 -0
- package/mark.js.map +1 -0
- package/mark.ts +108 -0
- package/mod.js +78 -0
- package/mod.js.map +1 -0
- package/mod.ts +153 -0
- package/outbound.js +170 -0
- package/outbound.js.map +1 -0
- package/outbound.ts +221 -0
- package/outbox.js +281 -0
- package/outbox.js.map +1 -0
- package/outbox.ts +343 -0
- package/pace.js +96 -0
- package/pace.js.map +1 -0
- package/pace.ts +91 -0
- package/package.json +32 -4
- package/port.js +128 -0
- package/port.js.map +1 -0
- package/port.ts +176 -0
- package/rebase.js +93 -0
- package/rebase.js.map +1 -0
- package/rebase.ts +77 -0
- package/revision.js +104 -0
- package/revision.js.map +1 -0
- package/revision.ts +146 -0
- package/saying.js +62 -0
- package/saying.js.map +1 -0
- package/saying.ts +69 -0
- package/socket.js +694 -0
- package/socket.js.map +1 -0
- package/socket.ts +927 -0
- package/sync.js +542 -0
- package/sync.js.map +1 -0
- package/sync.ts +705 -0
- package/tier.js +176 -0
- package/tier.js.map +1 -0
- package/tier.ts +211 -0
package/sync.ts
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
// Where the pieces are assembled: a client graph connected to a server.
|
|
2
|
+
//
|
|
3
|
+
// Three plugin hooks and one socket. The `precondition` hook runs inside the
|
|
4
|
+
// write's transaction, before the patches go in, and marks each bundle the
|
|
5
|
+
// caller passed in with a copy of the entity it is about to change — that mark
|
|
6
|
+
// is what tells the `effect` hook which bundles came from a caller, and what to
|
|
7
|
+
// put back if the server refuses them. The `rules` hook marks what the write's
|
|
8
|
+
// rules added the same way, since the server's answer replaces it and its
|
|
9
|
+
// refusal takes it back (./mark.ts). The `effect` hook runs after the commit
|
|
10
|
+
// and sends the write without waiting for a response: a local write over a
|
|
11
|
+
// local store is synchronous, and staying synchronous is most of the reason to
|
|
12
|
+
// run a graph in a page at all.
|
|
13
|
+
//
|
|
14
|
+
// One exception: a write that deletes is not applied optimistically. Deletion
|
|
15
|
+
// is final in this model, so a refused delete could never be put back; the
|
|
16
|
+
// precondition hook holds the whole list of bundles out of the transaction and
|
|
17
|
+
// sends it as it stands, and the server's response is applied here marked as an
|
|
18
|
+
// echo, carrying its own tombstones — exactly as the response to an accepted
|
|
19
|
+
// write is.
|
|
20
|
+
//
|
|
21
|
+
// Requests are serialized. Two writes posted at once could reach the server in
|
|
22
|
+
// either order, and the second one's response could then reconcile the first
|
|
23
|
+
// one's properties backwards. One promise chain, in the order the writes
|
|
24
|
+
// committed.
|
|
25
|
+
|
|
26
|
+
import type { Bundle, Eid, Graph, Plugin, Tx } from 'jsr:@yaks/graph@0.2.36'
|
|
27
|
+
import { after } from '@yaks/fp'
|
|
28
|
+
import { comps, dead } from '@yaks/graph/bundle'
|
|
29
|
+
import { status } from '@yaks/graph/errors'
|
|
30
|
+
import { isAlias, mint } from '@yaks/graph/identity'
|
|
31
|
+
import {
|
|
32
|
+
ACK,
|
|
33
|
+
asked,
|
|
34
|
+
asking,
|
|
35
|
+
clean,
|
|
36
|
+
ECHO,
|
|
37
|
+
echoed,
|
|
38
|
+
replicate,
|
|
39
|
+
ruling,
|
|
40
|
+
SENT,
|
|
41
|
+
} from './mark.js'
|
|
42
|
+
import {
|
|
43
|
+
exchange,
|
|
44
|
+
type Fetch,
|
|
45
|
+
type Refusal,
|
|
46
|
+
type Report,
|
|
47
|
+
WriteRefused,
|
|
48
|
+
WriteUnknown,
|
|
49
|
+
} from './outbound.js'
|
|
50
|
+
import { outward, relayed, syncOf } from './tier.js'
|
|
51
|
+
import { durableOutbox, type OutboxStore, type Pending } from './outbox.js'
|
|
52
|
+
import { pacer } from './pace.js'
|
|
53
|
+
import { type Mine, saying } from './saying.js'
|
|
54
|
+
import { land } from './inbound.js'
|
|
55
|
+
import { rebase } from './rebase.js'
|
|
56
|
+
import {
|
|
57
|
+
type Ask,
|
|
58
|
+
type Connect,
|
|
59
|
+
type Frame,
|
|
60
|
+
type Tab,
|
|
61
|
+
type Timer,
|
|
62
|
+
type Wire,
|
|
63
|
+
wire,
|
|
64
|
+
type WireOpts,
|
|
65
|
+
} from './socket.js'
|
|
66
|
+
|
|
67
|
+
/** Optional working-set policy. The client supplies retention here, rather
|
|
68
|
+
* than intercepting sockets or building a second sync/readiness registry. */
|
|
69
|
+
export type Replica = {
|
|
70
|
+
subscribe: (id: string, query: Ask, opts?: SubscribeOpts) => void
|
|
71
|
+
unsubscribe: (id: string) => void
|
|
72
|
+
/** apply one frame; `mine` is what this node is saying itself, which a
|
|
73
|
+
* reset frame leaves out (inbound.ts `hear`) */
|
|
74
|
+
land: (frame: Frame, mine?: Mine) => Bundle[] | Promise<Bundle[]>
|
|
75
|
+
/** Hold these rows as a local write left them until it is answered. What
|
|
76
|
+
* it returns lets go, and names the subscriptions whose answers it held a
|
|
77
|
+
* row back from, which are asked again. */
|
|
78
|
+
protect: (eids: Eid[]) => (accepted?: boolean) => string[]
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Local priming is optional: an authoritative server query may not be
|
|
82
|
+
* evaluable over the client's incomplete graph (search, ranking, walks). */
|
|
83
|
+
export type SubscribeOpts = {
|
|
84
|
+
/** Seed ownership from a local query before the first answer (default true). */
|
|
85
|
+
prime?: boolean
|
|
86
|
+
/** Exact app semantic identity, including query options, for bounded reopen. */
|
|
87
|
+
answerKey?: string
|
|
88
|
+
/** Deliver frames directly on the same socket, bypassing the graph replica
|
|
89
|
+
* and its persistence. A receiver owns its snapshot and updates. */
|
|
90
|
+
receive?: (frame: Frame) => void
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** How a graph is connected to a server. Only `url` is required; both
|
|
94
|
+
* transports default to the platform's own. */
|
|
95
|
+
export type SyncOpts = {
|
|
96
|
+
/** Durable intent storage; defaults to IndexedDB in a browser. */
|
|
97
|
+
outbox?: OutboxStore<Bundle[]>
|
|
98
|
+
/** Isolate apps/identities sharing an origin. Defaults to URL + headers. */
|
|
99
|
+
outboxScope?: string
|
|
100
|
+
/** the server's base URL — the origin `/apply`, `/query` and `/ws` sit under */
|
|
101
|
+
url: string
|
|
102
|
+
/** Working-set ownership, retention and pending-write protection. */
|
|
103
|
+
replica?: Replica
|
|
104
|
+
/** how a write is sent (default: the global `fetch`) */
|
|
105
|
+
fetch?: Fetch
|
|
106
|
+
/** Writes and subscription snapshots may use a host's own wire envelope. */
|
|
107
|
+
request?: (key: string, sent: Bundle[]) => Promise<Bundle[]>
|
|
108
|
+
initial?: (query: string) => Promise<Omit<Frame, 'id'>>
|
|
109
|
+
frame?: (frame: Frame) => void
|
|
110
|
+
/** Keep a hosted writer's receipt open during transient delivery failures. */
|
|
111
|
+
retryWrites?: boolean
|
|
112
|
+
cancelTimer?: (handle: unknown) => void
|
|
113
|
+
/** Local epoch milliseconds for clock measurement (default: monotonic epoch). */
|
|
114
|
+
time?: () => number
|
|
115
|
+
/** how the socket is opened (default: the global `WebSocket`) */
|
|
116
|
+
connect?: Connect
|
|
117
|
+
/** how a reconnect, and a relayed value's pace, is timed (default:
|
|
118
|
+
* `setTimeout`) */
|
|
119
|
+
timer?: Timer
|
|
120
|
+
/** headers on every `POST /apply` — an authorization, say */
|
|
121
|
+
headers?: Record<string, string>
|
|
122
|
+
/** where a refusal or a transport failure is surfaced (default: a warning) */
|
|
123
|
+
report?: Report
|
|
124
|
+
} & Pick<WireOpts, 'wait' | 'most' | 'held' | 'spread' | 'random'>
|
|
125
|
+
|
|
126
|
+
/** A graph's connection to a server: its subscriptions, and the state of the
|
|
127
|
+
* socket they are held on. */
|
|
128
|
+
export type Sync = {
|
|
129
|
+
/** the plugin this registered on the graph */
|
|
130
|
+
plugin: Plugin
|
|
131
|
+
/** open the socket without subscribing to anything */
|
|
132
|
+
open: () => void
|
|
133
|
+
/** subscribe to a query (or `true` for every committed write) */
|
|
134
|
+
subscribe: (query: Ask, id?: string, opts?: SubscribeOpts) => string
|
|
135
|
+
/** drop one subscription */
|
|
136
|
+
unsubscribe: (id: string) => void
|
|
137
|
+
/** Ask one subscription, or every subscription, for a fresh full frame from
|
|
138
|
+
* the server. */
|
|
139
|
+
refresh: (id?: string) => void
|
|
140
|
+
/** Store epoch milliseconds, calibrated over the socket on first use. Starts
|
|
141
|
+
* locally until a reply; retains its last offset while disconnected. */
|
|
142
|
+
now: () => number
|
|
143
|
+
/** whether the socket is open right now */
|
|
144
|
+
connected: () => boolean
|
|
145
|
+
/** say whether this page's tab is visible and focused, now and on every
|
|
146
|
+
* connection */
|
|
147
|
+
tab: (tab: Tab) => void
|
|
148
|
+
/** be called with true each time the socket opens, and with false each
|
|
149
|
+
* time an open one closes; not called immediately */
|
|
150
|
+
onConnection: (fn: (open: boolean) => void) => () => void
|
|
151
|
+
/** whether this subscription has successfully applied an answer on the
|
|
152
|
+
* current connection. Cached rows alone never make it ready. */
|
|
153
|
+
ready: (id: string) => boolean
|
|
154
|
+
/** be called when readiness changes (including on an empty first answer),
|
|
155
|
+
* and when the server refuses a subscription; not called immediately. The
|
|
156
|
+
* returned function removes the listener. */
|
|
157
|
+
onReady: (fn: (id: string, ready: boolean) => void) => () => void
|
|
158
|
+
/** why the server refused this subscription, until it answers it again */
|
|
159
|
+
refusal: (id: string) => Refusal | undefined
|
|
160
|
+
reopen: () => void
|
|
161
|
+
/** Send an input batch whose identity the server must resolve before this
|
|
162
|
+
* graph can hold it. The caller has separated browser-owned components.
|
|
163
|
+
* `key` names the write, so a send after a `WriteUnknown` under the same key
|
|
164
|
+
* is answered as the first one was, never applied twice. */
|
|
165
|
+
submit: (sent: Bundle[], key?: string) => Promise<Bundle[]>
|
|
166
|
+
/** Apply optimistically, but answer only after server acceptance. Local-only
|
|
167
|
+
* writes stay synchronous. Refusals and unknown outcomes reject. */
|
|
168
|
+
apply: (bundles: Bundle[], key?: string) => Bundle[] | Promise<Bundle[]>
|
|
169
|
+
outboxReady: Promise<void>
|
|
170
|
+
closeOutbox: () => void
|
|
171
|
+
refuse: (bundles: Bundle[], error: unknown, key?: string) => Promise<never>
|
|
172
|
+
pending: () => Pending<Bundle[]>[]
|
|
173
|
+
onPending: (fn: () => void) => () => void
|
|
174
|
+
retry: (key: string) => Promise<void>
|
|
175
|
+
forget: (key: string) => Promise<void>
|
|
176
|
+
/** resolves when every write in flight has been answered */
|
|
177
|
+
idle: () => Promise<void>
|
|
178
|
+
/** close the socket and stop reconnecting */
|
|
179
|
+
close: () => void
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let warn: Report = (t) =>
|
|
183
|
+
console.warn('@yaks/sync —', t.refused ?? t.error, t.sent)
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Connect a client graph to a server. The plugin registers itself on the graph
|
|
187
|
+
* you pass in, so one line is the whole setup:
|
|
188
|
+
*
|
|
189
|
+
* ```ts
|
|
190
|
+
* import { graph } from '@yaks/graph'
|
|
191
|
+
* import { ram } from '@yaks/ram'
|
|
192
|
+
* import { sync } from '@yaks/sync'
|
|
193
|
+
*
|
|
194
|
+
* // let g = graph({ storage: ram(vocab, { adopt: true }), vocab })
|
|
195
|
+
* // let link = sync(g, { url: 'https://recipes.example' })
|
|
196
|
+
* // link.subscribe('.recipe.course=dinner&.recipe.serves>4')
|
|
197
|
+
* ```
|
|
198
|
+
*
|
|
199
|
+
* From then on every write through `g.apply()` is applied locally at once and
|
|
200
|
+
* then sent to the server; everything the server pushes is applied locally too.
|
|
201
|
+
*/
|
|
202
|
+
export let sync = (graph: Graph, opts: SyncOpts): Sync => {
|
|
203
|
+
let report = opts.report ?? warn
|
|
204
|
+
let timer: Timer = opts.timer ?? ((fn, ms) => setTimeout(fn, ms))
|
|
205
|
+
let sending: Promise<void> = Promise.resolve()
|
|
206
|
+
let originals = new Map<string, {
|
|
207
|
+
bundles: Bundle[]
|
|
208
|
+
held: boolean
|
|
209
|
+
release?: (accepted?: boolean) => void
|
|
210
|
+
}>()
|
|
211
|
+
let outbox = durableOutbox<Bundle[], Bundle[]>({
|
|
212
|
+
scope: opts.outboxScope ?? JSON.stringify([opts.url, opts.headers ?? {}]),
|
|
213
|
+
store: opts.outbox,
|
|
214
|
+
timer: opts.timer,
|
|
215
|
+
cancelTimer: opts.cancelTimer,
|
|
216
|
+
waitForRetry: () => opts.retryWrites === true,
|
|
217
|
+
restored: opts.retryWrites
|
|
218
|
+
? async (entries) => {
|
|
219
|
+
for (let { key, sent, state } of entries) {
|
|
220
|
+
if (
|
|
221
|
+
state !== 'pending' || sent.some((b) =>
|
|
222
|
+
typeof b?.entity?.eid !== 'string' || isAlias(b.entity.eid) ||
|
|
223
|
+
dead(b)
|
|
224
|
+
)
|
|
225
|
+
) continue
|
|
226
|
+
let ids = sent.map((b) => b.entity.eid)
|
|
227
|
+
let held = new Map(
|
|
228
|
+
(await graph.get(ids)).map((b) => [b.entity.eid, b]),
|
|
229
|
+
)
|
|
230
|
+
let bundles = sent.map((b) =>
|
|
231
|
+
asking(b, held.get(b.entity.eid) ?? null)
|
|
232
|
+
)
|
|
233
|
+
await replicate(graph, sent)
|
|
234
|
+
originals.set(key, { bundles, held: false, release: protect(ids) })
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
: undefined,
|
|
238
|
+
report: (error) => {
|
|
239
|
+
if (
|
|
240
|
+
!(error instanceof WriteUnknown) && !(error instanceof WriteRefused)
|
|
241
|
+
) {
|
|
242
|
+
report({ sent: [], error, reverted: false })
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
send: async (key, sent) => {
|
|
246
|
+
let original = originals.get(key)
|
|
247
|
+
let reconcile = (landing: Bundle[]) => {
|
|
248
|
+
let ordered = [...originals]
|
|
249
|
+
let after = ordered.findIndex(([id]) => id === key) + 1
|
|
250
|
+
return rebase(
|
|
251
|
+
graph,
|
|
252
|
+
landing,
|
|
253
|
+
ordered.slice(after).map(([, write]) => write),
|
|
254
|
+
)
|
|
255
|
+
}
|
|
256
|
+
let result = await exchange(original?.bundles ?? sent, {
|
|
257
|
+
land: reconcile,
|
|
258
|
+
graph,
|
|
259
|
+
url: opts.url,
|
|
260
|
+
fetch: opts.fetch ?? ((r) => globalThis.fetch(r)),
|
|
261
|
+
headers: opts.headers,
|
|
262
|
+
report,
|
|
263
|
+
held: original?.held ?? true,
|
|
264
|
+
sent,
|
|
265
|
+
key,
|
|
266
|
+
request: opts.request,
|
|
267
|
+
moved: () => w.reopen(),
|
|
268
|
+
})
|
|
269
|
+
if (result.refused) {
|
|
270
|
+
original?.release?.(false)
|
|
271
|
+
originals.delete(key)
|
|
272
|
+
throw new WriteRefused(sent, result.refused)
|
|
273
|
+
}
|
|
274
|
+
if (result.error) throw result.error
|
|
275
|
+
original?.release?.(!original.held && !!result.applied?.length)
|
|
276
|
+
originals.delete(key)
|
|
277
|
+
return result.applied ?? []
|
|
278
|
+
},
|
|
279
|
+
})
|
|
280
|
+
let deliver = (
|
|
281
|
+
bundles: Bundle[],
|
|
282
|
+
sent: Bundle[],
|
|
283
|
+
held: boolean,
|
|
284
|
+
key: string = `outbox:${crypto.randomUUID()}`,
|
|
285
|
+
release?: (accepted?: boolean) => void,
|
|
286
|
+
) => {
|
|
287
|
+
if (!originals.has(key)) originals.set(key, { bundles, held, release })
|
|
288
|
+
return outbox.submit(sent, key)
|
|
289
|
+
}
|
|
290
|
+
let writes = 0
|
|
291
|
+
let receipts = new Map<number, {
|
|
292
|
+
key?: string
|
|
293
|
+
answer?: Promise<Bundle[] | undefined>
|
|
294
|
+
}>()
|
|
295
|
+
let asks = new Map<string, Ask>()
|
|
296
|
+
let receivers = new Map<string, (frame: Frame) => void>()
|
|
297
|
+
let members = new Map<string, Set<Eid>>()
|
|
298
|
+
// A fresh object on every invalidation guards asynchronous apply completion
|
|
299
|
+
// against a disconnect, re-point or unsubscribe while it was in flight.
|
|
300
|
+
let states = new Map<string, { ready: boolean }>()
|
|
301
|
+
let refusals = new Map<string, Refusal>()
|
|
302
|
+
let listeners = new Set<(id: string, ready: boolean) => void>()
|
|
303
|
+
let notify = (id: string, ready: boolean) => {
|
|
304
|
+
for (let fn of listeners) fn(id, ready)
|
|
305
|
+
}
|
|
306
|
+
let pending = (id: string) => {
|
|
307
|
+
let was = states.get(id)?.ready
|
|
308
|
+
states.set(id, { ready: false })
|
|
309
|
+
if (was) notify(id, false)
|
|
310
|
+
}
|
|
311
|
+
let said = saying()
|
|
312
|
+
let protect = (eids: Eid[]) => {
|
|
313
|
+
let release = opts.replica?.protect(eids)
|
|
314
|
+
return release && ((accepted?: boolean) => {
|
|
315
|
+
for (let id of release(accepted)) w.ask(id)
|
|
316
|
+
})
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
let queue = <T>(run: () => Promise<T>): Promise<T> => {
|
|
320
|
+
// Start admission now, not behind an HTTP response. Otherwise a second
|
|
321
|
+
// write could die in a promise chain before it ever reached durable disk.
|
|
322
|
+
let pending = run()
|
|
323
|
+
sending = Promise.all([sending, pending.catch(() => {})]).then(() => {})
|
|
324
|
+
return pending
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Post one write on the chain. `held` means it was never applied locally, so
|
|
328
|
+
// a refusal has nothing to revert and an unanswered request has nothing to
|
|
329
|
+
// keep pinned.
|
|
330
|
+
let send = (bundles: Bundle[], held = false) => {
|
|
331
|
+
let sent = outward(bundles, graph.vocab)
|
|
332
|
+
if (!sent.length) return
|
|
333
|
+
let release = protect(bundles.map((b) => b.entity.eid))
|
|
334
|
+
let receipt = receipts.get(bundles[0][ACK] as number)
|
|
335
|
+
let answer = queue(() =>
|
|
336
|
+
deliver(bundles, sent, held, receipt?.key, release).then(
|
|
337
|
+
async (applied) => {
|
|
338
|
+
// A held deletion deferred the whole caller batch. The HTTP door
|
|
339
|
+
// admits only server components, so its accepted answer cannot carry
|
|
340
|
+
// the page/peer half. Apply that half now through the ordinary graph
|
|
341
|
+
// hooks: page values stay local and peer values use their socket.
|
|
342
|
+
let companions = held
|
|
343
|
+
? bundles.flatMap((b) => {
|
|
344
|
+
if (dead(b)) return []
|
|
345
|
+
let own = Object.fromEntries(
|
|
346
|
+
comps(b).filter(([name]) =>
|
|
347
|
+
syncOf(graph.vocab, name) != 'server'
|
|
348
|
+
),
|
|
349
|
+
)
|
|
350
|
+
return Object.keys(own).length
|
|
351
|
+
? [{ entity: b.entity, ...own }]
|
|
352
|
+
: []
|
|
353
|
+
})
|
|
354
|
+
: []
|
|
355
|
+
let local = companions.length ? await graph.apply(companions) : []
|
|
356
|
+
return [...applied, ...local]
|
|
357
|
+
},
|
|
358
|
+
)
|
|
359
|
+
).catch((error) => {
|
|
360
|
+
if (
|
|
361
|
+
!(error instanceof WriteRefused) && !(error instanceof WriteUnknown)
|
|
362
|
+
) {
|
|
363
|
+
report({ sent, error, reverted: false })
|
|
364
|
+
}
|
|
365
|
+
throw error
|
|
366
|
+
})
|
|
367
|
+
// Background graph writes still report failures without an unhandled
|
|
368
|
+
// rejection. An acknowledged caller receives this same promise.
|
|
369
|
+
answer.catch(() => {})
|
|
370
|
+
for (let b of bundles) {
|
|
371
|
+
let receipt = receipts.get(b[ACK] as number)
|
|
372
|
+
if (receipt) receipt.answer = answer
|
|
373
|
+
}
|
|
374
|
+
return answer
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
let submit = (sent: Bundle[], key?: string): Promise<Bundle[]> =>
|
|
378
|
+
queue(() => deliver(sent, sent, true, key))
|
|
379
|
+
|
|
380
|
+
let refused = (
|
|
381
|
+
bundles: Bundle[],
|
|
382
|
+
error: unknown,
|
|
383
|
+
key?: string,
|
|
384
|
+
): Promise<never> => {
|
|
385
|
+
if (
|
|
386
|
+
error instanceof WriteRefused || !(error instanceof Error) ||
|
|
387
|
+
status(error) >= 500
|
|
388
|
+
) {
|
|
389
|
+
return Promise.reject(error)
|
|
390
|
+
}
|
|
391
|
+
let refusal = {
|
|
392
|
+
...error,
|
|
393
|
+
error: error.name,
|
|
394
|
+
message: error.message,
|
|
395
|
+
status: status(error),
|
|
396
|
+
}
|
|
397
|
+
return outbox.refuse(bundles, {
|
|
398
|
+
...refusal,
|
|
399
|
+
name: error.name,
|
|
400
|
+
}, key ?? `outbox:${mint()}`).then(() => {
|
|
401
|
+
throw new WriteRefused(bundles, refusal)
|
|
402
|
+
})
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
let apply = (
|
|
406
|
+
bundles: Bundle[],
|
|
407
|
+
key?: string,
|
|
408
|
+
): Bundle[] | Promise<Bundle[]> => {
|
|
409
|
+
let id = ++writes
|
|
410
|
+
let receipt: {
|
|
411
|
+
key?: string
|
|
412
|
+
answer?: Promise<Bundle[] | undefined>
|
|
413
|
+
} = { key }
|
|
414
|
+
receipts.set(id, receipt)
|
|
415
|
+
try {
|
|
416
|
+
let result = after(
|
|
417
|
+
graph.apply(bundles.map((b) => ({ ...b, [ACK]: id }))),
|
|
418
|
+
(local) => {
|
|
419
|
+
receipts.delete(id)
|
|
420
|
+
return receipt.answer?.then((applied) => applied ?? local) ?? local
|
|
421
|
+
},
|
|
422
|
+
)
|
|
423
|
+
if (result instanceof Promise) {
|
|
424
|
+
if (opts.retryWrites) {
|
|
425
|
+
return result.catch((error) => {
|
|
426
|
+
receipts.delete(id)
|
|
427
|
+
if (receipt.answer) throw error
|
|
428
|
+
return refused(bundles, error, key)
|
|
429
|
+
})
|
|
430
|
+
}
|
|
431
|
+
// A fire-and-forget caller still has report(). Awaiting this promise
|
|
432
|
+
// still rejects, so recovery-sensitive callers can keep their copies.
|
|
433
|
+
result.catch(() => receipts.delete(id))
|
|
434
|
+
}
|
|
435
|
+
return result
|
|
436
|
+
} catch (error) {
|
|
437
|
+
receipts.delete(id)
|
|
438
|
+
if (opts.retryWrites) return refused(bundles, error, key)
|
|
439
|
+
throw error
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// The entities a list names, as this replica holds them, by id.
|
|
444
|
+
let holding = (bundles: Bundle[], tx: Tx) =>
|
|
445
|
+
after(
|
|
446
|
+
tx.get([...new Set(bundles.map((b) => b.entity.eid))]),
|
|
447
|
+
(rows) => new Map(rows.map((b) => [b.entity.eid, b])),
|
|
448
|
+
)
|
|
449
|
+
// The caller's list, each marked with the copy to put back and written
|
|
450
|
+
// whatever the page held (`$touch`): its copy may be stale, and the
|
|
451
|
+
// server's copy decides what changes.
|
|
452
|
+
let touched = (bundles: Bundle[], was: Map<string, Bundle>) =>
|
|
453
|
+
bundles.map((b) => ({
|
|
454
|
+
...asking(b, was.get(b.entity.eid) ?? null),
|
|
455
|
+
$touch: true,
|
|
456
|
+
}))
|
|
457
|
+
|
|
458
|
+
let plugin: Plugin = {
|
|
459
|
+
name: '@yaks/sync',
|
|
460
|
+
// The two marks a batch carries through `apply()` (./mark.ts): what the
|
|
461
|
+
// caller sent, and what came back from the server.
|
|
462
|
+
requests: [SENT, ECHO, ACK],
|
|
463
|
+
hooks: {
|
|
464
|
+
// Before the transaction: a `$was` on an entity this replica doesn't
|
|
465
|
+
// hold was read from the server, which alone can judge it, so the
|
|
466
|
+
// whole list waits for the server and none of it is applied here.
|
|
467
|
+
// Here, because the precondition's own `$was` check runs before its
|
|
468
|
+
// hooks and would refuse the id as naming nothing.
|
|
469
|
+
prepare: (bundles, tx) => {
|
|
470
|
+
if (bundles.some(echoed) || !bundles.some((b) => b.$was)) return bundles
|
|
471
|
+
return after(holding(bundles, tx), (was) => {
|
|
472
|
+
if (bundles.every((b) => !b.$was || was.has(b.entity.eid))) {
|
|
473
|
+
return bundles
|
|
474
|
+
}
|
|
475
|
+
send(touched(bundles, was), true)
|
|
476
|
+
return []
|
|
477
|
+
})
|
|
478
|
+
},
|
|
479
|
+
// Inside the transaction, before the patches: the copy to put back.
|
|
480
|
+
precondition: (bundles, tx) => {
|
|
481
|
+
if (bundles.some(echoed)) return bundles
|
|
482
|
+
return after(holding(bundles, tx), (was) => {
|
|
483
|
+
let asked = touched(bundles, was)
|
|
484
|
+
// A delete waits for the server: the whole list is sent as it
|
|
485
|
+
// stands, and none of it is applied here until the response is.
|
|
486
|
+
if (bundles.some(dead)) {
|
|
487
|
+
send(asked, true)
|
|
488
|
+
return []
|
|
489
|
+
}
|
|
490
|
+
return asked
|
|
491
|
+
})
|
|
492
|
+
},
|
|
493
|
+
// After the rules, still before the patches: what they added, marked
|
|
494
|
+
// with the copy to put back. The server's own batch carries what its
|
|
495
|
+
// rules added, so a batch that came from it has nothing to mark.
|
|
496
|
+
rules: (bundles, tx) => {
|
|
497
|
+
let added = bundles.filter((b) => !asked(b))
|
|
498
|
+
if (!added.length || bundles.some(echoed)) return bundles
|
|
499
|
+
let eids = [...new Set(added.map((b) => b.entity.eid))]
|
|
500
|
+
return after(tx.get(eids), (held) => {
|
|
501
|
+
let was = new Map(held.map((b) => [b.entity.eid, b]))
|
|
502
|
+
return bundles.map((b) =>
|
|
503
|
+
asked(b) ? b : ruling(b, was.get(b.entity.eid) ?? null)
|
|
504
|
+
)
|
|
505
|
+
})
|
|
506
|
+
},
|
|
507
|
+
// After the commit: send it to the server, and reconcile the response.
|
|
508
|
+
// The marks are removed from what the caller gets back — they were this
|
|
509
|
+
// package's own bookkeeping, not part of anybody's data.
|
|
510
|
+
effect: (bundles) => {
|
|
511
|
+
if (bundles.length && !bundles.some(echoed)) {
|
|
512
|
+
send(bundles)
|
|
513
|
+
// The `sync: peers` half is sent over the socket instead: the
|
|
514
|
+
// server holds it under this connection and clears it when the
|
|
515
|
+
// connection closes, so the connection has to be the one that wrote
|
|
516
|
+
// it. It leaves at the component's pace (./pace.ts), and is kept as
|
|
517
|
+
// what this node is saying, for the next connection (./saying.ts).
|
|
518
|
+
let peers = relayed(bundles, graph.vocab)
|
|
519
|
+
said.wrote(peers, w.connected())
|
|
520
|
+
relay(peers)
|
|
521
|
+
}
|
|
522
|
+
return bundles.map(clean)
|
|
523
|
+
},
|
|
524
|
+
},
|
|
525
|
+
}
|
|
526
|
+
graph.use(plugin)
|
|
527
|
+
|
|
528
|
+
let w: Wire = wire({
|
|
529
|
+
get vocab() {
|
|
530
|
+
return graph.vocab
|
|
531
|
+
},
|
|
532
|
+
url: opts.url,
|
|
533
|
+
connect: opts.connect,
|
|
534
|
+
fetch: opts.fetch,
|
|
535
|
+
timer,
|
|
536
|
+
time: opts.time,
|
|
537
|
+
wait: opts.wait,
|
|
538
|
+
most: opts.most,
|
|
539
|
+
held: opts.held,
|
|
540
|
+
spread: opts.spread,
|
|
541
|
+
random: opts.random,
|
|
542
|
+
pending,
|
|
543
|
+
again: said.again,
|
|
544
|
+
land: (frame: Frame) => {
|
|
545
|
+
heard.add(frame.id)
|
|
546
|
+
return received(frame)
|
|
547
|
+
},
|
|
548
|
+
report: (error) => {
|
|
549
|
+
if (
|
|
550
|
+
!(error instanceof WriteUnknown) && !(error instanceof WriteRefused)
|
|
551
|
+
) {
|
|
552
|
+
report({ sent: [], error, reverted: false })
|
|
553
|
+
}
|
|
554
|
+
},
|
|
555
|
+
})
|
|
556
|
+
let heard = new Set<string>()
|
|
557
|
+
let received = (frame: Frame) => {
|
|
558
|
+
opts.frame?.(frame)
|
|
559
|
+
let receive = receivers.get(frame.id)
|
|
560
|
+
if (receive) return receive(frame)
|
|
561
|
+
if (frame.refused) {
|
|
562
|
+
// Kept for the watch to say why, and heard even by one never ready.
|
|
563
|
+
refusals.set(frame.id, frame.refused)
|
|
564
|
+
let was = states.get(frame.id)?.ready
|
|
565
|
+
pending(frame.id)
|
|
566
|
+
if (!was) notify(frame.id, false)
|
|
567
|
+
return report({
|
|
568
|
+
sent: [],
|
|
569
|
+
refused: frame.refused,
|
|
570
|
+
reverted: false,
|
|
571
|
+
subscription: frame.id,
|
|
572
|
+
})
|
|
573
|
+
}
|
|
574
|
+
// Another connection's word on a value takes it over (./saying.ts).
|
|
575
|
+
said.heard(frame.relay ?? [])
|
|
576
|
+
refusals.delete(frame.id)
|
|
577
|
+
let state = states.get(frame.id)
|
|
578
|
+
let safe = frame
|
|
579
|
+
// With a working-set policy, ownership lives there, not in a duplicate
|
|
580
|
+
// registry here. Standalone sync still protects cross-subscription rows.
|
|
581
|
+
if (!opts.replica) {
|
|
582
|
+
if (frame.peerCoverage || frame.peers || frame.peerGone) {
|
|
583
|
+
throw new Error('rider delivery requires a working-set replica')
|
|
584
|
+
}
|
|
585
|
+
let held = members.get(frame.id) ?? new Set<Eid>()
|
|
586
|
+
if (frame.reset) held.clear()
|
|
587
|
+
for (let b of frame.bundles ?? []) held.add(b.entity.eid)
|
|
588
|
+
for (let eid of frame.gone ?? []) held.delete(eid)
|
|
589
|
+
members.set(frame.id, held)
|
|
590
|
+
safe = {
|
|
591
|
+
...frame,
|
|
592
|
+
gone: frame.gone?.filter((eid) =>
|
|
593
|
+
![...members.values()].some((set) => set.has(eid))
|
|
594
|
+
),
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
let out = after(
|
|
598
|
+
opts.replica
|
|
599
|
+
? opts.replica.land(frame, said.mine)
|
|
600
|
+
: land(graph, safe, said.mine),
|
|
601
|
+
() => {
|
|
602
|
+
if (state && states.get(frame.id) === state && !state.ready) {
|
|
603
|
+
state.ready = true
|
|
604
|
+
notify(frame.id, true)
|
|
605
|
+
}
|
|
606
|
+
},
|
|
607
|
+
)
|
|
608
|
+
return out
|
|
609
|
+
}
|
|
610
|
+
let relay = pacer(() => graph.vocab, w.relay, timer)
|
|
611
|
+
let fill = (query: Ask, id: string) => {
|
|
612
|
+
if (!opts.initial || typeof query !== 'string' || w.connected()) return
|
|
613
|
+
let waiting = () => asks.has(id) && !heard.has(id)
|
|
614
|
+
void opts.initial(query).then((frame) => {
|
|
615
|
+
if (waiting()) return received({ ...frame, id })
|
|
616
|
+
}).catch((error) => {
|
|
617
|
+
if (
|
|
618
|
+
waiting() && error?.status >= 400 && error.status < 500 &&
|
|
619
|
+
![408, 425, 429].includes(error.status)
|
|
620
|
+
) {
|
|
621
|
+
return received({
|
|
622
|
+
id,
|
|
623
|
+
refused: { error: error.name, message: error.message },
|
|
624
|
+
})
|
|
625
|
+
}
|
|
626
|
+
})
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
let serial = 0
|
|
630
|
+
return {
|
|
631
|
+
plugin,
|
|
632
|
+
open: w.open,
|
|
633
|
+
subscribe: (query, id, subOpts) => {
|
|
634
|
+
// Register ownership before a synchronous transport can answer.
|
|
635
|
+
let key = id
|
|
636
|
+
if (key === undefined) {
|
|
637
|
+
do {
|
|
638
|
+
key = 's' + ++serial
|
|
639
|
+
} while (asks.has(key))
|
|
640
|
+
}
|
|
641
|
+
asks.set(key, query)
|
|
642
|
+
if (subOpts?.receive) receivers.set(key, subOpts.receive)
|
|
643
|
+
else opts.replica?.subscribe(key, query, subOpts)
|
|
644
|
+
try {
|
|
645
|
+
let id = w.subscribe(query, key)
|
|
646
|
+
fill(query, id)
|
|
647
|
+
return id
|
|
648
|
+
} catch (error) {
|
|
649
|
+
asks.delete(key)
|
|
650
|
+
if (!receivers.delete(key)) opts.replica?.unsubscribe(key)
|
|
651
|
+
throw error
|
|
652
|
+
}
|
|
653
|
+
},
|
|
654
|
+
refresh: (only) => {
|
|
655
|
+
for (let [id, query] of asks) {
|
|
656
|
+
if (only === undefined || only === id) w.subscribe(query, id)
|
|
657
|
+
}
|
|
658
|
+
},
|
|
659
|
+
unsubscribe: (id) => {
|
|
660
|
+
let ready = states.get(id)?.ready
|
|
661
|
+
states.delete(id)
|
|
662
|
+
refusals.delete(id)
|
|
663
|
+
heard.delete(id)
|
|
664
|
+
asks.delete(id)
|
|
665
|
+
members.delete(id)
|
|
666
|
+
w.unsubscribe(id)
|
|
667
|
+
if (!receivers.delete(id)) opts.replica?.unsubscribe(id)
|
|
668
|
+
if (ready) notify(id, false)
|
|
669
|
+
},
|
|
670
|
+
now: w.now,
|
|
671
|
+
connected: w.connected,
|
|
672
|
+
tab: w.tab,
|
|
673
|
+
onConnection: w.onConnection,
|
|
674
|
+
ready: (id) => states.get(id)?.ready ?? false,
|
|
675
|
+
onReady: (fn) => {
|
|
676
|
+
listeners.add(fn)
|
|
677
|
+
return () => listeners.delete(fn)
|
|
678
|
+
},
|
|
679
|
+
refusal: (id) => refusals.get(id),
|
|
680
|
+
reopen: w.reopen,
|
|
681
|
+
submit,
|
|
682
|
+
apply,
|
|
683
|
+
outboxReady: outbox.ready,
|
|
684
|
+
closeOutbox: outbox.close,
|
|
685
|
+
refuse: refused,
|
|
686
|
+
idle: () => sending,
|
|
687
|
+
pending: outbox.pending,
|
|
688
|
+
onPending: outbox.onPending,
|
|
689
|
+
retry: outbox.retry,
|
|
690
|
+
forget: outbox.forget,
|
|
691
|
+
close: () => {
|
|
692
|
+
outbox.close()
|
|
693
|
+
w.close()
|
|
694
|
+
for (let id of asks.keys()) {
|
|
695
|
+
if (!receivers.has(id)) opts.replica?.unsubscribe(id)
|
|
696
|
+
}
|
|
697
|
+
receivers.clear()
|
|
698
|
+
asks.clear()
|
|
699
|
+
members.clear()
|
|
700
|
+
states.clear()
|
|
701
|
+
refusals.clear()
|
|
702
|
+
listeners.clear()
|
|
703
|
+
},
|
|
704
|
+
}
|
|
705
|
+
}
|