@graview/ship 0.1.2 → 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.
Files changed (46) hide show
  1. package/README.md +312 -13
  2. package/dist/browser.d.ts +4 -4
  3. package/dist/browser.d.ts.map +1 -1
  4. package/dist/browser.js +2 -2
  5. package/dist/browser.js.map +1 -1
  6. package/dist/handler.d.ts +192 -26
  7. package/dist/handler.d.ts.map +1 -1
  8. package/dist/handler.js +383 -340
  9. package/dist/handler.js.map +1 -1
  10. package/dist/health.d.ts +12 -1
  11. package/dist/health.d.ts.map +1 -1
  12. package/dist/health.js +15 -4
  13. package/dist/health.js.map +1 -1
  14. package/dist/index.d.ts +7 -5
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +3 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/live-protocol.d.ts +451 -0
  19. package/dist/live-protocol.d.ts.map +1 -0
  20. package/dist/live-protocol.js +957 -0
  21. package/dist/live-protocol.js.map +1 -0
  22. package/dist/live.d.ts +156 -9
  23. package/dist/live.d.ts.map +1 -1
  24. package/dist/live.js +31 -1
  25. package/dist/live.js.map +1 -1
  26. package/dist/remote.d.ts +180 -5
  27. package/dist/remote.d.ts.map +1 -1
  28. package/dist/remote.js +793 -76
  29. package/dist/remote.js.map +1 -1
  30. package/dist/runtime.d.ts +7 -5
  31. package/dist/runtime.d.ts.map +1 -1
  32. package/dist/runtime.js +3 -2
  33. package/dist/runtime.js.map +1 -1
  34. package/dist/seat-headers.d.ts +6 -0
  35. package/dist/seat-headers.d.ts.map +1 -1
  36. package/dist/seat-headers.js +6 -0
  37. package/dist/seat-headers.js.map +1 -1
  38. package/dist/serve.d.ts +5 -3
  39. package/dist/serve.d.ts.map +1 -1
  40. package/dist/serve.js +18 -4
  41. package/dist/serve.js.map +1 -1
  42. package/dist/websocket.d.ts +1 -1
  43. package/dist/websocket.d.ts.map +1 -1
  44. package/dist/websocket.js +10 -2
  45. package/dist/websocket.js.map +1 -1
  46. package/package.json +3 -3
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, nextExpiry, PRESENCE_TTL_MS, 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 { LIVE_PATH } from "./live.js";
5
+ import { announcePresence, liveProtocol, presenceFrom, presenceSeenBy, seatOfTab, serverBatchIds, 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` the asking seat already landed is answered with the ops it made, and one that is somebody else's or not `batch:<tag>:<n>` is refused `invalid`; 409 with the policy's sentence and a `reason` when refused, 429 with `Retry-After` when the host is busy, 503 with the reason `unavailable` when it takes no changes for a while" },
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,138 @@ 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 } : {}),
132
+ // What the handler's store lands itself is in a batch no client could have named first.
133
+ storeOptions: { batchIds: serverBatchIds() },
136
134
  });
137
- const store = opened.store;
138
- /** Which modules are on, as the state says it (FR-12). */
139
- const enabledModules = () => [...store.modules.enabled].sort();
135
+ let opened = (await opening(options.app));
136
+ const { adapter, seed: _seed, scope: _scope, enabledModules: _modules, ...rest } = options;
137
+ const { handler, swap } = storeHandler({
138
+ ...rest,
139
+ store: opened.store,
140
+ flush: () => opened.flush(),
141
+ migrated: opened.migrated.map((op) => op.intent),
142
+ // Said by the adapter where it knows, because it is the only thing
143
+ // that does; `where` is for a caller with a better name for it.
144
+ where: options.where ?? adapter.root ?? scope,
145
+ }, adapter.name);
146
+ return {
147
+ ...handler,
148
+ get store() {
149
+ return handler.store;
150
+ },
151
+ get protocol() {
152
+ return handler.protocol;
153
+ },
154
+ get opened() {
155
+ return opened;
156
+ },
157
+ /*
158
+ * OPENED AGAIN, ON THE NEW DECLARATION. What is pending is written
159
+ * first, then the adapter is read again by `openStore`, which runs the
160
+ * migrations between the stored version and the new one — here, once,
161
+ * as it did at the start — while every request and message waits.
162
+ */
163
+ async declarationChanged(change) {
164
+ await swap(change.app, async () => {
165
+ if (change.store)
166
+ return { store: change.store, ...(change.flush ? { flush: change.flush } : {}), migrated: change.migrated ?? [] };
167
+ await opened.flush();
168
+ opened.close();
169
+ opened = await opening(change.app);
170
+ return { store: opened.store, flush: () => opened.flush(), migrated: opened.migrated.map((op) => op.intent) };
171
+ });
172
+ },
173
+ async close() {
174
+ await handler.close();
175
+ opened.close();
176
+ },
177
+ };
178
+ }
179
+ function storeHandler(options, adapterName = "held by the host") {
180
+ const seatOf = options.seatOf ?? (options.trustSeatHeaders ? seatFromHeaders : undefined);
181
+ const flush = async (landed = []) => {
182
+ await serving.flush?.(landed);
183
+ };
184
+ const serve = (app, store, flushing, migrated) => ({
185
+ app,
186
+ store,
187
+ flush: flushing,
188
+ migrated: [...migrated],
189
+ wire: wireOf(store),
190
+ protocol: liveProtocol({
191
+ store,
192
+ version: app.version ?? 1,
193
+ migrated,
194
+ // Only a flush the host has: one without pushes every op the moment it lands.
195
+ ...(flushing ? { flush: (landed) => flushing(landed) } : {}),
196
+ ...(options.build ? { build: options.build } : {}),
197
+ ...(options.minProtocol !== undefined ? { minProtocol: options.minProtocol } : {}),
198
+ ...(options.minHostProtocol !== undefined ? { minHostProtocol: options.minHostProtocol } : {}),
199
+ ...(options.viaClaimed ? { viaOf: options.viaClaimed } : {}),
200
+ ...(options.seatOfKey ? { seatOf: options.seatOfKey } : {}),
201
+ ...(options.refusal ? { refusal: options.refusal } : {}),
202
+ ...(options.withheldKey !== undefined ? { withheldKey: options.withheldKey } : {}),
203
+ ...(options.limit ? { limit: options.limit } : {}),
204
+ ...(options.admit ? { admit: options.admit } : {}),
205
+ }),
206
+ });
207
+ let serving = serve(options.app, options.store, options.flush, options.migrated ?? []);
208
+ /** Set while the declaration is being changed: every request and message waits for it. */
209
+ let changing;
210
+ /*
211
+ * THE CHANNEL IS THE HOST'S WORD (FR-52). `viaOf` when the host gave
212
+ * one; the via header when it trusts the seat headers; else what the
213
+ * route is. Never the client's body or message.
214
+ */
215
+ const viaFor = async (request, seat, otherwise) => {
216
+ const said = options.viaOf ? await options.viaOf(request, seat) : undefined;
217
+ if (typeof said === "string" && said.length > 0)
218
+ return said;
219
+ const header = options.trustSeatHeaders ? request.headers.get(SEAT_HEADERS.via) : null;
220
+ return header && header.length > 0 ? header : otherwise;
221
+ };
140
222
  /*
141
223
  * WHO IS HERE. Keyed by participant, named by the seat the request
142
224
  * carries — a poster cannot claim to be somebody else's seat — and
@@ -149,224 +231,207 @@ export async function createStoreHandler(options) {
149
231
  here = foldPresence(here, [], Date.now(), ttl);
150
232
  return [...here.values()];
151
233
  };
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() };
234
+ const arrive = (presence) => {
158
235
  here = foldPresence(here, [presence], Date.now(), ttl);
159
- return presence;
160
236
  };
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];
237
+ const forget = (participant) => {
238
+ here = new Map(here);
239
+ here.delete(participant);
240
+ };
241
+ const announce = (presence, ttlMs = VISITOR_PRESENCE_TTL_MS) => {
242
+ const now = Date.now();
243
+ here = foldPresence(here, announcePresence([], presence, ttlMs, now), now, ttl);
244
+ tellWhoIsHere();
245
+ watchVisitors();
178
246
  };
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
247
  /*
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.
248
+ * A VISITOR WHOSE TIME IS UP IS SAID TO GO: a timer set by `nextExpiry`,
249
+ * so every socket is told when an announced visitor's `until` passes,
250
+ * with nothing else happening. A hibernating host sets its alarm the same way.
191
251
  */
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
- });
235
- };
236
- const whoFor = (principal, who) => (sighted(principal) ? presenceSeenBy(who, seesId(store, principal)) : [...who]);
252
+ let visitorsGo;
253
+ function watchVisitors() {
254
+ if (visitorsGo)
255
+ clearTimeout(visitorsGo);
256
+ visitorsGo = undefined;
257
+ const next = nextExpiry([...here.values()]);
258
+ if (next === undefined)
259
+ return;
260
+ visitorsGo = setTimeout(() => {
261
+ visitorsGo = undefined;
262
+ tellWhoIsHere();
263
+ watchVisitors();
264
+ }, Math.max(0, next - Date.now()) + 1);
265
+ visitorsGo.unref?.();
266
+ }
237
267
  async function route(request) {
238
268
  if (request.method === "OPTIONS")
239
269
  return new Response(null, { status: 204, headers: CORS });
240
270
  const url = new URL(request.url, "http://localhost");
271
+ // Answered from the declaration served once any change under way is made (FR-43).
272
+ while (changing)
273
+ await changing;
274
+ const { store, wire, app } = serving;
275
+ /*
276
+ * WHICH DECLARATION, AND WHICH BUILD, ANSWERED (FR-43, FR-44): on every
277
+ * answer a poll reads, so a client without a socket learns the
278
+ * declaration changed — or that it runs another build — on its next one.
279
+ */
280
+ const buildOf = (seat, via) => (typeof options.build === "function" ? options.build({ seat, via }) : options.build);
281
+ const answering = (seat) => {
282
+ const build = buildOf(seat, "api");
283
+ return { version: app.version ?? 1, ...(build ? { build } : {}) };
284
+ };
241
285
  /*
242
286
  * WHO IS ASKING, OR NOTHING. Health is the only route a stranger gets:
243
287
  * it says whether the store is well, not what is in it.
244
288
  */
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
- }
289
+ if (!seatOf && url.pathname !== "/graview/health")
290
+ return unknownSeat(CANNOT_TELL);
250
291
  const seat = async () => seatOf(request);
251
292
  if (url.pathname === LIVE_PATH) {
252
293
  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
294
  }
254
- if (url.pathname === "/graview/state") {
255
- const seen = seenFor(await seat());
256
- return send(200, {
257
- version: options.app.version ?? 1,
258
- snapshot: seen.snapshot(),
259
- log: seen.log.all(),
260
- migrated: opened.migrated.map((op) => op.intent),
261
- enabledModules: enabledModules(),
262
- ...horizonOf(),
263
- });
264
- }
295
+ /*
296
+ * WHAT A SEAT MAY SEE NEVER LEAVES THE STORE (FR-02). Every read below is
297
+ * of the store as the asking seat sees it: its graph without what the
298
+ * policy keeps from it, and its log with every op in its place and the
299
+ * ones that touched what it may not see withheld (FR-16).
300
+ */
301
+ // The routes with semantics are the protocol's, so a host that routes its own requests answers them the same (`post`, `state`, `since`).
302
+ const asked = async (otherwise) => {
303
+ const author = await seat();
304
+ const via = await viaFor(request, author, otherwise);
305
+ const build = buildOf(author, via);
306
+ return { seat: author, via, ...(build ? { build } : {}) };
307
+ };
308
+ const answered = (answer) => send(answer.status, answer.body, answer.headers);
309
+ if (url.pathname === "/graview/state")
310
+ return answered(serving.protocol.state(await asked("api")));
265
311
  if (url.pathname === "/graview/since") {
266
312
  const seq = Number(url.searchParams.get("seq") ?? "-1");
267
- return send(200, { ops: since(await seat(), seq) });
313
+ return answered(serving.protocol.since(seq, await asked("api")));
268
314
  }
269
315
  if (url.pathname === "/graview/who")
270
- return send(200, { who: whoFor(await seat(), alive()) });
316
+ return send(200, { who: wire.whoFor(await seat(), alive()) });
271
317
  if (url.pathname === "/graview/here" && request.method === "POST") {
272
318
  const body = (await read(request));
273
319
  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." });
320
+ return send(400, { error: "A presence is a participant and a stop.", reason: "invalid" });
275
321
  }
276
322
  const asking = await seat();
277
- const mine = arrive(body.presence, asking);
323
+ const mine = presenceFrom(body.presence, asking);
324
+ arrive(mine);
278
325
  tellWhoIsHere();
279
326
  // Folded into the poll: the heartbeat carries back everybody else AND
280
327
  // the ops since, so being here costs no round trip of its own.
328
+ // `participant` is the key the server holds this poller under, so it can leave itself out (FR-47).
281
329
  return send(200, {
282
- who: whoFor(asking, alive().filter((presence) => presence.participant !== mine.participant)),
283
- ...(typeof body.seq === "number" ? { ops: since(asking, body.seq) } : {}),
330
+ participant: mine.participant,
331
+ who: wire.whoFor(asking, alive().filter((presence) => presence.participant !== mine.participant)),
332
+ ...(typeof body.seq === "number" ? { ops: wire.since(asking, body.seq) } : {}),
333
+ ...answering(asking),
284
334
  });
285
335
  }
286
336
  if (url.pathname === "/graview/leave" && request.method === "POST") {
287
337
  const body = (await read(request));
288
- if (typeof body.participant === "string") {
289
- here = new Map(here);
290
- here.delete(body.participant);
338
+ const asking = await seat();
339
+ // Only your own: a seat says it has gone, never that somebody else has.
340
+ const own = asking.id ? `${asking.kind}:${asking.id}:` : "";
341
+ if (typeof body.participant === "string" && body.participant.startsWith(own)) {
342
+ forget(body.participant);
291
343
  tellWhoIsHere();
292
344
  }
293
- return send(200, { who: whoFor(await seat(), alive()) });
345
+ return send(200, { who: wire.whoFor(asking, alive()) });
294
346
  }
295
347
  if (url.pathname === "/graview/health") {
348
+ /*
349
+ * A STRANGER GETS HEALTH, AND NO ID (FR-55). The counts are the whole
350
+ * store's; the links it names are only those the asking seat may be
351
+ * told of — and somebody the host cannot tell is judged as a seat
352
+ * with no id and no roles, so a store with sights names them nothing.
353
+ */
354
+ let asking = { kind: "human" };
355
+ if (seatOf) {
356
+ try {
357
+ asking = await seat();
358
+ }
359
+ catch {
360
+ // A poller the host does not recognise is still told whether the store is well.
361
+ }
362
+ }
296
363
  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,
364
+ ...health(store, { seat: asking }),
365
+ where: options.where ?? app.name,
366
+ adapter: adapterName,
302
367
  });
303
368
  }
304
- if (url.pathname === "/graview/export")
305
- return send(200, exportBundle(options.app, seenFor(await seat())));
369
+ if (url.pathname === "/graview/export") {
370
+ const asking = await seat();
371
+ // The log as the seat sees it, withheld ops under their opaque batch, as on every other route.
372
+ return send(200, exportBundle(app, wire.seenFor(asking), { log: wire.seenLog(asking) }));
373
+ }
306
374
  if (url.pathname === "/graview/ops" && request.method === "POST") {
307
- const body = (await read(request));
308
- const calls = body.calls ?? [];
309
- const author = await seat();
310
- const via = typeof body.via === "string" && body.via.length > 0 ? body.via : "api";
311
- /*
312
- * A STALE WRITE IS A CONFLICT, NOT A LOSS (FR-05). A field that moved
313
- * since the caller read it is refused by name — theirs and yours —
314
- * and nothing is written: what to do about it is the person's call.
315
- */
316
- const conflicts = body.undo ? [] : conflictsOf(author, calls, body.base);
317
- if (conflicts.length > 0)
318
- return send(409, { error: conflictSentence(conflicts), refused: true, conflict: true, conflicts });
319
- try {
320
- /*
321
- * Through the STORE, under the requester's own seat. The policy
322
- * refuses here exactly what it refuses in the browser — and the
323
- * refusal comes back with the policy's own sentence rather than a
324
- * bare 403, because that sentence is the product.
325
- */
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();
335
- // 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 });
338
- }
339
- catch (error) {
340
- return send(409, { error: error instanceof Error ? error.message : String(error), refused: true });
341
- }
375
+ const text = await request.text();
376
+ // What the calls came through is the host's to say, never the body's (FR-52).
377
+ const answer = await serving.protocol.post(text, await asked("api"));
378
+ // Ops a failed flush had held back are durable now: down every socket.
379
+ if (answer.landed)
380
+ heldBackDurable();
381
+ return answered(answer);
342
382
  }
343
- return send(404, { error: `Nothing at ${url.pathname}` });
383
+ return send(404, { error: `Nothing at ${url.pathname}`, reason: "missing" });
344
384
  }
345
385
  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);
386
+ const agentsFor = options.announceAgents === false ? 0 : typeof options.announceAgents === "number" ? options.announceAgents : VISITOR_PRESENCE_TTL_MS;
387
+ const watch = (store) => store.subscribe((_diff, ops) => {
388
+ serving.protocol.publish(ops, [...sockets].filter((live) => !live.answering));
389
+ if (agentsFor > 0)
390
+ agentsWereHere(ops);
369
391
  });
392
+ let unsubscribe = watch(serving.store);
393
+ /*
394
+ * Every op is pushed as it lands — but one whose flush failed is held
395
+ * back from every socket until a flush holds it (`liveProtocol`'s
396
+ * `flush`). When one does, each socket is caught up from its cursor.
397
+ */
398
+ function heldBackDurable(except) {
399
+ serving.protocol.publish([], [...sockets].filter((live) => live !== except && !live.answering));
400
+ }
401
+ /*
402
+ * AN AGENT THAT ACTED IS IN THE ROOM (FR-47), standing over the last
403
+ * thing it wrote: once per agent per change, and not at all for one that
404
+ * holds a socket here, which is in the room as itself already.
405
+ */
406
+ function agentsWereHere(ops) {
407
+ const last = new Map();
408
+ for (const op of ops)
409
+ if (op.author.kind === "agent")
410
+ last.set(`${op.author.id ?? ""}`, op);
411
+ let told = false;
412
+ for (const op of last.values())
413
+ told = agentIsHere(op.author, { over: op.writes[0] ?? null }) || told;
414
+ if (told)
415
+ tellWhoIsHere();
416
+ }
417
+ /** Stands an agent seat in the room for `agentsFor`, unless it is not an agent, is held by a socket here, or the host said not to. */
418
+ function agentIsHere(author, standing = {}) {
419
+ if (agentsFor <= 0 || author.kind !== "agent")
420
+ return false;
421
+ // A socket keeps its seat, or the host's key for it (`seatKey`).
422
+ const seated = (live) => (typeof live.seat === "string" ? options.seatOfKey?.(live.seat) : live.seat);
423
+ if ([...sockets].some((live) => seated(live)?.kind === "agent" && seated(live)?.id === author.id))
424
+ return false;
425
+ const now = Date.now();
426
+ here = foldPresence(here, announcePresence([], visitorPresence(author, { ...standing, now: new Date(now) }), agentsFor, now), now, ttl);
427
+ // Said to go when its time is up, as an announced visitor is.
428
+ watchVisitors();
429
+ return true;
430
+ }
431
+ const onCall = (call) => {
432
+ if (agentIsHere(call.principal))
433
+ tellWhoIsHere();
434
+ };
370
435
  /*
371
436
  * A socket's presence stands while the socket does; the TTL is for a
372
437
  * poller that went quiet, and a socket that went quiet is closed.
@@ -386,56 +451,8 @@ export async function createStoreHandler(options) {
386
451
  function tellWhoIsHere() {
387
452
  if (sockets.size === 0)
388
453
  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)) });
454
+ serving.protocol.tell(standing(), sockets);
392
455
  }
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
456
  /*
440
457
  * A page cannot set headers on a WebSocket. A store that trusts the seat
441
458
  * headers — loopback only — reads them from the upgrade's query instead,
@@ -457,85 +474,72 @@ export async function createStoreHandler(options) {
457
474
  }
458
475
  return found ? new Request(request.url, { headers }) : request;
459
476
  };
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;
477
+ async function seatFor(request) {
478
+ if (!seatOf)
479
+ return unknownSeat(CANNOT_TELL);
480
+ const asked = seatRequest(request);
467
481
  try {
468
- seat = await seatOf(seatRequest(request));
482
+ const seat = await seatOf(asked);
483
+ const via = await viaFor(asked, seat, "web");
484
+ // The host's key for the seat, when it keeps one, and the build this socket is served by.
485
+ const build = typeof options.build === "function" ? options.build({ seat, via }) : undefined;
486
+ // The seat's key, never its tab's: a key made from the session would be one view per tab.
487
+ return serving.protocol.open(options.seatKey?.(seatOfTab(seat)) ?? seat, via, build ? { build } : {});
469
488
  }
470
489
  catch (error) {
471
- return send(401, { error: error instanceof Error ? error.message : String(error) });
490
+ return unknownSeat(error instanceof Error ? error.message : String(error));
472
491
  }
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();
492
+ }
493
+ async function connect(request, socket) {
494
+ const state = await seatFor(request);
495
+ if (state instanceof Response)
496
+ return state;
497
+ const live = {
498
+ ...state,
499
+ socket,
500
+ answering: false,
501
+ open: true,
502
+ send: (text) => {
503
+ if (live.open)
504
+ socket.send(text);
505
+ },
506
+ // A socket whose seat the host lost is closed, so its client opens a new one.
507
+ close: (code, reason) => {
508
+ if (!live.open)
509
+ return;
510
+ live.open = false;
511
+ sockets.delete(live);
512
+ socket.close?.(code, reason);
513
+ },
481
514
  };
482
515
  const hear = async (text) => {
483
- let message;
516
+ const was = live.participant;
517
+ live.answering = true;
518
+ let received;
484
519
  try {
485
- message = JSON.parse(text);
520
+ // A message that came while the declaration was changing is answered under the new one (FR-43).
521
+ while (changing)
522
+ await changing;
523
+ received = await serving.protocol.receive(live, text, standing(), sockets);
486
524
  }
487
- catch {
488
- say(live, { t: "error", sentence: "A message on the live wire is one JSON object." });
489
- return;
525
+ finally {
526
+ live.answering = false;
490
527
  }
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;
528
+ if (live.cursor !== undefined) {
529
+ sockets.add(live);
530
+ // What landed while this socket's own answer waited for its flush, after its ack.
531
+ serving.protocol.publish([], [live]);
532
+ }
533
+ // Ops a failed flush had held back are durable now: down every other socket too.
534
+ if (received.landed)
535
+ heldBackDurable(live);
536
+ if (received.presence) {
537
+ arrive(received.presence);
538
+ tellWhoIsHere();
539
+ }
540
+ else if (received.presence === null && was) {
541
+ forget(was);
542
+ tellWhoIsHere();
539
543
  }
540
544
  };
541
545
  /*
@@ -550,14 +554,50 @@ export async function createStoreHandler(options) {
550
554
  close() {
551
555
  live.open = false;
552
556
  sockets.delete(live);
553
- leave();
557
+ if (live.participant) {
558
+ forget(live.participant);
559
+ delete live.participant;
560
+ tellWhoIsHere();
561
+ }
554
562
  },
555
563
  };
556
564
  }
557
- return {
558
- store,
559
- opened,
565
+ /*
566
+ * THE DECLARATION CHANGED (FR-43). What is pending on the old store is
567
+ * written, the new store is opened (or handed over), and every socket is
568
+ * told by the protocol over the new one, which forgets their cursors: a
569
+ * seq of the old store means nothing on the new one. Meanwhile every
570
+ * request and message waits, so nothing lands on the store let go.
571
+ */
572
+ const swap = async (app, open) => {
573
+ while (changing)
574
+ await changing;
575
+ let done = () => { };
576
+ changing = new Promise((resolve) => (done = resolve));
577
+ try {
578
+ await flush();
579
+ const next = await open();
580
+ unsubscribe();
581
+ serving = serve(app, next.store, next.flush ?? serving.flush, next.migrated);
582
+ unsubscribe = watch(serving.store);
583
+ serving.protocol.declared(sockets);
584
+ }
585
+ finally {
586
+ changing = undefined;
587
+ done();
588
+ }
589
+ };
590
+ const handler = {
591
+ get store() {
592
+ return serving.store;
593
+ },
594
+ get protocol() {
595
+ return serving.protocol;
596
+ },
560
597
  connect,
598
+ seatFor,
599
+ announce,
600
+ onCall,
561
601
  handle: async (request) => {
562
602
  try {
563
603
  return await route(request);
@@ -567,6 +607,8 @@ export async function createStoreHandler(options) {
567
607
  }
568
608
  },
569
609
  async close() {
610
+ if (visitorsGo)
611
+ clearTimeout(visitorsGo);
570
612
  for (const live of sockets) {
571
613
  live.open = false;
572
614
  try {
@@ -577,9 +619,10 @@ export async function createStoreHandler(options) {
577
619
  }
578
620
  }
579
621
  sockets.clear();
580
- await opened.flush();
581
- opened.close();
622
+ unsubscribe();
623
+ await flush();
582
624
  },
583
625
  };
626
+ return { handler, swap };
584
627
  }
585
628
  //# sourceMappingURL=handler.js.map