mirror of
https://github.com/Monkopedia/rouse-context.git
synced 2026-12-03 03:44:54 +00:00
Fix #146: Replace message-prefix log routing with typed LogLevel lambda
AppModule was routing `Log.e` vs `Log.w` vs `Log.i` by string-matching
message prefixes ("Audit:", "TunnelClient: disconnected:"). Severity is
known at the call site, not at wiring. Renaming a log string silently
downgraded severity, and "frame arrived after disconnect" landed as WARN
despite the spec calling for DEBUG.
Introduce `LogLevel { DEBUG, INFO, WARN, ERROR }` in both `:core:mcp` and
`:core:tunnel` (duplicated to avoid a cross-module dependency on a
four-value enum). Change `log: (String) -> Unit` to
`log: (LogLevel, String) -> Unit` on `ConnectionStateMachine`,
`TunnelClientImpl`, `MuxDemux`, `configureMcpRouting`, `McpSession`, and
the audit-emission helpers. Each call site declares its own severity.
AppModule's lambda becomes a simple `when (level)` switch onto
`android.util.Log`. The emitted log tags and severities are unchanged
for existing events; "frame arrived after disconnect" now correctly
lands at DEBUG.
Tests capture `Pair<LogLevel, String>` and assert the expected level.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
1142686d9a
commit
793091b8b5
12 changed files with 101 additions and 43 deletions
|
|
@ -347,11 +347,12 @@ val appModule = module {
|
|||
) ?: ""
|
||||
self == "alert" || ct == "alert"
|
||||
},
|
||||
log = { msg ->
|
||||
if (msg.startsWith("Audit:")) {
|
||||
Log.e("McpRouting", msg)
|
||||
} else {
|
||||
Log.w("McpRouting", msg)
|
||||
log = { level, msg ->
|
||||
when (level) {
|
||||
com.rousecontext.mcp.core.LogLevel.DEBUG -> Log.d("McpRouting", msg)
|
||||
com.rousecontext.mcp.core.LogLevel.INFO -> Log.i("McpRouting", msg)
|
||||
com.rousecontext.mcp.core.LogLevel.WARN -> Log.w("McpRouting", msg)
|
||||
com.rousecontext.mcp.core.LogLevel.ERROR -> Log.e("McpRouting", msg)
|
||||
}
|
||||
}
|
||||
).also { session ->
|
||||
|
|
@ -384,15 +385,30 @@ val appModule = module {
|
|||
TunnelClientImpl(
|
||||
scope = get(named("appScope")),
|
||||
webSocketFactory = get<LazyWebSocketFactory>(),
|
||||
log = { msg ->
|
||||
if (msg.startsWith("TunnelClient: disconnected:")) {
|
||||
Log.i("TunnelClient", msg)
|
||||
} else {
|
||||
Log.w("TunnelClient", msg)
|
||||
log = { level, msg ->
|
||||
when (level) {
|
||||
com.rousecontext.tunnel.LogLevel.DEBUG -> Log.d("TunnelClient", msg)
|
||||
com.rousecontext.tunnel.LogLevel.INFO -> Log.i("TunnelClient", msg)
|
||||
com.rousecontext.tunnel.LogLevel.WARN -> Log.w("TunnelClient", msg)
|
||||
com.rousecontext.tunnel.LogLevel.ERROR -> Log.e("TunnelClient", msg)
|
||||
}
|
||||
},
|
||||
stateMachineLog = { msg -> Log.w("ConnectionStateMachine", msg) },
|
||||
muxDemuxLog = { msg -> Log.w("MuxDemux", msg) }
|
||||
stateMachineLog = { level, msg ->
|
||||
when (level) {
|
||||
com.rousecontext.tunnel.LogLevel.DEBUG -> Log.d("ConnectionStateMachine", msg)
|
||||
com.rousecontext.tunnel.LogLevel.INFO -> Log.i("ConnectionStateMachine", msg)
|
||||
com.rousecontext.tunnel.LogLevel.WARN -> Log.w("ConnectionStateMachine", msg)
|
||||
com.rousecontext.tunnel.LogLevel.ERROR -> Log.e("ConnectionStateMachine", msg)
|
||||
}
|
||||
},
|
||||
muxDemuxLog = { level, msg ->
|
||||
when (level) {
|
||||
com.rousecontext.tunnel.LogLevel.DEBUG -> Log.d("MuxDemux", msg)
|
||||
com.rousecontext.tunnel.LogLevel.INFO -> Log.i("MuxDemux", msg)
|
||||
com.rousecontext.tunnel.LogLevel.WARN -> Log.w("MuxDemux", msg)
|
||||
com.rousecontext.tunnel.LogLevel.ERROR -> Log.e("MuxDemux", msg)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
package com.rousecontext.mcp.core
|
||||
|
||||
/**
|
||||
* Severity level for diagnostic log messages emitted by `:core:mcp` classes.
|
||||
*
|
||||
* The call site knows the intended severity; the wiring layer decides how to
|
||||
* map each level onto a concrete logging backend (e.g. `android.util.Log`).
|
||||
*
|
||||
* A separate enum is duplicated in `:core:tunnel` to keep the two modules free
|
||||
* of cross-dependencies.
|
||||
*/
|
||||
enum class LogLevel { DEBUG, INFO, WARN, ERROR }
|
||||
|
|
@ -77,7 +77,7 @@ fun Application.configureMcpRouting(
|
|||
securityAlertCheck: (() -> Boolean)? = null,
|
||||
serverName: String = "rouse-context",
|
||||
serverVersion: String = "0.1.0",
|
||||
log: (String) -> Unit = {}
|
||||
log: (LogLevel, String) -> Unit = { _, _ -> }
|
||||
) {
|
||||
install(ContentNegotiation) {
|
||||
json(mcpJson)
|
||||
|
|
@ -140,7 +140,7 @@ internal class McpRoutes(
|
|||
private val securityAlertCheck: (() -> Boolean)?,
|
||||
private val serverName: String,
|
||||
private val serverVersion: String,
|
||||
private val log: (String) -> Unit
|
||||
private val log: (LogLevel, String) -> Unit
|
||||
) {
|
||||
// Per-integration MCP servers, created lazily and cached
|
||||
private val integrationServers = mutableMapOf<String, IntegrationServer>()
|
||||
|
|
@ -231,6 +231,7 @@ internal class McpRoutes(
|
|||
mcpJson.parseToJsonElement(text).jsonObject
|
||||
} catch (e: Exception) {
|
||||
log(
|
||||
LogLevel.WARN,
|
||||
"McpRouting: /register body read failed: " +
|
||||
"${e::class.simpleName}: ${e.message}"
|
||||
)
|
||||
|
|
@ -570,6 +571,7 @@ internal class McpRoutes(
|
|||
}
|
||||
} catch (e: Exception) {
|
||||
log(
|
||||
LogLevel.WARN,
|
||||
"McpRouting: /mcp body read failed: " +
|
||||
"${e::class.simpleName}: ${e.message}"
|
||||
)
|
||||
|
|
@ -876,7 +878,7 @@ private fun emitAuditEvent(
|
|||
integration: String,
|
||||
startMs: Long,
|
||||
clock: Clock,
|
||||
log: (String) -> Unit
|
||||
log: (LogLevel, String) -> Unit
|
||||
) {
|
||||
val method = try {
|
||||
request["method"]?.jsonPrimitive?.content
|
||||
|
|
@ -919,7 +921,7 @@ private fun emitRequestEvent(
|
|||
method: String,
|
||||
startMs: Long,
|
||||
durationMs: Long,
|
||||
log: (String) -> Unit
|
||||
log: (LogLevel, String) -> Unit
|
||||
) {
|
||||
try {
|
||||
val params = request["params"]
|
||||
|
|
@ -936,7 +938,7 @@ private fun emitRequestEvent(
|
|||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
log("Audit: failed to emit onRequest event: ${e.message}")
|
||||
log(LogLevel.ERROR, "Audit: failed to emit onRequest event: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -948,7 +950,7 @@ private fun emitToolCallEvent(
|
|||
integration: String,
|
||||
startMs: Long,
|
||||
durationMs: Long,
|
||||
log: (String) -> Unit
|
||||
log: (LogLevel, String) -> Unit
|
||||
) {
|
||||
try {
|
||||
val params = request["params"]?.jsonObject ?: return
|
||||
|
|
@ -972,7 +974,7 @@ private fun emitToolCallEvent(
|
|||
)
|
||||
} catch (e: Exception) {
|
||||
// Audit is best-effort; never fail the request due to audit errors
|
||||
log("Audit: failed to emit tool-call event: ${e.message}")
|
||||
log(LogLevel.ERROR, "Audit: failed to emit tool-call event: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ class McpSession(
|
|||
private val securityAlertCheck: (() -> Boolean)? = null,
|
||||
private val serverName: String = "rouse-context",
|
||||
private val serverVersion: String = "0.1.0",
|
||||
private val log: (String) -> Unit = {}
|
||||
private val log: (LogLevel, String) -> Unit = { _, _ -> }
|
||||
) {
|
||||
|
||||
private val done = CompletableDeferred<Unit>()
|
||||
|
|
|
|||
|
|
@ -243,7 +243,7 @@ class HttpRoutingTest {
|
|||
val registry = testRegistry("health" to stubProvider("health", "Health Connect"))
|
||||
val tokenStore = InMemoryTokenStore()
|
||||
val deviceCodeManager = DeviceCodeManager(tokenStore = tokenStore)
|
||||
val captured = mutableListOf<String>()
|
||||
val captured = mutableListOf<Pair<LogLevel, String>>()
|
||||
|
||||
application {
|
||||
configureMcpRouting(
|
||||
|
|
@ -252,7 +252,7 @@ class HttpRoutingTest {
|
|||
deviceCodeManager = deviceCodeManager,
|
||||
hostname = "brave-falcon.rousecontext.com",
|
||||
integration = "health",
|
||||
log = { captured.add(it) }
|
||||
log = { level, msg -> captured.add(level to msg) }
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -263,7 +263,10 @@ class HttpRoutingTest {
|
|||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
assertTrue(
|
||||
"Expected /register body read failure log, got $captured",
|
||||
captured.any { it.startsWith("McpRouting: /register body read failed:") }
|
||||
captured.any {
|
||||
it.first == LogLevel.WARN &&
|
||||
it.second.startsWith("McpRouting: /register body read failed:")
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import kotlinx.coroutines.flow.asStateFlow
|
|||
* - ACTIVE -> CONNECTED (last stream closed)
|
||||
* - DISCONNECTING -> DISCONNECTED
|
||||
*/
|
||||
class ConnectionStateMachine(private val log: (String) -> Unit = {}) {
|
||||
class ConnectionStateMachine(private val log: (LogLevel, String) -> Unit = { _, _ -> }) {
|
||||
|
||||
private val _state = MutableStateFlow(TunnelState.DISCONNECTED)
|
||||
|
||||
|
|
@ -35,7 +35,10 @@ class ConnectionStateMachine(private val log: (String) -> Unit = {}) {
|
|||
fun transition(to: TunnelState): Boolean {
|
||||
val from = _state.value
|
||||
if (!isValidTransition(from, to)) {
|
||||
log("ConnectionStateMachine: ignoring invalid transition from $from to $to")
|
||||
log(
|
||||
LogLevel.WARN,
|
||||
"ConnectionStateMachine: ignoring invalid transition from $from to $to"
|
||||
)
|
||||
return false
|
||||
}
|
||||
_state.value = to
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
package com.rousecontext.tunnel
|
||||
|
||||
/**
|
||||
* Severity level for diagnostic log messages emitted by `:core:tunnel` classes.
|
||||
*
|
||||
* The call site knows the intended severity; the wiring layer decides how to
|
||||
* map each level onto a concrete logging backend (e.g. `android.util.Log`).
|
||||
*
|
||||
* A separate enum is duplicated in `:core:mcp` to keep the two modules free of
|
||||
* cross-dependencies.
|
||||
*/
|
||||
enum class LogLevel { DEBUG, INFO, WARN, ERROR }
|
||||
|
|
@ -14,7 +14,7 @@ import kotlinx.coroutines.sync.withLock
|
|||
*
|
||||
* Thread-safe: all access to the stream map is synchronized via a [Mutex].
|
||||
*/
|
||||
class MuxDemux(private val log: (String) -> Unit = {}) {
|
||||
class MuxDemux(private val log: (LogLevel, String) -> Unit = { _, _ -> }) {
|
||||
|
||||
private val streams = mutableMapOf<UInt, MuxStreamImpl>()
|
||||
private val streamsMutex = Mutex()
|
||||
|
|
@ -62,6 +62,7 @@ class MuxDemux(private val log: (String) -> Unit = {}) {
|
|||
incomingChannel.send(stream)
|
||||
} else {
|
||||
log(
|
||||
LogLevel.WARN,
|
||||
"MuxDemux: rejecting stream ${frame.streamId}, " +
|
||||
"limit $maxStreams reached"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -19,9 +19,9 @@ import kotlinx.coroutines.launch
|
|||
class TunnelClientImpl(
|
||||
private val scope: CoroutineScope,
|
||||
private val webSocketFactory: WebSocketFactory,
|
||||
private val log: (String) -> Unit = {},
|
||||
private val stateMachineLog: (String) -> Unit = {},
|
||||
private val muxDemuxLog: (String) -> Unit = {}
|
||||
private val log: (LogLevel, String) -> Unit = { _, _ -> },
|
||||
private val stateMachineLog: (LogLevel, String) -> Unit = { _, _ -> },
|
||||
private val muxDemuxLog: (LogLevel, String) -> Unit = { _, _ -> }
|
||||
) : TunnelClient {
|
||||
private val stateMachine = ConnectionStateMachine(log = stateMachineLog)
|
||||
private var muxDemux: MuxDemux? = null
|
||||
|
|
@ -41,6 +41,7 @@ class TunnelClientImpl(
|
|||
override suspend fun connect(url: String) {
|
||||
if (!stateMachine.transition(TunnelState.CONNECTING)) {
|
||||
log(
|
||||
LogLevel.WARN,
|
||||
"TunnelClient: connect() ignored, current state is ${stateMachine.state.value}"
|
||||
)
|
||||
return
|
||||
|
|
@ -62,7 +63,10 @@ class TunnelClientImpl(
|
|||
try {
|
||||
demux.handleFrame(muxFrame)
|
||||
} catch (_: kotlinx.coroutines.channels.ClosedSendChannelException) {
|
||||
log("TunnelClient: frame arrived after disconnect, ignoring")
|
||||
log(
|
||||
LogLevel.DEBUG,
|
||||
"TunnelClient: frame arrived after disconnect, ignoring"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -153,7 +157,7 @@ class TunnelClientImpl(
|
|||
}
|
||||
|
||||
private suspend fun handleDisconnect(error: TunnelError) {
|
||||
log("TunnelClient: disconnected: ${error.message}")
|
||||
log(LogLevel.INFO, "TunnelClient: disconnected: ${error.message}")
|
||||
_errors.emit(error)
|
||||
// Use quiet cleanup -- transport is already broken, don't try to send CLOSE frames
|
||||
muxDemux?.closeAllQuietly()
|
||||
|
|
|
|||
|
|
@ -183,8 +183,8 @@ class MuxDemuxTest {
|
|||
|
||||
@Test
|
||||
fun rejectedOpenInvokesLogLambda() = runBlocking {
|
||||
val captured = mutableListOf<String>()
|
||||
val demux = MuxDemux(log = { captured.add(it) })
|
||||
val captured = mutableListOf<Pair<LogLevel, String>>()
|
||||
val demux = MuxDemux(log = { level, msg -> captured.add(level to msg) })
|
||||
demux.maxStreams = 1
|
||||
demux.onOutgoingFrame = { /* swallow ERROR frame */ }
|
||||
|
||||
|
|
@ -199,7 +199,8 @@ class MuxDemuxTest {
|
|||
demux.handleFrame(MuxFrame.Open(streamId = 2u))
|
||||
|
||||
assertEquals(1, captured.size)
|
||||
assertTrue(captured[0].contains("rejecting stream 2"))
|
||||
assertEquals(LogLevel.WARN, captured[0].first)
|
||||
assertTrue(captured[0].second.contains("rejecting stream 2"))
|
||||
|
||||
coroutineContext.cancelChildren()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -158,12 +158,13 @@ class ConnectionStateMachineTest {
|
|||
|
||||
@Test
|
||||
fun invalidTransitionInvokesLogLambda() {
|
||||
val captured = mutableListOf<String>()
|
||||
val sm = ConnectionStateMachine(log = { captured.add(it) })
|
||||
val captured = mutableListOf<Pair<LogLevel, String>>()
|
||||
val sm = ConnectionStateMachine(log = { level, msg -> captured.add(level to msg) })
|
||||
sm.transition(TunnelState.CONNECTED)
|
||||
assertEquals(1, captured.size)
|
||||
assertTrue(captured[0].contains("invalid transition"))
|
||||
assertTrue(captured[0].contains("DISCONNECTED"))
|
||||
assertTrue(captured[0].contains("CONNECTED"))
|
||||
assertEquals(LogLevel.WARN, captured[0].first)
|
||||
assertTrue(captured[0].second.contains("invalid transition"))
|
||||
assertTrue(captured[0].second.contains("DISCONNECTED"))
|
||||
assertTrue(captured[0].second.contains("CONNECTED"))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -405,11 +405,11 @@ class TunnelClientImplTest {
|
|||
|
||||
@Test
|
||||
fun `connection failure invokes log lambda`() = runBlocking {
|
||||
val captured = mutableListOf<String>()
|
||||
val captured = mutableListOf<Pair<LogLevel, String>>()
|
||||
val client = TunnelClientImpl(
|
||||
this,
|
||||
KtorWebSocketFactory(),
|
||||
log = { captured.add(it) }
|
||||
log = { level, msg -> captured.add(level to msg) }
|
||||
)
|
||||
|
||||
// Connect to a port that nothing is listening on -- triggers handleDisconnect
|
||||
|
|
@ -420,8 +420,11 @@ class TunnelClientImplTest {
|
|||
delay(200)
|
||||
|
||||
assertTrue(
|
||||
captured.any { it.startsWith("TunnelClient: disconnected:") },
|
||||
"Expected log message starting with 'TunnelClient: disconnected:', got $captured"
|
||||
captured.any {
|
||||
it.first == LogLevel.INFO &&
|
||||
it.second.startsWith("TunnelClient: disconnected:")
|
||||
},
|
||||
"Expected INFO log starting with 'TunnelClient: disconnected:', got $captured"
|
||||
)
|
||||
|
||||
coroutineContext.cancelChildren()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue