LCOV - code coverage report
Current view: top level - matchscore/search - players.clj Coverage Total Hit
Test: lcov.info Lines: 99.2 % 128 127
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.search.players
       2              :   "The `players` search index: imported players searched by name with typo
       3              :   tolerance. PSA and ESF players can be followed; Rankedin and FSU
       4              :   players are found too (their profiles open at /players/<source>/<id>). Native
       5              :   Matchscore users are not in this public index.
       6              : 
       7              :   Postgres stays the source of truth; the index is rebuilt from it
       8              :   (`matchscore.search.indexer`). PSA/ESF search falls back to the
       9              :   Postgres query whenever Meilisearch is not configured, not built yet or failing;
      10              :   Rankedin and FSU search needs the index (empty without it).
      11              : 
      12              :   Matching differences from the Postgres search: typos are tolerated (\"elyas\"
      13              :   finds Elías), Cyrillic names are found by their Latin spelling (\"panov\" finds
      14              :   \"Панов Микита\"), but only the last word of the query is a prefix, so \"die eli\"
      15              :   no longer finds Diego Elías (\"diego eli\" does)."
      16              :   (:require
      17              :    [clojure.string :as str]
      18              :    [matchscore.domain.country-exclusion :as country-exclusion]
      19              :    [matchscore.domain.player-follow.search :as pg-search]
      20              :    [matchscore.search.meilisearch :as meili]
      21              :    [matchscore.search.translit :as translit]
      22              :    [next.jdbc :as jdbc]
      23              :    [next.jdbc.result-set :as rs]
      24              :    [taoensso.telemere :as t]))
      25              : 
      26              : 
      27            8 : (def index-name "players")
      28              : 
      29              : 
      30            8 : (def unranked
      31              :   "best_rank of players without a rank, so they sort after every ranked player."
      32              :   1000000)
      33              : 
      34              : 
      35            4 : (def followable-sources
      36              :   "Sources whose players can be followed; Postgres can search these without the index."
      37           12 :   ["psa" "esf"])
      38              : 
      39              : 
      40           28 : (def sources (into followable-sources ["rankedin" "fsu"]))
      41              : 
      42              : 
      43            8 : (def all-sources "searchPlayers source value that searches every source." "all")
      44              : 
      45              : 
      46            4 : (def watched-tables
      47              :   "Tables the documents are built from; a write to any of them triggers a rebuild."
      48           32 :   ["psa_players"
      49              :    "psa_ranking_entries"
      50              :    "esf_ranking_entries"
      51              :    "esf_ranking_categories"
      52              :    "rankedin_users"
      53              :    "fsu_players"
      54              :    "fsu_rating_entries"])
      55              : 
      56              : 
      57            4 : (def settings
      58           40 :   {:searchableAttributes ["full_name" "aliases"]
      59           12 :    :filterableAttributes ["source" "country_code"]
      60            8 :    :sortableAttributes   ["best_rank"]
      61              :    ;; Names whose first word matches come first (wordPosition inside `attribute`),
      62              :    ;; then the better ranked player, as in the Postgres search.
      63           28 :    :rankingRules         ["words" "typo" "proximity" "attribute" "exactness" "best_rank:asc"]
      64            8 :    :displayedAttributes  ["*"]
      65           12 :    :pagination           {:maxTotalHits pg-search/max-limit}})
      66              : 
      67              : 
      68            4 : (defn row->document
      69              :  "Index document for a player row (`pg-search/all-players` or the Rankedin/FSU queries)."
      70              :  [{:keys [source player-id full-name country-code city photo-url rank ranking]}]
      71           34 :  {:id           (str source "-" player-id)
      72            2 :   :source       source
      73            6 :   :player_id    (str player-id)
      74            2 :   :full_name    full-name
      75            6 :   :aliases      (translit/latin-aliases full-name)
      76            2 :   :country_code country-code
      77            2 :   :city         city
      78            2 :   :photo_url    photo-url
      79            2 :   :rank         rank
      80            2 :   :ranking      ranking
      81           11 :   :best_rank    (or rank unranked)})
      82              : 
      83              : 
      84            4 : (def ^:private rankedin-sql
      85              :   "Rankedin players (not the PSA/ESF draw users that share the table)."
      86           12 :   (str
      87              :    "SELECT rankedin_id::text AS player_id,
      88              :            NULLIF(trim(concat_ws(' ', first_name, last_name)), '') AS full_name,
      89              :            NULLIF(upper(trim(country_code)), '') AS country_code,
      90              :            photo_url, NULL::int AS rank, NULL::text AS ranking
      91              :       FROM rankedin_users
      92              :      WHERE source = 'rankedin' AND rankedin_id > 0
      93              :        AND NULLIF(trim(concat_ws(' ', first_name, last_name)), '') IS NOT NULL
      94              :        AND "
      95           12 :    (country-exclusion/allowed-sql "country_code")))
      96              : 
      97              : 
      98            8 : (def ^:private fsu-sql
      99              :   "FSU players (keyed by CRM profile id, like their profiles) with their best place
     100              :   in the newest rating of each category, preferring the Absolute rating."
     101              :   "WITH latest AS (
     102              :      SELECT category, max(snapshot_date) AS snapshot_date FROM fsu_rating_entries GROUP BY category),
     103              :    best AS (
     104              :      SELECT DISTINCT ON (e.crm_profile_id) e.crm_profile_id, e.place, e.category
     105              :        FROM fsu_rating_entries e
     106              :        JOIN latest l ON l.category = e.category AND l.snapshot_date = e.snapshot_date
     107              :       WHERE e.place IS NOT NULL
     108              :       ORDER BY e.crm_profile_id, (e.category <> 'Absolute'), e.place)
     109              :    SELECT p.crm_profile_id::text AS player_id, p.full_name, NULL::text AS country_code,
     110              :           NULLIF(trim(p.city), '') AS city, NULL::text AS photo_url,
     111              :           b.place AS rank, b.category AS ranking
     112              :      FROM fsu_players p
     113              :      LEFT JOIN best b ON b.crm_profile_id = p.crm_profile_id
     114              :     WHERE p.crm_profile_id IS NOT NULL AND NULLIF(trim(p.full_name), '') IS NOT NULL")
     115              : 
     116              : 
     117            4 : (defn- source-rows
     118              :   [ds source]
     119            3 :   (case source
     120            3 :     "rankedin" (mapv
     121            5 :                 #(assoc % :source source)
     122            8 :                 (jdbc/execute! ds [rankedin-sql] {:builder-fn rs/as-unqualified-kebab-maps}))
     123            3 :     "fsu"      (mapv
     124            5 :                 #(assoc % :source source)
     125            8 :                 (jdbc/execute! ds [fsu-sql] {:builder-fn rs/as-unqualified-kebab-maps}))
     126            4 :     (pg-search/all-players ds source)))
     127              : 
     128              : 
     129            4 : (defn documents
     130              :  "Every player document, built from Postgres."
     131              :  [ds]
     132           16 :  (into [] (comp (mapcat #(source-rows ds %)) (map row->document)) sources))
     133              : 
     134              : 
     135            4 : (defn- hit->player
     136              :   [{:keys [source player_id full_name country_code city photo_url rank ranking]}]
     137           11 :   {:source       source
     138            1 :    :player-id    player_id
     139            1 :    :full-name    full_name
     140            1 :    :country-code country_code
     141            1 :    :city         city
     142            1 :    :photo-url    photo_url
     143            1 :    :rank         rank
     144            1 :    :ranking      ranking
     145            6 :    :followable   (boolean (some #{source} followable-sources))})
     146              : 
     147              : 
     148            4 : (defn- source-filter
     149              :   "Meilisearch filter: one source, or every source but the `exclude`d ones (nil when
     150              :   nothing is filtered). Only known source names get into the filter."
     151              :   [source exclude]
     152           10 :   (if (not= all-sources source)
     153           10 :     (str "source = \"" source "\"")
     154           46 :     (some->>
     155           12 :       (filter (set exclude) sources)
     156            2 :       seq
     157           18 :       (map #(str "source != \"" % "\""))
     158            2 :       (str/join " AND "))))
     159              : 
     160              : 
     161            4 : (defn search-body
     162              :  "Meilisearch search body for a query, or nil when the query is too short.
     163              :   `exclude` drops sources from an `all-sources` search."
     164            6 :  ([source raw-query limit] (search-body source raw-query limit nil))
     165              :  ([source raw-query limit exclude]
     166           18 :   (when-let [terms (pg-search/query-terms raw-query)]
     167           10 :     (let [filter-expr (source-filter source exclude)]
     168           12 :       (cond->
     169           18 :         {:q     (str/join " " terms)
     170            6 :          :limit (pg-search/clamp-limit limit)
     171              :          ;; Every word must match; the default drops trailing words when results are
     172              :          ;; few, which turns "diego xyz" into every Diego.
     173              :          :matchingStrategy "all"}
     174            6 :         filter-expr (assoc :filter filter-expr))))))
     175              : 
     176              : 
     177            4 : (defn meili-search
     178              :  "Players from the index; throws when Meilisearch fails."
     179            7 :  ([client source raw-query limit] (meili-search client source raw-query limit nil))
     180              :  ([client source raw-query limit exclude]
     181           11 :   (if-let [body (search-body source raw-query limit exclude)]
     182           10 :     (mapv hit->player (:hits (meili/search client index-name body)))
     183            1 :     [])))
     184              : 
     185              : 
     186            4 : (defn- prefix-scores
     187              :   "Name -> 0 when the name starts with the query terms, else 1: the same score the
     188              :   single-source Postgres queries sort by, computed by Postgres for `names`."
     189              :   [ds names terms]
     190            5 :   (let [[score-sql score-params] (#'pg-search/prefix-score "t.n" terms)]
     191            2 :     (into
     192            1 :      {}
     193            6 :      (map (juxt :name :score))
     194            2 :      (jdbc/execute!
     195            1 :       ds
     196            2 :       (into
     197            6 :        [(str "SELECT t.n AS name, " score-sql " AS score FROM unnest(?::text[]) AS t(n)")]
     198            8 :        (concat score-params [(into-array String names)]))
     199            3 :       {:builder-fn rs/as-unqualified-maps}))))
     200              : 
     201              : 
     202            4 : (defn- merge-sources
     203              :   "The best `limit` of the per-source `candidates` (each source's own best matches),
     204              :   ordered like the single-source queries: name-prefix match, ranked before
     205              :   unranked, rank, name, player id."
     206              :   [ds candidates raw-query limit]
     207            8 :   (if-let [terms (pg-search/query-terms raw-query)]
     208           11 :     (let [scores (prefix-scores ds (distinct (keep :full-name candidates)) terms)]
     209            1 :       (->>
     210            1 :         candidates
     211            2 :         (sort-by
     212            1 :          (fn [{:keys [full-name rank player-id]}]
     213           19 :           [(get scores full-name 1) (nil? rank) (or rank 0) full-name (str player-id)]))
     214            3 :         (take limit)
     215            1 :         vec))
     216            0 :     []))
     217              : 
     218              : 
     219            4 : (defn- postgres-search
     220              :   "The Postgres search: one followable source, or all of them (but the `exclude`d
     221              :   ones) for `all-sources` (the best matches of every source, merged). Rankedin and
     222              :   FSU need the index."
     223              :   [ds source raw-query limit exclude]
     224            3 :   (mapv
     225            5 :    #(assoc % :followable true)
     226            6 :    (cond (= all-sources source)
     227            4 :          (let [limit (pg-search/clamp-limit limit)]
     228            2 :            (merge-sources
     229            1 :             ds
     230            2 :             (into
     231            1 :              []
     232           16 :              (comp (remove (set exclude)) (mapcat #(pg-search/search-players ds % raw-query limit)))
     233            1 :              followable-sources)
     234            1 :             raw-query
     235            1 :             limit))
     236              : 
     237           11 :          (some #{source} followable-sources) (pg-search/search-players ds source raw-query limit)
     238            1 :          :else [])))
     239              : 
     240              : 
     241            4 : (defn search-players
     242              :  "Players of `source` (one of `sources`, or `all-sources`) matching `raw-query`,
     243              :   best first. `exclude` lists sources an `all-sources` search leaves out. Uses
     244              :   Meilisearch when `client` is set, else (or when it fails, or for an ESF id)
     245              :   Postgres."
     246            8 :  ([ds client source raw-query limit] (search-players ds client source raw-query limit nil))
     247              :  ([ds client source raw-query limit exclude]
     248           10 :   (let [esf-id? (and
     249            5 :                  (#{"esf" all-sources} source)
     250            7 :                  (not (some #{"esf"} exclude))
     251            2 :                  (pg-search/parse-esid raw-query))]
     252           17 :     (cond (not (or (= all-sources source) (some #{source} sources))) []
     253              : 
     254            9 :           (or (nil? client) esf-id?)
     255           10 :           (postgres-search ds (if esf-id? "esf" source) raw-query limit exclude)
     256              : 
     257              :           :else
     258            1 :           (try
     259            7 :             (meili-search client source raw-query limit exclude)
     260              :             (catch Exception e
     261            8 :               (if (= "index_not_found" (:code (ex-data e)))
     262           22 :                 (t/log! :debug "Players search index not built yet; searching Postgres")
     263           92 :                 (t/log!
     264              :                  :warn
     265            4 :                  {:message   "Meilisearch player search failed; searching Postgres"
     266            1 :                   :exception e}))
     267            7 :               (postgres-search ds source raw-query limit exclude)))))))
        

Generated by: LCOV version 2.0-1