Skip to content

Commit

Permalink
Add deadlock prevention in SuperAccessDaemonClient
Browse files Browse the repository at this point in the history
  • Loading branch information
serivesmejia committed Oct 29, 2024
1 parent 57942a4 commit 2986052
Showing 1 changed file with 20 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ class SuperAccessDaemonClient {
}

fun sendRequest(request: SuperAccessDaemon.SuperAccessMessage.Request, onResponse: (Boolean) -> Unit) {
if(server.connections.isEmpty()) {
onResponse(false)
return
}

server.broadcast(SuperAccessDaemon.gson.toJson(request))

server.addResponseReceiver(request.id) { response ->
Expand Down Expand Up @@ -97,7 +102,7 @@ class SuperAccessDaemonClient {
}

lock.withLock {
condition.await(2, java.util.concurrent.TimeUnit.SECONDS)
condition.await(3, java.util.concurrent.TimeUnit.SECONDS)
}

return hasAccess
Expand All @@ -112,10 +117,19 @@ class SuperAccessDaemonClient {

val logger by loggerForThis()

val responseReceiver = mutableMapOf<ResponseCondition, ResponseReceiver>()
private val responseReceiver = mutableMapOf<ResponseCondition, ResponseReceiver>()

private val pendingRequests = mutableMapOf<Int, ResponseReceiver>()
private var processRestarts = 0

// Notify all pending requests if the process dies
private fun notifyPendingRequestsOfFailure() {
pendingRequests.forEach { key, value ->
value(SuperAccessDaemon.SuperAccessResponse.Failure(key))
}
pendingRequests.clear()
}

override fun onOpen(conn: WebSocket, p1: ClientHandshake?) {
val hostString = conn.localSocketAddress.hostString
if(hostString != "127.0.0.1" && hostString != "localhost" && hostString != "0.0.0.0") {
Expand All @@ -139,6 +153,7 @@ class SuperAccessDaemonClient {
p3: Boolean
) {
logger.info("SuperAccessDaemon is gone.")
notifyPendingRequestsOfFailure() // Notify all waiting clients
}

override fun onMessage(ws: WebSocket, msg: String) {
Expand All @@ -149,6 +164,8 @@ class SuperAccessDaemonClient {
receiver(response)
}
}

pendingRequests.remove(response.id)
}

override fun onError(p0: WebSocket?, p1: Exception?) {
Expand Down Expand Up @@ -182,12 +199,9 @@ class SuperAccessDaemonClient {
}

fun addResponseReceiver(id: Int, receiver: ResponseReceiver) {
pendingRequests[id] = receiver
responseReceiver[{ it.id == id }] = receiver
}

fun addResponseReceiver(condition: ResponseCondition, receiver: ResponseReceiver) {
responseReceiver[condition] = receiver
}
}

}

0 comments on commit 2986052

Please sign in to comment.