Skip to content

Commit

Permalink
[PBE-3993] Fix infinite reconnection calls for CoordinatorSocket (#1111)
Browse files Browse the repository at this point in the history
  • Loading branch information
liviu-timar authored Jun 13, 2024
1 parent d027598 commit 5b5f112
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -352,11 +352,9 @@ internal class StreamVideoImpl internal constructor(
}
}
scope.launch {
connectionModule.coordinatorSocket.errors.collect {
if (developmentMode) {
logger.e(it) { "failure on socket connection" }
} else {
logger.e(it) { "failure on socket connection" }
connectionModule.coordinatorSocket.errors.collect { throwable ->
(throwable as? ErrorResponse)?.let {
if (it.code == VideoErrorCode.TOKEN_EXPIRED.code) refreshToken(it)
}
}
}
Expand Down Expand Up @@ -427,19 +425,27 @@ internal class StreamVideoImpl internal constructor(
timer.finish()
Success(timer.duration)
} catch (e: ErrorResponse) {
if (e.code == VideoErrorCode.TOKEN_EXPIRED.code && tokenProvider != null) {
val newToken = tokenProvider.invoke(e)
connectionModule.updateToken(newToken)
// quickly reconnect with the new token
socketImpl.reconnect(0)
Failure(Error.GenericError("initialize error. trying to reconnect."))
if (e.code == VideoErrorCode.TOKEN_EXPIRED.code) {
refreshToken(e)
Failure(Error.GenericError("Initialize error. Token expired."))
} else {
throw e
}
}
}
}

private suspend fun refreshToken(error: Throwable) {
tokenProvider?.let {
val newToken = tokenProvider.invoke(error)
connectionModule.updateToken(newToken)

logger.d { "[refreshToken] Token has been refreshed with: $newToken" }

socketImpl.reconnect(0)
}
}

/**
* @see StreamVideo.deleteDevice
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,8 @@ public open class PersistentSocket<T>(
}

internal fun sendHealthCheck() {
println("sending health check")
logger.d { "sending health check" }

val healthCheckRequest = HealthCheckRequest()
socket?.send(healthCheckRequest.encodeByteString())
}
Expand All @@ -375,15 +376,18 @@ public open class PersistentSocket<T>(
object : HealthMonitor.HealthCallback {
override suspend fun reconnect() {
logger.i { "health monitor triggered a reconnect" }

val state = connectionState.value
if (state is SocketState.DisconnectedTemporarily) {
this@PersistentSocket.reconnect()
}
}

override fun check() {
logger.d { "health monitor ping" }
val state = connectionState.value

logger.d { "health monitor ping. Socket state: $state" }

(state as? SocketState.Connected)?.let {
sendHealthCheck()
}
Expand Down

0 comments on commit 5b5f112

Please sign in to comment.