Skip to content
Closed
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
52 changes: 52 additions & 0 deletions postgis-jasync/src/test/java/PostgisQueryTimeoutSpec.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.github.aysnc.sql.db.integration

import com.github.jasync.sql.db.exceptions.ConnectionStillRunningQueryException
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
import org.junit.Test
import java.time.Duration
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

class PostgisQueryTimeoutSpec : DatabaseTestHelper() {

@Test
fun `query timeout inside transaction should clear running query before rollback on same connection`() {
val timeoutConfiguration = conf.copy(queryTimeout = Duration.ofSeconds(1))

withHandler(timeoutConfiguration) { connection ->
executeQuery(
connection,
"""
CREATE OR REPLACE FUNCTION slow_jasync_function() RETURNS void AS $$ BEGIN PERFORM pg_sleep(5); END; $$ LANGUAGE plpgsql
""".trimIndent()
)
executeQuery(connection, "BEGIN")

// The query times out after one second; TimeoutScheduler fails the pending promise first and then
// triggers onQueryTimeout()/disconnect(), so this must surface as ExecutionException(TimeoutException).
val future = connection.sendQuery("SELECT slow_jasync_function()")
assertThatThrownBy {
future.get(10, TimeUnit.SECONDS)
}
.isInstanceOf(ExecutionException::class.java)
.hasCauseInstanceOf(TimeoutException::class.java)

// Wait for the timeout-driven disconnect to actually close the physical channel.
await.atMost(10, TimeUnit.SECONDS).untilCallTo { connection.isConnected() } matches { it == false }

assertThat(connection.isQuerying()).isFalse()

// Simulate the pool reusing the same physical connection for cleanup. The connection is already
// closed, so IllegalStateException is acceptable; what must never happen is that the stale query
// promise turns the cleanup failure into ConnectionStillRunningQueryException.
assertThatThrownBy {
connection.sendQuery("ROLLBACK")
}.isNotInstanceOf(ConnectionStillRunningQueryException::class.java)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import com.github.jasync.sql.db.ResultSet
import com.github.jasync.sql.db.column.ColumnDecoderRegistry
import com.github.jasync.sql.db.column.ColumnEncoderRegistry
import com.github.jasync.sql.db.exceptions.ConnectionStillRunningQueryException
import com.github.jasync.sql.db.exceptions.DatabaseException
import com.github.jasync.sql.db.exceptions.InsufficientParametersException
import com.github.jasync.sql.db.general.MutableResultSet
import com.github.jasync.sql.db.interceptor.PreparedStatementParams
Expand Down Expand Up @@ -143,8 +144,14 @@ class PostgreSQLConnection @JvmOverloads constructor(
}
}

override fun disconnect(): CompletableFuture<Connection> =
this.connectionHandler.disconnect().toCompletableFuture().mapAsync(configuration.executionContext) { c -> this }
override fun disconnect(): CompletableFuture<Connection> {
failQueryPromise(DatabaseException("Connection is being closed"))
return this.connectionHandler.disconnect().toCompletableFuture().mapAsync(configuration.executionContext) { c -> this }
}

override fun onDisconnect() {
failQueryPromise(DatabaseException("Connection closed"))
}

private fun onQueryTimeout() {
disconnect()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ interface PostgreSQLConnectionDelegate {
fun onError(throwable: Throwable)
fun onParameterStatus(message: ParameterStatusMessage)
fun onReadyForQuery()
fun onDisconnect() {}
fun onRowDescription(message: RowDescriptionMessage)
fun onNotificationResponse(message: NotificationResponse)
}
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ class PostgreSQLConnectionHandler(
@Suppress("RedundantUnitReturnType")
override fun channelInactive(ctx: ChannelHandlerContext) {
logger.info("Connection disconnected - {}", ctx.channel().remoteAddress())
connectionDelegate.onDisconnect()
}

override fun handlerAdded(ctx: ChannelHandlerContext) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.github.aysnc.sql.db.postgresql

import com.github.jasync.sql.db.Configuration
import com.github.jasync.sql.db.postgresql.codec.PostgreSQLConnectionDelegate
import com.github.jasync.sql.db.postgresql.codec.PostgreSQLConnectionHandler
import com.github.jasync.sql.db.postgresql.column.PostgreSQLColumnEncoderRegistry
import io.mockk.mockk
import io.mockk.verify
import io.netty.channel.ChannelHandlerContext
import org.junit.Test

class PostgreSQLConnectionHandlerTest {

@Test
fun `channelInactive should notify delegate about disconnect`() {
val delegate = mockk<PostgreSQLConnectionDelegate>(relaxed = true)
val configuration = Configuration("test")
val handler = PostgreSQLConnectionHandler(
configuration,
PostgreSQLColumnEncoderRegistry.Instance,
delegate,
configuration.eventLoopGroup,
configuration.executionContext
)
val ctx = mockk<ChannelHandlerContext>(relaxed = true)

handler.channelInactive(ctx)

verify { delegate.onDisconnect() }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.github.aysnc.sql.db.postgresql

import com.github.jasync.sql.db.QueryResult
import com.github.jasync.sql.db.postgresql.PostgreSQLConnection
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.Optional
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicReference

class PostgreSQLConnectionLifecycleTest {

@Test
fun `disconnect should fail and clear a pending query promise`() {
val connection = PostgreSQLConnection()
val pendingQuery = CompletableFuture<QueryResult>()
connection.setPendingQueryPromise(pendingQuery)

connection.disconnect()

assertThat(connection.isQuerying()).isFalse()
assertThat(pendingQuery.isCompletedExceptionally).isTrue()
}

@Test
fun `query timeout path should fail and clear a pending query promise`() {
val connection = PostgreSQLConnection()
val pendingQuery = CompletableFuture<QueryResult>()
connection.setPendingQueryPromise(pendingQuery)

invokeOnQueryTimeout(connection)

assertThat(connection.isQuerying()).isFalse()
assertThat(pendingQuery.isCompletedExceptionally).isTrue()
}

@Test
fun `channel disconnect should fail and clear a pending query promise`() {
val connection = PostgreSQLConnection()
val pendingQuery = CompletableFuture<QueryResult>()
connection.setPendingQueryPromise(pendingQuery)

connection.onDisconnect()

assertThat(connection.isQuerying()).isFalse()
assertThat(pendingQuery.isCompletedExceptionally).isTrue()
}

private fun PostgreSQLConnection.setPendingQueryPromise(promise: CompletableFuture<QueryResult>) {
val field = PostgreSQLConnection::class.java.getDeclaredField("queryPromiseReference")
field.isAccessible = true
@Suppress("UNCHECKED_CAST")
val reference = field.get(this) as AtomicReference<Optional<CompletableFuture<QueryResult>>>
reference.set(Optional.of(promise))
}

private fun invokeOnQueryTimeout(connection: PostgreSQLConnection) {
val method = PostgreSQLConnection::class.java.getDeclaredMethod("onQueryTimeout")
method.isAccessible = true
method.invoke(connection)
}
}