Line data Source code
1 4 : (ns matchscore.db.postgres.template-automation
2 : (:require
3 : [next.jdbc :as jdbc]
4 : [next.jdbc.result-set :as rs])
5 : (:import
6 : (java.time Instant)))
7 :
8 :
9 4 : (defn instant
10 : [value]
11 16 : (cond (nil? value) nil
12 8 : (instance? Instant value) value
13 6 : (string? value) (Instant/parse value)
14 2 : :else (.toInstant value)))
15 :
16 :
17 4 : (defn lock-template!
18 : "Serialize settings, manual creation and automatic creation on the template row."
19 : [tx template-id]
20 18 : (jdbc/execute-one! tx ["SELECT uuid FROM templates WHERE uuid = ?::uuid FOR UPDATE" template-id]))
21 :
22 :
23 4 : (defn unfinished-event
24 : [ds template-id]
25 4 : (jdbc/execute-one!
26 2 : ds
27 4 : ["SELECT e.uuid, e.public_id,
28 : max(e.datetime_end) OVER ()
29 : + make_interval(mins => t.automatic_event_creation_delay_minutes) AS due_at
30 : FROM events e JOIN templates t ON t.uuid = e.template_id
31 : WHERE e.template_id = ?::uuid AND e.state NOT IN ('completed', 'cancelled')
32 : ORDER BY e.datetime_start LIMIT 1"
33 2 : template-id]
34 6 : {:builder-fn rs/as-unqualified-kebab-maps}))
35 :
36 :
37 4 : (defn request-for-template
38 : [ds template-id]
39 4 : (jdbc/execute-one!
40 2 : ds
41 6 : ["SELECT * FROM template_event_creation_requests WHERE template_id = ?::uuid" template-id]
42 6 : {:builder-fn rs/as-unqualified-kebab-maps}))
43 :
44 :
45 4 : (defn- expected-deadline
46 : [unfinished request]
47 12 : (let [expected (instant (:due-at unfinished))
48 21 : queued (when (contains? #{"pending" "retrying" "failed"} (:status request))
49 5 : (instant (:due-at request)))]
50 : ;; Legacy templates can still be waiting on an earlier event after a later
51 : ;; event has finished. Its saved deadline must not move backwards.
52 17 : (if (and queued (.isAfter queued expected)) queued expected)))
53 :
54 :
55 4 : (defn status
56 : [ds template-id enabled?]
57 8 : (if-not enabled?
58 3 : {:status "disabled"}
59 10 : (let [unfinished (unfinished-event ds template-id)
60 8 : request (request-for-template ds template-id)]
61 8 : (cond unfinished
62 12 : {:status "waiting_for_completion"
63 12 : :due-at (str (expected-deadline unfinished request))
64 6 : :current-event-id (:uuid unfinished)
65 6 : :current-event-public-id (:public-id unfinished)}
66 :
67 20 : (contains? #{"pending" "retrying" "failed" "exhausted"} (:status request))
68 8 : {:status (:status request)
69 15 : :due-at (some->
70 3 : (:due-at request)
71 1 : instant
72 1 : str)
73 3 : :attempts (:attempts request)
74 3 : :last-error (:last-error request)}
75 :
76 6 : :else {:status "waiting_for_first_event"}))))
|