Line data Source code
1 4 : (ns matchscore.search.meilisearch
2 : "Thin Meilisearch client over java.net.http (the backend has no HTTP client
3 : library). Only the backend talks to Meilisearch; the frontend keeps using GraphQL.
4 :
5 : A client is a map {:url :api-key :index-prefix :timeout-ms :http}. Index names
6 : passed to the functions below are logical (\"players\"); `index-uid` adds the
7 : environment prefix, so branch databases sharing one Meilisearch don't collide."
8 : (:require
9 : [cheshire.core :as json]
10 : [clojure.string :as str]
11 : [matchscore.utils.otel :as otel])
12 : (:import
13 : (java.net URI)
14 : (java.net.http HttpClient HttpRequest HttpRequest$BodyPublishers HttpResponse$BodyHandlers)
15 : (java.time Duration)))
16 :
17 :
18 8 : (def default-search-timeout-ms 500)
19 :
20 :
21 8 : (def ^:private admin-timeout-ms 30000)
22 :
23 :
24 4 : (defn make-client
25 : "Client for `config` ({:url :api-key :index-prefix :timeout-ms}), or nil when no
26 : URL is configured (search then stays on Postgres)."
27 : [{:keys [url api-key index-prefix timeout-ms]}]
28 11 : (when-not (str/blank? url)
29 22 : {:url (str/replace url #"/+$" "")
30 12 : :api-key (when-not (str/blank? api-key) api-key)
31 11 : :index-prefix (or index-prefix "")
32 10 : :timeout-ms (or timeout-ms default-search-timeout-ms)
33 2 : :http (->
34 4 : (HttpClient/newBuilder)
35 8 : (.connectTimeout (Duration/ofSeconds 2))
36 : .build)}))
37 :
38 :
39 4 : (defn index-uid
40 : "Meilisearch uid of the logical index `index-name` in this environment."
41 : [client index-name]
42 12 : (str (:index-prefix client) index-name))
43 :
44 :
45 4 : (defn- request
46 : "Sends a request and returns {:status :body} with the body parsed as keyword JSON.
47 : Throws ex-info for statuses >= 400 except the ones in `ok-statuses`."
48 : [{:keys [url api-key ^HttpClient http]}
49 : method
50 : path
51 : body
52 : &
53 : {:keys [timeout-ms ok-statuses]
54 : :or {timeout-ms admin-timeout-ms
55 : ok-statuses #{}}}]
56 4 : (let [builder (->
57 8 : (HttpRequest/newBuilder (URI/create (str url path)))
58 4 : (.timeout (Duration/ofMillis timeout-ms))
59 : (.header "Content-Type" "application/json"))
60 9 : builder (if api-key (.header builder "Authorization" (str "Bearer " api-key)) builder)
61 4 : publisher (if (some? body)
62 5 : (HttpRequest$BodyPublishers/ofString (json/generate-string body))
63 2 : (HttpRequest$BodyPublishers/noBody))
64 8 : req (.build (.method builder (str/upper-case (name method)) publisher))
65 4 : resp (.send http req (HttpResponse$BodyHandlers/ofString))
66 1 : status (.statusCode resp)
67 1 : raw (.body resp)
68 9 : parsed (when-not (str/blank? raw) (json/parse-string raw true))]
69 15 : (when (and (>= status 400) (not (contains? ok-statuses status)))
70 1 : (throw
71 2 : (ex-info
72 15 : (str "Meilisearch " (name method) " " path " → " status ": " (:message parsed raw))
73 6 : {:type ::http-error
74 1 : :status status
75 3 : :code (:code parsed)
76 1 : :body parsed})))
77 4 : {:status status
78 1 : :body parsed}))
79 :
80 :
81 4 : (defn healthy?
82 : [client]
83 1 : (try
84 15 : (= "available" (get-in (request client :get "/health" nil :timeout-ms 2000) [:body :status]))
85 : (catch Exception _ false)))
86 :
87 :
88 4 : (defn get-index
89 : "Index info, or nil when the index doesn't exist."
90 : [client uid]
91 13 : (let [{:keys [status body]} (request client :get (str "/indexes/" uid) nil :ok-statuses #{404})]
92 7 : (when-not (= 404 status) body)))
93 :
94 :
95 4 : (defn wait-for-task!
96 : "Waits until task `task-uid` is done; returns the task. Throws when it failed or
97 : didn't finish within `timeout-ms`."
98 5 : ([client task-uid] (wait-for-task! client task-uid 120000))
99 : ([client task-uid timeout-ms]
100 5 : (let [deadline (+ (System/currentTimeMillis) timeout-ms)]
101 2 : (loop [pause 20]
102 12 : (let [task (:body (request client :get (str "/tasks/" task-uid) nil))]
103 5 : (case (:status task)
104 1 : "succeeded" task
105 0 : ("failed" "canceled") (throw
106 0 : (ex-info
107 0 : (str
108 0 : "Meilisearch task " task-uid
109 0 : " " (:status task)
110 0 : ": " (get-in task [:error :message]))
111 0 : {:type ::task-failed
112 0 : :task task}))
113 5 : (if (> (System/currentTimeMillis) deadline)
114 0 : (throw
115 0 : (ex-info
116 0 : (str "Meilisearch task " task-uid " still " (:status task))
117 0 : {:type ::task-timeout
118 0 : :task task}))
119 6 : (do (Thread/sleep (long pause)) (recur (min 500 (* 2 pause)))))))))))
120 :
121 :
122 4 : (defn- run-task!
123 : [client method path body]
124 14 : (wait-for-task! client (get-in (request client method path body) [:body :taskUid])))
125 :
126 :
127 4 : (defn create-index!
128 : [client uid]
129 4 : (run-task!
130 1 : client
131 : :post
132 : "/indexes"
133 5 : {:uid uid
134 : :primaryKey "id"}))
135 :
136 :
137 4 : (defn delete-index!
138 : "Deletes the index; nothing happens when it doesn't exist."
139 : [client uid]
140 15 : (when (get-index client uid) (run-task! client :delete (str "/indexes/" uid) nil)))
141 :
142 :
143 4 : (defn update-settings!
144 : [client uid settings]
145 10 : (run-task! client :patch (str "/indexes/" uid "/settings") settings))
146 :
147 :
148 4 : (defn add-documents!
149 : "Adds or replaces documents in batches of `batch-size`."
150 6 : ([client uid documents] (add-documents! client uid documents 5000))
151 : ([client uid documents batch-size]
152 29 : (doseq [batch (partition-all batch-size documents)]
153 12 : (run-task! client :post (str "/indexes/" uid "/documents?primaryKey=id") (vec batch)))))
154 :
155 :
156 4 : (defn swap-indexes!
157 : "Atomically swaps the contents of two existing indexes."
158 : [client uid-a uid-b]
159 11 : (run-task! client :post "/swap-indexes" [{:indexes [uid-a uid-b]}]))
160 :
161 :
162 4 : (defn search
163 : "Searches index `index-name` (logical name) with a Meilisearch search body; returns
164 : the response body ({:hits ...}). Throws on errors and timeouts."
165 : [client index-name body]
166 5 : (let [uid (index-uid client index-name)]
167 4 : (otel/with-span
168 : "meilisearch.search"
169 4 : {:db.system "meilisearch"
170 1 : :meilisearch.index uid}
171 2 : (:body
172 4 : (request
173 1 : client
174 : :post
175 5 : (str "/indexes/" uid "/search")
176 1 : body
177 : :timeout-ms
178 3 : (:timeout-ms client))))))
179 :
180 :
181 4 : (defn multi-search
182 : "Federated search over several logical indexes. `queries` are search bodies with
183 : an :index (logical name) instead of :indexUid; returns the response body."
184 : [client federation queries]
185 0 : (otel/with-span
186 : "meilisearch.multi-search"
187 0 : {:db.system "meilisearch"}
188 0 : (:body
189 0 : (request
190 0 : client
191 : :post
192 0 : "/multi-search" {:federation federation
193 0 : :queries (mapv
194 0 : (fn
195 : [{:keys [index]
196 : :as q}]
197 0 : (->
198 0 : q
199 0 : (dissoc :index)
200 0 : (assoc :indexUid (index-uid client index))))
201 0 : queries)}
202 0 : :timeout-ms (:timeout-ms client)))))
|