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
Remove deleted apps on sync (#78040)
Timofey Kachalovb0ba83e74a6c
diff --git a/e2e/test/scenarios/data-apps/sync.cy.spec.ts b/e2e/test/scenarios/data-apps/sync.cy.spec.tsindex 81c06129f34..f7f028123d0 100644--- a/e2e/test/scenarios/data-apps/sync.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/sync.cy.spec.ts@@ -92,4 +92,42 @@ describe("scenarios > data apps > repo sync", () => {.findByText(/isn.t ready yet/i, { timeout: 30000 }).should("be.visible");});++ it("prunes an app whose directory is removed from the repo on the next sync", () => {+ H.copySyncedCollectionFixture();+ H.copySyncedDataAppsFixture();+ H.commitToRepo("Add data apps");+ H.configureGitAndPullChanges("read-write");++ // Both apps are materialized from the first pull.+ cy.request("GET", "/api/apps").then(({ body: apps }) => {+ expect(apps.map((app: { name: string }) => app.name).sort()).to.deep.eq([+ "broken-bundle",+ "good",+ ]);+ });++ // Delete the good app's directory from the repo and sync again. The connected+ // repo is the source of truth, so the app must be pruned — not left serving.+ cy.exec(`rm -rf -- "${H.LOCAL_GIT_PATH}/data_apps/good"`);+ H.commitToRepo("Remove the good app from the repo");+ H.configureGitAndPullChanges("read-write");++ // `good` is gone; `broken-bundle` (still in the repo) survives.+ cy.request("GET", "/api/apps").then(({ body: apps }) => {+ expect(apps.map((app: { name: string }) => app.name)).to.deep.eq([+ "broken-bundle",+ ]);+ });+ cy.request({ url: "/api/apps/good", failOnStatusCode: false })+ .its("status")+ .should("eq", 404);++ // The admin list reflects the removal.+ cy.visit("/admin/settings/apps");+ cy.findByTestId("admin-layout-content").within(() => {+ cy.findByTestId("data-app-list-item-broken-bundle").should("exist");+ cy.findByTestId("data-app-list-item-good").should("not.exist");+ });+ });});diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/README.md b/enterprise/backend/src/metabase_enterprise/data_apps/README.mdnew file mode 100644index 00000000000..ff81d9d2316--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/README.md@@ -0,0 +1,133 @@+# Data apps (backend)++A **data app** is a JS bundle, authored in a git repository, that Metabase serves and runs inside a+Near Membrane sandbox in the browser. This README covers the backend half: how apps get from the+repository into the app DB, and how they're served. The sandbox, the app runtime, and the host+iframe live on the frontend and are out of scope here.++## Where apps come from++Apps are **not uploaded**. A single repository is connected to Metabase through remote-sync+(Admin → Settings → Remote sync), and each app lives in its own directory under `data_apps/` at the+repo root:++```+data_apps/+ sales/ # the directory name is the slug: /apps/sales+ data_app.yaml+ dist/index.js # the built bundle, committed+ ops/+ data_app.yaml+ dist/app.js+```++`data_app.yaml` declares the display name, the bundle path relative to the app's own directory, and+optionally the origins the sandboxed bundle may `fetch`/XHR. See `config.clj` for the format and its+validation.++**The directory name is the slug.** Nothing in the config declares it. This is what makes slug+collisions structurally impossible — a repo can't hold two `data_apps/sales` directories, and+discovery takes at most one config per directory.++## The sync pipeline++Data apps have no sync of their own; they ride the remote-sync import. Every pull — the manual+"Pull changes" button, the auto-import poll, or startup — ends in+`remote-sync.impl/materialize-data-apps!`, which adapts the imported snapshot to plain reader fns+and calls `data-apps.sync/sync-from-snapshot!`.++```+remote-sync import → snapshot → sync-from-snapshot! → discover configs+ → materialize each app+ → prune apps absent from the repo+```++`data_apps/` is deliberately **not** a serdes path, so apps are invisible to the serialization+layer and are counted separately in the pull summary (see `fold-data-app-changes` in+`remote_sync/impl.clj` — without it, a pull whose only change is a data app reports "no changes").++One import = one transaction. Discovery, upserts, and pruning all commit together.++## The repository is the source of truth++A sync **upserts every app it finds and deletes every row whose directory is gone.** The+consequences are worth stating explicitly, because they're the questions that come up:++| Event | What happens to apps |+|---|---|+| App directory removed from the repo | Row and cached bundle deleted on the next sync |+| Repo switched to a different one | Previous repo's apps are absent from the new snapshot, so they're dropped |+| Repo unlinked | Nothing — unlinking runs no sync, so apps survive |+| Repo has no `data_apps/` at all | All apps removed |+| Failed clone/fetch | Nothing — that throws before a snapshot exists, so deletion never fires |++Pruning is by **directory presence**, not by successful parse. An app whose directory is still+there but whose `data_app.yaml` is momentarily broken keeps its row and its last-good bundle, and is+marked with a `sync_error` — see failure isolation below. Local `enabled` state does not protect a+row: an app disabled in the admin UI and then deleted from the repo is still removed.++## Failure isolation++A sync must never take a working app offline, and one bad app must never abort the others. So+failures are recorded per app rather than thrown:++- **Malformed `data_app.yaml`** — collected into `:config-errors`. An app that already has a row is+ marked with `sync_error` (so the UI shows it as failed rather than silently presenting the+ last-good bundle as freshly synced); an app that has no row yet is simply not materialized.+- **Bundle missing or over the size cap** — the row's metadata is still upserted with `sync_error`+ set, and the previously cached bundle is kept.+- **Anything thrown at all** — `sync-from-snapshot!` catches and logs it, returning nil, so a+ data-app failure can't break the surrounding remote-sync import.++Because the bundle is cached in the app DB rather than read from the repo per request, a broken sync+degrades to "the app still serves its last good bundle, and the admin sees why it's stale."++## What survives a sync++`enabled` is admin-owned and is never written by a sync — an app disabled in the admin UI stays+disabled across pulls, and new rows get the DB default of true.++`:changed` accounting deliberately ignores `last_synced_sha` / `last_synced_at`: re-syncing+identical content at a new commit is not a change, so the pull summary reports real edits only.++## Serving++Routes are mounted at `/api/apps` (`api.clj`). Not `/app/*` — the server reserves that for static+assets (`metabase.server.routes/static-files-handler`).++- `GET /api/apps` — list; `?available=true` filters to enabled apps with no sync error.+- `GET /api/apps/:slug` — metadata for one enabled app.+- `GET /api/apps/:slug/bundle` — the cached bytes, with a content-hash ETag and `If-None-Match`+ → 304. Carries `X-Metabase-Data-App-Allowed-Hosts`, which the iframe reads to configure its+ sandbox fetch allowlist.+- `PUT /api/apps/:slug` — toggle `enabled` (superuser).+- `DELETE /api/apps/:slug` — drop a row and its bundle (superuser).+- `GET /api/apps/repo-status` — whether a repo is connected (superuser).++Responses are field-filtered by role: superusers get full metadata, everyone else gets `name` and+`display_name` only. The bundle blob is never serialized into JSON, and metadata reads go through+`select-non-blob` helpers so listing apps doesn't drag the bundles out of the DB.++`csp.clj` exposes an app's `allowed_hosts` to the core security middleware through a `defenterprise`+hook, which drives the `connect-src` of the iframe document's CSP. It's a separate namespace so the+middleware's lookup doesn't pull in route code.++## Permissions++**Viewing is not gated.** Any signed-in user may open any enabled app — `can-read?` is+unconditionally true, and the endpoints are `+auth`, so reaching a read check already implies+authentication. The data an app queries still runs through the QP under the viewing user's own+permissions, so a user without data access opens the app and sees no data.++**Managing is superuser-only** — enabling, disabling, deleting, and reading repo status.++## Namespace map++| Namespace | Responsibility |+|---|---|+| `sync.clj` | Discovery, materialization, pruning. The entry point remote-sync calls. |+| `config.clj` | `data_app.yaml` parsing and validation; the `data_apps/` layout constants. |+| `api.clj` | The `/api/apps` endpoints, bundle serving, ETag handling. |+| `models/data_app.clj` | The `:model/DataApp` Toucan model, permissions, blob coercion. |+| `csp.clj` | `allowed_hosts` lookup for the core CSP middleware. |+| `init.clj` | Loads the above so endpoints, models, and hooks register. |diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.cljindex 54020bb15b3..0ddf54020a5 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj@@ -1,11 +1,7 @@(ns metabase-enterprise.data-apps.api- "Data-app endpoints, mounted at `/api/apps`.-- Data apps come from the repository connected via the remote-sync feature. The- repo's `data_apps/<dir>/data_app.yaml` files are discovered on sync and each is- materialized as one `data_app` row, caching the app's bundle. Users navigate to- `/apps/:slug`, which fetches `/api/apps/:slug/bundle` and evaluates the- bytes inside a Near Membrane sandbox.+ "Data-app endpoints, mounted at `/api/apps`. Serves the bundles materialized by+ [[metabase-enterprise.data-apps.sync]]; see `README.md` in this directory for+ where apps come from and how the pieces fit together.Note: we can't use `/app/...` for the frontend or `/api/app/...` for the APIbecause Metabase's server reserves `/app/*` for serving static assets (see@@ -126,9 +122,10 @@(data-app/select-one-non-blob :id (:id app))))(api.macros/defendpoint :delete ["/:slug" :slug slug-regex] :- :nil- "Remove a single data app (its row and cached bundle). Intended for clearing- out apps once their repository is no longer connected — a sync never deletes,- and while a repo is connected it would just re-materialize the app."+ "Remove a single data app (its row and cached bundle). Intended for clearing out+ apps left behind by a repository that is no longer connected: while a repo is+ connected, an app still in it is re-materialized by the next sync, and one no+ longer in it is pruned by that sync anyway."[{:keys [slug]} :- [:map [:slug ms/NonBlankString]]](api/check-superuser);; `t2/delete!` returns the row count; a 0 means the slug wasn't there → 404.diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/config.clj b/enterprise/backend/src/metabase_enterprise/data_apps/config.cljindex ffb249c2d04..8cd086b111a 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/config.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/config.clj@@ -1,13 +1,6 @@(ns metabase-enterprise.data-apps.config- "Parsing + validation of a per-app `data_app.yaml`. Each data app lives in its- own directory under `data_apps/` at the repo root, alongside its built bundle:-- data_apps/- sales/ # the directory name is the slug: /apps/sales- data_app.yaml- dist/index.js-- where `data_app.yaml` is:+ "Parsing + validation of a per-app `data_app.yaml`, which sits in the app's own+ directory under `data_apps/` (see `README.md` in this directory for the layout):name: Sales dashboard # display namepath: dist/index.js # bundle path, relative to this app's directory@@ -103,8 +96,11 @@(throw (ex-info (tru "Could not parse {0}/{1}: {2}" dir config-file-name (ex-message e)){:status-code 400})))))-(defn- dir-slug- "The app's slug: the name of its directory (`data_apps/sales` -> `sales`)."+(defn dir-slug+ "The app's slug: the name of its directory (`data_apps/sales` -> `sales`). Used+ verbatim, never normalized. Public so discovery can label an app by its+ directory even when its `data_app.yaml` fails to parse (so a transiently broken+ config isn't treated as a removal)."[^String dir](subs dir (inc (str/last-index-of dir "/"))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.cljindex 82d7371da52..904acb0a6d5 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj@@ -56,10 +56,9 @@[& conditions](apply t2/select (into [:model/DataApp] non-blob-columns) conditions))-;; Any signed-in user may view (open) a data app. The `/api/apps` endpoints-;; are `+auth`, so reaching a read-check already means the user is authenticated.-;; Data the app queries still runs through the QP with the user's own-;; permissions, so a viewer without data access simply sees no data.+;; Deliberately ungated: any signed-in user may view a data app, and the `+auth`+;; endpoints mean reaching a read check already implies authentication. See the+;; README's permissions section for why this is safe.(defmethod mi/can-read? :model/DataApp([_instance] true)([_model _pk] true))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj b/enterprise/backend/src/metabase_enterprise/data_apps/sync.cljindex eadf59539e3..0d83759ba64 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj@@ -1,17 +1,14 @@(ns metabase-enterprise.data-apps.sync- "Materialize data apps from a synced repository snapshot.+ "Materialize data apps from a synced repository snapshot — discovery, upsert, and+ pruning. [[sync-from-snapshot!]] is the entry point remote-sync calls on every+ import.- Data apps ride the remote-sync import pipeline: whenever remote-sync pulls the- connected repository (manual \"Pull changes\", auto-import poll, or startup),- it calls [[sync-from-snapshot!]] with the just-imported snapshot. We discover- every `data_apps/<dir>/data_app.yaml` and materialize one `data_app` row per app- (caching the built bundle). A sync only upserts — it never deletes, so an app- whose directory is gone from the repo is kept until an admin removes it.+ See `README.md` in this directory for the pipeline, the source-of-truth rules+ (what a sync deletes, and what unlinking or switching repos does), and the+ failure-isolation guarantees this namespace implements.This namespace does no Git access of its own — the snapshot's `read-file` /- `list-files` come from remote-sync. The cached `bundle` blob is what serving- reads, so a failed sync never takes a working app offline, and the admin- `enabled` toggle is preserved across syncs."+ `list-files` come from remote-sync."(:require[clojure.string :as str][metabase-enterprise.data-apps.config :as data-app.config]@@ -57,23 +54,26 @@"Given the snapshot's `list-files` and `read-file` fns (where `read-file`returns file text or nil), iterate the folders under `data_apps/` and return oneentry per folder that is an app — it holds a `data_app.yaml`; a folder without- one is skipped. Each entry is a parsed app- `{:slug :display_name :bundle :allowed_hosts}` (with `:bundle` the repo-root- relative bundle path) or `{:config-error <message>}`. Parse/read failures are- isolated per app so one bad config can't abort the sync."+ one is skipped. Each entry carries `:slug` (the directory name) plus either the+ parsed app `{:display_name :bundle :allowed_hosts}` (with `:bundle` the+ repo-root relative bundle path) or `{:config-error <message>}`. Parse/read+ failures are isolated per app so one bad config can't abort the sync — and the+ `:slug` is present either way, so pruning can tell a directory that still exists+ (transiently broken config) from one that was removed."[list-files read-file](let [files (set (list-files))app-dirs (distinct (keep #(second (re-matches app-dir-regex %)) files))](for [dir app-dirs:let [config-path (files (str dir "/data_app.yaml"))]:when config-path]- (try- (if-let [content (read-file config-path)]- (let [{:keys [slug display_name path allowed_hosts]} (data-app.config/parse-app-config (->bytes content) dir)]- {:slug slug, :display_name display_name, :bundle (str dir "/" path), :allowed_hosts allowed_hosts})- {:config-error (tru "Could not read {0}." config-path)})- (catch Throwable e- {:config-error (ex-message e)})))))+ (let [slug (data-app.config/dir-slug dir)]+ (try+ (if-let [content (read-file config-path)]+ (let [{:keys [display_name path allowed_hosts]} (data-app.config/parse-app-config (->bytes content) dir)]+ {:slug slug, :display_name display_name, :bundle (str dir "/" path), :allowed_hosts allowed_hosts})+ {:slug slug, :config-error (tru "Could not read {0}." config-path)})+ (catch Throwable e+ {:slug slug, :config-error (ex-message e)}))))));;; ----------------------------------------------------- Materialize -----------------------------------------------------@@ -99,6 +99,17 @@(not= (vec (or (:allowed_hosts existing) []))(vec (or allowed_hosts [])))))+(defn- mark-config-error!+ "Record a `data_app.yaml` parse failure on an app that already has a row, keeping the+ row and its cached bundle and setting `sync_error`. An app with no row yet isn't+ materialized at all — there's nothing to serve. Returns true when this changed the+ app's recorded state, so callers can count it like any other change."+ [existing slug message]+ (boolean+ (when (and existing (not= (:sync_error existing) message))+ (t2/update! :model/DataApp :name slug {:sync_error message})+ true)))+(defn- sync-app!"Materialize one app. On bundle failure, the row's metadata is still upsertedwith `sync_error` set so the app appears in the list with its failure; the@@ -142,45 +153,50 @@:list-files (fn [] -> [<path-string> ...]):sha <commit-sha-string>}- Discovers every `data_apps/<dir>/data_app.yaml` and upserts a row per app in a- single transaction. Apps not present in the snapshot are left untouched (a- sync never deletes — removal is an explicit admin action). Returns- `{:synced <n>, :changed <n>, :sha <sha>, :config-errors [<message> ...]}`,- where `:changed` is how many apps this sync actually created/updated- (a `last_synced_sha` bump on an unchanged app does not count). A malformed- `data_app.yaml` is isolated (collected into `:config-errors`, that app skipped)- rather than aborting the others; per-app bundle failures are recorded on the- row.-- Two apps can't collide on a slug here: a slug *is* an app's directory name (see- the config namespace), a repo can't hold two `data_apps/<slug>` directories, and- discovery takes one config per directory (see [[discover-app-configs]])."+ Discovers every `data_apps/<dir>/data_app.yaml`, upserts a row per app, and prunes+ rows whose directory is gone from the snapshot — all in one transaction. Returns+ `{:synced <n>, :changed <n>, :removed <n>, :sha <sha>, :config-errors [<msg> ...]}`,+ where `:changed` counts apps actually created/updated (a `last_synced_sha` bump on+ unchanged content does not count) and `:removed` counts apps dropped for no longer+ being in the repo.++ See `README.md` in this directory for the source-of-truth rules this implements,+ and for why a broken config marks its app failed instead of pruning it."[{:keys [read-file list-files sha]}];; realize discovery once (it calls read-file/parse per config); `results` is;; then walked several times below- (let [results (vec (discover-app-configs list-files read-file))- good (filter :slug results)- errors (vec (keep :config-error results))+ (let [results (vec (discover-app-configs list-files read-file))+ good (remove :config-error results)+ errors (vec (keep :config-error results))+ ;; every app directory present in the repo (parsed or not) — the set of+ ;; slugs that should survive this sync+ present-slugs (into #{} (map :slug) results);; pre-sync rows, so we can tell a real change from a sha/timestamp bump- existing (into {} (map (juxt :name identity))- (t2/select [:model/DataApp :name :display_name :allowed_hosts- :bundle_path :bundle_hash :sync_error]))- changed- ;; Upsert-only: a sync never deletes. Apps materialized from a previous- ;; repo are kept (they survive unlinking, and switching repos), and an- ;; app whose directory name matches an existing app's is overridden in- ;; place by `upsert-by-name!`. Rows are removed only by an explicit admin- ;; action (see the API's DELETE).+ existing (into {} (map (juxt :name identity))+ (t2/select [:model/DataApp :name :display_name :allowed_hosts+ :bundle_path :bundle_hash :sync_error]))+ {:keys [changed removed]}(t2/with-transaction [_conn]- (reduce (fn [n cfg]- (cond-> n- (sync-app! (get existing (:slug cfg))- (assoc cfg :sha sha :read-file read-file))- inc))- 0 good))]- (log/infof "[data-app] synced sha=%s apps=%d changed=%d errors=%d"- sha (count good) changed (count errors))- {:synced (count good), :changed changed, :sha sha, :config-errors errors}))+ (let [changed (reduce (fn [n {:keys [slug config-error] :as cfg}]+ (cond-> n+ ;; A parse failure on an app that still exists marks+ ;; that row failed rather than syncing it; everything+ ;; else is materialized normally.+ (if config-error+ (mark-config-error! (get existing slug) slug config-error)+ (sync-app! (get existing slug)+ (assoc cfg :sha sha :read-file read-file)))+ inc))+ 0 results)+ ;; `enabled` is deliberately not consulted — see the README's+ ;; source-of-truth table. (`[:not-in #{}]` is invalid SQL, so delete-all.)+ removed (if (seq present-slugs)+ (t2/delete! :model/DataApp :name [:not-in present-slugs])+ (t2/delete! :model/DataApp))]+ {:changed changed, :removed removed}))]+ (log/infof "[data-app] synced sha=%s apps=%d changed=%d removed=%d errors=%d"+ sha (count good) changed removed (count errors))+ {:synced (count good), :changed changed, :removed removed, :sha sha, :config-errors errors}))(defn sync-from-snapshot!"Entry point for the remote-sync import pipeline. Materializes data apps fromdiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex c692254024b..42b05e54a47 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -398,10 +398,11 @@(vals (:by-path imported-data)))))(defn- fold-data-app-changes- "Fold the count of data apps changed by a pull into its `:outcome`. Data apps- live under `data_apps/` — outside serdes — and are materialized separately (see- [[materialize-data-apps!]]), so they're invisible to [[pulled-change-count]].- Without this, a pull whose only changes are data apps reports `pull-skipped` /+ "Fold the count of data apps a pull changed — upserted *or* removed — into its+ `:outcome`. Data apps live under `data_apps/` — outside serdes — and are+ materialized separately (see [[materialize-data-apps!]]), so they're invisible+ to [[pulled-change-count]]. Without this, a pull whose only changes are data+ apps (including one that only deletes an app) reports `pull-skipped` /`count 0`. Caller guarantees `da-changed` is positive."[outcome da-changed](case (:kind outcome)@@ -681,10 +682,14 @@;; Data apps ride the pull: re-materialize from the real source snapshot;; (the repo file tree under `data_apps/`), not the synthetic merged;; snapshot `load-snapshot!` sees. They're counted outside serdes, so fold- ;; their change count into the outcome — otherwise a data-app-only pull- ;; would report `pull-skipped` / `count 0`.+ ;; how many they upserted or removed into the outcome — otherwise a+ ;; data-app-only pull would report `pull-skipped` / `count 0`.(if (= :success (:status result))- (let [da-changed (:changed (materialize-data-apps! snapshot) 0)]+ (let [da-result (materialize-data-apps! snapshot)+ ;; Removals count too: a pull whose only change is deleting an app+ ;; directory upserts nothing (`:changed` 0) but still changed what+ ;; this instance serves, so it must report as a pull, not skipped.+ da-changed (+ (:changed da-result 0) (:removed da-result 0))](cond-> result(pos? da-changed) (update :outcome fold-data-app-changes da-changed)))result))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.cljindex a619d0f3b11..bbebf30a38d 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj@@ -161,18 +161,20 @@(snapshot (app-files "sales" {:name "Sales" :path "dist/index.js" :bundle "B"})))(is (= [] (:allowed_hosts (t2/select-one :model/DataApp :name "sales")))))))-(deftest import-keeps-apps-absent-from-snapshot-test+(deftest import-prunes-apps-absent-from-snapshot-test(mt/with-model-cleanup [:model/DataApp](data-app.sync/import-from-snapshot!(snapshot (merge (app-files "keep" {:name "Keep" :path "index.js" :bundle "KEEP"})(app-files "gone" {:name "Gone" :path "index.js" :bundle "GONE"}))))(is (= #{"keep" "gone"} (t2/select-fn-set :name :model/DataApp)))- ;; A sync never deletes: an app missing from a later snapshot is kept, not- ;; pruned. Removal is an explicit admin action (DELETE /api/apps/:slug).- (data-app.sync/import-from-snapshot!- (snapshot (app-files "keep" {:name "Keep" :path "index.js" :bundle "KEEP"})))- (is (= #{"keep" "gone"} (t2/select-fn-set :name :model/DataApp))- "the app absent from the later snapshot is kept")))+ ;; The connected repo is the source of truth: an app whose directory is gone+ ;; from a later snapshot is pruned. (An admin can also remove one explicitly+ ;; via DELETE /api/apps/:slug.)+ (is (=? {:removed 1}+ (data-app.sync/import-from-snapshot!+ (snapshot (app-files "keep" {:name "Keep" :path "index.js" :bundle "KEEP"})))))+ (is (= #{"keep"} (t2/select-fn-set :name :model/DataApp))+ "the app absent from the later snapshot is pruned")))(deftest delete-endpoint-test(mt/test-helpers-set-global-values!@@ -225,18 +227,20 @@(is (= #{"one" "two"} (t2/select-fn-set :name :model/DataApp))))))(deftest import-isolates-bad-config-test- (testing "a malformed data_app.yaml is isolated: other apps still sync, the bad one is reported, nothing is pruned"+ (testing "a malformed data_app.yaml is isolated: sibling apps in the same repo still sync and are not pruned, the bad one is reported"(mt/with-model-cleanup [:model/DataApp]- ;; pre-existing app that must survive a sync where another config is broken(data-app.sync/import-from-snapshot!(snapshot (app-files "existing" {:name "Existing" :path "i.js" :bundle "E"})))+ ;; The repo still holds "existing" and adds "good", alongside a broken "bad".+ ;; The broken config must not abort the others, nor prune its siblings.(let [result (data-app.sync/import-from-snapshot!- (snapshot (merge (app-files "good" {:name "Good" :path "i.js" :bundle "GOOD"})+ (snapshot (merge (app-files "existing" {:name "Existing" :path "i.js" :bundle "E"})+ (app-files "good" {:name "Good" :path "i.js" :bundle "GOOD"}){"data_apps/bad/data_app.yaml" "name: [unterminated"})))]- (is (=? {:synced 1} result))+ (is (=? {:synced 2 :removed 0} result))(is (= 1 (count (:config-errors result))))(is (= #{"existing" "good"} (t2/select-fn-set :name :model/DataApp))- "the good app is added and the pre-existing app is NOT pruned despite the bad config")))))+ "the bad config neither aborts nor prunes its sibling apps, and doesn't materialize itself")))))(deftest sync-from-snapshot!-never-throws-test(testing "a malformed data_app.yaml is isolated into :config-errors; the app just doesn't appear, the sync doesn't throw"diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.cljindex 9ebc61fa078..8f8d17b34d1 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj@@ -47,29 +47,70 @@(data-app.sync/import-from-snapshot!(snapshot (app-files "a" {:name "A renamed" :path "index.js" :bundle "V2"})))))))))-(deftest sync-across-repos-keeps-overrides-and-adds-test- (testing "linking repo A, unlinking, then linking repo B: keep A-only apps, override shared slugs with B, add B-only apps"+(deftest switching-repos-prunes-old-apps-overrides-shared-adds-new-test+ (testing "syncing a different repo: drop apps only the old repo had, override shared slugs, add new ones"(mt/with-model-cleanup [:model/DataApp];; Repo A: Foo + Bar(data-app.sync/import-from-snapshot!(snapshot (merge (app-files "foo" {:name "Foo" :path "index.js" :bundle "FOO"})(app-files "bar" {:name "Bar A" :path "index.js" :bundle "BAR-A"}))))(is (= #{"foo" "bar"} (t2/select-fn-set :name :model/DataApp)))- ;; Unlinking A doesn't sync (nothing prunes). Linking repo B (Bar + Baz)- ;; and importing it keeps Foo, overrides Bar by slug, and adds Baz.- (data-app.sync/import-from-snapshot!- (snapshot (merge (app-files "bar" {:name "Bar B" :path "index.js" :bundle "BAR-B"})- (app-files "baz" {:name "Baz" :path "index.js" :bundle "BAZ"}))))- (is (= #{"foo" "bar" "baz"} (t2/select-fn-set :name :model/DataApp))- "Foo (from repo A) is kept and Baz (from repo B) is added")- (is (= "Foo" (:display_name (t2/select-one :model/DataApp :name "foo")))- "Foo is untouched by repo B")+ ;; Repo B (Bar + Baz): the repo is the source of truth, so Foo (absent from B)+ ;; is pruned, Bar is overridden by slug, and Baz is added.+ (is (=? {:synced 2 :removed 1}+ (data-app.sync/import-from-snapshot!+ (snapshot (merge (app-files "bar" {:name "Bar B" :path "index.js" :bundle "BAR-B"})+ (app-files "baz" {:name "Baz" :path "index.js" :bundle "BAZ"}))))))+ (is (= #{"bar" "baz"} (t2/select-fn-set :name :model/DataApp))+ "Foo (only in repo A) is dropped; Baz (from repo B) is added")(let [bar (t2/select-one :model/DataApp :name "bar")](is (= "Bar B" (:display_name bar))- "Bar is overridden in place by repo B (slug conflict)")+ "Bar is overridden in place by repo B (shared slug)")(is (= "BAR-B" (String. ^bytes (:bundle bar) "UTF-8"))"Bar's cached bundle is repo B's")))))+(deftest an-empty-repo-prunes-all-apps-test+ (testing "syncing a repo with no data_apps/ removes every app (the repo has none)"+ (mt/with-model-cleanup [:model/DataApp]+ (data-app.sync/import-from-snapshot!+ (snapshot (app-files "solo" {:name "Solo" :path "index.js" :bundle "S"})))+ (is (= #{"solo"} (t2/select-fn-set :name :model/DataApp)))+ (is (=? {:synced 0 :removed 1}+ (data-app.sync/import-from-snapshot! (snapshot {}))))+ (is (empty? (t2/select-fn-set :name :model/DataApp))))))++(deftest a-broken-config-does-not-prune-the-existing-app-test+ (testing "a directory that still exists but whose data_app.yaml is now broken keeps the app (as a sync_error), it is not pruned"+ (mt/with-model-cleanup [:model/DataApp]+ (data-app.sync/import-from-snapshot!+ (snapshot (app-files "app" {:name "App" :path "index.js" :bundle "GOOD"})))+ (is (= "GOOD" (String. ^bytes (:bundle (t2/select-one :model/DataApp :name "app")) "UTF-8")))+ ;; Same directory, but its config no longer parses. The dir is still present,+ ;; so the app is kept — not treated as a removal — and its cached bundle stays.+ (let [result (data-app.sync/import-from-snapshot!+ (snapshot {"data_apps/app/data_app.yaml" "name: App\n" ; missing required "path"+ "data_apps/app/index.js" "GOOD"}))]+ (is (=? {:removed 0} result) "the app is not pruned")+ (is (= 1 (count (:config-errors result))))+ (is (=? {:changed 1} result)+ "marking the app failed counts as a change, so the pull isn't reported as a no-op"))+ (let [app (t2/select-one :model/DataApp :name "app")]+ (is (some? app) "the app survives a transiently broken config")+ (is (= "GOOD" (String. ^bytes (:bundle app) "UTF-8"))+ "its last-good cached bundle is retained")+ (is (str/includes? (:sync_error app) "path")+ "the parse failure is recorded on the row, so the UI shows it as failed rather than freshly synced")))))++(deftest a-broken-config-for-a-brand-new-app-materializes-nothing-test+ (testing "an app whose config never parsed has no row to mark — it simply isn't materialized"+ (mt/with-model-cleanup [:model/DataApp]+ (let [result (data-app.sync/import-from-snapshot!+ (snapshot {"data_apps/newbie/data_app.yaml" "name: Newbie\n" ; missing required "path"+ "data_apps/newbie/index.js" "X"}))]+ (is (= 1 (count (:config-errors result))))+ (is (=? {:synced 0 :changed 0 :removed 0} result))+ (is (empty? (t2/select-fn-set :name :model/DataApp)))))))+(defn- oversized-bundle ^String [](.repeat "a" (int (inc data-app.sync/max-bundle-bytes))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.cljindex f3d5a55bae7..ff589311a33 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj@@ -44,8 +44,8 @@(is (true? (:enabled app)))(is (= "SALESBUNDLE" (String. ^bytes (:bundle app) "UTF-8"))))))))-(deftest import-keeps-data-apps-absent-from-repo-test- (testing "an import whose repo no longer has an app dir keeps that app (a sync never deletes)"+(deftest import-prunes-data-apps-absent-from-repo-test+ (testing "an import whose repo no longer has an app dir prunes that app (the repo is the source of truth)"(mt/with-model-cleanup [:model/DataApp](import! {"main" {"data_apps/gone/data_app.yaml" "name: Gone\npath: ./i.js\n""data_apps/gone/i.js" "X"@@ -54,7 +54,23 @@(is (= #{"gone" "kept"} (t2/select-fn-set :name :model/DataApp)))(import! {"main" {"data_apps/kept/data_app.yaml" "name: Kept\npath: ./i.js\n""data_apps/kept/i.js" "K"}})- (is (some? (t2/select-one :model/DataApp :name "gone"))- "the app absent from the later import is kept, not pruned")+ (is (nil? (t2/select-one :model/DataApp :name "gone"))+ "the app absent from the later import is pruned")(is (some? (t2/select-one :model/DataApp :name "kept"))"the still-present app is kept"))))++(deftest deletion-only-pull-counts-the-removal-test+ (testing "a pull whose only change is removing an app still reports as a pull — the removal is counted, not a no-op"+ (mt/with-model-cleanup [:model/DataApp]+ ;; No serdes content, so the outcome's count comes purely from data apps.+ (import! {"main" {"README.md" "x"+ "data_apps/gone/data_app.yaml" "name: Gone\npath: ./i.js\n"+ "data_apps/gone/i.js" "X"}})+ (is (= #{"gone"} (t2/select-fn-set :name :model/DataApp)))+ ;; Same repo minus the app dir: nothing is upserted (`:changed` 0), one app removed.+ (let [result (import! {"main" {"README.md" "x"}})]+ (is (= :success (:status result)))+ (is (empty? (t2/select-fn-set :name :model/DataApp))+ "the app is pruned")+ (is (pos? (:count (:outcome result)))+ "the removal is folded into the pull outcome, so it isn't reported as pull-skipped/0")))))