Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ktor to 3.0.0 and refactor SSE handling #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ val h2_version: String by project
val postgres_version: String by project

plugins {
kotlin("jvm") version "1.9.10"
id("io.ktor.plugin") version "2.3.3"
id("org.jetbrains.kotlin.plugin.serialization") version "1.9.10"
kotlin("jvm") version "2.0.21"
id("io.ktor.plugin") version "3.0.0"
id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21"
}

group = "it.rattly"
Expand All @@ -24,11 +24,11 @@ application {

repositories {
mavenCentral()
maven { url = uri("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-js-wrappers") }
// maven { url = uri("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-js-wrappers") }
}

dependencies {
implementation("org.jetbrains:kotlin-css-jvm:1.0.0-pre.129-kotlin-1.4.20")
implementation("org.jetbrains.kotlin-wrappers:kotlin-css-jvm:1.0.0-pre.818")

implementation("io.ktor:ktor-server-core-jvm")
implementation("io.ktor:ktor-server-webjars-jvm")
Expand All @@ -38,10 +38,18 @@ dependencies {
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm")
implementation("io.ktor:ktor-server-html-builder-jvm")
implementation("io.ktor:ktor-server-cio-jvm")
implementation("io.ktor:ktor-server-sse")

implementation("org.webjars.npm:htmx.org:1.9.4")
implementation("org.webjars.npm:htmx.org:2.0.3")
implementation("org.postgresql:postgresql:$postgres_version")
implementation("com.h2database:h2:$h2_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("com.zaxxer:HikariCP:5.0.1")
implementation("com.zaxxer:HikariCP:6.0.0")
}

kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}

}
12 changes: 6 additions & 6 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
ktor_version=2.3.3
kotlin_version=1.9.10
logback_version=1.3.11
ktor_version=3.0.0
kotlin_version=2.0.21
logback_version=1.5.10
kotlin.code.style=official
exposed_version=0.41.1
h2_version=2.1.214
postgres_version=42.5.1
exposed_version=0.55.0
h2_version=2.3.232
postgres_version=42.7.4
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
10 changes: 5 additions & 5 deletions src/main/kotlin/it/rattly/Application.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.cio.*
import io.ktor.server.engine.*
import io.ktor.server.plugins.callloging.*
import io.ktor.server.plugins.calllogging.*
import io.ktor.server.plugins.compression.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
Expand All @@ -32,7 +32,7 @@ fun Application.module() {
fun Application.configureMisc() {
install(Webjars)

if (environment.developmentMode)
if (developmentMode)
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
Expand All @@ -46,9 +46,9 @@ fun Application.configureMisc() {
}

install(Compression) {
condition {
it.contentType != ContentType.Text.EventStream
}
condition {
it.contentType != ContentType.Text.EventStream
}

gzip {
priority = 1.0
Expand Down
48 changes: 13 additions & 35 deletions src/main/kotlin/it/rattly/plugins/SSE.kt
Original file line number Diff line number Diff line change
@@ -1,51 +1,29 @@
package it.rattly.plugins

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.utils.io.*
import kotlinx.coroutines.flow.Flow
import io.ktor.server.sse.*
import io.ktor.sse.*
import kotlinx.coroutines.flow.MutableSharedFlow

data class SseEvent(val data: String, val event: String? = null, val id: String? = null)

val sseFlow = MutableSharedFlow<SseEvent>()
val sseFlow = MutableSharedFlow<ServerSentEvent>()
suspend fun triggerSSE(author: String) {
sseFlow.emit(SseEvent(event = "newTodo", data = author))
sseFlow.emit(ServerSentEvent(data=author, event = "newTodo"))
}

fun Application.configureSSE() {
install(SSE)

routing {
get("/sse") {
val id = call.request.queryParameters["uid"] ?: throw BadRequestException("no id")
call.respondSse(sseFlow, id)
}
}
}

suspend fun ApplicationCall.respondSse(eventFlow: Flow<SseEvent>, id: String) {
response.cacheControl(CacheControl.NoCache(null))
respondBytesWriter(contentType = ContentType.Text.EventStream) {
eventFlow.collect { event ->
if (event.data == id)
return@collect

if (event.id != null) {
writeStringUtf8("id: ${event.id}\n")
sse("/sse") {
// not sure, how could we use the UID here
// probably, we could track the user sessions,
// but it's no use if we cannot track the user as SSE is not designed for this
val uid = call.request.queryParameters["uid"] ?: throw BadRequestException("no id")
sseFlow.collect {
send(it)
}

if (event.event != null) {
writeStringUtf8("event: ${event.event}\n")
}

for (dataLine in event.data.lines()) {
writeStringUtf8("data: $dataLine\n")
}
writeStringUtf8("\n")
flush()
}
}
}
}
11 changes: 3 additions & 8 deletions src/main/kotlin/it/rattly/plugins/db/Databases.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,14 @@ package it.rattly.plugins.db

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import it.rattly.plugins.db.todo.TodoService
import it.rattly.plugins.db.todo.todoRoutes
import kotlinx.coroutines.*
import java.sql.*
import java.sql.Connection


fun Application.configureDatabases() {
todoRoutes(TodoService(connectToPostgres(System.getenv("USE_EMBEDDED_DB").toBoolean())))
todoRoutes(TodoService(connectToPostgres()))
}

/**
Expand All @@ -38,7 +33,7 @@ fun Application.configureDatabases() {
* @return [Connection] that represent connection to the database. Please, don't forget to close this connection when
* your application shuts down by calling [Connection.close]
* */
fun connectToPostgres(embedded: Boolean): HikariDataSource {
fun connectToPostgres(embedded: Boolean = true): HikariDataSource {
Class.forName("org.postgresql.Driver")

val config = HikariConfig().apply {
Expand Down
5 changes: 2 additions & 3 deletions src/main/kotlin/it/rattly/plugins/db/todo/TodoService.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package it.rattly.plugins.db.todo

import com.zaxxer.hikari.HikariDataSource
import it.rattly.plugins.triggerSSE
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import org.intellij.lang.annotations.Language
import java.sql.Connection
import java.sql.Statement

@Serializable
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/it/rattly/views/layout/_layout.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ fun HTML.layout(e: BODY.() -> Unit) {
link(rel = "stylesheet", href = "https://cdn.simplecss.org/simple.min.css")
link(rel = "stylesheet", href = "/styles.css", type = "text/css")

val htmx = { e: String -> "webjars/htmx.org/1.9.4/$e" }
val htmx = { e: String -> "webjars/htmx.org/2.0.3/$e" }
script(src = htmx("dist/htmx.min.js")) {}
script(src = htmx("dist/ext/json-enc.js")) {}
script(src = htmx("dist/ext/sse.js")) {}
Expand Down
6 changes: 3 additions & 3 deletions src/main/kotlin/it/rattly/views/layout/styles.css.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ fun Application.configureStyles() = routing {
call.respondCss {
// padding left
rule(".pl") {
margin(left = 20.px)
marginLeft = 20.px
}
}
}
}

suspend inline fun ApplicationCall.respondCss(builder: CSSBuilder.() -> Unit) {
this.respondText(CSSBuilder().apply(builder).toString(), ContentType.Text.CSS)
suspend inline fun ApplicationCall.respondCss(builder: CssBuilder.() -> Unit) {
this.respondText(CssBuilder().apply(builder).toString(), ContentType.Text.CSS)
}
1 change: 0 additions & 1 deletion src/main/kotlin/it/rattly/views/todos/todo.list.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import it.rattly.views.layout.layout
import kotlinx.html.*
import kotlinx.html.InputType.*
import java.util.*
import java.util.concurrent.ThreadLocalRandom

fun HTML.listTodos() = layout {
val uid = UUID.randomUUID()
Expand Down