Add prioritized transport, bounded reconnect, and configurable keepalive
Carry numeric priorities through encrypted RPC and adapter writers with bounded admission. Correct push semantics and socket lifecycle cleanup, expose dispatch gating, and add opt-in connection health. Preserve the WebSocket setup API while allowing applications to override keepalive settings. Enable Android socket publication and document the 0.7.2-SNAPSHOT release workflow.
This commit is contained in:
1 parent
0a52bb5c03
commit
617f22dda1
27 files changed
+1154
-295
No files matched your search
@@ -0,0 +1,49 @@
|
||||
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.test.*
|
||||
import net.sergeych.crypto2.initCrypto
|
||||
import net.sergeych.kiloparsec.*
|
||||
import net.sergeych.utools.unpack
|
||||
import kotlin.test.*
|
||||
|
||||
class PriorityRpcTest {
|
||||
@Test fun encryptedConcurrentRepliesAndErrorsInheritPriority() = runTest {
|
||||
initCrypto()
|
||||
val echo by command<Int, Int>()
|
||||
val wait by command<Int, Int>()
|
||||
val fail by command<Int, Int>()
|
||||
val release = CompletableDeferred<Unit>()
|
||||
val entered = CompletableDeferred<Unit>()
|
||||
val ready = CompletableDeferred<Unit>()
|
||||
val requests = mutableListOf<Transport.Block>()
|
||||
val replies = mutableListOf<Transport.Block>()
|
||||
val (a, b) = createTestDevice()
|
||||
fun recording(device: Transport.Device, blocks: MutableList<Transport.Block>) = object : Transport.Device by device {
|
||||
override suspend fun send(block: UByteArray) {
|
||||
blocks += unpack<Transport.Block>(block)
|
||||
device.send(block)
|
||||
}
|
||||
}
|
||||
val server = KiloServerConnection(KiloInterface<Unit>().apply {
|
||||
on(echo) { it }
|
||||
on(wait) { entered.complete(Unit); release.await(); it }
|
||||
on(fail) { throw RemoteInterface.RemoteException("test-error") }
|
||||
}, recording(b, replies), Unit)
|
||||
val client = KiloClientConnection(KiloInterface<Unit>(), recording(a, requests), Unit)
|
||||
val jobs = listOf(launch { server.run() }, launch { client.run { if (it) ready.complete(Unit) } })
|
||||
try {
|
||||
ready.await()
|
||||
val slow = async { client.call(wait, 1, priority = 7) }
|
||||
entered.await()
|
||||
assertEquals(2, client.call(echo, 2, priority = 123))
|
||||
assertFalse(slow.isCompleted, "A pending reply must not prevent another concurrent call")
|
||||
assertFailsWith<RemoteInterface.RemoteException> { client.call(fail, 3, priority = 81) }
|
||||
release.complete(Unit); assertEquals(1, slow.await())
|
||||
for (priority in listOf(7, 123, 81)) {
|
||||
val request = requests.filterIsInstance<Transport.Block.Call>().single { it.priority == priority }
|
||||
val response = replies.filterIsInstance<Transport.Block.Response>().single { it.forId == request.id }
|
||||
assertEquals(priority, response.priority)
|
||||
}
|
||||
} finally { release.complete(Unit); jobs.forEach { it.cancelAndJoin() } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, ExperimentalUnsignedTypes::class)
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.test.*
|
||||
import net.sergeych.crypto2.initCrypto
|
||||
import net.sergeych.kiloparsec.*
|
||||
import kotlin.test.*
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class TransportAdmissionTest {
|
||||
@Test fun readyCallsDoNotAddPollingDelay() = runTest(timeout = 10.seconds) {
|
||||
val ping by command<Int, Int>()
|
||||
val (a, b) = createTestDevice()
|
||||
val local = LocalInterface<Unit>().apply { on(ping) { it } }
|
||||
val client = Transport(a, local, Unit)
|
||||
val server = Transport(b, local, Unit)
|
||||
val jobs = listOf(launch { client.run() }, launch { server.run() })
|
||||
try {
|
||||
val start = currentTime
|
||||
repeat(20) { assertEquals(it, client.call(ping, it)) }
|
||||
assertEquals(0L, currentTime - start, "Ready transports must not impose an artificial per-call delay")
|
||||
} finally { jobs.forEach { it.cancelAndJoin() } }
|
||||
}
|
||||
|
||||
@Test fun successfulPlainPushReturnsNormally() = runTest(timeout = 10.seconds) {
|
||||
val notify by command<Int, Unit>()
|
||||
val received = CompletableDeferred<Int>()
|
||||
val (a, b) = createTestDevice()
|
||||
val client = Transport(a, LocalInterface<Unit>(), Unit)
|
||||
val server = Transport(b, LocalInterface<Unit>().apply { on(notify) { received.complete(it); Unit } }, Unit)
|
||||
val jobs = listOf(launch { client.run() }, launch { server.run() })
|
||||
try {
|
||||
client.push(notify, 7)
|
||||
assertEquals(7, received.await())
|
||||
} finally { jobs.forEach { it.cancelAndJoin() } }
|
||||
}
|
||||
|
||||
@Test fun encryptedPushDoesNotWaitForRemoteHandler() = runTest(timeout = 10.seconds) {
|
||||
initCrypto()
|
||||
val notify by command<Int, Unit>()
|
||||
val ping by command<Int, Int>()
|
||||
val entered = CompletableDeferred<Unit>()
|
||||
val release = CompletableDeferred<Unit>()
|
||||
val ready = CompletableDeferred<Unit>()
|
||||
val (a, b) = createTestDevice()
|
||||
val server = KiloServerConnection(KiloInterface<Unit>().apply {
|
||||
on(notify) { entered.complete(Unit); release.await() }
|
||||
on(ping) { it }
|
||||
}, b, Unit)
|
||||
val client = KiloClientConnection(KiloInterface<Unit>(), a, Unit)
|
||||
val jobs = listOf(launch { server.run() }, launch { client.run { if (it) ready.complete(Unit) } })
|
||||
try {
|
||||
ready.await()
|
||||
val notification = async { client.push(notify, 7) }
|
||||
entered.await()
|
||||
runCurrent()
|
||||
assertTrue(notification.isCompleted, "Push must return before the remote handler finishes")
|
||||
notification.await()
|
||||
assertEquals(9, client.call(ping, 9), "A pending notification must not block ordinary RPC")
|
||||
} finally {
|
||||
release.complete(Unit)
|
||||
jobs.forEach { it.cancelAndJoin() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
package net.sergeych.kiloparsec.adapter
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.test.*
|
||||
import net.sergeych.crypto2.initCrypto
|
||||
import net.sergeych.kiloparsec.*
|
||||
import kotlin.math.ceil
|
||||
import kotlin.test.*
|
||||
|
||||
class PriorityLinkTest {
|
||||
@Test fun saturatedEncryptedLinkKeepsConcurrentControlResponsiveWithoutRateCap() = runTest {
|
||||
initCrypto()
|
||||
val bulk by command<UByteArray, Unit>()
|
||||
val ping by command<Int, Int>()
|
||||
val received = Channel<UByteArray>(Channel.UNLIMITED)
|
||||
val aInput = Channel<UByteArray>(Channel.UNLIMITED)
|
||||
val bInput = Channel<UByteArray>(Channel.UNLIMITED)
|
||||
var sentBytes = 0L
|
||||
val rate = 16_384
|
||||
fun endpoint(input: Channel<UByteArray>, destination: Channel<UByteArray>): Transport.Device {
|
||||
val writer = PriorityBlockWriter(backgroundScope) { block ->
|
||||
delay(ceil(block.size * 1000.0 / rate).toLong())
|
||||
sentBytes += block.size
|
||||
destination.send(block)
|
||||
}
|
||||
return ProxyDevice(input, Channel(), doClose = { writer.close(); input.close() }).also { it.priorityWriter = writer }
|
||||
}
|
||||
val a = endpoint(aInput, bInput)
|
||||
val b = endpoint(bInput, aInput)
|
||||
val ready = CompletableDeferred<Unit>()
|
||||
val api = KiloInterface<Unit>().apply {
|
||||
on(bulk) { received.send(it) }
|
||||
on(ping) { it }
|
||||
}
|
||||
val server = KiloServerConnection(api, b, Unit)
|
||||
val client = KiloClientConnection(api, a, Unit)
|
||||
val jobs = listOf(backgroundScope.launch { server.run() }, backgroundScope.launch { client.run { if (it) ready.complete(Unit) } })
|
||||
try {
|
||||
ready.await()
|
||||
val start = currentTime
|
||||
val initialBytes = sentBytes
|
||||
val producers = listOf<RemoteInterface>(client, server).flatMap { sender ->
|
||||
List(8) { backgroundScope.launch { while (isActive) sender.push(bulk, UByteArray(2000), priority = 0) } }
|
||||
}
|
||||
received.receive()
|
||||
repeat(10) {
|
||||
val began = currentTime
|
||||
assertEquals(it, client.call(ping, it, priority = 100))
|
||||
assertTrue(currentTime - began < 400, "control latency=${currentTime - began}")
|
||||
delay(80)
|
||||
}
|
||||
val elapsed = currentTime - start
|
||||
assertTrue((sentBytes - initialBytes) * 1000 / elapsed > rate * 1.6, "Writer must use available capacity")
|
||||
producers.forEach { it.cancelAndJoin() }
|
||||
} finally { jobs.forEach { it.cancelAndJoin() }; a.close(); b.close() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
package net.sergeych.kiloparsec.adapter
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.test.*
|
||||
import kotlinx.serialization.serializer
|
||||
import net.sergeych.bintools.DataSource
|
||||
import net.sergeych.bipack.BipackDecoder
|
||||
import net.sergeych.bipack.BipackEncoder
|
||||
import net.sergeych.kiloparsec.*
|
||||
import net.sergeych.utools.pack
|
||||
import net.sergeych.utools.unpack
|
||||
import kotlin.test.*
|
||||
|
||||
class PriorityTest {
|
||||
private fun block(priority: Int, id: Int = 1): UByteArray = pack<Transport.Block>(
|
||||
Transport.Block.Call(id.toUInt(), "example", ubyteArrayOf(1u, 2u)).also { it.priority = priority })
|
||||
|
||||
@Test fun legacyBodyAndTrailerCompatibility() {
|
||||
for (original in listOf(
|
||||
Transport.Block.Call(123456u, "test", UByteArray(3500) { it.toUByte() }),
|
||||
Transport.Block.Response(123456u, UByteArray(256)),
|
||||
Transport.Block.Error(123456u, "code", "message", UByteArray(180)),
|
||||
Transport.Block.Error(0u, "code", null, null),
|
||||
)) {
|
||||
val legacy = when (original) {
|
||||
is Transport.Block.Call -> ubyteArrayOf(0u) + BipackEncoder.encode(original).asUByteArray()
|
||||
is Transport.Block.Error -> ubyteArrayOf(1u) + BipackEncoder.encode(original).asUByteArray()
|
||||
is Transport.Block.Response -> ubyteArrayOf(2u) + BipackEncoder.encode(original).asUByteArray()
|
||||
}
|
||||
assertContentEquals(legacy, pack<Transport.Block>(original))
|
||||
assertEquals(0, unpack<Transport.Block>(legacy).priority)
|
||||
for (priority in listOf(Int.MIN_VALUE, -1, 0, 1, 100, Int.MAX_VALUE)) {
|
||||
original.priority = priority
|
||||
val packed = pack<Transport.Block>(original)
|
||||
assertEquals(priority, unpack<Transport.Block>(packed).priority)
|
||||
assertEquals(priority, blockPriority(packed))
|
||||
assertContentEquals(legacy, packed.copyOf(legacy.size))
|
||||
// Legacy decoding invokes the original body serializer and ignores trailing bytes.
|
||||
val oldRead = when (original) {
|
||||
is Transport.Block.Call -> BipackDecoder.decode<Transport.Block.Call>(packed.drop(1).toUByteArray())
|
||||
is Transport.Block.Response -> BipackDecoder.decode<Transport.Block.Response>(packed.drop(1).toUByteArray())
|
||||
is Transport.Block.Error -> BipackDecoder.decode<Transport.Block.Error>(packed.drop(1).toUByteArray())
|
||||
}
|
||||
assertEquals(0, oldRead.priority)
|
||||
}
|
||||
assertFailsWith<DataSource.EndOfData> { unpack<Transport.Block>(legacy + ubyteArrayOf(1u)) }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun numericOrderingStableTiesAndCancellation() = runTest {
|
||||
val release = CompletableDeferred<Unit>()
|
||||
val started = CompletableDeferred<Unit>()
|
||||
val sent = mutableListOf<Pair<Int, UInt>>()
|
||||
val writer = PriorityBlockWriter(backgroundScope) { bytes ->
|
||||
val b = unpack<Transport.Block>(bytes) as Transport.Block.Call
|
||||
if (b.id == 1u) { started.complete(Unit); release.await() }
|
||||
sent += b.priority to b.id
|
||||
}
|
||||
val first = async { writer.send(block(0, 1)) }
|
||||
started.await()
|
||||
val queued = listOf(0 to 2, 100 to 3, 2 to 4, 100 to 5, -10 to 6).map { (p, id) ->
|
||||
async { writer.send(block(p, id)) }
|
||||
}
|
||||
val cancelled = async { writer.send(block(Int.MAX_VALUE, 7)) }
|
||||
runCurrent(); cancelled.cancelAndJoin()
|
||||
release.complete(Unit)
|
||||
first.await(); queued.awaitAll()
|
||||
assertEquals(listOf(0 to 1u, 100 to 3u, 100 to 5u, 2 to 4u, 0 to 2u, -10 to 6u), sent)
|
||||
writer.close()
|
||||
}
|
||||
|
||||
@Test fun boundedAdmissionAndCloseReleaseWaiters() = runTest {
|
||||
val started = CompletableDeferred<Unit>()
|
||||
val writer = PriorityBlockWriter(backgroundScope, maxQueuedItems = 1) { started.complete(Unit); awaitCancellation() }
|
||||
val sending = async { runCatching { writer.send(block(0)) } }
|
||||
started.await()
|
||||
val queued = async { runCatching { writer.send(block(2)) } }
|
||||
runCurrent()
|
||||
assertFailsWith<RemoteInterface.Exception> { writer.send(block(100)) }
|
||||
writer.close()
|
||||
assertIs<CancellationException>(sending.await().exceptionOrNull())
|
||||
assertIs<RemoteInterface.ClosedException>(queued.await().exceptionOrNull())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user