mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-12-06 00:32:35 -08:00
Reuse read buffers on ipc stuff
This commit is contained in:
1 parent
ca04a615ef
commit
7ede75de8a
7 files changed
+127
-59
No files matched your search
@@ -17,6 +17,9 @@ const val DRIVER_PIPE = "\\\\.\\pipe\\SlimeVRDriver"
|
||||
const val FEEDER_PIPE = "\\\\.\\pipe\\SlimeVRInput"
|
||||
const val SOLARXR_PIPE = "\\\\.\\pipe\\SlimeVRRpc"
|
||||
|
||||
// Frames larger than this are refused: nothing in either protocol comes close
|
||||
internal const val MAX_FRAME_SIZE = 256 * 1024
|
||||
|
||||
suspend fun createIpcServers(appContext: AppContextProvider) = coroutineScope {
|
||||
if (appContext.featureFlags.supportsDriver) {
|
||||
launch { createDriverServers(appContext) }
|
||||
|
||||
@@ -7,12 +7,12 @@ import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runInterruptible
|
||||
import kotlinx.coroutines.supervisorScope
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.Buffer
|
||||
import java.io.IOException
|
||||
import java.net.SocketException
|
||||
import java.net.StandardProtocolFamily
|
||||
@@ -25,28 +25,31 @@ import java.nio.channels.SocketChannel
|
||||
import kotlin.io.path.Path
|
||||
|
||||
suspend fun createUnixDriverSocket(appContext: AppContextProvider) = acceptUnixClients(DRIVER_SOCKET_NAME) { channel ->
|
||||
val writer = FramedWriter(channel)
|
||||
handleDriverConnection(
|
||||
appContext = appContext,
|
||||
source = DriverBridgeSource.DRIVER,
|
||||
messages = readFramedMessages(channel),
|
||||
send = { bytes -> writeFramed(channel, bytes) },
|
||||
send = { frame -> writer.write(frame) },
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun createUnixFeederSocket(appContext: AppContextProvider) = acceptUnixClients(FEEDER_SOCKET_NAME) { channel ->
|
||||
val writer = FramedWriter(channel)
|
||||
handleDriverConnection(
|
||||
appContext = appContext,
|
||||
source = DriverBridgeSource.FEEDER,
|
||||
messages = readFramedMessages(channel),
|
||||
send = { bytes -> writeFramed(channel, bytes) },
|
||||
send = { frame -> writer.write(frame) },
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun createUnixSolarXRSocket(appContext: AppContextProvider) = acceptUnixClients(SOLARXR_SOCKET_NAME) { channel ->
|
||||
val writer = FramedWriter(channel)
|
||||
handleSolarXRBridge(
|
||||
appContext = appContext,
|
||||
messages = readFramedMessages(channel),
|
||||
send = { bytes -> writeFramed(channel, bytes) },
|
||||
send = { frame -> writer.write(frame) },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -59,31 +62,61 @@ private fun isSocketInUse(socketPath: String): Boolean = try {
|
||||
false
|
||||
}
|
||||
|
||||
// Length field is LE u32 and includes the 4-byte header itself
|
||||
// Length field is LE u32 and includes the 4-byte header itself.
|
||||
// The payload lands in one Buffer that every frame reuses
|
||||
private fun readFramedMessages(channel: SocketChannel) = flow {
|
||||
val lenBuf = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN)
|
||||
val dataBuf = ByteBuffer.allocate(MAX_FRAME_SIZE)
|
||||
val frame = Buffer()
|
||||
try {
|
||||
while (true) {
|
||||
lenBuf.clear()
|
||||
if (runInterruptible { channel.read(lenBuf) } == -1) break
|
||||
lenBuf.flip()
|
||||
|
||||
val dataBuf = ByteBuffer.allocate(lenBuf.int - 4)
|
||||
while (dataBuf.hasRemaining()) {
|
||||
if (runInterruptible { channel.read(dataBuf) } == -1) break
|
||||
}
|
||||
emit(dataBuf.array())
|
||||
val len = runInterruptible(Dispatchers.IO) { readFrame(channel, lenBuf, dataBuf) }
|
||||
if (len < 0) break
|
||||
frame.clear()
|
||||
frame.write(dataBuf.array(), 0, len)
|
||||
emit(frame)
|
||||
}
|
||||
} catch (e: SocketException) {
|
||||
AppLogger.ipc.warn("Exception on socket: ${e.message}")
|
||||
} catch (e: ClosedByInterruptException) {
|
||||
AppLogger.ipc.info("Socket read interrupted, dropping connection")
|
||||
}
|
||||
}.flowOn(Dispatchers.IO)
|
||||
}
|
||||
|
||||
private fun writeFramed(channel: SocketChannel, bytes: ByteArray) {
|
||||
val header = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(bytes.size + 4).flip()
|
||||
channel.write(arrayOf(header, ByteBuffer.wrap(bytes)))
|
||||
private fun readFrame(channel: SocketChannel, lenBuf: ByteBuffer, dataBuf: ByteBuffer): Int {
|
||||
lenBuf.clear()
|
||||
if (!readFully(channel, lenBuf)) return -1
|
||||
lenBuf.flip()
|
||||
|
||||
val len = lenBuf.int - 4
|
||||
if (len !in 0..MAX_FRAME_SIZE) throw IOException("Frame length out of range: ${len + 4}")
|
||||
dataBuf.clear().limit(len)
|
||||
return if (readFully(channel, dataBuf)) len else -1
|
||||
}
|
||||
|
||||
private fun readFully(channel: SocketChannel, buf: ByteBuffer): Boolean {
|
||||
while (buf.hasRemaining()) {
|
||||
if (channel.read(buf) == -1) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private class FramedWriter(private val channel: SocketChannel) {
|
||||
private val header = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN)
|
||||
private val payload = ByteBuffer.allocate(MAX_FRAME_SIZE)
|
||||
private val gather = arrayOf(header, payload)
|
||||
|
||||
fun write(frame: Buffer) {
|
||||
val len = frame.size.toInt()
|
||||
if (len > MAX_FRAME_SIZE) throw IOException("Frame too large to send: ${len + 4} bytes")
|
||||
payload.clear().limit(len)
|
||||
frame.read(payload.array(), 0, len)
|
||||
|
||||
header.clear()
|
||||
header.putInt(len + 4)
|
||||
header.flip()
|
||||
while (header.hasRemaining() || payload.hasRemaining()) channel.write(gather)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun acceptUnixClients(
|
||||
|
||||
@@ -9,15 +9,17 @@ import com.sun.jna.platform.win32.WinError
|
||||
import com.sun.jna.platform.win32.WinNT
|
||||
import com.sun.jna.win32.StdCallLibrary
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.Buffer
|
||||
import java.io.IOException
|
||||
|
||||
private val k32 = Kernel32.INSTANCE
|
||||
|
||||
private const val HEADER_SIZE = 4
|
||||
private const val MAX_FRAME_SIZE = 256 * 1024
|
||||
|
||||
private const val WAIT_SLICE_MILLIS = 200
|
||||
private const val WAIT_TIMEOUT = 0x102
|
||||
@@ -56,6 +58,9 @@ internal class PipeSlot(private val handle: WinNT.HANDLE) : AutoCloseable {
|
||||
|
||||
private val buffer = Memory(MAX_FRAME_SIZE.toLong())
|
||||
|
||||
// Staging area between the pinned native buffer and okio, reused so a frame costs no allocation
|
||||
private val scratch = ByteArray(MAX_FRAME_SIZE)
|
||||
|
||||
// Resolved once. The wrappers have to stay referenced to keep the native memory alive anyway, so
|
||||
// unwrapping them per call would only re-do work. `transferred` replaces an IntByReference that
|
||||
// was allocated on every completion.
|
||||
@@ -78,21 +83,31 @@ internal class PipeSlot(private val handle: WinNT.HANDLE) : AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun readFrame(): ByteArray? {
|
||||
if (!readInto(0, HEADER_SIZE)) return null
|
||||
// Returns false once the peer closed. The overlapped wait blocks the thread it runs on, so both
|
||||
// sides of the pipe stay on Dispatchers.IO
|
||||
suspend fun readFrameInto(out: Buffer): Boolean = withContext(Dispatchers.IO) {
|
||||
if (!readInto(0, HEADER_SIZE)) return@withContext false
|
||||
val total = buffer.getInt(0)
|
||||
if (total !in HEADER_SIZE..MAX_FRAME_SIZE) throw IOException("Frame length out of range: $total")
|
||||
if (!readInto(HEADER_SIZE, total - HEADER_SIZE)) return null
|
||||
return buffer.getByteArray(HEADER_SIZE.toLong(), total - HEADER_SIZE)
|
||||
if (!readInto(HEADER_SIZE, total - HEADER_SIZE)) return@withContext false
|
||||
|
||||
val payload = total - HEADER_SIZE
|
||||
buffer.read(HEADER_SIZE.toLong(), scratch, 0, payload)
|
||||
out.write(scratch, 0, payload)
|
||||
true
|
||||
}
|
||||
|
||||
suspend fun writeFrame(payload: ByteArray) {
|
||||
val total = payload.size + HEADER_SIZE
|
||||
suspend fun writeFrame(payload: Buffer) {
|
||||
val size = payload.size.toInt()
|
||||
val total = size + HEADER_SIZE
|
||||
if (total > MAX_FRAME_SIZE) throw IOException("Frame too large to send: $total bytes")
|
||||
payload.read(scratch, 0, size)
|
||||
buffer.setInt(0, total)
|
||||
buffer.write(HEADER_SIZE.toLong(), payload, 0, payload.size)
|
||||
buffer.write(HEADER_SIZE.toLong(), scratch, 0, size)
|
||||
|
||||
val written = transfer { Kernel32IO.WriteFile(handlePointer, buffer, total, null, overlappedPointer) }
|
||||
val written = withContext(Dispatchers.IO) {
|
||||
transfer { Kernel32IO.WriteFile(handlePointer, buffer, total, null, overlappedPointer) }
|
||||
}
|
||||
if (written != total) throw IOException("Pipe write incomplete: $written of $total bytes")
|
||||
}
|
||||
|
||||
|
||||
@@ -101,8 +101,8 @@ suspend fun startBindingProvider() = withContext(Dispatchers.IO) {
|
||||
suspend fun handleDriverConnection(
|
||||
appContext: AppContextProvider,
|
||||
source: DriverBridgeSource,
|
||||
messages: Flow<ByteArray>,
|
||||
send: suspend (ByteArray) -> Unit,
|
||||
messages: Flow<Buffer>,
|
||||
send: suspend (Buffer) -> Unit,
|
||||
) = coroutineScope {
|
||||
val sendMutex = Mutex()
|
||||
|
||||
@@ -111,7 +111,7 @@ suspend fun handleDriverConnection(
|
||||
|
||||
suspend fun sendMsg(msg: ProtobufMessage) = sendMutex.withLock {
|
||||
ProtobufMessage.ADAPTER.encode(encodeWriter, msg)
|
||||
send(encodeBuffer.readByteArray())
|
||||
send(encodeBuffer)
|
||||
}
|
||||
|
||||
val bridge = DriverBridge.create(
|
||||
|
||||
@@ -16,14 +16,13 @@ import dev.slimevr.solarxr.SolarXRBridgeBehaviour
|
||||
import dev.slimevr.solarxr.onSolarXRMessage
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.cio.CIO
|
||||
import io.ktor.util.moveToByteArray
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.cancelChildren
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.Buffer
|
||||
import solarxr_protocol.MessageBundle
|
||||
import solarxr_protocol.rpc.EnableSteamVRDriverRequest
|
||||
import solarxr_protocol.rpc.OpenKeybindSettingsRequest
|
||||
@@ -58,8 +57,8 @@ class OpenKeybindSettingsBehaviour : SolarXRBridgeBehaviour {
|
||||
|
||||
suspend fun handleSolarXRBridge(
|
||||
appContext: AppContextProvider,
|
||||
messages: Flow<ByteArray>,
|
||||
send: suspend (ByteArray) -> Unit,
|
||||
messages: Flow<Buffer>,
|
||||
send: suspend (Buffer) -> Unit,
|
||||
) = coroutineScope {
|
||||
val bridge = SolarXRBridge.create(
|
||||
id = appContext.server.nextHandle(),
|
||||
@@ -75,20 +74,27 @@ suspend fun handleSolarXRBridge(
|
||||
|
||||
appContext.server.context.dispatch(VRServerActions.SolarXRConnected(bridge))
|
||||
|
||||
// One builder for the life of the connection. clear() keeps the buffer it has already grown into,
|
||||
// so a datafeed frame stops re-growing from 256 bytes every time. Safe to share: this collector
|
||||
// handles one bundle at a time, and moveToByteArray copies the bytes out before send suspends.
|
||||
// One builder and one send buffer for the life of the connection. clear() keeps the buffer it has
|
||||
// already grown into, so a datafeed frame stops re-growing from 256 bytes every time. Safe to
|
||||
// share: this collector handles one bundle at a time, and send drains the buffer
|
||||
val fbb = FlatBufferBuilder(256)
|
||||
val sendBuffer = Buffer()
|
||||
|
||||
bridge.outbound.on<MessageBundle> { bundle ->
|
||||
fbb.clear()
|
||||
fbb.finish(bundle.encode(JvmFlatBufferWriter(fbb)))
|
||||
send(fbb.dataBuffer().moveToByteArray())
|
||||
sendBuffer.write(fbb.dataBuffer())
|
||||
send(sendBuffer)
|
||||
}.launchIn(this)
|
||||
|
||||
val receiveBuffer = ByteBuffer.wrap(ByteArray(MAX_FRAME_SIZE))
|
||||
val reader = JvmFlatBufferReader(receiveBuffer)
|
||||
|
||||
try {
|
||||
messages.collect { bytes ->
|
||||
val reader = JvmFlatBufferReader(ByteBuffer.wrap(bytes))
|
||||
messages.collect { frame ->
|
||||
val size = frame.size.toInt()
|
||||
frame.read(receiveBuffer.array(), 0, size)
|
||||
receiveBuffer.clear().limit(size)
|
||||
onSolarXRMessage(MessageBundle.decode(reader, reader.getInt(0)), bridge)
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -10,38 +10,42 @@ import dev.slimevr.driver.DriverBridgeSource
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.supervisorScope
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.Buffer
|
||||
|
||||
private val k32 = Kernel32.INSTANCE
|
||||
private val adv32 = Advapi32.INSTANCE
|
||||
|
||||
private const val PIPE_BUFFER_SIZE = 64 * 1024
|
||||
|
||||
private typealias ConnectionHandler = suspend (messages: Flow<ByteArray>, send: suspend (ByteArray) -> Unit) -> Unit
|
||||
private typealias ConnectionHandler = suspend (pipe: WinNT.HANDLE, writer: PipeSlot) -> Unit
|
||||
|
||||
suspend fun createWindowsDriverPipe(appContext: AppContextProvider) = acceptWindowsClients(DRIVER_PIPE) { messages, send ->
|
||||
handleDriverConnection(appContext, DriverBridgeSource.DRIVER, messages, send)
|
||||
suspend fun createWindowsDriverPipe(appContext: AppContextProvider) = acceptWindowsClients(DRIVER_PIPE) { pipe, writer ->
|
||||
handleDriverConnection(appContext, DriverBridgeSource.DRIVER, readFrames(pipe)) { frame -> writer.writeFrame(frame) }
|
||||
}
|
||||
|
||||
suspend fun createWindowsFeederPipe(appContext: AppContextProvider) = acceptWindowsClients(FEEDER_PIPE) { messages, send ->
|
||||
handleDriverConnection(appContext, DriverBridgeSource.FEEDER, messages, send)
|
||||
suspend fun createWindowsFeederPipe(appContext: AppContextProvider) = acceptWindowsClients(FEEDER_PIPE) { pipe, writer ->
|
||||
handleDriverConnection(appContext, DriverBridgeSource.FEEDER, readFrames(pipe)) { frame -> writer.writeFrame(frame) }
|
||||
}
|
||||
|
||||
suspend fun createWindowsSolarXRPipe(appContext: AppContextProvider) = acceptWindowsClients(SOLARXR_PIPE) { messages, send ->
|
||||
handleSolarXRBridge(appContext, messages, send)
|
||||
suspend fun createWindowsSolarXRPipe(appContext: AppContextProvider) = acceptWindowsClients(SOLARXR_PIPE) { pipe, writer ->
|
||||
handleSolarXRBridge(appContext, readFrames(pipe)) { frame -> writer.writeFrame(frame) }
|
||||
}
|
||||
|
||||
private fun readFrames(handle: WinNT.HANDLE) = flow {
|
||||
PipeSlot(handle).use { reader ->
|
||||
while (true) emit(reader.readFrame() ?: break)
|
||||
val frame = Buffer()
|
||||
while (true) {
|
||||
frame.clear()
|
||||
if (!reader.readFrameInto(frame)) break
|
||||
emit(frame)
|
||||
}
|
||||
}
|
||||
}.flowOn(Dispatchers.IO)
|
||||
}
|
||||
|
||||
private fun createSecurePipe(pipeName: String): WinNT.HANDLE {
|
||||
val descriptor = WinNT.SECURITY_DESCRIPTOR(64 * 1024)
|
||||
@@ -94,7 +98,7 @@ private suspend fun acceptWindowsClients(
|
||||
|
||||
launch(Dispatchers.Default) {
|
||||
try {
|
||||
handle(readFrames(pipe)) { bytes -> writer.writeFrame(bytes) }
|
||||
handle(pipe, writer)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -9,14 +9,19 @@ import io.ktor.server.routing.routing
|
||||
import io.ktor.server.websocket.WebSockets
|
||||
import io.ktor.server.websocket.webSocket
|
||||
import io.ktor.websocket.Frame
|
||||
import io.ktor.websocket.WebSocketSession
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import okio.Buffer
|
||||
|
||||
const val SOLARXR_PORT = 21110
|
||||
|
||||
suspend fun createSolarXRWebsocketServer(appContext: AppContextProvider) {
|
||||
val engine = embeddedServer(Netty, port = SOLARXR_PORT) {
|
||||
install(WebSockets)
|
||||
install(WebSockets) {
|
||||
// Frames land in a fixed buffer downstream, and ktor would otherwise take any size
|
||||
maxFrameSize = MAX_FRAME_SIZE.toLong()
|
||||
}
|
||||
|
||||
routing {
|
||||
webSocket {
|
||||
@@ -24,15 +29,17 @@ suspend fun createSolarXRWebsocketServer(appContext: AppContextProvider) {
|
||||
handleSolarXRBridge(
|
||||
appContext = appContext,
|
||||
messages = flow {
|
||||
val buffer = Buffer()
|
||||
for (frame in incoming) {
|
||||
when (frame) {
|
||||
is Frame.Binary -> emit(frame.data)
|
||||
is Frame.Close -> AppLogger.solarxr.info("[WS] Connection closed")
|
||||
else -> {}
|
||||
}
|
||||
if (frame is Frame.Close) AppLogger.solarxr.info("[WS] Connection closed")
|
||||
if (frame !is Frame.Binary) continue
|
||||
|
||||
buffer.clear()
|
||||
buffer.write(frame.data)
|
||||
emit(buffer)
|
||||
}
|
||||
},
|
||||
send = { bytes -> send(Frame.Binary(fin = true, data = bytes)) },
|
||||
send = { frame -> send(Frame.Binary(fin = true, data = frame.readByteArray())) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user