Skip to content

Implements suspendWebSocketConnection and resumeWebSocketConnection #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 27, 2025
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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,25 @@ suspend fun disconnect(): Result<Boolean>

--------------------

#### `ChatSession.suspendWebSocketConnection`
Disconnects the websocket and suspends reconnection attempts.

```
suspend fun suspendWebSocketConnection(): Result<Boolean>
```

--------------------


#### `ChatSession.resumeWebSocketConnection`
Resumes a suspended websocket and attempts to reconnect.

```
suspend fun resumeWebSocketConnection(): Result<Boolean>
```

--------------------

#### `ChatSession.sendMessage`
Sends a message within the chat session.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ interface ChatSession {
*/
suspend fun disconnect(): Result<Boolean>


/**
* Disconnects the websocket and suspends reconnection attempts.
* @return A Result indicating whether the suspension was successful.
*/
suspend fun suspendWebSocketConnection(): Result<Boolean>

/**
* Resumes a suspended websocket and attempts to reconnect.
* @return A Result indicating whether the resume was successful.
*/
suspend fun resumeWebSocketConnection(): Result<Boolean>

/**
* Sends a message.
* @param message The message content.
Expand Down Expand Up @@ -214,6 +227,18 @@ class ChatSessionImpl @Inject constructor(private val chatService: ChatService)
}
}

override suspend fun suspendWebSocketConnection(): Result<Boolean> {
return withContext(Dispatchers.IO) {
chatService.suspendWebSocketConnection()
}
}

override suspend fun resumeWebSocketConnection(): Result<Boolean> {
return withContext(Dispatchers.IO) {
chatService.resumeWebSocketConnection()
}
}

override suspend fun sendMessage(contentType: ContentType, message: String): Result<Boolean> {
return withContext(Dispatchers.IO) {
chatService.sendMessage(contentType, message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ interface WebSocketManager {
suspend fun connect(wsUrl: String, isReconnectFlow: Boolean = false)
suspend fun disconnect(reason: String?)
suspend fun parseTranscriptItemFromJson(jsonString: String): TranscriptItem?
fun suspendWebSocketConnection()
fun resumeWebSocketConnection()
}

class WebSocketManagerImpl @Inject constructor(
Expand All @@ -70,6 +72,7 @@ class WebSocketManagerImpl @Inject constructor(
private var webSocket: WebSocket? = null
private var isConnectedToNetwork: Boolean = false
private var isChatActive: Boolean = false
private var isChatSuspended: Boolean = false

private val _isReconnecting = MutableStateFlow(false)
override var isReconnecting: MutableStateFlow<Boolean>
Expand Down Expand Up @@ -113,9 +116,7 @@ class WebSocketManagerImpl @Inject constructor(
networkConnectionManager.isNetworkAvailable.collect { isAvailable ->
if (isAvailable) {
isConnectedToNetwork = true
if (isChatActive) {
reestablishConnection()
}
reestablishConnectionIfChatActive()
} else {
isConnectedToNetwork = false
Log.d("WebSocketManager", "Network connection lost")
Expand All @@ -128,9 +129,7 @@ class WebSocketManagerImpl @Inject constructor(
when (event) {
Lifecycle.Event.ON_RESUME -> {
Log.d("AppLifecycleObserver", "App in Foreground")
if (isChatActive) {
reestablishConnection()
}
reestablishConnectionIfChatActive()
}
Lifecycle.Event.ON_STOP -> {
Log.d("AppLifecycleObserver", "App in Background")
Expand Down Expand Up @@ -162,7 +161,7 @@ class WebSocketManagerImpl @Inject constructor(
CoroutineScope(Dispatchers.IO).launch {
// 4000 = disconnect websocket due to backgrounding.
if (code != 4000) {
isChatActive = false;
isChatActive = false
}
resetHeartbeatManagers()
webSocket?.close(code, reason)
Expand All @@ -173,6 +172,16 @@ class WebSocketManagerImpl @Inject constructor(
closeWebSocket(reason)
}

override fun suspendWebSocketConnection() {
isChatSuspended = true
closeWebSocket("Suspend WebSocket Connection", 4000)
}

override fun resumeWebSocketConnection() {
isChatSuspended = false
reestablishConnectionIfChatActive()
}

// --- WebSocket Listener ---

private fun createWebSocketListener(isReconnectFlow: Boolean) = object : WebSocketListener() {
Expand Down Expand Up @@ -219,17 +228,15 @@ class WebSocketManagerImpl @Inject constructor(
Log.i("WebSocket", "WebSocket closed with code: $code, reason: $reason")
if (code == 1000) {
isChatActive = false
} else if (isConnectedToNetwork && isChatActive && code != 4000) {
reestablishConnection()
} else if (code != 4000) {
reestablishConnectionIfChatActive()
}
}

private fun handleWebSocketFailure(t: Throwable) {
Log.e("WebSocket", "WebSocket failure: ${t.message}")
if (t is IOException && t.message == "Software caused connection abort") {
if (isChatActive && isConnectedToNetwork) {
reestablishConnection()
}
reestablishConnectionIfChatActive()
}
}

Expand Down Expand Up @@ -351,7 +358,7 @@ class WebSocketManagerImpl @Inject constructor(
private suspend fun onDeepHeartbeatMissed() {
this._eventPublisher.emit(ChatEvent.DeepHeartBeatFailure)
if (isConnectedToNetwork) {
reestablishConnection()
reestablishConnectionIfChatActive()
Log.w("WebSocket", "Deep Heartbeat missed, retrying connection")
} else {
Log.w("WebSocket", "Deep Heartbeat missed, no internet connection")
Expand All @@ -364,12 +371,26 @@ class WebSocketManagerImpl @Inject constructor(
}

// --- Helper Methods ---

private fun reestablishConnection() {
if (!_isReconnecting.value) {
_isReconnecting.value = true
requestNewWsUrl()
private fun reestablishConnectionIfChatActive() {
if (!isChatActive) {
Log.d("WebSocket", "Re-connection aborted due to inactive chat session")
return
}
if (!isConnectedToNetwork) {
Log.d("WebSocket", "Re-connection aborted due to missing network connectivity")
return
}
if (isChatSuspended) {
Log.d("WebSocket", "Re-connection aborted due suspended chat session.")

Choose a reason for hiding this comment

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

nit: missing 'to' in 'due to'. Same comment for ongoing reconnection case below. This can be fixed with PR for unit tests

return
}
if (_isReconnecting.value) {
Log.d("WebSocket", "Re-connection aborted due ongoing reconnection attempt.")
return
}

_isReconnecting.value = true
requestNewWsUrl()
}

private fun requestNewWsUrl() {
Expand Down Expand Up @@ -527,5 +548,4 @@ class WebSocketManagerImpl @Inject constructor(
serializedContent = rawData
)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@ interface ChatService {
*/
suspend fun disconnectChatSession(): Result<Boolean>

/**
* Disconnects the websocket and suspends reconnection attempts.
* @return A Result indicating whether the disconnection was successful.
*/
suspend fun suspendWebSocketConnection(): Result<Boolean>

/**
* Resumes a suspended websocket and attempts to reconnect.
* @return A Result indicating whether the disconnection was successful.
*/
suspend fun resumeWebSocketConnection(): Result<Boolean>

/**
* Sends a message.
* @param contentType The content type of the message.
Expand Down Expand Up @@ -198,7 +210,7 @@ class ChatServiceImpl @Inject constructor(
connectionDetailsProvider.updateChatDetails(chatDetails)
val connectionDetails =
awsClient.createParticipantConnection(chatDetails.participantToken).getOrThrow()
metricsManager.addCountMetric(MetricName.CreateParticipantConnection);
metricsManager.addCountMetric(MetricName.CreateParticipantConnection)
connectionDetailsProvider.updateConnectionDetails(connectionDetails)
setupWebSocket(connectionDetails.websocketUrl)
SDKLogger.logger.logDebug { "Participant Connected" }
Expand Down Expand Up @@ -452,6 +464,24 @@ class ChatServiceImpl @Inject constructor(
}
}

override suspend fun suspendWebSocketConnection(): Result<Boolean> {
return runCatching {
webSocketManager.suspendWebSocketConnection()
true
}.onFailure { exception ->
SDKLogger.logger.logError { "Failed to suspend chat: ${exception.message}" }
}
}

override suspend fun resumeWebSocketConnection(): Result<Boolean> {
return runCatching {
webSocketManager.resumeWebSocketConnection()
true
}.onFailure { exception ->
SDKLogger.logger.logError { "Failed to resume chat: ${exception.message}" }
}
}

override suspend fun sendMessage(contentType: ContentType, message: String): Result<Boolean> {
val connectionDetails = connectionDetailsProvider.getConnectionDetails()
?: return Result.failure(Exception("No connection details available"))
Expand All @@ -472,7 +502,7 @@ class ChatServiceImpl @Inject constructor(
message = message
).getOrThrow()

metricsManager.addCountMetric(MetricName.SendMessage);
metricsManager.addCountMetric(MetricName.SendMessage)

response.id?.let { id ->
updatePlaceholderMessage(oldId = recentlySentMessage.id, newId = id)
Expand All @@ -495,14 +525,14 @@ class ChatServiceImpl @Inject constructor(

// remove failed message from transcript & transcript dict
internalTranscript.removeAll { it.id == messageId }
transcriptDict.remove(messageId);
transcriptDict.remove(messageId)
// Send out updated transcript with old message removed
coroutineScope.launch {
_transcriptListPublisher.emit(internalTranscript)
}

// as the next step, attempt to resend the message based on its type
val attachmentUrl = tempMessageIdToFileUrl[messageId];
val attachmentUrl = tempMessageIdToFileUrl[messageId]
// if old message is an attachment
if (attachmentUrl != null) {
return sendAttachment(attachmentUrl)
Expand Down
Loading