Line data Source code
1 4 : (ns matchscore.jobs.telegram-match-notifications
2 : (:require
3 : [clojure.string :as str]
4 : [matchscore.db.postgres.telegram-match-notifications :as notification-db]
5 : [matchscore.jobs.scheduler :as scheduler]
6 : [matchscore.telegram.event-lock :as event-lock]
7 : [matchscore.telegram.formatting :as formatting]
8 : [matchscore.telegram.match-notifications :as match-notifications]
9 : [matchscore.telegram.messages :as messages]
10 : [taoensso.carmine :as car]
11 : [taoensso.telemere :as t]
12 : [telegrambot-lib.core :as tbot]))
13 :
14 :
15 8 : (def ^:private sync-lease-seconds 600)
16 :
17 :
18 8 : (def ^:private follow-up-delay-seconds 2)
19 :
20 :
21 8 : (defn- sync-pending-key [event-id] (str "tg:match-notifications:sync:pending:" event-id))
22 :
23 :
24 8 : (defn- sync-dirty-key [event-id] (str "tg:match-notifications:sync:dirty:" event-id))
25 :
26 :
27 4 : (defn- acquire-event-sync!
28 : [redis event-id token]
29 2 : (=
30 : 1
31 35 : (car/wcar
32 1 : redis
33 3 : (car/eval
34 5 : (str
35 : "local acquired=redis.call('set',KEYS[1],ARGV[1],'NX','EX',ARGV[2]);"
36 : "if acquired then redis.call('del',KEYS[2]); return 1; "
37 : "else redis.call('set',KEYS[2],'1','EX',ARGV[2]); return 0; end")
38 : 2
39 3 : (sync-pending-key event-id)
40 3 : (sync-dirty-key event-id)
41 1 : token
42 1 : sync-lease-seconds))))
43 :
44 :
45 4 : (defn- refresh-event-sync!
46 : [redis event-id token]
47 2 : (=
48 : 1
49 35 : (car/wcar
50 1 : redis
51 3 : (car/eval
52 4 : (str
53 : "if redis.call('get',KEYS[1])==ARGV[1] then "
54 : "redis.call('expire',KEYS[1],ARGV[2]); return 1; else return 0; end")
55 : 1
56 3 : (sync-pending-key event-id)
57 1 : token
58 1 : sync-lease-seconds))))
59 :
60 :
61 4 : (defn- release-event-sync!
62 : [redis event-id token]
63 35 : (car/wcar
64 1 : redis
65 3 : (car/eval
66 4 : (str
67 : "if redis.call('get',KEYS[1])==ARGV[1] then "
68 : "return redis.call('del',KEYS[1]); else return 0; end")
69 : 1
70 3 : (sync-pending-key event-id)
71 1 : token)))
72 :
73 :
74 4 : (defn- enqueue-event-sync!
75 6 : ([goose event-id token] (enqueue-event-sync! goose event-id token nil))
76 : ([goose event-id token delay-seconds]
77 3 : (scheduler/schedule-job
78 1 : goose
79 : `sync-event-job
80 16 : (cond-> {:args [(str event-id) token]} delay-seconds (assoc :delay-seconds delay-seconds)))))
81 :
82 :
83 4 : (defn schedule-event-sync!
84 : [goose event-id]
85 26 : (when (and goose event-id)
86 1 : (try
87 8 : (if-let [redis (:redis goose)]
88 4 : (let [event-id (str event-id)
89 4 : token (str (random-uuid))]
90 7 : (when (acquire-event-sync! redis event-id token)
91 1 : (try
92 5 : (enqueue-event-sync! goose event-id token)
93 7 : (catch Exception e (release-event-sync! redis event-id token) (throw e)))))
94 : ;; Preserve scheduling for tests and callers that intentionally provide
95 : ;; only Goose's client options.
96 0 : (scheduler/schedule-job goose `sync-event-job {:args [(str event-id)]}))
97 : (catch Exception e
98 : ;; The periodic recovery scan will rediscover the event. Do not turn an
99 : ;; already-committed organizer mutation into a failed HTTP response.
100 92 : (t/log!
101 : :error
102 5 : {:message "Failed to enqueue Telegram match notification sync"
103 3 : :event-id (str event-id)
104 1 : :exception e})))))
105 :
106 :
107 4 : (defn schedule-result-sync!
108 : [goose match-id actor-user-id operation]
109 6 : (when (and goose match-id)
110 0 : (try
111 0 : (scheduler/schedule-job
112 0 : goose
113 : `sync-result-job
114 0 : {:args [{:match-uuid (str match-id)
115 0 : :actor-user-id (some->
116 0 : actor-user-id
117 0 : str)
118 0 : :operation (name operation)}]})
119 : (catch Exception e
120 : ;; Canonical cards are repaired by discovery. A result-specific alert is
121 : ;; also repaired from its persisted pending row.
122 0 : (t/log!
123 : :error
124 0 : {:message "Failed to enqueue Telegram match result notification"
125 0 : :match-id (str match-id)
126 0 : :operation (name operation)
127 0 : :exception e})))))
128 :
129 :
130 4 : (defn- recipient-locale
131 : [event recipient]
132 2 : (formatting/normalize-locale
133 8 : (or
134 6 : (get-in recipient [:user-settings :language])
135 6 : (get-in recipient [:user-settings "language"])
136 1 : (:language event))))
137 :
138 :
139 4 : (defn- match-recipients
140 : [match]
141 12 : [{:participant-id (:home-participant-id match)
142 3 : :user-id (:home-user-id match)
143 3 : :telegram-id (:home-telegram-id match)
144 3 : :bot-access-status (:home-bot-access-status match)
145 3 : :user-settings (:home-user-settings match)
146 3 : :opponent-name (:away-name match)
147 3 : :opponent-user-id (:away-user-id match)}
148 11 : {:participant-id (:away-participant-id match)
149 3 : :user-id (:away-user-id match)
150 3 : :telegram-id (:away-telegram-id match)
151 3 : :bot-access-status (:away-bot-access-status match)
152 3 : :user-settings (:away-user-settings match)
153 3 : :opponent-name (:home-name match)
154 3 : :opponent-user-id (:home-user-id match)}])
155 :
156 :
157 7 : (defn- current-card-revision [match] (match-notifications/card-revision match))
158 :
159 :
160 7 : (defn- current-alert-revision [match] (match-notifications/result-revision match))
161 :
162 :
163 4 : (defn record-result-alerts!
164 : "Persists the recipients for a committed result mutation before it is queued.
165 : The event recovery scan can therefore deliver the alert even if enqueueing or
166 : a worker fails."
167 : [{:keys [pg]} match-id actor-user-id]
168 2 : (try
169 15 : (when-let [match (notification-db/match-context pg match-id)]
170 12 : (when-let [event (notification-db/event-context pg (:event-id match))]
171 5 : (when (notification-db/effective-enabled? event)
172 7 : (let [recipients (filterv :user-id (match-recipients match))
173 13 : actor-is-player? (some #(= (str actor-user-id) (str (:user-id %))) recipients)
174 2 : recipients (if actor-is-player?
175 3 : (filterv
176 10 : #(not= (str actor-user-id) (str (:user-id %)))
177 1 : recipients)
178 1 : recipients)
179 3 : revision (current-alert-revision match)]
180 26 : (doseq [recipient recipients]
181 2 : (notification-db/ensure-alert!
182 1 : pg
183 9 : {:event-id (:uuid event)
184 3 : :match-id (:uuid match)
185 3 : :recipient-user-id (:user-id recipient)
186 1 : :result-revision revision
187 8 : :status (if (match-notifications/user-enabled? (:user-settings recipient))
188 : "pending"
189 : "opted_out")}))))))
190 : (catch Exception e
191 : ;; The mutation has already committed. Canonical cards still self-heal via
192 : ;; event discovery, so log without failing the user's score submission.
193 92 : (t/log!
194 : :error
195 5 : {:message "Failed to persist Telegram match result notification recipients"
196 3 : :match-id (str match-id)
197 1 : :exception e}))))
198 :
199 :
200 4 : (defn- blocked-error?
201 : [exception]
202 4 : (let [{:keys [error_code description]} (ex-data exception)
203 7 : description (str/lower-case (or description ""))]
204 7 : (or
205 3 : (= 403 error_code)
206 : (and
207 3 : (= 400 error_code)
208 0 : (some
209 0 : #(str/includes? description %)
210 0 : ["bot was blocked" "chat not found" "user is deactivated"])))))
211 :
212 :
213 4 : (defn- sanitized-error
214 : [exception]
215 4 : (let [{:keys [error_code description]} (ex-data exception)]
216 13 : (str (or error_code "transport") ": " (or description (.getMessage exception)))))
217 :
218 :
219 4 : (defn- card-data
220 : [event match recipient status]
221 12 : {:event-id (:uuid event)
222 3 : :match-id (:uuid match)
223 3 : :recipient-user-id (:user-id recipient)
224 3 : :participant-id (:participant-id recipient)
225 3 : :telegram-id (:telegram-id recipient)
226 3 : :pairing-revision (match-notifications/pairing-revision match)
227 3 : :result-revision (current-card-revision match)
228 1 : :status status})
229 :
230 :
231 4 : (defn- existing-message-id
232 : [existing recipient]
233 2 : (when
234 1 : (=
235 8 : (some->
236 3 : (:telegram-id existing)
237 1 : str)
238 8 : (some->
239 3 : (:telegram-id recipient)
240 1 : str))
241 3 : (:message-id existing)))
242 :
243 :
244 4 : (defn- record-card-error!
245 : [ds event match recipient existing exception]
246 0 : (let [blocked? (blocked-error? exception)
247 0 : status (if blocked? "unreachable" "retrying")
248 0 : data (assoc (card-data event match recipient status)
249 0 : :message-id (existing-message-id existing recipient)
250 0 : :last-error (sanitized-error exception))]
251 0 : (notification-db/save-card! ds data)
252 0 : (when blocked? (notification-db/mark-user-denied! ds (:user-id recipient)))
253 0 : (t/log!
254 0 : (if blocked? :info :warn)
255 0 : {:message "Telegram match card delivery failed"
256 0 : :match-id (:uuid match)
257 0 : :user-id (:user-id recipient)
258 0 : :retryable? (not blocked?)
259 0 : :error (:last-error data)})))
260 :
261 :
262 4 : (defn- send-card!
263 : [{:keys [pg telegram-bot config]} event match recipient existing]
264 5 : (let [locale (recipient-locale event recipient)
265 2 : content (match-notifications/card
266 1 : locale
267 6 : (get-in config [:telegram :bot-username])
268 6 : (assoc match
269 3 : :opponent-name (:opponent-name recipient)
270 3 : :opponent-user-id (:opponent-user-id recipient)
271 3 : :recipient-participant-id (:participant-id recipient)))
272 4 : params (match-notifications/telegram-params recipient content)
273 4 : existing-id (existing-message-id existing recipient)
274 4 : edited? (and
275 1 : existing-id
276 0 : (= :ok (messages/edit! telegram-bot (assoc params :message_id existing-id))))
277 2 : message-id (if edited?
278 0 : existing-id
279 6 : (let [response (messages/request! tbot/send-message telegram-bot params)
280 6 : id (get-in response [:result :message_id])]
281 3 : (when-not id (throw (ex-info "Telegram returned no message id" {})))
282 1 : id))]
283 2 : (notification-db/save-card!
284 1 : pg
285 11 : (assoc (card-data event match recipient "sent")
286 1 : :message-id message-id
287 : :last-error nil))))
288 :
289 :
290 4 : (defn- sync-card!
291 : [{:keys [pg telegram-bot]
292 : :as system}
293 : event
294 : match
295 : recipient
296 : allow-completed?]
297 12 : (when (and (:user-id recipient) (:participant-id recipient))
298 4 : (let [pair-revision (match-notifications/pairing-revision match)
299 3 : result-revision (current-card-revision match)
300 9 : existing (notification-db/card pg (:uuid match) (:user-id recipient))
301 5 : same-pair? (= pair-revision (:pairing-revision existing))
302 5 : same-result? (= result-revision (:result-revision existing))
303 1 : same-chat? (=
304 8 : (some->
305 3 : (:telegram-id existing)
306 1 : str)
307 8 : (some->
308 3 : (:telegram-id recipient)
309 1 : str))
310 4 : message-id (existing-message-id existing recipient)
311 5 : user-enabled? (match-notifications/user-enabled? (:user-settings recipient))
312 8 : reachable? (and
313 1 : telegram-bot
314 3 : (:telegram-id recipient)
315 3 : (= "confirmed" (:bot-access-status recipient)))]
316 7 : (cond
317 : ;; Record every revision seen while opted out. This prevents replay when the
318 : ;; user opts back in, while allowing the next material change to notify them.
319 9 : (and (:telegram-id recipient) (not user-enabled?))
320 0 : (notification-db/save-card!
321 0 : pg
322 0 : (assoc (card-data event match recipient "opted_out") :message-id message-id))
323 :
324 : ;; First scan after re-enabling only acknowledges what was missed.
325 18 : (and existing (= "opted_out" (:status existing)) same-pair? same-result?)
326 2 : (notification-db/save-card!
327 1 : pg
328 11 : (assoc (card-data event match recipient "suppressed")
329 1 : :message-id message-id
330 : :last-error nil))
331 :
332 3 : (not reachable?)
333 0 : (when (:telegram-id recipient)
334 0 : (notification-db/save-card!
335 0 : pg
336 0 : (assoc (card-data event match recipient "unreachable") :message-id message-id)))
337 :
338 : ;; A periodic discovery scan must not create old cards for matches that
339 : ;; were already complete before the feature was enabled.
340 8 : (and (nil? existing) (:result match) (not allow-completed?)) nil
341 :
342 14 : (and
343 1 : existing
344 1 : same-chat?
345 1 : same-pair?
346 1 : same-result?
347 7 : (contains? #{"sent" "suppressed"} (:status existing)))
348 : nil
349 :
350 : :else
351 1 : (try
352 2 : (notification-db/save-card!
353 1 : pg
354 10 : (assoc (card-data event match recipient "pending") :message-id message-id))
355 7 : (send-card! system event match recipient existing)
356 0 : (catch Exception e (record-card-error! pg event match recipient existing e)))))))
357 :
358 :
359 4 : (defn- stale-card?
360 : [matches card]
361 8 : (let [match (get matches (str (:match-id card)))]
362 4 : (or
363 4 : (nil? match)
364 1 : (not
365 2 : (contains?
366 9 : #{(some->
367 3 : (:home-user-id match)
368 1 : str)
369 8 : (some->
370 3 : (:away-user-id match)
371 1 : str)}
372 8 : (some->
373 3 : (:recipient-user-id card)
374 1 : str))))))
375 :
376 :
377 4 : (defn- retire-stale-card!
378 : [{:keys [pg telegram-bot]} event card]
379 7 : (when-not (= "superseded" (:status card))
380 6 : (let [enabled? (match-notifications/user-enabled? (:user-settings card))]
381 14 : (if-not (and enabled? telegram-bot (:message-id card))
382 0 : (notification-db/update-card!
383 0 : pg
384 0 : (:uuid card)
385 0 : {:message-id (:message-id card)
386 0 : :pairing-revision (:pairing-revision card)
387 0 : :result-revision (:result-revision card)
388 : :status "superseded"
389 : :last-error nil})
390 1 : (try
391 3 : (let [result (messages/edit!
392 1 : telegram-bot
393 3 : (assoc
394 2 : (match-notifications/telegram-params
395 5 : {:telegram-id (:telegram-id card)}
396 2 : (match-notifications/stale-card
397 4 : (recipient-locale event card)
398 5 : {:event-name (:name event)}))
399 3 : :message_id (:message-id card)))]
400 0 : (notification-db/update-card!
401 0 : pg
402 0 : (:uuid card)
403 0 : {:message-id (:message-id card)
404 0 : :pairing-revision (:pairing-revision card)
405 0 : :result-revision (:result-revision card)
406 : :status "superseded"
407 0 : :last-error (when (= :missing result) "Telegram message no longer exists")}))
408 : (catch Exception e
409 4 : (let [blocked? (blocked-error? e)
410 3 : error (sanitized-error e)]
411 2 : (notification-db/update-card!
412 1 : pg
413 3 : (:uuid card)
414 9 : {:message-id (:message-id card)
415 3 : :pairing-revision (:pairing-revision card)
416 3 : :result-revision (:result-revision card)
417 3 : :status (if blocked? "superseded" "retrying")
418 1 : :last-error error})
419 2 : (when blocked? (notification-db/mark-user-denied! pg (:recipient-user-id card)))
420 91 : (t/log!
421 3 : (if blocked? :info :warn)
422 6 : {:message "Failed to retire stale Telegram match card"
423 3 : :card-id (:uuid card)
424 3 : :retryable? (not blocked?)
425 1 : :error error}))))))))
426 :
427 :
428 4 : (defn- alert-recipient
429 : [match user-id]
430 0 : (first
431 0 : (filter
432 0 : #(=
433 0 : (str user-id)
434 0 : (some->
435 0 : (:user-id %)
436 0 : str))
437 0 : (match-recipients match))))
438 :
439 :
440 4 : (defn- send-result-alert!
441 : [{:keys [pg telegram-bot config]} event match recipient revision deleted?]
442 11 : (let [existing (notification-db/alert pg (:uuid match) (:user-id recipient) revision)
443 4 : alert (or
444 1 : existing
445 1 : (notification-db/ensure-alert!
446 1 : pg
447 10 : {:event-id (:uuid event)
448 3 : :match-id (:uuid match)
449 3 : :recipient-user-id (:user-id recipient)
450 1 : :result-revision revision
451 : :status "pending"}))]
452 17 : (when (and alert (not (contains? #{"sent" "opted_out" "superseded"} (:status alert))))
453 3 : (cond
454 7 : (not (match-notifications/user-enabled? (:user-settings recipient)))
455 0 : (notification-db/update-alert!
456 0 : pg
457 0 : (:uuid alert)
458 0 : {:status "opted_out"
459 : :message-id nil
460 : :last-error nil})
461 :
462 2 : (not
463 15 : (and telegram-bot (:telegram-id recipient) (= "confirmed" (:bot-access-status recipient))))
464 0 : (notification-db/update-alert!
465 0 : pg
466 0 : (:uuid alert)
467 0 : {:status "unreachable"
468 : :message-id nil
469 : :last-error nil})
470 :
471 : :else
472 1 : (try
473 3 : (let [content (match-notifications/result-alert
474 4 : (recipient-locale event recipient)
475 6 : (get-in config [:telegram :bot-username])
476 6 : (assoc match
477 3 : :opponent-name (:opponent-name recipient)
478 3 : :opponent-user-id (:opponent-user-id recipient)
479 3 : :recipient-participant-id (:participant-id recipient))
480 1 : deleted?)
481 2 : response (messages/request!
482 1 : tbot/send-message
483 1 : telegram-bot
484 4 : (match-notifications/telegram-params recipient content))]
485 2 : (notification-db/update-alert!
486 1 : pg
487 3 : (:uuid alert)
488 6 : {:status "sent"
489 6 : :message-id (get-in response [:result :message_id])
490 : :last-error nil}))
491 : (catch Exception e
492 0 : (let [blocked? (blocked-error? e)]
493 0 : (notification-db/update-alert!
494 0 : pg
495 0 : (:uuid alert)
496 0 : {:status (if blocked? "unreachable" "retrying")
497 : :message-id nil
498 0 : :last-error (sanitized-error e)})
499 0 : (when blocked? (notification-db/mark-user-denied! pg (:user-id recipient)))
500 0 : (t/log!
501 0 : (if blocked? :info :warn)
502 0 : {:message "Telegram match result alert failed"
503 0 : :match-id (:uuid match)
504 0 : :user-id (:user-id recipient)
505 0 : :retryable? (not blocked?)}))))))))
506 :
507 :
508 4 : (defn- retry-alerts!
509 : [system event matches]
510 24 : (doseq [alert (notification-db/retryable-alerts (:pg system) (:uuid event))]
511 0 : (if-let [match (get matches (str (:match-id alert)))]
512 0 : (let [revision (current-alert-revision match)
513 0 : recipient (alert-recipient match (:recipient-user-id alert))]
514 0 : (if (and recipient (= revision (:result-revision alert)))
515 0 : (send-result-alert! system event match recipient revision (nil? (:result match)))
516 0 : (notification-db/update-alert!
517 0 : (:pg system)
518 0 : (:uuid alert)
519 0 : {:status "superseded"
520 : :message-id nil
521 : :last-error nil})))
522 0 : (notification-db/update-alert!
523 0 : (:pg system)
524 0 : (:uuid alert)
525 0 : {:status "superseded"
526 : :message-id nil
527 : :last-error nil}))))
528 :
529 :
530 4 : (defn- reconcile-event!
531 : [system event-id]
532 2 : (event-lock/with-lock
533 3 : (:pg system)
534 1 : event-id
535 1 : (fn []
536 12 : (when-let [event (notification-db/event-context (:pg system) event-id)]
537 5 : (when (notification-db/effective-enabled? event)
538 7 : (let [matches (notification-db/event-matches (:pg system) event-id)
539 13 : by-id (into {} (map (juxt (comp str :uuid) identity) matches))
540 6 : cards (notification-db/event-cards (:pg system) event-id)]
541 50 : (doseq [match matches
542 3 : recipient (match-recipients match)]
543 7 : (sync-card! system event match recipient false))
544 17 : (doseq [card cards :when (stale-card? by-id card)] (retire-stale-card! system event card))
545 5 : (retry-alerts! system event by-id)
546 4 : {:status :success
547 2 : :matches (count matches)}))))))
548 :
549 :
550 4 : (defn- finish-event-sync!
551 : [redis goose event-id token]
552 1 : (let [dirty?
553 2 : (=
554 : 1
555 35 : (car/wcar
556 1 : redis
557 3 : (car/eval
558 6 : (str
559 : "if redis.call('get',KEYS[1])~=ARGV[1] then return -1; end;"
560 : "if redis.call('exists',KEYS[2])==1 then "
561 : "redis.call('del',KEYS[2]); redis.call('expire',KEYS[1],ARGV[2]); return 1; "
562 : "else redis.call('del',KEYS[1]); return 0; end")
563 : 2
564 3 : (sync-pending-key event-id)
565 3 : (sync-dirty-key event-id)
566 1 : token
567 1 : sync-lease-seconds)))]
568 3 : (when dirty?
569 1 : (try
570 6 : (enqueue-event-sync! goose event-id token follow-up-delay-seconds)
571 : (catch Exception e
572 : ;; Keep the lease and restore the dirty marker so Goose's retry of the
573 : ;; current job can safely make another attempt.
574 0 : (car/wcar redis (car/set (sync-dirty-key event-id) "1" :ex sync-lease-seconds))
575 0 : (throw e))))))
576 :
577 :
578 4 : (defn sync-event-job
579 : "Discovers all currently resolved pairings for an enabled active event and
580 : reconciles the players' canonical Telegram cards. Concurrent requests for the
581 : same event are coalesced into at most one follow-up run. Safe to run repeatedly."
582 4 : ([system event-id] (reconcile-event! system event-id))
583 : ([system event-id token]
584 2 : (let [{:keys [redis goose]} system]
585 16 : (if (and redis token (not (refresh-event-sync! redis event-id token)))
586 3 : {:status :superseded}
587 0 : (let [result (reconcile-event! system event-id)]
588 0 : (when (and redis goose token) (finish-event-sync! redis goose event-id token))
589 0 : result)))))
590 :
591 :
592 4 : (defn sync-result-job
593 : "Updates both canonical cards after a committed result mutation and sends one
594 : short, deduplicated alert to the other player (or both for an organizer edit)."
595 : [system {:keys [match-uuid actor-user-id operation]}]
596 12 : (when-let [initial (notification-db/match-context (:pg system) match-uuid)]
597 4 : (let [event-id (:event-id initial)]
598 2 : (event-lock/with-lock
599 3 : (:pg system)
600 1 : event-id
601 1 : (fn []
602 7 : (let [event (notification-db/event-context (:pg system) event-id)
603 6 : match (notification-db/match-context (:pg system) match-uuid)]
604 13 : (when (and event match (notification-db/effective-enabled? event))
605 7 : (let [recipients (filterv :user-id (match-recipients match))
606 13 : actor-is-player? (some #(= (str actor-user-id) (str (:user-id %))) recipients)
607 2 : alert-recipients (if actor-is-player?
608 3 : (filterv
609 10 : #(not= (str actor-user-id) (str (:user-id %)))
610 1 : recipients)
611 0 : recipients)
612 3 : revision (current-alert-revision match)
613 3 : deleted? (= "delete" operation)]
614 33 : (doseq [recipient recipients] (sync-card! system event match recipient true))
615 26 : (doseq [recipient alert-recipients]
616 8 : (send-result-alert! system event match recipient revision deleted?))
617 4 : {:status :success
618 2 : :notified (count alert-recipients)}))))))))
|