refactor: extract PeerSessionManager for testable ICE buffering and glare handling

Extract the ICE candidate buffering, answer routing, and renegotiation
glare logic from CallController into a platform-independent
PeerSessionManager in commons/. This makes the three most critical
NIP-AC spec requirements testable as JVM unit tests with FakePeerSession:

1. Two-layer ICE candidate buffering (global + per-session)
   - Global buffer: candidates arriving before any PeerConnection exists
   - Per-session buffer: candidates arriving before setRemoteDescription
   - Candidates buffered while ringing are preserved when accepting

2. Renegotiation glare handling (pubkey comparison tiebreaker)
   - Higher pubkey wins, lower pubkey rolls back local offer
   - Full glare scenario test with two PeerSessionManagers

3. Callee-to-callee mesh initiation (lower pubkey initiates)

CallController now delegates to PeerSessionManager via a PeerSession
interface, with WebRtcPeerSessionAdapter bridging to WebRtcCallSession.

https://claude.ai/code/session_01AfRYTRCvtKqqDxeKQujUrx
This commit is contained in:
Claude
2026-04-05 15:17:29 +00:00
parent c2347c6cee
commit e9f1fcbd2a
4 changed files with 1010 additions and 144 deletions
@@ -0,0 +1,263 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.call
import com.vitorpamplona.quartz.nip01Core.core.HexKey
/**
* Represents a single ICE candidate received from a peer.
* Platform-neutral — does not depend on org.webrtc.
*/
data class IceCandidateData(
val sdp: String,
val sdpMid: String,
val sdpMLineIndex: Int,
)
/**
* Represents the signaling state of a peer connection.
* Maps 1:1 with WebRTC's PeerConnection.SignalingState.
*/
enum class SignalingState {
STABLE,
HAVE_LOCAL_OFFER,
HAVE_REMOTE_OFFER,
HAVE_LOCAL_PRANSWER,
HAVE_REMOTE_PRANSWER,
CLOSED,
}
/**
* Abstraction over a single peer connection's signaling operations.
* Implemented by the platform-specific WebRTC wrapper.
*/
interface PeerSession {
fun getSignalingState(): SignalingState?
fun setRemoteDescription(
type: SdpType,
sdp: String,
)
fun addIceCandidate(candidate: IceCandidateData)
fun createOffer(onSdpCreated: (String) -> Unit)
fun createAnswer(onSdpCreated: (String) -> Unit)
fun rollback(onDone: () -> Unit)
fun dispose()
}
enum class SdpType {
OFFER,
ANSWER,
}
/**
* Manages per-peer session state and ICE candidate buffering.
*
* This class encapsulates the NIP-AC spec requirements for:
* - **Two-layer ICE buffering**: global buffer (before session exists) and
* per-session buffer (before remote description is set)
* - **Renegotiation glare handling**: pubkey comparison tiebreaker
* - **Callee-to-callee mesh**: lower pubkey initiates
*
* It is platform-independent and testable without real WebRTC.
*/
class PeerSessionManager(
private val localPubKey: HexKey,
) {
data class SessionEntry(
val session: PeerSession,
var remoteDescriptionSet: Boolean = false,
val pendingIceCandidates: MutableList<IceCandidateData> = mutableListOf(),
)
private val sessions = mutableMapOf<HexKey, SessionEntry>()
/** Candidates received before a session exists for the sender. */
private val globalPendingIce = mutableMapOf<HexKey, MutableList<IceCandidateData>>()
// ---- Session management ----
fun registerSession(
peerPubKey: HexKey,
session: PeerSession,
): SessionEntry {
val globalPending = globalPendingIce.remove(peerPubKey) ?: emptyList()
val entry = SessionEntry(session)
entry.pendingIceCandidates.addAll(globalPending)
sessions[peerPubKey] = entry
return entry
}
fun getSession(peerPubKey: HexKey): SessionEntry? = sessions[peerPubKey]
fun hasSession(peerPubKey: HexKey): Boolean = sessions.containsKey(peerPubKey)
fun removeSession(peerPubKey: HexKey): SessionEntry? {
globalPendingIce.remove(peerPubKey)
return sessions.remove(peerPubKey)
}
fun allSessionKeys(): Set<HexKey> = sessions.keys.toSet()
// ---- ICE candidate routing (two-layer buffering) ----
/**
* Routes an incoming ICE candidate to the correct destination:
* 1. If session exists AND remote description is set → add directly
* 2. If session exists but remote description NOT set → buffer per-session
* 3. If no session exists → buffer globally (keyed by sender)
*
* Returns the action taken for testability.
*/
fun routeIceCandidate(
senderPubKey: HexKey,
candidate: IceCandidateData,
): IceRouteAction {
val entry = sessions[senderPubKey]
if (entry != null && entry.remoteDescriptionSet) {
entry.session.addIceCandidate(candidate)
return IceRouteAction.ADDED_DIRECTLY
} else if (entry != null) {
entry.pendingIceCandidates.add(candidate)
return IceRouteAction.BUFFERED_PER_SESSION
} else {
globalPendingIce.getOrPut(senderPubKey) { mutableListOf() }.add(candidate)
return IceRouteAction.BUFFERED_GLOBALLY
}
}
/**
* Flushes all per-session buffered candidates into the PeerConnection.
* Called after setRemoteDescription succeeds.
*/
fun flushPendingIceCandidates(peerPubKey: HexKey): Int {
val entry = sessions[peerPubKey] ?: return 0
entry.remoteDescriptionSet = true
val candidates = entry.pendingIceCandidates.toList()
entry.pendingIceCandidates.clear()
candidates.forEach { entry.session.addIceCandidate(it) }
return candidates.size
}
fun globalPendingCount(peerPubKey: HexKey): Int = globalPendingIce[peerPubKey]?.size ?: 0
fun sessionPendingCount(peerPubKey: HexKey): Int = sessions[peerPubKey]?.pendingIceCandidates?.size ?: 0
// ---- Renegotiation glare handling ----
/**
* Determines how to handle a renegotiation offer when we may have a pending
* local offer (glare condition).
*
* Per NIP-AC spec: "the peer with the higher pubkey wins (their offer takes priority).
* The losing peer MUST roll back their local offer."
*/
fun resolveRenegotiationGlare(
peerPubKey: HexKey,
remoteSdpOffer: String,
onAcceptRemote: (SessionEntry) -> Unit,
): GlareResolution {
val entry = sessions[peerPubKey] ?: return GlareResolution.NO_SESSION
val signalingState = entry.session.getSignalingState()
if (signalingState != SignalingState.HAVE_LOCAL_OFFER) {
// No glare — accept the remote offer directly
onAcceptRemote(entry)
return GlareResolution.NO_GLARE
}
// Glare detected: both sides sent offers simultaneously
return if (localPubKey > peerPubKey) {
// We win — our offer takes priority, ignore remote
GlareResolution.LOCAL_WINS
} else {
// We lose — rollback our local offer, accept remote
entry.session.rollback {
onAcceptRemote(entry)
}
GlareResolution.REMOTE_WINS_ROLLBACK
}
}
// ---- Callee-to-callee mesh ----
/**
* Determines if the local peer should initiate the offer to [peerPubKey].
* Per NIP-AC spec: "the peer with the lexicographically lower pubkey initiates."
*/
fun shouldInitiateOffer(peerPubKey: HexKey): Boolean = localPubKey < peerPubKey
// ---- Answer routing ----
/**
* Routes an incoming SDP answer to the correct session.
* Returns the action taken.
*/
fun routeAnswer(
peerPubKey: HexKey,
sdpAnswer: String,
): AnswerRouteAction {
val entry = sessions[peerPubKey] ?: return AnswerRouteAction.NO_SESSION
val signalingState = entry.session.getSignalingState()
if (signalingState != SignalingState.HAVE_LOCAL_OFFER) {
return AnswerRouteAction.IGNORED_WRONG_STATE
}
entry.session.setRemoteDescription(SdpType.ANSWER, sdpAnswer)
flushPendingIceCandidates(peerPubKey)
return AnswerRouteAction.APPLIED
}
// ---- Cleanup ----
fun disposeAll() {
for (entry in sessions.values) {
entry.session.dispose()
}
sessions.clear()
globalPendingIce.clear()
}
}
enum class IceRouteAction {
ADDED_DIRECTLY,
BUFFERED_PER_SESSION,
BUFFERED_GLOBALLY,
}
enum class GlareResolution {
NO_SESSION,
NO_GLARE,
LOCAL_WINS,
REMOTE_WINS_ROLLBACK,
}
enum class AnswerRouteAction {
APPLIED,
NO_SESSION,
IGNORED_WRONG_STATE,
}