Skip to content

Commit

Permalink
Make class thread safe.
Browse files Browse the repository at this point in the history
  • Loading branch information
HenrikJannsen committed Dec 7, 2024
1 parent a9c8a8f commit 6c0aa6e
Showing 1 changed file with 15 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,35 +30,38 @@ class RequestResponseHandler(private val sendFunction: suspend (WebSocketMessage
webSocketRequest: WebSocketRequest,
timeoutMillis: Long = 10_000
): WebSocketResponse? {
require(requestId == null) { "RequestResponseHandler is designed to be used only once per request ID" }
log.i { "Sending request with ID: ${webSocketRequest.requestId}" }
requestId = webSocketRequest.requestId
mutex.withLock { deferredWebSocketResponse = CompletableDeferred() }
mutex.withLock {
require(requestId == null) { "RequestResponseHandler is designed to be used only once per request ID" }
requestId = webSocketRequest.requestId
deferredWebSocketResponse = CompletableDeferred()

try {
sendFunction.invoke(webSocketRequest)
} catch (e: Exception) {
mutex.withLock { deferredWebSocketResponse?.completeExceptionally(e) }
throw e
try {
sendFunction.invoke(webSocketRequest)
} catch (e: Exception) {
deferredWebSocketResponse?.completeExceptionally(e)
throw e
}
}

return withTimeout(timeoutMillis) {
deferredWebSocketResponse?.await()
}
}

suspend fun onWebSocketResponse(webSocketResponse: WebSocketResponse) {
require(webSocketResponse.requestId == requestId) { "Request ID of response does not match our request ID" }
log.i { "Received response for request ID: ${webSocketResponse.requestId}" }
mutex.withLock { deferredWebSocketResponse?.complete(webSocketResponse) }
mutex.withLock {
require(webSocketResponse.requestId == requestId) { "Request ID of response does not match our request ID" }
deferredWebSocketResponse?.complete(webSocketResponse)
}
}

suspend fun dispose() {
log.i { "Disposing request handler for ID: $requestId" }
mutex.withLock {
deferredWebSocketResponse?.cancel()
deferredWebSocketResponse = null
requestId = null
}
requestId = null
}
}

0 comments on commit 6c0aa6e

Please sign in to comment.