@mmstack/mesh 21.9.1 → 21.10.1

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;
@@ -563,6 +596,39 @@ const OUTBOX_DEBOUNCE_MS = 300;
563
596
  function meshSync(source, opt) {
564
597
  const injector = opt.injector ?? inject(Injector);
565
598
  const status = signal('connecting', ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
599
+ const origin = signal(null, ...(ngDevMode ? [{ debugName: "origin" }] : /* istanbul ignore next */ []));
600
+ const members = signal([], ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
601
+ let membership;
602
+ // the last roster the links on the port were given; a socket drop blanks the session's, not this
603
+ let roster = [];
604
+ const signalingListeners = new Set();
605
+ let earlySignals = [];
606
+ // the ICE servers of the last welcome, for peer links that attach after it
607
+ let welcomeIce;
608
+ const deliverSignal = (cb, msg) => {
609
+ try {
610
+ cb(msg);
611
+ }
612
+ catch {
613
+ // A failed peer link must never interrupt the room's sync session or other listeners.
614
+ }
615
+ };
616
+ const signalMessage = (msg) => {
617
+ if (msg.t === 'welcome')
618
+ welcomeIce = msg.ice;
619
+ if (msg.t === 'welcome' && earlySignals !== null)
620
+ earlySignals = [];
621
+ if (msg.t === 'member' && msg.gone && earlySignals !== null) {
622
+ earlySignals = earlySignals.filter((held) => held.t !== 'signal' || held.from !== msg.origin);
623
+ }
624
+ if (msg.t === 'signal' &&
625
+ earlySignals !== null &&
626
+ earlySignals.length < 256) {
627
+ earlySignals.push(msg);
628
+ }
629
+ for (const cb of [...signalingListeners])
630
+ deliverSignal(cb, msg);
631
+ };
566
632
  const lastReason = signal(undefined, ...(ngDevMode ? [{ debugName: "lastReason" }] : /* istanbul ignore next */ []));
567
633
  const lastSyncedAt = signal(undefined, ...(ngDevMode ? [{ debugName: "lastSyncedAt" }] : /* istanbul ignore next */ []));
568
634
  const droppedOffline = signal(0, ...(ngDevMode ? [{ debugName: "droppedOffline" }] : /* istanbul ignore next */ []));
@@ -584,6 +650,8 @@ function meshSync(source, opt) {
584
650
  switch (status()) {
585
651
  case 'live':
586
652
  return { status: 'live', lastSyncedAt: at, ...extra };
653
+ case 'waiting':
654
+ return { status: 'waiting', lastSyncedAt: at, ...extra };
587
655
  case 'ejected': {
588
656
  const reason = lastReason();
589
657
  return reason && OUTDATED_REASONS.has(reason)
@@ -594,20 +662,27 @@ function meshSync(source, opt) {
594
662
  return { status: 'offline', lastSyncedAt: at, ...extra };
595
663
  }
596
664
  }, ...(ngDevMode ? [{ debugName: "health" }] : /* istanbul ignore next */ []));
597
- // Created lazily: with a persisted outbox we must adopt the stored origin BEFORE minting anything
665
+ // Created lazily: with a persisted outbox the slot lock and the restored tail come first, so the
666
+ // engine never mints before it knows the generation it is in
598
667
  let sync;
599
668
  let session;
600
669
  let started = false;
601
670
  let closed = false;
602
671
  let pendingPresence;
603
672
  let persistTimer;
673
+ let pendingPersist;
604
674
  let releaseLock;
605
675
  let cancelLock;
676
+ // this tab owns the persisted slot ('off', no Web Locks, or a granted lock); an ephemeral boot never does
677
+ let durable = false;
678
+ // the slot's clock high-water as restored: persisted back until this boot mints its own stamp
679
+ let restoredClock;
680
+ // resolves when the store has the payload (a failed write resolves too: persistence is best-effort)
606
681
  const doPersist = () => {
607
- if (closed || !opt.outbox || !started || !session)
608
- return;
682
+ if (closed || !opt.outbox || !started || !session || !durable)
683
+ return Promise.resolve(); // ephemeral: never writes
609
684
  const instance = session.instance();
610
- const clock = sync.lastStamp();
685
+ const clock = sync.lastStamp() ?? restoredClock;
611
686
  const payload = {
612
687
  origin: sync.origin,
613
688
  version: sync.watermark()[sync.origin] ?? 0,
@@ -616,25 +691,42 @@ function meshSync(source, opt) {
616
691
  floors: sync.floors(),
617
692
  ...(clock ? { clock } : {}),
618
693
  };
619
- void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));
694
+ const { store, key } = opt.outbox;
695
+ // Capture before queueing: teardown clears the session's tail immediately after this call.
696
+ const write = () => {
697
+ try {
698
+ return Promise.resolve(store.set(key, payload)).then(() => undefined, () => undefined);
699
+ }
700
+ catch {
701
+ return Promise.resolve(); // a failed save must not block later saves or lock release
702
+ }
703
+ };
704
+ // Keep the idle path synchronous, but never let an older save land after a newer one.
705
+ const pending = pendingPersist ? pendingPersist.then(write) : write();
706
+ pendingPersist = pending;
707
+ void pending.then(() => {
708
+ if (pendingPersist === pending)
709
+ pendingPersist = undefined;
710
+ });
711
+ return pending;
620
712
  };
621
- // coalesce outbox writes; `immediate` forces a synchronous-path write (first boot, teardown)
713
+ // coalesce outbox writes; `immediate` bypasses the debounce, but waits for earlier saves
622
714
  const persistOutbox = (immediate = false) => {
623
715
  if (!opt.outbox)
624
- return;
716
+ return Promise.resolve();
625
717
  if (immediate) {
626
718
  if (persistTimer !== undefined)
627
719
  clearTimeout(persistTimer);
628
720
  persistTimer = undefined;
629
- doPersist();
630
- return;
721
+ return doPersist();
631
722
  }
632
- if (persistTimer !== undefined)
633
- return;
634
- persistTimer = setTimeout(() => {
635
- persistTimer = undefined;
636
- doPersist();
637
- }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);
723
+ if (persistTimer === undefined) {
724
+ persistTimer = setTimeout(() => {
725
+ persistTimer = undefined;
726
+ void doPersist();
727
+ }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);
728
+ }
729
+ return Promise.resolve(); // the debounced path is not awaited
638
730
  };
639
731
  const dropLocks = () => {
640
732
  cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown
@@ -653,6 +745,7 @@ function meshSync(source, opt) {
653
745
  const initCore = (restore) => {
654
746
  if (closed)
655
747
  return;
748
+ restoredClock = restore?.clock;
656
749
  sync = opSync(source, {
657
750
  writer: opt.writer,
658
751
  instance: restore?.instance,
@@ -667,6 +760,8 @@ function meshSync(source, opt) {
667
760
  },
668
761
  });
669
762
  started = true;
763
+ // set once this session ends: only then are the links riding on its port retired
764
+ let ended = false;
670
765
  session = meshSession({
671
766
  room: opt.room,
672
767
  writer: opt.writer,
@@ -680,6 +775,28 @@ function meshSync(source, opt) {
680
775
  instance: restore?.instance,
681
776
  reconnect: opt.reconnect,
682
777
  hooks: {
778
+ onOrigin: (value) => origin.set(value),
779
+ onMembers: (value) => {
780
+ membership = value;
781
+ members.set(value ?? []);
782
+ if (value !== undefined) {
783
+ roster = value;
784
+ return;
785
+ }
786
+ if (earlySignals !== null)
787
+ earlySignals = [];
788
+ // Peer links outlive a socket drop: the next welcome re-lists who is still there. A
789
+ // borrowed port has no close of its own, so the session's end retires them here, from
790
+ // the last roster the links saw (a drop before the close already blanked the session's).
791
+ if (!ended)
792
+ return;
793
+ const retired = roster;
794
+ roster = [];
795
+ for (const origin of retired) {
796
+ signalMessage({ t: 'member', room: opt.room, origin, gone: true });
797
+ }
798
+ },
799
+ onMessage: signalMessage,
683
800
  onRefused: (env, reason) => {
684
801
  refused.update((n) => n + 1);
685
802
  opt.onRefused?.(env, reason);
@@ -700,16 +817,25 @@ function meshSync(source, opt) {
700
817
  onSynced: () => lastSyncedAt.set(Date.now()),
701
818
  onPeers: (map) => peerMap.set(map),
702
819
  onOutboxChange: () => {
703
- persistOutbox();
820
+ void persistOutbox();
704
821
  acked.set(!session?.hasUnacked());
705
822
  },
706
823
  onTerminal: () => {
707
- dropLocks();
824
+ ended = true;
708
825
  // latched: the tail is about to be dropped from the session, but it was never
709
826
  // acknowledged, so the answer to "is everything I wrote in the room" stays no
710
827
  if (session?.hasUnacked())
711
828
  acked.set(false);
712
- persistOutbox(true); // save the still-unacked tail for the next boot before dropping it
829
+ // save the still-unacked tail for the next boot, and release the lock only once the store
830
+ // has it: a successor granted earlier could restore the slot before this write lands
831
+ let saved;
832
+ try {
833
+ saved = persistOutbox(true);
834
+ }
835
+ catch {
836
+ saved = Promise.resolve(); // a failed capture must still hand the slot on
837
+ }
838
+ void saved.finally(dropLocks);
713
839
  },
714
840
  onLocalReject: (violation) => {
715
841
  if (isDevMode()) {
@@ -718,7 +844,11 @@ function meshSync(source, opt) {
718
844
  },
719
845
  },
720
846
  });
721
- if (restore && (restore.envs.length > 0 || restore.version > 0)) {
847
+ if (restore &&
848
+ (restore.envs.length > 0 ||
849
+ restore.version > 0 ||
850
+ (restore.floors?.length ?? 0) > 0 ||
851
+ restore.clock !== undefined)) {
722
852
  const kept = restore.envs.filter(restorable);
723
853
  const dropped = restore.envs.length - kept.length;
724
854
  if (dropped > 0) {
@@ -729,7 +859,7 @@ function meshSync(source, opt) {
729
859
  }
730
860
  sync.restore(kept, restore.version, restore.floors, restore.clock); // → the session's subscribe repopulates its unacked tail for resend
731
861
  }
732
- persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe
862
+ void persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe
733
863
  if (pendingPresence) {
734
864
  session.setPresence(pendingPresence.data);
735
865
  pendingPresence = undefined;
@@ -740,7 +870,7 @@ function meshSync(source, opt) {
740
870
  const connection = {
741
871
  status: computed(() => {
742
872
  const s = status();
743
- return s === 'connecting'
873
+ return s === 'connecting' || s === 'waiting'
744
874
  ? 'loading'
745
875
  : s === 'reconnecting'
746
876
  ? 'reloading'
@@ -748,7 +878,9 @@ function meshSync(source, opt) {
748
878
  ? 'error'
749
879
  : 'resolved';
750
880
  }),
751
- isLoading: computed(() => status() === 'connecting' || status() === 'reconnecting'),
881
+ isLoading: computed(() => status() === 'connecting' ||
882
+ status() === 'waiting' ||
883
+ status() === 'reconnecting'),
752
884
  hasValue: () => true,
753
885
  };
754
886
  runInInjectionContext(injector, () => registerResource(connection, { suspends: opt.register === 'suspend' }));
@@ -767,8 +899,9 @@ function meshSync(source, opt) {
767
899
  sync.destroy();
768
900
  };
769
901
  injector.get(DestroyRef).onDestroy(teardown);
770
- // Load the persisted outbox, then boot with the adopted origin. A fresh/unreadable slot boots clean.
902
+ // Load the persisted outbox, then boot on a fresh origin. A fresh/unreadable slot boots clean.
771
903
  const bootFromDisk = async () => {
904
+ durable = true; // every caller owns the slot
772
905
  if (closed || !opt.outbox)
773
906
  return;
774
907
  let saved;
@@ -795,33 +928,63 @@ function meshSync(source, opt) {
795
928
  }
796
929
  else {
797
930
  const locks = globalThis.navigator?.locks;
931
+ const mode = opt.outbox.crossTab ?? 'queue';
798
932
  if (!locks) {
799
933
  if (isDevMode()) {
800
- 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.');
934
+ 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.`);
801
935
  }
802
936
  void bootFromDisk();
937
+ return;
803
938
  }
804
- else {
939
+ const name = `@mmstack/mesh:outbox:${opt.outbox.key}`;
940
+ // hold a granted lock until teardown resolves this promise
941
+ const hold = (queued = false) => {
942
+ cancelLock = undefined; // granted — no longer abortable, only releasable
943
+ if (closed)
944
+ return Promise.resolve();
945
+ if (queued)
946
+ status.set('connecting'); // the wait ends with the grant
947
+ return new Promise((release) => {
948
+ releaseLock = release;
949
+ void bootFromDisk();
950
+ });
951
+ };
952
+ const queueUp = () => {
953
+ status.set('waiting');
805
954
  const abort = new AbortController();
806
955
  cancelLock = () => abort.abort();
807
956
  void locks
808
- .request(`@mmstack/mesh:outbox:${opt.outbox.key}`, { mode: 'exclusive', signal: abort.signal }, () => {
809
- cancelLock = undefined; // granted — no longer abortable, only releasable
810
- if (closed)
811
- return Promise.resolve();
812
- // hold the lock until teardown resolves this promise
813
- return new Promise((release) => {
814
- releaseLock = release;
815
- void bootFromDisk();
816
- });
817
- })
957
+ .request(name, { mode: 'exclusive', signal: abort.signal }, () => hold(true))
818
958
  .catch((e) => {
819
959
  // an aborted request is our own teardown; any other failure → degrade to no-lock
820
- if (!closed && e?.name !== 'AbortError') {
960
+ if (!closed &&
961
+ !started &&
962
+ e?.name !== 'AbortError') {
963
+ status.set('connecting'); // no longer waiting on anyone
821
964
  void bootFromDisk();
822
965
  }
823
966
  });
824
- }
967
+ };
968
+ // Web Locks forbids `signal` together with `ifAvailable`, hence the probe first
969
+ void locks
970
+ .request(name, { mode: 'exclusive', ifAvailable: true }, (lock) => {
971
+ if (lock === null) {
972
+ // another tab owns the slot
973
+ if (closed)
974
+ return Promise.resolve();
975
+ if (mode === 'ephemeral') {
976
+ initCore(); // live at once on a fresh origin; never reads or writes the slot
977
+ return Promise.resolve();
978
+ }
979
+ queueUp();
980
+ return Promise.resolve();
981
+ }
982
+ return hold();
983
+ })
984
+ .catch(() => {
985
+ if (!closed && !started)
986
+ void bootFromDisk(); // a broken lock manager degrades to no-lock
987
+ });
825
988
  }
826
989
  };
827
990
  if (opt.whenReady) {
@@ -834,6 +997,21 @@ function meshSync(source, opt) {
834
997
  }
835
998
  return {
836
999
  status: status.asReadonly(),
1000
+ origin: origin.asReadonly(),
1001
+ members: members.asReadonly(),
1002
+ signaling: {
1003
+ members: () => membership,
1004
+ iceServers: () => welcomeIce,
1005
+ send: (msg) => session?.sendSignal(msg),
1006
+ onMessage: (cb) => {
1007
+ signalingListeners.add(cb);
1008
+ const held = earlySignals ?? [];
1009
+ earlySignals = null;
1010
+ for (const msg of held)
1011
+ deliverSignal(cb, msg);
1012
+ return () => signalingListeners.delete(cb);
1013
+ },
1014
+ },
837
1015
  health,
838
1016
  acked: acked.asReadonly(),
839
1017
  whenAcked: () => (session ? session.whenAcked() : Promise.resolve()), // nothing written yet
@@ -975,16 +1153,202 @@ function directTransport(relay, ctx) {
975
1153
  };
976
1154
  }
977
1155
 
1156
+ /** The starting value: nothing listed. */
1157
+ const emptyLifecycle = new Map();
1158
+ /** The value after `close`; `step` recognises it by identity and ignores every later event. */
1159
+ const closedLifecycle = new Map();
1160
+ const hasPeer = (e) => e?.state === 'linking' || e?.state === 'open';
1161
+ const hasTimer = (e) => e?.state === 'linking' || e?.state === 'waiting';
1162
+ /**
1163
+ * Builds now for a listed origin with no peer; keeps an existing one. The open timeout is
1164
+ * armed before the build so a link that opens while it is being built cancels it.
1165
+ */
1166
+ const listOne = (s, origin, effects) => {
1167
+ const cur = s.get(origin);
1168
+ if (hasPeer(cur))
1169
+ return;
1170
+ if (cur)
1171
+ effects.push({ t: 'disarm', origin });
1172
+ effects.push({ t: 'armOpen', origin }, { t: 'build', origin });
1173
+ s.set(origin, {
1174
+ state: 'linking',
1175
+ attempt: cur?.attempt ?? 0,
1176
+ stalled: cur?.stalled ?? false,
1177
+ });
1178
+ };
1179
+ const unlistOne = (s, origin, effects) => {
1180
+ const cur = s.get(origin);
1181
+ if (!cur)
1182
+ return;
1183
+ if (hasPeer(cur))
1184
+ effects.push({ t: 'drop', origin });
1185
+ effects.push({ t: 'disarm', origin });
1186
+ s.delete(origin);
1187
+ };
1188
+ const none$1 = (s) => ({ next: s, effects: [] });
1189
+ /** One transition. Pure and total: an event that does not apply returns `s` and no effects. */
1190
+ function step(s, e) {
1191
+ if (s === closedLifecycle)
1192
+ return none$1(s);
1193
+ const effects = [];
1194
+ const next = new Map(s);
1195
+ switch (e.t) {
1196
+ case 'listed':
1197
+ if (hasPeer(s.get(e.origin)))
1198
+ return none$1(s);
1199
+ listOne(next, e.origin, effects);
1200
+ break;
1201
+ case 'welcome': {
1202
+ const listed = new Set(e.members);
1203
+ for (const origin of s.keys())
1204
+ if (!listed.has(origin))
1205
+ unlistOne(next, origin, effects);
1206
+ for (const origin of listed)
1207
+ listOne(next, origin, effects);
1208
+ break;
1209
+ }
1210
+ case 'gone':
1211
+ if (!s.has(e.origin))
1212
+ return none$1(s);
1213
+ unlistOne(next, e.origin, effects);
1214
+ break;
1215
+ case 'opened': {
1216
+ const cur = s.get(e.origin);
1217
+ if (cur?.state !== 'linking')
1218
+ return none$1(s);
1219
+ next.set(e.origin, { state: 'open', attempt: 0, stalled: false });
1220
+ effects.push({ t: 'disarm', origin: e.origin });
1221
+ break;
1222
+ }
1223
+ case 'lost': {
1224
+ const cur = s.get(e.origin);
1225
+ if (!cur || !hasPeer(cur))
1226
+ return none$1(s);
1227
+ next.set(e.origin, {
1228
+ state: 'waiting',
1229
+ attempt: cur.attempt + 1,
1230
+ stalled: true,
1231
+ });
1232
+ effects.push({ t: 'drop', origin: e.origin }, { t: 'armRetry', origin: e.origin, attempt: cur.attempt });
1233
+ break;
1234
+ }
1235
+ case 'due': {
1236
+ const cur = s.get(e.origin);
1237
+ if (cur?.state !== 'waiting')
1238
+ return none$1(s);
1239
+ next.set(e.origin, { ...cur, state: 'linking' });
1240
+ effects.push({ t: 'armOpen', origin: e.origin }, { t: 'build', origin: e.origin });
1241
+ break;
1242
+ }
1243
+ case 'close':
1244
+ for (const [origin, cur] of s) {
1245
+ if (hasPeer(cur))
1246
+ effects.push({ t: 'drop', origin });
1247
+ if (hasTimer(cur))
1248
+ effects.push({ t: 'disarm', origin });
1249
+ }
1250
+ return { next: closedLifecycle, effects };
1251
+ }
1252
+ return { next, effects };
1253
+ }
1254
+ /**
1255
+ * The wait before rebuild number `attempt` (0-based): equal jitter over a capped exponential,
1256
+ * so every delay lies in `[base / 2, base)` with `base = min(minMs * 2^attempt, maxMs)`.
1257
+ */
1258
+ function retryDelay(attempt, bounds, random) {
1259
+ const base = Math.min(bounds.minMs * 2 ** attempt, bounds.maxMs);
1260
+ return base / 2 + random() * (base / 2);
1261
+ }
1262
+
1263
+ /** How many signals are held for replay while a connection waits for its welcome. */
1264
+ const HELD_SIGNALS = 256;
978
1265
  /** The single reliable channel every link carries when no channels are asked for. */
979
1266
  const defaultPeerChannels = [
980
1267
  { label: 'mmstack-mesh' },
981
1268
  ];
982
- /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
983
- function rtcPeerConnector(config) {
984
- return ({ polite, sendSignal, channels = defaultPeerChannels }) => {
985
- const pc = new RTCPeerConnection(config);
1269
+ /**
1270
+ * WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only.
1271
+ *
1272
+ * `config` is the static configuration; ICE servers the relay issues replace its `iceServers`.
1273
+ * Without any ICE servers browsers hide host addresses behind mDNS names, so links only form
1274
+ * on one network segment. When ICE fails, or stays `disconnected` longer than
1275
+ * `disconnectGraceMs` (default 5000), the connector restarts ICE once. A second failure before
1276
+ * the link connects again, a closed connection, or a negotiation step the browser rejects
1277
+ * reports the link gone through `onClose`.
1278
+ */
1279
+ function rtcPeerConnector(config, opt) {
1280
+ const graceMs = opt?.disconnectGraceMs ?? 5000;
1281
+ return ({ polite, sendSignal, channels = defaultPeerChannels, iceServers, }) => {
1282
+ const pc = new RTCPeerConnection(iceServers
1283
+ ? {
1284
+ ...config,
1285
+ iceServers: iceServers.map((server) => ({
1286
+ ...server,
1287
+ urls: typeof server.urls === 'string'
1288
+ ? server.urls
1289
+ : [...server.urls],
1290
+ })),
1291
+ }
1292
+ : config);
986
1293
  let makingOffer = false;
987
1294
  let ignoreOffer = false;
1295
+ const goneCbs = new Set();
1296
+ let finished = false;
1297
+ let restartTried = false;
1298
+ let grace;
1299
+ const clearGrace = () => {
1300
+ if (grace !== undefined)
1301
+ clearTimeout(grace);
1302
+ grace = undefined;
1303
+ };
1304
+ const reportGone = () => {
1305
+ if (finished)
1306
+ return;
1307
+ finished = true;
1308
+ clearGrace();
1309
+ for (const cb of [...goneCbs])
1310
+ cb();
1311
+ };
1312
+ // one ICE restart per connected period; a second failure is the end of the link
1313
+ const failed = () => {
1314
+ if (finished)
1315
+ return;
1316
+ if (restartTried)
1317
+ return reportGone();
1318
+ restartTried = true;
1319
+ pc.restartIce();
1320
+ };
1321
+ const rejected = (step, err) => {
1322
+ if (finished || pc.signalingState === 'closed')
1323
+ return;
1324
+ if (isDevMode()) {
1325
+ console.warn(`[@mmstack/mesh] a peer link could not ${step}; it will be rebuilt`, err);
1326
+ }
1327
+ reportGone();
1328
+ };
1329
+ pc.oniceconnectionstatechange = () => {
1330
+ const state = pc.iceConnectionState;
1331
+ if (state === 'connected' || state === 'completed') {
1332
+ clearGrace();
1333
+ restartTried = false;
1334
+ }
1335
+ else if (state === 'failed') {
1336
+ clearGrace();
1337
+ failed();
1338
+ }
1339
+ else if (state === 'disconnected' && grace === undefined) {
1340
+ grace = setTimeout(() => {
1341
+ grace = undefined;
1342
+ const now = pc.iceConnectionState;
1343
+ if (now === 'disconnected' || now === 'failed')
1344
+ failed();
1345
+ }, graceMs);
1346
+ }
1347
+ };
1348
+ pc.onconnectionstatechange = () => {
1349
+ if (pc.connectionState === 'closed')
1350
+ reportGone();
1351
+ };
988
1352
  const makeChannel = () => {
989
1353
  const messageCbs = new Set();
990
1354
  const openCbs = new Set();
@@ -1047,6 +1411,9 @@ function rtcPeerConnector(config) {
1047
1411
  await pc.setLocalDescription();
1048
1412
  sendSignal({ description: pc.localDescription });
1049
1413
  }
1414
+ catch (err) {
1415
+ rejected('make an offer', err);
1416
+ }
1050
1417
  finally {
1051
1418
  makingOffer = false;
1052
1419
  }
@@ -1058,6 +1425,8 @@ function rtcPeerConnector(config) {
1058
1425
  channel: byLabel[channels[0].label],
1059
1426
  channels: byLabel,
1060
1427
  signal: async (data) => {
1428
+ if (pc.signalingState === 'closed')
1429
+ return;
1061
1430
  const { description, ice } = (data ?? {});
1062
1431
  if (description) {
1063
1432
  const collision = description.type === 'offer' &&
@@ -1065,10 +1434,15 @@ function rtcPeerConnector(config) {
1065
1434
  ignoreOffer = !polite && collision;
1066
1435
  if (ignoreOffer)
1067
1436
  return;
1068
- await pc.setRemoteDescription(description);
1069
- if (description.type === 'offer') {
1070
- await pc.setLocalDescription();
1071
- sendSignal({ description: pc.localDescription });
1437
+ try {
1438
+ await pc.setRemoteDescription(description);
1439
+ if (description.type === 'offer') {
1440
+ await pc.setLocalDescription();
1441
+ sendSignal({ description: pc.localDescription });
1442
+ }
1443
+ }
1444
+ catch (err) {
1445
+ rejected('apply the remote description', err);
1072
1446
  }
1073
1447
  }
1074
1448
  else if (ice) {
@@ -1081,7 +1455,10 @@ function rtcPeerConnector(config) {
1081
1455
  }
1082
1456
  }
1083
1457
  },
1458
+ onClose: (cb) => (goneCbs.add(cb), () => goneCbs.delete(cb)),
1084
1459
  close: () => {
1460
+ finished = true;
1461
+ clearGrace();
1085
1462
  for (const ch of made.values())
1086
1463
  ch.like.close();
1087
1464
  pc.close();
@@ -1120,6 +1497,16 @@ const unwrapSignal = (data) => {
1120
1497
  * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
1121
1498
  * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
1122
1499
  * still take the seat from each other on every reconnect; give each tab its own origin.
1500
+ *
1501
+ * A link that does not open every channel within `openTimeoutMs`, loses a channel, or is
1502
+ * reported gone by its connector is dropped and rebuilt after a jittered, capped backoff, for
1503
+ * as long as the relay lists its origin; a welcome or a join rebuilds at once. Either side may
1504
+ * rebuild: its new instance announces itself unaddressed, which makes the other side rebuild
1505
+ * its end addressed to it, as for a takeover. `stalled` lists the origins in that state.
1506
+ *
1507
+ * No link is built before the welcome of the connection it signals over: joins before it are
1508
+ * superseded by the welcome's roster and signals are held and replayed after it, so every link
1509
+ * is built with that welcome's ICE servers and never an earlier connection's.
1123
1510
  */
1124
1511
  function peerLinks(opt) {
1125
1512
  const injector = opt.injector ?? inject(Injector);
@@ -1131,6 +1518,17 @@ function peerLinks(opt) {
1131
1518
  const openPeers = signal(new Set(), ...(ngDevMode ? [{ debugName: "openPeers" }] : /* istanbul ignore next */ []));
1132
1519
  const members = signal(new Set(), ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
1133
1520
  const peers = new Map();
1521
+ const lifecycle = signal(emptyLifecycle, ...(ngDevMode ? [{ debugName: "lifecycle" }] : /* istanbul ignore next */ []));
1522
+ // one timer slot per origin: the open timeout or the rebuild timer, never both
1523
+ const timers = new Map();
1524
+ const openTimeoutMs = opt.openTimeoutMs ?? 15_000;
1525
+ const bounds = {
1526
+ minMs: opt.retry?.minMs ?? 1000,
1527
+ maxMs: opt.retry?.maxMs ?? 30_000,
1528
+ };
1529
+ const random = opt.random ?? Math.random;
1530
+ // the relay's ICE servers from the last welcome; undefined leaves the connector's own
1531
+ let iceServers;
1134
1532
  const openCbs = new Set();
1135
1533
  const messageCbs = new Set();
1136
1534
  const closeCbs = new Set();
@@ -1141,6 +1539,11 @@ function peerLinks(opt) {
1141
1539
  let reconnectTimer;
1142
1540
  let connected = false;
1143
1541
  let closed = false;
1542
+ // no link is built before the welcome of the connection it signals over, so every link
1543
+ // carries that welcome's ICE servers: joins are ignored and signals held until then
1544
+ let welcomed = false;
1545
+ let held = [];
1546
+ let heldWarned = false;
1144
1547
  // links are told apart by instance, never by order: a random tag plus a counter
1145
1548
  const tag = Math.random().toString(36).slice(2, 10);
1146
1549
  let linkSeq = 0;
@@ -1201,6 +1604,7 @@ function peerLinks(opt) {
1201
1604
  polite: opt.origin > origin,
1202
1605
  sendSignal: signal,
1203
1606
  channels: specs,
1607
+ ...(iceServers ? { iceServers } : {}),
1204
1608
  });
1205
1609
  const p = {
1206
1610
  id,
@@ -1210,6 +1614,12 @@ function peerLinks(opt) {
1210
1614
  unsubs: [() => (retired = true)],
1211
1615
  };
1212
1616
  peers.set(origin, p);
1617
+ const lost = () => {
1618
+ if (peers.get(origin) === p)
1619
+ feed({ t: 'lost', origin });
1620
+ };
1621
+ if (link.onClose)
1622
+ p.unsubs.push(link.onClose(lost));
1213
1623
  const early = building;
1214
1624
  building = null;
1215
1625
  // announce the instance, so a side that still holds a link to an earlier seat of this
@@ -1230,62 +1640,148 @@ function peerLinks(opt) {
1230
1640
  p.channels.set(label, state);
1231
1641
  p.unsubs.push(channel.onOpen(() => {
1232
1642
  state.open = true;
1233
- if (labels.every((l) => p.channels.get(l)?.open)) {
1643
+ if (peers.get(origin) === p &&
1644
+ labels.every((l) => p.channels.get(l)?.open)) {
1234
1645
  openPeers.update((set) => new Set(set).add(origin));
1646
+ feed({ t: 'opened', origin });
1647
+ // a link rebuilt by a takeover opens while its origin is already open to the
1648
+ // lifecycle, which then ignores the report: its open timeout ends here all the same
1649
+ if (untracked(lifecycle).get(origin)?.state === 'open')
1650
+ disarm(origin);
1235
1651
  }
1236
1652
  for (const cb of [...openCbs])
1237
1653
  cb(origin, label);
1238
1654
  }), channel.onMessage((frame) => {
1239
1655
  for (const cb of [...messageCbs])
1240
1656
  cb(origin, frame, label);
1241
- }), channel.onClose(() => dropPeer(origin)));
1657
+ }), channel.onClose(lost));
1242
1658
  }
1243
1659
  return p;
1244
1660
  };
1661
+ const disarm = (origin) => {
1662
+ const timer = timers.get(origin);
1663
+ if (timer !== undefined)
1664
+ clearTimeout(timer);
1665
+ timers.delete(origin);
1666
+ };
1667
+ const arm = (origin, ms, fire) => {
1668
+ disarm(origin);
1669
+ const timer = setTimeout(() => {
1670
+ if (timers.get(origin) !== timer)
1671
+ return;
1672
+ timers.delete(origin);
1673
+ feed(fire);
1674
+ }, ms);
1675
+ timers.set(origin, timer);
1676
+ };
1677
+ const execute = (f, remote) => {
1678
+ switch (f.t) {
1679
+ case 'drop':
1680
+ return dropPeer(f.origin);
1681
+ case 'disarm':
1682
+ return disarm(f.origin);
1683
+ }
1684
+ if (closed)
1685
+ return;
1686
+ switch (f.t) {
1687
+ case 'build':
1688
+ ensurePeer(f.origin, remote);
1689
+ return;
1690
+ case 'armOpen':
1691
+ return arm(f.origin, openTimeoutMs, { t: 'lost', origin: f.origin });
1692
+ case 'armRetry':
1693
+ return arm(f.origin, retryDelay(f.attempt, bounds, random), {
1694
+ t: 'due',
1695
+ origin: f.origin,
1696
+ });
1697
+ }
1698
+ };
1699
+ /**
1700
+ * Steps the lifecycle and runs its effects in order. The new state is stored first, so an
1701
+ * event an effect causes on the spot (a link that opens while it is built) steps from it.
1702
+ * `remote` addresses the build of a link made in answer to a signal.
1703
+ */
1704
+ function feed(e, remote) {
1705
+ const { next, effects } = step(untracked(lifecycle), e);
1706
+ if (next !== untracked(lifecycle))
1707
+ lifecycle.set(next);
1708
+ for (const f of effects)
1709
+ execute(f, remote);
1710
+ }
1245
1711
  const setMembers = (origins) => {
1246
1712
  const next = new Set(origins);
1247
1713
  members.set(next);
1248
1714
  for (const cb of [...memberCbs])
1249
1715
  cb([...next]);
1250
1716
  };
1251
- const welcomeMembers = (origins) => {
1717
+ const welcomeMembers = (origins, ice) => {
1252
1718
  setMembers(origins);
1253
- for (const origin of [...peers.keys()])
1254
- if (!members().has(origin))
1255
- dropPeer(origin);
1256
- for (const origin of origins)
1257
- ensurePeer(origin);
1719
+ iceServers = ice;
1720
+ welcomed = true;
1258
1721
  status.set('live');
1722
+ feed({ t: 'welcome', members: origins });
1723
+ const replay = held;
1724
+ held = [];
1725
+ for (const msg of replay) {
1726
+ if (closed)
1727
+ return;
1728
+ handleSignaling(msg);
1729
+ }
1259
1730
  };
1260
1731
  const handleSignaling = (msg) => {
1261
1732
  if (closed || msg.room !== opt.room)
1262
1733
  return;
1734
+ if (!welcomed && msg.t !== 'welcome' && msg.t !== 'reject') {
1735
+ // the welcome's roster supersedes joins before it; a leave discards what the origin sent
1736
+ if (msg.t === 'signal') {
1737
+ if (held.length < HELD_SIGNALS)
1738
+ held.push(msg);
1739
+ else if (isDevMode() && !heldWarned) {
1740
+ heldWarned = true;
1741
+ console.warn(`[@mmstack/mesh] more than ${HELD_SIGNALS} signals arrived before the welcome; the rest are dropped`);
1742
+ }
1743
+ }
1744
+ else if (msg.t === 'member' && msg.gone) {
1745
+ held = held.filter((h) => h.from !== msg.origin);
1746
+ }
1747
+ return;
1748
+ }
1263
1749
  switch (msg.t) {
1264
1750
  case 'welcome':
1265
- welcomeMembers(msg.members);
1751
+ welcomeMembers(msg.members, msg.ice);
1266
1752
  return;
1267
1753
  case 'member':
1268
1754
  setMembers(msg.gone
1269
1755
  ? [...members()].filter((origin) => origin !== msg.origin)
1270
1756
  : [...new Set([...members(), msg.origin])]);
1271
- if (msg.gone)
1272
- dropPeer(msg.origin);
1273
- else
1274
- ensurePeer(msg.origin);
1757
+ feed({ t: msg.gone ? 'gone' : 'listed', origin: msg.origin });
1275
1758
  return;
1276
1759
  case 'signal': {
1760
+ if (!members().has(msg.from)) {
1761
+ // the relay routes signals among members only and reports a join before the
1762
+ // joiner's first signal; anything else must not become a link that retries forever
1763
+ if (isDevMode()) {
1764
+ console.warn(`[@mmstack/mesh] dropped a signal from '${msg.from}', which the relay does not list`);
1765
+ }
1766
+ return;
1767
+ }
1277
1768
  const { link, to, payload } = unwrapSignal(msg.data);
1278
1769
  let peer = peers.get(msg.from);
1279
- if (link === undefined) {
1280
- // an unstamped sender: nothing to tell instances apart by
1281
- peer ??= ensurePeer(msg.from);
1770
+ if (link === undefined || (!peer && to === undefined)) {
1771
+ // no link to this member (lost and waiting to rebuild): its announce is the reason
1772
+ // to build now, addressed to its instance if stamped
1773
+ if (!peer)
1774
+ feed({ t: 'listed', origin: msg.from }, link);
1775
+ peer = peers.get(msg.from);
1776
+ if (!peer)
1777
+ return;
1282
1778
  }
1283
1779
  else if (to !== undefined && to !== peer?.id) {
1284
1780
  // addressed to an instance this side no longer has: a retired link's leftovers
1285
1781
  return;
1286
1782
  }
1287
1783
  else if (!peer) {
1288
- peer = ensurePeer(msg.from, link);
1784
+ return;
1289
1785
  }
1290
1786
  else if (peer.remote === undefined) {
1291
1787
  peer.remote = link;
@@ -1294,8 +1790,11 @@ function peerLinks(opt) {
1294
1790
  if (to === undefined) {
1295
1791
  // a new instance over there that does not know this side yet: a new seat or a
1296
1792
  // restarted link, so this side rebuilds, addressing it, which is what makes the
1297
- // rebuild final: the other side never rebuilds in answer to an addressed signal
1793
+ // rebuild final: the other side never rebuilds in answer to an addressed signal.
1794
+ // It replaces the instance, not a lost link: the lifecycle state stays and only
1795
+ // the open timeout moves to the new instance.
1298
1796
  dropPeer(msg.from);
1797
+ arm(msg.from, openTimeoutMs, { t: 'lost', origin: msg.from });
1299
1798
  peer = ensurePeer(msg.from, link);
1300
1799
  }
1301
1800
  else {
@@ -1326,7 +1825,7 @@ function peerLinks(opt) {
1326
1825
  signalingUnsubs = [unsub];
1327
1826
  const current = port.members();
1328
1827
  if (current !== undefined)
1329
- welcomeMembers(current);
1828
+ welcomeMembers(current, port.iceServers?.());
1330
1829
  return;
1331
1830
  }
1332
1831
  const t = opt.signaling();
@@ -1337,6 +1836,8 @@ function peerLinks(opt) {
1337
1836
  if (closed || transport !== t)
1338
1837
  return;
1339
1838
  transport = null;
1839
+ welcomed = false;
1840
+ held = [];
1340
1841
  status.set('connecting');
1341
1842
  reconnectTimer = setTimeout(connectSignaling, 1000);
1342
1843
  }),
@@ -1359,8 +1860,13 @@ function peerLinks(opt) {
1359
1860
  if (closed)
1360
1861
  return;
1361
1862
  closed = true;
1863
+ held = [];
1362
1864
  if (reconnectTimer !== undefined)
1363
1865
  clearTimeout(reconnectTimer);
1866
+ feed({ t: 'close' });
1867
+ // a takeover's open timeout on a link the lifecycle already counts open
1868
+ for (const origin of [...timers.keys()])
1869
+ disarm(origin);
1364
1870
  for (const origin of [...peers.keys()])
1365
1871
  dropPeer(origin);
1366
1872
  for (const unsub of signalingUnsubs.splice(0))
@@ -1384,6 +1890,7 @@ function peerLinks(opt) {
1384
1890
  return {
1385
1891
  status: status.asReadonly(),
1386
1892
  peers: computed(() => [...openPeers()]),
1893
+ stalled: computed(() => [...lifecycle()].filter(([, e]) => e.stalled).map(([origin]) => origin)),
1387
1894
  members: computed(() => [...members()]),
1388
1895
  onMembers: (cb) => {
1389
1896
  if (!closed)