LCOV - code coverage report
Current view: top level - matchscore/search - indexer.clj Coverage Total Hit
Test: lcov.info Lines: 96.9 % 96 93
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.search.indexer
       2              :   "Keeps the Meilisearch indexes in step with Postgres.
       3              : 
       4              :   Every index is derived: its documents are rebuilt from Postgres in full and
       5              :   swapped in atomically (build `<uid>_next`, swap with `<uid>`, drop the old
       6              :   copy). A rebuild runs when
       7              :   - the index doesn't exist (first start, Meilisearch volume lost),
       8              :   - any of its source tables was written since the last build, or
       9              :   - the last build is older than `max-age-seconds` (self-heal).
      10              : 
      11              :   Writes are detected with the per-table counters in pg_stat_user_tables
      12              :   (inserted + updated + deleted rows), so every writer counts: backend, scrapers
      13              :   (which write straight to Postgres and re-import by delete + insert) and manual
      14              :   SQL. The counters reset when Postgres restarts or stats are reset; that only
      15              :   causes one extra rebuild. Dev instances have no Debezium, so the outbox can't
      16              :   be used for this.
      17              : 
      18              :   Builds are serialised across backend replicas with a Redis lock; the last
      19              :   fingerprint and build time live in Redis too."
      20              :   (:require
      21              :    [clojure.string :as str]
      22              :    [matchscore.search.events :as events]
      23              :    [matchscore.search.meilisearch :as meili]
      24              :    [matchscore.search.players :as players]
      25              :    [next.jdbc :as jdbc]
      26              :    [next.jdbc.result-set :as rs]
      27              :    [taoensso.carmine :as car]
      28              :    [taoensso.telemere :as t]))
      29              : 
      30              : 
      31            4 : (def indexes
      32              :   "Index definitions: logical name, source tables, settings, document builder (fn [ds])."
      33           28 :   [{:name      players/index-name
      34            4 :     :tables    players/watched-tables
      35            4 :     :settings  players/settings
      36            4 :     :documents players/documents}
      37           24 :    {:name      events/index-name
      38            4 :     :tables    events/watched-tables
      39            4 :     :settings  events/settings
      40            4 :     :documents events/documents}])
      41              : 
      42              : 
      43           24 : (def max-age-seconds (* 24 60 60))
      44              : 
      45              : 
      46            8 : (def ^:private lock-seconds 600)
      47              : 
      48              : 
      49            4 : (defn- redis-key
      50              :   [client kind index-name]
      51            9 :   (str "search:" kind ":" (meili/index-uid client index-name)))
      52              : 
      53              : 
      54            4 : (defn table-fingerprint
      55              :  "String that changes whenever a row of `tables` is inserted, updated or deleted, or
      56              :   the statistics of the current database are reset (a reset zeroes the counters, so
      57              :   later writes could otherwise reproduce an earlier fingerprint)."
      58              :  [ds tables]
      59            2 :  (let
      60              :    [counters
      61            4 :     (->>
      62            4 :       (jdbc/execute!
      63            2 :        ds
      64            4 :        ["SELECT relname, (n_tup_ins + n_tup_upd + n_tup_del) AS writes
      65              :                        FROM pg_stat_user_tables
      66              :                       WHERE schemaname = 'public' AND relname = ANY(?)
      67              :                       ORDER BY relname"
      68            8 :         (into-array String tables)]
      69            6 :        {:builder-fn rs/as-unqualified-maps})
      70            4 :       (map
      71            2 :        (fn [{:keys [relname writes]}]
      72           10 :         (str relname "=" writes)))
      73            2 :       (str/join ","))
      74            4 :     reset (:stats_reset
      75            4 :            (jdbc/execute-one!
      76            2 :             ds
      77            4 :             ["SELECT stats_reset FROM pg_stat_database WHERE datname = current_database()"]
      78            6 :             {:builder-fn rs/as-unqualified-maps}))]
      79            6 :    (str
      80            2 :     counters
      81              :     ";reset="
      82           16 :     (some->
      83            2 :       reset
      84            1 :       str))))
      85              : 
      86              : 
      87            4 : (defn rebuild-needed?
      88              :  "Pure decision: rebuild when the index is missing, the fingerprint changed, or the
      89              :   last build is older than `max-age-seconds`."
      90              :  [{:keys [index-exists? fingerprint last-fingerprint last-built-at now]}]
      91           25 :  (or
      92            6 :   (not index-exists?)
      93            8 :   (not= fingerprint last-fingerprint)
      94            8 :   (nil? last-built-at)
      95            8 :   (> (- now last-built-at) max-age-seconds)))
      96              : 
      97              : 
      98            4 : (defn rebuild!
      99              :  "Rebuilds `index` from Postgres and swaps it in. Returns the document count."
     100              :  [ds client {:keys [name settings documents]}]
     101            5 :  (let [uid  (meili/index-uid client name)
     102            4 :        next (str uid "_next")
     103            3 :        docs (documents ds)]
     104            4 :    (meili/delete-index! client next)
     105            4 :    (meili/create-index! client next)
     106            5 :    (meili/update-settings! client next settings)
     107            5 :    (meili/add-documents! client next docs)
     108           11 :    (when-not (meili/get-index client uid) (meili/create-index! client uid))
     109            5 :    (meili/swap-indexes! client uid next)
     110            4 :    (meili/delete-index! client next)
     111            2 :    (count docs)))
     112              : 
     113              : 
     114            4 : (defn sync-index!
     115              :  "Rebuilds `index` when needed. Returns :rebuilt, :up-to-date or :locked."
     116              :  [ds
     117              :   redis
     118              :   client
     119              :   {:keys [name tables]
     120              :    :as   index}
     121              :   &
     122              :   {:keys [force?]}]
     123            5 :  (let [uid         (meili/index-uid client name)
     124            4 :        fingerprint (table-fingerprint ds tables)
     125            5 :        fp-key      (redis-key client "fingerprint" name)
     126            5 :        built-key   (redis-key client "built-at" name)
     127            5 :        lock-key    (redis-key client "lock" name)
     128           42 :        [last-fp last-built] (car/wcar redis (car/get fp-key) (car/get built-key))
     129            4 :        now         (quot (System/currentTimeMillis) 1000)]
     130            4 :    (if-not
     131            4 :      (or
     132            1 :       force?
     133            1 :       (rebuild-needed?
     134           12 :        {:index-exists?    (some? (meili/get-index client uid))
     135            1 :         :fingerprint      fingerprint
     136            1 :         :last-fingerprint last-fp
     137           17 :         :last-built-at    (some->
     138            1 :                             last-built
     139            1 :                             str
     140            1 :                             parse-long)
     141            1 :         :now              now}))
     142              :      :up-to-date
     143           48 :      (if-not (= "OK" (car/wcar redis (car/set lock-key "1" :nx :ex lock-seconds)))
     144              :        :locked
     145            1 :        (try
     146            4 :          (let [started (System/currentTimeMillis)
     147            5 :                n       (rebuild! ds client index)]
     148           46 :            (car/wcar redis (car/set fp-key fingerprint) (car/set built-key (str now)))
     149           92 :            (t/log!
     150              :             :info
     151            6 :             (str
     152              :              "Search index "
     153            1 :              uid
     154              :              " rebuilt: "
     155            1 :              n
     156              :              " documents in "
     157            4 :              (- (System/currentTimeMillis) started)
     158              :              " ms"))
     159              :            :rebuilt)
     160           39 :          (finally (car/wcar redis (car/del lock-key))))))))
     161              : 
     162              : 
     163            4 : (defn sync-all!
     164              :  "Syncs every index; a failing index is logged and doesn't stop the others."
     165              :  [ds redis client]
     166            2 :  (into
     167            1 :   {}
     168           28 :   (for [{:keys [name]
     169              :          :as   index}
     170            1 :         indexes]
     171            2 :     [name
     172            1 :      (try
     173            6 :        (sync-index! ds redis client index)
     174              :        (catch Exception e
     175            0 :          (t/log!
     176              :           :error
     177            0 :           {:message   (str "Search index " name " sync failed")
     178            0 :            :exception e})
     179              :          :failed))])))
        

Generated by: LCOV version 2.0-1