@mmstack/mesh 22.9.1 → 22.10.0

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.
@@ -1,7 +1,7 @@
1
1
  import { createWatch } from '@angular/core/primitives/signals';
2
2
  import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource, throttled } from '@mmstack/primitives/core';
3
3
  import { MESH_PROTO_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
4
- import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef, effect, untracked } from '@angular/core';
4
+ import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef, untracked, effect } from '@angular/core';
5
5
 
6
6
  const RECONNECT_BASE_MS = 500;
7
7
  function meshSession(opt) {
@@ -22,6 +22,7 @@ function meshSession(opt) {
22
22
  // a refusal asks for a fresh snapshot; one hello per burst, cleared by the welcome it earns
23
23
  let rehydrating = false;
24
24
  let peers = new Map();
25
+ let members;
25
26
  let presenceData;
26
27
  let hasPresence = false;
27
28
  let transport = null;
@@ -68,6 +69,8 @@ function meshSession(opt) {
68
69
  transport = null;
69
70
  peers = new Map();
70
71
  hooks.onPeers?.(peers);
72
+ members = undefined;
73
+ hooks.onMembers?.(members);
71
74
  setStatus(state, reason);
72
75
  };
73
76
  const sendEnv = (env) => {
@@ -80,6 +83,9 @@ function meshSession(opt) {
80
83
  transport?.send({ t: 'env', room: opt.room, env: out });
81
84
  };
82
85
  const sendHello = () => {
86
+ if (!transport)
87
+ return;
88
+ hooks.onOrigin?.(sync.origin);
83
89
  transport?.send({
84
90
  t: 'hello',
85
91
  room: opt.room,
@@ -148,6 +154,10 @@ function meshSession(opt) {
148
154
  rehydrating = false;
149
155
  peers = new Map(msg.peers.map((p) => [p.origin, p]));
150
156
  hooks.onPeers?.(peers);
157
+ members = [
158
+ ...new Set(msg.members.filter((origin) => origin !== sync.origin)),
159
+ ];
160
+ hooks.onMembers?.(members);
151
161
  const resync = msg.mode === 'snapshot' || instanceChanged;
152
162
  if (msg.mode === 'delta') {
153
163
  for (const env of msg.envs)
@@ -204,6 +214,17 @@ function meshSession(opt) {
204
214
  hooks.onPeers?.(peers);
205
215
  return;
206
216
  }
217
+ case 'member': {
218
+ if (members === undefined || msg.origin === sync.origin)
219
+ return;
220
+ members = msg.gone
221
+ ? members.filter((origin) => origin !== msg.origin)
222
+ : members.includes(msg.origin)
223
+ ? members
224
+ : [...members, msg.origin];
225
+ hooks.onMembers?.(members);
226
+ return;
227
+ }
207
228
  case 'eject':
208
229
  if (msg.writer === opt.writer)
209
230
  terminal('ejected', msg.reason);
@@ -241,11 +262,19 @@ function meshSession(opt) {
241
262
  const t = opt.transport();
242
263
  transport = t;
243
264
  unsubs = [
244
- t.onMessage(handle),
265
+ t.onMessage((msg) => {
266
+ if (closed || transport !== t || msg.room !== opt.room)
267
+ return;
268
+ handle(msg);
269
+ if (!closed || msg.t === 'reject' || msg.t === 'eject')
270
+ hooks.onMessage?.(msg);
271
+ }),
245
272
  t.onClose(() => {
246
273
  if (closed || transport !== t)
247
274
  return;
248
275
  transport = null;
276
+ members = undefined;
277
+ hooks.onMembers?.(members);
249
278
  setStatus('reconnecting');
250
279
  const delay = Math.min(opt.reconnect?.maxDelayMs ?? 15_000, RECONNECT_BASE_MS * 2 ** attempts++);
251
280
  reconnectTimer = schedule.set(() => {
@@ -289,6 +318,10 @@ function meshSession(opt) {
289
318
  unackedEnvs: () => [...unacked.values()],
290
319
  instance: () => instance,
291
320
  peers: () => peers,
321
+ sendSignal: (msg) => {
322
+ if (!closed && msg.room === opt.room)
323
+ transport?.send(msg);
324
+ },
292
325
  setPresence: (data) => {
293
326
  presenceData = data;
294
327
  hasPresence = true;
@@ -564,6 +597,41 @@ function meshSync(source, opt) {
564
597
  const injector = opt.injector ?? inject(Injector);
565
598
  const status = signal('connecting', /* @ts-ignore */
566
599
  ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
600
+ const origin = signal(null, /* @ts-ignore */
601
+ ...(ngDevMode ? [{ debugName: "origin" }] : /* istanbul ignore next */ []));
602
+ const members = signal([], /* @ts-ignore */
603
+ ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
604
+ let membership;
605
+ // the last roster the links on the port were given; a socket drop blanks the session's, not this
606
+ let roster = [];
607
+ const signalingListeners = new Set();
608
+ let earlySignals = [];
609
+ // the ICE servers of the last welcome, for peer links that attach after it
610
+ let welcomeIce;
611
+ const deliverSignal = (cb, msg) => {
612
+ try {
613
+ cb(msg);
614
+ }
615
+ catch {
616
+ // A failed peer link must never interrupt the room's sync session or other listeners.
617
+ }
618
+ };
619
+ const signalMessage = (msg) => {
620
+ if (msg.t === 'welcome')
621
+ welcomeIce = msg.ice;
622
+ if (msg.t === 'welcome' && earlySignals !== null)
623
+ earlySignals = [];
624
+ if (msg.t === 'member' && msg.gone && earlySignals !== null) {
625
+ earlySignals = earlySignals.filter((held) => held.t !== 'signal' || held.from !== msg.origin);
626
+ }
627
+ if (msg.t === 'signal' &&
628
+ earlySignals !== null &&
629
+ earlySignals.length < 256) {
630
+ earlySignals.push(msg);
631
+ }
632
+ for (const cb of [...signalingListeners])
633
+ deliverSignal(cb, msg);
634
+ };
567
635
  const lastReason = signal(undefined, /* @ts-ignore */
568
636
  ...(ngDevMode ? [{ debugName: "lastReason" }] : /* istanbul ignore next */ []));
569
637
  const lastSyncedAt = signal(undefined, /* @ts-ignore */
@@ -593,6 +661,8 @@ function meshSync(source, opt) {
593
661
  switch (status()) {
594
662
  case 'live':
595
663
  return { status: 'live', lastSyncedAt: at, ...extra };
664
+ case 'waiting':
665
+ return { status: 'waiting', lastSyncedAt: at, ...extra };
596
666
  case 'ejected': {
597
667
  const reason = lastReason();
598
668
  return reason && OUTDATED_REASONS.has(reason)
@@ -604,20 +674,27 @@ function meshSync(source, opt) {
604
674
  }
605
675
  }, /* @ts-ignore */
606
676
  ...(ngDevMode ? [{ debugName: "health" }] : /* istanbul ignore next */ []));
607
- // Created lazily: with a persisted outbox we must adopt the stored origin BEFORE minting anything
677
+ // Created lazily: with a persisted outbox the slot lock and the restored tail come first, so the
678
+ // engine never mints before it knows the generation it is in
608
679
  let sync;
609
680
  let session;
610
681
  let started = false;
611
682
  let closed = false;
612
683
  let pendingPresence;
613
684
  let persistTimer;
685
+ let pendingPersist;
614
686
  let releaseLock;
615
687
  let cancelLock;
688
+ // this tab owns the persisted slot ('off', no Web Locks, or a granted lock); an ephemeral boot never does
689
+ let durable = false;
690
+ // the slot's clock high-water as restored: persisted back until this boot mints its own stamp
691
+ let restoredClock;
692
+ // resolves when the store has the payload (a failed write resolves too: persistence is best-effort)
616
693
  const doPersist = () => {
617
- if (closed || !opt.outbox || !started || !session)
618
- return;
694
+ if (closed || !opt.outbox || !started || !session || !durable)
695
+ return Promise.resolve(); // ephemeral: never writes
619
696
  const instance = session.instance();
620
- const clock = sync.lastStamp();
697
+ const clock = sync.lastStamp() ?? restoredClock;
621
698
  const payload = {
622
699
  origin: sync.origin,
623
700
  version: sync.watermark()[sync.origin] ?? 0,
@@ -626,25 +703,42 @@ function meshSync(source, opt) {
626
703
  floors: sync.floors(),
627
704
  ...(clock ? { clock } : {}),
628
705
  };
629
- void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));
706
+ const { store, key } = opt.outbox;
707
+ // Capture before queueing: teardown clears the session's tail immediately after this call.
708
+ const write = () => {
709
+ try {
710
+ return Promise.resolve(store.set(key, payload)).then(() => undefined, () => undefined);
711
+ }
712
+ catch {
713
+ return Promise.resolve(); // a failed save must not block later saves or lock release
714
+ }
715
+ };
716
+ // Keep the idle path synchronous, but never let an older save land after a newer one.
717
+ const pending = pendingPersist ? pendingPersist.then(write) : write();
718
+ pendingPersist = pending;
719
+ void pending.then(() => {
720
+ if (pendingPersist === pending)
721
+ pendingPersist = undefined;
722
+ });
723
+ return pending;
630
724
  };
631
- // coalesce outbox writes; `immediate` forces a synchronous-path write (first boot, teardown)
725
+ // coalesce outbox writes; `immediate` bypasses the debounce, but waits for earlier saves
632
726
  const persistOutbox = (immediate = false) => {
633
727
  if (!opt.outbox)
634
- return;
728
+ return Promise.resolve();
635
729
  if (immediate) {
636
730
  if (persistTimer !== undefined)
637
731
  clearTimeout(persistTimer);
638
732
  persistTimer = undefined;
639
- doPersist();
640
- return;
733
+ return doPersist();
641
734
  }
642
- if (persistTimer !== undefined)
643
- return;
644
- persistTimer = setTimeout(() => {
645
- persistTimer = undefined;
646
- doPersist();
647
- }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);
735
+ if (persistTimer === undefined) {
736
+ persistTimer = setTimeout(() => {
737
+ persistTimer = undefined;
738
+ void doPersist();
739
+ }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);
740
+ }
741
+ return Promise.resolve(); // the debounced path is not awaited
648
742
  };
649
743
  const dropLocks = () => {
650
744
  cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown
@@ -663,6 +757,7 @@ function meshSync(source, opt) {
663
757
  const initCore = (restore) => {
664
758
  if (closed)
665
759
  return;
760
+ restoredClock = restore?.clock;
666
761
  sync = opSync(source, {
667
762
  writer: opt.writer,
668
763
  instance: restore?.instance,
@@ -677,6 +772,8 @@ function meshSync(source, opt) {
677
772
  },
678
773
  });
679
774
  started = true;
775
+ // set once this session ends: only then are the links riding on its port retired
776
+ let ended = false;
680
777
  session = meshSession({
681
778
  room: opt.room,
682
779
  writer: opt.writer,
@@ -690,6 +787,28 @@ function meshSync(source, opt) {
690
787
  instance: restore?.instance,
691
788
  reconnect: opt.reconnect,
692
789
  hooks: {
790
+ onOrigin: (value) => origin.set(value),
791
+ onMembers: (value) => {
792
+ membership = value;
793
+ members.set(value ?? []);
794
+ if (value !== undefined) {
795
+ roster = value;
796
+ return;
797
+ }
798
+ if (earlySignals !== null)
799
+ earlySignals = [];
800
+ // Peer links outlive a socket drop: the next welcome re-lists who is still there. A
801
+ // borrowed port has no close of its own, so the session's end retires them here, from
802
+ // the last roster the links saw (a drop before the close already blanked the session's).
803
+ if (!ended)
804
+ return;
805
+ const retired = roster;
806
+ roster = [];
807
+ for (const origin of retired) {
808
+ signalMessage({ t: 'member', room: opt.room, origin, gone: true });
809
+ }
810
+ },
811
+ onMessage: signalMessage,
693
812
  onRefused: (env, reason) => {
694
813
  refused.update((n) => n + 1);
695
814
  opt.onRefused?.(env, reason);
@@ -710,16 +829,25 @@ function meshSync(source, opt) {
710
829
  onSynced: () => lastSyncedAt.set(Date.now()),
711
830
  onPeers: (map) => peerMap.set(map),
712
831
  onOutboxChange: () => {
713
- persistOutbox();
832
+ void persistOutbox();
714
833
  acked.set(!session?.hasUnacked());
715
834
  },
716
835
  onTerminal: () => {
717
- dropLocks();
836
+ ended = true;
718
837
  // latched: the tail is about to be dropped from the session, but it was never
719
838
  // acknowledged, so the answer to "is everything I wrote in the room" stays no
720
839
  if (session?.hasUnacked())
721
840
  acked.set(false);
722
- persistOutbox(true); // save the still-unacked tail for the next boot before dropping it
841
+ // save the still-unacked tail for the next boot, and release the lock only once the store
842
+ // has it: a successor granted earlier could restore the slot before this write lands
843
+ let saved;
844
+ try {
845
+ saved = persistOutbox(true);
846
+ }
847
+ catch {
848
+ saved = Promise.resolve(); // a failed capture must still hand the slot on
849
+ }
850
+ void saved.finally(dropLocks);
723
851
  },
724
852
  onLocalReject: (violation) => {
725
853
  if (isDevMode()) {
@@ -728,7 +856,11 @@ function meshSync(source, opt) {
728
856
  },
729
857
  },
730
858
  });
731
- if (restore && (restore.envs.length > 0 || restore.version > 0)) {
859
+ if (restore &&
860
+ (restore.envs.length > 0 ||
861
+ restore.version > 0 ||
862
+ (restore.floors?.length ?? 0) > 0 ||
863
+ restore.clock !== undefined)) {
732
864
  const kept = restore.envs.filter(restorable);
733
865
  const dropped = restore.envs.length - kept.length;
734
866
  if (dropped > 0) {
@@ -739,7 +871,7 @@ function meshSync(source, opt) {
739
871
  }
740
872
  sync.restore(kept, restore.version, restore.floors, restore.clock); // → the session's subscribe repopulates its unacked tail for resend
741
873
  }
742
- persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe
874
+ void persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe
743
875
  if (pendingPresence) {
744
876
  session.setPresence(pendingPresence.data);
745
877
  pendingPresence = undefined;
@@ -750,7 +882,7 @@ function meshSync(source, opt) {
750
882
  const connection = {
751
883
  status: computed(() => {
752
884
  const s = status();
753
- return s === 'connecting'
885
+ return s === 'connecting' || s === 'waiting'
754
886
  ? 'loading'
755
887
  : s === 'reconnecting'
756
888
  ? 'reloading'
@@ -758,7 +890,9 @@ function meshSync(source, opt) {
758
890
  ? 'error'
759
891
  : 'resolved';
760
892
  }),
761
- isLoading: computed(() => status() === 'connecting' || status() === 'reconnecting'),
893
+ isLoading: computed(() => status() === 'connecting' ||
894
+ status() === 'waiting' ||
895
+ status() === 'reconnecting'),
762
896
  hasValue: () => true,
763
897
  };
764
898
  runInInjectionContext(injector, () => registerResource(connection, { suspends: opt.register === 'suspend' }));
@@ -779,6 +913,7 @@ function meshSync(source, opt) {
779
913
  injector.get(DestroyRef).onDestroy(teardown);
780
914
  // Load the persisted outbox, then boot with the adopted origin. A fresh/unreadable slot boots clean.
781
915
  const bootFromDisk = async () => {
916
+ durable = true; // every caller owns the slot
782
917
  if (closed || !opt.outbox)
783
918
  return;
784
919
  let saved;
@@ -805,33 +940,63 @@ function meshSync(source, opt) {
805
940
  }
806
941
  else {
807
942
  const locks = globalThis.navigator?.locks;
943
+ const mode = opt.outbox.crossTab ?? 'queue';
808
944
  if (!locks) {
809
945
  if (isDevMode()) {
810
- console.warn('[@mmstack/mesh] outbox crossTab:"queue" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock. Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:"off" to silence this.');
946
+ console.warn(`[@mmstack/mesh] outbox crossTab:"${mode}" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock ('queue' and 'ephemeral' both own the slot). Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:"off" to silence this.`);
811
947
  }
812
948
  void bootFromDisk();
949
+ return;
813
950
  }
814
- else {
951
+ const name = `@mmstack/mesh:outbox:${opt.outbox.key}`;
952
+ // hold a granted lock until teardown resolves this promise
953
+ const hold = (queued = false) => {
954
+ cancelLock = undefined; // granted — no longer abortable, only releasable
955
+ if (closed)
956
+ return Promise.resolve();
957
+ if (queued)
958
+ status.set('connecting'); // the wait ends with the grant
959
+ return new Promise((release) => {
960
+ releaseLock = release;
961
+ void bootFromDisk();
962
+ });
963
+ };
964
+ const queueUp = () => {
965
+ status.set('waiting');
815
966
  const abort = new AbortController();
816
967
  cancelLock = () => abort.abort();
817
968
  void locks
818
- .request(`@mmstack/mesh:outbox:${opt.outbox.key}`, { mode: 'exclusive', signal: abort.signal }, () => {
819
- cancelLock = undefined; // granted — no longer abortable, only releasable
820
- if (closed)
821
- return Promise.resolve();
822
- // hold the lock until teardown resolves this promise
823
- return new Promise((release) => {
824
- releaseLock = release;
825
- void bootFromDisk();
826
- });
827
- })
969
+ .request(name, { mode: 'exclusive', signal: abort.signal }, () => hold(true))
828
970
  .catch((e) => {
829
971
  // an aborted request is our own teardown; any other failure → degrade to no-lock
830
- if (!closed && e?.name !== 'AbortError') {
972
+ if (!closed &&
973
+ !started &&
974
+ e?.name !== 'AbortError') {
975
+ status.set('connecting'); // no longer waiting on anyone
831
976
  void bootFromDisk();
832
977
  }
833
978
  });
834
- }
979
+ };
980
+ // Web Locks forbids `signal` together with `ifAvailable`, hence the probe first
981
+ void locks
982
+ .request(name, { mode: 'exclusive', ifAvailable: true }, (lock) => {
983
+ if (lock === null) {
984
+ // another tab owns the slot
985
+ if (closed)
986
+ return Promise.resolve();
987
+ if (mode === 'ephemeral') {
988
+ initCore(); // live at once on a fresh origin; never reads or writes the slot
989
+ return Promise.resolve();
990
+ }
991
+ queueUp();
992
+ return Promise.resolve();
993
+ }
994
+ return hold();
995
+ })
996
+ .catch(() => {
997
+ if (!closed && !started)
998
+ void bootFromDisk(); // a broken lock manager degrades to no-lock
999
+ });
835
1000
  }
836
1001
  };
837
1002
  if (opt.whenReady) {
@@ -844,6 +1009,21 @@ function meshSync(source, opt) {
844
1009
  }
845
1010
  return {
846
1011
  status: status.asReadonly(),
1012
+ origin: origin.asReadonly(),
1013
+ members: members.asReadonly(),
1014
+ signaling: {
1015
+ members: () => membership,
1016
+ iceServers: () => welcomeIce,
1017
+ send: (msg) => session?.sendSignal(msg),
1018
+ onMessage: (cb) => {
1019
+ signalingListeners.add(cb);
1020
+ const held = earlySignals ?? [];
1021
+ earlySignals = null;
1022
+ for (const msg of held)
1023
+ deliverSignal(cb, msg);
1024
+ return () => signalingListeners.delete(cb);
1025
+ },
1026
+ },
847
1027
  health,
848
1028
  acked: acked.asReadonly(),
849
1029
  whenAcked: () => (session ? session.whenAcked() : Promise.resolve()), // nothing written yet
@@ -985,16 +1165,202 @@ function directTransport(relay, ctx) {
985
1165
  };
986
1166
  }
987
1167
 
1168
+ /** The starting value: nothing listed. */
1169
+ const emptyLifecycle = new Map();
1170
+ /** The value after `close`; `step` recognises it by identity and ignores every later event. */
1171
+ const closedLifecycle = new Map();
1172
+ const hasPeer = (e) => e?.state === 'linking' || e?.state === 'open';
1173
+ const hasTimer = (e) => e?.state === 'linking' || e?.state === 'waiting';
1174
+ /**
1175
+ * Builds now for a listed origin with no peer; keeps an existing one. The open timeout is
1176
+ * armed before the build so a link that opens while it is being built cancels it.
1177
+ */
1178
+ const listOne = (s, origin, effects) => {
1179
+ const cur = s.get(origin);
1180
+ if (hasPeer(cur))
1181
+ return;
1182
+ if (cur)
1183
+ effects.push({ t: 'disarm', origin });
1184
+ effects.push({ t: 'armOpen', origin }, { t: 'build', origin });
1185
+ s.set(origin, {
1186
+ state: 'linking',
1187
+ attempt: cur?.attempt ?? 0,
1188
+ stalled: cur?.stalled ?? false,
1189
+ });
1190
+ };
1191
+ const unlistOne = (s, origin, effects) => {
1192
+ const cur = s.get(origin);
1193
+ if (!cur)
1194
+ return;
1195
+ if (hasPeer(cur))
1196
+ effects.push({ t: 'drop', origin });
1197
+ effects.push({ t: 'disarm', origin });
1198
+ s.delete(origin);
1199
+ };
1200
+ const none$1 = (s) => ({ next: s, effects: [] });
1201
+ /** One transition. Pure and total: an event that does not apply returns `s` and no effects. */
1202
+ function step(s, e) {
1203
+ if (s === closedLifecycle)
1204
+ return none$1(s);
1205
+ const effects = [];
1206
+ const next = new Map(s);
1207
+ switch (e.t) {
1208
+ case 'listed':
1209
+ if (hasPeer(s.get(e.origin)))
1210
+ return none$1(s);
1211
+ listOne(next, e.origin, effects);
1212
+ break;
1213
+ case 'welcome': {
1214
+ const listed = new Set(e.members);
1215
+ for (const origin of s.keys())
1216
+ if (!listed.has(origin))
1217
+ unlistOne(next, origin, effects);
1218
+ for (const origin of listed)
1219
+ listOne(next, origin, effects);
1220
+ break;
1221
+ }
1222
+ case 'gone':
1223
+ if (!s.has(e.origin))
1224
+ return none$1(s);
1225
+ unlistOne(next, e.origin, effects);
1226
+ break;
1227
+ case 'opened': {
1228
+ const cur = s.get(e.origin);
1229
+ if (cur?.state !== 'linking')
1230
+ return none$1(s);
1231
+ next.set(e.origin, { state: 'open', attempt: 0, stalled: false });
1232
+ effects.push({ t: 'disarm', origin: e.origin });
1233
+ break;
1234
+ }
1235
+ case 'lost': {
1236
+ const cur = s.get(e.origin);
1237
+ if (!cur || !hasPeer(cur))
1238
+ return none$1(s);
1239
+ next.set(e.origin, {
1240
+ state: 'waiting',
1241
+ attempt: cur.attempt + 1,
1242
+ stalled: true,
1243
+ });
1244
+ effects.push({ t: 'drop', origin: e.origin }, { t: 'armRetry', origin: e.origin, attempt: cur.attempt });
1245
+ break;
1246
+ }
1247
+ case 'due': {
1248
+ const cur = s.get(e.origin);
1249
+ if (cur?.state !== 'waiting')
1250
+ return none$1(s);
1251
+ next.set(e.origin, { ...cur, state: 'linking' });
1252
+ effects.push({ t: 'armOpen', origin: e.origin }, { t: 'build', origin: e.origin });
1253
+ break;
1254
+ }
1255
+ case 'close':
1256
+ for (const [origin, cur] of s) {
1257
+ if (hasPeer(cur))
1258
+ effects.push({ t: 'drop', origin });
1259
+ if (hasTimer(cur))
1260
+ effects.push({ t: 'disarm', origin });
1261
+ }
1262
+ return { next: closedLifecycle, effects };
1263
+ }
1264
+ return { next, effects };
1265
+ }
1266
+ /**
1267
+ * The wait before rebuild number `attempt` (0-based): equal jitter over a capped exponential,
1268
+ * so every delay lies in `[base / 2, base)` with `base = min(minMs * 2^attempt, maxMs)`.
1269
+ */
1270
+ function retryDelay(attempt, bounds, random) {
1271
+ const base = Math.min(bounds.minMs * 2 ** attempt, bounds.maxMs);
1272
+ return base / 2 + random() * (base / 2);
1273
+ }
1274
+
1275
+ /** How many signals are held for replay while a connection waits for its welcome. */
1276
+ const HELD_SIGNALS = 256;
988
1277
  /** The single reliable channel every link carries when no channels are asked for. */
989
1278
  const defaultPeerChannels = [
990
1279
  { label: 'mmstack-mesh' },
991
1280
  ];
992
- /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
993
- function rtcPeerConnector(config) {
994
- return ({ polite, sendSignal, channels = defaultPeerChannels }) => {
995
- const pc = new RTCPeerConnection(config);
1281
+ /**
1282
+ * WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only.
1283
+ *
1284
+ * `config` is the static configuration; ICE servers the relay issues replace its `iceServers`.
1285
+ * Without any ICE servers browsers hide host addresses behind mDNS names, so links only form
1286
+ * on one network segment. When ICE fails, or stays `disconnected` longer than
1287
+ * `disconnectGraceMs` (default 5000), the connector restarts ICE once. A second failure before
1288
+ * the link connects again, a closed connection, or a negotiation step the browser rejects
1289
+ * reports the link gone through `onClose`.
1290
+ */
1291
+ function rtcPeerConnector(config, opt) {
1292
+ const graceMs = opt?.disconnectGraceMs ?? 5000;
1293
+ return ({ polite, sendSignal, channels = defaultPeerChannels, iceServers, }) => {
1294
+ const pc = new RTCPeerConnection(iceServers
1295
+ ? {
1296
+ ...config,
1297
+ iceServers: iceServers.map((server) => ({
1298
+ ...server,
1299
+ urls: typeof server.urls === 'string'
1300
+ ? server.urls
1301
+ : [...server.urls],
1302
+ })),
1303
+ }
1304
+ : config);
996
1305
  let makingOffer = false;
997
1306
  let ignoreOffer = false;
1307
+ const goneCbs = new Set();
1308
+ let finished = false;
1309
+ let restartTried = false;
1310
+ let grace;
1311
+ const clearGrace = () => {
1312
+ if (grace !== undefined)
1313
+ clearTimeout(grace);
1314
+ grace = undefined;
1315
+ };
1316
+ const reportGone = () => {
1317
+ if (finished)
1318
+ return;
1319
+ finished = true;
1320
+ clearGrace();
1321
+ for (const cb of [...goneCbs])
1322
+ cb();
1323
+ };
1324
+ // one ICE restart per connected period; a second failure is the end of the link
1325
+ const failed = () => {
1326
+ if (finished)
1327
+ return;
1328
+ if (restartTried)
1329
+ return reportGone();
1330
+ restartTried = true;
1331
+ pc.restartIce();
1332
+ };
1333
+ const rejected = (step, err) => {
1334
+ if (finished || pc.signalingState === 'closed')
1335
+ return;
1336
+ if (isDevMode()) {
1337
+ console.warn(`[@mmstack/mesh] a peer link could not ${step}; it will be rebuilt`, err);
1338
+ }
1339
+ reportGone();
1340
+ };
1341
+ pc.oniceconnectionstatechange = () => {
1342
+ const state = pc.iceConnectionState;
1343
+ if (state === 'connected' || state === 'completed') {
1344
+ clearGrace();
1345
+ restartTried = false;
1346
+ }
1347
+ else if (state === 'failed') {
1348
+ clearGrace();
1349
+ failed();
1350
+ }
1351
+ else if (state === 'disconnected' && grace === undefined) {
1352
+ grace = setTimeout(() => {
1353
+ grace = undefined;
1354
+ const now = pc.iceConnectionState;
1355
+ if (now === 'disconnected' || now === 'failed')
1356
+ failed();
1357
+ }, graceMs);
1358
+ }
1359
+ };
1360
+ pc.onconnectionstatechange = () => {
1361
+ if (pc.connectionState === 'closed')
1362
+ reportGone();
1363
+ };
998
1364
  const makeChannel = () => {
999
1365
  const messageCbs = new Set();
1000
1366
  const openCbs = new Set();
@@ -1057,6 +1423,9 @@ function rtcPeerConnector(config) {
1057
1423
  await pc.setLocalDescription();
1058
1424
  sendSignal({ description: pc.localDescription });
1059
1425
  }
1426
+ catch (err) {
1427
+ rejected('make an offer', err);
1428
+ }
1060
1429
  finally {
1061
1430
  makingOffer = false;
1062
1431
  }
@@ -1068,6 +1437,8 @@ function rtcPeerConnector(config) {
1068
1437
  channel: byLabel[channels[0].label],
1069
1438
  channels: byLabel,
1070
1439
  signal: async (data) => {
1440
+ if (pc.signalingState === 'closed')
1441
+ return;
1071
1442
  const { description, ice } = (data ?? {});
1072
1443
  if (description) {
1073
1444
  const collision = description.type === 'offer' &&
@@ -1075,10 +1446,15 @@ function rtcPeerConnector(config) {
1075
1446
  ignoreOffer = !polite && collision;
1076
1447
  if (ignoreOffer)
1077
1448
  return;
1078
- await pc.setRemoteDescription(description);
1079
- if (description.type === 'offer') {
1080
- await pc.setLocalDescription();
1081
- sendSignal({ description: pc.localDescription });
1449
+ try {
1450
+ await pc.setRemoteDescription(description);
1451
+ if (description.type === 'offer') {
1452
+ await pc.setLocalDescription();
1453
+ sendSignal({ description: pc.localDescription });
1454
+ }
1455
+ }
1456
+ catch (err) {
1457
+ rejected('apply the remote description', err);
1082
1458
  }
1083
1459
  }
1084
1460
  else if (ice) {
@@ -1091,7 +1467,10 @@ function rtcPeerConnector(config) {
1091
1467
  }
1092
1468
  }
1093
1469
  },
1470
+ onClose: (cb) => (goneCbs.add(cb), () => goneCbs.delete(cb)),
1094
1471
  close: () => {
1472
+ finished = true;
1473
+ clearGrace();
1095
1474
  for (const ch of made.values())
1096
1475
  ch.like.close();
1097
1476
  pc.close();
@@ -1130,6 +1509,16 @@ const unwrapSignal = (data) => {
1130
1509
  * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
1131
1510
  * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
1132
1511
  * still take the seat from each other on every reconnect; give each tab its own origin.
1512
+ *
1513
+ * A link that does not open every channel within `openTimeoutMs`, loses a channel, or is
1514
+ * reported gone by its connector is dropped and rebuilt after a jittered, capped backoff, for
1515
+ * as long as the relay lists its origin; a welcome or a join rebuilds at once. Either side may
1516
+ * rebuild: its new instance announces itself unaddressed, which makes the other side rebuild
1517
+ * its end addressed to it, as for a takeover. `stalled` lists the origins in that state.
1518
+ *
1519
+ * No link is built before the welcome of the connection it signals over: joins before it are
1520
+ * superseded by the welcome's roster and signals are held and replayed after it, so every link
1521
+ * is built with that welcome's ICE servers and never an earlier connection's.
1133
1522
  */
1134
1523
  function peerLinks(opt) {
1135
1524
  const injector = opt.injector ?? inject(Injector);
@@ -1144,6 +1533,18 @@ function peerLinks(opt) {
1144
1533
  const members = signal(new Set(), /* @ts-ignore */
1145
1534
  ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
1146
1535
  const peers = new Map();
1536
+ const lifecycle = signal(emptyLifecycle, /* @ts-ignore */
1537
+ ...(ngDevMode ? [{ debugName: "lifecycle" }] : /* istanbul ignore next */ []));
1538
+ // one timer slot per origin: the open timeout or the rebuild timer, never both
1539
+ const timers = new Map();
1540
+ const openTimeoutMs = opt.openTimeoutMs ?? 15_000;
1541
+ const bounds = {
1542
+ minMs: opt.retry?.minMs ?? 1000,
1543
+ maxMs: opt.retry?.maxMs ?? 30_000,
1544
+ };
1545
+ const random = opt.random ?? Math.random;
1546
+ // the relay's ICE servers from the last welcome; undefined leaves the connector's own
1547
+ let iceServers;
1147
1548
  const openCbs = new Set();
1148
1549
  const messageCbs = new Set();
1149
1550
  const closeCbs = new Set();
@@ -1154,6 +1555,11 @@ function peerLinks(opt) {
1154
1555
  let reconnectTimer;
1155
1556
  let connected = false;
1156
1557
  let closed = false;
1558
+ // no link is built before the welcome of the connection it signals over, so every link
1559
+ // carries that welcome's ICE servers: joins are ignored and signals held until then
1560
+ let welcomed = false;
1561
+ let held = [];
1562
+ let heldWarned = false;
1157
1563
  // links are told apart by instance, never by order: a random tag plus a counter
1158
1564
  const tag = Math.random().toString(36).slice(2, 10);
1159
1565
  let linkSeq = 0;
@@ -1214,6 +1620,7 @@ function peerLinks(opt) {
1214
1620
  polite: opt.origin > origin,
1215
1621
  sendSignal: signal,
1216
1622
  channels: specs,
1623
+ ...(iceServers ? { iceServers } : {}),
1217
1624
  });
1218
1625
  const p = {
1219
1626
  id,
@@ -1223,6 +1630,12 @@ function peerLinks(opt) {
1223
1630
  unsubs: [() => (retired = true)],
1224
1631
  };
1225
1632
  peers.set(origin, p);
1633
+ const lost = () => {
1634
+ if (peers.get(origin) === p)
1635
+ feed({ t: 'lost', origin });
1636
+ };
1637
+ if (link.onClose)
1638
+ p.unsubs.push(link.onClose(lost));
1226
1639
  const early = building;
1227
1640
  building = null;
1228
1641
  // announce the instance, so a side that still holds a link to an earlier seat of this
@@ -1243,62 +1656,148 @@ function peerLinks(opt) {
1243
1656
  p.channels.set(label, state);
1244
1657
  p.unsubs.push(channel.onOpen(() => {
1245
1658
  state.open = true;
1246
- if (labels.every((l) => p.channels.get(l)?.open)) {
1659
+ if (peers.get(origin) === p &&
1660
+ labels.every((l) => p.channels.get(l)?.open)) {
1247
1661
  openPeers.update((set) => new Set(set).add(origin));
1662
+ feed({ t: 'opened', origin });
1663
+ // a link rebuilt by a takeover opens while its origin is already open to the
1664
+ // lifecycle, which then ignores the report: its open timeout ends here all the same
1665
+ if (untracked(lifecycle).get(origin)?.state === 'open')
1666
+ disarm(origin);
1248
1667
  }
1249
1668
  for (const cb of [...openCbs])
1250
1669
  cb(origin, label);
1251
1670
  }), channel.onMessage((frame) => {
1252
1671
  for (const cb of [...messageCbs])
1253
1672
  cb(origin, frame, label);
1254
- }), channel.onClose(() => dropPeer(origin)));
1673
+ }), channel.onClose(lost));
1255
1674
  }
1256
1675
  return p;
1257
1676
  };
1677
+ const disarm = (origin) => {
1678
+ const timer = timers.get(origin);
1679
+ if (timer !== undefined)
1680
+ clearTimeout(timer);
1681
+ timers.delete(origin);
1682
+ };
1683
+ const arm = (origin, ms, fire) => {
1684
+ disarm(origin);
1685
+ const timer = setTimeout(() => {
1686
+ if (timers.get(origin) !== timer)
1687
+ return;
1688
+ timers.delete(origin);
1689
+ feed(fire);
1690
+ }, ms);
1691
+ timers.set(origin, timer);
1692
+ };
1693
+ const execute = (f, remote) => {
1694
+ switch (f.t) {
1695
+ case 'drop':
1696
+ return dropPeer(f.origin);
1697
+ case 'disarm':
1698
+ return disarm(f.origin);
1699
+ }
1700
+ if (closed)
1701
+ return;
1702
+ switch (f.t) {
1703
+ case 'build':
1704
+ ensurePeer(f.origin, remote);
1705
+ return;
1706
+ case 'armOpen':
1707
+ return arm(f.origin, openTimeoutMs, { t: 'lost', origin: f.origin });
1708
+ case 'armRetry':
1709
+ return arm(f.origin, retryDelay(f.attempt, bounds, random), {
1710
+ t: 'due',
1711
+ origin: f.origin,
1712
+ });
1713
+ }
1714
+ };
1715
+ /**
1716
+ * Steps the lifecycle and runs its effects in order. The new state is stored first, so an
1717
+ * event an effect causes on the spot (a link that opens while it is built) steps from it.
1718
+ * `remote` addresses the build of a link made in answer to a signal.
1719
+ */
1720
+ function feed(e, remote) {
1721
+ const { next, effects } = step(untracked(lifecycle), e);
1722
+ if (next !== untracked(lifecycle))
1723
+ lifecycle.set(next);
1724
+ for (const f of effects)
1725
+ execute(f, remote);
1726
+ }
1258
1727
  const setMembers = (origins) => {
1259
1728
  const next = new Set(origins);
1260
1729
  members.set(next);
1261
1730
  for (const cb of [...memberCbs])
1262
1731
  cb([...next]);
1263
1732
  };
1264
- const welcomeMembers = (origins) => {
1733
+ const welcomeMembers = (origins, ice) => {
1265
1734
  setMembers(origins);
1266
- for (const origin of [...peers.keys()])
1267
- if (!members().has(origin))
1268
- dropPeer(origin);
1269
- for (const origin of origins)
1270
- ensurePeer(origin);
1735
+ iceServers = ice;
1736
+ welcomed = true;
1271
1737
  status.set('live');
1738
+ feed({ t: 'welcome', members: origins });
1739
+ const replay = held;
1740
+ held = [];
1741
+ for (const msg of replay) {
1742
+ if (closed)
1743
+ return;
1744
+ handleSignaling(msg);
1745
+ }
1272
1746
  };
1273
1747
  const handleSignaling = (msg) => {
1274
1748
  if (closed || msg.room !== opt.room)
1275
1749
  return;
1750
+ if (!welcomed && msg.t !== 'welcome' && msg.t !== 'reject') {
1751
+ // the welcome's roster supersedes joins before it; a leave discards what the origin sent
1752
+ if (msg.t === 'signal') {
1753
+ if (held.length < HELD_SIGNALS)
1754
+ held.push(msg);
1755
+ else if (isDevMode() && !heldWarned) {
1756
+ heldWarned = true;
1757
+ console.warn(`[@mmstack/mesh] more than ${HELD_SIGNALS} signals arrived before the welcome; the rest are dropped`);
1758
+ }
1759
+ }
1760
+ else if (msg.t === 'member' && msg.gone) {
1761
+ held = held.filter((h) => h.from !== msg.origin);
1762
+ }
1763
+ return;
1764
+ }
1276
1765
  switch (msg.t) {
1277
1766
  case 'welcome':
1278
- welcomeMembers(msg.members);
1767
+ welcomeMembers(msg.members, msg.ice);
1279
1768
  return;
1280
1769
  case 'member':
1281
1770
  setMembers(msg.gone
1282
1771
  ? [...members()].filter((origin) => origin !== msg.origin)
1283
1772
  : [...new Set([...members(), msg.origin])]);
1284
- if (msg.gone)
1285
- dropPeer(msg.origin);
1286
- else
1287
- ensurePeer(msg.origin);
1773
+ feed({ t: msg.gone ? 'gone' : 'listed', origin: msg.origin });
1288
1774
  return;
1289
1775
  case 'signal': {
1776
+ if (!members().has(msg.from)) {
1777
+ // the relay routes signals among members only and reports a join before the
1778
+ // joiner's first signal; anything else must not become a link that retries forever
1779
+ if (isDevMode()) {
1780
+ console.warn(`[@mmstack/mesh] dropped a signal from '${msg.from}', which the relay does not list`);
1781
+ }
1782
+ return;
1783
+ }
1290
1784
  const { link, to, payload } = unwrapSignal(msg.data);
1291
1785
  let peer = peers.get(msg.from);
1292
- if (link === undefined) {
1293
- // an unstamped sender: nothing to tell instances apart by
1294
- peer ??= ensurePeer(msg.from);
1786
+ if (link === undefined || (!peer && to === undefined)) {
1787
+ // no link to this member (lost and waiting to rebuild): its announce is the reason
1788
+ // to build now, addressed to its instance if stamped
1789
+ if (!peer)
1790
+ feed({ t: 'listed', origin: msg.from }, link);
1791
+ peer = peers.get(msg.from);
1792
+ if (!peer)
1793
+ return;
1295
1794
  }
1296
1795
  else if (to !== undefined && to !== peer?.id) {
1297
1796
  // addressed to an instance this side no longer has: a retired link's leftovers
1298
1797
  return;
1299
1798
  }
1300
1799
  else if (!peer) {
1301
- peer = ensurePeer(msg.from, link);
1800
+ return;
1302
1801
  }
1303
1802
  else if (peer.remote === undefined) {
1304
1803
  peer.remote = link;
@@ -1307,8 +1806,11 @@ function peerLinks(opt) {
1307
1806
  if (to === undefined) {
1308
1807
  // a new instance over there that does not know this side yet: a new seat or a
1309
1808
  // restarted link, so this side rebuilds, addressing it, which is what makes the
1310
- // rebuild final: the other side never rebuilds in answer to an addressed signal
1809
+ // rebuild final: the other side never rebuilds in answer to an addressed signal.
1810
+ // It replaces the instance, not a lost link: the lifecycle state stays and only
1811
+ // the open timeout moves to the new instance.
1311
1812
  dropPeer(msg.from);
1813
+ arm(msg.from, openTimeoutMs, { t: 'lost', origin: msg.from });
1312
1814
  peer = ensurePeer(msg.from, link);
1313
1815
  }
1314
1816
  else {
@@ -1339,7 +1841,7 @@ function peerLinks(opt) {
1339
1841
  signalingUnsubs = [unsub];
1340
1842
  const current = port.members();
1341
1843
  if (current !== undefined)
1342
- welcomeMembers(current);
1844
+ welcomeMembers(current, port.iceServers?.());
1343
1845
  return;
1344
1846
  }
1345
1847
  const t = opt.signaling();
@@ -1350,6 +1852,8 @@ function peerLinks(opt) {
1350
1852
  if (closed || transport !== t)
1351
1853
  return;
1352
1854
  transport = null;
1855
+ welcomed = false;
1856
+ held = [];
1353
1857
  status.set('connecting');
1354
1858
  reconnectTimer = setTimeout(connectSignaling, 1000);
1355
1859
  }),
@@ -1372,8 +1876,13 @@ function peerLinks(opt) {
1372
1876
  if (closed)
1373
1877
  return;
1374
1878
  closed = true;
1879
+ held = [];
1375
1880
  if (reconnectTimer !== undefined)
1376
1881
  clearTimeout(reconnectTimer);
1882
+ feed({ t: 'close' });
1883
+ // a takeover's open timeout on a link the lifecycle already counts open
1884
+ for (const origin of [...timers.keys()])
1885
+ disarm(origin);
1377
1886
  for (const origin of [...peers.keys()])
1378
1887
  dropPeer(origin);
1379
1888
  for (const unsub of signalingUnsubs.splice(0))
@@ -1397,6 +1906,7 @@ function peerLinks(opt) {
1397
1906
  return {
1398
1907
  status: status.asReadonly(),
1399
1908
  peers: computed(() => [...openPeers()]),
1909
+ stalled: computed(() => [...lifecycle()].filter(([, e]) => e.stalled).map(([origin]) => origin)),
1400
1910
  members: computed(() => [...members()]),
1401
1911
  onMembers: (cb) => {
1402
1912
  if (!closed)