Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Make reindex! an async call (#62316)

Nathan Voxland1e82f4e558fc
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
index 743e776f96f..3f8e7d1e4e2 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
@@ -188,4 +188,4 @@
;; this means that the corresponding entries would have been missing or stale when we indexed them.
;; ideally, we would delay the indexing somehow, or only reindex what we've loaded.
;; while we're figuring that out, here's a crude stopgap.
- (search/reindex!)))
+ (search/reindex! {:async? false})))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj
index 58ee7a5640e..300d1bc47c5 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj
@@ -10,6 +10,7 @@
[metabase-enterprise.serialization.v2.load :as serdes.load]
[metabase-enterprise.serialization.v2.storage :as storage]
[metabase.models.serialization :as serdes]
+ [metabase.search.core :as search]
[metabase.settings.core :as setting]
[metabase.test :as mt]
[metabase.test.generate :as test-gen]
@@ -22,6 +23,12 @@
(set! *warn-on-reflection* true)
+;; `reindex!` below is ok in a parallel test since it's not actually executing anything
+#_{:clj-kondo/ignore [:metabase/validate-deftest]}
+(use-fixtures :each (fn [thunk]
+ (mt/with-dynamic-fn-redefs [search/reindex! (constantly nil)]
+ (thunk))))
+
(defn- dir->contents-set [p ^File dir]
(->> dir
.listFiles
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
index 8eb0651e381..a770c5a766b 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
@@ -9,11 +9,18 @@
[metabase-enterprise.serialization.v2.load :as serdes.load]
[metabase.actions.models :as action]
[metabase.models.serialization :as serdes]
+ [metabase.search.core :as search]
[metabase.test :as mt]
[metabase.util :as u]
[metabase.util.json :as json]
[toucan2.core :as t2]))
+;; `reindex!` below is ok in a parallel test since it's not actually executing anything
+#_{:clj-kondo/ignore [:metabase/validate-deftest]}
+(use-fixtures :each (fn [thunk]
+ (mt/with-dynamic-fn-redefs [search/reindex! (constantly nil)]
+ (thunk))))
+
(defn- no-labels [path]
(mapv #(dissoc % :label) path))
diff --git a/src/metabase/search/api.clj b/src/metabase/search/api.clj
index 1aaf1c9fa82..4c477a7cdf2 100644
--- a/src/metabase/search/api.clj
+++ b/src/metabase/search/api.clj
@@ -83,7 +83,7 @@
;; The job appears to wait on the main thread when run from tests, so, unfortunately, testing this branch is hard.
(if (and (task/job-exists? task.search-index/reindex-job-key) (or (not ingestion/*force-sync*) config/is-test?))
(do (task/trigger-now! task.search-index/reindex-job-key) {:message "task triggered"})
- (do (search/reindex!) {:message "done"}))
+ (do (search/reindex!) {:message "reindex triggered"}))
(throw (ex-info "Search index is not supported for this installation." {:status-code 501}))))
diff --git a/src/metabase/search/appdb/index.clj b/src/metabase/search/appdb/index.clj
index bab679ce1a8..799fb73a166 100644
--- a/src/metabase/search/appdb/index.clj
+++ b/src/metabase/search/appdb/index.clj
@@ -17,6 +17,7 @@
[metabase.util.i18n :as i18n]
[metabase.util.json :as json]
[metabase.util.log :as log]
+ [metabase.util.string :as string]
[toucan2.core :as t2])
(:import
(clojure.lang ExceptionInfo)
@@ -81,9 +82,11 @@
(:pending @*indexes*))
(defn gen-table-name
- "Generate a unique table name to use as a search index table."
- []
- (keyword (str/replace (str "search_index__" (u/lower-case-en (u/generate-nano-id))) #"-" "_")))
+ "Generate a unique table name to use as a search index table. If no suffix is provided, none will be used"
+ ([]
+ (gen-table-name ""))
+ ([suffix]
+ (keyword (str (str/replace (str "search_index__" (u/lower-case-en (u/generate-nano-id))) #"-" "_") suffix))))
(defn- table-name [kw]
(cond-> (name kw)
@@ -369,11 +372,18 @@
[& body]
`(if @#'*mocking-tables*
~@body
- (let [table-name# (gen-table-name)]
+ (let [table-name# (gen-table-name "_temp")
+ version# (str (string/random-string 8) "-temp")]
(binding [*mocking-tables* true
*indexes* (atom {:active table-name#})]
(try
+ (t2/insert! :model/SearchIndexMetadata {:engine :appdb
+ :version version#
+ :lang_code (i18n/site-locale-string)
+ :status :pending
+ :index_name (name table-name#)})
(create-table! table-name#)
~@body
(finally
- (#'drop-table! table-name#)))))))
+ (#'drop-table! table-name#)
+ (t2/delete! :model/SearchIndexMetadata :version version#)))))))
diff --git a/src/metabase/search/core.clj b/src/metabase/search/core.clj
index e552867f36f..d0e2e072b54 100644
--- a/src/metabase/search/core.clj
+++ b/src/metabase/search/core.clj
@@ -16,6 +16,8 @@
[metabase.util.log :as log]
[potemkin :as p]))
+(set! *warn-on-reflection* true)
+
(comment
;; Make sure to import all the engine implementations. In future this can happen automatically, as per drivers.
;;
@@ -114,10 +116,7 @@
(analytics/inc! :metabase-search/index-error)
(throw e)))))
-(defn reindex!
- "Populate a new index, and make it active. Simultaneously updates the current index."
- [& {:as opts}]
- ;; If there are multiple indexes, return the peak inserted for each type. In practice, they should all be the same.
+(defn- reindex-logic! [opts]
(when (supports-index?)
(try
(log/info "Reindexing searchable entities")
@@ -137,6 +136,17 @@
(analytics/inc! :metabase-search/index-error)
(throw e)))))
+(defn reindex!
+ "Populate a new index, and make it active. Simultaneously updates the current index.
+ Returns a future that will complete when the reindexing is done.
+ Respects `search.ingestion/*force-sync*` and waits for the future if it's true.
+ Alternately, if `:async?` is false, it will also run synchronously."
+ [& {:keys [async?] :or {async? true} :as opts}]
+ (let [f #(reindex-logic! opts)]
+ (if (or search.ingestion/*force-sync* (not async?))
+ (doto (promise) (deliver (f)))
+ (future (f)))))
+
(defn reset-tracking!
"Stop tracking the current indexes. Used when resetting the appdb."
[]
diff --git a/src/metabase/search/task/search_index.clj b/src/metabase/search/task/search_index.clj
index b4c53ed4e0f..b8ce1e8f111 100644
--- a/src/metabase/search/task/search_index.clj
+++ b/src/metabase/search/task/search_index.clj
@@ -8,8 +8,7 @@
[metabase.search.ingestion :as ingestion]
[metabase.startup.core :as startup]
[metabase.task.core :as task]
- [metabase.util.queue :as queue]
- [metabase.util.quick-task :as quick-task])
+ [metabase.util.queue :as queue])
(:import
(java.time Instant)
(java.util Date)
@@ -40,10 +39,10 @@
(task/defjob ^{DisallowConcurrentExecution true
:doc "Populate a new Search Index"}
SearchIndexReindex [_ctx]
- (search/reindex!))
+ (search/reindex! {:async? false}))
(defmethod startup/def-startup-logic! ::SearchIndexInit [_]
- (quick-task/submit-task! init!))
+ (doto (Thread. ^Runnable init!) .start))
(defmethod task/init! ::SearchIndexReindex [_]
(let [job (jobs/build
diff --git a/src/metabase/testing_api/api.clj b/src/metabase/testing_api/api.clj
index 2956fc462d5..142c8097c33 100644
--- a/src/metabase/testing_api/api.clj
+++ b/src/metabase/testing_api/api.clj
@@ -124,7 +124,7 @@
[:name ms/NonBlankString]]]
(.clear ^Queue @#'search.ingestion/queue)
(restore-snapshot! snapshot-name)
- (search/reindex!)
+ (search/reindex! {:async? false})
nil)
(api.macros/defendpoint :post "/echo"
diff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.clj
index 7a392d0aa3d..b947988e8a1 100644
--- a/test/metabase/search/api_test.clj
+++ b/test/metabase/search/api_test.clj
@@ -18,6 +18,7 @@
[metabase.search.appdb.index :as search.index]
[metabase.search.config :as search.config]
[metabase.search.core :as search]
+ [metabase.search.ingestion :as search.ingestion]
[metabase.search.test-util :as search.tu]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -35,7 +36,8 @@
(def ^:private default-collection {:id false :name nil :authority_level nil :type nil})
-(use-fixtures :each (fn [thunk] (search.tu/with-new-search-if-available (thunk))))
+(use-fixtures :each (fn [thunk] (binding [search.ingestion/*force-sync* true]
+ (search.tu/with-new-search-if-available (thunk)))))
(def ^:private default-search-row
{:archived false
@@ -457,7 +459,7 @@
:model/DashboardCard _ {:card_id card-id-5 :dashboard_id dash-id}
:model/DashboardCard _ {:card_id card-id-5 :dashboard_id dash-id}]
;; We do not synchronously update dashboard count
- (search/reindex!)
+ (search/reindex! {:async? false :in-place? true})
(is (= (sort-by :dashboardcard_count (cleaned-results dashboard-count-results))
(sort-by :dashboardcard_count (unsorted-search-request-data :rasta :q "dashboard-count")))))))
@@ -650,7 +652,7 @@
(search-request-data :crowberto :q "test"))))))
;; TODO need to isolate these two tests properly, they're sharing temp index
- (search/reindex!)
+ (search/reindex! {:async? false :in-place? true})
(testing "Basic search, should find 1 of each entity type and include bookmarks when available"
(with-search-items-in-collection {:keys [card dashboard]} "test"
@@ -1383,7 +1385,7 @@
{query-action :action-id} {:type :query :dataset_query (mt/native-query {:query (format "delete from %s" search-term)})}]
;; TODO investigate why the actions don't get indexed automatically
- (search/reindex!)
+ (search/reindex! {:async? false :in-place? true})
(testing "by default do not search for native content"
(is (= #{["card" mbql-card]
diff --git a/test/metabase/search/task/search_index_test.clj b/test/metabase/search/task/search_index_test.clj
index cc6ee9b2b8a..4841c276183 100644
--- a/test/metabase/search/task/search_index_test.clj
+++ b/test/metabase/search/task/search_index_test.clj
@@ -8,6 +8,8 @@
[metabase.search.test-util :as search.tu]
[toucan2.core :as t2]))
+(set! *warn-on-reflection* true)
+
;; TODO this is coupled to appdb engines at the moment
(defn- index-size []
(t2/count (search.index/active-table)))
@@ -28,12 +30,12 @@
;; TODO this is coupled to appdb engines at the moment
(t2/query (sql.helpers/drop-table (search.index/active-table)))
(testing "It can recreate the index from scratch"
- (is (search/reindex!))
+ (is (search/reindex! {:async? false}))
(let [initial-size (index-size)
table-name (search.index/active-table)]
(is (pos? initial-size))
(t2/delete! table-name (t2/select-one-pk table-name))
(is (= (dec initial-size) (index-size)))
(testing "It can cycle the index gracefully"
- (is (search/reindex!))
+ (is (search/reindex! {:async? false}))
(is (= initial-size (index-size))))))))
diff --git a/test/metabase/search/test_util.clj b/test/metabase/search/test_util.clj
index 7ef73e3c4b5..e1081a8a8f1 100644
--- a/test/metabase/search/test_util.clj
+++ b/test/metabase/search/test_util.clj
@@ -37,7 +37,7 @@
`(if (search/supports-index?)
(mt/with-dynamic-fn-redefs [search.impl/default-engine (constantly :search.engine/appdb)]
(with-temp-index-table
- (search/reindex!)
+ (search/reindex! {:async? false :in-place? true})
~@body))
~@body))
diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.clj
index b702968635e..76ca691082f 100644
--- a/test/metabase/test/util.clj
+++ b/test/metabase/test/util.clj
@@ -834,7 +834,7 @@
{:delete-from (t2/table-name model)
:where [:and max-id-condition additional-conditions]}))
;; TODO we don't (currently) have index update hooks on deletes, so we need this to ensure rollback happens.
- (search/reindex! {:in-place? true})))))
+ (search/reindex! {:in-place? true :async? false})))))
(defmacro with-model-cleanup
"Execute `body`, then delete any *new* rows created for each model in `models`. Calls `delete!`, so if the model has