Skip to content

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

feat(sdk): Add etag-based caching for the Hosted Embedding SDK bundle (#61283)

Timofey Kachalov940be59861b3
diff --git a/src/metabase/config/core.clj b/src/metabase/config/core.clj
index b92ed9ccef6..410824bd92f 100644
--- a/src/metabase/config/core.clj
+++ b/src/metabase/config/core.clj
@@ -130,6 +130,10 @@
(let [{:keys [tag hash]} mb-version-info]
(format "%s (%s)" tag hash)))
+(def ^String mb-version-hash
+ "A string representing the hash of the current version of Metabase."
+ (:hash mb-version-info))
+
(def ^String mb-app-id-string
"A formatted version string including the word 'Metabase' appropriate for passing along
with database connections so admins can identify them as Metabase ones.
diff --git a/src/metabase/server/middleware/etag_cache.clj b/src/metabase/server/middleware/etag_cache.clj
new file mode 100644
index 00000000000..5fffdceba9c
--- /dev/null
+++ b/src/metabase/server/middleware/etag_cache.clj
@@ -0,0 +1,58 @@
+(ns metabase.server.middleware.etag-cache
+ "ETag caching-related Ring middleware."
+ (:require
+ [clojure.string :as str]
+ [metabase.config.core :as config]
+ [ring.util.response :as response]))
+
+(set! *warn-on-reflection* true)
+
+(def etag-header
+ "Headers that tell browsers to cache a static resource and revalidate using the etag with the Metabase version hash."
+ {"Cache-Control" "public, max-age=0, must-revalidate"
+ ;; according to the spec, the ETag should be a quoted string
+ "ETag" (format "\"%s\"" config/mb-version-hash)})
+
+(defn- matches-metabase-version-hash?
+ "Returns true if the If-None-Match header (possibly weak/quoted) equals the current version hash."
+ [if-none-match-value]
+ (when if-none-match-value
+ (let [normalized
+ (-> if-none-match-value
+ ;; strip any leading "W/" (weak ETag) prefix
+ (str/replace-first #"^W/" "")
+ ;; strip any leading or trailing quotes
+ (str/replace #"^\"|\"$" ""))]
+ (= normalized config/mb-version-hash))))
+
+(def ^:private not-modified-response
+ "Returns a 304 Not Modified response with ETag and Cache-Control headers for the current Metabase version hash."
+ (-> (response/response "")
+ (response/status 304)
+ (update :headers merge etag-header)))
+
+(defn- js-response-with-etag
+ "Given a Ring response map (typically from `resource-response`), set
+ the correct Content-Type and Metabase-version-based cache headers
+ for embedding-sdk.js."
+ [response]
+ (-> response
+ (response/content-type "application/javascript; charset=UTF-8")
+ (update :headers merge etag-header)))
+
+(defn js-etag-handler
+ "Returns a Ring handler that serves a JS file with ETag/Cache-Control headers.
+ If the If-None-Match header matches the current version hash and not in dev mode,
+ returns a 304 Not Modified response instead."
+ [resource-path]
+ (fn [request]
+ (let [if-none-match (get-in request [:headers "if-none-match"])]
+ (if (and (not config/is-dev?)
+ (matches-metabase-version-hash? if-none-match))
+
+ ;; send the pre-built 304 response
+ not-modified-response
+
+ ;; else, serve the file
+ (js-response-with-etag
+ (response/resource-response resource-path))))))
diff --git a/src/metabase/server/routes.clj b/src/metabase/server/routes.clj
index a7dc3e73ef8..d7f2d271c52 100644
--- a/src/metabase/server/routes.clj
+++ b/src/metabase/server/routes.clj
@@ -10,6 +10,7 @@
[metabase.core.initialization-status :as init-status]
[metabase.query-processor.schema :as qp.schema]
[metabase.server.auth-wrapper :as auth-wrapper]
+ [metabase.server.middleware.etag-cache :as mw.etag-cache]
[metabase.server.routes.index :as index]
[metabase.system.core :as system]
[metabase.util :as u]
@@ -59,6 +60,15 @@
([_request respond _raise]
(respond (health-handler))))
+#_{:clj-kondo/ignore [:discouraged-var]}
+(defroutes ^:private static-files-handler
+ (GET "/embedding-sdk.js" request
+ ((mw.etag-cache/js-etag-handler "frontend_client/app/embedding-sdk.js") request))
+
+ ;; fall back to serving _all_ other files under /app
+ (route/resources "/" {:root "frontend_client/app"})
+ (route/not-found {:status 404 :body "Not found."}))
+
(mu/defn- api-handler :- ::api.macros/handler
[api-routes :- ::api.macros/handler]
(fn api-handler* [request respond raise]
@@ -89,10 +99,7 @@
;; ^/api/ -> All other API routes
(context "/api" [] (api-handler api-routes))
;; ^/app/ -> static files under frontend_client/app
- (context "/app" []
- (route/resources "/" {:root "frontend_client/app"})
- ;; return 404 for anything else starting with ^/app/ that doesn't exist
- (route/not-found {:status 404, :body "Not found."}))
+ (context "/app" [] static-files-handler)
;; ^/public/ -> Public frontend and download routes
(context "/public" [] public-routes)
;; ^/emebed/ -> Embed frontend and download routes
diff --git a/test/metabase/server/middleware/etag_cache_test.clj b/test/metabase/server/middleware/etag_cache_test.clj
new file mode 100644
index 00000000000..88eac2abb5a
--- /dev/null
+++ b/test/metabase/server/middleware/etag_cache_test.clj
@@ -0,0 +1,45 @@
+(ns metabase.server.middleware.etag-cache-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.config.core :as config]
+ [metabase.server.middleware.etag-cache :as mw.etag-cache]
+ [ring.util.response :as response]))
+
+(set! *warn-on-reflection* true)
+
+(deftest js-etag-handler-test
+ (testing "returns 304 when ETag matches and not in dev mode"
+ (with-redefs [config/is-dev? false
+ response/resource-response
+ (constantly {:status 200 :headers {} :body "dummy js"})]
+ (let [etag (format "\"%s\"" config/mb-version-hash)
+ handler (mw.etag-cache/js-etag-handler "frontend_client/app/embedding-sdk.js")
+ response (handler {:headers {"if-none-match" etag}})]
+ (is (= 304 (:status response)))
+ (is (= "" (:body response)))
+ (is (= mw.etag-cache/etag-header (:headers response))))))
+
+ (testing "returns 200 with correct headers when ETag does not match"
+ (with-redefs [config/is-dev? false
+ response/resource-response
+ (constantly {:status 200 :headers {} :body "dummy js"})]
+ (let [etag (format "\"different\"")
+ handler (mw.etag-cache/js-etag-handler "frontend_client/app/embedding-sdk.js")
+ response (handler {:headers {"if-none-match" etag}})
+ headers (:headers response)]
+ (is (= 200 (:status response)))
+ (is (= "application/javascript; charset=UTF-8"
+ (get headers "Content-Type")))
+ (is (= mw.etag-cache/etag-header
+ (select-keys headers (keys mw.etag-cache/etag-header))))))))
+
+(testing "returns 200 when in dev mode, ignoring ETag match"
+ (with-redefs [config/is-dev? true
+ response/resource-response
+ (constantly {:status 200 :headers {} :body "dummy js"})]
+ (let [etag (format "\"%s\"" config/mb-version-hash)
+ handler (mw.etag-cache/js-etag-handler "frontend_client/app/embedding-sdk.js")
+ response (handler {:headers {"if-none-match" etag}})]
+ (is (= 200 (:status response)))
+ (is (= mw.etag-cache/etag-header
+ (select-keys (:headers response) (keys mw.etag-cache/etag-header)))))))