@mmstack/mesh 22.9.0 → 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
- import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource } from '@mmstack/primitives/core';
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 } 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,38 +1165,254 @@ function directTransport(relay, ctx) {
985
1165
  };
986
1166
  }
987
1167
 
988
- /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
989
- function rtcPeerConnector(config) {
990
- return ({ polite, sendSignal }) => {
991
- const pc = new RTCPeerConnection(config);
992
- const messageCbs = new Set();
993
- const openCbs = new Set();
994
- const closeCbs = new Set();
995
- const pending = [];
996
- let dc = null;
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;
1277
+ /** The single reliable channel every link carries when no channels are asked for. */
1278
+ const defaultPeerChannels = [
1279
+ { label: 'mmstack-mesh' },
1280
+ ];
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);
997
1305
  let makingOffer = false;
998
1306
  let ignoreOffer = false;
999
- const attach = (channel) => {
1000
- dc = channel;
1001
- channel.onmessage = (e) => {
1002
- for (const cb of [...messageCbs])
1003
- cb(String(e.data));
1004
- };
1005
- channel.onopen = () => {
1006
- for (const frame of pending.splice(0))
1007
- channel.send(frame);
1008
- for (const cb of [...openCbs])
1009
- cb();
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
+ };
1364
+ const makeChannel = () => {
1365
+ const messageCbs = new Set();
1366
+ const openCbs = new Set();
1367
+ const closeCbs = new Set();
1368
+ const pending = [];
1369
+ let dc = null;
1370
+ const attach = (channel) => {
1371
+ dc = channel;
1372
+ channel.onmessage = (e) => {
1373
+ for (const cb of [...messageCbs])
1374
+ cb(String(e.data));
1375
+ };
1376
+ channel.onopen = () => {
1377
+ for (const frame of pending.splice(0))
1378
+ channel.send(frame);
1379
+ for (const cb of [...openCbs])
1380
+ cb();
1381
+ };
1382
+ channel.onclose = () => {
1383
+ for (const cb of [...closeCbs])
1384
+ cb();
1385
+ };
1010
1386
  };
1011
- channel.onclose = () => {
1012
- for (const cb of [...closeCbs])
1013
- cb();
1387
+ const like = {
1388
+ send: (frame) => {
1389
+ if (dc && dc.readyState === 'open')
1390
+ dc.send(frame);
1391
+ else
1392
+ pending.push(frame);
1393
+ },
1394
+ onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1395
+ onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1396
+ onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1397
+ close: () => dc?.close(),
1014
1398
  };
1399
+ return { attach, like };
1015
1400
  };
1016
- if (!polite)
1017
- attach(pc.createDataChannel('mmstack-mesh'));
1018
- else
1019
- pc.ondatachannel = (e) => attach(e.channel);
1401
+ const made = new Map(channels.map((c) => [c.label, makeChannel()]));
1402
+ // the impolite side opens every channel; the polite side adopts them by label
1403
+ if (!polite) {
1404
+ for (const spec of channels) {
1405
+ const init = {};
1406
+ if (spec.ordered !== undefined)
1407
+ init.ordered = spec.ordered;
1408
+ if (spec.maxRetransmits !== undefined)
1409
+ init.maxRetransmits = spec.maxRetransmits;
1410
+ made.get(spec.label)?.attach(pc.createDataChannel(spec.label, init));
1411
+ }
1412
+ }
1413
+ else {
1414
+ pc.ondatachannel = (e) => made.get(e.channel.label)?.attach(e.channel);
1415
+ }
1020
1416
  pc.onicecandidate = (e) => {
1021
1417
  if (e.candidate)
1022
1418
  sendSignal({ ice: e.candidate.toJSON() });
@@ -1027,24 +1423,22 @@ function rtcPeerConnector(config) {
1027
1423
  await pc.setLocalDescription();
1028
1424
  sendSignal({ description: pc.localDescription });
1029
1425
  }
1426
+ catch (err) {
1427
+ rejected('make an offer', err);
1428
+ }
1030
1429
  finally {
1031
1430
  makingOffer = false;
1032
1431
  }
1033
1432
  };
1433
+ const byLabel = {};
1434
+ for (const [label, ch] of made)
1435
+ byLabel[label] = ch.like;
1034
1436
  return {
1035
- channel: {
1036
- send: (frame) => {
1037
- if (dc && dc.readyState === 'open')
1038
- dc.send(frame);
1039
- else
1040
- pending.push(frame);
1041
- },
1042
- onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1043
- onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1044
- onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1045
- close: () => dc?.close(),
1046
- },
1437
+ channel: byLabel[channels[0].label],
1438
+ channels: byLabel,
1047
1439
  signal: async (data) => {
1440
+ if (pc.signalingState === 'closed')
1441
+ return;
1048
1442
  const { description, ice } = (data ?? {});
1049
1443
  if (description) {
1050
1444
  const collision = description.type === 'offer' &&
@@ -1052,10 +1446,15 @@ function rtcPeerConnector(config) {
1052
1446
  ignoreOffer = !polite && collision;
1053
1447
  if (ignoreOffer)
1054
1448
  return;
1055
- await pc.setRemoteDescription(description);
1056
- if (description.type === 'offer') {
1057
- await pc.setLocalDescription();
1058
- 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);
1059
1458
  }
1060
1459
  }
1061
1460
  else if (ice) {
@@ -1068,54 +1467,108 @@ function rtcPeerConnector(config) {
1068
1467
  }
1069
1468
  }
1070
1469
  },
1470
+ onClose: (cb) => (goneCbs.add(cb), () => goneCbs.delete(cb)),
1071
1471
  close: () => {
1072
- dc?.close();
1472
+ finished = true;
1473
+ clearGrace();
1474
+ for (const ch of made.values())
1475
+ ch.like.close();
1073
1476
  pc.close();
1074
1477
  },
1075
1478
  };
1076
1479
  };
1077
1480
  }
1078
1481
  /**
1079
- * Peer-to-peer mesh sync: the relay only signals
1080
- * and tracks membership; envelopes flow over WebRTC data channels and converge via the
1081
- * per-path register map. Catch-up is pairwise: on channel open both sides exchange
1082
- * watermarks; a side whose state is strictly covered hydrates from the other's FULL
1083
- * checkpoint (root + per-path register state + watermark), so supersession and precedence
1084
- * carry over intact: a late joiner is indistinguishable from a peer that saw every
1085
- * envelope. Two peers that each hold envelopes the other lacks keep their convergent
1086
- * go-forward guarantees but do not exchange the missed envelopes retroactively.
1482
+ * A signal payload split into its addressing and the connector's part: `link` is the sending
1483
+ * instance, `to` the receiving instance it was bound to when it sent (absent until it is).
1484
+ */
1485
+ const unwrapSignal = (data) => {
1486
+ if (typeof data !== 'object' || data === null)
1487
+ return { payload: data };
1488
+ const { link, to, ...rest } = data;
1489
+ if (typeof link !== 'string')
1490
+ return { payload: data };
1491
+ return {
1492
+ link,
1493
+ to: typeof to === 'string' ? to : undefined,
1494
+ payload: Object.keys(rest).length ? rest : undefined,
1495
+ };
1496
+ };
1497
+ /**
1498
+ * The link layer under peer-to-peer consumers: one peer connection per remote origin in the
1499
+ * room, set up from relay membership and negotiated over relay `signal` frames. Each link
1500
+ * carries the same labelled channels; frames are opaque strings, what they mean is the
1501
+ * consumer's business.
1087
1502
  *
1088
- * There is no relay admission here: no sequence, no generation, no refusals. Beside a
1089
- * relay-backed session over the same document a peer channel may hand on only envelopes the
1090
- * relay has sequenced, never a peer's own unacknowledged writes.
1503
+ * An origin is one seat: the relay hands a second connection with the same origin the seat
1504
+ * and reports it to the room as a plain join. Links tell seats apart by instance, not by
1505
+ * order: every link announces a random instance id in its signals and, once it knows the
1506
+ * instance across, addresses its signals to it. A signal addressed to an instance this side
1507
+ * no longer has is dropped. An unaddressed signal from an instance other than the one linked
1508
+ * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed
1509
+ * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
1510
+ * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
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.
1091
1522
  */
1092
- function webRtcMesh(source, opt) {
1523
+ function peerLinks(opt) {
1093
1524
  const injector = opt.injector ?? inject(Injector);
1094
1525
  const connector = opt.connector ?? rtcPeerConnector();
1526
+ const specs = opt.channels?.length ? opt.channels : defaultPeerChannels;
1527
+ const labels = specs.map((c) => c.label);
1528
+ const primary = labels[0];
1095
1529
  const status = signal('connecting', /* @ts-ignore */
1096
1530
  ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
1097
1531
  const openPeers = signal(new Set(), /* @ts-ignore */
1098
1532
  ...(ngDevMode ? [{ debugName: "openPeers" }] : /* istanbul ignore next */ []));
1533
+ const members = signal(new Set(), /* @ts-ignore */
1534
+ ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
1099
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;
1548
+ const openCbs = new Set();
1549
+ const messageCbs = new Set();
1550
+ const closeCbs = new Set();
1551
+ const endCbs = new Set();
1552
+ const memberCbs = new Set();
1100
1553
  let signalingUnsubs = [];
1101
1554
  let transport = null;
1102
1555
  let reconnectTimer;
1556
+ let connected = false;
1103
1557
  let closed = false;
1104
- const sync = opSync(source, {
1105
- writer: opt.writer,
1106
- policies: opt.policies,
1107
- policyVersion: opt.policyVersion,
1108
- injector,
1109
- });
1110
- const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1111
- const sendTo = (peer, msg) => {
1112
- peer.link.channel.send(JSON.stringify(msg));
1113
- };
1114
- const broadcast = (msg) => {
1115
- for (const peer of peers.values()) {
1116
- if (peer.open)
1117
- sendTo(peer, msg);
1118
- }
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;
1563
+ // links are told apart by instance, never by order: a random tag plus a counter
1564
+ const tag = Math.random().toString(36).slice(2, 10);
1565
+ let linkSeq = 0;
1566
+ const port = typeof opt.signaling === 'function' ? null : opt.signaling;
1567
+ const sendSignal = (msg) => {
1568
+ if (port)
1569
+ port.send(msg);
1570
+ else
1571
+ transport?.send(msg);
1119
1572
  };
1120
1573
  const dropPeer = (origin) => {
1121
1574
  const peer = peers.get(origin);
@@ -1130,75 +1583,245 @@ function webRtcMesh(source, opt) {
1130
1583
  next.delete(origin);
1131
1584
  return next;
1132
1585
  });
1586
+ for (const cb of [...closeCbs])
1587
+ cb(origin);
1133
1588
  };
1134
- const ensurePeer = (origin) => {
1135
- let peer = peers.get(origin);
1136
- if (peer)
1137
- return peer;
1589
+ /**
1590
+ * Builds the link to `origin`; `remote` is the instance on the other side when the link is
1591
+ * built in answer to one of its signals, so everything this side sends is addressed to it.
1592
+ */
1593
+ const ensurePeer = (origin, remote) => {
1594
+ const existing = peers.get(origin);
1595
+ if (existing)
1596
+ return existing;
1597
+ const id = `${tag}.${++linkSeq}`;
1598
+ // signals the connector sends while it is still being built wait until the peer is
1599
+ // registered, so the remote's synchronous answer finds it instead of building another
1600
+ let building = [];
1601
+ let retired = false;
1602
+ const signal = (data) => {
1603
+ if (retired)
1604
+ return;
1605
+ if (building) {
1606
+ building.push(data);
1607
+ return;
1608
+ }
1609
+ const stamped = typeof data === 'object' && data !== null
1610
+ ? {
1611
+ ...data,
1612
+ link: id,
1613
+ ...(p.remote === undefined ? {} : { to: p.remote }),
1614
+ }
1615
+ : data;
1616
+ sendSignal({ t: 'signal', room: opt.room, to: origin, data: stamped });
1617
+ };
1138
1618
  const link = connector({
1139
1619
  remote: origin,
1140
- polite: sync.origin > origin,
1141
- sendSignal: (data) => transport?.send({ t: 'signal', room: opt.room, to: origin, data }),
1620
+ polite: opt.origin > origin,
1621
+ sendSignal: signal,
1622
+ channels: specs,
1623
+ ...(iceServers ? { iceServers } : {}),
1142
1624
  });
1143
- peer = { link, open: false, unsubs: [] };
1144
- peers.set(origin, peer);
1145
- peer.unsubs.push(link.channel.onOpen(() => {
1146
- peer.open = true;
1147
- openPeers.update((set) => new Set(set).add(origin));
1148
- sendTo(peer, { t: 'hello', wm: sync.watermark() });
1149
- }), link.channel.onMessage((frame) => {
1150
- let msg;
1151
- try {
1152
- msg = JSON.parse(frame);
1153
- }
1154
- catch {
1155
- return;
1156
- }
1157
- handlePeerMsg(peer, msg);
1158
- }), link.channel.onClose(() => dropPeer(origin)));
1159
- return peer;
1160
- };
1161
- const handlePeerMsg = (peer, msg) => {
1162
- switch (msg.t) {
1163
- case 'hello': {
1164
- const snap = sync.snapshot();
1165
- if (covered(snap.wm, msg.wm))
1166
- sendTo(peer, { t: 'uptodate' });
1167
- else
1168
- sendTo(peer, { t: 'state', state: snap });
1169
- return;
1625
+ const p = {
1626
+ id,
1627
+ remote,
1628
+ link,
1629
+ channels: new Map(),
1630
+ unsubs: [() => (retired = true)],
1631
+ };
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));
1639
+ const early = building;
1640
+ building = null;
1641
+ // announce the instance, so a side that still holds a link to an earlier seat of this
1642
+ // origin (a takeover the relay reports as a plain join) replaces it
1643
+ signal({});
1644
+ for (const data of early)
1645
+ signal(data);
1646
+ for (const label of labels) {
1647
+ const channel = link.channels?.[label] ??
1648
+ (label === primary ? link.channel : undefined);
1649
+ if (!channel) {
1650
+ if (isDevMode()) {
1651
+ console.warn(`[@mmstack/mesh] the peer connector returned no channel labelled '${label}'`);
1652
+ }
1653
+ continue;
1170
1654
  }
1171
- case 'state': {
1172
- if (covered(sync.watermark(), msg.state.wm)) {
1173
- sync.hydrate(msg.state);
1655
+ const state = { channel, open: false };
1656
+ p.channels.set(label, state);
1657
+ p.unsubs.push(channel.onOpen(() => {
1658
+ state.open = true;
1659
+ if (peers.get(origin) === p &&
1660
+ labels.every((l) => p.channels.get(l)?.open)) {
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);
1174
1667
  }
1668
+ for (const cb of [...openCbs])
1669
+ cb(origin, label);
1670
+ }), channel.onMessage((frame) => {
1671
+ for (const cb of [...messageCbs])
1672
+ cb(origin, frame, label);
1673
+ }), channel.onClose(lost));
1674
+ }
1675
+ return p;
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)
1175
1687
  return;
1176
- }
1177
- case 'uptodate':
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);
1178
1705
  return;
1179
- case 'env':
1180
- sync.receive(msg.env);
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
+ }
1727
+ const setMembers = (origins) => {
1728
+ const next = new Set(origins);
1729
+ members.set(next);
1730
+ for (const cb of [...memberCbs])
1731
+ cb([...next]);
1732
+ };
1733
+ const welcomeMembers = (origins, ice) => {
1734
+ setMembers(origins);
1735
+ iceServers = ice;
1736
+ welcomed = true;
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)
1181
1743
  return;
1744
+ handleSignaling(msg);
1182
1745
  }
1183
1746
  };
1184
1747
  const handleSignaling = (msg) => {
1185
- if (msg.room !== opt.room)
1748
+ if (closed || msg.room !== opt.room)
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
+ }
1186
1763
  return;
1764
+ }
1187
1765
  switch (msg.t) {
1188
1766
  case 'welcome':
1189
- for (const origin of msg.members)
1190
- ensurePeer(origin);
1191
- status.set('live');
1767
+ welcomeMembers(msg.members, msg.ice);
1192
1768
  return;
1193
1769
  case 'member':
1194
- if (msg.gone)
1195
- dropPeer(msg.origin);
1196
- else
1197
- ensurePeer(msg.origin);
1770
+ setMembers(msg.gone
1771
+ ? [...members()].filter((origin) => origin !== msg.origin)
1772
+ : [...new Set([...members(), msg.origin])]);
1773
+ feed({ t: msg.gone ? 'gone' : 'listed', origin: msg.origin });
1198
1774
  return;
1199
- case 'signal':
1200
- ensurePeer(msg.from).link.signal(msg.data);
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
+ }
1784
+ const { link, to, payload } = unwrapSignal(msg.data);
1785
+ let peer = peers.get(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;
1794
+ }
1795
+ else if (to !== undefined && to !== peer?.id) {
1796
+ // addressed to an instance this side no longer has: a retired link's leftovers
1797
+ return;
1798
+ }
1799
+ else if (!peer) {
1800
+ return;
1801
+ }
1802
+ else if (peer.remote === undefined) {
1803
+ peer.remote = link;
1804
+ }
1805
+ else if (peer.remote !== link) {
1806
+ if (to === undefined) {
1807
+ // a new instance over there that does not know this side yet: a new seat or a
1808
+ // restarted link, so this side rebuilds, addressing it, which is what makes the
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.
1812
+ dropPeer(msg.from);
1813
+ arm(msg.from, openTimeoutMs, { t: 'lost', origin: msg.from });
1814
+ peer = ensurePeer(msg.from, link);
1815
+ }
1816
+ else {
1817
+ // built for this very instance, so it is the newer end of this link: adopt it
1818
+ peer.remote = link;
1819
+ }
1820
+ }
1821
+ if (payload !== undefined)
1822
+ peer.link.signal(payload);
1201
1823
  return;
1824
+ }
1202
1825
  case 'reject':
1203
1826
  close();
1204
1827
  return;
@@ -1209,6 +1832,18 @@ function webRtcMesh(source, opt) {
1209
1832
  return;
1210
1833
  for (const unsub of signalingUnsubs.splice(0))
1211
1834
  unsub();
1835
+ if (port) {
1836
+ const unsub = port.onMessage(handleSignaling);
1837
+ if (closed) {
1838
+ unsub();
1839
+ return;
1840
+ }
1841
+ signalingUnsubs = [unsub];
1842
+ const current = port.members();
1843
+ if (current !== undefined)
1844
+ welcomeMembers(current, port.iceServers?.());
1845
+ return;
1846
+ }
1212
1847
  const t = opt.signaling();
1213
1848
  transport = t;
1214
1849
  signalingUnsubs = [
@@ -1217,39 +1852,345 @@ function webRtcMesh(source, opt) {
1217
1852
  if (closed || transport !== t)
1218
1853
  return;
1219
1854
  transport = null;
1855
+ welcomed = false;
1856
+ held = [];
1857
+ status.set('connecting');
1220
1858
  reconnectTimer = setTimeout(connectSignaling, 1000);
1221
1859
  }),
1222
1860
  ];
1223
1861
  t.send({
1224
1862
  t: 'hello',
1225
1863
  room: opt.room,
1226
- origin: sync.origin,
1864
+ origin: opt.origin,
1227
1865
  proto: MESH_PROTO_VERSION,
1228
1866
  policyVersion: opt.policyVersion ?? 0,
1229
1867
  });
1230
1868
  };
1231
- const unsubLocal = sync.subscribe((env) => broadcast({ t: 'env', env }));
1869
+ const connect = () => {
1870
+ if (connected || closed)
1871
+ return;
1872
+ connected = true;
1873
+ connectSignaling();
1874
+ };
1232
1875
  const close = () => {
1233
1876
  if (closed)
1234
1877
  return;
1235
1878
  closed = true;
1879
+ held = [];
1236
1880
  if (reconnectTimer !== undefined)
1237
1881
  clearTimeout(reconnectTimer);
1238
- unsubLocal();
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);
1239
1886
  for (const origin of [...peers.keys()])
1240
1887
  dropPeer(origin);
1241
1888
  for (const unsub of signalingUnsubs.splice(0))
1242
1889
  unsub();
1243
1890
  transport?.close();
1244
1891
  transport = null;
1245
- sync.destroy();
1892
+ setMembers([]);
1893
+ memberCbs.clear();
1246
1894
  status.set('connecting');
1895
+ for (const cb of [...endCbs])
1896
+ cb();
1897
+ endCbs.clear();
1898
+ };
1899
+ const openChannel = (origin, label) => {
1900
+ const state = peers.get(origin)?.channels.get(label);
1901
+ return state?.open ? state.channel : null;
1247
1902
  };
1248
1903
  injector.get(DestroyRef).onDestroy(close);
1249
- connectSignaling();
1904
+ if (opt.autoConnect !== false)
1905
+ connect();
1250
1906
  return {
1251
1907
  status: status.asReadonly(),
1252
1908
  peers: computed(() => [...openPeers()]),
1909
+ stalled: computed(() => [...lifecycle()].filter(([, e]) => e.stalled).map(([origin]) => origin)),
1910
+ members: computed(() => [...members()]),
1911
+ onMembers: (cb) => {
1912
+ if (!closed)
1913
+ memberCbs.add(cb);
1914
+ cb([...members()]);
1915
+ return () => memberCbs.delete(cb);
1916
+ },
1917
+ channels: labels,
1918
+ onOpen: (cb) => {
1919
+ openCbs.add(cb);
1920
+ for (const [origin, peer] of peers) {
1921
+ for (const [label, state] of peer.channels) {
1922
+ if (state.open)
1923
+ cb(origin, label);
1924
+ }
1925
+ }
1926
+ return () => openCbs.delete(cb);
1927
+ },
1928
+ onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1929
+ onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1930
+ onEnd: (cb) => (endCbs.add(cb), () => endCbs.delete(cb)),
1931
+ send: (origin, frame, channel = primary) => {
1932
+ openChannel(origin, channel)?.send(frame);
1933
+ },
1934
+ broadcast: (frame, channel = primary) => {
1935
+ for (const origin of peers.keys())
1936
+ openChannel(origin, channel)?.send(frame);
1937
+ },
1938
+ connect,
1939
+ close,
1940
+ };
1941
+ }
1942
+
1943
+ /**
1944
+ * Peer-to-peer mesh sync: the relay only signals
1945
+ * and tracks membership; envelopes flow over WebRTC data channels and converge via the
1946
+ * per-path register map. Catch-up is pairwise: on channel open both sides exchange
1947
+ * watermarks; a side whose state is strictly covered hydrates from the other's FULL
1948
+ * checkpoint (root + per-path register state + watermark), so supersession and precedence
1949
+ * carry over intact: a late joiner is indistinguishable from a peer that saw every
1950
+ * envelope. Two peers that each hold envelopes the other lacks keep their convergent
1951
+ * go-forward guarantees but do not exchange the missed envelopes retroactively.
1952
+ *
1953
+ * There is no relay admission here: no sequence, no generation, no refusals. Beside a
1954
+ * relay-backed session over the same document a peer channel may hand on only envelopes the
1955
+ * relay has sequenced, never a peer's own unacknowledged writes.
1956
+ */
1957
+ function webRtcMesh(source, opt) {
1958
+ const injector = opt.injector ?? inject(Injector);
1959
+ const meshChannel = defaultPeerChannels[0];
1960
+ let closed = false;
1961
+ const sync = opSync(source, {
1962
+ writer: opt.writer,
1963
+ origin: opt.origin,
1964
+ policies: opt.policies,
1965
+ policyVersion: opt.policyVersion,
1966
+ injector,
1967
+ });
1968
+ // subscribe before signaling starts: a link can open, and its first frame arrive, while
1969
+ // the hello is still being answered
1970
+ const links = peerLinks({
1971
+ room: opt.room,
1972
+ origin: sync.origin,
1973
+ signaling: opt.signaling,
1974
+ connector: opt.connector,
1975
+ channels: [
1976
+ meshChannel,
1977
+ ...(opt.channels ?? []).filter((c) => c.label !== meshChannel.label),
1978
+ ],
1979
+ policyVersion: opt.policyVersion,
1980
+ autoConnect: false,
1981
+ injector,
1982
+ });
1983
+ const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1984
+ const sendTo = (origin, msg) => {
1985
+ links.send(origin, JSON.stringify(msg));
1986
+ };
1987
+ const handlePeerMsg = (origin, msg) => {
1988
+ switch (msg.t) {
1989
+ case 'hello': {
1990
+ const snap = sync.snapshot();
1991
+ if (covered(snap.wm, msg.wm))
1992
+ sendTo(origin, { t: 'uptodate' });
1993
+ else
1994
+ sendTo(origin, { t: 'state', state: snap });
1995
+ return;
1996
+ }
1997
+ case 'state': {
1998
+ if (covered(sync.watermark(), msg.state.wm)) {
1999
+ sync.hydrate(msg.state);
2000
+ }
2001
+ return;
2002
+ }
2003
+ case 'uptodate':
2004
+ return;
2005
+ case 'env':
2006
+ sync.receive(msg.env);
2007
+ return;
2008
+ }
2009
+ };
2010
+ links.onOpen((origin, channel) => {
2011
+ if (channel === meshChannel.label)
2012
+ sendTo(origin, { t: 'hello', wm: sync.watermark() });
2013
+ });
2014
+ links.onMessage((origin, frame, channel) => {
2015
+ if (channel !== meshChannel.label)
2016
+ return;
2017
+ let msg;
2018
+ try {
2019
+ msg = JSON.parse(frame);
2020
+ }
2021
+ catch {
2022
+ return;
2023
+ }
2024
+ handlePeerMsg(origin, msg);
2025
+ });
2026
+ const unsubLocal = sync.subscribe((env) => links.broadcast(JSON.stringify({ t: 'env', env })));
2027
+ const close = () => {
2028
+ if (closed)
2029
+ return;
2030
+ closed = true;
2031
+ unsubLocal();
2032
+ links.close();
2033
+ sync.destroy();
2034
+ };
2035
+ // a relay reject ends the links; the mesh ends with them
2036
+ links.onEnd(close);
2037
+ links.connect();
2038
+ return {
2039
+ origin: sync.origin,
2040
+ status: links.status,
2041
+ peers: links.peers,
2042
+ links,
2043
+ close,
2044
+ };
2045
+ }
2046
+
2047
+ /**
2048
+ * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that
2049
+ * waits for a retransmit is already stale, and ordering would hold newer frames behind it.
2050
+ * Put it in the `channels` of the {@link PeerLinks} the presence rides on.
2051
+ */
2052
+ const presenceChannel = {
2053
+ label: 'mmstack-presence',
2054
+ ordered: false,
2055
+ maxRetransmits: 0,
2056
+ };
2057
+ const none = Symbol('none');
2058
+ // one send counter per links object and channel, shared by every sender created on them
2059
+ const counters = new WeakMap();
2060
+ const counterOf = (links, label) => {
2061
+ let byLabel = counters.get(links);
2062
+ if (!byLabel)
2063
+ counters.set(links, (byLabel = new Map()));
2064
+ let counter = byLabel.get(label);
2065
+ if (!counter)
2066
+ byLabel.set(label, (counter = { seq: 0 }));
2067
+ return counter;
2068
+ };
2069
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
2070
+ /**
2071
+ * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no
2072
+ * ordering, no retransmits, no catch-up and no persistence. A new link sees nothing until the
2073
+ * sender's next `set`.
2074
+ *
2075
+ * Order comes from causality the receiver observes, never from clocks or from numbers chosen
2076
+ * by different senders. A value is held only for an origin in the roster, and it is removed
2077
+ * as soon as the origin leaves. Within one link the highest `seq` wins and anything at or
2078
+ * below it is dropped: one counter stamps every frame sent on that link in send order, so a
2079
+ * lower `seq` was sent earlier. A link that opens or closes starts its origin fresh, and a
2080
+ * frame of an old link cannot arrive on a new one. An origin that leaves and comes back
2081
+ * starts fresh. Every roster transition is consumed synchronously, even if no frame arrives
2082
+ * and nobody reads `peers` between leave and rejoin.
2083
+ *
2084
+ * The counter belongs to the links and the channel, not to this sender, so a sender closed
2085
+ * and recreated on the same links carries on where the last one stopped and is heard at
2086
+ * once. A new tab or device is a new link, which every receiver already treats as fresh.
2087
+ *
2088
+ * Values travel as JSON.
2089
+ */
2090
+ function rtcPresence(links, opt) {
2091
+ const injector = opt.injector ?? inject(Injector);
2092
+ const label = opt.channel ?? presenceChannel.label;
2093
+ if (!links.channels.includes(label)) {
2094
+ throw new Error(`[@mmstack/mesh] rtcPresence needs a '${label}' channel on its peer links`);
2095
+ }
2096
+ const held = new Map();
2097
+ const version = signal(0, /* @ts-ignore */
2098
+ ...(ngDevMode ? [{ debugName: "version" }] : /* istanbul ignore next */ []));
2099
+ const counter = counterOf(links, label);
2100
+ let closed = false;
2101
+ let roster = new Set();
2102
+ const forget = (origin) => {
2103
+ if (held.delete(origin))
2104
+ version.update((v) => v + 1);
2105
+ };
2106
+ const receive = (origin, frame) => {
2107
+ if (closed)
2108
+ return;
2109
+ let msg;
2110
+ try {
2111
+ msg = JSON.parse(frame);
2112
+ }
2113
+ catch {
2114
+ return;
2115
+ }
2116
+ if (typeof msg !== 'object' ||
2117
+ msg === null ||
2118
+ !isNum(msg.seq) ||
2119
+ !('value' in msg)) {
2120
+ return;
2121
+ }
2122
+ if (!roster.has(origin))
2123
+ return;
2124
+ const prev = held.get(origin);
2125
+ if (prev && msg.seq <= prev.seq)
2126
+ return;
2127
+ held.set(origin, { seq: msg.seq, value: msg.value });
2128
+ version.update((v) => v + 1);
2129
+ };
2130
+ const unsubs = [
2131
+ opt.roster((members) => {
2132
+ roster = new Set(members);
2133
+ for (const origin of held.keys())
2134
+ if (!roster.has(origin))
2135
+ forget(origin);
2136
+ }),
2137
+ links.onMessage((origin, frame, channel) => {
2138
+ if (channel === label)
2139
+ receive(origin, frame);
2140
+ }),
2141
+ // the link is the epoch: a new or lost link starts the origin fresh
2142
+ links.onOpen((origin, channel) => {
2143
+ if (channel === label)
2144
+ forget(origin);
2145
+ }),
2146
+ links.onClose(forget),
2147
+ links.onEnd(() => close()),
2148
+ ];
2149
+ const peers = computed(() => {
2150
+ version();
2151
+ if (closed)
2152
+ return new Map();
2153
+ const out = new Map();
2154
+ for (const [origin, entry] of held) {
2155
+ if (roster.has(origin))
2156
+ out.set(origin, entry.value);
2157
+ }
2158
+ return out;
2159
+ }, /* @ts-ignore */
2160
+ ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
2161
+ const destroyRef = injector.get(DestroyRef);
2162
+ const outgoing = throttled(none, {
2163
+ ms: opt.throttleMs ?? 33,
2164
+ leading: true,
2165
+ trailing: true,
2166
+ destroyRef,
2167
+ });
2168
+ const publisher = effect(() => {
2169
+ const value = outgoing();
2170
+ if (value === none || closed)
2171
+ return;
2172
+ untracked(() => links.broadcast(JSON.stringify({
2173
+ seq: counter.seq++,
2174
+ value,
2175
+ }), label));
2176
+ }, { ...(ngDevMode ? { debugName: "publisher" } : /* istanbul ignore next */ {}), injector });
2177
+ const close = () => {
2178
+ if (closed)
2179
+ return;
2180
+ closed = true;
2181
+ publisher.destroy();
2182
+ for (const unsub of unsubs.splice(0))
2183
+ unsub();
2184
+ held.clear();
2185
+ version.update((v) => v + 1);
2186
+ };
2187
+ destroyRef.onDestroy(close);
2188
+ return {
2189
+ set: (value) => {
2190
+ if (!closed)
2191
+ outgoing.set(value);
2192
+ },
2193
+ peers,
1253
2194
  close,
1254
2195
  };
1255
2196
  }
@@ -1258,5 +2199,5 @@ function webRtcMesh(source, opt) {
1258
2199
  * Generated bundle index. Do not edit.
1259
2200
  */
1260
2201
 
1261
- export { agentSeat, describeOp, directTransport, meshSync, rtcPeerConnector, setAtPath, webRtcMesh, webSocketTransport };
2202
+ export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
1262
2203
  //# sourceMappingURL=mmstack-mesh.mjs.map