Line data Source code
1 4 : (ns matchscore.realtime.nats-dispatcher
2 : (:require
3 : [cheshire.core :as json]
4 : [clojure.string :as str]
5 : [matchscore.realtime.core :as realtime]
6 : [matchscore.utils.otel :as otel]
7 : [taoensso.telemere :as t]))
8 :
9 :
10 4 : (defn- unwrap-payload
11 : "Debezium's outbox EventRouter + nats-jetstream sink wraps the routed
12 : `payload` JSONB column as {:schema {...} :payload \"<json-string>\"}. Parse
13 : the inner JSON string into a kebab-keyword map; pass already-flat maps
14 : through unchanged."
15 : [data]
16 9 : (let [inner (:payload data)] (if (string? inner) (json/parse-string inner true) data)))
17 :
18 :
19 4 : (defmulti dispatch-event
20 : "Dispatch a NATS event by aggregate type. `payload` is the unwrapped,
21 : parsed outbox payload map."
22 4 : (fn [aggregate-type _payload _ctx]
23 1 : aggregate-type))
24 :
25 :
26 12 : (defmethod dispatch-event :default
27 : [aggregate-type _payload _ctx]
28 96 : (t/log! :warn (str "Unhandled NATS aggregate type: " aggregate-type)))
29 :
30 :
31 12 : (defmethod dispatch-event "event"
32 : [_ payload {:keys [redis sente]}]
33 6 : (let [event-uuid (str (:uuid payload))
34 9 : event-type (if (contains? payload :state) "state_updated" (:event-type payload))
35 3 : ws-event (case event-type
36 3 : "state_updated" [:event/state-updated payload]
37 3 : [:event/updated payload])]
38 2 : (otel/add-attrs!
39 4 : {:event.uuid event-uuid
40 1 : :event.type event-type})
41 6 : (realtime/relay-to-event! sente redis event-uuid ws-event)))
42 :
43 :
44 12 : (defmethod dispatch-event "match_result"
45 : [_ payload {:keys [redis sente]}]
46 6 : (let [event-uuid (str (:event-uuid payload))
47 : ;; The outbox payload carries the result data but not the operation
48 : ;; type (that lives in the event_type column / a Debezium header that
49 : ;; the NATS sink drops). A deleted result has no :match-result.
50 6 : deleted? (not (contains? payload :match-result))
51 4 : event-type (if deleted? "deleted" "saved")
52 9 : ws-payload (assoc payload :match-uuid (str (:match-id payload)))
53 2 : ws-event (if deleted?
54 3 : [:match-result/deleted ws-payload]
55 3 : [:match-result/updated ws-payload])]
56 2 : (otel/add-attrs!
57 4 : {:event.uuid event-uuid
58 1 : :event.type event-type})
59 6 : (realtime/relay-to-event! sente redis event-uuid ws-event)))
60 :
61 :
62 4 : (defn dispatch!
63 : "Entry point called by the NATS consumer. Extracts aggregate type from subject
64 : and dispatches to the appropriate handler."
65 : [subject payload ctx]
66 7 : (let [aggregate-type (last (str/split subject #"\."))
67 3 : data (unwrap-payload payload)]
68 3 : (otel/with-span
69 4 : (str "nats.dispatch " aggregate-type)
70 5 : {:messaging.system "nats"
71 1 : :messaging.destination subject
72 1 : :nats.aggregate.type aggregate-type}
73 5 : (dispatch-event aggregate-type data ctx))))
|