2024-06-28 16:04:57 +05:30
|
|
|
{.push raises: [].}
|
2023-09-06 19:16:37 +02:00
|
|
|
|
2024-07-09 13:14:28 +02:00
|
|
|
import chronos, results
|
2024-05-16 22:29:11 +02:00
|
|
|
import ../../../common/databases/db_postgres, ../../../common/error_handling
|
2023-09-06 19:16:37 +02:00
|
|
|
|
|
|
|
## Simple query to validate that the postgres is working and attending requests
|
|
|
|
const HealthCheckQuery = "SELECT version();"
|
2023-10-30 15:16:49 +01:00
|
|
|
const CheckConnectivityInterval = 60.seconds
|
2023-09-06 19:16:37 +02:00
|
|
|
const MaxNumTrials = 20
|
|
|
|
const TrialInterval = 1.seconds
|
|
|
|
|
2024-03-16 00:08:47 +01:00
|
|
|
proc checkConnectivity*(
|
|
|
|
connPool: PgAsyncPool, onFatalErrorAction: OnFatalErrorHandler
|
|
|
|
) {.async.} =
|
2023-09-06 19:16:37 +02:00
|
|
|
while true:
|
2023-10-31 14:46:46 +01:00
|
|
|
(await connPool.pgQuery(HealthCheckQuery)).isOkOr:
|
2023-09-06 19:16:37 +02:00
|
|
|
## The connection failed once. Let's try reconnecting for a while.
|
|
|
|
## Notice that the 'exec' proc tries to establish a new connection.
|
|
|
|
|
|
|
|
block errorBlock:
|
|
|
|
## Force close all the opened connections. No need to close gracefully.
|
|
|
|
(await connPool.resetConnPool()).isOkOr:
|
2024-02-15 16:55:08 +05:30
|
|
|
onFatalErrorAction("checkConnectivity resetConnPool error: " & error)
|
2023-09-06 19:16:37 +02:00
|
|
|
|
|
|
|
var numTrial = 0
|
|
|
|
while numTrial < MaxNumTrials:
|
2023-10-31 14:46:46 +01:00
|
|
|
let res = await connPool.pgQuery(HealthCheckQuery)
|
2023-09-06 19:16:37 +02:00
|
|
|
if res.isOk():
|
|
|
|
## Connection resumed. Let's go back to the normal healthcheck.
|
|
|
|
break errorBlock
|
|
|
|
|
|
|
|
await sleepAsync(TrialInterval)
|
|
|
|
numTrial.inc()
|
|
|
|
|
|
|
|
## The connection couldn't be resumed. Let's inform the upper layers.
|
2024-02-15 16:55:08 +05:30
|
|
|
onFatalErrorAction("postgres health check error: " & error)
|
2023-09-06 19:16:37 +02:00
|
|
|
|
|
|
|
await sleepAsync(CheckConnectivityInterval)
|