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 disc/memory caching for hosted bundle on top of etag caching (#63014)

Timofey Kachalovab4e737c3116
diff --git a/e2e/support/helpers/e2e-browser-helpers.ts b/e2e/support/helpers/e2e-browser-helpers.ts
index 44279e2ebb0..99828d3d74c 100644
--- a/e2e/support/helpers/e2e-browser-helpers.ts
+++ b/e2e/support/helpers/e2e-browser-helpers.ts
@@ -5,7 +5,7 @@
* clear the cache between tests. Use this helper if you need to clear the cache.
*/
export function clearBrowserCache() {
- cy.wrap(
+ return cy.wrap(
Cypress.automation("remote:debugger:protocol", {
command: "Network.clearBrowserCache",
}),
diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle.cy.spec.tsx
index 65549fcccb0..0af0756ff3a 100644
--- a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle.cy.spec.tsx
@@ -15,6 +15,8 @@ import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embeddin
import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
import { deleteConflictingCljsGlobals } from "metabase/embedding-sdk/test/delete-conflicting-cljs-globals";
+const { H } = cy;
+
const sdkBundleCleanup = () => {
getSdkBundleScriptElement()?.remove();
delete window.METABASE_EMBEDDING_SDK_BUNDLE;
@@ -320,17 +322,19 @@ describe(
});
});
- describe("Error handling", () => {
+ describe("Error handling", { retries: 3 }, () => {
beforeEach(() => {
+ H.clearBrowserCache();
+
sdkBundleCleanup();
+
+ cy.intercept("GET", "**/app/embedding-sdk.js", {
+ statusCode: 404,
+ });
});
describe("when the SDK bundle can't be loaded", () => {
it("should show an error", () => {
- cy.intercept("GET", "**/app/embedding-sdk.js", {
- statusCode: 404,
- });
-
mountSdkContent(
<InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,
{
@@ -345,10 +349,6 @@ describe(
});
it("should show a custom error", () => {
- cy.intercept("GET", "**/app/embedding-sdk.js", {
- statusCode: 404,
- });
-
mountSdkContent(
<InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,
{
diff --git a/src/metabase/server/lib/etag_cache.clj b/src/metabase/server/lib/etag_cache.clj
new file mode 100644
index 00000000000..fa3c7d53694
--- /dev/null
+++ b/src/metabase/server/lib/etag_cache.clj
@@ -0,0 +1,33 @@
+(ns metabase.server.lib.etag-cache
+ "ETag caching-related utilities."
+ (:require
+ [clojure.string :as str]
+ [metabase.config.core :as config]
+ [ring.util.response :as response]))
+
+(set! *warn-on-reflection* true)
+
+(defn- current-etag-header []
+ {"ETag" (format "\"%s\"" config/mb-version-hash)})
+
+(defn- parse-if-none-match [if-none-match]
+ (->> (some-> if-none-match (str/split #"\s*,\s*"))
+ (map #(-> %
+ (str/replace-first #"^W/" "")
+ (str/replace #"^\"|\"$" "")))
+ set))
+
+(defn- etag-matches? [if-none-match]
+ (let [normalized-if-none-match (some-> if-none-match str/trim)]
+ (or (= "*" normalized-if-none-match)
+ (contains? (parse-if-none-match normalized-if-none-match) config/mb-version-hash))))
+
+(defn with-etag
+ "Return 304 + ETag if If-None-Match matches; else 200 base + ETag."
+ [response request]
+ (if (etag-matches? (get-in request [:headers "if-none-match"]))
+ (-> (response/response "")
+ (response/status 304)
+ (update :headers merge (current-etag-header)))
+ (-> response
+ (update :headers merge (current-etag-header)))))
diff --git a/src/metabase/server/middleware/embedding_sdk_bundle.clj b/src/metabase/server/middleware/embedding_sdk_bundle.clj
new file mode 100644
index 00000000000..ea04377baf1
--- /dev/null
+++ b/src/metabase/server/middleware/embedding_sdk_bundle.clj
@@ -0,0 +1,41 @@
+(ns metabase.server.middleware.embedding-sdk-bundle
+ "Embedding SDK Bundle related Ring middleware."
+ (:require
+ [metabase.config.core :as config]
+ [metabase.server.lib.etag-cache :as lib.etag-cache]
+ [ring.util.response :as response]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private bundle-resource "frontend_client/app/embedding-sdk.js")
+(def ^:private content-type "application/javascript; charset=UTF-8")
+(def ^:private default-cache-header {"Cache-Control" "public, max-age=60"})
+(def ^:private no-store-cache-header {"Cache-Control" "no-store"})
+(def ^:private vary-accept-encoding-header {"Vary" "Accept-Encoding"})
+
+(defn- not-found []
+ (-> (response/not-found "Not found")
+ (update :headers merge no-store-cache-header)))
+
+(defn- serve-for-dev [base]
+ (-> base
+ (response/content-type content-type)
+ (update :headers merge no-store-cache-header)))
+
+(defn- serve-for-prod [base request]
+ (let [resp (lib.etag-cache/with-etag base request)]
+ (cond-> resp
+ true (update :headers merge
+ default-cache-header
+ vary-accept-encoding-header)
+ (= 200 (:status resp)) (response/content-type content-type))))
+
+(defn serve-bundle-handler
+ "Serve /app/embedding-sdk.js. Prod: ETag + 60s caching (200/304). Dev: no-store."
+ []
+ (fn [request]
+ (let [base (response/resource-response bundle-resource)]
+ (cond
+ (nil? base) (not-found)
+ config/is-prod? (serve-for-prod base request)
+ :else (serve-for-dev base)))))
diff --git a/src/metabase/server/middleware/etag_cache.clj b/src/metabase/server/middleware/etag_cache.clj
deleted file mode 100644
index 5fffdceba9c..00000000000
--- a/src/metabase/server/middleware/etag_cache.clj
+++ /dev/null
@@ -1,58 +0,0 @@
-(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 d7f2d271c52..a548fb3b0c6 100644
--- a/src/metabase/server/routes.clj
+++ b/src/metabase/server/routes.clj
@@ -10,7 +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.middleware.embedding-sdk-bundle :as mw.embedding-sdk-bundle]
[metabase.server.routes.index :as index]
[metabase.system.core :as system]
[metabase.util :as u]
@@ -63,7 +63,7 @@
#_{: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))
+ ((mw.embedding-sdk-bundle/serve-bundle-handler) request))
;; fall back to serving _all_ other files under /app
(route/resources "/" {:root "frontend_client/app"})
diff --git a/test/metabase/server/lib/etag_cache_test.clj b/test/metabase/server/lib/etag_cache_test.clj
new file mode 100644
index 00000000000..c41745740b9
--- /dev/null
+++ b/test/metabase/server/lib/etag_cache_test.clj
@@ -0,0 +1,74 @@
+(ns metabase.server.lib.etag-cache-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.config.core :as config]
+ [metabase.server.lib.etag-cache :as lib.etag-cache]))
+
+(set! *warn-on-reflection* true)
+
+(defn- base-response
+ ([] (base-response {}))
+ ([headers]
+ {:status 200
+ :headers headers
+ :body "dummy js"}))
+
+(deftest with-etag-returns-304-when-etag-matches
+ (testing "Exact strong ETag match returns 304 with only ETag header added"
+ (let [etag (format "\"%s\"" config/mb-version-hash)
+ resp (lib.etag-cache/with-etag (base-response) {:headers {"if-none-match" etag}})]
+ (is (= 304 (:status resp)))
+ (is (= "" (:body resp)))
+ (is (= etag (get-in resp [:headers "ETag"])))
+ (is (nil? (get-in resp [:headers "Cache-Control"])))
+ (is (nil? (get-in resp [:headers "Content-Type"])))))
+
+ (testing "Weak ETag (W/) is treated as match"
+ (let [etag-weak (format "W/\"%s\"" config/mb-version-hash)
+ resp (lib.etag-cache/with-etag (base-response) {:headers {"if-none-match" etag-weak}})]
+ (is (= 304 (:status resp)))
+ (is (= "" (:body resp)))
+ (is (= (format "\"%s\"" config/mb-version-hash)
+ (get-in resp [:headers "ETag"])))))
+
+ (testing "Multiple ETags in If-None-Match; any match triggers 304"
+ (let [header (format "\"other\", W/\"%s\", \"another\"" config/mb-version-hash)
+ resp (lib.etag-cache/with-etag (base-response) {:headers {"if-none-match" header}})]
+ (is (= 304 (:status resp)))
+ (is (= (format "\"%s\"" config/mb-version-hash)
+ (get-in resp [:headers "ETag"]))))))
+
+(deftest with-etag-returns-200-and-adds-etag-when-no-match
+ (testing "ETag does not match → 200; adds ETag, preserves existing headers; no Cache-Control/Content-Type"
+ (let [resp (lib.etag-cache/with-etag
+ (base-response {"X-Foo" "bar"})
+ {:headers {"if-none-match" "\"different\""}})]
+ (is (= 200 (:status resp)))
+ (is (= "dummy js" (:body resp)))
+ (is (= (format "\"%s\"" config/mb-version-hash)
+ (get-in resp [:headers "ETag"])))
+ (is (= "bar" (get-in resp [:headers "X-Foo"])))
+ (is (nil? (get-in resp [:headers "Cache-Control"])))
+ (is (nil? (get-in resp [:headers "Content-Type"])))))
+
+ (testing "Missing If-None-Match → 200; adds ETag only"
+ (let [resp (lib.etag-cache/with-etag (base-response) {:headers {}})]
+ (is (= 200 (:status resp)))
+ (is (= "dummy js" (:body resp)))
+ (is (= (format "\"%s\"" config/mb-version-hash)
+ (get-in resp [:headers "ETag"])))
+ (is (nil? (get-in resp [:headers "Cache-Control"])))
+ (is (nil? (get-in resp [:headers "Content-Type"]))))))
+
+(deftest with-etag-returns-304-on-wildcard
+ (testing "If-None-Match: * (or with whitespace) returns 304 and only adds ETag"
+ (doseq [if-none-match-value ["*" " * " "* " " *"]]
+ (let [resp (lib.etag-cache/with-etag
+ {:status 200 :headers {} :body "dummy js"}
+ {:headers {"if-none-match" if-none-match-value}})]
+ (is (= 304 (:status resp)))
+ (is (= "" (:body resp)))
+ (is (= (format "\"%s\"" config/mb-version-hash)
+ (get-in resp [:headers "ETag"])))
+ (is (nil? (get-in resp [:headers "Cache-Control"])))
+ (is (nil? (get-in resp [:headers "Content-Type"])))))))
diff --git a/test/metabase/server/middleware/embedding_sdk_bundle_test.clj b/test/metabase/server/middleware/embedding_sdk_bundle_test.clj
new file mode 100644
index 00000000000..202c01d0ace
--- /dev/null
+++ b/test/metabase/server/middleware/embedding_sdk_bundle_test.clj
@@ -0,0 +1,72 @@
+(ns metabase.server.middleware.embedding-sdk-bundle-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.config.core :as config]
+ [metabase.server.lib.etag-cache :as lib.etag-cache]
+ [metabase.server.middleware.embedding-sdk-bundle :as mw.embedding-sdk-bundle]
+ [ring.util.response :as response]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private cache-header "public, max-age=60")
+(def ^:private js-ct "application/javascript; charset=UTF-8")
+
+(deftest serve-bundle-handler-prod-returns-304-and-adds-cache-header
+ (testing "Prod + ETag match → 304 with Cache-Control, ETag, Vary, TAO; no Content-Type"
+ (with-redefs [config/is-prod? true
+ response/resource-response (constantly {:status 200 :headers {} :body "dummy"})
+ ;; with-etag returns a 304 response with an ETag
+ lib.etag-cache/with-etag (fn [_base _req]
+ {:status 304
+ :headers {"ETag" "\"abc\""}
+ :body ""})]
+ (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)
+ resp (handler {:headers {"if-none-match" "\"abc\""}})]
+ (is (= 304 (:status resp)))
+ (is (= "" (:body resp)))
+ (is (= cache-header (get-in resp [:headers "Cache-Control"])))
+ (is (= "\"abc\"" (get-in resp [:headers "ETag"])))
+ (is (= "Accept-Encoding" (get-in resp [:headers "Vary"])))
+ (is (nil? (get-in resp [:headers "Content-Type"])) "304 should not include Content-Type")))))
+
+(deftest serve-bundle-handler-prod-returns-200-and-adds-cache-and-content-type
+ (testing "Prod + ETag miss → 200 with Cache-Control, ETag, Content-Type, Vary, TAO"
+ (with-redefs [config/is-prod? true
+ response/resource-response (constantly {:status 200 :headers {} :body "dummy"})
+ ;; with-etag returns a 200 response with an ETag applied
+ lib.etag-cache/with-etag (fn [base _req]
+ (update base :headers assoc "ETag" "\"abc\""))]
+ (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)
+ resp (handler {:headers {}})]
+ (is (= 200 (:status resp)))
+ (is (= cache-header (get-in resp [:headers "Cache-Control"])))
+ (is (= "\"abc\"" (get-in resp [:headers "ETag"])))
+ (is (= js-ct (get-in resp [:headers "Content-Type"])))
+ (is (= "Accept-Encoding" (get-in resp [:headers "Vary"])))
+ (is (= "dummy" (:body resp))))))
+
+ (deftest serve-bundle-handler-dev-skips-etag-and-sets-no-store
+ (testing "Dev skips with-etag and sets no-store + Content-Type, no prod-only headers"
+ (with-redefs [config/is-prod? false
+ response/resource-response (constantly {:status 200 :headers {} :body "dummy"})
+ ;; If it were called in dev, we’d see this exception
+ lib.etag-cache/with-etag (fn [& _]
+ (throw (ex-info "with-etag should not be called in dev" {})))]
+ (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)
+ resp (handler {:headers {}})]
+ (is (= 200 (:status resp)))
+ (is (= "no-store" (get-in resp [:headers "Cache-Control"])))
+ (is (= js-ct (get-in resp [:headers "Content-Type"])))
+ (is (nil? (get-in resp [:headers "Vary"])))
+ (is (= "dummy" (:body resp))))))
+
+ (deftest serve-bundle-handler-404-propagates
+ (testing "Missing resource → 404 with no-store; no prod-only headers"
+ (with-redefs [config/is-prod? true
+ response/resource-response (constantly nil)
+ lib.etag-cache/with-etag (fn [& args] (throw (ex-info "Not expected for 404" {:args args})))]
+ (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)
+ resp (handler {:headers {}})]
+ (is (= 404 (:status resp)))
+ (is (= "no-store" (get-in resp [:headers "Cache-Control"])))
+ (is (nil? (get-in resp [:headers "Vary"])))))))))
diff --git a/test/metabase/server/middleware/etag_cache_test.clj b/test/metabase/server/middleware/etag_cache_test.clj
deleted file mode 100644
index 88eac2abb5a..00000000000
--- a/test/metabase/server/middleware/etag_cache_test.clj
+++ /dev/null
@@ -1,45 +0,0 @@
-(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)))))))