Compare commits

..
8 Commits
Author SHA1 Message Date
sergeych e1a5873a0e less noise 2025-01-06 21:09:48 +03:00
sergeych 895193ba1c more ignores 2025-01-05 13:39:30 +03:00
sergeych ea6986dd07 0.5.2 migrated to kotlin 2.1, optStorage fixed 2025-01-05 13:38:13 +03:00
sergeych 748f273fb9 version bump 2023-07-23 20:39:19 +01:00
sergeych 6dfc418cb0 version bump 2023-07-21 16:06:41 +01:00
sergeych 8aa4b6bc3d 0.4.3-SNAPSHOT: disallow unintentionally overriding command implementations 2023-07-21 11:59:23 +01:00
sergeych 40fe234070 improved KVStorage support 2023-01-20 02:55:12 +01:00
sergeych 361d3f0b2b improved KVStorage support 2023-01-20 02:54:36 +01:00
15 changed files with 184 additions and 35 deletions

No files matched your search

+2
View File
@@ -1,3 +1,5 @@
.gradle .gradle
.idea .idea
build build
.gigaide
.kotlin
+2 -2
View File
@@ -2,7 +2,7 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
Current stable version is __0.4.2-SNAPSHOT__. The full-dpulex RPC over websock is ok, the security level is still disabled until the protocol part will be sabilized. Current stable version is __0.4.3-SNAPSHOT__. The full-dpulex RPC over websock is ok, the security level is still disabled until the protocol part will be sabilized.
This is a connection-agnostic, kotlin multiplaftorm library providing full-duplex RPC type binary protocol, effective to work with binary data, such as encrypted data, keys, multimedia, etc. Default implementation uses websockets transport (binary frames) available on all supported platofrms (currently, JS and JVM). This is a connection-agnostic, kotlin multiplaftorm library providing full-duplex RPC type binary protocol, effective to work with binary data, such as encrypted data, keys, multimedia, etc. Default implementation uses websockets transport (binary frames) available on all supported platofrms (currently, JS and JVM).
@@ -46,7 +46,7 @@ repsitories {
//... //...
dependencies { dependencies {
api("net.sergeych:parsec3:0.4.2-SNAPSHOT") api("net.sergeych:parsec3:0.4.3-SNAPSHOT")
} }
``` ```
+9 -9
View File
@@ -3,14 +3,14 @@ val kotlin_version: String by project
val logback_version: String by project val logback_version: String by project
plugins { plugins {
kotlin("multiplatform") version "1.7.21" kotlin("multiplatform") version "2.1.0"
kotlin("plugin.serialization") version "1.7.21" kotlin("plugin.serialization") version "2.1.0"
id("org.jetbrains.dokka") version "1.7.20" id("org.jetbrains.dokka") version "1.9.20"
`maven-publish` `maven-publish`
} }
group = "net.sergeych" group = "net.sergeych"
version = "0.4.2-SNAPSHOT" version = "0.5.3"
repositories { repositories {
mavenCentral() mavenCentral()
@@ -24,9 +24,9 @@ kotlin {
} }
jvm { jvm {
compilations.all { // compilations.all {
kotlinOptions.jvmTarget = "1.8" // kotlinOptions.jvmTarget = "1.8"
} // }
withJava() withJava()
testRuns["test"].executionTask.configure { testRuns["test"].executionTask.configure {
useJUnitPlatform() useJUnitPlatform()
@@ -35,7 +35,7 @@ kotlin {
js(IR) { js(IR) {
browser { browser {
commonWebpackConfig { commonWebpackConfig {
cssSupport.enabled = true // cssSupport.enabled = true
} }
} }
} }
@@ -53,7 +53,7 @@ kotlin {
api("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1") api("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1")
api("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0") api("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0")
api("net.sergeych:boss-serialization-mp:0.2.4-SNAPSHOT") api("net.sergeych:boss-serialization-mp:0.2.9")
api("net.sergeych:unikrypto:1.2.2-SNAPSHOT") api("net.sergeych:unikrypto:1.2.2-SNAPSHOT")
api("net.sergeych:mp_stools:1.3.2-SNAPSHOT") api("net.sergeych:mp_stools:1.3.2-SNAPSHOT")
-2
View File
@@ -1,6 +1,4 @@
kotlin.code.style=official kotlin.code.style=official
kotlin.mpp.enableGranularSourceSetsMetadata=true
kotlin.native.enableDependencyPropagation=false
kotlin.js.generate.executable.default=false kotlin.js.generate.executable.default=false
ktor_version=2.1.1 ktor_version=2.1.1
logback_version=1.2.10 logback_version=1.2.10
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
@@ -25,10 +25,13 @@ class AdapterBuilder<S : WithAdapter, H : CommandHost<S>>(
} }
/** /**
* Register command implementation * Register command implementation.
* @param ca command to implement
* @param overwrite allow replacing existing command implementation with a new block
* @param block command handler that implements the command
*/ */
fun <A, R> on(ca: CommandDescriptor<A, R>, block: suspend S.(A) -> R) { fun <A, R> on(ca: CommandDescriptor<A, R>,overwrite: Boolean=false, block: suspend S.(A) -> R) {
api.on(ca, block) api.on(ca, overwrite, block)
} }
val onCancelHandlers = mutableListOf<suspend () -> Unit>() val onCancelHandlers = mutableListOf<suspend () -> Unit>()
@@ -13,8 +13,8 @@ class CommandDescriptor<A, R>(
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
suspend operator fun invoke(adapter: Adapter<*>): R = adapter.invokeCommand(this,Unit as A) suspend operator fun invoke(adapter: Adapter<*>): R = adapter.invokeCommand(this,Unit as A)
operator fun <I: WithAdapter>invoke(commandHost: CommandHost<I>, block: suspend I.(A)->R) { operator fun <I: WithAdapter>invoke(commandHost: CommandHost<I>, overwrite: Boolean = false,block: suspend I.(A)->R) {
commandHost.on(this, block) commandHost.on(this, overwrite, block)
} }
} }
@@ -34,10 +34,16 @@ open class CommandHost<T: WithAdapter> {
private val handlers = mutableMapOf<String, suspend T.(ByteArray) -> ByteArray>() private val handlers = mutableMapOf<String, suspend T.(ByteArray) -> ByteArray>()
/** /**
* Provide implementation for a specific command in type-safe compile-time checked manner. the command * Provide implementation for a specific command in a type-safe compile-time checked manner.
* should be declared with [command] invocation. * The command should be declared with [command] invocation.
*
* Normally, existing command can't be replaced by new handlers and attempt to do so will throw
* [DuplicateCommandDefinition] at runtime. If it is done intentionally, set [overwrite] to
* true.
*/ */
fun <A, R> on(ca: CommandDescriptor<A, R>, block: suspend T.(A) -> R) { fun <A, R> on(ca: CommandDescriptor<A, R>, overwrite: Boolean = false, block: suspend T.(A) -> R) {
if( ca.name in handlers && !overwrite )
throw DuplicateCommandDefinition("command already defined: ${ca.name}")
handlers[ca.name] = {args -> handlers[ca.name] = {args ->
val decodedArgs = BossDecoder.decodeFrom<A>(ca.ass, args) val decodedArgs = BossDecoder.decodeFrom<A>(ca.ass, args)
BossEncoder.encode(ca.rss, block(decodedArgs)) BossEncoder.encode(ca.rss, block(decodedArgs))
@@ -2,7 +2,10 @@ package net.sergeych.parsec3
import net.sergeych.boss_serialization.BossDecoder import net.sergeych.boss_serialization.BossDecoder
import net.sergeych.boss_serialization_mp.BossEncoder import net.sergeych.boss_serialization_mp.BossEncoder
import net.sergeych.mptools.toDump import net.sergeych.mp_logger.LogTag
import net.sergeych.mp_logger.exception
import net.sergeych.mp_logger.info
import net.sergeych.mptools.encodeToHex
import kotlin.reflect.KProperty import kotlin.reflect.KProperty
import kotlin.reflect.KType import kotlin.reflect.KType
import kotlin.reflect.typeOf import kotlin.reflect.typeOf
@@ -16,15 +19,40 @@ import kotlin.reflect.typeOf
interface KVStorage { interface KVStorage {
operator fun get(key: String): ByteArray? operator fun get(key: String): ByteArray?
operator fun set(key: String, value: ByteArray?) operator fun set(key: String, value: ByteArray?)
operator fun contains(key: String): Boolean
/**
* Check whether key is in storage.
* Default implementation uses [keys]. You may override it for performance
*/
operator fun contains(key: String): Boolean = key in keys
val keys: Set<String>
val keys: Collection<String> /**
* Get number of object in the storage
* Default implementation uses [keys]. You may override it for performance
*/
val size: Int get() = keys.size
/**
* Clears all objects in the storage
* Default implementation uses [keys]. You may override it for performance
*/
fun clear() { fun clear() {
for (k in keys) this[k] = null for (k in keys) this[k] = null
} }
/**
* Default implementation uses [keys]. You may override it for performance
*/
fun isEmpty() = size == 0
/**
* Default implementation uses [keys]. You may override it for performance
*/
fun isNotEmpty() = size != 0
fun addAll(other: KVStorage) { fun addAll(other: KVStorage) {
for (k in other.keys) { for (k in other.keys) {
this[k] = other[k] this[k] = other[k]
@@ -39,12 +67,15 @@ inline operator fun <reified T> KVStorage.invoke(defaultValue: T,overrideName: S
inline fun <reified T> KVStorage.stored(defaultValue: T, overrideName: String? = null) = inline fun <reified T> KVStorage.stored(defaultValue: T, overrideName: String? = null) =
KVStorageDelegate<T>(this, typeOf<T>(), defaultValue, overrideName) KVStorageDelegate<T>(this, typeOf<T>(), defaultValue, overrideName)
inline fun <reified T> KVStorage.optStored(defaultValue: T? = null, overrideName: String? = null) =
KVStorageDelegate<T?>(this, typeOf<T>(), defaultValue, overrideName)
class KVStorageDelegate<T>( class KVStorageDelegate<T>(
private val storage: KVStorage, private val storage: KVStorage,
private val type: KType, private val type: KType,
private val defaultValue: T, private val defaultValue: T,
private val overrideName: String? = null, private val overrideName: String? = null,
) { ): LogTag("KVSD") {
private fun name(property: KProperty<*>): String = overrideName ?: property.name private fun name(property: KProperty<*>): String = overrideName ?: property.name
@@ -57,7 +88,13 @@ class KVStorageDelegate<T>(
if (data == null) if (data == null)
cachedValue = defaultValue cachedValue = defaultValue
else else
cachedValue = BossDecoder.decodeFrom(type, data) cachedValue = try {
info { " get ${name(property)}: ${type} [{${data.encodeToHex()}" }
BossDecoder.decodeFrom<T>(type, data)
} catch (e: Exception) {
exception { "failed to decode ${name(property)}: ${type}" to e }
defaultValue
}
cacheReady = true cacheReady = true
return cachedValue return cachedValue
} }
@@ -66,7 +103,6 @@ class KVStorageDelegate<T>(
// if (!cacheReady || value != cachedValue) { // if (!cacheReady || value != cachedValue) {
cachedValue = value cachedValue = value
cacheReady = true cacheReady = true
println("set ${name(property)} to ${BossEncoder.encode(type, value).toDump()}")
storage[name(property)] = BossEncoder.encode(type, value) storage[name(property)] = BossEncoder.encode(type, value)
// } // }
} }
@@ -110,7 +146,7 @@ class MemoryKVStorage(copyFrom: KVStorage? = null) : KVStorage {
return key in data return key in data
} }
override val keys: Collection<String> override val keys: Set<String>
get() = underlying?.keys ?: data.keys get() = underlying?.keys ?: data.keys
override fun clear() { override fun clear() {
@@ -17,3 +17,10 @@ class InvalidFrameException(text: String): ParsecException(ExceptionsRegistry.in
class UnknownCodeException(code: String,message: String?): ParsecException(code, message) class UnknownCodeException(code: String,message: String?): ParsecException(code, message)
class UnknownException(message: String?): ParsecException(ExceptionsRegistry.unknownErrorCode, message) class UnknownException(message: String?): ParsecException(ExceptionsRegistry.unknownErrorCode, message)
/**
* This exception is server-side, not intended to arise while processing commands, so it is not
* a parsec exception. It means some adapter is trying to redefine existing command, which is
* generally a fault.
*/
class DuplicateCommandDefinition(message: String) : RuntimeException(message)
+21 -1
View File
@@ -58,6 +58,7 @@ internal class AdapterTest {
val foo by command<String, String>() val foo by command<String, String>()
val ex by command<String,Unit>() val ex by command<String,Unit>()
val ex2 by command<String,Unit>() val ex2 by command<String,Unit>()
val nullableTest by command<Int,String?>()
} }
class ApiS2<T: WithAdapter> : CommandHost<T>() { class ApiS2<T: WithAdapter> : CommandHost<T>() {
// create command `foo` that takes a string argument and // create command `foo` that takes a string argument and
@@ -88,6 +89,9 @@ internal class AdapterTest {
on(ApiS1.ex2) { on(ApiS1.ex2) {
throw IllegalArgumentException() throw IllegalArgumentException()
} }
on(ApiS1.nullableTest) {
if( it == 1 ) "one" else null
}
onCancel { onCancel {
b1Cancelled = true b1Cancelled = true
} }
@@ -120,6 +124,9 @@ internal class AdapterTest {
assertEquals("%% loop-42foo %%", a1.invokeCommand(ApiS2<WithAdapter>().loopCall, "123")) assertEquals("%% loop-42foo %%", a1.invokeCommand(ApiS2<WithAdapter>().loopCall, "123"))
assertEquals("32142foo", a2.invokeCommand(ApiS1.foo, "321")) assertEquals("32142foo", a2.invokeCommand(ApiS1.foo, "321"))
assertEquals("one", a2.invokeCommand(ApiS1.nullableTest,1))
assertEquals(null, a2.invokeCommand(ApiS1.nullableTest,2))
assertEquals("---42foo", ApiS1.foo.invoke(a2, "---")) assertEquals("---42foo", ApiS1.foo.invoke(a2, "---"))
val x = assertThrows<IllegalArgumentException> { ApiS1.ex.invoke(a2, "foobar") } val x = assertThrows<IllegalArgumentException> { ApiS1.ex.invoke(a2, "foobar") }
assertEquals("foobar", x.message) assertEquals("foobar", x.message)
@@ -133,5 +140,18 @@ internal class AdapterTest {
assertTrue { b1Cancelled } assertTrue { b1Cancelled }
assertTrue { b2Cancelled } assertTrue { b2Cancelled }
} }
@Test
fun builderDupeErrorTest() = runTest {
assertThrows<DuplicateCommandDefinition> {
AdapterBuilder(ApiS1) {
newSession { TestSession("42") }
on(api.foo) {
it + buzz + "foo"
}
on(api.foo) {
it + buzz + "foo"
}
}
}
}
} }
@@ -0,0 +1,39 @@
package net.sergeych.parsec3
import net.sergeych.mp_tools.decodeBase64Compact
import net.sergeych.mp_tools.encodeToBase64Compact
import org.w3c.dom.Storage
import org.w3c.dom.set
/**
* Default KV storage in browser. Use if with `localStorage` or `sessionStorage`. Uses
* prefix for storage values to not to collide with other data
*/
class BrowserKVStorage(keyPrefix: String, private val bst: Storage) : KVStorage {
private val prefix = "$keyPrefix:"
fun k(key: String) = "$prefix$key"
override fun get(key: String): ByteArray? {
return bst.getItem(k(key))?.decodeBase64Compact()
}
override fun set(key: String, value: ByteArray?) {
val corrected = k(key)
if (value == null)
bst.removeItem(corrected)
else
bst.set(corrected, value.encodeToBase64Compact())
}
override val keys: Set<String>
get() {
val kk = mutableListOf<String>()
for (i in 0 until bst.length) {
val k = bst.key(i) ?: break
if( k.startsWith(prefix)) {
kk += k.substring(prefix.length)
}
}
return kk.toSet()
}
}
@@ -1,5 +1,7 @@
package net.sergeych.parsec3 package net.sergeych.parsec3
actual fun defaultNamedStorage(name: String): KVStorage { import kotlinx.browser.localStorage
TODO("Not yet implemented")
}
@Suppress("unused")
actual fun defaultNamedStorage(name: String): KVStorage = BrowserKVStorage(name, localStorage)
+36
View File
@@ -0,0 +1,36 @@
import kotlinx.browser.sessionStorage
import net.sergeych.parsec3.BrowserKVStorage
import net.sergeych.parsec3.optStored
import kotlin.test.*
class testBrowserKVStorage {
@Test
fun testStorage() {
val st = BrowserKVStorage("tpr", sessionStorage)
var foo: String? by st.optStored()
assertNull(foo)
foo = "bar"
assertEquals("bar", foo)
println(st.keys)
assertTrue { "foo" in st.keys }
assertFalse { "bar" in st.keys }
var bar: Int? by st.optStored()
assertNull(bar)
bar = 42
assertEquals(42, bar)
assertTrue { "foo" in st.keys }
assertTrue { "bar" in st.keys }
assertEquals("bar", foo)
val st2 = BrowserKVStorage("tpr", sessionStorage)
val foo2: String? by st.optStored(overrideName = "foo")
assertEquals("bar", foo2)
assertTrue(st2.isNotEmpty())
assertTrue(st.isNotEmpty())
st.clear()
assertTrue(st.isEmpty())
}
}
@@ -97,7 +97,7 @@ internal class WsServerKtTest {
@Test @Test
fun testWsServerReconnect() { fun testWsServerReconnect() {
embeddedServer(Netty, port = 8080) { embeddedServer(Netty, port = 8090) {
parsec3TransportServer( parsec3TransportServer(
TestApiServer, TestApiServer,
) { ) {
@@ -112,7 +112,7 @@ internal class WsServerKtTest {
}.start(wait = false) }.start(wait = false)
Log.connectConsole(Log.Level.DEBUG) Log.connectConsole(Log.Level.DEBUG)
val client = Parsec3WSClient("ws://localhost:8080/api/p3", TestApiClient) { val client = Parsec3WSClient("ws://localhost:8090/api/p3", TestApiClient) {
on(api.bar) { on(api.bar) {
"bar:$it" "bar:$it"
} }