@johnhenry/browsermesh-core 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/handshake.mjs +229 -48
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-core",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Identity, crypto, peer management, and trust primitives for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/handshake.mjs CHANGED
@@ -750,6 +750,29 @@ export class HandshakeCoordinator {
750
750
  /** @type {Map<string, Set<Function>>} */
751
751
  #listeners = new Map()
752
752
 
753
+ /**
754
+ * Tracks, per remote pod, the Promise for this coordinator's one and only
755
+ * negotiation with that peer -- whichever of connectToPeer()'s own offer
756
+ * or acceptConnection()'s handling of an incoming offer actually runs.
757
+ * Both methods consult and populate this map so that "glare" -- two pods
758
+ * each calling connectToPeer() on the other at close to the same time --
759
+ * always settles on exactly one negotiation instead of each side racing
760
+ * its own offerer AND answerer RTCPeerConnection for the same remote pod
761
+ * (four connections total for one pair instead of one each). See #202.
762
+ * @type {Map<string, Promise<{transport: object, sessionInfo: object}>>}
763
+ */
764
+ #peerConnections = new Map()
765
+
766
+ /**
767
+ * Deferred resolvers for connectToPeer() calls that lost the glare
768
+ * tie-break (see #isDesignatedOfferer) and are waiting for
769
+ * acceptConnection() to finish handling the designated offerer's
770
+ * incoming offer for the same remotePodId, instead of sending a second,
771
+ * competing offer of their own.
772
+ * @type {Map<string, Array<{ resolve: Function, reject: Function }>>}
773
+ */
774
+ #glareWaiters = new Map()
775
+
753
776
  /**
754
777
  * @param {object} opts
755
778
  * @param {string} opts.localPodId - Local pod identifier
@@ -796,46 +819,76 @@ export class HandshakeCoordinator {
796
819
  }
797
820
 
798
821
  const timeout = opts.timeout || DEFAULT_TIMEOUT_MS
822
+
823
+ // Glare handling (#202): reuse whatever negotiation with this
824
+ // remotePodId is already in flight or established, rather than
825
+ // starting a second, competing one.
826
+ const existing = this.#peerConnections.get(remotePodId)
827
+ if (existing) {
828
+ this.#onLog(2, `Reusing existing connection/negotiation with ${remotePodId}`)
829
+ return existing
830
+ }
831
+
832
+ if (!this.#isDesignatedOfferer(remotePodId)) {
833
+ // Both sides discover each other independently and both call
834
+ // connectToPeer() on each other at close to the same time -- classic
835
+ // WebRTC "glare". Resolve it with a deterministic tie-breaker both
836
+ // sides can compute alone, with no further coordination: the pod
837
+ // whose ID sorts lower is always the designated offerer. We are not
838
+ // it, so don't race our own offer -- wait for remotePodId's offer to
839
+ // arrive over signaling and be handled by acceptConnection(), and
840
+ // adopt that session instead.
841
+ this.#onLog(2, `Deferring to ${remotePodId} as designated offerer (glare tie-break)`)
842
+ return this.#waitForPeerConnection(remotePodId, timeout)
843
+ }
844
+
799
845
  this.#onLog(2, `Initiating connection to ${remotePodId}`)
800
846
 
801
847
  const endpointOpts = opts.endpoints || {
802
848
  webrtc: { config: { iceServers: opts.iceServers || [] } },
803
849
  }
804
850
 
805
- let timeoutHandle
806
- const transport = await Promise.race([
807
- this.#transportFactory.negotiate(
808
- this.#localPodId,
851
+ const promise = (async () => {
852
+ let timeoutHandle
853
+ const transport = await Promise.race([
854
+ this.#transportFactory.negotiate(
855
+ this.#localPodId,
856
+ remotePodId,
857
+ this.#signalingClient,
858
+ endpointOpts,
859
+ ),
860
+ new Promise((_, reject) => {
861
+ timeoutHandle = setTimeout(() => reject(new Error('Connection timeout')), timeout)
862
+ }),
863
+ ])
864
+ clearTimeout(timeoutHandle)
865
+
866
+ // TransportFactory.negotiate() returns a transport that has been
867
+ // created but not yet connected (see its docstring) -- no offer,
868
+ // answer or ICE candidate has crossed the wire yet. Mirror
869
+ // acceptConnection()'s `await transport.handleOffer(offer)` on the
870
+ // answerer side by actually driving the handshake here before this
871
+ // session is adopted as 'connected'.
872
+ if (typeof transport.connect === 'function') {
873
+ await transport.connect()
874
+ }
875
+
876
+ const sessionInfo = {
877
+ localPodId: this.#localPodId,
809
878
  remotePodId,
810
- this.#signalingClient,
811
- endpointOpts,
812
- ),
813
- new Promise((_, reject) => {
814
- timeoutHandle = setTimeout(() => reject(new Error('Connection timeout')), timeout)
815
- }),
816
- ])
817
- clearTimeout(timeoutHandle)
818
-
819
- // TransportFactory.negotiate() returns a transport that has been
820
- // created but not yet connected (see its docstring) -- no offer,
821
- // answer or ICE candidate has crossed the wire yet. Mirror
822
- // acceptConnection()'s `await transport.handleOffer(offer)` on the
823
- // answerer side by actually driving the handshake here before this
824
- // session is adopted as 'connected'.
825
- if (typeof transport.connect === 'function') {
826
- await transport.connect()
827
- }
879
+ transportType: transport.type,
880
+ establishedAt: Date.now(),
881
+ }
828
882
 
829
- const sessionInfo = {
830
- localPodId: this.#localPodId,
831
- remotePodId,
832
- transportType: transport.type,
833
- establishedAt: Date.now(),
834
- }
883
+ this.#onLog(2, `Connected to ${remotePodId} via ${transport.type}`)
884
+ const result = { transport, sessionInfo }
885
+ this.#forgetPeerConnectionOnClose(remotePodId, transport)
886
+ this.#fire('connected', { remotePodId, transport, sessionInfo })
887
+ return result
888
+ })()
835
889
 
836
- this.#onLog(2, `Connected to ${remotePodId} via ${transport.type}`)
837
- this.#fire('connected', { remotePodId, transport, sessionInfo })
838
- return { transport, sessionInfo }
890
+ this.#settlePeerConnection(remotePodId, promise)
891
+ return promise
839
892
  }
840
893
 
841
894
  /**
@@ -856,28 +909,54 @@ export class HandshakeCoordinator {
856
909
  throw new Error('SignalingClient is required for acceptConnection')
857
910
  }
858
911
 
912
+ // Glare handling (#202): mirror connectToPeer()'s dedup.
913
+ const existing = this.#peerConnections.get(remotePodId)
914
+ if (existing) {
915
+ if (this.#isDesignatedOfferer(remotePodId)) {
916
+ // We are the designated offerer for this pair and already have our
917
+ // own negotiation with remotePodId in flight or established. This
918
+ // incoming offer is a late/duplicate glare offer from the side
919
+ // that should have deferred to ours -- ignore it instead of
920
+ // starting a second, competing negotiation.
921
+ this.#onLog(1, `Ignoring incoming offer from ${remotePodId}: already the designated offerer (glare tie-break)`)
922
+ return existing
923
+ }
924
+ // Not the designated offerer, and already negotiating/negotiated
925
+ // with remotePodId (a duplicate/retried offer for the same pair,
926
+ // or this accept is already underway) -- reuse it.
927
+ this.#onLog(2, `Reusing existing negotiation with ${remotePodId}`)
928
+ return existing
929
+ }
930
+
859
931
  this.#onLog(2, `Accepting connection from ${remotePodId}`)
860
932
 
861
- const transport = await this.#transportFactory.create('webrtc', {
862
- localPodId: this.#localPodId,
863
- remotePodId,
864
- signaler: this.#signalingClient,
865
- })
933
+ const promise = (async () => {
934
+ const transport = await this.#transportFactory.create('webrtc', {
935
+ localPodId: this.#localPodId,
936
+ remotePodId,
937
+ signaler: this.#signalingClient,
938
+ })
866
939
 
867
- if (typeof transport.handleOffer === 'function') {
868
- await transport.handleOffer(offer)
869
- }
940
+ if (typeof transport.handleOffer === 'function') {
941
+ await transport.handleOffer(offer)
942
+ }
870
943
 
871
- const sessionInfo = {
872
- localPodId: this.#localPodId,
873
- remotePodId,
874
- transportType: transport.type,
875
- establishedAt: Date.now(),
876
- }
944
+ const sessionInfo = {
945
+ localPodId: this.#localPodId,
946
+ remotePodId,
947
+ transportType: transport.type,
948
+ establishedAt: Date.now(),
949
+ }
877
950
 
878
- this.#onLog(2, `Accepted connection from ${remotePodId}`)
879
- this.#fire('connected', { remotePodId, transport, sessionInfo })
880
- return { transport, sessionInfo }
951
+ this.#onLog(2, `Accepted connection from ${remotePodId}`)
952
+ const result = { transport, sessionInfo }
953
+ this.#forgetPeerConnectionOnClose(remotePodId, transport)
954
+ this.#fire('connected', { remotePodId, transport, sessionInfo })
955
+ return result
956
+ })()
957
+
958
+ this.#settlePeerConnection(remotePodId, promise)
959
+ return promise
881
960
  }
882
961
 
883
962
  /**
@@ -1020,6 +1099,108 @@ export class HandshakeCoordinator {
1020
1099
 
1021
1100
  // -- Internal -------------------------------------------------------------
1022
1101
 
1102
+ /**
1103
+ * Deterministic glare tie-break (#202): exactly one side of any pod pair
1104
+ * is the designated offerer, decided purely from both pods' own IDs so
1105
+ * both sides agree without any further coordination -- neither needs to
1106
+ * know what the other is doing, only its ID. The lower podId is always
1107
+ * the designated offerer; the higher podId always defers to the
1108
+ * incoming offer instead of sending its own.
1109
+ * @param {string} remotePodId
1110
+ * @returns {boolean} true when the local pod is the designated offerer.
1111
+ */
1112
+ #isDesignatedOfferer(remotePodId) {
1113
+ return this.#localPodId < remotePodId
1114
+ }
1115
+
1116
+ /**
1117
+ * Wait for acceptConnection() to settle a negotiation for remotePodId
1118
+ * that this coordinator lost the glare tie-break for, instead of racing
1119
+ * a second offer of its own. Resolves/rejects exactly like the
1120
+ * negotiation itself; rejects on timeout, matching connectToPeer()'s own
1121
+ * "Connection timeout" behavior for the offerer path.
1122
+ * @param {string} remotePodId
1123
+ * @param {number} timeoutMs
1124
+ * @returns {Promise<{transport: object, sessionInfo: object}>}
1125
+ */
1126
+ #waitForPeerConnection(remotePodId, timeoutMs) {
1127
+ // Re-check: acceptConnection() may have already settled this between
1128
+ // connectToPeer()'s own check and this call.
1129
+ const existing = this.#peerConnections.get(remotePodId)
1130
+ if (existing) return existing
1131
+
1132
+ return new Promise((resolve, reject) => {
1133
+ const entry = {}
1134
+ const timeoutHandle = setTimeout(() => {
1135
+ const list = this.#glareWaiters.get(remotePodId)
1136
+ if (list) {
1137
+ const idx = list.indexOf(entry)
1138
+ if (idx !== -1) list.splice(idx, 1)
1139
+ if (list.length === 0) this.#glareWaiters.delete(remotePodId)
1140
+ }
1141
+ reject(new Error(`Timed out waiting for ${remotePodId}'s offer (lost glare tie-break)`))
1142
+ }, timeoutMs)
1143
+ entry.resolve = (value) => { clearTimeout(timeoutHandle); resolve(value) }
1144
+ entry.reject = (err) => { clearTimeout(timeoutHandle); reject(err) }
1145
+
1146
+ if (!this.#glareWaiters.has(remotePodId)) this.#glareWaiters.set(remotePodId, [])
1147
+ this.#glareWaiters.get(remotePodId).push(entry)
1148
+ })
1149
+ }
1150
+
1151
+ /**
1152
+ * Record `promise` as this coordinator's one negotiation with
1153
+ * remotePodId, and wake any connectToPeer() calls that deferred to it
1154
+ * (see #waitForPeerConnection) once it settles. On rejection, forgets
1155
+ * the entry so a later, genuine reconnection attempt isn't permanently
1156
+ * blocked by a failed one.
1157
+ * @param {string} remotePodId
1158
+ * @param {Promise<{transport: object, sessionInfo: object}>} promise
1159
+ */
1160
+ #settlePeerConnection(remotePodId, promise) {
1161
+ this.#peerConnections.set(remotePodId, promise)
1162
+ promise.then(
1163
+ (value) => {
1164
+ const waiters = this.#glareWaiters.get(remotePodId)
1165
+ if (!waiters) return
1166
+ this.#glareWaiters.delete(remotePodId)
1167
+ for (const w of waiters) w.resolve(value)
1168
+ },
1169
+ (err) => {
1170
+ if (this.#peerConnections.get(remotePodId) === promise) {
1171
+ this.#peerConnections.delete(remotePodId)
1172
+ }
1173
+ const waiters = this.#glareWaiters.get(remotePodId)
1174
+ if (!waiters) return
1175
+ this.#glareWaiters.delete(remotePodId)
1176
+ for (const w of waiters) w.reject(err)
1177
+ },
1178
+ )
1179
+ }
1180
+
1181
+ /**
1182
+ * Once an established session's transport actually closes, forget it so
1183
+ * a genuine future reconnection to remotePodId isn't permanently blocked
1184
+ * by #peerConnections/#isDesignatedOfferer dedup (#202). No-op when the
1185
+ * transport exposes no onClose (mirrors connectViaToken()'s own handling
1186
+ * of that case).
1187
+ * @param {string} remotePodId
1188
+ * @param {object} transport
1189
+ */
1190
+ #forgetPeerConnectionOnClose(remotePodId, transport) {
1191
+ if (typeof transport.onClose !== 'function') return
1192
+ transport.onClose(() => {
1193
+ // Only delete if this transport's own entry is still the current
1194
+ // one -- a newer negotiation for the same remotePodId may already
1195
+ // have replaced it by the time this fires.
1196
+ const current = this.#peerConnections.get(remotePodId)
1197
+ if (!current) return
1198
+ current.then((v) => {
1199
+ if (v && v.transport === transport) this.#peerConnections.delete(remotePodId)
1200
+ }, () => {})
1201
+ })
1202
+ }
1203
+
1023
1204
  /**
1024
1205
  * Fire all listeners for a given event, swallowing listener errors.
1025
1206
  * @param {string} event