LCOV - code coverage report
Current view: top level - matchscore/application/template - automatic_events.clj Coverage Total Hit
Test: lcov.info Lines: 99.0 % 102 101
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.application.template.automatic-events
       2              :   (:require
       3              :    [matchscore.application.event.create :as event-create]
       4              :    [matchscore.db.postgres.template-automation :as automation-db]
       5              :    [matchscore.db.postgres.template-occurrence-exceptions :as occurrence-exception-db]
       6              :    [matchscore.domain.template.repository.postgres :as template-repo]
       7              :    [matchscore.utils.rrule :as rrule]
       8              :    [next.jdbc :as jdbc]
       9              :    [next.jdbc.result-set :as rs]
      10              :    [taoensso.telemere :as t])
      11              :   (:import
      12              :    (java.sql  Timestamp)
      13              :    (java.time Instant)))
      14              : 
      15              : 
      16            4 : (defn- next-start
      17              :   [tx template now]
      18           20 :   (when-not (and (seq (:rrule template)) (pos? (or (:duration template) 0)))
      19            7 :     (throw (ex-info "A recurring schedule and positive duration are required." {:permanent? true})))
      20            1 :   (let
      21              :     [existing
      22            2 :      (into
      23            1 :       #{}
      24            3 :       (map #(automation-db/instant (:datetime-start %)))
      25            2 :       (jdbc/execute!
      26            1 :        tx
      27            2 :        ["SELECT datetime_start FROM events
      28              :                          WHERE template_id = ?::uuid AND datetime_start >= ?"
      29            3 :         (:uuid template)
      30            3 :         (Timestamp/from now)]
      31            3 :        {:builder-fn rs/as-unqualified-kebab-maps}))
      32            7 :      skipped (occurrence-exception-db/starts-on-or-after tx (:uuid template) now)
      33            4 :      unavailable (into existing skipped)]
      34            2 :     (loop [cursor now]
      35           12 :       (when-let [start (rrule/next-occurrence (:rrule template) cursor)]
      36            7 :         (if (contains? unavailable start) (recur start) start)))))
      37              : 
      38              : 
      39            4 : (defn- event-data
      40              :   [template start]
      41            9 :   (assoc
      42            4 :    (update
      43            2 :     (select-keys
      44            1 :      template
      45           15 :      [:name
      46              :       :description
      47              :       :sport-code
      48              :       :activity-type-code
      49              :       :fee
      50              :       :fee-type
      51              :       :currency
      52              :       :timezone
      53              :       :language
      54              :       :duration
      55              :       :score-entry-mode
      56              :       :score-entry-default
      57              :       :club-ids
      58              :       :settings])
      59              :     :settings
      60            3 :     #(apply
      61            1 :       dissoc
      62              :       %
      63            9 :       [:telegram-match-notifications-enabled
      64              :        :telegram_match_notifications_enabled
      65              :        "telegram-match-notifications-enabled"
      66              :        "telegram_match_notifications_enabled"
      67              :        :payment-reminder
      68              :        :payment_reminder
      69              :        "payment-reminder"
      70              :        "payment_reminder"]))
      71            3 :    :template-id    (:uuid template)
      72            1 :    :datetime-start start
      73            4 :    :datetime-end   (.plusMillis ^Instant start (:duration template))
      74              :    :state          "active"
      75              :    :source         "matchscore"))
      76              : 
      77              : 
      78            4 : (defn- record-failure!
      79              :   [pg template-id request now exception]
      80            4 :   (jdbc/with-transaction
      81            1 :    [tx pg]
      82            4 :    (automation-db/lock-template! tx template-id)
      83            5 :    (let [current (automation-db/request-for-template tx template-id)]
      84              :      ;; A manual creation, disable, or newer terminal transition may already
      85              :      ;; have replaced this request while the failed transaction rolled back.
      86            2 :      (when
      87            4 :        (and
      88            1 :         (=
      89            8 :          (select-keys current [:source-event-id :due-at :attempts :updated-at])
      90            8 :          (select-keys request [:source-event-id :due-at :attempts :updated-at]))
      91            7 :         (contains? #{"pending" "retrying"} (:status current)))
      92            5 :        (let [attempts (inc (:attempts current))
      93           12 :              failed? (or (:permanent? (ex-data exception)) (>= attempts 10))
      94           10 :              seconds (min 3600 (* 30 (long (Math/pow 2 (dec attempts)))))
      95              :              message
      96            7 :              (if (:permanent? (ex-data exception))
      97            1 :                (.getMessage exception)
      98              :                "Unable to create the next event. Check template settings or create it manually.")]
      99            2 :          (jdbc/execute!
     100            1 :           tx
     101            2 :           ["UPDATE template_event_creation_requests
     102              :              SET status = ?, attempts = ?, last_error = ?, next_attempt_at = ?, updated_at = now()
     103              :              WHERE template_id = ?::uuid"
     104            4 :            (if failed? "failed" "retrying")
     105            1 :            attempts
     106            1 :            message
     107            4 :            (Timestamp/from (.plusSeconds ^Instant now seconds))
     108            1 :            template-id]))))))
     109              : 
     110              : 
     111            4 : (defn process-template!
     112              :  "Atomically claim a due request and create its successor. Safe across workers,
     113              :    restarts and concurrent manual creation. Returns the created event or nil."
     114              :  [{:keys [pg]
     115              :    :as   ctx}
     116              :   template-id
     117              :   ^Instant now]
     118            4 :  (let [attempt (atom nil)]
     119            2 :    (try
     120            1 :      (let
     121              :        [event
     122            4 :         (jdbc/with-transaction
     123            1 :          [tx pg]
     124            2 :          (when
     125            2 :            (jdbc/execute-one!
     126            1 :             tx
     127            3 :             ["SELECT uuid FROM templates WHERE uuid = ?::uuid FOR UPDATE SKIP LOCKED" template-id])
     128            5 :            (let [request  (automation-db/request-for-template tx template-id)
     129            2 :                  repo     (template-repo/make-repository
     130            6 :                            (jdbc/with-options tx {:builder-fn rs/as-kebab-maps}))
     131            5 :                  template (template-repo/find-by-id repo template-id nil)]
     132            2 :              (when
     133           12 :                (and
     134            3 :                 (:automatic-event-creation template)
     135            8 :                 (contains? #{"pending" "retrying"} (:status request))
     136            9 :                 (not (.isAfter (automation-db/instant (:next-attempt-at request)) now))
     137            4 :                 (nil? (automation-db/unfinished-event tx template-id)))
     138            4 :                (reset! attempt request)
     139           10 :                (if-let [start (next-start tx template now)]
     140              :                  ;; The event INSERT trigger fulfils the request; all class
     141              :                  ;; and participant inserts must commit with it.
     142            2 :                  (event-create/create-in-transaction!
     143            5 :                   (assoc ctx :pg tx)
     144            4 :                   (event-data template start)
     145            3 :                   (:created-by template))
     146            2 :                  (do
     147            2 :                    (jdbc/execute!
     148            1 :                     tx
     149            2 :                     ["UPDATE template_event_creation_requests
     150              :                            SET status = 'exhausted', last_error = NULL, updated_at = now()
     151              :                            WHERE template_id = ?::uuid"
     152            1 :                      template-id])
     153              :                    nil))))))]
     154            7 :        (when event (event-create/notify-created! ctx event))
     155            1 :        event)
     156              :      (catch Exception e
     157           92 :        (t/log!
     158              :         :error
     159            5 :         {:message     "Automatic event creation failed"
     160            1 :          :template-id template-id
     161            1 :          :exception   e})
     162           14 :        (when @attempt (record-failure! pg template-id @attempt now e))
     163              :        nil))))
     164              : 
     165              : 
     166            4 : (defn process-due!
     167              :  "Drain a bounded batch from PostgreSQL. Called immediately at startup and every
     168              :    five seconds; no delayed Redis job is required for durability."
     169            0 :  ([ctx] (process-due! ctx (Instant/now)))
     170              :  ([{:keys [pg]
     171              :     :as   ctx}
     172              :    now]
     173           25 :   (doseq
     174              :     [row
     175            2 :      (jdbc/execute!
     176            1 :       pg
     177            2 :       ["SELECT r.template_id FROM template_event_creation_requests r
     178              :                  JOIN templates t ON t.uuid = r.template_id
     179              :                  WHERE r.status IN ('pending', 'retrying') AND r.next_attempt_at <= ?
     180              :                    AND t.automatic_event_creation
     181              :                    AND NOT EXISTS (SELECT 1 FROM events e WHERE e.template_id = t.uuid
     182              :                      AND e.state NOT IN ('completed', 'cancelled'))
     183              :                  ORDER BY r.next_attempt_at LIMIT 25"
     184            3 :        (Timestamp/from now)]
     185            3 :       {:builder-fn rs/as-unqualified-kebab-maps})]
     186            7 :     (process-template! ctx (:template-id row) now))))
        

Generated by: LCOV version 2.0-1