The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
When setting settings, include 5 minute cookie of updated timestamp (#66338)
dpsutton2048f84d4bd1
diff --git a/src/metabase/server/handler.clj b/src/metabase/server/handler.cljindex 2e696d1be92..fa04ada943b 100644--- a/src/metabase/server/handler.clj+++ b/src/metabase/server/handler.clj@@ -15,6 +15,7 @@[metabase.server.middleware.request-id :as mw.request-id][metabase.server.middleware.security :as mw.security][metabase.server.middleware.session :as mw.session]+ [metabase.server.middleware.settings-cache :as mw.settings-cache][metabase.server.middleware.ssl :as mw.ssl][metabase.util.log :as log][metabase.util.malli :as mu]@@ -82,6 +83,7 @@#'mw.session/reset-session-timeout ; Resets the timeout cookie for user activity to [[metabase.request.cookies/session-timeout]]#'mw.session/bind-current-user ; Binds *current-user* and *current-user-id* if :metabase-user-id is non-nil#'mw.session/wrap-current-user-info ; looks for :metabase-session-key and sets :metabase-user-id and other info if Session ID is valid+ #'mw.settings-cache/wrap-settings-cache-check ; check cookie to refresh settings cache if needed#'analytics/embedding-mw ; reads sdk client headers, binds them to *client* and *version*, and tracks sdk-response metrics#'mw.session/wrap-session-key ; looks for a Metabase Session ID and assoc as :metabase-session-key#'mw.auth/wrap-static-api-key ; looks for a static Metabase API Key on the request and assocs as :metabase-api-keydiff --git a/src/metabase/server/middleware/settings_cache.clj b/src/metabase/server/middleware/settings_cache.cljnew file mode 100644index 00000000000..eab59afeb2f--- /dev/null+++ b/src/metabase/server/middleware/settings_cache.clj@@ -0,0 +1,50 @@+(ns metabase.server.middleware.settings-cache+ "Ring middleware to check for settings updates based on a cookie value."+ (:require+ [metabase.settings.core :as setting]+ [metabase.util.log :as log]+ [ring.util.response :as response]))++(def ^:private settings-last-updated-cookie-name "metabase.SETTINGS_LAST_UPDATED")++(defn- check-and-update-settings-cache+ "Check if the cookie timestamp is newer than our cached timestamp, and if so, update the cache."+ [request]+ (when-let [cookie-timestamp (get-in request [:cookies settings-last-updated-cookie-name :value])]+ (let [last-known-update (setting/cache-last-updated-at)]+ ;; If the cookie timestamp is newer than our cached timestamp, restore the cache+ (when (and last-known-update+ (try (pos? (compare cookie-timestamp last-known-update))+ (catch Exception _e+ (log/infof "Strange last known update cookie: %s" cookie-timestamp)+ false)))+ (log/info "Settings cookie indicates cache is out of date. Refreshing...")+ (setting/restore-cache!)+ ::restored))))++(defn- maybe-set-settings-last-updated-cookie+ "Set the most recent settings cache update timestamp if this request changed a setting (it will have+ the :cookie/settings-cache-timestamp) or if this request caused a cache to be updated."+ [restored? response]+ (if (or restored?+ (-> response :mb/cookies :cookie/settings-cache-timestamp))+ (if-let [timestamp (setting/cache-last-updated-at)]+ (response/set-cookie (update response :mb/cookies dissoc :cookie/settings-cache-timestamp)+ settings-last-updated-cookie-name+ timestamp+ {:path "/"+ :max-age (* 5 60)+ :same-site :lax})+ response)+ response))++(defn wrap-settings-cache-check+ "Middleware that checks if settings need to be refreshed based on a cookie value.++ When a setting is updated, the API sets a cookie with the settings-last-updated timestamp.+ This middleware checks that cookie on subsequent requests and updates the local cache if needed,+ ensuring consistency in multi-instance deployments without waiting for the 60-second polling interval."+ [handler]+ (fn [request respond raise]+ (let [restored? (check-and-update-settings-cache request)]+ (handler request (comp respond #(maybe-set-settings-last-updated-cookie restored? %)) raise))))diff --git a/src/metabase/settings/core.clj b/src/metabase/settings/core.cljindex 9a1c456e4bf..d459ea9168d 100644--- a/src/metabase/settings/core.clj+++ b/src/metabase/settings/core.clj@@ -118,6 +118,7 @@writable-settings][metabase.settings.models.setting.cachecache-update-check-interval-ms+ cache-last-updated-atrestore-cache!][metabase.settings.models.setting.multi-settingdefine-multi-settingdiff --git a/src/metabase/settings/models/setting/cache.clj b/src/metabase/settings/models/setting/cache.cljindex c035dbaa51d..1662ea1c8fa 100644--- a/src/metabase/settings/models/setting/cache.clj+++ b/src/metabase/settings/models/setting/cache.clj@@ -92,6 +92,12 @@;; changes(swap! (cache*) assoc settings-last-updated-key (t2/select-one-fn :value :model/Setting :key settings-last-updated-key)))+(defn cache-last-updated-at+ "Fetch the value of `settings-last-updated`, indicating the timestamp of the settings cache. Possibly null."+ []+ (let [current-cache (cache)]+ (core/get current-cache settings-last-updated-key)))+(defn- cache-out-of-date?"Check whether our Settings cache is out of date. We know the cache is out of date if either of the followingconditions is true:@@ -105,12 +111,12 @@(let [current-cache (cache)](boolean(or- ;; is the cache empty?+ ;; is the cache empty?(not current-cache)- ;; if not, get the cached value of `settings-last-updated`, and if it exists...- (when-let [last-known-update (core/get current-cache settings-last-updated-key)]- ;; compare it to the value in the DB. This is done be seeing whether a row exists- ;; WHERE value > <local-value>+ ;; if not, get the cached value of `settings-last-updated`, and if it exists...+ (when-let [last-known-update (cache-last-updated-at)]+ ;; compare it to the value in the DB. This is done be seeing whether a row exists+ ;; WHERE value > <local-value>(u/prog1 (t2/select-one-fn :value :model/Setting{:where [:and[:= :key settings-last-updated-key]diff --git a/src/metabase/settings_rest/api.clj b/src/metabase/settings_rest/api.cljindex 23f2b1c9b94..977bfbabc49 100644--- a/src/metabase/settings_rest/api.clj+++ b/src/metabase/settings_rest/api.clj@@ -23,6 +23,11 @@[& body]`(do-with-setting-access-control (fn [] ~@body)))+(defn- add-settings-last-updated-cookie+ "Add a cookie with the current settings-last-updated timestamp to the response."+ [response]+ (assoc-in response [:mb/cookies :cookie/settings-cache-timestamp] true))+;; TODO: deprecate /api/session/properties and have a single endpoint for listing settings(api.macros/defendpoint :get "/""Get all `Settings` and their values. You must be a superuser or have `setting` permission to do this.@@ -42,7 +47,7 @@settings :- [:map-of kebab-cased-keyword :any]](with-setting-access-control(setting/set-many! settings))- api/generic-204-no-content)+ (add-settings-last-updated-cookie api/generic-204-no-content))(api.macros/defendpoint :get "/:key""Fetch a single `Setting`."@@ -60,4 +65,4 @@{:keys [value]} :- [:map [:value :any]]](with-setting-access-control(setting/set! key value))- api/generic-204-no-content)+ (add-settings-last-updated-cookie api/generic-204-no-content))diff --git a/test/metabase/server/middleware/settings_cache_test.clj b/test/metabase/server/middleware/settings_cache_test.cljnew file mode 100644index 00000000000..0837df07ebc--- /dev/null+++ b/test/metabase/server/middleware/settings_cache_test.clj@@ -0,0 +1,60 @@+(ns metabase.server.middleware.settings-cache-test+ (:require+ [clj-http.cookies :as cookies]+ [clojure.test :refer :all]+ [metabase.server.middleware.settings-cache :as mw.settings-cache]+ [metabase.settings.core :as setting]+ [metabase.test :as mt]+ [ring.util.codec :as codec])+ (:import+ (org.apache.http.client CookieStore)+ (org.apache.http.cookie Cookie)+ (org.apache.http.impl.cookie BasicClientCookie)))++(set! *warn-on-reflection* true)++(def cookie-name (var-get #'mw.settings-cache/settings-last-updated-cookie-name))++(defn- update-cookie+ "Update the cookie in a cookie store with name `k` giving it value `v`. Keeps other properties like expiration and+ domain. Throws an error if the cookie is not found"+ [^CookieStore cs k v]+ (let [cookies (.getCookies cs)+ ^BasicClientCookie cookie (or (some (fn [^Cookie c] (when (= k (.getName c))+ c))+ cookies)+ (throw (ex-info "Did not find cookie"+ {:looking-for k+ :found (into []+ (map Cookie/.getName)+ cookies)})))]+ (.setValue cookie v)+ (.addCookie cs cookie)))++(deftest setting-settings-include-timestamp+ (mt/discard-setting-changes [site-name]+ (let [^CookieStore cs (cookies/cookie-store)]+ (testing "it sets the cookie when updating settings"+ (mt/user-real-request :crowberto :put 204 "setting/site-name"+ {:request-options {:cookie-store cs}}+ {:value "foo"})+ (let [setting-cookie (get (cookies/get-cookies cs) cookie-name)]+ (is (some? setting-cookie) "No cookie set")+ (is (= (setting/cache-last-updated-at)+ (-> setting-cookie :value codec/form-decode))+ "Cookie value is not most recent cache updated at timestamp")))++ (testing "And when that timestamp is outdated it restores the setting cache"+ (let [calls (atom 0)]+ ;; value in 2042 to simulate client has more recent settings+ (update-cookie cs cookie-name "2042-12-02+19%3A57%3A49.775909%2B00")+ (with-redefs [setting/restore-cache! (fn [] (swap! calls inc))]+ (mt/user-real-request :crowberto :get 200 "user/current"+ {:request-options {:cookie-store cs}})+ (is (= 1 @calls) "Cache was not restored based on cookie value")+ (testing "And that header resets the settings last updated at so we don't keep updating the cache"+ (let [setting-cookie (get (cookies/get-cookies cs) cookie-name)]+ (is (some? setting-cookie) "No cookie set")+ (is (= (setting/cache-last-updated-at)+ (-> setting-cookie :value codec/form-decode))+ "The most recent updated at was not set in the header")))))))))