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