Skip to content

Commit

Permalink
CID-3218: Agent should re-try reconnecting to back if connection closed
Browse files Browse the repository at this point in the history
  • Loading branch information
mohamedlajmileanix committed Nov 15, 2024
1 parent c9cb396 commit ca948b2
Showing 1 changed file with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,18 @@ import org.springframework.messaging.simp.stomp.StompHeaders
import org.springframework.messaging.simp.stomp.StompSession
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter
import org.springframework.stereotype.Component
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.CountDownLatch

@Component
class BrokerStompSessionHandler : StompSessionHandlerAdapter() {

companion object{
private const val RETRY_INTERVAL = 10000L
private const val MAX_RETRY_TIME = 600000L
}

@Lazy
@Autowired
private lateinit var webSocketService: WebSocketService
Expand Down Expand Up @@ -47,12 +55,32 @@ class BrokerStompSessionHandler : StompSessionHandlerAdapter() {
logger.error("Session closed. This could be due to a network error or the server closing the connection.")
isConnected = false
logger.info("Reconnecting...")
webSocketService.initSession()
retryConnection()
} else {
if (latch.count != 0L) latch.countDown()
}
}

private fun retryConnection() {
val timer = Timer()
val startTime = System.currentTimeMillis()
timer.schedule(object : TimerTask() {
override fun run() {
if (System.currentTimeMillis() - startTime > MAX_RETRY_TIME) {
logger.error("Failed to reconnect after ${MAX_RETRY_TIME / 60000} minutes. Stopping retries.")
timer.cancel()
return
}
logger.info("Attempting to reconnect...")
webSocketService.initSession()
if (isConnected) {
logger.info("Reconnected successfully.")
timer.cancel()
}
}
}, 0, RETRY_INTERVAL) // Retry every 10 seconds
}

fun isConnected(): Boolean {
awaitConnection()
return isConnected
Expand Down

0 comments on commit ca948b2

Please sign in to comment.