Line data Source code
1 4 : (ns matchscore.telegram.notifications-trigger
2 : (:require
3 : [matchscore.jobs.scheduler :as scheduler]
4 : [taoensso.carmine :as car]
5 : [taoensso.telemere :as t]))
6 :
7 :
8 8 : (def ^:private debounce-ttl-secs 4)
9 :
10 :
11 8 : (def ^:private debounce-delay-secs 3)
12 :
13 :
14 4 : (defn trigger-payment-refresh!
15 : "Coalesce payment and roster changes into one refresh of the event's live
16 : Telegram payment posts (who has paid, the closed version once all have).
17 : Same debounce as the participants post, on its own Redis key."
18 : [{:keys [redis goose]} event-uuid]
19 45 : (when (and redis goose event-uuid)
20 5 : (let [key (str "tg:payment-post:debounce:" event-uuid)
21 45 : won? (= "OK" (car/wcar redis (car/set key "1" :nx :ex debounce-ttl-secs)))]
22 3 : (when won?
23 3 : (scheduler/schedule-job
24 1 : goose
25 : `matchscore.jobs.telegram-payment-reminder/refresh-payment-posts-job
26 4 : {:delay-seconds debounce-delay-secs
27 2 : :args [event-uuid]})))))
28 :
29 :
30 4 : (defn trigger-now!
31 : "Schedule post-participants-job immediately.
32 : Use this when the caller has already finished a complete state transition
33 : and does not need the participant-change debounce window."
34 : [{:keys [goose]} event-uuid]
35 20 : (when (and goose event-uuid)
36 3 : (scheduler/schedule-job
37 1 : goose
38 : `matchscore.jobs.telegram-notifications/post-participants-job
39 4 : {:args [event-uuid]})
40 22 : (t/log! :debug (str "Scheduled immediate TG participant notification for event " event-uuid))))
41 :
42 :
43 4 : (defn trigger-debounced!
44 : "Coalesce rapid participant changes into a single Telegram notification.
45 : Uses an atomic Redis SET NX EX on tg:notify:debounce:{event-uuid} with TTL 4s.
46 : If we win the race, schedule post-participants-job with a 3s delay.
47 : If the key already exists, a job is already queued and will read the
48 : latest state when it fires — so we do nothing."
49 : [{:keys [redis goose]
50 : :as ctx}
51 : event-uuid]
52 : ;; The live payment post lists who still has to pay, so it follows the roster.
53 16 : (trigger-payment-refresh! ctx event-uuid)
54 45 : (when (and redis goose event-uuid)
55 5 : (let [key (str "tg:notify:debounce:" event-uuid)
56 45 : won? (= "OK" (car/wcar redis (car/set key "1" :nx :ex debounce-ttl-secs)))]
57 3 : (when won?
58 3 : (scheduler/schedule-job
59 1 : goose
60 : `matchscore.jobs.telegram-notifications/post-participants-job
61 4 : {:delay-seconds debounce-delay-secs
62 2 : :args [event-uuid]})
63 22 : (t/log! :debug (str "Scheduled TG participant notification for event " event-uuid))))))
|