Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import com.github.jasync.sql.db.interceptor.wrapPreparedStatementWithInterceptor
import com.github.jasync.sql.db.interceptor.wrapQueryWithInterceptors
import com.github.jasync.sql.db.util.FP
import com.github.jasync.sql.db.util.Failure
import com.github.jasync.sql.db.util.Try
import com.github.jasync.sql.db.util.complete
import com.github.jasync.sql.db.util.failed
import com.github.jasync.sql.db.util.flatMapAsync
import com.github.jasync.sql.db.util.flatMapTry
import com.github.jasync.sql.db.util.map
import com.github.jasync.sql.db.util.onCompleteAsync
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionException

abstract class ConcreteConnectionBase(
val configuration: Configuration
Expand All @@ -22,19 +24,60 @@ abstract class ConcreteConnectionBase(
override fun <A> inTransaction(f: (Connection) -> CompletableFuture<A>): CompletableFuture<A> {
return this.sendQuery("BEGIN").flatMapAsync(configuration.executionContext) {
val p = CompletableFuture<A>()
f(this).onCompleteAsync(configuration.executionContext) { ty1 ->
sendQuery(if (ty1.isFailure) "ROLLBACK" else "COMMIT").onCompleteAsync(configuration.executionContext) { ty2 ->
if (ty2.isFailure && ty1.isSuccess) {
p.failed((ty2 as Failure).exception)
} else {
p.complete(ty1)
}
val actionFuture = try {
f(this)
} catch (e: Throwable) {
FP.failed(e)
}
actionFuture.onCompleteAsync(configuration.executionContext) { ty1 ->
if (ty1.isFailure) {
rollbackAfterFailure((ty1 as Failure).exception, p)
} else {
commitAfterSuccess(ty1, p)
}
}
p
}
}

private fun <A> rollbackAfterFailure(rawException: Throwable, p: CompletableFuture<A>) {
val origException = unwrapCompletionException(rawException)
if (!this.isConnected() || this.isTimeout() || this.isQuerying()) {
if (this.isConnected() || this.isQuerying()) {
runCatching { this.disconnect() }.onFailure { disconnectEx ->
addSuppressedIfDifferent(origException, disconnectEx)
}
}
p.failed(origException)
return
}
try {
sendQuery("ROLLBACK").onCompleteAsync(configuration.executionContext) { ty2 ->
if (ty2.isFailure) {
addSuppressedIfDifferent(origException, (ty2 as Failure).exception)
}
p.failed(origException)
}
} catch (rollbackEx: Throwable) {
addSuppressedIfDifferent(origException, rollbackEx)
p.failed(origException)
}
}

private fun <A> commitAfterSuccess(result: Try<A>, p: CompletableFuture<A>) {
try {
sendQuery("COMMIT").onCompleteAsync(configuration.executionContext) { ty2 ->
if (ty2.isFailure) {
p.failed((ty2 as Failure).exception)
} else {
p.complete(result)
}
}
} catch (commitEx: Throwable) {
p.failed(commitEx)
}
}

protected fun releaseIfNeeded(
release: Boolean,
promise: CompletableFuture<QueryResult>,
Expand All @@ -44,11 +87,13 @@ abstract class ConcreteConnectionBase(
promise
} else {
promise.flatMapTry { queryResult, throwable ->
val released = this.releasePreparedStatement(query).map { queryResult }
if (throwable != null) {
if (this.isConnected() && !this.isTimeout() && !this.isQuerying()) {
runCatching { this.releasePreparedStatement(query) }
}
FP.failed(throwable)
} else {
released
this.releasePreparedStatement(query).map { queryResult }
}
}
}
Expand Down Expand Up @@ -81,3 +126,13 @@ abstract class ConcreteConnectionBase(

abstract override fun sendPreparedStatementDirect(params: PreparedStatementParams): CompletableFuture<QueryResult>
}

internal fun unwrapCompletionException(throwable: Throwable): Throwable =
(throwable as? CompletionException)?.cause ?: throwable

internal fun addSuppressedIfDifferent(primary: Throwable, secondary: Throwable) {
val unwrappedSecondary = unwrapCompletionException(secondary)
if (primary !== unwrappedSecondary) {
primary.addSuppressed(unwrappedSecondary)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ package com.github.jasync.sql.db
import com.github.jasync.sql.db.pool.ConnectionPool
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.future.await
import kotlinx.coroutines.future.future
import kotlinx.coroutines.withContext

val Connection.asSuspending get(): SuspendingConnection = SuspendingConnectionImpl(this)

Expand Down Expand Up @@ -309,8 +311,27 @@ class SuspendingConnectionImpl(val connection: Connection) : SuspendingConnectio
this.sendQuery("COMMIT")
return result
} catch (e: Throwable) {
this.sendQuery("ROLLBACK")
rollbackAfterFailure(e)
throw e
}
}

private suspend fun rollbackAfterFailure(e: Throwable) {
val concreteConnection = this.connection as? ConcreteConnection
if (concreteConnection != null && (!concreteConnection.isConnected() || concreteConnection.isTimeout() || concreteConnection.isQuerying())) {
if (concreteConnection.isConnected() || concreteConnection.isQuerying()) {
runCatching { concreteConnection.disconnect() }.onFailure { disconnectEx ->
addSuppressedIfDifferent(e, disconnectEx)
}
}
return
}
try {
withContext(NonCancellable) {
this@SuspendingConnectionImpl.sendQuery("ROLLBACK")
}
} catch (rollbackEx: Throwable) {
addSuppressedIfDifferent(e, rollbackEx)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,28 @@ class TimeoutSchedulerImpl(
}, this.toMillis(), TimeUnit.MILLISECONDS)
}

@JvmOverloads
fun <A> addTimeout(
promise: CompletableFuture<A>,
durationOption: Duration?,
connectionId: String
connectionId: String,
claimTimeout: (() -> Boolean)? = null
): ScheduledFuture<*>? {
return durationOption.nullableMap { duration ->
logger.trace { "adding timeout $duration for connectionId $connectionId" }
val scheduledFuture = duration.schedule {
if (promise.tryFailure(TimeoutException("Operation timeout after it took too long to return ($duration)"))) {
val timeoutException = TimeoutException("Operation timeout after it took too long to return ($duration)")
if (claimTimeout != null) {
if (!promise.isDone && claimTimeout()) {
logger.trace { "operation timeout for connectionId $connectionId" }
isTimeoutBool.set(true)
try {
onTimeout()
} finally {
promise.tryFailure(timeoutException)
}
}
} else if (promise.tryFailure(timeoutException)) {
logger.trace { "operation timeout for connectionId $connectionId" }
isTimeoutBool.set(true)
onTimeout()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import java.time.Duration
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
Expand Down Expand Up @@ -92,4 +93,52 @@ class TimeoutSchedulerSpec {
assertEquals(TIMEOUT_DID_NOT_PASS, promise.get())
assertEquals(false, timeoutScheduler.isTimeout())
}

@Test
fun `test claimTimeout runs isTimeout and onTimeout before completing promise`() {
val onTimeoutCalled = AtomicBoolean(false)
val observedTimeoutFlagOnCompletion = AtomicBoolean(false)
val observedCallbackOnCompletion = AtomicBoolean(false)
val timeoutScheduler = TimeoutSchedulerImpl(
ExecutorServiceUtils.CommonPool,
NettyUtils.DefaultEventLoopGroup
) {
onTimeoutCalled.set(true)
}
val promise = CompletableFuture<String>()
promise.whenComplete { _, _ ->
observedTimeoutFlagOnCompletion.set(timeoutScheduler.isTimeout())
observedCallbackOnCompletion.set(onTimeoutCalled.get())
}

timeoutScheduler.addTimeout(promise, Duration.ofMillis(50), "connectionId") { true }

try {
promise.get()
Assert.fail()
} catch (e: ExecutionException) {
assertTrue(e.cause is TimeoutException)
}
assertTrue(observedTimeoutFlagOnCompletion.get())
assertTrue(observedCallbackOnCompletion.get())
}

@Test
fun `test claimTimeout returning false skips timeout`() {
val onTimeoutCalled = AtomicBoolean(false)
val timeoutScheduler = TimeoutSchedulerImpl(
ExecutorServiceUtils.CommonPool,
NettyUtils.DefaultEventLoopGroup
) {
onTimeoutCalled.set(true)
}
val promise = CompletableFuture<String>()

timeoutScheduler.addTimeout(promise, Duration.ofMillis(50), "connectionId") { false }
Thread.sleep(200)

assertFalse(promise.isCompleted)
assertFalse(timeoutScheduler.isTimeout())
assertFalse(onTimeoutCalled.get())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ class MySQLConnection @JvmOverloads constructor(
private val createTimeoutSchedulerImpl =
TimeoutSchedulerImpl(configuration.executionContext, configuration.eventLoopGroup, this::onCreateTimeout)

@Volatile
private var channelClosed = false
private var reportErrorAfterChannelClosed = false

Expand All @@ -141,10 +142,11 @@ class MySQLConnection @JvmOverloads constructor(

fun close(): CompletableFuture<Connection> {
logger.trace { "close connection $connectionId" }
val wasConnected = this.connectionHandler.isConnected()
channelClosed = true
val exception = DatabaseException("Connection is being closed")
this.failQueryPromise(exception)
if (this.isConnected()) {
if (wasConnected) {
if (!this.disconnectionPromise.isCompleted) {
logger.trace { "send quit message $connectionId" }
this.connectionHandler.sendQuitMessage()
Expand All @@ -169,6 +171,8 @@ class MySQLConnection @JvmOverloads constructor(
}
}
}
} else {
this.disconnectionPromise.complete(this)
}

return this.disconnectionPromise
Expand Down Expand Up @@ -417,7 +421,9 @@ class MySQLConnection @JvmOverloads constructor(
this.setQueryPromise(promise)
this.checkStoredProcedureCall(query)
this.connectionHandler.sendQuery(query)
queryTimeoutSchedulerImpl.addTimeout(promise, configuration.queryTimeout, connectionId)
queryTimeoutSchedulerImpl.addTimeout(promise, configuration.queryTimeout, connectionId) {
claimQueryPromiseForTimeout(promise)
}
return promise
}

Expand Down Expand Up @@ -466,7 +472,7 @@ class MySQLConnection @JvmOverloads constructor(
disconnect()
}

override fun isConnected(): Boolean = this.connectionHandler.isConnected()
override fun isConnected(): Boolean = !channelClosed && this.connectionHandler.isConnected()

override fun hasRecentError(): Boolean = lastException != null

Expand All @@ -482,7 +488,9 @@ class MySQLConnection @JvmOverloads constructor(
this.setQueryPromise(promise)
this.checkStoredProcedureCall(params.query)
this.connectionHandler.sendPreparedStatement(params.query, params.values)
queryTimeoutSchedulerImpl.addTimeout(promise, configuration.queryTimeout, connectionId)
queryTimeoutSchedulerImpl.addTimeout(promise, configuration.queryTimeout, connectionId) {
claimQueryPromiseForTimeout(promise)
}
val closedPromise = this.releaseIfNeeded(params.release, promise, params.query)
return closedPromise
}
Expand Down Expand Up @@ -519,6 +527,17 @@ class MySQLConnection @JvmOverloads constructor(
}
}

private fun claimQueryPromiseForTimeout(promise: CompletableFuture<QueryResult>): Boolean {
val current = this.queryPromiseReference.get()
return if (current.isPresent && current.get() === promise && this.queryPromiseReference.compareAndSet(current, Optional.empty())) {
isStoredProcedureCall = false
lastResultSet = EMPTY_RESULT_SET
true
} else {
false
}
}

private fun clearQueryPromise(): Optional<CompletableFuture<QueryResult>> {
val currentPromise = this.queryPromiseReference.getAndSet(Optional.empty())
if (currentPromise.isPresent) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package com.github.jasync.sql.db.mysql

import com.github.jasync.sql.db.asSuspending
import com.github.jasync.sql.db.exceptions.ConnectionTimeoutedException
import com.github.jasync.sql.db.util.ExecutorServiceUtils
import com.github.jasync.sql.db.util.flatMapAsync
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.awaitility.kotlin.await
import org.awaitility.kotlin.matches
import org.awaitility.kotlin.untilCallTo
Expand Down Expand Up @@ -57,6 +62,33 @@ class QueryTimeoutSpec : ConnectionHelper() {
}
}

@Test
fun `inTransaction with short timeout surfaces TimeoutException and allows pool recovery`() {
val txTimeoutConfig = ContainerHelper.defaultConfiguration.copy(queryTimeout = Duration.ofMillis(150))
withConfigurablePool(txTimeoutConfig) { pool ->
verifyException(ExecutionException::class.java, TimeoutException::class.java) {
pool.inTransaction { conn ->
conn.sendQuery("select 1").flatMapAsync(ExecutorServiceUtils.CommonPool) {
conn.sendQuery("select sleep(10)")
}
}.get(10, TimeUnit.SECONDS)
}

assertThatThrownBy {
runBlocking {
pool.asSuspending.inTransaction { tx ->
tx.sendQuery("select 1")
tx.sendQuery("select sleep(10)")
}
}
}.isInstanceOf(TimeoutException::class.java)

await.untilCallTo { pool.inUseConnectionsCount } matches { it == 0 }
val rows = pool.sendQuery("select 1").get(10, TimeUnit.SECONDS).rows
assertThat(rows.size).isEqualTo(1)
}
}

private fun shortTimeoutConfiguration() =
ContainerHelper.defaultConfiguration.copy(queryTimeout = (Duration.ofMillis(10)))

Expand Down
Loading
Loading