@graview/ship 0.1.3 → 0.1.5

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/remote.js CHANGED
@@ -1,4 +1,4 @@
1
- import { FieldRevisions, foldPresence, PRESENCE_TTL_MS, ReceiveError, refusalOf, REMOTE_PRESENCE_TTL_MS, samePresence, Store, WIRE_PROTOCOL, writtenBy, } from "@graview/core";
1
+ import { FieldRevisions, foldPresence, ReceiveError, refusalOf, REMOTE_PRESENCE_TTL_MS, samePresence, Store, WIRE_PROTOCOL, writtenBy, } from "@graview/core";
2
2
  import { LIVE_PATH, LIVE_SUBPROTOCOL, LIVE_WIRE } from "./live.js";
3
3
  import { SEAT_HEADERS } from "./seat-headers.js";
4
4
  /** A call this client let go of for a new declaration or a reload: not refused, so nothing is taken back or said. */
@@ -59,6 +59,15 @@ class Unreached extends Error {
59
59
  }
60
60
  /** What a gateway in front of a server says when the server behind it is not there. */
61
61
  const AWAY = new Set([502, 503, 504]);
62
+ /** A 503 that is the host saying it takes no changes for a while (reason `unavailable`), not a gateway saying it is away. */
63
+ async function unavailableSaid(response) {
64
+ try {
65
+ return (await response.clone().json()).reason === "unavailable";
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ }
62
71
  /**
63
72
  * Opens a store from a server and keeps it in step with it.
64
73
  *
@@ -73,22 +82,32 @@ function localIds() {
73
82
  return () => `local-${who}-${++at}`;
74
83
  }
75
84
  const OPEN = 1;
85
+ const freshWiring = () => ({
86
+ refusals: new Set(),
87
+ conflicts: new Set(),
88
+ statuses: new Set(),
89
+ builds: new Set(),
90
+ who: new Set(),
91
+ declarations: new Set(),
92
+ tally: { reconnects: 0, rebases: 0, conflicts: 0, resyncs: 0 },
93
+ });
76
94
  export async function openRemote(options) {
77
- return (await opening(options, takeCarried(options.carry), "This app was updated while your changes were on the way.")).remote;
95
+ return (await opening(options, takeCarried(options.carry), "This app was updated while your changes were on the way.", freshWiring())).remote;
78
96
  }
79
97
  /**
80
98
  * The remote store, and what the store it replaces needs from it: the
81
99
  * sentences about carried calls nobody has heard yet, for it to tell
82
100
  * when the new store's own listeners are not there (FR-43).
83
101
  */
84
- async function opening(options, offered, lostSaid) {
102
+ async function opening(options, offered, lostSaid, wiring) {
85
103
  const call = options.fetch ?? fetch;
86
104
  const headers = { "content-type": "application/json", ...(options.headers ?? {}) };
87
105
  // Who, and through what: a claim only a server that trusts the seat headers believes (FR-06, FR-52).
88
106
  const seat = { ...seatHeaders(options.principal), [SEAT_HEADERS.via]: options.via ?? "web" };
89
107
  Object.assign(headers, seat);
90
108
  const live = options.live === true;
91
- const presenceEveryMs = options.presenceEveryMs ?? PRESENCE_TTL_MS / 2;
109
+ /** Undefined: the socket says `here` only on a change, because the server holds it while the socket is open. */
110
+ const presenceEveryMs = options.presenceEveryMs;
92
111
  const visible = options.visible ?? pageVisible;
93
112
  /*
94
113
  * WHETHER THE SERVER IS BEING REACHED (FR-49), for a host's banner. Every
@@ -96,18 +115,22 @@ async function opening(options, offered, lostSaid) {
96
115
  * the socket says so on its welcome and when a welcomed socket drops.
97
116
  */
98
117
  let status = "connecting";
99
- const statusListeners = new Set();
100
- const tally = { reconnects: 0, rebases: 0, conflicts: 0, resyncs: 0 };
118
+ const statusListeners = wiring.statuses;
119
+ const tally = wiring.tally;
101
120
  /** Calls that could not reach the server, each waiting to be sent again once it is back. */
102
121
  const held = [];
103
122
  const become = (next) => {
104
- if (next === status)
123
+ if (next === status || retiring)
105
124
  return;
106
125
  if (status === "offline" && next === "online")
107
126
  tally.reconnects++;
108
127
  status = next;
109
- for (const told of statusListeners)
110
- told(next);
128
+ // A store that replaced another and comes online says nothing its listeners were not already told.
129
+ if (wiring.told !== next) {
130
+ wiring.told = next;
131
+ for (const told of [...statusListeners])
132
+ told(next);
133
+ }
111
134
  if (next === "online")
112
135
  for (const waiting of held.splice(0))
113
136
  waiting.again();
@@ -123,6 +146,11 @@ async function opening(options, offered, lostSaid) {
123
146
  become("offline");
124
147
  throw new Unreached(error instanceof Error ? error.message : String(error));
125
148
  }
149
+ // A host that takes no changes for a while is reached, and says so: not away (FR-46).
150
+ if (response.status === 503 && (await unavailableSaid(response))) {
151
+ become("online");
152
+ return response;
153
+ }
126
154
  if (AWAY.has(response.status)) {
127
155
  if (!socketReady())
128
156
  become("offline");
@@ -143,14 +171,16 @@ async function opening(options, offered, lostSaid) {
143
171
  if (!live)
144
172
  status = "online";
145
173
  const enabledModules = state.enabledModules ?? options.enabledModules;
174
+ // The app as the host judges it (`localApp`), so the browser refuses only what the server would.
175
+ const app = (options.localApp ? options.localApp(options.app) : options.app);
146
176
  const store = new Store({
147
- schema: options.app.schema,
148
- mutations: options.app.mutations ?? [],
149
- invariants: options.app.invariants ?? [],
150
- ...(options.app.policy ? { policy: options.app.policy } : {}),
151
- ...(options.app.modules ? { modules: options.app.modules } : {}),
177
+ schema: app.schema,
178
+ mutations: app.mutations ?? [],
179
+ invariants: app.invariants ?? [],
180
+ ...(app.policy ? { policy: app.policy } : {}),
181
+ ...(app.modules ? { modules: app.modules } : {}),
152
182
  ...(enabledModules ? { enabledModules } : {}),
153
- ...(options.app.intelligence ? { intelligence: options.app.intelligence } : {}),
183
+ ...(app.intelligence ? { intelligence: app.intelligence } : {}),
154
184
  /*
155
185
  * The snapshot AND the log: the snapshot is the graph, the log is the
156
186
  * history that led to it. Folding the log alone would lose whatever the
@@ -190,8 +220,13 @@ async function opening(options, offered, lostSaid) {
190
220
  /** The key the server holds this client under, as its welcome or its last `here` said (FR-47). */
191
221
  let self;
192
222
  let known = new Map();
193
- const whoListeners = new Set();
223
+ const whoListeners = wiring.who;
224
+ /** Set when a list of who is here arrives; read when a dropped socket's held presences lapse. */
225
+ let heardWho = false;
194
226
  const heard = (who) => {
227
+ if (retiring)
228
+ return;
229
+ heardWho = true;
195
230
  const next = foldPresence(new Map(), who, Date.now(), REMOTE_PRESENCE_TTL_MS, mine?.participant);
196
231
  // Never yourself, under the key you made or the one the server built for you.
197
232
  if (self !== undefined)
@@ -204,7 +239,7 @@ async function opening(options, offered, lostSaid) {
204
239
  known = next;
205
240
  if (!changed)
206
241
  return;
207
- for (const listener of whoListeners)
242
+ for (const listener of [...whoListeners])
208
243
  listener([...known.values()]);
209
244
  };
210
245
  /*
@@ -420,6 +455,8 @@ async function opening(options, offered, lostSaid) {
420
455
  * turn and goes again from there, and the posts behind it wait for it.
421
456
  */
422
457
  let lane = Promise.resolve();
458
+ /** How many times in a row the host said it takes no changes for a while: the backoff's attempt. */
459
+ let unavailableTries = 0;
423
460
  const post = (body, mine) => {
424
461
  const turn = lane.then(() => posted(body, mine));
425
462
  lane = turn.catch(() => { });
@@ -454,15 +491,24 @@ async function opening(options, offered, lostSaid) {
454
491
  continue;
455
492
  }
456
493
  answer = (await response.json().catch(() => ({})));
457
- if (response.status !== 429 || closed)
458
- break;
459
494
  /*
460
- * BUSY, NOT REFUSED (FR-45): the host asked for it again later. The
461
- * change stays shown and pending, and goes again after the wait.
495
+ * ONE WAY TO WAIT, IN THE POST LANE. Not for a while (FR-46): a 503
496
+ * whose reason is `unavailable` — the host takes no changes now and
497
+ * cannot say how long — waits a backoff, as a reconnect would. Busy
498
+ * (FR-45): a 429 waits what it asks, `Retry-After` read in seconds and
499
+ * a JSON `retryAfter` in milliseconds (`retryAfterMs`). Either way the
500
+ * change stays shown and pending, refused by nobody, and goes again.
462
501
  */
463
- const header = Number(response.headers.get("retry-after"));
464
- const wait = typeof answer.retryAfter === "number" ? answer.retryAfter : Number.isFinite(header) && header > 0 ? header * 1000 : 1000;
465
- await new Promise((later) => setTimeout(later, Math.max(0, wait)));
502
+ let wait;
503
+ if (response.status === 503 && answer.reason === "unavailable" && !closed)
504
+ wait = backoffFor(options.backoff, unavailableTries++);
505
+ else {
506
+ unavailableTries = 0;
507
+ if (response.status !== 429 || closed)
508
+ break;
509
+ wait = retryAfterMs(response.headers.get("retry-after"), answer.retryAfter);
510
+ }
511
+ await new Promise((later) => setTimeout(later, wait));
466
512
  if (socketReady())
467
513
  return viaSocket(body, mine);
468
514
  }
@@ -534,7 +580,8 @@ async function opening(options, offered, lostSaid) {
534
580
  const sayWhere = (force = false) => {
535
581
  if (!mine || !socketReady() || !visible())
536
582
  return;
537
- if (!force && said && samePresence(mine, said) && Date.now() - saidAt < presenceEveryMs)
583
+ // Unchanged: said again only on a heartbeat the host opted into. The server holds it while the socket is open.
584
+ if (!force && said && samePresence(mine, said) && (presenceEveryMs === undefined || Date.now() - saidAt < presenceEveryMs))
538
585
  return;
539
586
  if (say({ t: "here", presence: mine })) {
540
587
  said = mine;
@@ -568,8 +615,16 @@ async function opening(options, offered, lostSaid) {
568
615
  const viaSocket = (body, mine) => new Promise((resolve, reject) => {
569
616
  const cid = mine ?? `send-${++counter}`;
570
617
  const message = body.undo
571
- ? { t: "undo", cid, batches: body.undo, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}) }
572
- : { t: "call", cid, calls: body.calls ?? [], ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}), ...(body.base?.length ? { base: body.base } : {}) };
618
+ ? { t: "undo", cid, batches: body.undo, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}), ...(body.via ? { via: body.via } : {}) }
619
+ : {
620
+ t: "call",
621
+ cid,
622
+ calls: body.calls ?? [],
623
+ ...(body.intent ? { intent: body.intent } : {}),
624
+ ...(body.batch ? { batch: body.batch } : {}),
625
+ ...(body.base?.length ? { base: body.base } : {}),
626
+ ...(body.via ? { via: body.via } : {}),
627
+ };
573
628
  waiting.set(cid, { message, ...(mine !== undefined ? { mine } : {}), resolve, reject });
574
629
  // Behind calls the host asked to wait: it goes with them.
575
630
  if (busy.size > 0) {
@@ -618,6 +673,7 @@ async function opening(options, offered, lostSaid) {
618
673
  return;
619
674
  }
620
675
  waiting.delete(message.cid);
676
+ unavailableTries = 0;
621
677
  if (waiter.mine !== undefined) {
622
678
  batches.set(waiter.mine, message.batch);
623
679
  settle(waiter.mine);
@@ -631,6 +687,11 @@ async function opening(options, offered, lostSaid) {
631
687
  const waiter = waiting.get(message.cid);
632
688
  if (!waiter)
633
689
  return;
690
+ // Not for a while, and not final (FR-46): kept, and sent again after a backoff, with every call made behind it.
691
+ if (message.t === "refused" && message.reason === "unavailable") {
692
+ hold(message.cid, backoffFor(options.backoff, unavailableTries++));
693
+ return;
694
+ }
634
695
  waiting.delete(message.cid);
635
696
  waiter.reject(message.t === "conflict"
636
697
  ? new StaleWrite(message.sentence, message.conflicts ?? [])
@@ -657,6 +718,19 @@ async function opening(options, offered, lostSaid) {
657
718
  case "reload":
658
719
  reloadOntoNewer(typeof message.reason === "string" ? message.reason : "This app was updated.");
659
720
  return;
721
+ case "error":
722
+ // The host lost who this socket is: a new socket's upgrade tells it again, and what was not answered is sent again there.
723
+ if (message.reopen === true && socket) {
724
+ const was = socket;
725
+ dropped(was);
726
+ try {
727
+ was.close(1000, "Opening again.");
728
+ }
729
+ catch {
730
+ // Already closing.
731
+ }
732
+ }
733
+ return;
660
734
  default:
661
735
  return;
662
736
  }
@@ -664,14 +738,13 @@ async function opening(options, offered, lostSaid) {
664
738
  /* ── SKEW AND CHANGE (FR-43, FR-44) ─────────────────────────────────── */
665
739
  /** Set once this store has been let go of, for a new declaration or a reload: it acts on nothing more. */
666
740
  let retiring = false;
667
- const declarationListeners = new Set();
668
- const buildListeners = new Set();
669
- let otherBuild;
741
+ const declarationListeners = wiring.declarations;
742
+ const buildListeners = wiring.builds;
670
743
  const noticeBuild = (build) => {
671
- if (otherBuild !== undefined || !options.build || typeof build !== "string" || build.length === 0 || build === options.build)
744
+ if (retiring || wiring.otherBuild !== undefined || !options.build || typeof build !== "string" || build.length === 0 || build === options.build)
672
745
  return;
673
- otherBuild = build;
674
- for (const listener of buildListeners)
746
+ wiring.otherBuild = build;
747
+ for (const listener of [...buildListeners])
675
748
  listener(build);
676
749
  };
677
750
  /** Every call this client applied that the server has not answered, oldest first; and how many undos are. */
@@ -681,7 +754,7 @@ async function opening(options, offered, lostSaid) {
681
754
  for (const batch of pending) {
682
755
  const made = asked.get(batch);
683
756
  if (made)
684
- carried.push({ calls: made.calls, ...(made.intent ? { intent: made.intent } : {}), batch });
757
+ carried.push({ calls: made.calls, ...(made.intent ? { intent: made.intent } : {}), ...(made.via ? { via: made.via } : {}), batch });
685
758
  else
686
759
  undos++;
687
760
  }
@@ -704,6 +777,8 @@ async function opening(options, offered, lostSaid) {
704
777
  clearTimeout(retry);
705
778
  if (busyTimer)
706
779
  clearTimeout(busyTimer);
780
+ if (lapse)
781
+ clearTimeout(lapse);
707
782
  // A post waiting for the server to be reached again goes with the rest instead.
708
783
  for (const waiting of held.splice(0))
709
784
  waiting.give(superseded);
@@ -737,11 +812,12 @@ async function opening(options, offered, lostSaid) {
737
812
  const standing = mine;
738
813
  retire("The app was changed.");
739
814
  try {
740
- const app = await resolveApp(version);
741
- const next = await opening({ ...options, app }, carried, "The app was changed while your changes were on the way.");
815
+ const resolved = await resolveApp(version);
816
+ // The host's wiring goes with it: its listeners, the counters, the build it was told of.
817
+ const next = await opening({ ...options, app: resolved }, carried, "The app was changed while your changes were on the way.", wiring);
742
818
  if (standing)
743
819
  next.remote.presence.here(standing);
744
- for (const listener of declarationListeners)
820
+ for (const listener of [...declarationListeners])
745
821
  listener(next.remote, version);
746
822
  const said = [...(undos > 0 ? [refused(undosSaid(undos, "The app was changed"))] : []), ...next.unheard()];
747
823
  for (const refusal of said)
@@ -805,7 +881,7 @@ async function opening(options, offered, lostSaid) {
805
881
  return;
806
882
  // From the last op this client has: the welcome brings exactly the ones after it.
807
883
  // Which codec, which protocol and which build this page speaks (FR-44).
808
- made.send(JSON.stringify({ t: "hello", seq: seen, protocol: WIRE_PROTOCOL, wire: LIVE_WIRE, ...(options.build ? { build: options.build.slice(0, 64) } : {}) }));
884
+ made.send(JSON.stringify({ t: "hello", seq: seen, protocol: WIRE_PROTOCOL, wire: LIVE_WIRE, ...(options.build ? { build: options.build.slice(0, 64) } : {}), ...(options.hostProtocol !== undefined ? { hostProtocol: options.hostProtocol } : {}) }));
809
885
  };
810
886
  made.onmessage = (event) => {
811
887
  if (socket !== made)
@@ -819,22 +895,51 @@ async function opening(options, offered, lostSaid) {
819
895
  }
820
896
  hear(message);
821
897
  };
822
- made.onclose = () => {
823
- if (socket !== made)
824
- return;
825
- const dropped = welcomed;
826
- socket = undefined;
827
- welcomed = false;
828
- said = null;
829
- // A socket that never opened says nothing a poll does not; one that was up and dropped is the server gone.
830
- if (dropped)
831
- become("offline");
832
- reconnect();
833
- };
898
+ made.onclose = () => dropped(made);
834
899
  made.onerror = () => {
835
900
  // The close follows; that is where reconnecting is decided.
836
901
  };
837
902
  };
903
+ /*
904
+ * WHAT A DROPPED SOCKET WAS TOLD STANDS NO LONGER ON THE SERVER'S WORD. A
905
+ * presence held by somebody's socket stands while the server lists it,
906
+ * and this client hears the server no longer. Unless a list comes within
907
+ * `REMOTE_PRESENCE_TTL_MS` — a welcome after a reconnect, a poll — the
908
+ * held ones are let go, as a word that old would be.
909
+ */
910
+ let lapse;
911
+ const lapseHeld = () => {
912
+ heardWho = false;
913
+ if (lapse)
914
+ clearTimeout(lapse);
915
+ lapse = setTimeout(() => {
916
+ lapse = undefined;
917
+ if (heardWho || closed)
918
+ return;
919
+ const kept = new Map([...known].filter(([, presence]) => presence.held !== "socket"));
920
+ if (kept.size === known.size)
921
+ return;
922
+ known = kept;
923
+ for (const listener of whoListeners)
924
+ listener([...known.values()]);
925
+ }, REMOTE_PRESENCE_TTL_MS);
926
+ lapse.unref?.();
927
+ };
928
+ /** A socket gone — closed, or one the host no longer knows: forgotten, and another opened after a backoff. */
929
+ function dropped(made) {
930
+ if (socket !== made)
931
+ return;
932
+ const wasUp = welcomed;
933
+ socket = undefined;
934
+ welcomed = false;
935
+ said = null;
936
+ // A socket that never opened says nothing a poll does not; one that was up and dropped is the server gone.
937
+ if (wasUp) {
938
+ become("offline");
939
+ lapseHeld();
940
+ }
941
+ reconnect();
942
+ }
838
943
  const reconnect = () => {
839
944
  if (closed)
840
945
  return;
@@ -858,12 +963,19 @@ async function opening(options, offered, lostSaid) {
858
963
  */
859
964
  const appliedAll = store.applyAll.bind(store);
860
965
  const undone = store.undo.bind(store);
861
- const refusals = new Set();
966
+ /*
967
+ * A PREVIEW IS JUDGED AS ITS APPLY WOULD BE (FR-56): as whoever is at this
968
+ * keyboard, by default, as `applyAll` below is. It goes nowhere — it is a
969
+ * rehearsal on this browser's store, and nothing of it is kept or sent.
970
+ */
971
+ const previewedAll = store.previewAll.bind(store);
972
+ store.previewAll = ((calls, previewOptions) => previewedAll(calls, { ...(options.principal ? { author: options.principal } : {}), ...previewOptions }));
973
+ const refusals = wiring.refusals;
862
974
  /** What became of carried calls before anybody listened: told to the first listener (FR-43, FR-44). */
863
975
  let unheard = [];
864
976
  /** A change of this client's that did not survive a new declaration or a reload: `invalid`, it no longer fits (FR-46). */
865
977
  const refused = (sentence) => ({ reason: "invalid", sentence });
866
- const conflictListeners = new Set();
978
+ const conflictListeners = wiring.conflicts;
867
979
  /** Set while `useMine` sends a change again: it goes without the revisions it was refused for. */
868
980
  let overriding = false;
869
981
  /*
@@ -912,7 +1024,7 @@ async function opening(options, offered, lostSaid) {
912
1024
  chosen = true;
913
1025
  overriding = true;
914
1026
  try {
915
- store.applyAll(made.calls, made.intent ? { intent: made.intent } : {});
1027
+ store.applyAll(made.calls, { ...(made.intent ? { intent: made.intent } : {}), ...(made.via ? { via: made.via } : {}) });
916
1028
  }
917
1029
  finally {
918
1030
  overriding = false;
@@ -956,7 +1068,7 @@ async function opening(options, offered, lostSaid) {
956
1068
  });
957
1069
  pending.push(result.batch);
958
1070
  provisional.add(result.batch);
959
- asked.set(result.batch, { calls, ...(applyOptions?.intent ? { intent: applyOptions.intent } : {}) });
1071
+ asked.set(result.batch, { calls, ...(applyOptions?.intent ? { intent: applyOptions.intent } : {}), ...(applyOptions?.via ? { via: applyOptions.via } : {}) });
960
1072
  // The revision of each field this changes, as this browser saw it — unless the person chose theirs over it.
961
1073
  const base = overriding ? [] : revisions.baseFor(result.ops, earlier);
962
1074
  answers.set(result.batch, track(transmit({
@@ -964,6 +1076,7 @@ async function opening(options, offered, lostSaid) {
964
1076
  ...(applyOptions?.intent ? { intent: applyOptions.intent } : {}),
965
1077
  batch: result.batch,
966
1078
  ...(base.length > 0 ? { base } : {}),
1079
+ ...(applyOptions?.via ? { via: applyOptions.via } : {}),
967
1080
  }, result.batch).catch((error) => takeBack(result.batch, error))));
968
1081
  return result;
969
1082
  });
@@ -992,6 +1105,7 @@ async function opening(options, offered, lostSaid) {
992
1105
  undo: ids.map((id) => batches.get(id) ?? id),
993
1106
  ...(undoOptions?.intent ? { intent: undoOptions.intent } : {}),
994
1107
  batch: result.batch,
1108
+ ...(undoOptions?.via ? { via: undoOptions.via } : {}),
995
1109
  }, result.batch))
996
1110
  .catch((error) => takeBack(result.batch, error))));
997
1111
  return result;
@@ -1014,6 +1128,9 @@ async function opening(options, offered, lostSaid) {
1014
1128
  },
1015
1129
  onWho(listener) {
1016
1130
  whoListeners.add(listener);
1131
+ // Told at once who is here already: a host that subscribes after the welcome is not shown an empty room.
1132
+ if (known.size > 0)
1133
+ listener([...known.values()]);
1017
1134
  return () => {
1018
1135
  whoListeners.delete(listener);
1019
1136
  };
@@ -1065,7 +1182,7 @@ async function opening(options, offered, lostSaid) {
1065
1182
  if (one.batch !== undefined && landed.has(one.batch))
1066
1183
  continue;
1067
1184
  try {
1068
- store.applyAll(one.calls, { ...(one.intent ? { intent: one.intent } : {}), ...(one.batch ? { batch: one.batch } : {}) });
1185
+ store.applyAll(one.calls, { ...(one.intent ? { intent: one.intent } : {}), ...(one.batch ? { batch: one.batch } : {}), ...(one.via ? { via: one.via } : {}) });
1069
1186
  }
1070
1187
  catch (error) {
1071
1188
  lost.push(named(one, error));
@@ -1095,8 +1212,8 @@ async function opening(options, offered, lostSaid) {
1095
1212
  },
1096
1213
  onBuild(listener) {
1097
1214
  buildListeners.add(listener);
1098
- if (otherBuild !== undefined)
1099
- listener(otherBuild);
1215
+ if (wiring.otherBuild !== undefined)
1216
+ listener(wiring.otherBuild);
1100
1217
  return () => buildListeners.delete(listener);
1101
1218
  },
1102
1219
  onConflict(listener) {
@@ -1113,6 +1230,7 @@ async function opening(options, offered, lostSaid) {
1113
1230
  return () => statusListeners.delete(listener);
1114
1231
  },
1115
1232
  counters: () => ({ ...tally }),
1233
+ who: () => [...known.values()],
1116
1234
  pending: () => pending.length + sendsOut,
1117
1235
  async settled() {
1118
1236
  // Whatever is in flight now — and whatever a settling handler put in flight after it.
@@ -1129,6 +1247,8 @@ async function opening(options, offered, lostSaid) {
1129
1247
  clearTimeout(retry);
1130
1248
  if (busyTimer)
1131
1249
  clearTimeout(busyTimer);
1250
+ if (lapse)
1251
+ clearTimeout(lapse);
1132
1252
  for (const waiting of held.splice(0))
1133
1253
  waiting.give(new Error("The client closed before the server could be reached."));
1134
1254
  const was = socket;
@@ -1171,6 +1291,35 @@ async function opening(options, offered, lostSaid) {
1171
1291
  return protocols.length > 0 ? new Socket(withSeat.toString(), protocols) : new Socket(withSeat.toString());
1172
1292
  }
1173
1293
  }
1294
+ /**
1295
+ * HOW LONG A 429 ASKS TO WAIT, IN MILLISECONDS (FR-45). The `Retry-After`
1296
+ * header is read as HTTP says — delta SECONDS, or an HTTP date — and the
1297
+ * JSON `retryAfter` as ship documents it, MILLISECONDS, the finer of the
1298
+ * two. A JSON wait under 50 beside a header that says the same number of
1299
+ * seconds is a host that said seconds in the body too (`retryAfter: 2`,
1300
+ * `Retry-After: 2` — two "milliseconds" is a retry storm, not a wait): the
1301
+ * header wins. Ship's own handler says a short wait as, say, 30 in the body
1302
+ * and 1 in the header, which is read as the 30 ms it means. Neither said:
1303
+ * a second.
1304
+ */
1305
+ function retryAfterMs(header, json, now = Date.now()) {
1306
+ let fromHeader;
1307
+ const said = header?.trim();
1308
+ if (said) {
1309
+ if (/^\d+(\.\d+)?$/.test(said))
1310
+ fromHeader = Number(said) * 1000;
1311
+ else {
1312
+ const date = Date.parse(said);
1313
+ if (Number.isFinite(date))
1314
+ fromHeader = Math.max(0, date - now);
1315
+ }
1316
+ }
1317
+ const fromJson = typeof json === "number" && Number.isFinite(json) && json >= 0 ? json : undefined;
1318
+ const secondsInTheBody = fromJson !== undefined && fromJson < 50 && fromHeader !== undefined && Math.abs(fromJson * 1000 - fromHeader) < 1000;
1319
+ if (fromJson !== undefined && !secondsInTheBody)
1320
+ return fromJson;
1321
+ return fromHeader ?? 1000;
1322
+ }
1174
1323
  /** The page's own reload, where there is a page. */
1175
1324
  function pageReload() {
1176
1325
  globalThis.location?.reload?.();