more metrics on dispatcher

This commit is contained in:
loucass003 committed 2026-09-11 15:57:15 +02:00
1 parent bd2c4da2f2
commit e8196425da
6 files changed
+46 -12

No files matched your search

@@ -6,6 +6,7 @@ import dev.slimevr.VRServerActions
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferReader
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferWriter
import dev.slimevr.logging.AppLogger
import dev.slimevr.solarxr.OutboundProbe
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.onSolarXRMessage
import io.ktor.server.application.install
@@ -31,7 +32,6 @@ suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider)
routing {
webSocket {
AppLogger.ipc.info("New connection")
coroutineScope {
val bridge = SolarXRBridge.create(
id = appContext.server.nextHandle(),
@@ -39,12 +39,18 @@ suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider)
scope = this,
)
AppLogger.ipc.info("SolarXR[${bridge.id}] connected (websocket)")
appContext.server.context.dispatch(VRServerActions.SolarXRConnected(bridge))
val probe = OutboundProbe(bridge.id, "websocket")
bridge.outbound.on<MessageBundle> { bundle ->
val fbb = FlatBufferBuilder(256)
fbb.finish(bundle.encode(JvmFlatBufferWriter(fbb)))
send(Frame.Binary(fin = true, data = fbb.dataBuffer().moveToByteArray()))
val data = fbb.dataBuffer().moveToByteArray()
val sendStartNanos = System.nanoTime()
send(Frame.Binary(fin = true, data = data))
probe.record(bundle, data.size, System.nanoTime() - sendStartNanos)
}.launchIn(this)
bridge.startObserving()
@@ -54,7 +60,7 @@ suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider)
for (frame in incoming) {
when (frame) {
is Frame.Binary -> emit(frame.data)
is Frame.Close -> AppLogger.ipc.info("Connection closed")
is Frame.Close -> AppLogger.ipc.info("SolarXR[${bridge.id}] connection closed")
else -> {}
}
}
@@ -63,6 +69,7 @@ suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider)
onSolarXRMessage(MessageBundle.decode(reader, reader.getInt(0)), bridge)
}
} finally {
AppLogger.ipc.info("SolarXR[${bridge.id}] disconnected (websocket)")
bridge.disconnect()
}
}
@@ -54,6 +54,10 @@ class Subscription<T : Any, P : Any> @PublishedApi internal constructor(
* quarter of [capacity], so a dispatcher that is starting to fall behind says so while it is still
* keeping up. Capacity stays large enough to absorb a GC pause without dropping; the warning
* threshold is what makes it early, not a small buffer.
*
* Each report also carries the window's slowest handler run and longest queue wait. A high handler
* time means the consumer is stuck inside a handler; a high wait next to a low handler time means
* the drain coroutine is not getting scheduled.
*/
class EventDispatcher<T : Any>(
private val name: String,
@@ -79,6 +83,11 @@ class EventDispatcher<T : Any>(
private val depth = AtomicInteger()
private val peakDepth = AtomicInteger()
// Windowed maxima surfaced in the saturation report. The drain coroutine is the only writer;
// saturationReport reads and clears them. A dropped sample under that race is acceptable here.
private val peakHandlerNanos = AtomicLong()
private val peakWaitNanos = AtomicLong()
// Warn on how full the mailbox gets, not on it overflowing. Overflow is the failure; depth is the
// leading indicator, and separating the two means the buffer can stay big enough to ride out a GC
// pause without that also delaying the warning.
@@ -98,17 +107,22 @@ class EventDispatcher<T : Any>(
depth.decrementAndGet()
val type = envelope.payload::class
val waitNanos = System.nanoTime() - envelope.enqueuedAtNanos
if (waitNanos > peakWaitNanos.get()) peakWaitNanos.set(waitNanos)
metrics?.recordQueueWait(waitNanos, envelope.enqueueDepth)
val handlersStartNanos = System.nanoTime()
if (metrics == null) {
for (sub in handlersFor(type)) sub.action(envelope.payload)
continue
}
metrics?.recordQueueWait(System.nanoTime() - envelope.enqueuedAtNanos, envelope.enqueueDepth)
for (sub in handlersFor(type)) {
val start = System.nanoTime()
sub.action(envelope.payload)
metrics?.recordHandler(System.nanoTime() - start, type)
} else {
for (sub in handlersFor(type)) {
val start = System.nanoTime()
sub.action(envelope.payload)
metrics?.recordHandler(System.nanoTime() - start, type)
}
}
val handlersNanos = System.nanoTime() - handlersStartNanos
if (handlersNanos > peakHandlerNanos.get()) peakHandlerNanos.set(handlersNanos)
}
}
@@ -176,6 +190,8 @@ class EventDispatcher<T : Any>(
val peak = peakDepth.getAndSet(depth.get().coerceAtLeast(0))
val drops = dropped.getAndSet(0)
val stalls = stalled.getAndSet(0)
val slowestHandlerMicros = peakHandlerNanos.getAndSet(0) / 1000
val longestWaitMicros = peakWaitNanos.getAndSet(0) / 1000
if (drops == 0L && stalls == 0L && peak < warnDepth) return null
val outcome = when {
@@ -183,7 +199,8 @@ class EventDispatcher<T : Any>(
stalls > 0L -> "$stalls producer stalls"
else -> "nothing lost yet"
}
return "$name mailbox peak $peak/$capacity in $SATURATION_REPORT_INTERVAL -> $outcome"
return "$name mailbox peak $peak/$capacity in $SATURATION_REPORT_INTERVAL -> $outcome" +
" | slowest handler ${slowestHandlerMicros}us, longest queue wait ${longestWaitMicros}us"
}
}
@@ -211,6 +211,11 @@ class DataFeedInitBehaviour(
receiver.datafeedTimers.forEach { it.cancelAndJoin() }
AppLogger.solarxr.info(
"SolarXR[${receiver.id}] data feed started: " +
dataFeeds.joinToString { "every ${it.minimumTimeSinceLast}ms" },
)
val timers = dataFeeds.mapIndexed { index, config ->
receiver.context.scope.launch {
val interval = config.minimumTimeSinceLast.toLong().milliseconds
@@ -75,6 +75,7 @@ class OpenBindingsProviderBehaviour : SolarXRBridgeBehaviour {
suspend fun handleSolarXRBridge(
appContext: AppContextProvider,
transport: String,
messages: Flow<Buffer>,
send: suspend (Buffer) -> Unit,
) = coroutineScope {
@@ -91,6 +92,7 @@ suspend fun handleSolarXRBridge(
},
)
AppLogger.solarxr.info("SolarXR[${bridge.id}] connected ($transport)")
appContext.server.context.dispatch(VRServerActions.SolarXRConnected(bridge))
// One builder and one send buffer for the life of the connection. clear() keeps the buffer it has
@@ -121,6 +123,7 @@ suspend fun handleSolarXRBridge(
onSolarXRMessage(MessageBundle.decode(reader, reader.getInt(0)), bridge)
}
} finally {
AppLogger.solarxr.info("SolarXR[${bridge.id}] disconnected ($transport)")
bridge.disconnect()
coroutineContext.cancelChildren()
}
@@ -27,6 +27,7 @@ suspend fun createUnixSolarXRSocket(appContext: AppContextProvider) = acceptUnix
val writer = FramedWriter(channel)
handleSolarXRBridge(
appContext = appContext,
transport = "ipc",
messages = readFramedMessages(channel),
send = { frame -> writer.write(frame) },
)
@@ -28,6 +28,7 @@ suspend fun createSolarXRWebsocketServer(appContext: AppContextProvider) {
AppLogger.solarxr.info("[WS] New connection")
handleSolarXRBridge(
appContext = appContext,
transport = "websocket",
messages = flow {
val buffer = Buffer()
for (frame in incoming) {