Maybe fix shutdown. Cannot hurt

This commit is contained in:
loucass003 committed 2026-08-26 23:18:07 +02:00
1 parent 44342c0d41
commit e5ecd500c8
2 files changed
+127 -89

No files matched your search

@@ -46,15 +46,31 @@ import dev.slimevr.util.installUncaughtExceptionReporting
import dev.slimevr.vmc.VMCManager
import dev.slimevr.vrcosc.VRCOSCManager
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.rpc.KeybindSupport
fun main(args: Array<String>) = runBlocking<Unit>(appCoroutineExceptionHandler + CoroutineName("Main")) {
setupDesktopLogging()
installUncaughtExceptionReporting()
// Electron (and Ctrl+C) terminate us with SIGTERM, which the JVM turns into a plain
// process halt once every registered shutdown hook thread finishes. Without this hook,
// awaitCancellation() below is never unblocked and the `finally { appContext.dispose() }`
// never runs, so cleanup only happens by accident (e.g. a library's own shutdown hook).
val rootJob = coroutineContext[Job]!!
Runtime.getRuntime().addShutdownHook(
Thread({
runBlocking { withTimeoutOrNull(5000) { rootJob.cancelAndJoin() } }
}, "graceful-shutdown"),
)
contextDebugEnabled = System.getProperty("slimevr.debug.context") == "true" ||
System.getenv("SLIMEVR_DEBUG_CONTEXT") == "true"
@@ -157,7 +173,7 @@ fun main(args: Array<String>) = runBlocking<Unit>(appCoroutineExceptionHandler +
try {
appContext.startObserving()
launch { createDesktopHIDManager(appContext, this) }
createDesktopHIDManager(appContext, this)
launch { createDesktopKeybindManager(appContext, this) }
launch { createSolarXRWebsocketServer(appContext) }
launch { createIpcServers(appContext) }
@@ -165,6 +181,8 @@ fun main(args: Array<String>) = runBlocking<Unit>(appCoroutineExceptionHandler +
awaitCancellation()
} finally {
appContext.dispose()
// A suspend call here would throw immediately otherwise: this finally
// runs after our own Job is already cancelled.
withContext(NonCancellable) { appContext.dispose() }
}
}
@@ -34,7 +34,15 @@ private const val HID_READ_BUFFER_SIZE = 64
// Bounds how long cancellation waits on the uninterruptible native read when a device is idle
private const val HID_READ_TIMEOUT_MS = 100
private val hidSpec = HidServicesSpecification().apply { isAutoStart = false }
// We manage device open/close/read ourselves; hid4java's own shutdown hook would call
// HidApi.exit() on a separate thread with no coordination, racing our in-flight native reads.
// hidapi's own contract forbids this (hid_exit must not run concurrently with hid_read on
// another thread), and the same call shape has hung indefinitely on Windows before:
// https://github.com/libusb/hidapi/issues/133
private val hidSpec = HidServicesSpecification().apply {
isAutoStart = false
isAutoShutdown = false
}
// Initialize the native HID library. Must be called before enumerateDevices.
private val hidServices by lazy { HidManager.getHidServices(hidSpec) }
@@ -60,99 +68,111 @@ private fun enumerateCompatibleDevices(directTrackersEnabled: Boolean): Map<Stri
private data class ActiveReceiver(val job: Job, val receiver: HIDReceiver)
fun createDesktopHIDManager(appContext: AppContextProvider, scope: CoroutineScope) {
fun createDesktopHIDManager(appContext: AppContextProvider, scope: CoroutineScope): Job {
val active = mutableMapOf<String, ActiveReceiver>()
scope.launch {
while (isActive) {
val directTrackersEnabled = appContext.config.settings.context.state.value.data.hidConfig.trackersOverHid
val found = withContext(Dispatchers.IO) {
try {
enumerateCompatibleDevices(directTrackersEnabled)
} catch (e: Exception) {
AppLogger.hid.error(e, "HID enumeration failed")
emptyMap()
}
}
// Devices no longer present + jobs that exited on their own (read error)
val toRemove = (active.keys - found.keys) +
active.entries.filter { !it.value.job.isActive }.map { it.key }
for (path in toRemove) {
val entry = active.remove(path) ?: continue
entry.job.cancel()
entry.job.join()
AppLogger.hid.info("HID device removed: $path")
}
// Open newly detected devices
for ((path, hidDevice) in found) {
if (path in active) continue
if (!hidDevice.open()) {
AppLogger.hid.warn("Failed to open HID device: $path")
continue
}
val serial = hidDevice.serialNumber ?: path
AppLogger.hid.info("HID device detected: $serial")
val deviceJob = SupervisorJob(scope.coroutineContext[Job])
val deviceScope = CoroutineScope(scope.coroutineContext + deviceJob)
val receiver = appContext.server.context.state.value.dongles.values
.find { it.context.state.value.serialNumber == serial }
?: run {
val id = appContext.server.nextHandle()
val created = HIDReceiver.create(
id = id,
serialNumber = serial,
isDirect = isCompatibleHidTracker(hidDevice.vendorId, hidDevice.productId),
appContext = appContext,
scope = scope,
)
appContext.server.context.dispatch(VRServerActions.NewDongle(id, created))
created
}
receiver.context.dispatch(HIDReceiverActions.SetStatus(DongleStatus.CONNECTED))
deviceScope.launch(Dispatchers.IO) {
return scope.launch {
try {
while (isActive) {
val directTrackersEnabled = appContext.config.settings.context.state.value.data.hidConfig.trackersOverHid
val found = withContext(Dispatchers.IO) {
try {
// Reused across reads: parseHIDPackets is told how much of it is live
val buffer = ByteArray(HID_READ_BUFFER_SIZE)
while (isActive) {
val read = try {
hidDevice.read(buffer, HID_READ_TIMEOUT_MS)
} catch (_: Exception) {
-1
}
when {
// read error, device gone
read < 0 -> return@launch
read > 0 -> parseHIDPackets(buffer, read).forEach { receiver.packetEvents.emit(it) }
// 0 is a timeout with no data: the read already blocked, so just go again
}
}
} finally {
withContext(NonCancellable + Dispatchers.IO) { hidDevice.close() }
withContext(NonCancellable) {
for (record in receiver.context.state.value.trackers.values) {
appContext.server.getDevice(record.deviceId)?.context?.dispatch(
DeviceActions.Update { copy(status = TrackerStatus.DISCONNECTED) },
)
}
receiver.context.dispatch(HIDReceiverActions.SetStatus(DongleStatus.DISCONNECTED))
}
enumerateCompatibleDevices(directTrackersEnabled)
} catch (e: Exception) {
AppLogger.hid.error(e, "HID enumeration failed")
emptyMap()
}
}
deviceJob.complete()
active[path] = ActiveReceiver(deviceJob, receiver)
// Devices no longer present + jobs that exited on their own (read error)
val toRemove = (active.keys - found.keys) +
active.entries.filter { !it.value.job.isActive }.map { it.key }
for (path in toRemove) {
val entry = active.remove(path) ?: continue
entry.job.cancel()
entry.job.join()
AppLogger.hid.info("HID device removed: $path")
}
// Open newly detected devices
for ((path, hidDevice) in found) {
if (path in active) continue
if (!hidDevice.open()) {
AppLogger.hid.warn("Failed to open HID device: $path")
continue
}
val serial = hidDevice.serialNumber ?: path
AppLogger.hid.info("HID device detected: $serial")
val deviceJob = SupervisorJob(scope.coroutineContext[Job])
val deviceScope = CoroutineScope(scope.coroutineContext + deviceJob)
val receiver = appContext.server.context.state.value.dongles.values
.find { it.context.state.value.serialNumber == serial }
?: run {
val id = appContext.server.nextHandle()
val created = HIDReceiver.create(
id = id,
serialNumber = serial,
isDirect = isCompatibleHidTracker(hidDevice.vendorId, hidDevice.productId),
appContext = appContext,
scope = scope,
)
appContext.server.context.dispatch(VRServerActions.NewDongle(id, created))
created
}
receiver.context.dispatch(HIDReceiverActions.SetStatus(DongleStatus.CONNECTED))
deviceScope.launch(Dispatchers.IO) {
try {
// Reused across reads: parseHIDPackets is told how much of it is live
val buffer = ByteArray(HID_READ_BUFFER_SIZE)
while (isActive) {
val read = try {
hidDevice.read(buffer, HID_READ_TIMEOUT_MS)
} catch (_: Exception) {
-1
}
when {
// read error, device gone
read < 0 -> return@launch
read > 0 -> parseHIDPackets(buffer, read).forEach { receiver.packetEvents.emit(it) }
// 0 is a timeout with no data: the read already blocked, so just go again
}
}
} finally {
withContext(NonCancellable + Dispatchers.IO) { hidDevice.close() }
withContext(NonCancellable) {
for (record in receiver.context.state.value.trackers.values) {
appContext.server.getDevice(record.deviceId)?.context?.dispatch(
DeviceActions.Update { copy(status = TrackerStatus.DISCONNECTED) },
)
}
receiver.context.dispatch(HIDReceiverActions.SetStatus(DongleStatus.DISCONNECTED))
}
}
}
deviceJob.complete()
active[path] = ActiveReceiver(deviceJob, receiver)
}
delay(HID_POLL_INTERVAL_MS)
}
} finally {
// Stop every in-flight native read before HidApi.exit() runs, so we never
// call hid_exit() while another thread is still inside hid_read()/hid_close().
withContext(NonCancellable) {
for (entry in active.values) {
entry.job.cancel()
entry.job.join()
}
withContext(Dispatchers.IO) { HidApi.exit() }
}
delay(HID_POLL_INTERVAL_MS)
}
}
}