diff --git a/gui/app/src/components/settings/pages/Serial.tsx b/gui/app/src/components/settings/pages/Serial.tsx index d9e36befd..a513be392 100644 --- a/gui/app/src/components/settings/pages/Serial.tsx +++ b/gui/app/src/components/settings/pages/Serial.tsx @@ -14,6 +14,7 @@ import { SerialTrackerGetWifiScanRequestT, SerialTrackerCustomCommandRequestT, SerialDeviceType, + SerialKeepaliveRequestT, } from 'solarxr-protocol'; import { useWebsocketAPI } from '@/hooks/websocket-api'; import { useSerialDevices } from '@/hooks/serial'; @@ -43,6 +44,9 @@ const consoleStatusMessage: Partial> = { const MAX_CONSOLE_CHARS = 200_000; +// Several of these fit in the server's grace window, so one dropped message costs nothing +const SERIAL_KEEPALIVE_MS = 4_000; + function appendLog(content: string, log: string) { const next = content + log; if (next.length <= MAX_CONSOLE_CHARS) return next; @@ -82,8 +86,17 @@ export function Serial() { const [isPaused, setPaused] = useState(false); + // The server holds every port this page opened and takes them back if the keepalive stops, so a + // tab that dies without unmounting doesn't leave them locked useEffect(() => { + const keepalive = setInterval(() => { + sendRPCPacket( + RpcMessage.SerialKeepaliveRequest, + new SerialKeepaliveRequestT() + ); + }, SERIAL_KEEPALIVE_MS); return () => { + clearInterval(keepalive); sendRPCPacket(RpcMessage.CloseSerialRequest, new CloseSerialRequestT()); }; }, []); 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 996174c9a..d29ac72b8 100644 --- a/server/core/src/main/java/dev/slimevr/firmware/serial.kt +++ b/server/core/src/main/java/dev/slimevr/firmware/serial.kt @@ -5,6 +5,7 @@ import dev.slimevr.config.Settings import dev.slimevr.config.SettingsActions import dev.slimevr.serial.FlashingHandler import dev.slimevr.serial.MAC_REGEX +import dev.slimevr.serial.SerialConsole import dev.slimevr.serial.SerialServer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -124,12 +125,29 @@ internal suspend fun doSerialFlashPostFlash( ) // The port re-enumerates after the flash, so it may take a moment to come back - val serialConn = serialServer.awaitConsole(portLocation, POST_FLASH_PORT_TIMEOUT) - if (serialConn == null) { + val lease = serialServer.awaitConsole(portLocation, POST_FLASH_PORT_TIMEOUT) + if (lease == null) { onStatus(FirmwareUpdateStatus.ERROR_DEVICE_NOT_FOUND, 0) return } + try { + provisionFlashedPort(lease.console, needManualReboot, ssid, password, settings, server, onStatus) + } finally { + lease.release() + } +} + +/** Reads the MAC off the freshly flashed tracker, hands it Wi-Fi credentials and waits for it to connect */ +private suspend fun provisionFlashedPort( + serialConn: SerialConsole, + needManualReboot: Boolean, + ssid: String?, + password: String?, + settings: Settings, + server: VRServer, + onStatus: suspend (FirmwareUpdateStatus, Int) -> Unit, +) { if (needManualReboot) { // wait for the device to reboot val rebooted = withTimeoutOrNull(60_000) { diff --git a/server/core/src/main/java/dev/slimevr/provisioning/module.kt b/server/core/src/main/java/dev/slimevr/provisioning/module.kt index 68b6b94b6..5874a58eb 100644 --- a/server/core/src/main/java/dev/slimevr/provisioning/module.kt +++ b/server/core/src/main/java/dev/slimevr/provisioning/module.kt @@ -132,29 +132,33 @@ data class ProvisioningManager( if (!selectScanPort(context, serialServer)) continue val portLocation = context.state.value.scan.portLocation ?: return@launch - val serialConn = serialServer.awaitConsole(portLocation, 3.seconds) + val lease = serialServer.awaitConsole(portLocation, 3.seconds) - if (serialConn == null) { + if (lease == null) { context.dispatch(ProvisioningActions.ScanStatusChanged(WifiScanStatus.NO_SERIAL_DEVICE_FOUND)) return@launch } - coroutineScope { - val work = async { - if (context.state.value.scan.networks.isEmpty()) { - scanWifiNetworks(context, serialConn) + try { + coroutineScope { + val work = async { + if (context.state.value.scan.networks.isEmpty()) { + scanWifiNetworks(context, lease.console) + } + awaitCancellation() } - awaitCancellation() + val disconnect = async { + serialServer.context.state.map { it.ports }.first { portLocation !in it } + } + select { + work.onAwait {} + disconnect.onAwait {} + } + work.cancel() + disconnect.cancel() } - val disconnect = async { - serialServer.context.state.map { it.ports }.first { portLocation !in it } - } - select { - work.onAwait {} - disconnect.onAwait {} - } - work.cancel() - disconnect.cancel() + } finally { + lease.release() } if (context.state.value.scan.networks.isEmpty()) { diff --git a/server/core/src/main/java/dev/slimevr/provisioning/phases.kt b/server/core/src/main/java/dev/slimevr/provisioning/phases.kt index 6a92b7389..3f3ec5050 100644 --- a/server/core/src/main/java/dev/slimevr/provisioning/phases.kt +++ b/server/core/src/main/java/dev/slimevr/provisioning/phases.kt @@ -195,14 +195,18 @@ internal suspend fun runProvisioningForPort( ) { context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.SERIAL_INIT)) - val serialConn = serialServer.awaitConsole(portLocation, 3.seconds) + val lease = serialServer.awaitConsole(portLocation, 3.seconds) - if (serialConn == null) { + if (lease == null) { context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.CONNECTION_ERROR)) return } - provisionPort(context, server, settings, serialConn, ssid, password) + try { + provisionPort(context, server, settings, lease.console, ssid, password) + } finally { + lease.release() + } } // Reboots the tracker and waits for a MAC address in the serial logs. diff --git a/server/core/src/main/java/dev/slimevr/serial/module.kt b/server/core/src/main/java/dev/slimevr/serial/module.kt index 1f4c6b74e..8395ba28d 100644 --- a/server/core/src/main/java/dev/slimevr/serial/module.kt +++ b/server/core/src/main/java/dev/slimevr/serial/module.kt @@ -12,14 +12,38 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull import solarxr_protocol.rpc.SerialDeviceType +import kotlin.concurrent.atomics.AtomicBoolean +import kotlin.concurrent.atomics.ExperimentalAtomicApi import kotlin.time.Duration private sealed interface Claim { - class Got(val console: SerialConsole) : Claim + class Got(val lease: SerialLease) : Claim data object Retry : Claim data object Failed : Claim } +/** An open port and how many leases are keeping it open */ +private class ConsoleHolder(val console: SerialConsole) { + var leases = 0 +} + +/** + * One holder's claim on a port. The port stays open while any lease on it is alive and closes once + * the last one is released, so every holder must [release] what it took. Releasing never suspends + * and repeats harmlessly + */ +@OptIn(ExperimentalAtomicApi::class) +class SerialLease internal constructor( + val console: SerialConsole, + private val onRelease: () -> Unit, +) { + private val released = AtomicBoolean(false) + + fun release() { + if (released.compareAndSet(false, true)) onRelease() + } +} + data class SerialServerState( val ports: Map, /** Ports a firmware flash holds. A claim outlasts the port re-enumerating mid-flash */ @@ -40,7 +64,7 @@ class SerialServer( private val watcher: SerialPortWatcher, ) { private val ownership = Mutex() - private val consoles = mutableMapOf() + private val consoles = mutableMapOf() fun startObserving() = context.observeAll(this) @@ -63,15 +87,16 @@ class SerialServer( } } - suspend fun awaitConsole(portLocation: String, timeout: Duration): SerialConsole? = withTimeoutOrNull(timeout) { + /** The caller owns the returned lease and must release it, or the port never closes */ + suspend fun awaitConsole(portLocation: String, timeout: Duration): SerialLease? = withTimeoutOrNull(timeout) { claimConsole(portLocation) } - private suspend fun claimConsole(portLocation: String): SerialConsole? { + private suspend fun claimConsole(portLocation: String): SerialLease? { while (true) { context.state.map { isFree(it, portLocation) }.first { it } when (val claim = ownership.withLock { claimOnce(portLocation) }) { - is Claim.Got -> return claim.console + is Claim.Got -> return claim.lease is Claim.Failed -> return null is Claim.Retry -> {} } @@ -81,17 +106,38 @@ class SerialServer( private suspend fun claimOnce(portLocation: String): Claim { if (!isFree(context.state.value, portLocation)) return Claim.Retry consoles[portLocation]?.let { existing -> - if (existing.closed.isActive) return Claim.Got(existing) + if (existing.console.closed.isActive) return Claim.Got(lease(portLocation, existing)) // this port failed and the cleanup in [watchForClose] hasn't run yet closeConsole(portLocation) } AppLogger.serial.info("Opening serial console on $portLocation") val clearResetLines = context.state.value.ports[portLocation]?.type == SerialDeviceType.ESP_TRACKER val console = SerialConsole.open(watcher, portLocation, clearResetLines) ?: return Claim.Failed - consoles[portLocation] = console + val holder = ConsoleHolder(console) + consoles[portLocation] = holder AppLogger.serial.info("Opened serial console on $portLocation") watchForClose(console) - return Claim.Got(console) + return Claim.Got(lease(portLocation, holder)) + } + + /** + * Hands out a lease on [holder]. Call under [ownership] and with no suspension before the lease + * reaches its holder, so a cancelled claim can't leave the count raised + */ + private fun lease(portLocation: String, holder: ConsoleHolder): SerialLease { + holder.leases++ + return SerialLease(holder.console) { + context.scope.launch { + ownership.withLock { + holder.leases-- + // A claim that landed while this release was queued keeps the port open + if (holder.leases == 0 && consoles[portLocation] === holder) { + AppLogger.serial.info("Last holder of $portLocation released it") + closeConsole(portLocation) + } + } + } + } } suspend fun openForFlashing(portLocation: String): FlashingHandler? = ownership.withLock { @@ -112,17 +158,17 @@ class SerialServer( } private suspend fun closeConsole(portLocation: String) { - val console = consoles.remove(portLocation) ?: return + val holder = consoles.remove(portLocation) ?: return AppLogger.serial.info("Closing serial console on $portLocation") - console.close() + holder.console.close() } private fun watchForClose(console: SerialConsole) { context.scope.launch { console.closed.join() - if (consoles[console.portLocation] === console) AppLogger.serial.warn("Serial port ${console.portLocation} reported itself closed") + if (consoles[console.portLocation]?.console === console) AppLogger.serial.warn("Serial port ${console.portLocation} reported itself closed") ownership.withLock { - if (consoles[console.portLocation] === console) closeConsole(console.portLocation) + if (consoles[console.portLocation]?.console === console) closeConsole(console.portLocation) } } } diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/provisioning.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/provisioning.kt index 8f31dc04b..e818e12d0 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/provisioning.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/provisioning.kt @@ -3,6 +3,7 @@ package dev.slimevr.solarxr.rpc import dev.slimevr.VRServer import dev.slimevr.device.Device import dev.slimevr.firmware.isOnlineStatus +import dev.slimevr.logging.AppLogger import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour @@ -12,6 +13,8 @@ import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.job +import kotlinx.coroutines.launch import solarxr_protocol.datatypes.DeviceOrigin import solarxr_protocol.rpc.StartWifiProvisioningRequest import solarxr_protocol.rpc.StartWifiScanRequest @@ -27,9 +30,25 @@ class ProvisioningBehaviour( private val provisioningManager: ProvisioningManager, ) : SolarXRBridgeBehaviour { override fun observe(receiver: SolarXRBridge) { + // The manager is shared by every client, so only the one that started a session stops it on + // its way out. A client that crashes or reloads never sends the stop itself, and provisioning + // holds serial ports + var startedProvisioning = false + var startedScan = false + + receiver.context.scope.coroutineContext.job.invokeOnCompletion { + if (!startedProvisioning && !startedScan) return@invokeOnCompletion + provisioningManager.context.scope.launch { + AppLogger.solarxr.info("Client left while provisioning, stopping it") + if (startedProvisioning) provisioningManager.stopProvisioning() + if (startedScan) provisioningManager.stopWifiScan() + } + } + receiver.rpcDispatcher.on { event -> val ssid = event.ssid ?: return@on + startedProvisioning = true provisioningManager.startProvisioning( server, ssid, @@ -38,14 +57,17 @@ class ProvisioningBehaviour( }.launchIn(receiver.context.scope) receiver.rpcDispatcher.on { + startedProvisioning = false provisioningManager.stopProvisioning() }.launchIn(receiver.context.scope) receiver.rpcDispatcher.on { + startedScan = true provisioningManager.startWifiScan() }.launchIn(receiver.context.scope) receiver.rpcDispatcher.on { + startedScan = false provisioningManager.stopWifiScan() }.launchIn(receiver.context.scope) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/serial.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/serial.kt index e5aeb3b63..7e5201bf1 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/serial.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/serial.kt @@ -2,12 +2,14 @@ package dev.slimevr.solarxr.rpc import dev.slimevr.logging.AppLogger import dev.slimevr.serial.SerialConsole +import dev.slimevr.serial.SerialLease import dev.slimevr.serial.SerialServer import dev.slimevr.serial.SerialServerState import dev.slimevr.serial.sortPorts import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope @@ -20,13 +22,16 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.job import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import solarxr_protocol.rpc.CloseSerialRequest import solarxr_protocol.rpc.OpenSerialRequest import solarxr_protocol.rpc.SerialConsoleStatus import solarxr_protocol.rpc.SerialDevice import solarxr_protocol.rpc.SerialDevicesRequest import solarxr_protocol.rpc.SerialDevicesResponse +import solarxr_protocol.rpc.SerialKeepaliveRequest import solarxr_protocol.rpc.SerialTrackerCustomCommandRequest import solarxr_protocol.rpc.SerialTrackerFactoryResetRequest import solarxr_protocol.rpc.SerialTrackerGetInfoRequest @@ -39,9 +44,29 @@ import kotlin.time.Duration.Companion.seconds // Wait before reopening a port whose console dropped while the port stayed plugged in private val REOPEN_DELAY = 1.seconds +// How long the client has to renew its hold before the server takes the ports back +private val KEEPALIVE_GRACE = 15.seconds + private const val LOG_QUEUE_CAPACITY = 2000 private const val MAX_BATCH_CHARS = 16_000 +/** + * Reuses the lease this client already holds on the port, replacing it when the port died under it. + * Leases stay in [leases] for as long as the client keeps its console open + */ +private suspend fun claimForClient( + serialServer: SerialServer, + leases: MutableMap, + portLocation: String, +): SerialLease? { + leases[portLocation]?.let { held -> + if (held.console.closed.isActive) return held + held.release() + leases -= portLocation + } + return serialServer.awaitConsole(portLocation, Duration.INFINITE)?.also { leases[portLocation] = it } +} + /** * Follows one port: streams its console while open, reports why it isn't otherwise, and opens it * again when it comes back or a flash releases it @@ -51,6 +76,7 @@ private suspend fun runConsoleSession( serialServer: SerialServer, portLocation: String, activeConsole: MutableStateFlow, + leases: MutableMap, ) = coroutineScope { launch { serialServer.context.state @@ -65,8 +91,8 @@ private suspend fun runConsoleSession( if (isPortFree(serialServer.context.state.value, portLocation)) { receiver.sendRpc(SerialUpdateResponse(status = SerialConsoleStatus.OPENING)) } - val console = serialServer.awaitConsole(portLocation, Duration.INFINITE) - if (console == null) { + val lease = claimForClient(serialServer, leases, portLocation) + if (lease == null) { // The port refused to open, so there is nothing to do until something changes val before = serialServer.context.state.value receiver.sendRpc(SerialUpdateResponse(status = SerialConsoleStatus.OPEN_FAILED)) @@ -74,6 +100,7 @@ private suspend fun runConsoleSession( continue } + val console = lease.console activeConsole.value = console val device = serialServer.context.state.value.ports[portLocation]?.toSerialDevice() receiver.sendRpc(SerialUpdateResponse(status = SerialConsoleStatus.OPEN, device = device)) @@ -118,9 +145,29 @@ class SerialBehaviour(private val serialServer: SerialServer) : SolarXRBridgeBeh override fun observe(receiver: SolarXRBridge) { val scope = receiver.context.scope - // A client has one console open at a time var session: Job? = null + var watchdog: Job? = null val activeConsole = MutableStateFlow(null) + val leases = mutableMapOf() + val renewals = Channel(Channel.CONFLATED) + + fun releaseLeases() { + leases.values.forEach { it.release() } + leases.clear() + } + + suspend fun endSession() { + session?.cancelAndJoin() + session = null + watchdog?.cancel() + watchdog = null + activeConsole.value = null + releaseLeases() + } + + // A client that crashes, reloads or loses its socket never sends CloseSerialRequest, so the + // scope dying has to drop its claims too + scope.coroutineContext.job.invokeOnCompletion { releaseLeases() } // The full list goes out on every change. Clients replace their list, so removals need no event serialServer.context.state @@ -139,15 +186,27 @@ class SerialBehaviour(private val serialServer: SerialServer) : SolarXRBridgeBeh receiver.rpcDispatcher.on { req -> val portLocation = req.port ?: return@on AppLogger.solarxr.info("Serial console requested on $portLocation") - session?.cancel() + // Joining keeps the old session from adding a lease after this one took over the map + session?.cancelAndJoin() activeConsole.value = null - session = scope.launch { runConsoleSession(receiver, serialServer, portLocation, activeConsole) } + session = scope.launch { runConsoleSession(receiver, serialServer, portLocation, activeConsole, leases) } + if (watchdog == null) { + watchdog = scope.launch { + while (withTimeoutOrNull(KEEPALIVE_GRACE) { renewals.receive() } != null) continue + AppLogger.solarxr.warn("Serial keepalive stopped, taking the client's consoles back") + watchdog = null + endSession() + } + } + }.launchIn(scope) + + receiver.rpcDispatcher.on { + renewals.trySend(Unit) }.launchIn(scope) receiver.rpcDispatcher.on { - session?.cancel() - session = null - activeConsole.value = null + AppLogger.solarxr.info("Serial consoles released by the client") + endSession() }.launchIn(scope) receiver.rpcDispatcher.on { diff --git a/server/core/src/test/java/dev/slimevr/TestSerial.kt b/server/core/src/test/java/dev/slimevr/TestSerial.kt index f5e61d16a..c864e2c8c 100644 --- a/server/core/src/test/java/dev/slimevr/TestSerial.kt +++ b/server/core/src/test/java/dev/slimevr/TestSerial.kt @@ -32,6 +32,7 @@ class FakeSerialPortWatcher( private val lineSinks = mutableMapOf Unit>() private val closeSinks = mutableMapOf Unit>() val openCount = mutableMapOf() + val closeCount = mutableMapOf() val clearResetLinesCalls = mutableMapOf() var failOpen = false @@ -43,7 +44,12 @@ class FakeSerialPortWatcher( clearResetLinesCalls[portLocation] = clearResetLines lineSinks[portLocation] = onLine closeSinks[portLocation] = onClosed - return SerialPortHandle(portLocation, "Fake $portLocation", { written += it }, {}) + return SerialPortHandle( + portLocation, + "Fake $portLocation", + { written += it }, + { closeCount[portLocation] = (closeCount[portLocation] ?: 0) + 1 }, + ) } override fun openForFlashing() = flashingHandler() diff --git a/server/core/src/test/java/dev/slimevr/serial/SerialServerTest.kt b/server/core/src/test/java/dev/slimevr/serial/SerialServerTest.kt index 284b362f1..46b7ecd6b 100644 --- a/server/core/src/test/java/dev/slimevr/serial/SerialServerTest.kt +++ b/server/core/src/test/java/dev/slimevr/serial/SerialServerTest.kt @@ -72,22 +72,99 @@ class SerialServerTest { val second = serial.server.awaitConsole("COM1", 5.seconds) assertNotNull(first) - assertSame(first, second) + assertNotNull(second) + assertSame(first.console, second.console) assertEquals(1, serial.watcher.openCount["COM1"]) } + @Test + fun `releasing the last lease closes the port`() = runTest { + val serial = buildTestSerial(backgroundScope) + serial.plug(fakePort()) + val lease = serial.server.awaitConsole("COM1", 5.seconds)!! + + lease.release() + advanceTimeBy(1) + + assertEquals(true, lease.console.closed.isCompleted) + assertEquals(1, serial.watcher.closeCount["COM1"]) + } + + @Test + fun `the port stays open while another lease holds it`() = runTest { + val serial = buildTestSerial(backgroundScope) + serial.plug(fakePort()) + val first = serial.server.awaitConsole("COM1", 5.seconds)!! + val second = serial.server.awaitConsole("COM1", 5.seconds)!! + + first.release() + advanceTimeBy(1) + assertEquals(true, first.console.closed.isActive) + + second.release() + advanceTimeBy(1) + assertEquals(true, first.console.closed.isCompleted) + assertEquals(1, serial.watcher.closeCount["COM1"]) + } + + @Test + fun `releasing the same lease twice leaves a later claim open`() = runTest { + val serial = buildTestSerial(backgroundScope) + serial.plug(fakePort()) + val first = serial.server.awaitConsole("COM1", 5.seconds)!! + first.release() + first.release() + advanceTimeBy(1) + + val second = serial.server.awaitConsole("COM1", 5.seconds)!! + advanceTimeBy(1) + + assertEquals(true, second.console.closed.isActive) + assertEquals(1, serial.watcher.closeCount["COM1"]) + } + + @Test + fun `a released port opens again on the next claim`() = runTest { + val serial = buildTestSerial(backgroundScope) + serial.plug(fakePort()) + val first = serial.server.awaitConsole("COM1", 5.seconds)!! + first.release() + advanceTimeBy(1) + + val second = serial.server.awaitConsole("COM1", 5.seconds) + + assertNotNull(second) + assertNotSame(first.console, second.console) + assertEquals(2, serial.watcher.openCount["COM1"]) + } + + @Test + fun `releasing a lease on an unplugged port does not close a replugged console`() = runTest { + val serial = buildTestSerial(backgroundScope) + serial.plug(fakePort()) + val first = serial.server.awaitConsole("COM1", 5.seconds)!! + + serial.unplug("COM1") + serial.plug(fakePort()) + val second = serial.server.awaitConsole("COM1", 5.seconds)!! + first.release() + advanceTimeBy(1) + + assertEquals(true, second.console.closed.isActive) + } + @Test fun `awaitConsole waits for the port to appear`() = runTest { val serial = buildTestSerial(backgroundScope) - var console: SerialConsole? = null - val job = launch { console = serial.server.awaitConsole("COM1", 30.seconds) } + var lease: SerialLease? = null + val job = launch { lease = serial.server.awaitConsole("COM1", 30.seconds) } advanceTimeBy(1_000) - assertNull(console) + assertNull(lease) serial.plug(fakePort()) job.join() - assertNotNull(console) + assertNotNull(lease) } @Test @@ -110,7 +187,7 @@ class SerialServerTest { fun `console keeps receiving after more lines than the log holds`() = runTest { val serial = buildTestSerial(backgroundScope) serial.plug(fakePort()) - val console = serial.server.awaitConsole("COM1", 5.seconds)!! + val console = serial.server.awaitConsole("COM1", 5.seconds)!!.console val last = backgroundScope.launch { console.lines.first { it == "line 1200" } } advanceTimeBy(1) @@ -126,7 +203,7 @@ class SerialServerTest { fun `clearLog drops the replayed lines`() = runTest { val serial = buildTestSerial(backgroundScope) serial.plug(fakePort()) - val console = serial.server.awaitConsole("COM1", 5.seconds)!! + val console = serial.server.awaitConsole("COM1", 5.seconds)!!.console serial.emitLine("COM1", "a") console.clearLog() @@ -141,12 +218,12 @@ class SerialServerTest { val first = serial.server.awaitConsole("COM1", 5.seconds)!! serial.unplug("COM1") - assertEquals(true, first.closed.isCompleted) + assertEquals(true, first.console.closed.isCompleted) serial.plug(fakePort()) val second = serial.server.awaitConsole("COM1", 5.seconds) assertNotNull(second) - assertNotSame(first, second) + assertNotSame(first.console, second.console) } @Test @@ -157,11 +234,11 @@ class SerialServerTest { serial.watcher.failPort("COM1") advanceTimeBy(1) - assertEquals(true, first.closed.isCompleted) + assertEquals(true, first.console.closed.isCompleted) val second = serial.server.awaitConsole("COM1", 5.seconds) assertNotNull(second) - assertNotSame(first, second) + assertNotSame(first.console, second.console) } @Test @@ -174,19 +251,19 @@ class SerialServerTest { val second = serial.server.awaitConsole("COM1", 5.seconds) assertNotNull(second) - assertNotSame(first, second) + assertNotSame(first.console, second.console) } @Test fun `openForFlashing takes the port from its console`() = runTest { val serial = buildTestSerial(backgroundScope) serial.plug(fakePort()) - val console = serial.server.awaitConsole("COM1", 5.seconds)!! + val lease = serial.server.awaitConsole("COM1", 5.seconds)!! val handler = serial.server.openForFlashing("COM1") assertNotNull(handler) - assertEquals(true, console.closed.isCompleted) + assertEquals(true, lease.console.closed.isCompleted) assertEquals(setOf("COM1"), serial.server.context.state.value.flashing) } @@ -241,15 +318,15 @@ class SerialServerTest { val serial = buildTestSerial(backgroundScope) serial.plug(fakePort()) val handler = serial.server.openForFlashing("COM1")!! - var console: SerialConsole? = null - val job = launch { console = serial.server.awaitConsole("COM1", 30.seconds) } + var lease: SerialLease? = null + val job = launch { lease = serial.server.awaitConsole("COM1", 30.seconds) } advanceTimeBy(1_000) - assertNull(console) + assertNull(lease) handler.closeSerial() job.join() - assertNotNull(console) + assertNotNull(lease) } @Test diff --git a/server/core/src/test/java/dev/slimevr/solarxr/ProvisioningBehaviourTest.kt b/server/core/src/test/java/dev/slimevr/solarxr/ProvisioningBehaviourTest.kt new file mode 100644 index 000000000..e04182776 --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/solarxr/ProvisioningBehaviourTest.kt @@ -0,0 +1,92 @@ +package dev.slimevr.solarxr + +import dev.slimevr.TestAppContext +import dev.slimevr.TestSerial +import dev.slimevr.VRServer +import dev.slimevr.buildTestSerial +import dev.slimevr.buildTestSettings +import dev.slimevr.buildTestVrServerStub +import dev.slimevr.context.Context +import dev.slimevr.provisioning.ProvisioningManager +import dev.slimevr.serial.SerialPortInfo +import dev.slimevr.solarxr.rpc.ProvisioningBehaviour +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runTest +import solarxr_protocol.rpc.StartWifiScanRequest +import kotlin.test.Test +import kotlin.test.assertEquals +import dev.slimevr.provisioning.reduce as reduceProvisioning + +private fun fakePort(loc: String = "COM1") = SerialPortInfo(loc, "Fake $loc", 0x1A86, 0x7523) + +private fun buildManager(serial: TestSerial, scope: CoroutineScope): ProvisioningManager { + val context = Context.create( + initialState = ProvisioningManager.INITIAL_STATE, + scope = scope, + reducer = ::reduceProvisioning, + name = "ProvisioningBehaviourTest", + ) + return ProvisioningManager( + context = context, + serialServer = serial.server, + settings = buildTestSettings(scope), + scope = scope, + ).also { it.startObserving() } +} + +private fun buildBridge(id: Int, server: VRServer, manager: ProvisioningManager, scope: CoroutineScope): Pair { + val bridgeScope = CoroutineScope(scope.coroutineContext + Job()) + val context = Context.create( + initialState = SolarXRBridgeState(dataFeedConfigs = listOf()), + scope = bridgeScope, + reducer = ::reduce, + behaviours = listOf(ProvisioningBehaviour(server, manager)), + name = "SolarXRProvisioningTest[$id]", + ) + val bridge = SolarXRBridge(id = id, context = context, appContext = object : TestAppContext() {}) + bridge.startObserving() + return bridge to bridgeScope +} + +@OptIn(ExperimentalCoroutinesApi::class) +class ProvisioningBehaviourTest { + @Test + fun `a client going away while scanning releases the port`() = runTest { + val serial = buildTestSerial(backgroundScope) + val manager = buildManager(serial, backgroundScope) + val server = buildTestVrServerStub(backgroundScope) + val (bridge, bridgeScope) = buildBridge(1, server, manager, backgroundScope) + serial.plug(fakePort()) + + bridge.rpcDispatcher.emit(StartWifiScanRequest()) + advanceTimeBy(4_000) + assertEquals(1, serial.watcher.openCount["COM1"]) + + bridgeScope.cancel() + advanceTimeBy(1_000) + + assertEquals(1, serial.watcher.closeCount["COM1"]) + } + + @Test + fun `a client that never scanned does not stop another client's scan`() = runTest { + val serial = buildTestSerial(backgroundScope) + val manager = buildManager(serial, backgroundScope) + val server = buildTestVrServerStub(backgroundScope) + val (scanner, _) = buildBridge(1, server, manager, backgroundScope) + val (_, idleScope) = buildBridge(2, server, manager, backgroundScope) + serial.plug(fakePort()) + + scanner.rpcDispatcher.emit(StartWifiScanRequest()) + advanceTimeBy(4_000) + + idleScope.cancel() + advanceTimeBy(1_000) + + assertEquals(null, serial.watcher.closeCount["COM1"]) + } +} diff --git a/solarxr-protocol b/solarxr-protocol index 0fd3d4c31..2bb24be95 160000 --- a/solarxr-protocol +++ b/solarxr-protocol @@ -1 +1 @@ -Subproject commit 0fd3d4c31bbe9fed706a5c4c25cb882002a63374 +Subproject commit 2bb24be959d58b822e1431a1067e9f6b057a8f03