Completed for a grade of four
This commit is contained in:
@@ -6,6 +6,7 @@ import com.mtusi.messenger.main.plugins.configureContentNegotiation
|
||||
import com.mtusi.messenger.main.plugins.configureCors
|
||||
import com.mtusi.messenger.main.plugins.configureDatabase
|
||||
import com.mtusi.messenger.main.plugins.configureDefaultHeaders
|
||||
import com.mtusi.messenger.main.plugins.configureGracefulShutdown
|
||||
import com.mtusi.messenger.main.plugins.configureInstanceId
|
||||
import com.mtusi.messenger.main.plugins.configureKoin
|
||||
import com.mtusi.messenger.main.plugins.configureRedis
|
||||
@@ -29,6 +30,7 @@ fun Application.module() {
|
||||
configureKoin()
|
||||
configureDatabase()
|
||||
configureRedis()
|
||||
configureGracefulShutdown()
|
||||
|
||||
configureContentNegotiation()
|
||||
configureDefaultHeaders()
|
||||
|
||||
+7
@@ -3,6 +3,7 @@ package com.mtusi.messenger.main.infrastructure.controllers.health
|
||||
import com.mtusi.messenger.main.extensions.respondError
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.health.responses.HealthResponse
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import com.mtusi.messenger.main.plugins.isDraining
|
||||
import com.mtusi.messenger.main.plugins.suspendedTransaction
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.application.log
|
||||
@@ -20,6 +21,12 @@ fun Routing.configureHealthRouting() = route("/health") {
|
||||
// PostgreSQL is the only dependency of the synchronous path: without it nothing can be served.
|
||||
get("ready") {
|
||||
|
||||
// SIGTERM received: leave the balancer's rotation while requests in flight are still being finished.
|
||||
if (call.application.isDraining) {
|
||||
call.respondError(ErrorCode.UNAVAILABLE, "shutting down")
|
||||
return@get
|
||||
}
|
||||
|
||||
val isDatabaseReachable = try {
|
||||
suspendedTransaction {
|
||||
exec("SELECT 1")
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.ApplicationStopPreparing
|
||||
import io.ktor.server.application.log
|
||||
import io.ktor.util.AttributeKey
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
private val DrainingKey = AttributeKey<AtomicBoolean>("Draining")
|
||||
|
||||
/**
|
||||
* True once the application received SIGTERM: /health/ready answers 503 from then on.
|
||||
*/
|
||||
val Application.isDraining: Boolean
|
||||
get() = attributes.getOrNull(DrainingKey)?.get() == true
|
||||
|
||||
/**
|
||||
* On SIGTERM the replica first fails its readiness check and keeps serving for `shutdown.drainDelayMs`, so the
|
||||
* balancer takes it out of rotation while it still answers. Only then Ktor closes the listening socket and waits
|
||||
* for requests in flight (`shutdownGracePeriod` / `shutdownTimeout`).
|
||||
*
|
||||
* ApplicationStopPreparing is raised synchronously before the engine closes its channels, so blocking here delays
|
||||
* the close itself.
|
||||
*/
|
||||
fun Application.configureGracefulShutdown() {
|
||||
|
||||
val drainDelayMs = environment.config.propertyOrNull("shutdown.drainDelayMs")?.getString()?.toLong() ?: 0
|
||||
val draining = AtomicBoolean(false)
|
||||
|
||||
attributes.put(DrainingKey, draining)
|
||||
|
||||
monitor.subscribe(ApplicationStopPreparing) {
|
||||
draining.set(true)
|
||||
log.info("Shutting down: readiness is 503, still serving for $drainDelayMs ms")
|
||||
Thread.sleep(drainDelayMs)
|
||||
log.info("Drain delay is over, closing the listening socket")
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,19 @@ ktor {
|
||||
host = ${?APP_HOST}
|
||||
port = 8080
|
||||
port = ${?APP_PORT}
|
||||
shutdownGracePeriod = 3000
|
||||
shutdownTimeout = 10000
|
||||
# After the drain (see `shutdown`): Netty waits for 1 s without new activity, at most 5 s in total.
|
||||
shutdownGracePeriod = 1000
|
||||
shutdownTimeout = 5000
|
||||
}
|
||||
}
|
||||
|
||||
shutdown {
|
||||
# Time between SIGTERM and closing the socket while /health/ready is already 503.
|
||||
# Behind HAProxy (check every 1 s, 2 failures) 3 s is enough to leave rotation; a single local process needs none.
|
||||
drainDelayMs = 0
|
||||
drainDelayMs = ${?SHUTDOWN_DRAIN_DELAY_MS}
|
||||
}
|
||||
|
||||
database {
|
||||
host = "localhost"
|
||||
host = ${?DB_HOST}
|
||||
|
||||
@@ -191,6 +191,7 @@ class DependencyFailureTest {
|
||||
@Test
|
||||
fun `without PostgreSQL requests fail with a bounded 503`() {
|
||||
val database = TestDatabase.create().also { it.start() }
|
||||
TestDatabase.awaitConnectable(database)
|
||||
|
||||
try {
|
||||
runApp(database = database, databaseConnectionTimeoutMs = 2000) { client ->
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.mtusi.messenger.main.support
|
||||
|
||||
import org.testcontainers.containers.PostgreSQLContainer
|
||||
import java.sql.DriverManager
|
||||
import java.sql.SQLException
|
||||
import org.testcontainers.utility.DockerImageName
|
||||
|
||||
/**
|
||||
@@ -20,6 +22,22 @@ object TestDatabase {
|
||||
/**
|
||||
* A separate, not yet started container for tests that stop the database.
|
||||
*/
|
||||
/**
|
||||
* Docker Desktop may refuse the first connections through a fresh port mapping for a moment after the container
|
||||
* reported ready; tests with a short pool timeout wait for a real connection first.
|
||||
*/
|
||||
fun awaitConnectable(container: PostgreSQLContainer<*>, timeoutMs: Long = 15000) {
|
||||
val deadline = System.currentTimeMillis() + timeoutMs
|
||||
while (true) {
|
||||
try {
|
||||
DriverManager.getConnection(container.jdbcUrl, container.username, container.password).use { return }
|
||||
} catch (e: SQLException) {
|
||||
if (System.currentTimeMillis() > deadline) throw e
|
||||
Thread.sleep(200)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun create(): PostgreSQLContainer<*> {
|
||||
return PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres"))
|
||||
.withDatabaseName(NAME)
|
||||
|
||||
Reference in New Issue
Block a user