Skip to content

Commit

Permalink
dbconn: use signal to coordinate resp from db instead of multiple awaits
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivansete-status committed Sep 28, 2024
1 parent 7331660 commit d758f2e
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions waku/common/databases/db_postgres/dbconn.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import
std/[times, strutils, asyncnet, os, sequtils],
results,
chronos,
chronos/threadsync,
metrics,
re,
chronicles
Expand Down Expand Up @@ -139,20 +140,28 @@ proc waitQueryToFinish(
## The 'rowCallback' param is != nil when the underlying query wants to retrieve results (SELECT.)
## For other queries, like "INSERT", 'rowCallback' should be nil.

debug "waitQueryToFinish", requestId, connName = db.connName
var dataAvailable = false
var triggered = false
var signal = ThreadSignalPtr.new().valueOr:
return err("error creating ThreadSignalPtr in waitQueryToFinish: " & $error)

proc onDataAvailable(udata: pointer) {.gcsafe, raises: [].} =
dataAvailable = true
if not triggered:
signal.fireSync().isOkOr:
error "error triggering coordination signal in dbconn", error = $error
triggered = true

let asyncFd = cast[asyncengine.AsyncFD](pqsocket(db.conn))

asyncengine.addReader2(asyncFd, onDataAvailable).isOkOr:
return err("failed to add event reader in waitQueryToFinish: " & $error)
defer:
asyncengine.removeReader2(asyncFd).isOkOr:
return err("failed to remove event reader in waitQueryToFinish: " & $error)
signal.close().isOkOr:
return err("error closing data available signal: " & $error)

debug "waitQueryToFinish", requestId, connName = db.connName
while not dataAvailable:
await sleepAsync(timer.milliseconds(1))
debug "waitQueryToFinish", requestId, connName = db.connName
await signal.wait()

## Now retrieve the result
while true:
Expand Down

0 comments on commit d758f2e

Please sign in to comment.