racket / db

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

PostgreSQL: notification handler is not triggered immediately on push

Bogdanp opened this issue · comments

I set up a notification handler on a pg connection, then made that connection LISTEN on a channel and I expected the handler to get called whenever something got published on the channel. Instead, it only gets called the next time I perform an operation on that connection after something gets published.

Looking at the code for the PostgreSQL driver, I can see that there isn't a background thread waiting on incoming data from the connection, so async notifications are only processed during/after other interactions with the connection, which explains what I'm seeing.

I was able to get around this by relying on the undocumented async-message-evt method, by spawning a thread and continually syncing on that evt:

;; The DB library needs a little push to handle async events as soon as
;; they occur. If its `async-message-evt' isnt't being synced, then it
;; won't detect async messages until the next time it gets queried.
(define (make-async-message-waiter conn)
  (thread
   (lambda _
     (let loop ()
       (sync
        (handle-evt
         (send+ conn
                (get-base)
                (async-message-evt))
         (lambda _ (loop)))
        (handle-evt
         (thread-receive-evt)
         (lambda _ (void))))))))

This works, but it would be better if the connection itself did this. At the very least, this behavior and the workaround should be documented. I'd be happy to contribute either of those things; just let me know which you prefer!

Same issue. Thanks for the workaround!