Merge pull request #19 from InsanusMokrassar/0.3.0

0.3.0
This commit is contained in:
InsanusMokrassar 2021-06-07 19:38:43 +06:00 committed by GitHub
commit 466e531faf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 253 additions and 170 deletions

View File

@ -1,5 +1,21 @@
# Changelog # Changelog
## 0.3.0
* `Versions`
* `kotlin`: `1.4.32` -> `1.5.10`
* `coroutines`: `1.4.3` -> `1.5.0`
* `serialization`: `1.1.0` -> `1.2.1`
* `exposed`: `0.31.1` -> `0.32.1`
* `sdi`: `0.4.1` -> `0.5.0`
* `tgbotapi`: `0.34.1` -> `0.35.0`
* `microutils`: `0.4.36` -> `0.5.7`
* `Bot`
* Add plugin `PluginsHolder`
* Rewrite mechanism of `Config` working
* `PlaguBot` now is correctly serializable/deserializable
## 0.2.1 ## 0.2.1
* `Versions` * `Versions`

View File

@ -24,7 +24,7 @@ suspend inline fun initPlaguBot(
suspend fun main(args: Array<String>) { suspend fun main(args: Array<String>) {
val (configPath) = args val (configPath) = args
val file = File(configPath) val file = File(configPath)
val config = configJsonFormat.decodeFromString(ConfigSerializer, file.readText()) val config = configAndPluginsConfigJsonFormat.decodeFromString(PluginsConfigurationSerializer, file.readText()) as Config
PlaguBot(config).start().join() PlaguBot(config).start().join()
} }

View File

@ -1,8 +1,7 @@
package dev.inmo.plagubot package dev.inmo.plagubot
import dev.inmo.micro_utils.coroutines.safelyWithoutExceptions import dev.inmo.micro_utils.coroutines.safelyWithoutExceptions
import dev.inmo.plagubot.config.Config import dev.inmo.plagubot.config.*
import dev.inmo.plagubot.config.database
import dev.inmo.tgbotapi.bot.Ktor.telegramBot import dev.inmo.tgbotapi.bot.Ktor.telegramBot
import dev.inmo.tgbotapi.extensions.api.bot.setMyCommands import dev.inmo.tgbotapi.extensions.api.bot.setMyCommands
import dev.inmo.tgbotapi.extensions.behaviour_builder.BehaviourContext import dev.inmo.tgbotapi.extensions.behaviour_builder.BehaviourContext
@ -20,6 +19,7 @@ val Map<String, Any>.plagubot
@Serializable @Serializable
data class PlaguBot( data class PlaguBot(
@Serializable(PluginsConfigurationSerializer::class)
private val config: Config private val config: Config
) : Plugin { ) : Plugin {
@Transient @Transient

View File

@ -0,0 +1,25 @@
package dev.inmo.plagubot
import dev.inmo.plagubot.config.PluginsConfigurationSerializer
import dev.inmo.plagubot.config.SimplePluginsConfiguration
import dev.inmo.tgbotapi.extensions.behaviour_builder.BehaviourContext
import dev.inmo.tgbotapi.types.BotCommand
import kotlinx.serialization.Serializable
import org.jetbrains.exposed.sql.Database
@Serializable
data class PluginsHolder(
@Serializable(PluginsConfigurationSerializer::class)
private val pluginsConfiguration: SimplePluginsConfiguration
) : Plugin {
override suspend fun getCommands(): List<BotCommand> = pluginsConfiguration.plugins.flatMap {
it.getCommands()
}
override suspend fun BehaviourContext.invoke(database: Database, params: Map<String, Any>) {
val finalParams = pluginsConfiguration.params ?.plus(params) ?: params
pluginsConfiguration.plugins.forEach {
it.apply { invoke(database, finalParams) }
}
}
}

View File

@ -1,166 +1,15 @@
package dev.inmo.plagubot.config package dev.inmo.plagubot.config
import com.github.matfax.klassindex.KlassIndex
import dev.inmo.plagubot.Plugin import dev.inmo.plagubot.Plugin
import dev.inmo.plagubot.PluginSerializer import dev.inmo.sdi.Module
import dev.inmo.sdi.* import kotlinx.serialization.Contextual
import kotlinx.serialization.* import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.reflect.KClass
@InternalSerializationApi
internal inline fun <T : Plugin> KClass<T>.includeIn(builder: PolymorphicModuleBuilder<Plugin>) = builder.subclass(this, serializer())
@InternalSerializationApi
internal val configJsonFormat: Json
get() = Json {
ignoreUnknownKeys = true
serializersModule = SerializersModule {
polymorphic(Plugin::class) {
KlassIndex.getSubclasses(Plugin::class).flatMap { kclass ->
kclass.includeIn(this)
kclass.annotations.mapNotNull { it as? SerialName }.map {
it.value to kclass.serializer()
} + listOfNotNull(
kclass.simpleName ?.let {
it to kclass.serializer()
}
)
}.toMap().let {
default { requiredType ->
it[requiredType]
}
}
}
}
}
@Serializable @Serializable
data class Config( data class Config(
val plugins: List<@Contextual Plugin>, override val plugins: List<@Contextual Plugin>,
val database: DatabaseConfig = DatabaseConfig(), val database: DatabaseConfig = DatabaseConfig(),
val botToken: String, val botToken: String,
@Contextual @Contextual
val params: Module? = null override val params: Module? = null
) ) : PluginsConfiguration
@Serializer(Plugin::class)
private class InternalPluginSerializer(
private val params: Module
) : KSerializer<Plugin> {
override val descriptor: SerialDescriptor = PluginSerializer.descriptor
@InternalSerializationApi
override fun deserialize(decoder: Decoder): Plugin {
val asJson = JsonElement.serializer().deserialize(decoder)
return if (asJson is JsonPrimitive) {
params[asJson.jsonPrimitive.content] as Plugin
} else {
val jsonFormat = ((decoder as? JsonDecoder)?.json ?: configJsonFormat)
jsonFormat.decodeFromJsonElement(PluginSerializer, asJson)
}
}
@InternalSerializationApi
override fun serialize(encoder: Encoder, value: Plugin) {
params.keys.firstOrNull { params[it] === value } ?.also {
encoder.encodeString(it)
} ?: PluginSerializer.serialize(encoder, value)
}
}
private val DefaultModuleSerializer = ModuleSerializer(emptyList()) {
}
@Serializer(Module::class)
private class InternalModuleSerializer(
private val original: JsonElement?,
private val params: Module
) : KSerializer<Module> {
override val descriptor: SerialDescriptor = PluginSerializer.descriptor
@InternalSerializationApi
override fun deserialize(decoder: Decoder): Module {
val asJson = JsonElement.serializer().deserialize(decoder)
return if (asJson == original) {
params
} else {
configJsonFormat.decodeFromJsonElement(DefaultModuleSerializer, asJson)
}
}
@InternalSerializationApi
override fun serialize(encoder: Encoder, value: Module) = DefaultModuleSerializer.serialize(encoder, value)
}
private fun internalPluginSerializerSerializersModule(
internalPluginSerializer: InternalPluginSerializer,
internalModuleSerializer: InternalModuleSerializer?
) = SerializersModule {
contextual(internalPluginSerializer)
contextual(internalModuleSerializer ?: return@SerializersModule)
}
@Serializer(Config::class)
internal object ConfigSerializer : KSerializer<Config> {
private val jsonSerializer = JsonObject.serializer()
private val moduleSerializer = ModuleSerializer()
@InternalSerializationApi
override fun deserialize(decoder: Decoder): Config {
val json = jsonSerializer.deserialize(decoder)
val jsonFormat = (decoder as? JsonDecoder) ?.json ?: configJsonFormat
val paramsRow = json["params"]
val resultJsonFormat = if (paramsRow != null && paramsRow != JsonNull) {
val params = jsonFormat.decodeFromJsonElement(
moduleSerializer,
paramsRow
)
val pluginsSerializer = InternalPluginSerializer(params)
val moduleSerializer = InternalModuleSerializer(paramsRow, params)
Json(jsonFormat) {
serializersModule = decoder.serializersModule.overwriteWith(
internalPluginSerializerSerializersModule(pluginsSerializer, moduleSerializer)
)
}
} else {
jsonFormat
}
return resultJsonFormat.decodeFromJsonElement(
Config.serializer(),
json
)
}
@InternalSerializationApi
override fun serialize(encoder: Encoder, value: Config) {
if (value.params != null) {
val pluginsSerializer = InternalPluginSerializer(value.params)
val jsonFormat = Json(configJsonFormat) {
serializersModule = encoder.serializersModule.overwriteWith(
internalPluginSerializerSerializersModule(pluginsSerializer, null)
)
}
jsonSerializer.serialize(
encoder,
jsonFormat.encodeToJsonElement(
Config.serializer(),
value
) as JsonObject
)
} else {
Config.serializer().serialize(encoder, value)
}
}
}

View File

@ -0,0 +1,190 @@
package dev.inmo.plagubot.config
import com.github.matfax.klassindex.KlassIndex
import dev.inmo.plagubot.Plugin
import dev.inmo.plagubot.PluginSerializer
import dev.inmo.sdi.Module
import dev.inmo.sdi.ModuleSerializer
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.reflect.KClass
@InternalSerializationApi
internal inline fun <T : Plugin> KClass<T>.includeIn(builder: PolymorphicModuleBuilder<Plugin>) = builder.subclass(this, serializer())
@InternalSerializationApi
internal val configAndPluginsConfigJsonFormat: Json
get() = Json {
ignoreUnknownKeys = true
serializersModule = SerializersModule {
polymorphic(Plugin::class) {
KlassIndex.getSubclasses(Plugin::class).flatMap { kclass ->
kclass.includeIn(this)
kclass.annotations.mapNotNull { it as? SerialName }.map {
it.value to kclass.serializer()
} + listOfNotNull(
kclass.simpleName ?.let {
it to kclass.serializer()
}
)
}.toMap().let {
default { requiredType ->
it[requiredType]
}
}
}
}
}
internal interface PluginsConfiguration {
val plugins: List<Plugin>
val params: Module?
}
@Serializable
data class SimplePluginsConfiguration(
override val plugins: List<@Contextual Plugin>,
@Contextual
override val params: Module? = null
) : PluginsConfiguration
internal val DefaultModuleSerializer = ModuleSerializer(emptyList()) {
}
@Serializer(Plugin::class)
internal class InternalPluginSerializer(
private val params: Module
) : KSerializer<Plugin> {
override val descriptor: SerialDescriptor = PluginSerializer.descriptor
@InternalSerializationApi
override fun deserialize(decoder: Decoder): Plugin {
val asJson = JsonElement.serializer().deserialize(decoder)
return if (asJson is JsonPrimitive) {
params[asJson.jsonPrimitive.content] as Plugin
} else {
val jsonFormat = ((decoder as? JsonDecoder)?.json ?: configAndPluginsConfigJsonFormat)
jsonFormat.decodeFromJsonElement(PluginSerializer, asJson)
}
}
@InternalSerializationApi
override fun serialize(encoder: Encoder, value: Plugin) {
params.keys.firstOrNull { params[it] === value } ?.also {
encoder.encodeString(it)
} ?: PluginSerializer.serialize(encoder, value)
}
}
@Serializer(Module::class)
internal class InternalModuleSerializer(
private val original: JsonElement?,
private val params: Module
) : KSerializer<Module> {
override val descriptor: SerialDescriptor = PluginSerializer.descriptor
@InternalSerializationApi
override fun deserialize(decoder: Decoder): Module {
val asJson = JsonElement.serializer().deserialize(decoder)
return if (asJson == original) {
params
} else {
configAndPluginsConfigJsonFormat.decodeFromJsonElement(DefaultModuleSerializer, asJson)
}
}
@InternalSerializationApi
override fun serialize(encoder: Encoder, value: Module) = DefaultModuleSerializer.serialize(encoder, value)
}
internal fun internalPluginSerializerSerializersModule(
internalPluginSerializer: InternalPluginSerializer,
internalModuleSerializer: InternalModuleSerializer?
) = SerializersModule {
contextual(internalPluginSerializer)
contextual(internalModuleSerializer ?: return@SerializersModule)
}
@Serializer(PluginsConfiguration::class)
internal object PluginsConfigurationSerializer : KSerializer<PluginsConfiguration> {
private val jsonSerializer = JsonObject.serializer()
private val moduleSerializer = ModuleSerializer()
override val descriptor: SerialDescriptor = jsonSerializer.descriptor
@InternalSerializationApi
override fun deserialize(decoder: Decoder): PluginsConfiguration {
val json = jsonSerializer.deserialize(decoder)
val jsonFormat = (decoder as? JsonDecoder) ?.json ?: configAndPluginsConfigJsonFormat
val paramsRow = json["params"]
val resultJsonFormat = if (paramsRow != null && paramsRow != JsonNull) {
val params = jsonFormat.decodeFromJsonElement(
moduleSerializer,
paramsRow
)
val pluginsSerializer = InternalPluginSerializer(params)
val moduleSerializer = InternalModuleSerializer(paramsRow, params)
Json(jsonFormat) {
serializersModule = decoder.serializersModule.overwriteWith(
internalPluginSerializerSerializersModule(pluginsSerializer, moduleSerializer)
)
}
} else {
jsonFormat
}
return try {
resultJsonFormat.decodeFromJsonElement(
Config.serializer(),
json
)
} catch (e: SerializationException) {
resultJsonFormat.decodeFromJsonElement(
SimplePluginsConfiguration.serializer(),
json
)
}
}
@InternalSerializationApi
override fun serialize(encoder: Encoder, value: PluginsConfiguration) {
val params = value.params
val serializer = when (value) {
is Config -> Config.serializer()
is SimplePluginsConfiguration -> SimplePluginsConfiguration.serializer()
else -> return
}
if (params != null) {
val pluginsSerializer = InternalPluginSerializer(params)
val jsonFormat = Json(configAndPluginsConfigJsonFormat) {
serializersModule = encoder.serializersModule.overwriteWith(
internalPluginSerializerSerializersModule(pluginsSerializer, null)
)
}
jsonSerializer.serialize(
encoder,
when (value) {
is Config -> jsonFormat.encodeToJsonElement(Config.serializer(), value)
is SimplePluginsConfiguration -> jsonFormat.encodeToJsonElement(SimplePluginsConfiguration.serializer(), value)
else -> return
} as JsonObject
)
} else {
when (value) {
is Config -> Config.serializer().serialize(encoder, value)
is SimplePluginsConfiguration -> SimplePluginsConfiguration.serializer().serialize(encoder, value)
else -> return
}
}
}
}

View File

@ -22,13 +22,16 @@ class ConfigTest {
} }
} }
""".trimIndent() """.trimIndent()
val config = configJsonFormat.decodeFromString(ConfigSerializer, rawConfig) val config = configAndPluginsConfigJsonFormat.decodeFromString(PluginsConfigurationSerializer, rawConfig) as Config
assert(config.plugins.size == 1) assert(config.plugins.size == 1)
assert(config.plugins.first() is HelloPlugin) assert(config.plugins.first() is HelloPlugin)
assert((config.plugins.first() as HelloPlugin).parameter == "Example") assert((config.plugins.first() as HelloPlugin).parameter == "Example")
val redecoded = configJsonFormat.decodeFromString(ConfigSerializer, configJsonFormat.encodeToString(ConfigSerializer, config)) val redecoded = configAndPluginsConfigJsonFormat.decodeFromString(
PluginsConfigurationSerializer,
configAndPluginsConfigJsonFormat.encodeToString(PluginsConfigurationSerializer, config)
) as Config
assertEquals(config.database, redecoded.database) assertEquals(config.database, redecoded.database)
assertEquals(config.plugins, redecoded.plugins) assertEquals(config.plugins, redecoded.plugins)
assertEquals(config.botToken, redecoded.botToken) assertEquals(config.botToken, redecoded.botToken)

View File

@ -4,14 +4,14 @@ org.gradle.parallel=true
kotlin.js.generate.externals=true kotlin.js.generate.externals=true
kotlin.incremental=true kotlin.incremental=true
kotlin_version=1.4.32 kotlin_version=1.5.10
kotlin_coroutines_version=1.4.3 kotlin_coroutines_version=1.5.0
kotlin_serialisation_runtime_version=1.1.0 kotlin_serialisation_runtime_version=1.2.1
kotlin_exposed_version=0.31.1 kotlin_exposed_version=0.32.1
sdi_version=0.4.1 sdi_version=0.5.0
tgbotapi_version=0.34.1 tgbotapi_version=0.35.0
microutils_version=0.4.36 microutils_version=0.5.7
klassindex_version=4.1.0-rc.1 klassindex_version=4.1.0-rc.1
sqlite_version=3.34.0 sqlite_version=3.34.0
@ -19,4 +19,4 @@ sqlite_version=3.34.0
github_release_plugin_version=2.2.12 github_release_plugin_version=2.2.12
group=dev.inmo group=dev.inmo
version=0.2.1 version=0.3.0