Skip to content

Commit

Permalink
Fix rules engine
Browse files Browse the repository at this point in the history
  • Loading branch information
IRus committed Aug 19, 2023
1 parent 24eb4b4 commit 76d0ba6
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 121 deletions.
12 changes: 8 additions & 4 deletions core/src/main/kotlin/io/heapy/kotbot/bot/_kotbot.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ public data class Kotbot(
requestTimeout = 60_000
}
},
public val json: Json = Json {
ignoreUnknownKeys = true
},
public val json: Json = kotbotJson,
)

public val kotbotJson: Json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
explicitNulls = false
}

public suspend fun Kotbot.receiveUpdates(
timeout: Int = 50,
limit: Int = 100,
Expand Down Expand Up @@ -150,7 +154,7 @@ public suspend inline fun <Response> Kotbot.requestForJson(
}
}

private inline fun <reified T : Any> logger(): Logger =
internal inline fun <reified T : Any> logger(): Logger =
LoggerFactory.getLogger(T::class.java)

private val log = logger<Kotbot>()
34 changes: 27 additions & 7 deletions core/src/test/kotlin/io/heapy/kotbot/bot/Tests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,9 @@ class KotbotTest {
}

companion object {
private var offset: Int? = null
private val log = logger<KotbotTest>()

private val env = dotenv()

private val kotbot = Kotbot(
Expand All @@ -373,13 +376,26 @@ class KotbotTest {
@JvmStatic
@BeforeAll
fun setUp() = runBlocking {
log.info("Drain updates")

kotbot
.execute(
GetUpdates(
limit = 100,
timeout = 0,
)
)
.also {
log.info("Drained updates: {}", it.size)
}

kotbot.execute(
SendMessage(
chat_id = qaUserId.chatId,
text = """
*Kotbot smoke test started\!*
Job: [${env["CI_JOB_ID"]}](${env["CI_JOB_URL"]})
Github run [${env["GITHUB_RUN_ID"]}](${env["GITHUB_SERVER_URL"]}/${env["GITHUB_REPOSITORY"]}/actions/runs/${env["GITHUB_RUN_ID"]})
""".trimIndent(),
parse_mode = "MarkdownV2",
disable_web_page_preview = true,
Expand All @@ -396,10 +412,10 @@ class KotbotTest {
SendMessage(
chat_id = qaUserId.chatId,
text = """
*Kotbot smoke test finished\!*
Job: [${env.get("CI_JOB_ID")}](${env["CI_JOB_URL"]})
""".trimIndent(),
*Kotbot smoke test finished\!*
Github run [${env["GITHUB_RUN_ID"]}](${env["GITHUB_SERVER_URL"]}/${env["GITHUB_REPOSITORY"]}/actions/runs/${env["GITHUB_RUN_ID"]})
""".trimIndent(),
parse_mode = "MarkdownV2",
disable_web_page_preview = true
)
Expand All @@ -417,10 +433,14 @@ class KotbotTest {
kotbot
.execute(
GetUpdates(
offset = null,
offset = offset,
allowed_updates = listOf("callback_query")
)
)
.onEach {
offset = it.update_id + 1
println("Received update: ${it.update_id}")
}
.find {
(it.callback_query?.message?.message_id == message.message_id) &&
(it.callback_query?.from?.id == qaUserId)
Expand Down
26 changes: 26 additions & 0 deletions core/src/test/kotlin/io/heapy/kotbot/bot/methods/GetUpdatesTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package io.heapy.kotbot.bot.methods

import io.heapy.kotbot.bot.kotbotJson
import io.heapy.kotbot.bot.method.GetUpdates
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test

class GetUpdatesTest {
@Test
fun `test get updates method`() {
val request = kotbotJson.encodeToString(
GetUpdates.serializer(),
GetUpdates(
offset = 1,
limit = 100,
timeout = 0,
allowed_updates = listOf("message", "edited_channel_post", "callback_query"),
)
)

assertEquals(
"""{"offset":1,"limit":100,"timeout":0,"allowed_updates":["message","edited_channel_post","callback_query"]}""",
request
)
}
}
4 changes: 4 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
coroutines = "1.7.3"
flyway = "9.21.1"
hikari = "5.0.1"
jooq = "3.18.6"
jsoup = "1.16.1"
junit = "5.10.0"
kotlin = "1.9.0"
Expand All @@ -16,6 +17,9 @@ serialization = "1.5.1"
[libraries]
flyway = { module = "org.flywaydb:flyway-core", version.ref = "flyway" }

jooq-core = { module = "org.jooq:jooq", version.ref = "jooq" }
jooq-codegen = { module = "org.jooq:jooq-codegen", version.ref = "jooq" }

jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" }

junit = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" }
Expand Down
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ include(
"core",
"core-gen",
"tgkotbot",
"tgkotbot-dataops",
)
14 changes: 14 additions & 0 deletions tgkotbot-dataops/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
plugins {
alias(libs.plugins.kotlin.jvm)
}

repositories {
mavenCentral()
}

dependencies {
implementation(libs.jooq.codegen)
implementation(libs.flyway)
implementation(libs.postgresql)
implementation(libs.logback)
}
34 changes: 9 additions & 25 deletions tgkotbot/src/main/kotlin/io/heapy/kotbot/KotlinChatsBot.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import io.micrometer.core.instrument.Tags
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.toList

class KotlinChatsBot(
private val kotbot: Kotbot,
Expand Down Expand Up @@ -42,8 +41,8 @@ class KotlinChatsBot(
try {
val command = commands.find { command ->
command.name == update.name
&& command.context == update.context
&& command.access.isAllowed(update.access)
&& command.context == update.context
&& command.access.isAllowed(update.access)
} ?: return false

command.execute(kotbot, update)
Expand Down Expand Up @@ -72,25 +71,10 @@ class KotlinChatsBot(
get() = message?.text?.split(' ')?.getOrNull(0)

internal suspend fun executeRules(update: Update) {
rules
.map { rule -> rule to rule.validate(update) }
.flatMap { (rule, flow) ->
try {
flow.toList().also { actions ->
if (actions.isNotEmpty()) {
recordRuleTrigger(rule)
}
}
} catch (e: Exception) {
log.error("Exception in rule {}", rule, e)
recordRuleFailure(rule)
listOf()
}
}
.distinct()
.forEach {
kotbot.executeSafely(it)
}
val actions = Actions()
return rules.forEach { rule ->
rule.validate(kotbot, update, actions)
}
}

internal fun recordRuleTrigger(rule: Rule) {
Expand All @@ -114,9 +98,9 @@ class KotlinChatsBot(

private val log = logger<KotlinChatsBot>()

internal suspend fun <Response> Kotbot.executeSafely(
method: Method<Response>
): Response? {
internal suspend fun <Request : Method<Request, Result>, Result> Kotbot.executeSafely(
method: Request,
): Result? {
return try {
execute(method)
} catch (e: Exception) {
Expand Down
Loading

0 comments on commit 76d0ba6

Please sign in to comment.