Line data Source code
1 4 : (ns matchscore.telegram.event-lock
2 : (:require
3 : [matchscore.utils.db :as utils.db]
4 : [next.jdbc :as jdbc]))
5 :
6 :
7 8 : (def lock-busy ::lock-busy)
8 :
9 :
10 4 : (defn lock-busy?
11 : [exception]
12 7 : (= lock-busy (:type (ex-data exception))))
13 :
14 :
15 4 : (defn with-lock
16 : "Serialize sends, edits and terminal cleanup for an event across workers. Unlike
17 : the debounce lease, this lock cannot expire during a slow Telegram request."
18 : [pg event-id f]
19 16 : (jdbc/with-transaction
20 4 : [tx pg]
21 : ;; Fail for Goose to retry instead of occupying pool connections while waiting
22 : ;; behind another worker that needs those same connections to finish its work.
23 9 : (when-not
24 8 : (:locked
25 8 : (utils.db/unqualify-keys
26 8 : (jdbc/execute-one!
27 4 : tx
28 8 : ["SELECT pg_try_advisory_xact_lock(hashtextextended(?, 0)) AS locked"
29 16 : (str "telegram-event:" event-id)])))
30 1 : (throw
31 3 : (ex-info
32 : "Telegram event update is already running"
33 4 : {:type lock-busy
34 1 : :event-id event-id})))
35 8 : (f)))
|