@graview/ship 0.1.2 → 0.1.3

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/dist/handler.js CHANGED
@@ -1,7 +1,8 @@
1
- import { FieldRevisions, foldPresence, hidesFrom, isUnset, participantKey, WIRE_PROTOCOL, PRESENCE_TTL_MS, redact, seenBy, seesId, } from "@graview/core";
1
+ import { foldPresence, PRESENCE_TTL_MS, refusalOf, VISITOR_PRESENCE_TTL_MS, } from "@graview/core";
2
2
  import { exportBundle } from "./export.js";
3
3
  import { health } from "./health.js";
4
- import { conflictSentence, LIVE_PATH } from "./live.js";
4
+ import { bytesOf, conflictSentence, LIVE_PATH } from "./live.js";
5
+ import { announcePresence, liveProtocol, presenceFrom, presenceSeenBy, visitorPresence, wireOf, } from "./live-protocol.js";
5
6
  import { openStore } from "./open-store.js";
6
7
  import { SEAT_HEADERS } from "./seat-headers.js";
7
8
  /**
@@ -41,7 +42,9 @@ import { SEAT_HEADERS } from "./seat-headers.js";
41
42
  * Polling is the floor, on purpose: a poll is a thing a person can
42
43
  * reproduce with `curl`, and a thing every runtime can answer. Beside it,
43
44
  * `connect` serves the live wire (FR-05, `./live.ts`) to whatever socket a
44
- * host hands it, and `GET /graview/live` names it on the wire.
45
+ * host hands it, and `GET /graview/live` names it on the wire. The live
46
+ * protocol itself is `liveProtocol` (`./live-protocol.ts`), over state a
47
+ * host may hold instead of this closure (FR-41).
45
48
  */
46
49
  /**
47
50
  * THE WIRE, AS A CONTRACT. Every route the handler answers, in one place a
@@ -53,16 +56,16 @@ import { SEAT_HEADERS } from "./seat-headers.js";
53
56
  */
54
57
  export const WIRE = [
55
58
  { method: "GET", path: "/graview/state", says: "the graph, the log, the stored version and the modules on" },
56
- { method: "POST", path: "/graview/ops", says: "calls in, the ops they produced out — or `undo`, batches to take back; 409 with the policy's sentence when refused" },
59
+ { method: "POST", path: "/graview/ops", says: "calls in, the ops they produced out — or `undo`, batches to take back; a `batch` already in the log is answered with the ops it made; 409 with the policy's sentence and a `reason` when refused, 429 with `Retry-After` when the host is busy" },
57
60
  { method: "GET", path: "/graview/since", says: "the ops appended after ?seq=N — everyone else's" },
58
61
  { method: "GET", path: "/graview/health", says: "ship's own report, plus where the data is" },
59
62
  { method: "GET", path: "/graview/export", says: "the whole store as one bundle, the way out" },
60
- { method: "POST", path: "/graview/here", says: "say where you are; answers with who else is, and the ops since `seq`" },
63
+ { method: "POST", path: "/graview/here", says: "say where you are; answers with who else is, the ops since `seq`, and the `participant` key you are held under" },
61
64
  { method: "GET", path: "/graview/who", says: "who is here right now" },
62
- { method: "POST", path: "/graview/leave", says: "say you have gone" },
63
- { method: "GET", path: LIVE_PATH, says: "the live wire: a WebSocket of hello/welcome, call/undo/ack/refused/conflict, ops and presence; 426 to a plain request" },
65
+ { method: "POST", path: "/graview/leave", says: "say you have gone — only ever yourself" },
66
+ { method: "GET", path: LIVE_PATH, says: "the live wire: a WebSocket of hello/welcome, call/undo/ack/refused/conflict/busy, ops and presence, declaration and reload; 426 to a plain request" },
64
67
  ];
65
- export { SEAT_HEADERS };
68
+ export { presenceSeenBy, SEAT_HEADERS };
66
69
  const KINDS = new Set(["human", "agent", "rule", "system"]);
67
70
  const list = (value) => (value ? value.split(",").filter(Boolean) : undefined);
68
71
  const decoded = (value) => (value ? decodeURIComponent(value) : undefined);
@@ -84,59 +87,129 @@ export function seatFromHeaders(request) {
84
87
  ...(forId ? { onBehalfOf: { kind: "human", id: forId, ...(forRoles ? { roles: forRoles } : {}), ...(forName ? { name: forName } : {}) } } : {}),
85
88
  };
86
89
  }
87
- /**
88
- * WHO IS HERE, AS ONE SEAT MAY BE TOLD (FR-02). Somebody whose own record
89
- * the seat may not see is not shown to it at all; anybody else is, without
90
- * where they stand or what they hover when that names a record the seat
91
- * may not see. A participant whose id is no record is shown as they are.
92
- */
93
- export function presenceSeenBy(who, sees) {
94
- const names = (value) => value.split(/[/?#=&,;]/).every((part) => part === "" || sees(decodeURIComponent(part)));
95
- return who
96
- .filter((presence) => {
97
- // `kind:id:session`, and an id may hold a colon of its own: every reading of it must be one the seat sees.
98
- const parts = presence.participant.split(":");
99
- return parts.slice(2).every((_, at) => sees(parts.slice(1, at + 2).join(":")));
100
- })
101
- .map((presence) => ({
102
- ...presence,
103
- stop: names(presence.stop) ? presence.stop : "",
104
- ...(typeof presence.over === "string" && !sees(presence.over) ? { over: null } : {}),
105
- ...(presence.robot?.at && !sees(presence.robot.at) ? { robot: { ...presence.robot, at: null } } : {}),
106
- }));
107
- }
108
90
  /** A browser on another origin is the ordinary case for an embed. */
109
91
  const CORS = {
110
92
  "access-control-allow-origin": "*",
111
93
  "access-control-allow-headers": ["content-type", "authorization", ...Object.values(SEAT_HEADERS)].join(", "),
112
94
  "access-control-allow-methods": "GET, POST, OPTIONS",
113
95
  };
114
- function send(status, body) {
115
- return new Response(JSON.stringify(body), { status, headers: { ...CORS, "content-type": "application/json" } });
96
+ function send(status, body, headers = {}) {
97
+ return new Response(JSON.stringify(body), { status, headers: { ...CORS, "content-type": "application/json", ...headers } });
116
98
  }
117
99
  async function read(request) {
118
100
  const text = await request.text();
119
101
  return text.length === 0 ? {} : JSON.parse(text);
120
102
  }
121
- /**
122
- * Open the store and answer the wire for it. The migration runs HERE, once,
123
- * against the stored graph — which is the whole reason a server is the
124
- * honest place for it. A browser that migrates its own copy migrates it once
125
- * per browser; a server that migrates the roster migrates the roster.
126
- */
103
+ /** "Who is asking" refused: the reason a program reads beside the sentence (FR-46). */
104
+ const unknownSeat = (error) => send(401, { error, reason: "forbidden" });
105
+ const CANNOT_TELL = "This store cannot tell who is asking: the host gives serveStore a seatOf, or trusts the seat headers (trustSeatHeaders) on a server only it can reach.";
127
106
  export async function createStoreHandler(options) {
107
+ if (options.store) {
108
+ const { handler, swap } = storeHandler(options);
109
+ return {
110
+ ...handler,
111
+ get store() {
112
+ return handler.store;
113
+ },
114
+ get protocol() {
115
+ return handler.protocol;
116
+ },
117
+ async declarationChanged(change) {
118
+ const { store } = change;
119
+ if (!store)
120
+ throw new Error("A handler over a store the host holds is handed the store migrated to the new declaration: declarationChanged({ app, store }).");
121
+ await swap(change.app, async () => ({ store, ...(change.flush ? { flush: change.flush } : {}), migrated: change.migrated ?? [] }));
122
+ },
123
+ };
124
+ }
128
125
  const scope = options.scope ?? options.app.name;
129
- const seatOf = options.seatOf ?? (options.trustSeatHeaders ? seatFromHeaders : undefined);
130
- const opened = await openStore({
131
- app: options.app,
126
+ const opening = (app) => openStore({
127
+ app,
132
128
  adapter: options.adapter,
133
129
  scope,
134
130
  ...(options.seed ? { seed: options.seed } : {}),
135
131
  ...(options.enabledModules ? { enabledModules: options.enabledModules } : {}),
136
132
  });
137
- const store = opened.store;
138
- /** Which modules are on, as the state says it (FR-12). */
139
- const enabledModules = () => [...store.modules.enabled].sort();
133
+ let opened = (await opening(options.app));
134
+ const { adapter, seed: _seed, scope: _scope, enabledModules: _modules, ...rest } = options;
135
+ const { handler, swap } = storeHandler({
136
+ ...rest,
137
+ store: opened.store,
138
+ flush: () => opened.flush(),
139
+ migrated: opened.migrated.map((op) => op.intent),
140
+ // Said by the adapter where it knows, because it is the only thing
141
+ // that does; `where` is for a caller with a better name for it.
142
+ where: options.where ?? adapter.root ?? scope,
143
+ }, adapter.name);
144
+ return {
145
+ ...handler,
146
+ get store() {
147
+ return handler.store;
148
+ },
149
+ get protocol() {
150
+ return handler.protocol;
151
+ },
152
+ get opened() {
153
+ return opened;
154
+ },
155
+ /*
156
+ * OPENED AGAIN, ON THE NEW DECLARATION. What is pending is written
157
+ * first, then the adapter is read again by `openStore`, which runs the
158
+ * migrations between the stored version and the new one — here, once,
159
+ * as it did at the start — while every request and message waits.
160
+ */
161
+ async declarationChanged(change) {
162
+ await swap(change.app, async () => {
163
+ if (change.store)
164
+ return { store: change.store, ...(change.flush ? { flush: change.flush } : {}), migrated: change.migrated ?? [] };
165
+ await opened.flush();
166
+ opened.close();
167
+ opened = await opening(change.app);
168
+ return { store: opened.store, flush: () => opened.flush(), migrated: opened.migrated.map((op) => op.intent) };
169
+ });
170
+ },
171
+ async close() {
172
+ await handler.close();
173
+ opened.close();
174
+ },
175
+ };
176
+ }
177
+ function storeHandler(options, adapterName = "held by the host") {
178
+ const seatOf = options.seatOf ?? (options.trustSeatHeaders ? seatFromHeaders : undefined);
179
+ const flush = async () => {
180
+ await serving.flush?.();
181
+ };
182
+ const serve = (app, store, flushing, migrated) => ({
183
+ app,
184
+ store,
185
+ flush: flushing,
186
+ migrated: [...migrated],
187
+ wire: wireOf(store),
188
+ protocol: liveProtocol({
189
+ store,
190
+ version: app.version ?? 1,
191
+ migrated,
192
+ flush,
193
+ ...(options.build ? { build: options.build } : {}),
194
+ ...(options.minProtocol !== undefined ? { minProtocol: options.minProtocol } : {}),
195
+ ...(options.limit ? { limit: options.limit } : {}),
196
+ }),
197
+ });
198
+ let serving = serve(options.app, options.store, options.flush, options.migrated ?? []);
199
+ /** Set while the declaration is being changed: every request and message waits for it. */
200
+ let changing;
201
+ /*
202
+ * THE CHANNEL IS THE HOST'S WORD (FR-52). `viaOf` when the host gave
203
+ * one; the via header when it trusts the seat headers; else what the
204
+ * route is. Never the client's body or message.
205
+ */
206
+ const viaFor = async (request, seat, otherwise) => {
207
+ const said = options.viaOf ? await options.viaOf(request, seat) : undefined;
208
+ if (typeof said === "string" && said.length > 0)
209
+ return said;
210
+ const header = options.trustSeatHeaders ? request.headers.get(SEAT_HEADERS.via) : null;
211
+ return header && header.length > 0 ? header : otherwise;
212
+ };
140
213
  /*
141
214
  * WHO IS HERE. Keyed by participant, named by the seat the request
142
215
  * carries — a poster cannot claim to be somebody else's seat — and
@@ -149,173 +222,137 @@ export async function createStoreHandler(options) {
149
222
  here = foldPresence(here, [], Date.now(), ttl);
150
223
  return [...here.values()];
151
224
  };
152
- const arrive = (told, seat) => {
153
- // The session is what follows the seat's own `kind:id:` — an id may hold a colon (`shopper:bethan`).
154
- const own = `${seat.kind}:${seat.id ?? ""}:`;
155
- const session = told.participant.startsWith(own) ? told.participant.slice(own.length) : (told.participant.split(":").at(-1) ?? "");
156
- const participant = seat.id ? participantKey({ kind: seat.kind, id: seat.id, session }) : told.participant;
157
- const presence = { ...told, participant, at: new Date().toISOString() };
225
+ const arrive = (presence) => {
158
226
  here = foldPresence(here, [presence], Date.now(), ttl);
159
- return presence;
160
227
  };
161
- /*
162
- * WHAT A SEAT MAY SEE NEVER LEAVES THE STORE (FR-02). Every read below is
163
- * of the store as the asking seat sees it: its graph without what the
164
- * policy keeps from it, and its log with every op in its place and the
165
- * ones that touched what it may not see withheld (FR-16).
166
- */
167
- const seenFor = (principal) => seenBy(store, principal);
168
- // Kept from a seat: what its sight does not reach (FR-02), and the kinds of a module that is off (FR-12).
169
- const sighted = (principal) => hidesFrom(store, principal);
170
- /*
171
- * The ops after `seq`, as the seat sees them: the same ops `seenBy`'s log
172
- * holds after it (each op is withheld or not on its own), without
173
- * redacting the whole log for every push down every socket.
174
- */
175
- const since = (principal, seq) => {
176
- const after = store.log.opsFrom(Math.max(0, Math.floor(seq) + 1));
177
- return sighted(principal) ? redact(after, seesId(store, principal)) : [...after];
228
+ const forget = (participant) => {
229
+ here = new Map(here);
230
+ here.delete(participant);
178
231
  };
179
- const lastSeq = () => store.log.length - 1;
180
- /*
181
- * WHERE THE LOG BEGINS, when it was compacted behind an undo horizon
182
- * (FR-23): a client hydrating on the state is handed the tail, and its
183
- * log begins where the server's does. Said only when it is past 0, so a
184
- * store that was never compacted answers exactly as before.
185
- */
186
- const horizonOf = () => (store.log.horizon > 0 ? { horizon: store.log.horizon } : {});
187
- /*
188
- * EVERY FIELD'S REVISION (FR-05): the seq of the op that last wrote it,
189
- * read off the log once and kept current as ops land. A call that says
190
- * it saw an older one is a stale write, refused by name.
191
- */
192
- const revisions = FieldRevisions.of(store.log.all());
193
- const conflictsOf = (author, calls, base) => {
194
- if (!Array.isArray(base) || base.length === 0)
195
- return [];
196
- const sees = sighted(author) ? seesId(store, author) : () => true;
197
- // A record the seat may not see is not there to have moved: the call itself is refused for naming it.
198
- const claimed = base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number" && sees(entry.node));
199
- const stale = revisions.stale(claimed);
200
- if (stale.length === 0)
201
- return [];
202
- /*
203
- * A conflict is a choice — keep theirs, or put yours over it — and only
204
- * a call that could still land offers one. A call the policy refuses,
205
- * or one that no longer runs on the graph as it is (somebody finished
206
- * it first), is refused for that, in its own sentence.
207
- */
208
- if (store.policy && calls.some((call) => !store.permits(call, author).ok))
209
- return [];
210
- const yours = new Map();
211
- try {
212
- for (const primitive of store.previewAll(calls).primitives) {
213
- if (primitive.op === "patch-node")
214
- for (const [field, value] of Object.entries(primitive.after))
215
- yours.set(`${primitive.id}\u0000${field}`, isUnset(value) ? undefined : value);
216
- }
217
- }
218
- catch {
219
- return [];
220
- }
221
- return stale.map((entry) => {
222
- const rev = revisions.of(entry.node, entry.field);
223
- const wrote = rev >= store.log.horizon ? store.log.opsFrom(rev)[0] : undefined;
224
- const shown = wrote && sighted(author) ? redact([wrote], sees)[0] : wrote;
225
- return {
226
- node: entry.node,
227
- field: entry.field,
228
- theirs: store.graph.getNode(entry.node)?.[entry.field],
229
- yours: yours.get(`${entry.node}\u0000${entry.field}`),
230
- by: shown?.author.name ?? shown?.author.id ?? "Someone",
231
- rev,
232
- saw: entry.rev,
233
- };
234
- });
232
+ const announce = (presence, ttlMs = VISITOR_PRESENCE_TTL_MS) => {
233
+ const now = Date.now();
234
+ here = foldPresence(here, announcePresence([], presence, ttlMs, now), now, ttl);
235
+ tellWhoIsHere();
235
236
  };
236
- const whoFor = (principal, who) => (sighted(principal) ? presenceSeenBy(who, seesId(store, principal)) : [...who]);
237
237
  async function route(request) {
238
238
  if (request.method === "OPTIONS")
239
239
  return new Response(null, { status: 204, headers: CORS });
240
240
  const url = new URL(request.url, "http://localhost");
241
+ // Answered from the declaration served once any change under way is made (FR-43).
242
+ while (changing)
243
+ await changing;
244
+ const { store, wire, app, migrated } = serving;
245
+ /*
246
+ * WHICH DECLARATION, AND WHICH BUILD, ANSWERED (FR-43, FR-44): on every
247
+ * answer a poll reads, so a client without a socket learns the
248
+ * declaration changed — or that it runs another build — on its next one.
249
+ */
250
+ const answering = { version: app.version ?? 1, ...(options.build ? { build: options.build } : {}) };
241
251
  /*
242
252
  * WHO IS ASKING, OR NOTHING. Health is the only route a stranger gets:
243
253
  * it says whether the store is well, not what is in it.
244
254
  */
245
- if (!seatOf && url.pathname !== "/graview/health") {
246
- return send(401, {
247
- error: "This store cannot tell who is asking: the host gives serveStore a seatOf, or trusts the seat headers (trustSeatHeaders) on a server only it can reach.",
248
- });
249
- }
255
+ if (!seatOf && url.pathname !== "/graview/health")
256
+ return unknownSeat(CANNOT_TELL);
250
257
  const seat = async () => seatOf(request);
251
258
  if (url.pathname === LIVE_PATH) {
252
259
  return send(426, { error: `${LIVE_PATH} is a WebSocket: open one, say hello, and the store's ops come to you. A plain request polls /graview/since instead.` });
253
260
  }
261
+ /*
262
+ * WHAT A SEAT MAY SEE NEVER LEAVES THE STORE (FR-02). Every read below is
263
+ * of the store as the asking seat sees it: its graph without what the
264
+ * policy keeps from it, and its log with every op in its place and the
265
+ * ones that touched what it may not see withheld (FR-16).
266
+ */
254
267
  if (url.pathname === "/graview/state") {
255
- const seen = seenFor(await seat());
268
+ const seen = wire.seenFor(await seat());
256
269
  return send(200, {
257
- version: options.app.version ?? 1,
270
+ ...answering,
258
271
  snapshot: seen.snapshot(),
259
272
  log: seen.log.all(),
260
- migrated: opened.migrated.map((op) => op.intent),
261
- enabledModules: enabledModules(),
262
- ...horizonOf(),
273
+ migrated,
274
+ enabledModules: wire.enabledModules(),
275
+ ...wire.horizonOf(),
263
276
  });
264
277
  }
265
278
  if (url.pathname === "/graview/since") {
266
279
  const seq = Number(url.searchParams.get("seq") ?? "-1");
267
- return send(200, { ops: since(await seat(), seq) });
280
+ return send(200, { ops: wire.since(await seat(), seq), ...answering });
268
281
  }
269
282
  if (url.pathname === "/graview/who")
270
- return send(200, { who: whoFor(await seat(), alive()) });
283
+ return send(200, { who: wire.whoFor(await seat(), alive()) });
271
284
  if (url.pathname === "/graview/here" && request.method === "POST") {
272
285
  const body = (await read(request));
273
286
  if (!body.presence || typeof body.presence.participant !== "string" || typeof body.presence.stop !== "string") {
274
- return send(400, { error: "A presence is a participant and a stop." });
287
+ return send(400, { error: "A presence is a participant and a stop.", reason: "invalid" });
275
288
  }
276
289
  const asking = await seat();
277
- const mine = arrive(body.presence, asking);
290
+ const mine = presenceFrom(body.presence, asking);
291
+ arrive(mine);
278
292
  tellWhoIsHere();
279
293
  // Folded into the poll: the heartbeat carries back everybody else AND
280
294
  // the ops since, so being here costs no round trip of its own.
295
+ // `participant` is the key the server holds this poller under, so it can leave itself out (FR-47).
281
296
  return send(200, {
282
- who: whoFor(asking, alive().filter((presence) => presence.participant !== mine.participant)),
283
- ...(typeof body.seq === "number" ? { ops: since(asking, body.seq) } : {}),
297
+ participant: mine.participant,
298
+ who: wire.whoFor(asking, alive().filter((presence) => presence.participant !== mine.participant)),
299
+ ...(typeof body.seq === "number" ? { ops: wire.since(asking, body.seq) } : {}),
300
+ ...answering,
284
301
  });
285
302
  }
286
303
  if (url.pathname === "/graview/leave" && request.method === "POST") {
287
304
  const body = (await read(request));
288
- if (typeof body.participant === "string") {
289
- here = new Map(here);
290
- here.delete(body.participant);
305
+ const asking = await seat();
306
+ // Only your own: a seat says it has gone, never that somebody else has.
307
+ const own = asking.id ? `${asking.kind}:${asking.id}:` : "";
308
+ if (typeof body.participant === "string" && body.participant.startsWith(own)) {
309
+ forget(body.participant);
291
310
  tellWhoIsHere();
292
311
  }
293
- return send(200, { who: whoFor(await seat(), alive()) });
312
+ return send(200, { who: wire.whoFor(asking, alive()) });
294
313
  }
295
314
  if (url.pathname === "/graview/health") {
296
315
  return send(200, {
297
- ...health(store, options.app),
298
- // Said by the adapter where it knows, because it is the only thing
299
- // that does; `where` is for a caller with a better name for it.
300
- where: options.where ?? options.adapter.root ?? scope,
301
- adapter: options.adapter.name,
316
+ ...health(store, app),
317
+ where: options.where ?? app.name,
318
+ adapter: adapterName,
302
319
  });
303
320
  }
304
321
  if (url.pathname === "/graview/export")
305
- return send(200, exportBundle(options.app, seenFor(await seat())));
322
+ return send(200, exportBundle(app, wire.seenFor(await seat())));
306
323
  if (url.pathname === "/graview/ops" && request.method === "POST") {
307
- const body = (await read(request));
324
+ const text = await request.text();
325
+ const body = (text.length === 0 ? {} : JSON.parse(text));
308
326
  const calls = body.calls ?? [];
309
327
  const author = await seat();
310
- const via = typeof body.via === "string" && body.via.length > 0 ? body.via : "api";
328
+ // What the calls came through is the host's to say, never the body's (FR-52).
329
+ const via = await viaFor(request, author, "api");
330
+ // A batch already in the log is a call sent again after its answer was lost — or offered again on a new declaration, or after a reload (FR-43, FR-44): answered with what it made, as on the socket (FR-49).
331
+ const already = wire.answered(body.batch);
332
+ if (already.length > 0)
333
+ return send(200, { ops: wire.shown(author, already), batch: body.batch, ...answering });
334
+ /*
335
+ * THE HOST'S LIMITS, BEFORE ANYTHING IS JUDGED. Busy is 429 and the
336
+ * change is kept to send again (FR-45); a hard cap is refused, `limit`,
337
+ * and the change is taken back (FR-46).
338
+ */
339
+ const limited = options.limit
340
+ ? await options.limit({ seat: author, via, t: body.undo ? "undo" : "call", bytes: bytesOf(text), calls: body.undo ? [] : calls })
341
+ : undefined;
342
+ if (limited && "refuse" in limited)
343
+ return send(413, { error: limited.refuse, refused: true, reason: "limit", ...answering });
344
+ if (limited) {
345
+ const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
346
+ return send(429, { error: limited.sentence ?? `The store is busy: send it again in ${retryAfter} ms.`, busy: true, retryAfter }, { "retry-after": String(Math.ceil(retryAfter / 1000)) });
347
+ }
311
348
  /*
312
349
  * A STALE WRITE IS A CONFLICT, NOT A LOSS (FR-05). A field that moved
313
350
  * since the caller read it is refused by name — theirs and yours —
314
351
  * and nothing is written: what to do about it is the person's call.
315
352
  */
316
- const conflicts = body.undo ? [] : conflictsOf(author, calls, body.base);
353
+ const conflicts = body.undo ? [] : wire.conflictsOf(author, calls, body.base);
317
354
  if (conflicts.length > 0)
318
- return send(409, { error: conflictSentence(conflicts), refused: true, conflict: true, conflicts });
355
+ return send(409, { error: conflictSentence(conflicts), refused: true, conflict: true, conflicts, ...answering });
319
356
  try {
320
357
  /*
321
358
  * Through the STORE, under the requester's own seat. The policy
@@ -323,50 +360,49 @@ export async function createStoreHandler(options) {
323
360
  * refusal comes back with the policy's own sentence rather than a
324
361
  * bare 403, because that sentence is the product.
325
362
  */
326
- const result = body.undo
327
- ? store.undo(body.undo, { author, via, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}) })
328
- : store.applyAll(calls, {
329
- author,
330
- via,
331
- ...(body.intent ? { intent: body.intent } : {}),
332
- ...(body.batch ? { batch: body.batch } : {}),
333
- });
334
- await opened.flush();
363
+ const applying = { author, via, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}) };
364
+ const result = body.undo ? store.undo(body.undo, applying) : store.applyAll(calls, applying);
365
+ await flush();
335
366
  // An act may make what its own seat may not see: that op goes back withheld, as it would on a poll.
336
- const ops = sighted(author) ? redact(result.ops, seesId(store, author)) : result.ops;
337
- return send(200, { ops, batch: result.batch });
367
+ return send(200, { ops: wire.shown(author, result.ops), batch: result.batch, ...answering });
338
368
  }
339
369
  catch (error) {
340
- return send(409, { error: error instanceof Error ? error.message : String(error), refused: true });
370
+ const { sentence, ...why } = refusalOf(error);
371
+ return send(409, { error: sentence, refused: true, ...why, ...answering });
341
372
  }
342
373
  }
343
- return send(404, { error: `Nothing at ${url.pathname}` });
374
+ return send(404, { error: `Nothing at ${url.pathname}`, reason: "missing" });
344
375
  }
345
376
  const sockets = new Set();
346
- const say = (live, message) => {
347
- if (!live.open)
348
- return;
349
- try {
350
- live.socket.send(JSON.stringify(message));
351
- }
352
- catch {
353
- // A socket that cannot be written to is closing; its close is what forgets it.
354
- }
355
- };
356
- const push = (live) => {
357
- if (live.cursor >= lastSeq())
358
- return;
359
- const ops = since(live.seat, live.cursor);
360
- live.cursor = lastSeq();
361
- if (ops.length > 0)
362
- say(live, { t: "ops", seq: live.cursor, ops });
363
- };
364
- store.subscribe((_diff, ops) => {
365
- revisions.note(ops);
366
- for (const live of sockets)
367
- if (!live.answering)
368
- push(live);
377
+ const agentsFor = options.announceAgents === false ? 0 : typeof options.announceAgents === "number" ? options.announceAgents : VISITOR_PRESENCE_TTL_MS;
378
+ const watch = (store) => store.subscribe((_diff, ops) => {
379
+ serving.protocol.publish(ops, [...sockets].filter((live) => !live.answering));
380
+ if (agentsFor > 0)
381
+ agentsWereHere(ops);
369
382
  });
383
+ let unsubscribe = watch(serving.store);
384
+ /*
385
+ * AN AGENT THAT ACTED IS IN THE ROOM (FR-47), standing over the last
386
+ * thing it wrote: once per agent per change, and not at all for one that
387
+ * holds a socket here, which is in the room as itself already.
388
+ */
389
+ function agentsWereHere(ops) {
390
+ const last = new Map();
391
+ for (const op of ops)
392
+ if (op.author.kind === "agent")
393
+ last.set(`${op.author.id ?? ""}`, op);
394
+ let told = false;
395
+ for (const op of last.values()) {
396
+ const author = op.author;
397
+ if ([...sockets].some((live) => live.seat.kind === "agent" && live.seat.id === author.id))
398
+ continue;
399
+ const now = Date.now();
400
+ here = foldPresence(here, announcePresence([], visitorPresence(author, { over: op.writes[0] ?? null, now: new Date(now) }), agentsFor, now), now, ttl);
401
+ told = true;
402
+ }
403
+ if (told)
404
+ tellWhoIsHere();
405
+ }
370
406
  /*
371
407
  * A socket's presence stands while the socket does; the TTL is for a
372
408
  * poller that went quiet, and a socket that went quiet is closed.
@@ -386,56 +422,8 @@ export async function createStoreHandler(options) {
386
422
  function tellWhoIsHere() {
387
423
  if (sockets.size === 0)
388
424
  return;
389
- const who = standing();
390
- for (const live of sockets)
391
- say(live, { t: "presence", who: whoFor(live.seat, who.filter((presence) => presence.participant !== live.participant)) });
425
+ serving.protocol.tell(standing(), sockets);
392
426
  }
393
- /** A call or an undo from a socket: judged as its seat, exactly as `POST /graview/ops` judges it. */
394
- const answer = async (live, message) => {
395
- const cid = typeof message.cid === "string" ? message.cid : "";
396
- const author = live.seat;
397
- const via = typeof message.via === "string" && message.via.length > 0 ? message.via : "web";
398
- const intent = typeof message.intent === "string" && message.intent.length > 0 ? message.intent : undefined;
399
- const batch = typeof message.batch === "string" && message.batch.length > 0 ? message.batch : undefined;
400
- const shown = (ops) => (sighted(author) ? redact(ops, seesId(store, author)) : [...ops]);
401
- push(live);
402
- /*
403
- * SENT TWICE, ANSWERED ONCE. A client that lost its socket before the
404
- * ack sends the call again under the same batch; one already in the
405
- * log is answered with the ops it made.
406
- */
407
- const already = batch ? store.log.all().filter((op) => op.batch === batch) : [];
408
- if (already.length > 0) {
409
- say(live, { t: "ack", cid, seq: already.at(-1).seq, batch: batch, ops: shown(already) });
410
- return;
411
- }
412
- const calls = message.t === "call" && Array.isArray(message.calls) ? message.calls : [];
413
- if (message.t === "call") {
414
- const conflicts = conflictsOf(author, calls, message.base);
415
- if (conflicts.length > 0) {
416
- say(live, { t: "conflict", cid, sentence: conflictSentence(conflicts), conflicts });
417
- return;
418
- }
419
- }
420
- let result;
421
- live.answering = true;
422
- try {
423
- const applying = { author, via, ...(intent ? { intent } : {}), ...(batch ? { batch } : {}) };
424
- result = message.t === "undo" ? store.undo(Array.isArray(message.batches) ? message.batches : [], applying) : store.applyAll(calls, applying);
425
- }
426
- catch (error) {
427
- say(live, { t: "refused", cid, sentence: error instanceof Error ? error.message : String(error) });
428
- return;
429
- }
430
- finally {
431
- live.answering = false;
432
- }
433
- // Every op before this call's went down this socket before it landed; its own go in the ack.
434
- live.cursor = lastSeq();
435
- const ops = shown(result.ops);
436
- await opened.flush();
437
- say(live, { t: "ack", cid, seq: ops.at(-1)?.seq ?? live.cursor, batch: result.batch, ops });
438
- };
439
427
  /*
440
428
  * A page cannot set headers on a WebSocket. A store that trusts the seat
441
429
  * headers — loopback only — reads them from the upgrade's query instead,
@@ -457,85 +445,57 @@ export async function createStoreHandler(options) {
457
445
  }
458
446
  return found ? new Request(request.url, { headers }) : request;
459
447
  };
460
- async function connect(request, socket) {
461
- if (!seatOf) {
462
- return send(401, {
463
- error: "This store cannot tell who is asking: the host gives serveStore a seatOf, or trusts the seat headers (trustSeatHeaders) on a server only it can reach.",
464
- });
465
- }
466
- let seat;
448
+ async function seatFor(request) {
449
+ if (!seatOf)
450
+ return unknownSeat(CANNOT_TELL);
451
+ const asked = seatRequest(request);
467
452
  try {
468
- seat = await seatOf(seatRequest(request));
453
+ const seat = await seatOf(asked);
454
+ return serving.protocol.open(seat, await viaFor(asked, seat, "web"));
469
455
  }
470
456
  catch (error) {
471
- return send(401, { error: error instanceof Error ? error.message : String(error) });
457
+ return unknownSeat(error instanceof Error ? error.message : String(error));
472
458
  }
473
- const live = { seat, socket, cursor: Number.POSITIVE_INFINITY, answering: false, open: true };
474
- const leave = () => {
475
- if (!live.participant)
476
- return;
477
- here = new Map(here);
478
- here.delete(live.participant);
479
- delete live.participant;
480
- tellWhoIsHere();
459
+ }
460
+ async function connect(request, socket) {
461
+ const state = await seatFor(request);
462
+ if (state instanceof Response)
463
+ return state;
464
+ const live = {
465
+ ...state,
466
+ socket,
467
+ answering: false,
468
+ open: true,
469
+ send: (text) => {
470
+ if (live.open)
471
+ socket.send(text);
472
+ },
481
473
  };
482
474
  const hear = async (text) => {
483
- let message;
475
+ const was = live.participant;
476
+ live.answering = true;
477
+ let received;
484
478
  try {
485
- message = JSON.parse(text);
479
+ // A message that came while the declaration was changing is answered under the new one (FR-43).
480
+ while (changing)
481
+ await changing;
482
+ received = await serving.protocol.receive(live, text, standing());
486
483
  }
487
- catch {
488
- say(live, { t: "error", sentence: "A message on the live wire is one JSON object." });
489
- return;
484
+ finally {
485
+ live.answering = false;
490
486
  }
491
- if (!message || typeof message !== "object")
492
- return;
493
- switch (message.t) {
494
- case "hello": {
495
- const seq = typeof message.seq === "number" && Number.isFinite(message.seq) ? message.seq : undefined;
496
- sockets.add(live);
497
- live.cursor = lastSeq();
498
- if (seq === undefined) {
499
- const seen = seenFor(seat);
500
- say(live, {
501
- t: "welcome",
502
- protocol: WIRE_PROTOCOL,
503
- seq: live.cursor,
504
- ops: [],
505
- state: { version: options.app.version ?? 1, snapshot: seen.snapshot(), log: seen.log.all(), migrated: opened.migrated.map((op) => op.intent), enabledModules: enabledModules(), ...horizonOf() },
506
- });
507
- }
508
- else {
509
- say(live, { t: "welcome", protocol: WIRE_PROTOCOL, seq: live.cursor, ops: since(seat, seq) });
510
- }
511
- const who = standing().filter((presence) => presence.participant !== live.participant);
512
- if (who.length > 0)
513
- say(live, { t: "presence", who: whoFor(seat, who) });
514
- return;
515
- }
516
- case "call":
517
- case "undo":
518
- if (!sockets.has(live)) {
519
- say(live, { t: "refused", cid: String(message.cid ?? ""), sentence: "Say hello first: the live wire answers calls once it knows what the client has." });
520
- return;
521
- }
522
- return answer(live, message);
523
- case "here": {
524
- const told = message.presence;
525
- if (!told || typeof told.participant !== "string" || typeof told.stop !== "string") {
526
- say(live, { t: "error", sentence: "A presence is a participant and a stop." });
527
- return;
528
- }
529
- live.participant = arrive(told, seat).participant;
530
- tellWhoIsHere();
531
- return;
532
- }
533
- case "bye":
534
- leave();
535
- return;
536
- default:
537
- // A message this server does not know is ignored, never refused (docs/stability.md).
538
- return;
487
+ if (live.cursor !== undefined) {
488
+ sockets.add(live);
489
+ // What landed while this socket's own answer waited for its flush, after its ack.
490
+ serving.protocol.publish([], [live]);
491
+ }
492
+ if (received.presence) {
493
+ arrive(received.presence);
494
+ tellWhoIsHere();
495
+ }
496
+ else if (received.presence === null && was) {
497
+ forget(was);
498
+ tellWhoIsHere();
539
499
  }
540
500
  };
541
501
  /*
@@ -550,14 +510,49 @@ export async function createStoreHandler(options) {
550
510
  close() {
551
511
  live.open = false;
552
512
  sockets.delete(live);
553
- leave();
513
+ if (live.participant) {
514
+ forget(live.participant);
515
+ delete live.participant;
516
+ tellWhoIsHere();
517
+ }
554
518
  },
555
519
  };
556
520
  }
557
- return {
558
- store,
559
- opened,
521
+ /*
522
+ * THE DECLARATION CHANGED (FR-43). What is pending on the old store is
523
+ * written, the new store is opened (or handed over), and every socket is
524
+ * told by the protocol over the new one, which forgets their cursors: a
525
+ * seq of the old store means nothing on the new one. Meanwhile every
526
+ * request and message waits, so nothing lands on the store let go.
527
+ */
528
+ const swap = async (app, open) => {
529
+ while (changing)
530
+ await changing;
531
+ let done = () => { };
532
+ changing = new Promise((resolve) => (done = resolve));
533
+ try {
534
+ await flush();
535
+ const next = await open();
536
+ unsubscribe();
537
+ serving = serve(app, next.store, next.flush ?? serving.flush, next.migrated);
538
+ unsubscribe = watch(serving.store);
539
+ serving.protocol.declared(sockets);
540
+ }
541
+ finally {
542
+ changing = undefined;
543
+ done();
544
+ }
545
+ };
546
+ const handler = {
547
+ get store() {
548
+ return serving.store;
549
+ },
550
+ get protocol() {
551
+ return serving.protocol;
552
+ },
560
553
  connect,
554
+ seatFor,
555
+ announce,
561
556
  handle: async (request) => {
562
557
  try {
563
558
  return await route(request);
@@ -577,9 +572,10 @@ export async function createStoreHandler(options) {
577
572
  }
578
573
  }
579
574
  sockets.clear();
580
- await opened.flush();
581
- opened.close();
575
+ unsubscribe();
576
+ await flush();
582
577
  },
583
578
  };
579
+ return { handler, swap };
584
580
  }
585
581
  //# sourceMappingURL=handler.js.map