https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
h

Hakon Grotte

05/15/2023, 8:33 AM
I'm experiencing a problem with ktor's testApplication in combination with Kotlin Exposed + HikariCP. It seems that the connections are not properly closed / leaking between my tests. The first hint of this is that each test logs a HikariCP with a new "id-suffix" in the name: First test:
HikariPool-1 - Start completed
HikariPool-2 - Start completed
...
HikariPool-1 - Shutdown completed
HikariPool-2 - Shutdown initiated
second test:
HikariPool-3 - Start completed
HikariPool-4 - Start completed
...
HikariPool-3 - Shutdown completed
HikariPool-4 - Shutdown initiated
etc, increasing linearly with the number of tests. I close the HikariCP during the
ApplicationStopPreparing
event in ktor (more info in thread). All the tests use the a custom
testApplication
method for reusable setup with the same mssql testcontainer. Usually test 'X' fails because it starts using a connection from a HikariPool of one of the previous tests (which is then closed), causing
java.sql.SQLException: HikariDataSource HikariDataSource (HikariPool-10) has been closed.
Is this expected behavior with the
testApplication
?
I am doing a similar approach as Ktor's CP + Exposed example to start the connection pool:
Database.connect(databaseFactory.hikariDataSource)
, and this approach for flyway migration:
val flyway = Flyway
      .configure()            
.dataSource(databaseFactory.flywayDataSource)
      .load()
flyway.migrate()
Both DS are of type
HikariDataSource
I close the connections with the following code:
environment.monitor.subscribe(ApplicationStopPreparing) {
databaseFactory.flywayDataSource.close()
databaseFactory.hikariDataSource.close()
}
s

spand

05/15/2023, 8:45 AM
A couple of notes from a working setup: • The increasing id only means that one is created for each test and arent reused. Its the same with standard executors and such. Your code shows that they are closed so how could they leak ? • We also close the
Database
object returned from
Database.connect
:
fun Database.asCloseable() = Closeable {
    TransactionManager.closeAndUnregister(this)
}
h

Hakon Grotte

05/15/2023, 9:48 AM
Thanks for the answer! I actually already tried a similar approach inside a method with Junit's
@AfterEach
when investigating this error:
TransactionManager.defaultDatabase?.let { TransactionManager.closeAndUnregister(it) }
. I like the approach with the Closeable interface you suggest: I invoked the database.close() inside the
ApplicationStopPreparing
lambda subscription. Unfortunately, the problem still persists:
java.lang.RuntimeException: database org.jetbrains.exposed.sql.Database@5d7badc6 don't have any transaction manager
	at org.jetbrains.exposed.sql.transactions.TransactionApiKt.getTransactionManager(TransactionApi.kt:157)
	at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.closeAsync(Suspended.kt:87)
	at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.access$closeAsync(Suspended.kt:1)
	at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$suspendedTransactionAsyncInternal$1.invokeSuspend(Suspended.kt:140)
	at _COROUTINE._BOUNDARY._(CoroutineDebugging.kt:46)
    at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$newSuspendedTransaction$2.invokeSuspend(Suspended.kt:59)
This database object
database org.jetbrains.exposed.sql.Database@5d7badc6
was created in a preceding test, so the problem is essentially the same as before.
s

spand

05/15/2023, 10:21 AM
Looks like you still have a coroutine running when close. Hard to say if it is exposed or you. (We dont use suspend transactions)
If its you then you need a better lifecycle handling throughout in your application
ie. wait for or cancel your coroutines or "background jobs"
h

Hakon Grotte

05/16/2023, 10:10 AM
Hi again! I tried looking for "bad lifecycle handling" in my application, but couldn't find any. Thus I tried to create a minimal reproducible example: https://github.com/graesj/ktor-exposed-hikaricp-test-failure Let me know if you see anything weird being done. cc. @Aleksei Tirman [JB] - do you want be to submit a Github issue?
s

spand

05/16/2023, 10:20 AM
Its probably not the issue but I think you should close the
Database
first.
h

Hakon Grotte

05/16/2023, 10:52 AM
yeah that might be, but I still manage to raise the test failure
a

Aleksei Tirman [JB]

05/18/2023, 10:09 AM
@Hakon Grotte all of the tests in the
DbConnectionWithKtorTest
class pass. How to reproduce the problem using your project?
h

Hakon Grotte

05/19/2023, 9:26 AM
Thanks for investigating! That's unfortunate, I'm assuming you tried to run it multiple times? I will try to modify the tests so they fail more often when I get back next week. Which Java runtime are you using? I'll try to replicate with it
a

Aleksei Tirman [JB]

05/19/2023, 9:29 AM
I use Correto JDK 11
h

Hakon Grotte

05/23/2023, 7:10 AM
Quick update: I was able to stop the tests failures entirely by explicitly passing the Database object to the
newSuspendedTransaction
. Unfortunately, I was unable to modify tests for increased probability of failure, but managed to reproduce locally with Correto JDK 11. @Aleksei Tirman [JB] sorry for taking your time. For those interested: The Exposed code location close to "picking the old Database object" seems to be somewhere around the red line in the image (the rest are usually null with newSuspendedTransaction). This code path can naturally be avoided by passing the Database object (the blue line). Following the red code line
TransactionManager.manager
brings me to `TransactionApi.kt`:
private val currentThreadManager = TransactionManagerThreadLocal()

val manager: TransactionManager
    get() = currentThreadManager.get()
, where the former class uses Java
ThreadLocal
to wrap the TransactionManager. Perhaps there is some interop issues between Java ThreadLocal and Kotlin Coroutines 🤷‍♂️
s

spand

05/23/2023, 7:22 AM
Not sure what your conclusion is but I cannot see how it should be possible to avoid passing the db explicitly. (We also do this).
h

Hakon Grotte

05/23/2023, 7:27 AM
Exposed stores all the Database objects upon
.connect()
and even has a
defaultDatabase
variable:
internal val currentDefaultDatabase = AtomicReference<Database>()

        var defaultDatabase: Database?
            @Synchronized get() = currentDefaultDatabase.get() ?: databases.firstOrNull()
            @Synchronized set(value) { currentDefaultDatabase.set(value) }

        private val databases = ConcurrentLinkedDeque<Database>()

        private val registeredDatabases = ConcurrentHashMap<Database, TransactionManager>()
, so that's how it's possible
s

spand

05/23/2023, 7:28 AM
Yes if you only ever need one for the entire jvm. That goes out the windows when you want to test your code.