@graview/ship 0.1.0 → 0.1.2
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/README.md +54 -6
- package/dist/browser-adapter.d.ts +9 -9
- package/dist/browser-adapter.d.ts.map +1 -1
- package/dist/browser-adapter.js +6 -3
- package/dist/browser-adapter.js.map +1 -1
- package/dist/browser.d.ts +10 -6
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +4 -2
- package/dist/browser.js.map +1 -1
- package/dist/cli.d.ts +17 -7
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +41 -7
- package/dist/cli.js.map +1 -1
- package/dist/export.d.ts +27 -2
- package/dist/export.d.ts.map +1 -1
- package/dist/export.js +38 -5
- package/dist/export.js.map +1 -1
- package/dist/file-adapter.d.ts +8 -8
- package/dist/file-adapter.d.ts.map +1 -1
- package/dist/file-adapter.js +58 -8
- package/dist/file-adapter.js.map +1 -1
- package/dist/handler.d.ts +162 -0
- package/dist/handler.d.ts.map +1 -0
- package/dist/handler.js +585 -0
- package/dist/handler.js.map +1 -0
- package/dist/health.d.ts +9 -0
- package/dist/health.d.ts.map +1 -1
- package/dist/health.js +5 -1
- package/dist/health.js.map +1 -1
- package/dist/index.d.ts +12 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/live.d.ts +150 -0
- package/dist/live.d.ts.map +1 -0
- package/dist/live.js +44 -0
- package/dist/live.js.map +1 -0
- package/dist/meta.d.ts +13 -0
- package/dist/meta.d.ts.map +1 -0
- package/dist/meta.js +2 -0
- package/dist/meta.js.map +1 -0
- package/dist/open-store.d.ts +56 -7
- package/dist/open-store.d.ts.map +1 -1
- package/dist/open-store.js +141 -12
- package/dist/open-store.js.map +1 -1
- package/dist/remote.d.ts +93 -12
- package/dist/remote.d.ts.map +1 -1
- package/dist/remote.js +446 -76
- package/dist/remote.js.map +1 -1
- package/dist/runtime.d.ts +32 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +21 -0
- package/dist/runtime.js.map +1 -0
- package/dist/seat-headers.d.ts +20 -0
- package/dist/seat-headers.d.ts.map +1 -0
- package/dist/seat-headers.js +20 -0
- package/dist/seat-headers.js.map +1 -0
- package/dist/serve.d.ts +15 -107
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +82 -217
- package/dist/serve.js.map +1 -1
- package/dist/source-edit.d.ts.map +1 -1
- package/dist/source-edit.js +6 -1
- package/dist/source-edit.js.map +1 -1
- package/dist/steps.d.ts +43 -0
- package/dist/steps.d.ts.map +1 -1
- package/dist/steps.js +69 -0
- package/dist/steps.js.map +1 -1
- package/dist/websocket.d.ts +14 -0
- package/dist/websocket.d.ts.map +1 -0
- package/dist/websocket.js +155 -0
- package/dist/websocket.js.map +1 -0
- package/package.json +6 -2
package/dist/remote.js
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
|
-
import { foldPresence, PRESENCE_TTL_MS, samePresence, Store, } from "@graview/core";
|
|
1
|
+
import { FieldRevisions, foldPresence, PRESENCE_TTL_MS, REMOTE_PRESENCE_TTL_MS, samePresence, Store, WIRE_PROTOCOL, writtenBy, } from "@graview/core";
|
|
2
|
+
import { LIVE_PATH } from "./live.js";
|
|
3
|
+
import { SEAT_HEADERS } from "./seat-headers.js";
|
|
4
|
+
/** A refusal that is a stale write: the server's sentence, and the fields that moved. */
|
|
5
|
+
class StaleWrite extends Error {
|
|
6
|
+
conflicts;
|
|
7
|
+
constructor(message, conflicts) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.conflicts = conflicts;
|
|
10
|
+
this.name = "StaleWrite";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
2
13
|
/**
|
|
3
14
|
* Opens a store from a server and keeps it in step with it.
|
|
4
15
|
*
|
|
@@ -12,20 +23,24 @@ function localIds() {
|
|
|
12
23
|
let at = 0;
|
|
13
24
|
return () => `local-${who}-${++at}`;
|
|
14
25
|
}
|
|
26
|
+
const OPEN = 1;
|
|
15
27
|
export async function openRemote(options) {
|
|
16
28
|
const call = options.fetch ?? fetch;
|
|
17
29
|
const headers = { "content-type": "application/json", ...(options.headers ?? {}) };
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
30
|
+
Object.assign(headers, seatHeaders(options.principal));
|
|
31
|
+
const live = options.live === true;
|
|
32
|
+
const reached = await call(`${options.url}/graview/state`, { headers });
|
|
33
|
+
if (!reached.ok)
|
|
34
|
+
throw new Error((await reached.json().catch(() => ({}))).error ?? `The server refused (${reached.status})`);
|
|
35
|
+
const state = (await reached.json());
|
|
36
|
+
const enabledModules = state.enabledModules ?? options.enabledModules;
|
|
23
37
|
const store = new Store({
|
|
24
38
|
schema: options.app.schema,
|
|
25
39
|
mutations: options.app.mutations ?? [],
|
|
26
40
|
invariants: options.app.invariants ?? [],
|
|
27
41
|
...(options.app.policy ? { policy: options.app.policy } : {}),
|
|
28
42
|
...(options.app.modules ? { modules: options.app.modules } : {}),
|
|
43
|
+
...(enabledModules ? { enabledModules } : {}),
|
|
29
44
|
...(options.app.intelligence ? { intelligence: options.app.intelligence } : {}),
|
|
30
45
|
/*
|
|
31
46
|
* The snapshot AND the log: the snapshot is the graph, the log is the
|
|
@@ -34,6 +49,8 @@ export async function openRemote(options) {
|
|
|
34
49
|
*/
|
|
35
50
|
snapshot: state.snapshot,
|
|
36
51
|
log: state.log,
|
|
52
|
+
// A compacted server hands over its tail: this log begins where that one does (FR-23).
|
|
53
|
+
...(state.horizon !== undefined ? { horizon: state.horizon } : {}),
|
|
37
54
|
/*
|
|
38
55
|
* IDS THIS CLIENT CANNOT SHARE WITH ANYBODY.
|
|
39
56
|
*
|
|
@@ -51,17 +68,20 @@ export async function openRemote(options) {
|
|
|
51
68
|
ids: localIds(),
|
|
52
69
|
...(options.storeOptions ?? {}),
|
|
53
70
|
});
|
|
54
|
-
let seen = state.log.at(-1)?.seq ?? -1;
|
|
71
|
+
let seen = state.log.at(-1)?.seq ?? (state.horizon ?? 0) - 1;
|
|
72
|
+
/** Every field's revision as the server's ops this client has say it (FR-05). */
|
|
73
|
+
const revisions = FieldRevisions.of(state.log);
|
|
55
74
|
/*
|
|
56
75
|
* PRESENCE, beside the log and never in it. `mine` is the last word this
|
|
57
|
-
* browser said about itself; it goes out with every poll
|
|
58
|
-
* and what comes back is folded into `known` for
|
|
76
|
+
* browser said about itself; it goes out with every poll (or down the
|
|
77
|
+
* socket) while it stands, and what comes back is folded into `known` for
|
|
78
|
+
* whoever is listening.
|
|
59
79
|
*/
|
|
60
80
|
let mine = null;
|
|
61
81
|
let known = new Map();
|
|
62
82
|
const whoListeners = new Set();
|
|
63
83
|
const heard = (who) => {
|
|
64
|
-
const next = foldPresence(new Map(), who, Date.now(),
|
|
84
|
+
const next = foldPresence(new Map(), who, Date.now(), REMOTE_PRESENCE_TTL_MS, mine?.participant);
|
|
65
85
|
let changed = next.size !== known.size;
|
|
66
86
|
if (!changed)
|
|
67
87
|
for (const [participant, presence] of next)
|
|
@@ -73,14 +93,63 @@ export async function openRemote(options) {
|
|
|
73
93
|
for (const listener of whoListeners)
|
|
74
94
|
listener([...known.values()]);
|
|
75
95
|
};
|
|
76
|
-
|
|
77
|
-
|
|
96
|
+
/*
|
|
97
|
+
* THE LOG READS `[confirmed…, pending…]`. `pending` is this browser's own
|
|
98
|
+
* batches, applied here and not yet answered, oldest first. Whatever
|
|
99
|
+
* arrives from the server lands UNDER them by `store.rebase`: the pending
|
|
100
|
+
* tail is rolled back, the server's ops land in its order, and the
|
|
101
|
+
* pending calls are applied again on top, heard as one change. A batch
|
|
102
|
+
* the server has answered or refused is dropped, so its provisional op
|
|
103
|
+
* never sits in the log beside the server's op for the same press.
|
|
104
|
+
*
|
|
105
|
+
* `provisional` is every batch whose provisional ops may still be in the
|
|
106
|
+
* log: a batch is dropped once, and only while it is, because a live
|
|
107
|
+
* client's batch id is the one the server's op lands in too, and
|
|
108
|
+
* dropping it again would cut the server's op.
|
|
109
|
+
*/
|
|
110
|
+
const pending = [];
|
|
111
|
+
const provisional = new Set();
|
|
112
|
+
const settle = (batch) => {
|
|
113
|
+
const at = pending.indexOf(batch);
|
|
114
|
+
if (at >= 0)
|
|
115
|
+
pending.splice(at, 1);
|
|
116
|
+
};
|
|
117
|
+
/** Socket calls not yet answered, by cid: what was sent, and how to tell the sender. */
|
|
118
|
+
const waiting = new Map();
|
|
119
|
+
const land = (ops, drop = []) => {
|
|
120
|
+
if (ops.length === 0 && drop.length === 0)
|
|
78
121
|
return [];
|
|
79
|
-
|
|
80
|
-
|
|
122
|
+
/*
|
|
123
|
+
* A live client names the batch its call lands in, so an op of the
|
|
124
|
+
* server's in one of its pending batches IS that batch's answer —
|
|
125
|
+
* pushed, or caught up on after a reconnect, before its ack arrived.
|
|
126
|
+
*/
|
|
127
|
+
const echoed = live ? pending.filter((batch) => ops.some((op) => op.batch === batch)) : [];
|
|
128
|
+
for (const batch of echoed)
|
|
129
|
+
settle(batch);
|
|
130
|
+
const dropping = [...new Set([...drop, ...echoed])].filter((batch) => provisional.has(batch));
|
|
131
|
+
if (ops.length > 0) {
|
|
132
|
+
seen = Math.max(seen, ...ops.map((op) => op.seq));
|
|
133
|
+
revisions.note(ops);
|
|
134
|
+
}
|
|
135
|
+
const landed = store.rebase({ confirmed: ops, pending: [...pending], drop: dropping }).confirmed;
|
|
136
|
+
for (const batch of dropping)
|
|
137
|
+
provisional.delete(batch);
|
|
138
|
+
for (const batch of echoed) {
|
|
139
|
+
const answered = waiting.get(batch);
|
|
140
|
+
if (!answered)
|
|
141
|
+
continue;
|
|
142
|
+
waiting.delete(batch);
|
|
143
|
+
answered.resolve({ ops: ops.filter((op) => op.batch === batch), batch });
|
|
144
|
+
}
|
|
145
|
+
return landed;
|
|
146
|
+
};
|
|
147
|
+
const since = async (seq) => {
|
|
148
|
+
const response = await call(`${options.url}/graview/since?seq=${seq}`, { headers });
|
|
149
|
+
return (await response.json()).ops ?? [];
|
|
81
150
|
};
|
|
82
151
|
const pull = async () => {
|
|
83
|
-
if (mine) {
|
|
152
|
+
if (mine && !socketReady()) {
|
|
84
153
|
const response = await call(`${options.url}/graview/here`, {
|
|
85
154
|
method: "POST",
|
|
86
155
|
headers,
|
|
@@ -90,35 +159,14 @@ export async function openRemote(options) {
|
|
|
90
159
|
heard(who ?? []);
|
|
91
160
|
return land(ops ?? []);
|
|
92
161
|
}
|
|
93
|
-
|
|
94
|
-
const { ops } = (await response.json());
|
|
95
|
-
return land(ops);
|
|
96
|
-
};
|
|
97
|
-
const presence = {
|
|
98
|
-
here(next) {
|
|
99
|
-
mine = next;
|
|
100
|
-
},
|
|
101
|
-
onWho(listener) {
|
|
102
|
-
whoListeners.add(listener);
|
|
103
|
-
return () => {
|
|
104
|
-
whoListeners.delete(listener);
|
|
105
|
-
};
|
|
106
|
-
},
|
|
107
|
-
leave() {
|
|
108
|
-
if (!mine)
|
|
109
|
-
return;
|
|
110
|
-
const body = JSON.stringify({ participant: mine.participant });
|
|
111
|
-
mine = null;
|
|
112
|
-
// A page on its way out gets one shot; a beacon is what survives it.
|
|
113
|
-
const beacon = globalThis.navigator?.sendBeacon;
|
|
114
|
-
if (beacon)
|
|
115
|
-
beacon.call(globalThis.navigator, `${options.url}/graview/leave`, body);
|
|
116
|
-
else
|
|
117
|
-
void call(`${options.url}/graview/leave`, { method: "POST", headers, body }).catch(() => { });
|
|
118
|
-
},
|
|
162
|
+
return land(await since(seen));
|
|
119
163
|
};
|
|
120
164
|
/** The server's batch for each provisional one this browser minted, so an undo names what the server has. */
|
|
121
165
|
const batches = new Map();
|
|
166
|
+
/** Each provisional batch's post, so an undo of it waits until the server has named it. */
|
|
167
|
+
const answers = new Map();
|
|
168
|
+
/** What each provisional batch asked for, so a conflict's `useMine` can ask again. */
|
|
169
|
+
const asked = new Map();
|
|
122
170
|
/** Every post not yet answered, so `settled` can wait for the verdicts. */
|
|
123
171
|
const inFlight = new Set();
|
|
124
172
|
const track = (promise) => {
|
|
@@ -127,28 +175,192 @@ export async function openRemote(options) {
|
|
|
127
175
|
return promise;
|
|
128
176
|
};
|
|
129
177
|
/*
|
|
130
|
-
* `
|
|
131
|
-
* applied
|
|
132
|
-
*
|
|
133
|
-
*
|
|
178
|
+
* `mine` names the provisional batch this post answers, when the call was
|
|
179
|
+
* applied here first: the server's op lands and the provisional one is
|
|
180
|
+
* dropped, in one rebase. `send` never applies first, so its answer
|
|
181
|
+
* lands under whatever is pending.
|
|
134
182
|
*/
|
|
135
|
-
const post = async (body,
|
|
183
|
+
const post = async (body, mine) => {
|
|
136
184
|
const response = await call(`${options.url}/graview/ops`, {
|
|
137
185
|
method: "POST",
|
|
138
186
|
headers,
|
|
139
|
-
|
|
187
|
+
// A person at an interface, unless the caller said otherwise (FR-06).
|
|
188
|
+
body: JSON.stringify({ via: options.via ?? "web", ...body }),
|
|
140
189
|
});
|
|
141
190
|
const answer = (await response.json());
|
|
142
191
|
if (!response.ok) {
|
|
143
192
|
// The policy's own sentence, carried across the wire unchanged: a
|
|
144
193
|
// refusal a person can read is the whole point of having one.
|
|
145
|
-
|
|
194
|
+
const sentence = answer.error ?? `The server refused (${response.status})`;
|
|
195
|
+
throw answer.conflict ? new StaleWrite(sentence, answer.conflicts ?? []) : new Error(sentence);
|
|
196
|
+
}
|
|
197
|
+
let ops = answer.ops ?? [];
|
|
198
|
+
/*
|
|
199
|
+
* ONE OP NEVER JUMPS ANOTHER. Somebody else's op may have landed on the
|
|
200
|
+
* server between this client's last look and its call: the answer's
|
|
201
|
+
* ops then start past the next seq this client has, and taking them in
|
|
202
|
+
* as they are would number them out of the server's order — and the
|
|
203
|
+
* next poll, asking from past them, would never bring the one between.
|
|
204
|
+
* So the gap is asked for first, and lands with them.
|
|
205
|
+
*/
|
|
206
|
+
const first = ops[0]?.seq;
|
|
207
|
+
if (first !== undefined && first > seen + 1)
|
|
208
|
+
ops = await since(seen);
|
|
209
|
+
if (mine !== undefined) {
|
|
210
|
+
if (answer.batch)
|
|
211
|
+
batches.set(mine, answer.batch);
|
|
212
|
+
settle(mine);
|
|
213
|
+
}
|
|
214
|
+
land(ops, mine !== undefined ? [mine] : []);
|
|
215
|
+
return { ops: answer.ops ?? [], ...(answer.batch ? { batch: answer.batch } : {}) };
|
|
216
|
+
};
|
|
217
|
+
/* ── THE SOCKET (FR-05) ─────────────────────────────────────────────── */
|
|
218
|
+
let socket;
|
|
219
|
+
/** Set once the server has said welcome on the socket now open. */
|
|
220
|
+
let welcomed = false;
|
|
221
|
+
let closed = false;
|
|
222
|
+
let attempts = 0;
|
|
223
|
+
let retry;
|
|
224
|
+
let counter = 0;
|
|
225
|
+
let saidAt = 0;
|
|
226
|
+
let said = null;
|
|
227
|
+
let opened = () => { };
|
|
228
|
+
const openedLive = new Promise((done) => {
|
|
229
|
+
opened = done;
|
|
230
|
+
});
|
|
231
|
+
const socketReady = () => live && welcomed && socket?.readyState === OPEN;
|
|
232
|
+
const say = (message) => {
|
|
233
|
+
if (!socketReady())
|
|
234
|
+
return false;
|
|
235
|
+
try {
|
|
236
|
+
socket.send(JSON.stringify(message));
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
const sayWhere = (force = false) => {
|
|
244
|
+
if (!mine || !socketReady())
|
|
245
|
+
return;
|
|
246
|
+
if (!force && said && samePresence(mine, said) && Date.now() - saidAt < PRESENCE_TTL_MS / 2)
|
|
247
|
+
return;
|
|
248
|
+
if (say({ t: "here", presence: mine })) {
|
|
249
|
+
said = mine;
|
|
250
|
+
saidAt = Date.now();
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
/** A call down the socket; its answer lands when it comes, in the order the server said it. */
|
|
254
|
+
const viaSocket = (body, mine) => new Promise((resolve, reject) => {
|
|
255
|
+
const cid = mine ?? `send-${++counter}`;
|
|
256
|
+
const via = options.via ?? "web";
|
|
257
|
+
const message = body.undo
|
|
258
|
+
? { t: "undo", cid, batches: body.undo, via, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}) }
|
|
259
|
+
: { t: "call", cid, calls: body.calls ?? [], via, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}), ...(body.base?.length ? { base: body.base } : {}) };
|
|
260
|
+
waiting.set(cid, { message, ...(mine !== undefined ? { mine } : {}), resolve, reject });
|
|
261
|
+
// Not open: it goes when the socket is back, after the welcome has caught this client up.
|
|
262
|
+
say(message);
|
|
263
|
+
});
|
|
264
|
+
/** Down the socket when it is up, over HTTP when it is not. */
|
|
265
|
+
const transmit = (body, mine) => (socketReady() ? viaSocket(body, mine) : post(body, mine));
|
|
266
|
+
const hear = (message) => {
|
|
267
|
+
switch (message.t) {
|
|
268
|
+
case "welcome": {
|
|
269
|
+
welcomed = true;
|
|
270
|
+
attempts = 0;
|
|
271
|
+
land(message.ops ?? []);
|
|
272
|
+
// Whatever was sent and never answered goes again: the server answers a batch it already has with its ops.
|
|
273
|
+
for (const waiter of waiting.values())
|
|
274
|
+
say(waiter.message);
|
|
275
|
+
sayWhere(true);
|
|
276
|
+
opened();
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
case "ops":
|
|
280
|
+
land(message.ops ?? []);
|
|
281
|
+
return;
|
|
282
|
+
case "ack": {
|
|
283
|
+
const waiter = waiting.get(message.cid);
|
|
284
|
+
if (!waiter) {
|
|
285
|
+
land(message.ops ?? []);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
waiting.delete(message.cid);
|
|
289
|
+
if (waiter.mine !== undefined) {
|
|
290
|
+
batches.set(waiter.mine, message.batch);
|
|
291
|
+
settle(waiter.mine);
|
|
292
|
+
}
|
|
293
|
+
land(message.ops ?? [], waiter.mine !== undefined ? [waiter.mine] : []);
|
|
294
|
+
waiter.resolve({ ops: message.ops ?? [], batch: message.batch });
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
case "refused":
|
|
298
|
+
case "conflict": {
|
|
299
|
+
const waiter = waiting.get(message.cid);
|
|
300
|
+
if (!waiter)
|
|
301
|
+
return;
|
|
302
|
+
waiting.delete(message.cid);
|
|
303
|
+
waiter.reject(message.t === "conflict" ? new StaleWrite(message.sentence, message.conflicts ?? []) : new Error(message.sentence));
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
case "presence":
|
|
307
|
+
heard(message.who ?? []);
|
|
308
|
+
return;
|
|
309
|
+
default:
|
|
310
|
+
return;
|
|
146
311
|
}
|
|
147
|
-
const ops = answer.ops ?? [];
|
|
148
|
-
land(ops, applied);
|
|
149
|
-
return { ops, ...(answer.batch ? { batch: answer.batch } : {}) };
|
|
150
312
|
};
|
|
151
|
-
const
|
|
313
|
+
const connect = () => {
|
|
314
|
+
if (closed || !live)
|
|
315
|
+
return;
|
|
316
|
+
const url = `${options.url.replace(/^http/, "ws").replace(/\/$/, "")}${LIVE_PATH}`;
|
|
317
|
+
const { "content-type": _json, ...carried } = headers;
|
|
318
|
+
let made;
|
|
319
|
+
try {
|
|
320
|
+
made = (options.socket ?? platformSocket)(url, carried);
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
return reconnect();
|
|
324
|
+
}
|
|
325
|
+
socket = made;
|
|
326
|
+
welcomed = false;
|
|
327
|
+
made.onopen = () => {
|
|
328
|
+
if (socket !== made)
|
|
329
|
+
return;
|
|
330
|
+
// From the last op this client has: the welcome brings exactly the ones after it.
|
|
331
|
+
made.send(JSON.stringify({ t: "hello", seq: seen, protocol: WIRE_PROTOCOL }));
|
|
332
|
+
};
|
|
333
|
+
made.onmessage = (event) => {
|
|
334
|
+
if (socket !== made)
|
|
335
|
+
return;
|
|
336
|
+
let message;
|
|
337
|
+
try {
|
|
338
|
+
message = JSON.parse(String(event.data));
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
hear(message);
|
|
344
|
+
};
|
|
345
|
+
made.onclose = () => {
|
|
346
|
+
if (socket !== made)
|
|
347
|
+
return;
|
|
348
|
+
socket = undefined;
|
|
349
|
+
welcomed = false;
|
|
350
|
+
said = null;
|
|
351
|
+
reconnect();
|
|
352
|
+
};
|
|
353
|
+
made.onerror = () => {
|
|
354
|
+
// The close follows; that is where reconnecting is decided.
|
|
355
|
+
};
|
|
356
|
+
};
|
|
357
|
+
const reconnect = () => {
|
|
358
|
+
if (closed)
|
|
359
|
+
return;
|
|
360
|
+
const wait = Math.min(10_000, 250 * 2 ** attempts) * (0.75 + Math.random() * 0.5);
|
|
361
|
+
attempts++;
|
|
362
|
+
retry = setTimeout(connect, wait);
|
|
363
|
+
};
|
|
152
364
|
/*
|
|
153
365
|
* APPLIED HERE FIRST, DECIDED THERE.
|
|
154
366
|
*
|
|
@@ -166,24 +378,60 @@ export async function openRemote(options) {
|
|
|
166
378
|
const appliedAll = store.applyAll.bind(store);
|
|
167
379
|
const undone = store.undo.bind(store);
|
|
168
380
|
const refusals = new Set();
|
|
381
|
+
const conflictListeners = new Set();
|
|
382
|
+
/** Set while `useMine` sends a change again: it goes without the revisions it was refused for. */
|
|
383
|
+
let overriding = false;
|
|
169
384
|
/*
|
|
170
|
-
* A refusal takes the optimism back
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
385
|
+
* A refusal takes the optimism back: the provisional batch is dropped
|
|
386
|
+
* by a rebase, which rolls it back and applies whatever is still pending
|
|
387
|
+
* again on top. Nothing is undone, so nothing is judged a second time
|
|
388
|
+
* and nothing is added to the log: the press simply never happened here,
|
|
389
|
+
* as it never happened there.
|
|
175
390
|
*/
|
|
176
|
-
const takeBack = (batch, error) => {
|
|
391
|
+
const takeBack = async (batch, error) => {
|
|
177
392
|
const reason = error instanceof Error ? error.message : String(error);
|
|
393
|
+
settle(batch);
|
|
178
394
|
try {
|
|
179
|
-
|
|
180
|
-
if (store.canUndo(batch).ok)
|
|
181
|
-
undone(batch, asMe);
|
|
395
|
+
land([], [batch]);
|
|
182
396
|
}
|
|
183
397
|
catch {
|
|
184
398
|
// A take-back that cannot run leaves the interface wrong, and
|
|
185
399
|
// saying so is still better than saying nothing.
|
|
186
400
|
}
|
|
401
|
+
const made = asked.get(batch);
|
|
402
|
+
asked.delete(batch);
|
|
403
|
+
/*
|
|
404
|
+
* A stale write means this client is behind: theirs is on the server
|
|
405
|
+
* and not yet here. A socket has already pushed it; a poller asks, so
|
|
406
|
+
* what stands on screen when the person chooses is theirs.
|
|
407
|
+
*/
|
|
408
|
+
if (error instanceof StaleWrite && !socketReady())
|
|
409
|
+
await pull().catch(() => []);
|
|
410
|
+
if (error instanceof StaleWrite && conflictListeners.size > 0) {
|
|
411
|
+
let chosen = false;
|
|
412
|
+
const conflict = {
|
|
413
|
+
sentence: reason,
|
|
414
|
+
conflicts: error.conflicts,
|
|
415
|
+
keepTheirs() {
|
|
416
|
+
chosen = true;
|
|
417
|
+
},
|
|
418
|
+
useMine() {
|
|
419
|
+
if (chosen || !made)
|
|
420
|
+
return;
|
|
421
|
+
chosen = true;
|
|
422
|
+
overriding = true;
|
|
423
|
+
try {
|
|
424
|
+
store.applyAll(made.calls, made.intent ? { intent: made.intent } : {});
|
|
425
|
+
}
|
|
426
|
+
finally {
|
|
427
|
+
overriding = false;
|
|
428
|
+
}
|
|
429
|
+
},
|
|
430
|
+
};
|
|
431
|
+
for (const told of conflictListeners)
|
|
432
|
+
told(conflict);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
187
435
|
for (const told of refusals)
|
|
188
436
|
told(reason);
|
|
189
437
|
};
|
|
@@ -196,6 +444,12 @@ export async function openRemote(options) {
|
|
|
196
444
|
* exactly the changes an agent had made.
|
|
197
445
|
*/
|
|
198
446
|
store.applyAll = ((calls, applyOptions) => {
|
|
447
|
+
/*
|
|
448
|
+
* What this browser's earlier presses, still pending, wrote: a field
|
|
449
|
+
* one of them changed is this browser's own to change again, not a
|
|
450
|
+
* revision anybody else could have moved.
|
|
451
|
+
*/
|
|
452
|
+
const earlier = writtenBy(store.log.all().filter((op) => provisional.has(op.batch)));
|
|
199
453
|
/*
|
|
200
454
|
* As WHOEVER IS AT THIS KEYBOARD, by default.
|
|
201
455
|
*
|
|
@@ -209,35 +463,81 @@ export async function openRemote(options) {
|
|
|
209
463
|
...(options.principal ? { author: options.principal } : {}),
|
|
210
464
|
...applyOptions,
|
|
211
465
|
});
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
466
|
+
pending.push(result.batch);
|
|
467
|
+
provisional.add(result.batch);
|
|
468
|
+
asked.set(result.batch, { calls, ...(applyOptions?.intent ? { intent: applyOptions.intent } : {}) });
|
|
469
|
+
// The revision of each field this changes, as this browser saw it — unless the person chose theirs over it.
|
|
470
|
+
const base = overriding ? [] : revisions.baseFor(result.ops, earlier);
|
|
471
|
+
answers.set(result.batch, track(transmit({
|
|
472
|
+
calls,
|
|
473
|
+
...(applyOptions?.intent ? { intent: applyOptions.intent } : {}),
|
|
474
|
+
...(live ? { batch: result.batch } : {}),
|
|
475
|
+
...(base.length > 0 ? { base } : {}),
|
|
476
|
+
}, result.batch).catch((error) => takeBack(result.batch, error))));
|
|
218
477
|
return result;
|
|
219
478
|
});
|
|
220
479
|
// `apply` is `applyAll` of one — and it must go through the patched one.
|
|
221
480
|
store.apply = ((callMade, applyOptions) => store.applyAll([callMade], applyOptions));
|
|
222
481
|
store.undo = ((batchIds, undoOptions) => {
|
|
223
482
|
const ids = typeof batchIds === "string" ? [batchIds] : batchIds;
|
|
224
|
-
|
|
483
|
+
/*
|
|
484
|
+
* A provisional batch the server has answered is not in this log any
|
|
485
|
+
* more: the server's op for it is. So it is undone by the name it
|
|
486
|
+
* became, here as there.
|
|
487
|
+
*/
|
|
488
|
+
const result = undone(ids.map((id) => batches.get(id) ?? id), {
|
|
225
489
|
...(options.principal ? { author: options.principal } : {}),
|
|
226
490
|
...undoOptions,
|
|
227
491
|
});
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
492
|
+
pending.push(result.batch);
|
|
493
|
+
provisional.add(result.batch);
|
|
494
|
+
/*
|
|
495
|
+
* Named as the server knows them: a provisional batch by the one it
|
|
496
|
+
* became, once the server has said what that is.
|
|
497
|
+
*/
|
|
498
|
+
const before = Promise.allSettled(ids.map((id) => answers.get(id)));
|
|
499
|
+
answers.set(result.batch, track(before
|
|
500
|
+
.then(() => transmit({
|
|
501
|
+
undo: ids.map((id) => batches.get(id) ?? id),
|
|
502
|
+
...(undoOptions?.intent ? { intent: undoOptions.intent } : {}),
|
|
503
|
+
...(live ? { batch: result.batch } : {}),
|
|
504
|
+
}, result.batch))
|
|
505
|
+
.catch((error) => takeBack(result.batch, error))));
|
|
236
506
|
return result;
|
|
237
507
|
});
|
|
508
|
+
const send = async (calls, sending = {}) => (await track(transmit({ calls, ...sending }))).ops;
|
|
509
|
+
const presence = {
|
|
510
|
+
here(next) {
|
|
511
|
+
mine = next;
|
|
512
|
+
sayWhere();
|
|
513
|
+
},
|
|
514
|
+
onWho(listener) {
|
|
515
|
+
whoListeners.add(listener);
|
|
516
|
+
return () => {
|
|
517
|
+
whoListeners.delete(listener);
|
|
518
|
+
};
|
|
519
|
+
},
|
|
520
|
+
leave() {
|
|
521
|
+
if (!mine)
|
|
522
|
+
return;
|
|
523
|
+
const body = JSON.stringify({ participant: mine.participant });
|
|
524
|
+
mine = null;
|
|
525
|
+
if (say({ t: "bye" }))
|
|
526
|
+
return;
|
|
527
|
+
// A page on its way out gets one shot; a beacon is what survives it.
|
|
528
|
+
const beacon = globalThis.navigator?.sendBeacon;
|
|
529
|
+
if (beacon)
|
|
530
|
+
beacon.call(globalThis.navigator, `${options.url}/graview/leave`, body);
|
|
531
|
+
else
|
|
532
|
+
void call(`${options.url}/graview/leave`, { method: "POST", headers, body }).catch(() => { });
|
|
533
|
+
},
|
|
534
|
+
};
|
|
238
535
|
const every = options.pollMs ?? 800;
|
|
239
536
|
const timer = every > 0 && typeof setInterval === "function"
|
|
240
537
|
? setInterval(() => {
|
|
538
|
+
// A live client hears everything on its socket; it polls only while that is down.
|
|
539
|
+
if (socketReady())
|
|
540
|
+
return;
|
|
241
541
|
void pull().catch(() => {
|
|
242
542
|
// A poll that cannot reach the server is a poll that will try
|
|
243
543
|
// again; throwing here would take the interface down with the
|
|
@@ -245,6 +545,12 @@ export async function openRemote(options) {
|
|
|
245
545
|
});
|
|
246
546
|
}, every)
|
|
247
547
|
: null;
|
|
548
|
+
if (live) {
|
|
549
|
+
connect();
|
|
550
|
+
let waited;
|
|
551
|
+
await Promise.race([openedLive, new Promise((done) => (waited = setTimeout(done, options.openTimeoutMs ?? 3000)))]);
|
|
552
|
+
clearTimeout(waited);
|
|
553
|
+
}
|
|
248
554
|
return {
|
|
249
555
|
store,
|
|
250
556
|
version: state.version,
|
|
@@ -255,6 +561,13 @@ export async function openRemote(options) {
|
|
|
255
561
|
refusals.add(listener);
|
|
256
562
|
return () => refusals.delete(listener);
|
|
257
563
|
},
|
|
564
|
+
onConflict(listener) {
|
|
565
|
+
conflictListeners.add(listener);
|
|
566
|
+
return () => conflictListeners.delete(listener);
|
|
567
|
+
},
|
|
568
|
+
revision: (node, field) => revisions.of(node, field),
|
|
569
|
+
seq: () => seen,
|
|
570
|
+
transport: () => (socketReady() ? "socket" : "poll"),
|
|
258
571
|
async settled() {
|
|
259
572
|
// Whatever is in flight now — and whatever a settling handler put in flight after it.
|
|
260
573
|
while (inFlight.size > 0)
|
|
@@ -265,7 +578,64 @@ export async function openRemote(options) {
|
|
|
265
578
|
if (timer)
|
|
266
579
|
clearInterval(timer);
|
|
267
580
|
presence.leave();
|
|
581
|
+
closed = true;
|
|
582
|
+
if (retry)
|
|
583
|
+
clearTimeout(retry);
|
|
584
|
+
const was = socket;
|
|
585
|
+
socket = undefined;
|
|
586
|
+
welcomed = false;
|
|
587
|
+
try {
|
|
588
|
+
was?.close(1000, "Closed.");
|
|
589
|
+
}
|
|
590
|
+
catch {
|
|
591
|
+
// Already gone.
|
|
592
|
+
}
|
|
268
593
|
},
|
|
269
594
|
};
|
|
595
|
+
/** The platform's WebSocket, with the headers where the runtime can send them. */
|
|
596
|
+
function platformSocket(url, carried) {
|
|
597
|
+
const Socket = globalThis.WebSocket;
|
|
598
|
+
if (!Socket)
|
|
599
|
+
throw new Error("This runtime has no WebSocket; the client polls instead.");
|
|
600
|
+
const page = typeof globalThis.document !== "undefined";
|
|
601
|
+
if (!page) {
|
|
602
|
+
try {
|
|
603
|
+
return new Socket(url, { headers: carried });
|
|
604
|
+
}
|
|
605
|
+
catch {
|
|
606
|
+
// A runtime whose WebSocket takes protocols only: the seat rides in the query, as a page's does.
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
const withSeat = new URL(url);
|
|
610
|
+
for (const [name, value] of Object.entries(seatHeaders(options.principal)))
|
|
611
|
+
withSeat.searchParams.set(name, value);
|
|
612
|
+
return new Socket(withSeat.toString());
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* A principal as the headers a TRUSTED server reads (`trustSeatHeaders`):
|
|
617
|
+
* who, as what, by what name, and for whom. A server that does not trust
|
|
618
|
+
* headers ignores every one of them and asks its own `seatOf`.
|
|
619
|
+
*/
|
|
620
|
+
export function seatHeaders(principal) {
|
|
621
|
+
const headers = {};
|
|
622
|
+
if (!principal)
|
|
623
|
+
return headers;
|
|
624
|
+
if (principal.id)
|
|
625
|
+
headers[SEAT_HEADERS.seat] = principal.id;
|
|
626
|
+
if (principal.roles?.length)
|
|
627
|
+
headers[SEAT_HEADERS.roles] = principal.roles.join(",");
|
|
628
|
+
if (principal.kind !== "human")
|
|
629
|
+
headers[SEAT_HEADERS.kind] = principal.kind;
|
|
630
|
+
if (principal.name)
|
|
631
|
+
headers[SEAT_HEADERS.name] = encodeURIComponent(principal.name);
|
|
632
|
+
const person = principal.onBehalfOf;
|
|
633
|
+
if (person?.id)
|
|
634
|
+
headers[SEAT_HEADERS.for] = person.id;
|
|
635
|
+
if (person?.roles?.length)
|
|
636
|
+
headers[SEAT_HEADERS.forRoles] = person.roles.join(",");
|
|
637
|
+
if (person?.name)
|
|
638
|
+
headers[SEAT_HEADERS.forName] = encodeURIComponent(person.name);
|
|
639
|
+
return headers;
|
|
270
640
|
}
|
|
271
641
|
//# sourceMappingURL=remote.js.map
|