diff --git a/server/core/src/main/java/dev/slimevr/app-context.kt b/server/core/src/main/java/dev/slimevr/app-context.kt index 4a2977288..f325502ee 100644 --- a/server/core/src/main/java/dev/slimevr/app-context.kt +++ b/server/core/src/main/java/dev/slimevr/app-context.kt @@ -39,6 +39,7 @@ interface AppContextProvider : Phase1ContextProvider { val vmcManager: VMCManager val vrcOscManager: VRCOSCManager fun startObserving() + suspend fun dispose() } class AppContext( @@ -69,4 +70,8 @@ class AppContext( vmcManager.startObserving() vrcOscManager.startObserving() } + + override suspend fun dispose() { + udpServer.dispose() + } } diff --git a/server/core/src/main/java/dev/slimevr/bvh/behaviours.kt b/server/core/src/main/java/dev/slimevr/bvh/behaviours.kt index 1302e5cdc..17e4fdd34 100644 --- a/server/core/src/main/java/dev/slimevr/bvh/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/bvh/behaviours.kt @@ -39,8 +39,13 @@ class BVHRecordingBehaviour( .distinctUntilChanged() .onEach { (recording, path) -> if (recording && stream == null) { - val resolvedPath = resolveBvhPath(storage, path ?: return@onEach) ?: return@onEach + val resolvedPath = resolveBvhPath(storage, path ?: return@onEach) + if (resolvedPath == null) { + receiver.context.dispatch(BVHActions.StopRecording) + return@onEach + } try { + AppLogger.bvh.info("Opening BVH recording at ${storage.displayPath(resolvedPath)}") stream = BvhStream(storage.openTextFile(resolvedPath)).also { it.writeHeader(skeleton.computed.value) // TODO: we could write the initial T-Pose or whatever here @@ -51,6 +56,7 @@ class BVHRecordingBehaviour( } } else if (!recording && stream != null) { try { + AppLogger.bvh.info("Finalizing BVH recording") stream?.close() } catch (e: Exception) { AppLogger.bvh.error("Failed to finalize BVH recording", e) @@ -61,7 +67,12 @@ class BVHRecordingBehaviour( }.launchIn(receiver.context.scope) skeleton.computed.onEach { bones -> - stream?.writeFrame(bones) + try { + stream?.writeFrame(bones) + } catch (e: Exception) { + AppLogger.bvh.error("Failed to write BVH frame", e) + receiver.context.dispatch(BVHActions.StopRecording) + } }.launchIn(receiver.context.scope) } } diff --git a/server/core/src/main/java/dev/slimevr/bvh/stream.kt b/server/core/src/main/java/dev/slimevr/bvh/stream.kt index e8957e851..24959b32b 100644 --- a/server/core/src/main/java/dev/slimevr/bvh/stream.kt +++ b/server/core/src/main/java/dev/slimevr/bvh/stream.kt @@ -8,6 +8,8 @@ import dev.slimevr.skeleton.DEFAULT_BONE_OFFSETS import io.github.axisangles.ktmath.EulerOrder import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import solarxr_protocol.datatypes.BodyPart private const val FRAME_COUNT_DIGITS = Long.MAX_VALUE.toString().length @@ -17,55 +19,70 @@ private const val POSITION_SCALE = 1f class BvhStream( private val file: TextFileHandle, ) { + private val mutex = Mutex() private var frameCount = 0L private var frameCountOffset = 0L private var frameTimeOffset = 0L private var lastFrameTime = System.currentTimeMillis() private val frameIntervals = mutableListOf() + private var closed = false suspend fun writeHeader(bones: Map) { - file.write("HIERARCHY\n") - writeBone(BodyPart.HEAD, null, bones, 0) - file.write("MOTION\n") - file.write("Frames: ") - file.flush() - frameCountOffset = file.position() - frameCount = 0L - file.write(getBufferedFrameCount(0L) + "\n") - file.write("Frame Time: ") - file.flush() - frameTimeOffset = file.position() - file.write(getBufferedFrameInterval(0.01f) + "\n") - lastFrameTime = System.currentTimeMillis() + mutex.withLock { + check(!closed) { "BVH stream is closed" } + file.write("HIERARCHY\n") + writeBone(BodyPart.HEAD, null, bones, 0) + file.write("MOTION\n") + file.write("Frames: ") + file.flush() + frameCountOffset = file.position() + frameCount = 0L + file.write(getBufferedFrameCount(0L) + "\n") + file.write("Frame Time: ") + file.flush() + frameTimeOffset = file.position() + file.write(getBufferedFrameInterval(0.01f) + "\n") + lastFrameTime = System.currentTimeMillis() + } } suspend fun writeFrame(bones: Map) { - val now = System.currentTimeMillis() - if (frameCount > 0) { - val interval = (now - lastFrameTime) / 1000f - frameIntervals.add(interval) - } - lastFrameTime = now + mutex.withLock { + if (closed) return - val head = bones[BodyPart.HEAD] - val pos = head?.headPosition ?: Vector3.NULL - file.write("${pos.x * POSITION_SCALE} ${pos.y * POSITION_SCALE} ${pos.z * POSITION_SCALE}") - writeRotations(BodyPart.HEAD, bones) - file.write("\n") - frameCount++ + val now = System.currentTimeMillis() + if (frameCount > 0) { + val interval = (now - lastFrameTime) / 1000f + frameIntervals.add(interval) + } + lastFrameTime = now + + val head = bones[BodyPart.HEAD] + val pos = head?.headPosition ?: Vector3.NULL + file.write("${pos.x * POSITION_SCALE} ${pos.y * POSITION_SCALE} ${pos.z * POSITION_SCALE}") + writeRotations(BodyPart.HEAD, bones) + file.write("\n") + frameCount++ + } } suspend fun close() { - file.flush() - val avgInterval = if (frameIntervals.isNotEmpty()) frameIntervals.average().toFloat() else 0.01f + mutex.withLock { + if (closed) return + closed = true - file.seek(frameCountOffset) - file.write(getBufferedFrameCount(frameCount)) + file.flush() + val avgInterval = if (frameIntervals.isNotEmpty()) frameIntervals.average().toFloat() else 0.01f - file.seek(frameTimeOffset) - file.write(getBufferedFrameInterval(avgInterval)) + file.seek(frameCountOffset) + file.write(getBufferedFrameCount(frameCount)) - file.close() + file.seek(frameTimeOffset) + file.write(getBufferedFrameInterval(avgInterval)) + file.flush() + + file.close() + } } private fun getBufferedFrameCount(frameCount: Long): String { diff --git a/server/core/src/main/java/dev/slimevr/context/context.kt b/server/core/src/main/java/dev/slimevr/context/context.kt index 9edbc2613..cdfb7e430 100644 --- a/server/core/src/main/java/dev/slimevr/context/context.kt +++ b/server/core/src/main/java/dev/slimevr/context/context.kt @@ -75,9 +75,10 @@ class Context( mutableStateFlow.update { currentState -> reduce(currentState, action) } return } + val caller = captureCallerBehaviour() val before = mutableStateFlow.value mutableStateFlow.update { currentState -> reduce(currentState, action) } - debugMiddleware.onDispatch(null, before, action, mutableStateFlow.value) + debugMiddleware.onDispatch(caller, before, action, mutableStateFlow.value) } fun dispatchAll(actions: List) { @@ -87,11 +88,12 @@ class Context( } return } + val caller = captureCallerBehaviour() val before = mutableStateFlow.value mutableStateFlow.update { currentState -> actions.fold(currentState) { s, action -> reduce(s, action) } } - debugMiddleware.onDispatchAll(null, before, actions, mutableStateFlow.value) + debugMiddleware.onDispatchAll(caller, before, actions, mutableStateFlow.value) } fun observeAll(receiver: C) = behaviours.snapshot().forEach { behaviour -> @@ -105,6 +107,16 @@ class Context( } } + private fun captureCallerBehaviour(): String? { + val knownBehaviourClasses = behaviours.snapshot().mapTo(HashSet()) { behaviour -> + behaviour::class.qualifiedName ?: behaviour::class.simpleName.orEmpty() + } + return Throwable().stackTrace + .firstOrNull { frame -> frame.className in knownBehaviourClasses } + ?.className + ?.substringAfterLast('.') + } + companion object { fun create( initialState: S, @@ -114,7 +126,8 @@ class Context( name: String, ): Context { val mutableStateFlow = MutableStateFlow(initialState) - val scopeWithName = CoroutineScope(scope.coroutineContext + CoroutineName(name)) + val contextJob = SupervisorJob(scope.coroutineContext[Job]) + val scopeWithName = CoroutineScope(scope.coroutineContext + contextJob + CoroutineName(name)) val effectiveDebugMiddleware = if (ContextDebug.enabled) debugMiddleware else null val context = Context( mutableStateFlow, diff --git a/server/core/src/main/java/dev/slimevr/firmware/ota.kt b/server/core/src/main/java/dev/slimevr/firmware/ota.kt index 2df90d20c..5acf083ca 100644 --- a/server/core/src/main/java/dev/slimevr/firmware/ota.kt +++ b/server/core/src/main/java/dev/slimevr/firmware/ota.kt @@ -10,6 +10,8 @@ import io.ktor.network.sockets.aSocket import io.ktor.network.sockets.openReadChannel import io.ktor.network.sockets.openWriteChannel import io.ktor.network.sockets.port +import io.ktor.utils.io.ByteReadChannel +import io.ktor.utils.io.ByteWriteChannel import io.ktor.utils.io.discardExact import io.ktor.utils.io.readRemaining import io.ktor.utils.io.writeFully @@ -17,16 +19,9 @@ import io.ktor.utils.io.core.buildPacket import io.ktor.utils.io.core.readText import io.ktor.utils.io.core.writeFully import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout -import kotlinx.coroutines.withTimeoutOrNull import solarxr_protocol.datatypes.DeviceId -import solarxr_protocol.datatypes.TrackerStatus import solarxr_protocol.rpc.FirmwarePart import solarxr_protocol.rpc.FirmwareUpdateStatus import java.security.MessageDigest @@ -87,26 +82,37 @@ private suspend fun otaUpload( ): Boolean { val socket = withTimeout(30_000) { tcpServer.accept() } return socket.use { - val output = socket.openWriteChannel(autoFlush = true) - val input = socket.openReadChannel() - - var offset = 0 - while (offset < firmware.size) { - onProgress(((offset.toDouble() / firmware.size) * 100).toInt()) - - val chunkLen = min(OTA_CHUNK_SIZE, firmware.size - offset) - output.writeFully(firmware, offset, offset + chunkLen) - offset += chunkLen - - withTimeout(1_000) { input.discardExact(4) } - } - - output.flush() - val response = withTimeout(10_000) { input.readRemaining().readByteArray().decodeToString() } - response.contains("OK") + uploadFirmware( + output = socket.openWriteChannel(autoFlush = true), + input = socket.openReadChannel(), + firmware = firmware, + onProgress = onProgress, + ) } } +internal suspend fun uploadFirmware( + output: ByteWriteChannel, + input: ByteReadChannel, + firmware: ByteArray, + onProgress: suspend (Int) -> Unit, +): Boolean { + var offset = 0 + while (offset < firmware.size) { + onProgress(((offset.toDouble() / firmware.size) * 100).toInt()) + + val chunkLen = min(OTA_CHUNK_SIZE, firmware.size - offset) + output.writeFully(firmware, offset, offset + chunkLen) + offset += chunkLen + + withTimeout(1_000) { input.discardExact(4) } + } + + output.flush() + val response = withTimeout(10_000) { input.readRemaining().readByteArray().decodeToString() } + return response.contains("OK") +} + suspend fun doOtaFlash( deviceIp: String, deviceId: DeviceId, @@ -154,21 +160,7 @@ suspend fun doOtaFlash( onStatus(FirmwareUpdateStatus.REBOOTING, 0) - // Wait for the device to come back online after reboot. - // flatMapLatest switches to the matched device's own state flow so that status changes, - // which don't emit a new VRServerState, are also observed. - @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) - val connected = withTimeoutOrNull(60_000) { - server.context.state - .flatMapLatest { state -> - val device = state.devices.values.find { it.context.state.value.id.toUByte() == deviceId.id } - device?.context?.state?.map { it.status != TrackerStatus.DISCONNECTED } ?: flowOf(false) - } - .filter { it } - .first() - } - - if (connected == null) { + if (waitForReconnected(server, deviceId) == null) { onStatus(FirmwareUpdateStatus.ERROR_TIMEOUT, 0) return } diff --git a/server/core/src/main/java/dev/slimevr/firmware/reconnect.kt b/server/core/src/main/java/dev/slimevr/firmware/reconnect.kt new file mode 100644 index 000000000..281be8676 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/firmware/reconnect.kt @@ -0,0 +1,61 @@ +package dev.slimevr.firmware + +import dev.slimevr.VRServer +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withTimeoutOrNull +import solarxr_protocol.datatypes.DeviceId +import solarxr_protocol.datatypes.TrackerStatus + +private fun isOnlineStatus(status: TrackerStatus): Boolean = when (status) { + TrackerStatus.NONE, + TrackerStatus.DISCONNECTED, + TrackerStatus.TIMED_OUT, + -> false + + else -> true +} + +@OptIn(ExperimentalCoroutinesApi::class) +private fun deviceStatusFlow( + server: VRServer, + matches: (Int, String?) -> Boolean, +) = server.context.state.flatMapLatest { state -> + val device = state.devices.values.find { device -> + val deviceState = device.context.state.value + matches(deviceState.id, deviceState.macAddress) + } + device?.context?.state?.map { it.status } ?: flowOf(TrackerStatus.DISCONNECTED) +} + +suspend fun waitForConnected( + server: VRServer, + macAddress: String, + timeoutMs: Long = 30_000, +): Boolean? = withTimeoutOrNull(timeoutMs) { + deviceStatusFlow(server) { _, deviceMac -> deviceMac?.uppercase() == macAddress } + .filter(::isOnlineStatus) + .first() + true +} + +suspend fun waitForReconnected( + server: VRServer, + deviceId: DeviceId, + timeoutMs: Long = 60_000, +): Boolean? = withTimeoutOrNull(timeoutMs) { + val statuses = deviceStatusFlow(server) { id, _ -> id.toUByte() == deviceId.id } + .distinctUntilChanged() + + if (isOnlineStatus(statuses.first())) { + statuses.first { status -> !isOnlineStatus(status) } + } + + statuses.first(::isOnlineStatus) + true +} diff --git a/server/core/src/main/java/dev/slimevr/firmware/serial.kt b/server/core/src/main/java/dev/slimevr/firmware/serial.kt index 571208a54..5528b8878 100644 --- a/server/core/src/main/java/dev/slimevr/firmware/serial.kt +++ b/server/core/src/main/java/dev/slimevr/firmware/serial.kt @@ -9,17 +9,13 @@ import dev.slimevr.serial.SerialConnection import dev.slimevr.serial.SerialServer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull -import solarxr_protocol.datatypes.TrackerStatus import solarxr_protocol.rpc.FirmwarePart import solarxr_protocol.rpc.FirmwareUpdateStatus @@ -32,16 +28,6 @@ fun interface FirmwareFlasher { ) } -object NoopFirmwareFlasher : FirmwareFlasher { - override suspend fun flash( - portLocation: String, - handler: FlashingHandler, - parts: List, - onProgress: (Int) -> Unit, - ) = Unit -} - -@OptIn(ExperimentalCoroutinesApi::class) suspend fun doSerialFlash( portLocation: String, parts: List, @@ -212,17 +198,3 @@ internal suspend fun doSerialFlashPostFlash( onStatus(FirmwareUpdateStatus.DONE, 0) } - -suspend fun waitForConnected(server: VRServer, macAddress: String): Boolean? = - @OptIn(ExperimentalCoroutinesApi::class) - withTimeoutOrNull(30_000) { - server.context.state - .flatMapLatest { state -> - val device = - state.devices.values.find { it.context.state.value.macAddress?.uppercase() == macAddress } - device?.context?.state?.map { it.status != TrackerStatus.DISCONNECTED } - ?: flowOf(false) - } - .filter { it } - .first() - } diff --git a/server/core/src/main/java/dev/slimevr/oscquery/discovery.kt b/server/core/src/main/java/dev/slimevr/oscquery/discovery.kt index 58c1b021a..a986976bd 100644 --- a/server/core/src/main/java/dev/slimevr/oscquery/discovery.kt +++ b/server/core/src/main/java/dev/slimevr/oscquery/discovery.kt @@ -4,12 +4,13 @@ import com.appstractive.dnssd.DiscoveryEvent import com.appstractive.dnssd.discoverServices import dev.slimevr.AppLogger import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp" @@ -17,6 +18,7 @@ private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp" class OscQueryDiscovery( private val serviceType: String = OSC_JSON_SERVICE_TYPE, private val serviceFilter: (String) -> Boolean = { true }, + private val discoverServicesFlow: (String) -> Flow = ::discoverServices, ) { private val mutableServices = MutableStateFlow>(emptyList()) val services: StateFlow> = mutableServices.asStateFlow() @@ -25,11 +27,11 @@ class OscQueryDiscovery( fun start(scope: CoroutineScope) { if (job != null) return - job = scope.launch(Dispatchers.Default) { - discoverServices(serviceType).collectLatest { event -> + job = scope.launch { + discoverServicesFlow(serviceType).collect { event -> when (event) { is DiscoveryEvent.Discovered -> { - if (!serviceFilter(event.service.name)) return@collectLatest + if (!serviceFilter(event.service.name)) return@collect event.resolve() } @@ -40,8 +42,8 @@ class OscQueryDiscovery( } } - fun close() { - job?.cancel() + suspend fun close() { + job?.cancelAndJoin() job = null mutableServices.value = emptyList() } diff --git a/server/core/src/main/java/dev/slimevr/udp/behaviours.kt b/server/core/src/main/java/dev/slimevr/udp/behaviours.kt index 0e78eeaa5..ad30a6bc0 100644 --- a/server/core/src/main/java/dev/slimevr/udp/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/udp/behaviours.kt @@ -192,6 +192,7 @@ object HandshakeBehaviour : UDPConnectionBehaviour { mcuType = packet.data.mcuType, firmware = packet.data.firmware ?: firmware, protocolVersion = packet.data.protocolVersion, + status = TrackerStatus.OK, ) }, ) diff --git a/server/core/src/main/java/dev/slimevr/udp/server.kt b/server/core/src/main/java/dev/slimevr/udp/server.kt index 2419db925..e352edc19 100644 --- a/server/core/src/main/java/dev/slimevr/udp/server.kt +++ b/server/core/src/main/java/dev/slimevr/udp/server.kt @@ -5,10 +5,13 @@ import dev.slimevr.AppLogger import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import io.ktor.network.selector.SelectorManager +import io.ktor.network.sockets.BoundDatagramSocket import io.ktor.network.sockets.InetSocketAddress import io.ktor.network.sockets.aSocket import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlin.time.measureTime @@ -33,6 +36,10 @@ object UdpServerBaseBehaviour : UdpServerBehaviour { } class UdpServer(val context: UdpServerContext) { + private var receiveJob: Job? = null + private var socket: BoundDatagramSocket? = null + private var selectorManager: SelectorManager? = null + fun startObserving() = context.observeAll(this) fun findConnectionForDevice(deviceId: Int): UDPConnection? = context.state.value.connections.values.find { conn -> @@ -40,12 +47,14 @@ class UdpServer(val context: UdpServerContext) { } fun startReceiving(appContext: AppContextProvider, scope: CoroutineScope) { - scope.launch { + if (receiveJob != null) return + receiveJob = scope.launch { val port = appContext.config.settings.context.state.value.data.trackerPort val selectorManager = SelectorManager(Dispatchers.IO) val socket = aSocket(selectorManager).udp().bind(port = port) - - launch { + this@UdpServer.selectorManager = selectorManager + this@UdpServer.socket = socket + try { while (isActive) { val recvPacket = socket.receive() val took = measureTime { @@ -79,10 +88,23 @@ class UdpServer(val context: UdpServerContext) { AppLogger.udp.warn("Packet processing took too long ${took.inWholeMilliseconds}") } } + } finally { + this@UdpServer.receiveJob = null + this@UdpServer.socket = null + this@UdpServer.selectorManager = null + socket.close() + selectorManager.close() } } } + suspend fun dispose() { + socket?.close() + selectorManager?.close() + receiveJob?.cancelAndJoin() + receiveJob = null + } + companion object { val INITIAL_STATE = UdpServerState(connections = emptyMap()) diff --git a/server/core/src/test/java/dev/slimevr/TestServer.kt b/server/core/src/test/java/dev/slimevr/TestServer.kt index 8f6abbacf..767eb4491 100644 --- a/server/core/src/test/java/dev/slimevr/TestServer.kt +++ b/server/core/src/test/java/dev/slimevr/TestServer.kt @@ -116,4 +116,5 @@ abstract class TestAppContext : AppContextProvider { override val vmcManager: VMCManager get() = error("not used in test") override val vrcOscManager: VRCOSCManager get() = error("not used in test") override fun startObserving() {} + override suspend fun dispose() = Unit } diff --git a/server/core/src/test/java/dev/slimevr/bvh/BvhStreamTest.kt b/server/core/src/test/java/dev/slimevr/bvh/BvhStreamTest.kt new file mode 100644 index 000000000..2d89dc5f4 --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/bvh/BvhStreamTest.kt @@ -0,0 +1,88 @@ +package dev.slimevr.bvh + +import dev.slimevr.config.TextFileHandle +import dev.slimevr.skeleton.DEFAULT_SKELETON_STATE +import dev.slimevr.skeleton.buildBones +import io.github.axisangles.ktmath.Vector3 +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class BvhStreamTest { + @Test + fun `close persists header and frame data`() = runTest { + val file = InMemoryBvhFile() + val stream = BvhStream(file) + val initialBones = buildBones(DEFAULT_SKELETON_STATE) + val firstFrame = buildBones(DEFAULT_SKELETON_STATE, rootHead = Vector3(1f, 2f, 3f)) + val secondFrame = buildBones(DEFAULT_SKELETON_STATE, rootHead = Vector3(4f, 5f, 6f)) + + stream.writeHeader(initialBones) + stream.writeFrame(firstFrame) + stream.writeFrame(secondFrame) + stream.close() + + val content = file.content() + assertTrue(content.contains("HIERARCHY")) + assertTrue(content.contains("MOTION")) + assertTrue(content.contains("Frames: 2")) + assertTrue(content.contains("1.0 2.0 3.0")) + assertTrue(content.contains("4.0 5.0 6.0")) + } + + @Test + fun `writeFrame after close is ignored`() = runTest { + val file = InMemoryBvhFile() + val stream = BvhStream(file) + val bones = buildBones(DEFAULT_SKELETON_STATE) + + stream.writeHeader(bones) + stream.close() + val before = file.content() + + stream.writeFrame(buildBones(DEFAULT_SKELETON_STATE, rootHead = Vector3(7f, 8f, 9f))) + + assertEquals(before, file.content()) + } +} + +private class InMemoryBvhFile : TextFileHandle { + private val chars = mutableListOf() + private var pointer = 0 + private var closed = false + + override suspend fun write(text: String) { + check(!closed) { "file is closed" } + ensureCapacity(pointer) + text.forEachIndexed { index, char -> + val position = pointer + index + if (position < chars.size) { + chars[position] = char + } else { + chars.add(char) + } + } + pointer += text.length + } + + override suspend fun flush() = Unit + + override suspend fun position(): Long = pointer.toLong() + + override suspend fun seek(position: Long) { + pointer = position.toInt() + } + + override suspend fun close() { + closed = true + } + + fun content(): String = chars.joinToString("") + + private fun ensureCapacity(target: Int) { + while (chars.size < target) { + chars.add(' ') + } + } +} diff --git a/server/core/src/test/java/dev/slimevr/context/ContextCallerCaptureTest.kt b/server/core/src/test/java/dev/slimevr/context/ContextCallerCaptureTest.kt new file mode 100644 index 000000000..92baca2e0 --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/context/ContextCallerCaptureTest.kt @@ -0,0 +1,55 @@ +package dev.slimevr.context + +import dev.slimevr.context.debug.ContextDebug +import dev.slimevr.context.debug.DebugMiddleware +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals + +private sealed interface TestAction { + object Increment : TestAction +} + +private object DispatchingBehaviour : Behaviour> { + override fun reduce(state: Int, action: TestAction): Int = when (action) { + TestAction.Increment -> state + 1 + } + + fun trigger(context: Context) { + context.dispatch(TestAction.Increment) + } + + override fun observe(receiver: Context) { + trigger(receiver) + } +} + +private class RecordingDebugMiddleware : DebugMiddleware { + var caller: String? = null + + override fun onDispatch(caller: String?, before: Int, action: TestAction, after: Int) { + this.caller = caller + } + + override fun onDispatchAll(caller: String?, before: Int, actions: List, after: Int) = Unit +} + +class ContextCallerCaptureTest { + + @Test + fun `dispatch reports calling behaviour`() { + ContextDebug.enabled = true + + val middleware = RecordingDebugMiddleware() + val context = Context.create( + initialState = 0, + scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined), + behaviours = listOf(DispatchingBehaviour), + debugMiddleware = middleware, + name = "TestContext", + ) + + context.observeAll(context) + assertEquals("DispatchingBehaviour", middleware.caller) + } +} diff --git a/server/core/src/test/java/dev/slimevr/context/ContextScopeIsolationTest.kt b/server/core/src/test/java/dev/slimevr/context/ContextScopeIsolationTest.kt new file mode 100644 index 000000000..64c3087ae --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/context/ContextScopeIsolationTest.kt @@ -0,0 +1,41 @@ +package dev.slimevr.context + +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +private object NoopBehaviour : Behaviour + +class ContextScopeIsolationTest { + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `direct context child failure does not cancel parent scope`() = runTest { + val uncaught = mutableListOf() + val handler = CoroutineExceptionHandler { _, throwable -> uncaught += throwable } + val parentJob = Job() + val parentScope = CoroutineScope(StandardTestDispatcher(testScheduler) + parentJob + handler) + val context = Context.create( + initialState = 0, + scope = parentScope, + behaviours = listOf(NoopBehaviour), + name = "IsolatedContext", + ) + + context.scope.launch { + error("boom") + } + + advanceUntilIdle() + + assertTrue(parentJob.isActive) + assertEquals(1, uncaught.size) + } +} diff --git a/server/core/src/test/java/dev/slimevr/firmware/OtaUploadTest.kt b/server/core/src/test/java/dev/slimevr/firmware/OtaUploadTest.kt new file mode 100644 index 000000000..f966d43b0 --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/firmware/OtaUploadTest.kt @@ -0,0 +1,123 @@ +package dev.slimevr.firmware + +import dev.slimevr.VRServer +import dev.slimevr.VRServerActions +import dev.slimevr.buildTestVrServerStub +import dev.slimevr.device.Device +import dev.slimevr.device.DeviceActions +import dev.slimevr.device.DeviceOrigin +import io.ktor.utils.io.ByteChannel +import io.ktor.utils.io.readRemaining +import io.ktor.utils.io.writeFully +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.io.readByteArray +import solarxr_protocol.datatypes.DeviceId +import solarxr_protocol.datatypes.TrackerStatus +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +private fun addUdpDevice( + server: VRServer, + scope: kotlinx.coroutines.CoroutineScope, + id: Int = server.nextHandle(), + macAddress: String? = null, +): Device { + val device = Device.create( + scope = scope, + id = id, + address = "192.168.1.100", + macAddress = macAddress, + origin = DeviceOrigin.UDP, + protocolVersion = 0, + ) + server.context.dispatch(VRServerActions.NewDevice(device.context.state.value.id, device)) + return device +} + +class OtaUploadTest { + @Test + fun `uploadFirmware writes complete payload across chunk boundaries`() = runTest { + val firmware = ByteArray(2048 + 17) { index -> index.toByte() } + val output = ByteChannel(autoFlush = true) + val input = ByteChannel(autoFlush = true) + val progress = mutableListOf() + + repeat(2) { + input.writeFully(ByteArray(4)) + } + input.writeFully("OK".encodeToByteArray()) + input.close() + + assertTrue( + uploadFirmware( + output = output, + input = input, + firmware = firmware, + onProgress = { value -> progress += value }, + ), + ) + + output.close() + assertContentEquals(firmware, output.readRemaining().readByteArray()) + assertEquals(listOf(0, 99), progress) + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `waitForConnected ignores timed out status`() = runTest { + val vrServer = buildTestVrServerStub(backgroundScope) + val device = addUdpDevice(vrServer, backgroundScope, macAddress = "AA:BB:CC:DD:EE:FF") + var result: Boolean? = null + + val job = backgroundScope.launch { + result = waitForConnected(vrServer, "AA:BB:CC:DD:EE:FF", timeoutMs = 1_000) + } + + runCurrent() + assertFalse(job.isCompleted) + + device.context.dispatch(DeviceActions.Update { copy(status = TrackerStatus.TIMED_OUT) }) + runCurrent() + assertFalse(job.isCompleted) + + device.context.dispatch(DeviceActions.Update { copy(status = TrackerStatus.OK) }) + runCurrent() + + assertEquals(true, result) + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `waitForReconnected requires offline then online transition`() = runTest { + val vrServer = buildTestVrServerStub(backgroundScope) + val device = addUdpDevice(vrServer, backgroundScope) + device.context.dispatch(DeviceActions.Update { copy(status = TrackerStatus.OK) }) + var result: Boolean? = null + + val job = backgroundScope.launch { + result = waitForReconnected( + vrServer, + DeviceId(device.context.state.value.id.toUByte()), + timeoutMs = 1_000, + ) + } + + runCurrent() + assertFalse(job.isCompleted) + + device.context.dispatch(DeviceActions.Update { copy(status = TrackerStatus.TIMED_OUT) }) + runCurrent() + assertFalse(job.isCompleted) + + device.context.dispatch(DeviceActions.Update { copy(status = TrackerStatus.OK) }) + runCurrent() + + assertEquals(true, result) + } +} diff --git a/server/desktop/build.gradle.kts b/server/desktop/build.gradle.kts index df77763bb..85ec7ba1d 100644 --- a/server/desktop/build.gradle.kts +++ b/server/desktop/build.gradle.kts @@ -91,6 +91,8 @@ dependencies { implementation("io.ktor:ktor-server-core-jvm:$ktor_version") implementation("io.ktor:ktor-server-netty-jvm:$ktor_version") implementation("io.ktor:ktor-server-websockets-jvm:$ktor_version") + + testImplementation(kotlin("test")) } tasks.shadowJar { diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt index 153f35593..f9d5057fd 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt @@ -29,10 +29,11 @@ import dev.slimevr.trackingchecklist.TrackingChecklist import dev.slimevr.udp.UdpServer import dev.slimevr.vmc.VMCManager import dev.slimevr.vrcosc.VRCOSCManager +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking -fun main(args: Array) = runBlocking { +fun main(args: Array) = runBlocking { ContextDebug.enabled = System.getProperty("slimevr.debug.context") == "true" || System.getenv("SLIMEVR_DEBUG_CONTEXT") == "true" @@ -78,12 +79,16 @@ fun main(args: Array) = runBlocking { vrcOscManager = vrcOscManager, ) - appContext.startObserving() + try { + appContext.startObserving() - launch { createDesktopHIDManager(appContext, this) } - launch { createSolarXRWebsocketServer(appContext) } - launch { createIpcServers(appContext) } - launch { setupDesktopNetworkProfileChecker(this, networkProfileManager) } + launch { createDesktopHIDManager(appContext, this) } + launch { createSolarXRWebsocketServer(appContext) } + launch { createIpcServers(appContext) } + launch { setupDesktopNetworkProfileChecker(this, networkProfileManager) } - Unit + awaitCancellation() + } finally { + appContext.dispose() + } } diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/config/storage.kt b/server/desktop/src/main/java/dev/slimevr/desktop/config/storage.kt index ae903ae1f..9318136a4 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/config/storage.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/config/storage.kt @@ -56,7 +56,10 @@ class DesktopConfigStorage( override fun displayPath(path: String): String = resolve(path).absolutePath - private fun resolve(path: String): File = File(root, path) + private fun resolve(path: String): File { + val requested = File(path) + return if (requested.isAbsolute) requested else File(root, path) + } } private class RandomAccessTextFileHandle( @@ -79,6 +82,7 @@ private class RandomAccessTextFileHandle( } override suspend fun close() = withContext(Dispatchers.IO) { + file.fd.sync() file.close() } }