@graview/ship 0.1.3 → 0.1.4
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 +210 -19
- package/dist/handler.d.ts +66 -9
- package/dist/handler.d.ts.map +1 -1
- package/dist/handler.js +129 -82
- package/dist/handler.js.map +1 -1
- package/dist/health.d.ts +12 -1
- package/dist/health.d.ts.map +1 -1
- package/dist/health.js +15 -4
- package/dist/health.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/live-protocol.d.ts +266 -23
- package/dist/live-protocol.d.ts.map +1 -1
- package/dist/live-protocol.js +671 -94
- package/dist/live-protocol.js.map +1 -1
- package/dist/live.d.ts +39 -8
- package/dist/live.d.ts.map +1 -1
- package/dist/live.js.map +1 -1
- package/dist/remote.d.ts +41 -9
- package/dist/remote.d.ts.map +1 -1
- package/dist/remote.js +199 -57
- package/dist/remote.js.map +1 -1
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +1 -1
- package/dist/runtime.js.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +1 -0
- package/dist/serve.js.map +1 -1
- package/package.json +3 -3
package/dist/live-protocol.js
CHANGED
|
@@ -1,18 +1,52 @@
|
|
|
1
|
-
import { FieldRevisions, hidesFrom, hueFor, isUnset, participantKey, redact, seenBy, seesId, refusalOf, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, } from "@graview/core";
|
|
1
|
+
import { argumentWords, FieldRevisions, InvalidArguments, UnknownMutationError, hidesFrom, hueFor, isUnset, namesUnseen, participantKey, redact, seatLens, sha256Hex, seenBy, seesId, refusalOf, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, } from "@graview/core";
|
|
2
2
|
import { bytesOf, conflictSentence, LIVE_WIRE } from "./live.js";
|
|
3
|
+
/** The longest `cid` a socket's call or undo may name: it is kept in `held` while the call is busy. */
|
|
4
|
+
const MAX_CID = 64;
|
|
5
|
+
/** A change the host's `admit` answered: thrown through the store, which puts the change back. */
|
|
6
|
+
class NotAdmitted extends Error {
|
|
7
|
+
answer;
|
|
8
|
+
constructor(answer) {
|
|
9
|
+
super("Not admitted by the host.");
|
|
10
|
+
this.answer = answer;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** A client's claim of what its change came through: a short string, or none. */
|
|
14
|
+
const claimOfVia = (via) => (typeof via === "string" && via.length > 0 ? via.slice(0, 64) : undefined);
|
|
15
|
+
/**
|
|
16
|
+
* A STORE'S REFUSAL, SAID TO A PERSON (FR-46). The store's own sentences
|
|
17
|
+
* were written for a developer: `Invalid arguments for mutation "add"
|
|
18
|
+
* label: Too small…`, and an unknown act listed every act the app has.
|
|
19
|
+
* Arguments are said field by field in the words the form asked in, and
|
|
20
|
+
* an unknown act by the name the call gave; anything else is the
|
|
21
|
+
* refusal's own sentence, the policy's among them.
|
|
22
|
+
*/
|
|
23
|
+
export function wireRefusalOf(store, error) {
|
|
24
|
+
const refusal = refusalOf(error);
|
|
25
|
+
if (error instanceof UnknownMutationError)
|
|
26
|
+
return { ...refusal, sentence: `This app has no act called “${error.mutation}”.` };
|
|
27
|
+
if (error instanceof InvalidArguments) {
|
|
28
|
+
const mutation = store.allMutations().find((one) => one.name === error.mutation);
|
|
29
|
+
const said = error.issues.map((issue) => {
|
|
30
|
+
const message = issue.message.replace(/^./, (first) => first.toLowerCase());
|
|
31
|
+
return issue.path.length > 0 ? `${argumentWords(store.schema, mutation, String(issue.path[0])).label} — ${message}` : message;
|
|
32
|
+
});
|
|
33
|
+
return { ...refusal, sentence: `“${mutation?.title ?? error.mutation}” was not made: ${said.join("; ")}.` };
|
|
34
|
+
}
|
|
35
|
+
return refusal;
|
|
36
|
+
}
|
|
3
37
|
/** For whom an author acts, as a presence says it: the person's id and name, or nothing. */
|
|
4
38
|
const forWhom = (author) => author.onBehalfOf?.id ? { onBehalfOf: author.onBehalfOf.id, ...(author.onBehalfOf.name ? { onBehalfOfName: author.onBehalfOf.name } : {}) } : {};
|
|
5
39
|
/**
|
|
6
40
|
* A PRESENCE AS THE SERVER BUILDS IT. Keyed by the seat — a client cannot
|
|
7
41
|
* claim to be somebody else — with only the session taken from what it
|
|
8
42
|
* said, and stamped with the server's clock. What it is, and for whom it
|
|
9
|
-
* acts, are the seat's (FR-47): a claimed `kind`, `onBehalfOf
|
|
10
|
-
* is dropped, and the seat's name stands over a claimed one. `participant`
|
|
43
|
+
* acts, are the seat's (FR-47): a claimed `kind`, `onBehalfOf`, `until` or
|
|
44
|
+
* `held` is dropped, and the seat's name stands over a claimed one. `participant`
|
|
11
45
|
* is the key the server already gave this socket (its welcome said it):
|
|
12
46
|
* given, the claimed key is not read at all.
|
|
13
47
|
*/
|
|
14
48
|
export function presenceFrom(told, seat, now = new Date(), participant) {
|
|
15
|
-
const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, at: _at, ...said } = told;
|
|
49
|
+
const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, held: _held, at: _at, ...said } = told;
|
|
16
50
|
// The session is what follows the seat's own `kind:id:` — an id may hold a colon (`shopper:bethan`).
|
|
17
51
|
const own = `${seat.kind}:${seat.id ?? ""}:`;
|
|
18
52
|
const session = claimed.startsWith(own) ? claimed.slice(own.length) : (claimed.split(":").at(-1) ?? "");
|
|
@@ -51,6 +85,27 @@ export function announcePresence(who, presence, ttlMs = VISITOR_PRESENCE_TTL_MS,
|
|
|
51
85
|
const stamped = { ...presence, at: new Date(now).toISOString(), until: new Date(now + ttlMs).toISOString() };
|
|
52
86
|
return [...who.filter((one) => one.participant !== presence.participant && (one.until === undefined || now < Date.parse(one.until))), stamped];
|
|
53
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* WHO IS HERE, AS THE SOCKETS SAY IT: a presence whose participant one of
|
|
90
|
+
* the host's sockets holds is held by that socket (`held: "socket"`, and no
|
|
91
|
+
* `until` — it stands while the socket does); everybody else, a visitor
|
|
92
|
+
* with its `until` among them, as the host built them. A new list: the
|
|
93
|
+
* host's own is not changed.
|
|
94
|
+
*/
|
|
95
|
+
function heldBySockets(who, peers) {
|
|
96
|
+
const held = new Set();
|
|
97
|
+
for (const peer of peers)
|
|
98
|
+
if (peer.participant)
|
|
99
|
+
held.add(peer.participant);
|
|
100
|
+
if (held.size === 0)
|
|
101
|
+
return [...who];
|
|
102
|
+
return who.map((presence) => {
|
|
103
|
+
if (!held.has(presence.participant))
|
|
104
|
+
return presence;
|
|
105
|
+
const { until: _until, ...standing } = presence;
|
|
106
|
+
return { ...standing, held: "socket" };
|
|
107
|
+
});
|
|
108
|
+
}
|
|
54
109
|
/** A key for a socket that has not said one, minted by the server: the welcome tells the client what it is. */
|
|
55
110
|
const mintSession = () => globalThis.crypto.randomUUID().slice(0, 8);
|
|
56
111
|
/**
|
|
@@ -80,19 +135,138 @@ export function presenceSeenBy(who, sees) {
|
|
|
80
135
|
};
|
|
81
136
|
});
|
|
82
137
|
}
|
|
83
|
-
|
|
138
|
+
/**
|
|
139
|
+
* THE SHAPE OF A BATCH A CLIENT NAMES: what a `Store` mints by default,
|
|
140
|
+
* `batch:<tag>:<n>` for a change and `undo:<tag>:<n>` for a take-back,
|
|
141
|
+
* the tag 1–24 lowercase letters and digits and `n` up to 12 digits. A
|
|
142
|
+
* client names the batch its call lands in, so a call sent twice is
|
|
143
|
+
* answered once (FR-49) — and anything else a client names is refused
|
|
144
|
+
* `invalid`, so it cannot claim a batch the host mints for itself
|
|
145
|
+
* (`setup`, `migration:v2`) before the host does.
|
|
146
|
+
*/
|
|
147
|
+
const CLIENT_BATCH = /^(?:batch|undo):[0-9a-z]{1,24}:[0-9]{1,12}$/;
|
|
148
|
+
/** Whether a client may name this batch: `batch:<tag>:<n>` or `undo:<tag>:<n>`, as a `Store` mints them. */
|
|
149
|
+
export function isClientBatch(batch) {
|
|
150
|
+
return typeof batch === "string" && CLIENT_BATCH.test(batch);
|
|
151
|
+
}
|
|
152
|
+
/** A tag for one minter, from the platform's random source. */
|
|
153
|
+
const mintTag = () => globalThis.crypto.randomUUID().replace(/-/g, "").slice(0, 12);
|
|
154
|
+
/**
|
|
155
|
+
* BATCH IDS NO CLIENT CAN NAME FIRST: `served:<kind>:<tag>:<n>`, outside
|
|
156
|
+
* the shape `isClientBatch` accepts. Hand it to the host's own store —
|
|
157
|
+
* `new Store({ batchIds: serverBatchIds() })`, or `openStore`'s
|
|
158
|
+
* `storeOptions` — so what the host lands itself (an agent's RPC, a
|
|
159
|
+
* migration, a seed) is in a batch no client could have claimed.
|
|
160
|
+
* `createStoreHandler` mints its own this way, and `liveProtocol` mints
|
|
161
|
+
* one for a call that names none.
|
|
162
|
+
*/
|
|
163
|
+
export function serverBatchIds() {
|
|
164
|
+
const tag = mintTag();
|
|
165
|
+
let count = 0;
|
|
166
|
+
return (kind) => `served:${kind}:${tag}:${++count}`;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* THE SAME SEAT. An op is the asking seat's own when its author is the
|
|
170
|
+
* same kind and id — and, for an agent, acts for the same person: Claude
|
|
171
|
+
* for Ada is not Claude for Bo.
|
|
172
|
+
*/
|
|
173
|
+
export function authoredBy(author, seat) {
|
|
174
|
+
if (author.kind !== seat.kind || (author.id ?? "") !== (seat.id ?? ""))
|
|
175
|
+
return false;
|
|
176
|
+
return seat.kind !== "agent" || (author.onBehalfOf?.id ?? "") === (seat.onBehalfOf?.id ?? "");
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* THE KEY A STORE'S WITHHELD BATCHES ARE MINTED UNDER, when the host gives
|
|
180
|
+
* none: drawn once per store held, so every route and socket over one
|
|
181
|
+
* store says the same opaque batch for one batch.
|
|
182
|
+
*/
|
|
183
|
+
const WITHHELD_KEYS = new WeakMap();
|
|
184
|
+
/**
|
|
185
|
+
* EACH STORE'S OPAQUE BATCHES, BY KEY: a keyed hash per batch, made once
|
|
186
|
+
* for every route and socket over the store rather than once per protocol
|
|
187
|
+
* made over it — a protocol is made again on every wake.
|
|
188
|
+
*/
|
|
189
|
+
const OPAQUE_BATCHES = new WeakMap();
|
|
190
|
+
export function wireOf(store, withheldKey) {
|
|
84
191
|
const sighted = (principal) => hidesFrom(store, principal);
|
|
85
|
-
|
|
192
|
+
/*
|
|
193
|
+
* A WITHHELD OP SAYS NOBODY'S SESSION. Its batch is the one its author's
|
|
194
|
+
* client minted — `batch:<that browser's tag>:<n>` — which would tell a
|
|
195
|
+
* seat that may not see the change which session made it, and link it to
|
|
196
|
+
* the changes it may see. So it is served under `withheld:<16 hex>`, a
|
|
197
|
+
* keyed SHA-256 of the batch: the same for every op of one batch, and not
|
|
198
|
+
* one a seat can work back from, the key never leaving the server. The
|
|
199
|
+
* seat that made it is served its own.
|
|
200
|
+
*/
|
|
201
|
+
let key = withheldKey;
|
|
202
|
+
if (key === undefined) {
|
|
203
|
+
key = WITHHELD_KEYS.get(store) ?? mintTag() + mintTag();
|
|
204
|
+
WITHHELD_KEYS.set(store, key);
|
|
205
|
+
}
|
|
206
|
+
let byKey = OPAQUE_BATCHES.get(store);
|
|
207
|
+
if (!byKey)
|
|
208
|
+
OPAQUE_BATCHES.set(store, (byKey = new Map()));
|
|
209
|
+
let opaque = byKey.get(key);
|
|
210
|
+
if (!opaque)
|
|
211
|
+
byKey.set(key, (opaque = new Map()));
|
|
212
|
+
const opaqueBatch = (batch) => {
|
|
213
|
+
let said = opaque.get(batch);
|
|
214
|
+
if (said === undefined) {
|
|
215
|
+
said = `withheld:${sha256Hex(`${key}\u0000${batch}`).slice(0, 16)}`;
|
|
216
|
+
opaque.set(batch, said);
|
|
217
|
+
}
|
|
218
|
+
return said;
|
|
219
|
+
};
|
|
220
|
+
const unattributed = (principal, served, authorOf) => served.map((op, at) => {
|
|
221
|
+
if (!op.withheld)
|
|
222
|
+
return op;
|
|
223
|
+
const author = authorOf(op, at);
|
|
224
|
+
return author && authoredBy(author, principal) ? op : { ...op, batch: opaqueBatch(op.batch) };
|
|
225
|
+
});
|
|
226
|
+
// Withheld in place (FR-16), no id the seat may not see in any of them (FR-55), and no session it may not see.
|
|
227
|
+
const shown = (principal, ops) => sighted(principal) ? unattributed(principal, redact(ops, seatLens(store, principal)), (_op, at) => ops[at]?.author) : [...ops];
|
|
86
228
|
/*
|
|
87
229
|
* EVERY FIELD'S REVISION (FR-05): the seq of the op that last wrote it,
|
|
88
230
|
* read off the log once and caught up from wherever the log has grown
|
|
89
231
|
* to since — no subscription, so nothing here goes stale while a host
|
|
90
232
|
* sleeps, and a host that made this again reads the same revisions.
|
|
91
233
|
*/
|
|
92
|
-
|
|
93
|
-
|
|
234
|
+
/*
|
|
235
|
+
* WHO EACH CLIENT TAG IS: the author of the first op landed under it,
|
|
236
|
+
* read off the log once and caught up as it grows — derived, so a host
|
|
237
|
+
* that wakes reads the same owners the sleeper had.
|
|
238
|
+
*/
|
|
239
|
+
/*
|
|
240
|
+
* Both read on first asking, not when the protocol is made: a host makes
|
|
241
|
+
* it again on every wake, and most wakes are a message that names no
|
|
242
|
+
* batch and carries no base.
|
|
243
|
+
*/
|
|
244
|
+
const owners = new Map();
|
|
245
|
+
const own = (ops) => {
|
|
246
|
+
for (const op of ops) {
|
|
247
|
+
if (!isClientBatch(op.batch))
|
|
248
|
+
continue;
|
|
249
|
+
const tag = op.batch.split(":")[1];
|
|
250
|
+
if (!owners.has(tag))
|
|
251
|
+
owners.set(tag, op.author);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
let owned = store.log.horizon;
|
|
255
|
+
const tagOwner = (tag) => {
|
|
256
|
+
if (store.log.length > owned) {
|
|
257
|
+
own(store.log.opsFrom(owned));
|
|
258
|
+
owned = store.log.length;
|
|
259
|
+
}
|
|
260
|
+
return owners.get(tag);
|
|
261
|
+
};
|
|
262
|
+
let revisions;
|
|
263
|
+
let noted = 0;
|
|
94
264
|
const current = () => {
|
|
95
|
-
if (
|
|
265
|
+
if (!revisions) {
|
|
266
|
+
revisions = FieldRevisions.of(store.log.all());
|
|
267
|
+
noted = store.log.length;
|
|
268
|
+
}
|
|
269
|
+
else if (store.log.length > noted) {
|
|
96
270
|
revisions.note(store.log.opsFrom(noted));
|
|
97
271
|
noted = store.log.length;
|
|
98
272
|
}
|
|
@@ -105,21 +279,60 @@ export function wireOf(store) {
|
|
|
105
279
|
shown,
|
|
106
280
|
since: (principal, seq) => shown(principal, store.log.opsFrom(Math.max(0, Math.floor(seq) + 1))),
|
|
107
281
|
seenFor: (principal) => seenBy(store, principal),
|
|
282
|
+
seenLog(principal) {
|
|
283
|
+
const log = seenBy(store, principal).log.all();
|
|
284
|
+
if (!sighted(principal))
|
|
285
|
+
return [...log];
|
|
286
|
+
// The seat's log holds every op in its place: who made one is the store's op at the same place.
|
|
287
|
+
const all = store.log.all();
|
|
288
|
+
return unattributed(principal, log, (op, at) => (all[at]?.id === op.id ? all[at].author : all.find((one) => one.id === op.id)?.author));
|
|
289
|
+
},
|
|
108
290
|
whoFor: (principal, who) => {
|
|
109
291
|
// A visitor whose announced time has passed is never told of, though a host may still hold it.
|
|
110
292
|
const now = Date.now();
|
|
111
293
|
const standing = who.filter((presence) => presence.until === undefined || now < Date.parse(presence.until));
|
|
112
294
|
return sighted(principal) ? presenceSeenBy(standing, seesId(store, principal)) : standing;
|
|
113
295
|
},
|
|
114
|
-
|
|
296
|
+
claim(batch, seat) {
|
|
297
|
+
if (batch === undefined || batch === null || batch === "")
|
|
298
|
+
return {};
|
|
299
|
+
if (!isClientBatch(batch)) {
|
|
300
|
+
const said = typeof batch === "string" ? `“${batch.length > 40 ? `${batch.slice(0, 37)}…` : batch}”` : "a batch that is not a string";
|
|
301
|
+
return {
|
|
302
|
+
refusal: {
|
|
303
|
+
reason: "invalid",
|
|
304
|
+
sentence: `A client names its batch batch:<tag>:<n> or undo:<tag>:<n>, as a Store mints it; ${said} is not one. Send the change without a batch, or under one this client minted.`,
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
/*
|
|
309
|
+
* A TAG IS THE FIRST SEAT'S. A client's tag is in every op it lands,
|
|
310
|
+
* so a batch it has not sent yet — `batch:<tag>:<n+1>` — could be
|
|
311
|
+
* named first by anybody who saw one. The store's own minting tag is
|
|
312
|
+
* nobody's to name: what the host lands later would join it.
|
|
313
|
+
*/
|
|
314
|
+
const tag = batch.split(":")[1];
|
|
315
|
+
if (tag === store.batchTag) {
|
|
316
|
+
return { refusal: { reason: "invalid", sentence: "That batch is under the server's own tag: send the change under a batch this client minted." } };
|
|
317
|
+
}
|
|
318
|
+
const owner = tagOwner(tag);
|
|
319
|
+
if (owner && !authoredBy(owner, seat)) {
|
|
320
|
+
return { refusal: { reason: "invalid", sentence: "That batch is under somebody else's tag: send the change under a batch this client minted." } };
|
|
321
|
+
}
|
|
322
|
+
const ops = store.log.all().filter((op) => op.batch === batch);
|
|
323
|
+
if (ops.some((op) => !authoredBy(op.author, seat))) {
|
|
324
|
+
return { refusal: { reason: "invalid", sentence: "That batch is somebody else's: send the change under a batch this client minted." } };
|
|
325
|
+
}
|
|
326
|
+
return ops.length > 0 ? { answered: ops } : {};
|
|
327
|
+
},
|
|
115
328
|
horizonOf: () => (store.log.horizon > 0 ? { horizon: store.log.horizon } : {}),
|
|
116
329
|
enabledModules: () => [...store.modules.enabled].sort(),
|
|
117
330
|
conflictsOf(author, calls, base) {
|
|
118
331
|
if (!Array.isArray(base) || base.length === 0)
|
|
119
332
|
return [];
|
|
120
|
-
const
|
|
121
|
-
// A record the seat
|
|
122
|
-
const claimed = base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number" &&
|
|
333
|
+
const lens = sighted(author) ? seatLens(store, author) : undefined;
|
|
334
|
+
// A record the seat is not served is not there to have moved: the call itself is refused for naming it.
|
|
335
|
+
const claimed = base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number" && (!lens || lens.shows(entry.node)));
|
|
123
336
|
const revs = current();
|
|
124
337
|
const stale = revs.stale(claimed);
|
|
125
338
|
if (stale.length === 0)
|
|
@@ -132,6 +345,9 @@ export function wireOf(store) {
|
|
|
132
345
|
*/
|
|
133
346
|
if (store.policy && calls.some((call) => !store.permits(call, author).ok))
|
|
134
347
|
return [];
|
|
348
|
+
// Nor does a call naming a record that is not there for this seat: it is refused as missing, a hidden record and an absent one alike (FR-55).
|
|
349
|
+
if (calls.some((call) => store.missingFor(call, author)))
|
|
350
|
+
return [];
|
|
135
351
|
const yours = new Map();
|
|
136
352
|
try {
|
|
137
353
|
for (const primitive of store.previewAll(calls).primitives) {
|
|
@@ -146,12 +362,15 @@ export function wireOf(store) {
|
|
|
146
362
|
return stale.map((entry) => {
|
|
147
363
|
const rev = revs.of(entry.node, entry.field);
|
|
148
364
|
const wrote = rev >= store.log.horizon ? store.log.opsFrom(rev)[0] : undefined;
|
|
149
|
-
const seen = wrote &&
|
|
365
|
+
const seen = wrote && lens ? redact([wrote], lens)[0] : wrote;
|
|
366
|
+
// Theirs as the seat's view serves the record: a field naming what it may not see is cleared there too (FR-55).
|
|
367
|
+
const theirs = (lens ? seenBy(store, author) : store).graph.getNode(entry.node)?.[entry.field];
|
|
368
|
+
const mine = yours.get(`${entry.node}\u0000${entry.field}`);
|
|
150
369
|
return {
|
|
151
370
|
node: entry.node,
|
|
152
371
|
field: entry.field,
|
|
153
|
-
theirs
|
|
154
|
-
yours:
|
|
372
|
+
theirs,
|
|
373
|
+
yours: lens && namesUnseen(mine, lens.sees) ? undefined : mine,
|
|
155
374
|
by: seen?.author.name ?? seen?.author.id ?? "Someone",
|
|
156
375
|
rev,
|
|
157
376
|
saw: entry.rev,
|
|
@@ -160,77 +379,294 @@ export function wireOf(store) {
|
|
|
160
379
|
},
|
|
161
380
|
};
|
|
162
381
|
}
|
|
163
|
-
const say = (peer, message) =>
|
|
382
|
+
const say = (peer, message) => sayText(peer, JSON.stringify(message));
|
|
383
|
+
const sayText = (peer, text) => {
|
|
164
384
|
try {
|
|
165
|
-
peer.send(
|
|
385
|
+
peer.send(text);
|
|
166
386
|
}
|
|
167
387
|
catch {
|
|
168
388
|
// A socket that cannot be written to is closing; its close is what forgets it.
|
|
169
389
|
}
|
|
170
390
|
};
|
|
391
|
+
const aSight = () => ({ seats: new Map(), texts: new Map() });
|
|
392
|
+
/**
|
|
393
|
+
* A SEAT, NOT ITS TAB: the principal without its session — and without the
|
|
394
|
+
* session of the person an agent acts for. What a seat is served never
|
|
395
|
+
* depends on which tab asks, so its key never does either: the key a
|
|
396
|
+
* handler asks a host for (`seatKey`), and the one a sight is kept under.
|
|
397
|
+
*/
|
|
398
|
+
export function seatOfTab(seat) {
|
|
399
|
+
const { session: _session, onBehalfOf, ...rest } = seat;
|
|
400
|
+
return { ...rest, ...(onBehalfOf ? { onBehalfOf: seatOfTab(onBehalfOf) } : {}) };
|
|
401
|
+
}
|
|
402
|
+
/** What a socket's seat is, as a key a sight is kept under: a host's key, or the seat written out — one per seat, however many tabs hold it. */
|
|
403
|
+
const seatKeyOf = (peer) => (typeof peer.seat === "string" ? `key:${peer.seat}` : `seat:${JSON.stringify(seatOfTab(peer.seat))}`);
|
|
404
|
+
/** What a socket whose seat the host lost is told, and the code it is closed with. */
|
|
405
|
+
const SEAT_LOST = "The host no longer knows who this socket is: open it again, and it reads who you are from the new one.";
|
|
406
|
+
const SEAT_LOST_CODE = 4000;
|
|
407
|
+
/** The host lost this socket's seat: told to open again, closed when it can be, and served nothing more. */
|
|
408
|
+
const lost = (peer) => {
|
|
409
|
+
delete peer.cursor;
|
|
410
|
+
say(peer, { t: "error", reopen: true, sentence: SEAT_LOST });
|
|
411
|
+
try {
|
|
412
|
+
peer.close?.(SEAT_LOST_CODE, "Seat no longer known: open it again.");
|
|
413
|
+
}
|
|
414
|
+
catch {
|
|
415
|
+
// Already closing.
|
|
416
|
+
}
|
|
417
|
+
};
|
|
171
418
|
/**
|
|
172
419
|
* THE PROTOCOL OVER A STORE. Cheap to make, and safe to make again on
|
|
173
420
|
* every wake: what it keeps is derived from the store.
|
|
174
421
|
*/
|
|
175
422
|
export function liveProtocol(options) {
|
|
176
423
|
const { store } = options;
|
|
177
|
-
const wire = wireOf(store);
|
|
178
|
-
/**
|
|
179
|
-
const
|
|
180
|
-
|
|
424
|
+
const wire = wireOf(store, options.withheldKey);
|
|
425
|
+
/** A call that names no batch lands in one minted here, outside the shape a client may name. */
|
|
426
|
+
const mintServed = serverBatchIds();
|
|
427
|
+
/**
|
|
428
|
+
* OPS THAT LANDED AND ARE NOT DURABLE: a flush rejected them. Held back
|
|
429
|
+
* from every socket — nothing is sent past the first of them, so none is
|
|
430
|
+
* skipped — until a flush holds them. Derived: a host that wakes makes
|
|
431
|
+
* its store again from what is durable, where none of them is.
|
|
432
|
+
*/
|
|
433
|
+
let unsaved = [];
|
|
434
|
+
/**
|
|
435
|
+
* OPS THAT LANDED AND ARE BEING FLUSHED: held back from every socket like
|
|
436
|
+
* the unsaved ones, so a change anybody else hears is a change that is
|
|
437
|
+
* written. Only with a `flush`: a host without one pushes at once.
|
|
438
|
+
*/
|
|
439
|
+
let flying = [];
|
|
440
|
+
/** While the store takes a change (its subscribers hear it then): the seq its ops begin at, held back like the rest. */
|
|
441
|
+
let taking;
|
|
442
|
+
let flushing = Promise.resolve();
|
|
443
|
+
/** The first seq held back from every socket — not durable, or not yet — before `before`, when one is. */
|
|
444
|
+
const heldFrom = (before = Number.POSITIVE_INFINITY) => {
|
|
445
|
+
let first = taking !== undefined && taking < before ? taking : undefined;
|
|
446
|
+
for (const op of [...unsaved, ...flying])
|
|
447
|
+
if (op.seq < before && (first === undefined || op.seq < first))
|
|
448
|
+
first = op.seq;
|
|
449
|
+
return first;
|
|
450
|
+
};
|
|
451
|
+
/**
|
|
452
|
+
* THROUGH THE HOST'S FLUSH, ONE AT A TIME: `ops` and every op a failed
|
|
453
|
+
* flush left before them. Says whether they are durable now, and which
|
|
454
|
+
* ops became durable — for the host to publish.
|
|
455
|
+
*/
|
|
456
|
+
const durable = (ops) => {
|
|
457
|
+
const turn = flushing.then(async () => {
|
|
458
|
+
const ids = new Set(unsaved.map((op) => op.id));
|
|
459
|
+
const handing = [...unsaved, ...ops.filter((op) => !ids.has(op.id))].sort((a, b) => a.seq - b.seq);
|
|
460
|
+
const handed = new Set(handing.map((op) => op.id));
|
|
461
|
+
try {
|
|
462
|
+
await options.flush?.(handing);
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
unsaved = handing;
|
|
466
|
+
flying = flying.filter((op) => !handed.has(op.id));
|
|
467
|
+
return { failed: true };
|
|
468
|
+
}
|
|
469
|
+
unsaved = unsaved.filter((op) => !handed.has(op.id));
|
|
470
|
+
flying = flying.filter((op) => !handed.has(op.id));
|
|
471
|
+
return { saved: handing };
|
|
472
|
+
});
|
|
473
|
+
flushing = turn.catch(() => { });
|
|
474
|
+
return turn;
|
|
475
|
+
};
|
|
476
|
+
/** Whether any of these ops is not durable yet. */
|
|
477
|
+
const unsavedIn = (ops) => unsaved.length > 0 && ops.some((op) => unsaved.some((one) => one.id === op.id));
|
|
478
|
+
const UNSAVED = "Your change could not be saved just now. It is kept, and sent again until it is.";
|
|
479
|
+
/** The principal a socket is: its seat, or what the host's `seatOf` says its key names — once per key in one sight. */
|
|
480
|
+
const principalOf = (peer, sight) => {
|
|
481
|
+
if (typeof peer.seat !== "string")
|
|
482
|
+
return peer.seat;
|
|
483
|
+
if (!sight)
|
|
484
|
+
return options.seatOf?.(peer.seat);
|
|
485
|
+
const key = seatKeyOf(peer);
|
|
486
|
+
if (!sight.seats.has(key))
|
|
487
|
+
sight.seats.set(key, options.seatOf?.(peer.seat));
|
|
488
|
+
return sight.seats.get(key);
|
|
489
|
+
};
|
|
490
|
+
/** The ops after this socket's cursor up to `last`, down it now, as its seat sees them — written once per seat and run in one sight. */
|
|
491
|
+
const sendUpTo = (peer, last, ops, known, sight) => {
|
|
492
|
+
if (peer.cursor === undefined || peer.cursor >= last)
|
|
181
493
|
return;
|
|
182
|
-
const
|
|
183
|
-
if (
|
|
494
|
+
const seat = known ?? principalOf(peer, sight);
|
|
495
|
+
if (!seat)
|
|
184
496
|
return;
|
|
185
497
|
const from = peer.cursor + 1;
|
|
186
|
-
// The ops handed in, when they are the whole of what this peer is missing; the log otherwise.
|
|
187
|
-
const after = ops && ops.length > 0 && ops[0].seq <= from && ops.at(-1).seq === last ? ops.filter((op) => op.seq >= from) : store.log.opsFrom(from);
|
|
188
498
|
peer.cursor = last;
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const author = peer.seat;
|
|
196
|
-
const intent = typeof message.intent === "string" && message.intent.length > 0 ? message.intent : undefined;
|
|
197
|
-
const batch = typeof message.batch === "string" && message.batch.length > 0 ? message.batch : undefined;
|
|
198
|
-
catchUp(peer);
|
|
199
|
-
// A client that lost its socket before the ack sends the call again under the same batch: `answered` says what it made.
|
|
200
|
-
const already = wire.answered(batch);
|
|
201
|
-
if (already.length > 0) {
|
|
202
|
-
say(peer, { t: "ack", cid, seq: already.at(-1).seq, batch: batch, ops: wire.shown(author, already) });
|
|
203
|
-
return { cursor: peer.cursor };
|
|
499
|
+
const key = sight ? `${seatKeyOf(peer)}\u0000${from}\u0000${last}` : undefined;
|
|
500
|
+
const kept = key !== undefined ? sight.texts.get(key) : undefined;
|
|
501
|
+
if (kept !== undefined) {
|
|
502
|
+
if (kept.length > 0)
|
|
503
|
+
sayText(peer, kept);
|
|
504
|
+
return;
|
|
204
505
|
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
506
|
+
// The ops handed in, when they are the whole of what this peer is missing; the log otherwise.
|
|
507
|
+
const after = (ops && ops.length > 0 && ops[0].seq <= from && ops.at(-1).seq >= last ? ops.filter((op) => op.seq >= from) : store.log.opsFrom(from)).filter((op) => op.seq <= last);
|
|
508
|
+
const text = after.length > 0 ? JSON.stringify({ t: "ops", seq: last, ops: wire.shown(seat, after) }) : "";
|
|
509
|
+
if (key !== undefined)
|
|
510
|
+
sight.texts.set(key, text);
|
|
511
|
+
if (text.length > 0)
|
|
512
|
+
sayText(peer, text);
|
|
513
|
+
};
|
|
514
|
+
/** Every op this socket has not been sent, down it now, as its seat sees them — up to the first that is not durable. */
|
|
515
|
+
const catchUp = (peer, ops, known, sight) => {
|
|
516
|
+
const held = heldFrom();
|
|
517
|
+
sendUpTo(peer, held === undefined ? wire.lastSeq() : Math.min(wire.lastSeq(), held - 1), ops, known, sight);
|
|
518
|
+
};
|
|
519
|
+
/** What the host's `limit` says of a change, before it is judged; nothing when it has none. */
|
|
520
|
+
const limitOf = async (seat, via, change, bytes) => options.limit ? options.limit({ seat, via, t: change.t, bytes, calls: change.t === "call" ? change.calls : [] }) : undefined;
|
|
521
|
+
/**
|
|
522
|
+
* ONE CHANGE, JUDGED AS ITS SEAT — the socket's and `POST /graview/ops`'s
|
|
523
|
+
* alike, so the two can never disagree. A stale write is a conflict and
|
|
524
|
+
* nothing is written (FR-05); then through the store, under the seat and
|
|
525
|
+
* the host's channel (never the client's, FR-52), in the batch the client
|
|
526
|
+
* named or one minted here; then flushed. `applied` runs between the
|
|
527
|
+
* store taking it and the flush, for the socket to move its cursor.
|
|
528
|
+
*/
|
|
529
|
+
const land = async (seat, via, change, bytes, applied) => {
|
|
530
|
+
if (change.t === "call") {
|
|
531
|
+
const conflicts = wire.conflictsOf(seat, change.calls, change.base);
|
|
532
|
+
if (conflicts.length > 0)
|
|
533
|
+
return { conflicts };
|
|
212
534
|
}
|
|
535
|
+
const batch = typeof change.batch === "string" && change.batch.length > 0 ? change.batch : mintServed(change.t === "undo" ? "undo" : "batch");
|
|
213
536
|
let result;
|
|
537
|
+
// A host that publishes from the store's own subscription does so inside the apply: hold from here.
|
|
538
|
+
if (options.flush)
|
|
539
|
+
taking = wire.lastSeq() + 1;
|
|
214
540
|
try {
|
|
215
|
-
// The
|
|
216
|
-
const
|
|
217
|
-
|
|
541
|
+
// The host's caps on what it would do, asked of the store's own plan before anything is kept.
|
|
542
|
+
const admit = options.admit;
|
|
543
|
+
const admitting = admit
|
|
544
|
+
? (planned) => {
|
|
545
|
+
const answer = admit({ seat, via, t: change.t, bytes, calls: change.t === "call" ? change.calls : [] }, planned);
|
|
546
|
+
if (answer)
|
|
547
|
+
throw new NotAdmitted(answer);
|
|
548
|
+
}
|
|
549
|
+
: undefined;
|
|
550
|
+
const applying = { author: seat, via, ...(change.intent ? { intent: change.intent } : {}), batch, ...(admitting ? { admit: admitting } : {}) };
|
|
551
|
+
result = change.t === "undo" ? store.undo(change.batches, applying) : store.applyAll(change.calls, applying);
|
|
218
552
|
}
|
|
219
553
|
catch (error) {
|
|
220
|
-
|
|
554
|
+
taking = undefined;
|
|
555
|
+
if (error instanceof NotAdmitted)
|
|
556
|
+
return { limited: error.answer };
|
|
557
|
+
const worded = options.refusal?.(error, change.calls, { seat, via });
|
|
558
|
+
return { refusal: worded ?? wireRefusalOf(store, error) };
|
|
559
|
+
}
|
|
560
|
+
// Being written: nobody else hears it until it is (`heldFrom`).
|
|
561
|
+
if (options.flush)
|
|
562
|
+
flying = [...flying, ...result.ops];
|
|
563
|
+
taking = undefined;
|
|
564
|
+
applied?.(result.ops);
|
|
565
|
+
const flushed = await durable(result.ops);
|
|
566
|
+
return { result, saved: "saved" in flushed ? flushed.saved : undefined };
|
|
567
|
+
};
|
|
568
|
+
/** A change as the socket's message says it. */
|
|
569
|
+
const changeOf = (message) => ({
|
|
570
|
+
t: message.t,
|
|
571
|
+
calls: message.t === "call" && Array.isArray(message.calls) ? message.calls : [],
|
|
572
|
+
batches: message.t === "undo" && Array.isArray(message.batches) ? message.batches : [],
|
|
573
|
+
intent: typeof message.intent === "string" && message.intent.length > 0 ? message.intent : undefined,
|
|
574
|
+
batch: message.batch,
|
|
575
|
+
base: message.t === "call" ? message.base : undefined,
|
|
576
|
+
claimed: claimOfVia(message.via),
|
|
577
|
+
});
|
|
578
|
+
/** What a change came through: the host's word, or a claim its `viaOf` accepts (FR-52). */
|
|
579
|
+
const viaFor = (peer, change) => {
|
|
580
|
+
const judged = options.viaOf?.(peer, change.claimed);
|
|
581
|
+
return typeof judged === "string" && judged.length > 0 ? judged : peer.via;
|
|
582
|
+
};
|
|
583
|
+
/**
|
|
584
|
+
* THE HOST'S WORD ON A SOCKET'S CALL (FR-45, FR-46) — its `limit`'s, or
|
|
585
|
+
* its `admit`'s: refused at a cap, unavailable for a while, or busy, when
|
|
586
|
+
* every later call waits behind it.
|
|
587
|
+
*/
|
|
588
|
+
const sayLimited = (peer, cid, limited) => {
|
|
589
|
+
if ("refuse" in limited) {
|
|
590
|
+
delete peer.held;
|
|
591
|
+
say(peer, { t: "refused", cid, reason: "limit", sentence: limited.refuse });
|
|
592
|
+
}
|
|
593
|
+
else if ("unavailable" in limited) {
|
|
594
|
+
// Not for a while, and no wait to name: refused `unavailable`, which the client keeps and sends again, backing off.
|
|
595
|
+
delete peer.held;
|
|
596
|
+
say(peer, { t: "refused", cid, reason: "unavailable", sentence: limited.unavailable });
|
|
597
|
+
}
|
|
598
|
+
else {
|
|
599
|
+
const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
|
|
600
|
+
peer.held = { cid, until: Date.now() + retryAfter };
|
|
601
|
+
say(peer, { t: "busy", cid, retryAfter, ...(limited.sentence ? { sentence: limited.sentence } : {}) });
|
|
602
|
+
}
|
|
603
|
+
return { cursor: peer.cursor };
|
|
604
|
+
};
|
|
605
|
+
/** The same word over HTTP: 413 `limit`, 503 `unavailable`, or 429 with `Retry-After`. */
|
|
606
|
+
const limitedReply = (limited, said) => {
|
|
607
|
+
if ("refuse" in limited)
|
|
608
|
+
return reply(413, { error: limited.refuse, refused: true, reason: "limit", ...said });
|
|
609
|
+
if ("unavailable" in limited)
|
|
610
|
+
return reply(503, { error: limited.unavailable, refused: true, reason: "unavailable", ...said });
|
|
611
|
+
const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
|
|
612
|
+
return reply(429, { error: limited.sentence ?? `The store is busy: send it again in ${retryAfter} ms.`, busy: true, retryAfter }, { "retry-after": String(Math.ceil(retryAfter / 1000)) });
|
|
613
|
+
};
|
|
614
|
+
/** A call or an undo from a socket, past its claim and the host's limit: judged as its seat, exactly as `POST /graview/ops` judges it. */
|
|
615
|
+
const answer = async (peer, seat, cid, change, via, bytes) => {
|
|
616
|
+
catchUp(peer, undefined, seat);
|
|
617
|
+
const prior = peer.cursor;
|
|
618
|
+
/*
|
|
619
|
+
* Every op before this call's went down this socket before it landed;
|
|
620
|
+
* its own go in the ack. Unless one before it is held back as not
|
|
621
|
+
* durable: then the cursor stays, and they go down after the flush.
|
|
622
|
+
*/
|
|
623
|
+
const landing = await land(seat, via, change, bytes, (own) => {
|
|
624
|
+
if (own.length === 0 || heldFrom(own[0].seq) === undefined)
|
|
625
|
+
peer.cursor = wire.lastSeq();
|
|
626
|
+
});
|
|
627
|
+
// What it would do is over the host's caps: nothing was kept.
|
|
628
|
+
if (landing.limited)
|
|
629
|
+
return sayLimited(peer, cid, landing.limited);
|
|
630
|
+
if (landing.conflicts) {
|
|
631
|
+
say(peer, { t: "conflict", cid, sentence: conflictSentence(landing.conflicts), conflicts: [...landing.conflicts] });
|
|
221
632
|
return { cursor: peer.cursor };
|
|
222
633
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
634
|
+
if (landing.refusal) {
|
|
635
|
+
say(peer, { t: "refused", cid, ...landing.refusal });
|
|
636
|
+
return { cursor: peer.cursor };
|
|
637
|
+
}
|
|
638
|
+
const { result, saved } = landing;
|
|
639
|
+
if (!saved) {
|
|
640
|
+
// Not durable: refused `unavailable`, which the client keeps and sends again; nothing is acked and the cursor does not move.
|
|
641
|
+
peer.cursor = prior;
|
|
642
|
+
say(peer, { t: "refused", cid, reason: "unavailable", sentence: UNSAVED });
|
|
643
|
+
return { cursor: prior };
|
|
644
|
+
}
|
|
645
|
+
return acked(peer, seat, cid, result.batch, result.ops, saved);
|
|
646
|
+
};
|
|
647
|
+
/** The ack of ops that are durable: what was held back before them goes first, so none is skipped. */
|
|
648
|
+
const acked = (peer, seat, cid, batch, own, saved) => {
|
|
649
|
+
const first = own[0]?.seq;
|
|
650
|
+
if (first !== undefined) {
|
|
651
|
+
sendUpTo(peer, first - 1, undefined, seat);
|
|
652
|
+
peer.cursor = Math.max(peer.cursor, own.at(-1).seq);
|
|
653
|
+
}
|
|
654
|
+
const ops = wire.shown(seat, own);
|
|
655
|
+
say(peer, { t: "ack", cid, seq: ops.at(-1)?.seq ?? peer.cursor, batch, ops });
|
|
656
|
+
return { cursor: peer.cursor, ...(saved && saved.length > 0 ? { landed: saved } : {}) };
|
|
657
|
+
};
|
|
658
|
+
/** The host's build a socket — or a route's request — is served by (FR-44): its own, else the protocol's word for it. */
|
|
659
|
+
const buildFor = (peer) => peer.hostBuild ?? (typeof options.build === "function" ? options.build(peer) : options.build);
|
|
660
|
+
/** Which declaration, and which build, answered (FR-43, FR-44): on every route's answer a poll reads. */
|
|
661
|
+
const answering = (asked) => {
|
|
662
|
+
const build = buildFor({ seat: asked.seat, via: asked.via, ...(asked.build ? { hostBuild: asked.build } : {}) });
|
|
663
|
+
return { version: options.version ?? 1, ...(build ? { build } : {}) };
|
|
229
664
|
};
|
|
665
|
+
const reply = (status, body, headers = {}) => ({ status, body, headers });
|
|
230
666
|
return {
|
|
231
667
|
store,
|
|
232
|
-
open: (seat, via) => ({ seat, via }),
|
|
233
|
-
async receive(peer, text, who = []) {
|
|
668
|
+
open: (seat, via, opening = {}) => ({ seat, via, ...(opening.build ? { hostBuild: opening.build.slice(0, 64) } : {}) }),
|
|
669
|
+
async receive(peer, text, who = [], peers = [peer]) {
|
|
234
670
|
let message;
|
|
235
671
|
try {
|
|
236
672
|
message = JSON.parse(text);
|
|
@@ -242,6 +678,13 @@ export function liveProtocol(options) {
|
|
|
242
678
|
const unchanged = () => (peer.cursor !== undefined ? { cursor: peer.cursor } : {});
|
|
243
679
|
if (!message || typeof message !== "object")
|
|
244
680
|
return unchanged();
|
|
681
|
+
// Who this socket is, on this message: its seat, or the principal its key names now.
|
|
682
|
+
const seat = principalOf(peer);
|
|
683
|
+
if (!seat) {
|
|
684
|
+
lost(peer);
|
|
685
|
+
return {};
|
|
686
|
+
}
|
|
687
|
+
const served = { seat, via: peer.via, ...(peer.hostBuild ? { hostBuild: peer.hostBuild } : {}) };
|
|
245
688
|
switch (message.t) {
|
|
246
689
|
case "hello": {
|
|
247
690
|
/*
|
|
@@ -263,16 +706,29 @@ export function liveProtocol(options) {
|
|
|
263
706
|
});
|
|
264
707
|
return {};
|
|
265
708
|
}
|
|
709
|
+
// The host's own half of the wire, numbered by the host: an older page reloads onto a build that speaks it.
|
|
710
|
+
const hostSpeaks = typeof message.hostProtocol === "number" && Number.isFinite(message.hostProtocol) ? message.hostProtocol : 0;
|
|
711
|
+
if (options.minHostProtocol !== undefined && hostSpeaks < options.minHostProtocol) {
|
|
712
|
+
delete peer.cursor;
|
|
713
|
+
say(peer, {
|
|
714
|
+
t: "reload",
|
|
715
|
+
reason: "This app was updated, and this page is from before it. Reload the page; changes not yet sent are offered again after it.",
|
|
716
|
+
protocol: options.minProtocol ?? WIRE_PROTOCOL,
|
|
717
|
+
hostProtocol: options.minHostProtocol,
|
|
718
|
+
});
|
|
719
|
+
return {};
|
|
720
|
+
}
|
|
266
721
|
if (typeof message.build === "string" && message.build.length > 0)
|
|
267
722
|
peer.build = message.build.slice(0, 64);
|
|
268
723
|
const seq = typeof message.seq === "number" && Number.isFinite(message.seq) ? message.seq : undefined;
|
|
269
724
|
peer.cursor = wire.lastSeq();
|
|
270
725
|
// Its own key, built from the seat, so the client can leave itself out of who is here (FR-47).
|
|
271
|
-
peer.participant ??= participantKey({ kind:
|
|
726
|
+
peer.participant ??= participantKey({ kind: seat.kind, ...(seat.id ? { id: seat.id } : {}), session: mintSession() });
|
|
272
727
|
const participant = peer.participant;
|
|
273
|
-
const
|
|
728
|
+
const build = buildFor(served);
|
|
729
|
+
const said = { protocol: WIRE_PROTOCOL, wire: LIVE_WIRE, version: options.version ?? 1, participant, ...(build ? { build } : {}) };
|
|
274
730
|
if (seq === undefined) {
|
|
275
|
-
const seen = wire.seenFor(
|
|
731
|
+
const seen = wire.seenFor(seat);
|
|
276
732
|
say(peer, {
|
|
277
733
|
t: "welcome",
|
|
278
734
|
...said,
|
|
@@ -281,7 +737,7 @@ export function liveProtocol(options) {
|
|
|
281
737
|
state: {
|
|
282
738
|
version: options.version ?? 1,
|
|
283
739
|
snapshot: seen.snapshot(),
|
|
284
|
-
log:
|
|
740
|
+
log: wire.seenLog(seat),
|
|
285
741
|
migrated: [...(options.migrated ?? [])],
|
|
286
742
|
enabledModules: wire.enabledModules(),
|
|
287
743
|
...wire.horizonOf(),
|
|
@@ -289,20 +745,62 @@ export function liveProtocol(options) {
|
|
|
289
745
|
});
|
|
290
746
|
}
|
|
291
747
|
else {
|
|
292
|
-
|
|
748
|
+
// Caught up to what is written: an op still being flushed, or one a flush failed, comes once it holds.
|
|
749
|
+
const held = heldFrom();
|
|
750
|
+
if (held !== undefined)
|
|
751
|
+
peer.cursor = Math.max(Math.floor(seq), held - 1);
|
|
752
|
+
say(peer, { t: "welcome", ...said, seq: peer.cursor, ops: wire.since(seat, seq).filter((op) => op.seq <= peer.cursor) });
|
|
293
753
|
}
|
|
294
|
-
const others = who.filter((presence) => presence.participant !== peer.participant);
|
|
754
|
+
const others = heldBySockets(who, [peer, ...peers]).filter((presence) => presence.participant !== peer.participant);
|
|
295
755
|
if (others.length > 0)
|
|
296
|
-
say(peer, { t: "presence", who: wire.whoFor(
|
|
756
|
+
say(peer, { t: "presence", who: wire.whoFor(seat, others) });
|
|
297
757
|
return { cursor: peer.cursor };
|
|
298
758
|
}
|
|
299
759
|
case "call":
|
|
300
760
|
case "undo": {
|
|
301
761
|
const cid = String(message.cid ?? "");
|
|
762
|
+
// A cid is kept while its call is busy: a long one would crowd the host's attachment.
|
|
763
|
+
if (cid.length > MAX_CID) {
|
|
764
|
+
say(peer, { t: "refused", cid, reason: "invalid", sentence: `A call's cid is at most ${MAX_CID} characters; this one is ${cid.length}. Name it again shorter.` });
|
|
765
|
+
return unchanged();
|
|
766
|
+
}
|
|
302
767
|
if (peer.cursor === undefined) {
|
|
303
768
|
say(peer, { t: "refused", cid, reason: "invalid", sentence: "Say hello first: the live wire answers calls once it knows what the client has." });
|
|
304
769
|
return {};
|
|
305
770
|
}
|
|
771
|
+
/*
|
|
772
|
+
* SENT AGAIN AFTER IT LANDED: answered with what it made, before the
|
|
773
|
+
* host is asked anything. A call whose ack was lost is never told
|
|
774
|
+
* busy, capped or unavailable for a change already made — and only
|
|
775
|
+
* ever with the asking seat's own ops (`claim`).
|
|
776
|
+
*/
|
|
777
|
+
const change = changeOf(message);
|
|
778
|
+
const claim = wire.claim(message.batch, seat);
|
|
779
|
+
if (claim.refusal) {
|
|
780
|
+
catchUp(peer, undefined, seat);
|
|
781
|
+
if (peer.held?.cid === cid)
|
|
782
|
+
delete peer.held;
|
|
783
|
+
say(peer, { t: "refused", cid, ...claim.refusal });
|
|
784
|
+
return { cursor: peer.cursor };
|
|
785
|
+
}
|
|
786
|
+
if (claim.answered) {
|
|
787
|
+
if (peer.held?.cid === cid)
|
|
788
|
+
delete peer.held;
|
|
789
|
+
// Landed, but a flush failed it: flushed again, and acked only once it holds.
|
|
790
|
+
if (unsavedIn(claim.answered)) {
|
|
791
|
+
const flushed = await durable([]);
|
|
792
|
+
if (!("saved" in flushed)) {
|
|
793
|
+
catchUp(peer, undefined, seat);
|
|
794
|
+
say(peer, { t: "refused", cid, reason: "unavailable", sentence: UNSAVED });
|
|
795
|
+
return { cursor: peer.cursor };
|
|
796
|
+
}
|
|
797
|
+
catchUp(peer, undefined, seat);
|
|
798
|
+
return acked(peer, seat, cid, message.batch, claim.answered, flushed.saved);
|
|
799
|
+
}
|
|
800
|
+
catchUp(peer, undefined, seat);
|
|
801
|
+
say(peer, { t: "ack", cid, seq: claim.answered.at(-1).seq, batch: message.batch, ops: wire.shown(seat, claim.answered) });
|
|
802
|
+
return { cursor: peer.cursor };
|
|
803
|
+
}
|
|
306
804
|
/*
|
|
307
805
|
* BUSY IS NOT REFUSED (FR-45). A call made after one that was told
|
|
308
806
|
* to wait waits too, whatever the rate says now: the client sends
|
|
@@ -313,28 +811,13 @@ export function liveProtocol(options) {
|
|
|
313
811
|
say(peer, { t: "busy", cid, retryAfter: Math.max(0, peer.held.until - now) });
|
|
314
812
|
return { cursor: peer.cursor };
|
|
315
813
|
}
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
bytes: bytesOf(text),
|
|
322
|
-
calls: message.t === "call" && Array.isArray(message.calls) ? message.calls : [],
|
|
323
|
-
})
|
|
324
|
-
: undefined;
|
|
325
|
-
if (limited && "refuse" in limited) {
|
|
326
|
-
delete peer.held;
|
|
327
|
-
say(peer, { t: "refused", cid, reason: "limit", sentence: limited.refuse });
|
|
328
|
-
return { cursor: peer.cursor };
|
|
329
|
-
}
|
|
330
|
-
if (limited) {
|
|
331
|
-
const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
|
|
332
|
-
peer.held = { cid, until: now + retryAfter };
|
|
333
|
-
say(peer, { t: "busy", cid, retryAfter, ...(limited.sentence ? { sentence: limited.sentence } : {}) });
|
|
334
|
-
return { cursor: peer.cursor };
|
|
335
|
-
}
|
|
814
|
+
const via = viaFor(served, change);
|
|
815
|
+
const bytes = bytesOf(text);
|
|
816
|
+
const limited = await limitOf(seat, via, change, bytes);
|
|
817
|
+
if (limited)
|
|
818
|
+
return sayLimited(peer, cid, limited);
|
|
336
819
|
delete peer.held;
|
|
337
|
-
return answer(peer,
|
|
820
|
+
return answer(peer, seat, cid, change, via, bytes);
|
|
338
821
|
}
|
|
339
822
|
case "here": {
|
|
340
823
|
const told = message.presence;
|
|
@@ -342,7 +825,8 @@ export function liveProtocol(options) {
|
|
|
342
825
|
say(peer, { t: "error", sentence: "A presence is a participant and a stop." });
|
|
343
826
|
return unchanged();
|
|
344
827
|
}
|
|
345
|
-
|
|
828
|
+
// Held by this socket: it stands while the socket does, with no heartbeat to keep it.
|
|
829
|
+
const presence = { ...presenceFrom(told, seat, new Date(), peer.participant), held: "socket" };
|
|
346
830
|
peer.participant = presence.participant;
|
|
347
831
|
return { ...unchanged(), presence };
|
|
348
832
|
}
|
|
@@ -357,16 +841,109 @@ export function liveProtocol(options) {
|
|
|
357
841
|
}
|
|
358
842
|
},
|
|
359
843
|
publish(ops, peers) {
|
|
360
|
-
|
|
361
|
-
catchUp(peer, ops);
|
|
362
|
-
},
|
|
363
|
-
tell(who, peers) {
|
|
844
|
+
const sight = aSight();
|
|
364
845
|
for (const peer of peers) {
|
|
365
846
|
if (peer.cursor === undefined)
|
|
366
847
|
continue;
|
|
367
|
-
|
|
848
|
+
const seat = principalOf(peer, sight);
|
|
849
|
+
if (!seat)
|
|
850
|
+
lost(peer);
|
|
851
|
+
else
|
|
852
|
+
catchUp(peer, ops, seat, sight);
|
|
368
853
|
}
|
|
369
854
|
},
|
|
855
|
+
tell(said, peers) {
|
|
856
|
+
const sight = aSight();
|
|
857
|
+
const all = [...peers];
|
|
858
|
+
const who = heldBySockets(said, all);
|
|
859
|
+
for (const peer of all) {
|
|
860
|
+
if (peer.cursor === undefined)
|
|
861
|
+
continue;
|
|
862
|
+
const seat = principalOf(peer, sight);
|
|
863
|
+
if (!seat) {
|
|
864
|
+
lost(peer);
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
say(peer, { t: "presence", who: wire.whoFor(seat, who.filter((presence) => presence.participant !== peer.participant)) });
|
|
868
|
+
}
|
|
869
|
+
},
|
|
870
|
+
async post(text, asked) {
|
|
871
|
+
const said = answering(asked);
|
|
872
|
+
let body;
|
|
873
|
+
try {
|
|
874
|
+
body = text.length === 0 ? {} : JSON.parse(text);
|
|
875
|
+
}
|
|
876
|
+
catch {
|
|
877
|
+
return reply(400, { error: "A change is one JSON object: { calls } to make, or { undo } to take back.", reason: "invalid" });
|
|
878
|
+
}
|
|
879
|
+
if (!body || typeof body !== "object")
|
|
880
|
+
return reply(400, { error: "A change is one JSON object: { calls } to make, or { undo } to take back.", reason: "invalid" });
|
|
881
|
+
const undo = Array.isArray(body.undo) ? body.undo : undefined;
|
|
882
|
+
const change = {
|
|
883
|
+
t: undo ? "undo" : "call",
|
|
884
|
+
calls: !undo && Array.isArray(body.calls) ? body.calls : [],
|
|
885
|
+
batches: undo ?? [],
|
|
886
|
+
intent: typeof body.intent === "string" && body.intent.length > 0 ? body.intent : undefined,
|
|
887
|
+
batch: body.batch,
|
|
888
|
+
base: undo ? undefined : body.base,
|
|
889
|
+
claimed: claimOfVia(body.via),
|
|
890
|
+
};
|
|
891
|
+
const via = viaFor({ seat: asked.seat, via: asked.via, ...(asked.build ? { hostBuild: asked.build } : {}) }, change);
|
|
892
|
+
// Sent again after its answer was lost — or offered again on a new declaration, or after a reload (FR-43, FR-44, FR-49): only ever the asker's own ops.
|
|
893
|
+
const claim = wire.claim(change.batch, asked.seat);
|
|
894
|
+
if (claim.refusal)
|
|
895
|
+
return reply(409, { error: claim.refusal.sentence, refused: true, reason: claim.refusal.reason, ...said });
|
|
896
|
+
if (claim.answered) {
|
|
897
|
+
// Landed, but a flush failed it: flushed again, and answered only once it holds.
|
|
898
|
+
if (unsavedIn(claim.answered)) {
|
|
899
|
+
const flushed = await durable([]);
|
|
900
|
+
if (!("saved" in flushed))
|
|
901
|
+
return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
|
|
902
|
+
return { ...reply(200, { ops: wire.shown(asked.seat, claim.answered), batch: change.batch, ...said }), landed: flushed.saved };
|
|
903
|
+
}
|
|
904
|
+
return reply(200, { ops: wire.shown(asked.seat, claim.answered), batch: change.batch, ...said });
|
|
905
|
+
}
|
|
906
|
+
/*
|
|
907
|
+
* THE HOST'S LIMITS, BEFORE ANYTHING IS JUDGED. Busy is 429 and the
|
|
908
|
+
* change is kept to send again (FR-45); a hard cap is refused, `limit`,
|
|
909
|
+
* and the change is taken back (FR-46); unavailable is 503, kept.
|
|
910
|
+
*/
|
|
911
|
+
const bytes = bytesOf(text);
|
|
912
|
+
const limited = await limitOf(asked.seat, via, change, bytes);
|
|
913
|
+
if (limited)
|
|
914
|
+
return limitedReply(limited, said);
|
|
915
|
+
const landing = await land(asked.seat, via, change, bytes);
|
|
916
|
+
// What it would do is over the host's caps (its `admit`): nothing was kept.
|
|
917
|
+
if (landing.limited)
|
|
918
|
+
return limitedReply(landing.limited, said);
|
|
919
|
+
// A stale write is a conflict, not a loss (FR-05): theirs and yours, by name, and nothing written.
|
|
920
|
+
if (landing.conflicts)
|
|
921
|
+
return reply(409, { error: conflictSentence(landing.conflicts), refused: true, conflict: true, conflicts: landing.conflicts, ...said });
|
|
922
|
+
// The policy's own sentence rather than a bare 403, because that sentence is the product.
|
|
923
|
+
if (landing.refusal) {
|
|
924
|
+
const { sentence, ...why } = landing.refusal;
|
|
925
|
+
return reply(409, { error: sentence, refused: true, ...why, ...said });
|
|
926
|
+
}
|
|
927
|
+
// Not durable: refused `unavailable`, which the client keeps and sends again.
|
|
928
|
+
if (!landing.saved)
|
|
929
|
+
return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
|
|
930
|
+
// An act may make what its own seat may not see: that op goes back withheld, as it would on a poll.
|
|
931
|
+
return { ...reply(200, { ops: wire.shown(asked.seat, landing.result.ops), batch: landing.result.batch, ...said }), landed: landing.saved };
|
|
932
|
+
},
|
|
933
|
+
state(asked) {
|
|
934
|
+
const seen = wire.seenFor(asked.seat);
|
|
935
|
+
return reply(200, {
|
|
936
|
+
...answering(asked),
|
|
937
|
+
snapshot: seen.snapshot(),
|
|
938
|
+
log: wire.seenLog(asked.seat),
|
|
939
|
+
migrated: [...(options.migrated ?? [])],
|
|
940
|
+
enabledModules: wire.enabledModules(),
|
|
941
|
+
...wire.horizonOf(),
|
|
942
|
+
});
|
|
943
|
+
},
|
|
944
|
+
since(seq, asked) {
|
|
945
|
+
return reply(200, { ops: wire.since(asked.seat, seq), ...answering(asked) });
|
|
946
|
+
},
|
|
370
947
|
declared(peers) {
|
|
371
948
|
for (const peer of peers) {
|
|
372
949
|
if (peer.cursor === undefined)
|