Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ fun Routing.wsRouting(
return@webSocket
}

if (!wsSessionManager.isAcceptingSessions()) {
logger.info { "WS connection rejected: $appInstanceId while session manager paused" }
close(CloseReason(CloseReason.Codes.GOING_AWAY, "Session manager paused"))
return@webSocket
}

val authenticationRequested =
call.request.queryParameters["authVersion"] == WsAuthenticationCodec.VERSION.toString()
val serverAuthentication =
Expand Down Expand Up @@ -90,7 +96,9 @@ fun Routing.wsRouting(
SyncApi.supportsPairingV3(serverAuthentication?.remotePairingVersion),
peerCapabilities = serverAuthentication?.remoteCapabilities.orEmpty(),
)
wsSessionManager.registerSession(appInstanceId, wsSession)
if (!wsSessionManager.registerSession(appInstanceId, wsSession)) {
return@webSocket
}

dispatchWsSessionMessages(
appInstanceId = appInstanceId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,26 @@ class WsClientConnector(
private val inFlightLock = SynchronizedObject()
private val inFlightHandshakes = HashMap<String, InFlightHandshake>()

init {
wsSessionManager.addOnPausedListener {
cancelInFlightHandshakes()
}
}

fun cancelInFlightHandshakes() {
val jobsToCancel =
synchronized(inFlightLock) {
if (inFlightHandshakes.isEmpty()) {
emptyList()
} else {
val jobs = inFlightHandshakes.values.map { it.job }
inFlightHandshakes.clear()
jobs
}
}
jobsToCancel.forEach { it.cancel() }
}

/**
* Attempt to open a WebSocket connection to a remote peer.
* This is called opportunistically after HTTP CONNECTED state is reached.
Expand All @@ -54,11 +74,16 @@ class WsClientConnector(
onHandshakeFinished: () -> Unit = {},
): Boolean =
runCatching {
if (!wsSessionManager.isAcceptingSessions()) {
logger.debug { "WebSocket connect skipped for $targetAppInstanceId at $host:$port (paused)" }
return false
}
val path =
"/ws/sync?appInstanceId=${appInfo.appInstanceId}" +
"&targetAppInstanceId=$targetAppInstanceId" +
"&authVersion=${WsAuthenticationCodec.VERSION}"

var sessionRegistered = false
client.webSocket(host = host, port = port, path = path) {
val rawSession = WsSession(this, targetAppInstanceId)
val receivedChallenge =
Expand Down Expand Up @@ -124,8 +149,12 @@ class WsClientConnector(
peerSupportsChunkedPayload = SyncApi.supportsPairingV3(challenge.pairingVersion),
peerCapabilities = challenge.capabilities,
)
wsSessionManager.registerSession(targetAppInstanceId, wsSession)
val registered = wsSessionManager.registerSession(targetAppInstanceId, wsSession)
onHandshakeFinished()
if (!registered) {
return@webSocket
}
sessionRegistered = true

dispatchWsSessionMessages(
appInstanceId = targetAppInstanceId,
Expand All @@ -149,7 +178,7 @@ class WsClientConnector(
}
}
}
true
sessionRegistered
}.onFailure { e ->
logger.debug(e) { "WebSocket connection to $targetAppInstanceId at $host:$port failed (fallback to HTTP)" }
}.getOrDefault(false)
Expand Down Expand Up @@ -188,13 +217,17 @@ class WsClientConnector(
var previousJobToCancel: Job? = null
val shouldStart =
synchronized(inFlightLock) {
val existing = inFlightHandshakes[targetAppInstanceId]
if (existing != null && existing.host == host && existing.port == port) {
if (!wsSessionManager.isAcceptingSessions()) {
false
} else {
previousJobToCancel = existing?.job
inFlightHandshakes[targetAppInstanceId] = candidate
true
val existing = inFlightHandshakes[targetAppInstanceId]
if (existing != null && existing.host == host && existing.port == port) {
false
} else {
previousJobToCancel = existing?.job
inFlightHandshakes[targetAppInstanceId] = candidate
true
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions app/src/commonMain/kotlin/com/crosspaste/net/ws/WsMessage.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ const val WS_MAX_PAYLOAD_SIZE: Long = 128L * 1024 * 1024
/** Maximum accepted [WsEnvelopeHeader.payloadChunkCount], derived from the two limits above. */
const val WS_MAX_PAYLOAD_CHUNK_COUNT: Int = (WS_MAX_PAYLOAD_SIZE / WS_PAYLOAD_CHUNK_SIZE).toInt()

/**
* Per-session memory budget for queued (not yet processed) inbound business payloads.
* Sized to [WS_MAX_PAYLOAD_SIZE] so a single max-size paste is always accepted when
* the queue is empty, while preventing unbounded memory growth if a peer pushes large
* messages faster than decryption and DB ingestion can drain them.
*/
const val WS_MAX_PENDING_PAYLOAD_BYTES: Long = WS_MAX_PAYLOAD_SIZE

/** Per-session upper bound on queued inbound business messages (guards against zero-byte floods). */
const val WS_MAX_PENDING_MESSAGES: Int = 256

/**
* Wire header sent as a Text frame (JSON).
* When [hasPayload] is true, the next [payloadChunkCount] frames MUST be Binary
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,15 @@ import com.crosspaste.secure.SecureStore
import com.crosspaste.utils.getFileUtils
import com.crosspaste.utils.getJsonUtils
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.websocket.CloseReason
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.locks.synchronized
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.coroutines.cancellation.CancellationException

class WsMessageHandler(
Expand Down Expand Up @@ -384,29 +390,68 @@ class WsMessageHandler(
}
}

private class WsInboundQueueOverflowException : Exception()

private const val OVERFLOW_CLOSE_TIMEOUT_MS = 1_000L

/**
* Runs a WebSocket session's receive loop while decoupling lightweight control/response
* frames from slower business messages. Control and response frames run inline on the
* receive loop; business messages run serially in FIFO order on a per-session worker so
* paste ordering is preserved without blocking heartbeats or ACKs.
*
* Enforces a per-session byte budget ([maxPendingPayloadBytes]) and message count cap
* ([maxPendingMessages]) on queued business messages. If a peer pushes faster than the
* worker drains and exceeds the budget, the session is closed with
* [CloseReason.Codes.TRY_AGAIN_LATER] so the sender falls back to its existing retry/HTTP
* path instead of accumulating unbounded payload buffers in memory.
*/
internal suspend fun dispatchWsSessionMessages(
appInstanceId: String,
wsSession: WsSession,
wsMessageHandler: WsMessageHandler,
onReadLoopFinished: () -> Unit,
maxPendingPayloadBytes: Long = WS_MAX_PENDING_PAYLOAD_BYTES,
maxPendingMessages: Int = WS_MAX_PENDING_MESSAGES,
readLoop: suspend (dispatch: suspend (WsEnvelope) -> Unit) -> Unit,
) = coroutineScope {
val logger = KotlinLogging.logger("WsSessionDispatcher")
val workChannel = Channel<WsEnvelope>(Channel.UNLIMITED)
val budgetLock = SynchronizedObject()
var pendingBytes = 0L
var pendingMessages = 0

fun tryReserve(payloadBytes: Long): Boolean =
synchronized(budgetLock) {
if (pendingMessages >= maxPendingMessages ||
pendingBytes + payloadBytes > maxPendingPayloadBytes
) {
false
} else {
pendingBytes += payloadBytes
pendingMessages += 1
true
}
}

fun release(payloadBytes: Long) {
synchronized(budgetLock) {
pendingBytes = (pendingBytes - payloadBytes).coerceAtLeast(0L)
pendingMessages = (pendingMessages - 1).coerceAtLeast(0)
}
}

launch {
for (envelope in workChannel) {
val payloadBytes = envelope.payload.size.toLong()
try {
wsMessageHandler.handleMessage(appInstanceId, envelope)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logger.error(e) { "Unhandled error processing WS ${envelope.type} from $appInstanceId" }
} finally {
release(payloadBytes)
}
}
}
Expand All @@ -416,9 +461,37 @@ internal suspend fun dispatchWsSessionMessages(
if (WsMessageHandler.isControlOrResponse(envelope.type)) {
wsMessageHandler.handleMessage(appInstanceId, envelope)
} else {
workChannel.send(envelope)
val payloadBytes = envelope.payload.size.toLong()
if (!tryReserve(payloadBytes)) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — Preserve extension clipboard pushes when the queue overflows

Problem and impact

When the receiver's business queue hits either limit, this branch closes the socket with 1013 and drops the triggering PASTE_PUSH. A clipboard item copied while the desktop receiver is backed up can stay in the extension's history without ever reaching the desktop, even after the socket reconnects.

Evidence

web/src/background/service-worker.ts:247–273 sends the push through wsManager.send() without a requestId. web/src/shared/ws/ws-manager.ts:191–200 reports success after the socket write. Reconnect only reopens the socket, and the extension's HTTP sync pulls desktop history in the other direction (service-worker.ts:412–432). The receiver's overflow test confirms that the triggering envelope is never handled.

Suggestion

Use the existing correlated paste ACK for extension pushes and keep unacknowledged items pending for retry after reconnect. Cover a push dropped by 1013 in a regression test.

Confidence 95/100

logger.warn {
"WS inbound business queue budget exceeded for $appInstanceId " +
"(incomingBytes=$payloadBytes, maxBytes=$maxPendingPayloadBytes, " +
"maxMessages=$maxPendingMessages); closing session"
}
try {
withTimeoutOrNull(OVERFLOW_CLOSE_TIMEOUT_MS) {
wsSession.close(
reason = "Inbound business queue budget exceeded",
code = CloseReason.Codes.TRY_AGAIN_LATER,
)
}
} catch (e: CancellationException) {
currentCoroutineContext().ensureActive()
} catch (e: Exception) {
logger.debug(e) { "Error closing overflowed WS session for $appInstanceId" }
}
throw WsInboundQueueOverflowException()
}
try {
workChannel.send(envelope)
} catch (e: Throwable) {
release(payloadBytes)
throw e
}
}
}
} catch (_: WsInboundQueueOverflowException) {
// Session already closed above; fall through to finally to tear down worker & notify manager.
} finally {
workChannel.close()
onReadLoopFinished()
Expand Down
7 changes: 5 additions & 2 deletions app/src/commonMain/kotlin/com/crosspaste/net/ws/WsSession.kt
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,11 @@ class WsSession(
}
} ?: false

suspend fun close(reason: String = "Normal closure") {
session.close(CloseReason(CloseReason.Codes.NORMAL, reason))
suspend fun close(
reason: String = "Normal closure",
code: CloseReason.Codes = CloseReason.Codes.NORMAL,
) {
session.close(CloseReason(code, reason))
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package com.crosspaste.net.ws

import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.util.collections.*
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.locks.synchronized
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
Expand All @@ -14,6 +16,9 @@ class WsSessionManager {
private val pendingRequests = WsPendingRequests()

private val sessions: ConcurrentMap<String, WsSession> = ConcurrentMap()
private val lifecycleLock = SynchronizedObject()
private var acceptingSessions = true
private val onPausedListeners = mutableListOf<() -> Unit>()

private var onSessionClosed: ((String) -> Unit)? = null

Expand All @@ -27,11 +32,61 @@ class WsSessionManager {
onSessionOpened = callback
}

fun addOnPausedListener(listener: () -> Unit) {
synchronized(lifecycleLock) {
onPausedListeners.add(listener)
}
}

fun isAcceptingSessions(): Boolean = synchronized(lifecycleLock) { acceptingSessions }

/**
* Stops accepting new sessions or handshakes, cancels any in-flight handshakes
* registered via [addOnPausedListener], and closes all active sessions.
* Call [resume] when background pause ends.
*/
suspend fun pause() {
val listeners =
synchronized(lifecycleLock) {
acceptingSessions = false
onPausedListeners.toList()
}
listeners.forEach { listener ->
try {
listener()
} catch (e: Exception) {
logger.warn(e) { "Error in WsSessionManager onPaused listener" }
}
}
closeAll()
}

/** Re-enables accepting WebSocket handshakes and session registrations after [pause]. */
fun resume() {
synchronized(lifecycleLock) {
acceptingSessions = true
}
}

suspend fun registerSession(
appInstanceId: String,
session: WsSession,
) {
val existing = sessions.put(appInstanceId, session)
): Boolean {
var rejected = false
val existing =
synchronized(lifecycleLock) {
if (!acceptingSessions) {
rejected = true
null
} else {
sessions.put(appInstanceId, session)
}
}
if (rejected) {
logger.info { "Rejected WebSocket session registration for $appInstanceId while paused" }
closeSessionSafely(appInstanceId, session, "Session manager paused")
return false
}
if (existing != null) {
logger.info { "Replaced existing WebSocket session for $appInstanceId" }
pendingRequests.failForSession(existing, "WebSocket session replaced for $appInstanceId")
Expand All @@ -40,6 +95,7 @@ class WsSessionManager {
logger.info { "Registered WebSocket session for $appInstanceId" }
}
onSessionOpened?.invoke(appInstanceId)
return true
}

fun unregisterSession(appInstanceId: String) {
Expand Down
Loading