Fix WebSocket events being silently dropped on buffer overflow (#313)
* Fix WebSocket events being silently dropped on buffer overflow Increases the MutableSharedFlow `extraBufferCapacity` from 64 to 256 and changes the `onBufferOverflow` policy to `BufferOverflow.DROP_OLDEST` in `HermesWsClient.kt`. This fixes an issue where the slow collection (e.g., due to DB writes) caused the buffer to fill up and silently drop incoming real-time WebSocket events. By setting `DROP_OLDEST`, `tryEmit()` remains functional without suspending, allowing real-time events to be retained and prioritized. Fixes #275 * Fix ktlint formatting issues in HermesWsClient.kt The formatting changes adhere to ktlint rules required by the CI pipeline: - Removed a trailing comma in MutableSharedFlow initialization to avoid multiline expression wrapping errors. - Sorted imports to be in lexicographical order. These formatting changes fix the failing CI check. Fixes #275 * Fix WebSocket events being silently dropped on buffer overflow Increases the MutableSharedFlow `extraBufferCapacity` from 64 to 256 and changes the `onBufferOverflow` policy to `BufferOverflow.DROP_OLDEST` in `HermesWsClient.kt`. This fixes an issue where the slow collection (e.g., due to DB writes) caused the buffer to fill up and silently drop incoming real-time WebSocket events. By setting `DROP_OLDEST`, `tryEmit()` remains functional without suspending, allowing real-time events to be retained and prioritized. Fixes #275 * Fix WebSocket events being silently dropped on buffer overflow Increases the MutableSharedFlow extraBufferCapacity from 64 to 256 and changes the onBufferOverflow policy to BufferOverflow.DROP_OLDEST in HermesWsClient.kt. This fixes an issue where the slow collection (e.g., due to DB writes) caused the buffer to fill up and silently drop incoming real-time WebSocket events. By setting DROP_OLDEST, tryEmit() remains functional without suspending, allowing real-time events to be retained and prioritized. Fixes #275 * Fix WebSocket events being silently dropped on buffer overflow Increases the MutableSharedFlow extraBufferCapacity from 64 to 256 and changes the onBufferOverflow policy to BufferOverflow.DROP_OLDEST in HermesWsClient.kt. This fixes an issue where the slow collection (e.g., due to DB writes) caused the buffer to fill up and silently drop incoming real-time WebSocket events. By setting DROP_OLDEST, tryEmit() remains functional without suspending, allowing real-time events to be retained and prioritized. Fixes #275 * Fix WebSocket events being silently dropped on buffer overflow Increases the MutableSharedFlow extraBufferCapacity from 64 to 256 and changes the onBufferOverflow policy to BufferOverflow.DROP_OLDEST in HermesWsClient.kt. This fixes an issue where the slow collection (e.g., due to DB writes) caused the buffer to fill up and silently drop incoming real-time WebSocket events. By setting DROP_OLDEST, tryEmit() remains functional without suspending, allowing real-time events to be retained and prioritized. Fixes #275 --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com>
This commit is contained in:
1 parent
2c6e437a5b
commit
eb71ae3a46
41 files changed
+666
-246
No files matched your search
@@ -57,6 +57,10 @@ object AuthManager {
|
||||
|
||||
private val _bottomNavDisplayModeFlow = MutableStateFlow<BottomNavDisplayMode>(BottomNavDisplayMode.ICON_AND_TEXT)
|
||||
val bottomNavDisplayModeFlow: StateFlow<BottomNavDisplayMode> = _bottomNavDisplayModeFlow.asStateFlow()
|
||||
|
||||
private val _tokenFlow = MutableStateFlow<String?>(null)
|
||||
val tokenFlow: StateFlow<String?> = _tokenFlow.asStateFlow()
|
||||
|
||||
private val gson = com.google.gson.Gson()
|
||||
|
||||
/**
|
||||
@@ -84,6 +88,7 @@ object AuthManager {
|
||||
_useDynamicColorsFlow.value = isUseDynamicColors()
|
||||
_themePresetFlow.value = getThemePreset()
|
||||
_bottomNavDisplayModeFlow.value = getBottomNavDisplayMode()
|
||||
_tokenFlow.value = getToken()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +108,9 @@ object AuthManager {
|
||||
>() {}.type
|
||||
gson.fromJson(json, type) ?: emptyList()
|
||||
} catch (e: Exception) {
|
||||
if (com.m57.hermescontrol.BuildConfig.DEBUG) {
|
||||
android.util.Log.w("AuthManager", "Failed to parse connection profiles", e)
|
||||
}
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
@@ -119,6 +127,9 @@ object AuthManager {
|
||||
token: String?,
|
||||
) {
|
||||
requirePrefs().edit().putString("token_$profileId", token).apply()
|
||||
if (getSelectedProfileId() == profileId) {
|
||||
_tokenFlow.value = token
|
||||
}
|
||||
}
|
||||
|
||||
fun getSelectedProfileId(): String? {
|
||||
@@ -128,6 +139,7 @@ object AuthManager {
|
||||
|
||||
fun setSelectedProfileId(id: String?) {
|
||||
requirePrefs().edit().putString(KEY_SELECTED_PROFILE_ID, id).apply()
|
||||
_tokenFlow.value = getToken()
|
||||
}
|
||||
|
||||
// ── Token ────────────────────────────────────────────────────────────
|
||||
@@ -135,8 +147,7 @@ object AuthManager {
|
||||
fun getToken(): String? {
|
||||
val selectedId = getSelectedProfileId()
|
||||
if (selectedId != null) {
|
||||
val token = getProfileToken(selectedId)
|
||||
if (token != null) return token
|
||||
return getProfileToken(selectedId)
|
||||
}
|
||||
return requirePrefs().getString(KEY_TOKEN, null)
|
||||
}
|
||||
@@ -147,6 +158,7 @@ object AuthManager {
|
||||
setProfileToken(selectedId, token)
|
||||
} else {
|
||||
requirePrefs().edit().putString(KEY_TOKEN, token).apply()
|
||||
_tokenFlow.value = token
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,10 @@ import androidx.room.PrimaryKey
|
||||
* thread. The [timestamp] field preserves original ordering even if Room
|
||||
* reorders internally.
|
||||
*/
|
||||
@Entity(tableName = "chat_messages")
|
||||
@Entity(
|
||||
tableName = "chat_messages",
|
||||
indices = [androidx.room.Index(value = ["session_id", "timestamp"])],
|
||||
)
|
||||
data class ChatMessageEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
|
||||
@@ -4,11 +4,13 @@ import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.m57.hermescontrol.BuildConfig
|
||||
|
||||
@Database(
|
||||
entities = [ChatMessageEntity::class],
|
||||
version = 1,
|
||||
version = 2,
|
||||
exportSchema = true,
|
||||
)
|
||||
abstract class HermesDatabase : RoomDatabase() {
|
||||
@@ -18,6 +20,16 @@ abstract class HermesDatabase : RoomDatabase() {
|
||||
@Volatile
|
||||
private var instance: HermesDatabase? = null
|
||||
|
||||
private val MIGRATION_1_2 =
|
||||
object : Migration(1, 2) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"CREATE INDEX IF NOT EXISTS `index_chat_messages_session_id_timestamp` " +
|
||||
"ON `chat_messages` (`session_id`, `timestamp`)",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun get(context: Context): HermesDatabase =
|
||||
instance ?: synchronized(this) {
|
||||
instance ?: Room
|
||||
@@ -25,7 +37,8 @@ abstract class HermesDatabase : RoomDatabase() {
|
||||
context.applicationContext,
|
||||
HermesDatabase::class.java,
|
||||
"hermes_control.db",
|
||||
).apply {
|
||||
).addMigrations(MIGRATION_1_2)
|
||||
.apply {
|
||||
if (BuildConfig.DEBUG) {
|
||||
fallbackToDestructiveMigration(false)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.m57.hermescontrol.data.remote
|
||||
|
||||
import com.m57.hermescontrol.BuildConfig
|
||||
import com.m57.hermescontrol.data.local.AuthManager
|
||||
import okhttp3.CertificatePinner
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
@@ -23,6 +24,8 @@ object ApiClient {
|
||||
@Volatile
|
||||
private var service: HermesApiService? = null
|
||||
|
||||
private val connectionPool = okhttp3.ConnectionPool()
|
||||
|
||||
/** The current [HermesApiService] instance. Lazily created on first access. */
|
||||
val hermesApi: HermesApiService
|
||||
get() {
|
||||
@@ -113,11 +116,18 @@ object ApiClient {
|
||||
chain.proceed(request)
|
||||
}
|
||||
|
||||
// SEC-11: No certificate pinning is configured by default since the app
|
||||
// intentionally uses HTTP for LAN and hosts are dynamic.
|
||||
// CertificatePinner infrastructure is provided here if HTTPS is used with a known host.
|
||||
val certificatePinner = CertificatePinner.Builder().build()
|
||||
|
||||
val okHttp =
|
||||
OkHttpClient
|
||||
.Builder()
|
||||
.connectionPool(connectionPool)
|
||||
.addInterceptor(authInterceptor)
|
||||
.addInterceptor(logging)
|
||||
.certificatePinner(certificatePinner)
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.writeTimeout(15, TimeUnit.SECONDS)
|
||||
|
||||
@@ -9,14 +9,20 @@ import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.buffer
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.shareIn
|
||||
import kotlinx.coroutines.launch
|
||||
import okhttp3.CertificatePinner
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
@@ -74,19 +80,42 @@ object HermesWsClient {
|
||||
@Volatile
|
||||
private var reconnectJob: Job? = null
|
||||
|
||||
// SEC-11: No certificate pinning is configured by default since the app
|
||||
// intentionally uses HTTP for LAN and hosts are dynamic.
|
||||
// CertificatePinner infrastructure is provided here if HTTPS is used with a known host.
|
||||
private val certificatePinner = CertificatePinner.Builder().build()
|
||||
|
||||
private val okHttpClient =
|
||||
OkHttpClient
|
||||
.Builder()
|
||||
.certificatePinner(certificatePinner)
|
||||
.readTimeout(0, TimeUnit.MILLISECONDS) // keep-alive forever
|
||||
.pingInterval(30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
// ── Public observable stream ─────────────────────────────────────────
|
||||
|
||||
private val _events = MutableSharedFlow<WsEvent>(extraBufferCapacity = 64)
|
||||
private val rawMessages =
|
||||
MutableSharedFlow<String>(
|
||||
extraBufferCapacity = 256,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
|
||||
/** Collect this from ViewModels to receive all parsed [WsEvent]s. */
|
||||
val events: SharedFlow<WsEvent> = _events.asSharedFlow()
|
||||
val events: SharedFlow<WsEvent> =
|
||||
rawMessages
|
||||
.buffer()
|
||||
.map { text ->
|
||||
try {
|
||||
val rpc = gson.fromJson(text, JsonRpcResponse::class.java)
|
||||
EventParser.parse(rpc, text)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to parse message", e)
|
||||
WsEvent.Unknown(text)
|
||||
}
|
||||
}
|
||||
.flowOn(Dispatchers.IO)
|
||||
.shareIn(wsScope, SharingStarted.Eagerly)
|
||||
|
||||
// ── Connection status flow ──────────────────────────────────────────
|
||||
private val _connectionStatus = MutableStateFlow(ConnectionStatus.DISCONNECTED)
|
||||
@@ -163,7 +192,8 @@ object HermesWsClient {
|
||||
val url = AuthManager.wsUrl()
|
||||
// B2 (Jun 18 2026, kanban t_8884db16): url contains the auth token
|
||||
// as a query param — never stream to logcat in release builds.
|
||||
if (BuildConfig.DEBUG) Log.d(TAG, "Connecting to $url")
|
||||
val safeUrl = url.replace(Regex("token=[^&]+"), "token=REDACTED")
|
||||
if (BuildConfig.DEBUG) Log.d(TAG, "Connecting to $safeUrl")
|
||||
|
||||
val request = Request.Builder().url(url).build()
|
||||
webSocket = okHttpClient.newWebSocket(request, WsListenerImpl())
|
||||
@@ -209,10 +239,6 @@ object HermesWsClient {
|
||||
}
|
||||
}
|
||||
|
||||
private fun emit(event: WsEvent) {
|
||||
_events.tryEmit(event)
|
||||
}
|
||||
|
||||
// ── Listener ─────────────────────────────────────────────────────────
|
||||
|
||||
private class WsListenerImpl : WebSocketListener() {
|
||||
@@ -234,14 +260,7 @@ object HermesWsClient {
|
||||
// AI reply tokens and tool output — never stream to logcat in
|
||||
// release builds.
|
||||
if (BuildConfig.DEBUG) Log.d(TAG, "← $text")
|
||||
try {
|
||||
val rpc = gson.fromJson(text, JsonRpcResponse::class.java)
|
||||
val event = EventParser.parse(rpc, text)
|
||||
emit(event)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to parse message", e)
|
||||
emit(WsEvent.Unknown(text))
|
||||
}
|
||||
rawMessages.tryEmit(text)
|
||||
}
|
||||
|
||||
override fun onClosing(
|
||||
|
||||
Reference in new issue
Block a user