Skip to content

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

Write data app resources as YAML in the app's git repo instead of creating them through the API (#83248)

Timofey Kachalov1b79d41d6701
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 0dabd1ebcce..64b9eb9013f 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -3084,6 +3084,7 @@
{:team "Embedding"
:api #{metabase.typed-schemas.core}
:uses #{actions
+ audit-app
collections
lib
lib.be
@@ -3091,8 +3092,8 @@
lib.types
metabot
metrics
- models
permissions
+ premium-features
queries
system
util
@@ -3761,13 +3762,16 @@
enterprise/data-apps
{:team "Embedding"
- :api #{metabase-enterprise.data-apps.api metabase-enterprise.data-apps.init}
- :uses #{api
+ :api #{metabase-enterprise.data-apps.api metabase-enterprise.data-apps.core metabase-enterprise.data-apps.init}
+ :uses #{actions
+ api
api-scope
collections
+ driver
events
lib
lib.be
+ lib.metadata
lib.schema
models
permissions
@@ -3776,13 +3780,17 @@
request
settings
util
- warehouse-schema-overlay}
- :model-imports #{:model/Card
+ warehouse-schema-overlay
+ enterprise/serialization}
+ :model-imports #{:model/Action
+ :model/Card
:model/Collection
:model/DataPermissions
:model/Database
+ :model/Field
:model/Permissions
:model/PermissionsGroup
+ :model/QueryAction
:model/Table
:model/User}
:model-exports #{:model/DataApp}}
@@ -4227,6 +4235,7 @@
task.history
util
warehouse-schema-overlay
+ enterprise/data-apps
enterprise/serialization
enterprise/transforms.python}
:model-exports #{:model/RemoteSyncTask}
diff --git a/.github/workflows/embedding-sdk-host-sample-apps-tests.yml b/.github/workflows/embedding-sdk-host-sample-apps-tests.yml
index 5c0fe3ae655..fc358538a96 100644
--- a/.github/workflows/embedding-sdk-host-sample-apps-tests.yml
+++ b/.github/workflows/embedding-sdk-host-sample-apps-tests.yml
@@ -424,7 +424,7 @@ jobs:
if: steps.prebuilt-cljs.outcome != 'success'
run: bun run build-pure:cljs
- # The data-app suite synchronizes real actions, and Metabase only permits
+ # The data-app suite publishes copies of real actions, and Metabase only permits
# those against a writable warehouse, which comes from the `qa-db`
# snapshot below. That snapshot creator builds every QA database in one
# pass — Mongo and MySQL included — so all three have to be up even though
diff --git a/bin/embedding-sdk/test-sdk-package.mjs b/bin/embedding-sdk/test-sdk-package.mjs
index 562ff1425c4..9af0d452420 100644
--- a/bin/embedding-sdk/test-sdk-package.mjs
+++ b/bin/embedding-sdk/test-sdk-package.mjs
@@ -56,7 +56,7 @@ try {
fs.readFileSync(path.join(installedPackage, "package.json"), "utf8"),
);
- // Check that both esbuild and typescript modules are installed and can be used
+ // Check that the esbuild module the CLI bundles definition files with is installed and can be used
execFileSync(
process.execPath,
[
@@ -66,26 +66,26 @@ try {
const sdkRequire = createRequire(${JSON.stringify(path.join(installedPackage, "package.json"))});
sdkRequire("esbuild").transformSync("const value: number = 1", { loader: "ts" });
- sdkRequire("typescript").transpileModule("const value: number = 1", {});
`,
],
NPM_COMMAND_OPTIONS,
);
- // Check that the installed CLI has data apps sync command
- const output = execFileSync(
- process.execPath,
- [
- path.join(installedPackage, manifest.bin),
- "data-apps",
- "sync-resources",
- "--help",
- ],
- NPM_COMMAND_OPTIONS,
- );
+ for (const command of ["print-resources", "check-resources"]) {
+ const output = execFileSync(
+ process.execPath,
+ [
+ path.join(installedPackage, manifest.bin),
+ "data-apps",
+ command,
+ "--help",
+ ],
+ NPM_COMMAND_OPTIONS,
+ );
- assert.match(output, /Usage: .*sync-resources/);
- assert.match(output, /--app-root/);
+ assert.match(output, new RegExp(`Usage: .*${command}`));
+ assert.match(output, /--app-root/);
+ }
console.log("SDK package smoke test passed.");
} finally {
diff --git a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.gitignore b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.gitignore
index 2414f775f65..c7b7eb1dd6a 100644
--- a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.gitignore
+++ b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.gitignore
@@ -11,5 +11,7 @@ build
# debug
npm-debug.log*
-# generated test action declarations
+# written at test time by the data-app resource specs
/actions/
+/queries/
+/collections/
diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx
index ea1de5ae100..3f2f935350b 100644
--- a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx
+++ b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx
@@ -198,14 +198,14 @@ function NativeQueryPage() {
}
function Actions() {
- const { actionId, actionParams } = getTestEnv();
- // A data app names its actions by definition. Nothing synchronizes here, so
- // the copy the definition points at is the authored action itself.
+ const { actionId, actionEntityId, actionParams } = getTestEnv();
+ // A data app names its actions by definition. This fixture has no
+ // collection files, so the copy the definition points at is the authored action.
const action = useAction(
actionId
? defineAction({
action: { id: actionId, parameters: [] },
- copiedActionId: actionId,
+ copiedActionEntityId: actionEntityId,
})
: null,
);
diff --git a/e2e/support/assets/data-apps/synced-actions-app/data_app.yaml b/e2e/support/assets/data-apps/synced-actions-app/data_app.yaml
index c8bf7f8c6da..6e85142fbf4 100644
--- a/e2e/support/assets/data-apps/synced-actions-app/data_app.yaml
+++ b/e2e/support/assets/data-apps/synced-actions-app/data_app.yaml
@@ -2,8 +2,9 @@ version: 1
name: Synced Actions App
slug: synced-actions-app
path: ./dist/index.js
-entity_id: nPu5r1EndcM_D8TQfLk9c
+collection: syncedActionsAppColl1
+entity_id: syncedActionsAppEnt01
serdes/meta:
- model: DataApp
- id: nPu5r1EndcM_D8TQfLk9c
+ id: syncedActionsAppEnt01
label: synced-actions-app
diff --git a/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx b/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx
index 65b5641499e..37fe315eba6 100644
--- a/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx
+++ b/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx
@@ -1,14 +1,13 @@
import { useAction } from "@metabase/embedding-sdk-react/data-app";
import { useState } from "react";
-// @ts-expect-error generated at test time
import { CreateScore } from "../actions/orders.action";
/**
* Passes a source-controlled definition to `useAction` rather than a bare ID, so
- * a production build executes whatever `sync-resources` wrote into it — the copy
+ * a production build executes the copy its `copiedActionEntityId` names, the one
* the app's own group is permitted to run. The spec that drives this app writes
- * `actions/orders.action.ts` before synchronizing.
+ * `actions/orders.action.ts` and the app's collection files before publishing it.
*/
export default function App() {
const action = useAction(CreateScore);
diff --git a/e2e/support/assets/data-apps/synced-app/data_app.yaml b/e2e/support/assets/data-apps/synced-app/data_app.yaml
index 3e282a17794..d9f8fd7e08c 100644
--- a/e2e/support/assets/data-apps/synced-app/data_app.yaml
+++ b/e2e/support/assets/data-apps/synced-app/data_app.yaml
@@ -2,8 +2,9 @@ version: 1
name: Synced App
slug: synced-app
path: ./dist/index.js
-entity_id: 4vxutiAe703DZgttXwORO
+collection: syncedAppCollection01
+entity_id: syncedAppEntityId0001
serdes/meta:
- model: DataApp
- id: 4vxutiAe703DZgttXwORO
+ id: syncedAppEntityId0001
label: synced-app
diff --git a/e2e/support/assets/data-apps/synced-app/src/App.tsx b/e2e/support/assets/data-apps/synced-app/src/App.tsx
index efd45bb0685..59f5861dcf8 100644
--- a/e2e/support/assets/data-apps/synced-app/src/App.tsx
+++ b/e2e/support/assets/data-apps/synced-app/src/App.tsx
@@ -4,8 +4,9 @@ import { OrdersCount } from "../queries/orders.query";
/**
* Consumes a source-controlled query rather than an inline one, so a production
- * build runs whatever `sync-resources` wrote into the declaration. The spec that
- * drives this app writes `queries/orders.query.ts` before synchronizing.
+ * build runs the saved question its `savedQuestionEntityId` names. The spec that
+ * drives this app writes `queries/orders.query.ts` and the app's collection files
+ * before publishing it.
*/
export default function App() {
const orders = useMetabaseQuery(OrdersCount);
diff --git a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app.yaml b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app.yaml
new file mode 100644
index 00000000000..2c851a85b49
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app.yaml
@@ -0,0 +1,7 @@
+name: 'Data App: Good App'
+namespace: data-apps
+entity_id: goodAppCollection0000
+serdes/meta:
+- id: goodAppCollection0000
+ label: data_app__good_app
+ model: Collection
diff --git a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app/orders_goodAppOrdersQuestion.yaml b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app/orders_goodAppOrdersQuestion.yaml
new file mode 100644
index 00000000000..bf1dcb45781
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app/orders_goodAppOrdersQuestion.yaml
@@ -0,0 +1,20 @@
+name: Orders
+entity_id: goodAppOrdersQuestion
+type: question
+display: table
+collection_id: goodAppCollection0000
+creator_id: [email protected]
+dataset_query:
+ lib/type: mbql/query
+ database: Sample Database
+ stages:
+ - lib/type: mbql.stage/mbql
+ source-table:
+ - Sample Database
+ - PUBLIC
+ - ORDERS
+visualization_settings: {}
+serdes/meta:
+- id: goodAppOrdersQuestion
+ label: orders
+ model: Card
diff --git a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__second_app.yaml b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__second_app.yaml
new file mode 100644
index 00000000000..021da477763
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__second_app.yaml
@@ -0,0 +1,7 @@
+name: 'Data App: Second App'
+namespace: data-apps
+entity_id: secondAppCollection00
+serdes/meta:
+- id: secondAppCollection00
+ label: data_app__second_app
+ model: Collection
diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml b/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml
index 712c4c8a6c4..35501aabdb2 100644
--- a/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml
+++ b/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml
@@ -3,6 +3,7 @@ name: Good App
slug: good
description: A well-formed app that syncs cleanly
path: ./index.js
+collection: goodAppCollection0000
entity_id: Ioxf30LzIQCGwbCNtaG62
serdes/meta:
- model: DataApp
diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/second-app/data_app.yaml b/e2e/support/assets/example_synced_data_apps/data_apps/second-app/data_app.yaml
index 57d564db974..13dc4a3b727 100644
--- a/e2e/support/assets/example_synced_data_apps/data_apps/second-app/data_app.yaml
+++ b/e2e/support/assets/example_synced_data_apps/data_apps/second-app/data_app.yaml
@@ -2,6 +2,7 @@ version: 1
name: Second App
slug: second-app
path: ./index.js
+collection: secondAppCollection00
entity_id: A-0Jd9Jt80EIbt1hOavWS
serdes/meta:
- model: DataApp
diff --git a/e2e/support/config.js b/e2e/support/config.js
index 1ac44b282f6..ba2c83ca9ab 100644
--- a/e2e/support/config.js
+++ b/e2e/support/config.js
@@ -32,10 +32,7 @@ import {
} from "./helpers/e2e-custom-viz-dev-server-tasks";
import {
buildDataApp,
- removeDataAppDeclaration,
removeDataAppPaths,
- scaffoldDataApp,
- syncDataApp,
writeDataAppFiles,
} from "./helpers/e2e-data-app-tasks";
import { signJwt } from "./helpers/e2e-jwt-tasks";
@@ -315,10 +312,7 @@ const defaultConfig = {
startCustomVizDevServer,
stopCustomVizDevServer,
buildDataApp,
- syncDataApp,
- scaffoldDataApp,
writeDataAppFiles,
- removeDataAppDeclaration,
removeDataAppPaths,
...perTestCaptureTasks,
});
diff --git a/e2e/support/cypress_sample_instance_data.js b/e2e/support/cypress_sample_instance_data.js
index 9872ce801b0..63c10eb96a6 100644
--- a/e2e/support/cypress_sample_instance_data.js
+++ b/e2e/support/cypress_sample_instance_data.js
@@ -28,6 +28,11 @@ export const ORDERS_COUNT_QUESTION_ID = _.findWhere(
{ name: "Orders, Count" },
).id;
+export const ORDERS_COUNT_QUESTION_ENTITY_ID = _.findWhere(
+ SAMPLE_INSTANCE_DATA.questions,
+ { name: "Orders, Count" },
+).entity_id;
+
export const ORDERS_BY_YEAR_QUESTION_ID = _.findWhere(
SAMPLE_INSTANCE_DATA.questions,
{ name: "Orders, Count, Grouped by Created At (year)" },
diff --git a/e2e/support/helpers/api/createApiKey.ts b/e2e/support/helpers/api/createApiKey.ts
index ad4e581deac..ce2b5eb55f4 100644
--- a/e2e/support/helpers/api/createApiKey.ts
+++ b/e2e/support/helpers/api/createApiKey.ts
@@ -1,5 +1,7 @@
+import type { CreateApiKeyResponse } from "metabase-types/api";
+
export const createApiKey = (name: string, group_id: number) => {
- return cy.request("POST", "/api/api-key", {
+ return cy.request<CreateApiKeyResponse>("POST", "/api/api-key", {
name,
group_id,
});
diff --git a/e2e/support/helpers/build-data-app-fixture.mjs b/e2e/support/helpers/build-data-app-fixture.mjs
index 1d18213b3fe..32a9a0bc397 100644
--- a/e2e/support/helpers/build-data-app-fixture.mjs
+++ b/e2e/support/helpers/build-data-app-fixture.mjs
@@ -61,5 +61,11 @@ await build({
...buildInfoDefine,
"process.env.IS_EMBEDDING_SDK": '"true"',
},
- plugins: dataAppConfig().plugins,
+ // A fixture's definitions come from `testEnv` or from files a spec writes, so
+ // the resource check that guards an author's build is covered by the resource
+ // specs instead. `dataAppConfig` nests its plugins in an array, so flatten
+ // before filtering.
+ plugins: dataAppConfig()
+ .plugins.flat(Infinity)
+ .filter((plugin) => plugin?.name !== "metabase-resource-check"),
});
diff --git a/e2e/support/helpers/data-app-fixture-paths.mjs b/e2e/support/helpers/data-app-fixture-paths.mjs
index d66d35de330..fcdf0fd950c 100644
--- a/e2e/support/helpers/data-app-fixture-paths.mjs
+++ b/e2e/support/helpers/data-app-fixture-paths.mjs
@@ -15,11 +15,6 @@ export const DATA_APP_BUILD_SCRIPT = path.join(
"e2e/support/helpers/build-data-app-fixture.mjs",
);
-export const DATA_APP_SYNC_SCRIPT = path.join(
- REPO_ROOT,
- "e2e/support/helpers/sync-data-app-fixture.mjs",
-);
-
export const SDK_DATA_APP_DEV_CONFIG_SOURCE = path.join(
REPO_ROOT,
"enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.ts",
diff --git a/e2e/support/helpers/data-app-test-env.ts b/e2e/support/helpers/data-app-test-env.ts
index ca7a9a95648..4b6be4443f7 100644
--- a/e2e/support/helpers/data-app-test-env.ts
+++ b/e2e/support/helpers/data-app-test-env.ts
@@ -11,15 +11,15 @@
export type DataAppTestEnv = {
/**
* A deployed app runs the card its query was published as, so every query the
- * fixture renders names one. The swap drops the static clauses the card
- * already contains, so each id must match its whole authored query.
+ * fixture renders names one by entity ID. The swap drops the static clauses the
+ * card already contains, so each card must match its whole authored query.
*/
scalarQuery: {
source: TableSource;
aggregations: CountAggregation[];
- savedQuestionSourceId: number;
+ savedQuestionEntityId: string;
};
- questionQuery: { source: TableSource; savedQuestionSourceId: number };
+ questionQuery: { source: TableSource; savedQuestionEntityId: string };
/**
* `/download-question` page: the id of a saved CHART question (so a `.png`
* export is offered). Passed in because the id tracks the Cypress snapshot.
@@ -45,15 +45,22 @@ export type DataAppTestEnv = {
/**
* `/query-states` page: a deliberately invalid query (a card that does not
* exist), so the hook resolves to an `error` state rather than to the refusal
- * an unsynchronized query would raise; the page also exercises `refetch`.
+ * a query without a saved question would raise; the page also exercises
+ * `refetch`.
*/
- errorQuery?: { source: TableSource; savedQuestionSourceId: number };
+ errorQuery?: { source: TableSource; savedQuestionEntityId: string };
/**
* `/actions` page: the id of the action the spec creates and `useAction`
* executes, so it can't be hard-coded in the app. Left out to exercise the "no
* action id" path, where the hook must not request anything.
*/
actionId?: number;
+ /**
+ * `/actions` page: the entity ID of that action. A deployed app runs the copy
+ * its definition names by entity ID; this fixture has no collection files, so the
+ * "copy" is the action itself.
+ */
+ actionEntityId?: string;
/** `/actions` page: the parameters the page passes to `execute()`. */
actionParams?: Record<string, string | number>;
/**
diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.ts
index b516f582733..efb10d564b2 100644
--- a/e2e/support/helpers/e2e-data-app-helpers.ts
+++ b/e2e/support/helpers/e2e-data-app-helpers.ts
@@ -1,5 +1,9 @@
-import { USER_GROUPS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
+import { nanoid } from "@reduxjs/toolkit";
+import yaml from "js-yaml";
+
+import { USERS, USER_GROUPS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
import * as Urls from "metabase/urls/data-apps";
+import { NANOID_LENGTH } from "metabase-types/api";
import type {
Collection,
CollectionId,
@@ -7,13 +11,22 @@ import type {
CollectionPermissionsGraph,
DataApp,
Group,
+ RemoteSyncTask,
WritebackAction,
} from "metabase-types/api";
+import { isObject } from "metabase-types/guards";
-import { createTestNativeQuery } from "./api";
+import { createApiKey, createTestNativeQuery } from "./api";
import type { DataAppTestEnv } from "./data-app-test-env";
import { getIframeBody } from "./e2e-embedding-helpers";
-import { LOCAL_GIT_PATH } from "./e2e-remote-sync-helpers";
+import {
+ LOCAL_GIT_PATH,
+ commitToRepo,
+ configureGit,
+ configureGitAndPullChanges,
+ copySyncedCollectionFixture,
+ setupGitSync,
+} from "./e2e-remote-sync-helpers";
export const DATA_APP_NAME = "kitchen-sink";
export const DATA_APP_DISPLAY_NAME = "Kitchen Sink";
@@ -33,7 +46,6 @@ export const fakeDataApp = (overrides: Partial<DataApp> = {}): DataApp => ({
outdated: false,
bundle_path: "dist/index.js",
enabled: true,
- draft: false,
resource_collection_id: 1,
permission_group_id: null,
table_ids: [],
@@ -166,7 +178,7 @@ export function assertNoDataAppScopeDenials() {
expect(
scopeDenials,
`data-app scope rejections:\n${scopeDenials.join("\n")}`,
- ).to.be.empty;
+ ).to.deep.eq([]);
});
}
@@ -288,19 +300,14 @@ export function createDataAppScoreboardAction({
/**
* The dev host app is a real vite data app with the published SDK installed, so
- * synchronizing it exercises the package an author actually consumes rather than
- * the stub the scratch fixture provides.
+ * its CLI and build are the ones an author actually runs.
*/
export const dataAppHostAppRoot = () =>
`${Cypress.config("projectRoot")}/${DATA_APP_DEV_HOST_APP_DIR}`;
-const actionDeclarationsFile = (appRoot: string) =>
- `${appRoot}/actions/orders.action.ts`;
-
/**
- * Clears everything synchronization generates in the host app. Both sync specs
- * drive the same checked-in directory, so each has to start from a clean tree —
- * a stray `actions/` would otherwise be discovered by the query spec's sync.
+ * Clears what the resource specs write into the host app. They drive the same
+ * checked-in directory, so each has to start from a clean tree.
*/
export function resetDataAppHostAppSources() {
const appRoot = dataAppHostAppRoot();
@@ -309,80 +316,244 @@ export function resetDataAppHostAppSources() {
paths: [
`${appRoot}/queries`,
`${appRoot}/actions`,
- `${appRoot}/resources_metadata.json`,
+ `${appRoot}/collections`,
+ ],
+ });
+}
+
+/** A new entity ID, as `representations generate-entity-id` makes one for an author. */
+export const newEntityId = () => nanoid(NANOID_LENGTH);
+
+/**
+ * A table as serialized YAML references it: database, schema, and table name.
+ * The schema is null for a database without schemas.
+ */
+export type PortableTable = [
+ database: string,
+ schema: string | null,
+ table: string,
+];
+
+type ResourceEntity = Record<string, unknown>;
+
+/** The slug serialization labels an entity with, from its name: lowercase, every other character an underscore. */
+const slugOf = (name: string) =>
+ name.toLowerCase().replace(/[^\p{L}\p{N}_.]/gu, "_");
+
+const serdesMeta = (model: string, entityId: string, name: string) => [
+ { id: entityId, label: slugOf(name), model },
+];
+
+/** The app's collection: a root collection of the `data-apps` namespace. */
+const resourceCollection = (
+ entityId: string,
+ name: string,
+): ResourceEntity => ({
+ name,
+ namespace: "data-apps",
+ entity_id: entityId,
+ "serdes/meta": serdesMeta("Collection", entityId, name),
+});
+
+/**
+ * A card in the app's collection, as an author writes it: a saved question from a
+ * query definition, or a copy of a metric from the repository. `stage`
+ * holds the clauses besides the source table.
+ */
+const resourceCard = ({
+ entityId,
+ name,
+ type,
+ collection,
+ table,
+ stage = {},
+}: {
+ entityId: string;
+ name: string;
+ type: "question" | "metric";
+ collection: string;
+ table: PortableTable;
+ stage?: ResourceEntity;
+}): ResourceEntity => ({
+ name,
+ type,
+ display: type === "metric" ? "scalar" : "table",
+ entity_id: entityId,
+ collection_id: collection,
+ creator_id: USERS.admin.email,
+ dataset_query: {
+ "lib/type": "mbql/query",
+ database: table[0],
+ stages: [
+ { "lib/type": "mbql.stage/mbql", "source-table": table, ...stage },
],
+ },
+ visualization_settings: {},
+ "serdes/meta": serdesMeta("Card", entityId, name),
+});
+
+/**
+ * The copies of the actions `copies` name, as an author writes them into the
+ * app's collection: what Metabase serializes for each source action, with the
+ * copy's entity ID and in the app's `collection`.
+ */
+export function serializeDataAppActionCopies(
+ copies: Array<{ sourceActionId: number; entityId: string }>,
+ collection: string,
+) {
+ return cy
+ .request<{ actions: Array<{ entity: ResourceEntity }> }>(
+ "POST",
+ "/api/apps/serialize-resources",
+ {
+ collection,
+ actions: copies.map(({ sourceActionId }) => sourceActionId),
+ },
+ )
+ .then(({ body }) =>
+ cy.wrap(
+ copies.map(({ entityId }, index): ResourceEntity => {
+ const { entity } = body.actions[index];
+
+ return {
+ ...entity,
+ entity_id: entityId,
+ collection_id: collection,
+ "serdes/meta": serdesMeta("Action", entityId, String(entity.name)),
+ };
+ }),
+ { log: false },
+ ),
+ );
+}
+
+/**
+ * The YAML an author writes for an app's collection, in the Metabase
+ * representation format: plain data for `writeDataAppResources`, read from
+ * nothing and written nowhere by itself.
+ */
+export const dataAppRepresentations = {
+ collection: resourceCollection,
+ card: resourceCard,
+};
+
+const fileName = (entity: ResourceEntity) =>
+ `${slugOf(String(entity.name))}_${String(entity.entity_id)}.yaml`;
+
+/**
+ * Writes the files of an app's collection as YAML under `collections/data_apps/`
+ * of `root`, as serialization lays them out: the collection's own file beside
+ * a directory of its name that holds the cards and actions. `root` is the
+ * repository the app lives in, or the app itself when it stands alone, as the
+ * CLI reads them. Replaces what was there for that collection.
+ */
+export function writeDataAppResources(
+ root: string,
+ {
+ collection,
+ cards = [],
+ actions = [],
+ }: {
+ collection: ResourceEntity;
+ cards?: ResourceEntity[];
+ actions?: ResourceEntity[];
+ },
+) {
+ const collectionsDir = `${root}/collections/data_apps`;
+ const stem = slugOf(String(collection.name));
+ const collectionDir = `${collectionsDir}/${stem}`;
+
+ cy.task("removeDataAppPaths", {
+ paths: [`${collectionsDir}/${stem}.yaml`, collectionDir],
+ });
+
+ return cy.task("writeDataAppFiles", {
+ files: {
+ [`${collectionsDir}/${stem}.yaml`]: yaml.dump(collection),
+ ...Object.fromEntries(
+ [...cards, ...actions].map((entity) => [
+ `${collectionDir}/${fileName(entity)}`,
+ yaml.dump(entity),
+ ]),
+ ),
+ },
});
}
+/** Declares one `defineAction` per action, as the generated schema names it, with the ID of its copy. */
export function declareDataAppActions(
appRoot: string,
- sourceActionIds: number[],
+ actions: Array<{
+ exportName: string;
+ sourceActionId: number;
+ copiedActionEntityId: string;
+ }>,
) {
return cy.task("writeDataAppFiles", {
files: {
- [actionDeclarationsFile(appRoot)]: [
+ [`${appRoot}/actions/orders.action.ts`]: [
'import { defineAction } from "@metabase/embedding-sdk-react/data-app";',
- ...sourceActionIds.map(
- (id) =>
- `export const Action${id} = defineAction({ action: { id: ${id}, parameters: [] } });`,
+ ...actions.map(
+ ({ exportName, sourceActionId, copiedActionEntityId }) =>
+ `export const ${exportName} = defineAction({ copiedActionEntityId: "${copiedActionEntityId}", action: { id: ${sourceActionId}, parameters: [] } });`,
),
].join("\n"),
},
});
}
-const queryDeclarationsFile = (appRoot: string) =>
- `${appRoot}/queries/orders.query.ts`;
-
-/** Declares one `defineQuery` per entry, as an app author would. */
+/** Declares one `defineQuery` per entry, as an app author would, with the ID of its saved question. */
export function declareDataAppQueries(
appRoot: string,
- declarations: Array<{ name: string; tableId: number; limit?: number }>,
+ declarations: Array<{
+ name: string;
+ tableId: number;
+ savedQuestionEntityId: string;
+ metricId?: number;
+ }>,
) {
return cy.task("writeDataAppFiles", {
files: {
- [queryDeclarationsFile(appRoot)]: [
+ [`${appRoot}/queries/orders.query.ts`]: [
'import { defineQuery } from "@metabase/embedding-sdk-react/data-app";',
- ...declarations.map(({ name, tableId, limit }) => {
- const clauses = limit === undefined ? "" : `, limit: ${limit}`;
- return `export const ${name} = defineQuery({ source: { type: "table", id: ${tableId} }${clauses} });`;
- }),
+ ...declarations.map(
+ ({ name, tableId, savedQuestionEntityId, metricId }) => {
+ const clauses =
+ metricId === undefined
+ ? ""
+ : `, aggregations: [{ type: "metric", id: ${metricId} }]`;
+ return `export const ${name} = defineQuery({ savedQuestionEntityId: "${savedQuestionEntityId}", source: { type: "table", id: ${tableId} }${clauses} });`;
+ },
+ ),
].join("\n"),
},
});
}
/**
- * Deletes one declaration in place, so the rest keep the generated IDs
- * synchronization injected — which is what an author removing one does.
- * Splits on the declaration keyword rather than on lines, because an injected
- * ID lands on its own line and makes a declaration span several.
+ * Runs the data app CLI the host app has installed, the one an author runs:
+ * `embedding-sdk-react data-apps <command>`. `check-resources` never calls Metabase; `print-resources`
+ * reaches it through `env` (see `dataAppCliEnv`).
*/
-function removeDeclaration(filePath: string, exportName: string) {
- return cy.task("removeDataAppDeclaration", { filePath, exportName });
-}
-
-export function removeDataAppQueryDeclaration(appRoot: string, name: string) {
- return removeDeclaration(queryDeclarationsFile(appRoot), name);
-}
-
-export function removeDataAppActionDeclaration(
- appRoot: string,
- sourceActionId: number,
-) {
- return removeDeclaration(
- actionDeclarationsFile(appRoot),
- `Action${sourceActionId}`,
+export function runDataAppCli(command: string, env?: Record<string, string>) {
+ return cy.exec(
+ `cd "${dataAppHostAppRoot()}" && ./node_modules/.bin/embedding-sdk-react data-apps ${command}`,
+ { failOnNonZeroExit: false, timeout: 60_000, env },
);
}
-/** Runs the real `sync-resources` CLI against the instance under test. */
-export function syncDataAppResources(apiKey: string, appRoot: string) {
- return cy.task<{ ok: boolean; error: string | null }>("syncDataApp", {
- appRoot,
- metabaseUrl: Cypress.config("baseUrl"),
- apiKey,
- });
+/**
+ * The instance and an admin API key a data-app command reaches Metabase with,
+ * as the environment variables `.env.local` would otherwise hold.
+ */
+export function dataAppCliEnv() {
+ return createApiKey(
+ `data-app-cli-e2e-${Date.now()}`,
+ USER_GROUPS.ADMIN_GROUP,
+ ).then(({ body }) => ({
+ DATA_APP_MB_URL: String(Cypress.config("baseUrl")),
+ DATA_APP_MB_API_KEY: body.unmasked_key,
+ }));
}
export const copySyncedDataAppsFixture = () =>
@@ -391,50 +562,166 @@ export const copySyncedDataAppsFixture = () =>
destination: LOCAL_GIT_PATH,
});
-/** The test repo is not an npm project, so `defineQuery` needs a stub to resolve. */
-export function declareSyncedDataAppQuery(slug: string, tableId: number) {
- const appRoot = `${LOCAL_GIT_PATH}/data_apps/${slug}`;
- const packageRoot = `${appRoot}/node_modules/@metabase/embedding-sdk-react`;
+/**
+ * Pulls `example_synced_data_apps` through a real remote-sync import, so a spec
+ * gets real app rows, each with its resource collection and permission group.
+ * Both `good` and `second-app` are served. `goodAppCards` replaces the
+ * `good` app's saved questions, so a spec decides which tables it reads.
+ */
+export function pullExampleDataApps({
+ goodAppCards,
+}: { goodAppCards?: ResourceEntity[] } = {}) {
+ setupGitSync();
+ copySyncedCollectionFixture();
+ copySyncedDataAppsFixture();
+ if (goodAppCards) {
+ writeDataAppResources(LOCAL_GIT_PATH, {
+ collection: resourceCollection(
+ "goodAppCollection0000",
+ "Data App: Good App",
+ ),
+ cards: goodAppCards,
+ });
+ }
+ commitToRepo("Add data apps");
+ configureGitAndPullChanges("read-write");
+}
- return cy.task("writeDataAppFiles", {
- files: {
- [`${packageRoot}/package.json`]: JSON.stringify({
- name: "@metabase/embedding-sdk-react",
- exports: { "./data-app": "./data-app.js" },
- }),
- [`${packageRoot}/data-app.js`]: "exports.defineQuery = (q) => q;",
- [`${appRoot}/queries/orders.query.ts`]: [
- 'import { defineQuery } from "@metabase/embedding-sdk-react/data-app";',
- `export const Orders = defineQuery({ source: { type: "table", id: ${tableId} } });`,
- "",
- ].join("\n"),
- },
+/** A data app whose resources loaded: it has its collection and its permission group. */
+export type SyncedDataApp = DataApp & {
+ resource_collection_id: number;
+ permission_group_id: number;
+};
+
+/** The host app's checked-in `data_app.yaml`, as serialization reads it. */
+export const DATA_APP_HOST_APP_MANIFEST = `version: 1
+name: Vite 6 Data App
+slug: vite-6-data-app-host-app
+path: ./dist/index.js
+allowed_hosts:
+ - https://allowed.data-app.test
+entity_id: qxpaPkU_WRE2ZQu0cmpqD
+serdes/meta:
+- model: DataApp
+ id: qxpaPkU_WRE2ZQu0cmpqD
+ label: vite-6-data-app-host-app
+`;
+
+const isSyncedDataApp = (app: DataApp): app is SyncedDataApp =>
+ typeof app.resource_collection_id === "number" &&
+ typeof app.permission_group_id === "number";
+
+/**
+ * Writes the app's manifest into the sync repository as `data_apps/<slug>`, makes
+ * the repository's `collections/data_apps/` what the host app holds, and
+ * commits them, as an author does. The bundle is a placeholder, since specs
+ * serve the built one through `mockDataApp`. Pass `initializeRepo: false` to
+ * write into the repository an earlier call set up.
+ */
+function commitDataApp(
+ appRoot: string,
+ slug: string,
+ { initializeRepo = true }: { initializeRepo?: boolean } = {},
+) {
+ const appDir = `${LOCAL_GIT_PATH}/data_apps/${slug}`;
+ const collectionsDir = `${LOCAL_GIT_PATH}/collections/data_apps`;
+
+ if (initializeRepo) {
+ setupGitSync();
+ copySyncedCollectionFixture();
+ }
+ // A copy only adds, so a file the author deleted would stay in the repository.
+ cy.task("removeDataAppPaths", { paths: [collectionsDir] });
+ cy.task("copyDirectory", {
+ source: `${appRoot}/collections/data_apps`,
+ destination: collectionsDir,
+ });
+ cy.readFile(`${appRoot}/data_app.yaml`).then((manifest: string) =>
+ cy.task("writeDataAppFiles", {
+ files: {
+ [`${appDir}/data_app.yaml`]: manifest,
+ [`${appDir}/dist/index.js`]: "// served by the spec",
+ },
+ }),
+ );
+ commitToRepo(`Publish ${slug}`);
+}
+
+/**
+ * Publishes the app with a pull and yields it once its resources loaded: with
+ * its collection and its permission group, which the admin list carries.
+ */
+export function publishDataApp(
+ appRoot: string,
+ slug: string,
+ options?: { initializeRepo?: boolean },
+) {
+ commitDataApp(appRoot, slug, options);
+ configureGitAndPullChanges("read-write");
+
+ return cy.request<DataApp[]>("/api/apps").then(({ body: apps }) => {
+ const app = apps.find(({ name }) => name === slug);
+
+ if (!app) {
+ throw new Error(`The pull loaded no data app named ${slug}.`);
+ }
+ if (!isSyncedDataApp(app)) {
+ throw new Error(
+ `Data app ${slug} loaded without its resource collection or group.`,
+ );
+ }
+
+ return cy.wrap(app, { log: false });
});
}
-export function createDataAppApiKey() {
+const IMPORT_POLL_LIMIT = 120;
+
+/** Yields the error of the import that is running or just ran, once it fails. */
+function waitForImportError(retries = 0): Cypress.Chainable<string> {
+ if (retries > IMPORT_POLL_LIMIT) {
+ throw new Error("The import did not fail in time.");
+ }
+
return cy
- .request<{ unmasked_key: string }>("POST", "/api/api-key", {
- name: `data-app-sync-e2e-${Date.now()}`,
- group_id: USER_GROUPS.ADMIN_GROUP,
- })
- .then(({ body }) => body.unmasked_key);
+ .request<RemoteSyncTask | null>("/api/ee/remote-sync/current-task")
+ .then(({ body }) => {
+ if (body?.sync_task_type === "import" && body.status === "errored") {
+ return cy.wrap(body.error_message ?? "", { log: false });
+ }
+
+ if (body?.sync_task_type === "import" && body.status === "successful") {
+ throw new Error(
+ "The import succeeded, but its resources should have been refused.",
+ );
+ }
+
+ cy.wait(500);
+ return waitForImportError(retries + 1);
+ });
}
/**
- * A second app beside the host app, for cases that need two of them. It reuses
- * the host app's `node_modules`, so `defineQuery` still resolves through the
- * published SDK, and its manifest declares `slug` as its slug.
+ * Publishes an app whose resource files the pull is expected to refuse, and
+ * yields the pull's error. A refused file fails the whole pull, so nothing of
+ * the app loads.
*/
-export function createSecondDataApp(slug: string) {
- cy.task("scaffoldDataApp", { appName: slug, sdkFrom: dataAppHostAppRoot() });
+export function publishDataAppExpectingRefusal(
+ appRoot: string,
+ slug: string,
+ options?: { initializeRepo?: boolean },
+) {
+ commitDataApp(appRoot, slug, options);
+ configureGit("read-write");
+ cy.request("POST", "/api/ee/remote-sync/import", { expected_branch: "main" });
- return `${Cypress.config("projectRoot")}/e2e/tmp/${slug}`;
+ return waitForImportError();
}
/**
- * Runs the host app's own production build. The SDK's `metabase-resource-sync-check`
- * plugin runs on `buildStart`, so this is what refuses to bundle a stale app.
+ * Runs the host app's own production build. The SDK's `metabase-resource-check`
+ * plugin runs on `buildStart`, so this is what refuses to bundle an app whose
+ * collection files don't back its definitions.
*/
export function buildDataAppHostApp() {
return cy.exec(`cd "${dataAppHostAppRoot()}" && npm run build`, {
@@ -443,20 +730,6 @@ export function buildDataAppHostApp() {
});
}
-/** The app's own permission group — the one its viewers are given. */
-export function dataAppPermissionGroupId(slug: string) {
- return cy.request<DataApp>(`/api/apps/${slug}`).then(({ body }) => {
- const groupId = body.permission_group_id;
-
- if (typeof groupId !== "number") {
- throw new Error(`Data app ${slug} has no permission group.`);
- }
-
- return cy.wrap(groupId, { log: false });
- });
-}
-
-/** Puts a user in the app's own permission group, as granting app access does. */
const DATA_APP_DEV_HOST_APP_DIR =
"e2e/embedding-sdk-host-apps/vite-6-data-app-host-app";
@@ -539,3 +812,53 @@ function waitForDataAppDevServerEnv(
);
});
}
+
+/**
+ * The `/* metadata: {...} *\/` block of the generated typed-schema entry that
+ * opens with `entry` (its first match): the one at the entry's own depth, not
+ * a nested entity's.
+ */
+export function typedSchemaMetadata(
+ body: string,
+ entry: string,
+): Record<string, unknown> {
+ const lines = body.split("\n");
+ const start = lines.findIndex((line) => line.trim() === entry);
+ if (start === -1) {
+ throw new Error(`The typed schema has no entry \`${entry}\`.`);
+ }
+ const indent = lines[start].search(/\S/);
+ // The entry's closing brace, so a sibling's block is never mistaken for its own.
+ const end = lines.findIndex(
+ (line, index) =>
+ index > start &&
+ line.search(/\S/) === indent &&
+ line.trimStart().startsWith("}"),
+ );
+ const blockStart = lines.findIndex(
+ (line, index) =>
+ index > start &&
+ index < end &&
+ line.search(/\S/) === indent + 2 &&
+ line.trimStart().startsWith("/* metadata: "),
+ );
+ if (blockStart === -1) {
+ throw new Error(`The typed schema has no metadata for \`${entry}\`.`);
+ }
+ const blockEnd = lines.findIndex(
+ (line, index) => index >= blockStart && line.trimEnd().endsWith(" */"),
+ );
+ const block = lines
+ .slice(blockStart, blockEnd + 1)
+ .join("\n")
+ .trim();
+
+ const metadata: unknown = JSON.parse(
+ block.slice("/* metadata: ".length, block.length - " */".length),
+ );
+ if (!isObject(metadata)) {
+ throw new Error(`The metadata of \`${entry}\` is not an object.`);
+ }
+
+ return metadata;
+}
diff --git a/e2e/support/helpers/e2e-data-app-tasks.ts b/e2e/support/helpers/e2e-data-app-tasks.ts
index da800cc0f66..af56e9e5417 100644
--- a/e2e/support/helpers/e2e-data-app-tasks.ts
+++ b/e2e/support/helpers/e2e-data-app-tasks.ts
@@ -5,7 +5,6 @@ import path from "node:path";
import {
DATA_APP_BUILD_SCRIPT,
DATA_APP_FIXTURES_DIR,
- DATA_APP_SYNC_SCRIPT,
REPO_ROOT,
} from "./data-app-fixture-paths.mjs";
@@ -40,29 +39,6 @@ function run(script: string, args: string[], env: NodeJS.ProcessEnv = {}) {
});
}
-export async function syncDataApp({
- appRoot,
- metabaseUrl,
- apiKey,
-}: {
- appRoot: string;
- metabaseUrl: string;
- apiKey: string;
-}): Promise<{ ok: boolean; error: string | null }> {
- try {
- await run(DATA_APP_SYNC_SCRIPT, [appRoot], {
- DATA_APP_MB_URL: metabaseUrl,
- DATA_APP_MB_API_KEY: apiKey,
- });
- return { ok: true, error: null };
- } catch (error) {
- return {
- ok: false,
- error: error instanceof Error ? error.message : String(error),
- };
- }
-}
-
export async function buildDataApp({
appName,
}: {
@@ -97,35 +73,6 @@ function inRepo(target: string) {
* so a spec changes an app in one round trip, and so nothing is composed into a
* shell string.
*/
-export async function scaffoldDataApp({
- appName,
- sdkFrom,
-}: {
- appName: string;
- sdkFrom: string;
-}): Promise<string> {
- // The task owns the location so a caller cannot aim the `rmSync` below elsewhere.
- if (path.basename(appName) !== appName) {
- throw new Error(`A scaffolded app is named, not located: ${appName}`);
- }
-
- const root = path.join(REPO_ROOT, "e2e", "tmp", appName);
-
- fs.rmSync(root, { recursive: true, force: true });
- fs.mkdirSync(root, { recursive: true });
- // The SDK the app synchronizes against, without a second npm install.
- fs.symlinkSync(
- path.join(inRepo(sdkFrom), "node_modules"),
- path.join(root, "node_modules"),
- );
- fs.writeFileSync(
- path.join(root, "data_app.yaml"),
- `name: ${appName}\nslug: ${appName}\npath: ./dist/index.js\n`,
- );
-
- return root;
-}
-
export async function writeDataAppFiles({
files,
}: {
@@ -141,30 +88,6 @@ export async function writeDataAppFiles({
return null;
}
-export async function removeDataAppDeclaration({
- filePath,
- exportName,
-}: {
- filePath: string;
- exportName: string;
-}): Promise<null> {
- const target = inRepo(filePath);
- const [imports, ...declarations] = fs
- .readFileSync(target, "utf8")
- .split("export const ");
-
- fs.writeFileSync(
- target,
- imports +
- declarations
- .filter((declaration) => !declaration.startsWith(`${exportName} `))
- .map((declaration) => `export const ${declaration}`)
- .join(""),
- );
-
- return null;
-}
-
export async function removeDataAppPaths({
paths,
}: {
diff --git a/e2e/support/helpers/e2e-remote-sync-helpers.ts b/e2e/support/helpers/e2e-remote-sync-helpers.ts
index 24504552d16..acf731edc34 100644
--- a/e2e/support/helpers/e2e-remote-sync-helpers.ts
+++ b/e2e/support/helpers/e2e-remote-sync-helpers.ts
@@ -351,7 +351,10 @@ export const closeSyncResultModal = () => {
cy.findByTestId("sync-success-close-button").click();
};
-const TASK_POLL_LIMIT = 30;
+// An import's first native SQL parse starts the Python parser, which on a slow runner takes longer than the
+// fifteen seconds thirty polls allow. Giving up while the import still runs is worse than waiting: a retry
+// restores the app DB under the live import, which then dies on a closed connection.
+const TASK_POLL_LIMIT = 120;
export const waitForTask = (
{ taskName }: { taskName: "import" | "export" },
diff --git a/e2e/support/helpers/sync-data-app-fixture.mjs b/e2e/support/helpers/sync-data-app-fixture.mjs
deleted file mode 100644
index 517b446f725..00000000000
--- a/e2e/support/helpers/sync-data-app-fixture.mjs
+++ /dev/null
@@ -1,50 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-import { pathToFileURL } from "node:url";
-
-import { build as bundle } from "esbuild";
-
-import { DATA_APP_FIXTURES_DIR, REPO_ROOT } from "./data-app-fixture-paths.mjs";
-
-const appRoot = process.argv[2];
-if (!appRoot) {
- console.error("usage: sync-data-app-fixture.mjs <appRoot>");
- process.exit(2);
-}
-
-const { DATA_APP_MB_URL, DATA_APP_MB_API_KEY } = process.env;
-if (!DATA_APP_MB_URL || !DATA_APP_MB_API_KEY) {
- console.error("DATA_APP_MB_URL and DATA_APP_MB_API_KEY must be set");
- process.exit(2);
-}
-
-const SDK_PACKAGE_DIR = path.join(
- REPO_ROOT,
- "enterprise/frontend/src/embedding-sdk-package",
-);
-
-const scratchDir = path.join(DATA_APP_FIXTURES_DIR, ".build");
-fs.mkdirSync(scratchDir, { recursive: true });
-const entry = path.join(scratchDir, "sync-resources.mjs");
-
-// The synchronization sources are TypeScript and reach the SDK package by its
-// build alias, so bundle them the way the fixture build does before importing.
-await bundle({
- entryPoints: [path.join(SDK_PACKAGE_DIR, "data-app-query-sync/sync.ts")],
- outfile: entry,
- bundle: true,
- platform: "node",
- format: "esm",
- packages: "external",
- alias: { "embedding-sdk-package": SDK_PACKAGE_DIR },
- logLevel: "warning",
-});
-
-const { syncResources } = await import(pathToFileURL(entry).href);
-
-await syncResources({
- appRoot,
- metabaseUrl: DATA_APP_MB_URL,
- apiKey: DATA_APP_MB_API_KEY,
- log: (message) => console.log(`[sync-resources] ${message}`),
-});
diff --git a/e2e/support/timings.json b/e2e/support/timings.json
index 478f821e669..c1560f2d935 100644
--- a/e2e/support/timings.json
+++ b/e2e/support/timings.json
@@ -553,11 +553,11 @@
"duration": 1127
},
{
- "spec": "../test/scenarios/data-apps/sync-resources-production-actions.cy.spec.ts",
+ "spec": "../test/scenarios/data-apps/resources-production-actions.cy.spec.ts",
"duration": 14247
},
{
- "spec": "../test/scenarios/data-apps/sync-resources-production.cy.spec.ts",
+ "spec": "../test/scenarios/data-apps/resources-production.cy.spec.ts",
"duration": 15285
},
{
diff --git a/e2e/test-host-app/data-apps/resources-actions.cy.spec.ts b/e2e/test-host-app/data-apps/resources-actions.cy.spec.ts
new file mode 100644
index 00000000000..a5823cb9261
--- /dev/null
+++ b/e2e/test-host-app/data-apps/resources-actions.cy.spec.ts
@@ -0,0 +1,179 @@
+import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
+import type { WritebackAction } from "metabase-types/api";
+
+const { H } = cy;
+
+const TEST_TABLE = "scoreboard_actions";
+
+/** The app is published under its directory's name. */
+const APP_SLUG = "vite-6-data-app-host-app";
+
+const APP_ROOT = () => H.dataAppHostAppRoot();
+const MANIFEST_FILE = () => `${APP_ROOT()}/data_app.yaml`;
+
+const COLLECTION = "hostAppCollection0002";
+
+const SCORE = { team_name: "Data App FC", score: 7 };
+
+type Copy = { source: WritebackAction; entityId: string; exportName: string };
+
+/**
+ * Loads actions into an app the way an author does: the source actions exist
+ * in Metabase, belonging to no model, and the author copies what Metabase
+ * serializes for them into the app's collection with new entity IDs. A
+ * repository pull is what creates the copies.
+ */
+describe(
+ "Embedding SDK: data-app resources (actions)",
+ { tags: ["@external", "@actions"] },
+ () => {
+ beforeEach(() => {
+ H.restore("postgres-writable");
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+
+ H.resetTestTable({ type: "postgres", table: TEST_TABLE });
+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEST_TABLE });
+ H.setActionsEnabledForDB(WRITABLE_DB_ID);
+
+ // The specs share a checked-in host app, so start from a clean tree.
+ H.resetDataAppHostAppSources();
+ cy.writeFile(
+ MANIFEST_FILE(),
+ `${H.DATA_APP_HOST_APP_MANIFEST}collection: ${COLLECTION}\n`,
+ );
+ });
+
+ // Leave the checked-in host app as it was.
+ after(() => {
+ H.resetDataAppHostAppSources();
+ cy.writeFile(MANIFEST_FILE(), H.DATA_APP_HOST_APP_MANIFEST);
+ });
+
+ /** Declares `copies` and writes them, changed by `edit`, into the app's collection. */
+ const writeCopies = (
+ copies: Copy[],
+ edit: (copy: Record<string, unknown>) => Record<string, unknown> = (
+ copy,
+ ) => copy,
+ ) => {
+ H.declareDataAppActions(
+ APP_ROOT(),
+ copies.map(({ source, entityId, exportName }) => ({
+ exportName,
+ sourceActionId: source.id,
+ copiedActionEntityId: entityId,
+ })),
+ );
+
+ return H.serializeDataAppActionCopies(
+ copies.map(({ source, entityId }) => ({
+ sourceActionId: source.id,
+ entityId,
+ })),
+ COLLECTION,
+ ).then((actions) =>
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: H.dataAppRepresentations.collection(
+ COLLECTION,
+ "Data App: Vite 6 Data App",
+ ),
+ actions: actions.map(edit),
+ }),
+ );
+ };
+
+ /** Two source actions that belong to no model, with a copy of each written. */
+ const copyTwoActions = () =>
+ H.createDataAppScoreboardAction({ name: "Add team" }).then((add) =>
+ H.createDataAppScoreboardAction({ name: "Add rival" }).then((rival) => {
+ const copies: [Copy, Copy] = [
+ { source: add, entityId: H.newEntityId(), exportName: "AddTeam" },
+ {
+ source: rival,
+ entityId: H.newEntityId(),
+ exportName: "AddRival",
+ },
+ ];
+
+ writeCopies(copies);
+
+ return cy.wrap(copies, { log: false });
+ }),
+ );
+
+ /** Which of the copies with `entityIds` Metabase holds. */
+ const copiesLoaded = (entityIds: string[]) =>
+ cy
+ .request<WritebackAction[]>("/api/action")
+ .then(({ body }) =>
+ body
+ .map((action) => action.entity_id)
+ .filter((entityId) => entityIds.includes(entityId)),
+ );
+
+ it("lets the app's group execute a published copy but not the action it was copied from", () => {
+ copyTwoActions().then(([{ source, entityId }]) => {
+ // A user whose groups read no collection: the copy is reachable through
+ // the app's group alone, and the source action, in the root collection,
+ // through none of them.
+ H.publishDataApp(APP_ROOT(), APP_SLUG).then((app) => {
+ H.addUserToGroup(app.permission_group_id, USERS.nocollection.email);
+ });
+
+ cy.signIn("nocollection");
+ cy.request({
+ method: "POST",
+ url: `/api/action/${entityId}/execute`,
+ body: { parameters: SCORE },
+ })
+ .its("status")
+ .should("be.oneOf", [200, 204]);
+
+ cy.request({
+ method: "POST",
+ url: `/api/action/${source.id}/execute`,
+ body: { parameters: SCORE },
+ failOnStatusCode: false,
+ })
+ .its("status")
+ .should("eq", 403);
+ });
+ });
+
+ it("deletes a copied action on the next pull once its file is gone", () => {
+ copyTwoActions().then(([kept, removed]) => {
+ const entityIds = [kept.entityId, removed.entityId];
+
+ H.publishDataApp(APP_ROOT(), APP_SLUG);
+ copiesLoaded(entityIds).should("have.members", entityIds);
+
+ writeCopies([kept]);
+ H.publishDataApp(APP_ROOT(), APP_SLUG, { initializeRepo: false });
+
+ copiesLoaded(entityIds).should("deep.equal", [kept.entityId]);
+ });
+ });
+
+ it("refuses a copy of an action that belongs to a model, and loads none of them", () => {
+ copyTwoActions().then((copies) => {
+ const [first] = copies;
+
+ // A data app runs only actions that belong to no model.
+ writeCopies(copies, (copy) =>
+ copy.entity_id === first.entityId
+ ? { ...copy, model_id: H.newEntityId() }
+ : copy,
+ );
+
+ H.publishDataAppExpectingRefusal(APP_ROOT(), APP_SLUG).then((error) => {
+ expect(error).to.contain("must belong to no model");
+ copiesLoaded(copies.map(({ entityId }) => entityId)).should(
+ "deep.equal",
+ [],
+ );
+ });
+ });
+ });
+ },
+);
diff --git a/e2e/test-host-app/data-apps/resources.cy.spec.ts b/e2e/test-host-app/data-apps/resources.cy.spec.ts
new file mode 100644
index 00000000000..7ce06e6905d
--- /dev/null
+++ b/e2e/test-host-app/data-apps/resources.cy.spec.ts
@@ -0,0 +1,303 @@
+import { USERS } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { PortableTable } from "e2e/support/helpers";
+import type { Card, CollectionItem } from "metabase-types/api";
+
+const { H } = cy;
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+/** The app is published under its directory's name. */
+const APP_SLUG = "vite-6-data-app-host-app";
+
+const APP_ROOT = () => H.dataAppHostAppRoot();
+const MANIFEST_FILE = () => `${APP_ROOT()}/data_app.yaml`;
+
+const COLLECTION = "hostAppCollection0001";
+
+const ORDERS_TABLE: PortableTable = ["Sample Database", "PUBLIC", "ORDERS"];
+
+const collection = () =>
+ H.dataAppRepresentations.collection(COLLECTION, "Data App: Vite 6 Data App");
+
+/** The saved question an author writes for a plain `Orders` definition. */
+const ordersQuestion = (entityId: string, stage = {}) =>
+ H.dataAppRepresentations.card({
+ entityId,
+ name: "Orders",
+ type: "question",
+ collection: COLLECTION,
+ table: ORDERS_TABLE,
+ stage,
+ });
+
+const metricAggregation = (metric: string) => ({
+ aggregation: [["metric", { "lib/uuid": crypto.randomUUID() }, metric]],
+});
+
+/**
+ * Runs the app's resources end to end against the dev host app, a real vite
+ * data app with the published SDK installed: the CLI an author runs, the build
+ * guard, and the repository pull that loads what the author wrote.
+ */
+describe("Embedding SDK: data-app resources (queries)", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+
+ // The specs share a checked-in host app, so start from a clean tree.
+ H.resetDataAppHostAppSources();
+ cy.writeFile(
+ MANIFEST_FILE(),
+ `${H.DATA_APP_HOST_APP_MANIFEST}collection: ${COLLECTION}\n`,
+ );
+ });
+
+ // Leave the checked-in host app as it was.
+ after(() => {
+ H.resetDataAppHostAppSources();
+ cy.writeFile(MANIFEST_FILE(), H.DATA_APP_HOST_APP_MANIFEST);
+ });
+
+ describe("the CLI", () => {
+ it("prints the query Metabase builds from a definition, as an author writes the saved question from it", () => {
+ const question = H.newEntityId();
+ H.declareDataAppQueries(APP_ROOT(), [
+ { name: "Orders", tableId: ORDERS_ID, savedQuestionEntityId: question },
+ ]);
+
+ H.dataAppCliEnv().then((env) =>
+ H.runDataAppCli("print-resources", env).then(({ exitCode, stdout }) => {
+ expect(exitCode, stdout).to.eq(0);
+ const printed = JSON.parse(stdout);
+ expect(printed).to.deep.include({
+ actions: [],
+ metrics: [],
+ });
+ const [query] = printed.queries;
+ expect(query).to.deep.include({
+ export: "Orders",
+ file: "queries/orders.query.ts",
+ savedQuestionEntityId: question,
+ metrics: [],
+ });
+ // The saved question is complete: the author writes it as it is.
+ expect(query.entity).to.deep.include({
+ entity_id: question,
+ collection_id: COLLECTION,
+ name: "Orders",
+ type: "question",
+ display: "table",
+ dataset_query: {
+ "lib/type": "mbql/query",
+ database: "Sample Database",
+ stages: [
+ {
+ "lib/type": "mbql.stage/mbql",
+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],
+ },
+ ],
+ },
+ "serdes/meta": [{ model: "Card", id: question, label: "orders" }],
+ });
+ expect(query.entity.creator_id).to.be.a("string");
+ }),
+ );
+ });
+
+ it("checks that the resources back every definition, listing every problem", () => {
+ const question = H.newEntityId();
+ const stale = H.newEntityId();
+ H.declareDataAppQueries(APP_ROOT(), [
+ { name: "Orders", tableId: ORDERS_ID, savedQuestionEntityId: question },
+ ]);
+
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: collection(),
+ cards: [ordersQuestion(question)],
+ });
+ H.runDataAppCli("check-resources").then(({ exitCode, stdout }) => {
+ expect(exitCode).to.eq(0);
+ expect(stdout).to.contain(
+ "The app's collection files back every definition.",
+ );
+ });
+
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: collection(),
+ cards: [ordersQuestion(stale)],
+ });
+ H.runDataAppCli("check-resources").then(({ exitCode, stderr }) => {
+ expect(exitCode).not.to.eq(0);
+ expect(stderr).to.contain(
+ `queries/orders.query.ts:Orders names saved question ${question}, which no file in collections/data_apps/ holds in the app's collection.`,
+ );
+ expect(stderr).to.contain(
+ "is a resource that is not referenced anywhere.",
+ );
+ });
+ });
+ });
+
+ it("publishes the saved question with a pull, readable by the app's group alone", () => {
+ const question = H.newEntityId();
+ H.declareDataAppQueries(APP_ROOT(), [
+ { name: "Orders", tableId: ORDERS_ID, savedQuestionEntityId: question },
+ ]);
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: collection(),
+ cards: [ordersQuestion(question)],
+ });
+ H.publishDataApp(APP_ROOT(), APP_SLUG).then((app) => {
+ expect(app.table_ids).to.deep.eq([ORDERS_ID]);
+
+ cy.request<Card>(`/api/card/${question}`).then(({ body: card }) => {
+ expect(card.collection_id).to.eq(app.resource_collection_id);
+ expect(card.name).to.eq("Orders");
+
+ H.addUserToGroup(app.permission_group_id, USERS.normal.email);
+
+ cy.signInAsNormalUser();
+ cy.request(`/api/card/${question}`)
+ .its("body.id")
+ .should("eq", card.id);
+
+ cy.signIn("nocollection");
+ cy.request({ url: `/api/card/${question}`, failOnStatusCode: false })
+ .its("status")
+ .should("eq", 403);
+ });
+ });
+ });
+
+ it("publishes a copy of the metric a query uses, readable by the app's group alone", () => {
+ H.createQuestion({
+ name: "Orders count",
+ type: "metric",
+ query: { "source-table": ORDERS_ID, aggregation: [["count"]] },
+ }).then(({ body: metric }) => {
+ const question = H.newEntityId();
+ const metricCopy = H.newEntityId();
+
+ H.declareDataAppQueries(APP_ROOT(), [
+ {
+ name: "OrdersCount",
+ tableId: ORDERS_ID,
+ metricId: metric.id,
+ savedQuestionEntityId: question,
+ },
+ ]);
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: collection(),
+ cards: [
+ ordersQuestion(question, metricAggregation(metricCopy)),
+ H.dataAppRepresentations.card({
+ entityId: metricCopy,
+ name: "Orders count",
+ type: "metric",
+ collection: COLLECTION,
+ table: ORDERS_TABLE,
+ stage: {
+ aggregation: [["count", { "lib/uuid": crypto.randomUUID() }]],
+ },
+ }),
+ ],
+ });
+ H.publishDataApp(APP_ROOT(), APP_SLUG).then((app) => {
+ cy.request<{ data: CollectionItem[] }>(
+ `/api/collection/${app.resource_collection_id}/items?models=metric`,
+ ).then(({ body: { data: metrics } }) => {
+ expect(metrics.map(({ name }) => name)).to.deep.eq(["Orders count"]);
+ const [copy] = metrics;
+ expect(copy.id, "a copy, not the source metric").not.to.eq(metric.id);
+
+ H.addUserToGroup(app.permission_group_id, USERS.normal.email);
+
+ cy.signInAsNormalUser();
+ cy.request(`/api/card/${copy.id}`).its("status").should("eq", 200);
+ cy.request<Card>(`/api/card/${question}`).then(({ body: card }) => {
+ cy.request("POST", `/api/card/${card.id}/query`)
+ .its("body.data.rows.0.0")
+ .should("be.greaterThan", 0);
+ });
+
+ cy.signIn("nocollection");
+ cy.request({ url: `/api/card/${copy.id}`, failOnStatusCode: false })
+ .its("status")
+ .should("eq", 403);
+ });
+ });
+ });
+ });
+
+ it("refuses resources that read a card outside the app, and loads none of them", () => {
+ H.createQuestion({
+ name: "Orders count",
+ type: "metric",
+ query: { "source-table": ORDERS_ID, aggregation: [["count"]] },
+ }).then(({ body: metric }) => {
+ const question = H.newEntityId();
+
+ H.declareDataAppQueries(APP_ROOT(), [
+ {
+ name: "OrdersCount",
+ tableId: ORDERS_ID,
+ metricId: metric.id,
+ savedQuestionEntityId: question,
+ },
+ ]);
+ // The question reads the source metric instead of a copy in the app.
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: collection(),
+ cards: [ordersQuestion(question, metricAggregation(metric.entity_id))],
+ });
+
+ H.publishDataAppExpectingRefusal(APP_ROOT(), APP_SLUG).then((error) => {
+ expect(error).to.contain(
+ `references Card ${metric.entity_id}, which is not one of the app's resources`,
+ );
+ cy.request({ url: `/api/card/${question}`, failOnStatusCode: false })
+ .its("status")
+ .should("eq", 404);
+ });
+ });
+ });
+
+ describe("the build guard", () => {
+ /** `cy.exec` reports the command's output; vite prints this only on success. */
+ const expectBuildToSucceed = () =>
+ H.buildDataAppHostApp().should((result) => {
+ expect(`${result.stdout}${result.stderr}`).to.contain("built in");
+ });
+
+ // `metabase-resource-check` runs on buildStart and never calls Metabase, so
+ // an app whose definitions name missing resources is refused before it can
+ // be bundled.
+ it("refuses to build when a definition's saved question is missing", () => {
+ const question = H.newEntityId();
+ H.declareDataAppQueries(APP_ROOT(), [
+ { name: "Orders", tableId: ORDERS_ID, savedQuestionEntityId: question },
+ ]);
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: collection(),
+ cards: [ordersQuestion(question)],
+ });
+ expectBuildToSucceed();
+
+ H.writeDataAppResources(APP_ROOT(), { collection: collection() });
+ H.buildDataAppHostApp().should((result) => {
+ const output = `${result.stdout}${result.stderr}`;
+ expect(output, "the build is refused").to.contain(
+ `names saved question ${question}, which no file in collections/data_apps/ holds in the app's collection.`,
+ );
+ expect(output).not.to.contain("built in");
+ });
+
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: collection(),
+ cards: [ordersQuestion(question)],
+ });
+ expectBuildToSucceed();
+ });
+ });
+});
diff --git a/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.ts b/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.ts
deleted file mode 100644
index c2df6a01352..00000000000
--- a/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.ts
+++ /dev/null
@@ -1,357 +0,0 @@
-import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
-import {
- addUserToGroup,
- createDataAppApiKey,
- createDataAppCollection,
- createDataAppScoreboardAction,
- dataAppHostAppRoot,
- dataAppPermissionGroupId,
- declareDataAppActions,
- removeDataAppActionDeclaration,
- resetDataAppHostAppSources,
- syncDataAppResources,
-} from "e2e/support/helpers";
-import type { WritebackAction } from "metabase-types/api";
-
-const { H } = cy;
-
-const TEST_TABLE = "scoreboard_actions";
-
-/** The `slug` the app's `data_app.yaml` declares. */
-const APP_SLUG = "vite-6-data-app-host-app";
-
-const APP_ROOT = () => dataAppHostAppRoot();
-
-const PARAMETERS = { team_name: "Data App FC", score: 7 };
-
-/**
- * Drives the real `sync-resources` CLI against a live instance, so the copies are
- * checked against Metabase rather than a fake of its API. The unit suite covers
- * the decision logic; this covers the contract.
- */
-describe(
- "Embedding SDK: data-app sync-resources (actions)",
- { tags: ["@external", "@actions"] },
- () => {
- beforeEach(() => {
- H.restore("postgres-writable");
- cy.signInAsAdmin();
- H.activateToken("bleeding-edge");
-
- H.resetTestTable({ type: "postgres", table: TEST_TABLE });
- H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEST_TABLE });
- H.setActionsEnabledForDB(WRITABLE_DB_ID);
-
- resetDataAppHostAppSources();
- createDataAppApiKey().as("apiKey");
- });
-
- after(() => {
- resetDataAppHostAppSources();
- });
-
- const sync = () =>
- cy.get<string>("@apiKey").then((apiKey) => {
- syncDataAppResources(apiKey, APP_ROOT()).then(({ ok, error }) => {
- expect(error, "sync-resources failed").to.eq(null);
- expect(ok).to.eq(true);
- });
- });
-
- /** The actions Metabase holds in the app's own collection. */
- const copiedActions = () =>
- cy.request(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {
- expect(app.resource_collection_id, "resource collection").to.be.a(
- "number",
- );
- return cy
- .request<WritebackAction[]>("/api/action")
- .then(({ body }) =>
- body.filter(
- (action) => action.collection_id === app.resource_collection_id,
- ),
- );
- });
-
- /** Runs a sync that must be refused, and returns the message it refused with. */
- const syncExpectingRefusal = (message: string) =>
- cy.get<string>("@apiKey").then((apiKey) => {
- syncDataAppResources(apiKey, APP_ROOT()).should(({ ok, error }) => {
- expect(ok, "sync-resources should have refused").to.eq(false);
- expect(error).to.contain(message);
- });
- });
-
- /** Declares one action, without syncing yet. */
- const declareOneAction = () =>
- createDataAppScoreboardAction().then((action) => {
- declareDataAppActions(APP_ROOT(), [action.id]);
- return cy.wrap(action, { log: false });
- });
-
- /** Syncs one declared action and hands back the copy Metabase now holds. */
- const syncOneAction = () =>
- declareOneAction().then((action) => {
- sync();
- return copiedActions().then(([copiedAction]) =>
- cy.wrap({ action, copiedAction }, { log: false }),
- );
- });
-
- it("copies each declared action into the app collection, then deletes each copy as its declaration is removed", () => {
- createDataAppScoreboardAction({ name: "Add team" }).then((add) => {
- createDataAppScoreboardAction({ name: "Add rival" }).then((rival) => {
- declareDataAppActions(APP_ROOT(), [add.id, rival.id]);
-
- sync();
-
- copiedActions().then((actions) => {
- expect(actions).to.have.length(2);
- actions.forEach((copy) => {
- expect(copy.model_id, "a copy belongs to no model").to.eq(null);
- expect([add.id, rival.id]).not.to.include(copy.id);
- });
- });
-
- // Injected back into source: the ID a production build runs.
- cy.readFile(`${APP_ROOT()}/actions/orders.action.ts`).should(
- "match",
- /copiedActionId: \d+/,
- );
-
- cy.readFile(`${APP_ROOT()}/resources_metadata.json`).then(
- (lockfile) => {
- expect(lockfile.actions).to.have.length(2);
- },
- );
-
- sync();
- copiedActions().should("have.length", 2);
-
- removeDataAppActionDeclaration(APP_ROOT(), rival.id);
- sync();
- copiedActions().should("have.length", 1);
-
- removeDataAppActionDeclaration(APP_ROOT(), add.id);
- sync();
- copiedActions().should("have.length", 0);
- cy.readFile(`${APP_ROOT()}/resources_metadata.json`).then(
- (lockfile) => {
- expect(lockfile.actions).to.have.length(0);
- },
- );
- });
- });
- });
-
- it("updates the copy in place when the source action changes", () => {
- syncOneAction().then(({ action, copiedAction }) => {
- cy.request("PUT", `/api/action/${action.id}`, {
- description: "now documented",
- });
-
- sync();
-
- copiedActions().then((actions) => {
- expect(actions).to.have.length(1);
- expect(actions[0].id).to.eq(copiedAction.id);
- expect(actions[0].description).to.eq("now documented");
- });
- });
- });
-
- it("leaves the copy untouched when nothing changed", () => {
- syncOneAction().then(({ copiedAction }) => {
- sync();
-
- copiedActions().then(([action]) => {
- expect(action.id).to.eq(copiedAction.id);
- expect(action.updated_at, "the copy was not rewritten").to.eq(
- copiedAction.updated_at,
- );
- });
- });
- });
-
- it("restores a copy edited directly in Metabase", () => {
- syncOneAction().then(({ copiedAction }) => {
- cy.request("PUT", `/api/action/${copiedAction.id}`, {
- name: "Edited by hand",
- });
-
- sync();
-
- copiedActions().then((actions) => {
- expect(actions).to.have.length(1);
- expect(actions[0].id).to.eq(copiedAction.id);
- expect(actions[0].name).to.eq(copiedAction.name);
- });
- });
- });
-
- describe("permissions", () => {
- const joinAppGroup = () =>
- dataAppPermissionGroupId(APP_SLUG).then((groupId) => {
- addUserToGroup(groupId, USERS.normal.email);
- return cy.wrap(groupId, { log: false });
- });
-
- // The copy is the whole point: an app's viewers hold read on the app's
- // collection, so only the copy is reachable to them.
- it("lets the app's group execute the copy but not the action it was copied from", () => {
- createDataAppCollection({
- name: "Source actions",
- access: "none",
- }).then((collection) => {
- createDataAppScoreboardAction({
- collectionId: collection.id,
- }).then((action) => {
- declareDataAppActions(APP_ROOT(), [action.id]);
- sync();
- joinAppGroup();
-
- copiedActions().then(([copiedAction]) => {
- cy.signInAsNormalUser();
- cy.request({
- method: "POST",
- url: `/api/action/${copiedAction.id}/execute`,
- body: { parameters: PARAMETERS },
- })
- .its("status")
- .should("be.oneOf", [200, 204]);
-
- // The same request against the source, so the two are like for like.
- cy.request({
- method: "POST",
- url: `/api/action/${action.id}/execute`,
- body: { parameters: PARAMETERS },
- failOnStatusCode: false,
- })
- .its("status")
- .should("eq", 403);
- });
- });
- });
- });
-
- it("reports a copy that was deleted in Metabase without being re-synced", () => {
- syncOneAction().then(({ copiedAction }) => {
- joinAppGroup();
-
- // The source still names this copy, but a production bundle built
- // before the deletion keeps addressing it.
- cy.request("DELETE", `/api/action/${copiedAction.id}`);
-
- cy.signInAsNormalUser();
- cy.request({
- method: "POST",
- url: `/api/action/${copiedAction.id}/execute`,
- body: { parameters: PARAMETERS },
- failOnStatusCode: false,
- })
- .its("status")
- .should("eq", 404);
- });
- });
- });
-
- describe("recovery", () => {
- it("reuses the existing copy when copiedActionId is missing from the source", () => {
- syncOneAction().then(({ action, copiedAction }) => {
- // Rewriting the declarations drops the injected ID, as a bad merge would.
- declareDataAppActions(APP_ROOT(), [action.id]);
- sync();
-
- copiedActions().then((actions) => {
- expect(actions).to.have.length(1);
- expect(actions[0].id, "the copy is reused, not replaced").to.eq(
- copiedAction.id,
- );
- });
- cy.readFile(`${APP_ROOT()}/actions/orders.action.ts`).should(
- "contain",
- `copiedActionId: ${copiedAction.id}`,
- );
- });
- });
-
- it("recreates the copy when it is deleted in Metabase", () => {
- syncOneAction().then(({ copiedAction }) => {
- cy.request("DELETE", `/api/action/${copiedAction.id}`);
- sync();
-
- copiedActions().then((actions) => {
- expect(actions).to.have.length(1);
- expect(actions[0].id).not.to.eq(copiedAction.id);
- });
- });
- });
- });
-
- describe("refusals", () => {
- // `GET /api/action/:id` filters archived actions out, so an archived source
- // is unreadable rather than readable-and-flagged.
- it("copies nothing when a declared action is archived and cannot be read", () => {
- declareOneAction().then((action) => {
- cy.request("PUT", `/api/action/${action.id}`, { archived: true });
-
- syncExpectingRefusal(`Could not read action ${action.id}`);
- copiedActions().should("have.length", 0);
- });
- });
-
- it("copies nothing when a declared action belongs to a model", () => {
- H.createModelFromTableName({
- tableName: TEST_TABLE,
- modelName: "Scoreboard model",
- });
- cy.get<number>("@modelId").then((modelId) =>
- H.createImplicitAction({ model_id: modelId, kind: "create" }).then(
- ({ body: action }) => {
- declareDataAppActions(APP_ROOT(), [action.id]);
-
- syncExpectingRefusal("is not a query action without a model");
- copiedActions().should("have.length", 0);
- },
- ),
- );
- });
-
- // Validation itself is unit-tested; what matters here is that a rejected
- // lockfile stops the CLI before it mutates anything.
- it("refuses to sync when resources_metadata.json is corrupt, leaving the copy alone", () => {
- syncOneAction().then(({ copiedAction }) => {
- cy.writeFile(`${APP_ROOT()}/resources_metadata.json`, "{ not json");
-
- syncExpectingRefusal("Could not read resources_metadata.json");
-
- copiedActions().then((actions) => {
- expect(actions, "the copy is left alone").to.have.length(1);
- expect(actions[0].id).to.eq(copiedAction.id);
- });
- });
- });
-
- it("refuses to sync when a copy was moved out of the app collection", () => {
- syncOneAction().then(({ copiedAction }) => {
- cy.request("POST", "/api/collection", {
- name: "Elsewhere",
- namespace: "data-actions",
- }).then(({ body: collection }) => {
- cy.request("PUT", `/api/action/${copiedAction.id}`, {
- collection_id: collection.id,
- });
-
- syncExpectingRefusal(
- `Action ${copiedAction.id} is the copy of action`,
- );
- // Refusing is only worth anything if the copy is left alone.
- cy.request(`/api/action/${copiedAction.id}`)
- .its("body.collection_id")
- .should("eq", collection.id);
- });
- });
- });
- });
- },
-);
diff --git a/e2e/test-host-app/data-apps/sync-resources.cy.spec.ts b/e2e/test-host-app/data-apps/sync-resources.cy.spec.ts
deleted file mode 100644
index 01173e4c225..00000000000
--- a/e2e/test-host-app/data-apps/sync-resources.cy.spec.ts
+++ /dev/null
@@ -1,729 +0,0 @@
-import { USERS, USER_GROUPS } from "e2e/support/cypress_data";
-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-import {
- addUserToGroup,
- buildDataAppHostApp,
- createDataAppApiKey,
- createSecondDataApp,
- dataAppHostAppRoot,
- dataAppPermissionGroupId,
- declareDataAppQueries,
- removeDataAppQueryDeclaration,
- resetDataAppHostAppSources,
- setDataAppCollectionAccess,
- syncDataAppResources,
-} from "e2e/support/helpers";
-import type { Card, DataApp } from "metabase-types/api";
-
-const { H } = cy;
-const { ORDERS_ID } = SAMPLE_DATABASE;
-
-/** The `slug` the app's `data_app.yaml` declares. */
-const APP_SLUG = "vite-6-data-app-host-app";
-
-/** The fields these specs read off a card the app collection holds. */
-type AppCard = { id: number; name: string; collection_id: number | null };
-
-const APP_ROOT = () => dataAppHostAppRoot();
-const LOCKFILE = () => `${APP_ROOT()}/resources_metadata.json`;
-const QUERIES_FILE = () => `${APP_ROOT()}/queries/orders.query.ts`;
-const MANIFEST_FILE = () => `${APP_ROOT()}/data_app.yaml`;
-
-const AUTHORED_MANIFEST = `version: 1
-name: Vite 6 Data App
-slug: vite-6-data-app-host-app
-path: ./dist/index.js
-allowed_hosts:
- - https://allowed.data-app.test
-entity_id: qxpaPkU_WRE2ZQu0cmpqD
-serdes/meta:
-- model: DataApp
- id: qxpaPkU_WRE2ZQu0cmpqD
- label: vite-6-data-app-host-app
-`;
-
-/**
- * The query half of `sync-resources`, run against the dev host app: a real vite
- * data app with the published SDK installed, so `defineQuery` resolves through
- * the package an author actually consumes rather than a stub.
- */
-describe("Embedding SDK: data-app sync-resources (queries)", () => {
- const resetHostAppSources = () => {
- resetDataAppHostAppSources();
- cy.writeFile(MANIFEST_FILE(), AUTHORED_MANIFEST);
- };
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- H.activateToken("bleeding-edge");
-
- // The query and actions specs share a checked-in host app, so start clean.
- resetHostAppSources();
- createDataAppApiKey().as("apiKey");
- });
-
- after(() => {
- resetHostAppSources();
- });
-
- const sync = () =>
- cy.get<string>("@apiKey").then((apiKey) => {
- syncDataAppResources(apiKey, APP_ROOT()).then(({ ok, error }) => {
- expect(error, "sync-resources failed").to.eq(null);
- expect(ok).to.eq(true);
- });
- });
-
- const syncExpectingRefusal = (message: string) =>
- cy.get<string>("@apiKey").then((apiKey) => {
- syncDataAppResources(apiKey, APP_ROOT()).should(({ ok, error }) => {
- expect(ok, "sync-resources should have refused").to.eq(false);
- expect(error).to.contain(message);
- });
- });
-
- /** The saved questions Metabase holds in the app's own collection. */
- const savedQuestions = () =>
- cy.request<DataApp>(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {
- expect(app.resource_collection_id, "resource collection").to.be.a(
- "number",
- );
- return cy
- .request<{
- data: AppCard[];
- }>(`/api/collection/${app.resource_collection_id}/items?models=card`)
- .then(({ body }) => body.data);
- });
-
- /** Declares one query and syncs it, handing back the card Metabase created. */
- const syncOneQuery = () => {
- declareDataAppQueries(APP_ROOT(), [{ name: "Orders", tableId: ORDERS_ID }]);
- sync();
- return savedQuestions().then(([card]) => cy.wrap(card, { log: false }));
- };
-
- it("names the definition whose query Metabase could not resolve", () => {
- declareDataAppQueries(APP_ROOT(), [{ name: "Orders", tableId: 999999 }]);
-
- syncExpectingRefusal("Could not resolve queries/orders.query.ts:Orders");
-
- savedQuestions().should("have.length", 0);
- });
-
- it("creates the saved question, writes its ID back, and re-syncs without changes", () => {
- declareDataAppQueries(APP_ROOT(), [
- { name: "Orders", tableId: ORDERS_ID, limit: 5 },
- ]);
-
- sync();
-
- savedQuestions().then((cards) => {
- expect(cards).to.have.length(1);
-
- cy.readFile(QUERIES_FILE()).should(
- "contain",
- `savedQuestionSourceId: ${cards[0].id}`,
- );
- cy.readFile(LOCKFILE()).then((lockfile) => {
- expect(lockfile.queries).to.have.length(1);
- expect(lockfile.queries[0].savedQuestionSourceId).to.eq(cards[0].id);
- });
-
- sync();
- savedQuestions().then((after) => {
- expect(after).to.have.length(1);
- expect(after[0].id).to.eq(cards[0].id);
- });
- });
- });
-
- it("deletes the saved question when its declaration is removed", () => {
- syncOneQuery().then(() => {
- removeDataAppQueryDeclaration(APP_ROOT(), "Orders");
- sync();
-
- savedQuestions().should("have.length", 0);
- cy.readFile(LOCKFILE()).then((lockfile) => {
- expect(lockfile.queries).to.have.length(0);
- });
- });
- });
-
- // Removing a declaration deletes the copy and its lockfile entry, but the ID the
- // sync wrote into the source stays in source control. Bringing the declaration
- // back has to make a fresh copy: there is no card left to adopt.
- it("re-creates the copy when a removed declaration comes back naming the deleted card", () => {
- syncOneQuery().then((card) => {
- cy.readFile(QUERIES_FILE()).then((authored: string) => {
- expect(
- authored,
- "the sync wrote the copy's ID into the source",
- ).to.contain(`savedQuestionSourceId: ${card.id}`);
-
- removeDataAppQueryDeclaration(APP_ROOT(), "Orders");
- sync();
- savedQuestions().should("have.length", 0);
-
- // Exactly what restoring the file from source control brings back.
- cy.writeFile(QUERIES_FILE(), authored);
- sync();
-
- savedQuestions().then((recreated) => {
- expect(recreated).to.have.length(1);
- expect(
- recreated[0].id,
- "the deleted card is not resurrected",
- ).not.to.eq(card.id);
- cy.readFile(QUERIES_FILE())
- .should("contain", `savedQuestionSourceId: ${recreated[0].id}`)
- .should("not.contain", `savedQuestionSourceId: ${card.id}`);
- });
- });
- });
- });
-
- it("names the trash when a restored declaration points at a trashed copy", () => {
- syncOneQuery().then((card) => {
- cy.readFile(QUERIES_FILE()).then((authored: string) => {
- cy.request("PUT", `/api/card/${card.id}`, { archived: true });
-
- removeDataAppQueryDeclaration(APP_ROOT(), "Orders");
- sync();
- cy.readFile(LOCKFILE()).then((lockfile) => {
- expect(lockfile.queries, "the entry is dropped").to.have.length(0);
- });
-
- cy.writeFile(QUERIES_FILE(), authored);
- syncExpectingRefusal(`card ${card.id}, which is in the trash`);
- });
- });
- });
-
- it("restores a hand-edited card's name instead of replacing the card", () => {
- syncOneQuery().then((card) => {
- cy.request("PUT", `/api/card/${card.id}`, { name: "Renamed by hand" });
-
- sync();
-
- savedQuestions().then((cards) => {
- expect(cards, "the card is updated in place").to.have.length(1);
- expect(cards[0].id).to.eq(card.id);
- expect(cards[0].name).to.eq("Orders");
- });
- });
- });
-
- it("brings back a saved question that was trashed on its own", () => {
- syncOneQuery().then((card) => {
- cy.request("PUT", `/api/card/${card.id}`, { archived: true });
-
- sync();
-
- cy.request(`/api/card/${card.id}`).then(({ body: restored }) => {
- expect(restored.archived, "the copy is out of the trash").to.eq(false);
- expect(restored.collection_id).to.eq(card.collection_id);
- });
- });
- });
-
- describe("trashed metric copies", () => {
- beforeEach(() => {
- H.createQuestion({
- name: "Count of orders",
- type: "metric",
- query: { "source-table": ORDERS_ID, aggregation: [["count"]] },
- display: "scalar",
- })
- .its("body.id")
- .as("sourceMetricId");
-
- cy.log("define a query that uses metrics");
- cy.get<number>("@sourceMetricId").then((id) => {
- cy.writeFile(
- QUERIES_FILE(),
- [
- 'import { defineQuery } from "@metabase/embedding-sdk-react/data-app";',
-
- "export const OrdersCount = defineQuery({",
- ` source: { type: "table", id: ${ORDERS_ID} },`,
- ` aggregations: [{ type: "metric", id: ${id}, sourceTableId: ${ORDERS_ID} }],`,
- "});",
- ].join("\n"),
- );
- });
-
- sync();
-
- cy.readFile(LOCKFILE()).then((lockfile) => {
- expect(lockfile.metrics).to.have.length(1);
- expect(lockfile.queries).to.have.length(1);
-
- cy.wrap(lockfile.metrics[0].copiedMetricId).as("copiedMetricId");
- cy.wrap(lockfile.queries[0].savedQuestionSourceId).as("questionId");
- });
-
- cy.log("archive the copied metric");
- cy.get<number>("@copiedMetricId").then((id) => {
- cy.request<Card>(`/api/card/${id}`).its("body").as("metricCopy");
-
- H.archiveQuestion(id);
- });
-
- cy.get<Card>("@metricCopy").then((copy) => {
- cy.log("the copied metric is archived");
-
- cy.request<Card>(`/api/card/${copy.id}`).should(({ body }) => {
- expect(body.archived).to.eq(true);
- expect(body.collection_id).not.to.eq(copy.collection_id);
- });
- });
- });
-
- it("restores a trashed metric copy after sync", () => {
- sync();
-
- cy.get<Card>("@metricCopy").then((copy) => {
- cy.log("the archived metric should no longer be archived after sync");
-
- cy.request<Card>(`/api/card/${copy.id}`).should(({ body }) => {
- expect(body.archived).to.eq(false);
- expect(body.collection_id).to.eq(copy.collection_id);
- });
-
- cy.log("the copied metric in the lockfile remains the same");
- cy.readFile(LOCKFILE())
- .its("metrics.0.copiedMetricId")
- .should("eq", copy.id);
- });
-
- cy.get<number>("@questionId").then((id) => H.visitQuestion(id));
-
- H.assertQueryBuilderRowCount(1);
- });
-
- it("leaves a trashed metric copy in trash after its source is removed", () => {
- H.removeDataAppQueryDeclaration(APP_ROOT(), "OrdersCount");
-
- sync();
-
- cy.get<number>("@copiedMetricId").then((id) => {
- cy.log("the copied metric should remain archived after sync");
- cy.request<Card>(`/api/card/${id}`)
- .its("body.archived")
- .should("eq", true);
- });
-
- cy.readFile(LOCKFILE()).should((lockfile) => {
- expect(lockfile.metrics).to.deep.eq([]);
- expect(lockfile.queries).to.deep.eq([]);
- });
-
- cy.get<number>("@sourceMetricId").then((id) => {
- cy.log("the source metric should not be archived");
- cy.request<Card>(`/api/card/${id}`)
- .its("body.archived")
- .should("eq", false);
- });
- });
- });
-
- it("recreates the saved question after it is deleted in Metabase", () => {
- syncOneQuery().then((card) => {
- cy.request("DELETE", `/api/card/${card.id}`);
-
- sync();
-
- savedQuestions().then((cards) => {
- expect(cards).to.have.length(1);
- expect(cards[0].id).not.to.eq(card.id);
- });
- cy.readFile(QUERIES_FILE()).should("not.contain", `Id: ${card.id}`);
- });
- });
-
- it("restores savedQuestionSourceId from the lockfile when the source loses it", () => {
- syncOneQuery().then((card) => {
- // Rewriting the declaration drops the injected ID, as a bad merge would.
- declareDataAppQueries(APP_ROOT(), [
- { name: "Orders", tableId: ORDERS_ID },
- ]);
-
- sync();
-
- savedQuestions().then((cards) => {
- expect(cards, "the card is reused, not replaced").to.have.length(1);
- expect(cards[0].id).to.eq(card.id);
- });
- cy.readFile(QUERIES_FILE()).should(
- "contain",
- `savedQuestionSourceId: ${card.id}`,
- );
- });
- });
-
- it("rebuilds a missing lockfile entry from the ID left in the source", () => {
- syncOneQuery().then((card) => {
- cy.writeFile(LOCKFILE(), { queries: [], actions: [] });
-
- sync();
-
- // The inline ID proves ownership, so the entry is rebuilt.
- savedQuestions().then((cards) => {
- expect(cards).to.have.length(1);
- expect(cards[0].id).to.eq(card.id);
- });
- cy.readFile(LOCKFILE()).then((lockfile) => {
- expect(lockfile.queries).to.have.length(1);
- expect(lockfile.queries[0].savedQuestionSourceId).to.eq(card.id);
- });
- });
- });
-
- // A card in the trash reports the Trash as its collection, so one moved out
- // and trashed afterwards is indistinguishable from the app's own. Deleting is
- // permanent, so neither is deleted.
- it("leaves a trashed card in the trash when its declaration is removed", () => {
- syncOneQuery().then((card) => {
- cy.request("PUT", `/api/card/${card.id}`, { archived: true });
- removeDataAppQueryDeclaration(APP_ROOT(), "Orders");
-
- sync();
-
- cy.request(`/api/card/${card.id}`)
- .its("body.archived")
- .should("eq", true);
- cy.readFile(LOCKFILE()).then((lockfile) => {
- expect(lockfile.queries, "no longer tracked").to.have.length(0);
- });
- });
- });
-
- it("refuses to delete a card that was moved out of the app collection", () => {
- syncOneQuery().then((card) => {
- cy.request("POST", "/api/collection", { name: "Elsewhere" }).then(
- ({ body: collection }) => {
- cy.request("PUT", `/api/card/${card.id}`, {
- collection_id: collection.id,
- });
- removeDataAppQueryDeclaration(APP_ROOT(), "Orders");
-
- syncExpectingRefusal(`Move card ${card.id} back to`);
- cy.request(`/api/card/${card.id}`)
- .its("body.collection_id")
- .should("eq", collection.id);
- },
- );
- });
- });
-
- // Trashing the collection archives everything in it, and the app is served
- // from those copies, so a sync that reports success has not actually recovered.
- it("brings the app collection and its copies back out of the trash", () => {
- syncOneQuery().then((card) => {
- cy.request(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {
- cy.request("PUT", `/api/collection/${app.resource_collection_id}`, {
- archived: true,
- });
- cy.request(`/api/card/${card.id}`)
- .its("body.archived")
- .should("eq", true);
-
- sync();
-
- cy.request(`/api/collection/${app.resource_collection_id}`)
- .its("body.archived")
- .should("eq", false);
- cy.request(`/api/card/${card.id}`)
- .its("body.archived")
- .should("eq", false);
- });
- });
- });
-
- describe("the app's lifecycle", () => {
- it("takes the collection and the group with it when the app is removed", () => {
- syncOneQuery().then((card) => {
- dataAppPermissionGroupId(APP_SLUG).then((groupId) => {
- cy.request(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {
- cy.request("DELETE", `/api/apps/${APP_SLUG}`);
-
- // Nothing is left for a former viewer to reach.
- cy.request({
- url: `/api/collection/${app.resource_collection_id}`,
- failOnStatusCode: false,
- })
- .its("status")
- .should("eq", 404);
- cy.request({
- url: `/api/permissions/group/${groupId}`,
- failOnStatusCode: false,
- })
- .its("status")
- .should("eq", 404);
- cy.request({ url: `/api/card/${card.id}`, failOnStatusCode: false })
- .its("status")
- .should("eq", 404);
- });
- });
- });
- });
-
- // Everything the CLI drives is superuser-gated, starting with the draft it
- // asks for first, so a key that is not an admin's gets nowhere.
- it("refuses to synchronize at all for a key that is not an admin's", () => {
- declareDataAppQueries(APP_ROOT(), [
- { name: "Orders", tableId: ORDERS_ID },
- ]);
-
- cy.request("POST", "/api/api-key", {
- name: `data-app-sync-e2e-non-admin-${Date.now()}`,
- group_id: USER_GROUPS.COLLECTION_GROUP,
- }).then(({ body: key }) => {
- syncDataAppResources(key.unmasked_key, APP_ROOT()).should(
- ({ ok, error }) => {
- expect(ok, "sync-resources should have refused").to.eq(false);
- expect(error).to.contain("403");
- expect(error, "refused at the first call it makes").to.contain(
- `/api/apps/${APP_SLUG}/draft`,
- );
- },
- );
-
- // The draft call is the one that creates the app, so a refusal leaves
- // nothing behind at all — not even the app to hold copies.
- cy.request({ url: `/api/apps/${APP_SLUG}`, failOnStatusCode: false })
- .its("status")
- .should("eq", 404);
- });
- });
- });
-
- describe("two apps on one instance", () => {
- const OTHER_SLUG = "sync-resources-second-app";
-
- it("keeps each app's copies in its own collection, reachable only by its own group", () => {
- const otherRoot = createSecondDataApp(OTHER_SLUG);
-
- syncOneQuery().then((card) => {
- declareDataAppQueries(otherRoot, [
- { name: "OtherOrders", tableId: ORDERS_ID },
- ]);
- cy.get<string>("@apiKey").then((apiKey) => {
- syncDataAppResources(apiKey, otherRoot).then(({ error }) => {
- expect(error, "second app sync failed").to.eq(null);
- });
- });
-
- cy.request(`/api/apps/${OTHER_SLUG}`).then(({ body: otherApp }) => {
- dataAppPermissionGroupId(APP_SLUG).then((groupId) => {
- expect(
- otherApp.resource_collection_id,
- "each app gets its own collection",
- ).not.to.eq(null);
- expect(otherApp.permission_group_id).not.to.eq(groupId);
-
- // Joining one app's group must not reach the other app's copy.
- addUserToGroup(groupId, USERS.normal.email);
-
- cy.request(
- `/api/collection/${otherApp.resource_collection_id}/items?models=card`,
- ).then(({ body }) => {
- const otherCard = body.data[0];
- expect(otherCard.id, "the apps hold different cards").not.to.eq(
- card.id,
- );
-
- cy.signInAsNormalUser();
- cy.request(`/api/card/${card.id}`)
- .its("body.id")
- .should("eq", card.id);
- cy.request({
- url: `/api/card/${otherCard.id}`,
- failOnStatusCode: false,
- })
- .its("status")
- .should("eq", 403);
- });
- });
- });
- });
- });
- });
-
- describe("the build guard", () => {
- /** `cy.exec` reports the command's output; vite prints this only on success. */
- const expectBuildToSucceed = () =>
- buildDataAppHostApp().should((result) => {
- expect(`${result.stdout}${result.stderr}`).to.contain("built in");
- });
-
- // `metabase-resource-sync-check` runs on buildStart, so a stale app is
- // refused before it can be bundled and served.
- it("refuses to build when the source and the lockfile disagree", () => {
- syncOneQuery().then(() => {
- expectBuildToSucceed();
-
- // A hand-edited declaration no longer matches its lockfile entry.
- declareDataAppQueries(APP_ROOT(), [
- { name: "Orders", tableId: ORDERS_ID, limit: 3 },
- ]);
-
- buildDataAppHostApp().should((result) => {
- const output = `${result.stdout}${result.stderr}`;
- expect(output, "the build is refused").to.contain(
- "is not synchronized",
- );
- expect(output).not.to.contain("built in");
- });
-
- // Synchronizing makes it buildable again.
- sync();
- expectBuildToSucceed();
- });
- });
- });
-
- describe("permissions", () => {
- /** Puts the normal user in the app's group, as granting app access does. */
- const joinAppGroup = () =>
- dataAppPermissionGroupId(APP_SLUG).then((groupId) => {
- addUserToGroup(groupId, USERS.normal.email);
- return cy.wrap(groupId, { log: false });
- });
-
- it("does not let a viewer modify the copy it can read", () => {
- syncOneQuery().then((card) => {
- joinAppGroup();
-
- cy.signInAsNormalUser();
- cy.request(`/api/card/${card.id}`).its("body.id").should("eq", card.id);
-
- // The grant is collection read, never readwrite.
- cy.request({
- method: "PUT",
- url: `/api/card/${card.id}`,
- body: { name: "Renamed by a viewer" },
- failOnStatusCode: false,
- })
- .its("status")
- .should("eq", 403);
- cy.request({
- method: "DELETE",
- url: `/api/card/${card.id}`,
- failOnStatusCode: false,
- })
- .its("status")
- .should("eq", 403);
- });
- });
-
- // The app collection is server-owned, so each sync reasserts exclusive
- // access — including over a grant an admin made deliberately.
- it("takes back access an admin granted another group on the app collection", () => {
- syncOneQuery().then((card) => {
- cy.request(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {
- setDataAppCollectionAccess(app.resource_collection_id, "read");
-
- cy.signInAsNormalUser();
- cy.request(`/api/card/${card.id}`)
- .its("body.id")
- .should("eq", card.id);
-
- cy.signInAsAdmin();
- sync();
-
- cy.signInAsNormalUser();
- cy.request({ url: `/api/card/${card.id}`, failOnStatusCode: false })
- .its("status")
- .should("eq", 403);
- });
- });
- });
-
- it("grants the group nothing beyond the app's own collection", () => {
- cy.request("POST", "/api/collection", { name: "Private" }).then(
- ({ body: collection }) => {
- // The normal user belongs to groups that can read new collections, so
- // close this one: the claim under test is that joining the app group
- // grants the app's collection and nothing else.
- setDataAppCollectionAccess(collection.id, "none");
-
- H.createQuestion({
- name: "Private question",
- query: { "source-table": ORDERS_ID },
- collection_id: collection.id,
- }).then(({ body: unrelated }) => {
- syncOneQuery().then((card) => {
- joinAppGroup();
-
- cy.signInAsNormalUser();
- cy.request(`/api/card/${card.id}`)
- .its("body.id")
- .should("eq", card.id);
- cy.request({
- url: `/api/card/${unrelated.id}`,
- failOnStatusCode: false,
- })
- .its("status")
- .should("eq", 403);
- });
- });
- },
- );
- });
-
- it("leaves the group with nothing once the declaration is removed", () => {
- syncOneQuery().then((card) => {
- joinAppGroup();
-
- cy.signInAsNormalUser();
- cy.request(`/api/card/${card.id}`).its("body.id").should("eq", card.id);
-
- cy.signInAsAdmin();
- removeDataAppQueryDeclaration(APP_ROOT(), "Orders");
- sync();
-
- // The copy is deleted with its declaration, so there is nothing left to
- // read — the group's collection grant now covers an empty collection.
- cy.signInAsNormalUser();
- cy.request({ url: `/api/card/${card.id}`, failOnStatusCode: false })
- .its("status")
- .should("eq", 404);
- });
- });
-
- // The copy exists so an app's viewers can read it: they are given the app's
- // own group, which holds read on the app's collection and nothing else.
- it("lets the app's group read the copy while the rest of the instance cannot", () => {
- syncOneQuery().then((card) => {
- dataAppPermissionGroupId(APP_SLUG).then((groupId) => {
- cy.signInAsNormalUser();
- cy.request({ url: `/api/card/${card.id}`, failOnStatusCode: false })
- .its("status")
- .should("eq", 403);
-
- cy.signInAsAdmin();
- addUserToGroup(groupId, USERS.normal.email);
-
- cy.signInAsNormalUser();
- cy.request(`/api/card/${card.id}`)
- .its("body.id")
- .should("eq", card.id);
- });
- });
- });
-
- // `read-check-data-app` 403s a non-member, and the app view turns that status
- // into its own empty state instead of loading the bundle.
- it("tells a viewer outside the group that the app is not theirs to open", () => {
- syncOneQuery().then(() => {
- cy.signInAsNormalUser();
- cy.visit(`/apps/${APP_SLUG}`);
-
- cy.findByText("You don’t have access to this data app").should("exist");
- cy.get("iframe").should("not.exist");
- });
- });
- });
-});
diff --git a/e2e/test/scenarios/data-apps/actions.cy.spec.ts b/e2e/test/scenarios/data-apps/actions.cy.spec.ts
index 04407352fdf..8cbd59063e6 100644
--- a/e2e/test/scenarios/data-apps/actions.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/actions.cy.spec.ts
@@ -34,7 +34,12 @@ describe(
createDataAppScoreboardAction().then((action) => {
H.mockDataApp(APP_NAME, {
displayName: APP_DISPLAY_NAME,
- testEnv: { ...TEST_ENV, actionId: action.id, actionParams },
+ testEnv: {
+ ...TEST_ENV,
+ actionId: action.id,
+ actionEntityId: action.entity_id,
+ actionParams,
+ },
});
});
@@ -107,6 +112,7 @@ describe(
testEnv: {
...TEST_ENV,
actionId: action.id,
+ actionEntityId: action.entity_id,
actionParams: { team_name: "Data App FC", score: 7 },
},
});
diff --git a/e2e/test/scenarios/data-apps/admin.cy.spec.ts b/e2e/test/scenarios/data-apps/admin.cy.spec.ts
index 53cd10f5c01..efc71c9529f 100644
--- a/e2e/test/scenarios/data-apps/admin.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/admin.cy.spec.ts
@@ -53,8 +53,9 @@ describe("scenarios > data apps > admin management", () => {
});
it("keeps a data app's permission group out of the admin Groups list", () => {
- // Provisioning a data app draft creates its permission group as a side effect.
- cy.request("POST", "/api/apps/orders-app/draft").then(({ body }) => {
+ // Pulling an app creates its permission group as a side effect.
+ H.pullExampleDataApps();
+ cy.request<DataApp>("GET", "/api/apps/good").then(({ body }) => {
const dataAppGroupId = body.permission_group_id;
// The groups API does not return data-app groups.
@@ -66,7 +67,7 @@ describe("scenarios > data apps > admin management", () => {
cy.visit("/admin/people/groups");
cy.findByTestId("admin-panel").within(() => {
cy.findByText("All Users").should("be.visible");
- cy.findByText("Data App: orders-app").should("not.exist");
+ cy.findByText("Data App: good").should("not.exist");
});
});
});
@@ -101,10 +102,11 @@ describe("scenarios > data apps > admin management", () => {
describe("outdated apps", () => {
// Only a bump of the supported version makes a real app outdated, so the flag
// the API computes is patched onto a real app's responses instead.
- const OUTDATED_APP = "orders-app";
+ const OUTDATED_APP = "good";
function markAppOutdated() {
- cy.request<DataApp>("POST", `/api/apps/${OUTDATED_APP}/draft`)
+ H.pullExampleDataApps();
+ cy.request<DataApp>("GET", `/api/apps/${OUTDATED_APP}`)
.its("body.display_name")
.as("outdatedAppName");
diff --git a/e2e/test/scenarios/data-apps/helpers/index.ts b/e2e/test/scenarios/data-apps/helpers/index.ts
index 687ecbd6dad..9cf5c588974 100644
--- a/e2e/test/scenarios/data-apps/helpers/index.ts
+++ b/e2e/test/scenarios/data-apps/helpers/index.ts
@@ -1,7 +1,7 @@
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
- ORDERS_COUNT_QUESTION_ID,
- ORDERS_QUESTION_ID,
+ ORDERS_COUNT_QUESTION_ENTITY_ID,
+ ORDERS_QUESTION_ENTITY_ID,
} from "e2e/support/cypress_sample_instance_data";
import type { DataAppTestEnv } from "e2e/support/helpers";
@@ -18,7 +18,7 @@ const source = { type: "table" as const, id: ORDERS_ID };
/**
* The `testEnv` the fixture's Overview page reads (Orders count + question).
*
- * Both carry a `savedQuestionSourceId`, because a deployed app runs the card its
+ * Both carry a `savedQuestionEntityId`, because a deployed app runs the card its
* query was published as — a bare table source is refused. Each id names a
* snapshot question equivalent to the authored query, since the swap drops the
* static clauses the card already contains.
@@ -27,7 +27,7 @@ export const DATA_APP_TEST_ENV: DataAppTestEnv = {
scalarQuery: {
source,
aggregations: [{ type: "operator", operator: "count", args: [] }],
- savedQuestionSourceId: ORDERS_COUNT_QUESTION_ID,
+ savedQuestionEntityId: ORDERS_COUNT_QUESTION_ENTITY_ID,
},
- questionQuery: { source, savedQuestionSourceId: ORDERS_QUESTION_ID },
+ questionQuery: { source, savedQuestionEntityId: ORDERS_QUESTION_ENTITY_ID },
};
diff --git a/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.ts b/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.ts
index 6820200faef..450d3ec1d76 100644
--- a/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.ts
@@ -16,7 +16,7 @@ import {
const { H } = cy;
const { ORDERS_ID } = SAMPLE_DATABASE;
-const APP_NAME = "legacy-permission-test";
+const APP_NAME = "good";
// Exercise real queries: preserving the permission graph alone does not prove that data still loads.
describe("scenarios > data apps > legacy view data permissions", () => {
@@ -112,9 +112,8 @@ function assertAccessSurvivesAppMembership() {
);
cy.signInAsAdmin();
- cy.request<DataApp>("POST", `/api/apps/${APP_NAME}/draft`)
- .its("body")
- .as("app");
+ H.pullExampleDataApps();
+ cy.request<DataApp>(`/api/apps/${APP_NAME}`).its("body").as("app");
cy.log("assign the no data user to the data app group");
cy.get<DataApp>("@app").then(({ permission_group_id }) => {
diff --git a/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.ts b/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.ts
new file mode 100644
index 00000000000..5ca9cff28ef
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.ts
@@ -0,0 +1,126 @@
+import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
+
+const { H } = cy;
+
+const TEST_TABLE = "scoreboard_actions";
+
+const APP_SLUG = "synced-actions-app";
+const APP_DISPLAY_NAME = "Synced Actions App";
+
+/** The fixture's `data_app.yaml` names this collection. */
+const COLLECTION = "syncedActionsAppColl1";
+
+const APP_ROOT = () =>
+ `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${APP_SLUG}`;
+
+/**
+ * The action half of the production path. Outside the dev preview
+ * `toExecutableActionId` runs `copiedActionEntityId`, the copy in the app's
+ * collection, because that is the only action an app's viewers may execute.
+ * The copy reaches Metabase through the app's collection files and a repository pull.
+ */
+describe(
+ "scenarios > data apps > resources in production (actions)",
+ { tags: ["@external", "@actions"] },
+ () => {
+ const removeTestFiles = () =>
+ cy.task("removeDataAppPaths", {
+ paths: [`${APP_ROOT()}/actions`, `${APP_ROOT()}/collections`],
+ });
+
+ beforeEach(() => {
+ H.restore("postgres-writable");
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+
+ H.resetTestTable({ type: "postgres", table: TEST_TABLE });
+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEST_TABLE });
+ H.setActionsEnabledForDB(WRITABLE_DB_ID);
+
+ removeTestFiles();
+ });
+
+ after(() => {
+ removeTestFiles();
+ });
+
+ /**
+ * Declares an action that belongs to no model, writes the copy an author
+ * writes from its serialization, publishes the app, and yields it with the copy's
+ * entity ID.
+ */
+ const publishApp = () =>
+ H.createDataAppScoreboardAction().then((source) => {
+ const actionCopy = H.newEntityId();
+
+ H.declareDataAppActions(APP_ROOT(), [
+ {
+ exportName: "CreateScore",
+ sourceActionId: source.id,
+ copiedActionEntityId: actionCopy,
+ },
+ ]);
+
+ return H.serializeDataAppActionCopies(
+ [{ sourceActionId: source.id, entityId: actionCopy }],
+ COLLECTION,
+ )
+ .then((actions) =>
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: H.dataAppRepresentations.collection(
+ COLLECTION,
+ "Data App: Synced Actions App",
+ ),
+ actions,
+ }),
+ )
+ .then(() => H.publishDataApp(APP_ROOT(), APP_SLUG))
+ .then((app) => cy.wrap({ app, actionCopy }, { log: false }));
+ });
+
+ it("serializes the action an author copies, with no model, as its file holds it", () => {
+ H.createDataAppScoreboardAction().then((source) => {
+ // Executing the action reads this, so the copy must keep it.
+ cy.request("PUT", `/api/action/${source.id}`, {
+ visualization_settings: {
+ fields: { score: { id: "score", hidden: true, defaultValue: 0 } },
+ },
+ });
+
+ cy.request("POST", "/api/apps/serialize-resources", {
+ collection: COLLECTION,
+ actions: [source.id],
+ }).then(({ body }) => {
+ expect(body.actions[0].entity).to.deep.include({
+ entity_id: source.entity_id,
+ type: "query",
+ });
+ expect(body.actions[0].entity).not.to.have.property("model_id");
+ expect(body.actions[0].entity)
+ .to.have.nested.property("visualization_settings.fields.score")
+ .that.deep.include({ hidden: true, defaultValue: 0 });
+ });
+ });
+ });
+
+ it("executes the app's copy rather than the authored action, for a member of the app's group", () => {
+ publishApp().then(({ app, actionCopy }) => {
+ H.addUserToGroup(app.permission_group_id, USERS.normal.email);
+
+ cy.signInAsNormalUser();
+ cy.intercept("POST", "/api/action/*/execute").as("execute");
+ H.mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });
+ cy.visit(`/apps/${APP_SLUG}`);
+
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("action-execute", { timeout: 30000 }).click();
+ cy.findByTestId("action-output").should("have.text", "executed");
+ });
+
+ cy.wait("@execute")
+ .its("request.url")
+ .should("contain", `/api/action/${actionCopy}/execute`);
+ });
+ });
+ },
+);
diff --git a/e2e/test/scenarios/data-apps/resources-production.cy.spec.ts b/e2e/test/scenarios/data-apps/resources-production.cy.spec.ts
new file mode 100644
index 00000000000..32b0d0cc56f
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/resources-production.cy.spec.ts
@@ -0,0 +1,184 @@
+import { SAMPLE_DB_ID, USERS } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { PortableTable } from "e2e/support/helpers";
+import type { Card } from "metabase-types/api";
+
+const { H } = cy;
+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
+
+const APP_SLUG = "synced-app";
+const APP_DISPLAY_NAME = "Synced App";
+
+/** The fixture's `data_app.yaml` names this collection. */
+const COLLECTION = "syncedAppCollection01";
+const QUESTION = "syncedAppOrdersCount1";
+
+const ORDERS_TABLE: PortableTable = ["Sample Database", "PUBLIC", "ORDERS"];
+
+const APP_ROOT = () =>
+ `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${APP_SLUG}`;
+
+/**
+ * The definition as source control holds it. `id` is the sample database's
+ * ORDERS table, written from the same constant, so a snapshot change fails
+ * loudly rather than silently.
+ */
+const DECLARATION = [
+ "import {",
+ " aggregations,",
+ " breakout,",
+ " defineQuery,",
+ '} from "@metabase/embedding-sdk-react/data-app";',
+ "",
+ "const OrdersUserId = {",
+ ' type: "column" as const,',
+ ` fieldId: ${ORDERS.USER_ID},`,
+ ` tableId: ${ORDERS_ID},`,
+ ' name: "USER_ID",',
+ ' displayName: "User ID",',
+ ' jsType: "number",',
+ "};",
+ "",
+ "export const OrdersCount = defineQuery({",
+ ` savedQuestionEntityId: "${QUESTION}",`,
+ ` source: { type: "table", id: ${ORDERS_ID} },`,
+ " aggregations: [aggregations.count()],",
+ " breakouts: [breakout(OrdersUserId)],",
+ "});",
+ "",
+].join("\n");
+
+/** The saved question an author writes for `OrdersCount`. */
+const ORDERS_COUNT_QUESTION = H.dataAppRepresentations.card({
+ entityId: QUESTION,
+ name: "OrdersCount",
+ type: "question",
+ collection: COLLECTION,
+ table: ORDERS_TABLE,
+ stage: {
+ aggregation: [["count", { "lib/uuid": crypto.randomUUID() }]],
+ breakout: [
+ [
+ "field",
+ { "lib/uuid": crypto.randomUUID() },
+ [...ORDERS_TABLE, "USER_ID"],
+ ],
+ ],
+ },
+});
+
+/**
+ * What a shipped data app actually does: outside the dev preview
+ * `isDataAppDev()` is false, so the SDK runs the saved question the definition
+ * names, the only resource an app's viewers are permitted to read, rather than
+ * the authored source. The question reaches Metabase the way it does for an
+ * author: written into the app's collection files, committed, and loaded by a repository pull.
+ */
+describe("scenarios > data apps > resources in production", () => {
+ const removeTestFiles = () =>
+ cy.task("removeDataAppPaths", {
+ paths: [`${APP_ROOT()}/queries`, `${APP_ROOT()}/collections`],
+ });
+
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+
+ removeTestFiles();
+ cy.task("writeDataAppFiles", {
+ files: { [`${APP_ROOT()}/queries/orders.query.ts`]: DECLARATION },
+ });
+ H.writeDataAppResources(APP_ROOT(), {
+ collection: H.dataAppRepresentations.collection(
+ COLLECTION,
+ "Data App: Synced App",
+ ),
+ cards: [ORDERS_COUNT_QUESTION],
+ });
+ });
+
+ after(() => {
+ removeTestFiles();
+ });
+
+ /** Publishes the fixture and yields the app with the ID of the card it must now run. */
+ const publishApp = () =>
+ H.publishDataApp(APP_ROOT(), APP_SLUG).then((app) =>
+ cy
+ .request<Card>(`/api/card/${QUESTION}`)
+ .then(({ body: card }) =>
+ cy.wrap({ app, cardId: card.id }, { log: false }),
+ ),
+ );
+
+ it("runs the saved question rather than the authored table query", () => {
+ publishApp().then(({ cardId }) => {
+ cy.intercept("POST", "/api/dataset").as("dataset");
+ H.mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });
+ cy.visit(`/apps/${APP_SLUG}`);
+
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("synced-app-total", { timeout: 30000 }).should(
+ ($total) => {
+ expect(Number($total.text())).to.be.greaterThan(0);
+ },
+ );
+ });
+
+ cy.wait("@dataset").then(({ request }) => {
+ const [stage] = request.body.stages ?? [];
+ expect(stage?.["source-card"], "runs the saved question").to.eq(cardId);
+ expect(stage?.["source-table"], "not the authored table").to.eq(
+ undefined,
+ );
+ });
+ });
+ });
+
+ // The swap is only safe if the saved question the author wrote returns what
+ // the definition does. The dev preview runs the definition; production runs
+ // the card. A deployed app cannot run the definition at all, so the two sides
+ // are captured separately rather than side by side.
+ it("returns the same rows from the saved question as from the authored query", () => {
+ publishApp().then(({ cardId }) => {
+ cy.request("POST", "/api/dataset", {
+ type: "query",
+ database: SAMPLE_DB_ID,
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", ORDERS.USER_ID, null]],
+ },
+ }).then(({ body: authored }) => {
+ cy.request("POST", `/api/card/${cardId}/query`).then(
+ ({ body: published }) => {
+ expect(published.data.rows).to.deep.eq(authored.data.rows);
+ expect(
+ published.data.rows[0][1],
+ "a match on two empty results would be vacuous",
+ ).to.be.greaterThan(0);
+ },
+ );
+ });
+ });
+ });
+
+ it("serves the app to a member of its permission group", () => {
+ publishApp().then(({ app }) => {
+ H.addUserToGroup(app.permission_group_id, USERS.normal.email);
+
+ cy.signInAsNormalUser();
+ H.mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });
+ cy.visit(`/apps/${APP_SLUG}`);
+
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("synced-app-total", { timeout: 30000 }).should(
+ ($total) => {
+ expect(Number($total.text())).to.be.greaterThan(0);
+ },
+ );
+ });
+ });
+ });
+});
diff --git a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts b/e2e/test/scenarios/data-apps/sdk.cy.spec.ts
index 92ed89be735..cd36ffe053a 100644
--- a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/sdk.cy.spec.ts
@@ -26,11 +26,11 @@ describe("scenarios > data apps > SDK runtime", () => {
displayName: APP_DISPLAY_NAME,
testEnv: {
...TEST_ENV,
- // A card that doesn't exist → the query resolves to an error, rather
- // than to the refusal an unsynchronized table source would raise.
+ // A card that doesn't exist, so the query resolves to an error rather
+ // than to the refusal a query without a saved question would raise.
errorQuery: {
source: { type: "table", id: ORDERS_ID },
- savedQuestionSourceId: 999999,
+ savedQuestionEntityId: "missingQuestionEntity",
},
},
});
diff --git a/e2e/test/scenarios/data-apps/semantic-schema.cy.spec.ts b/e2e/test/scenarios/data-apps/semantic-schema.cy.spec.ts
index ae28c894c9c..ba566f9e521 100644
--- a/e2e/test/scenarios/data-apps/semantic-schema.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/semantic-schema.cy.spec.ts
@@ -48,30 +48,17 @@ describe("scenarios > data apps > semantic schema", () => {
"GET",
"/api/typed-schemas/v1/typescript?include-metric-library=true",
).then(({ body }) => {
- const comments = commentsAbove(body, "revenue: {");
+ const metadata = H.typedSchemaMetadata(body, "revenue: {");
- expect(comments).to.include(`// Description: ${METRIC_DESCRIPTION}`);
- expect(comments).to.include("// Filters:");
- expect(
- comments.some(
- (line) => line.startsWith("// - ") && line.includes("Created At"),
- ),
- ).to.eq(true);
+ expect(metadata.description).to.eq(METRIC_DESCRIPTION);
+ expect(metadata.filters).to.satisfy(
+ (filters: unknown) =>
+ Array.isArray(filters) &&
+ filters.some(
+ (filter) =>
+ typeof filter === "string" && filter.includes("Created At"),
+ ),
+ );
});
});
});
-
-/** The comment lines directly above the schema entry that opens with `entry`. */
-function commentsAbove(body: string, entry: string) {
- const lines = body.split("\n").map((line) => line.trim());
- const comments: string[] = [];
-
- for (let index = lines.indexOf(entry) - 1; index >= 0; index--) {
- if (!lines[index].startsWith("//")) {
- break;
- }
- comments.unshift(lines[index]);
- }
-
- return comments;
-}
diff --git a/e2e/test/scenarios/data-apps/sync-resources-production-actions.cy.spec.ts b/e2e/test/scenarios/data-apps/sync-resources-production-actions.cy.spec.ts
deleted file mode 100644
index ada94da2865..00000000000
--- a/e2e/test/scenarios/data-apps/sync-resources-production-actions.cy.spec.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
-import {
- addUserToGroup,
- createDataAppApiKey,
- createDataAppScoreboardAction,
- dataAppIframe,
- dataAppPermissionGroupId,
- mockDataApp,
- syncDataAppResources,
-} from "e2e/support/helpers";
-
-const { H } = cy;
-
-const TEST_TABLE = "scoreboard_actions";
-
-const APP_SLUG = "synced-actions-app";
-const APP_DISPLAY_NAME = "Synced Actions App";
-
-const APP_ROOT = () =>
- `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${APP_SLUG}`;
-const ACTION_FILE = () => `${APP_ROOT()}/actions/orders.action.ts`;
-const MANIFEST_FILE = () => `${APP_ROOT()}/data_app.yaml`;
-const LOCKFILE = () => `${APP_ROOT()}/resources_metadata.json`;
-
-/** The manifest as source control holds it. */
-const AUTHORED_MANIFEST = [
- "version: 1",
- `name: ${APP_DISPLAY_NAME}`,
- `slug: ${APP_SLUG}`,
- "path: ./dist/index.js",
- "entity_id: nPu5r1EndcM_D8TQfLk9c",
- "serdes/meta:",
- "- model: DataApp",
- " id: nPu5r1EndcM_D8TQfLk9c",
- " label: synced-actions-app",
- "",
-].join("\n");
-
-/** The declaration as source control holds it, with no generated ID yet. */
-const declaration = (sourceActionId: number) =>
- [
- 'import { defineAction } from "@metabase/embedding-sdk-react/data-app";',
- "",
- "export const CreateScore = defineAction({",
- ` action: { id: ${sourceActionId}, parameters: [] },`,
- "});",
- "",
- ].join("\n");
-
-/**
- * The action half of the production path. Outside the dev preview
- * `toExecutableActionId` runs `copiedActionId` — the copy in the app's collection —
- * because that is the only action an app's viewers may execute.
- */
-describe(
- "scenarios > data apps > sync-resources in production (actions)",
- { tags: ["@external", "@actions"] },
- () => {
- // Restore the source files and remove the lockfile before each synchronization.
- const restoreAuthoredFixture = () => {
- cy.writeFile(ACTION_FILE(), declaration(1));
- cy.writeFile(MANIFEST_FILE(), AUTHORED_MANIFEST);
- cy.task("removeDataAppPaths", { paths: [LOCKFILE()] });
- };
-
- beforeEach(() => {
- H.restore("postgres-writable");
- cy.signInAsAdmin();
- H.activateToken("bleeding-edge");
-
- H.resetTestTable({ type: "postgres", table: TEST_TABLE });
- H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEST_TABLE });
- H.setActionsEnabledForDB(WRITABLE_DB_ID);
-
- restoreAuthoredFixture();
- createDataAppApiKey().as("apiKey");
- });
-
- after(() => {
- restoreAuthoredFixture();
- });
-
- /** Declares an action, synchronizes, and returns both action IDs. */
- const syncApp = () =>
- createDataAppScoreboardAction().then((action) => {
- cy.writeFile(ACTION_FILE(), declaration(action.id));
-
- return cy.get<string>("@apiKey").then((apiKey) =>
- syncDataAppResources(apiKey, APP_ROOT()).then(({ ok, error }) => {
- expect(error, "sync-resources failed").to.eq(null);
- expect(ok).to.eq(true);
-
- return cy
- .readFile(`${APP_ROOT()}/resources_metadata.json`)
- .then((lockfile) => {
- const copiedActionId = lockfile.actions?.[0]?.copiedActionId;
-
- if (typeof copiedActionId !== "number") {
- throw new Error("The sync wrote no action to the lockfile.");
- }
-
- return cy.wrap(
- { sourceActionId: action.id, copiedActionId },
- { log: false },
- );
- });
- }),
- );
- });
-
- it("executes the synchronized copy rather than the authored action", () => {
- syncApp().then(({ sourceActionId, copiedActionId }) => {
- expect(copiedActionId).not.to.eq(sourceActionId);
-
- cy.intercept("POST", "/api/action/*/execute").as("execute");
- mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });
- cy.visit(`/apps/${APP_SLUG}`);
-
- dataAppIframe(APP_DISPLAY_NAME).within(() => {
- cy.findByTestId("action-execute", { timeout: 30000 }).click();
- cy.findByTestId("action-output").should("have.text", "executed");
- });
-
- // The proof that production took the synchronized path.
- cy.wait("@execute")
- .its("request.url")
- .should("contain", `/api/action/${copiedActionId}/execute`);
- });
- });
-
- it("lets a member of the app's group execute it", () => {
- syncApp().then(({ copiedActionId }) => {
- dataAppPermissionGroupId(APP_SLUG).then((groupId) => {
- addUserToGroup(groupId, USERS.normal.email);
-
- cy.signInAsNormalUser();
- cy.intercept("POST", "/api/action/*/execute").as("execute");
- mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });
- cy.visit(`/apps/${APP_SLUG}`);
-
- dataAppIframe(APP_DISPLAY_NAME).within(() => {
- cy.findByTestId("action-execute", { timeout: 30000 }).click();
- cy.findByTestId("action-output").should("have.text", "executed");
- });
-
- cy.wait("@execute")
- .its("request.url")
- .should("contain", `/api/action/${copiedActionId}/execute`);
- });
- });
- });
- },
-);
diff --git a/e2e/test/scenarios/data-apps/sync-resources-production.cy.spec.ts b/e2e/test/scenarios/data-apps/sync-resources-production.cy.spec.ts
deleted file mode 100644
index b2d292e1386..00000000000
--- a/e2e/test/scenarios/data-apps/sync-resources-production.cy.spec.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { SAMPLE_DB_ID, USERS } from "e2e/support/cypress_data";
-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-import {
- addUserToGroup,
- createDataAppApiKey,
- dataAppIframe,
- dataAppPermissionGroupId,
- mockDataApp,
- syncDataAppResources,
-} from "e2e/support/helpers";
-
-const { H } = cy;
-const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
-
-const APP_SLUG = "synced-app";
-const APP_DISPLAY_NAME = "Synced App";
-
-const APP_ROOT = () =>
- `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${APP_SLUG}`;
-const QUERY_FILE = () => `${APP_ROOT()}/queries/orders.query.ts`;
-const MANIFEST_FILE = () => `${APP_ROOT()}/data_app.yaml`;
-const LOCKFILE = () => `${APP_ROOT()}/resources_metadata.json`;
-
-/** The manifest as source control holds it. */
-const AUTHORED_MANIFEST = [
- "version: 1",
- `name: ${APP_DISPLAY_NAME}`,
- `slug: ${APP_SLUG}`,
- "path: ./dist/index.js",
- "entity_id: 4vxutiAe703DZgttXwORO",
- "serdes/meta:",
- "- model: DataApp",
- " id: 4vxutiAe703DZgttXwORO",
- " label: synced-app",
- "",
-].join("\n");
-
-/** The declaration as source control holds it, with no generated ID yet. */
-const AUTHORED_DECLARATION = [
- "import {",
- " aggregations,",
- " breakout,",
- " defineQuery,",
- '} from "@metabase/embedding-sdk-react/data-app";',
- "",
- "/**",
- " * Authored state, as it sits in source control before a sync. `id` is the sample",
- " * database's ORDERS table (`SAMPLE_DATABASE.ORDERS_ID`); the spec writes this file",
- " * from the same constant, so a snapshot change fails loudly rather than silently.",
- " * Synchronization writes `savedQuestionSourceId` in here, and the spec restores",
- " * this file afterwards.",
- " */",
- "const OrdersUserId = {",
- ' type: "column" as const,',
- ` fieldId: ${ORDERS.USER_ID},`,
- ` tableId: ${ORDERS_ID},`,
- ' name: "USER_ID",',
- ' displayName: "User ID",',
- ' jsType: "number",',
- "};",
- "",
- "export const OrdersCount = defineQuery({",
- ` source: { type: "table", id: ${ORDERS_ID} },`,
- " aggregations: [aggregations.count()],",
- " breakouts: [breakout(OrdersUserId)],",
- "});",
-].join("\n");
-
-/**
- * What a shipped data app actually does: outside the dev preview `isDataAppDev()`
- * is false, so the SDK addresses the synchronized copy — the only resource an
- * app's viewers are permitted to read — rather than the authored source.
- */
-describe("scenarios > data apps > sync-resources in production", () => {
- // Restore the source files and remove the lockfile before each synchronization.
- const restoreAuthoredFixture = () => {
- cy.writeFile(QUERY_FILE(), `${AUTHORED_DECLARATION}\n`);
- cy.writeFile(MANIFEST_FILE(), AUTHORED_MANIFEST);
- cy.task("removeDataAppPaths", { paths: [LOCKFILE()] });
- };
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- H.activateToken("bleeding-edge");
-
- restoreAuthoredFixture();
- createDataAppApiKey().as("apiKey");
- });
-
- after(() => {
- restoreAuthoredFixture();
- });
-
- /** Synchronizes the fixture and returns the card the app must now address. */
- const syncApp = () =>
- cy.get<string>("@apiKey").then((apiKey) =>
- syncDataAppResources(apiKey, APP_ROOT()).then(({ ok, error }) => {
- expect(error, "sync-resources failed").to.eq(null);
- expect(ok).to.eq(true);
-
- return cy
- .readFile(`${APP_ROOT()}/resources_metadata.json`)
- .then((lockfile) => {
- const cardId = lockfile.queries?.[0]?.savedQuestionSourceId;
-
- if (typeof cardId !== "number") {
- throw new Error("The sync wrote no query entry to the lockfile.");
- }
-
- return cy.wrap(cardId, { log: false });
- });
- }),
- );
-
- it("runs the synchronized card rather than the authored table query", () => {
- syncApp().then((cardId) => {
- cy.readFile(QUERY_FILE()).should(
- "contain",
- `savedQuestionSourceId: ${cardId}`,
- );
-
- cy.intercept("POST", "/api/dataset").as("dataset");
- mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });
- cy.visit(`/apps/${APP_SLUG}`);
-
- dataAppIframe(APP_DISPLAY_NAME).within(() => {
- cy.findByTestId("synced-app-total", { timeout: 30000 }).should(
- ($total) => {
- expect(Number($total.text())).to.be.greaterThan(0);
- },
- );
- });
-
- // The proof that production took the synchronized path: the query runs
- // against the copied card, not the table the declaration names.
- cy.wait("@dataset").then(({ request }) => {
- const [stage] = request.body.stages ?? [];
- expect(stage?.["source-card"], "runs the synchronized card").to.eq(
- cardId,
- );
- expect(stage?.["source-table"], "not the authored table").to.be
- .undefined;
- });
- });
- });
-
- // The swap is only safe if both sides return the same thing. The dev preview
- // runs the authored query unswapped; production runs the card it was published
- // as. A deployed app cannot run the authored query at all, so the two sides are
- // captured separately rather than side by side.
- it("returns the same rows from the published card as from the authored query", () => {
- syncApp().then((cardId) => {
- cy.request("POST", "/api/dataset", {
- type: "query",
- database: SAMPLE_DB_ID,
- query: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- breakout: [["field", ORDERS.USER_ID, null]],
- },
- }).then(({ body: authored }) => {
- cy.request("POST", `/api/card/${cardId}/query`).then(
- ({ body: published }) => {
- expect(published.data.rows).to.deep.eq(authored.data.rows);
- expect(
- published.data.rows[0][1],
- "a match on two empty results would be vacuous",
- ).to.be.greaterThan(0);
- },
- );
- });
- });
- });
-
- it("serves the app to a member of its permission group", () => {
- syncApp().then(() => {
- dataAppPermissionGroupId(APP_SLUG).then((groupId) => {
- addUserToGroup(groupId, USERS.normal.email);
-
- cy.signInAsNormalUser();
- mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });
- cy.visit(`/apps/${APP_SLUG}`);
-
- dataAppIframe(APP_DISPLAY_NAME).within(() => {
- cy.findByTestId("synced-app-total", { timeout: 30000 }).should(
- ($total) => {
- expect(Number($total.text())).to.be.greaterThan(0);
- },
- );
- });
- });
- });
- });
-});
diff --git a/e2e/test/scenarios/data-apps/sync.cy.spec.ts b/e2e/test/scenarios/data-apps/sync.cy.spec.ts
index 325ba2a13b1..35d9c0baf03 100644
--- a/e2e/test/scenarios/data-apps/sync.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/sync.cy.spec.ts
@@ -1,5 +1,10 @@
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { DataApp } from "metabase-types/api";
+
const { H } = cy;
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
/**
* Drives a real remote-sync pull of a repo whose `data_apps/` holds two apps, each a `data_app.yaml` with its bundle
* next to it, and asserts that pulls materialize and remove them.
@@ -40,15 +45,36 @@ describe("scenarios > data apps > repo sync", () => {
});
cy.request("/api/apps/good/bundle").its("status").should("eq", 200);
+
+ // The good app's collection files were loaded with it: its collection, and
+ // the saved question in it, addressed by the entity IDs the files carry.
+ cy.request<DataApp>("/api/apps/good").then(({ body: app }) => {
+ cy.request("/api/collection/goodAppCollection0000")
+ .its("body.id")
+ .should("eq", app.resource_collection_id);
+ cy.request("/api/card/goodAppOrdersQuestion")
+ .its("body.collection_id")
+ .should("eq", app.resource_collection_id);
+ expect(app.table_ids).to.deep.eq([ORDERS_ID]);
+ });
});
- it("removes an app whose directory is removed from the repo on the next sync", () => {
+ it("removes an app whose directory and collection files are removed from the repo on the next sync", () => {
H.copySyncedCollectionFixture();
H.copySyncedDataAppsFixture();
H.commitToRepo("Add data apps");
H.configureGitAndPullChanges("read-write");
- cy.exec(`rm -rf -- "${H.LOCAL_GIT_PATH}/data_apps/good"`);
+ // An author deletes an app by deleting its directory and its collection's
+ // files in one commit; the pull deletes the app, and the app deletes its
+ // collection with what it holds.
+ cy.task("removeDataAppPaths", {
+ paths: [
+ `${H.LOCAL_GIT_PATH}/data_apps/good`,
+ `${H.LOCAL_GIT_PATH}/collections/data_apps/data_app__good_app.yaml`,
+ `${H.LOCAL_GIT_PATH}/collections/data_apps/data_app__good_app`,
+ ],
+ });
H.commitToRepo("Remove the good app from the repo");
H.configureGitAndPullChanges("read-write");
@@ -60,5 +86,17 @@ describe("scenarios > data apps > repo sync", () => {
cy.request({ url: "/api/apps/good", failOnStatusCode: false })
.its("status")
.should("eq", 404);
+ cy.request({
+ url: "/api/card/goodAppOrdersQuestion",
+ failOnStatusCode: false,
+ })
+ .its("status")
+ .should("eq", 404);
+ cy.request({
+ url: "/api/collection/goodAppCollection0000",
+ failOnStatusCode: false,
+ })
+ .its("status")
+ .should("eq", 404);
});
});
diff --git a/e2e/test/scenarios/data-apps/user-access.cy.spec.ts b/e2e/test/scenarios/data-apps/user-access.cy.spec.ts
index ec032ee8c2b..c4d31c320fc 100644
--- a/e2e/test/scenarios/data-apps/user-access.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/user-access.cy.spec.ts
@@ -5,6 +5,7 @@ import {
COLLECTION_GROUP_ID,
DATA_GROUP_ID,
} from "e2e/support/cypress_sample_instance_data";
+import type { PortableTable } from "e2e/support/helpers";
import {
type DataApp,
DataPermission,
@@ -14,11 +15,11 @@ import {
const { H } = cy;
-const DATA_APP_NAME = "user-access-test";
-
const { ORDERS_ID, PRODUCTS_ID } = SAMPLE_DATABASE;
const SYNCED_APP_SLUG = "good";
+const DATA_APP_NAME = SYNCED_APP_SLUG;
+const DATA_APP_DISPLAY_NAME = "Good App";
const ALLOWED_HOST = "https://secret-api.data-app.test";
const NORMAL_USER_NAME = `${USERS.normal.first_name} ${USERS.normal.last_name}`;
@@ -29,20 +30,10 @@ describe("scenarios > data apps > user access (EMB-2328)", () => {
H.restore();
cy.signInAsAdmin();
H.activateToken("bleeding-edge");
-
- cy.request<DataApp>("POST", `/api/apps/${DATA_APP_NAME}/draft`).then(
- ({ body: app }) => {
- expect(app.permission_group_id).not.to.be.null;
-
- cy.wrap(app.permission_group_id, { log: false }).as("dataAppGroupId");
- },
- );
});
it("adds and removes a data app user by pasting a single email", () => {
- cy.request("PUT", `/api/apps/${DATA_APP_NAME}/table-dependencies`, {
- table_ids: [],
- });
+ pullAppReading([]);
cy.visit("/admin/settings/apps");
openManageUserAccessFromAppRow();
@@ -54,7 +45,7 @@ describe("scenarios > data apps > user access (EMB-2328)", () => {
H.main().within(() => {
cy.findByRole("link", { name: "Data apps" }).should("be.visible");
- cy.findByText(DATA_APP_NAME).should("be.visible");
+ cy.findByText(DATA_APP_DISPLAY_NAME).should("be.visible");
cy.findByText("No one has access yet").should("be.visible");
cy.findByRole("heading", { name: "Manage access to this app" }).should(
@@ -92,6 +83,8 @@ describe("scenarios > data apps > user access (EMB-2328)", () => {
});
it("adds users from comma-separated emails without duplicating existing members", () => {
+ pullAppReading([]);
+
cy.get<number>("@dataAppGroupId").then((groupId) => {
H.addUserToGroup(groupId, USERS.normal.email);
});
@@ -146,12 +139,10 @@ describe("scenarios > data apps > user access (EMB-2328)", () => {
H.activateToken("bleeding-edge");
- cy.get<Table>("@sqliteTable").then(({ id, schema }) => {
+ cy.get<Table>("@sqliteTable").then(({ name, schema }) => {
expect(schema).to.equal("");
- cy.request("PUT", `/api/apps/${DATA_APP_NAME}/table-dependencies`, {
- table_ids: [id],
- });
+ pullAppReading([["sqlite", null, name]]);
});
cy.get<number>("@dataAppGroupId").then((groupId) => {
@@ -238,9 +229,16 @@ describe("scenarios > data apps > user access (EMB-2328)", () => {
},
});
- cy.request("PUT", `/api/apps/${DATA_APP_NAME}/table-dependencies`, {
- table_ids: [ORDERS_ID, PRODUCTS_ID],
- });
+ pullAppReading([
+ ["Sample Database", "PUBLIC", "ORDERS"],
+ ["Sample Database", "PUBLIC", "PRODUCTS"],
+ ]);
+ cy.request<DataApp>(`/api/apps/${DATA_APP_NAME}`)
+ .its("body.table_ids")
+ .should(
+ "deep.equal",
+ [ORDERS_ID, PRODUCTS_ID].sort((a, b) => a - b),
+ );
cy.get<number>("@dataAppGroupId").then((groupId) => {
H.addUserToGroup(groupId, USERS.normal.email);
@@ -336,7 +334,7 @@ describe("scenarios > data apps > user access (EMB-2328)", () => {
cy.visit("/admin/settings/apps");
dataAppRow().within(() => {
- cy.findByText(DATA_APP_NAME).should("be.visible");
+ cy.findByText(DATA_APP_DISPLAY_NAME).should("be.visible");
cy.findByRole("link", {
name: "Some users are missing data access.",
@@ -356,6 +354,7 @@ describe("scenarios > data apps > user access (EMB-2328)", () => {
"name: Good App",
`slug: ${SYNCED_APP_SLUG}`,
"path: ./index.js",
+ "collection: goodAppCollection0000",
"allowed_hosts:",
` - ${ALLOWED_HOST}`,
"entity_id: Ioxf30LzIQCGwbCNtaG62",
@@ -440,10 +439,36 @@ const dataAppRow = () =>
function openManageUserAccessFromAppRow() {
dataAppRow()
- .findByRole("button", { name: `Actions for ${DATA_APP_NAME}` })
+ .findByRole("button", { name: `Actions for ${DATA_APP_DISPLAY_NAME}` })
.click();
H.popover().findByText("Manage user access").click();
}
const userRow = (email: string) => H.main().findByText(email).closest("tr");
+
+/**
+ * Pulls the example data apps with the `good` app's saved questions replaced by
+ * one per table in `tables`, so the app depends on exactly those tables. The
+ * import records them as the app's table dependencies.
+ */
+function pullAppReading(tables: PortableTable[]) {
+ H.pullExampleDataApps({
+ goodAppCards: tables.map((table, index) =>
+ H.dataAppRepresentations.card({
+ entityId: `goodAppReads${String(index).padStart(9, "0")}`,
+ name: table[2],
+ type: "question",
+ collection: "goodAppCollection0000",
+ table,
+ }),
+ ),
+ });
+
+ cy.request<DataApp>(`/api/apps/${DATA_APP_NAME}`).then(({ body: app }) => {
+ expect(app.resource_collection_id).to.be.a("number");
+ expect(app.permission_group_id).not.to.eq(null);
+
+ cy.wrap(app.permission_group_id, { log: false }).as("dataAppGroupId");
+ });
+}
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/README.md b/enterprise/backend/src/metabase_enterprise/data_apps/README.md
index 698c12f29c9..f84139bc96f 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/README.md
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/README.md
@@ -33,12 +33,15 @@ data_apps/
data_app.yaml # serdes/meta, entity_id, slug, name, description, version, path, allowed_hosts, collection
dist/index.js # the bundle
collections/
- main/
+ data_apps/
data_app__sales.yaml # the app's resource collection (namespace: data-apps)
data_app__sales/
*.yaml # the saved questions, metric copies, and action copies the app runs
```
+Collections of the `data-apps` namespace are written under `collections/data_apps/`, as the
+`transforms` and `snippets` namespaces have their folders.
+
The YAML keeps the keys a hand-written manifest uses: `slug` is the `name` column, `name` the
`display_name`, `path` the `bundle_path`, and `collection` the entity ID of the app's resource
collection, which the app depends on and so loads after. The bundle travels as a serdes *resource
@@ -47,45 +50,48 @@ the YAML, and ingestion reads the paths `serdes/resource-paths` returns back in.
must stay inside the entity's directory.
`enabled` is admin-owned and never leaves the instance; the permission group and `table_ids` are
-server-managed; `bundle_hash` is recomputed from the bundle on import. Drafts are not exported.
+server-managed; `bundle_hash` is recomputed from the bundle on import.
A targeted export of an app brings its collection and what it holds along (`serdes/descendants`).
-An import matches an app by `entity_id`, falling back to its slug so it takes over a draft, and
-reasserts the app's resources. A manifest that names a collection the repository lacks, or one
+An import matches an app by `entity_id` and reasserts the app's resources; a manifest whose slug an app
+made on the instance holds is refused. A manifest that names a collection the repository lacks, or one
other than the collection the app already owns, fails to load. It is a no-op without the
`:data-apps` feature.
-Remote sync treats data apps like any other entity, globally rather than per collection; the app's
-collection and what it holds travel with it as its serdes descendants. Because the bundle is a separate file, a pull that changes
-only a bundle, or an export that touches an app, takes the full rather than the incremental path.
-An app's directory also holds its source, which serialization doesn't own, so exports replace only
-the YAML and resource files in `data_apps/`.
-
-## Drafts
-
-`POST /api/apps/:slug/draft` reserves a slug and creates the app's resources before the app itself
-exists, so its resources can be prepared ahead of time. Creating the app fills the draft.
+Remote sync treats data apps like any other entity, globally rather than per collection, and their
+collections like any namespace's: in scope for import, cleanup and export by their namespace. Before
+an import loads anything, `resource_validation.clj` checks every manifest with its collection and
+the cards and actions in it, and fails the pull naming the file that a load couldn't take as the
+author meant it. Because the bundle is a separate file, a pull that changes only a bundle, or an
+export that touches an app, takes the full rather than the incremental path. An app's directory
+also holds its source, which serialization doesn't own, so exports replace only the YAML and
+resource files in `data_apps/`.
+
+An author deletes an app by deleting its directory and its collection's files under
+`collections/data_apps/` in one commit: the pull deletes the app, and the app's `before-delete`
+hook deletes the collection with what it holds. A commit that deletes the directory but keeps the
+collection's files still deletes the app and its collection; the next export removes the files,
+and until then a full pull loads them back as a collection no app owns.
## 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 that aren't drafts.
+- `GET /api/apps` — list; `?available=true` filters to enabled apps.
- `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.
- `GET /api/apps/sandbox-host` — the empty document loaded as the Near-Membrane realm iframe,
carrying the CSP that confines `'unsafe-eval'` to that realm.
-- `POST /api/apps` — create an app from its manifest fields and bundle text, filling a draft with
- the same slug (superuser).
+- `POST /api/apps` — create an app from its manifest fields and bundle text (superuser).
- `PUT /api/apps/:slug` — update manifest fields or the bundle, or toggle `enabled` (superuser).
- `DELETE /api/apps/:slug` — drop a row, its bundle, and its owned resources (superuser).
-- `POST /api/apps/:slug/draft` — create or reuse a draft row with its resources (superuser).
-- `POST /api/apps/:slug/query` — resolve an authored query definition into a serializable
- Metabase query plus the table IDs it touches (superuser).
- `GET /api/apps/repo-status` — whether a repo is connected (superuser).
+- `POST /api/apps/serialize-resources` — what the files of an app's collection are written from: the query Metabase builds
+ from each `defineQuery` definition, and the actions and metrics it copies, all as serialization writes
+ them (`resource_serialization.clj`). An action must belong to no model (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
@@ -97,7 +103,7 @@ middleware's lookup doesn't pull in route code.
## Permissions
-Each app owns two server-managed resources, created with the app (or its draft) and reasserted on
+Each app owns two server-managed resources, created with the app and reasserted on
every import: a **collection** holding the copies the app is served from (saved questions, actions,
table-sourced metrics) and a **permissions group** its users belong to. The collection is a root
collection of the `data-apps` namespace, created as the app's row is inserted unless an import names
@@ -118,18 +124,24 @@ view-data of its own, so a viewer without access to an app's tables (e.g. a sand
data from it — their own groups' permissions and sandboxes apply unchanged. Because the group grants
nothing, it can never lift another group's sandbox, so sandboxing needs no data-app special-casing.
-**Managing is superuser-only** — enabling, disabling, deleting, drafts, query resolution, and repo
-status.
+**Managing is superuser-only** — enabling, disabling, deleting, and repo status.
+Exporting an app's resources also needs a superuser.
## Namespace map
| Namespace | Responsibility |
| --------------------- | --------------------------------------------------------------------------------------------------- |
-| `apps.clj` | Creating apps and drafts; the connected repository's URL. |
+| `apps.clj` | Creating apps; the connected repository's URL. |
+| `core.clj` | What other modules ask: resource file problems and table dependencies. |
| `config.clj` | The serialized layout and data app contract version constants. |
| `schema.clj` | Column schemas, with the normalization and validation every write goes through. |
| `api.clj` | The `/api/apps` endpoints, bundle serving, ETag handling. |
| `resources.clj` | Lifecycle of the app-owned collection and permission group: creation, view-data blocking, deletion. |
| `models/data_app.clj` | The `:model/DataApp` Toucan model: hooks, permissions, default fields, serialization. |
+| `resource_serialization.clj` | The serialization an app's resource files are written from: built queries, actions, metrics. |
+| `query_definition.clj`| The closed schema of a `defineQuery` definition the serialization accepts. |
+| `resource_validation.clj` | What the files of an app's collection may hold, checked on the whole snapshot before an import. |
+| `resource_tables.clj` | The tables an app's resources read, recorded on the app after an import. |
+| `db.clj` | The module's application-database queries. |
| `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.clj
index 93743739a3a..efe8372d0ba 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
@@ -12,6 +12,7 @@
[metabase-enterprise.data-apps.db :as data-apps.db]
[metabase-enterprise.data-apps.models.data-app :as data-app]
[metabase-enterprise.data-apps.query-definition :as query-definition]
+ [metabase-enterprise.data-apps.resource-serialization :as data-app.resource-serialization]
[metabase-enterprise.data-apps.schema :as data-apps.schema]
[metabase-enterprise.data-apps.user-access :as data-app.user-access]
[metabase.api-scope.data-app :as api-scope]
@@ -19,9 +20,6 @@
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
[metabase.events.core :as events]
- [metabase.lib-be.core :as lib-be]
- [metabase.lib-be.schema :as lib-be.schema]
- [metabase.lib.core :as lib]
[metabase.remote-sync.core :as remote-sync]
[metabase.settings.core :as setting]
[metabase.util :as u]
@@ -135,37 +133,6 @@
[:configured :boolean]
[:url [:maybe :string]]])
-(def ^:private MetricResponse
- [:map {:closed true}
- [:id ms/PositiveInt]
- [:name ms/NonBlankString]
- [:type [:enum :metric]]
- [:collection_id [:maybe ms/PositiveInt]]
- [:dataset_query ::lib-be.schema/maybe-legacy-query]
- [:database_id ms/PositiveInt]
- [:display [:maybe [:or :keyword :string]]]
- [:visualization_settings [:maybe ms/VisualizationSettings]]
- [:description [:maybe :string]]])
-
-(def ^:private QueryResolutionResponse
- [:map
- [:database_id ms/PositiveInt]
- [:dataset_query ::lib-be.schema/maybe-legacy-query]
- [:table_ids [:sequential ms/PositiveInt]]
- [:metrics [:sequential MetricResponse]]])
-
-(def ^:private TableDependenciesRequest
- [:map {:closed true}
- [:table_ids [:sequential {:distinct true} ms/PositiveInt]]])
-
-(def ^:private QueryTableDependenciesRequest
- [:map {:closed true}
- [:dataset_queries [:sequential ::lib-be.schema/maybe-legacy-query]]])
-
-(def ^:private QueryTableDependenciesResponse
- [:map {:closed true}
- [:table_ids [:sequential ms/PositiveInt]]])
-
(def ^:private PermissionWarningsRequest
[:map {:closed true}
[:user_ids [:sequential {:min 1 :max 100 :distinct true} ms/PositiveInt]]])
@@ -183,6 +150,39 @@
[:user_id ms/PositiveInt]
[:missing_tables [:sequential MissingTable]]])
+(def ^:private SerializeResourcesRequest
+ [:map {:closed true}
+ [:collection ms/NanoIdString]
+ [:queries {:default []} [:sequential [:map {:closed true}
+ [:export ms/NonBlankString]
+ [:entity_id ms/NanoIdString]
+ [:query ::query-definition/query-definition]]]]
+ [:actions {:default []} [:sequential {:distinct true} ms/PositiveInt]]])
+
+(def ^:private SerializedQuery
+ [:or
+ [:map {:closed true}
+ [:export :string]
+ [:entity :map]
+ [:metrics [:sequential :string]]]
+ [:map {:closed true}
+ [:export :string]
+ [:error :string]]])
+
+(def ^:private SerializedEntity
+ [:or
+ [:map {:closed true}
+ [:id ms/PositiveInt]
+ [:entity :map]]
+ [:map {:closed true}
+ [:id ms/PositiveInt]
+ [:error :string]]])
+
+(def ^:private SerializeResourcesResponse
+ [:map {:closed true}
+ [:queries [:sequential SerializedQuery]]
+ [:actions [:sequential SerializedEntity]]
+ [:metrics [:sequential SerializedEntity]]])
;;; --------------------------------------------- Repo status ---------------------------------------------
(api.macros/defendpoint :get "/repo-status" :- RepoStatusResponse
@@ -267,7 +267,7 @@
app)
(api.macros/defendpoint :get "/" :- [:sequential [:or DataAppResponse PublicDataAppResponse]]
- "List the data apps. Pass `available=true` to return only enabled apps that aren't drafts. An outdated app is never
+ "List the data apps. Pass `available=true` to return only enabled apps. An outdated app is never
available, and otherwise listed only to superusers, who see it badged."
[_route-params
{:keys [available]} :- [:map {:closed true} [:available {:optional true} [:maybe :boolean]]]]
@@ -299,12 +299,12 @@
(api/check-403 (remote-sync/model-editable? :model/DataApp app)))
(api.macros/defendpoint :post "/" :- DataAppResponse
- "Create a data app from its manifest fields and bundle. A draft with the same slug becomes the app."
+ "Create a data app from its manifest fields and bundle."
[_route-params
_query-params
body :- CreateDataAppRequest]
(api/create-check :model/DataApp body)
- (check-editable! (assoc body :draft false))
+ (check-editable! body)
(let [app (data-apps.db/data-app (data-apps.apps/create-app! (with-bundle body)))]
(events/publish-event! :event/data-app-create {:object app :user-id api/*current-user-id*})
(data-app-response app)))
@@ -339,19 +339,6 @@
;; above (returning `generic-204-no-content` would fail that validation).
nil)
-(api.macros/defendpoint :put ["/:slug/table-dependencies" :slug slug-regex] :- DataAppResponse
- "Store the tables used by the resources from a successful data app resource synchronization."
- [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]
- _query-params
- {table-ids :table_ids} :- TableDependenciesRequest]
- (let [app (write-check-data-app slug)
- table-ids (vec (sort table-ids))]
- (api/check-400 (= (set table-ids)
- (data-apps.db/existing-table-ids table-ids))
- (tru "One or more tables do not exist."))
- (data-apps.db/update-data-app! (:id app) {:table_ids table-ids})
- (data-app-response (data-apps.db/data-app (:id app)))))
-
(api.macros/defendpoint :post ["/:slug/user-permission-warnings" :slug slug-regex]
:- [:sequential PermissionWarning]
"Return warnings for users who cannot access every table used by a data app."
@@ -367,84 +354,17 @@
(tru "Tenant users cannot be added to data apps."))
(data-app.user-access/permission-warnings (:table_ids app) users)))
-(defn- query-table-ids
- "The tables a query reads, including ones it reaches only through an implicit join."
- [query]
- (into (set (lib/all-source-table-ids query))
- (lib/all-implicitly-joined-table-ids query)))
-
-(defn- referenced-card-ids
- "Ids of the cards -- metrics, source questions, template-tag questions -- that `metric`'s own
- definition reads."
- [metric]
- (-> (lib-be/application-database-metadata-provider (:database_id metric))
- (lib/query (:dataset_query metric))
- lib/all-source-card-ids))
-
-(defn- referenced-metrics
- "Return direct metric references, rejecting any whose own definition reads another card.
-
- Sync copies a referenced metric but rewrites nothing inside the copy, and copies nothing the copy
- in turn reads, so those references still point at the originals. The app would publish successfully
- and then fail for every viewer without access to the originals' collections, so refuse it here.
-
- This runs on every sync rather than at codegen, so a metric edited into this shape after its schema
- was generated is caught too."
- [query]
- (let [metric-ids (lib/all-source-card-ids query)
- metrics (sort-by :id (data-apps.db/metrics-by-ids metric-ids))
- nested (filter (comp seq referenced-card-ids) metrics)]
- (api/check-400 (empty? nested)
- (tru "Data app queries cannot use metrics that reference other saved questions or metrics: {0}"
- (str/join ", " (map :name nested))))
- (mapv #(update (select-keys % [:id :name :type :collection_id :dataset_query
- :database_id :display :visualization_settings :description])
- :dataset_query
- lib/prepare-for-serialization)
- metrics)))
-
-(api.macros/defendpoint :post ["/:slug/query" :slug slug-regex] :- QueryResolutionResponse
- "Resolve an authored data-app query definition into a serializable Metabase query."
- [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]
- _query-params
- query-def :- ::query-definition/query-definition]
- (write-check-data-app slug)
- (let [{source-type :type, table-id :id} (get-in query-def [:stages 0 :source])
- _ (api/check-400 (= (keyword source-type) :table)
- "Data app query definitions must use a table source.")
- database-id (api/check-404 (data-apps.db/table-database-id table-id))
- query (lib/test-query (lib-be/application-database-metadata-provider database-id) query-def)]
- {:database_id database-id
- :dataset_query (lib/prepare-for-serialization query)
- :table_ids (vec (sort (query-table-ids query)))
- :metrics (referenced-metrics query)}))
-
-(api.macros/defendpoint :post ["/:slug/query-table-dependencies" :slug slug-regex]
- :- QueryTableDependenciesResponse
- "Return the tables read by already-saved queries, including ones reached only through an implicit join.
-
- Sync copies actions and metrics whose queries it never resolves through `/query`, and only
- this metadata-based lookup sees an implicit join: the id of a table reached through a foreign key
- appears nowhere in the query itself."
- [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]
+(api.macros/defendpoint :post "/serialize-resources" :- SerializeResourcesResponse
+ "Serialize what the files of a data app's collection are written from, as serialization writes it: the saved question
+ holding the query Metabase builds from each `defineQuery` definition in `queries`, in the app's `collection`,
+ the actions in `actions`, which must belong to no model, and the metrics the queries aggregate. Each item answers
+ on its own, with its serialization or the error that stops it. For superusers: the files are written into the app's
+ repository, which only an admin works with."
+ [_route-params
_query-params
- {dataset-queries :dataset_queries} :- QueryTableDependenciesRequest]
- (write-check-data-app slug)
- {:table_ids (->> dataset-queries
- (mapcat (fn [dataset-query]
- (-> (lib-be/application-database-metadata-provider (:database dataset-query))
- (lib/query dataset-query)
- query-table-ids)))
- set
- sort
- vec)})
-
-(api.macros/defendpoint :post ["/:slug/draft" :slug slug-regex] :- DataAppResponse
- "Create or reuse a data app draft, which reserves a slug and the app's resources before the app is created."
- [{:keys [slug]} :- [:map {:closed true} [:slug ::data-apps.schema/slug]]]
- (api/create-check :model/DataApp {:name slug})
- (data-apps.apps/ensure-draft! slug)
- (data-app-response (data-apps.db/data-app-by-slug slug)))
+ {:keys [queries actions collection]} :- SerializeResourcesRequest]
+ (api/check-superuser)
+ (data-app.resource-serialization/serialize-resources collection queries actions))
;; Not tagged `data-apps:base`, though the bundle route below is — which looks backwards until
;; you place the two callers. `DataAppView` fetches this metadata on the *host* page to decide
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/apps.clj b/enterprise/backend/src/metabase_enterprise/data_apps/apps.clj
index 02f6bc155e7..0f72cf61179 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/apps.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/apps.clj
@@ -1,9 +1,8 @@
(ns metabase-enterprise.data-apps.apps
- "Creating data apps and their drafts, and the connected repository's URL."
+ "Creating data apps, and the connected repository's URL."
(:require
[clojure.string :as str]
[metabase-enterprise.data-apps.db :as data-apps.db]
- [metabase-enterprise.data-apps.resources :as data-app.resources]
[metabase.api.common :as api]
[metabase.settings.core :as setting]
[metabase.util.i18n :refer [tru]]
@@ -11,10 +10,6 @@
(set! *warn-on-reflection* true)
-(def ^:private draft-bundle-path
- "The bundle path of a draft, until the app is created."
- "dist/index.js")
-
(defn repo-url
"The connected remote-sync repository URL, or nil when none is configured. Read
by keyword so this OSS namespace has no compile-time dependency on the
@@ -25,39 +20,10 @@
(when-not (str/blank? url)
url)))
-(defn- create-draft!
- [slug]
- (let [app (t2/with-transaction [_conn]
- (when-not (data-apps.db/data-app-exists? slug)
- (data-apps.db/insert-data-app!
- {:name slug
- :display_name slug
- :bundle_path draft-bundle-path
- :draft true}))
- (data-apps.db/data-app-by-slug slug))]
- (data-app.resources/ensure-resources! app)))
-
-(defn ensure-draft!
- "Create a data app draft when needed and ensure its permission resources.
- Creating the app later fills the same row with its manifest and bundle."
- [slug]
- (try
- (create-draft! slug)
- (catch Throwable e
- (if (data-apps.db/data-app-exists? slug)
- (create-draft! slug)
- (throw e)))))
-
(defn create-app!
- "Create the data app `row`, filling the draft with its slug if there is one, and return its ID. Throws a 409
- when a data app that isn't a draft already has the slug."
+ "Create the data app `row` and return its ID. Throws a 409 when a data app already has the slug."
[{slug :name :as row}]
(t2/with-transaction [_conn]
- (let [existing (data-apps.db/data-app-by-slug slug)
- row (assoc row :draft false)]
- (api/check (or (nil? existing) (:draft existing))
- [409 (tru "A data app with this slug already exists.")])
- (if existing
- (do (data-apps.db/update-data-app! (:id existing) (dissoc row :name))
- (:id existing))
- (data-apps.db/insert-data-app-returning-pk! row)))))
+ (api/check (not (data-apps.db/data-app-exists? slug))
+ [409 (tru "A data app with this slug already exists.")])
+ (data-apps.db/insert-data-app-returning-pk! row)))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/core.clj b/enterprise/backend/src/metabase_enterprise/data_apps/core.clj
new file mode 100644
index 00000000000..b9cd0f49064
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/core.clj
@@ -0,0 +1,14 @@
+(ns metabase-enterprise.data-apps.core
+ "What other modules may ask the data-apps module: what the files of an app's collection may hold, and the tables
+ those read."
+ (:require
+ [metabase-enterprise.data-apps.resource-tables :as resource-tables]
+ [metabase-enterprise.data-apps.resource-validation :as resource-validation]
+ [potemkin :as p]))
+
+(p/import-vars
+ [resource-tables
+ record-table-dependencies!]
+ [resource-validation
+ problems
+ warnings])
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj
index 07b9a918c0a..d8049b86b36 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj
@@ -12,7 +12,7 @@
(def non-blob-columns
"Every DataApp column except the raw bundle blob."
[:id :entity_id :name :display_name :description :version :bundle_path :enabled :allowed_hosts
- :resource_collection_id :permission_group_id :table_ids :draft :bundle_hash :created_at :updated_at])
+ :resource_collection_id :permission_group_id :table_ids :bundle_hash :created_at :updated_at])
(def ^:private non-blob-model
(into [:model/DataApp] non-blob-columns))
@@ -27,25 +27,17 @@
[slug :- :string]
(t2/select-one non-blob-model :name slug))
-(mu/defn draft-by-slug
- "The draft DataApp named `slug` without its bundle, or nil."
- [slug :- :string]
- (t2/select-one non-blob-model :name slug :draft true))
-
(mu/defn enabled-data-app-by-slug
"The enabled DataApp named `slug` without its bundle, or nil."
[slug :- :string]
(t2/select-one non-blob-model :name slug :enabled true))
(mu/defn data-apps
- "Every DataApp without its bundle, ordered by display name; only the enabled ones that aren't drafts when
- `available?`."
+ "Every DataApp without its bundle, ordered by display name; only the enabled ones when `available?`."
[available? :- [:maybe :boolean]]
(t2/select non-blob-model
(cond-> {:order-by [[:display_name :asc]]}
- available? (assoc :where [:and
- [:= :enabled true]
- [:= :draft false]]))))
+ available? (assoc :where [:= :enabled true]))))
(mu/defn data-app-bundle
"The bundle bytes of the DataApp with `data-app-id`."
@@ -63,37 +55,26 @@
filter-column (assoc :where [:in filter-column filter-ids])
(seq order-columns) (assoc :order-by (mapv (fn [column] [column :asc]) order-columns)))))
-(defn table-database-id
- "The database ID for the Table with `table-id`, or nil."
- [table-id]
- (t2/select-one-fn :db_id :model/Table :id table-id
- {:from [(warehouse-schema-overlay/table-query {:user-settings? false})]}))
-
-(defn existing-table-ids
- "The IDs from `table-ids` that belong to existing Tables."
- [table-ids]
- (if (seq table-ids)
- (t2/select-pks-set :model/Table :id [:in table-ids]
- {:from [(warehouse-schema-overlay/table-query {:user-settings? false})]})
- #{}))
-
(defn users-for-permission-warnings
"The fields needed to calculate permission warnings for Users with `user-ids`."
[user-ids]
(t2/select [:model/User :id :is_superuser :is_active :tenant_id] :id [:in user-ids]))
-(defn metrics-by-ids
- "The metric Cards with `metric-ids`."
- [metric-ids]
- (if (seq metric-ids)
- (t2/select :model/Card :id [:in metric-ids] :type "metric")
- []))
-
(mu/defn data-app-exists?
"Whether a DataApp named `slug` exists."
[slug :- :string]
(t2/exists? :model/DataApp :name slug))
+(mu/defn data-app-entity-id-named
+ "The `:entity_id` of the DataApp named `slug`, or nil."
+ [slug :- :string]
+ (t2/select-one-fn :entity_id :model/DataApp :name slug))
+
+(mu/defn resource-collection?
+ "Whether the Collection with `collection-id` is the resource collection of a DataApp."
+ [collection-id :- pos-int?]
+ (t2/exists? :model/DataApp :resource_collection_id collection-id))
+
(mu/defn insert-data-app!
"Insert the DataApp `row`."
[row :- ::data-apps.schema/data-app.update]
@@ -143,7 +124,7 @@
(defn resource-collection-ids
"The IDs of the resource collections owned by data apps."
[]
- (t2/select-fn-set :resource_collection_id :model/DataApp))
+ (t2/select-fn-set :resource_collection_id :model/DataApp :resource_collection_id [:not= nil]))
(mu/defn resource-collection-id
"The ID of the resource collection owned by the DataApp with `data-app-id`."
@@ -165,6 +146,81 @@
[:= :g.is_data_app_group false]]})
#{}))
+(defn resource-collection-owned?
+ "Whether a data app owns the collection with `collection-id`."
+ [collection-id]
+ (t2/exists? :model/DataApp :resource_collection_id collection-id))
+
+(defn data-app-by-entity-id
+ "The `:id`, `:entity_id`, and `:resource_collection_id` of the DataApp with `entity-id`, or nil."
+ [entity-id]
+ (t2/select-one [:model/DataApp :id :entity_id :resource_collection_id] :entity_id entity-id))
+
+(defn data-apps-with-resource-collections
+ "The `:id` and `:resource_collection_id` of every DataApp that has a resource collection."
+ []
+ (t2/select [:model/DataApp :id :resource_collection_id] :resource_collection_id [:not= nil]))
+
+(defn active-table?
+ "Whether the table with `table-id` is active."
+ [table-id]
+ (some? (t2/select-one-pk :model/Table :id table-id :active true
+ {:from [(warehouse-schema-overlay/table-query {:user-settings? false})]})))
+
+(defn active-field?
+ "Whether the field with `field-id` is active."
+ [field-id]
+ (some? (t2/select-one-pk :model/Field :id field-id :active true
+ {:from [(warehouse-schema-overlay/field-query {:user-settings? false})]})))
+
+(defn collections-by-entity-ids
+ "The `:id`, `:entity_id` and `:namespace` of the collections with `entity-ids`."
+ [entity-ids]
+ (if (seq entity-ids)
+ (t2/query {:select [:id :entity_id :namespace] :from [:collection] :where [:in :entity_id entity-ids]})
+ []))
+
+(defn cards-by-entity-ids
+ "The `:entity_id` and `:collection_id` of the cards with `entity-ids`."
+ [entity-ids]
+ (if (seq entity-ids)
+ (t2/query {:select [:entity_id :collection_id] :from [:report_card] :where [:in :entity_id entity-ids]})
+ []))
+
+(defn actions-by-entity-ids
+ "The `:entity_id` and `:collection_id` of the actions with `entity-ids`."
+ [entity-ids]
+ (if (seq entity-ids)
+ (t2/select [:model/Action :entity_id :collection_id] :entity_id [:in entity-ids])
+ []))
+
+(defn table-ids-named
+ "The IDs of the active tables in the database with `database-id` that `refs` (maps of `:schema` and `:table`)
+ name: by name, and by schema when the reference has one, ignoring case."
+ [database-id refs]
+ (if (seq refs)
+ (let [lower #(some-> % u/lower-case-en)
+ tables (t2/select [:model/Table :id :schema :name] :db_id database-id :active true
+ {:from [(warehouse-schema-overlay/table-query {:user-settings? false})]
+ :where [:in [:lower :name] (into [] (keep (comp lower :table)) refs)]})]
+ (into (sorted-set)
+ (for [{:keys [schema table]} refs
+ {:keys [id] :as named} tables
+ :when (and (= (lower table) (lower (:name named)))
+ (or (nil? schema) (= (lower schema) (lower (:schema named)))))]
+ id)))
+ #{}))
+
+(defn collection-dataset-queries
+ "The queries of the cards and of the query actions in the collection with `collection-id`."
+ [collection-id]
+ (into (t2/select-fn-vec :dataset_query :model/Card :collection_id collection-id)
+ (t2/select-fn-vec :dataset_query :model/QueryAction
+ {:select [:qa.*]
+ :from [[:query_action :qa]]
+ :join [[:action :a] [:= :a.id :qa.action_id]]
+ :where [:= :a.collection_id collection-id]})))
+
(defn resource-collection
"The resource collection with `collection-id`, or nil."
[collection-id]
@@ -192,6 +248,25 @@
:object [:in paths]
:group_id [:not= group-id]))
+(defn table
+ "The active Table with `table-id`, or nil. The typed schema lists only active tables."
+ [table-id]
+ (t2/select-one :model/Table :id table-id :active true {:from [(warehouse-schema-overlay/table-query)]}))
+
+(defn destination-database-ids
+ "The IDs among `database-ids` of the databases that are routing destinations."
+ [database-ids]
+ (if (seq database-ids)
+ (t2/select-fn-set :id :model/Database :id [:in database-ids] :router_database_id [:not= nil])
+ #{}))
+
+(defn cards-by-ids
+ "The Cards with `card-ids`."
+ [card-ids]
+ (if (seq card-ids)
+ (t2/select :model/Card :id [:in card-ids])
+ []))
+
(defn table-details
"Table names and database details for `table-ids`."
[table-ids]
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.clj
index 1603915164e..c97e982a670 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
@@ -153,7 +153,7 @@
:skip [;; admin-owned state of this instance
:enabled
;; set by the import itself
- :draft :bundle_hash
+ :bundle_hash
;; server-managed resources, recreated on import
:permission_group_id :table_ids]
:transform {:created_at (serdes/date)
@@ -177,17 +177,17 @@
(defmethod serdes/extract-query "DataApp"
[model-name {:keys [filter-column filter-ids] :as opts}]
- (eduction (remove :draft)
- (data-apps.db/reducible-data-apps-with-bundles filter-column filter-ids
- (serdes/extract-order-columns model-name opts))))
+ (data-apps.db/reducible-data-apps-with-bundles filter-column filter-ids
+ (serdes/extract-order-columns model-name opts)))
(defmethod serdes/deserialization-dependencies "DataApp" [{:keys [collection resource_collection_id]}]
- ;; A manifest names the collection as `collection`; serialization's own checks ask by the column.
+ ;; The resource collection the manifest names loads first, so the app links to it as it lands. A manifest names it
+ ;; as `collection`; serialization's own checks ask by the column.
(when-let [collection-entity-id (or collection resource_collection_id)]
[[{:model "Collection" :id collection-entity-id}]]))
(defmethod serdes/descendants "DataApp" [_model-name id _opts]
- ;; An app's resource collection, and through it what it holds, travel with the app.
+ ;; An app's resource collection, and through it the copies it holds, travel with the app.
(when-let [collection-id (data-apps.db/resource-collection-id id)]
{["Collection" collection-id] {"DataApp" id}}))
@@ -201,10 +201,14 @@
(defmethod serdes/load-one! "DataApp"
[ingested maybe-local]
- (let [local (or maybe-local (data-apps.db/draft-by-slug (:slug ingested)))
- app (serdes/default-load-one! ingested local)]
- (data-apps.db/update-data-app! (:id app) {:draft false})
- (when local
+ ;; an app made on the instance keeps its slug: the unique index would refuse the insert anyway, but with an error
+ ;; that doesn't say what to do
+ (when (and (nil? maybe-local) (data-apps.db/data-app-exists? (:slug ingested)))
+ (throw (ex-info (tru "A data app named \"{0}\" already exists on this instance. Delete it, or give the app in the repository another slug."
+ (:slug ingested))
+ {:status-code 400})))
+ (let [app (serdes/default-load-one! ingested maybe-local)]
+ (when maybe-local
(data-app.resources/ensure-resources! app))
app))
@@ -216,7 +220,13 @@
(data-apps.db/data-app-group-ids))
(defenterprise data-app-collection-ids
- "The resource collections of the data apps, which hold the copies `sync-resources` makes."
+ "The resource collections of the data apps, which hold the copies an app runs."
:feature :none
[]
(data-apps.db/resource-collection-ids))
+
+(defenterprise data-app-collection?
+ "Whether the Collection with `collection-id` is a data app's resource collection."
+ :feature :none
+ [collection-id]
+ (data-apps.db/resource-collection? collection-id))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/query_definition.clj b/enterprise/backend/src/metabase_enterprise/data_apps/query_definition.clj
index e4fe864ebe1..6889e71757e 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/query_definition.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/query_definition.clj
@@ -84,6 +84,13 @@
[:operator ::operator]
[:args {:default []} [:sequential [:ref ::expression]]]])
+(mr/def ::aggregation-operator-expression
+ "An aggregation can be named; a filter or a nested argument can't, so `name` is refused there rather than dropped."
+ [:merge
+ ::operator-expression
+ [:map {:closed true :decode/normalize {:compile query-map-decoder}}
+ [:name {:optional true} string?]]])
+
(mr/def ::expression
[:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
:dispatch (comp keyword :type)}
@@ -109,9 +116,16 @@
[:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :metric]]
[:id [:ref ::lib.schema.id/metric]]])
+(mr/def ::aggregation-expression
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
+ [:column [:ref ::column]]
+ [:literal [:ref ::literal-expression]]
+ [:operator [:ref ::aggregation-operator-expression]]])
+
(mr/def ::aggregation
[:or
- [:ref ::expression]
+ [:ref ::aggregation-expression]
[:ref ::measure]
[:ref ::metric]])
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/resource_serialization.clj b/enterprise/backend/src/metabase_enterprise/data_apps/resource_serialization.clj
new file mode 100644
index 00000000000..d2b467677d5
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/resource_serialization.clj
@@ -0,0 +1,234 @@
+(ns metabase-enterprise.data-apps.resource-serialization
+ "What the files of a data app's collection are written from, as serialization writes it: the saved question that holds
+ the query Metabase builds from each `defineQuery` definition, each action the app runs, and the metrics its queries
+ aggregate. Nothing here references an entity by numeric ID, so the author copies it into the app's collection as it
+ is, apart from what makes it a copy.
+
+ The endpoint is for superusers, who write an app's repository, so nothing here is checked against the caller.
+ Opening it to anyone else needs that put back: every source, and every table a query reads at any depth. What a
+ routing destination backs is left out, as the typed schema leaves it out."
+ (:require
+ [clojure.string :as str]
+ [clojure.walk :as walk]
+ [metabase-enterprise.data-apps.db :as data-apps.db]
+ [metabase-enterprise.data-apps.query-definition :as query-definition]
+ [metabase-enterprise.serialization.dump :as serialization.dump]
+ [metabase.actions.core :as actions]
+ [metabase.api.common :as api]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.lib.core :as lib]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.models.serialization :as serdes]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]))
+
+(set! *warn-on-reflection* true)
+
+(defn- fail
+ "Throws the refusal of an item: a reason the author has to act on, which is not a failure of the serialization."
+ [message]
+ (throw (ex-info message {::refusal true})))
+
+(defn- with-item-error
+ "Calls `serialize`, or answers `item` with the `:error` that stopped it, so one item that can't be serialized doesn't
+ fail the rest. Anything other than a refusal is logged, so a bug in the serialization leaves a trace on the server."
+ [item serialize]
+ (try
+ (serialize)
+ (catch Exception e
+ (when-not (::refusal (ex-data e))
+ (log/warn e "Could not serialize a data app resource" item))
+ (assoc item :error (or (ex-message e) (tru "Could not serialize it."))))))
+
+(defn- extract-by-entity-id
+ "The entities of `model-name` with `ids`, as serialization extracts them, keyed by entity ID: one extraction for
+ them all. Serialization leaves out what it can't extract (an exploration's card), and goes on past one it fails
+ on, so an entity missing from the result couldn't be extracted; [[extraction-error]] says why."
+ [model-name ids]
+ (if (seq ids)
+ (into {}
+ (comp (filter map?)
+ (map (juxt (comp :id last :serdes/meta) identity)))
+ (serdes/extract-all model-name {:filter-column :id :filter-ids (vec ids) :continue-on-error true}))
+ {}))
+
+(defn- extraction-error
+ "Why serialization can't extract the `model-name` entity with `id`, or nil when it leaves the entity out without an
+ error: the one entity is extracted on its own, with the error let through. Serialization wraps what fails inside
+ an extraction in \"Error extracting ...\" at each level, so the reason is the innermost cause."
+ [model-name id]
+ (try
+ ;; reduced rather than seq'd: the extraction is a reducible, not a seq
+ (run! identity (serdes/extract-all model-name {:filter-column :id :filter-ids [id]}))
+ nil
+ (catch Exception e
+ (ex-message (last (take-while some? (iterate ex-cause e)))))))
+
+(defn- cards-read
+ "The IDs, as a comma-separated string, of the cards the `model-name` entity `source` references everywhere
+ serialization looks (its query, its visualization settings, its parameters' value sources, ...), except
+ `own-cards`, or nil when it references none. A data app's resources can't hold them, so a copy referencing one
+ would fail to load."
+ [model-name {:keys [parameters] :as source} own-cards]
+ (some->> (concat (serdes/serialization-dependencies model-name source)
+ ;; An action's dependencies leave out its parameters, which a card's include.
+ (serdes/parameters-deps true parameters))
+ (keep (fn [path]
+ (let [{:keys [model id]} (last path)]
+ (when (and (= "Card" model) (not (contains? own-cards id)))
+ id))))
+ distinct
+ not-empty
+ sort
+ (str/join ", ")))
+
+(defn- check-copyable
+ "Throws when the `model-name` entity `source`, labelled `label` and extracted as `serialized`, can't be copied into a
+ data app's resources: it's archived (the pull refuses it), a routing destination backs it, it references a card other
+ than `own-cards`, or serialization couldn't extract it, with the reason when it gave one."
+ [label model-name {:keys [archived database_id] :as source} serialized own-cards]
+ (when archived
+ (fail (tru "{0} is archived." label)))
+ (when (seq (data-apps.db/destination-database-ids #{database_id}))
+ (fail (tru "{0} is backed by a routing destination database." label)))
+ (when-let [card-ids (cards-read model-name source own-cards)]
+ (fail (tru "{0} reads card {1}, which a data app''s resources can''t hold." label card-ids)))
+ (when-not serialized
+ (fail (if-let [cause (extraction-error model-name (:id source))]
+ (tru "Could not serialize {0}: {1}" label cause)
+ (tru "Could not serialize {0}." label)))))
+
+(def ^:private public-keys
+ "What makes a source public or embedded. A copy never is, and the pull refuses a file that says it is."
+ [:public_uuid :made_public_by_id :enable_embedding :embedding_params :embedding_type])
+
+(defn- as-written
+ "`entity` as the author writes it: in the key order serialization writes, without the keys it leaves unset, which
+ the format omits, and without what makes the source public or embedded. The query is kept whole; nothing in it is
+ unset."
+ [entity]
+ (let [query (:dataset_query entity)]
+ (serialization.dump/serialization-deep-sort
+ (cond-> (walk/postwalk (fn [x] (if (map? x) (into {} (remove (comp nil? val)) x) x))
+ (apply dissoc entity :dataset_query public-keys))
+ query (assoc :dataset_query query)))))
+
+(defn- export-name->card-name
+ "The saved question's name from the definition's export name: its words, as `ProductsList` is `Products list`."
+ [export]
+ (-> export
+ (str/replace #"([a-z0-9])([A-Z])" "$1 $2")
+ (str/replace #"[\s_]+" " ")
+ u/lower-case-en
+ str/capitalize))
+
+(defn- question-card
+ "The saved question an author writes for a `defineQuery` definition, as a card for serialization to extract: the
+ query Metabase `built`, created by the caller, with the definition's entity ID, which the definition carries so the
+ file is complete as printed. The app's collection is set on the extracted entity, since serialization resolves a
+ collection by numeric ID."
+ [{:keys [export entity_id]} built]
+ {:entity_id entity_id
+ :name (export-name->card-name export)
+ :type :question
+ :display :table
+ :creator_id api/*current-user-id*
+ :database_id (:database built)
+ :dataset_query (lib/prepare-for-serialization built)
+ :visualization_settings {}
+ :parameters []
+ :parameter_mappings []})
+
+(mu/defn- built-query
+ "The query Metabase builds from `query-definition`, as the dev preview does, once its source table and every table
+ it reads at any depth, through a foreign key, a metric it aggregates or a column remapping, exist as the typed
+ schema lists them. (A routing destination has no tables of its own, only cards.)"
+ [{[{{table-id :id} :source}] :stages, :as query-definition} :- ::query-definition/query-definition]
+ (let [table (data-apps.db/table table-id)]
+ (when-not table
+ (fail (tru "Table {0} does not exist." (str table-id))))
+ (let [built (lib/test-query (lib-be/application-database-metadata-provider (:db_id table)) query-definition)]
+ ;; The request schema accepts what a type lets through, such as a fractional limit, and the checks in lib
+ ;; that would refuse it are off in production: an invalid query must not serialize and then fail when it runs.
+ (when-not (mr/validate ::lib.schema/query built)
+ (fail (tru "The definition does not build a valid query.")))
+ ;; Types generated before a table was deactivated still reach its columns through a foreign key, as does the
+ ;; query of a metric the built query holds only the ID of, and a column remapped to display another table's
+ ;; column joins that table only when the query runs. The query would fail on the table when it runs.
+ (doseq [read-id (sort (into (:table (lib/all-referenced-entity-ids-recursive built))
+ (keep :table-id)
+ (lib/returned-columns built -1 built {:include-remaps? true})))]
+ (when-not (data-apps.db/table read-id)
+ (fail (tru "Table {0} does not exist." (str read-id)))))
+ built)))
+
+(mu/defn- serialize-query
+ "A `defineQuery` definition as `{:export :entity :metric_ids}`, the entity being the saved question that holds the
+ query Metabase builds from it, in the app's collection with `collection-entity-id`, or `{:export :error}`."
+ [collection-entity-id :- ms/NanoIdString
+ {:keys [export query] :as definition} :- [:map {:closed true}
+ [:export ms/NonBlankString]
+ [:entity_id ms/NanoIdString]
+ [:query ::query-definition/query-definition]]]
+ (with-item-error
+ {:export export}
+ (fn []
+ (let [built (built-query query)]
+ {:export export
+ :entity (as-written (assoc (serdes/extract-one "Card" {} (question-card definition built))
+ :collection_id collection-entity-id))
+ :metric_ids (vec (sort (lib/all-source-card-ids built)))}))))
+
+(defn- serialize-metric
+ "The metric `card` as `{:id :entity}`, or `{:id :error}` when the app can't copy it. `serialized` is what
+ serialization extracts for it, if anything."
+ [card-id card serialized]
+ (with-item-error
+ {:id card-id}
+ (fn []
+ (let [label (tru "Metric {0}" (str card-id))]
+ (when-not (and card (= :metric (keyword (:type card))))
+ (fail (tru "{0} does not exist." label)))
+ (check-copyable label "Card" card serialized #{})
+ {:id card-id, :entity (as-written serialized)}))))
+
+(defn- serialize-action
+ "The action with `action-id` as `{:id :entity}`, or `{:id :error}` when the app can't copy it. `serialized` is what
+ serialization extracts for the action, if anything. A data app runs only actions that belong to no model, as the typed
+ schema lists only those."
+ [action-id action serialized]
+ (with-item-error
+ {:id action-id}
+ (fn []
+ (let [label (tru "Action {0}" (str action-id))]
+ (when-not action
+ (fail (tru "{0} does not exist." label)))
+ (when (:model_id action)
+ (fail (tru "{0} belongs to a model. A data app runs query actions that belong to no model." label)))
+ (check-copyable label "Action" action serialized #{})
+ {:id action-id, :entity (as-written serialized)}))))
+
+(defn serialize-resources
+ "Serialize the saved question built from each of `queries` (`{:export <name> :query <definition> :entity_id <id>}`),
+ in the app's collection with `collection-entity-id`, the actions with `action-ids`, and the metrics the queries
+ aggregate. Each item comes back on its own, with its serialization or the error that stops it, so one item that
+ can't be serialized doesn't hide the rest. A query lists the entity IDs of the metrics it references, which the
+ author points at the app's copies."
+ [collection-entity-id queries action-ids]
+ (serdes/with-cache
+ (let [queries (mapv (partial serialize-query collection-entity-id) queries)
+ actions-by-id (into {} (map (juxt :id identity)) (actions/select-actions-for-ids nil action-ids))
+ metric-ids (into (sorted-set) (mapcat :metric_ids) queries)
+ cards-by-id (into {} (map (juxt :id identity)) (data-apps.db/cards-by-ids metric-ids))
+ serialized-card (comp (extract-by-entity-id "Card" (keys cards-by-id)) :entity_id cards-by-id)
+ serialized-action (comp (extract-by-entity-id "Action" (keys actions-by-id)) :entity_id actions-by-id)]
+ {:queries (mapv (fn [{:keys [metric_ids] :as query}]
+ (cond-> (dissoc query :metric_ids)
+ (not (:error query)) (assoc :metrics (mapv (comp :entity_id cards-by-id) metric_ids))))
+ queries)
+ :actions (mapv #(serialize-action % (actions-by-id %) (serialized-action %)) action-ids)
+ :metrics (mapv #(serialize-metric % (cards-by-id %) (serialized-card %)) metric-ids)})))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/resource_tables.clj b/enterprise/backend/src/metabase_enterprise/data_apps/resource_tables.clj
new file mode 100644
index 00000000000..aceaf93a2b7
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/resource_tables.clj
@@ -0,0 +1,77 @@
+(ns metabase-enterprise.data-apps.resource-tables
+ "The tables a data app's resources read, recorded on the app for the permission warnings an admin sees when
+ granting access: a viewer who can't read one of them gets an app that fails for them."
+ (:require
+ [clojure.string :as str]
+ [metabase-enterprise.data-apps.db :as data-apps.db]
+ [metabase.driver :as driver]
+ [metabase.driver.util :as driver.u]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.util.log :as log]))
+
+(set! *warn-on-reflection* true)
+
+(defn- parseable-sql
+ "`sql` as a parser reads it: optional clauses kept as the SQL they hold, a card tag as a plain name, a snippet tag
+ as its snippet's SQL with the snippets inside it, looked up through `query`'s metadata provider, and any other
+ template tag as it is."
+ ([query sql]
+ (parseable-sql query sql #{}))
+ ([query sql expanded]
+ (letfn [(render [token]
+ (cond
+ (string? token) token
+ ;; a parser reads neither `[[` nor `]]`, and a table named inside a clause is read like one outside
+ (= :metabase.lib.parse/optional (:type token)) (apply str (map render (:contents token)))
+ ;; a card tag stands where a table does
+ (= \# (first (:name token))) "mb_card"
+ (str/starts-with? (:name token) "snippet:")
+ (let [snippet-name (str/trim (subs (:name token) (count "snippet:")))]
+ ;; a snippet that includes itself is read once
+ (if (contains? expanded snippet-name)
+ ""
+ (parseable-sql query
+ (or (:content (lib.metadata/native-query-snippet-by-name query snippet-name)) "")
+ (conj expanded snippet-name))))
+ :else (str "{{" (:name token) "}}")))]
+ (apply str (map render (lib/parse {} sql))))))
+
+(defn- native-table-ids
+ "The tables a native query names in its SQL, as its driver's parser reads them, and in its table template tags."
+ [{database-id :database, :as query}]
+ (let [parseable (lib/with-native-query query (parseable-sql query (lib/raw-native-query query)))]
+ (into (data-apps.db/table-ids-named database-id
+ (driver/native-query-table-refs (driver.u/database->driver database-id) parseable))
+ (map :table)
+ (lib/native-query-table-references query))))
+
+(defn- query-table-ids [dataset-query]
+ (let [query (lib/query (lib-be/application-database-metadata-provider (:database dataset-query)) dataset-query)]
+ (if (lib/native? query)
+ (native-table-ids query)
+ (into (set (lib/all-source-table-ids query))
+ (lib/all-implicitly-joined-table-ids query)))))
+
+(defn collection-table-ids
+ "The tables the cards and the query actions in the collection with `collection-id` read, including
+ the ones a query reaches only through an implicit join."
+ [collection-id]
+ (->> (data-apps.db/collection-dataset-queries collection-id)
+ (into #{} (mapcat (fn [dataset-query]
+ ;; a query whose tables can't be read, such as a native query on a driver that can't
+ ;; parse one, must not fail the pull that loaded it
+ (try
+ (query-table-ids dataset-query)
+ (catch Exception e
+ (log/warn e "Could not read the tables of a data app query")
+ nil)))))
+ sort
+ vec))
+
+(defn record-table-dependencies!
+ "Record on every data app the tables its resources read. Runs after an import, since that is what changes them."
+ []
+ (doseq [{:keys [id resource_collection_id]} (data-apps.db/data-apps-with-resource-collections)]
+ (data-apps.db/update-data-app! id {:table_ids (collection-table-ids resource_collection_id)})))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/resource_validation.clj b/enterprise/backend/src/metabase_enterprise/data_apps/resource_validation.clj
new file mode 100644
index 00000000000..0ff0dcae478
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/resource_validation.clj
@@ -0,0 +1,433 @@
+(ns metabase-enterprise.data-apps.resource-validation
+ "What a data app's resources may hold. An app's resources are its collection, the one its `data_app.yaml` names as
+ `collection`, and the cards and actions in it, all ordinary entity files under `collections/`. A load trusts what it
+ reads: it updates whatever row carries an entity ID and resolves references to any local entity. These checks run
+ on the ingested files first, so an app's resources can only be its own collection, in the `data-apps` namespace,
+ and, in it, questions, metrics, and query actions that belong to no model, referencing nothing else of Metabase's
+ but what already exists."
+ (:require
+ [clojure.string :as str]
+ [clojure.walk :as walk]
+ [metabase-enterprise.data-apps.db :as data-apps.db]
+ [metabase.models.db :as models.db]
+ [metabase.models.serialization :as serdes]
+ [metabase.util.i18n :refer [tru]]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private external-dependency-models
+ "Models a resource may reference outside the app. They must already exist: a load never creates them."
+ #{"Database" "Table" "Field" "NativeQuerySnippet" "Segment" "Measure"})
+
+(def ^:private card-types #{"question" "metric"})
+
+(defn- leaf [path]
+ (last path))
+
+(defn- problem [file message]
+ {:file file :message message})
+
+(defn- identity-problems [{:keys [path model entity]}]
+ (let [meta-path (:serdes/meta entity)
+ {meta-model :model meta-id :id} (leaf meta-path)]
+ (when-not (and (= 1 (count meta-path))
+ (= model meta-model)
+ (serdes/entity-id? (:entity_id entity))
+ (= meta-id (:entity_id entity)))
+ [(problem path (tru "{0} must hold a single {1} whose serdes/meta ID is its entity_id." path model))])))
+
+(defn- creator-problems
+ "A load creates the user a `creator_id` names when it has to, but can't save a card or action without one."
+ [{:keys [path entity]}]
+ (when (nil? (:creator_id entity))
+ [(problem path (tru "{0} must name its creator in creator_id." path))]))
+
+(defn- public-problems [{:keys [path entity]}]
+ (when (or (some entity [:public_uuid :made_public_by_id :embedding_params :embedding_type])
+ (:enable_embedding entity))
+ [(problem path (tru "{0} must not be public or embedded." path))]))
+
+(defn- type-name [entity]
+ (let [t (:type entity)]
+ (when (or (string? t) (keyword? t))
+ (name t))))
+
+(defn- action-children-problems
+ "Serdes loads an action's implicit and query rows whatever its type, so a query action's file must carry exactly
+ its query row."
+ [{:keys [path entity]}]
+ (let [counts (update-vals (select-keys entity [:implicit :query]) count)]
+ (when (not= {:query 1} (into {} (remove (comp zero? val)) counts))
+ [(problem path (tru "{0} must carry exactly one query, and no implicit action." path))])))
+
+(defn- parameter-source-problems
+ "An action's parameters can take their values from a card, which its dependencies don't include."
+ [{:keys [path entity]}]
+ (when (some (comp :card_id :values_source_config) (:parameters entity))
+ [(problem path (tru "{0} must not take parameter values from a card." path))]))
+
+(defn- model-problems [{:keys [path model entity] :as file}]
+ (case model
+ "Collection"
+ (concat
+ (when (not= "data-apps" (some-> (:namespace entity) name))
+ [(problem path (tru "{0} must be in the data-apps collection namespace." path))])
+ (when (or (some entity [:parent_id :personal_owner_id :authority_level :type :archive_operation_id])
+ (:is_remote_synced entity)
+ (:is_sample entity)
+ (:archived entity))
+ [(problem path (tru "{0} must be a root collection that is not remote-synced or archived." path))]))
+
+ "Card"
+ (concat
+ (when-not (card-types (type-name entity))
+ [(problem path (tru "{0} must be a question or metric." path))])
+ (when-not (and (map? (:dataset_query entity)) (some? (:database (:dataset_query entity))))
+ [(problem path (tru "{0} must hold a query." path))])
+ (when (:archived entity)
+ [(problem path (tru "{0} must not be archived." path))])
+ (when (some entity [:dashboard_id :document_id])
+ [(problem path (tru "{0} must not belong to a dashboard or document." path))])
+ (creator-problems file)
+ (public-problems file))
+
+ "Action"
+ (concat
+ ;; a data app runs only query actions that belong to no model, the ones the typed schema lists
+ (when (not= "query" (type-name entity))
+ [(problem path (tru "{0} must be a query action." path))])
+ (when (some? (:model_id entity))
+ [(problem path (tru "{0} must belong to no model." path))])
+ (when (:archived entity)
+ [(problem path (tru "{0} must not be archived." path))])
+ (action-children-problems file)
+ (parameter-source-problems file)
+ (creator-problems file)
+ (public-problems file))))
+
+(defn- dependencies
+ "The serdes dependencies of the entity in `file`, or nil with a problem when they can't be read."
+ [{:keys [path entity]}]
+ (try
+ [(serdes/deserialization-dependencies entity) nil]
+ (catch Exception e
+ [nil (problem path (tru "{0} is malformed: {1}" path (ex-message e)))])))
+
+(defn- dependency-problems
+ [collection-entity-id card-entity-ids {:keys [path] :as file}]
+ (let [[deps malformed] (dependencies file)]
+ (if malformed
+ [malformed]
+ (for [dependency deps
+ :let [{:keys [model id]} (leaf dependency)]
+ :when (case model
+ "Collection" (not= id collection-entity-id)
+ "Card" (not (contains? card-entity-ids id))
+ (not (contains? external-dependency-models model)))]
+ (problem path (tru "{0} references {1} {2}, which is not one of the app''s resources." path model id))))))
+
+(defn- numeric-reference-problems
+ "A serialized query names cards, tables, fields and snippets by entity ID or by path. A numeric ID names a row on one
+ instance only, and the dependency checks, which read entity IDs, don't see it."
+ [{:keys [path entity]}]
+ (let [numeric? (volatile! false)
+ ;; a card as a source table, in the older form
+ card-ref? (fn [x] (and (string? x) (re-matches #"card__\d+" x)))]
+ (walk/postwalk (fn [x]
+ (when (or (and (map? x)
+ (or (some #(integer? (get x %))
+ [:source-card :source-table :card-id :snippet-id :table-id :source-field :database])
+ (card-ref? (:source-table x))))
+ (and (vector? x)
+ (or (string? (first x)) (keyword? (first x)))
+ (contains? #{"field" "metric" "segment" "measure"} (name (first x)))
+ (some integer? (rest x))))
+ (vreset! numeric? true))
+ x)
+ (select-keys entity [:dataset_query :query]))
+ (when @numeric?
+ [(problem path (tru "{0} must not reference a card, table, field, snippet or database by numeric ID." path))])))
+
+(defn- duplicate-problems [resources]
+ (for [[[model entity-id] files] (group-by (juxt :model (comp :entity_id :entity)) resources)
+ :when (< 1 (count files))]
+ (problem (:path (first files))
+ (tru "{0} {1} is defined by more than one file: {2}." model entity-id (str/join ", " (map :path files))))))
+
+(defn- external-dependency-problems
+ "`defined` holds the `[model entity-id]` of each dependency that the same pull loads from outside `data_apps/`."
+ [defined resources]
+ (for [{:keys [path] :as file} resources
+ dependency (first (dependencies file))
+ :let [{:keys [model id]} (leaf dependency)]
+ :when (and (contains? external-dependency-models model)
+ (not (contains? defined [model id]))
+ (nil? (serdes/load-find-local dependency)))]
+ (problem path (tru "{0} references {1} {2}, which does not exist on this instance." path model id))))
+
+(defn- portable-refs
+ "The portable table references (`[db schema table]`) and field references (`[db schema table field ...]`) that
+ `entity` makes, in each place where serialization reads one: a query's source table, a field clause in either form,
+ the source field of a field clause, a table template tag, and a column of the result metadata."
+ [entity]
+ (let [refs (volatile! #{})
+ names? (fn [x] (and (vector? x) (string? (first x)) (every? #(or (nil? %) (string? %)) x)))
+ table? (fn [x] (and (names? x) (= 3 (count x))))
+ field? (fn [x] (and (names? x) (< 3 (count x))))
+ add! (fn [kind x] (vswap! refs conj [kind x]))]
+ (walk/postwalk (fn [x]
+ (cond
+ (map? x)
+ (do
+ (doseq [k [:source-table :table-id :table_id]
+ :when (table? (get x k))]
+ (add! :table (get x k)))
+ (when (field? (:source-field x))
+ (add! :field (:source-field x)))
+ ;; a column of the result metadata names its field as `:id`
+ (when (and (contains? x :base_type) (field? (:id x)))
+ (add! :field (:id x))))
+
+ (and (vector? x) (#{"field" :field} (first x)))
+ (doseq [part (rest x)
+ :when (field? part)]
+ (add! :field part)))
+ x)
+ (select-keys entity [:dataset_query :query :parameter_mappings :result_metadata]))
+ @refs))
+
+(defn- missing-table-and-field-problems
+ "Serialization creates an inactive placeholder for a table or field a query names that this instance doesn't
+ have. A data app's query would then run against nothing, so the file is refused instead."
+ [{:keys [path] :as file}]
+ (let [table-id (fn [[db-name schema table-name]]
+ (some-> (models.db/database-id-by-name db-name)
+ (as-> database-id (models.db/table-id-by-name table-name schema database-id))
+ ;; an inactive table is one that sync no longer finds, or a placeholder
+ (as-> id (when (data-apps.db/active-table? id) id))))]
+ (for [[kind [db-name schema table-name & field-names :as ref]] (sort-by second (portable-refs (:entity file)))
+ :when (or (nil? (table-id [db-name schema table-name]))
+ (and (= kind :field)
+ (nil? (models.db/field-pk-in-path (table-id [db-name schema table-name]) (reverse field-names)))))]
+ (problem path (tru "{0} references {1} {2}, which does not exist on this instance."
+ path (if (= kind :table) "table" "field") (pr-str ref))))))
+
+(defn- inactive-field-warnings
+ "A warning for each inactive field `file` references: one sync no longer finds, which the app's query would run
+ against. One column isn't the app, so the file loads with the field logged, unlike an inactive table."
+ [{:keys [path] :as file}]
+ (for [[kind [db-name schema table-name & field-names :as ref]] (sort-by second (portable-refs (:entity file)))
+ :when (= kind :field)
+ :let [field-id (some-> (models.db/database-id-by-name db-name)
+ (as-> database-id (models.db/table-id-by-name table-name schema database-id))
+ (models.db/field-pk-in-path (reverse field-names)))]
+ :when (and field-id (not (data-apps.db/active-field? field-id)))]
+ (problem path (tru "{0} references field {1}, which is inactive on this instance." path (pr-str ref)))))
+
+(defn- ownership-problems
+ "Serdes would update any row carrying an entity ID a file names, so a file may only name what this app owns:
+ the collection its manifest names, if it exists, must be the collection the app has, or one of the namespace that
+ no app owns, and existing cards and actions must be in it."
+ [app-entity-id manifest-path collection-entity-id resources]
+ (let [app (data-apps.db/data-app-by-entity-id app-entity-id)
+ app-collection-id (:resource_collection_id app)
+ collections (data-apps.db/collections-by-entity-ids [collection-entity-id])
+ ;; a collection on the instance that no app owns, or this app owns, may be the app's; another app's may not
+ owned? (fn [collection-id]
+ (or (= app-collection-id collection-id)
+ (not (data-apps.db/resource-collection-owned? collection-id))))
+ ;; a collection of the namespace that no app owns is the app's to claim with what it holds: what an earlier
+ ;; pull loaded into it before the app itself failed to load
+ claimable-id (when (nil? app-collection-id)
+ (some (fn [{:keys [id] collection-namespace :namespace}]
+ (when (and (= :data-apps (keyword collection-namespace))
+ (not (data-apps.db/resource-collection-owned? id)))
+ id))
+ collections))
+ in-collection? (fn [collection-id]
+ (or (and (some? app-collection-id) (= app-collection-id collection-id))
+ (and (some? claimable-id) (= claimable-id collection-id))))
+ entity-ids-of (fn [model]
+ (into [] (comp (filter (comp #{model} :model)) (map (comp :entity_id :entity))) resources))
+ file-of (fn [model entity-id]
+ (some #(when (and (= model (:model %)) (= entity-id (:entity_id (:entity %)))) (:path %))
+ resources))]
+ (concat
+ ;; the app's hooks refuse a change of collection, but only after the load has moved what it reached first
+ (when (and (some? app-collection-id) (not-any? #(= app-collection-id (:id %)) collections))
+ [(problem manifest-path
+ (tru "{0} names collection {1}, but the app already has a collection, and a data app''s collection cannot be changed."
+ manifest-path collection-entity-id))])
+ (for [{:keys [id entity_id] collection-namespace :namespace} collections
+ :let [message (cond
+ (not= :data-apps (keyword collection-namespace))
+ (tru "Collection {0} already exists outside the data-apps namespace, so it can''t become a data app''s collection. Give the app a collection of its own: a new entity ID in data_app.yaml and in the collection''s file."
+ entity_id)
+
+ (not (owned? id))
+ (tru "Collection {0} already exists and is another data app''s collection. Give the app a collection of its own: a new entity ID in data_app.yaml and in the collection''s file."
+ entity_id))]
+ :when message]
+ (problem (or (file-of "Collection" entity_id) manifest-path) message))
+ (for [[model rows] [["Card" (data-apps.db/cards-by-entity-ids (entity-ids-of "Card"))]
+ ["Action" (data-apps.db/actions-by-entity-ids (entity-ids-of "Action"))]]
+ {:keys [entity_id collection_id]} rows
+ :when (not (in-collection? collection_id))]
+ (problem (file-of model entity_id)
+ (tru "{0} {1} already exists outside this data app''s collection, so the app can''t load it. Move it back if it belongs to this app."
+ model entity_id))))))
+
+(defn- model-of [entity]
+ (:model (last (:serdes/meta entity))))
+
+(defn- app-resources
+ "Among `files`, the collection with `collection-entity-id` and the cards and actions in it, each with its `:model`."
+ [collection-entity-id files]
+ (for [{:keys [entity] :as file} files
+ :let [model (model-of entity)]
+ :when (or (and (= "Collection" model) (= collection-entity-id (:entity_id entity)))
+ (and (contains? #{"Card" "Action"} model)
+ (= collection-entity-id (:collection_id entity))))]
+ (assoc file :model model)))
+
+(defn- app-problems
+ "The problems of one app: its manifest file, and among `files` its collection and the cards and actions in it."
+ [defined manifest files]
+ (let [manifest-problems (identity-problems (assoc manifest :model "DataApp"))
+ collection-entity-id (-> manifest :entity :collection)
+ app-entity-id (-> manifest :entity :entity_id)
+ resources (app-resources collection-entity-id files)
+ collection-files (filter (comp #{"Collection"} :model) resources)]
+ (cond
+ (seq manifest-problems)
+ manifest-problems
+
+ (nil? collection-entity-id)
+ [(problem (:path manifest) (tru "{0} must name the app''s resource collection as `collection`." (:path manifest)))]
+
+ (empty? collection-files)
+ [(problem (:path manifest)
+ (tru "The collection {0} that {1} names is not in the repository. Write it under collections/data_apps/ and commit it."
+ collection-entity-id (:path manifest)))]
+
+ :else
+ (let [cards (filter (comp #{"Card"} :model) resources)
+ card-entity-ids (into #{} (map (comp :entity_id :entity)) cards)
+ structural (concat (duplicate-problems resources)
+ (mapcat identity-problems resources))]
+ (if (seq structural)
+ structural
+ (concat
+ (mapcat model-problems resources)
+ (mapcat numeric-reference-problems resources)
+ (mapcat (partial dependency-problems collection-entity-id card-entity-ids) resources)
+ (ownership-problems app-entity-id (:path manifest) collection-entity-id resources)
+ (external-dependency-problems defined resources)
+ (mapcat missing-table-and-field-problems resources)))))))
+
+(defn- shared-collection-problems
+ "Two apps can't name one collection: only one of them would own it."
+ [manifests]
+ (for [[collection-entity-id named-by] (group-by (comp :collection :entity) manifests)
+ :when (and collection-entity-id (< 1 (count named-by)))
+ {:keys [path]} named-by]
+ (problem path (tru "{0} names collection {1}, which another data app also names." path collection-entity-id))))
+
+(defn- shared-resource-problems
+ "Two apps can't define one card or action: a load would give it to whichever file loads last."
+ [manifests files]
+ (let [resources (for [{:keys [entity path]} manifests
+ resource (app-resources (:collection entity) files)]
+ (assoc resource :manifest path))]
+ (for [[[model entity-id] defined-by] (group-by (juxt :model (comp :entity_id :entity)) resources)
+ :when (< 1 (count (into #{} (map :manifest) defined-by)))
+ {:keys [path]} defined-by]
+ (problem path (tru "{0} {1} is defined by more than one data app: {2}." model entity-id (str/join ", " (map :path defined-by)))))))
+
+(defn- shared-entity-id-problems
+ "Two manifests can't carry one entity ID: a load keeps one app, and the other's collection is left with no owner."
+ [manifests]
+ (for [[entity-id carried-by] (group-by (comp :entity_id :entity) manifests)
+ :when (and entity-id (< 1 (count carried-by)))
+ {:keys [path]} carried-by]
+ (problem path (tru "{0} has the entity ID {1}, which another data app also has." path entity-id))))
+
+(defn- shared-slug-problems
+ "Two manifests can't carry one slug: a load keeps the first app and refuses the second after it has started."
+ [manifests]
+ (for [[slug carried-by] (group-by (comp :slug :entity) manifests)
+ :when (and slug (< 1 (count carried-by)))
+ {:keys [path]} carried-by]
+ (problem path (tru "{0} has the slug {1}, which another data app also has." path slug))))
+
+(defn- taken-slug-problems
+ "An app made on the instance keeps its slug, and a load would refuse the repository's app only after its collection
+ and cards had loaded."
+ [manifests]
+ (for [{:keys [path entity]} manifests
+ :let [slug (:slug entity)
+ taken-by (when (string? slug) (data-apps.db/data-app-entity-id-named slug))]
+ :when (and taken-by (not= taken-by (:entity_id entity)))]
+ (problem path (tru "{0} has the slug {1}, which a data app made on this instance already has. Delete that app, or give the app in the repository another slug."
+ path slug))))
+
+(defn- child-collection-problems
+ "A data app's collection holds no collections, and a load would refuse one only after it had started."
+ [manifests files]
+ (let [app-collections (into #{} (keep (comp :collection :entity)) manifests)]
+ (for [{:keys [path entity]} files
+ :when (and (= "Collection" (model-of entity)) (contains? app-collections (:parent_id entity)))]
+ (problem path (tru "{0} is a collection inside a data app''s collection, which can''t hold one." path)))))
+
+(defn- other-content-problems
+ "A data app's collection holds cards and actions only, and a load would refuse anything else only after it had
+ started."
+ [manifests files]
+ (let [app-collections (into #{} (keep (comp :collection :entity)) manifests)]
+ (for [{:keys [path entity]} files
+ :when (and (contains? app-collections (:collection_id entity))
+ (not (contains? #{"Card" "Action"} (model-of entity))))]
+ (problem path (tru "{0} is in a data app''s collection, which holds only questions, metrics and query actions." path)))))
+
+(defn- defined-dependencies
+ "The `[model entity-id]` of each snippet, segment and measure that `files` load: a resource that names one counts
+ it as present, since the same pull brings it."
+ [files]
+ (into #{}
+ (comp (map (comp (juxt :model :id) last :serdes/meta :entity))
+ (filter (comp #{"NativeQuerySnippet" "Segment" "Measure"} first)))
+ files))
+
+(defn- manifests-among
+ "The manifest files among `files`: the entities that say they are a DataApp, and the files at a manifest's path too,
+ as one that doesn't say what it is would be skipped by the load, and the app deleted as no longer in the repository."
+ [files]
+ (filter #(or (= "DataApp" (model-of (:entity %)))
+ (re-matches #"data_apps/[^/]+/data_app\.yaml" (:path %)))
+ files))
+
+(defn warnings
+ "What a pull logs about the data apps among the entity files `files` (see [[problems]]), each as `{:file :message}`:
+ what loads, but may not run as the author meant it."
+ [files]
+ (for [{:keys [entity]} (manifests-among files)
+ resource (app-resources (:collection entity) files)
+ warning (inactive-field-warnings resource)]
+ warning))
+
+(defn problems
+ "The problems with the data apps among the entity files `files` (`{:path :entity}`, every entity file of the
+ snapshot), each as `{:file :message}`. An app whose resources have a problem can't be loaded as the author meant
+ it, so an import that sees one fails naming the file."
+ [files]
+ (let [manifests (manifests-among files)
+ defined (defined-dependencies files)]
+ (concat
+ (shared-entity-id-problems manifests)
+ (shared-slug-problems manifests)
+ (taken-slug-problems manifests)
+ (shared-collection-problems manifests)
+ (shared-resource-problems manifests files)
+ (child-collection-problems manifests files)
+ (other-content-problems manifests files)
+ (mapcat #(app-problems defined % files) manifests))))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj b/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj
index ff0c1ccff90..f44f703efd6 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj
@@ -114,8 +114,7 @@
[:version {:optional true} ::version]
[:resource_collection_id {:optional true} [:maybe ms/PositiveInt]]
[:permission_group_id {:optional true} [:maybe ms/PositiveInt]]
- [:table_ids {:optional true} [:maybe [:sequential ms/PositiveInt]]]
- [:draft {:optional true} [:maybe :boolean]]])
+ [:table_ids {:optional true} [:maybe [:sequential ms/PositiveInt]]]])
(mr/def ::data-app.insert
"What an insert of a DataApp accepts: [[::data-app.update]] with its slug, display name, and bundle path required."
diff --git a/enterprise/backend/src/metabase_enterprise/library/core.clj b/enterprise/backend/src/metabase_enterprise/library/core.clj
index 7cb97cbf1dc..73fc0046fcf 100644
--- a/enterprise/backend/src/metabase_enterprise/library/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/library/core.clj
@@ -8,4 +8,4 @@
(p/import-vars
[metabase-enterprise.library.validation
- check-allowed-content])
+ check-library-content])
diff --git a/enterprise/backend/src/metabase_enterprise/library/validation.clj b/enterprise/backend/src/metabase_enterprise/library/validation.clj
index 2fd0a98e460..18d0b1e3a76 100644
--- a/enterprise/backend/src/metabase_enterprise/library/validation.clj
+++ b/enterprise/backend/src/metabase_enterprise/library/validation.clj
@@ -30,7 +30,7 @@
collection/library-dashboards-collection-type}
:error-message "Can only add dashboards to the 'Dashboards' collection"}})
-(defenterprise check-allowed-content
+(defenterprise check-library-content
"Check if the collection's content matches the allowed content.
Throws an exception if it does not"
:feature :library
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
index 3b9c00a0ba4..48f75e9b94b 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
@@ -36,7 +36,14 @@
:feature :none
[collection]
(or (= (settings/remote-sync-type) :read-write)
- (not (collections/remote-synced-collection? collection))))
+ (not (or (collections/remote-synced-collection? collection)
+ ;; a data app's collection is synced with the app; without remote sync nothing writes its files
+ (and (settings/remote-sync-enabled)
+ (spec/data-apps-namespace-collection?
+ {:namespace (if (and (map? collection) (contains? collection :namespace))
+ (:namespace collection)
+ ;; the root collection has no ID, and nothing in it is synced
+ (some-> (u/id collection) remote-sync.db/collection-namespace))}))))))
(defenterprise table-editable?
"Determines if a table's metadata should be editable.
@@ -452,6 +459,10 @@
(remote-sync.db/collections sync-on)))
(update :sync-off #(when-let [sync-off (seq %)]
(remote-sync.db/collections sync-off))))]
+ ;; a data app's collection is synced with its app, and a pull refuses its file once it says remote-synced
+ (when (some spec/data-apps-namespace-collection? sync-on)
+ (throw (ex-info (tru "A data app''s collection is synced with its app and can''t be marked as synced.")
+ {:status-code 400})))
(try
(t2/with-transaction [_]
(when (seq sync-on)
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj
index aff3b05a831..357584c20d1 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj
@@ -13,7 +13,7 @@
(def ^:private ConditionKey
"The column keys used in the `:conditions` / `:cascade-filter` / `:removal-conditions` of a remote-sync model
spec (see `metabase-enterprise.remote-sync.spec`)."
- [:enum :exploration_id :built_in_type :active :entity_id :collection_id :model_id :archived :archived_at :draft])
+ [:enum :exploration_id :built_in_type :active :entity_id :collection_id :model_id :archived :archived_at])
(def ^:private Conditions
"A map of column to value (possibly nil) or Toucan 2 operator-vector value, or nil for none."
@@ -475,16 +475,17 @@
[namespace-name :- :string]
(t2/select [:model/Collection :id :entity_id] :namespace namespace-name))
-(mu/defn collection-namespace :- [:maybe [:or :keyword :string]]
- "The namespace of the Collection with `collection-id`, or nil."
- [collection-id :- ::lib.schema.id/collection]
- (t2/select-one-fn :namespace [:model/Collection :namespace] :id collection-id))
-
(mu/defn collection-ids-in-namespace
"The IDs of the Collections of `namespace-name`."
[namespace-name :- :string]
(t2/select-pks-vec :model/Collection :namespace namespace-name))
+(mu/defn collection-namespace
+ "The namespace of the Collection with `collection-id`, nil for the default namespace or no such Collection."
+ [collection-id :- [:maybe ms/PositiveInt]]
+ (when collection-id
+ (t2/select-one-fn :namespace :model/Collection :id collection-id)))
+
(mu/defn remote-synced-collection-ids
"The IDs of the remote-synced Collections."
[]
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
index 39e2d5175b2..fe175ca40a0 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
@@ -3,6 +3,7 @@
[clojure.string :as str]
[diehard.core :as dh]
[java-time.api :as t]
+ [metabase-enterprise.data-apps.core :as data-apps]
[metabase-enterprise.remote-sync.db :as remote-sync.db]
[metabase-enterprise.remote-sync.guards :as guards]
[metabase-enterprise.remote-sync.merge :as remote-sync.merge]
@@ -141,6 +142,10 @@
(instance? java.net.UnknownHostException (ex-cause e)))
"Network error: Unable to reach git repository host"
+ ;; the validator names a file, whose path may hold any word the matches below look for
+ (= (:error (ex-data e)) :metabase-enterprise.remote-sync.source.ingestable/invalid-data-app-files)
+ (str "Failed to reload from git repository: " message)
+
(str/includes? message "Authentication failed")
"Authentication failed: Please check your git credentials"
@@ -574,6 +579,15 @@
(remote-sync.db/update-rso! (:id existing) {:status status :status_changed_at timestamp})
(remote-sync.db/insert-rso! (-> row (dissoc :id) (assoc :status_changed_at timestamp))))))
+(defn- record-data-app-tables!
+ "Record the tables each data app's resources read, after a load or an export, logging a failure: the load's
+ transaction has committed and the export's commit is pushed by then, so a failure must not undo their record."
+ []
+ (try
+ (data-apps/record-table-dependencies!)
+ (catch Exception e
+ (log/warn e "Could not record the tables of the data apps"))))
+
(defn- import-merged!
"Import in merge mode. Should only be called when you have a base-snapshot and its version differs from snaphot's version.
@@ -604,6 +618,7 @@
:finalize! (fn []
(restore-dirty-objects! dirty-objects sync-timestamp)
(finalize!)))
+ (record-data-app-tables!)
(log/infof "Pull merge: folded in %d remote change(s) (added %d, updated %d, removed %d); kept %d local change(s)"
(apply + (vals summary)) (:added summary) (:updated summary) (:removed summary)
(count dirty-objects))
@@ -636,11 +651,14 @@
(try
(let [snapshot-version (source.p/version snapshot)
last-imported-version (remote-sync.task/last-version)
+ ;; before anything is read for loading, the files of each data app's collection are checked; a pull of
+ ;; the commit already imported loads nothing, so there is nothing to check
+ _ (when (or force? merge? (not= last-imported-version snapshot-version))
+ (source.ingestable/check-data-app-files! snapshot))
first-import? (nil? last-imported-version)
;; force-deletion? defaults to force? when a caller doesn't pass it.
force-deletion? (if (nil? force-deletion?) force? force-deletion?)
- finalize! (fn []
- (remote-sync.task/set-version! task-id snapshot-version))
+ finalize! (fn [] (remote-sync.task/set-version! task-id snapshot-version))
report (import-progress-reporter task-id)
path-filters (mapv #(re-pattern (str % "/.*")) serialization/legal-top-level-paths)
;; First-import conflicts only block the first import; deletion conflicts block every import (an
@@ -700,7 +718,8 @@
:else
(let [_ (log/info "Remote sync full import: forced")
- imported-data (load-snapshot! snapshot report sync-timestamp :finalize! finalize!)]
+ imported-data (u/prog1 (load-snapshot! snapshot report sync-timestamp :finalize! finalize!)
+ (record-data-app-tables!))]
(log/info "Successfully reloaded entities from git repository")
{:status :success
:version snapshot-version
@@ -738,7 +757,8 @@
first-import? "first import"
:else "changes not incrementally loadable")
_ (log/infof "Remote sync full import: %s" reason)
- imported-data (load-snapshot! snapshot report sync-timestamp :finalize! finalize!)]
+ imported-data (u/prog1 (load-snapshot! snapshot report sync-timestamp :finalize! finalize!)
+ (record-data-app-tables!))]
(log/info "Successfully reloaded entities from git repository")
{:status :success
:version snapshot-version
@@ -810,7 +830,8 @@
:conflicts labels
:merge-summary summary
:message "Export blocked: the same content was changed both locally and on the remote branch."})
- (let [[_ version] (commit-staged! snapshot message
+ (let [_ (source.ingestable/check-data-app-files! (source/specs->snapshot merged))
+ [_ version] (commit-staged! snapshot message
(fn [commit]
(source/replace-managed-files! commit snapshot) ; merged set replaces the managed files wholesale
(run! #(source.p/stage-upsert! commit %) merged)))
@@ -835,6 +856,7 @@
:finalize! (fn []
(remote-sync.db/mark-all-rsos-synced! sync-timestamp)
(remote-sync.task/set-version! task-id version)))
+ (record-data-app-tables!)
(log/infof "Exported with merge: folded in %d remote change(s) (added %d, updated %d, removed %d); pushed %d"
pulled (:added summary) (:updated summary) (:removed summary) (if empty? 0 pushed-count))
{:status :success :version version :merge-summary summary
@@ -1203,6 +1225,7 @@
(doseq [removed-ids (partition-all 500 (find-departed-entities export-rows))]
(remote-sync.db/delete-rsos! removed-ids))
(mark-rows-synced! (remote-sync.db/all-rso-ids) synced sync-timestamp))
+ (record-data-app-tables!)
(if (= version :remote-sync/empty-commit)
(do
(log/info "Remote sync full export: re-serialized content matches remote; skipped empty commit")
@@ -1236,6 +1259,7 @@
(doseq [removed-ids (partition-all 500 removed-ids)]
(remote-sync.db/delete-rsos! removed-ids))
(mark-rows-synced! (map :id synced) synced sync-timestamp))
+ (record-data-app-tables!)
(if (= version :remote-sync/empty-commit)
(do (log/info "Remote sync incremental export: nothing changed; skipped empty commit")
{:status :success :outcome {:kind "push-skipped"}})
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source/ingestable.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source/ingestable.clj
index d3b8edf2ec5..6820e7b2dca 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source/ingestable.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source/ingestable.clj
@@ -1,6 +1,7 @@
(ns metabase-enterprise.remote-sync.source.ingestable
(:require
[clojure.string :as str]
+ [metabase-enterprise.data-apps.core :as data-apps]
[metabase-enterprise.remote-sync.source.protocol :as source.p]
[metabase-enterprise.serialization.core :as serialization]
[metabase.models.serialization :as serdes]
@@ -32,6 +33,29 @@
(serdes/restore-path
(serialization/read-timestamps (yaml/parse-string file-content {:key-fn serialization/parse-key}))))
+(defn check-data-app-files!
+ "Throws, naming each file, when a data app's files in `snapshot` (its manifest, its collection, and what the
+ collection holds) carry what a load can't take as the author meant it. Serialization trusts what it reads, so this
+ is what keeps an app's resources to its own collection; it runs on the whole snapshot before any import, since an
+ incremental import ingests only the changed files. A file that doesn't parse is left to ingestion to report, but a
+ manifest that doesn't is kept, so that its own problem names it rather than the app being deleted as no longer in
+ the repository."
+ [snapshot]
+ (let [files (vec (for [path (source.p/list-files snapshot)
+ :when (serialization/entity-file-path? path)
+ :let [entity (try
+ (ingest-content (source.p/read-file snapshot path))
+ (catch Exception _ nil))]
+ :when (or entity (re-matches #"data_apps/[^/]+/data_app\.yaml" path))]
+ {:path path :entity entity}))
+ problems (data-apps/problems files)]
+ (when (seq problems)
+ (throw (ex-info (str/join " " (map (fn [{:keys [file message]}] (format "Invalid data app file %s: %s" file message))
+ problems))
+ {:files (mapv :file problems) :error ::invalid-data-app-files})))
+ (doseq [{:keys [file message]} (data-apps/warnings files)]
+ (log/warnf "Data app file %s: %s" file message))))
+
(defn- ingest-all
"Returns {:entities {stripped-hierarchy {:content <yaml-string> :path <repo-path>}}, :errors [Exception...]}.
The repo `:path` is the actual file the entity was read from (including any dedup suffix), so callers
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj
index ec21393f8ae..4298d178e00 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj
@@ -374,7 +374,6 @@
:archived-key nil
:tracking {:select-fields [:name]
:field-mappings {:model_name :name}}
- :conditions {:draft false}
:removal {:statuses #{"removed" "delete"}}
:resources? true
:export-scope :all
@@ -724,6 +723,11 @@
(or (snippets-namespace-collection? object)
(data-actions-namespace-collection? object)))
+(defn data-apps-namespace-collection?
+ "Check if this is a data-apps-namespace collection: a data app's resource collection, synced with the app."
+ [object]
+ (= (keyword (:namespace object)) collections/data-apps-ns))
+
(defn library-collection?
"Check if this is the Library collection."
[collection]
@@ -731,13 +735,14 @@
(defn should-sync-collection?
"Check if a collection should be synced - either remote-synced, transforms-namespace with setting enabled,
- or snippets-namespace with Library synced."
+ snippets-namespace with Library synced, or data-apps-namespace, a data app's collection, synced with the app."
[collection]
(or (collections/remote-synced-collection? collection)
(and (rs-settings/remote-sync-transforms)
(transforms-namespace-collection? collection))
(and (rs-settings/library-is-remote-synced?)
- (library-namespace-collection? collection))))
+ (library-namespace-collection? collection))
+ (data-apps-namespace-collection? collection)))
(defn all-syncable-collection-ids
"Returns a vector of all collection IDs that are eligible for remote sync.
@@ -745,6 +750,7 @@
- Collections with is_remote_synced=true
- Transforms-namespace collections (when remote-sync-transforms setting is enabled)
- Snippets- and data-actions-namespace collections (when Library is remote-synced)
+ - Data-apps-namespace collections (data apps are synced globally)
Used by import cleanup to determine which collections to scope deletions to."
[]
@@ -756,7 +762,8 @@
(when (rs-settings/library-is-remote-synced?)
(remote-sync.db/collection-ids-in-namespace "snippets"))
(when (rs-settings/library-is-remote-synced?)
- (remote-sync.db/collection-ids-in-namespace (name collections/data-actions-ns)))]))
+ (remote-sync.db/collection-ids-in-namespace (name collections/data-actions-ns)))
+ (remote-sync.db/collection-ids-in-namespace (name collections/data-apps-ns))]))
(def ^:private max-conflict-names
"Cap on how many entity names a collection deletion conflict carries, so the payload stays bounded when
@@ -850,13 +857,18 @@
(defmethod check-eligibility-by-type :collection
[{:keys [eligibility] :as spec} object]
(let [collection-type (:collection eligibility)
- collection-id (:collection_id object)]
- (if (library-synced-object? spec object)
+ collection-id (:collection_id object)
+ ;; what sits in a data app's collection is synced with the app, an action without a model included: the
+ ;; app's copies belong to no model, and are the app's rather than the Library's
+ in-data-app? (and (some? collection-id)
+ (data-apps-namespace-collection? {:namespace (remote-sync.db/collection-namespace collection-id)}))]
+ (if (and (library-synced-object? spec object) (not in-data-app?))
(and (rs-settings/library-is-remote-synced?)
(library-content? spec object))
(case collection-type
:remote-synced
- (collections/remote-synced-collection? collection-id)
+ (or (collections/remote-synced-collection? collection-id)
+ in-data-app?)
:transforms-namespace
(and (rs-settings/remote-sync-transforms)
@@ -871,7 +883,8 @@
(and (rs-settings/remote-sync-transforms)
(transforms-namespace-collection? object))
(and (rs-settings/library-is-remote-synced?)
- (library-namespace-collection? object)))
+ (library-namespace-collection? object))
+ (data-apps-namespace-collection? object))
false))))
@@ -1275,7 +1288,8 @@
(collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace "snippets")))
(when (rs-settings/library-is-remote-synced?)
(collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace
- (name collections/data-actions-ns))))))
+ (name collections/data-actions-ns))))
+ (collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace (name collections/data-apps-ns)))))
:derived
(library-synced-root-export-roots spec)))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj
index 4149cd355d4..45fa6cfefad 100644
--- a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj
@@ -10,7 +10,6 @@
[metabase.actions.core :as actions]
[metabase.api.macros.defendpoint.closed-schemas :as closed-schemas]
[metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]
[metabase.permissions.core :as perms]
[metabase.test :as mt]
[metabase.util.json :as json]
@@ -121,10 +120,7 @@
(is (=? {:display_name "Demo" :enabled true} (t2/select-one :model/DataApp :name "demo"))))
(testing "enabling and disabling stays allowed"
(is (=? {:enabled false}
- (mt/user-http-request :crowberto :put 200 "apps/demo" {:enabled false}))))
- (testing "drafts are outside sync, so they can still be created and deleted"
- (mt/user-http-request :crowberto :post 200 "apps/draft-app/draft")
- (mt/user-http-request :crowberto :delete 204 "apps/draft-app")))
+ (mt/user-http-request :crowberto :put 200 "apps/demo" {:enabled false})))))
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-type :read-write]
(testing "a read-write instance allows changes"
@@ -145,275 +141,6 @@
(deftest ^:parallel query-definition-request-schema-is-closed-test
(is (empty? (closed-schemas/findings ::query-definition/query-definition))))
-(deftest superuser-can-resolve-a-query-definition-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [response (mt/user-http-request
- :crowberto :post 200 "apps/demo/query"
- {:stages [{:source {:type "table" :id (mt/id :venues) :name "Venues"
- :fields {:price {:type "column" :name "PRICE" :jsType "number"}}
- :segments {} :measures {}
- :columns [{:name "PRICE" :jsType "number"}]}
- :orderBys [{:type "column" :name "PRICE" :tableId (mt/id :venues)
- :fieldId (mt/id :venues :price) :baseType "type/Integer"
- :effectiveType "type/Integer" :defaultTemporalBucket nil
- :direction "asc" :jsType "number" :description "Price tier"}]
- :filters [{:type "operator" :operator ">"
- :args [{:type "column" :name "PRICE" :description "Price tier"}
- {:type "literal" :value 2}]}]
- :limit 5}]})]
- (is (= (mt/id) (:database_id response)))
- (is (=? {:dataset_query {:lib/type "mbql/query"
- :database (mt/id)
- :stages [{:lib/type "mbql.stage/mbql"
- :source-table (mt/id :venues)
- :filters [[">" {} ["field" {} (mt/id :venues :price)] 2]]
- :order-by [["asc" {} ["field" {} (mt/id :venues :price)]]]
- :limit 5}]}}
- response))))))
-
-(deftest query-definition-normalizes-nested-binning-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (doseq [[field-name field-id binning expected]
- [["PRICE" (mt/id :venues :price)
- {:strategy "num-bins" :numBins 10} {:strategy "num-bins" :num-bins 10}]
- ["LATITUDE" (mt/id :venues :latitude)
- {:strategy "bin-width" :binWidth 20.0} {:strategy "bin-width" :bin-width 20.0}]
- ["PRICE" (mt/id :venues :price)
- {:strategy "default"} {:strategy "default"}]]]
- (let [column {:type "column" :name field-name :description "A numeric field" :binning binning}
- response (mt/user-http-request
- :crowberto :post 200 "apps/demo/query"
- {:stages [{:source {:type "table" :id (mt/id :venues)}
- :aggregations [{:type "operator" :operator "count" :args []}]
- :breakouts [column]
- :orderBys [(assoc column :direction "asc")]}]})]
- (is (=? {:dataset_query
- {:stages [{:breakout [["field" {:binning expected} field-id]]
- :order-by [["asc" {} ["field" {:binning expected} field-id]]]}]}}
- response)))))))
-
-(deftest query-definition-rejects-unknown-nested-binning-options-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [response (mt/user-http-request
- :crowberto :post 400 "apps/demo/query"
- {:stages [{:source {:type "table" :id (mt/id :venues)}
- :breakouts [{:type "column" :name "PRICE"
- :binning {:strategy "num-bins" :numBins 10 :unexpected true}}]}]})]
- (is (= {:errors {:stages [{:breakouts [{:binning {:unexpected ["disallowed key"]}}]}]}}
- response))))))
-
-(deftest query-definition-resolves-an-aggregation-with-sdk-metadata-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [response (mt/user-http-request
- :crowberto :post 200 "apps/demo/query"
- {:stages [{:source {:type "table" :id (mt/id :venues)}
- :aggregations [{:type "operator"
- :operator "count"
- :args []
- :columns [{:name "count"
- :displayName "Count"
- :jsType "number"}]}]}]})]
- (is (=? {:dataset_query {:stages [{:aggregation [["count" {}]]}]}}
- response))))))
-
-(deftest query-definition-ignores-the-enabled-option-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [table-id (mt/id :venues)
- response (mt/user-http-request
- :crowberto :post 200 "apps/demo/query"
- {:stages [{:source {:type "table" :id table-id}
- :enabled false}]})]
- (is (=? {:dataset_query {:stages [{:source-table table-id}]}}
- response))))))
-
-(deftest query-definition-rejects-unsupported-fields-over-http-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (doseq [[path expected-errors]
- [[[:unexpected] {:unexpected ["disallowed key"]}]
- [[:stages 0 :joins] {:stages [{:joins ["disallowed key"]}]}]
- [[:stages 0 :expressions] {:stages [{:expressions ["disallowed key"]}]}]
- [[:stages 0 :source :unexpected] {:stages [{:source {:unexpected ["disallowed key"]}}]}]
- [[:stages 0 :fields 0 :unexpected] {:stages [{:fields [{:unexpected ["disallowed key"]}]}]}]]]
- (testing (str "Reject unsupported fields at " path)
- (let [query {:stages [{:source {:type "table" :id (mt/id :venues)}
- :fields [{:type "column" :name "PRICE"}]}]}
- response (mt/user-http-request :crowberto :post 400 "apps/demo/query"
- (assoc-in query path []))]
- (is (= {:errors expected-errors} response))))))))
-
-(deftest query-definition-resolves-a-metric-with-sdk-metadata-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [metadata-provider (mt/metadata-provider)
- venue-count-query (-> (lib/query metadata-provider
- (lib.metadata/table metadata-provider (mt/id :venues)))
- (lib/aggregate (lib/count)))]
- (mt/with-temp [:model/Card {metric-id :id}
- {:name "Venue count"
- :type :metric
- :database_id (mt/id)
- :table_id (mt/id :venues)
- :dataset_query venue-count-query}]
- (let [response (mt/user-http-request
- :crowberto :post 200 "apps/demo/query"
- {:stages [{:source {:type "table" :id (mt/id :venues)}
- :aggregations [{:type "metric" :id metric-id :name "Venue count"
- :databaseId (mt/id) :sourceTableId (mt/id :venues)
- :sourceCardId nil :mappedTableIds [(mt/id :venues)]
- :columns {:count {:type "column" :name "count" :jsType "number"}}
- :dimensions {}}]}]})]
- (is (= [metric-id] (mapv :id (:metrics response))))))))))
-
-(deftest rejects-metrics-whose-definition-reads-another-card-test
- (testing "sync copies a referenced metric but rewrites nothing inside the copy, so a metric that
- itself reads another card would publish and then fail for viewers without access to that
- card's collection -- resolving the query has to refuse it"
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [metadata-provider (mt/metadata-provider)
- venues (lib.metadata/table metadata-provider (mt/id :venues))
- venue-count-query (-> (lib/query metadata-provider venues)
- (lib/aggregate (lib/count)))
- orders-query (lib/query metadata-provider
- (lib.metadata/table metadata-provider (mt/id :orders)))
- app-query (fn [metric-id]
- {:stages [{:source {:type "table" :id (mt/id :venues)}
- :aggregations [{:type "metric" :id metric-id}]}]})]
- (mt/with-temp [:model/Card {inner-metric-id :id}
- {:name "Venue count"
- :type :metric
- :database_id (mt/id)
- :table_id (mt/id :venues)
- :dataset_query venue-count-query}
- :model/Card {question-id :id}
- {:name "Orders"
- :type :question
- :database_id (mt/id)
- :table_id (mt/id :orders)
- :dataset_query orders-query}]
- (let [;; built after the cards exist, so the provider can resolve them
- provider (mt/metadata-provider)
- nested-query (lib/test-query provider (app-query inner-metric-id))
- question-sourced-query (lib/query provider (lib.metadata/card provider question-id))]
- (testing "the inner metric on its own resolves"
- (is (= [inner-metric-id]
- (mapv :id (:metrics (mt/user-http-request
- :crowberto :post 200 "apps/demo/query"
- (app-query inner-metric-id)))))))
- (mt/with-temp [:model/Card {nested-metric-id :id}
- {:name "Nested venue count"
- :type :metric
- :database_id (mt/id)
- :table_id (mt/id :venues)
- :dataset_query nested-query}
- :model/Card {question-metric-id :id}
- {:name "Orders question metric"
- :type :metric
- :database_id (mt/id)
- :table_id (mt/id :orders)
- :dataset_query question-sourced-query}]
- (testing "a metric that references another metric is refused"
- (is (= (str "Data app queries cannot use metrics that reference other saved questions"
- " or metrics: Nested venue count")
- (mt/user-http-request
- :crowberto :post 400 "apps/demo/query"
- (app-query nested-metric-id)))))
- (testing "so is one built on a saved question, which sync does not copy either"
- (is (= (str "Data app queries cannot use metrics that reference other saved questions"
- " or metrics: Orders question metric")
- (mt/user-http-request
- :crowberto :post 400 "apps/demo/query"
- (app-query question-metric-id)))))))))))))
-
-(deftest resolved-query-includes-implicitly-joined-tables-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [orders-id (mt/id :orders)
- products-id (mt/id :products)
- product-id-field-id (mt/id :orders :product_id)
- response (mt/user-http-request
- :crowberto :post 200 "apps/demo/query"
- {:stages [{:source {:type "table" :id orders-id}
- :breakouts [{:type "column"
- :name "CATEGORY"
- :source-field-id product-id-field-id}]}]})]
- (is (= #{orders-id products-id}
- (set (:table_ids response))))))))
-
-(deftest saved-query-table-dependencies-include-implicitly-joined-tables-test
- (testing "sync copies models, actions and metrics whose queries never pass through /query, and the
- table an implicit join reaches is named nowhere in such a query -- only this lookup finds it"
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [metadata-provider (mt/metadata-provider)
- orders-query (lib/query metadata-provider
- (lib.metadata/table metadata-provider (mt/id :orders)))
- category (->> (lib/breakoutable-columns orders-query)
- (filter #(= (:id %) (mt/id :products :category)))
- first)
- model-query (lib/breakout orders-query category)]
- (mt/with-temp [:model/Card {model-id :id}
- {:name "Orders by category"
- :type :model
- :database_id (mt/id)
- :table_id (mt/id :orders)
- :dataset_query model-query}]
- (let [dataset-query (t2/select-one-fn :dataset_query :model/Card :id model-id)
- response (mt/user-http-request
- :crowberto :post 200 "apps/demo/query-table-dependencies"
- {:dataset_queries [dataset-query]})]
- (is (= #{(mt/id :orders) (mt/id :products)}
- (set (:table_ids response)))))))))))
-
-(deftest superuser-can-store-table-dependencies-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (let [table-ids [(mt/id :venues) (mt/id :orders)]]
- (is (= (sort table-ids)
- (:table_ids
- (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"
- {:table_ids (reverse table-ids)}))))
- (is (= (sort table-ids)
- (t2/select-one-fn :table_ids :model/DataApp :name "demo")))
- (is (= []
- (:table_ids
- (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"
- {:table_ids []}))))))))
-
-(deftest non-superuser-cannot-store-table-dependencies-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (is (= "You don't have permissions to do that."
- (mt/user-http-request :rasta :put 403 "apps/demo/table-dependencies"
- {:table_ids [(mt/id :venues)]}))))))
-
-(deftest table-dependencies-validates-table-ids-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (is (= "One or more tables do not exist."
- (mt/user-http-request :crowberto :put 400 "apps/demo/table-dependencies"
- {:table_ids [Integer/MAX_VALUE]})))
- (is (= [] (t2/select-one-fn :table_ids :model/DataApp :name "demo"))))))
-
(deftest user-permission-warnings-test
(mt/with-premium-features #{:data-apps :advanced-permissions :sandboxes}
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Sandbox]
@@ -428,8 +155,7 @@
(is (= []
(mt/user-http-request :crowberto :post 200 "apps/demo/user-permission-warnings"
{:user_ids [user-id]}))))
- (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"
- {:table_ids [allowed-table-id missing-table-id]})
+ (t2/update! :model/DataApp :name "demo" {:table_ids [allowed-table-id missing-table-id]})
(perms/add-user-to-group! user-id app-group-id)
(perms/set-table-permission! app-group-id
missing-table-id
@@ -513,8 +239,7 @@
(filter (comp #{"demo"} :name))
first
:has_user_permission_warnings)]
- (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"
- {:table_ids [table-id]})
+ (t2/update! :model/DataApp :name "demo" {:table_ids [table-id]})
(perms/add-user-to-group! user-id app-group-id)
(is (true? (warning?)))
(perms/set-table-permission! (perms/all-users-group)
@@ -534,8 +259,7 @@
(mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}]
(perms/add-user-to-group! user-id app-group-id)
(t2/update! :model/User :id user-id {:is_active false})
- (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"
- {:table_ids [table-id]})
+ (t2/update! :model/DataApp :name "demo" {:table_ids [table-id]})
(is (false? (->> (mt/user-http-request :crowberto :get 200 "apps")
(filter (comp #{"demo"} :name))
first
@@ -581,11 +305,8 @@
(deftest data-app-write-endpoints-require-feature-token-test
(mt/with-premium-features #{}
- (mt/user-http-request :crowberto :put 402 "apps/demo/table-dependencies"
- {:table_ids []})
(mt/user-http-request :crowberto :post 402 "apps/demo/user-permission-warnings"
- {:user_ids [(mt/user->id :rasta)]})
- (mt/user-http-request :crowberto :post 402 "apps/demo/draft")))
+ {:user_ids [(mt/user->id :rasta)]})))
(deftest data-app-membership-additions-require-feature-token-test
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
@@ -631,90 +352,34 @@
(mt/user-http-request :crowberto :put 204 endpoint)
(is (not (t2/exists? :model/PermissionsGroupMembership :group_id group-id)))))))
-(deftest query-definition-must-use-a-table-source-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (is (some? (mt/user-http-request :crowberto :post 400 "apps/demo/query"
- {:stages [{:source {:type "card" :id 1}}]}))))))
-
-(deftest query-definition-source-must-be-valid-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (is (some? (mt/user-http-request :crowberto :post 400 "apps/demo/query"
- {:stages [{:source {:type 1 :id (mt/id :venues)}}]}))))))
-
-(deftest non-superuser-cannot-resolve-a-query-definition-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (create-app!)
- (is (= "You don't have permissions to do that."
- (mt/user-http-request :rasta :post 403 "apps/demo/query"
- {:stages [{:source {:type "table" :id (mt/id :venues)}}]}))))))
-
-(deftest superuser-can-create-or-reuse-a-data-app-draft-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (let [first-response (mt/user-http-request :crowberto :post 200 "apps/draft-app/draft")
- second-response (mt/user-http-request :crowberto :post 200 "apps/draft-app/draft")]
- (is (=? {:name "draft-app"
- :resource_collection_id pos-int?
- :permission_group_id pos-int?}
- first-response))
- (is (= (select-keys first-response [:resource_collection_id :permission_group_id])
- (select-keys second-response [:resource_collection_id :permission_group_id])))
- (is (=? {:bundle nil :draft true}
- (t2/select-one [:model/DataApp :bundle :draft] :name "draft-app")))))))
-
-(deftest non-superuser-cannot-create-a-data-app-draft-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (is (= "You don't have permissions to do that."
- (mt/user-http-request :rasta :post 403 "apps/draft-app/draft")))
- (is (not (t2/exists? :model/DataApp :name "draft-app"))))))
-
-(deftest data-app-draft-must-have-a-valid-slug-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (is (=? {:errors {:slug #".*lowercase letters.*"}}
- (mt/user-http-request :crowberto :post 400 "apps/Draft/draft")))
- (is (not (t2/exists? :model/DataApp :name "Draft"))))))
-
(deftest data-app-group-reaches-only-copied-actions-test
- (testing "an action is reachable exactly when its model lives in the data app collection"
+ (testing "an action is reachable exactly when it lives in the data app collection"
(mt/with-premium-features #{:data-apps}
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
(mt/with-non-admin-groups-no-root-collection-perms
;; Its own slug: the `Data App: <slug>` group outlives other tests in
;; this namespace, so sharing "demo" collides on the group name.
(let [{:keys [permission_group_id resource_collection_id]}
- (data-apps.apps/ensure-draft! "action-perms-app")
- metadata-provider (mt/metadata-provider)
- venues (lib.metadata/table metadata-provider (mt/id :venues))]
+ (first (t2/insert-returning-instances! :model/DataApp
+ {:name "action-perms-app"
+ :display_name "Action perms app"
+ :bundle_path "data_apps/action-perms-app/index.js"}))]
(perms/add-user-to-group! (mt/user->id :rasta) permission_group_id)
- (mt/with-temp
- [:model/Collection {source-collection-id :id} {}
- :model/Card {source-model-id :id} {:type :model
- :collection_id source-collection-id
- :dataset_query (lib/query metadata-provider venues)}
- ;; What `npm run sync-resources` produces: a copy of the model in the
- ;; app's own collection, carrying its own copy of the action.
- :model/Card {copied-model-id :id} {:type :model
- :collection_id resource_collection_id
- :dataset_query (lib/query metadata-provider venues)}]
- (let [action {:name "Create Venue", :type :implicit, :kind :row/create}
- source-id (actions/insert! (assoc action :model_id source-model-id))
- copied-id (actions/insert! (assoc action :model_id copied-model-id))]
+ ;; an action on no model lives in a data actions collection, as a data app runs them
+ (mt/with-temp [:model/Collection {source-collection-id :id} {:namespace :data-actions}]
+ ;; A query action on no model, as a data app runs them, and its copy in the app's own collection.
+ (let [action {:name "Rename venue"
+ :type :query
+ :database_id (mt/id)
+ :dataset_query (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = 'x'")}
+ source-id (actions/insert! (assoc action :collection_id source-collection-id))
+ copied-id (actions/insert! (assoc action :collection_id resource_collection_id))]
(testing "the app's group reads the action copied into its collection"
(is (=? {:id copied-id}
(mt/user-http-request :rasta :get 200 (str "action/" copied-id)))))
(testing "the same group cannot read the source action it was copied from"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "action/" source-id)))))
- (testing "copying does not widen access to the source model"
- (is (= "You don't have permissions to do that."
- (mt/user-http-request :rasta :get 403 (str "card/" source-model-id)))))
(testing "a superuser still reads both"
(is (=? {:id source-id}
(mt/user-http-request :crowberto :get 200 (str "action/" source-id)))))))))))))
@@ -725,8 +390,6 @@
(t2/insert! :model/DataApp :name "ready" :display_name "Ready" :bundle_path "data_apps/ready/index.js")
(t2/insert! :model/DataApp :name "disabled" :display_name "Disabled" :bundle_path "data_apps/disabled/index.js"
:enabled false)
- (t2/insert! :model/DataApp :name "draft" :display_name "Draft" :bundle_path "data_apps/draft/index.js"
- :draft true)
(is (=? [{:name "ready" :display_name "Ready"}]
(mt/user-http-request :rasta :get 200 "apps?available=true"))))))
@@ -839,7 +502,6 @@
:allowed_hosts ["https://api.example.com"]
:version 1
:enabled true
- :draft false
:bundle_hash string?
:resource_collection_id pos-int?
:permission_group_id pos-int?}
@@ -859,15 +521,6 @@
(mt/user-http-request :crowberto :post 400 "apps" (merge app-request {:name "other"} bad))
(is (not (t2/exists? :model/DataApp :name "other")) (str "should refuse: " (pr-str bad)))))))))
-(deftest create-endpoint-fills-a-draft-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (let [draft (mt/user-http-request :crowberto :post 200 "apps/demo/draft")]
- (is (=? {:id (:id draft)
- :draft false
- :resource_collection_id (:resource_collection_id draft)}
- (mt/user-http-request :crowberto :post 200 "apps" app-request)))))))
-
(deftest update-endpoint-test
(mt/test-helpers-set-global-values!
(mt/with-premium-features #{:data-apps}
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/apps_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/apps_test.clj
index f8e0c8d89ce..bc0d2f9bec7 100644
--- a/enterprise/backend/test/metabase_enterprise/data_apps/apps_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/apps_test.clj
@@ -2,8 +2,7 @@
(:require
[clojure.test :refer :all]
[metabase-enterprise.data-apps.apps :as data-apps.apps]
- [metabase.test :as mt]
- [toucan2.core :as t2]))
+ [metabase.test :as mt]))
(set! *warn-on-reflection* true)
@@ -13,23 +12,6 @@
:bundle_path "dist/index.js"
:bundle (.getBytes "BUNDLE" "UTF-8")})
-(deftest concurrent-draft-creation-is-safe-test
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (let [drafts (doall (repeatedly 2 #(future (data-apps.apps/ensure-draft! "draft-app"))))]
- (doseq [draft drafts]
- @draft)
- (is (= 1 (t2/count :model/DataApp :name "draft-app"))))))
-
-(deftest create-app-fills-a-draft-with-the-same-slug-test
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (let [{:keys [resource_collection_id]} (data-apps.apps/ensure-draft! "sales")
- draft-id (t2/select-one-pk :model/DataApp :name "sales")]
- (is (= draft-id (data-apps.apps/create-app! app-row)))
- (is (=? {:display_name "Sales"
- :draft false
- :resource_collection_id resource_collection_id}
- (t2/select-one :model/DataApp draft-id))))))
-
(deftest create-app-refuses-a-taken-slug-test
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
(data-apps.apps/create-app! app-row)
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/query_definition_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/query_definition_test.clj
index 71f019847cc..af02b2a041b 100644
--- a/enterprise/backend/test/metabase_enterprise/data_apps/query_definition_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/query_definition_test.clj
@@ -24,6 +24,22 @@
(deftest ^:parallel supported-query-fields-test
(is (nil? (mr/explain ::query-definition/query-definition query-definition))))
+(deftest ^:parallel named-aggregation-test
+ (testing "an aggregation named in its definition, which the SDK sends as `name`"
+ (is (nil? (mr/explain ::query-definition/query-definition
+ (assoc-in query-definition [:stages 0 :aggregations]
+ [{:type :operator :operator :sum :name "revenue"
+ :args [{:type :column :name "PRICE"}]}]))))))
+
+(deftest ^:parallel only-an-aggregation-is-named-test
+ (testing "a name on a filter or a nested argument is refused rather than dropped"
+ (doseq [path [[:stages 0 :filters 0]
+ [:stages 0 :aggregations 0 :args 0]]]
+ (testing (pr-str path)
+ (is (some? (mr/explain ::query-definition/query-definition
+ (assoc-in query-definition path
+ {:type :operator :operator :count :name "n" :args []}))))))))
+
(deftest ^:parallel unknown-query-fields-test
(doseq [path [[] [:stages 0] [:stages 0 :source]
[:stages 0 :fields 0]
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/resource_serialization_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/resource_serialization_test.clj
new file mode 100644
index 00000000000..a8836315b6a
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/resource_serialization_test.clj
@@ -0,0 +1,495 @@
+(ns metabase-enterprise.data-apps.resource-serialization-test
+ "`POST /api/apps/serialize-resources`: what the files of a data app's collection are written from."
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [medley.core :as m]
+ [metabase-enterprise.data-apps.resource-serialization :as resource-serialization]
+ [metabase-enterprise.data-apps.test-util :as data-apps.tu]
+ [metabase.actions.core :as actions]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.models.serialization :as serdes]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [metabase.util.malli.fn :as mu.fn]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private app-collection "appCollectionEntity01")
+
+(defn- with-ids
+ "`queries` with an entity ID each, as a definition carries one, unless a query brings its own."
+ [queries]
+ (mapv #(merge {:entity_id (u/generate-nano-id)} %) queries))
+
+(defn- serialize!
+ "Serialize `body` as `user`, in the app collection `app-collection` unless `body` names one, each query with an entity
+ ID unless it brings one."
+ ([user status body]
+ (serialize! user status body #{:data-apps}))
+ ([user status body features]
+ (mt/with-premium-features features
+ (mt/user-http-request user :post status "apps/serialize-resources"
+ (cond-> (merge {:collection app-collection} body)
+ (:queries body) (update :queries with-ids))))))
+
+(deftest serialization-needs-each-querys-entity-id-test
+ (testing "the saved question is written with the definition's entity ID, so every query names one"
+ (mt/with-premium-features #{:data-apps}
+ (is (=? {:errors {:queries some?}}
+ (mt/user-http-request :crowberto :post 400 "apps/serialize-resources"
+ {:collection app-collection
+ :queries [{:export "Venues" :query {:stages [{:source {:type "table" :id (mt/id :venues)}}]}}]
+ :actions []}))))))
+
+(deftest serialization-needs-the-apps-collection-test
+ (testing "the saved question is written into the app's collection, so the request names it"
+ (mt/with-premium-features #{:data-apps}
+ (is (=? {:errors {:collection some?}}
+ (mt/user-http-request :crowberto :post 400 "apps/serialize-resources" {:queries [] :actions []}))))))
+
+(defn- db-name []
+ (t2/select-one-fn :name :model/Database (mt/id)))
+
+(defn- table-path [table]
+ [(db-name) "PUBLIC" table])
+
+(defn- field-path [table field]
+ [(db-name) "PUBLIC" table field])
+
+(defn- venues-column [field-name & {:as extra}]
+ (merge {:type "column" :name field-name :tableId (mt/id :venues) :sourceName "VENUES"} extra))
+
+(deftest serializes-a-query-with-every-reference-portable-test
+ (let [response (serialize! :crowberto 200
+ {:queries [{:export "PriceByCategory"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :filters [{:type "operator" :operator ">"
+ :args [(venues-column "PRICE")
+ {:type "literal" :value 1}]}]
+ :aggregations [{:type "operator" :operator "sum" :name "total"
+ :args [(venues-column "PRICE")]}]
+ :breakouts [{:type "column"
+ :name "NAME"
+ :sourceName "CATEGORIES"
+ :sourceFieldId (mt/id :venues :category_id)}]
+ :orderBys [{:type "column"
+ :name "total"
+ :direction "desc"}]
+ :limit 5}]}}]})]
+ (testing "the query Metabase builds from the definition, referencing tables and fields by name"
+ (let [price (field-path "VENUES" "PRICE")
+ category-id (field-path "VENUES" "CATEGORY_ID")
+ category (field-path "CATEGORIES" "NAME")]
+ (is (=? {:queries [{:export "PriceByCategory"
+ :metrics []
+ :entity {:dataset_query {:lib/type "mbql/query"
+ :database (db-name)
+ :stages [{:source-table (table-path "VENUES")
+ :filters [[">" {} ["field" {} price] 1]]
+ :aggregation [["sum" {:name "total"} ["field" {} price]]]
+ :breakout [["field" {:source-field category-id} category]]
+ :order-by [["desc" {} ["aggregation"
+ {:lib/source-name "total"}
+ string?]]]
+ :limit 5}]}}}]}
+ response))))
+ (testing "only the uuid the order by points at is kept, and it is the aggregation's"
+ (let [stage (-> response :queries first :entity :dataset_query :stages first)]
+ (is (= (get-in stage [:aggregation 0 1 :lib/uuid])
+ (get-in stage [:order-by 0 2 2])))
+ (is (nil? (get-in stage [:filters 0 1 :lib/uuid])))))))
+
+(deftest only-a-superuser-serializes-test
+ (testing "an app's resources are written into its repository, which only an admin works with"
+ (let [body {:queries [{:export "Venues" :query {:stages [{:source {:type "table" :id (mt/id :venues)}}]}}]}]
+ (is (= "You don't have permissions to do that." (serialize! :rasta 403 body)))
+ (is (=? {:queries [{:export "Venues" :entity map?}]} (serialize! :crowberto 200 body))))))
+
+(deftest lists-the-metrics-a-query-aggregates-test
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id]}]
+ (let [metric-eid (t2/select-one-fn :entity_id :model/Card :id metric-id)]
+ (is (=? {:queries [{:export "VenueCount"
+ :metrics [metric-eid]
+ :entity {:dataset_query {:stages [{:aggregation [["metric" {} metric-eid]]}]}}}]
+ :metrics [{:id metric-id
+ :entity {:entity_id metric-eid
+ :type "metric"
+ :dataset_query {:stages [{:source-table (table-path "VENUES")}]}}}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "VenueCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id metric-id}]}]}}]})))))))
+
+(deftest answers-each-query-on-its-own-test
+ (is (=? {:queries [{:export "Venues" :entity {:dataset_query {:stages [{:source-table (table-path "VENUES")}]}}}
+ {:export "Broken" :error "No column found"}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "Venues"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}}]}}
+ {:export "Broken"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :fields [(venues-column "NOT_A_COLUMN")]}]}}]}))))
+
+(deftest serializes-a-query-action-test
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [action-id]}]
+ (let [response (serialize! :crowberto 200 {:actions [action-id]})]
+ (is (=? {:actions [{:id action-id
+ :entity {:entity_id (t2/select-one-fn :entity_id :model/Action :id action-id)
+ :type "query"
+ :query [{:database_id (db-name)
+ :dataset_query {:database (db-name)}}]}}]}
+ response))
+ (is (not (contains? (-> response :actions first :entity) :model_id))
+ "it names no model")))))
+
+(deftest refuses-an-action-that-belongs-to-a-model-test
+ (testing "a data app runs only actions that belong to no model, as the typed schema lists only those"
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [model-action-id]}]
+ (is (=? {:actions [{:id model-action-id :error #"Action \d+ belongs to a model\..*"}]}
+ (serialize! :crowberto 200 {:actions [model-action-id]})))))))
+
+(deftest refuses-what-a-copy-cannot-hold-test
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id model-id]}]
+ (let [mp (mt/metadata-provider)
+ model-count (lib/aggregate (lib/query mp (lib.metadata/card mp model-id)) (lib/count))]
+ (mt/with-temp [:model/Card {reading-metric-id :id} {:name "Metric reading a model"
+ :type :metric
+ :database_id (mt/id)
+ :dataset_query model-count}]
+ (let [card-sql-id (actions/insert! {:name "Read a card"
+ :type :query
+ :database_id (mt/id)
+ :dataset_query (lib/native-query
+ mp (str "SELECT * FROM {{#" metric-id "}}"))})
+ reads-metric {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id reading-metric-id}]}]}
+ response (serialize! :crowberto 200
+ {:queries [{:export "ReadsMetric" :query reads-metric}]
+ :actions [card-sql-id Integer/MAX_VALUE]})]
+ (testing "a query action whose SQL reads a card"
+ (is (=? {:id card-sql-id :error (re-pattern (str ".*reads card " metric-id ".*"))}
+ (nth (:actions response) 0))))
+ (testing "an action that does not exist"
+ (is (=? {:error #".*does not exist.*"} (nth (:actions response) 1))))
+ (testing "a metric that reads a card; the query that aggregates it is still built"
+ (is (=? {:queries [{:export "ReadsMetric" :entity map?}]
+ :metrics [{:id reading-metric-id :error (re-pattern (str ".*reads card " model-id ".*"))}]}
+ response)))))))))
+
+(deftest rejects-unsupported-definitions-test
+ (testing "the request accepts only what data app definitions support"
+ (doseq [path [[:queries 0 :query :stages 0 :joins]
+ [:queries 0 :query :stages 0 :expressions]]]
+ (testing (pr-str path)
+ (serialize! :crowberto 400
+ (assoc-in {:queries [{:export "Venues"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}}]}}]}
+ path []))))))
+
+(deftest refuses-a-table-that-does-not-exist-test
+ (is (=? {:queries [{:export "Nothing" :error (str "Table " Integer/MAX_VALUE " does not exist.")}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "Nothing"
+ :query {:stages [{:source {:type "table" :id Integer/MAX_VALUE}}]}}]})))
+ (testing "a deactivated table is gone too, as it is from the typed schema"
+ (mt/with-temp [:model/Table {table-id :id} {:db_id (mt/id) :active false}]
+ (is (=? {:queries [{:export "Gone" :error (str "Table " table-id " does not exist.")}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "Gone"
+ :query {:stages [{:source {:type "table" :id table-id}}]}}]}))))))
+
+(deftest refuses-a-column-that-reaches-a-deactivated-table-test
+ (testing "types generated before categories was deactivated still select its name through venues.category_id, and
+ the query would fail on the implicit join when it runs"
+ (mt/with-temp-vals-in-db :model/Table (mt/id :categories) {:active false}
+ (is (=? {:queries [{:export "VenueCategories" :error (str "Table " (mt/id :categories) " does not exist.")}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "VenueCategories"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :fields [{:type "column" :name "NAME" :source-field-id (mt/id :venues :category_id)}]}]}}]}))))))
+
+(deftest refuses-a-metric-that-reaches-a-deactivated-table-test
+ (testing "a metric the query aggregates reads categories through venues.category_id in its own query, which the
+ built query holds only the ID of, and the query would fail on the table when it runs"
+ (let [mp (mt/metadata-provider)
+ venues (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ categories (mt/id :categories)
+ category (m/find-first (comp #{(mt/id :categories :name)} :id) (lib/filterable-columns venues))]
+ (mt/with-temp [:model/Card {bars-id :id} {:name "Bars"
+ :type :metric
+ :database_id (mt/id)
+ :dataset_query (-> venues
+ (lib/filter (lib/= category "Bar"))
+ (lib/aggregate (lib/count)))}
+ :model/Card {count-id :id} {:name "Venue count"
+ :type :metric
+ :database_id (mt/id)
+ :dataset_query (lib/aggregate venues (lib/count))}]
+ (mt/with-temp-vals-in-db :model/Table categories {:active false}
+ (is (=? {:queries [{:export "BarCount" :error (str "Table " categories " does not exist.")}
+ {:export "VenueCount" :entity map?}]
+ :metrics [{:id count-id :entity map?}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "BarCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id bars-id}]}]}}
+ {:export "VenueCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id count-id}]}]}}]}))))))))
+
+(deftest refuses-a-column-remapped-to-a-deactivated-table-test
+ (testing "venues.category_id displays categories.name, a join the query processor adds only when the query runs, so
+ the built query never names categories"
+ (let [categories (mt/id :categories)
+ venues {:type "table" :id (mt/id :venues)}]
+ (mt/with-column-remappings [venues.category_id categories.name]
+ (mt/with-temp-vals-in-db :model/Table categories {:active false}
+ (is (=? {:queries [{:export "VenueCategoryIds" :error (str "Table " categories " does not exist.")}
+ {:export "VenuePrices" :entity map?}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "VenueCategoryIds"
+ :query {:stages [{:source venues
+ :fields [{:type "column" :name "CATEGORY_ID"}]}]}}
+ {:export "VenuePrices"
+ :query {:stages [{:source venues
+ :fields [{:type "column" :name "PRICE"}]}]}}]}))))))))
+
+(deftest refuses-a-definition-that-builds-an-invalid-query-test
+ (testing "the request schema accepts what a type lets through, and lib's own checks are off in production, so the
+ built query is checked: an invalid one must not serialize and then fail when it runs"
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-current-user (mt/user->id :crowberto)
+ (binding [mu.fn/*enforce* false]
+ (is (=? {:queries [{:export "Half" :error "The definition does not build a valid query."}
+ {:export "Whole" :entity map?}]}
+ (resource-serialization/serialize-resources
+ app-collection
+ (with-ids [{:export "Half" :query {:stages [{:source {:type :table :id (mt/id :venues)} :limit 1.5}]}}
+ {:export "Whole" :query {:stages [{:source {:type :table :id (mt/id :venues)} :limit 2}]}}])
+ []))))))))
+
+(deftest a-public-source-serializes-as-the-private-copy-the-author-writes-test
+ (testing "what makes a source public or embedded is left out, since the pull refuses a copy that says it is"
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id action-id]}]
+ (t2/update! :model/Card :id metric-id {:public_uuid (str (random-uuid))
+ :made_public_by_id (mt/user->id :crowberto)
+ :enable_embedding true
+ :embedding_params {}})
+ (t2/update! :model/Action :id action-id {:public_uuid (str (random-uuid))
+ :made_public_by_id (mt/user->id :crowberto)})
+ (let [{:keys [actions metrics] :as response} (serialize! :crowberto 200
+ {:queries [{:export "VenueCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id metric-id}]}]}}]
+ :actions [action-id]})]
+ (is (=? {:actions [{:id action-id :entity map?}] :metrics [{:id metric-id :entity map?}]} response))
+ (doseq [{:keys [entity]} (concat actions metrics)]
+ (is (not-any? (partial contains? entity)
+ [:public_uuid :made_public_by_id :enable_embedding :embedding_params :embedding_type]))))))))
+
+(deftest an-item-serialization-cannot-extract-answers-with-the-cause-test
+ (testing "one entity that fails inside its extraction comes back with the reason, which serialization wraps at each
+ level, and the rest still serialize"
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id action-id]}]
+ (t2/update! :model/Card :id metric-id {:visualization_settings {:broken true}})
+ (let [export-settings (mt/original-fn #'serdes/export-visualization-settings)]
+ (mt/with-dynamic-fn-redefs [serdes/export-visualization-settings (fn [settings]
+ (if (:broken settings)
+ (throw (ex-info "the metric is broken" {}))
+ (export-settings settings)))]
+ ;; called directly: the redefinition is bound on this thread, not on the one a request runs on
+ (is (=? {:queries [{:export "VenueCount" :entity map?}]
+ :actions [{:id action-id :entity map?}]
+ :metrics [{:id metric-id :error (str "Could not serialize Metric " metric-id ": the metric is broken")}]}
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-current-user (mt/user->id :crowberto)
+ (resource-serialization/serialize-resources
+ app-collection
+ (with-ids [{:export "VenueCount"
+ :query {:stages [{:source {:type :table :id (mt/id :venues)}
+ :aggregations [{:type :metric :id metric-id}]}]}}])
+ [action-id])))))))))))
+
+(deftest an-item-serialization-leaves-out-answers-without-a-reason-test
+ (testing "a card materialized by an exploration Summary is one serialization leaves out without an error"
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id]}]
+ (mt/with-temp [:model/Exploration {exploration-id :id} {:name "Explo" :creator_id (mt/user->id :crowberto)}
+ :model/Document {summary-id :id} {:name "Summary"
+ :creator_id (mt/user->id :crowberto)
+ :exploration_id exploration-id}]
+ (t2/update! :model/Card :id metric-id {:document_id summary-id})
+ (is (=? {:metrics [{:id metric-id :error (str "Could not serialize Metric " metric-id ".")}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "VenueCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id metric-id}]}]}}]}))))))))
+
+(deftest a-failure-of-the-serialization-is-logged-and-a-refusal-is-not-test
+ (testing "a refusal is the author's to act on; anything else is a failure the server keeps a trace of"
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-log-messages-for-level [messages [metabase-enterprise.data-apps.resource-serialization :warn]]
+ (is (=? {:queries [{:export "Broken" :error "No column found"}
+ {:export "Nothing" :error (str "Table " Integer/MAX_VALUE " does not exist.")}]}
+ (resource-serialization/serialize-resources
+ app-collection
+ (with-ids [{:export "Broken"
+ :query {:stages [{:source {:type :table :id (mt/id :venues)}
+ :fields [{:type :column :name "NOT_A_COLUMN"}]}]}}
+ {:export "Nothing"
+ :query {:stages [{:source {:type :table :id Integer/MAX_VALUE}}]}}])
+ [])))
+ (let [logged (filter #(str/includes? (:message %) "Could not serialize a data app resource") (messages))]
+ (is (= 1 (count logged)))
+ (is (str/includes? (:message (first logged)) "Broken"))))))))
+
+(deftest refuses-archived-sources-test
+ (testing "the pull refuses an archived resource, so the serialization refuses an archived source"
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [action-id]}]
+ (t2/update! :model/Action :id action-id {:archived true})
+ (is (=? {:actions [{:id action-id :error #".*is archived.*"}]}
+ (serialize! :crowberto 200 {:actions [action-id]})))))))
+
+(deftest refuses-an-action-whose-parameter-values-come-from-a-card-test
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id]}]
+ (let [mp (mt/metadata-provider)
+ action-id (actions/insert! {:name "Pick"
+ :type :query
+ :database_id (mt/id)
+ :dataset_query (lib/native-query mp "UPDATE venues SET name = {{name}}")
+ :parameters [{:id "name" :slug "name" :type :string/=
+ :values_source_type :card
+ :values_source_config {:card_id metric-id}}]})]
+ (is (=? {:actions [{:id action-id :error (re-pattern (str ".*reads card " metric-id ".*"))}]}
+ (serialize! :crowberto 200 {:actions [action-id]})))))))
+
+(deftest serializes-a-segment-reference-by-entity-id-test
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Segment {segment-id :id, segment-eid :entity_id}
+ {:name "Cheap"
+ :table_id (mt/id :venues)
+ :definition (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/filter (lib/< (lib.metadata/field mp (mt/id :venues :price)) 3)))}]
+ (is (=? {:queries [{:export "Cheap"
+ :entity {:dataset_query {:stages [{:filters [["segment" {} segment-eid]]}]}}}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "Cheap"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :filters [{:type "segment" :id segment-id}]}]}}]}))))))
+
+(deftest refuses-sources-on-a-routing-destination-test
+ (testing "a routing destination is reachable only through its router, so the typed schema leaves out what it backs,
+ and so does the serialization"
+ (mt/with-temp [:model/Database {router-id :id} {}
+ :model/DatabaseRouter _ {:database_id router-id :user_attribute "region"}
+ :model/Database {destination-id :id} {:router_database_id router-id}]
+ (let [action-id (actions/insert! {:name "Rename venue"
+ :type :query
+ :database_id destination-id
+ :dataset_query {:lib/type :mbql/query
+ :database destination-id
+ :stages [{:lib/type :mbql.stage/native
+ :native "UPDATE venues SET name = 'x'"}]}})]
+ (is (=? {:actions [{:id action-id :error #".*is backed by a routing destination.*"}]}
+ (serialize! :crowberto 200 {:actions [action-id]})))))))
+
+(deftest refuses-a-source-whose-settings-read-a-card-test
+ (testing "a copy keeps every card its serialization references, so a click behaviour linking a saved question is refused
+ like a query reading one"
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id model-id]}]
+ (t2/update! :model/Card :id metric-id
+ {:visualization_settings {:click_behavior {:type "link" :linkType "question" :targetId model-id}}})
+ (is (=? {:metrics [{:id metric-id :error (re-pattern (str ".*reads card " model-id ".*"))}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "VenueCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id metric-id}]}]}}]})))))))
+
+(deftest extracts-the-cards-and-the-actions-once-test
+ (testing "the cards and the actions are each extracted in one serialization query, however many the app uses"
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id action-id model-action-id]}]
+ (let [calls (atom [])
+ extract (mt/original-fn #'resource-serialization/extract-by-entity-id)]
+ (mt/with-dynamic-fn-redefs [resource-serialization/extract-by-entity-id (fn [model-name ids]
+ (swap! calls conj model-name)
+ (extract model-name ids))]
+ (is (=? {:actions [{:entity map?} {:error string?}] :metrics [{:entity map?}]}
+ (serialize! :crowberto 200
+ {:queries [{:export "VenueCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id metric-id}]}]}}]
+ :actions [action-id model-action-id]}))))
+ (is (= {"Card" 1 "Action" 1} (frequencies @calls))))))))
+
+(deftest serializes-the-saved-question-an-author-writes-test
+ (testing "a query comes back as the saved question that holds it: named after the export, in the app's collection,
+ with the definition's entity ID, created by the caller, and nothing unset"
+ (let [{:keys [entity]} (-> (serialize! :crowberto 200
+ {:collection "appCollectionEntity01"
+ :queries [{:export "VenuesList"
+ :entity_id "savedQuestionEntity01"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :limit 5}]}}]})
+ :queries first)]
+ (is (=? {:serdes/meta [{:model "Card" :id "savedQuestionEntity01" :label "venues_list"}]
+ :entity_id "savedQuestionEntity01"
+ :collection_id "appCollectionEntity01"
+ :name "Venues list"
+ :type "question"
+ :display "table"
+ :creator_id "[email protected]"
+ :visualization_settings {}
+ :parameters []
+ :parameter_mappings []
+ :dataset_query {:database (db-name)
+ :stages [{:source-table (table-path "VENUES") :limit 5}]}}
+ entity))
+ (is (not-any? (partial contains? entity)
+ [:description :collection_position :public_uuid :card_schema :archived :enable_embedding])
+ "what serialization leaves unset or at its default is left out, as the format omits it"))))
+
+(deftest card-names-from-export-names-test
+ (are [export card-name] (= card-name (#'resource-serialization/export-name->card-name export))
+ "VenuesList" "Venues list"
+ "ordersByMonth" "Orders by month"
+ "top_10_products" "Top 10 products"
+ "Revenue" "Revenue"))
+
+(deftest keys-come-in-the-order-serialization-writes-them-test
+ (testing "the printed entity comes in the order serialization writes a file, so an author keeps it"
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [{:keys [entity]} (-> (resource-serialization/serialize-resources
+ app-collection
+ ;; decoded, as the endpoint hands a definition over
+ (with-ids [{:export "Venues" :query {:stages [{:source {:type :table :id (mt/id :venues)}}]}}])
+ [])
+ :queries first)]
+ (is (= [:database :stages :lib/type] (keys (:dataset_query entity))))
+ (is (< (.indexOf ^java.util.List (vec (keys entity)) :name)
+ (.indexOf ^java.util.List (vec (keys entity)) :dataset_query))))))))
+
+(deftest omits-the-settings-an-action-leaves-unset-test
+ (testing "nulls inside an action's form settings, which the format omits, are left out of its serialization"
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [action-id]}]
+ (t2/update! :model/Action action-id
+ {:visualization_settings {:fields {:name {:id "name" :hidden true :description nil}}
+ :column_settings nil}})
+ (let [{:keys [entity]} (-> (serialize! :crowberto 200 {:actions [action-id]}) :actions first)]
+ (is (= {:fields {:name {:id "name" :hidden true}}} (:visualization_settings entity)))
+ (is (not (contains? entity :description))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/resource_tables_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/resource_tables_test.clj
new file mode 100644
index 00000000000..b5c4a77d596
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/resource_tables_test.clj
@@ -0,0 +1,46 @@
+(ns metabase-enterprise.data-apps.resource-tables-test
+ "The tables a data app's resources read, recorded for the permission warnings an admin sees."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-apps.resource-tables :as resource-tables]
+ [metabase.lib.core :as lib]
+ [metabase.test :as mt]))
+
+(set! *warn-on-reflection* true)
+
+(deftest a-table-in-an-optional-clause-is-recorded-test
+ (testing "an optional clause is ordinary query syntax that a parser doesn't read, and the tables inside it are read
+ like the ones outside"
+ (let [native (fn [sql] (lib/native-query (mt/metadata-provider) sql))]
+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace :data-apps}
+ :model/Card _ {:collection_id collection-id
+ :dataset_query (native "SELECT * FROM venues WHERE 1=1 [[AND name = {{name}}]]")}
+ :model/Card _ {:collection_id collection-id
+ :dataset_query (native "SELECT * FROM venues v [[JOIN checkins c ON c.venue_id = v.id AND c.id = {{id}}]]")}]
+ (is (= (sort [(mt/id :venues) (mt/id :checkins)])
+ (resource-tables/collection-table-ids collection-id))
+ "checkins is named only inside the optional clause")))))
+
+(deftest a-table-joined-to-a-card-tag-is-recorded-test
+ (testing "a card tag stands where a table does, and the parser reads the query around it"
+ (let [native (fn [sql] (lib/native-query (mt/metadata-provider) sql))]
+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace :data-apps}
+ :model/Card {venues-id :id} {:collection_id collection-id
+ :dataset_query (native "SELECT * FROM venues")}
+ :model/Card _ {:collection_id collection-id
+ :dataset_query (native (format "SELECT * FROM {{#%d}} x JOIN checkins c ON c.venue_id = x.id" venues-id))}]
+ (is (= (sort [(mt/id :venues) (mt/id :checkins)])
+ (resource-tables/collection-table-ids collection-id)))))))
+
+(deftest a-table-in-a-snippet-is-recorded-test
+ (testing "a snippet tag stands for the SQL its snippet holds, snippets inside it included, so the tables it names
+ are read like the ones around it"
+ (let [native (fn [sql] (lib/native-query (mt/metadata-provider) sql))]
+ (mt/with-temp [:model/NativeQuerySnippet _ {:name "venues table" :content "venues"}
+ :model/NativeQuerySnippet _ {:name "checked in" :content "id IN (SELECT venue_id FROM checkins)"}
+ :model/NativeQuerySnippet _ {:name "open" :content "price > 1 AND {{snippet: checked in}}"}
+ :model/Collection {collection-id :id} {:namespace :data-apps}
+ :model/Card _ {:collection_id collection-id
+ :dataset_query (native "SELECT * FROM {{snippet: venues table}} v WHERE {{snippet: open}}")}]
+ (is (= (sort [(mt/id :venues) (mt/id :checkins)])
+ (resource-tables/collection-table-ids collection-id)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/resource_validation_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/resource_validation_test.clj
new file mode 100644
index 00000000000..f96b3afb2e6
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/resource_validation_test.clj
@@ -0,0 +1,424 @@
+(ns metabase-enterprise.data-apps.resource-validation-test
+ "What the files of a data app's collection may hold, checked on the ingested files before anything loads."
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-apps.core :as data-apps]
+ [metabase-enterprise.data-apps.test-util :as data-apps.tu]
+ [metabase-enterprise.serialization.core :as serialization]
+ [metabase.test :as mt]
+ [metabase.util.yaml :as yaml]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private collection-eid (data-apps.tu/collection-entity-id "shop"))
+
+(def ^:private question-eid "shopQuestionListVenue")
+
+(defn- venues-query []
+ {:stages [{:source {:type "table" :id (mt/id :venues)} :limit 5}]})
+
+(defn- ingest [content]
+ (serialization/read-timestamps (yaml/parse-string content {:key-fn serialization/parse-key})))
+
+(defn- files
+ "The data app entity files of the repo `tree`, as ingestion hands them to the check."
+ [tree]
+ (for [[path content] tree
+ :when (str/ends-with? path ".yaml")]
+ {:path path :entity (ingest content)}))
+
+(def ^:private collection-name "Data App: shop")
+
+(def ^:private collection-dir (str "collections/data_apps/" (data-apps.tu/collection-dir collection-name) "/"))
+
+(def ^:private collection-path (data-apps.tu/collection-path collection-name))
+
+(def ^:private question-path (str collection-dir "venueslist_"))
+
+(def ^:private action-path (str collection-dir "rename_venue_"))
+
+(defn- shop
+ "The repo files of the `shop` app with `resources`, a map of repo paths to YAML text (see `data-apps.tu/app-files`)."
+ [resources & {:as options}]
+ (data-apps.tu/app-files "shop" (merge {:name "Shop" :path "index.js" :bundle "B"
+ :collection collection-eid :resources resources}
+ options)))
+
+(defn- question-resources []
+ (data-apps.tu/build-resources collection-name collection-eid [{:entity_id question-eid :name "VenuesList" :query (venues-query)}] []))
+
+(defn- edit-file
+ "`tree` with the YAML of the first file whose path starts with `prefix` changed by `f`."
+ [tree prefix f]
+ (let [path (some #(when (str/starts-with? % prefix) %) (sort (keys tree)))]
+ (update tree path #(yaml/generate-string (f (yaml/parse-string %))))))
+
+(defn- messages [tree]
+ (mapv :message (data-apps/problems (files tree))))
+
+(defn- first-problem [tree]
+ (first (data-apps/problems (files tree))))
+
+(deftest valid-resources-have-no-problems-test
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id action-id]}]
+ (let [resources (data-apps.tu/build-resources
+ collection-name collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}
+ {:entity_id "shopQuestionMetricVen" :name "VenueCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id metric-id}]}]}}]
+ [action-id])]
+ (is (= [] (messages (shop resources))))))))
+
+(deftest an-app-with-only-its-collection-has-no-problems-test
+ (is (= [] (messages (data-apps.tu/app-files "shop" {:name "Shop" :path "index.js" :bundle "B" :collection collection-eid})))))
+
+(deftest a-file-is-named-with-its-problem-test
+ (let [tree (edit-file (shop (question-resources)) question-path #(assoc % :archived true))]
+ (is (=? {:file #"collections/data_apps/data_app__shop/.*\.yaml" :message #".*must not be archived\."}
+ (first-problem tree)))))
+
+(deftest refuses-what-a-resource-may-not-hold-test
+ (let [refused (fn [tree message]
+ (is (some #(str/includes? % message) (messages tree)) message))]
+ (testing "a manifest naming a collection whose file isn't in the repository"
+ (refused (shop (question-resources) :collection (data-apps.tu/collection-entity-id "other"))
+ "is not in the repository"))
+ (testing "a card that isn't a question or metric: a model has no place, now that no action hangs off one"
+ (doseq [card-type ["dashboard" "model"]]
+ (refused (edit-file (shop (question-resources)) question-path #(assoc % :type card-type))
+ "must be a question or metric")))
+ (testing "a card whose query names no database"
+ (refused (edit-file (shop (question-resources)) question-path #(assoc % :dataset_query {}))
+ "must hold a query"))
+ (testing "a public card"
+ (refused (edit-file (shop (question-resources)) question-path #(assoc % :public_uuid "8e2a9c55-6b0f-4b43-a1c4-fb5c0c1b2b0a"))
+ "must not be public or embedded"))
+ (testing "a card that reads a card outside the app"
+ (mt/with-temp [:model/Card {other-id :id} {:dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :venues)}}}]
+ (let [other-eid (t2/select-one-fn :entity_id :model/Card :id other-id)]
+ (refused (edit-file (shop (question-resources)) question-path
+ #(update % :dataset_query assoc :stages [{:lib/type "mbql.stage/mbql" :source-card other-eid}]))
+ (str "references Card " other-eid)))))
+ (testing "a file whose serdes/meta doesn't identify what it holds"
+ (refused (edit-file (shop (question-resources)) question-path #(assoc % :serdes/meta [{:model "Card" :id "someOtherEntityId0001"}]))
+ "must hold a single Card whose serdes/meta ID is its entity_id"))
+ (testing "a table that doesn't exist"
+ (refused (edit-file (shop (question-resources)) question-path
+ #(assoc-in % [:dataset_query :stages 0 :source-table] [(:name (mt/db)) "PUBLIC" "NO_SUCH_TABLE"]))
+ "NO_SUCH_TABLE"))
+ (testing "a manifest that doesn't identify the app, which a load would refuse"
+ (refused (edit-file (shop nil) "data_apps/shop/data_app.yaml" #(dissoc % :entity_id))
+ "must hold a single DataApp whose serdes/meta ID is its entity_id")
+ (refused (edit-file (shop nil) "data_apps/shop/data_app.yaml" #(assoc % :entity_id "someOtherEntityId0001"))
+ "must hold a single DataApp whose serdes/meta ID is its entity_id"))
+ (testing "a manifest naming no collection"
+ (refused (shop (question-resources) :collection nil) "must name the app's resource collection")
+ (refused (shop nil :collection nil) "must name the app's resource collection"))
+ (testing "a manifest naming a collection the repository doesn't hold"
+ (refused (shop (dissoc (question-resources) collection-path)) "is not in the repository")
+ (refused (shop nil) "is not in the repository"))))
+
+(deftest refuses-an-action-the-app-cannot-run-test
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [model-id action-id]}]
+ (let [model-eid (t2/select-one-fn :entity_id :model/Card :id model-id)
+ resources (data-apps.tu/build-resources collection-name collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [action-id])]
+ (is (= [] (messages (shop resources))) "a query action that belongs to no model is fine")
+ (testing "a data app runs only actions that belong to no model, the ones the typed schema lists"
+ (is (some #(str/includes? % "must belong to no model")
+ (messages (edit-file (shop resources) action-path #(assoc % :model_id model-eid))))))
+ (testing "and only query actions"
+ (is (some #(str/includes? % "must be a query action")
+ (messages (edit-file (shop resources) action-path
+ #(assoc % :type "implicit" :query [] :implicit [{:kind "row/create"}])))))
+ (is (some #(str/includes? % "must carry exactly one query, and no implicit action")
+ (messages (edit-file (shop resources) action-path #(assoc % :implicit [{:kind "row/create"}]))))))
+ (testing "a card or action has to name its creator, since a load can't save one without"
+ (is (some #(str/includes? % "must name its creator in creator_id")
+ (messages (edit-file (shop resources) action-path #(dissoc % :creator_id)))))
+ (is (some #(str/includes? % "must name its creator in creator_id")
+ (messages (edit-file (shop resources) question-path #(dissoc % :creator_id))))))
+ (testing "an action outside the app's collection isn't the app's, so it isn't checked as its resource"
+ (is (= [] (messages (edit-file (shop resources) action-path #(assoc % :collection_id "elsewhere0000000000a" :model_id model-eid))))))))))
+
+(deftest refuses-what-this-app-does-not-own-test
+ (testing "serialization would update any row carrying an entity ID a file names, so a file may only name the app's own"
+ (testing "a card whose entity ID belongs to a card elsewhere"
+ (mt/with-temp [:model/Card _ {:name "Someone else's" :entity_id question-eid}]
+ (is (some #(str/includes? % (str "Card " question-eid " already exists outside")) (messages (shop (question-resources)))))))
+ (testing "a collection that is another app's"
+ (mt/with-temp [:model/Collection {collection-id :id} {:entity_id collection-eid :name "Theirs" :namespace :data-apps}
+ :model/DataApp _ {:name "theirs" :display_name "Theirs" :bundle_path "index.js"
+ :resource_collection_id collection-id}]
+ (is (some #(str/includes? % "already exists and is another data app's collection") (messages (shop (question-resources)))))))
+ (testing "a collection outside the data-apps namespace, which a load would move into it"
+ (mt/with-temp [:model/Collection _ {:entity_id collection-eid :name "Finance"}]
+ (is (some #(str/includes? % "already exists outside the data-apps namespace") (messages (shop (question-resources)))))))
+ (testing "the app's own collection and card"
+ (mt/with-temp [:model/Collection {collection-id :id} {:entity_id collection-eid :name "Mine" :namespace :data-apps}
+ :model/DataApp _ {:name "shop" :display_name "Shop" :bundle_path "index.js"
+ :entity_id (data-apps.tu/app-entity-id "shop")
+ :resource_collection_id collection-id}
+ :model/Card _ {:name "Mine" :entity_id question-eid :collection_id collection-id}]
+ (is (= [] (messages (shop (question-resources)))))))))
+
+(deftest refuses-a-field-that-doesnt-exist-test
+ (testing "a field a query names has to exist, on a database without schemas too"
+ (mt/with-temp [:model/Database {db-id :id} {:engine :h2 :name "no-schemas"}
+ :model/Table {table-id :id} {:db_id db-id :name "T" :schema nil :active true}
+ :model/Field _ {:table_id table-id :name "ID" :base_type :type/Integer}]
+ (let [filtering-on (fn [db schema table field]
+ (edit-file (shop (question-resources)) question-path
+ #(assoc % :database_id db
+ :dataset_query {:database db
+ :lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [db schema table]
+ :filters [["=" {} ["field" {} [db schema table field]] 1]]}]})))]
+ (is (some #(str/includes? % "NOPE") (messages (filtering-on "no-schemas" nil "T" "NOPE"))))
+ (is (= [] (messages (filtering-on "no-schemas" nil "T" "ID"))))
+ (is (some #(str/includes? % "NOPE") (messages (filtering-on (:name (mt/db)) "PUBLIC" "VENUES" "NOPE"))))))))
+
+(deftest refuses-a-table-or-field-named-in-any-reference-test
+ (testing "serialization makes a placeholder for a missing table or field wherever a file references one"
+ (let [db (:name (mt/db))
+ refused (fn [missing f]
+ (is (some #(str/includes? % missing)
+ (messages (edit-file (shop (question-resources)) question-path f)))
+ missing))]
+ (testing "result metadata"
+ (refused "NOPE_META" #(assoc % :result_metadata [{:name "NOPE"
+ :base_type "type/Text"
+ :id [db "PUBLIC" "VENUES" "NOPE_META"]}])))
+ (testing "the source field of a field reference"
+ (refused "NOPE_SOURCE" #(assoc-in % [:dataset_query :stages 0 :fields]
+ [["field" {:source-field [db "PUBLIC" "VENUES" "NOPE_SOURCE"]}
+ [db "PUBLIC" "VENUES" "ID"]]])))
+ (testing "a field reference in the older form"
+ (refused "NOPE_LEGACY" #(assoc-in % [:dataset_query :stages 0 :filters]
+ [["=" {} ["field" [db "PUBLIC" "VENUES" "NOPE_LEGACY"] nil] 1]])))
+ (testing "a table template tag"
+ (refused "NOPE_TAG_TABLE" #(assoc % :dataset_query
+ {:database db
+ :lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/native"
+ :native "SELECT * FROM {{t}}"
+ :template-tags {"t" {:type "table"
+ :name "t"
+ :display-name "T"
+ :id "7f2c2a0e-6c1e-4b53-9d0a-0d5a3a1d1c12"
+ :table-id [db "PUBLIC" "NOPE_TAG_TABLE"]}}}]})))
+ (testing "a list of strings that isn't a reference is left alone, even when it starts with a database's name"
+ (is (= [] (messages (edit-file (shop (question-resources)) question-path
+ #(assoc % :visualization_settings {:some.custom/labels [db "Alpha" "Beta"]}))))))
+ (testing "and a file that names only what exists has no problems"
+ (is (= [] (messages (shop (question-resources)))))))))
+
+(deftest refuses-more-of-what-a-resource-may-not-hold-test
+ (let [refused (fn [tree message]
+ (is (some #(str/includes? % message) (messages tree)) message))
+ tree (fn [] (shop (question-resources)))]
+ (testing "a collection file that isn't a root collection of the data-apps namespace"
+ (doseq [change [{:parent_id "someOtherCollection01"} {:archived true} {:is_remote_synced true}
+ {:authority_level "official"} {:type "instance-analytics"}]]
+ (refused (edit-file (tree) collection-path #(merge % change))
+ "must be a root collection that is not remote-synced or archived"))
+ (doseq [change [{:namespace "snippets"} {:namespace nil}]]
+ (refused (edit-file (tree) collection-path #(merge % change))
+ "must be in the data-apps collection namespace")))
+ (testing "a card that belongs to a dashboard or a document"
+ (refused (edit-file (tree) question-path #(assoc % :dashboard_id "someDashboardEntity01"))
+ "must not belong to a dashboard or document")
+ (refused (edit-file (tree) question-path #(assoc % :document_id "someDocumentEntityI01"))
+ "must not belong to a dashboard or document"))
+ (testing "an embedded card"
+ (refused (edit-file (tree) question-path #(assoc % :enable_embedding true))
+ "must not be public or embedded"))
+ (testing "a snippet that the instance doesn't have"
+ (refused (edit-file (tree) question-path
+ #(assoc % :dataset_query
+ {:database (:database (:dataset_query %))
+ :lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/native"
+ :native "SELECT 1 {{snippet: s}}"
+ :template-tags {"snippet: s" {:type "snippet"
+ :name "snippet: s"
+ :display-name "Snippet: s"
+ :id "7f2c2a0e-6c1e-4b53-9d0a-0d5a3a1d1c13"
+ :snippet-name "s"
+ :snippet-id "nowhereSnippetEid0000"}}}]}))
+ "references NativeQuerySnippet nowhereSnippetEid0000, which does not exist on this instance"))
+ (testing "one card defined by two files"
+ (let [resources (question-resources)
+ path (some #(when (str/includes? % question-eid) %) (keys resources))]
+ (refused (shop (assoc resources (str collection-dir "copy.yaml") (get resources path)))
+ "is defined by more than one file")))))
+
+(deftest refuses-an-action-that-takes-its-parameter-values-from-a-card-test
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [action-id]}]
+ (let [resources (data-apps.tu/build-resources
+ collection-name collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [action-id])
+ tree (edit-file (shop resources) action-path
+ #(assoc % :parameters [{:id "name" :slug "name" :type "string/="
+ :values_source_config {:card_id question-eid}}]))]
+ (is (some #(str/includes? % "must not take parameter values from a card") (messages tree)))))))
+
+(deftest refuses-a-reference-by-numeric-id-test
+ (testing "a numeric ID names a row on one instance, and slips past the checks that read entity IDs"
+ (mt/with-temp [:model/Card {other-id :id} {:dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :venues)}}}]
+ (let [refused (fn [f]
+ (is (some #(str/includes? % "numeric ID")
+ (messages (edit-file (shop (question-resources)) question-path f)))))
+ native (fn [tag]
+ #(assoc % :dataset_query {:database (:database (:dataset_query %))
+ :lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/native"
+ :native "SELECT * FROM {{t}}"
+ :template-tags {"t" (merge {:name "t" :display-name "T"
+ :id "7f2c2a0e-6c1e-4b53-9d0a-0d5a3a1d1c12"}
+ tag)}}]}))]
+ (testing "a card"
+ (refused #(update % :dataset_query assoc :stages [{:lib/type "mbql.stage/mbql" :source-card other-id}])))
+ (testing "a table"
+ (refused #(assoc-in % [:dataset_query :stages 0 :source-table] (mt/id :venues))))
+ (testing "a field"
+ (refused #(assoc-in % [:dataset_query :stages 0 :filters] [["=" {} ["field" {} (mt/id :venues :id)] 1]])))
+ (testing "a field in the older form"
+ (refused #(assoc-in % [:dataset_query :stages 0 :filters] [["=" {} ["field" (mt/id :venues :id) nil] 1]])))
+ (testing "a card template tag"
+ (refused (native {:type "card" :card-id other-id})))
+ (testing "a snippet template tag"
+ (refused (native {:type "snippet" :snippet-name "s" :snippet-id 1})))
+ (testing "a table template tag"
+ (refused (native {:type "table" :table-id (mt/id :venues)})))))))
+
+(deftest refuses-more-references-by-numeric-id-test
+ (testing "a card as the source table in the older form, the source field of a field reference, and a database"
+ (mt/with-temp [:model/Card {other-id :id} {:dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :venues)}}}]
+ (let [refused (fn [f]
+ (is (some #(str/includes? % "numeric ID")
+ (messages (edit-file (shop (question-resources)) question-path f)))))]
+ (refused #(assoc-in % [:dataset_query :stages 0 :source-table] (str "card__" other-id)))
+ (refused #(assoc-in % [:dataset_query :stages 0 :fields]
+ [["field" {:source-field (mt/id :venues :category_id)} "NAME"]]))
+ (refused #(assoc-in % [:dataset_query :database] (mt/id)))))))
+
+(deftest refuses-a-change-of-the-apps-collection-test
+ (testing "the app's hooks refuse a change of collection, but only after the load has moved what it reached first"
+ (mt/with-temp [:model/Collection {collection-id :id} {:entity_id collection-eid :name "Mine" :namespace :data-apps}
+ :model/DataApp _ {:name "shop" :display_name "Shop" :bundle_path "index.js"
+ :entity_id (data-apps.tu/app-entity-id "shop")
+ :resource_collection_id collection-id}]
+ (let [other-eid (data-apps.tu/collection-entity-id "other")
+ resources (data-apps.tu/build-resources collection-name other-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [])]
+ (is (some #(str/includes? % "a data app's collection cannot be changed")
+ (messages (shop resources :collection other-eid))))
+ (testing "the collection the app has is fine"
+ (is (= [] (messages (shop (question-resources))))))))))
+
+(deftest refuses-a-manifest-that-doesnt-say-what-it-is-test
+ (testing "a data_app.yaml without serdes/meta would be skipped by the load, and the app deleted as no longer in the
+ repository"
+ (is (some #(str/includes? % "must hold a single DataApp whose serdes/meta ID is its entity_id")
+ (messages (edit-file (shop nil) "data_apps/shop/data_app.yaml" #(dissoc % :serdes/meta)))))))
+
+(deftest refuses-two-manifests-with-one-entity-id-test
+ (testing "a load keeps one app, and the other's collection is left with no owner"
+ (let [tree (merge (shop (question-resources))
+ (data-apps.tu/app-files "shop2" {:name "Shop 2" :path "index.js" :bundle "B"
+ :entity_id (data-apps.tu/app-entity-id "shop")}))]
+ (is (= 2 (count (filter #(str/includes? % "which another data app also has") (messages tree))))))))
+
+(deftest refuses-a-manifest-whose-slug-an-app-made-here-has-test
+ (testing "an app made on the instance keeps its slug, and a load would refuse the repository's app only after its
+ collection and cards had loaded"
+ (mt/with-temp [:model/DataApp _ {:name "shop" :display_name "Shop" :bundle_path "index.js"
+ :entity_id "madeHereAppEntity0001"}]
+ (is (some #(str/includes? % "a data app made on this instance already has")
+ (messages (shop (question-resources))))))))
+
+(deftest refuses-two-manifests-with-one-slug-test
+ (testing "a load keeps the first app and refuses the second after it has started"
+ (let [tree (merge (shop (question-resources))
+ (edit-file (data-apps.tu/app-files "shop2" {:name "Shop 2" :path "index.js" :bundle "B"})
+ "data_apps/shop2/data_app.yaml" #(assoc % :slug "shop")))]
+ (is (= 2 (count (filter #(str/includes? % "has the slug") (messages tree))))))))
+
+(deftest refuses-other-content-in-the-apps-collection-test
+ (testing "a data app's collection holds cards and actions only, and a load would refuse anything else only after it
+ had started"
+ (let [tree (assoc (shop (question-resources))
+ (str collection-dir "launches.yaml")
+ (yaml/generate-string {:name "Launches"
+ :entity_id "shopTimelineLaunches0"
+ :collection_id collection-eid
+ :serdes/meta [{:model "Timeline" :id "shopTimelineLaunches0"}]}))]
+ (is (some #(str/includes? % "holds only questions, metrics and query actions") (messages tree))))))
+
+(deftest accepts-what-a-failed-pull-left-in-the-collection-the-app-claims-test
+ (testing "a card loaded into the app's collection before the app itself failed to load is the app's to claim"
+ (mt/with-temp [:model/Collection {collection-id :id} {:entity_id collection-eid :name "Mine" :namespace :data-apps}
+ :model/Card _ {:name "Left behind" :entity_id question-eid :collection_id collection-id}]
+ (is (= [] (messages (shop (question-resources)))))
+ (testing "but not one in another collection of the namespace"
+ (mt/with-temp [:model/Collection {other-id :id} {:name "Other" :namespace :data-apps}]
+ (t2/update! :model/Card :entity_id question-eid {:collection_id other-id})
+ (is (some #(str/includes? % "already exists outside this data app's collection")
+ (messages (shop (question-resources))))))))))
+
+(deftest refuses-a-table-that-is-inactive-test
+ (testing "an inactive table is one that sync no longer finds, so the app's query would run against nothing"
+ (let [resources (question-resources)]
+ (mt/with-temp-vals-in-db :model/Table (mt/id :venues) {:active false}
+ (is (some #(str/includes? % "references table [") (messages (shop resources))))))))
+
+(deftest warns-of-a-field-that-is-inactive-test
+ (testing "an inactive field is one that sync no longer finds: one column isn't the app, so the file loads and the
+ pull logs the field rather than refusing the repository until the file changes"
+ (let [resources (data-apps.tu/build-resources
+ collection-name collection-eid
+ [{:entity_id question-eid :name "VenuePrices"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :fields [{:type "column" :name "PRICE"}]}]}}]
+ [])
+ warnings (fn [tree] (mapv :message (data-apps/warnings (files tree))))]
+ (mt/with-temp-vals-in-db :model/Field (mt/id :venues :price) {:active false}
+ (is (= [] (messages (shop resources))))
+ (is (some #(str/includes? % "references field") (warnings (shop resources)))))
+ (testing "an active field is nothing to log"
+ (is (= [] (warnings (shop resources))))))))
+
+(deftest refuses-a-collection-inside-the-apps-collection-test
+ (testing "a data app's collection holds no collections, and a load would refuse one only after it had started"
+ (let [inner "innerCollectionEnt01"
+ tree (assoc (shop (question-resources))
+ (str collection-dir "inner.yaml")
+ (yaml/generate-string {:serdes/meta [{:model "Collection" :id inner :label "inner"}]
+ :entity_id inner
+ :name "Inner"
+ :namespace "data-apps"
+ :parent_id collection-eid}))]
+ (is (some #(str/includes? % "is a collection inside a data app's collection") (messages tree))))))
+
+(deftest accepts-the-collection-files-of-an-app-the-commit-no-longer-holds-test
+ (testing "the files of a collection no manifest names, what a deleted app's directory leaves behind, don't fail the
+ pull: it deletes the app, whose hook deletes the collection, and the next export removes the files"
+ (let [tree (dissoc (shop (question-resources)) "data_apps/shop/data_app.yaml" "data_apps/shop/index.js")]
+ (is (= [] (messages tree))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj
index 096e23e51bc..7b91f521dd3 100644
--- a/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj
@@ -25,7 +25,7 @@
(mt/with-temp [:model/Collection {ancestor-id :id} {:name "Filed under" :location "/"}]
(let [app (create-data-app! "wrens")
{:keys [resource_collection_id]} (data-app.resources/ensure-resources! app)]
- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"same namespace as its parent"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"cannot move a data app's collection"
(collection/move-collection!
(t2/select-one :model/Collection :id resource_collection_id)
(collection/children-location (t2/select-one :model/Collection :id ancestor-id)))))
@@ -41,9 +41,11 @@
;; can put the copy there.
(mt/with-test-user :crowberto
(mt/with-temp [:model/Card {card-id :id} {:collection_id resource_collection_id}]
- (collection/archive-or-unarchive-collection!
- (t2/select-one :model/Collection :id resource_collection_id)
- {:archived true})
+ ;; a data app's collection can no longer be trashed, so trash it as an instance from before that rule did
+ (mt/with-dynamic-fn-redefs [perms/data-app-collection? (constantly false)]
+ (collection/archive-or-unarchive-collection!
+ (t2/select-one :model/Collection :id resource_collection_id)
+ {:archived true}))
(is (true? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))
"precondition: the collection is in the trash")
(is (true? (t2/select-one-fn :archived :model/Card :id card-id))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj
index 7730c3238ec..4dace786d2e 100644
--- a/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj
@@ -2,10 +2,12 @@
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
- [metabase-enterprise.data-apps.apps :as data-apps.apps]
[metabase-enterprise.serialization.core :as serialization]
[metabase-enterprise.serialization.test-util :as ts]
[metabase-enterprise.serialization.v2.extract :as extract]
+ [metabase.actions.core :as actions]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.models.serialization :as serdes]
[metabase.test :as mt]
[metabase.util.yaml :as yaml]
@@ -27,7 +29,7 @@
[dir & {:keys [with-collections?]}]
(serialization/store! (if with-collections?
(extract/extract {:targets (mapv (fn [id] ["DataApp" id])
- (t2/select-pks-vec :model/DataApp :draft false))
+ (t2/select-pks-vec :model/DataApp))
:no-settings true
:no-data-model true})
(serdes/extract-all "DataApp" {}))
@@ -78,11 +80,6 @@
(is (= "console.log(1)"
(slurp (io/file dump-dir "data_apps" "sales-ops" "dist" "index.js")))))))))
-(deftest drafts-are-not-exported-test
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (data-apps.apps/ensure-draft! "draft-app")
- (is (empty? (into [] (serdes/extract-all "DataApp" {}))))))
-
(deftest round-trip-test
(mt/with-premium-features #{:data-apps}
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
@@ -102,8 +99,7 @@
:display_name "Sales Ops"
:bundle_path "dist/index.js"
:bundle_hash (:bundle_hash app)
- :allowed_hosts ["https://api.example.com"]
- :draft false}
+ :allowed_hosts ["https://api.example.com"]}
imported))
(is (= "console.log(1)" (bundle-text imported)))
(testing "the import links the collection the manifest names and creates the permission group"
@@ -151,21 +147,6 @@
(is (= "console.log(2)" (bundle-text updated)))
(is (not= (:bundle_hash app) (:bundle_hash updated)))))))))
-(deftest import-takes-over-a-draft-with-the-same-slug-test
- (mt/with-premium-features #{:data-apps}
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
- (ts/with-random-dump-dir [dump-dir "data-app-draft-"]
- (let [draft (data-apps.apps/ensure-draft! "draft-app")
- id (t2/select-one-pk :model/DataApp :name "draft-app")]
- (write-app-files! dump-dir "draft_app" (app-yaml "Ld3cXiYs9n8HP3q3FvC7R" "draft-app")
- {"dist/index.js" "BUNDLE"})
- (import! dump-dir)
- (is (=? {:id id
- :entity_id "Ld3cXiYs9n8HP3q3FvC7R"
- :draft false
- :resource_collection_id (:resource_collection_id draft)}
- (t2/select-one :model/DataApp :name "draft-app"))))))))
-
(deftest import-rejects-invalid-apps-test
(mt/with-premium-features #{:data-apps}
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
@@ -201,13 +182,17 @@
(import! dump-dir)
(is (nil? (t2/select-one-fn :description :model/DataApp :id (:id app)))))))))
-(deftest import-does-not-take-over-an-app-that-is-not-a-draft-test
+(deftest import-does-not-take-over-an-app-made-on-the-instance-test
(mt/with-premium-features #{:data-apps}
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
(ts/with-random-dump-dir [dump-dir "data-app-takeover-"]
(let [app (insert-app!)]
(write-app-files! dump-dir "sales-ops" (app-yaml "Ld3cXiYs9n8HP3q3FvC7R" "sales-ops") {"dist/index.js" "B"})
- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Failed to load" (import! dump-dir)))
+ (let [e (try (import! dump-dir) nil (catch clojure.lang.ExceptionInfo e e))]
+ (is (re-find #"Failed to load" (ex-message e)))
+ (testing "the pull says what to do, rather than failing on the slug's unique index"
+ (is (re-find #"named \"sales-ops\" already exists on this instance"
+ (ex-message (ex-cause e))))))
(is (=? {:entity_id (:entity_id app)} (t2/select-one :model/DataApp :id (:id app)))))))))
(deftest export-includes-data-apps-test
@@ -215,3 +200,34 @@
(let [app (insert-app!)]
(is (some #(= [{:model "DataApp" :id (:entity_id app)}] (map (fn [m] (dissoc m :label)) (:serdes/meta %)))
(into [] (extract/extract {:no-collections true :no-data-model true :no-settings true})))))))
+
+(deftest round-trip-with-resources-test
+ (testing "an app travels with its collection and what that holds, written under collections/data_apps/"
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card :model/Action]
+ (ts/with-random-dump-dir [dump-dir "data-app-resources-"]
+ (let [app (insert-app!)
+ collection-id (:resource_collection_id app)
+ mp (mt/metadata-provider)
+ query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]
+ (mt/with-temp [:model/Card {question-eid :entity_id} {:name "Venues list" :type :question
+ :collection_id collection-id :dataset_query query}]
+ (let [action-id (actions/insert! {:name "Rename venue"
+ :type :query
+ :collection_id collection-id
+ :database_id (mt/id)
+ :dataset_query (lib/native-query mp "UPDATE venues SET name = 'x'")})
+ action-eid (t2/select-one-fn :entity_id :model/Action :id action-id)]
+ (export! dump-dir :with-collections? true)
+ (testing "the files sit under the collection's directory of the data-apps namespace"
+ (doseq [path ["data_app__sales_ops.yaml" "data_app__sales_ops/venues_list.yaml"
+ "data_app__sales_ops/rename_venue.yaml"]]
+ (is (.exists (io/file dump-dir "collections" "data_apps" path)) path)))
+ (t2/delete! :model/DataApp (:id app))
+ (is (not (t2/exists? :model/Card :entity_id question-eid)) "deleting the app deletes its collection's cards")
+ (import! dump-dir)
+ (let [imported (t2/select-one :model/DataApp :entity_id (:entity_id app))
+ collection-id (:resource_collection_id imported)]
+ (is (pos-int? collection-id))
+ (is (= collection-id (t2/select-one-fn :collection_id :model/Card :entity_id question-eid)))
+ (is (= collection-id (t2/select-one-fn :collection_id :model/Action :entity_id action-eid))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj b/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj
new file mode 100644
index 00000000000..f655774e908
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj
@@ -0,0 +1,188 @@
+(ns metabase-enterprise.data-apps.test-util
+ (:require
+ [clojure.string :as str]
+ [metabase-enterprise.serialization.core :as serialization]
+ [metabase-enterprise.serialization.dump :as serialization.dump]
+ [metabase.actions.core :as actions]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.models.serialization :as serdes]
+ [metabase.models.serialization.resolve :as resolve]
+ [metabase.test :as mt]
+ [metabase.util.yaml :as yaml]
+ [toucan2.core :as t2])
+ (:import
+ (java.nio.charset StandardCharsets)
+ (java.security MessageDigest)))
+
+(set! *warn-on-reflection* true)
+
+(defn collection-entity-id
+ "A stable resource collection entity ID for the app in `data_apps/<slug>`."
+ [slug]
+ (subs (str slug "-" (apply str (repeat 21 "c"))) 0 21))
+
+(defn app-entity-id
+ "A stable entity ID for the app in `data_apps/<slug>`."
+ [slug]
+ (subs (str slug "-" (apply str (repeat 21 "a"))) 0 21))
+
+(defn collection-file
+ "The text of the collection file for a data app's collection with `entity-id`, in the data-apps namespace."
+ [entity-id collection-name]
+ (yaml/generate-string {:name collection-name
+ :namespace "data-apps"
+ :entity_id entity-id
+ :serdes/meta [{:model "Collection" :id entity-id :label (serialization/slugify-name collection-name)}]}))
+
+(defn collection-dir
+ "The directory under `collections/data_apps/` that holds what the collection named `collection-name` holds, and the
+ stem of the collection's own file, as serialization writes them."
+ [collection-name]
+ (serialization/slugify-name collection-name))
+
+(defn collection-path
+ "The repo path of the file of the collection named `collection-name`, as serialization writes it."
+ [collection-name]
+ (format "collections/data_apps/%s.yaml" (collection-dir collection-name)))
+
+(defn app-files
+ "Repo files for one data app, as serialization writes them: its `data_app.yaml` under `data_apps/<dir>/` (slug and
+ entity ID from `dir` unless given), a bundle at `path` with `bundle` content, and its `resources`, repo paths to
+ file text (see [[build-resources]]), which default to the file of its collection under `collections/data_apps/`;
+ `:resources nil` makes an app whose collection has no file."
+ [dir {:keys [name path bundle description version allowed_hosts slug entity_id collection resources]
+ :or {slug dir}
+ :as options}]
+ (let [entity-id (or entity_id (app-entity-id dir))
+ collection (if (contains? options :collection) collection (collection-entity-id dir))
+ collection-name (str "Data App: " slug)
+ resources (if (contains? options :resources)
+ resources
+ (when collection {(collection-path collection-name) (collection-file collection collection-name)}))]
+ (merge
+ {(format "data_apps/%s/data_app.yaml" dir)
+ (yaml/generate-string
+ (cond-> {:serdes/meta [{:model "DataApp" :id entity-id :label slug}]
+ :entity_id entity-id
+ :slug slug
+ :name name
+ :path path}
+ collection (assoc :collection collection)
+ description (assoc :description description)
+ version (assoc :version version)
+ (seq allowed_hosts) (assoc :allowed_hosts allowed_hosts)))
+ (format "data_apps/%s/%s" dir path) bundle}
+ resources)))
+
+(defn copy-entity-id
+ "A stable entity ID for the copy of the `kind` entity `source-entity-id` in the app whose collection is
+ `collection-entity-id`."
+ [kind collection-entity-id source-entity-id]
+ (let [^bytes digest (.digest (MessageDigest/getInstance "SHA-256")
+ (.getBytes (str/join "\u0000" [kind collection-entity-id source-entity-id])
+ StandardCharsets/UTF_8))]
+ (apply str (for [i (range 21)]
+ (.charAt "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-" (bit-and (aget digest i) 63))))))
+
+(def ^:private instance-fields
+ {:collection_id nil :collection_position nil :dashboard_id nil :document_id nil :archived false
+ :archived_directly false :public_uuid nil :made_public_by_id nil :enable_embedding false
+ :embedding_params nil :embedding_type nil :creator_id nil :created_at nil})
+
+(defn- question [{:keys [entity_id name]} query]
+ (merge instance-fields
+ {:entity_id entity_id :name name :type :question :display :table :description nil
+ :creator_id (mt/user->id :crowberto)
+ :collection_preview true :card_schema nil :database_id (:database query)
+ :dataset_query (lib/prepare-for-serialization query) :visualization_settings {}
+ :parameters [] :parameter_mappings [] :result_metadata nil :dimensions nil :dimension_mappings nil}))
+
+(defn- action-copy [action entity-id]
+ (merge (select-keys action [:name :description :type :parameters :parameter_mappings :visualization_settings])
+ (select-keys instance-fields [:archived :public_uuid :made_public_by_id :created_at])
+ {:creator_id (mt/user->id :crowberto)}
+ {:query (t2/select :model/QueryAction :action_id (:id action))
+ :implicit (t2/select :model/ImplicitAction :action_id (:id action))}
+ {:entity_id entity-id :model_id nil}))
+
+(defn- collection [entity-id collection-name]
+ {:entity_id entity-id :name collection-name :slug nil :description nil :location "/" :namespace :data-apps :type nil
+ :authority_level nil :archived false :archived_directly false :archive_operation_id nil
+ :is_remote_synced false :is_sample false :personal_owner_id nil :created_at nil})
+
+(defn- copy-overriding-resolver [base card-id->copy-entity-id]
+ (reify resolve/SerdesExportResolver
+ (export-fk [_ id model]
+ (or (when (= "Card" (name model)) (card-id->copy-entity-id id))
+ (resolve/export-fk base id model)))
+ (export-fk-keyed [_ id model field] (resolve/export-fk-keyed base id model field))
+ (export-user [_ id] (resolve/export-user base id))
+ (export-table-fk [_ id] (resolve/export-table-fk base id))
+ (export-field-fk [_ id] (resolve/export-field-fk base id))))
+
+(defn- file-path
+ "The repo path of an entity of the collection named `collection-name`: the collection's own file, or a file in the
+ collection's directory named after the entity, with its entity ID so a test can find it."
+ [collection-name entity]
+ (let [{:keys [model id label]} (last (:serdes/meta entity))]
+ (if (= model "Collection")
+ (collection-path collection-name)
+ (format "collections/data_apps/%s/%s_%s.yaml" (collection-dir collection-name) (serialization/slugify-name label) id))))
+
+(defn build-resources
+ "The files an author commits for the collection named `collection-name` with `collection-entity-id`, keyed by their
+ repo path under `collections/data_apps/`: the collection, a saved question per `{:entity_id :name :query}` in
+ `queries`, and copies of the metrics those use and of the actions with `action-ids`, which belong to no model.
+ Copies get [[copy-entity-id]]s."
+ [collection-name collection-entity-id queries action-ids]
+ (let [resolved (for [{:keys [query] :as spec} queries
+ :let [table-id (get-in query [:stages 0 :source :id])
+ mp (lib-be/application-database-metadata-provider
+ (t2/select-one-fn :db_id :model/Table :id table-id))]]
+ {:spec spec :query (lib/test-query mp query)})
+ metrics (t2/select :model/Card :id [:in (into #{-1} (mapcat (comp lib/all-source-card-ids :query)) resolved)])
+ actions (map #(t2/select-one :model/Action :id %) action-ids)
+ copy-id (fn [kind source] (copy-entity-id kind collection-entity-id (:entity_id source)))
+ copy-ids (into {} (map (juxt :id (partial copy-id "metric"))) metrics)
+ extract (fn [model-name instance]
+ (cond-> (serdes/extract-one model-name {} instance)
+ (not= "Collection" model-name) (assoc :collection_id collection-entity-id)))
+ entities (serdes/with-cache
+ (binding [resolve/*export-resolver* (copy-overriding-resolver resolve/*export-resolver* copy-ids)]
+ (doall
+ (concat
+ [(extract "Collection" (collection collection-entity-id collection-name))]
+ (for [{:keys [spec query]} resolved]
+ (extract "Card" (question spec query)))
+ (for [card metrics]
+ (extract "Card" (merge card instance-fields {:entity_id (copy-ids (:id card))
+ :creator_id (mt/user->id :crowberto)})))
+ (for [action actions]
+ (extract "Action" (action-copy action (copy-id "action" action))))))))]
+ (into (sorted-map) (map (juxt (partial file-path collection-name) serialization.dump/yaml-content)) entities)))
+
+(defn do-with-sources!
+ "Call `f` with the sources a data app copies, a venues metric and a query action that belongs to no model, and with
+ what it can't copy, a venues model and an action on it, as `{:metric-id :action-id :model-id :model-action-id}`."
+ [f]
+ (let [mp (mt/metadata-provider)
+ query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]
+ (mt/with-temp [:model/Card {metric-id :id} {:name "Venue count"
+ :type :metric
+ :database_id (mt/id)
+ :dataset_query (lib/aggregate query (lib/count))}
+ :model/Card {model-id :id} {:name "Venues model"
+ :type :model
+ :database_id (mt/id)
+ :dataset_query query}]
+ (f {:metric-id metric-id
+ :action-id (actions/insert! {:name "Rename venue"
+ :type :query
+ :database_id (mt/id)
+ :dataset_query (lib/native-query mp "UPDATE venues SET name = {{name}}")
+ :parameters [{:id "name" :slug "name" :type :string/=}]})
+ :model-id model-id
+ :model-action-id (actions/insert! {:name "Create venue" :type :implicit :kind :row/create
+ :model_id model-id})}))))
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.clj
index 42e2fd494e8..7228c2938ef 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
@@ -1,12 +1,22 @@
(ns metabase-enterprise.remote-sync.data-apps-test
"Data apps are serdes entities: remote sync imports and exports them like any other, with each app's bundle as a
- resource file next to its `data_app.yaml`."
+ resource file next to its `data_app.yaml`, and its collection under `collections/data_apps/` like any collection
+ of a namespace."
(:require
+ [clojure.string :as str]
[clojure.test :refer :all]
+ [metabase-enterprise.data-apps.core :as data-apps]
+ [metabase-enterprise.data-apps.test-util :as data-apps.tu]
[metabase-enterprise.remote-sync.impl :as impl]
+ [metabase-enterprise.remote-sync.models.remote-sync-object :as remote-sync.object]
[metabase-enterprise.remote-sync.models.remote-sync-task :as remote-sync.task]
[metabase-enterprise.remote-sync.source.protocol :as source.p]
[metabase-enterprise.remote-sync.test-helpers :as test-helpers]
+ [metabase.actions.core :as actions]
+ [metabase.collections.models.collection :as collection]
+ [metabase.driver :as driver]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.search.test-util :as search.tu]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -21,15 +31,15 @@
(def ^:private sales-eid "w8YkMQBwU4kOD0-pZ1nJk")
(defn- app-tree
- "Repo files for the data app `slug` with entity id `eid`: its `data_app.yaml` and its bundle at `dist/index.js`."
+ "Repo files for the data app `slug` with entity id `eid`: its `data_app.yaml`, its bundle at `dist/index.js`, and
+ its collection's file under `collections/data_apps/`."
[eid slug bundle]
- {(str "data_apps/" slug "/data_app.yaml")
- (yaml/generate-string {:serdes/meta [{:model "DataApp" :id eid :label slug}]
- :entity_id eid
- :slug slug
- :name "Sales"
- :path "dist/index.js"})
- (str "data_apps/" slug "/dist/index.js") bundle})
+ (data-apps.tu/app-files slug {:name "Sales" :path "dist/index.js" :bundle bundle :entity_id eid}))
+
+(defn- app-files-in
+ "The files of `repo` that serialization writes for data apps: under `data_apps/` and `collections/data_apps/`."
+ [repo]
+ (into #{} (filter #(re-find #"^(data_apps|collections/data_apps)/" %)) (keys repo)))
(defn- new-task! [sync-task-type]
(t2/insert-returning-pk! :model/RemoteSyncTask {:sync_task_type sync-task-type :initiated_by (mt/user->id :rasta)}))
@@ -60,7 +70,8 @@
`(search.tu/with-index-disabled
(mt/with-premium-features #{:data-apps}
(mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-enabled true remote-sync-transforms false]
- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
+ ;; the cleanup deletes without hooks, so what a pull loads into an app's collection is listed too
+ (mt/with-model-cleanup [:model/DataApp :model/Action :model/Card :model/Collection :model/PermissionsGroup]
~@body)))))
(deftest pull-imports-and-prunes-data-apps-test
@@ -68,17 +79,19 @@
(let [src (test-helpers/versioned-source :trees {"v0" (app-tree sales-eid "sales" "BUNDLE-V1")
"v1" {"README.md" "x"}}
:current "v0")]
- (testing "a pull imports the app and its bundle"
- (is (=? {:status :success :outcome {:kind "pulled" :count 1}} (import-at! src "v0" :force? true)))
- (is (=? {:entity_id sales-eid :display_name "Sales" :draft false :resource_collection_id pos-int?}
+ (testing "a pull imports the app, its collection and its bundle"
+ (is (=? {:status :success :outcome {:kind "pulled" :count 2}} (import-at! src "v0" :force? true)))
+ (is (=? {:entity_id sales-eid :display_name "Sales" :resource_collection_id pos-int?}
(t2/select-one :model/DataApp :name "sales")))
(is (= "BUNDLE-V1" (bundle-text "sales"))))
- (testing "a pull whose repo no longer has the app removes it"
- (is (= :success (:status (import-at! src "v1"))))
- (is (not (t2/exists? :model/DataApp :name "sales")))))))
+ (testing "a pull whose repo no longer has the app's files removes it, and the hook removes its collection"
+ (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :name "sales")]
+ (is (= :success (:status (import-at! src "v1"))))
+ (is (not (t2/exists? :model/DataApp :name "sales")))
+ (is (not (t2/exists? :model/Collection :id collection-id))))))))
(deftest bundle-only-pull-updates-the-bundle-test
- (testing "a pull that changes only an app's bundle file falls back to a full import, so the new bundle lands"
+ (testing "a pull that changes only an app's bundle file lands the new bundle"
(with-data-apps-sync
(let [src (test-helpers/versioned-source :trees {"v0" (app-tree sales-eid "sales" "BUNDLE-V1")
"v1" (app-tree sales-eid "sales" "BUNDLE-V2")}
@@ -96,11 +109,13 @@
:display_name "Sales"
:bundle_path "dist/index.js"
:bundle "BUNDLE"})
- (testing "a created app is exported as its manifest and its bundle file"
+ (testing "a created app is exported as its manifest, its bundle file, and its collection's file"
(is (= :success (:status (export! mock))))
- (is (=? {:slug "sales" :name "Sales" :path "dist/index.js"}
+ (is (=? {:slug "sales" :name "Sales" :path "dist/index.js" :collection string?}
(yaml/parse-string (get (repo) "data_apps/sales/data_app.yaml"))))
- (is (= "BUNDLE" (get (repo) "data_apps/sales/dist/index.js"))))
+ (is (= "BUNDLE" (get (repo) "data_apps/sales/dist/index.js")))
+ (is (=? {:name "Data App: sales" :namespace "data-apps"}
+ (yaml/parse-string (get (repo) "collections/data_apps/data_app__sales.yaml")))))
(testing "an updated bundle is exported"
(mt/user-http-request :crowberto :put 200 "apps/sales" {:bundle "BUNDLE-V2"})
(is (= :success (:status (export! mock))))
@@ -112,8 +127,8 @@
:bundle "OPS"})
(mt/user-http-request :crowberto :delete 204 "apps/sales")
(is (= :success (:status (export! mock))))
- (is (= #{"data_apps/ops/data_app.yaml" "data_apps/ops/app.js"}
- (into #{} (filter #(re-find #"^data_apps/" %)) (keys (repo)))))))))
+ (is (= #{"data_apps/ops/data_app.yaml" "data_apps/ops/app.js" "collections/data_apps/data_app__ops.yaml"}
+ (app-files-in (repo))))))))
(deftest export-keeps-files-serialization-does-not-own-test
(testing "an export rewrites an app's manifest and bundle but leaves the app's source next to them alone"
@@ -137,8 +152,9 @@
(testing "deleting the app removes only the files serialization owns"
(mt/user-http-request :crowberto :delete 204 "apps/sales")
(is (= :success (:status (export! mock))))
- (is (= (into #{"data_apps/ops/data_app.yaml" "data_apps/ops/app.js"} (keys source))
- (into #{} (filter #(re-find #"^data_apps/" %)) (keys (repo))))))))))
+ (is (= (into #{"data_apps/ops/data_app.yaml" "data_apps/ops/app.js" "collections/data_apps/data_app__ops.yaml"}
+ (keys source))
+ (app-files-in (repo)))))))))
(deftest pull-refuses-to-delete-an-unpushed-app-test
(testing "a pull whose repo lacks an app created here but not pushed yet is a conflict, not a silent delete"
@@ -152,3 +168,835 @@
:bundle "OPS"})
(is (=? {:status :conflict} (import-at! src "v1")))
(is (t2/exists? :model/DataApp :name "ops"))))))
+
+;;; ------------------------------------------------- Resources -------------------------------------------------
+
+(def ^:private shop-collection-eid (data-apps.tu/collection-entity-id "shop"))
+
+(def ^:private question-eid "shopQuestionListVenue")
+
+(defn- venues-query []
+ {:stages [{:source {:type "table" :id (mt/id :venues)} :limit 5}]})
+
+(def ^:private shop-collection-name "Data App: shop")
+
+(def ^:private shop-collection-dir
+ (str "collections/data_apps/" (data-apps.tu/collection-dir shop-collection-name) "/"))
+
+(defn- shop-tree
+ "The repo files of the `shop` app with `resources` (see `data-apps.tu/build-resources`), the resources under
+ `collections/data_apps/data_app__shop/`."
+ [resources]
+ (data-apps.tu/app-files "shop" {:name "Shop" :path "index.js" :bundle "B"
+ :collection shop-collection-eid :resources resources}))
+
+(defn- shop-collection-id []
+ (t2/select-one-fn :resource_collection_id :model/DataApp :name "shop"))
+
+(deftest pull-loads-an-apps-resources-test
+ (testing "a pull loads an app's resource files as the entities they are, into the collection the manifest names"
+ (with-data-apps-sync
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [metric-id action-id]}]
+ (let [resources (data-apps.tu/build-resources
+ shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}
+ {:entity_id "shopQuestionMetricVen" :name "VenueCount"
+ :query {:stages [{:source {:type "table" :id (mt/id :venues)}
+ :aggregations [{:type "metric" :id metric-id}]}]}}]
+ [action-id])
+ src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)} :current "v0")
+ copy-eid (fn [kind source-model source-id]
+ (data-apps.tu/copy-entity-id kind shop-collection-eid (t2/select-one-fn :entity_id source-model :id source-id)))]
+ (let [result (import-at! src "v0" :force? true)]
+ (is (= :success (:status result)) (:message result)))
+ (let [collection-id (shop-collection-id)]
+ (testing "the app is linked to the collection the files define"
+ (is (= collection-id (t2/select-one-pk :model/Collection :entity_id shop-collection-eid))))
+ (testing "each query is a saved question in the collection"
+ (is (=? {:type :question :name "VenuesList" :collection_id collection-id}
+ (t2/select-one :model/Card :entity_id question-eid))))
+ (testing "the metric a query uses is copied"
+ (is (=? {:type :metric :collection_id collection-id}
+ (t2/select-one :model/Card :entity_id (copy-eid "metric" :model/Card metric-id)))))
+ (testing "the action is copied into the collection, on no model"
+ (is (=? {:type :query :collection_id collection-id :model_id nil}
+ (t2/select-one :model/Action :entity_id (copy-eid "action" :model/Action action-id)))))
+ (testing "the source is untouched"
+ (is (nil? (t2/select-one-fn :collection_id :model/Action :id action-id))))
+ (testing "the app records the tables its resources read"
+ (is (= [(mt/id :venues)] (t2/select-one-fn :table_ids :model/DataApp :name "shop")))))))))))
+
+(deftest pull-updates-and-removes-resources-with-their-files-test
+ (with-data-apps-sync
+ (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}
+ {:entity_id "shopQuestionOther0001" :name "Other" :query (venues-query)}]
+ [])
+ file-of (fn [eid] (some #(when (str/includes? % eid) %) (keys resources)))
+ renamed (update resources (file-of question-eid) #(yaml/generate-string (assoc (yaml/parse-string %) :name "Renamed")))
+ src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)
+ "v1" (shop-tree renamed)
+ "v2" (shop-tree (dissoc renamed (file-of "shopQuestionOther0001")))}
+ :current "v0")]
+ (let [result (import-at! src "v0" :force? true)]
+ (is (= :success (:status result)) (:message result)))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)]
+ (testing "a changed file updates the card in place"
+ (is (= :success (:status (import-at! src "v1"))))
+ (is (= "Renamed" (t2/select-one-fn :name :model/Card :id card-id))))
+ (testing "a card whose file is gone is removed"
+ (is (= :success (:status (import-at! src "v2"))))
+ (is (t2/exists? :model/Card :id card-id))
+ (is (not (t2/exists? :model/Card :entity_id "shopQuestionOther0001"))))))))
+
+(deftest pull-refuses-resources-an-app-may-not-hold-test
+ (testing "a resource file a load can't take as meant fails the pull, naming the file, before anything loads"
+ (with-data-apps-sync
+ (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [])
+ card-file (some #(when (str/includes? % question-eid) %) (keys resources))
+ archived (update resources card-file #(yaml/generate-string (assoc (yaml/parse-string %) :archived true)))
+ src (test-helpers/versioned-source :trees {"v0" (shop-tree archived)} :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :error (:status result)))
+ (is (str/includes? (:message result) card-file))
+ (testing "nothing loaded"
+ (is (not (t2/exists? :model/DataApp :name "shop")))
+ (is (not (t2/exists? :model/Collection :entity_id shop-collection-eid)))
+ (is (not (t2/exists? :model/Card :entity_id question-eid))))))))
+
+(deftest pull-refuses-to-take-over-a-card-elsewhere-test
+ (testing "a file naming the entity ID of a card outside the app can't move it into the app's collection"
+ (with-data-apps-sync
+ (mt/with-temp [:model/Card {foreign-id :id} {:name "Someone else's" :entity_id question-eid}]
+ (let [src (test-helpers/versioned-source
+ :trees {"v0" (shop-tree (data-apps.tu/build-resources shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ []))}
+ :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :error (:status result)))
+ (is (str/includes? (:message result) shop-collection-dir))
+ (is (= "Someone else's" (t2/select-one-fn :name :model/Card :id foreign-id))))))))
+
+(deftest export-writes-an-apps-resources-under-its-collection-test
+ (testing "what an app's collection holds is exported under collections/data_apps/, like any namespace's content"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" {}})
+ repo #(get @(:files-atom mock) "main")]
+ (mt/user-http-request :crowberto :post 200 "apps" {:name "sales"
+ :display_name "Sales"
+ :bundle_path "dist/index.js"
+ :bundle "BUNDLE"})
+ (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :name "sales")
+ mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card _ {:name "Venues list"
+ :type :question
+ :collection_id collection-id
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}]
+ (actions/insert! {:name "Rename venue"
+ :type :query
+ :collection_id collection-id
+ :database_id (mt/id)
+ :dataset_query (lib/native-query mp "UPDATE venues SET name = 'x'")})
+ (is (= :success (:status (export! mock))))
+ (is (= #{"data_apps/sales/data_app.yaml"
+ "data_apps/sales/dist/index.js"
+ "collections/data_apps/data_app__sales.yaml"
+ "collections/data_apps/data_app__sales/venues_list.yaml"
+ "collections/data_apps/data_app__sales/rename_venue.yaml"}
+ (app-files-in (repo))))
+ (is (empty? (filter #(re-find #"^(collections/main|actions)/" %) (keys (repo))))
+ "nothing of the app's lands in the default namespace's directories")))))))
+
+(defn- question-resources []
+ (data-apps.tu/build-resources shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ []))
+
+(defn- resource-files
+ "The files of data apps' collections in `mock`'s repository."
+ [mock]
+ (into #{} (filter #(re-find #"^collections/data_apps/" %)) (keys (get @(:files-atom mock) "main"))))
+
+(defn- file-named
+ "Whether a file of `mock`'s repository under `collections/data_apps/` has a name starting with `stem`."
+ [mock stem]
+ (some #(str/starts-with? (last (str/split % #"/")) stem) (resource-files mock)))
+
+(deftest export-keeps-the-file-of-a-resource-edited-here-test
+ (testing "a card and an action edited in Metabase are exported as changed, not removed from the repository"
+ (with-data-apps-sync
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [action-id]}]
+ (let [resources (data-apps.tu/build-resources
+ shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [action-id])
+ mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree resources)})]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)
+ copy-id (t2/select-one-pk :model/Action :collection_id (shop-collection-id))]
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:description "edited here"})
+ (mt/with-actions-enabled
+ (mt/user-http-request :crowberto :put 200 (str "action/" copy-id) {:name "Renamed venue"}))
+ (is (= :success (:status (export! mock))))
+ (is (file-named mock "venueslist"))
+ (is (file-named mock "renamed_venue"))
+ (is (some #(str/includes? (get-in @(:files-atom mock) ["main" %]) "edited here") (resource-files mock)))
+ (testing "and a pull of what was exported keeps both"
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (is (t2/exists? :model/Card :id card-id))
+ (is (t2/exists? :model/Action :id copy-id))))))))))
+
+(deftest a-read-only-instance-refuses-an-edit-to-a-resource-test
+ (testing "with remote sync read-only, a card in an app's collection can't be edited here, like any synced card"
+ (with-data-apps-sync
+ (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)]
+ (testing "without remote sync the card is not synced, so it can be edited"
+ (mt/with-temporary-setting-values [remote-sync-type :read-only remote-sync-url nil]
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:description "edited without sync"})))
+ (mt/with-temporary-setting-values [remote-sync-type :read-only remote-sync-url "https://example.com/repo.git"]
+ (mt/user-http-request :crowberto :put 403 (str "card/" card-id) {:description "edited here"})
+ (testing "and the instance still pulls"
+ (is (= :success (:status (import-at! src "v0" :force? true)))))))))))
+
+(deftest an-apps-collection-holds-only-what-a-pull-accepts-test
+ (testing "what the resource validator would refuse on a pull can't be saved into an app's collection"
+ (with-data-apps-sync
+ (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")
+ mp (mt/metadata-provider)
+ q (lib/->legacy-MBQL (lib/query mp (lib.metadata/table mp (mt/id :venues))))]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (let [collection-id (shop-collection-id)
+ card (fn [status card-type]
+ (mt/user-http-request :crowberto :post status "card"
+ {:name "Saved here" :type card-type :display "table"
+ :visualization_settings {} :collection_id collection-id
+ :dataset_query q}))]
+ (mt/user-http-request :crowberto :post 400 "dashboard" {:name "Saved here" :collection_id collection-id})
+ (is (not (t2/exists? :model/Dashboard :name "Saved here")))
+ (is (= "A data app's collection can hold only questions, metrics, and query actions"
+ (mt/user-http-request :crowberto :post 400 "collection" {:name "Inside" :parent_id collection-id :namespace "data-apps"})))
+ (is (not (t2/exists? :model/Collection :name "Inside")))
+ (card 400 "model")
+ (is (not (t2/exists? :model/Card :collection_id collection-id :type :model)))
+ (is (=? {:collection_id collection-id :type :question}
+ (t2/select-one :model/Card :id (:id (card 200 "question")))))
+ (testing "a bookmark is not content"
+ (mt/user-http-request :crowberto :post 200 (str "bookmark/collection/" collection-id)))
+ (testing "with the library feature too, whose check runs in the same place"
+ (mt/with-additional-premium-features #{:library}
+ (card 400 "model")))
+ (testing "a question a load checks as a possible dashboard question, before its dashboard is known, is a question here"
+ (is (= (collection/check-allowed-content :question collection-id)
+ (collection/check-allowed-content :dashboard-question collection-id))))
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Elsewhere"}]
+ (mt/user-http-request :crowberto :put 400 (str "dashboard/" dashboard-id) {:collection_id collection-id})
+ (is (nil? (t2/select-one-fn :collection_id :model/Dashboard :id dashboard-id)))))))))
+
+(deftest a-card-in-an-apps-collection-stays-what-a-pull-accepts-test
+ (testing "a card there can't become what the resource validator refuses, since the next export would write it"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})
+ mp (mt/metadata-provider)
+ q (lib/->legacy-MBQL (lib/query mp (lib.metadata/table mp (mt/id :venues))))]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)
+ collection-id (shop-collection-id)]
+ (testing "archived, public, or a model"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/user-http-request :crowberto :post 400 (str "card/" card-id "/public_link")))
+ (mt/user-http-request :crowberto :put 400 (str "card/" card-id) {:archived true})
+ (mt/user-http-request :crowberto :put 400 (str "card/" card-id) {:type "model"})
+ (is (=? {:archived false :public_uuid nil :type :question} (t2/select-one :model/Card :id card-id))))
+ (testing "a card that is already public can't be moved in"
+ (mt/with-temp [:model/Card {public-id :id} {:name "Already public"
+ :dataset_query q
+ :public_uuid (str (random-uuid))
+ :made_public_by_id (mt/user->id :crowberto)}]
+ (mt/user-http-request :crowberto :put 400 (str "card/" public-id) {:collection_id collection-id})
+ (is (nil? (t2/select-one-fn :collection_id :model/Card :id public-id)))))
+ (testing "it can still be edited, and the export keeps its file"
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:description "still editable"})
+ (is (= :success (:status (export! mock))))
+ (is (file-named mock "venueslist"))
+ (is (= :success (:status (import-at! mock "main" :force? true)))))
+ (testing "a card anywhere else still can be archived"
+ (mt/with-temp [:model/Card {other-id :id} {:name "Elsewhere"}]
+ (mt/user-http-request :crowberto :put 200 (str "card/" other-id) {:archived true}))))))))
+
+(deftest a-card-another-app-card-reads-stays-in-the-apps-collection-test
+ (testing "a card that another card of the app reads can't leave the collection or be deleted: the export would write
+ the reader into a file every pull refuses"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})
+ mp (mt/metadata-provider)
+ venues-q (lib/->legacy-MBQL (lib/query mp (lib.metadata/table mp (mt/id :venues))))]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)
+ collection-id (shop-collection-id)
+ reads-card (fn [id] (lib/->legacy-MBQL (lib/query mp (lib.metadata/card mp id))))
+ reader-id (:id (mt/user-http-request :crowberto :post 200 "card"
+ {:name "Reads VenuesList"
+ :display "table"
+ :visualization_settings {}
+ :collection_id collection-id
+ :dataset_query (reads-card card-id)}))]
+ (testing "the card it reads can't be moved out"
+ (mt/user-http-request :crowberto :put 400 (str "card/" card-id) {:collection_id nil})
+ (is (= collection-id (t2/select-one-fn :collection_id :model/Card :id card-id))))
+ (testing "nor as a dashboard question, which a card other cards read can't become"
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Elsewhere"}]
+ (mt/user-http-request :crowberto :put 400 (str "card/" card-id) {:dashboard_id dashboard-id})
+ (is (= collection-id (t2/select-one-fn :collection_id :model/Card :id card-id)))))
+ (testing "or deleted"
+ (mt/user-http-request :crowberto :delete 400 (str "card/" card-id))
+ (is (t2/exists? :model/Card :id card-id)))
+ (testing "one request that moves a card in and changes its query from a card outside to a table is fine"
+ (mt/with-temp [:model/Card {outside-id :id} {:name "Outside" :dataset_query venues-q}
+ :model/Card {mover-id :id} {:name "Mover" :dataset_query (reads-card outside-id)}]
+ (mt/user-http-request :crowberto :put 200 (str "card/" mover-id)
+ {:collection_id collection-id :dataset_query venues-q})
+ (is (= collection-id (t2/select-one-fn :collection_id :model/Card :id mover-id)))))
+ (testing "once the reader has left, the card can leave too"
+ (mt/user-http-request :crowberto :put 200 (str "card/" reader-id) {:collection_id nil})
+ (is (nil? (t2/select-one-fn :collection_id :model/Card :id reader-id)))
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:collection_id nil})
+ (is (nil? (t2/select-one-fn :collection_id :model/Card :id card-id)))))))))
+
+(deftest deleting-an-app-deletes-cards-that-read-each-other-test
+ (testing "the refusal to delete a card another app card reads is the endpoint's: deleting the app deletes its
+ collection with every card in it, readers and read"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})
+ mp (mt/metadata-provider)]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)
+ collection-id (shop-collection-id)
+ reader-id (:id (mt/user-http-request :crowberto :post 200 "card"
+ {:name "Reads VenuesList"
+ :display "table"
+ :visualization_settings {}
+ :collection_id collection-id
+ :dataset_query (lib/->legacy-MBQL (lib/query mp (lib.metadata/card mp card-id)))}))]
+ (mt/user-http-request :crowberto :delete 204 "apps/shop")
+ (is (not (t2/exists? :model/Collection :id collection-id)))
+ (is (not (t2/exists? :model/Card :id [:in [card-id reader-id]]))))))))
+
+(deftest a-pull-of-the-commit-already-imported-is-skipped-test
+ (testing "a pull that would load nothing isn't failed by the state of the instance"
+ (with-data-apps-sync
+ (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (t2/update! :model/Card :entity_id question-eid {:collection_id nil})
+ (is (=? {:status :success :outcome {:kind "pull-skipped"}} (import-at! src "v0")))
+ (testing "a pull that would load is still refused"
+ (is (= :error (:status (import-at! src "v0" :force? true)))))))))
+
+(deftest pull-refuses-two-apps-that-name-one-collection-test
+ (with-data-apps-sync
+ (let [shared (data-apps.tu/collection-entity-id "shared")
+ app (fn [slug] (data-apps.tu/app-files slug {:name slug :path "index.js" :bundle "B" :collection shared}))
+ src (test-helpers/versioned-source :trees {"v0" (merge (app "first") (app "second"))} :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :error (:status result)))
+ (is (str/includes? (:message result) "data_apps/first/data_app.yaml"))
+ (is (str/includes? (:message result) "data_apps/second/data_app.yaml"))
+ (testing "nothing loaded"
+ (is (not (t2/exists? :model/DataApp :name [:in ["first" "second"]])))
+ (is (not (t2/exists? :model/Collection :entity_id shared)))))))
+
+(deftest pull-refuses-two-apps-that-define-one-card-test
+ (with-data-apps-sync
+ (let [app (fn [slug]
+ (let [collection (data-apps.tu/collection-entity-id slug)]
+ (data-apps.tu/app-files slug {:name slug :path "index.js" :bundle "B" :collection collection
+ :resources (data-apps.tu/build-resources
+ (str "Data App: " slug) collection
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [])})))
+ src (test-helpers/versioned-source :trees {"v0" (merge (app "first") (app "second"))} :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :error (:status result)))
+ (is (str/includes? (:message result) "collections/data_apps/data_app__first/"))
+ (is (str/includes? (:message result) "collections/data_apps/data_app__second/"))
+ (testing "nothing loaded"
+ (is (not (t2/exists? :model/Card :entity_id question-eid)))
+ (is (not (t2/exists? :model/DataApp :name [:in ["first" "second"]])))
+ (is (not (t2/exists? :model/Collection :entity_id [:in (map data-apps.tu/collection-entity-id ["first" "second"])])))))))
+
+;; a driver that can't name the tables of a native query: `driver/native-query-table-refs` has no method for it
+(driver/register! ::no-table-refs :abstract? true)
+
+(deftest pull-survives-a-query-whose-tables-cant-be-read-test
+ (testing "a native query on a driver that can't name its tables doesn't fail the pull; the app records the rest"
+ (with-data-apps-sync
+ (mt/with-temp [:model/Database _ {:engine ::no-table-refs :name "no-table-refs"}]
+ (let [resources (data-apps.tu/build-resources
+ shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}
+ {:entity_id "shopQuestionNative000" :name "Native" :query (venues-query)}]
+ [])
+ path (some #(when (str/includes? % "shopQuestionNative000") %) (keys resources))
+ native (assoc (yaml/parse-string (get resources path))
+ :database_id "no-table-refs"
+ :dataset_query {:database "no-table-refs"
+ :lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/native" :native "{\"find\": \"orders\"}"}]})
+ src (test-helpers/versioned-source
+ :trees {"v0" (shop-tree (assoc resources path (yaml/generate-string native)))}
+ :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :success (:status result)) (:message result))
+ (is (= "v0" (remote-sync.task/last-version)))
+ (is (= [(mt/id :venues)] (t2/select-one-fn :table_ids :model/DataApp :name "shop"))))))))
+
+(deftest pull-refuses-a-manifest-that-names-a-collection-it-doesnt-define-test
+ (testing "a manifest with no resource files can't claim a collection that is already here"
+ (with-data-apps-sync
+ (mt/with-temp [:model/Collection {collection-id :id, collection-eid :entity_id} {:name "Finance"}
+ :model/Card {card-id :id} {:name "Finance card" :collection_id collection-id}]
+ (let [src (test-helpers/versioned-source
+ :trees {"v0" (data-apps.tu/app-files "shop" {:name "Shop" :path "index.js" :bundle "B"
+ :collection collection-eid :resources nil})}
+ :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :error (:status result)))
+ (is (str/includes? (:message result) "data_apps/shop/data_app.yaml"))
+ (is (t2/exists? :model/Collection :id collection-id))
+ (is (t2/exists? :model/Card :id card-id)))))))
+
+(deftest pull-refuses-a-manifest-that-doesnt-parse-test
+ (testing "a data_app.yaml that holds no map can't say which app it is, so the pull refuses it naming the manifest,
+ rather than deleting the app as no longer in the repository"
+ (with-data-apps-sync
+ (let [v0 (shop-tree (question-resources))
+ src (test-helpers/versioned-source :trees {"v0" v0
+ "empty" (assoc v0 "data_apps/shop/data_app.yaml" "")
+ "list" (assoc v0 "data_apps/shop/data_app.yaml" "- a\n")
+ "text" (assoc v0 "data_apps/shop/data_app.yaml" "shop\n")}
+ :current "v0")]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (doseq [version ["empty" "list" "text"]]
+ (testing version
+ (let [result (import-at! src version)]
+ (is (= :error (:status result)))
+ (is (str/includes? (str (:message result)) "data_apps/shop/data_app.yaml must hold a single DataApp")
+ (:message result))
+ (is (t2/exists? :model/DataApp :name "shop")))))))))
+
+(defn- export-merged!
+ "Export to `src` with `merge`, as an instance whose last sync was `base-version` does once the remote has advanced."
+ [src base-version]
+ (t2/delete! :model/RemoteSyncTask :sync_task_type "export")
+ (let [task (new-task! "export")
+ result (impl/export! (source.p/snapshot src) task "export"
+ :merge? true :source src :base-snapshot (source.p/snapshot-at src base-version))]
+ (impl/handle-task-result! result task)
+ result))
+
+(deftest an-export-that-merges-checks-and-records-like-a-pull-test
+ (with-data-apps-sync
+ (testing "a remote file that a pull refuses is refused by an export that merges it in"
+ (mt/with-temp [:model/Collection {elsewhere :id} {:name "Elsewhere"}
+ :model/Card {foreign-id :id} {:name "Someone else's" :entity_id "foreignCardEntityId00"
+ :collection_id elsewhere}]
+ (let [remote (data-apps.tu/build-resources
+ shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}
+ {:entity_id "foreignCardEntityId00" :name "Taken" :query (venues-query)}]
+ [])
+ src (test-helpers/versioned-source
+ :trees {"v0" (shop-tree (question-resources)) "v1" (shop-tree remote)}
+ :current "v1")]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (is (= :error (:status (export-merged! src "v0"))))
+ (is (=? {:name "Someone else's" :collection_id elsewhere}
+ (t2/select-one :model/Card :id foreign-id))))))))
+
+(deftest an-export-that-merges-records-the-tables-test
+ (with-data-apps-sync
+ (let [remote (data-apps.tu/build-resources
+ shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}
+ {:entity_id "shopQuestionCheckins0" :name "Checkins"
+ :query {:stages [{:source {:type "table" :id (mt/id :checkins)} :limit 5}]}}]
+ [])
+ src (test-helpers/versioned-source
+ :trees {"v0" (shop-tree (question-resources)) "v1" (shop-tree remote)}
+ :current "v1")]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (is (= :success (:status (export-merged! src "v0"))))
+ (is (= (sort [(mt/id :venues) (mt/id :checkins)])
+ (t2/select-one-fn :table_ids :model/DataApp :name "shop"))))))
+
+(deftest pull-loads-a-snippet-with-the-card-that-uses-it-test
+ (testing "a resource may use a snippet that the same pull brings"
+ (with-data-apps-sync
+ (mt/with-model-cleanup [:model/NativeQuerySnippet]
+ (let [snippet-eid "appSnippetEntityId000"
+ resources (question-resources)
+ path (some #(when (str/includes? % question-eid) %) (keys resources))
+ parsed (yaml/parse-string (get resources path))
+ native (assoc parsed :dataset_query
+ {:database (:database (:dataset_query parsed))
+ :lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/native"
+ :native "SELECT * FROM venues {{snippet: Remote Snippet}}"
+ :template-tags {"snippet: Remote Snippet"
+ {:type "snippet"
+ :name "snippet: Remote Snippet"
+ :id "7f2c2a0e-6c1e-4b53-9d0a-0d5a3a1d1c11"
+ :display-name "Snippet: Remote Snippet"
+ :snippet-name "Remote Snippet"
+ :snippet-id snippet-eid}}}]})
+ tree (merge (shop-tree (assoc resources path (yaml/generate-string native)))
+ {"snippets/remote_snippet.yaml"
+ (test-helpers/generate-snippet-yaml snippet-eid "Remote Snippet" "WHERE 1 = 1")})
+ src (test-helpers/versioned-source :trees {"v0" tree} :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :success (:status result)) (:message result))
+ (is (t2/exists? :model/NativeQuerySnippet :entity_id snippet-eid))
+ (is (=? {:query_type :native} (t2/select-one :model/Card :entity_id question-eid)))
+ (testing "a snippet that nothing defines is still refused"
+ (let [src (test-helpers/versioned-source
+ :trees {"v0" (shop-tree (assoc resources path
+ (yaml/generate-string
+ (assoc-in native [:dataset_query :stages 0 :template-tags
+ "snippet: Remote Snippet" :snippet-id]
+ "nowhereSnippetEid0000"))))}
+ :current "v0")]
+ (is (= :error (:status (import-at! src "v0" :force? true)))))))))))
+
+(deftest pull-records-the-table-a-native-query-names-test
+ (testing "a native query's table is matched by name whatever its case"
+ (with-data-apps-sync
+ (let [resources (question-resources)
+ path (some #(when (str/includes? % question-eid) %) (keys resources))
+ parsed (yaml/parse-string (get resources path))
+ native (assoc parsed :dataset_query {:database (:database (:dataset_query parsed))
+ :lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/native"
+ :native "select * from Venues"}]})
+ src (test-helpers/versioned-source
+ :trees {"v0" (shop-tree (assoc resources path (yaml/generate-string native)))}
+ :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :success (:status result)) (:message result))
+ (is (= [(mt/id :venues)] (t2/select-one-fn :table_ids :model/DataApp :name "shop")))))))
+
+(deftest an-apps-collection-cant-be-moved-to-the-trash-test
+ (testing "trashing it would drop the app's resource files on the next export"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [before (resource-files mock)]
+ (mt/user-http-request :crowberto :put 400 (str "collection/" (shop-collection-id)) {:archived true})
+ (is (= :success (:status (export! mock))))
+ (is (= before (resource-files mock)))
+ (testing "deleting the app still deletes its collection"
+ (let [collection-id (shop-collection-id)]
+ (mt/user-http-request :crowberto :delete 204 "apps/shop")
+ (is (not (t2/exists? :model/Collection :id collection-id))))))))))
+
+(deftest pull-records-the-table-a-query-action-names-test
+ (testing "the tables an action's SQL names are recorded apart from the tables the questions read"
+ (with-data-apps-sync
+ (let [mp (mt/metadata-provider)
+ action-id (actions/insert! {:name "Clear checkins"
+ :type :query
+ :database_id (mt/id)
+ :dataset_query (lib/native-query mp "DELETE FROM checkins WHERE id = {{id}}")
+ :parameters [{:id "id" :slug "id" :type :number/=}]})
+ resources (data-apps.tu/build-resources
+ shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [action-id])
+ src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)} :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :success (:status result)) (:message result))
+ (is (= (sort [(mt/id :venues) (mt/id :checkins)])
+ (t2/select-one-fn :table_ids :model/DataApp :name "shop")))))))
+
+(deftest an-apps-own-yaml-is-left-alone-test
+ (testing "a YAML file in the app's directory that isn't its manifest is the app's own: not loaded, not removed"
+ (with-data-apps-sync
+ (let [own "data_apps/shop/i18n/en.yaml"
+ mock (test-helpers/create-mock-source
+ :initial-files {"main" (assoc (shop-tree (question-resources)) own "greeting: hello\n")})]
+ (let [result (import-at! mock "main" :force? true)]
+ (is (= :success (:status result)) (:message result)))
+ (mt/user-http-request :crowberto :put 200 "apps/shop" {:bundle "B2"})
+ (is (= :success (:status (export! mock))))
+ (is (= "greeting: hello\n" (get-in @(:files-atom mock) ["main" own])))))))
+
+(deftest deleting-an-apps-files-deletes-the-app-and-its-collection-test
+ (testing "an author deletes an app by deleting its directory and its collection's files under collections/data_apps/"
+ (with-data-apps-sync
+ (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [])
+ src (test-helpers/versioned-source :trees {"v0" (shop-tree resources) "v1" {"README.md" "x"}}
+ :current "v0")]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (let [collection-id (shop-collection-id)]
+ (is (t2/exists? :model/Card :entity_id question-eid :collection_id collection-id))
+ (is (= :success (:status (import-at! src "v1"))))
+ (is (not (t2/exists? :model/DataApp :name "shop")))
+ (testing "the hook deletes the collection and what it held"
+ (is (not (t2/exists? :model/Collection :id collection-id)))
+ (is (not (t2/exists? :model/Card :entity_id question-eid)))))))))
+
+(deftest deleting-an-apps-directory-without-its-collection-files-still-deletes-the-app-test
+ (testing "an author deletes an app's directory but leaves its collection's files: the pull doesn't fail, it deletes
+ the app, and with it its collection and what it held"
+ (with-data-apps-sync
+ (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [])
+ v0 (shop-tree resources)
+ v1 (dissoc v0 "data_apps/shop/data_app.yaml" "data_apps/shop/index.js")
+ src (test-helpers/versioned-source :trees {"v0" v0 "v1" v1} :current "v0")]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (let [collection-id (shop-collection-id)]
+ (is (t2/exists? :model/Card :entity_id question-eid :collection_id collection-id))
+ (let [result (import-at! src "v1")]
+ (is (= :success (:status result)) (:message result)))
+ (is (not (t2/exists? :model/DataApp :name "shop")))
+ (is (not (t2/exists? :model/Collection :id collection-id)))
+ (is (not (t2/exists? :model/Card :entity_id question-eid))))))))
+
+(deftest a-read-only-instance-still-serves-the-root-collection-test
+ (testing "with remote sync read-only, a card in no collection is read and edited as before: nothing there is synced"
+ (with-data-apps-sync
+ (mt/with-temp [:model/Card {card-id :id} {:name "In the root" :collection_id nil}]
+ (mt/with-temporary-setting-values [remote-sync-type :read-only remote-sync-url "https://example.com/repo.git"]
+ (mt/user-http-request :crowberto :get 200 (str "card/" card-id))
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:description "edited in the root"}))))))
+
+(deftest a-card-in-an-apps-collection-reads-only-the-apps-cards-test
+ (testing "a card there can't read a card outside the app's collection: the export would write a file every pull refuses"
+ (with-data-apps-sync
+ (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")
+ mp (mt/metadata-provider)]
+ (is (= :success (:status (import-at! src "v0" :force? true))))
+ (mt/with-temp [:model/Card {other-id :id} {:name "Elsewhere"
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Card {own-id :id} {:name "Own"
+ :collection_id (shop-collection-id)
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}]
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)
+ collection-id (shop-collection-id)
+ reading (fn [id] (lib/->legacy-MBQL (lib/query mp (lib.metadata/card mp id))))
+ save (fn [status collection-id query]
+ (mt/user-http-request :crowberto :post status "card"
+ {:name "Saved" :type "question" :display "table"
+ :visualization_settings {} :collection_id collection-id
+ :dataset_query query}))]
+ (save 400 collection-id (reading other-id))
+ (is (not (t2/exists? :model/Card :name "Saved")))
+ (let [query-before (t2/select-one-fn :dataset_query :model/Card :id card-id)]
+ (mt/user-http-request :crowberto :put 400 (str "card/" card-id) {:dataset_query (reading other-id)})
+ (is (= query-before (t2/select-one-fn :dataset_query :model/Card :id card-id))))
+ (testing "one of the app's own cards is fine"
+ (save 200 collection-id (reading own-id))
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:dataset_query (reading own-id)}))
+ (testing "as is a card elsewhere reading the card outside"
+ (save 200 nil (reading other-id)))))))))
+
+(deftest a-card-in-an-apps-collection-cant-take-embedding-settings-test
+ (testing "embedding parameters would make the export write a file every pull refuses, with embedding itself left off"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)]
+ (mt/with-temporary-setting-values [enable-embedding-static true]
+ (mt/user-http-request :crowberto :put 400 (str "card/" card-id) {:embedding_params {}})
+ (testing "a card elsewhere takes them"
+ (mt/with-temp [:model/Card {other-id :id} {:name "Elsewhere"}]
+ (mt/user-http-request :crowberto :put 200 (str "card/" other-id) {:embedding_params {}}))))
+ (is (= :success (:status (export! mock))))
+ (is (= :success (:status (import-at! mock "main" :force? true)))))))))
+
+(deftest an-apps-collection-cant-be-made-official-or-moved-test
+ (testing "either would make the export write a file every pull refuses"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [collection-id (shop-collection-id)
+ before (resource-files mock)]
+ (mt/with-additional-premium-features #{:official-collections}
+ (mt/user-http-request :crowberto :put 400 (str "collection/" collection-id) {:authority_level "official"}))
+ (mt/with-temp [:model/Collection {other-id :id} {:name "Other root" :namespace :data-apps}]
+ (mt/user-http-request :crowberto :put 400 (str "collection/" collection-id) {:parent_id other-id}))
+ (testing "a rename still works"
+ (mt/user-http-request :crowberto :put 200 (str "collection/" collection-id) {:name "Renamed"}))
+ (is (=? {:authority_level nil :location "/" :name "Renamed"} (t2/select-one :model/Collection :id collection-id)))
+ (is (= :success (:status (export! mock))))
+ (testing "and the export writes the collection's files, under the new name"
+ (is (= (count before) (count (resource-files mock))))
+ (is (file-named mock "venueslist")))
+ (is (= :success (:status (import-at! mock "main" :force? true)))))))))
+
+(deftest an-action-in-an-apps-collection-cant-be-archived-test
+ (testing "an export leaves out an archived action, and the next pull would then delete it from every instance"
+ (with-data-apps-sync
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [action-id]}]
+ (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [action-id])
+ mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree resources)})]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [copy-id (t2/select-one-pk :model/Action :collection_id (shop-collection-id))
+ before (resource-files mock)]
+ (mt/with-actions-enabled
+ (mt/user-http-request :crowberto :put 400 (str "action/" copy-id) {:archived true})
+ (testing "it can still be renamed"
+ (mt/user-http-request :crowberto :put 200 (str "action/" copy-id) {:name "Renamed"}))
+ (testing "and the source can still be archived"
+ (mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived true})))
+ (is (false? (t2/select-one-fn :archived :model/Action :id copy-id)))
+ (is (= :success (:status (export! mock))))
+ (testing "and the export keeps the action's file, under its new name"
+ (is (= (count before) (count (resource-files mock))))
+ (is (file-named mock "renamed"))))))))))
+
+(deftest an-apps-collection-cant-be-marked-remote-synced-test
+ (testing "an app's collection is synced with its app, and a pull refuses its file once it says remote-synced"
+ (with-data-apps-sync
+ (mt/with-additional-premium-features #{:remote-sync}
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [collection-id (shop-collection-id)]
+ (mt/with-dynamic-fn-redefs [impl/finish-remote-config! (constantly nil)]
+ (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings" {:collections {collection-id true}})
+ (is (false? (t2/select-one-fn :is_remote_synced :model/Collection :id collection-id)))
+ (testing "an ordinary collection still can be"
+ (mt/with-temp [:model/Collection {other-id :id} {:name "Ordinary"}]
+ (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings" {:collections {other-id true}})
+ (is (true? (t2/select-one-fn :is_remote_synced :model/Collection :id other-id))))))))))))
+
+(deftest an-action-in-an-apps-collection-stays-what-a-pull-accepts-test
+ (testing "an action there can't be made public or read a card outside the collection: the next export would write it
+ into a file every pull refuses"
+ (with-data-apps-sync
+ (data-apps.tu/do-with-sources!
+ (fn [{:keys [action-id]}]
+ (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [action-id])
+ mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree resources)})]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [copy-id (t2/select-one-pk :model/Action :collection_id (shop-collection-id))
+ card-id (t2/select-one-pk :model/Card :entity_id question-eid)
+ reads (fn [id]
+ (let [tag (str "#" id)]
+ {:database (mt/id)
+ :type :native
+ :native {:query (str "SELECT * FROM {{" tag "}}")
+ :template-tags {tag {:type :card
+ :card-id id
+ :name tag
+ :display-name tag
+ :id (str (random-uuid))}}}}))]
+ (mt/with-actions-enabled
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/user-http-request :crowberto :post 400 (str "action/" copy-id "/public_link"))
+ (is (nil? (t2/select-one-fn :public_uuid :model/Action :id copy-id)))
+ (testing "the source action still can be"
+ (mt/user-http-request :crowberto :post 200 (str "action/" action-id "/public_link"))))
+ (mt/with-temp [:model/Card {outside-id :id} {:name "Outside"}]
+ (let [query-before (t2/select-one-fn :dataset_query :model/QueryAction :action_id copy-id)]
+ (mt/user-http-request :crowberto :put 400 (str "action/" copy-id) {:dataset_query (reads outside-id)})
+ (is (= query-before (t2/select-one-fn :dataset_query :model/QueryAction :action_id copy-id)))))
+ (testing "it can read the app's own card"
+ (mt/user-http-request :crowberto :put 200 (str "action/" copy-id) {:dataset_query (reads card-id)})
+ (is (= #{card-id}
+ (into #{} (keep :card-id)
+ (filter map? (tree-seq coll? seq (t2/select-one-fn :dataset_query :model/QueryAction :action_id copy-id))))))))
+ (is (= :success (:status (export! mock))))
+ (is (= :success (:status (import-at! mock "main" :force? true)))))))))))
+
+(deftest a-pull-whose-table-record-fails-still-loads-test
+ (testing "the tables are recorded after the load's transaction, so a failure there is logged and the pull stands"
+ (with-data-apps-sync
+ (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")]
+ (mt/with-dynamic-fn-redefs [data-apps/record-table-dependencies! (fn [] (throw (ex-info "the tables can't be recorded" {})))]
+ (let [result (import-at! src "v0" :force? true)]
+ (is (= :success (:status result)) (:message result))))
+ (is (t2/exists? :model/DataApp :name "shop"))
+ (is (= "v0" (remote-sync.task/last-version)))))))
+
+(deftest the-bulk-move-endpoint-moves-app-cards-through-the-model-test
+ (testing "POST /api/card/collections runs the checks a PUT runs, and the export sees the move"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})
+ mp (mt/metadata-provider)
+ q (lib/->legacy-MBQL (lib/query mp (lib.metadata/table mp (mt/id :venues))))]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)
+ collection-id (shop-collection-id)]
+ (testing "a model can't be moved in"
+ (mt/with-temp [:model/Card {model-id :id} {:name "A model" :type :model :dataset_query q}]
+ (mt/user-http-request :crowberto :post 400 "card/collections" {:card_ids [model-id] :collection_id collection-id})
+ (is (nil? (t2/select-one-fn :collection_id :model/Card :id model-id)))))
+ (testing "the app's card moved out is gone from the app's files on the next export"
+ (mt/user-http-request :crowberto :post 200 "card/collections" {:card_ids [card-id] :collection_id nil})
+ (is (nil? (t2/select-one-fn :collection_id :model/Card :id card-id)))
+ (is (= :success (:status (export! mock))))
+ (is (not (file-named mock "venueslist")))
+ (is (= :success (:status (import-at! mock "main" :force? true))))))))))
+
+(deftest a-refused-pull-names-the-file-whatever-its-name-test
+ (testing "a validator failure is reported as what it is when a path has \"branch\" in it, not as a branch error"
+ (with-data-apps-sync
+ (let [collection-eid (data-apps.tu/collection-entity-id "branch-ops")
+ resources (data-apps.tu/build-resources "Data App: branch-ops" collection-eid
+ [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]
+ [])
+ card-file (some #(when (str/includes? % question-eid) %) (keys resources))
+ tree (data-apps.tu/app-files "branch-ops"
+ {:name "Branch Ops" :path "index.js" :bundle "B" :collection collection-eid
+ :resources (update resources card-file
+ #(yaml/generate-string (assoc (yaml/parse-string %) :type "model")))})
+ src (test-helpers/versioned-source :trees {"v0" tree} :current "v0")
+ result (import-at! src "v0" :force? true)]
+ (is (= :error (:status result)))
+ (is (str/includes? (:message result) "must be a question or metric"))
+ (is (str/includes? (:message result) card-file))))))
+
+(deftest an-export-records-the-tables-test
+ (testing "editing a resource card and exporting is how an app changes on a read-write instance, and the permission
+ warnings follow the export rather than the next pull"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})
+ mp (mt/metadata-provider)]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (is (= [(mt/id :venues)] (t2/select-one-fn :table_ids :model/DataApp :name "shop")))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)]
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id)
+ {:dataset_query (lib/->legacy-MBQL (lib/query mp (lib.metadata/table mp (mt/id :checkins))))})
+ (is (= :success (:status (export! mock))))
+ (is (= [(mt/id :checkins)] (t2/select-one-fn :table_ids :model/DataApp :name "shop"))))))))
+
+(deftest an-export-whose-table-record-fails-still-records-the-export-test
+ (testing "the commit is pushed before the tables are recorded, so a failure there must not undo the record of it"
+ (with-data-apps-sync
+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})
+ mp (mt/metadata-provider)]
+ (is (= :success (:status (import-at! mock "main" :force? true))))
+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)]
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id)
+ {:dataset_query (lib/->legacy-MBQL (lib/query mp (lib.metadata/table mp (mt/id :checkins))))})
+ (is (seq (remote-sync.object/dirty-rows)))
+ (mt/with-dynamic-fn-redefs [data-apps/record-table-dependencies! (fn [] (throw (ex-info "the tables can't be recorded" {})))]
+ (let [result (export! mock)]
+ (is (= :success (:status result)) (:message result))))
+ (testing "the export is recorded: the rows are synced"
+ (is (empty? (remote-sync.object/dirty-rows)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj
index 06a6017ffee..3c5c7397076 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj
@@ -287,28 +287,26 @@
;;; ------------------------------------------- Data app ledger backfill -------------------------------------------
(defn- do-with-untracked-data-apps!
- "Runs `f` with `{:published :draft :tracked}` data app ids under `remote-sync-type` `sync-type`, where only
+ "Runs `f` with `{:published :tracked}` data app ids under `remote-sync-type` `sync-type`, where only
`:tracked` has a DataApp ledger row."
[sync-type f]
(mt/with-temporary-setting-values [:remote-sync-url "file://my/repo.git"
:remote-sync-type sync-type
:remote-sync-branch "main"]
(mt/with-model-cleanup [:model/RemoteSyncObject :model/DataApp :model/Collection :model/PermissionsGroup]
- (let [insert-app! (fn [slug draft?]
+ (let [insert-app! (fn [slug]
(t2/insert-returning-pk! :model/DataApp {:name slug
:display_name slug
:bundle_path "index.js"
- :bundle (.getBytes "BUNDLE" "UTF-8")
- :draft draft?}))
- published (insert-app! "published" false)
- draft (insert-app! "draft" true)
- tracked (insert-app! "tracked" false)]
+ :bundle (.getBytes "BUNDLE" "UTF-8")}))
+ published (insert-app! "published")
+ tracked (insert-app! "tracked")]
(t2/delete! :model/RemoteSyncObject :model_type "DataApp")
(t2/insert! :model/RemoteSyncObject {:model_type "DataApp" :model_id tracked :model_name "tracked"
:status "synced" :status_changed_at (t/offset-date-time)})
(mt/with-dynamic-fn-redefs [impl/async-import! (constantly nil)
remote-sync.object/dirty? (constantly false)]
- (f {:published published :draft draft :tracked tracked}))))))
+ (f {:published published :tracked tracked}))))))
(defn- data-app-rso-statuses []
(t2/select-fn->fn :model_id :status :model/RemoteSyncObject :model_type "DataApp"))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj
index c08c0942b92..abd8603642d 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj
@@ -389,7 +389,8 @@
(collections.tu/with-library-synced
(is (true? (eligible? root-action)))
(is (true? (eligible? folder-action)))
- (is (false? (eligible? app-action))))
+ ;; an app's copy is synced with the app, whatever the Library does
+ (is (true? (eligible? app-action))))
(collections.tu/with-library-not-synced
(is (false? (eligible? root-action)))
(is (false? (eligible? folder-action)))))))))
@@ -417,7 +418,8 @@
(mt/with-current-user (mt/user->id :crowberto)
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git" remote-sync-type :read-only]
(is (false? (mi/can-write? (t2/select-one :model/Action :id root-action))))
- (is (true? (mi/can-write? (t2/select-one :model/Action :id app-action)))))
+ ;; an app's copy is synced with the app, which a read-only instance can't push either
+ (is (false? (mi/can-write? (t2/select-one :model/Action :id app-action)))))
(mt/with-temporary-setting-values [remote-sync-type :read-write]
(is (true? (mi/can-write? (t2/select-one :model/Action :id root-action)))))))))))
@@ -433,12 +435,12 @@
(testing "model-editable? returns true for every model while remote sync is not configured"
(mt/with-temporary-setting-values [remote-sync-url nil
remote-sync-type :read-only]
- (is (true? (spec/model-editable? :model/DataApp {:draft false})))
- (is (= {1 true} (spec/batch-model-editable? :model/DataApp [{:id 1 :draft false}]))))
+ (is (true? (spec/model-editable? :model/DataApp {})))
+ (is (= {1 true} (spec/batch-model-editable? :model/DataApp [{:id 1}]))))
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-type :read-only]
- (is (false? (spec/model-editable? :model/DataApp {:draft false})))
- (is (= {1 false} (spec/batch-model-editable? :model/DataApp [{:id 1 :draft false}]))))))
+ (is (false? (spec/model-editable? :model/DataApp {})))
+ (is (= {1 false} (spec/batch-model-editable? :model/DataApp [{:id 1}]))))))
(deftest model-editable?-read-write-mode-test
(testing "model-editable? returns true in read-write mode regardless of eligibility"
diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.ts b/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.ts
deleted file mode 100644
index 9cc22e16225..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import path from "node:path";
-
-import { getResourceSyncCredentials } from "../../data-app-query-sync/env";
-import { syncResources } from "../../data-app-query-sync/sync";
-
-export async function syncResourcesAction(appRoot = process.cwd()) {
- const resolvedRoot = path.resolve(appRoot);
- await syncResources({
- appRoot: resolvedRoot,
- ...getResourceSyncCredentials(resolvedRoot),
- });
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.unit.spec.ts
deleted file mode 100644
index 110a31c30c0..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.unit.spec.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import path from "node:path";
-
-import { getResourceSyncCredentials } from "../../data-app-query-sync/env";
-import { syncResources } from "../../data-app-query-sync/sync";
-
-import { syncResourcesAction } from "./sync-resources";
-
-jest.mock("../../data-app-query-sync/env", () => ({
- getResourceSyncCredentials: jest.fn(),
-}));
-jest.mock("../../data-app-query-sync/sync", () => ({
- syncResources: jest.fn(),
-}));
-
-describe("syncResourcesAction", () => {
- it("resolves the app root and loads its credentials", async () => {
- jest.mocked(getResourceSyncCredentials).mockReturnValue({
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- });
-
- await syncResourcesAction("data_apps/orders");
-
- const appRoot = path.resolve("data_apps/orders");
- expect(getResourceSyncCredentials).toHaveBeenCalledWith(appRoot);
- expect(syncResources).toHaveBeenCalledWith({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- });
- });
-
- it("uses the current directory by default", async () => {
- jest.mocked(getResourceSyncCredentials).mockReturnValue({
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- });
-
- await syncResourcesAction();
-
- const appRoot = path.resolve(process.cwd());
- expect(getResourceSyncCredentials).toHaveBeenCalledWith(appRoot);
- expect(syncResources).toHaveBeenCalledWith({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- });
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.ts b/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.ts
index 274a724e29f..8f92f9f8f60 100644
--- a/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.ts
@@ -1,17 +1,41 @@
import type { Command } from "commander";
-import { syncResourcesAction } from "../actions/sync-resources";
+import { checkResources } from "../../data-app-resources/check";
+import { serializeResources } from "../../data-app-resources/serialize";
+
+type AppRootOptions = { appRoot: string };
+
+/** Adds `name` as a data app command that runs from the app's directory unless `--app-root` says otherwise. */
+const addAppCommand = (parent: Command, name: string, description: string) =>
+ parent
+ .command(name)
+ .description(description)
+ .option("--app-root <path>", "data app directory", process.cwd());
export function addDataAppsCommands(program: Command) {
const dataAppsCommand = program
.command("data-apps")
.description("manage Metabase data apps");
- dataAppsCommand
- .command("sync-resources")
- .description(
- "synchronize data app query and action definitions into its collection",
+ addAppCommand(
+ dataAppsCommand,
+ "print-resources",
+ "print what the files of the data app's collection are written from, serialized by Metabase, as JSON",
+ )
+ .argument(
+ "[file]",
+ "only the definitions in this file, relative to the app directory",
)
- .option("--app-root <path>", "data app directory", process.cwd())
- .action(({ appRoot }: { appRoot: string }) => syncResourcesAction(appRoot));
+ .action(async (file: string | undefined, { appRoot }: AppRootOptions) => {
+ process.stdout.write(`${await serializeResources(appRoot, file)}\n`);
+ });
+
+ addAppCommand(
+ dataAppsCommand,
+ "check-resources",
+ "check that the files of the data app's collection, under collections/data_apps/, back its query and action definitions",
+ ).action(async ({ appRoot }: AppRootOptions) => {
+ await checkResources(appRoot);
+ process.stdout.write("The app's collection files back every definition.\n");
+ });
}
diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.unit.spec.ts
index 1a308e458f8..0d91e445659 100644
--- a/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.unit.spec.ts
@@ -1,36 +1,111 @@
+import fs from "node:fs";
+import path from "node:path";
+
import { Command } from "commander";
-import { syncResourcesAction } from "../actions/sync-resources";
+import {
+ makeApp,
+ setupResourceTests,
+ writeAction,
+ writeQuery,
+ writeResource,
+} from "../../data-app-resources/tests/setup";
import { addDataAppsCommands } from "./data-apps";
-jest.mock("../actions/sync-resources", () => ({
- syncResourcesAction: jest.fn(),
-}));
+const QUESTION = "questionEntityId00010";
+
+async function run(...args: string[]) {
+ const program = new Command();
+ addDataAppsCommands(program);
+ await program.parseAsync(["node", "cli", "data-apps", ...args]);
+}
+
+function appWithQuery() {
+ const appRoot = makeApp();
+ writeQuery(
+ appRoot,
+ `export const Orders = defineQuery({ savedQuestionEntityId: "${QUESTION}", source: { type: "table", id: 1 } });`,
+ );
+ return appRoot;
+}
describe("data app commands", () => {
- it("runs resource synchronization for the requested app root", async () => {
- const program = new Command();
- addDataAppsCommands(program);
-
- await program.parseAsync([
- "node",
- "cli",
- "data-apps",
- "sync-resources",
+ setupResourceTests();
+
+ let stdout: jest.SpyInstance;
+
+ beforeEach(() => {
+ stdout = jest.spyOn(process.stdout, "write").mockImplementation(() => true);
+ });
+
+ const printed = () =>
+ stdout.mock.calls.map(([chunk]) => String(chunk)).join("");
+
+ it("prints the serialization of one file's definitions, relative to the app root", async () => {
+ const appRoot = appWithQuery();
+ writeAction(
+ appRoot,
+ `export const Create = defineAction({ action: { id: 51, parameters: [] } });`,
+ );
+ fs.writeFileSync(
+ path.join(appRoot, ".env.local"),
+ "DATA_APP_MB_URL=http://metabase.test\nDATA_APP_MB_API_KEY=mb_test_key\n",
+ );
+ jest.spyOn(global, "fetch").mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ queries: [{ export: "Orders", entity: {}, metrics: [] }],
+ actions: [],
+ metrics: [],
+ }),
+ ),
+ );
+
+ await run(
+ "print-resources",
+ "queries/orders.query.ts",
"--app-root",
- "data_apps/orders",
- ]);
+ appRoot,
+ );
- expect(syncResourcesAction).toHaveBeenCalledWith("data_apps/orders");
+ expect(JSON.parse(printed())).toEqual({
+ queries: [
+ {
+ export: "Orders",
+ file: "queries/orders.query.ts",
+ savedQuestionEntityId: QUESTION,
+ entity: {},
+ metrics: [],
+ },
+ ],
+ actions: [],
+ metrics: [],
+ });
});
- it("runs resource synchronization from the current directory by default", async () => {
- const program = new Command();
- addDataAppsCommands(program);
+ it("confirms resources that back every definition", async () => {
+ const appRoot = appWithQuery();
+ writeResource(appRoot, "data_app/orders.yaml", {
+ name: "Orders",
+ type: "question",
+ entity_id: QUESTION,
+ "serdes/meta": [{ model: "Card", id: QUESTION }],
+ });
+
+ await run("check-resources", "--app-root", appRoot);
+
+ expect(printed()).toBe(
+ "The app's collection files back every definition.\n",
+ );
+ });
- await program.parseAsync(["node", "cli", "data-apps", "sync-resources"]);
+ it("fails when a definition's resource is missing", async () => {
+ const appRoot = appWithQuery();
- expect(syncResourcesAction).toHaveBeenCalledWith(process.cwd());
+ await expect(run("check-resources", "--app-root", appRoot)).rejects.toThrow(
+ `queries/orders.query.ts:Orders names saved question ${QUESTION}, which no file in collections/data_apps/ holds in the app's collection.`,
+ );
+ expect(printed()).toBe("");
});
});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts
index 03c6d6c0fc5..e7cf3457017 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts
@@ -6,10 +6,27 @@ import { load as parseYaml } from "js-yaml";
export type DataAppManifest = {
slug?: string;
allowed_hosts?: string[];
+ /** The entity ID of the app's collection, whose file sits under the repository's `collections/data_apps/`. */
+ collection?: string;
};
const isString = (value: unknown): value is string => typeof value === "string";
+const parseCollection = (
+ value: unknown,
+ manifestPath: string,
+): string | undefined => {
+ if (value == null) {
+ return undefined;
+ }
+
+ if (!isString(value)) {
+ throw new Error(`${manifestPath}: "collection" must be an entity ID.`);
+ }
+
+ return value;
+};
+
const parseAllowedHosts = (
value: unknown,
manifestPath: string,
@@ -73,7 +90,7 @@ export const readManifest = (
);
}
- const raw: { slug?: unknown; allowed_hosts?: unknown } =
+ const raw: { slug?: unknown; allowed_hosts?: unknown; collection?: unknown } =
typeof parsed === "object" && parsed !== null ? parsed : {};
return {
@@ -81,6 +98,7 @@ export const readManifest = (
manifest: {
slug: parseSlug(raw.slug, manifestPath),
allowed_hosts: parseAllowedHosts(raw.allowed_hosts, manifestPath),
+ collection: parseCollection(raw.collection, manifestPath),
},
};
};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.unit.spec.ts
index beed6289a4c..4facc961c1e 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.unit.spec.ts
@@ -58,6 +58,24 @@ describe("readManifest", () => {
});
});
+ describe("collection", () => {
+ it("reads the resource collection's entity ID", () => {
+ setup({ [YAML_PATH]: "collection: appCollectionEntity01\n" });
+
+ expect(readManifest(APP_ROOT)?.manifest.collection).toBe(
+ "appCollectionEntity01",
+ );
+ });
+
+ it("throws when it is not a string", () => {
+ setup({ [YAML_PATH]: "collection: [1, 2]\n" });
+
+ expect(() => readManifest(APP_ROOT)).toThrow(
+ '"collection" must be an entity ID',
+ );
+ });
+ });
+
describe("allowed_hosts", () => {
it("reads allowed_hosts as a list of strings", () => {
setup({
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts
index 4ad5840d3df..e8d8b2889f1 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts
@@ -8,7 +8,7 @@ import {
loadEnv,
} from "vite";
-import { checkResourcesSynced } from "../data-app-query-sync/sync";
+import { checkResources } from "../data-app-resources/check";
import { dataAppBuildPlugins, dataAppLibBuild } from "./config/build-config";
import { getDataAppDefine } from "./config/define";
@@ -39,10 +39,10 @@ function dataAppVitePlugin(): PluginOption[] {
...dataAppBuildPlugins(),
dataAppSandboxDevPlugin(appSlug, allowedHosts),
{
- name: "metabase-resource-sync-check",
+ name: "metabase-resource-check",
apply: "build",
buildStart: async () => {
- await checkResourcesSynced(appRoot);
+ await checkResources(appRoot);
},
},
{
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.unit.spec.ts
index 59f9de99f43..156029e6848 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.unit.spec.ts
@@ -1,3 +1,13 @@
+import { isObject } from "metabase-types/guards";
+
+import {
+ COLLECTION,
+ makeApp,
+ setupResourceTests,
+ writeQuery,
+ writeResource,
+} from "../data-app-resources/tests/setup";
+
import { readManifest } from "./config/read-manifest";
import { dataAppConfig } from "./index";
@@ -50,4 +60,80 @@ describe("dataAppConfig", () => {
expect(dataAppConfig({ port: 4000 }).server?.port).toBe(4000);
});
+
+ describe("the resource check", () => {
+ setupResourceTests();
+
+ const QUESTION = "questionEntityId00010";
+
+ type ResourceCheckPlugin = {
+ apply: unknown;
+ buildStart: () => Promise<void>;
+ };
+
+ const isResourceCheckPlugin = (
+ candidate: unknown,
+ ): candidate is ResourceCheckPlugin =>
+ isObject(candidate) &&
+ candidate.name === "metabase-resource-check" &&
+ typeof candidate.buildStart === "function";
+
+ // Vite accepts nested plugin arrays, and `dataAppConfig` returns one.
+ const flatten = (option: unknown): unknown[] =>
+ Array.isArray(option) ? option.flatMap(flatten) : [option];
+
+ /** The plugin of an app in `appRoot`, which vite runs from its own directory. */
+ const resourceCheckPlugin = (appRoot: string) => {
+ jest.spyOn(process, "cwd").mockReturnValue(appRoot);
+ mockedReadManifest.mockReturnValue({
+ manifestPath: `${appRoot}/data_app.yaml`,
+ manifest: { collection: COLLECTION },
+ });
+
+ const plugin = flatten(dataAppConfig().plugins).find(
+ isResourceCheckPlugin,
+ );
+
+ if (!plugin) {
+ throw new Error("The resource check plugin is missing.");
+ }
+
+ return plugin;
+ };
+
+ const appWithQuery = () => {
+ const appRoot = makeApp();
+ writeQuery(
+ appRoot,
+ `export const Orders = defineQuery({ savedQuestionEntityId: "${QUESTION}", source: { type: "table", id: 1 } });`,
+ );
+ return appRoot;
+ };
+
+ it("runs only for a production build", () => {
+ expect(resourceCheckPlugin(appWithQuery()).apply).toBe("build");
+ });
+
+ it("lets the build start when the app's resources back its definitions", async () => {
+ const appRoot = appWithQuery();
+ writeResource(appRoot, "data_app/orders.yaml", {
+ name: "Orders",
+ type: "question",
+ entity_id: QUESTION,
+ "serdes/meta": [{ model: "Card", id: QUESTION }],
+ });
+
+ await expect(
+ resourceCheckPlugin(appRoot).buildStart(),
+ ).resolves.toBeUndefined();
+ });
+
+ it("fails the build when a definition's resource is missing", async () => {
+ await expect(
+ resourceCheckPlugin(appWithQuery()).buildStart(),
+ ).rejects.toThrow(
+ `queries/orders.query.ts:Orders names saved question ${QUESTION}, which no file in collections/data_apps/ holds in the app's collection.`,
+ );
+ });
+ });
});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/README.md b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/README.md
deleted file mode 100644
index 378d264aa99..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/README.md
+++ /dev/null
@@ -1,104 +0,0 @@
-# Resource sync
-
-A data app runs in a browser sandbox as one of its viewers, not as its author. Those viewers reach
-Metabase through a permission group that can read exactly one collection: the app's own. So a query
-the app runs, and an action it triggers, have to be reachable **through that collection** or they
-fail on permissions.
-
-Resource sync is the build-time step that makes that true. It reads the definitions an app commits
-to source control, materializes them inside the app's collection, and writes back the generated IDs.
-`npm run sync-resources` (`embedding-sdk-react data-apps sync-resources`) is the entry point.
-
-The backend half — the collection and permission group themselves — lives in
-`metabase_enterprise/data_apps/resources.clj`. See that module's README for how apps are served.
-
-## What an app declares
-
-Two directories at the data-app root, beside `package.json`:
-
-```
-queries/orders.query.ts export const RevenueQuery = defineQuery({ source: schema.tables.orders })
-actions/orders.action.ts export const CreateOrder = defineAction({ action: schema.actions.shipOrder })
-```
-
-Nothing else is scanned — definitions under `src/` are invisible to sync, which is a common
-authoring mistake.
-
-## The pipeline
-
-`syncResources` (`sync.ts`) runs four steps:
-
-1. **Discover** every `defineQuery` / `defineAction` in those directories (`discover.ts`).
-2. **Ensure resources** — `POST /api/apps/:slug/draft` creates the app row if it doesn't exist
- yet, plus its collection and permission group.
-3. **Reconcile queries** (`reconcile.ts`) — each authored query becomes a saved question in the
- collection, and its ID is injected back into the source as `savedQuestionSourceId`.
-4. **Reconcile actions** (`reconcile-actions.ts`) — each declared action, a query action that
- belongs to no model, is copied into the collection, and the copy's ID is injected back as
- `copiedActionId`.
-
-## Actions
-
-An action without a model resolves its permissions through its own collection, so copying the
-action into the app collection is what makes it runnable by the app's viewers. Each lockfile entry
-maps a source action to its copy; a copy is updated when its source changes, recreated when it was
-deleted, and deleted when its declaration goes away. An action that belongs to a model is refused.
-
-## Discovery is deliberately strict
-
-`discover.ts` parses each file twice over. The TypeScript AST locates `defineQuery`/`defineAction`
-calls and enforces that each one directly initializes a **named exported** variable with a single
-object literal. The file is then bundled with esbuild and evaluated — **twice** — and the two results
-compared, so a definition that isn't deterministic can't produce a fingerprint that changes under it.
-
-Write-back re-parses from disk rather than reusing the AST from discovery, because reconciliation
-injects sequentially and an earlier injection into the same file shifts every offset after it.
-
-## The lockfile is ownership proof
-
-`resources_metadata.json` is generated, committed, and never hand-edited:
-
-```jsonc
-{
- "queries": [
- { "tableId": 1, "hash": "v1:sha256:…", "savedQuestionSourceId": 54 },
- ],
- "actions": [
- { "sourceActionId": 51, "copiedActionId": 91, "hash": "v1:sha256:…" },
- ],
-}
-```
-
-It is not a cache. It is the only evidence that a card or action in Metabase belongs to this app,
-and every mutating path checks it first. The `hash` fields fingerprint the payload last copied; sync
-compares it against the live copy, which catches both an edited source and a copy edited in Metabase.
-
-## Invariants
-
-These hold across both reconcilers, and are what the tests are mostly about:
-
-- **Nothing is mutated or deleted without lockfile proof**, plus a live ownership check — still a
- question, still in the app's collection, an action still without a model in the app's collection. Anything
- that has moved is refused with recovery instructions rather than silently touched.
-- **The lockfile flushes after every single mutation**, so a crash mid-run leaves resumable state.
-- **`404` is the only recoverable failure.** Any other status rethrows; recreate-after-404
- additionally requires lockfile proof.
-- **On the backend, ownership is the foreign key, never the name.** A same-named group is refused,
- not adopted — adoption would hand its existing members the app's data access on a name match.
-
-## Dev preview vs production build
-
-Generated IDs only take effect in a production build. `isDataAppDev()` gates both swaps, so an app
-runs against the original table and the authored action before it has ever been synchronized:
-
-| | Dev preview | Production |
-| ------------ | ------------------- | -------------------------------------------- |
-| query source | the table | the saved question (`savedQuestionSourceId`) |
-| action | the authored action | the copy (`copiedActionId`) |
-
-Both swaps live in the bundle — `toSourceInput` and `toExecutableActionId` — not in app code, so an
-author passes the definition and never branches on the environment.
-
-`checkResourcesSynced` runs at `buildStart` for production builds only. It re-reads the source and
-the lockfile and fails the build when they disagree, so a stale app can't ship: a stale build isn't
-broken, it's silently pointed at whatever the saved question was when it was last synced.
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/ast/query-source.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/ast/query-source.ts
deleted file mode 100644
index 27565b04093..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/ast/query-source.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-
-import ts from "typescript";
-
-import { SDK_PACKAGE_NAME } from "embedding-sdk-package/cli/constants/config";
-
-export interface QuerySource {
- exportName: string;
- filePath: string;
-}
-
-interface InspectedQuerySource extends QuerySource {
- object: ts.ObjectLiteralExpression;
- sourceFile: ts.SourceFile;
-}
-
-/** A source-controlled definition kind, and where synchronization looks for it. */
-export interface DefinitionKind {
- directory: string;
- factory: string;
- idKey: string;
- /** Article included, so it reads in "did not evaluate to … object". */
- description: string;
-}
-
-export const QUERY_DEFINITIONS: DefinitionKind = {
- directory: "queries",
- factory: "defineQuery",
- idKey: "savedQuestionSourceId",
- description: "a query",
-};
-
-export const ACTION_DEFINITIONS: DefinitionKind = {
- directory: "actions",
- factory: "defineAction",
- idKey: "copiedActionId",
- description: "an action",
-};
-
-const DATA_APP_MODULE = SDK_PACKAGE_NAME + "/data-app";
-
-const QUERY_FILE_EXTENSIONS = [
- ".js",
- ".jsx",
- ".ts",
- ".tsx",
- ".cjs",
- ".cts",
- ".mjs",
- ".mts",
-];
-
-export function findDefinitionSources(
- appRoot: string,
- kind: DefinitionKind,
-): QuerySource[] {
- return listQueryFiles(path.join(appRoot, kind.directory)).flatMap(
- (filePath) => inspectFile(filePath, kind),
- );
-}
-
-/** Writes a generated ID back into its definition. */
-export function injectGeneratedId(
- target: QuerySource,
- kind: DefinitionKind,
- id: number,
-) {
- const source = inspectFile(target.filePath, kind).find(
- ({ exportName }) => exportName === target.exportName,
- );
-
- if (!source) {
- throw new Error(
- `Could not find ${target.exportName} in ${target.filePath}.`,
- );
- }
-
- // Keep the definition's other properties and spreads, removing the old ID.
- const propertiesWithoutId = source.object.properties.filter(
- (prop) =>
- !(
- prop.name &&
- (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) &&
- prop.name.text === kind.idKey
- ),
- );
-
- // Put the generated ID last so a spread cannot overwrite it with an old ID.
- const updatedDefinition = ts.factory.updateObjectLiteralExpression(
- source.object,
- [
- ...propertiesWithoutId,
-
- ts.factory.createPropertyAssignment(
- kind.idKey,
- ts.factory.createNumericLiteral(id),
- ),
- ],
- );
-
- const replacement = ts
- .createPrinter()
- .printNode(ts.EmitHint.Expression, updatedDefinition, source.sourceFile);
-
- const contents = source.sourceFile.text;
- const updated = `${contents.slice(0, source.object.getStart(source.sourceFile))}${replacement}${contents.slice(source.object.getEnd())}`;
- fs.writeFileSync(target.filePath, updated);
-}
-
-function listQueryFiles(directory: string): string[] {
- if (!fs.existsSync(directory)) {
- return [];
- }
-
- return fs
- .readdirSync(directory, { withFileTypes: true })
- .flatMap((entry) => {
- const itemPath = path.join(directory, entry.name);
- return entry.isDirectory() ? listQueryFiles(itemPath) : [itemPath];
- })
- .filter(isQueryFile)
- .sort();
-}
-
-const isQueryFile = (filePath: string) =>
- QUERY_FILE_EXTENSIONS.some((extension) => filePath.endsWith(extension));
-
-const hasExportModifier = (node: ts.Node) =>
- ts.canHaveModifiers(node)
- ? ts
- .getModifiers(node)
- ?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
- : false;
-
-function isDataAppImport(
- statement: ts.Statement,
-): statement is ts.ImportDeclaration {
- return (
- ts.isImportDeclaration(statement) &&
- ts.isStringLiteral(statement.moduleSpecifier) &&
- statement.moduleSpecifier.text === DATA_APP_MODULE
- );
-}
-
-function getDataAppNamedImports(statement: ts.Statement) {
- if (!isDataAppImport(statement)) {
- return undefined;
- }
-
- const namedBindings = statement.importClause?.namedBindings;
-
- if (!namedBindings || !ts.isNamedImports(namedBindings)) {
- return undefined;
- }
-
- return namedBindings.elements;
-}
-
-const isFactoryImport = (item: ts.ImportSpecifier, factory: string) =>
- (item.propertyName ?? item.name).text === factory;
-
-const isDirectVariableInitialization = (
- declaration: ts.Node,
- initializer: ts.CallExpression,
-): declaration is ts.VariableDeclaration & { name: ts.Identifier } =>
- ts.isVariableDeclaration(declaration) &&
- declaration.initializer === initializer &&
- ts.isIdentifier(declaration.name);
-
-const isNamedExportStatement = (statement: ts.Node | undefined) =>
- Boolean(
- statement &&
- ts.isVariableStatement(statement) &&
- hasExportModifier(statement),
- );
-
-const definitionObjectArgument = (node: ts.CallExpression) => {
- const [argument] = node.arguments;
- return node.arguments.length === 1 && ts.isObjectLiteralExpression(argument)
- ? argument
- : undefined;
-};
-
-const isDirectNamedDefinition = (
- node: ts.CallExpression,
- declaration: ts.Node,
- statement: ts.Node | undefined,
-): declaration is ts.VariableDeclaration & { name: ts.Identifier } =>
- isDirectVariableInitialization(declaration, node) &&
- isNamedExportStatement(statement);
-
-const isFactoryCall = (
- node: ts.Node,
- names: Set<string>,
-): node is ts.CallExpression =>
- ts.isCallExpression(node) &&
- ts.isIdentifier(node.expression) &&
- names.has(node.expression.text);
-
-function inspectFile(
- filePath: string,
- kind: DefinitionKind,
-): InspectedQuerySource[] {
- const contents = fs.readFileSync(filePath, "utf8");
-
- const sourceFile = ts.createSourceFile(
- filePath,
- contents,
- ts.ScriptTarget.Latest,
- true,
- filePath.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
- );
-
- const factoryNames = new Set<string>();
-
- for (const statement of sourceFile.statements) {
- const namedImports = getDataAppNamedImports(statement);
-
- if (!namedImports) {
- continue;
- }
-
- for (const item of namedImports) {
- if (isFactoryImport(item, kind.factory)) {
- factoryNames.add(item.name.text);
- }
- }
- }
-
- const definitionSources: InspectedQuerySource[] = [];
-
- const visit = (node: ts.Node) => {
- if (isFactoryCall(node, factoryNames)) {
- const declaration = node.parent;
- const statement = declaration.parent?.parent;
- const object = definitionObjectArgument(node);
-
- if (!isDirectNamedDefinition(node, declaration, statement) || !object) {
- throw new Error(
- `${filePath}: ${kind.factory} must directly initialize a named exported variable with one object literal.`,
- );
- }
-
- definitionSources.push({
- exportName: declaration.name.text,
- filePath,
- object,
- sourceFile,
- });
- }
-
- ts.forEachChild(node, visit);
- };
-
- visit(sourceFile);
-
- return definitionSources;
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/canonical.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/canonical.ts
deleted file mode 100644
index a94441eccda..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/canonical.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { createHash } from "node:crypto";
-
-import { isRecord } from "./guards";
-
-/** Serializes a query with stable object-key ordering. */
-export const canonicalJson = (value: unknown): string =>
- JSON.stringify(canonicalize(value));
-
-/** Returns the source table and stable hash of an authored query. */
-export function getQueryFingerprint(query: Record<string, unknown>) {
- const source = query.source;
-
- if (
- !isRecord(source) ||
- source.type !== "table" ||
- typeof source.id !== "number" ||
- !Number.isInteger(source.id) ||
- source.id <= 0
- ) {
- throw new Error("Synchronized queries must use a valid table source.");
- }
-
- const tableId = source.id;
- const authoredDsl: Record<string, unknown> = {
- ...query,
- source: { type: "table" },
- };
-
- delete authoredDsl.savedQuestionSourceId;
-
- const hash = createHash("sha256")
- .update(canonicalJson(authoredDsl))
- .digest("hex");
-
- return { tableId, hash: `v1:sha256:${hash}` };
-}
-
-/**
- * Returns the stable hash of a payload copied into a data app collection.
- * Generated Lib UUIDs are normalized so a re-read of the same source does not
- * read as drift.
- */
-export function getPayloadFingerprint(value: unknown): string {
- const hash = createHash("sha256")
- .update(getCanonicalQueryJson(value))
- .digest("hex");
-
- return `v1:sha256:${hash}`;
-}
-
-/** Serializes a resolved query while removing generated Lib-only fields. */
-export function getCanonicalQueryJson(value: unknown): string {
- const canonical = canonicalize(value);
- const generatedIds = new Map<string, number>();
-
- JSON.stringify(canonical, (key, item) => {
- if (
- key === "lib/uuid" &&
- typeof item === "string" &&
- !generatedIds.has(item)
- ) {
- generatedIds.set(item, generatedIds.size);
- }
- return item;
- });
-
- return JSON.stringify(canonical, (key, item) => {
- if (key === "lib/uuid") {
- return undefined;
- }
- if (key === "lib/metadata" && item === null) {
- return undefined;
- }
- const generatedId =
- typeof item === "string" ? generatedIds.get(item) : undefined;
- return generatedId === undefined
- ? item
- : `generated-query-id:${generatedId}`;
- });
-}
-
-/** Validates a query value and recursively sorts object keys. */
-function canonicalize(value: unknown, seen = new Set<object>()): unknown {
- const type = typeof value;
-
- if (value === null || type === "string" || type === "boolean") {
- return value;
- }
-
- if (type === "number") {
- if (!Number.isFinite(value)) {
- throw new Error("Query definitions cannot contain non-finite numbers.");
- }
-
- return value;
- }
-
- if (typeof value !== "object") {
- throw new Error(`Query definitions cannot contain ${type} values.`);
- }
-
- if (seen.has(value)) {
- throw new Error("Query definitions cannot contain circular references.");
- }
-
- if (!Array.isArray(value)) {
- const prototype = Object.getPrototypeOf(value);
-
- if (prototype !== Object.prototype && prototype !== null) {
- throw new Error("Query definitions must contain only plain objects.");
- }
- }
-
- seen.add(value);
-
- const result = Array.isArray(value)
- ? value.map((item) => canonicalize(item, seen))
- : Object.fromEntries(
- Object.entries(value)
- .sort(([first], [second]) => {
- if (first < second) {
- return -1;
- }
- if (first > second) {
- return 1;
- }
- return 0;
- })
- .map(([key, item]) => [key, canonicalize(item, seen)]),
- );
-
- seen.delete(value);
-
- return result;
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/discover.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/discover.ts
deleted file mode 100644
index 371bfbc6db7..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/discover.ts
+++ /dev/null
@@ -1,229 +0,0 @@
-import { createRequire } from "node:module";
-import path from "node:path";
-
-import { build } from "esbuild";
-
-import {
- ACTION_DEFINITIONS,
- type DefinitionKind,
- QUERY_DEFINITIONS,
- type QuerySource,
- findDefinitionSources,
-} from "./ast/query-source";
-import { canonicalJson, getQueryFingerprint } from "./canonical";
-import { isPositiveInteger, isRecord } from "./guards";
-import { getRelativeDefinitionLocation } from "./messages";
-import type { DiscoveredAction, DiscoveredQuery } from "./types";
-
-interface EvaluatedDefinition extends QuerySource {
- value: Record<string, unknown>;
-}
-
-async function evaluateModule(filePath: string) {
- const result = await build({
- absWorkingDir: path.dirname(filePath),
- bundle: true,
- entryPoints: [filePath],
- format: "cjs",
- packages: "external",
- platform: "node",
- target: "node20",
- write: false,
- logLevel: "silent",
- });
-
- const compiled = result.outputFiles[0]?.text;
-
- if (!compiled) {
- throw new Error(`Could not evaluate ${filePath}.`);
- }
-
- const runtimeModule: { exports: Record<string, unknown> } = { exports: {} };
- const runtimeRequire = createRequire(filePath);
-
- new Function("require", "module", "exports", compiled)(
- runtimeRequire,
- runtimeModule,
- runtimeModule.exports,
- );
-
- return runtimeModule.exports;
-}
-
-function positiveId(value: unknown, location: string, idKey: string) {
- if (value === undefined) {
- return undefined;
- }
-
- if (!isPositiveInteger(value)) {
- throw new Error(`${location} has an invalid ${idKey}.`);
- }
-
- return value;
-}
-
-/**
- * Evaluates every definition of `kind`, proving each one is deterministic so a
- * generated ID always describes the same authored value.
- */
-async function evaluateDefinitions(
- appRoot: string,
- kind: DefinitionKind,
-): Promise<EvaluatedDefinition[]> {
- const sourcesByFile = new Map<string, QuerySource[]>();
-
- for (const source of findDefinitionSources(appRoot, kind)) {
- sourcesByFile.set(source.filePath, [
- ...(sourcesByFile.get(source.filePath) ?? []),
- source,
- ]);
- }
-
- const evaluated: EvaluatedDefinition[] = [];
-
- for (const [filePath, fileSources] of sourcesByFile) {
- const [first, second] = await Promise.all([
- evaluateModule(filePath),
- evaluateModule(filePath),
- ]);
-
- for (const { exportName } of fileSources) {
- const value = first[exportName];
- const repeatedValue = second[exportName];
-
- const location = getRelativeDefinitionLocation(appRoot, {
- filePath,
- exportName,
- });
-
- if (!isRecord(value)) {
- throw new Error(
- `${location} did not evaluate to ${kind.description} object.`,
- );
- }
-
- let deterministic: boolean;
- try {
- deterministic = canonicalJson(value) === canonicalJson(repeatedValue);
- } catch (error) {
- throw new Error(
- `${location} could not be canonicalized: ${String(error)}`,
- );
- }
-
- if (!deterministic) {
- throw new Error(`${location} is not deterministic.`);
- }
-
- evaluated.push({ exportName, filePath, value });
- }
- }
-
- return evaluated;
-}
-
-/**
- * Rejects two definitions claiming the same ID, which would otherwise let one
- * copied definition silently take ownership of another's Metabase entity.
- */
-function assertUniqueIds(
- entries: Array<{ id: number | undefined; location: string }>,
- subject: string,
-) {
- const byId = new Map<number, string[]>();
-
- for (const { id, location } of entries) {
- if (id) {
- byId.set(id, [...(byId.get(id) ?? []), location]);
- }
- }
-
- for (const [id, locations] of byId) {
- if (locations.length > 1) {
- throw new Error(
- `${subject} ${id} is referenced by ${locations.join(", ")}. Remove the ID from the copied definition and sync again.`,
- );
- }
- }
-}
-
-export async function discoverQueries(
- appRoot: string,
-): Promise<DiscoveredQuery[]> {
- const definitions = await evaluateDefinitions(appRoot, QUERY_DEFINITIONS);
-
- const discovered = definitions.map(({ exportName, filePath, value }) => {
- const { tableId, hash } = getQueryFingerprint(value);
-
- return {
- exportName,
- filePath,
- query: value,
- savedQuestionSourceId: positiveId(
- value[QUERY_DEFINITIONS.idKey],
- getRelativeDefinitionLocation(appRoot, { filePath, exportName }),
- QUERY_DEFINITIONS.idKey,
- ),
- tableId,
- hash,
- };
- });
-
- assertUniqueIds(
- discovered.map((query) => ({
- id: query.savedQuestionSourceId,
- location: getRelativeDefinitionLocation(appRoot, query),
- })),
- "Saved question",
- );
-
- return discovered;
-}
-
-export async function discoverActions(
- appRoot: string,
-): Promise<DiscoveredAction[]> {
- const definitions = await evaluateDefinitions(appRoot, ACTION_DEFINITIONS);
-
- const discovered = definitions.map(({ exportName, filePath, value }) => {
- const location = getRelativeDefinitionLocation(appRoot, {
- filePath,
- exportName,
- });
- const action = value.action;
-
- if (!isRecord(action) || !isPositiveInteger(action.id)) {
- throw new Error(
- `${location} must reference a generated action, such as \`schema.actions.<action>\`.`,
- );
- }
-
- return {
- exportName,
- filePath,
- copiedActionId: positiveId(
- value[ACTION_DEFINITIONS.idKey],
- location,
- ACTION_DEFINITIONS.idKey,
- ),
- sourceActionId: action.id,
- };
- });
-
- assertUniqueIds(
- discovered.map((action) => ({
- id: action.sourceActionId,
- location: getRelativeDefinitionLocation(appRoot, action),
- })),
- "Action",
- );
- assertUniqueIds(
- discovered.map((action) => ({
- id: action.copiedActionId,
- location: getRelativeDefinitionLocation(appRoot, action),
- })),
- "Generated action",
- );
-
- return discovered;
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/env.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/env.ts
deleted file mode 100644
index cc908a52ddc..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/env.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-import { parseEnv } from "node:util";
-
-import { findEnvRoot } from "../data-app-dev/config/find-env-root";
-
-function parseEnvFile(filePath: string) {
- if (!fs.existsSync(filePath)) {
- return {};
- }
- return parseEnv(fs.readFileSync(filePath, "utf8"));
-}
-
-export function getResourceSyncCredentials(appRoot: string) {
- const values = {
- ...parseEnvFile(path.join(findEnvRoot(appRoot), ".env.local")),
- ...process.env,
- };
- const metabaseUrl = values.DATA_APP_MB_URL;
- const apiKey = values.DATA_APP_MB_API_KEY;
- if (!metabaseUrl || !apiKey) {
- throw new Error(
- "DATA_APP_MB_URL and DATA_APP_MB_API_KEY must be set in .env.local.",
- );
- }
- return { metabaseUrl, apiKey };
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/guards.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/guards.ts
deleted file mode 100644
index de7346b74c4..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/guards.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/** Metabase IDs are always positive integers, so anything else is corrupt input. */
-export function isPositiveInteger(value: unknown): value is number {
- return typeof value === "number" && Number.isInteger(value) && value > 0;
-}
-
-/** A plain object, as distinct from an array or null. */
-export const isRecord = (value: unknown): value is Record<string, unknown> =>
- value !== null && typeof value === "object" && !Array.isArray(value);
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/lockfile.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/lockfile.ts
deleted file mode 100644
index 9a424804cb9..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/lockfile.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-
-import { isPositiveInteger, isRecord } from "./guards";
-import type {
- ActionLockEntry,
- MetricLockEntry,
- QueryLockEntry,
- ResourceLockfile,
-} from "./types";
-
-export const RESOURCE_LOCKFILE = "resources_metadata.json";
-
-const HASH_PATTERN = /^v1:sha256:[0-9a-f]{64}$/;
-
-function isHash(value: unknown): value is string {
- return typeof value === "string" && HASH_PATTERN.test(value);
-}
-
-function isQueryLockEntry(value: unknown): value is QueryLockEntry {
- return (
- isRecord(value) &&
- isPositiveInteger(value.tableId) &&
- isPositiveInteger(value.savedQuestionSourceId) &&
- isHash(value.hash)
- );
-}
-
-function isActionLockEntry(value: unknown): value is ActionLockEntry {
- return (
- isRecord(value) &&
- isPositiveInteger(value.sourceActionId) &&
- isPositiveInteger(value.copiedActionId) &&
- isHash(value.hash)
- );
-}
-
-function isMetricLockEntry(value: unknown): value is MetricLockEntry {
- return (
- isRecord(value) &&
- isPositiveInteger(value.sourceMetricId) &&
- isPositiveInteger(value.copiedMetricId) &&
- isHash(value.hash)
- );
-}
-
-function parseMetrics(value: unknown): MetricLockEntry[] {
- if (value === undefined) {
- return [];
- }
-
- if (
- !Array.isArray(value) ||
- value.some((entry) => !isMetricLockEntry(entry))
- ) {
- throw new Error(`${RESOURCE_LOCKFILE} contains an invalid metric entry.`);
- }
-
- assertUnique(
- value.map((entry) => entry.sourceMetricId),
- "source metric ID",
- );
-
- assertUnique(
- value.map((entry) => entry.copiedMetricId),
- "copied metric ID",
- );
-
- return value;
-}
-
-function assertUnique(ids: number[], subject: string) {
- if (new Set(ids).size !== ids.length) {
- throw new Error(`${RESOURCE_LOCKFILE} contains a duplicate ${subject}.`);
- }
-}
-
-function parseQueries(value: unknown): QueryLockEntry[] {
- if (
- !Array.isArray(value) ||
- value.some((entry) => !isQueryLockEntry(entry))
- ) {
- throw new Error(`${RESOURCE_LOCKFILE} contains an invalid entry.`);
- }
-
- const queries: QueryLockEntry[] = value;
-
- assertUnique(
- queries.map((entry) => entry.savedQuestionSourceId),
- "saved question ID",
- );
-
- return queries;
-}
-
-function parseActions(value: unknown): ActionLockEntry[] {
- if (value === undefined) {
- return [];
- }
-
- if (
- !Array.isArray(value) ||
- value.some((entry) => !isActionLockEntry(entry))
- ) {
- throw new Error(`${RESOURCE_LOCKFILE} contains an invalid action entry.`);
- }
-
- const actions: ActionLockEntry[] = value;
-
- assertUnique(
- actions.map(({ sourceActionId }) => sourceActionId),
- "source action ID",
- );
- assertUnique(
- actions.map(({ copiedActionId }) => copiedActionId),
- "copied action ID",
- );
-
- return actions;
-}
-
-export function readResourceLockfile(appRoot: string): ResourceLockfile {
- const lockfilePath = path.join(appRoot, RESOURCE_LOCKFILE);
-
- if (!fs.existsSync(lockfilePath)) {
- return { queries: [], actions: [], metrics: [] };
- }
-
- let value: unknown;
- try {
- value = JSON.parse(fs.readFileSync(lockfilePath, "utf8"));
- } catch (error) {
- throw new Error(`Could not read ${RESOURCE_LOCKFILE}: ${String(error)}`);
- }
-
- if (!isRecord(value)) {
- throw new Error(`${RESOURCE_LOCKFILE} contains an invalid entry.`);
- }
-
- if (
- value.collectionId !== undefined &&
- !isPositiveInteger(value.collectionId)
- ) {
- throw new Error(`${RESOURCE_LOCKFILE} contains an invalid collection ID.`);
- }
-
- return {
- ...(value.collectionId === undefined
- ? undefined
- : { collectionId: value.collectionId }),
- queries: parseQueries(value.queries ?? []),
- actions: parseActions(value.actions),
- metrics: parseMetrics(value.metrics),
- };
-}
-
-export function writeResourceLockfile(
- appRoot: string,
- lockfile: ResourceLockfile,
-) {
- fs.writeFileSync(
- path.join(appRoot, RESOURCE_LOCKFILE),
- `${JSON.stringify(lockfile, null, 2)}\n`,
- );
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/messages.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/messages.ts
deleted file mode 100644
index 66c6841ee81..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/messages.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import path from "node:path";
-
-export function getErrorMessage(error: unknown) {
- return error instanceof Error ? error.message : String(error);
-}
-
-export function getRelativeDefinitionLocation(
- appRoot: string,
- { filePath, exportName }: { filePath: string; exportName: string },
-) {
- return `${path.relative(appRoot, filePath)}:${exportName}`;
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/metabase-client.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/metabase-client.ts
deleted file mode 100644
index ebfcafc2f8b..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/metabase-client.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-import type {
- DataAppMetadata,
- DataAppMetric,
- MetabaseAction,
- MetabaseCard,
-} from "./types";
-
-export class MetabaseApiError extends Error {
- constructor(
- public readonly status: number,
- message: string,
- ) {
- super(message);
- }
-}
-
-/**
- * Resolves to `null` on a confirmed 404, so a caller can treat "gone" as
- * recoverable. Any other failure still throws: only a 404 proves the entity is
- * absent rather than unreachable.
- */
-export const orNullOn404 = async <T>(
- request: Promise<T>,
-): Promise<T | null> => {
- try {
- return await request;
- } catch (error) {
- if (error instanceof MetabaseApiError && error.status === 404) {
- return null;
- }
- throw error;
- }
-};
-
-export class MetabaseClient {
- constructor(
- private readonly baseUrl: string,
- private readonly apiKey: string,
- ) {}
-
- private async request<T>(pathname: string, init?: RequestInit): Promise<T> {
- const baseUrl = new URL(this.baseUrl);
- baseUrl.pathname = `${baseUrl.pathname.replace(/\/?$/, "/")}api/${pathname.replace(/^\//, "")}`;
- const requestUrl = baseUrl;
- const method = (init?.method ?? "GET").toUpperCase();
- const response = await fetch(requestUrl, {
- ...init,
- signal: init?.signal ?? AbortSignal.timeout(60_000),
- headers: {
- "content-type": "application/json",
- "x-api-key": this.apiKey,
- ...init?.headers,
- },
- });
- if (!response.ok) {
- const message = await response.text();
- throw new MetabaseApiError(
- response.status,
- // eslint-disable-next-line metabase/no-literal-metabase-strings -- CLI protocol error names the remote service.
- `Metabase returned ${response.status} for ${method} ${requestUrl}: ${message}`,
- );
- }
- if (response.status === 204) {
- // The generic return type is controlled by the caller for no-content requests.
- return undefined as T;
- }
- const body: unknown = await response.json();
- // The endpoint-specific methods define the trusted API response contract.
- return body as T;
- }
-
- ensureDraft(slug: string) {
- return this.request<DataAppMetadata>(
- `apps/${encodeURIComponent(slug)}/draft`,
- { method: "POST" },
- );
- }
-
- updateTableDependencies(slug: string, tableIds: number[]) {
- return this.request<DataAppMetadata>(
- `apps/${encodeURIComponent(slug)}/table-dependencies`,
- {
- method: "PUT",
- body: JSON.stringify({ table_ids: tableIds }),
- },
- );
- }
-
- /**
- * Resolves the tables that already-saved queries read. Only the server sees an
- * implicit join: the table a foreign key reaches appears nowhere in the query,
- * so walking its JSON would leave that table out of the app's dependencies.
- */
- async resolveTableDependencies(
- slug: string,
- datasetQueries: ReadonlyArray<Record<string, unknown>>,
- ): Promise<number[]> {
- if (datasetQueries.length === 0) {
- return [];
- }
-
- const { table_ids } = await this.request<{ table_ids: number[] }>(
- `apps/${encodeURIComponent(slug)}/query-table-dependencies`,
- {
- method: "POST",
- body: JSON.stringify({ dataset_queries: datasetQueries }),
- },
- );
-
- return table_ids;
- }
-
- async resolveQuery(slug: string, query: Record<string, unknown>) {
- const resolved = await this.request<{
- database_id: number;
- dataset_query: Record<string, unknown>;
- table_ids: number[];
- metrics?: DataAppMetric[];
- }>(`apps/${encodeURIComponent(slug)}/query`, {
- method: "POST",
- body: JSON.stringify({ stages: [query] }),
- });
- return { ...resolved, metrics: resolved.metrics ?? [] };
- }
-
- getCard(id: number) {
- return this.request<MetabaseCard>(`card/${id}`);
- }
-
- createCard(input: {
- name: string;
- collectionId: number;
- datasetQuery: Record<string, unknown>;
- }) {
- return this.request<MetabaseCard>("card", {
- method: "POST",
- body: JSON.stringify({
- name: input.name,
- type: "question",
- dataset_query: input.datasetQuery,
- display: "table",
- visualization_settings: {},
- collection_id: input.collectionId,
- }),
- });
- }
-
- updateCard(
- id: number,
- input: {
- name: string;
- collectionId: number;
- datasetQuery: Record<string, unknown>;
- },
- ) {
- return this.request<MetabaseCard>(`card/${id}`, {
- method: "PUT",
- body: JSON.stringify({
- name: input.name,
- type: "question",
- dataset_query: input.datasetQuery,
- collection_id: input.collectionId,
- archived: false,
- }),
- });
- }
-
- moveCardToCollection(id: number, collectionId: number) {
- return this.request<MetabaseCard>(`card/${id}`, {
- method: "PUT",
- body: JSON.stringify({ collection_id: collectionId }),
- });
- }
-
- deleteCard(id: number) {
- return this.request<void>(`card/${id}`, { method: "DELETE" });
- }
-
- createMetric(input: MetricInput) {
- return this.request<MetabaseCard>("card", {
- method: "POST",
- body: JSON.stringify(metricBody(input)),
- });
- }
-
- updateMetric(id: number, input: MetricInput) {
- return this.request<MetabaseCard>(`card/${id}`, {
- method: "PUT",
- body: JSON.stringify(metricBody(input)),
- });
- }
-
- getAction(id: number) {
- return this.request<MetabaseAction>(`action/${id}`);
- }
-
- createAction(body: Record<string, unknown>) {
- return this.request<MetabaseAction>("action", {
- method: "POST",
- body: JSON.stringify(body),
- });
- }
-
- updateAction(id: number, body: Record<string, unknown>) {
- return this.request<MetabaseAction>(`action/${id}`, {
- method: "PUT",
- body: JSON.stringify(body),
- });
- }
-
- deleteAction(id: number) {
- return this.request<void>(`action/${id}`, { method: "DELETE" });
- }
-}
-
-interface MetricInput {
- name: string;
- collectionId: number;
- datasetQuery: Record<string, unknown>;
- display: string;
- visualizationSettings: Record<string, unknown>;
- description: string | null;
-}
-
-const metricBody = (input: MetricInput) => ({
- name: input.name,
- type: "metric",
- archived: false,
- dataset_query: input.datasetQuery,
- display: input.display,
- visualization_settings: input.visualizationSettings,
- description: input.description,
- collection_id: input.collectionId,
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-actions.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-actions.ts
deleted file mode 100644
index 30f68662afe..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-actions.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-import { ACTION_DEFINITIONS, injectGeneratedId } from "./ast/query-source";
-import { getPayloadFingerprint } from "./canonical";
-import { isPositiveInteger } from "./guards";
-import { writeResourceLockfile } from "./lockfile";
-import { getErrorMessage, getRelativeDefinitionLocation } from "./messages";
-import type { MetabaseClient } from "./metabase-client";
-import { orNullOn404 } from "./metabase-client";
-import type {
- ActionLockEntry,
- DiscoveredAction,
- MetabaseAction,
- ResourceLockfile,
-} from "./types";
-
-export interface ReconcileActionsOptions {
- appRoot: string;
- slug: string;
- collectionId: number;
- actions: DiscoveredAction[];
- lockfile: ResourceLockfile;
- client: MetabaseClient;
- log: (message: string) => void;
-}
-
-interface ResolvedAction {
- action: DiscoveredAction;
- source: MetabaseAction;
-}
-
-function pickDefined(source: Record<string, unknown>) {
- return Object.fromEntries(
- Object.entries(source).filter(([, value]) => value !== undefined),
- );
-}
-
-/** Also the fingerprint input, so drift is measured over exactly what gets copied. */
-function actionCopyFields(source: MetabaseAction) {
- return pickDefined({
- name: source.name,
- type: source.type,
- description: source.description,
- visualization_settings: source.visualization_settings,
- parameters: source.parameters,
- parameter_mappings: source.parameter_mappings,
- dataset_query: source.dataset_query,
- database_id: source.database_id,
- });
-}
-
-async function resolveActions({
- appRoot,
- collectionId,
- actions,
- lockfile,
- client,
-}: ReconcileActionsOptions): Promise<ResolvedAction[]> {
- const copiedIds = new Set(
- lockfile.actions.map(({ copiedActionId }) => copiedActionId),
- );
-
- return Promise.all(
- actions.map(async (action) => {
- const location = getRelativeDefinitionLocation(appRoot, action);
- let source: MetabaseAction;
- try {
- // `GET /api/action/:id` filters archived actions out, so an archived
- // source surfaces here as a 404 rather than a readable payload.
- source = await client.getAction(action.sourceActionId);
- } catch (error) {
- throw new Error(
- `Could not read action ${action.sourceActionId} for ${location}: ${getErrorMessage(error)}`,
- );
- }
-
- if (isPositiveInteger(source.model_id) || source.type !== "query") {
- throw new Error(
- `${location} references action ${action.sourceActionId}, which is not a query action without a model. A data app runs only query actions that belong to no model.`,
- );
- }
-
- // A copy is synchronized state: declaring it as a source would make the
- // next run delete it once its own source is dropped.
- if (copiedIds.has(source.id) || source.collection_id === collectionId) {
- throw new Error(
- `${location} references action ${action.sourceActionId}, which is a copy synchronized into this data app. Declare the action it was copied from instead.`,
- );
- }
-
- return { action, source };
- }),
- );
-}
-
-function isOwnedActionCopy(copy: MetabaseAction, collectionId: number) {
- return (
- !isPositiveInteger(copy.model_id) && copy.collection_id === collectionId
- );
-}
-
-function assertOwnedActionCopy(
- copy: MetabaseAction,
- sourceActionId: number,
- collectionId: number,
-) {
- if (!isOwnedActionCopy(copy, collectionId)) {
- throw new Error(
- `Action ${copy.id} is the copy of action ${sourceActionId} but is no longer in data app collection ${collectionId}, so it was left untouched. Move it back or delete it manually, then run sync-resources again.`,
- );
- }
-}
-
-async function reconcileAction(
- { appRoot, collectionId, client, lockfile, log }: ReconcileActionsOptions,
- { action, source }: ResolvedAction,
-) {
- const fields = actionCopyFields(source);
- const hash = getPayloadFingerprint(fields);
- let mapping: ActionLockEntry | undefined = lockfile.actions.find(
- ({ sourceActionId }) => sourceActionId === source.id,
- );
- let copy = mapping
- ? await orNullOn404(client.getAction(mapping.copiedActionId))
- : null;
-
- if (mapping && copy) {
- assertOwnedActionCopy(copy, source.id, collectionId);
- }
-
- // A lost lockfile entry: adopt the copy the declaration still names rather
- // than leaving it behind in the app collection beside a new one.
- if (!mapping && isPositiveInteger(action.copiedActionId)) {
- const named = await orNullOn404(client.getAction(action.copiedActionId));
- const claimed = lockfile.actions.some(
- ({ copiedActionId }) => copiedActionId === action.copiedActionId,
- );
-
- if (named && !claimed && isOwnedActionCopy(named, collectionId)) {
- mapping = { sourceActionId: source.id, copiedActionId: named.id, hash };
- lockfile.actions.push(mapping);
- writeResourceLockfile(appRoot, lockfile);
- log(`adopted action: action ${source.id} -> action ${named.id}`);
- copy = named;
- }
- }
-
- if (mapping && !copy) {
- lockfile.actions.splice(lockfile.actions.indexOf(mapping), 1);
- mapping = undefined;
- }
-
- if (!mapping || !copy) {
- const created = await client.createAction({
- ...fields,
- collection_id: collectionId,
- });
-
- if (!isPositiveInteger(created.id)) {
- throw new Error("The Action API did not return a valid action ID.");
- }
-
- lockfile.actions.push({
- sourceActionId: source.id,
- copiedActionId: created.id,
- hash,
- });
-
- injectGeneratedId(action, ACTION_DEFINITIONS, created.id);
- writeResourceLockfile(appRoot, lockfile);
- log(`copied action: action ${source.id} -> action ${created.id}`);
-
- return;
- }
-
- // Fingerprint the copy rather than trusting the lockfile: that also catches
- // a copy edited directly in Metabase, which the source hash cannot see.
- if (getPayloadFingerprint(actionCopyFields(copy)) !== hash) {
- await client.updateAction(mapping.copiedActionId, fields);
- mapping.hash = hash;
- writeResourceLockfile(appRoot, lockfile);
- log(`updated action: action ${mapping.copiedActionId}`);
- }
-
- if (action.copiedActionId !== mapping.copiedActionId) {
- injectGeneratedId(action, ACTION_DEFINITIONS, mapping.copiedActionId);
- log(
- `restored action ID: ${action.exportName} -> action ${mapping.copiedActionId}`,
- );
- }
-}
-
-async function removeUnusedActions(
- { appRoot, collectionId, client, lockfile, log }: ReconcileActionsOptions,
- desiredIds: Set<number>,
-) {
- for (const mapping of [...lockfile.actions]) {
- if (desiredIds.has(mapping.sourceActionId)) {
- continue;
- }
-
- const copy = await orNullOn404(client.getAction(mapping.copiedActionId));
-
- if (copy) {
- assertOwnedActionCopy(copy, mapping.sourceActionId, collectionId);
- await client.deleteAction(mapping.copiedActionId);
- log(`deleted action: action ${mapping.copiedActionId}`);
- }
-
- lockfile.actions.splice(lockfile.actions.indexOf(mapping), 1);
- writeResourceLockfile(appRoot, lockfile);
- }
-}
-
-/**
- * Makes the data app collection hold a copy of exactly the actions the app
- * declares, copying an action when its declaration appears and deleting the
- * copy when the declaration goes away. Returns the tables those actions read.
- */
-export async function reconcileActions(options: ReconcileActionsOptions) {
- const { slug, client } = options;
- const resolved = await resolveActions(options);
-
- for (const entry of resolved) {
- await reconcileAction(options, entry);
- }
-
- await removeUnusedActions(
- options,
- new Set(resolved.map(({ source }) => source.id)),
- );
-
- return client.resolveTableDependencies(
- slug,
- resolved.flatMap(({ source }) =>
- source.dataset_query ? [source.dataset_query] : [],
- ),
- );
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-metrics.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-metrics.ts
deleted file mode 100644
index 4b7e3e69e66..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-metrics.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-import { getPayloadFingerprint } from "./canonical";
-import { isPositiveInteger, isRecord } from "./guards";
-import { writeResourceLockfile } from "./lockfile";
-import type { MetabaseClient } from "./metabase-client";
-import { orNullOn404 } from "./metabase-client";
-import { getSavedCardSourceIds } from "./saved-card-sources";
-import type { DataAppMetric, ResourceLockfile } from "./types";
-
-interface ResolvedQuery {
- dataset_query: Record<string, unknown>;
- metrics: DataAppMetric[];
-}
-
-const metricInput = (metric: DataAppMetric, collectionId: number) => ({
- name: metric.name,
- collectionId,
- datasetQuery: metric.dataset_query,
- display: metric.display ?? "table",
- visualizationSettings: metric.visualization_settings ?? {},
- description: metric.description ?? null,
-});
-
-type MetricClause = readonly [
- type: "metric",
- options: unknown,
- metricId: number,
- ...rest: unknown[],
-];
-
-// A MBQL metric clause has the form ["metric", options, metricId].
-const METRIC_ID_INDEX = 2;
-
-const isMetricCard = (value: { type: string }): value is DataAppMetric =>
- value.type === "metric";
-
-const isMetricClause = (clause: unknown): clause is MetricClause =>
- Array.isArray(clause) &&
- clause[0] === "metric" &&
- typeof clause[METRIC_ID_INDEX] === "number";
-
-function getMetricClauseIds(
- clause: unknown,
- ids = new Set<number>(),
-): Set<number> {
- if (Array.isArray(clause)) {
- if (isMetricClause(clause)) {
- ids.add(clause[METRIC_ID_INDEX]);
-
- return ids;
- }
-
- clause.forEach((item) => getMetricClauseIds(item, ids));
- } else if (isRecord(clause)) {
- Object.values(clause).forEach((item) => getMetricClauseIds(item, ids));
- }
-
- return ids;
-}
-
-/**
- * Rewrite a metric clause to
- * swap the original metric id with the copied metric id.
- */
-function rewriteMetricClause(
- [type, options, metricId, ...rest]: MetricClause,
- copiedMetricIdBySourceMetricId: Map<number, number>,
-): MetricClause {
- const copiedMetricId = copiedMetricIdBySourceMetricId.get(metricId);
-
- if (copiedMetricId === undefined) {
- throw new Error(`Missing copied metric for metric ${metricId}.`);
- }
-
- return [type, options, copiedMetricId, ...rest];
-}
-
-function rewriteMetricClauses(
- clause: unknown,
- copiedMetricIdBySourceMetricId: Map<number, number>,
-): unknown {
- if (Array.isArray(clause)) {
- if (isMetricClause(clause)) {
- return rewriteMetricClause(clause, copiedMetricIdBySourceMetricId);
- }
-
- return clause.map((item) =>
- rewriteMetricClauses(item, copiedMetricIdBySourceMetricId),
- );
- }
-
- if (clause === null || typeof clause !== "object") {
- return clause;
- }
-
- return Object.fromEntries(
- Object.entries(clause).map(([key, item]) => [
- key,
- rewriteMetricClauses(item, copiedMetricIdBySourceMetricId),
- ]),
- );
-}
-
-function removeMetricLockEntry(
- appRoot: string,
- lockfile: ResourceLockfile,
- sourceMetricId: number,
-) {
- const index = lockfile.metrics.findIndex(
- (entry) => entry.sourceMetricId === sourceMetricId,
- );
-
- if (index >= 0) {
- lockfile.metrics.splice(index, 1);
- writeResourceLockfile(appRoot, lockfile);
- }
-}
-
-type ReconcilerContext = {
- appRoot: string;
- collectionId: number;
- lockfile: ResourceLockfile;
- log: (message: string) => void;
-};
-
-export async function reconcileRemovedMetrics({
- appRoot,
- collectionId,
- previousEntries,
- liveMetricIds,
- lockfile,
- client,
- log,
-}: ReconcilerContext & {
- liveMetricIds: Set<number>;
- previousEntries: ResourceLockfile["metrics"];
-
- client: Pick<MetabaseClient, "getCard" | "deleteCard">;
-}) {
- for (const entry of previousEntries) {
- if (liveMetricIds.has(entry.sourceMetricId)) {
- continue;
- }
-
- const copiedMetric = await orNullOn404(
- client.getCard(entry.copiedMetricId),
- );
-
- if (copiedMetric?.archived === true) {
- // archived metrics are moved to the trash collection, so we cannot tell
- // whether the copied metric were moved elsewhere before being trashed.
- // leave it in trash and stop tracking it instead of permanently deleting it.
- log(`left in the trash: metric ${copiedMetric.id}`);
- } else if (copiedMetric) {
- if (
- !isMetricCard(copiedMetric) ||
- copiedMetric.collection_id !== collectionId
- ) {
- throw new Error(
- `Metric ${copiedMetric.id} is no longer in data app collection ${collectionId}. Move it back, then run sync-resources again.`,
- );
- }
-
- await client.deleteCard(copiedMetric.id);
-
- log(`deleted metric: ${copiedMetric.id}`);
- }
-
- removeMetricLockEntry(appRoot, lockfile, entry.sourceMetricId);
- }
-}
-
-export async function reconcileMetrics({
- appRoot,
- collectionId,
- resolvedQueries,
- lockfile,
- client,
- log,
-}: ReconcilerContext & {
- resolvedQueries: ResolvedQuery[];
-
- client: Pick<
- MetabaseClient,
- "getCard" | "createMetric" | "updateMetric" | "deleteCard"
- >;
-}) {
- const previousEntries = [...lockfile.metrics];
-
- const metrics = [
- ...new Map(
- resolvedQueries.flatMap(({ metrics }) =>
- metrics.map((metric) => [metric.id, metric]),
- ),
- ).values(),
- ];
-
- const liveMetricIds = new Set(metrics.map((metric) => metric.id));
-
- const missingMetricIds = [
- ...new Set(
- resolvedQueries.flatMap(({ dataset_query }) => [
- ...getMetricClauseIds(dataset_query),
- ]),
- ),
- ]
- .filter((metricId) => !liveMetricIds.has(metricId))
- .sort((a, b) => a - b);
-
- if (missingMetricIds.length > 0) {
- throw new Error(
- `These metrics are missing and cannot be reconciled: ${missingMetricIds.join(", ")}.`,
- );
- }
-
- const metricsWithSavedCardSources = metrics
- .filter((metric) => getSavedCardSourceIds(metric.dataset_query).size > 0)
- .map((metric) => metric.id)
- .sort((a, b) => a - b);
-
- if (metricsWithSavedCardSources.length > 0) {
- throw new Error(
- `Metrics with saved-card joins cannot be synchronized: ${metricsWithSavedCardSources.join(", ")}.`,
- );
- }
-
- const copiedMetricIdBySourceMetricId = new Map<number, number>();
-
- for (const metric of metrics) {
- const input = metricInput(metric, collectionId);
- const hash = getPayloadFingerprint(input);
-
- const entry = lockfile.metrics.find(
- ({ sourceMetricId }) => sourceMetricId === metric.id,
- );
-
- const copiedMetric = entry
- ? await orNullOn404(client.getCard(entry.copiedMetricId))
- : null;
-
- if (copiedMetric) {
- // track metrics that are moved out of the data app collection, but allow
- // archived metrics (moved to the trash collection) to be restored
- const isOutsideDataAppCollection =
- copiedMetric.collection_id !== collectionId &&
- copiedMetric.archived !== true;
-
- if (!isMetricCard(copiedMetric) || isOutsideDataAppCollection) {
- throw new Error(
- `Metric ${copiedMetric.id} is not managed by data app collection ${collectionId}.`,
- );
- }
-
- const changed =
- copiedMetric.archived === true ||
- getPayloadFingerprint(metricInput(copiedMetric, collectionId)) !== hash;
-
- if (changed) {
- await client.updateMetric(copiedMetric.id, input);
- }
-
- copiedMetricIdBySourceMetricId.set(metric.id, copiedMetric.id);
-
- if (entry) {
- entry.hash = hash;
- }
-
- log(
- `${changed ? "updated" : "unchanged"} metric: ${metric.id} -> ${copiedMetric.id}`,
- );
- } else {
- const created = await client.createMetric(input);
-
- if (!isPositiveInteger(created.id)) {
- throw new Error("The copied metric does not have a valid ID.");
- }
-
- copiedMetricIdBySourceMetricId.set(metric.id, created.id);
-
- if (entry) {
- Object.assign(entry, { copiedMetricId: created.id, hash });
- } else {
- lockfile.metrics.push({
- hash,
- sourceMetricId: metric.id,
- copiedMetricId: created.id,
- });
- }
-
- log(`copied metric: ${metric.id} -> ${created.id}`);
- }
-
- writeResourceLockfile(appRoot, lockfile);
- }
-
- for (const resolved of resolvedQueries) {
- const rewrittenMetricQuery = rewriteMetricClauses(
- resolved.dataset_query,
- copiedMetricIdBySourceMetricId,
- );
-
- if (!isRecord(rewrittenMetricQuery)) {
- throw new Error("Rewritten metric query must be an object.");
- }
-
- resolved.dataset_query = rewrittenMetricQuery;
- }
-
- return { previousEntries, liveMetricIds };
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile.ts
deleted file mode 100644
index cbe94ecb983..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile.ts
+++ /dev/null
@@ -1,507 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-
-import { QUERY_DEFINITIONS, injectGeneratedId } from "./ast/query-source";
-import { getCanonicalQueryJson } from "./canonical";
-import { isPositiveInteger } from "./guards";
-import { RESOURCE_LOCKFILE, writeResourceLockfile } from "./lockfile";
-import { getErrorMessage, getRelativeDefinitionLocation } from "./messages";
-import type { MetabaseClient } from "./metabase-client";
-import { orNullOn404 } from "./metabase-client";
-import { reconcileMetrics, reconcileRemovedMetrics } from "./reconcile-metrics";
-import type {
- DiscoveredQuery,
- QueryLockEntry,
- ResourceLockfile,
-} from "./types";
-
-type QueryCard = Awaited<ReturnType<MetabaseClient["getCard"]>>;
-
-interface ResolvedQuery {
- query: DiscoveredQuery;
- resolved: Awaited<ReturnType<MetabaseClient["resolveQuery"]>>;
-}
-
-interface ReconciliationContext {
- appRoot: string;
- collectionId: number;
- client: MetabaseClient;
- lockfile: ResourceLockfile;
- recoveredIds: Map<DiscoveredQuery, number>;
- repairedLockfileIds: Set<number>;
- cardsById: Map<number, QueryCard | null>;
- log: (message: string) => void;
-}
-
-export interface ReconcileQueriesOptions {
- appRoot: string;
- slug: string;
- collectionId: number;
- queries: DiscoveredQuery[];
- lockfile: ResourceLockfile;
- client: MetabaseClient;
- log: (message: string) => void;
-}
-
-function queryWithoutGeneratedId(query: DiscoveredQuery) {
- const authored = { ...query.query };
- delete authored.savedQuestionSourceId;
- return authored;
-}
-
-function lockEntry(query: DiscoveredQuery, id: number): QueryLockEntry {
- return {
- tableId: query.tableId,
- hash: query.hash,
- savedQuestionSourceId: id,
- };
-}
-
-function replaceLockEntry(
- entries: QueryLockEntry[],
- previousId: number | undefined,
- next: QueryLockEntry,
-) {
- const index = previousId
- ? entries.findIndex(
- ({ savedQuestionSourceId }) => savedQuestionSourceId === previousId,
- )
- : -1;
- if (index >= 0) {
- entries[index] = next;
- } else {
- entries.push(next);
- }
-}
-
-function recoverMissingQueryIds(
- appRoot: string,
- queries: DiscoveredQuery[],
- previousEntries: QueryLockEntry[],
-) {
- const claimedIds = new Set(
- queries.flatMap(({ savedQuestionSourceId }) =>
- savedQuestionSourceId ? [savedQuestionSourceId] : [],
- ),
- );
- const recoveredIds = new Map<DiscoveredQuery, number>();
-
- for (const query of queries) {
- if (query.savedQuestionSourceId) {
- continue;
- }
-
- const candidates = previousEntries.filter(
- (entry) =>
- entry.tableId === query.tableId &&
- entry.hash === query.hash &&
- !claimedIds.has(entry.savedQuestionSourceId),
- );
-
- if (candidates.length > 1) {
- throw new Error(
- `${getRelativeDefinitionLocation(appRoot, query)} matches multiple lockfile entries. Restore its savedQuestionSourceId manually and run sync-resources again.`,
- );
- }
-
- const [candidate] = candidates;
-
- if (candidate) {
- recoveredIds.set(query, candidate.savedQuestionSourceId);
- claimedIds.add(candidate.savedQuestionSourceId);
- }
- }
-
- return recoveredIds;
-}
-
-function savedQuestionId(
- query: DiscoveredQuery,
- recoveredIds: Map<DiscoveredQuery, number>,
-) {
- return query.savedQuestionSourceId ?? recoveredIds.get(query);
-}
-
-async function resolveQueries(
- appRoot: string,
- slug: string,
- queries: DiscoveredQuery[],
- client: MetabaseClient,
-): Promise<ResolvedQuery[]> {
- return Promise.all(
- queries.map(async (query) => {
- try {
- return {
- query,
- resolved: await client.resolveQuery(
- slug,
- queryWithoutGeneratedId(query),
- ),
- };
- } catch (error) {
- throw new Error(
- `Could not resolve ${getRelativeDefinitionLocation(appRoot, query)}: ${getErrorMessage(error)}`,
- );
- }
- }),
- );
-}
-
-async function fetchReferencedCards(
- queries: DiscoveredQuery[],
- recoveredIds: Map<DiscoveredQuery, number>,
- client: MetabaseClient,
-) {
- const cardsById = new Map<number, QueryCard | null>();
- await Promise.all(
- queries.map(async (query) => {
- const id = savedQuestionId(query, recoveredIds);
-
- if (!id) {
- return;
- }
-
- cardsById.set(id, await orNullOn404(client.getCard(id)));
- }),
- );
- return cardsById;
-}
-
-function findLockfileRepairs(
- queries: DiscoveredQuery[],
- recoveredIds: Map<DiscoveredQuery, number>,
- entries: QueryLockEntry[],
- cardsById: Map<number, QueryCard | null>,
- collectionId: number,
-) {
- const repairs: Array<{ query: DiscoveredQuery; id: number }> = [];
-
- for (const query of queries) {
- const id = savedQuestionId(query, recoveredIds);
-
- if (!id) {
- continue;
- }
-
- const card = cardsById.get(id);
-
- if (card && card.id !== id) {
- throw new Error(
- `The Card API returned card ${card.id} when card ${id} was requested.`,
- );
- }
-
- if (!card) {
- continue;
- }
-
- const isLockfileProven = entries.some(
- ({ savedQuestionSourceId }) => savedQuestionSourceId === id,
- );
-
- if (isLockfileProven) {
- if (card.type !== "question") {
- throw new Error(`Card ${id} is no longer a saved question.`);
- }
-
- continue;
- }
-
- if (card.archived === true) {
- throw new Error(
- `${query.exportName} references card ${id}, which is in the trash. Restore it to data app collection ${collectionId} to publish it again, or drop \`savedQuestionSourceId: ${id}\` from the declaration to publish a new copy, then run sync-resources again.`,
- );
- }
-
- if (card.type !== "question" || card.collection_id !== collectionId) {
- throw new Error(
- `${query.exportName} references card ${id}, but the lockfile does not prove ownership and the card cannot be safely adopted.`,
- );
- }
-
- repairs.push({ query, id });
- }
-
- return repairs;
-}
-
-function applyLockfileRepairs(
- appRoot: string,
- lockfile: ResourceLockfile,
- repairs: Array<{ query: DiscoveredQuery; id: number }>,
-) {
- const repairedIds = new Set<number>();
-
- for (const { query, id } of repairs) {
- lockfile.queries.push(lockEntry(query, id));
- writeResourceLockfile(appRoot, lockfile);
- repairedIds.add(id);
- }
-
- return repairedIds;
-}
-
-function queriesMatch(card: QueryCard, resolved: ResolvedQuery["resolved"]) {
- return (
- getCanonicalQueryJson(card.dataset_query) ===
- getCanonicalQueryJson(resolved.dataset_query)
- );
-}
-
-function logExistingCardOutcome(
- context: ReconciliationContext,
- query: DiscoveredQuery,
- card: QueryCard,
- existingEntry: QueryLockEntry,
- needsUpdate: boolean,
-) {
- const { recoveredIds, repairedLockfileIds, log } = context;
- const recoveredId = recoveredIds.get(query);
-
- if (needsUpdate) {
- const authoredChanged =
- existingEntry.tableId !== query.tableId ||
- existingEntry.hash !== query.hash;
- const action =
- authoredChanged || card.name !== query.exportName
- ? "updated"
- : "restored";
- const checkpoint = recoveredId
- ? "restored source ID, "
- : repairedLockfileIds.has(card.id)
- ? "repaired lockfile, "
- : "";
-
- log(`${checkpoint}${action}: card ${card.id}`);
- } else if (recoveredId) {
- log(`restored source ID: ${query.exportName} -> card ${card.id}`);
- } else if (repairedLockfileIds.has(card.id)) {
- log(`repaired lockfile: ${query.exportName} -> card ${card.id}`);
- } else {
- log(`unchanged: card ${card.id}`);
- }
-}
-
-async function reconcileLiveQuery(
- context: ReconciliationContext,
- { query, resolved }: ResolvedQuery,
-) {
- const { appRoot, collectionId, client, lockfile, recoveredIds, cardsById } =
- context;
- const authoritative = {
- name: query.exportName,
- collectionId,
- datasetQuery: resolved.dataset_query,
- };
- const recoveredId = recoveredIds.get(query);
- const previousId = savedQuestionId(query, recoveredIds);
- const card = previousId ? cardsById.get(previousId) : null;
-
- if (!card) {
- const created = await client.createCard(authoritative);
-
- if (!isPositiveInteger(created.id)) {
- throw new Error("The Card API did not return a valid saved question ID.");
- }
-
- injectGeneratedId(query, QUERY_DEFINITIONS, created.id);
- replaceLockEntry(
- lockfile.queries,
- previousId,
- lockEntry(query, created.id),
- );
- writeResourceLockfile(appRoot, lockfile);
- context.log(
- previousId
- ? `recreated: card ${previousId} -> card ${created.id}`
- : `created: ${query.exportName} -> card ${created.id}`,
- );
-
- return created.id;
- }
-
- if (recoveredId) {
- injectGeneratedId(query, QUERY_DEFINITIONS, recoveredId);
- }
-
- const existingEntry = lockfile.queries.find(
- ({ savedQuestionSourceId }) => savedQuestionSourceId === card.id,
- );
-
- if (!existingEntry) {
- throw new Error(
- `${query.exportName} references card ${card.id}, but the lockfile does not prove ownership.`,
- );
- }
-
- if (card.type !== "question") {
- throw new Error(`Card ${card.id} is no longer a saved question.`);
- }
-
- const needsUpdate =
- card.name !== query.exportName ||
- card.collection_id !== collectionId ||
- // A copy trashed on its own keeps its collection, so only `archived` says so.
- card.archived === true ||
- !queriesMatch(card, resolved);
-
- if (needsUpdate) {
- await client.updateCard(card.id, authoritative);
- }
-
- logExistingCardOutcome(context, query, card, existingEntry, needsUpdate);
- replaceLockEntry(lockfile.queries, card.id, lockEntry(query, card.id));
- writeResourceLockfile(appRoot, lockfile);
-
- return card.id;
-}
-
-async function reconcileLiveQueries(
- context: ReconciliationContext,
- resolvedQueries: ResolvedQuery[],
-) {
- const liveIds = new Set<number>();
-
- for (const resolvedQuery of resolvedQueries) {
- liveIds.add(await reconcileLiveQuery(context, resolvedQuery));
- }
-
- return liveIds;
-}
-
-function removeLockEntry(
- appRoot: string,
- lockfile: ResourceLockfile,
- id: number,
-) {
- const index = lockfile.queries.findIndex(
- ({ savedQuestionSourceId }) => savedQuestionSourceId === id,
- );
-
- if (index >= 0) {
- lockfile.queries.splice(index, 1);
- writeResourceLockfile(appRoot, lockfile);
- }
-}
-
-async function reconcileRemovedQueries(
- context: ReconciliationContext,
- previousEntries: QueryLockEntry[],
- liveIds: Set<number>,
-) {
- const { appRoot, collectionId, client, lockfile, log } = context;
- for (const entry of previousEntries) {
- if (liveIds.has(entry.savedQuestionSourceId)) {
- continue;
- }
-
- const card = await orNullOn404(client.getCard(entry.savedQuestionSourceId));
-
- if (!card) {
- removeLockEntry(appRoot, lockfile, entry.savedQuestionSourceId);
-
- continue;
- }
-
- // The trash masks a card's collection, so a copy trashed from the app
- // collection reads the same as one moved out and trashed afterwards. Stop
- // tracking it either way: deleting is permanent, and the card is already
- // where someone put it to be deleted.
- if (card.archived === true) {
- removeLockEntry(appRoot, lockfile, card.id);
- log(`left in the trash: card ${card.id}`);
-
- continue;
- }
-
- if (card.type !== "question" || card.collection_id !== collectionId) {
- const recovery =
- card.type === "question"
- ? `Move card ${card.id} back to data app collection ${collectionId} or delete it manually`
- : `Change card ${card.id} back to a saved question in data app collection ${collectionId} or delete it manually`;
-
- throw new Error(
- `Card ${card.id} belongs to a removed query but is no longer an owned question in the data app collection, so it was left untouched. ${recovery}, then run sync-resources again.`,
- );
- }
-
- await client.deleteCard(card.id);
-
- removeLockEntry(appRoot, lockfile, card.id);
- log(`deleted: card ${card.id}`);
- }
-}
-
-export async function reconcileQueries({
- appRoot,
- slug,
- collectionId,
- queries,
- lockfile,
- client,
- log,
-}: ReconcileQueriesOptions) {
- const previousEntries = [...lockfile.queries];
- const recoveredIds = recoverMissingQueryIds(
- appRoot,
- queries,
- previousEntries,
- );
- const resolvedQueries = await resolveQueries(appRoot, slug, queries, client);
- const metricReconciliation = await reconcileMetrics({
- appRoot,
- collectionId,
- resolvedQueries: resolvedQueries.map(({ resolved }) => resolved),
- lockfile,
- client,
- log,
- });
- const cardsById = await fetchReferencedCards(queries, recoveredIds, client);
- const repairs = findLockfileRepairs(
- queries,
- recoveredIds,
- lockfile.queries,
- cardsById,
- collectionId,
- );
- const repairedLockfileIds = applyLockfileRepairs(appRoot, lockfile, repairs);
- const context: ReconciliationContext = {
- appRoot,
- collectionId,
- client,
- lockfile,
- recoveredIds,
- repairedLockfileIds,
- cardsById,
- log,
- };
- const liveIds = await reconcileLiveQueries(context, resolvedQueries);
-
- await reconcileRemovedMetrics({
- appRoot,
- collectionId,
- ...metricReconciliation,
- lockfile,
- client,
- log,
- });
- await reconcileRemovedQueries(context, previousEntries, liveIds);
-
- if (!fs.existsSync(path.join(appRoot, RESOURCE_LOCKFILE))) {
- writeResourceLockfile(appRoot, lockfile);
- }
-
- const queryTableIds = resolvedQueries.flatMap(
- ({ resolved }) => resolved.table_ids,
- );
- const metricTableIds = await client.resolveTableDependencies(
- slug,
- resolvedQueries.flatMap(({ resolved }) =>
- resolved.metrics.map((metric) => metric.dataset_query),
- ),
- );
-
- return [...new Set([...queryTableIds, ...metricTableIds])].sort(
- (a, b) => a - b,
- );
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/saved-card-sources.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/saved-card-sources.ts
deleted file mode 100644
index 2155e6caf5f..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/saved-card-sources.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { isPositiveInteger, isRecord } from "./guards";
-
-/**
- * Finds saved-question IDs used as sources anywhere in a query, including joins and nested stages.
- * Supports `source-card` IDs and legacy `source-table: "card__<id>"` references.
- */
-export function getSavedCardSourceIds(
- query: unknown,
- ids = new Set<number>(),
-): Set<number> {
- if (Array.isArray(query)) {
- query.forEach((item) => getSavedCardSourceIds(item, ids));
- } else if (isRecord(query)) {
- Object.entries(query).forEach(([key, value]) => {
- if (key === "source-card" && isPositiveInteger(value)) {
- ids.add(value);
- } else if (key === "source-table" && typeof value === "string") {
- const match = /^card__(\d+)$/.exec(value);
- const id = match && Number(match[1]);
-
- if (isPositiveInteger(id)) {
- ids.add(id);
- }
- }
-
- getSavedCardSourceIds(value, ids);
- });
- }
-
- return ids;
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/sync.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/sync.ts
deleted file mode 100644
index 2037a38db36..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/sync.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import path from "node:path";
-
-import { readManifest } from "../data-app-dev/config/read-manifest";
-
-import { discoverActions, discoverQueries } from "./discover";
-import { isPositiveInteger } from "./guards";
-import {
- RESOURCE_LOCKFILE,
- readResourceLockfile,
- writeResourceLockfile,
-} from "./lockfile";
-import { MetabaseClient, orNullOn404 } from "./metabase-client";
-import { reconcileQueries } from "./reconcile";
-import { reconcileActions } from "./reconcile-actions";
-import type { DiscoveredAction, ResourceLockfile } from "./types";
-
-export interface SyncResourcesOptions {
- appRoot: string;
- metabaseUrl: string;
- apiKey: string;
- log?: (message: string) => void;
-}
-
-function staleDefinition(
- appRoot: string,
- definition: { filePath: string; exportName: string },
-): never {
- throw new Error(
- `${path.relative(appRoot, definition.filePath)}:${definition.exportName} is not synchronized. Run \`npm run sync-resources\` and rebuild.`,
- );
-}
-
-function checkQueriesSynchronized(
- appRoot: string,
- queries: Awaited<ReturnType<typeof discoverQueries>>,
- lockfile: ResourceLockfile,
-) {
- const byId = new Map(
- lockfile.queries.map((entry) => [entry.savedQuestionSourceId, entry]),
- );
- for (const query of queries) {
- const id = query.savedQuestionSourceId;
- const entry = id ? byId.get(id) : undefined;
- if (
- !id ||
- !entry ||
- entry.tableId !== query.tableId ||
- entry.hash !== query.hash
- ) {
- staleDefinition(appRoot, query);
- }
- }
- const liveIds = new Set(
- queries.flatMap(({ savedQuestionSourceId }) =>
- savedQuestionSourceId ? [savedQuestionSourceId] : [],
- ),
- );
- if (
- lockfile.queries.some(
- ({ savedQuestionSourceId }) => !liveIds.has(savedQuestionSourceId),
- )
- ) {
- throw new Error(
- `${RESOURCE_LOCKFILE} contains a removed query. Run \`npm run sync-resources\` and rebuild.`,
- );
- }
-}
-
-function checkActionsSynchronized(
- appRoot: string,
- actions: DiscoveredAction[],
- lockfile: ResourceLockfile,
-) {
- const byId = new Map(
- lockfile.actions.map((entry) => [entry.sourceActionId, entry] as const),
- );
-
- for (const action of actions) {
- const entry = byId.get(action.sourceActionId);
-
- if (!entry || entry.copiedActionId !== action.copiedActionId) {
- staleDefinition(appRoot, action);
- }
- }
-
- const liveIds = new Set(actions.map(({ sourceActionId }) => sourceActionId));
- const hasRemovedAction = lockfile.actions.some(
- ({ sourceActionId }) => !liveIds.has(sourceActionId),
- );
-
- if (hasRemovedAction) {
- throw new Error(
- `${RESOURCE_LOCKFILE} contains a removed action. Run \`npm run sync-resources\` and rebuild.`,
- );
- }
-}
-
-export async function checkResourcesSynced(appRoot: string) {
- const [queries, actions] = await Promise.all([
- discoverQueries(appRoot),
- discoverActions(appRoot),
- ]);
- const lockfile = readResourceLockfile(appRoot);
-
- checkQueriesSynchronized(appRoot, queries, lockfile);
- checkActionsSynchronized(appRoot, actions, lockfile);
-}
-
-/**
- * Move synchronized copies when the app gets a new collection. Collection read
- * access lets app viewers run the copies. Move only copies that remain in the
- * previous synchronized collection.
- */
-async function moveCopiesToAppCollection(
- appRoot: string,
- lockfile: ResourceLockfile,
- collectionId: number,
- client: MetabaseClient,
- log: (message: string) => void,
-) {
- const previousCollectionId = lockfile.collectionId;
-
- if (previousCollectionId === collectionId) {
- return;
- }
-
- if (previousCollectionId !== undefined) {
- const copiedCardIds = [
- ...lockfile.queries.map((entry) => entry.savedQuestionSourceId),
- ...lockfile.metrics.map((entry) => entry.copiedMetricId),
- ];
-
- for (const cardId of copiedCardIds) {
- const card = await orNullOn404(client.getCard(cardId));
-
- if (card?.collection_id !== previousCollectionId) {
- continue;
- }
-
- await client.moveCardToCollection(cardId, collectionId);
- log(`moved card ${cardId} into data app collection ${collectionId}`);
- }
-
- for (const { copiedActionId } of lockfile.actions) {
- const action = await orNullOn404(client.getAction(copiedActionId));
-
- if (action?.collection_id !== previousCollectionId) {
- continue;
- }
-
- await client.updateAction(copiedActionId, {
- collection_id: collectionId,
- });
- log(
- `moved action ${copiedActionId} into data app collection ${collectionId}`,
- );
- }
- }
-
- lockfile.collectionId = collectionId;
- writeResourceLockfile(appRoot, lockfile);
-}
-
-export async function syncResources({
- appRoot,
- metabaseUrl,
- apiKey,
- log = (message) => process.stdout.write(`${message}\n`),
-}: SyncResourcesOptions) {
- const [queries, actions] = await Promise.all([
- discoverQueries(appRoot),
- discoverActions(appRoot),
- ]);
- const lockfile = readResourceLockfile(appRoot);
- const client = new MetabaseClient(metabaseUrl, apiKey);
- const slug = readManifest(appRoot)?.manifest.slug;
- if (!slug) {
- throw new Error(
- `${path.join(appRoot, "data_app.yaml")} must declare the app's "slug".`,
- );
- }
- const app = await client.ensureDraft(slug);
- if (!isPositiveInteger(app.resource_collection_id)) {
- throw new Error(`Data app ${slug} does not have a resource collection.`);
- }
-
- await moveCopiesToAppCollection(
- appRoot,
- lockfile,
- app.resource_collection_id,
- client,
- log,
- );
-
- const queryTableIds = await reconcileQueries({
- appRoot,
- slug,
- collectionId: app.resource_collection_id,
- queries,
- lockfile,
- client,
- log,
- });
- const actionTableIds = await reconcileActions({
- appRoot,
- slug,
- collectionId: app.resource_collection_id,
- actions,
- lockfile,
- client,
- log,
- });
-
- const tableIds = [...new Set([...queryTableIds, ...actionTableIds])].sort(
- (a, b) => a - b,
- );
-
- await client.updateTableDependencies(slug, tableIds);
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/canonical.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/canonical.unit.spec.ts
deleted file mode 100644
index 230d0206348..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/canonical.unit.spec.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import {
- canonicalJson,
- getCanonicalQueryJson,
- getQueryFingerprint,
-} from "../canonical";
-
-import { setupResourceSyncTests } from "./setup";
-
-describe("query canonicalization", () => {
- setupResourceSyncTests();
-
- it("uses a property-order-independent authored DSL fingerprint", () => {
- const first = getQueryFingerprint({
- source: { type: "table", id: 1 },
- limit: 5,
- });
- const second = getQueryFingerprint({
- limit: 5,
- source: { id: 2, type: "table" },
- savedQuestionSourceId: 99,
- });
- expect(first.hash).toBe(second.hash);
- expect(first.tableId).toBe(1);
- expect(second.tableId).toBe(2);
- expect(canonicalJson({ b: 1, a: 2 })).toBe('{"a":2,"b":1}');
- expect(canonicalJson({ ä: 2, z: 1 })).toBe('{"z":1,"ä":2}');
- });
-
- it("rejects non-serializable query definitions", () => {
- expect(() => canonicalJson({ value: undefined })).toThrow(
- "cannot contain undefined values",
- );
- });
-
- it("rejects unsupported values and invalid table sources", () => {
- const circular: { self?: unknown } = {};
- circular.self = circular;
-
- expect(() => canonicalJson(circular)).toThrow("circular references");
- expect(() => canonicalJson({ value: new Date() })).toThrow(
- "only plain objects",
- );
- expect(() => canonicalJson({ value: Infinity })).toThrow(
- "non-finite numbers",
- );
- expect(() => getQueryFingerprint({})).toThrow("valid table source");
- expect(() =>
- getQueryFingerprint({ source: { type: "table", id: 0 } }),
- ).toThrow("valid table source");
- });
-
- it("preserves references while normalizing generated query IDs", () => {
- const queryWithGeneratedIds = (
- firstId: string,
- secondId: string,
- orderById: string,
- ) => ({
- stages: [
- {
- aggregation: [
- ["sum", { "lib/uuid": firstId }, ["field", {}, 1]],
- ["sum", { "lib/uuid": secondId }, ["field", {}, 2]],
- ],
- "order-by": [["desc", {}, ["aggregation", {}, orderById]]],
- },
- ],
- });
- const normalized = (value: unknown) => getCanonicalQueryJson(value);
- const first = queryWithGeneratedIds("first-a", "second-a", "second-a");
- const same = queryWithGeneratedIds("first-b", "second-b", "second-b");
- const different = queryWithGeneratedIds("first-c", "second-c", "first-c");
-
- expect(normalized(first)).toBe(normalized(same));
- expect(normalized(first)).not.toBe(normalized(different));
- });
-
- it("omits empty lib/metadata from query", () => {
- expect(
- getCanonicalQueryJson({
- database: 1,
- stages: [],
- "lib/metadata": null,
- }),
- ).toBe(getCanonicalQueryJson({ database: 1, stages: [] }));
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/discover.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/discover.unit.spec.ts
deleted file mode 100644
index fa6c372eebf..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/discover.unit.spec.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-import fs from "node:fs";
-
-import {
- ACTION_DEFINITIONS,
- QUERY_DEFINITIONS,
- injectGeneratedId,
-} from "../ast/query-source";
-import { discoverActions, discoverQueries } from "../discover";
-import { checkResourcesSynced } from "../sync";
-
-import {
- FAKE_HASH,
- makeApp,
- setupResourceSyncTests,
- writeAction,
- writeQuery,
- writeQueryLockfile,
-} from "./setup";
-
-describe("query discovery", () => {
- setupResourceSyncTests();
-
- it("discovers a direct named definition", async () => {
- const appRoot = makeApp();
- writeQuery(
- appRoot,
- `export const Orders = defineQuery({ savedQuestionSourceId: 10, source: { type: "table", id: 1 }, limit: 5 });`,
- );
-
- await expect(discoverQueries(appRoot)).resolves.toEqual([
- expect.objectContaining({
- exportName: "Orders",
- savedQuestionSourceId: 10,
- tableId: 1,
- hash: expect.stringMatching(/^v1:sha256:[a-f0-9]{64}$/),
- }),
- ]);
- });
-
- it("rejects copied saved question IDs", async () => {
- const appRoot = makeApp();
-
- writeQuery(
- appRoot,
- `export const First = defineQuery({ savedQuestionSourceId: 10, source: { type: "table", id: 1 } });
- export const Second = defineQuery({ savedQuestionSourceId: 10, source: { type: "table", id: 1 } });`,
- );
-
- await expect(discoverQueries(appRoot)).rejects.toThrow(
- "Saved question 10 is referenced by",
- );
- });
-
- it("replaces a quoted saved question ID", async () => {
- const appRoot = makeApp();
- const filePath = writeQuery(
- appRoot,
- `export const Orders = defineQuery({ "savedQuestionSourceId": 10, source: { type: "table", id: 1 } });`,
- );
- const [query] = await discoverQueries(appRoot);
-
- injectGeneratedId(query, QUERY_DEFINITIONS, 20);
-
- const contents = fs.readFileSync(filePath, "utf8");
- expect(contents).toContain("savedQuestionSourceId: 20");
- expect(contents).not.toContain('savedQuestionSourceId": 10');
- });
-
- it.each([
- ["a shorthand ID", "savedQuestionSourceId"],
- ["a spread ID", "...defaults"],
- [
- "an explicit ID followed by a spread",
- "savedQuestionSourceId: 10, ...defaults",
- ],
- ])("reuses the generated query ID instead of %s", async (_, properties) => {
- const appRoot = makeApp();
-
- writeQuery(
- appRoot,
- `const savedQuestionSourceId = 10;
- const defaults = { savedQuestionSourceId };
- export const Orders = defineQuery({ ${properties}, source: { type: "table", id: 1 } });`,
- );
-
- const [query] = await discoverQueries(appRoot);
- injectGeneratedId(query, QUERY_DEFINITIONS, 20);
-
- const [updatedQuery] = await discoverQueries(appRoot);
- expect(updatedQuery.savedQuestionSourceId).toBe(20);
- injectGeneratedId(updatedQuery, QUERY_DEFINITIONS, 30);
-
- const [recoveredQuery] = await discoverQueries(appRoot);
- expect(recoveredQuery.savedQuestionSourceId).toBe(30);
- });
-
- it("fails a read-only build check when source and lockfile drift", async () => {
- const appRoot = makeApp();
-
- writeQuery(
- appRoot,
- `export const Orders = defineQuery({ savedQuestionSourceId: 10, source: { type: "table", id: 1 }, limit: 5 });`,
- );
-
- writeQueryLockfile(appRoot, [
- {
- tableId: 1,
- hash: FAKE_HASH,
- savedQuestionSourceId: 10,
- },
- ]);
-
- await expect(checkResourcesSynced(appRoot)).rejects.toThrow(
- "is not synchronized",
- );
- });
-});
-
-describe("action discovery", () => {
- setupResourceSyncTests();
-
- it("discovers named definitions and the action each references", async () => {
- const appRoot = makeApp();
-
- writeAction(
- appRoot,
- `export const Create = defineAction({ copiedActionId: 91, action: { id: 51, parameters: [] } });
- export const Update = defineAction({ action: { id: 52, parameters: [] } });`,
- );
-
- const discovered = await discoverActions(appRoot);
-
- expect(
- discovered.map(({ exportName, sourceActionId, copiedActionId }) => ({
- exportName,
- sourceActionId,
- copiedActionId,
- })),
- ).toEqual([
- { exportName: "Create", sourceActionId: 51, copiedActionId: 91 },
- { exportName: "Update", sourceActionId: 52, copiedActionId: undefined },
- ]);
- });
-
- it("reuses the generated action ID instead of shorthand and spread IDs", async () => {
- const appRoot = makeApp();
-
- writeAction(
- appRoot,
- `const copiedActionId = 91;
- const defaults = { copiedActionId };
- export const Create = defineAction({ copiedActionId, ...defaults, action: { id: 51, parameters: [] } });`,
- );
-
- const [action] = await discoverActions(appRoot);
- injectGeneratedId(action, ACTION_DEFINITIONS, 92);
-
- const [updatedAction] = await discoverActions(appRoot);
- expect(updatedAction.copiedActionId).toBe(92);
- });
-
- it("rejects two definitions claiming the same source action", async () => {
- const appRoot = makeApp();
-
- writeAction(
- appRoot,
- `export const First = defineAction({ action: { id: 51, parameters: [] } });
- export const Second = defineAction({ action: { id: 51, parameters: [] } });`,
- );
-
- await expect(discoverActions(appRoot)).rejects.toThrow(
- "Action 51 is referenced by",
- );
- });
-
- it("rejects a copied definition that carries another's generated ID", async () => {
- const appRoot = makeApp();
-
- writeAction(
- appRoot,
- `export const First = defineAction({ copiedActionId: 91, action: { id: 51, parameters: [] } });
- export const Second = defineAction({ copiedActionId: 91, action: { id: 52, parameters: [] } });`,
- );
-
- await expect(discoverActions(appRoot)).rejects.toThrow(
- "Generated action 91 is referenced by",
- );
- });
-
- it("rejects a definition that does not reference a generated action", async () => {
- const appRoot = makeApp();
-
- writeAction(
- appRoot,
- `export const Create = defineAction({ action: { name: "not a schema entry" } });`,
- );
-
- await expect(discoverActions(appRoot)).rejects.toThrow(
- "must reference a generated action",
- );
- });
-
- it("rejects a hand-edited generated ID", async () => {
- const appRoot = makeApp();
-
- writeAction(
- appRoot,
- `export const Create = defineAction({ copiedActionId: 0, action: { id: 51, parameters: [] } });`,
- );
-
- await expect(discoverActions(appRoot)).rejects.toThrow(
- "has an invalid copiedActionId",
- );
- });
-
- it("requires a definition to initialize an exported variable", async () => {
- const appRoot = makeApp();
-
- writeAction(
- appRoot,
- `const Create = defineAction({ action: { id: 51, parameters: [] } });`,
- );
-
- await expect(discoverActions(appRoot)).rejects.toThrow(
- "defineAction must directly initialize a named exported variable",
- );
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/env.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/env.unit.spec.ts
deleted file mode 100644
index 5538152f687..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/env.unit.spec.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-
-import { getResourceSyncCredentials } from "../env";
-
-import { makeApp, setupResourceSyncTests } from "./setup";
-
-describe("resource sync credentials", () => {
- setupResourceSyncTests();
-
- it("loads credentials from the repository .env.local", () => {
- const repoRoot = makeApp();
- const appRoot = path.join(repoRoot, "data_apps/orders");
- fs.mkdirSync(appRoot, { recursive: true });
- fs.writeFileSync(
- path.join(repoRoot, ".env.local"),
- "DATA_APP_MB_URL=http://metabase.test\nDATA_APP_MB_API_KEY=file-key\n",
- );
- jest.replaceProperty(process, "env", {});
-
- expect(getResourceSyncCredentials(appRoot)).toEqual({
- metabaseUrl: "http://metabase.test",
- apiKey: "file-key",
- });
- });
-
- it("prefers process environment credentials", () => {
- const appRoot = makeApp();
- fs.writeFileSync(
- path.join(appRoot, ".env.local"),
- "DATA_APP_MB_URL=http://file.test\nDATA_APP_MB_API_KEY=file-key\n",
- );
- jest.replaceProperty(process, "env", {
- DATA_APP_MB_URL: "http://process.test",
- DATA_APP_MB_API_KEY: "process-key",
- });
-
- expect(getResourceSyncCredentials(appRoot)).toEqual({
- metabaseUrl: "http://process.test",
- apiKey: "process-key",
- });
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/lockfile.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/lockfile.unit.spec.ts
deleted file mode 100644
index 2726e887a15..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/lockfile.unit.spec.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-
-import { RESOURCE_LOCKFILE, readResourceLockfile } from "../lockfile";
-import type { ResourceLockfile } from "../types";
-
-import { FAKE_HASH, makeApp, setupResourceSyncTests } from "./setup";
-
-function write(appRoot: string, value: unknown) {
- fs.writeFileSync(
- path.join(appRoot, RESOURCE_LOCKFILE),
- typeof value === "string" ? value : JSON.stringify(value),
- );
-}
-
-function query(savedQuestionSourceId: number) {
- return { tableId: 1, hash: FAKE_HASH, savedQuestionSourceId };
-}
-
-function action(sourceActionId: number, copiedActionId: number) {
- return { sourceActionId, copiedActionId, hash: FAKE_HASH };
-}
-
-describe("resource lockfile", () => {
- setupResourceSyncTests();
-
- it("reads an absent lockfile as empty", () => {
- expect(readResourceLockfile(makeApp())).toEqual({
- queries: [],
- actions: [],
- metrics: [],
- });
- });
-
- it("round-trips queries and actions", () => {
- const appRoot = makeApp();
- const lockfile: ResourceLockfile = {
- queries: [query(40)],
- actions: [action(51, 91)],
- metrics: [],
- };
- write(appRoot, lockfile);
-
- expect(readResourceLockfile(appRoot)).toEqual(lockfile);
- });
-
- it("defaults a missing actions key rather than failing", () => {
- const appRoot = makeApp();
- write(appRoot, { queries: [query(40)] });
-
- expect(readResourceLockfile(appRoot)).toEqual({
- queries: [query(40)],
- actions: [],
- metrics: [],
- });
- });
-
- // A lockfile is an ownership record: every rejection below is a file that
- // would otherwise let synchronization mutate content it cannot prove it owns.
- it.each([
- ["unparseable JSON", "{ not json", "Could not read"],
- // A bare array is the shape no version writes; accepting it would let a
- // hand-edited file silently drop every action entry.
- ["a bare array", [query(40)], "contains an invalid entry"],
- [
- "a malformed hash",
- { queries: [{ ...query(40), hash: "nope" }] },
- "contains an invalid entry",
- ],
- [
- "a non-integer saved question ID",
- { queries: [{ ...query(40), savedQuestionSourceId: 1.5 }] },
- "contains an invalid entry",
- ],
- [
- "a malformed action mapping",
- { queries: [], actions: [{ sourceActionId: 51 }] },
- "contains an invalid action entry",
- ],
- [
- "a duplicate saved question ID",
- { queries: [query(40), query(40)] },
- "duplicate saved question ID",
- ],
- [
- "a duplicate source action ID",
- { queries: [], actions: [action(51, 91), action(51, 92)] },
- "duplicate source action ID",
- ],
- [
- "a duplicate copied action ID",
- { queries: [], actions: [action(51, 91), action(52, 91)] },
- "duplicate copied action ID",
- ],
- ])("rejects %s", (_name, value, message) => {
- const appRoot = makeApp();
- write(appRoot, value);
-
- expect(() => readResourceLockfile(appRoot)).toThrow(message);
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-actions.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-actions.unit.spec.ts
deleted file mode 100644
index 9699f181470..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-actions.unit.spec.ts
+++ /dev/null
@@ -1,268 +0,0 @@
-import fs from "node:fs";
-
-import { discoverActions } from "../discover";
-import { MetabaseApiError, MetabaseClient } from "../metabase-client";
-import { reconcileActions } from "../reconcile-actions";
-import type { MetabaseAction, ResourceLockfile } from "../types";
-
-import {
- FAKE_HASH,
- makeApp,
- setupResourceSyncTests,
- writeAction,
-} from "./setup";
-
-const COLLECTION_ID = 35;
-
-const SOURCE: MetabaseAction = {
- id: 51,
- name: "Ship order",
- type: "query",
- model_id: null,
- collection_id: 7,
- description: null,
- parameters: [{ id: "id", type: "number/=" }],
- visualization_settings: {},
- dataset_query: { database: 1, stages: [] },
- database_id: 1,
-};
-
-const notFound = () => new MetabaseApiError(404, "Not found");
-
-const createMockClient = () => {
- const client = new MetabaseClient("http://localhost:3000", "test-key");
- return Object.assign(client, {
- getAction: jest.spyOn(client, "getAction"),
- createAction: jest.spyOn(client, "createAction"),
- updateAction: jest.spyOn(client, "updateAction").mockResolvedValue(SOURCE),
- deleteAction: jest.spyOn(client, "deleteAction").mockResolvedValue(),
- resolveTableDependencies: jest
- .spyOn(client, "resolveTableDependencies")
- .mockResolvedValue([4]),
- });
-};
-
-function emptyLockfile(): ResourceLockfile {
- return { queries: [], actions: [], metrics: [] };
-}
-
-async function run(
- appRoot: string,
- lockfile: ResourceLockfile,
- client: ReturnType<typeof createMockClient>,
-) {
- const log = jest.fn();
- const tableIds = await reconcileActions({
- appRoot,
- slug: "orders",
- collectionId: COLLECTION_ID,
- actions: await discoverActions(appRoot),
- lockfile,
- client,
- log,
- });
- return { tableIds, log };
-}
-
-describe("action reconciliation", () => {
- setupResourceSyncTests();
-
- it("copies a declared action into the app collection and injects the copy's id", async () => {
- const appRoot = makeApp();
- const file = writeAction(
- appRoot,
- `export const Ship = defineAction({ action: { id: 51, parameters: [] } });`,
- );
- const client = createMockClient();
- client.getAction.mockResolvedValueOnce(SOURCE);
- client.createAction.mockResolvedValue({ ...SOURCE, id: 91 });
- const lockfile = emptyLockfile();
-
- const { tableIds } = await run(appRoot, lockfile, client);
-
- expect(client.createAction).toHaveBeenCalledWith({
- name: "Ship order",
- type: "query",
- description: null,
- visualization_settings: {},
- parameters: [{ id: "id", type: "number/=" }],
- dataset_query: { database: 1, stages: [] },
- database_id: 1,
- collection_id: COLLECTION_ID,
- });
- expect(lockfile.actions).toEqual([
- { sourceActionId: 51, copiedActionId: 91, hash: expect.any(String) },
- ]);
- expect(fs.readFileSync(file, "utf8")).toContain("copiedActionId: 91");
- expect(client.resolveTableDependencies).toHaveBeenCalledWith("orders", [
- SOURCE.dataset_query,
- ]);
- expect(tableIds).toEqual([4]);
- });
-
- it("refuses an action that belongs to a model", async () => {
- const appRoot = makeApp();
- writeAction(
- appRoot,
- `export const Ship = defineAction({ action: { id: 51, parameters: [] } });`,
- );
- const client = createMockClient();
- client.getAction.mockResolvedValueOnce({ ...SOURCE, model_id: 80 });
-
- await expect(run(appRoot, emptyLockfile(), client)).rejects.toThrow(
- "which is not a query action without a model",
- );
- expect(client.createAction).not.toHaveBeenCalled();
- });
-
- it("updates a copy that drifted from its source", async () => {
- const appRoot = makeApp();
- writeAction(
- appRoot,
- `export const Ship = defineAction({ copiedActionId: 91, action: { id: 51, parameters: [] } });`,
- );
- const client = createMockClient();
- client.getAction.mockResolvedValueOnce(SOURCE).mockResolvedValueOnce({
- ...SOURCE,
- id: 91,
- name: "Old name",
- collection_id: COLLECTION_ID,
- });
- const lockfile: ResourceLockfile = {
- ...emptyLockfile(),
- actions: [{ sourceActionId: 51, copiedActionId: 91, hash: FAKE_HASH }],
- };
-
- await run(appRoot, lockfile, client);
-
- expect(client.updateAction).toHaveBeenCalledWith(
- 91,
- expect.objectContaining({ name: "Ship order" }),
- );
- expect(client.createAction).not.toHaveBeenCalled();
- });
-
- it("recreates a copy that was deleted in Metabase", async () => {
- const appRoot = makeApp();
- writeAction(
- appRoot,
- `export const Ship = defineAction({ copiedActionId: 91, action: { id: 51, parameters: [] } });`,
- );
- const client = createMockClient();
- client.getAction
- .mockResolvedValueOnce(SOURCE)
- .mockRejectedValueOnce(notFound());
- client.createAction.mockResolvedValue({ ...SOURCE, id: 92 });
- const lockfile: ResourceLockfile = {
- ...emptyLockfile(),
- actions: [{ sourceActionId: 51, copiedActionId: 91, hash: FAKE_HASH }],
- };
-
- await run(appRoot, lockfile, client);
-
- expect(lockfile.actions).toEqual([
- { sourceActionId: 51, copiedActionId: 92, hash: expect.any(String) },
- ]);
- });
-
- it("leaves a copy that moved out of the app collection untouched", async () => {
- const appRoot = makeApp();
- writeAction(
- appRoot,
- `export const Ship = defineAction({ copiedActionId: 91, action: { id: 51, parameters: [] } });`,
- );
- const client = createMockClient();
- client.getAction
- .mockResolvedValueOnce(SOURCE)
- .mockResolvedValueOnce({ ...SOURCE, id: 91, collection_id: 8 });
- const lockfile: ResourceLockfile = {
- ...emptyLockfile(),
- actions: [{ sourceActionId: 51, copiedActionId: 91, hash: FAKE_HASH }],
- };
-
- await expect(run(appRoot, lockfile, client)).rejects.toThrow(
- "is no longer in data app collection 35",
- );
- expect(client.updateAction).not.toHaveBeenCalled();
- });
-
- it("deletes the copy of an action whose declaration was removed", async () => {
- const appRoot = makeApp();
- const client = createMockClient();
- client.getAction.mockResolvedValueOnce({
- ...SOURCE,
- id: 91,
- collection_id: COLLECTION_ID,
- });
- const lockfile: ResourceLockfile = {
- ...emptyLockfile(),
- actions: [{ sourceActionId: 51, copiedActionId: 91, hash: FAKE_HASH }],
- };
-
- await run(appRoot, lockfile, client);
-
- expect(client.deleteAction).toHaveBeenCalledWith(91);
- expect(lockfile.actions).toEqual([]);
- });
-
- it("refuses a declared action that is one of the app's own copies", async () => {
- const appRoot = makeApp();
- writeAction(
- appRoot,
- `export const Ship = defineAction({ action: { id: 91, parameters: [] } });`,
- );
- const client = createMockClient();
- client.getAction.mockResolvedValueOnce({
- ...SOURCE,
- id: 91,
- collection_id: COLLECTION_ID,
- });
-
- await expect(run(appRoot, emptyLockfile(), client)).rejects.toThrow(
- "which is a copy synchronized into this data app",
- );
- expect(client.createAction).not.toHaveBeenCalled();
- expect(client.deleteAction).not.toHaveBeenCalled();
- });
-
- it("adopts the copy a declaration names when its lockfile entry was lost", async () => {
- const appRoot = makeApp();
- writeAction(
- appRoot,
- `export const Ship = defineAction({ copiedActionId: 91, action: { id: 51, parameters: [] } });`,
- );
- const client = createMockClient();
- client.getAction.mockResolvedValueOnce(SOURCE).mockResolvedValueOnce({
- ...SOURCE,
- id: 91,
- collection_id: COLLECTION_ID,
- });
- const lockfile = emptyLockfile();
-
- await run(appRoot, lockfile, client);
-
- expect(client.createAction).not.toHaveBeenCalled();
- expect(lockfile.actions).toEqual([
- { sourceActionId: 51, copiedActionId: 91, hash: expect.any(String) },
- ]);
- });
-
- it("leaves a copy that moved out of the app collection when its declaration is removed", async () => {
- const appRoot = makeApp();
- const client = createMockClient();
- client.getAction.mockResolvedValueOnce({
- ...SOURCE,
- id: 91,
- collection_id: 8,
- });
- const lockfile: ResourceLockfile = {
- ...emptyLockfile(),
- actions: [{ sourceActionId: 51, copiedActionId: 91, hash: FAKE_HASH }],
- };
-
- await expect(run(appRoot, lockfile, client)).rejects.toThrow(
- "is no longer in data app collection 35",
- );
- expect(client.deleteAction).not.toHaveBeenCalled();
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-metrics.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-metrics.unit.spec.ts
deleted file mode 100644
index 8a56bf390c1..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-metrics.unit.spec.ts
+++ /dev/null
@@ -1,487 +0,0 @@
-import { MetabaseApiError, MetabaseClient } from "../metabase-client";
-import {
- reconcileMetrics,
- reconcileRemovedMetrics,
-} from "../reconcile-metrics";
-import type { DataAppMetric, ResourceLockfile } from "../types";
-
-import { jsonResponse, makeApp, setupResourceSyncTests } from "./setup";
-
-const HASH = `v1:sha256:${"0".repeat(64)}`;
-
-const createMockClient = () => ({
- getCard: jest.fn(),
- updateMetric: jest.fn(),
- createMetric: jest.fn(),
- deleteCard: jest.fn(),
-});
-
-describe("metric reconciliation", () => {
- setupResourceSyncTests();
-
- it("does not update an unchanged copied metric", async () => {
- const client = createMockClient();
-
- client.getCard.mockResolvedValue({
- id: 404,
- name: "Lifetime value",
- type: "metric",
- collection_id: 35,
- dataset_query: { database: 1, stages: [] },
- display: "table",
- visualization_settings: {},
- description: null,
- });
-
- const lockfile: ResourceLockfile = {
- queries: [],
- actions: [],
- metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],
- };
-
- const log = jest.fn();
-
- await reconcileMetrics({
- appRoot: makeApp(),
- collectionId: 35,
- resolvedQueries: [
- {
- dataset_query: { aggregation: [["metric", {}, 251]] },
- metrics: [
- {
- id: 251,
- name: "Lifetime value",
- type: "metric",
- collection_id: 1,
- dataset_query: {
- database: 1,
- "lib/metadata": null,
- stages: [],
- },
- display: "table",
- visualization_settings: {},
- description: null,
- },
- ],
- },
- ],
- lockfile,
- client,
- log,
- });
-
- expect(client.updateMetric).not.toHaveBeenCalled();
- expect(log).toHaveBeenCalledWith("unchanged metric: 251 -> 404");
- });
-
- it("copies a missing metric and rewrites metric references", async () => {
- const client = createMockClient();
- client.createMetric.mockResolvedValue({ id: 404 });
-
- const lockfile: ResourceLockfile = {
- queries: [],
- actions: [],
- metrics: [],
- };
-
- const metric: DataAppMetric = {
- id: 251,
- name: "Lifetime value",
- type: "metric",
- collection_id: 1,
- dataset_query: { database: 1, stages: [] },
- display: "table",
- visualization_settings: {},
- description: null,
- };
-
- const resolvedQuery = {
- dataset_query: {
- stages: [{ aggregation: [["metric", {}, 251]] }],
- },
- metrics: [metric],
- };
-
- await reconcileMetrics({
- appRoot: makeApp(),
- collectionId: 35,
- resolvedQueries: [resolvedQuery],
- lockfile,
- client,
- log: jest.fn(),
- });
-
- expect(client.createMetric).toHaveBeenCalledWith({
- name: "Lifetime value",
- collectionId: 35,
- datasetQuery: { database: 1, stages: [] },
- display: "table",
- visualizationSettings: {},
- description: null,
- });
-
- expect(lockfile.metrics).toEqual([
- { sourceMetricId: 251, copiedMetricId: 404, hash: expect.any(String) },
- ]);
-
- expect(resolvedQuery.dataset_query).toEqual({
- stages: [{ aggregation: [["metric", {}, 404]] }],
- });
- });
-
- it("updates a changed copied metric", async () => {
- const client = createMockClient();
-
- client.getCard.mockResolvedValue({
- id: 404,
- name: "Old metric name",
- type: "metric",
- collection_id: 35,
- dataset_query: { database: 1, stages: [] },
- display: "table",
- visualization_settings: {},
- description: null,
- });
-
- const lockfile: ResourceLockfile = {
- queries: [],
- actions: [],
- metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],
- };
-
- await reconcileMetrics({
- appRoot: makeApp(),
- collectionId: 35,
- resolvedQueries: [
- {
- dataset_query: { aggregation: [["metric", {}, 251]] },
- metrics: [
- {
- id: 251,
- name: "Lifetime value",
- type: "metric",
- collection_id: 1,
- dataset_query: { database: 1, stages: [] },
- display: "table",
- visualization_settings: {},
- description: null,
- },
- ],
- },
- ],
- lockfile,
- client,
- log: jest.fn(),
- });
-
- expect(client.updateMetric).toHaveBeenCalledWith(404, {
- name: "Lifetime value",
- collectionId: 35,
- datasetQuery: { database: 1, stages: [] },
- display: "table",
- visualizationSettings: {},
- description: null,
- });
- });
-
- it("replaces a missing copied metric and rewrites its references", async () => {
- const client = createMockClient();
-
- client.getCard.mockRejectedValue(
- new MetabaseApiError(404, "Metric not found"),
- );
-
- client.createMetric.mockResolvedValue({ id: 405 });
-
- const lockfile: ResourceLockfile = {
- queries: [],
- actions: [],
- metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],
- };
-
- const resolvedQuery = {
- dataset_query: { stages: [{ aggregation: [["metric", {}, 251]] }] },
- metrics: [
- {
- id: 251,
- name: "Lifetime value",
- type: "metric" as const,
- collection_id: 1,
- dataset_query: { database: 1, stages: [] },
- display: "table",
- visualization_settings: {},
- description: null,
- },
- ],
- };
-
- await reconcileMetrics({
- appRoot: makeApp(),
- collectionId: 35,
- resolvedQueries: [resolvedQuery],
- lockfile,
- client,
- log: jest.fn(),
- });
-
- expect(client.createMetric).toHaveBeenCalledTimes(1);
-
- expect(lockfile.metrics).toEqual([
- { sourceMetricId: 251, copiedMetricId: 405, hash: expect.any(String) },
- ]);
-
- expect(resolvedQuery.dataset_query).toEqual({
- stages: [{ aggregation: [["metric", {}, 405]] }],
- });
- });
-
- it("fails before copying metrics when a resolved query omits a metric", async () => {
- const client = createMockClient();
-
- await expect(
- reconcileMetrics({
- appRoot: makeApp(),
- collectionId: 35,
- resolvedQueries: [
- {
- dataset_query: {
- stages: [{ aggregation: [["metric", {}, 251]] }],
- },
- metrics: [],
- },
- ],
- lockfile: { queries: [], actions: [], metrics: [] },
- client,
- log: jest.fn(),
- }),
- ).rejects.toThrow(
- "These metrics are missing and cannot be reconciled: 251.",
- );
-
- expect(client.createMetric).not.toHaveBeenCalled();
- expect(client.updateMetric).not.toHaveBeenCalled();
- });
-
- it("rejects a metric that joins a saved card", async () => {
- const client = createMockClient();
-
- await expect(
- reconcileMetrics({
- appRoot: makeApp(),
- collectionId: 35,
- resolvedQueries: [
- {
- dataset_query: {
- stages: [{ aggregation: [["metric", {}, 251]] }],
- },
- metrics: [
- {
- id: 251,
- name: "Lifetime value",
- type: "metric",
- collection_id: 1,
- dataset_query: {
- stages: [
- {
- "source-table": 1,
- joins: [{ stages: [{ "source-card": 99 }] }],
- },
- ],
- },
- display: "table",
- visualization_settings: {},
- description: null,
- },
- ],
- },
- ],
- lockfile: { queries: [], actions: [], metrics: [] },
- client,
- log: jest.fn(),
- }),
- ).rejects.toThrow(
- "Metrics with saved-card joins cannot be synchronized: 251.",
- );
-
- expect(client.createMetric).not.toHaveBeenCalled();
- expect(client.updateMetric).not.toHaveBeenCalled();
- });
-
- it("deletes a copied metric when no query references it", async () => {
- const appRoot = makeApp();
- const client = createMockClient();
-
- client.getCard.mockResolvedValue({
- id: 404,
- name: "Lifetime value",
- type: "metric",
- collection_id: 35,
- dataset_query: { database: 1, stages: [] },
- });
-
- const lockfile: ResourceLockfile = {
- queries: [],
- actions: [],
- metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],
- };
-
- const log = jest.fn();
-
- const metricReconciliation = await reconcileMetrics({
- appRoot,
- collectionId: 35,
- resolvedQueries: [],
- lockfile,
- client,
- log,
- });
-
- expect(client.deleteCard).not.toHaveBeenCalled();
-
- await reconcileRemovedMetrics({
- appRoot,
- collectionId: 35,
- ...metricReconciliation,
- lockfile,
- client,
- log,
- });
-
- expect(client.deleteCard).toHaveBeenCalledWith(404);
- expect(lockfile.metrics).toEqual([]);
- expect(log).toHaveBeenCalledWith("deleted metric: 404");
- });
-
- describe("archived and moved copies", () => {
- const metric: DataAppMetric = {
- id: 251,
- name: "Lifetime value",
- type: "metric",
- collection_id: 1,
- dataset_query: { database: 1, stages: [] },
- display: "table",
- visualization_settings: {},
- description: null,
- };
-
- let appRoot: string;
- let lockfile: ResourceLockfile;
-
- beforeEach(() => {
- appRoot = makeApp();
-
- lockfile = {
- queries: [],
- actions: [],
- metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],
- };
- });
-
- it("sends the restore payload for an unchanged archived metric", async () => {
- const copy = {
- ...metric,
- id: 404,
- collection_id: 99,
- archived: true,
- };
-
- const fetchMock = jest
- .spyOn(global, "fetch")
- .mockResolvedValueOnce(jsonResponse(copy))
- .mockResolvedValueOnce(jsonResponse({ ...copy, archived: false }));
-
- const resolvedQuery = {
- dataset_query: { aggregation: [["metric", {}, 251]] },
- metrics: [metric],
- };
-
- await reconcileMetrics({
- appRoot,
- collectionId: 35,
- resolvedQueries: [resolvedQuery],
- lockfile,
- client: new MetabaseClient("http://metabase.test", "secret"),
- log: jest.fn(),
- });
-
- expect(fetchMock).toHaveBeenCalledTimes(2);
-
- expect(fetchMock).toHaveBeenLastCalledWith(
- new URL("http://metabase.test/api/card/404"),
- expect.objectContaining({
- method: "PUT",
- body: expect.any(String),
- }),
- );
-
- expect(JSON.parse(String(fetchMock.mock.calls[1][1]?.body))).toEqual({
- name: "Lifetime value",
- type: "metric",
- archived: false,
- collection_id: 35,
- dataset_query: metric.dataset_query,
- display: "table",
- visualization_settings: {},
- description: null,
- });
- });
-
- describe("unarchived copies moved outside the app collection", () => {
- let client: ReturnType<typeof createMockClient>;
-
- beforeEach(() => {
- client = createMockClient();
-
- client.getCard.mockResolvedValue({
- ...metric,
- id: 404,
- collection_id: 99,
- archived: false,
- });
- });
-
- it("does not update a metric copy that is moved to other collection", async () => {
- await expect(
- reconcileMetrics({
- appRoot,
- collectionId: 35,
- lockfile,
- client,
- log: jest.fn(),
- resolvedQueries: [{ dataset_query: {}, metrics: [metric] }],
- }),
- ).rejects.toThrow(/data app collection 35/);
-
- expect(client.updateMetric).not.toHaveBeenCalled();
- expect(client.createMetric).not.toHaveBeenCalled();
- expect(client.deleteCard).not.toHaveBeenCalled();
-
- expect(lockfile.metrics).toEqual([
- { sourceMetricId: 251, copiedMetricId: 404, hash: HASH },
- ]);
- });
-
- it("does not delete a metric copy that is moved to other collection when its source is removed", async () => {
- await expect(
- reconcileRemovedMetrics({
- appRoot,
- collectionId: 35,
- lockfile,
- client,
- log: jest.fn(),
- previousEntries: [...lockfile.metrics],
- liveMetricIds: new Set(),
- }),
- ).rejects.toThrow(/data app collection 35/);
-
- expect(client.updateMetric).not.toHaveBeenCalled();
- expect(client.createMetric).not.toHaveBeenCalled();
- expect(client.deleteCard).not.toHaveBeenCalled();
-
- expect(lockfile.metrics).toEqual([
- { sourceMetricId: 251, copiedMetricId: 404, hash: HASH },
- ]);
- });
- });
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-upsert.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-upsert.unit.spec.ts
deleted file mode 100644
index 04de498b7f2..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-upsert.unit.spec.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-import path from "node:path";
-
-import { discoverQueries } from "../discover";
-import { syncResources } from "../sync";
-
-import {
- jsonResponse,
- makeApp,
- setupResourceSyncTests,
- writeQuery,
- writeQueryLockfile,
-} from "./setup";
-
-describe("query reconciliation upserts", () => {
- setupResourceSyncTests();
-
- it("ignores fresh generated UUIDs when comparing saved questions", async () => {
- const appRoot = makeApp();
- const slug = path.basename(appRoot);
- writeQuery(
- appRoot,
- `export const Orders = defineQuery({ savedQuestionSourceId: 35, source: { type: "table", id: 1 } });`,
- );
- const [query] = await discoverQueries(appRoot);
- writeQueryLockfile(appRoot, [
- {
- tableId: query.tableId,
- hash: query.hash,
- savedQuestionSourceId: 35,
- },
- ]);
- const queryWithAggregationUuid = (uuid: string) => ({
- database: 1,
- stages: [
- {
- aggregation: [["sum", { "lib/uuid": uuid }, ["field", {}, 1]]],
- "order-by": [["desc", {}, ["aggregation", {}, uuid]]],
- },
- ],
- });
- const requests: Array<{ method: string; pathname: string }> = [];
- const log = jest.fn();
- jest.spyOn(global, "fetch").mockImplementation(async (input, init) => {
- const pathname = new URL(String(input)).pathname;
- const method = init?.method ?? "GET";
- requests.push({ method, pathname });
- if (pathname === `/api/apps/${slug}/draft` && method === "POST") {
- return jsonResponse({ name: slug, resource_collection_id: 20 });
- }
- if (pathname === `/api/apps/${slug}/query` && method === "POST") {
- return jsonResponse({
- database_id: 1,
- dataset_query: queryWithAggregationUuid("fresh-uuid"),
- table_ids: [1],
- });
- }
- if (pathname === "/api/card/35" && method === "GET") {
- return jsonResponse({
- id: 35,
- name: "Orders",
- type: "question",
- collection_id: 20,
- dataset_query: queryWithAggregationUuid("saved-uuid"),
- });
- }
- if (pathname === "/api/card/35" && method === "PUT") {
- return jsonResponse({ id: 35 });
- }
- if (
- pathname === `/api/apps/${slug}/table-dependencies` &&
- method === "PUT"
- ) {
- return jsonResponse({ name: slug, table_ids: [1] });
- }
- throw new Error(`Unexpected ${method} ${pathname}`);
- });
-
- await syncResources({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- log,
- });
-
- expect(requests).not.toContainEqual({
- method: "PUT",
- pathname: "/api/card/35",
- });
- expect(log).toHaveBeenCalledWith("unchanged: card 35");
- });
-
- it("reports an exported query rename as an update", async () => {
- const appRoot = makeApp();
- const slug = path.basename(appRoot);
- writeQuery(
- appRoot,
- `export const RenamedOrders = defineQuery({ savedQuestionSourceId: 80, source: { type: "table", id: 1 } });`,
- );
- const [query] = await discoverQueries(appRoot);
- writeQueryLockfile(appRoot, [
- {
- tableId: query.tableId,
- hash: query.hash,
- savedQuestionSourceId: 80,
- },
- ]);
- const log = jest.fn();
- jest.spyOn(global, "fetch").mockImplementation(async (input, init) => {
- const pathname = new URL(String(input)).pathname;
- const method = init?.method ?? "GET";
- if (pathname === `/api/apps/${slug}/draft` && method === "POST") {
- return jsonResponse({ name: slug, resource_collection_id: 20 });
- }
- if (pathname === `/api/apps/${slug}/query` && method === "POST") {
- return jsonResponse({
- database_id: 1,
- dataset_query: { database: 1 },
- table_ids: [1],
- });
- }
- if (pathname === "/api/card/80" && method === "GET") {
- return jsonResponse({
- id: 80,
- name: "Orders",
- type: "question",
- collection_id: 20,
- dataset_query: { database: 1 },
- });
- }
- if (pathname === "/api/card/80" && method === "PUT") {
- return jsonResponse({ id: 80 });
- }
- if (
- pathname === `/api/apps/${slug}/table-dependencies` &&
- method === "PUT"
- ) {
- return jsonResponse({ name: slug, table_ids: [1] });
- }
-
- throw new Error(`Unexpected ${method} ${pathname}`);
- });
-
- await syncResources({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- log,
- });
-
- expect(log).toHaveBeenCalledWith("updated: card 80");
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/setup.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/setup.ts
deleted file mode 100644
index 29737731dab..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/setup.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import fs from "node:fs";
-import os from "node:os";
-import path from "node:path";
-
-export function setupResourceSyncTests(): void {
- const appRoots: string[] = [];
-
- afterEach(() => {
- jest.restoreAllMocks();
-
- appRoots.forEach((appRoot) =>
- fs.rmSync(appRoot, { recursive: true, force: true }),
- );
- });
-
- trackedAppRoots = appRoots;
-}
-
-let trackedAppRoots: string[] | undefined;
-
-export function makeApp() {
- const appRoot = fs.mkdtempSync(
- path.join(os.tmpdir(), "data-app-query-sync-"),
- );
-
- trackedAppRoots?.push(appRoot);
-
- fs.mkdirSync(path.join(appRoot, "queries"));
- fs.mkdirSync(path.join(appRoot, "actions"));
- fs.writeFileSync(
- path.join(appRoot, "data_app.yaml"),
- `slug: ${path.basename(appRoot)}\n`,
- );
-
- const packageRoot = path.join(
- appRoot,
- "node_modules/@metabase/embedding-sdk-react",
- );
-
- fs.mkdirSync(packageRoot, { recursive: true });
- fs.writeFileSync(
- path.join(packageRoot, "package.json"),
- JSON.stringify({
- name: "@metabase/embedding-sdk-react",
- exports: { "./data-app": "./data-app.js" },
- }),
- );
-
- fs.writeFileSync(
- path.join(packageRoot, "data-app.js"),
- [
- "exports.defineQuery = (query) => query;",
- "exports.defineAction = (definition) => definition;",
- ].join("\n"),
- );
-
- return appRoot;
-}
-
-export function writeAction(appRoot: string, body: string) {
- const filePath = path.join(appRoot, "actions/orders.action.ts");
- fs.writeFileSync(
- filePath,
- `import { defineAction } from "@metabase/embedding-sdk-react/data-app";\n${body}\n`,
- );
- return filePath;
-}
-
-export const FAKE_HASH = `v1:sha256:${"0".repeat(64)}`;
-
-export function writeQueryLockfile(
- appRoot: string,
- queries: Array<{
- tableId: number;
- hash: string;
- savedQuestionSourceId: number;
- }>,
-) {
- fs.writeFileSync(
- path.join(appRoot, "resources_metadata.json"),
- JSON.stringify({ queries, actions: [] }),
- );
-}
-
-export function writeQuery(appRoot: string, body: string) {
- const filePath = path.join(appRoot, "queries/orders.query.ts");
- fs.writeFileSync(
- filePath,
- `import { defineQuery } from "@metabase/embedding-sdk-react/data-app";\n${body}\n`,
- );
- return filePath;
-}
-
-export function jsonResponse(body: unknown, status = 200) {
- return new Response(status === 204 ? null : JSON.stringify(body), {
- status,
- headers: { "content-type": "application/json" },
- });
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/sync.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/sync.unit.spec.ts
deleted file mode 100644
index f81667f096f..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/sync.unit.spec.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-
-import { discoverQueries } from "../discover";
-import { syncResources } from "../sync";
-
-import {
- jsonResponse,
- makeApp,
- setupResourceSyncTests,
- writeQuery,
- writeQueryLockfile,
-} from "./setup";
-
-describe("query synchronization", () => {
- setupResourceSyncTests();
-
- it("synchronizes the app named by the manifest's slug, not its directory", async () => {
- const appRoot = makeApp();
- fs.writeFileSync(path.join(appRoot, "data_app.yaml"), "slug: other-app\n");
- const fetchSpy = jest.spyOn(global, "fetch").mockResolvedValue(
- new Response("Not found.", {
- status: 404,
- headers: { "content-type": "text/plain" },
- }),
- );
-
- await expect(
- syncResources({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- log: jest.fn(),
- }),
- ).rejects.toThrow(/apps\/other-app\/draft/);
- expect(String(fetchSpy.mock.calls[0][0])).toBe(
- "http://metabase.test/api/apps/other-app/draft",
- );
- });
-
- it("refuses an app whose manifest declares no slug", async () => {
- const appRoot = makeApp();
- fs.writeFileSync(path.join(appRoot, "data_app.yaml"), "name: App\n");
- const fetchSpy = jest.spyOn(global, "fetch");
-
- await expect(
- syncResources({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- log: jest.fn(),
- }),
- ).rejects.toThrow(/must declare the app's "slug"/);
- expect(fetchSpy).not.toHaveBeenCalled();
- });
-
- it("identifies the request that failed", async () => {
- const appRoot = makeApp();
- const slug = path.basename(appRoot);
- jest.spyOn(global, "fetch").mockResolvedValue(
- new Response("Not found.", {
- status: 404,
- headers: { "content-type": "text/plain" },
- }),
- );
-
- await expect(
- syncResources({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- log: jest.fn(),
- }),
- ).rejects.toThrow(
- `Metabase returned 404 for POST http://metabase.test/api/apps/${slug}/draft: Not found.`,
- );
- });
-
- it("stores an empty dependency set after synchronizing an empty app", async () => {
- const appRoot = makeApp();
- const slug = path.basename(appRoot);
- const requests: Array<{
- method: string;
- pathname: string;
- body?: string;
- }> = [];
-
- jest.spyOn(global, "fetch").mockImplementation(async (input, init) => {
- const pathname = new URL(String(input)).pathname;
- const method = init?.method ?? "GET";
- requests.push({ method, pathname, body: init?.body?.toString() });
-
- if (pathname === `/api/apps/${slug}/draft` && method === "POST") {
- return jsonResponse({ name: slug, resource_collection_id: 20 });
- }
- if (
- pathname === `/api/apps/${slug}/table-dependencies` &&
- method === "PUT"
- ) {
- return jsonResponse({ name: slug, table_ids: [] });
- }
-
- throw new Error(`Unexpected ${method} ${pathname}`);
- });
-
- await syncResources({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- log: jest.fn(),
- });
-
- expect(requests.at(-1)).toEqual({
- method: "PUT",
- pathname: `/api/apps/${slug}/table-dependencies`,
- body: JSON.stringify({ table_ids: [] }),
- });
- });
-
- it("stores the tables a copied metric reaches through a foreign key", async () => {
- const appRoot = makeApp();
- const slug = path.basename(appRoot);
- writeQuery(
- appRoot,
- `export const Orders = defineQuery({ savedQuestionSourceId: 35, source: { type: "table", id: 1 } });`,
- );
- const [query] = await discoverQueries(appRoot);
- writeQueryLockfile(appRoot, [
- { tableId: query.tableId, hash: query.hash, savedQuestionSourceId: 35 },
- ]);
-
- // Sources table 1 and groups by a table 2 column reached through a foreign
- // key, so 2 appears nowhere in the query and only the server can report it.
- const metricQuery = { database: 1, stages: [{ "source-table": 1 }] };
- const requests: Array<{
- method: string;
- pathname: string;
- body?: string;
- }> = [];
-
- jest.spyOn(global, "fetch").mockImplementation(async (input, init) => {
- const pathname = new URL(String(input)).pathname;
- const method = init?.method ?? "GET";
- requests.push({ method, pathname, body: init?.body?.toString() });
-
- if (pathname === `/api/apps/${slug}/draft` && method === "POST") {
- return jsonResponse({ name: slug, resource_collection_id: 20 });
- }
- if (pathname === `/api/apps/${slug}/query` && method === "POST") {
- return jsonResponse({
- database_id: 1,
- dataset_query: { database: 1 },
- table_ids: [1],
- metrics: [
- {
- id: 251,
- name: "Revenue",
- type: "metric",
- collection_id: 1,
- dataset_query: metricQuery,
- database_id: 1,
- display: "table",
- visualization_settings: {},
- description: null,
- },
- ],
- });
- }
- if (pathname === "/api/card" && method === "POST") {
- return jsonResponse({ id: 404 });
- }
- if (pathname === "/api/card/35" && method === "GET") {
- return jsonResponse({
- id: 35,
- name: "Orders",
- type: "question",
- collection_id: 20,
- dataset_query: { database: 1 },
- });
- }
- if (
- pathname === `/api/apps/${slug}/query-table-dependencies` &&
- method === "POST"
- ) {
- return jsonResponse({ table_ids: [1, 2] });
- }
- if (
- pathname === `/api/apps/${slug}/table-dependencies` &&
- method === "PUT"
- ) {
- return jsonResponse({ name: slug, table_ids: [1, 2] });
- }
-
- throw new Error(`Unexpected ${method} ${pathname}`);
- });
-
- await syncResources({
- appRoot,
- metabaseUrl: "http://metabase.test",
- apiKey: "secret",
- log: jest.fn(),
- });
-
- expect(requests).toContainEqual({
- method: "POST",
- pathname: `/api/apps/${slug}/query-table-dependencies`,
- body: JSON.stringify({ dataset_queries: [metricQuery] }),
- });
- expect(requests.at(-1)).toEqual({
- method: "PUT",
- pathname: `/api/apps/${slug}/table-dependencies`,
- body: JSON.stringify({ table_ids: [1, 2] }),
- });
- });
-});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/types.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/types.ts
deleted file mode 100644
index cc824a367b9..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/types.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-export interface QueryLockEntry {
- tableId: number;
- hash: string;
- savedQuestionSourceId: number;
-}
-
-export interface ActionLockEntry {
- sourceActionId: number;
- copiedActionId: number;
- hash: string;
-}
-
-export interface MetricLockEntry {
- sourceMetricId: number;
- copiedMetricId: number;
- hash: string;
-}
-
-export interface ResourceLockfile {
- /** Where the copies were last synchronized, so a moved app reads apart from a moved copy. */
- collectionId?: number;
- queries: QueryLockEntry[];
- actions: ActionLockEntry[];
- metrics: MetricLockEntry[];
-}
-
-export interface DataAppMetric extends MetabaseCard {
- type: "metric";
-}
-
-export interface DiscoveredQuery {
- exportName: string;
- filePath: string;
- query: Record<string, unknown>;
- savedQuestionSourceId?: number;
- tableId: number;
- hash: string;
-}
-
-export interface DiscoveredAction {
- exportName: string;
- filePath: string;
- copiedActionId?: number;
- sourceActionId: number;
-}
-
-export interface DataAppMetadata {
- name: string;
- resource_collection_id: number;
-}
-
-export interface MetabaseCard {
- id: number;
- name: string;
- type: string;
- collection_id: number | null;
- archived?: boolean;
- dataset_query: Record<string, unknown>;
- database_id?: number | null;
- display?: string | null;
- visualization_settings?: Record<string, unknown> | null;
- description?: string | null;
-}
-
-export interface MetabaseAction {
- id: number;
- name: string;
- type: string;
- model_id: number | null;
- collection_id?: number | null;
- archived?: boolean;
- description?: string | null;
- parameters?: unknown[] | null;
- parameter_mappings?: Record<string, unknown> | null;
- visualization_settings?: Record<string, unknown> | null;
- dataset_query?: Record<string, unknown> | null;
- database_id?: number | null;
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/README.md b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/README.md
new file mode 100644
index 00000000000..570c9a43e21
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/README.md
@@ -0,0 +1,113 @@
+# Data app resources
+
+A data app runs in a browser sandbox as one of its viewers, not as its author. Those viewers reach
+Metabase through a permission group that can read exactly one collection: the app's own. So a query
+the app runs, and an action it triggers, have to be reachable **through that collection** or they
+fail on permissions.
+
+The files of the app's collection make that true. Under the repository's `collections/data_apps/`, the
+folder of the `data-apps` collection namespace, they hold serdes YAML for the app's collection, a saved
+question per query, and copies of the actions the app runs and of the metrics its queries use. The
+author (in practice, an agent following the data-app skills) writes that YAML from the app's
+definitions. Nothing changes in Metabase until the repository is pulled: the pull loads the files as
+serialized content, like everything else the repository holds, so a local experiment can't break the
+running app, and the saved questions never get ahead of the app code that is deployed.
+
+`check-resources` reads nothing from Metabase; `print-resources` asks it for the serialization.
+
+## What an app declares
+
+Two directories at the data-app root, beside `package.json`:
+
+```
+queries/orders.query.ts export const RevenueQuery = defineQuery({ savedQuestionEntityId: "…", source: schema.tables.orders })
+actions/orders.action.ts export const CreateOrder = defineAction({ copiedActionEntityId: "…", action: schema.actions.createOrder })
+```
+
+Nothing else is scanned: definitions under `src/` are invisible to both commands, which is a common
+authoring mistake.
+
+## What the app's collection holds
+
+```
+data_apps/<slug>/data_app.yaml collection: <entity ID of the app's collection>
+collections/data_apps/<collection>.yaml the app's collection, a root collection of the data-apps namespace
+collections/data_apps/<collection>/*.yaml a saved question per query, copies of the metrics they use, and a copy of each action
+```
+
+`<collection>` is the collection's name as serialization slugs it (`data_app__sales` for `Data App: Sales`).
+The commands find the app's files by content, as a pull does: the collection whose `entity_id` the
+manifest's `collection` names, and the cards and actions whose `collection_id` is it, wherever they sit
+under `collections/data_apps/`. The repository is the directory that holds the app's `data_apps/`; an
+app that isn't under `data_apps/` is its own root, so its files sit under its own `collections/`.
+
+A data app runs only query actions that belong to no model, which the typed schema lists under
+`schema.actions`. Such an action's permissions resolve through its own collection, so making it
+reachable means copying it into the app's collection. Metrics a query uses are copied for the same
+reason, and the question reads the copy. Every saved question and copy is written from what
+`print-resources` prints, whose references are already in the form the YAML uses, with new entity IDs
+and references rewritten to the copies.
+
+## `print-resources`
+
+`embedding-sdk-react data-apps print-resources [file]` (`serialize.ts`) sends the evaluated definitions (all
+of them, or those in `file`, relative to the app directory) to `POST /api/apps/serialize-resources`, with the
+instance and API key from `.env.local`, and prints the answer as JSON: the saved question Metabase
+writes for each `defineQuery` definition, each `defineAction`'s source action, and the metrics the
+queries aggregate, all as serialization writes them, each beside the definition's file and entity ID.
+An action that belongs to a model comes back with an error. The endpoint answers only a superuser, so
+the API key must be one in the Administrators group. The saved question is complete: named after the export, in the
+collection `data_app.yaml` names, with the definition's `savedQuestionEntityId`, created by the API
+key's user, and holding the query Metabase builds with the same `createTestQuery` code the dev preview
+runs. Every entity comes in the key order serialization writes a file and without the keys serialization
+leaves unset, which the format omits, so the author transcribes rather than composes. An item that can't
+be built or copied comes back with its `error`; the rest still come back. The command refuses to run
+before `data_app.yaml` names the app's collection, since the saved questions are written into it.
+
+## `check-resources`
+
+`embedding-sdk-react data-apps check-resources` (`check.ts`) checks only what a repository pull can't:
+the pull validates the files on their own, never against the app's code. It fails, listing every
+problem, for:
+
+- a manifest that names no collection, or one whose collection has no file under
+ `collections/data_apps/`: the pull refuses the app before it loads anything;
+- a definition without its entity ID, or naming one no file in the app's collection holds, or a query
+ naming a card that isn't a question: the pull would load, and the app would fail at runtime in
+ production;
+- a question or action no definition names: the pull would load it into the app's collection, and a
+ leftover action is one more write the app's viewers can run.
+
+It runs at `buildStart` for production builds, so `npm run build` fails the same way. The YAML's format
+is `validate-schema`'s job (the template's `npm run check-resources` runs it after this check), and the rest of the resource
+rules (the collection's namespace, duplicate or foreign entity IDs, what a card or action may hold) are the pull's.
+Nothing checks that a saved question's query matches its definition.
+
+## Discovery evaluates the definitions
+
+`discover.ts` bundles every file under `queries/` (or `actions/`) into one module with esbuild,
+evaluates it, and takes every exported object as a definition: `defineQuery` and `defineAction`
+return their argument as is, and the two directories hold nothing else. A definition a second file
+re-exports keeps its identity through the single bundle, so it counts once, for the first file that
+exports it; `print-resources <file>` reads that file's exports alone, so a barrel doesn't claim them.
+Anything that isn't a definition is rejected by the serialization endpoint's schema, not here.
+
+Discovery refuses what makes a definition unusable on its own or against the others: an action that
+doesn't reference a generated action, two definitions of one source action, two claiming one entity
+ID. Every command needs that, `print-resources` included. What a definition lacks against the app's
+collection files is `check-resources`' to report. A definition's own entity ID is the exception: the saved
+question is printed with it, so `print-resources` refuses a `defineQuery` without `savedQuestionEntityId`
+and names it, and the author generates the ID with `npx representations generate-entity-id` first.
+
+## Dev preview vs production build
+
+The entity IDs only take effect in a production build. `isDataAppDev()` gates both swaps, so an app
+runs against the original table and the authored action before its resources exist:
+
+| | Dev preview | Production |
+| ------------ | ------------------- | -------------------------------------------- |
+| query source | the table | the saved question (`savedQuestionEntityId`) |
+| action | the authored action | the copy (`copiedActionEntityId`) |
+
+Both swaps live in the bundle (`toSourceInput` and `toExecutableActionId`), not in app code, so an
+author passes the definition and never branches on the environment.
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/check.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/check.ts
new file mode 100644
index 00000000000..426de64ee61
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/check.ts
@@ -0,0 +1,163 @@
+import path from "node:path";
+
+import { readManifest } from "../data-app-dev/config/read-manifest";
+
+import {
+ discoverActions,
+ discoverQueries,
+ getRelativeDefinitionLocation,
+} from "./discover";
+import {
+ type AppResources,
+ COLLECTIONS_DIR,
+ type ResourceFile,
+ readResources,
+} from "./resources";
+import type { DiscoveredAction, DiscoveredQuery } from "./types";
+
+const isQuestion = (file: ResourceFile) =>
+ file.model === "Card" && file.entity.type === "question";
+
+function definitionProblems(
+ appRoot: string,
+ queries: DiscoveredQuery[],
+ actions: DiscoveredAction[],
+ files: ResourceFile[],
+) {
+ const fileOf = (model: ResourceFile["model"], entityId: string) =>
+ files.find(
+ (file) => file.model === model && file.entity.entity_id === entityId,
+ );
+
+ const queryProblems = queries.flatMap((query) => {
+ const location = getRelativeDefinitionLocation(appRoot, query);
+ const entityId = query.savedQuestionEntityId;
+
+ if (!entityId) {
+ return [`${location} has no savedQuestionEntityId.`];
+ }
+
+ const file = fileOf("Card", entityId);
+
+ if (!file) {
+ return [
+ `${location} names saved question ${entityId}, which no file in ${COLLECTIONS_DIR}/ holds in the app's collection.`,
+ ];
+ }
+
+ return isQuestion(file)
+ ? []
+ : [`${location} names ${file.path}, which is not a question.`];
+ });
+
+ const actionProblems = actions.flatMap((action) => {
+ const location = getRelativeDefinitionLocation(appRoot, action);
+ const entityId = action.copiedActionEntityId;
+
+ if (!entityId) {
+ return [`${location} has no copiedActionEntityId.`];
+ }
+
+ return fileOf("Action", entityId)
+ ? []
+ : [
+ `${location} names action ${entityId}, which no file in ${COLLECTIONS_DIR}/ holds in the app's collection.`,
+ ];
+ });
+
+ return [...queryProblems, ...actionProblems];
+}
+
+/**
+ * A question or action no definition names is still loaded by a pull: the
+ * question and the action into the app's collection, where the action is one
+ * more write the app's viewers can run.
+ */
+function leftoverProblems(
+ queries: DiscoveredQuery[],
+ actions: DiscoveredAction[],
+ files: ResourceFile[],
+) {
+ const namedEntityIds: Record<ResourceFile["model"], Set<unknown>> = {
+ Card: new Set(queries.map((query) => query.savedQuestionEntityId)),
+ Action: new Set(actions.map((action) => action.copiedActionEntityId)),
+ };
+ const isNamed = ({ model, entity }: ResourceFile) =>
+ typeof entity.entity_id === "string" &&
+ namedEntityIds[model].has(entity.entity_id);
+
+ return files
+ .filter(
+ (file) => (isQuestion(file) || file.model === "Action") && !isNamed(file),
+ )
+ .map(
+ (file) => `${file.path} is a resource that is not referenced anywhere.`,
+ );
+}
+
+/**
+ * The app's collection files, located through the collection its manifest
+ * names, or the problem that keeps them from being located: a pull refuses a
+ * manifest that names no collection, or one whose collection the repository
+ * doesn't hold, before it loads anything.
+ */
+function locateResources(
+ appRoot: string,
+): { resources: AppResources } | { problems: string[] } {
+ const manifest = readManifest(appRoot);
+
+ if (!manifest) {
+ throw new Error(`No data_app.yaml found in ${appRoot}.`);
+ }
+
+ const collection = manifest.manifest.collection;
+
+ if (collection === undefined) {
+ return {
+ problems: [
+ `data_app.yaml names no collection. Write the app's collection under ${COLLECTIONS_DIR}/ and name its entity ID as \`collection\`.`,
+ ],
+ };
+ }
+
+ const resources = readResources(appRoot, collection);
+
+ return resources.collectionPath === undefined
+ ? {
+ problems: [
+ `data_app.yaml names collection ${collection}, which no file in ${COLLECTIONS_DIR}/ holds.`,
+ ],
+ }
+ : { resources };
+}
+
+/**
+ * Fails when the app's definitions and the files of its collection disagree in
+ * a way a repository pull can't see: the pull validates the files on their own,
+ * never against the app's code. Reads nothing from Metabase.
+ */
+export async function checkResources(appDirectory: string) {
+ const appRoot = path.resolve(appDirectory);
+ const [queries, actions] = await Promise.all([
+ discoverQueries(appRoot),
+ discoverActions(appRoot),
+ ]);
+ const located = locateResources(appRoot);
+
+ const problems =
+ "problems" in located
+ ? located.problems
+ : [
+ ...definitionProblems(
+ appRoot,
+ queries,
+ actions,
+ located.resources.files,
+ ),
+ ...leftoverProblems(queries, actions, located.resources.files),
+ ];
+
+ if (problems.length > 0) {
+ throw new Error(problems.join("\n"));
+ }
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/discover.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/discover.ts
new file mode 100644
index 00000000000..cccabfc1485
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/discover.ts
@@ -0,0 +1,286 @@
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import path from "node:path";
+
+import { build } from "esbuild";
+
+import { isEntityId, isObject } from "./guards";
+import type { DiscoveredAction, DiscoveredQuery } from "./types";
+
+/** A source-controlled definition kind, and where the CLI looks for it. */
+interface DefinitionKind {
+ directory: string;
+ idKey: string;
+}
+
+export const QUERY_DEFINITIONS: DefinitionKind = {
+ directory: "queries",
+ idKey: "savedQuestionEntityId",
+};
+
+const ACTION_DEFINITIONS: DefinitionKind = {
+ directory: "actions",
+ idKey: "copiedActionEntityId",
+};
+
+const DEFINITION_FILE_EXTENSIONS = [
+ ".js",
+ ".jsx",
+ ".ts",
+ ".tsx",
+ ".cjs",
+ ".cts",
+ ".mjs",
+ ".mts",
+];
+
+/** Where a definition is, as messages name it: `queries/orders.query.ts:Orders`. */
+export function getRelativeDefinitionLocation(
+ appRoot: string,
+ { filePath, exportName }: { filePath: string; exportName: string },
+) {
+ return `${path.relative(appRoot, filePath)}:${exportName}`;
+}
+
+interface EvaluatedDefinition {
+ exportName: string;
+ filePath: string;
+ value: Record<string, unknown>;
+}
+
+function listDefinitionFiles(directory: string): string[] {
+ if (!fs.existsSync(directory)) {
+ return [];
+ }
+
+ return fs
+ .readdirSync(directory, { recursive: true, encoding: "utf8" })
+ .filter((relativePath) =>
+ DEFINITION_FILE_EXTENSIONS.some((extension) =>
+ relativePath.endsWith(extension),
+ ),
+ )
+ .map((relativePath) => path.join(directory, relativePath))
+ .sort();
+}
+
+/**
+ * Bundles every definition file into one module and evaluates it, so a file
+ * two others import is instantiated once and its definitions keep their
+ * identity across them.
+ */
+async function evaluateFiles(directory: string, filePaths: string[]) {
+ const result = await build({
+ stdin: {
+ contents: filePaths
+ .map(
+ (filePath, index) =>
+ `export * as file${index} from ${JSON.stringify(filePath)};`,
+ )
+ .join("\n"),
+ resolveDir: directory,
+ loader: "ts",
+ },
+ absWorkingDir: directory,
+ bundle: true,
+ format: "cjs",
+ packages: "external",
+ platform: "node",
+ target: "node22",
+ write: false,
+ logLevel: "silent",
+ });
+
+ const compiled = result.outputFiles[0]?.text;
+
+ if (!compiled) {
+ throw new Error(`Could not evaluate the definitions in ${directory}.`);
+ }
+
+ const runtimeModule: { exports: Record<string, unknown> } = { exports: {} };
+
+ new Function("require", "module", "exports", compiled)(
+ createRequire(path.join(directory, "definitions.ts")),
+ runtimeModule,
+ runtimeModule.exports,
+ );
+
+ return filePaths.map((filePath, index) => ({
+ filePath,
+ exports: runtimeModule.exports[`file${index}`],
+ }));
+}
+
+/** Narrows discovery to one definition file, the one `print-resources <file>` is asked about. */
+interface DiscoveryOptions {
+ filePath?: string;
+}
+
+/**
+ * Every object a definition file exports is a definition: `defineQuery` and
+ * `defineAction` return their argument as is, and the directories hold nothing
+ * else. An object re-exported by a second file counts once, for the first file
+ * that exports it; asking for one file reads that file's exports alone, so a
+ * barrel that re-exports its definitions doesn't claim them.
+ */
+async function evaluateDefinitions(
+ appRoot: string,
+ kind: DefinitionKind,
+ { filePath: requestedFilePath }: DiscoveryOptions,
+): Promise<EvaluatedDefinition[]> {
+ const directory = path.join(appRoot, kind.directory);
+ const filePaths = listDefinitionFiles(directory);
+
+ if (filePaths.length === 0) {
+ return [];
+ }
+
+ const seen = new Set<object>();
+ const evaluated: EvaluatedDefinition[] = [];
+
+ for (const { filePath, exports } of await evaluateFiles(
+ directory,
+ filePaths,
+ )) {
+ if (requestedFilePath !== undefined && filePath !== requestedFilePath) {
+ continue;
+ }
+
+ for (const [exportName, value] of Object.entries(
+ isObject(exports) ? exports : {},
+ )) {
+ if (isObject(value) && !seen.has(value)) {
+ seen.add(value);
+ evaluated.push({ exportName, filePath, value });
+ }
+ }
+ }
+
+ return evaluated;
+}
+
+function definedEntityId(value: unknown, location: string, idKey: string) {
+ if (value === undefined) {
+ return undefined;
+ }
+
+ if (!isEntityId(value)) {
+ throw new Error(`${location} has an invalid ${idKey}.`);
+ }
+
+ return value;
+}
+
+/** Rejects two definitions claiming the same ID, as a copied definition would. */
+function assertUniqueIds(
+ entries: Array<{ id: number | string | undefined; location: string }>,
+ subject: string,
+ fix: string,
+) {
+ const byId = new Map<number | string, string[]>();
+
+ for (const { id, location } of entries) {
+ if (id !== undefined) {
+ byId.set(id, [...(byId.get(id) ?? []), location]);
+ }
+ }
+
+ for (const [id, locations] of byId) {
+ if (locations.length > 1) {
+ throw new Error(
+ `${subject} ${id} is referenced by ${locations.join(", ")}. ${fix}`,
+ );
+ }
+ }
+}
+
+export async function discoverQueries(
+ appRoot: string,
+ options: DiscoveryOptions = {},
+): Promise<DiscoveredQuery[]> {
+ const definitions = await evaluateDefinitions(
+ appRoot,
+ QUERY_DEFINITIONS,
+ options,
+ );
+
+ const discovered = definitions.map(({ exportName, filePath, value }) => ({
+ exportName,
+ filePath,
+ query: value,
+ savedQuestionEntityId: definedEntityId(
+ value[QUERY_DEFINITIONS.idKey],
+ getRelativeDefinitionLocation(appRoot, { filePath, exportName }),
+ QUERY_DEFINITIONS.idKey,
+ ),
+ }));
+
+ assertUniqueIds(
+ discovered.map((query) => ({
+ id: query.savedQuestionEntityId,
+ location: getRelativeDefinitionLocation(appRoot, query),
+ })),
+ "Saved question",
+ "Give each definition its own saved question.",
+ );
+
+ return discovered;
+}
+
+const isGeneratedActionId = (id: unknown): id is number =>
+ typeof id === "number" && Number.isInteger(id) && id > 0;
+
+export async function discoverActions(
+ appRoot: string,
+ options: DiscoveryOptions = {},
+): Promise<DiscoveredAction[]> {
+ const definitions = await evaluateDefinitions(
+ appRoot,
+ ACTION_DEFINITIONS,
+ options,
+ );
+
+ const discovered = definitions.map(({ exportName, filePath, value }) => {
+ const location = getRelativeDefinitionLocation(appRoot, {
+ filePath,
+ exportName,
+ });
+ const action = value.action;
+
+ if (!isObject(action) || !isGeneratedActionId(action.id)) {
+ throw new Error(
+ `${location} must reference a generated action, such as \`schema.actions.<action>\`.`,
+ );
+ }
+
+ return {
+ exportName,
+ filePath,
+ copiedActionEntityId: definedEntityId(
+ value[ACTION_DEFINITIONS.idKey],
+ location,
+ ACTION_DEFINITIONS.idKey,
+ ),
+ sourceActionId: action.id,
+ };
+ });
+
+ assertUniqueIds(
+ discovered.map((action) => ({
+ id: action.sourceActionId,
+ location: getRelativeDefinitionLocation(appRoot, action),
+ })),
+ "Action",
+ "Declare each action once.",
+ );
+ assertUniqueIds(
+ discovered.map((action) => ({
+ id: action.copiedActionEntityId,
+ location: getRelativeDefinitionLocation(appRoot, action),
+ })),
+ "Copied action",
+ "Give each definition its own copy.",
+ );
+
+ return discovered;
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/env.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/env.ts
new file mode 100644
index 00000000000..f93e27b40e9
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/env.ts
@@ -0,0 +1,33 @@
+import fs from "node:fs";
+import path from "node:path";
+import { parseEnv } from "node:util";
+
+import { findEnvRoot } from "../data-app-dev/config/find-env-root";
+import {
+ DATA_APP_MB_API_KEY_ENV,
+ DATA_APP_MB_URL_ENV,
+} from "../data-app-dev/constants/env";
+
+function readEnvFile(filePath: string) {
+ return fs.existsSync(filePath)
+ ? parseEnv(fs.readFileSync(filePath, "utf8"))
+ : {};
+}
+
+/** The Metabase instance and API key the dev preview uses: the repo-root `.env.local`, overridden by the environment. */
+export function getMetabaseCredentials(appRoot: string) {
+ const values = {
+ ...readEnvFile(path.join(findEnvRoot(appRoot), ".env.local")),
+ ...process.env,
+ };
+ const metabaseUrl = values[DATA_APP_MB_URL_ENV];
+ const apiKey = values[DATA_APP_MB_API_KEY_ENV];
+
+ if (!metabaseUrl || !apiKey) {
+ throw new Error(
+ `${DATA_APP_MB_URL_ENV} and ${DATA_APP_MB_API_KEY_ENV} must be set, in the repo-root .env.local or the environment.`,
+ );
+ }
+
+ return { metabaseUrl: metabaseUrl.replace(/\/+$/, ""), apiKey };
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/guards.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/guards.ts
new file mode 100644
index 00000000000..8be9e9dc7fa
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/guards.ts
@@ -0,0 +1,9 @@
+// `metabase-types/guards` and `metabase-types/api` are main-app code, which the
+// SDK package's non-CLI code can't import (`no-external-references-for-sdk-package-code`).
+
+export const isObject = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null;
+
+/** A Metabase entity ID: a 21-character NanoID. */
+export const isEntityId = (value: unknown): value is string =>
+ typeof value === "string" && /^[A-Za-z0-9_-]{21}$/.test(value);
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/resources.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/resources.ts
new file mode 100644
index 00000000000..92dd08ad2c4
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/resources.ts
@@ -0,0 +1,122 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { load as parseYaml } from "js-yaml";
+
+import { isObject } from "./guards";
+import type { ResourceModel } from "./types";
+
+/**
+ * Where the repository holds the collections of the `data-apps` namespace: an
+ * app's collection, and the saved questions and copies in it, as serialization
+ * writes them. A pull reads the files by their content, not their location, so
+ * the check does too: the app's files are the ones that name its collection.
+ */
+export const COLLECTIONS_DIR = "collections/data_apps";
+
+const RESOURCE_MODELS: readonly ResourceModel[] = ["Card", "Action"];
+
+export interface ResourceFile {
+ /** Relative to the repository root. */
+ path: string;
+ model: ResourceModel;
+ entity: Record<string, unknown>;
+}
+
+export interface AppResources {
+ /** The repository the app lives in, which `COLLECTIONS_DIR` is under. */
+ repoRoot: string;
+ /** The file of the app's collection, relative to the repository root, when one holds it. */
+ collectionPath?: string;
+ /** The cards and actions in the app's collection. */
+ files: ResourceFile[];
+}
+
+/**
+ * The repository an app lives in: the directory that holds its `data_apps/`
+ * directory. An app that isn't under `data_apps/` stands in for its own
+ * repository, so its collection files sit under its own `collections/`.
+ */
+export function repoRootOf(appRoot: string) {
+ const parent = path.dirname(appRoot);
+
+ return path.basename(parent) === "data_apps" ? path.dirname(parent) : appRoot;
+}
+
+function listYamlFiles(directory: string): string[] {
+ if (!fs.existsSync(directory)) {
+ return [];
+ }
+
+ return fs
+ .readdirSync(directory, { withFileTypes: true })
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .flatMap((entry) => {
+ const entryPath = path.join(directory, entry.name);
+
+ if (entry.isDirectory()) {
+ return listYamlFiles(entryPath);
+ }
+
+ // A pull skips hidden files, so a check that counted them could pass an
+ // app whose resources never load.
+ return entry.isFile() &&
+ !entry.name.startsWith(".") &&
+ entry.name.endsWith(".yaml")
+ ? [entryPath]
+ : [];
+ });
+}
+
+function readEntity(repoRoot: string, filePath: string) {
+ const relativePath = path.relative(repoRoot, filePath);
+
+ try {
+ const entity: unknown = parseYaml(fs.readFileSync(filePath, "utf8"));
+ return { path: relativePath, entity: isObject(entity) ? entity : {} };
+ } catch (error) {
+ throw new Error(`Could not parse ${relativePath}: ${String(error)}`);
+ }
+}
+
+/** The model a serialized entity's `serdes/meta` names, as a pull reads it. */
+function modelOf(entity: Record<string, unknown>): unknown {
+ const meta = entity["serdes/meta"];
+ const leaf = Array.isArray(meta) ? meta[meta.length - 1] : undefined;
+
+ return isObject(leaf) ? leaf.model : undefined;
+}
+
+const isResourceModel = (model: unknown): model is ResourceModel =>
+ RESOURCE_MODELS.some((resourceModel) => resourceModel === model);
+
+/**
+ * The files of the app's collection, the one with `collectionEntityId`: the
+ * collection's own file, and the cards and actions whose `collection_id` is it,
+ * wherever they sit under the repository's `collections/data_apps/`.
+ */
+export function readResources(
+ appRoot: string,
+ collectionEntityId: string,
+): AppResources {
+ const repoRoot = repoRootOf(appRoot);
+ const entities = listYamlFiles(path.join(repoRoot, COLLECTIONS_DIR)).map(
+ (filePath) => readEntity(repoRoot, filePath),
+ );
+
+ const collectionPath = entities.find(
+ ({ entity }) =>
+ modelOf(entity) === "Collection" &&
+ entity.entity_id === collectionEntityId,
+ )?.path;
+
+ const files = entities.flatMap(({ path: filePath, entity }) => {
+ const model = modelOf(entity);
+
+ return isResourceModel(model) && entity.collection_id === collectionEntityId
+ ? [{ path: filePath, model, entity }]
+ : [];
+ });
+
+ return { repoRoot, collectionPath, files };
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/serialize.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/serialize.ts
new file mode 100644
index 00000000000..0f1d7c961b5
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/serialize.ts
@@ -0,0 +1,162 @@
+import path from "node:path";
+
+import { readManifest } from "../data-app-dev/config/read-manifest";
+
+import {
+ QUERY_DEFINITIONS,
+ discoverActions,
+ discoverQueries,
+ getRelativeDefinitionLocation,
+} from "./discover";
+import { getMetabaseCredentials } from "./env";
+import { isObject } from "./guards";
+import { COLLECTIONS_DIR } from "./resources";
+import type { DiscoveredQuery } from "./types";
+
+type IdentifiedQuery = DiscoveredQuery & { savedQuestionEntityId: string };
+
+const isIdentified = (query: DiscoveredQuery): query is IdentifiedQuery =>
+ query.savedQuestionEntityId !== undefined;
+
+interface SerializedResources {
+ queries: Record<string, unknown>[];
+ actions: Record<string, unknown>[];
+ metrics: unknown[];
+}
+
+const isObjectArray = (value: unknown): value is Record<string, unknown>[] =>
+ Array.isArray(value) && value.every(isObject);
+
+function isSerializedResources(value: unknown): value is SerializedResources {
+ return (
+ isObject(value) &&
+ isObjectArray(value.queries) &&
+ isObjectArray(value.actions) &&
+ Array.isArray(value.metrics)
+ );
+}
+
+async function requestSerialization(
+ appRoot: string,
+ body: { collection: string; queries: unknown[]; actions: number[] },
+): Promise<SerializedResources> {
+ const { metabaseUrl, apiKey } = getMetabaseCredentials(appRoot);
+ const response = await fetch(`${metabaseUrl}/api/apps/serialize-resources`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "X-API-Key": apiKey },
+ body: JSON.stringify(body),
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ `The serialization request failed (${response.status}): ${await response.text()}`,
+ );
+ }
+
+ const serialized: unknown = await response.json();
+
+ if (!isSerializedResources(serialized)) {
+ throw new Error("The serialization response has an unexpected body.");
+ }
+
+ return serialized;
+}
+
+/**
+ * What the files of the app's collection are written from, as JSON, for the
+ * definitions in `file` (relative to the app root, as files are printed) or
+ * every definition: the saved question Metabase writes for each `defineQuery`
+ * definition, in the collection `data_app.yaml` names and with the
+ * definition's entity ID, each `defineAction`'s action, and the metrics the
+ * queries aggregate, all as serialization writes them.
+ * One request to the Metabase instance and API key in `.env.local`.
+ */
+export async function serializeResources(appDirectory: string, file?: string) {
+ const appRoot = path.resolve(appDirectory);
+ const filePath = file === undefined ? undefined : path.resolve(appRoot, file);
+ const queries = await discoverQueries(appRoot, { filePath });
+ const actions = await discoverActions(appRoot, { filePath });
+
+ if (filePath !== undefined && queries.length + actions.length === 0) {
+ throw new Error(
+ `${path.relative(appRoot, filePath)} has no defineQuery or defineAction definitions.`,
+ );
+ }
+
+ const collection = readManifest(appRoot)?.manifest.collection;
+
+ if (collection === undefined) {
+ throw new Error(
+ `No data_app.yaml in ${appRoot} names the app's collection. Write the collection under ${COLLECTIONS_DIR}/ and name its entity ID as \`collection\` first: the saved questions are written into it.`,
+ );
+ }
+
+ // The saved question is printed with the definition's entity ID, so the file is complete as printed.
+ const unidentified = queries.filter((query) => !isIdentified(query));
+
+ if (unidentified.length > 0) {
+ throw new Error(
+ unidentified
+ .map(
+ (query) =>
+ `${getRelativeDefinitionLocation(appRoot, query)} has no savedQuestionEntityId. Generate one with \`npx representations generate-entity-id\` and set it first: its saved question is printed with it.`,
+ )
+ .join("\n"),
+ );
+ }
+
+ const identified = queries.filter(isIdentified);
+
+ const serialized = await requestSerialization(appRoot, {
+ collection,
+ queries: identified.map(({ exportName, query, savedQuestionEntityId }) => {
+ const { [QUERY_DEFINITIONS.idKey]: _entityId, ...definition } = query;
+ return {
+ export: exportName,
+ entity_id: savedQuestionEntityId,
+ query: { stages: [definition] },
+ };
+ }),
+ actions: actions.map(({ sourceActionId }) => sourceActionId),
+ });
+
+ const serializedActions = new Map(
+ serialized.actions.map((action) => [action.id, action]),
+ );
+
+ if (serialized.queries.length !== identified.length) {
+ throw new Error(
+ `The serialization response holds ${serialized.queries.length} queries; ${identified.length} were requested.`,
+ );
+ }
+
+ const missingActions = actions
+ .map(({ sourceActionId }) => sourceActionId)
+ .filter((id) => !serializedActions.has(id));
+
+ if (missingActions.length > 0) {
+ throw new Error(
+ `The serialization response is missing action ${missingActions.join(", ")}.`,
+ );
+ }
+
+ return JSON.stringify(
+ {
+ queries: identified.map((query, index) => ({
+ export: query.exportName,
+ file: path.relative(appRoot, query.filePath),
+ savedQuestionEntityId: query.savedQuestionEntityId,
+ ...serialized.queries[index],
+ })),
+ actions: actions.map((action) => ({
+ export: action.exportName,
+ file: path.relative(appRoot, action.filePath),
+ copiedActionEntityId: action.copiedActionEntityId ?? null,
+ ...serializedActions.get(action.sourceActionId),
+ })),
+ metrics: serialized.metrics,
+ },
+ null,
+ 2,
+ );
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/check.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/check.unit.spec.ts
new file mode 100644
index 00000000000..12320bcfc29
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/check.unit.spec.ts
@@ -0,0 +1,221 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { checkResources } from "../check";
+
+import {
+ COLLECTION,
+ makeApp,
+ setupResourceTests,
+ writeAction,
+ writeQuery,
+ writeResource,
+} from "./setup";
+
+const QUESTION = "questionEntityId00010";
+const METRIC = "metricCopyEntityId001";
+const ACTION = "actionCopyEntityId001";
+
+const cardFile = (entityId: string, type: string) => ({
+ name: entityId,
+ type,
+ entity_id: entityId,
+ "serdes/meta": [{ model: "Card", id: entityId }],
+});
+
+const actionFile = (entityId: string) => ({
+ name: "Create",
+ type: "query",
+ entity_id: entityId,
+ "serdes/meta": [{ model: "Action", id: entityId }],
+});
+
+/** An app whose collection files back its one query and one action. */
+function checkedApp(options?: Parameters<typeof makeApp>[0]) {
+ const appRoot = makeApp(options);
+ writeQuery(
+ appRoot,
+ `export const Orders = defineQuery({ savedQuestionEntityId: "${QUESTION}", source: { type: "table", id: 1 } });`,
+ );
+ writeAction(
+ appRoot,
+ `export const Create = defineAction({ copiedActionEntityId: "${ACTION}", action: { id: 51, parameters: [] } });`,
+ );
+ writeResource(
+ appRoot,
+ "data_app/orders.yaml",
+ cardFile(QUESTION, "question"),
+ );
+ writeResource(appRoot, "data_app/revenue.yaml", cardFile(METRIC, "metric"));
+ writeResource(appRoot, "data_app/create.yaml", actionFile(ACTION));
+ return appRoot;
+}
+
+describe("resource check", () => {
+ setupResourceTests();
+
+ it("passes when every definition's file exists and nothing is left over", async () => {
+ await expect(checkResources(checkedApp())).resolves.toBeUndefined();
+ });
+
+ it("fails for a query without a saved question ID", async () => {
+ const appRoot = checkedApp();
+ fs.appendFileSync(
+ path.join(appRoot, "queries/orders.query.ts"),
+ `export const Products = defineQuery({ source: { type: "table", id: 2 } });\n`,
+ );
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ "queries/orders.query.ts:Products has no savedQuestionEntityId.",
+ );
+ });
+
+ it("fails for a query whose saved question has no file", async () => {
+ const appRoot = checkedApp();
+ fs.rmSync(path.join(appRoot, "collections/data_apps/data_app/orders.yaml"));
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ `queries/orders.query.ts:Orders names saved question ${QUESTION}, which no file in collections/data_apps/ holds in the app's collection.`,
+ );
+ });
+
+ it("ignores hidden files, which a pull skips", async () => {
+ const appRoot = checkedApp();
+ fs.renameSync(
+ path.join(appRoot, "collections/data_apps/data_app/orders.yaml"),
+ path.join(appRoot, "collections/data_apps/data_app/.orders.yaml"),
+ );
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ `names saved question ${QUESTION}, which no file in collections/data_apps/ holds in the app's collection.`,
+ );
+ });
+
+ it("fails for a query that names a card that is not a question", async () => {
+ const appRoot = checkedApp();
+ writeResource(
+ appRoot,
+ "data_app/orders.yaml",
+ cardFile(QUESTION, "metric"),
+ );
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ "queries/orders.query.ts:Orders names collections/data_apps/data_app/orders.yaml, which is not a question.",
+ );
+ });
+
+ it("fails for an action without a copied action ID", async () => {
+ const appRoot = checkedApp();
+ fs.appendFileSync(
+ path.join(appRoot, "actions/orders.action.ts"),
+ `export const Update = defineAction({ action: { id: 52, parameters: [] } });\n`,
+ );
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ "actions/orders.action.ts:Update has no copiedActionEntityId.",
+ );
+ });
+
+ it("fails for an action whose copy has no file", async () => {
+ const appRoot = checkedApp();
+ fs.rmSync(path.join(appRoot, "collections/data_apps/data_app/create.yaml"));
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ `actions/orders.action.ts:Create names action ${ACTION}, which no file in collections/data_apps/ holds in the app's collection.`,
+ );
+ });
+
+ it.each([
+ [
+ "a question no query names",
+ "data_app/stale.yaml",
+ cardFile("staleQuestionEntity01", "question"),
+ "collections/data_apps/data_app/stale.yaml is a resource that is not referenced anywhere.",
+ ],
+ [
+ "an action no definition names",
+ "data_app/stale.yaml",
+ actionFile("staleActionEntityId01"),
+ "collections/data_apps/data_app/stale.yaml is a resource that is not referenced anywhere.",
+ ],
+ ])("fails for %s", async (_, relativePath, entity, message) => {
+ const appRoot = checkedApp();
+ writeResource(appRoot, relativePath, entity);
+
+ await expect(checkResources(appRoot)).rejects.toThrow(message);
+ });
+
+ it("reports an action no definition names even when a query names the same ID", async () => {
+ const appRoot = checkedApp();
+ writeResource(appRoot, "data_app/stale.yaml", actionFile(QUESTION));
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ "collections/data_apps/data_app/stale.yaml is a resource that is not referenced anywhere.",
+ );
+ });
+
+ it("reports a question file without an entity ID even when a definition lacks one too", async () => {
+ const appRoot = checkedApp();
+ fs.appendFileSync(
+ path.join(appRoot, "queries/orders.query.ts"),
+ `export const Products = defineQuery({ source: { type: "table", id: 2 } });\n`,
+ );
+ writeResource(appRoot, "data_app/unnamed.yaml", {
+ name: "Unnamed",
+ type: "question",
+ collection_id: COLLECTION,
+ "serdes/meta": [{ model: "Card" }],
+ });
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ "collections/data_apps/data_app/unnamed.yaml is a resource that is not referenced anywhere.",
+ );
+ });
+
+ it("reads the files of an app under the repository's data_apps/", async () => {
+ await expect(
+ checkResources(checkedApp({ underDataApps: true })),
+ ).resolves.toBeUndefined();
+ });
+
+ it("leaves a card in another collection alone", async () => {
+ const appRoot = checkedApp();
+ writeResource(appRoot, "other/stale.yaml", {
+ ...cardFile("otherQuestionEntity01", "question"),
+ collection_id: "otherCollectionEntit1",
+ });
+
+ await expect(checkResources(appRoot)).resolves.toBeUndefined();
+ });
+
+ it("fails for a manifest that names no collection", async () => {
+ const appRoot = checkedApp();
+ fs.writeFileSync(
+ path.join(appRoot, "data_app.yaml"),
+ "name: Shop\nslug: shop\npath: dist/index.js\n",
+ );
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ "data_app.yaml names no collection.",
+ );
+ });
+
+ it("fails for a collection whose file is missing", async () => {
+ const appRoot = checkedApp();
+ fs.rmSync(path.join(appRoot, "collections/data_apps/data_app.yaml"));
+
+ await expect(checkResources(appRoot)).rejects.toThrow(
+ `data_app.yaml names collection ${COLLECTION}, which no file in collections/data_apps/ holds.`,
+ );
+ });
+
+ it("reports every problem at once", async () => {
+ const appRoot = checkedApp();
+ fs.rmSync(path.join(appRoot, "collections/data_apps/data_app/orders.yaml"));
+ fs.rmSync(path.join(appRoot, "collections/data_apps/data_app/create.yaml"));
+
+ const error = await checkResources(appRoot).catch((e: Error) => e);
+ expect(String(error)).toContain(`saved question ${QUESTION}`);
+ expect(String(error)).toContain(`action ${ACTION}`);
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/discover.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/discover.unit.spec.ts
new file mode 100644
index 00000000000..21a0aca7098
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/discover.unit.spec.ts
@@ -0,0 +1,169 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { discoverActions, discoverQueries } from "../discover";
+
+import { makeApp, setupResourceTests, writeAction, writeQuery } from "./setup";
+
+const QUESTION_10 = "questionEntityId00010";
+const ACTION_91 = "actionEntityId0000091";
+
+describe("query discovery", () => {
+ setupResourceTests();
+
+ it("discovers a direct named definition", async () => {
+ const appRoot = makeApp();
+ writeQuery(
+ appRoot,
+ `export const Orders = defineQuery({ savedQuestionEntityId: "${QUESTION_10}", source: { type: "table", id: 1 }, limit: 5 });`,
+ );
+
+ await expect(discoverQueries(appRoot)).resolves.toEqual([
+ expect.objectContaining({
+ exportName: "Orders",
+ savedQuestionEntityId: QUESTION_10,
+ }),
+ ]);
+ });
+
+ it("rejects a saved question ID two definitions share", async () => {
+ const appRoot = makeApp();
+
+ writeQuery(
+ appRoot,
+ `export const First = defineQuery({ savedQuestionEntityId: "${QUESTION_10}", source: { type: "table", id: 1 } });
+ export const Second = defineQuery({ savedQuestionEntityId: "${QUESTION_10}", source: { type: "table", id: 1 } });`,
+ );
+
+ await expect(discoverQueries(appRoot)).rejects.toThrow(
+ `Saved question ${QUESTION_10} is referenced by`,
+ );
+ });
+
+ it("counts a definition another file re-exports once, and skips exports that aren't objects", async () => {
+ const appRoot = makeApp();
+ writeQuery(
+ appRoot,
+ `export const Orders = defineQuery({ savedQuestionEntityId: "${QUESTION_10}", source: { type: "table", id: 1 } });
+ export const LIMIT = 5;`,
+ );
+ fs.writeFileSync(
+ path.join(appRoot, "queries/index.ts"),
+ 'export { Orders } from "./orders.query";\n',
+ );
+
+ await expect(discoverQueries(appRoot)).resolves.toEqual([
+ expect.objectContaining({ exportName: "Orders" }),
+ ]);
+ });
+
+ it("finds the definitions of one file even when a barrel sorted before it re-exports them", async () => {
+ const appRoot = makeApp();
+ const filePath = writeQuery(
+ appRoot,
+ `export const Orders = defineQuery({ savedQuestionEntityId: "${QUESTION_10}", source: { type: "table", id: 1 } });`,
+ );
+ fs.writeFileSync(
+ path.join(appRoot, "queries/index.ts"),
+ 'export { Orders } from "./orders.query";\n',
+ );
+
+ await expect(discoverQueries(appRoot, { filePath })).resolves.toEqual([
+ expect.objectContaining({ exportName: "Orders", filePath }),
+ ]);
+ });
+
+ it("rejects an invalid saved question ID", async () => {
+ const appRoot = makeApp();
+
+ writeQuery(
+ appRoot,
+ `export const Orders = defineQuery({ savedQuestionEntityId: 10, source: { type: "table", id: 1 } });`,
+ );
+
+ await expect(discoverQueries(appRoot)).rejects.toThrow(
+ "has an invalid savedQuestionEntityId",
+ );
+ });
+});
+
+describe("action discovery", () => {
+ setupResourceTests();
+
+ it("discovers named definitions and the action each references", async () => {
+ const appRoot = makeApp();
+
+ writeAction(
+ appRoot,
+ `export const Create = defineAction({ copiedActionEntityId: "${ACTION_91}", action: { id: 51, entityId: "sourceActionEntity051", parameters: [] } });
+ export const Update = defineAction({ action: { id: 52, parameters: [] } });`,
+ );
+
+ await expect(discoverActions(appRoot)).resolves.toEqual([
+ expect.objectContaining({
+ exportName: "Create",
+ sourceActionId: 51,
+ copiedActionEntityId: ACTION_91,
+ }),
+ expect.objectContaining({
+ exportName: "Update",
+ sourceActionId: 52,
+ copiedActionEntityId: undefined,
+ }),
+ ]);
+ });
+
+ it("rejects two definitions claiming the same source action", async () => {
+ const appRoot = makeApp();
+
+ writeAction(
+ appRoot,
+ `export const First = defineAction({ action: { id: 51, parameters: [] } });
+ export const Second = defineAction({ action: { id: 51, parameters: [] } });`,
+ );
+
+ await expect(discoverActions(appRoot)).rejects.toThrow(
+ /Action 51 is referenced by .*\. Declare each action once\./,
+ );
+ });
+
+ it("rejects a copied definition that carries another's copied action ID", async () => {
+ const appRoot = makeApp();
+
+ writeAction(
+ appRoot,
+ `export const First = defineAction({ copiedActionEntityId: "${ACTION_91}", action: { id: 51, parameters: [] } });
+ export const Second = defineAction({ copiedActionEntityId: "${ACTION_91}", action: { id: 52, parameters: [] } });`,
+ );
+
+ await expect(discoverActions(appRoot)).rejects.toThrow(
+ `Copied action ${ACTION_91} is referenced by`,
+ );
+ });
+
+ it("rejects a definition that does not reference a generated action", async () => {
+ const appRoot = makeApp();
+
+ writeAction(
+ appRoot,
+ `export const Create = defineAction({ action: { name: "not a schema entry" } });`,
+ );
+
+ await expect(discoverActions(appRoot)).rejects.toThrow(
+ "must reference a generated action",
+ );
+ });
+
+ it("rejects an invalid copied action ID", async () => {
+ const appRoot = makeApp();
+
+ writeAction(
+ appRoot,
+ `export const Create = defineAction({ copiedActionEntityId: 91, action: { id: 51, parameters: [] } });`,
+ );
+
+ await expect(discoverActions(appRoot)).rejects.toThrow(
+ "has an invalid copiedActionEntityId",
+ );
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/serialize.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/serialize.unit.spec.ts
new file mode 100644
index 00000000000..0ced06d55de
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/serialize.unit.spec.ts
@@ -0,0 +1,217 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { serializeResources } from "../serialize";
+
+import { makeApp, setupResourceTests, writeAction, writeQuery } from "./setup";
+
+const QUESTION = "questionEntityId00010";
+const ACTION_COPY = "actionCopyEntityId001";
+
+const COLLECTION = "appCollectionEntity01";
+
+const SERIALIZED = {
+ queries: [
+ {
+ export: "Orders",
+ entity: {
+ entity_id: QUESTION,
+ collection_id: COLLECTION,
+ name: "Orders",
+ dataset_query: { database: "Sample Database" },
+ },
+ metrics: [],
+ },
+ ],
+ actions: [{ id: 51, entity: { entity_id: "sourceActionEntity051" } }],
+ metrics: [],
+};
+
+function appWithDefinitions() {
+ const appRoot = makeApp();
+ fs.writeFileSync(
+ path.join(appRoot, ".env.local"),
+ "DATA_APP_MB_URL=http://metabase.test/\nDATA_APP_MB_API_KEY=mb_test_key\n",
+ );
+ fs.writeFileSync(
+ path.join(appRoot, "data_app.yaml"),
+ `name: Orders\npath: ./dist/index.js\ncollection: ${COLLECTION}\n`,
+ );
+ writeQuery(
+ appRoot,
+ `export const Orders = defineQuery({ savedQuestionEntityId: "${QUESTION}", source: { type: "table", id: 1 }, limit: 5 });`,
+ );
+ writeAction(
+ appRoot,
+ `export const Create = defineAction({ copiedActionEntityId: "${ACTION_COPY}", action: { id: 51, parameters: [] } });`,
+ );
+ return appRoot;
+}
+
+function mockSerialization(response: Response) {
+ return jest.spyOn(global, "fetch").mockResolvedValue(response);
+}
+
+describe("serializing what resources are written from", () => {
+ setupResourceTests();
+
+ it("refuses to print before the manifest names the app's collection", async () => {
+ const appRoot = appWithDefinitions();
+ fs.writeFileSync(
+ path.join(appRoot, "data_app.yaml"),
+ "name: Orders\npath: ./dist/index.js\n",
+ );
+ const fetchSpy = mockSerialization(
+ new Response(JSON.stringify(SERIALIZED)),
+ );
+
+ await expect(serializeResources(appRoot)).rejects.toThrow(
+ "names the app's collection",
+ );
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("refuses to print a query that has no saved question ID yet", async () => {
+ const appRoot = appWithDefinitions();
+ fs.appendFileSync(
+ path.join(appRoot, "queries/orders.query.ts"),
+ `export const Products = defineQuery({ source: { type: "table", id: 2 } });\n`,
+ );
+ const fetchSpy = mockSerialization(
+ new Response(JSON.stringify(SERIALIZED)),
+ );
+
+ await expect(serializeResources(appRoot)).rejects.toThrow(
+ "queries/orders.query.ts:Products has no savedQuestionEntityId.",
+ );
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("sends the definitions with their IDs, the app's collection, and the action IDs in one request, and prints the serialization beside each definition", async () => {
+ const appRoot = appWithDefinitions();
+ const fetchSpy = mockSerialization(
+ new Response(JSON.stringify(SERIALIZED)),
+ );
+
+ const printed = JSON.parse(await serializeResources(appRoot));
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0];
+ expect(url).toBe("http://metabase.test/api/apps/serialize-resources");
+ expect(init?.headers).toEqual({
+ "Content-Type": "application/json",
+ "X-API-Key": "mb_test_key",
+ });
+ expect(JSON.parse(String(init?.body))).toEqual({
+ collection: COLLECTION,
+ queries: [
+ {
+ export: "Orders",
+ entity_id: QUESTION,
+ query: { stages: [{ source: { type: "table", id: 1 }, limit: 5 }] },
+ },
+ ],
+ actions: [51],
+ });
+ expect(printed).toEqual({
+ queries: [
+ {
+ export: "Orders",
+ file: "queries/orders.query.ts",
+ savedQuestionEntityId: QUESTION,
+ entity: SERIALIZED.queries[0].entity,
+ metrics: [],
+ },
+ ],
+ actions: [
+ {
+ export: "Create",
+ file: "actions/orders.action.ts",
+ copiedActionEntityId: ACTION_COPY,
+ id: 51,
+ entity: { entity_id: "sourceActionEntity051" },
+ },
+ ],
+ metrics: [],
+ });
+ });
+
+ it("sends only the definitions in the given file", async () => {
+ const appRoot = appWithDefinitions();
+ const fetchSpy = mockSerialization(
+ new Response(JSON.stringify({ ...SERIALIZED, actions: [] })),
+ );
+
+ await serializeResources(appRoot, "queries/orders.query.ts");
+
+ expect(JSON.parse(String(fetchSpy.mock.calls[0][1]?.body))).toEqual({
+ collection: COLLECTION,
+ queries: [expect.objectContaining({ export: "Orders" })],
+ actions: [],
+ });
+ });
+
+ it("fails for a file with no definitions", async () => {
+ const appRoot = appWithDefinitions();
+
+ await expect(serializeResources(appRoot, "src/App.tsx")).rejects.toThrow(
+ "src/App.tsx has no defineQuery or defineAction definitions.",
+ );
+ });
+
+ it("fails without the Metabase instance and API key", async () => {
+ const appRoot = appWithDefinitions();
+ fs.rmSync(path.join(appRoot, ".env.local"));
+ // The shell's own variables would stand in for the file.
+ const shell = {
+ url: process.env.DATA_APP_MB_URL,
+ key: process.env.DATA_APP_MB_API_KEY,
+ };
+ delete process.env.DATA_APP_MB_URL;
+ delete process.env.DATA_APP_MB_API_KEY;
+
+ try {
+ await expect(serializeResources(appRoot)).rejects.toThrow(
+ "DATA_APP_MB_URL and DATA_APP_MB_API_KEY must be set, in the repo-root .env.local or the environment.",
+ );
+ } finally {
+ if (shell.url !== undefined) {
+ process.env.DATA_APP_MB_URL = shell.url;
+ }
+ if (shell.key !== undefined) {
+ process.env.DATA_APP_MB_API_KEY = shell.key;
+ }
+ }
+ });
+
+ it("fails when the response has a query too few", async () => {
+ const appRoot = appWithDefinitions();
+ mockSerialization(
+ new Response(JSON.stringify({ ...SERIALIZED, queries: [] })),
+ );
+
+ await expect(serializeResources(appRoot)).rejects.toThrow(
+ "The serialization response holds 0 queries; 1 were requested.",
+ );
+ });
+
+ it("fails when the response lacks a requested action", async () => {
+ const appRoot = appWithDefinitions();
+ mockSerialization(
+ new Response(JSON.stringify({ ...SERIALIZED, actions: [] })),
+ );
+
+ await expect(serializeResources(appRoot)).rejects.toThrow(
+ "The serialization response is missing action 51.",
+ );
+ });
+
+ it("fails with the response when the serialization request fails", async () => {
+ const appRoot = appWithDefinitions();
+ mockSerialization(new Response("Unauthenticated", { status: 401 }));
+
+ await expect(serializeResources(appRoot)).rejects.toThrow(
+ "The serialization request failed (401): Unauthenticated",
+ );
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/setup.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/setup.ts
new file mode 100644
index 00000000000..57367408028
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/tests/setup.ts
@@ -0,0 +1,136 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { dump as dumpYaml } from "js-yaml";
+
+import { repoRootOf } from "../resources";
+
+const appRoots: string[] = [];
+
+/** Removes every app `makeApp` created and restores mocks after each test. */
+export function setupResourceTests(): void {
+ afterEach(() => {
+ jest.restoreAllMocks();
+
+ appRoots
+ .splice(0)
+ .forEach((appRoot) =>
+ fs.rmSync(appRoot, { recursive: true, force: true }),
+ );
+ });
+}
+
+/** The entity ID of the collection `makeApp`'s manifest names. */
+export const COLLECTION = "appCollectionEntity01";
+
+/**
+ * Creates an app with `queries/`, `actions/`, a manifest naming `COLLECTION`,
+ * the collection's file, and a stub of the SDK's data-app entry. The app is
+ * its own repository root, or lives at `data_apps/shop/` under one with
+ * `underDataApps`.
+ */
+export function makeApp({ underDataApps = false } = {}) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "data-app-resources-"));
+ appRoots.push(root);
+
+ const appRoot = underDataApps ? path.join(root, "data_apps", "shop") : root;
+
+ fs.mkdirSync(path.join(appRoot, "queries"), { recursive: true });
+ fs.mkdirSync(path.join(appRoot, "actions"));
+ fs.writeFileSync(
+ path.join(appRoot, "data_app.yaml"),
+ dumpYaml({
+ name: "Shop",
+ slug: "shop",
+ path: "dist/index.js",
+ collection: COLLECTION,
+ entity_id: "appEntityId0000000001",
+ "serdes/meta": [
+ { model: "DataApp", id: "appEntityId0000000001", label: "shop" },
+ ],
+ }),
+ );
+ writeResource(appRoot, "data_app.yaml", {
+ name: "Data App: Shop",
+ namespace: "data-apps",
+ entity_id: COLLECTION,
+ "serdes/meta": [{ model: "Collection", id: COLLECTION }],
+ });
+
+ const packageRoot = path.join(
+ appRoot,
+ "node_modules/@metabase/embedding-sdk-react",
+ );
+
+ fs.mkdirSync(packageRoot, { recursive: true });
+ fs.writeFileSync(
+ path.join(packageRoot, "package.json"),
+ JSON.stringify({
+ name: "@metabase/embedding-sdk-react",
+ exports: { "./data-app": "./data-app.js" },
+ }),
+ );
+
+ fs.writeFileSync(
+ path.join(packageRoot, "data-app.js"),
+ [
+ "exports.defineQuery = (query) => query;",
+ "exports.defineAction = (definition) => definition;",
+ ].join("\n"),
+ );
+
+ return appRoot;
+}
+
+export function writeAction(appRoot: string, body: string) {
+ const filePath = path.join(appRoot, "actions/orders.action.ts");
+ fs.writeFileSync(
+ filePath,
+ `import { defineAction } from "@metabase/embedding-sdk-react/data-app";\n${body}\n`,
+ );
+ return filePath;
+}
+
+export function writeQuery(appRoot: string, body: string) {
+ const filePath = path.join(appRoot, "queries/orders.query.ts");
+ fs.writeFileSync(
+ filePath,
+ `import { defineQuery } from "@metabase/embedding-sdk-react/data-app";\n${body}\n`,
+ );
+ return filePath;
+}
+
+/**
+ * Writes `entity` as YAML to `collections/data_apps/<relativePath>` of the
+ * app's repository, in the app's collection unless the entity says otherwise.
+ */
+export function writeResource(
+ appRoot: string,
+ relativePath: string,
+ entity: Record<string, unknown>,
+) {
+ const filePath = path.join(
+ repoRootOf(appRoot),
+ "collections/data_apps",
+ relativePath,
+ );
+ const inCollection =
+ entity["serdes/meta"] === undefined ||
+ modelOf(entity) === "Collection" ||
+ "collection_id" in entity
+ ? entity
+ : { ...entity, collection_id: COLLECTION };
+
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, dumpYaml(inCollection));
+ return filePath;
+}
+
+function modelOf(entity: Record<string, unknown>) {
+ const meta = entity["serdes/meta"];
+ const leaf = Array.isArray(meta) ? meta[meta.length - 1] : undefined;
+ return typeof leaf === "object" && leaf !== null && "model" in leaf
+ ? leaf.model
+ : undefined;
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-resources/types.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/types.ts
new file mode 100644
index 00000000000..6be7aca1f9c
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-resources/types.ts
@@ -0,0 +1,15 @@
+export interface DiscoveredQuery {
+ exportName: string;
+ filePath: string;
+ query: Record<string, unknown>;
+ savedQuestionEntityId?: string;
+}
+
+export interface DiscoveredAction {
+ exportName: string;
+ filePath: string;
+ copiedActionEntityId?: string;
+ sourceActionId: number;
+}
+
+export type ResourceModel = "Card" | "Action";
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts
index dec06cfb971..883de52431a 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts
@@ -2,13 +2,13 @@ import type { DefinedAction } from "./types";
/**
* Defines a source-controlled data app action. `action` names the generated
- * action the app runs. `copiedActionId` is generated state — synchronization
- * writes it back, so never set or edit it by hand.
+ * action the app runs. `copiedActionEntityId` is the entity ID of the action's
+ * copy in the app's collection under `collections/data_apps/`, which a production build runs.
*/
export function defineAction<
const TDefinition extends {
action: { id: number; parameters: readonly unknown[] };
- copiedActionId?: number;
+ copiedActionEntityId?: string;
},
>(definition: TDefinition): TDefinition & DefinedAction {
// `DefinedAction` has no runtime member, so the object is returned as is; the
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts
index e851685f6f3..7dfa55cc2d3 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts
@@ -7,12 +7,13 @@ import type {
} from "./types";
type SavedQuestionBinding = {
- savedQuestionSourceId?: number;
+ savedQuestionEntityId?: string;
};
/**
- * Defines a source-controlled data app query that can be synchronized to a
- * saved question.
+ * Defines a source-controlled data app query. `savedQuestionEntityId` is the
+ * entity ID of its saved question in the app's collection under `collections/data_apps/`, which a
+ * production build runs.
*/
export function defineQuery<
TEntity extends TableSchema | undefined = undefined,
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.unit.spec.ts
index 13aa1589042..3fee15703df 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.unit.spec.ts
@@ -3,7 +3,7 @@ import { defineQuery } from "./define-query";
describe("defineQuery", () => {
it("returns the query definition unchanged", () => {
const query = {
- savedQuestionSourceId: 54,
+ savedQuestionEntityId: "revenueQuestionEntity",
source: { type: "table", id: 1 },
limit: 10,
} as const;
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx
index dba79404563..18f2df78109 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx
@@ -1,6 +1,12 @@
// Register mocks before loading the modules under test.
// oxfmt-ignore
-import { createMockStore, resetTestState, stagesOf } from "./setup";
+import {
+ PUBLISHED_QUESTION_ENTITY_ID,
+ createMockStore,
+ mockRunRtkEndpoint,
+ resetTestState,
+ stagesOf,
+} from "./setup";
import { resolveDatasetQuery as resolveDatasetQueryInBundle } from "embedding-sdk-bundle/lib/create-metabase-query";
import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
@@ -17,7 +23,7 @@ afterEach(() => {
const STATIC_QUERY = {
source: TEST_SCHEMA.tables.orders,
- savedQuestionSourceId: 41,
+ savedQuestionEntityId: PUBLISHED_QUESTION_ENTITY_ID,
};
const statusFilter = filter(
@@ -26,39 +32,71 @@ const statusFilter = filter(
"paid",
);
-describe("an unsynchronized table source", () => {
- const UNSYNCHRONIZED_QUERY = { source: TEST_SCHEMA.tables.orders };
+describe("a table source without a saved question", () => {
+ const QUERY_WITHOUT_SAVED_QUESTION = { source: TEST_SCHEMA.tables.orders };
it("is refused in a deployed data app", async () => {
EMBEDDING_SDK_CONFIG.isDataApp = true;
await expect(
- resolveDatasetQueryInBundle(createMockStore())(UNSYNCHRONIZED_QUERY),
- ).rejects.toThrow("has not been synchronized");
+ resolveDatasetQueryInBundle(createMockStore())(
+ QUERY_WITHOUT_SAVED_QUESTION,
+ ),
+ ).rejects.toThrow(
+ "This query has no saved question. Write it to the app's collection under `collections/data_apps/`",
+ );
});
- it("still runs in the dev preview, before the first sync", async () => {
+ it("still runs in the dev preview, before the app's resources exist", async () => {
EMBEDDING_SDK_CONFIG.isDataApp = true;
EMBEDDING_SDK_CONFIG.isDataAppDev = true;
- const datasetQuery =
- await resolveDatasetQueryInBundle(createMockStore())(
- UNSYNCHRONIZED_QUERY,
- );
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())(
+ QUERY_WITHOUT_SAVED_QUESTION,
+ );
expect(stagesOf(datasetQuery)).toMatchObject([{ "source-table": 1 }]);
});
it("still runs outside a data app, where the SDK addresses tables directly", async () => {
- const datasetQuery =
- await resolveDatasetQueryInBundle(createMockStore())(
- UNSYNCHRONIZED_QUERY,
- );
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())(
+ QUERY_WITHOUT_SAVED_QUESTION,
+ );
expect(stagesOf(datasetQuery)).toMatchObject([{ "source-table": 1 }]);
});
});
+describe("a table source backed by a saved question in a deployed data app", () => {
+ beforeEach(() => {
+ EMBEDDING_SDK_CONFIG.isDataApp = true;
+ });
+
+ it("looks the published card up by its entity ID", async () => {
+ const datasetQuery =
+ await resolveDatasetQueryInBundle(createMockStore())(STATIC_QUERY);
+
+ expect(stagesOf(datasetQuery)[0]).toMatchObject({ "source-card": 41 });
+ expect(mockRunRtkEndpoint).toHaveBeenCalledWith(
+ { id: PUBLISHED_QUESTION_ENTITY_ID },
+ expect.anything(),
+ expect.objectContaining({ name: "getCard" }),
+ { forceRefetch: false },
+ );
+ });
+
+ it("explains a published card the instance hasn't imported yet", async () => {
+ mockRunRtkEndpoint.mockRejectedValueOnce({
+ status: 404,
+ data: "Not found.",
+ });
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())(STATIC_QUERY),
+ ).rejects.toThrow("This app's saved questions have not been imported.");
+ });
+});
+
describe("dynamic query clauses", () => {
// The swap these cover is a data-app rule; elsewhere the table is what runs.
beforeEach(() => {
@@ -116,7 +154,7 @@ describe("dynamic query clauses", () => {
source: TEST_SCHEMA.tables.orders,
aggregations: [count()],
breakouts: [TEST_SCHEMA.tables.orders.fields.status],
- savedQuestionSourceId: 41,
+ savedQuestionEntityId: PUBLISHED_QUESTION_ENTITY_ID,
};
const production = await resolveDatasetQueryInBundle(createMockStore())(
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/setup.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/setup.tsx
index 4c9ea4d8a08..4502215c097 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/setup.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/setup.tsx
@@ -13,6 +13,7 @@ import { selectMetadataProviderUnfiltered } from "metabase/metadata-store";
import { fetchTableMetadata } from "metabase/redux/tables";
import * as Lib from "metabase-lib";
import type { DatasetQuery } from "metabase-types/api";
+import { isObject } from "metabase-types/guards";
import { TEST_METADATA } from "./fixtures";
@@ -134,9 +135,16 @@ export function createDeferred<TValue>() {
return { promise, resolve, reject };
}
+/** The entity ID a published "Orders question" (card 41) resolves from. */
+export const PUBLISHED_QUESTION_ENTITY_ID = "ordersQuestionEntity1";
+
export const resetTestState = (): void => {
jest.clearAllMocks();
- mockRunRtkEndpoint.mockResolvedValue(undefined);
+ mockRunRtkEndpoint.mockImplementation(async (request) =>
+ isObject(request) && request.id === PUBLISHED_QUESTION_ENTITY_ID
+ ? TEST_METADATA.questions[41]
+ : undefined,
+ );
// One fixture drives the provider and both cache lookups.
const metadata = TEST_METADATA as unknown as Lib.Metadata;
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts
index 9f9e5876c89..3ae0013a8a2 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts
@@ -15,13 +15,13 @@ import { TEST_SCHEMA } from "./fixtures";
type OrdersTable = (typeof TEST_SCHEMA)["tables"]["orders"];
-const queryWithInvalidSavedQuestionSourceId = {
- savedQuestionSourceId: "54",
+const queryWithInvalidSavedQuestionEntityId = {
+ savedQuestionEntityId: 54,
source: TEST_SCHEMA.tables.orders,
} as const;
-// @ts-expect-error saved-question source IDs are numeric
-defineQuery(queryWithInvalidSavedQuestionSourceId);
+// @ts-expect-error saved-question entity IDs are strings
+defineQuery(queryWithInvalidSavedQuestionEntityId);
// @ts-expect-error query definitions with breakouts require aggregations
defineQuery({
@@ -29,13 +29,13 @@ defineQuery({
breakouts: [breakout(TEST_SCHEMA.tables.orders.fields.createdAt)],
});
-const actionWithInvalidActionSourceId = {
- copiedActionId: "91",
+const actionWithInvalidCopiedActionEntityId = {
+ copiedActionEntityId: 91,
action: TEST_SCHEMA.actions.createOrder,
} as const;
-// @ts-expect-error generated action source IDs are numeric
-defineAction(actionWithInvalidActionSourceId);
+// @ts-expect-error copied action entity IDs are strings
+defineAction(actionWithInvalidCopiedActionEntityId);
// @ts-expect-error action definitions must reference a generated action
defineAction({ action: TEST_SCHEMA.tables.orders });
@@ -121,7 +121,7 @@ breakout(TEST_SCHEMA.tables.orders.fields.status, { unit: "month" });
function InvalidTypeFixtures() {
const staticQuery = defineQuery({
source: TEST_SCHEMA.tables.orders,
- savedQuestionSourceId: 41,
+ savedQuestionEntityId: "ordersQuestionEntity1",
});
// @ts-expect-error a query is a `defineQuery` export from `queries/`, never an inline object
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts
index 34456b06b18..82dff006135 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts
@@ -19,23 +19,25 @@ import { TEST_SCHEMA } from "./fixtures";
type OrdersTable = (typeof TEST_SCHEMA)["tables"]["orders"];
const revenueQuery = defineQuery({
- savedQuestionSourceId: 54,
+ savedQuestionEntityId: "revenueQuestionEntity",
source: TEST_SCHEMA.tables.orders,
limit: 10,
});
-const _savedQuestionSourceId: 54 = revenueQuery.savedQuestionSourceId;
+const _savedQuestionEntityId: "revenueQuestionEntity" =
+ revenueQuery.savedQuestionEntityId;
const _queryLimit: 10 = revenueQuery.limit;
const CreateOrder = defineAction({
- copiedActionId: 91,
+ copiedActionEntityId: "createOrderCopyEntity",
action: TEST_SCHEMA.actions.createOrder,
});
-const _copiedActionId: 91 = CreateOrder.copiedActionId;
+const _copiedActionEntityId: "createOrderCopyEntity" =
+ CreateOrder.copiedActionEntityId;
const _sourceActionId: 51 = CreateOrder.action.id;
-// A definition is authored without a generated ID; synchronization writes one.
+// A definition is valid before its copy is written.
const UpdateOrder = defineAction({
action: TEST_SCHEMA.actions.updateOrder,
});
@@ -191,7 +193,7 @@ function ValidTypeFixtures() {
// A static query published as a card, with dynamic clauses layered on top.
const staticQuery = defineQuery({
source: TEST_SCHEMA.tables.orders,
- savedQuestionSourceId: 41,
+ savedQuestionEntityId: "ordersQuestionEntity1",
});
const dynamicResult = useMetabaseQuery(staticQuery, {
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx
index 04a66a31278..999dc1f87e2 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx
@@ -1,6 +1,7 @@
// Register mocks before loading the modules under test.
// oxfmt-ignore
import {
+ PUBLISHED_QUESTION_ENTITY_ID,
TEST_DATASET_QUERY,
createDeferred,
createMockDatasetQuery,
@@ -430,7 +431,7 @@ describe("dynamic query clauses", () => {
useMetabaseQuery(
defineQuery({
source: TEST_SCHEMA.tables.orders,
- savedQuestionSourceId: 41,
+ savedQuestionEntityId: PUBLISHED_QUESTION_ENTITY_ID,
}),
{
filters: [filter(TEST_SCHEMA.tables.orders.fields.status, "=", "x")],
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts
index b97dda470d1..b7bf7360d48 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts
@@ -412,7 +412,14 @@ type StageClauses<TDimension, TAggregation, TFilter> = {
type TableQueryBase<TTable> = {
source: TTable extends TableSchema ? SourceQuerySpec<TTable> : TableSchema;
fields?: readonly FieldReference<TTable>[];
- savedQuestionSourceId?: number;
+ /**
+ * The entity ID of this query's saved question in the app's collection,
+ * under the repository's `collections/data_apps/`. A production build runs
+ * that card instead of the table: it sits in the app's collection, which the
+ * app's viewers can read, and a table source isn't. The dev preview ignores
+ * it and runs the table source.
+ */
+ savedQuestionEntityId?: string;
} & StageClauses<
FieldReference<TTable>,
AnyAggregation<TTable>,
diff --git a/enterprise/frontend/src/embedding-sdk-package/package.template.json b/enterprise/frontend/src/embedding-sdk-package/package.template.json
index eb493a0215c..2fa0dfdb99f 100644
--- a/enterprise/frontend/src/embedding-sdk-package/package.template.json
+++ b/enterprise/frontend/src/embedding-sdk-package/package.template.json
@@ -51,7 +51,6 @@
"react-dom": ">=18 <=19"
},
"dependencies": {
- "esbuild": "^0.28.1",
- "typescript": "^6.0.3"
+ "esbuild": "^0.28.1"
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx
index 5b499d3bb34..ff12558c491 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx
@@ -149,18 +149,6 @@ describe("ManageDataAppsPage", () => {
).toBeInTheDocument();
});
- it("labels drafts", async () => {
- setup({
- apps: [
- createMockDataApp({ id: 1, display_name: "Live App" }),
- createMockDataApp({ id: 2, display_name: "Draft App", draft: true }),
- ],
- });
-
- expect(await screen.findByText("Draft App")).toBeInTheDocument();
- expect(screen.getAllByText("Draft")).toHaveLength(1);
- });
-
it("shows how many hosts an app is allowed to reach", async () => {
setup({
apps: [
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx
index f156c2ed692..8e5364fde9a 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx
@@ -23,6 +23,11 @@ const DATA_APP_SKILLS = [
"metabase-data-app-migrate",
];
+// Writes the YAML an app's resources are committed as. It lives in another
+// repository, which has no release branches to pin to.
+const REPRESENTATION_SKILL_COMMAND =
+ "npx skills add metabase/agent-skills/skills --skill metabase-representation-format";
+
export const DataAppSkillsSection = () => {
// Pin the data-app skills (and the template bundled inside `metabase-data-app-setup`)
// to the branch matching this instance: `release-x.<major>.x`, or `master` for
@@ -39,9 +44,10 @@ export const DataAppSkillsSection = () => {
// Joined with shell line-continuations (` \` + newline) so each `--skill` is on
// its own line for readability, while the copied text is still one runnable
// command when pasted.
- const installSkillCommand = [skillCommandBase, ...skillSelectors].join(
- " \\\n",
- );
+ const installSkillCommand = [
+ [skillCommandBase, ...skillSelectors].join(" \\\n"),
+ REPRESENTATION_SKILL_COMMAND,
+ ].join(" && \\\n");
return (
<Stack gap="sm">
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx
index e60e8ff477f..0ac019a8df3 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx
@@ -58,6 +58,14 @@ describe("DataAppSkillsSection", () => {
},
);
+ it("also installs the skill for writing Metabase YAML, in the same copied command", async () => {
+ setup("v0.64.0");
+
+ expect(await copyCommand()).toContain(
+ " && \\\nnpx skills add metabase/agent-skills/skills --skill metabase-representation-format",
+ );
+ });
+
// Release builds pin to their `release-x.<major>.x` branch; local, snapshot,
// and unknown builds fall back to `master`.
it.each<[tag: string | undefined, branch: string]>([
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx
index fd1c2a0bf26..83660f9950e 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx
@@ -1,5 +1,3 @@
-import { t } from "ttag";
-
import { Group, Stack, Text } from "metabase/ui";
import * as Urls from "metabase/urls";
import type { DataApp } from "metabase-types/api";
@@ -18,7 +16,7 @@ const Bullet = () => (
);
export const DataAppSummary = ({ app }: Props) => {
- const isOpenable = app.enabled && !app.draft && !app.outdated;
+ const isOpenable = app.enabled && !app.outdated;
return (
<Group align="center" flex="1" wrap="nowrap" miw={0}>
@@ -62,16 +60,6 @@ export const DataAppSummary = ({ app }: Props) => {
{Urls.dataApp(app.name)}
</Text>
- {app.draft && (
- <>
- <Bullet />
-
- <Text size="sm" c="text-tertiary" lh="1.4">
- {t`Draft`}
- </Text>
- </>
- )}
-
{app.allowed_hosts.length > 0 && (
<>
<Bullet />
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx
index 8684bb145a4..21dd234cdad 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx
@@ -31,23 +31,6 @@ describe("DataAppSummary", () => {
).not.toBeInTheDocument();
});
- it("renders a draft's name as plain text (it has no bundle to open)", () => {
- renderWithProviders(
- <DataAppSummary
- app={createMockDataApp({
- display_name: "Sales",
- enabled: true,
- draft: true,
- })}
- />,
- );
-
- expect(screen.getByText("Sales")).toBeInTheDocument();
- expect(
- screen.queryByRole("link", { name: "Sales" }),
- ).not.toBeInTheDocument();
- });
-
it("renders an outdated app's name as plain text (it refuses to open)", () => {
renderWithProviders(
<DataAppSummary
@@ -92,20 +75,4 @@ describe("DataAppSummary", () => {
).not.toBeInTheDocument();
});
});
-
- describe("draft badge", () => {
- it("labels a draft", () => {
- renderWithProviders(
- <DataAppSummary app={createMockDataApp({ draft: true })} />,
- );
-
- expect(screen.getByText("Draft")).toBeInTheDocument();
- });
-
- it("doesn't label an app that isn't a draft", () => {
- renderWithProviders(<DataAppSummary app={createMockDataApp()} />);
-
- expect(screen.queryByText("Draft")).not.toBeInTheDocument();
- });
- });
});
diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
index 6ef3842fe5f..6df55775f52 100644
--- a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
@@ -13,6 +13,7 @@ import { selectMetadataProviderUnfiltered } from "metabase/metadata-store";
import { fetchTableMetadata } from "metabase/redux/tables";
import * as Lib from "metabase-lib";
import type {
+ Card,
DatasetQuery,
TestColumnSpec,
TestExpressionSpec,
@@ -20,6 +21,7 @@ import type {
TestStageSpec,
TestStageWithSourceSpec,
} from "metabase-types/api";
+import { isObject } from "metabase-types/guards";
import { loadReferencedMetricMetadata } from "./metric-metadata";
import { validateDynamicQuery, validateQueryInput } from "./validation";
@@ -39,17 +41,18 @@ export const resolveDatasetQuery: ResolveDatasetQuery =
);
}
- const sourceInput = toSourceInput(input);
+ const { sourceInput, publishedCard } = await toSourceInput(store, input);
validateQueryInput(sourceInput);
validateDynamicQuery(dynamicQuery);
- await loadSourceMetadata(store, sourceInput);
+ await loadSourceMetadata(store, sourceInput, publishedCard);
return resolveQueryFromLoadedMetadata(
sourceInput,
dynamicQuery,
store.getState(),
+ publishedCard,
);
};
@@ -61,30 +64,65 @@ type SdkState = ReturnType<SdkStore["getState"]>;
* to run the query, through the collection it lives in. Its static clauses are
* already baked into the card, so only the source and the dynamic stage remain.
*/
-function toSourceInput(input: QueryInput): QueryInput {
+async function toSourceInput(
+ store: SdkStore,
+ input: QueryInput,
+): Promise<{ sourceInput: QueryInput; publishedCard?: Card }> {
// Only a data app runs published cards. In the dev preview they do not exist
// yet, and outside a data app they never do, so the table is what runs.
if (!isTableInput(input) || isDataAppDev() || !isDataApp()) {
- return input;
+ return { sourceInput: input };
}
- if (
- input.savedQuestionSourceId === null ||
- input.savedQuestionSourceId === undefined
- ) {
+ const entityId = input.savedQuestionEntityId;
+
+ if (entityId === undefined) {
// An app's viewers can only read the published cards, so a table source 403s.
throw new Error(
- "This query has not been synchronized. Define it with `defineQuery(...)` in `queries/`, run `npm run sync-resources`, and rebuild.",
+ "This query has no saved question. Write it to the app's collection under `collections/data_apps/`, set its `savedQuestionEntityId` in `defineQuery(...)` in `queries/`, run `npm run check-resources`, commit, and rebuild.",
);
}
- return { source: { type: "card", id: input.savedQuestionSourceId } };
+ const publishedCard = await fetchPublishedCard(store, entityId);
+
+ return {
+ sourceInput: { source: { type: "card", id: publishedCard.id } },
+ publishedCard,
+ };
+}
+
+/**
+ * The published card is addressed by the entity ID its resource file gives it,
+ * which Metabase only knows once the repository is imported. Query metadata and
+ * the query itself address cards by numeric ID.
+ */
+async function fetchPublishedCard(
+ store: SdkStore,
+ entityId: string,
+): Promise<Card> {
+ try {
+ return await runRtkEndpoint(
+ { id: entityId },
+ store.dispatch,
+ cardApi.endpoints.getCard,
+ { forceRefetch: false },
+ );
+ } catch (error) {
+ if (isObject(error) && error.status === 404) {
+ throw new Error(
+ "This app's saved questions have not been imported. Pull the connected repository again, or check the app's sync status.",
+ );
+ }
+
+ throw error;
+ }
}
function resolveQueryFromLoadedMetadata(
input: QueryInput,
dynamicQuery: DynamicQueryInput | undefined,
state: SdkState,
+ publishedCard: Card | undefined,
) {
if (!isQueryInput(input)) {
throw new Error(
@@ -92,7 +130,8 @@ function resolveQueryFromLoadedMetadata(
);
}
- const databaseId = getSourceDatabaseId(input, state);
+ const databaseId =
+ publishedCard?.dataset_query?.database ?? getSourceDatabaseId(input, state);
const provider = selectMetadataProviderUnfiltered(state, databaseId);
const sourceStage = toStageSpec(input);
@@ -177,7 +216,16 @@ function toResultColumnExpressionSpec(
return spec;
}
-async function loadSourceMetadata(store: SdkStore, input: QueryInput) {
+async function loadSourceMetadata(
+ store: SdkStore,
+ input: QueryInput,
+ publishedCard: Card | undefined,
+) {
+ if (publishedCard) {
+ await loadCardQueryMetadata(store, publishedCard.id);
+ return;
+ }
+
if (input.source.type === "card") {
await loadCardMetadata(store, input.source.id);
return;
@@ -194,12 +242,19 @@ async function loadCardMetadata(store: SdkStore, id: number) {
runRtkEndpoint({ id }, store.dispatch, cardApi.endpoints.getCard, {
forceRefetch: false,
}),
- runRtkEndpoint(id, store.dispatch, cardApi.endpoints.getCardQueryMetadata, {
- forceRefetch: false,
- }),
+ loadCardQueryMetadata(store, id),
]);
}
+function loadCardQueryMetadata(store: SdkStore, id: number) {
+ return runRtkEndpoint(
+ id,
+ store.dispatch,
+ cardApi.endpoints.getCardQueryMetadata,
+ { forceRefetch: false },
+ );
+}
+
function getSourceDatabaseId(input: QueryInput, state: SdkState) {
if (isTableInput(input)) {
return getTableDatabaseId(input.source.id, state);
diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts
index 7adb5cc73e4..475dd6a22ce 100644
--- a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts
@@ -51,7 +51,7 @@ const isActionDefinition = (
): input is SdkActionDefinition => isObject(input) && "action" in input;
/**
- * The action that actually runs. Outside the dev preview the synchronized copy
+ * The action that actually runs. Outside the dev preview the app's copy
* replaces the authored action: the copy is what grants an app's viewers
* permission to run it, through the app's collection.
*/
@@ -59,7 +59,7 @@ function toExecutableActionId(input: SdkActionInput): SdkActionId {
if (!isActionDefinition(input)) {
if (isDataApp()) {
throw new Error(
- `Action ${input} was passed to \`useAction\` as a raw id. A data app must pass the \`defineAction(...)\` export, so the synchronized action runs.`,
+ `Action ${input} was passed to \`useAction\` as a raw id. A data app must pass the \`defineAction(...)\` export, so the app's copy of the action runs.`,
);
}
@@ -70,13 +70,13 @@ function toExecutableActionId(input: SdkActionInput): SdkActionId {
return input.action.id;
}
- if (input.copiedActionId === null || input.copiedActionId === undefined) {
+ if (input.copiedActionEntityId === undefined) {
throw new Error(
- "This action has not been synchronized. Run `npm run sync-resources` and rebuild.",
+ "This action has no copy. Copy it into the app's collection under `collections/data_apps/`, set its `copiedActionEntityId`, run `npm run check-resources`, commit, and rebuild.",
);
}
- return input.copiedActionId;
+ return input.copiedActionEntityId;
}
/**
diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts
index 19818841a03..bc366104fc6 100644
--- a/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts
@@ -34,16 +34,16 @@ describe("executeAction", () => {
EMBEDDING_SDK_CONFIG.isDataAppDev = false;
});
- describe("a synchronized action definition", () => {
+ describe("an action definition with a copied action", () => {
const AUTHORED_ID = 51;
- const COPIED_ID = 91;
+ const COPIED_ENTITY_ID = "copiedActionEntity091";
const definition = {
action: { id: AUTHORED_ID },
- copiedActionId: COPIED_ID,
+ copiedActionEntityId: COPIED_ENTITY_ID,
};
const expectExecuted = async (
- id: number,
+ id: number | string,
actionId: Parameters<ReturnType<typeof executeAction>>[0]["actionId"],
) => {
fetchMock.post(`path:/api/action/${id}/execute`, {
@@ -61,10 +61,11 @@ describe("executeAction", () => {
it("runs the copy in a production build", async () => {
EMBEDDING_SDK_CONFIG.isDataApp = true;
- await expectExecuted(COPIED_ID, definition);
+ await expectExecuted(COPIED_ENTITY_ID, definition);
});
it("runs the authored action in the dev preview", async () => {
+ EMBEDDING_SDK_CONFIG.isDataApp = true;
EMBEDDING_SDK_CONFIG.isDataAppDev = true;
await expectExecuted(AUTHORED_ID, definition);
@@ -74,12 +75,14 @@ describe("executeAction", () => {
await expectExecuted(AUTHORED_ID, { action: { id: AUTHORED_ID } });
});
- it("refuses an unsynchronized definition in a production build", async () => {
+ it("refuses a definition without a copied action in a production build", async () => {
EMBEDDING_SDK_CONFIG.isDataApp = true;
await expect(
executeAction(setup())({ actionId: { action: { id: AUTHORED_ID } } }),
- ).rejects.toThrow("has not been synchronized");
+ ).rejects.toThrow(
+ "This action has no copy. Copy it into the app's collection under `collections/data_apps/`",
+ );
});
it("refuses a raw id inside a data app", async () => {
diff --git a/frontend/src/embedding-sdk-bundle/types/action.ts b/frontend/src/embedding-sdk-bundle/types/action.ts
index 22e6e7fdf51..3518f60d034 100644
--- a/frontend/src/embedding-sdk-bundle/types/action.ts
+++ b/frontend/src/embedding-sdk-bundle/types/action.ts
@@ -5,14 +5,13 @@ export type SdkActionId = number | SdkEntityId;
/**
* How a data app names an action: the `defineAction` export, which is what a
- * data app must pass. `copiedActionId` addresses the copy synchronization made
- * in the app's own collection — the only one its viewers can read. The dev
- * preview runs `action` instead, so an app works before its first
- * synchronization.
+ * data app must pass. `copiedActionEntityId` addresses the copy in the app's own
+ * collection, the only one its viewers can read. The dev preview runs `action`
+ * instead, so an app works before its resources are written.
*/
export type SdkActionDefinition = {
action: { id: SdkActionId };
- copiedActionId?: number;
+ copiedActionEntityId?: SdkEntityId;
};
export type SdkActionInput = SdkActionId | SdkActionDefinition;
diff --git a/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts b/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts
index 609242fbd7e..579da54ffcf 100644
--- a/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts
+++ b/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts
@@ -17,14 +17,7 @@ export type TableQueryInput = Omit<TestStageWithSourceSpec, "source"> & {
source: TableSchema;
limit?: number;
enabled?: boolean;
-
- /**
- * The saved question this static query was published as at build time. Running
- * the card is what lets an app's viewers run the query at all: it sits in a
- * collection whose permission group grants them access, which a table source
- * cannot do. The dev preview ignores it and keeps the table source.
- */
- savedQuestionSourceId?: number;
+ savedQuestionEntityId?: string;
};
/**
diff --git a/frontend/src/metabase-types/api/data-app.ts b/frontend/src/metabase-types/api/data-app.ts
index b4be2037834..e85aa2a3dd0 100644
--- a/frontend/src/metabase-types/api/data-app.ts
+++ b/frontend/src/metabase-types/api/data-app.ts
@@ -24,8 +24,6 @@ export interface DataApp {
bundle_path: string;
/** Admin toggle. When false the app is not served. */
enabled: boolean;
- /** Whether the app is a draft that reserves its slug before the app is created. */
- draft: boolean;
/** The collection that contains this app's saved questions and models. */
resource_collection_id: number;
/** The group that grants users access to this data app. */
diff --git a/frontend/src/metabase-types/api/mocks/data-app.ts b/frontend/src/metabase-types/api/mocks/data-app.ts
index 12d9c48033f..1a3049b89c0 100644
--- a/frontend/src/metabase-types/api/mocks/data-app.ts
+++ b/frontend/src/metabase-types/api/mocks/data-app.ts
@@ -10,7 +10,6 @@ export const createMockDataApp = (opts?: Partial<DataApp>): DataApp => ({
outdated: false,
bundle_path: "dist/index.js",
enabled: true,
- draft: false,
resource_collection_id: 1,
permission_group_id: 1,
table_ids: [],
diff --git a/resources/migrations/065/20261007_drop_data_app_drafts.yaml b/resources/migrations/065/20261007_drop_data_app_drafts.yaml
new file mode 100644
index 00000000000..4b9e663bf36
--- /dev/null
+++ b/resources/migrations/065/20261007_drop_data_app_drafts.yaml
@@ -0,0 +1,33 @@
+## Data app drafts reserved a slug and the app's resources before the app itself existed, for the SDK's query
+## sync, which is gone. A draft row has no bundle and can never be served: the rows go, with the collections
+## they left empty, and the column with them.
+
+databaseChangeLog:
+ - changeSet:
+ id: v65.2026-10-07T00:00:00
+ author: timofei
+ comment: Remove data app drafts and the collections they left empty
+ changes:
+ - customChange:
+ class: metabase.app_db.custom_migrations.DeleteDataAppDrafts
+ rollback: []
+
+ - changeSet:
+ id: v65.2026-10-07T00:00:01
+ author: timofei
+ comment: Drop data_app.draft, nothing creates drafts anymore
+ changes:
+ - dropColumn:
+ tableName: data_app
+ columnName: draft
+ rollback:
+ - addColumn:
+ tableName: data_app
+ columns:
+ - column:
+ name: draft
+ type: ${boolean.type}
+ defaultValueBoolean: false
+ remarks: Whether this row is a data app draft before its first repository import
+ constraints:
+ nullable: false
diff --git a/rspack.embedding-sdk-node.config.js b/rspack.embedding-sdk-node.config.js
index 04bee1faad6..7e0dd253081 100644
--- a/rspack.embedding-sdk-node.config.js
+++ b/rspack.embedding-sdk-node.config.js
@@ -3,6 +3,7 @@
// Node-targeted builds for the SDK package: the `npx` CLI and the data-app dev
// preset (`@metabase/embedding-sdk-react/data-app-dev/config`). Both run
// in Node (not the browser), so they can't go through the browser rspack bundle.
+const fs = require("fs");
const path = require("path");
const rspack = require("@rspack/core");
@@ -69,10 +70,18 @@ const cliConfig = {
library: { type: "commonjs2" },
},
resolve: sharedResolve,
- externals: ["esbuild", "typescript"],
+ externals: ["esbuild"],
module: sharedModule,
plugins: [
new rspack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }),
+ {
+ // npm sets a bin's executable bit when it installs a packed package, but not when the
+ // package is linked (`file:`), where the bin link points at this file itself.
+ apply: (compiler) =>
+ compiler.hooks.afterEmit.tap("ExecutableCli", () =>
+ fs.chmodSync(path.join(SDK_DIST_PATH, "cli.js"), 0o755),
+ ),
+ },
],
optimization: { minimize: true, minimizer },
};
@@ -99,7 +108,6 @@ const dataAppDevConfig = {
"vite-plugin-svgr",
"vite-plugin-css-injected-by-js",
"esbuild",
- "typescript",
],
externalsType: "module",
output: {
diff --git a/skills/metabase-data-app-actions/SKILL.md b/skills/metabase-data-app-actions/SKILL.md
index 024a0fe8df4..dccf42829a4 100644
--- a/skills/metabase-data-app-actions/SKILL.md
+++ b/skills/metabase-data-app-actions/SKILL.md
@@ -1,6 +1,8 @@
---
name: metabase-data-app-actions
description: Use when a Metabase data app needs to trigger a write or mutation — submitting a form, updating a row, deleting an entry, running a saved action, or any "do something" interaction. Covers invoking an existing action via `useAction`, parameter typing, response handling, and the critical post-action refresh of any UI data the action may have changed.
+metadata:
+ version: master
---
# Triggering actions from a Metabase data app
@@ -27,8 +29,8 @@ import { useAction } from "@metabase/embedding-sdk-react/data-app";
const { execute, isExecuting, result, error, reset } = useAction(MyAction);
```
-- **Import it from `@metabase/embedding-sdk-react/data-app`.** That entry's `useAction` is the data-app form: it accepts a `defineAction(...)` export or `null` and nothing else. The main entry's `useAction` is the general SDK hook, which also takes plain objects and raw ids, so it cannot enforce the definition; a data app that imports it from the main entry compiles with an unsynchronized action and fails in production.
-- **The argument** is the `defineAction(...)` export itself, declared in the app's root-level `actions/` directory (one `<topic>.action.ts` file per topic, beside `package.json`, never under `src/`) — pass `MyAction`, not `MyAction.copiedActionId`. The hook accepts nothing else in a data app: an inline `{ action: ... }` object, the schema entry, or a spread copy of a definition fails to compile with `Property 'definedWithDefineAction' is missing`. Fix that by adding the export to `actions/`, not with a cast and not by calling `defineAction(...)` at the hook, which compiles but is never synchronized. A production build then runs the synchronized copy in the app's own collection; the dev preview keeps running the authored action, so an app works before it has ever been synchronized. Do **not** pass `schema.actions.<action>` or its `.id`: the entry is a compile error, and the raw id names the authored action, which the app's users cannot read, so the call fails on permissions in production.
+- **Import it from `@metabase/embedding-sdk-react/data-app`.** That entry's `useAction` is the data-app form: it accepts a `defineAction(...)` export or `null` and nothing else. The main entry's `useAction` is the general SDK hook, which also takes plain objects and raw ids, so it cannot enforce the definition at compile time; in a data app, a raw id still fails at runtime with "was passed to `useAction` as a raw id".
+- **The argument** is the `defineAction(...)` export itself, declared in the app's root-level `actions/` directory (one `<topic>.action.ts` file per topic, beside `package.json`, never under `src/`) — pass `MyAction`, not `MyAction.copiedActionEntityId`. The hook accepts nothing else in a data app: an inline `{ action: ... }` object, the schema entry, or a spread copy of a definition fails to compile with `Property 'definedWithDefineAction' is missing`. Fix that by adding the export to `actions/`, not with a cast and not by calling `defineAction(...)` at the hook, which compiles but never gets a copy. A production build then runs the copy its `copiedActionEntityId` names in the app's own collection, under the repo's `collections/data_apps/`; the dev preview keeps running the authored action, so an app works before its resources exist. Writing those copies is covered by the data-app guidance on writing the files of an app's collection (use skill discovery). Do **not** pass `schema.actions.<action>` or its `.id`: the entry is a compile error, and a data app refuses the raw id at runtime with "was passed to `useAction` as a raw id".
- **Don't write the generics.** The definition carries its schema entry, so the hook infers both the parameters object and the discriminated `result` from it: `parameters[]` becomes a keyed object (`required: true` entries are required keys, each value typed from its `jsType`), and `type: "query"` makes the kind `"sql"`. The raw-id form exists only on the SDK's `useAction` from the main entry, where `useAction<TParameters, TKind>(42)` needs them spelled out since an id describes nothing; a data app never names an action by id.
- **`execute(parameters)`** — triggers the action. Parameters object is keyed by parameter `slug`; parameters declared `required: true` are required keys, everything else optional. Returns the response body on success AND throws on failure (the error is also written to `error` state for render-time consumers). Resolves to `null` (without making a request) when `actionId` is `null` or the SDK is not yet initialized — guard the call site if those cases are reachable.
- **No `enabled` / `options` argument.** The hook only ever runs when `execute(...)` is called, so a gate option would be redundant. Skip the action by branching in the event handler:
@@ -182,7 +184,7 @@ No hand-rolled `!name || !email` checks.
When an action appears to succeed but the screen doesn't update, or a call fails with a 400:
1. Log `result`, `error`, and `isExecuting` after `await execute(...)` to confirm the request actually went through and succeeded.
-2. Confirm `useAction` was called with the `defineAction(...)` export imported from `actions/`. Passing the schema entry, an inline object, or a spread copy is a compile error; passing its `.id` compiles but leaves `execute` untyped and 403s in production, since the authored action is not the one an app's users can run. Calling `defineAction(...)` inside the component compiles too, but `sync-resources` scans only `actions/`, so that action is never copied and also 403s.
+2. Confirm `useAction` was called with the `defineAction(...)` export imported from `actions/`. Passing the schema entry, an inline object, or a spread copy is a compile error; passing its `.id` compiles but leaves `execute` untyped and fails at runtime with "was passed to `useAction` as a raw id". Calling `defineAction(...)` inside the component compiles too, but it has no copy in the app's collection, so a deployed app throws "This action has no copy". The same error means a definition in `actions/` lacks its `copiedActionEntityId`.
3. Log the object passed to `execute({ ... })`. Every key must match a parameter `slug` from `schema.actions.<action>.parameters`; every value must match its declared `jsType`.
4. List every data view on the screen that reads the rows the action writes. Confirm each one's data hook is mounted ABOVE the action trigger so its refresh callback can be passed down.
5. Confirm the refresh callback is called AFTER `await execute(...)` AND that the refresh itself is awaited. When multiple refreshes apply, confirm they're awaited together (`Promise.all`).
@@ -191,8 +193,8 @@ When an action appears to succeed but the screen doesn't update, or a call fails
## Common Mistakes
- Importing `useAction` from `@metabase/embedding-sdk-react` instead of `@metabase/embedding-sdk-react/data-app`. The main entry's hook is the general SDK one and accepts anything, so the definition check never runs.
-- Declaring the action anywhere but root-level `actions/`: inline at the hook, wrapped in `defineAction(...)` inside a component, or under `src/actions/`. Only `actions/` is synchronized.
-- Passing `schema.actions.<action>.id` to `useAction` instead of the `defineAction(...)` export. `execute` then accepts any `Record<string, unknown>`, typos like `{ wrongKey: 1 }` slip through, and production 403s because the authored action is not the one an app's users can run.
+- Declaring the action anywhere but root-level `actions/`: inline at the hook, wrapped in `defineAction(...)` inside a component, or under `src/actions/`. Only definitions in `actions/` are checked against the app's collection files.
+- Passing `schema.actions.<action>.id` to `useAction` instead of the `defineAction(...)` export. `execute` then accepts any `Record<string, unknown>`, typos like `{ wrongKey: 1 }` slip through, and a data app refuses the raw id at runtime with "was passed to `useAction` as a raw id".
- Forgetting to refresh after a successful action. The UI keeps rendering stale data with no error or warning.
- Rendering `"Failed"` / `"Something went wrong"` / `String(error)` instead of the real backend message. Always extract `error.data.message` / `error.data.errors` (the diagnostic the user needs is in there) and render it verbatim — see *Showing the error message*.
- Calling the refresh callback without `await`ing it. The modal dismisses or the form clears before fresh data arrives, leaving the user staring at the stale view for a beat.
diff --git a/skills/metabase-data-app-migrate/SKILL.md b/skills/metabase-data-app-migrate/SKILL.md
index f8f1eee6e40..8c30ee0cef6 100644
--- a/skills/metabase-data-app-migrate/SKILL.md
+++ b/skills/metabase-data-app-migrate/SKILL.md
@@ -1,6 +1,8 @@
---
name: metabase-data-app-migrate
description: Migrate an existing Metabase data app that Metabase marks Outdated (its `data_app.yaml` `version` is below the data-app contract version the installed skills and SDK target) to the current version, one upgrade at a time, with a resumable procedure. Use when Metabase shows an app as Outdated, `npm run typecheck` or `npm run build` fails after an SDK upgrade, or an existing app's `version` is behind the one the installed skills target. Not for creating an app.
+metadata:
+ version: master
---
# Migrate a data app to the current contract version
@@ -29,14 +31,18 @@ Every step below follows from these. Never break them.
3. **Compiler and build gates run only at the target version.** The installed
SDK is the target, so an app halfway through several upgrades cannot type-check
or build. Do not run them earlier and do not "fix" their failures earlier.
-4. **Nothing generated is edited by hand.** `savedQuestionSourceId`,
- `copiedActionId`, `resources_metadata.json`, and `dist/` are written by
- `npm run build` (`sync-resources`), never by you.
+4. **Nothing generated is edited by hand.** `dist/` is written by
+ `npm run build` and `src/metabase.data.ts` by the typed-schema export, never
+ by you. The files of the app's collection under `collections/data_apps/`
+ and the entity IDs its definitions name (`savedQuestionEntityId`,
+ `copiedActionEntityId`) change only where an upgrade guide says so,
+ following the data-app guidance on writing the files of an app's
+ collection (use skill discovery).
## Step 0 - Locate the app and read its state
Work from the app directory, `<repo>/data_apps/<slug>/`. Resolve the repo root
-with `ROOT="$(git rev-parse --show-toplevel)"`. The final build needs the
+with `ROOT="$(git rev-parse --show-toplevel)"`. The instance checks need the
repo-root `.env.local` credentials (`DATA_APP_MB_URL`, `DATA_APP_MB_API_KEY`).
Check them by sourcing the file in a subshell and printing only whether both are
set; never print the file or its variables. The key must belong to an admin:
@@ -107,7 +113,7 @@ For each `N` from the HEAD version up to `target - 1`:
4. Run the guide's _Done-check summary_. Every line must print `ok`.
5. Only now set `version: N+1` in `data_app.yaml`. This is the one edit to that line.
6. If `N+1 < target`: from the repo root,
- `git add data_apps/<slug> && git commit -m "Migrate <slug> data app to data-app version N+1" -- data_apps/<slug>`.
+ `git add data_apps/<slug> collections/data_apps && git commit -m "Migrate <slug> data app to data-app version N+1" -- data_apps/<slug> collections/data_apps`.
The pathspec keeps anything staged outside the app out of the commit.
No push, no typecheck, no build. If the user asks why, say the app cannot
compile until the last upgrade.
@@ -121,8 +127,9 @@ Do not batch steps across upgrades. Do not touch `version` before item 5.
names an SDK symbol no upgrade guide mentions is a gap in the guides, not a user
problem: surface the exact error, say which guide should have covered it, and
stop. Otherwise, at most three fix rounds, then stop and ask.
-2. `npm run build`. It runs `sync-resources` and refuses to bundle when
- definitions and `resources_metadata.json` disagree; follow its message.
+2. `npm run check-resources`, then `npm run build`, which refuses to bundle
+ when the app's collection files don't back the definitions. Follow their messages;
+ neither calls Metabase.
3. `npm run dev`, then take the preview URL from the `Local:` line Vite prints.
The template asks for port 5174, but Vite moves to the next free port when
that one is taken, so never assume it. Open that URL, then read the
@@ -133,11 +140,11 @@ Do not batch steps across upgrades. Do not touch `version` before item 5.
Expect `clients: 1` and no entry with `"alert": true`. `clients: 0` means no
preview tab is open, so an empty feed proves nothing.
4. `git status` from the repo root must show only: the upgrade edits,
- `data_app.yaml`, the built bundle, `resources_metadata.json` if resources
- changed, and the package lockfile if the SDK was re-pinned. Anything else
- inside the app directory is a user edit; say so before committing.
+ `data_app.yaml`, the built bundle, the app's collection files if an upgrade changed them,
+ and the package lockfile if the SDK was re-pinned. Anything else inside the
+ app directory is a user edit; say so before committing.
5. From the repo root,
- `git add data_apps/<slug> && git commit -m "Migrate <slug> data app to data-app version M" -- data_apps/<slug>`,
+ `git add data_apps/<slug> collections/data_apps && git commit -m "Migrate <slug> data app to data-app version M" -- data_apps/<slug> collections/data_apps`,
push, and tell the user to **Pull changes** under Admin > Data apps.
6. Prove it. After the pull:
```bash
@@ -176,7 +183,7 @@ few representative diagnostics rather than pasting it whole.
- Set or edit `version` before the upgrade's checks pass, or by more than one at a time.
- Skip an upgrade, or apply two upgrades' steps at once.
- Run `npm run typecheck` or `npm run build` before the last upgrade, or push before the final gates pass.
-- Hand-edit `savedQuestionSourceId`, `copiedActionId`, `resources_metadata.json`, or `dist/`.
+- Hand-edit `dist/` or `src/metabase.data.ts`, or change the app's collection files or a definition's entity ID beyond what an upgrade guide says.
- Copy a step's outcome from the previous session's chat instead of re-running its **Done when**.
- Migrate with a checklist of your own when an upgrade guide exists; when one does not exist for an upgrade you need, stop and say so.
diff --git a/skills/metabase-data-app-migrate/references/maintainer-checklist.md b/skills/metabase-data-app-migrate/references/maintainer-checklist.md
index 2b4427f61e1..225142e1d75 100644
--- a/skills/metabase-data-app-migrate/references/maintainer-checklist.md
+++ b/skills/metabase-data-app-migrate/references/maintainer-checklist.md
@@ -6,7 +6,7 @@ only for a change an app author must act on. Decide the category first:
| Change | Bump? | Proven by | What the upgrade guide contains |
| ------------------------------------------------------------------------------------------------------------------ | ---------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `@metabase/embedding-sdk-react/data-app` API: components, hooks, types, the bundle factory, `providerProps` | yes, after one deprecation release | `npm run typecheck` | the symbol table from the `.d.ts` diff, with replacements |
-| `data_app.yaml` fields, `queries/` and `actions/` conventions, generated-id keys, `resources_metadata.json` format | yes | `npm run build` (`sync-resources`) | mechanical steps; `sync-resources` upgrades the state it owns |
+| `data_app.yaml` fields, `queries/` and `actions/` conventions, entity-ID keys, the layout of the app's collection files | yes | `npm run check-resources` and `npm run build` | mechanical steps, including every edit to the app's collection files |
| What an app may declare or run under the permission model | yes | the instance API, read by the agent with the app's API key | instance steps whose _Done when_ is an API response |
| Instance-only changes: the app group's grants, collection layout, provisioning | **no** | nothing app-side | none; ship a backend migration and make provisioning converge on the next pull |
diff --git a/skills/metabase-data-app-migrate/references/upgrade-guide-template.md b/skills/metabase-data-app-migrate/references/upgrade-guide-template.md
index 228ac28ec35..3ee873345bb 100644
--- a/skills/metabase-data-app-migrate/references/upgrade-guide-template.md
+++ b/skills/metabase-data-app-migrate/references/upgrade-guide-template.md
@@ -50,7 +50,7 @@ Every row is a `tsc` error at v<N+1>. List types as well as values.
## Other contract changes
-<Manifest fields, `queries/` and `actions/` layout, generated-id keys, factory
+<Manifest fields, `queries/` and `actions/` layout, entity-ID keys, the layout of the app's collection files, factory
shape, `providerProps`, sandbox rules, what an app may declare, or "none".>
## Steps
diff --git a/skills/metabase-data-app-routing/SKILL.md b/skills/metabase-data-app-routing/SKILL.md
index 9679a8e71a1..b78893dbf91 100644
--- a/skills/metabase-data-app-routing/SKILL.md
+++ b/skills/metabase-data-app-routing/SKILL.md
@@ -1,6 +1,8 @@
---
name: metabase-data-app-routing
description: Add client-side routing (multiple pages) to an existing Metabase data-app project using the host-provided `DataAppRouter`, `DataAppLink`, and `useDataAppLocation` primitives. Use when the user has an existing data-app project and wants more than one page.
+metadata:
+ version: master
---
# Add routing to a data-app
diff --git a/skills/metabase-data-app-semantic-layer/SKILL.md b/skills/metabase-data-app-semantic-layer/SKILL.md
index 273b5a00a0b..e4d1d6c4de6 100644
--- a/skills/metabase-data-app-semantic-layer/SKILL.md
+++ b/skills/metabase-data-app-semantic-layer/SKILL.md
@@ -1,6 +1,8 @@
---
name: metabase-data-app-semantic-layer
description: Use when building, creating, or editing data apps that should query Metabase tables and metrics through generated schema files like metabase.data.ts or *.metabase.data.ts.
+metadata:
+ version: master
---
# Metabase Data App Semantic Layer
@@ -9,15 +11,15 @@ description: Use when building, creating, or editing data apps that should query
Keep the semantic layer and presentation layer separate.
-- All Metabase context must come from the generated schema file, usually `src/metabase.data.ts` or `src/*.metabase.data.ts`.
+- All Metabase context must come from the generated schema file, usually `src/metabase.data.ts` or `src/*.metabase.data.ts` (its runtime object and the `/* metadata: {...} */` block an entry opens with when it has context to give), and what the files of the app's collection are written from must come from `npm run print-resources`. Never from Metabase YAML in the repository, and never from your own API calls.
- Do not discover data through MCP tools, create Metabase content, create tables, or edit the semantic layer while building the React UI.
- Import data app query helpers from `@metabase/embedding-sdk-react/data-app`.
- Every query is a `defineQuery(...)` named export in the root-level `queries/` directory, and every action a `defineAction(...)` named export in the root-level `actions/` directory, both beside `package.json`. Create both directories before writing the first hook call; the template ships them, each with a README. The hooks enforce this at compile time: `useMetabaseQuery`, `useMetabaseQueryObject`, and `useAction` reject an inline object, a `satisfies MetabaseQueryOptions` object, and a spread copy of a definition. The error reads `Property 'definedWithDefineQuery' is missing` (or `'definedWithDefineAction'`); the fix is always to move the object into `queries/` or `actions/` as a definition and import it, never a cast.
-- Never remove, edit, or copy a generated `savedQuestionSourceId` or `copiedActionId`, even if it appears unused. Preserve it during refactors; use `npm run sync-resources` to repair or replace generated IDs.
+- Every `savedQuestionEntityId` and `copiedActionEntityId` names a file in the app's collection (see *Write every query and action into the app's collection*). Keep it through refactors and renames, never copy it to another definition, and never remove it while its file exists.
- Prefer generated schema objects over raw IDs or strings. Extract local constants for top-level table objects.
- Never hand-write `DatasetQuery`/MBQL objects in app code. Do not pass inline query objects like `{ type: "query", query: { "source-table": table.id } }`, raw `source-table` clauses, raw field IDs, bare table IDs, or metric IDs to SDK components, `useMetabaseQuery`, or `useMetabaseQueryObject`. Prefer generated table and metric schema objects; for simple table-source queries, an explicit source reference like `{ type: "table", id: table.id }` is also valid.
- Build queries with `source: schema.tables.<name>`, generated `fields`, generated `segments`, generated `measures`, generated metrics in `aggregations`, generated metric `dimensions`, `filter(...)`, `breakout(...)`, `orderBy(...)`, and `aggregations` helpers such as `aggregations.count()` and `aggregations.sum(...)`. Do not use `source: schema.metrics.<name>`; metrics are aggregation expressions, not query sources.
-- Do not use existing saved questions as `useMetabaseQuery` or `useMetabaseQueryObject` sources. Typed schemas do not expose `schema.questions` or support `question-collections` while data-app reconciliation cannot copy existing saved questions into the app collection.
+- Do not use existing saved questions as `useMetabaseQuery` or `useMetabaseQueryObject` sources. Typed schemas do not expose `schema.questions` or support `question-collections`, since an app's resources can't copy existing saved questions.
- Prefer semantically rich table queries over shallow table dumps. Use curated table measures, segments, filters, and breakouts when they make the generated app more useful.
- Prefer semantic-layer definitions over React-side inference. If the schema has a segment or measure for a concept, use it instead of recreating the concept from raw rows. Both belong to the static query only — the dynamic second argument cannot take them, see *Static and dynamic query parts*.
- Filter UI must default to showing data. Empty controls, "All" options, and incomplete custom ranges should produce no filter instead of blocking queries or showing a blank dashboard.
@@ -69,7 +71,8 @@ If the user asks for any mutation-like flow, such as creating, updating, deletin
The Metabase URL and API key live in the **repo-root** `.env.local` as
`DATA_APP_MB_URL` and `DATA_APP_MB_API_KEY` (one file per repo, usually two levels up
-from the app dir, not in the app dir). The command below `source`s that file so
+from the app dir, not in the app dir). The key must be one in the Administrators group:
+the typed schema answers only an admin, and any other key gets a `403`. The command below `source`s that file so
the shell substitutes the values straight into `curl` — you never read, extract,
or handle the credentials yourself.
@@ -107,30 +110,73 @@ fi
)
```
+An entry in the generated file opens with a `/* metadata: {...} */` block of JSON, before its runtime properties, when it has context to give for writing the app: such as a field's display name, description, and semantic type, a table's database, schema, and real name, and a metric's description, filters, and whether it's verified. It is a comment, so it never reaches the bundle and the app never imports it; read it, and never edit or reformat the file.
+
After a successful export, verify that the schema contains every entity needed for the requested app. If any are missing, revise the scope using available context or ask for the missing context before building the UI.
If schema generation fails, do not hide, paraphrase away, or retry past the error. Surface the typed-schema error to the user, including the failing ids, names, and message when present.
-## Synchronize every query and action
+## Write every query and action into the app's collection
-Everything an end-to-end prototype runs is permission-bound: it runs against a copy in the app's own collection; read access to that collection lets viewers run the app's cards, but they see the data only if they already have access to the underlying tables — the app grants the collection, not the tables. Declare each one as a named export in a root-level directory beside `package.json` — `queries/` for `defineQuery(...)`, `actions/` for `defineAction(...)`. `npm run sync-resources` scans only those two directories, so a definition under `src/queries/`, `src/actions/`, or any other source directory is silently never synchronized. Discovery covers `.js`, `.jsx`, `.ts`, `.tsx`, `.cjs`, `.cts`, `.mjs`, and `.mts`.
+Every query and action a data app runs goes through a copy in the app's own collection: read access to that collection lets viewers run the app's cards, but they see data only from tables they can already read, since the app grants the collection, not the tables. Declare each one as a named export in a root-level directory beside `package.json` — `queries/` for `defineQuery(...)`, `actions/` for `defineAction(...)`. The CLI scans only those two directories, so a definition under `src/queries/`, `src/actions/`, or any other source directory is never seen. Discovery covers `.js`, `.jsx`, `.ts`, `.tsx`, `.cjs`, `.cts`, `.mjs`, and `.mts`.
```ts
import { defineAction, defineQuery } from "@metabase/embedding-sdk-react/data-app";
import schema from "../src/metabase.data";
// queries/revenue.query.ts
-export const RevenueQuery = defineQuery({ source: schema.tables.orders });
+export const RevenueQuery = defineQuery({
+ savedQuestionEntityId: "<entity ID of its saved question>",
+ source: schema.tables.orders,
+});
// actions/orders.action.ts
export const CreateOrder = defineAction({
+ copiedActionEntityId: "<entity ID of its copied action>",
action: schema.actions.createOrder,
});
```
-One `sync-resources` run reconciles both. For a query it materializes the authored table query as a saved question and injects `savedQuestionSourceId`. For an action it copies the action into the app collection and injects `copiedActionId`; the copy disappears with its declaration. Never copy an action into the app collection by hand.
+Each definition is backed by serialized Metabase YAML that you write into the repository's `collections/data_apps/` directory, where the collections of the `data-apps` namespace live, as Metabase exports them. Nothing changes in Metabase until the repository is pulled; the pull loads the files into the app's collection as serialized content, like everything else the repository holds, so write the files instead of creating anything in that collection by hand. From the app's directory, `data_apps/<slug>/`, that directory is `../../collections/data_apps/`.
+
+```
+data_apps/<slug>/data_app.yaml collection: <entity ID of the app's collection>
+collections/data_apps/<collection>.yaml the app's collection, a root collection of the data-apps namespace
+collections/data_apps/<collection>/<name>.yaml a saved question per query, copies of the metrics they use, and a copy of each action the app runs
+```
+
+`<collection>` is the collection's name as Metabase slugs it: `data_app__sales` for `Data App: Sales`. The pull and the CLI find the app's files by content, not by path: the collection whose `entity_id` the manifest names, and the cards and actions whose `collection_id` is it.
+
+Write the YAML in the Metabase representation format. **Before writing or editing any file under `collections/data_apps/`, load the skill for reading and writing Metabase representation YAML** (use skill discovery), and follow it and its format spec for every file there: the collection, cards, and actions. If no such skill is available, install it with `npx skills add metabase/agent-skills/skills --skill metabase-representation-format`; if it still can't be loaded, stop and tell the user instead of writing the files. None of these replaces it: YAML from an earlier app (including files in git history), a search of the spec for one field, or `npm run check-resources` passing, whose schema validation checks the schema, not the format's conventions. Every card and copy is written from what `npm run print-resources` prints, as below; the format skill is how you write it. Never guess a field's shape. Generate every new entity ID with `npx representations generate-entity-id` (`--count <n>` for several), from the app's own dev dependencies; never invent one, reuse one from another app, or keep a source entity's ID on its copy.
+
+1. **Collection.** Once per app, write `collections/data_apps/<collection>.yaml` as a collection named `Data App: <app name>` with `namespace: data-apps`, and put its entity ID in `data_app.yaml` as `collection: <id>`. It must be a root collection of that namespace: no `parent_id`, `personal_owner_id`, `type`, `authority_level`, or `archive_operation_id`, and not `is_remote_synced`, `is_sample`, or `archived`. The pull refuses a manifest without `collection:`, and one whose collection has no file in the repository.
+
+2. **Print what the resources are written from.** Every `defineQuery` carries its `savedQuestionEntityId` and every `defineAction` its `copiedActionEntityId` before you print, generated with `npx representations generate-entity-id`: the saved question is printed with the definition's ID, so `print-resources` refuses a query without one and names it. Then `npm run print-resources` (optionally with one file, `npm run print-resources -- queries/revenue.query.ts`) sends the app's definitions to Metabase, using `DATA_APP_MB_URL` and `DATA_APP_MB_API_KEY` from the repo-root `.env.local`, and prints, as JSON, everything as serialization writes it, every reference by name or entity ID rather than numeric ID:
+ - `queries`: each definition's `export`, `file`, and `savedQuestionEntityId`, the saved question Metabase writes for it as `entity` (named after the export, in the app's collection, with that entity ID, holding the query the dev preview runs), and the entity IDs of the `metrics` it aggregates;
+ - `actions`: each definition's `export`, `file`, and `copiedActionEntityId`, and the source action as `entity`;
+ - `metrics`: the metrics the queries aggregate, each as `entity`.
+
+ The numeric `id` beside an action or metric only says which source it is; no file of the app's collection holds it.
-Pass the definition itself to the hook and let the SDK resolve what runs — a production build runs the copy, while the dev preview runs the authored table or action, so an app works before its first synchronization:
+ The export answers only an admin, so the API key must be one in the Administrators group. With any other key the command fails with `403`: stop and tell the user, and never write the files another way.
+
+ An item that can't be built or copied has an `error` instead (for example a field the query names that doesn't exist, an action that belongs to a model, or a metric or action that reads another card); stop and tell the user. Run it again after any definition changes, and update the files it affects.
+
+3. **A saved question per query.** Write the printed `entity` to `collections/data_apps/<collection>/<name>.yaml` as it is. Its name, `type`, `display`, `creator_id`, `collection_id`, entity ID, and `serdes/meta` are already set; add nothing. The one change is in its `dataset_query`: each metric reference (`[metric, {}, <entity ID>]`) points at the app's copy of that metric (step 4) instead of the source metric's entity ID. Write it yourself in the format skill's layout (how it lays out MBQL clauses), keeping the printed key order, not by serializing the printed JSON with a script: a script skips the format skill, and its output isn't checked against the format. The query is what the dev preview ran, so any difference in it changes what production runs; after writing the file, parse it back and compare it with the printed entity, and fix every difference other than the metric references.
+
+4. **A copy per metric.** Each metric a query aggregates must be copied too, since viewers can read only the app's collection. Write the metric's printed `entity` into `collections/data_apps/<collection>/` as a card with a new entity ID and `collection_id` set to the app's collection, and reference the copy's entity ID from every question that uses the metric. One copy serves them all.
+
+5. **A copy per action.** Write the action's printed `entity` into `collections/data_apps/<collection>/` with a new entity ID, set as the definition's `copiedActionEntityId`, and `collection_id` set to the app's collection. The app runs only query actions that belong to no model, so a copy never has a `model_id`.
+
+Write every card and copy yourself from the printed export, following the format skill, never from YAML (not the repository's exported collections or its top-level `actions/`, not another app's collection, not git history), never from your own API calls, and never with a script that dumps the printed JSON as YAML. Its references are already in the form the YAML uses, so copy them as they are. A copy keeps exactly what its export prints, except what makes it a copy: a new `entity_id` (and the matching `serdes/meta` `id`, with a label from the copy's name) and `collection_id`. The print already leaves out what serialization leaves unset or at its default (`description`, `archived`, `enable_embedding`, `public_uuid`, a form field's unset settings, ...), as the format omits them: never add a key the print doesn't have, never keep one with a `null` value, and keep the printed key order.
+
+Every card and action carries the `creator_id` the print gives; Metabase replaces it with its internal user when it loads the app.
+
+If a source the app needs isn't in `src/metabase.data.ts`, or its export has an `error`, stop and tell the user; never write a replacement from scratch. After a source changes in Metabase, run `npm run print-resources` again and write its copy again, keeping the copy's entity ID.
+
+Run `npm run check-resources`, and fix every file it reports. It fails, listing every problem, when the definitions and the files of the app's collection disagree: a manifest naming no collection or one without a file, a definition without its entity ID or naming one no file holds, a query naming a card that isn't a question, or a question or action no definition names; then it validates every Metabase YAML file in the repository, the app's collection files included, against the format's schema. `npm run build` runs the first check. Delete a metric copy yourself once nothing uses it. Neither command calls Metabase. The next pull validates everything again, and refuses the app's resources with a message naming the file, shown on the Data apps admin page. Fix that file and push again.
+
+Pass the definition itself to the hook and let the SDK resolve what runs — a production build runs the copy, while the dev preview runs the authored table or action, so an app works before its resources exist:
```ts
const { data } = useMetabaseQuery(RevenueQuery, {
@@ -140,17 +186,13 @@ const { data } = useMetabaseQuery(RevenueQuery, {
const { execute, isExecuting, error } = useAction(CreateOrder);
```
-Never pass an inline table-source query (not even a read-only, filter-option, or helper query), a raw action id, `savedQuestionSourceId`, `copiedActionId`, or a hand-built `{ source: { type: "card", id } }`, and never spread a definition into a new object. Each defeats the swap; the authored ids also bypass the permission boundary. TypeScript rejects most of these: the hooks accept only what `defineQuery`/`defineAction` returned, so an inline object, a `satisfies`-typed object, a spread copy, and `schema.actions.<action>` all fail to compile. When `tsc` reports `Property 'definedWithDefineQuery' is missing` or `Property 'definedWithDefineAction' is missing`, the argument is not a definition: move it into `queries/` or `actions/` and import the export. Do not silence it with a cast or by wrapping the inline object in `defineQuery(...)` at the call site, which compiles but leaves the query unsynchronized. Keep fixed permission-boundary filters, aggregations, and breakouts inside `defineQuery` — synchronization bakes them into the saved question, so don't apply them again outside it, and put runtime clauses in the hook's second argument (see *Static and dynamic query parts*). `useAction` needs no generics: the definition types `execute`'s parameters and `result`.
-
-Wire `package.json` with `"sync-resources": "embedding-sdk-react data-apps sync-resources"` and `"build": "npm run sync-resources && vite build"`, then run `npm run build` after adding, changing, renaming, or removing any definition; run `sync-resources` directly only to inspect generated state before a build. It reads `DATA_APP_MB_URL` and `DATA_APP_MB_API_KEY` from the repo-root `.env.local`.
-
-Inline generated IDs and `resources_metadata.json` are generated state: never delete or hand-edit either. A missing ID is restored automatically when the definition still identifies its resource — a query by its table and authored hash matching one unclaimed lockfile entry, an action by declaring the same source action — while a duplicated ID fails the run. Do not test or hand off the app until `npm run build` succeeds, every live definition carries a positive generated ID, and `resources_metadata.json` holds its matching entry. Commit every generated change. The build stops before bundling when synchronization fails.
+Never pass an inline table-source query (not even a read-only, filter-option, or helper query), a raw action id, `savedQuestionEntityId`, `copiedActionEntityId`, or a hand-built `{ source: { type: "card", id } }`, and never spread a definition into a new object. Each defeats the swap; the authored ids also bypass the permission boundary. TypeScript rejects most of these: the hooks accept only what `defineQuery`/`defineAction` returned, so an inline object, a `satisfies`-typed object, a spread copy, and `schema.actions.<action>` all fail to compile. When `tsc` reports `Property 'definedWithDefineQuery' is missing` or `Property 'definedWithDefineAction' is missing`, the argument is not a definition: move it into `queries/` or `actions/` and import the export. Do not silence it with a cast or by wrapping the inline object in `defineQuery(...)` at the call site, which compiles but is never backed by a saved question. Keep fixed permission-boundary filters, aggregations, and breakouts inside `defineQuery` — they are baked into the saved question, so don't apply them again outside it, and put runtime clauses in the hook's second argument (see *Static and dynamic query parts*). `useAction` needs no generics: the definition types `execute`'s parameters and `result`.
-If synchronization fails, surface the exact error and stop. Fix local shape, serialization, duplicate-ID, or lockfile errors before retrying. A confirmed `404` is recovered automatically; authentication, permission, network, server, collection-ownership, and Card-type failures must not trigger manual Card or action creation, deletion, ID replacement, or lockfile editing. Treat a successful run that discovers nothing as a failure when the app has queries or actions. Synchronization copies actions but never creates them, so an action the app needs must already exist in Metabase, without a model, and be picked up by a regenerated schema; if the run reports that actions are not enabled for the database, stop and tell the user to enable them rather than working around it.
+Wire `package.json` with `"print-resources": "embedding-sdk-react data-apps print-resources"`, `"check-resources": "embedding-sdk-react data-apps check-resources && representations validate-schema --folder ../.."` (with `@metabase/representations` as a dev dependency), and `"build": "vite build"`. After adding, changing, renaming, or removing any definition, update the files of the app's collection, then run `npm run check-resources` and `npm run build`. Do not test or hand off the app until `npm run build` succeeds. Commit `data_app.yaml`, the app's files under `collections/data_apps/`, and the definitions together; the app picks them up when Metabase pulls the repository.
## Standard pattern
-Two files per query: the definition in `queries/`, the hook call in the component.
+Two files per query: the definition in `queries/`, the hook call in the component. The examples from here on leave out `savedQuestionEntityId` to stay short; every real definition carries it (see *Write every query and action into the app's collection*).
```ts
// queries/orders.query.ts
@@ -248,7 +290,7 @@ const { data } = useMetabaseQuery(CompletedOrders, {
If a control must switch a segment on and off, that is a choice between static queries, not a dynamic clause: define one query per state and pick the query, or express the same condition as a filter on a result column.
-Do not remove or hand-edit `savedQuestionSourceId` if you find it on a query object, or `copiedActionId` on an action definition. Both are generated synchronization state — see *Synchronize every query and action*.
+Do not remove `savedQuestionEntityId` if you find it on a query object, or `copiedActionEntityId` on an action definition. Each names the definition's file in the app's collection — see *Write every query and action into the app's collection*.
## Table query recipes
@@ -400,7 +442,7 @@ Hook typing:
- Both hooks take a `defineQuery` export imported from `queries/` and nothing else; an inline object is a compile error. Write no generics on the hooks.
- `useMetabaseQuery(...)` infers typed row data from the definition. Put `defineQuery<typeof table>` on the definition when ownership validation matters.
- `useMetabaseQueryObject(...)` returns `{ query, error, isLoading }`. Pass the `query` property to `card={{ query }}`.
-- Do not use `as Parameters<typeof useMetabaseQuery>[0]` or `as DefinedQuery` to quiet query typing errors. The first hides invalid table fields, metric aggregations, and breakouts; the second hides an unsynchronized query that fails in production.
+- Do not use `as Parameters<typeof useMetabaseQuery>[0]` or `as DefinedQuery` to quiet query typing errors. The first hides invalid table fields, metric aggregations, and breakouts; the second hides a query without a saved question, which fails in production.
The basic prop contract is:
@@ -685,7 +727,8 @@ If no curated schema entry supports the intended UI, leave the section out or as
- Run `npm run typecheck`. `Property 'definedWithDefineQuery' is missing` or `Property 'definedWithDefineAction' is missing` means a hook received something other than a `queries/` or `actions/` export; move the object there and import it.
- Search touched files for `useMetabaseQuery(`, `useMetabaseQueryObject(`, and `useAction(`. The first argument must be an identifier imported from `queries/` or `actions/`; a `{`, a `defineQuery(`, a `defineAction(`, or a spread there is wrong even when it compiles. The second argument of the query hooks is the dynamic object and is written inline.
- Confirm `queries/` and `actions/` sit beside `package.json`, not under `src/`, and that every definition the app renders lives there.
-- Run `npm run build`; it synchronizes queries before producing the bundle.
+- Confirm you loaded the representation format skill and checked every file of the app's collection against it; say so in the hand-off, or say that you didn't.
+- Confirm every definition has its entity ID and its file in the app's collection, and each saved question matches its definition. Run `npm run check-resources`, then `npm run build`; both fail when the app's collection files no longer back the definitions.
- Keep TypeScript diagnostics compact in the chat or handoff. Use the full output locally to fix the app, but report grouped root causes and only a few representative diagnostics instead of pasting the entire `tsc` output.
- Verify every rendered value can be traced to a returned row property, schema field, measure, or deterministic transform.
- Search touched files for `row[0]`, `row[1]`, `row.orderedAt`, `row.orderDate`, `as unknown as`, `DisplayRow`, `<select`, `margin`, `rate`, `score`, `percent`, `%`, `* 100`, and `.toFixed`; fix positional rows, result-key guesses, entity `<select>` filters, and unsupported business-field interpretations.
@@ -695,10 +738,12 @@ If no curated schema entry supports the intended UI, leave the section out or as
## Common Mistakes
-- Creating or searching for Metabase content during app building.
+- Creating or searching for Metabase content during app building. The files of the app's collection are written from `npm run print-resources`, never created in Metabase.
+- Copying a metric or action from Metabase YAML in the repository (its exports, its top-level `actions/`, or git history), or from your own API calls, instead of from `npm run print-resources`.
+- Writing a saved question yourself, adding a key the print doesn't have, or changing anything in the printed entity other than a metric reference to the app's copy.
- Writing the query object at the hook call instead of exporting it from `queries/` with `defineQuery`, or the action at `useAction` instead of from `actions/` with `defineAction`. Both are compile errors now; the fix is the directory, not a cast.
-- Wrapping the inline object in `defineQuery(...)` or `defineAction(...)` at the call site. It compiles, but `sync-resources` never sees it, so it is refused in production.
-- Putting definitions under `src/queries/` or `src/actions/`, where `sync-resources` never looks.
+- Wrapping the inline object in `defineQuery(...)` or `defineAction(...)` at the call site. It compiles, but it is never backed by a saved question, so it is refused in production.
+- Putting definitions under `src/queries/` or `src/actions/`, where the CLI never looks.
- Importing older hooks instead of `useMetabaseQuery`.
- Copying raw numeric IDs into constants instead of using generated schema objects.
- Inventing ad hoc measure objects such as `{ name: "count" }` or `{ name: "sum", field: fieldId }`.
diff --git a/skills/metabase-data-app-setup/SKILL.md b/skills/metabase-data-app-setup/SKILL.md
index 84674b6d6af..6c48ecacd9c 100644
--- a/skills/metabase-data-app-setup/SKILL.md
+++ b/skills/metabase-data-app-setup/SKILL.md
@@ -1,13 +1,15 @@
---
name: metabase-data-app-setup
-description: Scaffold a new Metabase data-app into the connected remote-sync repository's `data_apps/<app>/` directory from the `data-app-template`. Use when the user asks to start, create, scaffold, or set up a data-app from scratch.
+description: Scaffold a new Metabase data-app into the connected remote-sync repository's `data_apps/<app>/` directory from the `data-app-template`. Use when the user asks to start, create, scaffold, or set up a data-app from scratch, or to remove one.
+metadata:
+ version: master
---
# Create a Metabase Data App
A Metabase **data-app** is a single JS bundle that the host loads inside a Near Membrane sandbox and renders inside its own React tree. The scaffold is a Vite + React + TypeScript project: source under `src/`, a dev server that previews the app against a real Metabase **through the same Near Membrane sandbox + distortion rules Metabase uses in production** — so `npm run dev` behaves like production, including for third-party libraries the app bundles — and `npm run build` producing a single `dist/index.js`. (Because the sandbox runs a built bundle, a change rebuilds it and does a *soft reload* — re-evaluates the bundle in the sandbox and remounts the app, keeping auth/SDK loaded — rather than hot-swapping modules; component state resets, but there's no full browser refresh.) The dev preview also shows a corner **⚠ Diagnostics** toolbar that captures runtime errors — including the sandbox's otherwise-opaque blocked-API messages — so failures surface instead of being swallowed. The same data is served as JSON at `http://localhost:5174/__data-app/diagnostics`, which is how *you* read it (see "Reading the diagnostics feed" below) — you have a shell, not a browser, and these failures are invisible from the terminal otherwise.
-**Data apps are served from Git** (they can also be created and updated through `/api/apps`). A single repository is connected to Metabase via remote-sync (Admin → Settings → Remote sync). Each app lives in its own directory `data_apps/<slug>/` inside that repo — its source, a `data_app.yaml` (slug/name/path), and the committed built bundle at the `path` its `data_app.yaml` declares (`dist/index.js` by default). On each remote-sync import Metabase materializes each app and serves it at `/apps/<slug>`, where the slug is the `slug` its `data_app.yaml` declares. So this skill always scaffolds **into the connected repo's `data_apps/<slug>/` directory**, never as a standalone project.
+**Data apps are served from Git** (they can also be created and updated through `/api/apps`). A single repository is connected to Metabase via remote-sync (Admin → Settings → Remote sync). Each app lives in its own directory `data_apps/<slug>/` inside that repo — its source, a `data_app.yaml` (slug/name/path/collection), and the committed built bundle at the `path` its `data_app.yaml` declares (`dist/index.js` by default). Its collection, with its saved questions and the copies of the metrics and actions it uses, is YAML under the repo's `collections/data_apps/`, like every collection of the `data-apps` namespace. On each remote-sync import Metabase materializes each app and serves it at `/apps/<slug>`, where the slug is the `slug` its `data_app.yaml` declares. So this skill always scaffolds **into the connected repo's `data_apps/<slug>/` directory**, never as a standalone project.
**The scaffold ships inside this skill at `./template/`** — a Vite + React + TypeScript project that was installed alongside the skill. Step 3 just copies it into the app directory; the skill then guides you through the customization + first-app-content steps — it never generates project files from scratch. If you find yourself writing `package.json`, `vite.config.ts`, `tsconfig.json`, or `src/index.tsx` by hand, stop — copy the template instead.
@@ -16,6 +18,7 @@ A Metabase **data-app** is a single JS bundle that the host loads inside a Near
- "scaffold a new data app" / "create a Metabase data app" / "set up a data-app project"
- "I want to build a data app" / any vague intent to author a data app
- Starting a fresh agent task that will produce a data-app bundle.
+- "remove the <slug> data app" / "delete a data app" — only *Removing an app* below applies.
- Do **not** use this skill for an existing data-app project when the task is to
build screens, use Metabase data, generate or refresh schema files, wire saved
questions / tables / metrics / actions, add filters, or author data hooks.
@@ -124,14 +127,14 @@ Once the template is in `<repo>/data_apps/<slug>/` (run everything below from th
fi
```
- If it prints `MISSING`, **ask the user to fill `DATA_APP_MB_URL` (the running Metabase instance) and `DATA_APP_MB_API_KEY` (Admin → Authentication → API keys) in `<repo>/.env.local` themselves** — up front, before anything needs the key.
+ If it prints `MISSING`, **ask the user to fill `DATA_APP_MB_URL` (the running Metabase instance) and `DATA_APP_MB_API_KEY` (Admin → Authentication → API keys, a key in the Administrators group, since the typed schema answers only an admin) in `<repo>/.env.local` themselves** — up front, before anything needs the key.
> **Never ask the user to paste the API key into the chat, and never `cat` / `echo` / print `.env.local` or its variables.** It's git-ignored and may hold *other* secrets — the file's contents and the key must never enter the conversation or your context. Every command that needs the key `source`s the file (as above) so the shell uses the value directly; you only ever see the `creds present` / `MISSING` signal, never the secret itself. (`creds present` only means both vars are filled and not the default `mb_replace_me` placeholder — not that the URL or key are valid; a bad key surfaces later when a request fails.)
5. `npm install` (or whichever package manager the user prefers — the template ships with no lockfile, so `npm` / `yarn` / `pnpm` / `bun` all work; use the project's existing lockfile if one appears post-clone).
6. **The lockfile and the built bundle must both be committed.** Metabase serves the file at the `path` declared in `data_app.yaml` (the template builds to `dist/index.js`) straight from the committed Git tree, and the lockfile keeps installs reproducible. **Verify with `git status`** after `npm install` and a build: both must appear as committable files.
7. `npm run dev` and confirm the preview at http://localhost:5174 renders the starter "Hello, data app" message.
8. If the preview hits CORS, add `http://localhost:5174` under Admin → Embedding → Embedded analytics SDK → CORS.
-9. **Edit `data_app.yaml`** (it ships with the template, in the app directory). This is the per-app config Metabase reads on sync — one file per app. Generate a new entity id with `node -e "console.log(require('crypto').randomBytes(16).toString('base64url').slice(0, 21))"` and fill in its fields for this app:
+9. **Edit `data_app.yaml`** (it ships with the template, in the app directory). This is the per-app config Metabase reads on sync — one file per app. Its fields, which of them are required, and their rules are defined in the Data App section of the Metabase representation format spec: load the skill for reading and writing Metabase representation YAML (use skill discovery) and follow its spec. If no such skill is available, install it with `npx skills add metabase/agent-skills/skills --skill metabase-representation-format`; if it still can't be loaded, stop and tell the user. Generate the app's entity ID with `npx representations generate-entity-id` (from the app's own dev dependencies, after `npm install`) and fill in the fields for this app; leave `path` as the template ships it unless you change the build output:
```yaml
version: 1 # data app contract version — leave as-is (see below)
@@ -149,7 +152,10 @@ Once the template is in `<repo>/data_apps/<slug>/` (run everything below from th
label: sales-app
```
- Commit it alongside the built bundle (the file `path` points at).
+ Commit it alongside the built bundle (the file `path` points at). It also
+ gets a `collection:` line, the entity ID of the app's own collection, whose
+ file is written under the repo's `collections/data_apps/` in Step 5. Never
+ copy that line from another app.
**`description`** — optional: a single short sentence saying what the app
does, shown under its name in the admin UI so admins can tell apps apart at a
@@ -191,12 +197,20 @@ At this point the data app exists. Keep this workflow focused on creating the
project scaffold and proving the starter bundle works.
1. Run `npm run typecheck`.
-2. Run `npm run build`.
-3. Confirm `git status` shows the app source, lockfile, `data_app.yaml`, and the
- built bundle (`dist/index.js` by default) as committable files.
-4. If the user asked for a live preview, run `npm run dev` and confirm the
+2. Write the app's collection: generate an entity ID with
+ `npx representations generate-entity-id`, write the collection's file under
+ the repo's `collections/data_apps/`, and add `collection: <id>` to
+ `data_app.yaml` (use skill discovery to find the data-app guidance on
+ writing the files of an app's collection). Then run
+ `npm run check-resources`, which also validates the repository's YAML
+ against the format. It changes nothing in Metabase.
+3. Run `npm run build`.
+4. Confirm `git status` shows the app source, lockfile, `data_app.yaml`, the
+ collection's file under `collections/data_apps/`, and the built bundle
+ (`dist/index.js` by default) as committable files.
+5. If the user asked for a live preview, run `npm run dev` and confirm the
starter "Hello, data app" screen renders through the sandbox preview.
-5. With the preview open, check the diagnostics feed once — it is the only place
+6. With the preview open, check the diagnostics feed once — it is the only place
runtime failures appear to you (see *Reading the diagnostics feed*):
```bash
@@ -323,7 +337,7 @@ src/
├── index.tsx (template — the factory; don't edit)
├── App.tsx (routing + composition only)
├── theme.ts
-├── metabase.data.ts (generated schema — see the semantic-layer skill)
+├── metabase.data.ts (generated schema — use skill discovery for the data-app semantic layer)
├── pages/ (one file per screen)
│ ├── Overview.tsx
│ └── CustomerDetail.tsx
@@ -337,7 +351,7 @@ src/
└── customer.ts
```
-Vite bundles everything reachable from `src/index.tsx` into a single `dist/index.js` IIFE — the `src/` layout is purely for your own readability. `queries/` and `actions/` are not: `npm run build` synchronizes exactly those two root-level directories to Metabase, and the query and action hooks accept only the `defineQuery` / `defineAction` exports declared there. A query object written at a hook call, under `src/`, or spread from a definition does not compile (`Property 'definedWithDefineQuery' is missing`); the fix is to move it into `queries/` and import it, never a cast.
+Vite bundles everything reachable from `src/index.tsx` into a single `dist/index.js` IIFE — the `src/` layout is purely for your own readability. `queries/` and `actions/` are not: each definition in those two root-level directories is backed by a file in the app's collection under the repo's `collections/data_apps/`, `npm run build` fails until they match, and the query and action hooks accept only the `defineQuery` / `defineAction` exports declared there. A query object written at a hook call, under `src/`, or spread from a definition does not compile (`Property 'definedWithDefineQuery' is missing`); the fix is to move it into `queries/` and import it, never a cast.
**If the app has multiple tabs (or any top-level screen switcher), the default — leftmost / first — tab MUST be selected on initial load.** The app should never boot to a blank page, an empty shell, or a "nothing selected" state that waits for the user to click. Agents repeatedly forget this. For local-state tabs, initialize the active tab to the first one so the very first render shows it:
@@ -345,7 +359,7 @@ Vite bundles everything reachable from `src/index.tsx` into a single `dist/index
const [active, setActive] = useState(TABS[0].id); // default = leftmost tab
```
-If the tabs are instead backed by URL routes (multiple pages), the same rule applies via the router — see the `metabase-data-app-routing` skill for making the base path `/` resolve to the default tab. Either way, verify by loading the app fresh: the leftmost tab's content is visible immediately and reads as selected.
+If the tabs are instead backed by URL routes (multiple pages), the same rule applies via the router — use skill discovery for data-app routing to make the base path `/` resolve to the default tab. Either way, verify by loading the app fresh: the leftmost tab's content is visible immediately and reads as selected.
**The build output is one self-contained `.js` file — nothing else.** The backend serves a single bundle, so there are no sidecar files: CSS is inlined into the JS, and every imported asset (images, fonts, SVGs-as-URLs) is base64-inlined as a data URI. So `import logo from "./logo.png"` / `import iconUrl from "./icon.svg"` give you a ready-to-use data-URI string, and SVGs can also be imported as React components with the **`?react`** suffix (built-in `svgr`): `import Icon from "./icon.svg?react"`. Everything gets baked into `dist/index.js` — just keep large binaries out, since inlining inflates the bundle. (If your editor doesn't recognize a `?react` import, add `declare module "*.svg?react";` to a `.d.ts` in `src/`.)
@@ -532,19 +546,34 @@ Do not wrap `InteractiveQuestion` or `StaticQuestion` in containers that clip or
Data apps are delivered by Git — you commit the app directory and Metabase pulls it on its next remote-sync import.
-1. `npm run build` → produces the bundle at your `data_app.yaml` `path` (the template builds to `dist/index.js`).
-2. From the **repo root**, commit the app directory — its `data_app.yaml`, the built bundle (the file `path` points at), the source, and the lockfile — and **push**:
+1. After any change to `queries/` or `actions/`, update the files of the app's collection under `collections/data_apps/` to match (regenerating `src/metabase.data.ts` first if it doesn't cover what the definitions use), and run `npm run check-resources`. Nothing reaches Metabase until the pull in step 4 applies it.
+2. `npm run build` produces the bundle at your `data_app.yaml` `path` (the template builds to `dist/index.js`). It fails when the app's collection files don't match the definitions; fix them and rebuild.
+3. From the **repo root**, commit the app directory — its `data_app.yaml`, the built bundle (the file `path` points at), the source, and the lockfile — together with the app's collection files, and **push**:
```bash
- git add data_apps/<slug>
+ git add data_apps/<slug> collections/data_apps
git commit -m "Add <slug> data app"
git push
```
-3. The app appears in Metabase on the next remote-sync import — a manual **Pull changes** (Admin → Data apps / Remote sync), the auto-import poll, or a restart — reachable at `/apps/<slug>`.
+4. The app appears in Metabase on the next remote-sync import — a manual **Pull changes** (Admin > Data apps / Remote sync), the auto-import poll, or a restart — reachable at `/apps/<slug>`.
> **Don't offer to "deploy" the app or ask how the bundle reaches a staging environment** — there is no separate deploy step, and the question only confuses users: Metabase imports the committed bundle straight from the connected repo on its next sync. Once the change is on the branch Metabase syncs from — however the user gets it there (a merged PR, or a push straight to that branch) — just tell them to pull it in and open the app in Metabase at `/apps/<slug>`.
-- **To update:** commit a new build and pull again.
-- **To remove:** delete the app's directory from the repo and push — the next sync removes it.
+- **To update:** update the app's collection files if the definitions changed, commit a new build, and pull again.
+- **To remove:** see *Removing an app* below.
+
+## Removing an app
+
+When the user asks to remove or delete a data app, delete its directory **and** its collection's files in one commit, from the repo root, and push:
+
+```bash
+git rm -r data_apps/<slug> collections/data_apps/<collection>.yaml collections/data_apps/<collection>
+git commit -m "Remove <slug> data app"
+git push
+```
+
+`<collection>` is the collection `data_app.yaml` names as `collection`: the file under `collections/data_apps/` whose `entity_id` is that value, and the directory of the same name beside it (`data_app__order_desk` for `Data App: Order Desk`). The next pull removes the app, and with it its collection, saved questions, metric copies and action copies.
+
+A directory deleted without its collection's files still removes the app on the next pull, and with it the collection; the next push from Metabase then deletes those files from the repository. Delete both anyway: until that push, a pull that reloads every file brings the collection back as one no app owns, and the push would then keep it. The other way round is refused: an app whose directory stays while its collection file is gone fails the pull.
## Common pitfalls
@@ -559,7 +588,7 @@ Data apps are delivered by Git — you commit the app directory and Metabase pul
| Bundle is multi-MB. | React/the SDK should be externalized by the contract plugin — confirm `vite.config.ts` still uses `dataAppConfig()` and the pinned data-apps SDK tag is installed. (A large but not multi-MB bundle can also be inlined assets — see the single-file note above.) |
| `dist/index.js` doesn't assign to `__dataAppFactory__`. | `src/index.tsx` must `export default` the `DataAppFactory` — the preset wires that into the IIFE global. |
| `Cannot find module '@metabase/embedding-sdk-react'`. | Run `npm install` (or the equivalent for your package manager). Types come from the package directly. |
-| `Property 'definedWithDefineQuery' is missing` / `Property 'definedWithDefineAction' is missing` on a hook call. | The hook got an inline object, a `satisfies`-typed object, or a spread copy instead of a definition. Export it with `defineQuery` from root-level `queries/` (or `defineAction` from `actions/`) and pass the import. Do not cast, and do not wrap the object in `defineQuery(...)` at the call site: that compiles but is never synchronized. |
+| `Property 'definedWithDefineQuery' is missing` / `Property 'definedWithDefineAction' is missing` on a hook call. | The hook got an inline object, a `satisfies`-typed object, or a spread copy instead of a definition. Export it with `defineQuery` from root-level `queries/` (or `defineAction` from `actions/`) and pass the import. Do not cast, and do not wrap the object in `defineQuery(...)` at the call site: that compiles but is never backed by a saved question. |
| Drill popups don't open / SDK components show empty / "MetabaseProvider not found" at runtime in dev. | `App.tsx` is rendering its own `<MetabaseProvider>` — remove it. The dev entry (SDK) and the production host provide the provider; wrapping it inside the bundle routes the SDK's state paths through the sandbox and breaks them. |
| Dev preview blank / `Bundle did not assign a function to __dataAppFactory__` / sandbox errors in dev. | `src/index.tsx` isn't default-exporting the factory, or your app code throws while the sandbox evaluates the bundle. Read the real error from the diagnostics feed (`curl -s "http://localhost:5174/__data-app/diagnostics?startEventId=0"`), or the dev toolbar's **Diagnostics** panel. |
| A network call works in `npm run dev` but is blocked after syncing to Metabase. | It was never allowed — you edited `allowed_hosts` without restarting the dev server, so the running sandbox and CSP still use the boot-time list. Restart `npm run dev`; the feed's `manifest` section flags this as `restartRequired`. |
diff --git a/skills/metabase-data-app-setup/template/README.md b/skills/metabase-data-app-setup/template/README.md
index 941b35212d8..96a1d1f5db1 100644
--- a/skills/metabase-data-app-setup/template/README.md
+++ b/skills/metabase-data-app-setup/template/README.md
@@ -6,14 +6,15 @@ SDK) that Metabase renders inside an isolated, sandboxed iframe at
Data apps are delivered through **Git**: this directory lives at
`data_apps/<slug>/` inside a repository connected to Metabase via remote sync.
-You commit the built bundle (`dist/index.js`), and on the next remote-sync
-import Metabase materializes the app and serves it.
+You commit the built bundle (`dist/index.js`) and the files of the app's
+collection under the repo's `collections/data_apps/`, and on the next
+remote-sync import Metabase materializes the app and serves it.
## Develop
```bash
npm install # or yarn / pnpm / bun — no lockfile shipped
-cp .env.local.example .env.local # set DATA_APP_MB_URL + DATA_APP_MB_API_KEY
+cp .env.local.example ../../.env.local # repo root: set DATA_APP_MB_URL + DATA_APP_MB_API_KEY
npm run dev # preview at http://localhost:5174
```
@@ -27,12 +28,25 @@ Admin → Embedding → Embedded analytics SDK → CORS.
## Ship
```bash
+npm run print-resources # prints what the app's collection files are written from, as JSON
+npm run check-resources # checks the app's collection files back every definition, then validates the repository's Metabase YAML
npm run build # produces a single dist/index.js
```
-Commit `dist/index.js` (the `path` declared in `data_app.yaml`) along with your
-source. The app appears at `/apps/<slug>` after Metabase's next remote-sync
-import (manual "Pull changes", auto-import, or startup).
+The repo's `collections/data_apps/` holds the app's collection, a saved question
+per query, and copies of the metrics and actions the app uses, as Metabase YAML:
+`<collection>.yaml` beside a `<collection>/` directory of its contents. They are
+written from what `npm run print-resources` prints, which Metabase exports for
+the app's definitions; `data_app.yaml`'s `collection:` names the collection, and
+each definition names its file by entity ID. Only `print-resources` calls
+Metabase, with the URL and API key in the repo-root `.env.local`.
+Update those files after any change to `queries/` or `actions/`; the check and
+the build fail until they match.
+
+Commit `dist/index.js` (the `path` declared in `data_app.yaml`), the app's
+collection files, and your source. The app appears at `/apps/<slug>` after
+Metabase's next remote-sync import (manual "Pull changes", auto-import, or
+startup), which also loads the collection files.
## Upgrading
@@ -46,7 +60,7 @@ your coding agent by the same command as the other data-app skills; do not edit
```
.
-├── data_app.yaml - manifest: version, name, bundle path, allowed_hosts
+├── data_app.yaml - manifest: version, name, bundle path, allowed_hosts, collection
├── package.json - @metabase/embedding-sdk-react + react/react-dom + Vite toolchain
├── vite.config.ts - one-liner: `export default dataAppConfig()`
├── tsconfig.json
@@ -64,8 +78,8 @@ your coding agent by the same command as the other data-app skills; do not edit
`queries/` and `actions/` are not optional: the query hooks accept only a
`defineQuery(...)` export and `useAction` only a `defineAction(...)` export, and
-`npm run build` synchronizes exactly those two directories to Metabase. Read
-their READMEs before the first hook call.
+each definition in those two directories is backed by a file in the app's collection under the repo's `collections/data_apps/`.
+Read their READMEs before the first hook call.
The build, dev server, Near-Membrane sandbox, and bundle contract all live in
the SDK behind `dataAppConfig()` — there's no `index.html` or separate dev entry
diff --git a/skills/metabase-data-app-setup/template/actions/README.md b/skills/metabase-data-app-setup/template/actions/README.md
index 14a912f7430..65d0877b1bb 100644
--- a/skills/metabase-data-app-setup/template/actions/README.md
+++ b/skills/metabase-data-app-setup/template/actions/README.md
@@ -14,6 +14,7 @@ import { defineAction } from "@metabase/embedding-sdk-react/data-app";
import schema from "../src/metabase.data";
export const CreateOrder = defineAction({
+ copiedActionEntityId: "<entity ID of the copy in the app's collection>",
action: schema.actions.createOrder,
});
```
@@ -51,16 +52,20 @@ export function CreateOrderForm({ onCreated }: { onCreated: () => void }) {
Rules:
-- This directory sits beside `package.json`, not under `src/`. Synchronization
- (`npm run sync-resources`, run by `npm run build`) scans only `queries/` and
- `actions/`, so a definition anywhere else is never synchronized, and the
- authored action is refused for the app's viewers in production.
+- This directory sits beside `package.json`, not under `src/`. The CLI scans
+ only `queries/` and `actions/`, so a definition anywhere else never gets a
+ copy, and the authored action is refused for the app's viewers in production.
- Actions exist only when the generated schema includes actions
- (`include-actions=true`). Synchronization copies actions; it never creates
- them, and a missing one is created as a query action without a model.
+ (`include-actions=true`). The app runs a copy of each action, written from
+ what `npm run print-resources` prints; it never creates actions.
- Pass the export itself to `useAction`. Never pass
`schema.actions.<action>` or its `.id`.
-- `copiedActionId` is written by synchronization. Never add, edit, or remove it
- by hand; commit it together with `resources_metadata.json`.
+- `copiedActionEntityId` is the entity ID of the action's copy in the app's
+ collection, under the repo's `collections/data_apps/`. After adding a
+ definition, write the copy there, run `npm run check-resources`, and commit
+ the definitions and the collection files together. `npm run build` fails
+ until they match.
+- Never copy a `copiedActionEntityId` to another definition, or remove it while
+ its copy exists.
- After `execute` resolves, refresh every query on screen the action could have
changed.
diff --git a/skills/metabase-data-app-setup/template/package.json b/skills/metabase-data-app-setup/template/package.json
index 32d2e236fc6..f839ea2c657 100644
--- a/skills/metabase-data-app-setup/template/package.json
+++ b/skills/metabase-data-app-setup/template/package.json
@@ -5,8 +5,9 @@
"type": "module",
"scripts": {
"dev": "vite --port 5174",
- "build": "npm run sync-resources && vite build",
- "sync-resources": "embedding-sdk-react data-apps sync-resources",
+ "build": "vite build",
+ "print-resources": "embedding-sdk-react data-apps print-resources",
+ "check-resources": "embedding-sdk-react data-apps check-resources && representations validate-schema --folder ../..",
"typecheck": "tsc --noEmit"
},
"dependencies": {
@@ -15,6 +16,7 @@
"react-dom": "^18.3.1"
},
"devDependencies": {
+ "@metabase/representations": "^1.5.1",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^6.0.2",
diff --git a/skills/metabase-data-app-setup/template/queries/README.md b/skills/metabase-data-app-setup/template/queries/README.md
index 1b7ffc88ca2..ee1267b070e 100644
--- a/skills/metabase-data-app-setup/template/queries/README.md
+++ b/skills/metabase-data-app-setup/template/queries/README.md
@@ -18,9 +18,14 @@ import schema from "../src/metabase.data";
const orders = schema.tables.orders;
-export const OrdersList = defineQuery({ source: orders, limit: 100 });
+export const OrdersList = defineQuery({
+ savedQuestionEntityId: "<entity ID of its saved question>",
+ source: orders,
+ limit: 100,
+});
export const OrdersByMonth = defineQuery({
+ savedQuestionEntityId: "<entity ID of its saved question>",
source: orders,
aggregations: [aggregations.count()],
breakouts: [breakout(orders.fields.createdAt, { unit: "month" })],
@@ -53,14 +58,21 @@ export function Overview() {
Rules:
-- This directory sits beside `package.json`, not under `src/`. `npm run
-sync-resources` (run by `npm run build`) scans only `queries/` and `actions/`,
- so a definition anywhere else is never synchronized and fails in production.
+- This directory sits beside `package.json`, not under `src/`. The CLI scans
+ only `queries/` and `actions/`, so a definition anywhere else never gets a
+ saved question and fails in production.
- Keep a definition static. A clause whose value comes from a control (a
selected filter, a date range, a search box) goes in the hook's second
argument, never inside `defineQuery`.
- One export per query the app renders. Filter-option queries, KPI queries, and
helper queries are queries too.
- Pass the export itself to the hook. Never spread or copy it.
-- `savedQuestionSourceId` is written by synchronization. Never add, edit, or
- remove it by hand; commit it together with `resources_metadata.json`.
+- Each definition carries `savedQuestionEntityId`, the entity ID of its saved
+ question in the app's collection, under the repo's `collections/data_apps/`.
+ After adding or changing a definition, update that card
+ (`npm run print-resources` shows what it must hold). A metric it aggregates
+ is copied into the app's collection too, written from what the same command
+ prints. Then run `npm run check-resources`, and commit the definitions and
+ the collection files together. `npm run build` fails until they match.
+- Never copy a `savedQuestionEntityId` to another definition, or remove it while
+ its card exists.
diff --git a/src/metabase/actions/db.clj b/src/metabase/actions/db.clj
index f1d7141e656..2eaeaf7230f 100644
--- a/src/metabase/actions/db.clj
+++ b/src/metabase/actions/db.clj
@@ -60,6 +60,14 @@
[card-id :- ::lib.schema.id/card]
(t2/select-one-fn :collection_id [:model/Card :collection_id] :id card-id))
+(mu/defn card-ids-outside-collection
+ "Among `card-ids`, the IDs of the Cards that are not in the Collection with `collection-id`."
+ [card-ids :- [:set ::lib.schema.id/card]
+ collection-id :- ::lib.schema.id/collection]
+ (t2/select-pks-set :model/Card {:where [:and
+ [:in :id card-ids]
+ [:or [:= :collection_id nil] [:not= :collection_id collection-id]]]}))
+
(mu/defn collection-exists?
"Whether the Collection with `collection-id` exists."
[collection-id :- ::lib.schema.id/collection]
diff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.clj
index 3b6f694606a..36e1dd680a2 100644
--- a/src/metabase/actions/models.clj
+++ b/src/metabase/actions/models.clj
@@ -1,5 +1,6 @@
(ns metabase.actions.models
(:require
+ [clojure.string :as str]
[medley.core :as m]
[metabase.actions.actions :as actions]
[metabase.actions.db :as actions.db]
@@ -160,7 +161,14 @@
(check-implicit-action-model model-id)
(check-implicit-actions-supported action))
(when (some #(contains? (t2/changes <>) %) [:collection_id :model_id])
- (check-collection-content <>)))))
+ (check-collection-content <>))
+ (let [in-data-app? (and (some? (:collection_id <>)) (perms/data-app-collection? (:collection_id <>)))]
+ ;; an export leaves out an archived action, and the next pull would then delete it from every instance
+ (when (and in-data-app? (changed? :archived) (:archived <>))
+ (throw (ex-info (tru "An action in a data app''s collection can''t be archived.") {:status-code 400})))
+ ;; an export writes the link into the action's file, which every pull then refuses
+ (when (and in-data-app? (changed? :public_uuid) (:public_uuid <>))
+ (throw (ex-info (tru "An action in a data app''s collection can''t be made public.") {:status-code 400})))))))
(defn- set-query-database
"`query-action` with the `:database_id` of its query, when it has one."
@@ -251,9 +259,34 @@
;;; ------------------------------------------------ CRUD fns -----------------------------------------------------
+(defn- query-card-ids
+ "The IDs of the Cards the native `query` reads through card template tags."
+ [query]
+ (into #{}
+ (keep (fn [path]
+ (let [{:keys [model id]} (last path)]
+ (when (= "Card" model) id))))
+ (serdes/mbql-deps true query)))
+
+(defn- check-data-app-action-query
+ "Throws when `query`, of an action in the Collection with `collection-id`, reads a card outside that collection
+ while the collection is a data app's."
+ [collection-id query]
+ ;; the next export writes the action into the app's files, and a pull refuses one that reads a card outside
+ (when (and (some? collection-id)
+ (perms/data-app-collection? collection-id))
+ (let [card-ids (query-card-ids query)
+ outside (when (seq card-ids)
+ (actions.db/card-ids-outside-collection card-ids collection-id))]
+ (when (seq outside)
+ (throw (ex-info (tru "An action in a data app''s collection can read only the app''s own cards, not card {0}."
+ (str/join ", " (sort outside)))
+ {:status-code 400}))))))
+
;;; TODO (Cam 10/2/25) -- this should just be the default Toucan 2 insert behavior for an action
(mu/defn- insert*! :- ::actions.schema/id
[action-data :- ::actions.schema/action.for-insert]
+ (check-data-app-action-query (:collection_id action-data) (:dataset_query action-data))
(t2/with-transaction [_conn]
(let [action (actions.db/insert-action! (select-keys action-data action-columns))
row (-> (apply dissoc action-data action-columns)
@@ -274,6 +307,12 @@
existing-action :- ::actions.schema/action]
(let [updates (cond-> (assoc updates :type (or (:type updates) (:type existing-action)))
(get updates :model_id (:model_id existing-action)) (dissoc :collection_id))]
+ (check-data-app-action-query (if (contains? updates :collection_id)
+ (:collection_id updates)
+ (:collection_id existing-action))
+ (if (contains? updates :dataset_query)
+ (:dataset_query updates)
+ (:dataset_query existing-action)))
(t2/with-transaction [_conn]
(when-let [action-row (not-empty (select-keys updates action-columns))]
(actions.db/update-action! id action-row))
diff --git a/src/metabase/app_db/custom_migrations.clj b/src/metabase/app_db/custom_migrations.clj
index 7f23f6285bd..e947a151161 100644
--- a/src/metabase/app_db/custom_migrations.clj
+++ b/src/metabase/app_db/custom_migrations.clj
@@ -2337,3 +2337,21 @@
(t2/reducible-query {:select [:id :name]
:from [:data_app]
:where [:= :resource_collection_id nil]})))
+
+(define-migration DeleteDataAppDrafts
+ ;; A draft reserved a data app's slug and resources before the app existed, for the SDK's query sync, which is
+ ;; gone. A draft has no bundle and can never be served, so the row goes, with the permission group made for it,
+ ;; as deleting an app deletes both. Its collection goes too when nothing was put in it; one that holds content
+ ;; stays for an admin to look at.
+ (doseq [{:keys [id resource_collection_id permission_group_id]} (t2/select :data_app :draft true)]
+ (t2/query {:delete-from :data_app :where [:= :id id]})
+ (when permission_group_id
+ (t2/query {:delete-from :permissions_group :where [:= :id permission_group_id]}))
+ (when resource_collection_id
+ (let [in-collection (fn [table] (t2/exists? table :collection_id resource_collection_id))
+ location (str "/" resource_collection_id "/")]
+ (when-not (or (some in-collection [:report_card :action :report_dashboard :document :timeline :pulse
+ :native_query_snippet :metabase_table :transform])
+ (t2/exists? :collection :location [:like (str location "%")]))
+ (t2/query {:delete-from :permissions :where [:= :collection_id resource_collection_id]})
+ (t2/query {:delete-from :collection :where [:= :id resource_collection_id]}))))))
diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.clj
index 5b11ebdb9d1..1f7e1e307b4 100644
--- a/src/metabase/collections/models/collection.clj
+++ b/src/metabase/collections/models/collection.clj
@@ -597,12 +597,27 @@
(tru "A Collection placed in a remote-synced Collection must also be remote-synced."))]
(throw (ex-info msg {:status-code 400, :errors {:location msg}})))))))
-(defenterprise check-allowed-content
- "Checks contents of a collection before saving it. The OSS implementation is a no-op."
+(defenterprise check-library-content
+ "Checks contents of a library collection before saving it. The OSS implementation is a no-op."
metabase-enterprise.library.validation
[_model-type _collection-id]
true)
+(defn check-allowed-content
+ "Checks the content of a collection before saving it. Throws when the collection with `collection-id` can't hold
+ content of `model-type`."
+ [model-type collection-id]
+ ;; a data app's collection holds only what a pull of the app accepts; a bookmark is a user's pointer, not content.
+ ;; A load checks every question as a possible dashboard question before its dashboard is known, so that is a
+ ;; question here.
+ (when (and collection-id
+ (some? model-type)
+ (not= :model/CollectionBookmark model-type)
+ (not (contains? #{:question :dashboard-question :metric :action} (keyword model-type)))
+ (perms/data-app-collection? collection-id))
+ (throw (ex-info "A data app's collection can hold only questions, metrics, and query actions" {:status-code 400})))
+ (check-library-content model-type collection-id))
+
(defenterprise check-library-update
"Checks that a collection of type `:library` only contains allowed changes."
metabase-enterprise.library.validation
@@ -1846,6 +1861,9 @@
:new-location new-location})))
(when (= (:type collection) tenant-specific-root-collection-type)
(throw (ex-info "Can't move a tenant collection" {:status-code 400})))
+ ;; an export writes a data app's collection under another as a file every pull refuses
+ (when (perms/data-app-collection? (:id collection))
+ (throw (ex-info "You cannot move a data app's collection." {:status-code 400})))
;; first move this Collection
(log/infof "Moving Collection %s and its descendants from %s to %s"
(u/the-id collection) (:location collection) new-location)
@@ -1880,7 +1898,8 @@
(assert-valid-location collection)
(assert-not-personal-collection-for-api-key collection)
(assert-valid-namespace (merge {:namespace nil} collection))
- (check-allowed-content (:type collection) (when-let [location (:location (t2/changes collection))] (location-path->parent-id location)))
+ ;; a collection without a type is a plain child collection, which a parent may refuse like any other content
+ (check-allowed-content (or (:type collection) :collection) (when-let [location (:location (t2/changes collection))] (location-path->parent-id location)))
(u/prog1 (-> collection
(assoc :slug (slugify collection-name))
(cond->
@@ -2068,6 +2087,12 @@
(api/check
(not (is-trash? collection-before-updates))
[400 "You cannot modify the Trash Collection."])
+ ;; an export leaves out a trashed collection, which would delete the app's resource files, and writes an
+ ;; official one into a file every pull refuses
+ (api/check
+ (not (and (or (:archived collection-updates) (some? (:authority_level collection-updates)))
+ (perms/data-app-collection? (:id collection-before-updates))))
+ [400 "You cannot move a data app's collection to the trash or make it official."])
;; VARIOUS CHECKS BEFORE DOING ANYTHING:
;; (1) if this is a personal Collection, check that the 'propsed' changes are allowed
(when (or (:personal_owner_id collection-before-updates)
@@ -2083,7 +2108,7 @@
(throw (ex-info msg {:status-code 400, :errors {:namespace msg}})))))
(assert-valid-namespace (merge (select-keys collection-before-updates [:namespace]) collection-updates))
;; (3.6) Check that the parent collection allows this collection to be there
- (check-allowed-content (:type collection) (when-let [location (:location collection)] (location-path->parent-id location)))
+ (check-allowed-content (or (:type collection) :collection) (when-let [location (:location collection)] (location-path->parent-id location)))
;; (3.7) Check if it's a semantic-library collection that can't be updated
(check-library-update collection)
;; (4) If we're moving a Collection from a location on a Personal Collection hierarchy to a location not on one,
@@ -2226,14 +2251,8 @@
(merge child-colls dashboards cards documents timelines actions tables transforms)))
(defmethod serdes/storage-path "Collection" [coll {:keys [collections]}]
- (let [path (get collections (:entity_id coll))
- ns-folder (case (:namespace coll)
- :snippets "snippets"
- :transforms "transforms"
- :data-actions "data-actions"
- nil "main"
- "main")]
- (into [{:label "collections"} {:label ns-folder}] path)))
+ (into [{:label "collections"} {:label (serdes/collection-namespace-folder (:namespace coll))}]
+ (get collections (:entity_id coll))))
(defn- parent-id->location-path [parent-id]
(if-not parent-id
diff --git a/src/metabase/internal_stats/data_apps.clj b/src/metabase/internal_stats/data_apps.clj
index ad38a434bac..151e222f43e 100644
--- a/src/metabase/internal_stats/data_apps.clj
+++ b/src/metabase/internal_stats/data_apps.clj
@@ -3,6 +3,6 @@
[metabase.internal-stats.db :as internal-stats.db]))
(defn data-app-stats
- "How many data apps this instance actually serves: enabled ones that aren't drafts."
+ "How many data apps this instance actually serves: the enabled ones."
[]
{:data-app-count (internal-stats.db/enabled-data-app-count)})
diff --git a/src/metabase/internal_stats/db.clj b/src/metabase/internal_stats/db.clj
index dc50df1866c..75d7aa287b5 100644
--- a/src/metabase/internal_stats/db.clj
+++ b/src/metabase/internal_stats/db.clj
@@ -10,9 +10,9 @@
[toucan2.core :as t2]))
(mu/defn enabled-data-app-count
- "The number of enabled data apps that aren't drafts."
+ "The number of enabled data apps."
[]
- (t2/count :data_app :enabled true :draft false))
+ (t2/count :data_app :enabled true))
(mu/defn embedded-dashboard-count
"The number of unarchived Dashboards with embedding enabled."
diff --git a/src/metabase/models/db.clj b/src/metabase/models/db.clj
index b88e61278c4..df9f956885e 100644
--- a/src/metabase/models/db.clj
+++ b/src/metabase/models/db.clj
@@ -221,9 +221,9 @@
(t2/delete! model parent-column parent-id :entity_id [:not-in entity-ids]))
(mu/defn collection-paths-columns
- "The id, entity id, location, and name of every Collection."
+ "The id, entity id, location, name, and namespace of every Collection."
[]
- (t2/select [:model/Collection :id :entity_id :location :name]))
+ (t2/select [:model/Collection :id :entity_id :location :name :namespace]))
(mu/defn dashboard-entity-ids-and-names
"The entity id and name of every Dashboard."
diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.clj
index 8d656102bdd..042e8a1ff56 100644
--- a/src/metabase/models/serialization.clj
+++ b/src/metabase/models/serialization.clj
@@ -784,14 +784,26 @@
[id-str]
(resolve/entity-id? id-str))
+(defn collection-namespace-folder
+ "The folder under `collections/` that holds the collections of `collection-namespace`, `main` for the default one.
+ The `data-apps` namespace is the `data_apps` folder, spelled like the top-level directory of the apps themselves."
+ [collection-namespace]
+ (case (some-> collection-namespace keyword)
+ :snippets "snippets"
+ :transforms "transforms"
+ :data-actions "data-actions"
+ :data-apps "data_apps"
+ "main"))
+
(defn storage-default-collection-path
"Implements the most common structure for [[storage-path]].
Returns a vector of maps with `:label` and `:key` for each path segment.
- Result: `[{:label \"collections\"} {:label ns-folder} <collection-hierarchy> {:label entity-name :key entity_id}]`"
+ Result: `[{:label \"collections\"} {:label ns-folder} <collection-hierarchy> {:label entity-name :key entity_id}]`.
+ The folder is the one of the entity's collection's namespace when it has a collection, `ns-folder` otherwise."
([entity ctx]
(storage-default-collection-path entity ctx "main"))
- ([entity {:keys [collections]} ns-folder]
- (into [{:label "collections"} {:label ns-folder}]
+ ([entity {:keys [collections collection-namespace-folders]} ns-folder]
+ (into [{:label "collections"} {:label (get collection-namespace-folders (:collection_id entity) ns-folder)}]
cat [(get collections (:collection_id entity))
[{:label (:name entity) :key (:entity_id entity)}]])))
@@ -813,6 +825,8 @@
the collection hierarchy.
- `:dashboards` maps dashboard entity_id to `{:label ... :key ...}` for use as virtual subcollections.
- `:documents` maps document entity_id to `{:label ... :key ...}` for use as virtual subcollections.
+ - `:collection-namespace-folders` maps collection entity_id to the folder under `collections/` its namespace
+ is written to (see [[collection-namespace-folder]]).
- `:unique-name-fns` is an atom of `{parent-key -> unique-name-fn}` where each `unique-name-fn` is a
`lib/non-truncating-unique-name-generator`, used to deduplicate names within the same folder during export."
[]
@@ -834,6 +848,9 @@
(for [{:keys [entity_id name]} (models.db/document-entity-ids-and-names)]
[entity_id {:label name :key entity_id}]))]
{:collections coll->path
+ :collection-namespace-folders (into {}
+ (for [{:keys [entity_id namespace]} colls]
+ [entity_id (collection-namespace-folder namespace)]))
:dashboards dashboards
:documents documents
:unique-name-fns (atom {})}))
diff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.clj
index a72088f2503..75b5c272739 100644
--- a/src/metabase/permissions/core.clj
+++ b/src/metabase/permissions/core.clj
@@ -42,6 +42,7 @@
batch-delete-permissions!
batch-insert-permissions!
data-app-collection-ids
+ data-app-collection?
data-app-group-ids
data-app-view-data-permission-level
disable-perms-cache
diff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.clj
index f36954389e9..8f4756cc07d 100644
--- a/src/metabase/permissions/models/data_permissions.clj
+++ b/src/metabase/permissions/models/data_permissions.clj
@@ -1348,6 +1348,12 @@
[]
#{})
+(defenterprise data-app-collection?
+ "Whether the collection with `collection-id` is one a data app owns. OSS has none."
+ metabase-enterprise.data-apps.models.data-app
+ [_collection-id]
+ false)
+
(defenterprise new-table-sandboxed-groups
"Returns the subset of `group-ids` whose new tables on `db-id` have a sandbox somewhere in this DB, and must therefore
have their `view-data` forced to `:blocked` regardless of the new table's schema.
diff --git a/src/metabase/queries/card_write_checks.clj b/src/metabase/queries/card_write_checks.clj
index 980f264e63c..144b26b55e0 100644
--- a/src/metabase/queries/card_write_checks.clj
+++ b/src/metabase/queries/card_write_checks.clj
@@ -120,6 +120,14 @@
(api/create-check :model/Card {:collection_id (actual-collection-id card)})
(check-no-save-cycle! ::no-id query)))
+(defn check-allowed-to-delete-card!
+ "Throw a 400 when `card` is in a data app's collection and another card there reads it. For `DELETE /api/card/:id`
+ rather than the delete hook: deleting the collection deletes its cards together, readers and read."
+ [{:keys [id collection_id]}]
+ (when-let [reader (card/data-app-card-reader collection_id id)]
+ (throw (ex-info (tru "Card {0} in the data app''s collection reads this card, so it can''t be deleted." reader)
+ {:status-code 400}))))
+
(mu/defn check-allowed-to-update-card!
"The post-write permission/validation stack for updating a card, mirroring `PUT /api/card/:id`.
Run *after* the card's write-check: `card-before-update` is the existing card, `card-updates`
diff --git a/src/metabase/queries/core.clj b/src/metabase/queries/core.clj
index 3b07446c5bc..5374abe9bd1 100644
--- a/src/metabase/queries/core.clj
+++ b/src/metabase/queries/core.clj
@@ -33,8 +33,7 @@
card-param-remapped-value]
[metabase.queries.db
card-query-info
- cards-queries-info
- move-actions-of-models!]
+ cards-queries-info]
[metabase.queries.models.card
check-shared-dashboard-timeline-permissions!
check-newly-exposed-dashcards-timeline-permissions!
@@ -46,6 +45,7 @@
[metabase.queries.card-write-checks
actual-collection-id
check-allowed-to-create-card!
+ check-allowed-to-delete-card!
check-allowed-to-run-query!
check-allowed-to-update-card!
check-card-can-be-saved!
diff --git a/src/metabase/queries/db.clj b/src/metabase/queries/db.clj
index 0e9acc5eeef..66d6b744518 100644
--- a/src/metabase/queries/db.clj
+++ b/src/metabase/queries/db.clj
@@ -589,3 +589,15 @@
:id [:in ^:allow-subquery {:select [:stored_result_id]
:from [:stored_result_use]
:where [:= :card_id card-id]}]))
+
+(defn card-ids-outside-collection
+ "Among `card-ids`, the IDs of the cards that are not in the collection with `collection-id`."
+ [card-ids collection-id]
+ (t2/select-pks-set :model/Card {:where [:and
+ [:in :id card-ids]
+ [:or [:= :collection_id nil] [:not= :collection_id collection-id]]]}))
+
+(defn other-cards-in-collection
+ "The cards in the collection with `collection-id`, leaving out the card with `card-id`."
+ [collection-id card-id]
+ (t2/select :model/Card :collection_id collection-id :id [:not= card-id]))
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index 89181c75e95..0f02d5a598f 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -4,6 +4,7 @@
(:require
[better-cond.core :as b]
[clojure.set :as set]
+ [clojure.string :as str]
[honey.sql.helpers :as sql.helpers]
[medley.core :as m]
[metabase.analytics-interface.core :as analytics]
@@ -993,6 +994,53 @@
:dashboard-question
(:type card)))
+(defn- check-data-app-card
+ "Throws unless `card`, when it is in a data app's collection, is what a pull of the app accepts: a question or
+ metric that is not archived, public or embedded, reading no card outside the collection. The next export writes
+ the card into the app's files, and every pull refuses a file that says otherwise."
+ [{:keys [collection_id] :as card}]
+ (when (and (some? collection_id)
+ (perms/data-app-collection? collection_id))
+ ;; a new card without a type is a question, the column's default
+ (when (or (not (contains? #{:question :metric} (keyword (or (:type card) :question))))
+ (:archived card)
+ (:public_uuid card)
+ (:enable_embedding card)
+ (:embedding_params card)
+ (:embedding_type card))
+ (throw (ex-info "A card in a data app's collection must be a question or metric that is not archived, public or embedded"
+ {:status-code 400})))
+ (let [card-ids (into #{}
+ (keep (fn [path]
+ (let [{:keys [model id]} (last path)]
+ (when (= "Card" model) id))))
+ (serdes/serialization-dependencies "Card" card))
+ outside (when (seq card-ids)
+ (queries.db/card-ids-outside-collection card-ids collection_id))]
+ (when (seq outside)
+ (throw (ex-info (str "A card in a data app's collection can read only the app's own cards, not card "
+ (str/join ", " (sort outside)))
+ {:status-code 400}))))))
+
+(defn data-app-card-reader
+ "The ID of a card in the data app's collection `collection-id` that reads the card with `card-id`, if one does."
+ [collection-id card-id]
+ (when (and (some? collection-id)
+ (perms/data-app-collection? collection-id))
+ (some (fn [other]
+ (when (some #(= {:model "Card" :id card-id} (select-keys (last %) [:model :id]))
+ (serdes/serialization-dependencies "Card" other))
+ (:id other)))
+ (queries.db/other-cards-in-collection collection-id card-id))))
+
+(defn- check-data-app-card-stays
+ "Throws when the card with `id` leaves the data app's collection `from` while another card there reads it."
+ [id from]
+ ;; the next export would write the reader into a file every pull refuses
+ (when-let [reader (data-app-card-reader from id)]
+ (throw (ex-info (tru "Card {0} in the data app''s collection reads this card, so it can''t leave the collection." reader)
+ {:status-code 400}))))
+
(t2/define-before-insert :model/Card
[card]
(check-timeline-visibility-permissions! card *copy-source-card*)
@@ -1008,7 +1056,8 @@
pre-insert
populate-query-fields
public-sharing/add-public-uuid-prefix)
- (collection/check-allowed-content (library-content-type <> mi/*deserializing?*) (:collection_id <>))))
+ (collection/check-allowed-content (library-content-type <> mi/*deserializing?*) (:collection_id <>))
+ (check-data-app-card <>)))
(t2/define-after-insert :model/Card
[card]
@@ -1077,6 +1126,8 @@
(when (or (contains? changes :visualization_settings) (contains? changes :display))
(check-timeline-visibility-permissions! card original))
(check-allowed-content card changes)
+ (when (contains? changes :collection_id)
+ (check-data-app-card-stays (:id card) (:collection_id original)))
(-> card
(dissoc :verified-result-metadata?)
(migrate-schema-governed-columns original changes)
@@ -1086,6 +1137,8 @@
;; populate-query-fields must run before pre-update in case source_card_id should be nilled.
;; Only allow it to nil out a stale table_id when the query itself is changing.
(populate-query-fields (contains? changes :dataset_query))
+ ;; after the query's columns are set again: `source_card_id` is one of the references it reads
+ (doto check-data-app-card)
(clear-metabot-origin changes)
(pre-update changes)
(move-model-actions original)
diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.clj
index 5cd342756ee..b29dbfcbfea 100644
--- a/src/metabase/queries_rest/api/card.clj
+++ b/src/metabase/queries_rest/api/card.clj
@@ -673,6 +673,7 @@
(let [card (api/write-check :model/Card id)
;; the database deletes the card's actions through the foreign key, with no events of their own
actions (queries-rest.db/actions-for-model id)]
+ (queries/check-allowed-to-delete-card! card)
(queries-rest.db/delete-card! id)
(events/publish-event! :event/card-delete {:object card :user-id api/*current-user-id*})
(doseq [action actions]
@@ -716,7 +717,9 @@
(api/write-check :model/Collection new-collection-id-or-nil))
;; for each affected card...
(when (seq card-ids)
- (let [cards (queries-rest.db/cards-to-move-to-collection (set card-ids) new-collection-id-or-nil)] ; poisioned NULLs = ick
+ (let [cards (queries-rest.db/cards-to-move-to-collection (set card-ids) new-collection-id-or-nil) ; poisioned NULLs = ick
+ ;; whole, as the update event's previous object: a listener reads a card's metadata from it
+ before (when (seq cards) (queries-rest.db/cards-by-id (map u/the-id cards)))]
;; ...check that we have write permissions for it...
(doseq [card cards]
(api/write-check card))
@@ -732,14 +735,18 @@
;; are gone and update the position in the new collection
(when-let [cards-with-position (seq (filter :collection_position cards))]
(update-collection-positions! new-collection-id-or-nil cards-with-position))
- ;; ok, everything checks out. Set the new `collection_id` for all the Cards that haven't been updated already
- (when-let [cards-without-position (seq (for [card cards
- :when (not (:collection_position card))]
- (u/the-id card)))]
- (queries-rest.db/set-cards-collection-raw! (set cards-without-position) new-collection-id-or-nil)
- (queries/move-actions-of-models! (set cards-without-position) new-collection-id-or-nil))
+ ;; ok, everything checks out. Set the new `collection_id` for all the Cards that haven't been updated already,
+ ;; through the model, so that each card's checks run and its hooks move what moves with it
+ (doseq [card cards
+ :when (not (:collection_position card))]
+ (queries-rest.db/update-card! (u/the-id card) {:collection_id new-collection-id-or-nil}))
(doseq [card cards]
- (collection/check-for-remote-sync-update card)))))
+ (collection/check-for-remote-sync-update card)))
+ ;; what a single card's update publishes too: remote sync listens to learn what entered or left its scope
+ (doseq [card cards]
+ (events/publish-event! :event/card-update {:object (queries-rest.db/card (u/the-id card))
+ :previous-object (get before (u/the-id card))
+ :user-id api/*current-user-id*}))))
(when new-collection-id-or-nil
(events/publish-event! :event/collection-touch {:collection-id new-collection-id-or-nil :user-id api/*current-user-id*})))
diff --git a/src/metabase/queries_rest/db.clj b/src/metabase/queries_rest/db.clj
index 79905fcaeff..61981cf8aeb 100644
--- a/src/metabase/queries_rest/db.clj
+++ b/src/metabase/queries_rest/db.clj
@@ -170,12 +170,6 @@
(when new-collection-id-or-nil
[:= :collection_id nil])]]}))
-(mu/defn set-cards-collection-raw!
- "Move the Cards with `card-ids` to the Collection with `collection-id` without running model hooks."
- [card-ids :- [:set ::lib.schema.id/card]
- collection-id :- [:maybe ::lib.schema.id/collection]]
- (t2/update! (t2/table-name :model/Card) {:id [:in card-ids]} {:collection_id collection-id}))
-
(mu/defn stored-result
"The StoredResult with `id`, or nil."
[id :- ms/PositiveInt]
diff --git a/src/metabase/typed_schemas/build.clj b/src/metabase/typed_schemas/build.clj
index a2f5097d22a..e89a24ad656 100644
--- a/src/metabase/typed_schemas/build.clj
+++ b/src/metabase/typed_schemas/build.clj
@@ -94,8 +94,7 @@
This is the only impure stage of the pipeline: everything downstream of the
returned [[Items]] is pure. All reads go through a
[[metabase.typed-schemas.source/SchemaSource]] — the application database by
- default, filtered to what the current user can read; tests reify the
- protocol with literal values."
+ default; tests reify the protocol with literal values."
([options]
(fetch-items options source/app-db-source))
([options source]
diff --git a/src/metabase/typed_schemas/core.clj b/src/metabase/typed_schemas/core.clj
index e42d11ba681..da8d89d275f 100644
--- a/src/metabase/typed_schemas/core.clj
+++ b/src/metabase/typed_schemas/core.clj
@@ -1,8 +1,8 @@
(ns metabase.typed-schemas.core
"Typed schemas: TypeScript modules that describe questions, actions, tables
and metrics to coding agents. Runtime objects
- feed the Lib.createTestQuery DSL; `//` comments carry context for humans and
- agents.
+ feed the Lib.createTestQuery DSL; each entry's `/* metadata: {...} */` block
+ carries context for humans and agents.
The public surface is deliberately small — the schema value and its
rendering, mirroring the module's data/print split:
@@ -10,9 +10,11 @@
(-> options build-semantic-schema render-typescript) ; options -> TS string
These public functions are compositions of the internal pipeline stages;
- their definitions below show the whole pipeline. Fetching filters by what
- the current user can read, so callers outside a request must bind a
- current-user context first.
+ their definitions below show the whole pipeline. The schema is for
+ superusers, so fetching no longer filters by what the caller can read. The
+ table and metric details lookups still read-check the current user, so a
+ non-admin calling [[build-semantic-schema]] gets a 403, and callers outside
+ a request must bind a current-user context first.
Keep the separation when extending this module:
@@ -22,7 +24,7 @@
- Everything downstream of fetched items stays pure. Timestamps, site URL,
and any other environment values enter through the `info` argument, not by
calling out from assembly or rendering code.
- - Which keys render as runtime data vs comments is policy in
+ - Which keys render as runtime data vs metadata is policy in
`metabase.typed-schemas.render`; TypeScript syntax lives only in the
`metabase.typed-schemas.javascript` printer.
- REST query-parameter strings are decoded once, in
diff --git a/src/metabase/typed_schemas/db.clj b/src/metabase/typed_schemas/db.clj
index 031dd0a1ea6..51a0d6225f2 100644
--- a/src/metabase/typed_schemas/db.clj
+++ b/src/metabase/typed_schemas/db.clj
@@ -2,7 +2,6 @@
"Application database queries for the typed schemas module. Every function here is a direct Toucan 2 call with no
additional logic, so the rest of the module never talks to `toucan2.core` itself."
(:require
- [metabase.collections.models.collection :as collection]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.queries.core :as queries]
[metabase.util.malli :as mu]
@@ -25,8 +24,9 @@
[:= column -1])))
(mu/defn cards-ordered-by-name
- "The readable, non-archived Cards of `card-type` among `database-ids` and/or `collection-ids` (either nil for
- unscoped), in name then id order."
+ "The non-archived Cards of `card-type` among `database-ids` and/or `collection-ids` (either nil for unscoped), in
+ name then id order. The schema is for superusers, who see every collection, and what an archived collection or
+ the trash holds is archived itself."
[card-type :- [:enum :model :question :metric]
database-ids :- [:maybe [:set ::lib.schema.id/database]]
collection-ids :- [:maybe [:set ::lib.schema.id/collection]]]
@@ -34,7 +34,6 @@
{:where [:and
[:= :type (name card-type)]
[:= :archived false]
- (collection/visible-collection-filter-clause :collection_id)
(scope-filter-clause database-ids :database_id)
(scope-filter-clause collection-ids :collection_id)]
:order-by [[:name :asc] [:id :asc]]}))
@@ -56,8 +55,8 @@
(t2/select [:model/Table :id :db_id :name :display_name] :id [:in table-ids] {:from [(warehouse-schema-overlay/table-query)]}))
(mu/defn model-less-query-action-ids
- "The ids of the unarchived query Actions without a model in collections the current user can see, outside
- `excluded-collection-ids`, among `database-ids` (nil for unscoped), in name then id order."
+ "The ids of the unarchived query Actions without a model outside `excluded-collection-ids`, among `database-ids`
+ (nil for unscoped), in name then id order."
[database-ids :- [:maybe [:set ::lib.schema.id/database]]
excluded-collection-ids :- [:set ::lib.schema.id/collection]]
(t2/select-pks-vec :model/Action
@@ -65,8 +64,6 @@
[:= :model_id nil]
[:= :type "query"]
[:= :archived false]
- (collection/visible-collection-filter-clause :collection_id
- {:root-namespace collection/data-actions-ns})
(when (seq excluded-collection-ids)
[:or [:= :collection_id nil] [:not-in :collection_id excluded-collection-ids]])
(when database-ids
diff --git a/src/metabase/typed_schemas/javascript.clj b/src/metabase/typed_schemas/javascript.clj
index e69e5e2a6e8..2f5f21a3c04 100644
--- a/src/metabase/typed_schemas/javascript.clj
+++ b/src/metabase/typed_schemas/javascript.clj
@@ -10,10 +10,12 @@
[:arr expr-or-item ...] ; array literal
[:obj entry ...] ; object literal
- Object entries are `[key expr]` or `[key {:comments [...]} expr]`; array
- items are bare expressions or `[:item {:comments [...]} expr]`. Comments are
- plain strings; the printer prefixes them with `//` on their own lines above
- the entry. Statements:
+ Object entries are `[key expr]` or `[key {:metadata {...}} obj]`; array
+ items are bare expressions or `[:item {:metadata {...}} obj]`, where `obj`
+ is an `[:obj ...]`. Metadata is a JSON-encodable map, printed as a
+ `/* metadata: {...} */` block first inside the entry's object, before its
+ properties, so a reader meets it before the data it describes and it never
+ reaches runtime code. Statements:
[:const \"tables\" expr] ; const tables = <expr> as const;
[:raw \"function helper() {...}\"] ; verbatim TypeScript
@@ -24,7 +26,7 @@
[:module
[:const \"tables\"
- [:obj [\"orders\" {:comments [\"Entity ID: abc123\"]}
+ [:obj [\"orders\" {:metadata {\"entityId\" \"abc123\"}}
[:obj [\"type\" [:lit \"table\"]]
[\"ids\" [:arr [:lit 1] [:lit 2]]]]]]]
[:export-default [:ref \"tables\"]]]
@@ -32,8 +34,8 @@
prints as:
const tables = {
- // Entity ID: abc123
orders: {
+ /* metadata: { \"entityId\": \"abc123\" } */
type: \"table\",
ids: [ 1, 2 ]
}
@@ -43,11 +45,14 @@
Rendering rules: arrays whose items are all literals print on one line;
`:call` arguments always print inline; object keys print bare when they are
- valid JavaScript identifiers and quoted otherwise. [[render-js]] prints a
- `:module`; [[Module]] is the Malli schema for the whole grammar.
+ valid JavaScript identifiers and quoted otherwise. A metadata block whose
+ values are all scalars prints on one line, so a field costs a reader one line
+ of the file; one with a nested array or object prints as
+ `JSON.stringify(x, null, 2)` would, one array item per line. [[render-js]]
+ prints a `:module`; [[Module]] is the Malli schema for the whole grammar.
The printer is deliberately option-free and policy-free: decisions about
- *what* to emit (runtime keys, comments, compaction) belong in
+ *what* to emit (runtime keys, metadata, compaction) belong in
`metabase.typed-schemas.render`, which builds this AST. If the output needs
new syntax, add a node type and its printer here rather than concatenating
TypeScript strings elsewhere."
@@ -67,12 +72,14 @@
(def Module
"Malli schema for the TypeScript AST accepted by [[render-js]]."
[:schema {:registry
- {::comment-options [:map {:closed true}
- [:comments {:optional true} [:sequential :string]]]
- ::entry [:or
- [:tuple key-schema [:ref ::expr]]
- [:tuple key-schema [:ref ::comment-options] [:ref ::expr]]]
- ::item [:tuple [:= :item] [:ref ::comment-options] [:ref ::expr]]
+ {::entry-options [:map {:closed true}
+ [:metadata {:optional true} [:map-of key-schema :any]]]
+ ;; Metadata prints as a block inside the entry's object, so only an object can carry it.
+ ::entry [:or
+ [:tuple key-schema [:ref ::expr]]
+ [:tuple key-schema [:ref ::entry-options] [:ref ::obj]]]
+ ::item [:tuple [:= :item] [:ref ::entry-options] [:ref ::obj]]
+ ::obj [:cat [:= :obj] [:* [:schema [:ref ::entry]]]]
::expr [:multi {:dispatch first}
[:lit [:tuple [:= :lit] :any]]
[:ref [:cat [:= :ref] [:+ key-schema]]]
@@ -80,7 +87,7 @@
[:arr [:cat [:= :arr] [:* [:or
[:schema [:ref ::item]]
[:schema [:ref ::expr]]]]]]
- [:obj [:cat [:= :obj] [:* [:schema [:ref ::entry]]]]]]
+ [:obj [:ref ::obj]]]
::statement [:multi {:dispatch first}
[:const [:tuple [:= :const] key-schema [:ref ::expr]]]
[:raw [:tuple [:= :raw] :string]]
@@ -128,24 +135,38 @@
(str "[" (json/encode segment-name) "]")))))))
(defn- entry-parts
- "Returns `[key comment-options expr]` for either entry form."
+ "Returns `[key entry-options expr]` for either entry form."
[entry]
(if (= 3 (count entry))
entry
[(first entry) nil (second entry)]))
(defn- item-parts
- "Returns `[comment-options expr]` for either array item form."
+ "Returns `[entry-options expr]` for either array item form."
[item]
(if (and (vector? item) (= :item (first item)))
[(second item) (nth item 2)]
[nil item]))
-(defn- comment-block
- "Returns `// ...` comment lines followed by a newline, or nil without comments."
- [indent comments]
- (when (seq comments)
- (str (str/join "\n" (map #(str (spaces indent) "// " %) comments)) "\n")))
+(defn- metadata-json
+ "Renders `metadata` as JSON: on one line when every value is a scalar, otherwise as `JSON.stringify(x, null, 2)`
+ would, with each line after the first indented by `indent`."
+ [metadata indent]
+ (if (not-any? coll? (vals metadata))
+ (str "{ "
+ (str/join ", " (for [[k v] metadata]
+ (str (json/encode (u/qualified-name k)) ": " (json/encode v))))
+ " }")
+ (str/replace (json/encode metadata {:pretty {:indent-arrays? true :object-field-value-separator ": "}})
+ "\n" (str "\n" (spaces indent)))))
+
+(defn- metadata-block
+ "Returns a `/* metadata: {...} */` block. A `*/` can only occur inside a JSON string, where it is written as the
+ equivalent `*\\/`, so the block always ends where it should."
+ [indent metadata]
+ (str (spaces indent) "/* metadata: "
+ (str/replace (metadata-json metadata indent) "*/" "*\\/")
+ " */"))
(declare render-expression)
@@ -160,8 +181,13 @@
:arr (str "[ " (str/join ", " (map render-inline (rest node))) " ]")
:obj (str "{ "
(str/join ", " (for [entry (rest node)
- :let [[entry-key _ expr] (entry-parts entry)]]
- (str (javascript-key entry-key) ": " (render-inline expr))))
+ :let [[entry-key options expr] (entry-parts entry)]]
+ (do
+ ;; An inline object has no room for a block, so refuse rather than drop it.
+ (when (seq (:metadata options))
+ (throw (ex-info "Metadata can only be attached to an object on its own lines."
+ {:node node})))
+ (str (javascript-key entry-key) ": " (render-inline expr)))))
" }")))
(defn- literal-node?
@@ -169,20 +195,20 @@
(and (vector? node) (= :lit (first node))))
(defn- render-object
- [entries indent]
- (if (empty? entries)
- "{ }"
- (str "{\n"
- (str/join ",\n"
- (for [entry entries
- :let [[entry-key options expr] (entry-parts entry)
- entry-indent (+ indent 2)]]
- (str (comment-block entry-indent (:comments options))
- (spaces entry-indent)
- (javascript-key entry-key)
- ": "
- (render-expression expr entry-indent))))
- "\n" (spaces indent) "}")))
+ [entries indent metadata]
+ (let [inner-indent (+ indent 2)
+ lines (for [entry entries
+ :let [[entry-key options expr] (entry-parts entry)]]
+ (str (spaces inner-indent)
+ (javascript-key entry-key)
+ ": "
+ (render-expression expr inner-indent (:metadata options))))
+ ;; the block comes first, so a reader meets it before the properties it describes
+ body (str/join "\n" (remove str/blank? [(when (seq metadata) (metadata-block inner-indent metadata))
+ (str/join ",\n" lines)]))]
+ (if (str/blank? body)
+ "{ }"
+ (str "{\n" body "\n" (spaces indent) "}"))))
(defn- render-array
[items indent]
@@ -199,19 +225,23 @@
(for [item items
:let [[options expr] (item-parts item)
item-indent (+ indent 2)]]
- (str (comment-block item-indent (:comments options))
- (spaces item-indent)
- (render-expression expr item-indent))))
+ (str (spaces item-indent)
+ (render-expression expr item-indent (:metadata options)))))
"\n" (spaces indent) "]")))
(defn- render-expression
- [node indent]
- (case (first node)
- :lit (json/encode (second node))
- :ref (reference-path (rest node))
- :call (render-inline node)
- :obj (render-object (rest node) indent)
- :arr (render-array (rest node) indent)))
+ "Renders `node` at `indent`. `metadata`, when present, prints inside `node`, which must then be an object."
+ ([node indent]
+ (render-expression node indent nil))
+ ([node indent metadata]
+ (when (and (seq metadata) (not= :obj (first node)))
+ (throw (ex-info "Metadata can only be attached to an object." {:node node})))
+ (case (first node)
+ :lit (json/encode (second node))
+ :ref (reference-path (rest node))
+ :call (render-inline node)
+ :obj (render-object (rest node) indent metadata)
+ :arr (render-array (rest node) indent))))
(defn- render-statement
[statement]
diff --git a/src/metabase/typed_schemas/render.clj b/src/metabase/typed_schemas/render.clj
index 1353e07afd8..27aae76e987 100644
--- a/src/metabase/typed_schemas/render.clj
+++ b/src/metabase/typed_schemas/render.clj
@@ -2,7 +2,7 @@
"Converts semantic schema values into the TypeScript AST.
This is the pure policy stage of the typed-schema pipeline: it decides which
- schema keys become runtime data, which become `//` context comments, and how
+ schema keys become runtime data, which become `/* metadata */` blocks, and how
metric dimensions compact into `pickFields(...)` calls. The output is the
tagged-vector AST described in [[metabase.typed-schemas.javascript]];
[[schema->ast]] produces it, and the public
@@ -21,29 +21,29 @@
;; The rendered schema serves two audiences:
;; - `:runtime` keys are executable data consumed by the Lib.createTestQuery DSL.
-;; - `:comment` keys are emitted as nearby JavaScript comments for coding agents
-;; and humans, preserving useful context without making the runtime object
-;; larger or more ambiguous than the DSL needs.
+;; - `:metadata` keys are emitted as a `/* metadata: {...} */` block inside the
+;; entity for coding agents and humans, preserving useful context without
+;; making the runtime object larger or more ambiguous than the DSL needs.
(def ^:private schema-render-policy
- {:question {:runtime [:type :id :name :display :columns :parameters]
- :comment [:entityId :description :verified]}
- :table {:runtime [:type :id :name :fields :segments :measures]
- :comment [:entityId :description :databaseName :schemaName :tableName]}
- :field {:runtime [:type :name :sourceName :jsType :fieldId :tableId
- :baseType :effectiveType :defaultTemporalBucket]
- :comment [:displayName :description :semanticType :unit]}
- :segment {:runtime [:type :id :tableId :name]
- :comment [:entityId :description]}
- :measure {:runtime [:type :id :tableId :name :columns]
- :comment [:entityId :description]}
- :metric {:runtime [:type :id :name :databaseId :sourceTableId :sourceCardId
- :mappedTableIds :columns :dimensions]
- :comment [:entityId :description :filters :verified :sourceTable]}
- :metric-dimension {:runtime [:type :id :fieldId :metricId :tableId :sourceName :sourceFieldId
- :name :jsType :baseType :effectiveType :defaultTemporalBucket]
- :comment [:displayName :description :semanticType :unit]}
- :column {:runtime [:type :name :jsType]
- :comment [:displayName :description :baseType :effectiveType :semanticType :unit]}})
+ {:question {:runtime [:type :id :name :display :columns :parameters]
+ :metadata [:entityId :description :verified]}
+ :table {:runtime [:type :id :name :fields :segments :measures]
+ :metadata [:entityId :description :databaseName :schemaName :tableName]}
+ :field {:runtime [:type :name :sourceName :jsType :fieldId :tableId
+ :baseType :effectiveType :defaultTemporalBucket]
+ :metadata [:displayName :description :semanticType :unit]}
+ :segment {:runtime [:type :id :tableId :name]
+ :metadata [:entityId :description]}
+ :measure {:runtime [:type :id :tableId :name :columns]
+ :metadata [:entityId :description]}
+ :metric {:runtime [:type :id :name :databaseId :sourceTableId :sourceCardId
+ :mappedTableIds :columns :dimensions]
+ :metadata [:entityId :description :filters :verified :sourceTable]}
+ :metric-dimension {:runtime [:type :id :fieldId :metricId :tableId :sourceName :sourceFieldId
+ :name :jsType :baseType :effectiveType :defaultTemporalBucket]
+ :metadata [:displayName :description :semanticType :unit]}
+ :column {:runtime [:type :name :jsType]
+ :metadata [:displayName :description :baseType :effectiveType :semanticType :unit]}})
;; Nested entity kinds by parent kind and entry key. Map values hold keyed
;; entity maps; sequential values hold entity vectors. Metric `:dimensions` are
@@ -55,78 +55,47 @@
:measure {:columns :column}
:metric {:columns :column}})
-(def ^:private comment-labels
- {:baseType "Base type"
- :databaseName "Database"
- :description "Description"
- :displayName "Display name"
- :effectiveType "Effective type"
- :entityId "Entity ID"
- :filters "Filters"
- :schemaName "Schema"
- :semanticType "Semantic type"
- :sourceTable "Source table"
- :tableName "Table"
- :unit "Unit"
- :verified "Verified"})
-
(defn- policy-runtime-keys
"Returns the keys that should be emitted as runtime data for a schema node."
[kind value]
(filter #(contains? value %)
(get-in schema-render-policy [kind :runtime])))
-(defn- redundant-table-name-comment?
- "Returns true when a table-name comment would duplicate the object key."
+(defn- redundant-table-name?
+ "Returns true when a table's name would duplicate its object key."
[entry-key table-name]
(and (some? entry-key)
(some? table-name)
(= (name entry-key) (str table-name))))
-(defn- policy-comment-keys
- "Returns the keys that should be rendered as context comments for a schema node."
- [kind value entry-key]
- (->> (get-in schema-render-policy [kind :comment])
- (remove #(and (= kind :table)
- (= % :tableName)
- (redundant-table-name-comment? entry-key (get value %))))
- (filter #(contains? value %))))
-
-(defn- comment-value
- "Formats a schema value for a single-line JavaScript comment."
+(defn- metadata-value
+ "Returns `value` as written in a metadata block, or nil when there is nothing to write: a nil or blank value says
+ nothing, so a map loses such keys at any depth (a table without a schema has no `schemaName`)."
[value]
(cond
- (nil? value) nil
- (map? value) (->> [(:databaseName value) (:schemaName value) (:tableName value)]
- (keep identity)
- (str/join "."))
- :else (str value)))
-
-(defn- entity-comments
- "Returns comment strings for context-only schema fields of an entity.
-
- Fields listed under `:comment` in [[schema-render-policy]] are useful context
- for humans and coding agents, but are intentionally omitted from runtime
- objects consumed by the Lib.createTestQuery DSL."
+ (string? value) (when-not (str/blank? value) value)
+ (map? value) (not-empty (into {} (keep (fn [[k v]] (when-some [v (metadata-value v)] [k v]))) value))
+ (coll? value) (not-empty (into [] (keep metadata-value) value))
+ :else value))
+
+(defn- entity-metadata
+ "Returns the metadata-only keys of an entity, in policy order, or nil when it has none."
[kind value entry-key]
- (let [single-line #(str/replace % #"\R+" " ")]
- (seq (mapcat (fn [comment-key]
- (let [label (get comment-labels comment-key (name comment-key))
- value (get value comment-key)]
- ;; A list gets a line per item, so a long one stays readable instead of being truncated.
- (if (sequential? value)
- (when (seq value)
- (cons (str label ":") (map #(str "- " (single-line (str %))) value)))
- (let [comment-text (comment-value value)]
- (when-not (str/blank? comment-text)
- [(str label ": " (single-line comment-text))])))))
- (policy-comment-keys kind value entry-key)))))
+ (not-empty
+ (apply array-map
+ (mapcat (fn [metadata-key]
+ (when-some [metadata (metadata-value (get value metadata-key))]
+ (when-not (and (= kind :table)
+ (= metadata-key :tableName)
+ (redundant-table-name? entry-key metadata))
+ [(name metadata-key) metadata])))
+ (get-in schema-render-policy [kind :metadata])))))
(defn- generic->node
"Converts a schema value without render policy into an AST expression.
Values outside the policy table (action namespaces, parameter maps, instance
- metadata) emit every key and no comments."
+ metadata) emit every key and no metadata block."
[value]
(cond
(javascript/expression? value) value
@@ -142,8 +111,8 @@
[entities kind]
(into [:obj]
(for [[entry-key entity] entities]
- (if-let [comments (entity-comments kind entity entry-key)]
- [entry-key {:comments comments} (entity->node entity kind)]
+ (if-let [metadata (entity-metadata kind entity entry-key)]
+ [entry-key {:metadata metadata} (entity->node entity kind)]
[entry-key (entity->node entity kind)]))))
(defn- entities->arr
@@ -151,8 +120,8 @@
[entities kind]
(into [:arr]
(for [entity entities]
- (if-let [comments (entity-comments kind entity nil)]
- [:item {:comments comments} (entity->node entity kind)]
+ (if-let [metadata (entity-metadata kind entity nil)]
+ [:item {:metadata metadata} (entity->node entity kind)]
(entity->node entity kind)))))
(defn- dimensions->obj
diff --git a/src/metabase/typed_schemas/schema/action.clj b/src/metabase/typed_schemas/schema/action.clj
index 41542d0749a..dc8f403866c 100644
--- a/src/metabase/typed_schemas/schema/action.clj
+++ b/src/metabase/typed_schemas/schema/action.clj
@@ -79,7 +79,7 @@
:entityId entity_id)))
(defn action-schemas
- "Returns schema entries for the readable query actions without a model among `database-ids` (nil for unscoped),
+ "Returns schema entries for the query actions without a model among `database-ids` (nil for unscoped),
leaving out the copies data apps own."
[database-ids]
(let [ids (typed-schemas.db/model-less-query-action-ids database-ids (set (perms/data-app-collection-ids)))
diff --git a/src/metabase/typed_schemas/schema/common.clj b/src/metabase/typed_schemas/schema/common.clj
index 105fcea3cb8..60b8b844696 100644
--- a/src/metabase/typed_schemas/schema/common.clj
+++ b/src/metabase/typed_schemas/schema/common.clj
@@ -2,10 +2,11 @@
"Shared typed-schema source helpers."
(:require
[medley.core :as m]
+ [metabase.audit-app.core :as audit]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.metabot.core :as metabot]
- [metabase.models.interface :as mi]
+ [metabase.premium-features.core :as premium-features]
[metabase.typed-schemas.db :as typed-schemas.db]))
(set! *warn-on-reflection* true)
@@ -20,19 +21,25 @@
(when (seq db-ids)
(typed-schemas.db/destination-database-ids db-ids)))
+(defn- without-unavailable-cards
+ "`cards` without any backed by a destination (routed) database -- see [[destination-db-ids]] -- and, while the
+ audit feature is off, without the audit database's and the audit collection's: the card details lookup refuses
+ one in the audit collection, and one on the audit database would be listed without its table."
+ [cards]
+ (let [destination-ids (destination-db-ids (into #{} (keep :database_id) cards))
+ audit-off? (not (premium-features/enable-audit-app?))]
+ (cond->> cards
+ (seq destination-ids) (remove #(contains? destination-ids (:database_id %)))
+ audit-off? (remove #(or (= audit/audit-db-id (:database_id %))
+ (some-> (:collection_id %) audit/is-collection-id-audit?))))))
+
(defn select-schema-cards
- "Returns readable, non-archived cards for schema generation.
+ "Returns non-archived cards for schema generation.
- Metrics, models and saved questions are backed by cards. They need
- the same visibility, archived, database and collection filters, and exclude cards backed by a
- destination (routed) database -- see [[destination-db-ids]]."
+ Metrics, models and saved questions are backed by cards. They need the same archived, database and collection
+ filters, and leave out the cards the schema can't serve -- see [[without-unavailable-cards]]."
[card-type database-ids collection-ids]
- (let [cards (->> (typed-schemas.db/cards-ordered-by-name card-type database-ids collection-ids)
- (filter mi/can-read?))
- destination-ids (destination-db-ids (into #{} (keep :database_id) cards))]
- (if (seq destination-ids)
- (remove #(contains? destination-ids (:database_id %)) cards)
- cards)))
+ (without-unavailable-cards (typed-schemas.db/cards-ordered-by-name card-type database-ids collection-ids)))
(defn aggregation-result-column-with-metadata-provider
"Returns an aggregation result column using an existing metadata provider."
diff --git a/src/metabase/typed_schemas/schema/metric.clj b/src/metabase/typed_schemas/schema/metric.clj
index a3b9e35ab6c..9150b8cdb53 100644
--- a/src/metabase/typed_schemas/schema/metric.clj
+++ b/src/metabase/typed_schemas/schema/metric.clj
@@ -6,8 +6,6 @@
[metabase.lib.core :as lib]
[metabase.metabot.core :as metabot]
[metabase.metrics.core :as metrics]
- [metabase.models.interface :as mi]
- [metabase.permissions.core :as perms]
[metabase.typed-schemas.common :as common]
[metabase.typed-schemas.db :as typed-schemas.db]
[metabase.typed-schemas.schema.common :as schema.common]
@@ -165,34 +163,28 @@
(let [{:keys [dimensions dimension_mappings]} (typed-schemas.db/card-dimensions id)]
(enrich-dimensions-with-mappings dimensions dimension_mappings)))
-(defn- readable-table-source-rows
- "Returns readable table rows for table-backed metric dimensions."
+(defn- table-source-rows
+ "Returns table rows for table-backed metric dimensions."
[table-ids]
(when (seq table-ids)
- (perms/prime-table-perms-cache {:table-ids (set table-ids)})
- (->> (typed-schemas.db/table-names table-ids)
- (filter mi/can-read?))))
+ (typed-schemas.db/table-names table-ids)))
(defn- table-key-disambiguators
"Returns table display keys used to disambiguate compacted metric dimensions."
- ([table-ids]
- (table-key-disambiguators table-ids (readable-table-source-rows table-ids)))
- ([_dimension-table-ids table-rows]
- (when (seq table-rows)
- (->> table-rows
- (map (fn [{:keys [id name display_name]}]
- [id (common/pascal-case (common/generated-key (or display_name name) id))]))
- (into {})))))
+ [table-rows]
+ (when (seq table-rows)
+ (->> table-rows
+ (map (fn [{:keys [id name display_name]}]
+ [id (common/pascal-case (common/generated-key (or display_name name) id))]))
+ (into {}))))
(defn- table-source-names
"Returns table names emitted as metric dimension source names."
- ([table-ids]
- (table-source-names table-ids (readable-table-source-rows table-ids)))
- ([_dimension-table-ids table-rows]
- (when (seq table-rows)
- (->> table-rows
- (map (juxt :id :name))
- (into {})))))
+ [table-rows]
+ (when (seq table-rows)
+ (->> table-rows
+ (map (juxt :id :name))
+ (into {}))))
(defn- source-table-schema
"Returns the metric source table identity from portable table metadata."
@@ -252,9 +244,9 @@
[metric-id details source-card-id-value]
(let [dimension-table-id-pairs (metric-dimensions-with-table-ids details source-card-id-value)
table-ids (->> dimension-table-id-pairs (keep second) (filter integer?) distinct)
- table-rows (readable-table-source-rows table-ids)
- table-key-by-id (table-key-disambiguators table-ids table-rows)
- table-source-name-by-id (table-source-names table-ids table-rows)
+ table-rows (table-source-rows table-ids)
+ table-key-by-id (table-key-disambiguators table-rows)
+ table-source-name-by-id (table-source-names table-rows)
dimension-schemas (mapv (fn [[dimension table-id]]
(dimension-schema dimension
metric-id
@@ -306,10 +298,10 @@
[database-ids collection-ids]
(for [metric (remove source-card-id
(schema.common/select-schema-cards :metric database-ids collection-ids))
- ;; Sync only supports metrics that resolve entirely from tables, and the CLI aborts
- ;; `sync-resources` on one that does not. `source-card-id` sees only stage 0, so a
- ;; table-sourced metric joining a saved question reached the CLI and failed there;
- ;; check the whole query for saved-card dependencies to match what sync accepts.
+ ;; A data app can copy only metrics that resolve entirely from tables: a copy reading a
+ ;; saved question references a card outside the app's resources, which the pull refuses.
+ ;; `source-card-id` sees only stage 0, so a table-sourced metric joining a saved question
+ ;; would get through; check the whole query for saved-card dependencies instead.
:when (not (references-saved-card? metric))
:let [details (metric-details metric)]
:when details]
diff --git a/src/metabase/typed_schemas/schema/table.clj b/src/metabase/typed_schemas/schema/table.clj
index 579960b7aac..bf48fc3e8be 100644
--- a/src/metabase/typed_schemas/schema/table.clj
+++ b/src/metabase/typed_schemas/schema/table.clj
@@ -2,10 +2,10 @@
"Typed schema generation for tables, fields, segments and measures."
(:require
[medley.core :as m]
+ [metabase.audit-app.core :as audit]
[metabase.lib-be.core :as lib-be]
[metabase.metabot.core :as metabot]
- [metabase.models.interface :as mi]
- [metabase.permissions.core :as perms]
+ [metabase.premium-features.core :as premium-features]
[metabase.typed-schemas.common :as common]
[metabase.typed-schemas.db :as typed-schemas.db]
[metabase.typed-schemas.schema.common :as schema.common]))
@@ -37,32 +37,30 @@
:tableId (when (integer? table-id) table-id)
:defaultTemporalBucket (:unit field)))))
-(defn- filter-readable-tables
- "Filters tables down to the ones the current user can read, excluding any backed by a destination
- (routed) database -- see [[schema.common/destination-db-ids]]."
+(defn- without-unavailable-tables
+ "`tables` without any backed by a destination (routed) database -- see [[schema.common/destination-db-ids]] -- and
+ without the audit database's while the audit feature is off, since the table details lookup refuses those."
[tables]
- (perms/prime-table-perms-cache {:db-ids (into #{} (keep :db_id) tables)
- :table-ids (into #{} (map :id) tables)})
(let [destination-ids (schema.common/destination-db-ids (into #{} (keep :db_id) tables))
- tables (if (seq destination-ids)
- (remove #(contains? destination-ids (:db_id %)) tables)
- tables)]
- (filter mi/can-read? tables)))
+ audit-off? (not (premium-features/enable-audit-app?))]
+ (cond->> tables
+ (seq destination-ids) (remove #(contains? destination-ids (:db_id %)))
+ audit-off? (remove #(= audit/audit-db-id (:db_id %))))))
(defn select-tables
- "Returns readable tables, with optional database and table-id scopes.
+ "Returns the active tables, with optional database and table-id scopes.
- Library and database endpoint paths both need the same active/readable table
- rules; only their id filters differ."
+ Library and database endpoint paths both need the same active-table rules;
+ only their id filters differ."
[database-ids table-ids]
(->> (typed-schemas.db/active-tables-in-scope database-ids table-ids)
- (filter-readable-tables)))
+ (without-unavailable-tables)))
(defn select-library-tables
"Returns published tables from the library based on the given scope."
[{:keys [data-collection-ids]}]
(->> (typed-schemas.db/published-library-tables-in-collections data-collection-ids)
- (filter-readable-tables)))
+ (without-unavailable-tables)))
(defn segment-schema
"Returns the schema for a segment."
diff --git a/src/metabase/typed_schemas/scope.clj b/src/metabase/typed_schemas/scope.clj
index 40e73d49d78..cbf3a4fa83d 100644
--- a/src/metabase/typed_schemas/scope.clj
+++ b/src/metabase/typed_schemas/scope.clj
@@ -7,16 +7,14 @@
representations and coding agents pass names and entity ids precisely
because numeric ids don't travel.
- A *scope* is what references resolve to on this instance: the concrete,
- permission-filtered sets of row ids that bound what fetching selects for the
- current user. Resolution:
+ A *scope* is what references resolve to on this instance: the concrete
+ sets of row ids that bound what fetching selects. The schema is for
+ superusers, so nothing is checked against the caller. Resolution:
- - filters to what the current user can read;
- expands collection references to include their descendants;
- distinguishes nil (no reference given: unscoped) from the empty set
(references resolved to nothing: match nothing);
- - throws a 404 naming the collection references that don't resolve —
- missing and unreadable are deliberately indistinguishable — while
+ - throws a 404 naming the collection references that don't resolve, while
database references that don't resolve yield an empty scope, and
therefore an empty schema rather than an error.
@@ -27,7 +25,6 @@
(:require
[clojure.string :as str]
[metabase.collections.models.collection :as collection]
- [metabase.models.interface :as mi]
[metabase.typed-schemas.db :as typed-schemas.db]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]))
@@ -43,7 +40,7 @@
"librarylibrarymetrics")
(defn database-ids-for-ref
- "Returns readable database ids matching a typed database reference.
+ "Returns the database ids matching a typed database reference.
An id matches at most one database. Database names are not unique, so a
name reference can genuinely match several databases — currently their
@@ -52,14 +49,8 @@
(when database-ref
(let [{:keys [id name]} database-ref]
(if id
- (let [database (typed-schemas.db/database id)]
- (if (and database (mi/can-read? database))
- #{id}
- #{}))
- (->> (typed-schemas.db/databases-named name)
- (filter mi/can-read?)
- (map :id)
- set)))))
+ (if (typed-schemas.db/database id) #{id} #{})
+ (into #{} (map :id) (typed-schemas.db/databases-named name))))))
(defn- not-found!
[collection-refs]
@@ -69,19 +60,16 @@
:collection-refs (vec collection-refs)})))
(defn- resolve-collection-refs!
- "Batch-resolves collection references into readable collection rows, in ref
- order.
+ "Batch-resolves collection references into collection rows, in ref order.
Throws a 404 naming every reference that does not resolve to a collection
- satisfying `usable-collection?` that the current user can read; missing and
- unreadable references are deliberately indistinguishable."
+ satisfying `usable-collection?`."
[collection-refs usable-collection?]
(let [ids (into #{} (keep :id) collection-refs)
entity-ids (into #{} (keep :entity-id) collection-refs)
usable? (fn [collection]
(and collection
- (usable-collection? collection)
- (mi/can-read? collection)))
+ (usable-collection? collection)))
by-id (when (seq ids)
(into {} (map (juxt :id identity))
(typed-schemas.db/collections ids)))
@@ -110,7 +98,7 @@
(collection/descendants-flat-for collections)))))
(def LibraryScope
- "A resolved library scope: the readable library collection tree, expanded to
+ "A resolved library scope: the library collection tree, expanded to
descendants and classified by collection type. `:data-collection-ids` bound
published table selection; `:metric-collection-ids` bound metric selection."
[:map {:closed true}
diff --git a/src/metabase/typed_schemas/source.clj b/src/metabase/typed_schemas/source.clj
index 7b8cc1f73f6..4a8fc913341 100644
--- a/src/metabase/typed_schemas/source.clj
+++ b/src/metabase/typed_schemas/source.clj
@@ -1,11 +1,10 @@
(ns metabase.typed-schemas.source
"Data access for typed schemas, reified as a protocol.
- [[SchemaSource]] names every read that [[metabase.typed-schemas.core/fetch-items]]
+ [[SchemaSource]] names every read that [[metabase.typed-schemas.build/fetch-items]]
performs, so the module's data-access surface is one definition instead of
selects scattered across namespaces. [[app-db-source]] is the production
- implementation, backed by the application database and filtered by what the
- current user can read.
+ implementation, backed by the application database.
Tests reify the protocol with literal values instead of redefining selection
functions:
@@ -21,7 +20,7 @@
When the pipeline needs to read something new, add a protocol method and its
[[app-db-source]] implementation here — do not call `t2`/`metabot` directly
- from `metabase.typed-schemas.core` or anything downstream of it. That keeps
+ from `metabase.typed-schemas.build` or anything downstream of it. That keeps
the module's data-access surface enumerable and every downstream stage
testable with literal values."
(:require
@@ -40,7 +39,7 @@
entities. A nil `database-ids`/`collection-ids` argument means unscoped;
an empty set matches nothing."
(database-ids [source database-ref]
- "Readable database ids matching a database reference, or nil without one.")
+ "Database ids matching a database reference, or nil without one.")
(collection-ids [source collection-refs]
"Ids of the referenced collections and their descendants, or nil without refs.")
(library-scope [source scope-options]
diff --git a/src/metabase/typed_schemas_rest/api.clj b/src/metabase/typed_schemas_rest/api.clj
index e5d94fff37c..0c9abce5ed1 100644
--- a/src/metabase/typed_schemas_rest/api.clj
+++ b/src/metabase/typed_schemas_rest/api.clj
@@ -5,6 +5,7 @@
typed options in [[metabase.typed-schemas-rest.api.query-params]] at this
boundary, and everything in `metabase.typed-schemas.*` works on typed data."
(:require
+ [metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.typed-schemas-rest.api.query-params :as query-params]
[metabase.typed-schemas.core :as typed-schemas]
@@ -40,12 +41,14 @@
:boolean]]])
(api.macros/defendpoint :get "/v1/typescript" :- :any
- "Generate a TypeScript semantic schema module."
+ "Generate a TypeScript semantic schema module. For superusers: a data app's author builds from it, and only an
+ admin works with an app's repository."
[_route-params
query-params :- TypedSchemaQueryParams
_body-params
{{question-collections "question-collections"
include-models "include-models"} :query-params}]
+ (api/check-superuser)
(when (some? question-collections)
(throw (ex-info "The question-collections query parameter is not supported."
{:status-code 400})))
diff --git a/test/metabase/app_db/custom_migrations_test.clj b/test/metabase/app_db/custom_migrations_test.clj
index 5a03e10bacd..cbb782de655 100644
--- a/test/metabase/app_db/custom_migrations_test.clj
+++ b/test/metabase/app_db/custom_migrations_test.clj
@@ -3117,3 +3117,59 @@
(is (=? {:name "Data App: ops" :slug "data_app__ops" :location "/" :namespace "data-apps"}
(t2/select-one :collection :id collection-id)))
(is (= 21 (count (t2/select-one-fn :entity_id :collection :id collection-id))))))))))
+
+(deftest delete-data-app-drafts-test
+ (testing "v65.2026-10-07T00:00:00: draft rows go, with their groups and the collections they left empty"
+ (impl/test-migrations ["v65.2026-10-07T00:00:00"] [migrate!]
+ (let [insert-collection! (fn [name]
+ (t2/insert-returning-pk! :collection {:name name
+ :slug name
+ :location "/"
+ :namespace "data-apps"
+ :entity_id (u/generate-nano-id)
+ :created_at :%now}))
+ insert-group! (fn [slug]
+ (t2/insert-returning-pk! :permissions_group {:name (str "Data App: " slug)
+ :entity_id (u/generate-nano-id)
+ :is_data_app_group true}))
+ insert-app! (fn [slug draft? collection-id group-id]
+ (t2/insert-returning-pk! :data_app {:name slug
+ :display_name slug
+ :bundle_path "dist/index.js"
+ :entity_id (u/generate-nano-id)
+ :draft draft?
+ :resource_collection_id collection-id
+ :permission_group_id group-id
+ :created_at :%now
+ :updated_at :%now}))
+ empty-coll (insert-collection! "empty")
+ used-coll (insert-collection! "used")
+ kept-coll (insert-collection! "kept")
+ empty-group (insert-group! "empty-draft")
+ used-group (insert-group! "used-draft")
+ kept-group (insert-group! "real")
+ empty-draft (insert-app! "empty-draft" true empty-coll empty-group)
+ used-draft (insert-app! "used-draft" true used-coll used-group)
+ real-app (insert-app! "real" false kept-coll kept-group)]
+ (t2/insert! :permissions {:object (str "/collection/" empty-coll "/read/") :group_id 1 :collection_id empty-coll})
+ ;; something was put in the used draft's collection: a child collection here, cards and actions count the same
+ (t2/insert! :collection {:name "Inside"
+ :slug "inside"
+ :location (str "/" used-coll "/")
+ :namespace "data-apps"
+ :entity_id (u/generate-nano-id)
+ :created_at :%now})
+ (migrate!)
+ (testing "every draft row is gone, with its group"
+ (is (not (t2/exists? :data_app :id empty-draft)))
+ (is (not (t2/exists? :data_app :id used-draft)))
+ (is (not (t2/exists? :permissions_group :id [:in [empty-group used-group]]))))
+ (testing "the empty collection went with its draft, grants included"
+ (is (not (t2/exists? :collection :id empty-coll)))
+ (is (not (t2/exists? :permissions :collection_id empty-coll))))
+ (testing "a collection holding content stays"
+ (is (t2/exists? :collection :id used-coll)))
+ (testing "an app that is not a draft is untouched"
+ (is (t2/exists? :data_app :id real-app))
+ (is (t2/exists? :collection :id kept-coll))
+ (is (t2/exists? :permissions_group :id kept-group)))))))
diff --git a/test/metabase/internal_stats/data_apps_test.clj b/test/metabase/internal_stats/data_apps_test.clj
index 9d946185d47..92336a2190d 100644
--- a/test/metabase/internal_stats/data_apps_test.clj
+++ b/test/metabase/internal_stats/data_apps_test.clj
@@ -32,9 +32,6 @@
(is (= 2 (- (:data-app-count (sut/data-app-stats)) before))))
(testing "an app the admin disabled is out of service, so it doesn't count"
(create! :enabled false)
- (is (= 2 (- (:data-app-count (sut/data-app-stats)) before))))
- (testing "a draft is not served, so it doesn't count even when enabled"
- (create! :draft true)
(is (= 2 (- (:data-app-count (sut/data-app-stats)) before)))))
(finally
(t2/delete! :data_app :name [:in @app-names])))))
diff --git a/test/metabase/typed_schemas/common_test.clj b/test/metabase/typed_schemas/common_test.clj
index 8a7d2d547e3..c9aee8fdd94 100644
--- a/test/metabase/typed_schemas/common_test.clj
+++ b/test/metabase/typed_schemas/common_test.clj
@@ -1,6 +1,9 @@
(ns metabase.typed-schemas.common-test
(:require
[clojure.test :refer :all]
+ [metabase.audit-app.core :as audit]
+ [metabase.audit-app.impl :as audit.impl]
+ [metabase.config.core :as config]
[metabase.test :as mt]
[metabase.typed-schemas.common :as typed-schemas.common]
[metabase.typed-schemas.schema.common :as schema.common]))
@@ -85,6 +88,22 @@
(is (contains? card-ids open-card-id))
(is (not (contains? card-ids destination-card-id))))))))
+(deftest the-audit-apps-cards-are-left-out-without-the-audit-feature-test
+ (let [cards [{:id 1 :database_id (mt/id)}
+ {:id 2 :database_id audit/audit-db-id}
+ {:id 3 :database_id (mt/id) :collection_id 7}]]
+ ;; the var itself rather than its re-export through core, which only follows the root of this one
+ (mt/with-dynamic-fn-redefs [audit.impl/is-collection-id-audit? #(= % 7)]
+ (testing "a card in the audit collection 403s on its details lookup and one on the audit database has no table
+ while the feature is off, so the schema leaves both out rather than fail an unscoped request"
+ (mt/with-premium-features #{}
+ (is (= [1] (map :id (#'schema.common/without-unavailable-cards cards))))))
+ ;; a premium feature is never on without the EE code, whatever the token says
+ (when config/ee-available?
+ (testing "with the feature on they are listed"
+ (mt/with-premium-features #{:audit-app}
+ (is (= [1 2 3] (map :id (#'schema.common/without-unavailable-cards cards))))))))))
+
(deftest ^:parallel keyed-map-never-drops-an-entity-test
(testing "a disambiguated key that equals another entity's own key is disambiguated again rather than overwriting it"
(let [entities [{:key "step", :id 1} {:key "step", :id 23} {:key "step1", :id 7} {:key "step11", :id 40}]
diff --git a/test/metabase/typed_schemas/javascript_test.clj b/test/metabase/typed_schemas/javascript_test.clj
index 7e96a67823d..85485158701 100644
--- a/test/metabase/typed_schemas/javascript_test.clj
+++ b/test/metabase/typed_schemas/javascript_test.clj
@@ -33,10 +33,10 @@
(is (= ["const x = [ 1, 2, 3 ] as const;"]
(render-lines [:const "x" [:arr [:lit 1] [:lit 2] [:lit 3]]]))))
-(deftest arrays-of-objects-render-multiline-with-comments-test
+(deftest arrays-of-objects-render-multiline-with-metadata-test
(is (= ["const x = ["
- " // Display name: Total"
" {"
+ " /* metadata: { \"displayName\": \"Total\" } */"
" name: \"total\""
" },"
" {"
@@ -45,26 +45,64 @@
"] as const;"]
(render-lines
[:const "x" [:arr
- [:item {:comments ["Display name: Total"]}
+ [:item {:metadata {"displayName" "Total"}}
[:obj ["name" [:lit "total"]]]]
[:obj ["name" [:lit "tax"]]]]]))))
-(deftest objects-render-comments-and-quote-non-identifier-keys-test
+(deftest objects-render-metadata-first-and-quote-non-identifier-keys-test
(is (= ["const x = {"
- " // Entity ID: abc123"
- " // Description: All orders"
" orders: {"
+ " /* metadata: { \"entityId\": \"abc123\", \"description\": \"All orders\" } */"
" type: \"table\","
" \"has-totals\": true"
" }"
"} as const;"]
(render-lines
[:const "x" [:obj
- ["orders" {:comments ["Entity ID: abc123"
- "Description: All orders"]}
+ ["orders" {:metadata (array-map "entityId" "abc123"
+ "description" "All orders")}
[:obj ["type" [:lit "table"]]
["has-totals" [:lit true]]]]]]))))
+(deftest metadata-renders-in-an-otherwise-empty-object-test
+ (is (= ["const x = {"
+ " orders: {"
+ " /* metadata: { \"id\": 1 } */"
+ " }"
+ "} as const;"]
+ (render-lines
+ [:const "x" [:obj ["orders" {:metadata {"id" 1}} [:obj]]]]))))
+
+(deftest metadata-with-nested-values-renders-one-item-per-line-test
+ (is (= ["const x = {"
+ " orders: {"
+ " /* metadata: {"
+ " \"filters\": ["
+ " \"Status is paid\","
+ " \"Total is greater than 10\""
+ " ],"
+ " \"sourceTable\": {"
+ " \"databaseName\": \"Sample\","
+ " \"tableName\": \"ORDERS\""
+ " }"
+ " } */"
+ " id: 1"
+ " }"
+ "} as const;"]
+ (render-lines
+ [:const "x" [:obj ["orders" {:metadata (array-map "filters" ["Status is paid" "Total is greater than 10"]
+ "sourceTable" (array-map "databaseName" "Sample"
+ "tableName" "ORDERS"))}
+ [:obj ["id" [:lit 1]]]]]]))))
+
+(deftest metadata-cannot-end-its-comment-early-test
+ (testing "`*/` inside a value is written as `*\\/`, which JSON reads back as `*/`"
+ (let [rendered (javascript/render-js
+ [:module [:const "x" [:obj ["orders" {:metadata {"description" "Paid orders /* see note */"}}
+ [:obj ["id" [:lit 1]]]]]]])]
+ (is (str/includes? rendered "\"description\": \"Paid orders /* see note *\\/\""))
+ (is (= 1 (count (re-seq #"\*/" rendered)))))))
+
(deftest call-expressions-render-inline-test
(is (= ["const x = {"
" orders: pickFields(tables.orders.fields, [ \"total\" ], { sourceFieldId: 42 })"
@@ -93,13 +131,25 @@
[:module
[:raw "function helper() {}"]
[:const "tables"
- [:obj ["orders" {:comments ["Entity ID: abc"]}
- [:obj ["ids" [:arr [:lit 1] [:item {:comments ["c"]} [:obj]]]]
+ [:obj ["orders" {:metadata {"entityId" "abc"}}
+ [:obj ["ids" [:arr [:lit 1] [:item {:metadata {"name" "c"}} [:obj]]]]
["fields" [:call "pickFields" [:ref "tables" "orders"]]]]]]]
[:export-default [:ref "schema"]]])))
(deftest module-schema-rejects-unknown-nodes-test
(are [module] (not (mr/validate javascript/Module module))
[:module [:const "x" [:string "not-a-node"]]]
- [:module [:const "x" [:obj ["key" {:commentz ["typo"]} [:lit 1]]]]]
+ [:module [:const "x" [:obj ["key" {:metadataz {"typo" 1}} [:lit 1]]]]]
+ ;; Comments were replaced by metadata blocks.
+ [:module [:const "x" [:obj ["key" {:comments ["Entity ID: abc"]} [:obj]]]]]
+ ;; A block prints inside an object, so metadata on anything else has nowhere to go.
+ [:module [:const "x" [:obj ["key" {:metadata {"entityId" "abc"}} [:lit 1]]]]]
+ [:module [:const "x" [:arr [:item {:metadata {"entityId" "abc"}} [:lit 1]]]]]
[:const "x" [:lit 1]]))
+
+(deftest metadata-inside-a-call-argument-is-refused-test
+ (testing "a `:call` argument prints on one line, where a block can't go, so its metadata is an error, not dropped"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Metadata can only be attached to an object"
+ (javascript/render-js
+ [:module [:const "x" [:call "pickFields"
+ [:obj ["orders" {:metadata {"entityId" "abc"}} [:obj]]]]]])))))
diff --git a/test/metabase/typed_schemas/render_test.clj b/test/metabase/typed_schemas/render_test.clj
index 4cb9179a837..29dbf330da9 100644
--- a/test/metabase/typed_schemas/render_test.clj
+++ b/test/metabase/typed_schemas/render_test.clj
@@ -74,23 +74,51 @@
:baseType "type/DateTime"
:jsType "Date"}}}}})
-(deftest typescript-renderer-emits-comments-and-runtime-metadata-test
+(deftest typescript-renderer-emits-metadata-blocks-and-runtime-data-test
(let [body (typed-schemas/render-typescript compacting-schema)]
- ;; Emit comments to provide context for agents
- (is (str/includes? body "// Description: Saved orders"))
- (is (str/includes? body "// Description: Total order revenue"))
- (is (re-find #"// Filters:\n\s*// - Status is paid\n\s*// - Created At is in the previous 30 days\n" body))
- (is (str/includes? body "// Display name: Payment Method"))
- (is (str/includes? body "// Semantic type: type/Category"))
- ;; Emit metadata needed for the Lib.createTestQuery DSL
- (is (str/includes? body "ordersQuestion: {\n type: \"card\""))
- (is (str/includes? body "paymentMethod: {\n type: \"column\""))
- (is (str/includes? body "databaseId: 1"))
- (is (str/includes? body "sourceTableId: 10"))
- (is (str/includes? body "mappedTableIds: [ 10, 20 ]"))
- ;; Comment-only metadata should not become runtime fields.
- (is (not (str/includes? body "displayName: \"Payment Method\"")))
- (is (not (str/includes? body "filters:")))))
+ (testing "context for agents is a metadata block, never a line comment"
+ (is (not (re-find #"(?m)^\s*//" body)))
+ (testing "an entry opens with its block, so a reader meets the context before the data"
+ (is (re-find #"(?s)ordersQuestion: \{\n\s*/\* metadata: \{ \"description\": \"Saved orders\" \} \*/\n\s*type: \"card\"" body))
+ (is (str/includes? body "\"description\": \"Total order revenue\""))
+ (is (str/includes? body (str "/* metadata: { \"displayName\": \"Payment Method\", "
+ "\"semanticType\": \"type/Category\" } */\n type: \"column\""))))
+ (testing "a block with a nested value prints one array item per line"
+ (is (re-find #"(?s)\"filters\": \[\n\s*\"Status is paid\",\n\s*\"Created At is in the previous 30 days\"\n\s*\]" body))))
+ (testing "data for the Lib.createTestQuery DSL stays runtime"
+ (is (str/includes? body "ordersQuestion: {\n /* metadata:"))
+ (is (str/includes? body "paymentMethod: {\n /* metadata:"))
+ (is (str/includes? body "databaseId: 1"))
+ (is (str/includes? body "sourceTableId: 10"))
+ (is (str/includes? body "mappedTableIds: [ 10, 20 ]")))
+ (testing "metadata-only keys never become runtime fields"
+ (is (not (str/includes? body "displayName: \"Payment Method\"")))
+ (is (not (str/includes? body "filters:"))))))
+
+(deftest typescript-renderer-omits-what-a-metadata-block-has-nothing-to-say-test
+ (let [body (typed-schemas/render-typescript
+ {:schemaVersion 2
+ :tables {"orders" {:type "table"
+ :id 10
+ :name "Orders"
+ :description " "
+ :fields {}}}
+ :metrics {"revenue" {:type "metric"
+ :id 31
+ :sourceTable {:databaseName "Sample Database"
+ :schemaName nil
+ :tableName "ORDERS"}}
+ "profit" {:type "metric"
+ :id 32
+ :sourceTable {:databaseName "Sample Database"
+ :schemaName ""
+ :tableName "PRODUCTS"}}}})]
+ (testing "a table in a database without schemas has no schema key, whether the schema is nil or blank"
+ (is (= 2 (count (re-seq #"\"sourceTable\": \{\n\s*\"databaseName\": \"Sample Database\",\n\s*\"tableName\": \"(ORDERS|PRODUCTS)\"\n\s*\}" body))))
+ (is (not (str/includes? body "null")))
+ (is (not (str/includes? body "schemaName"))))
+ (testing "a blank description is not written"
+ (is (not (str/includes? body "description"))))))
(deftest typescript-renderer-compacts-metric-dimensions-test
(let [body (typed-schemas/render-typescript compacting-schema)]
@@ -143,16 +171,16 @@
[:obj ["sourceFieldId" [:lit 42]]]]
(obj-entry dimensions "franchises")))))
-(deftest schema->ast-splits-runtime-keys-from-comments-test
+(deftest schema->ast-splits-runtime-keys-from-metadata-test
(let [ast (render/schema->ast compacting-schema)
fields (-> (module-const ast "tables")
(obj-entry "orders")
(obj-entry :fields))
[entry-key options field-node] (-> fields rest first)]
- (testing "comment-only policy keys become entry comments"
+ (testing "metadata-only policy keys become the entry's metadata"
(is (= "paymentMethod" entry-key))
- (is (= {:comments ["Display name: Payment Method"
- "Semantic type: type/Category"]}
+ (is (= {:metadata {"displayName" "Payment Method"
+ "semanticType" "type/Category"}}
options)))
(testing "runtime policy keys become object entries"
(is (= [:lit "payment_method"] (obj-entry field-node :name)))
diff --git a/test/metabase/typed_schemas/schema/metric_test.clj b/test/metabase/typed_schemas/schema/metric_test.clj
index 08181085594..583ccfcf2df 100644
--- a/test/metabase/typed_schemas/schema/metric_test.clj
+++ b/test/metabase/typed_schemas/schema/metric_test.clj
@@ -3,8 +3,6 @@
[clojure.test :refer :all]
[metabase.lib.core :as lib]
[metabase.metabot.core :as metabot]
- [metabase.models.interface :as mi]
- [metabase.permissions.core :as perms]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.typed-schemas.db :as typed-schemas.db]
@@ -152,8 +150,8 @@
(deftest metric-schemas-excludes-metrics-that-join-a-saved-question-test
;; Metric 258 is table-sourced and joins a saved question, so `source-card-id` — which only reads
- ;; stage 0's source — passes it. The CLI checks the whole query and rejects it, aborting
- ;; `sync-resources` for any app that uses it, so codegen has to drop it here as well.
+ ;; stage 0's source — passes it. A data app's copy of it would reference a saved question outside
+ ;; the app's resources, which the pull refuses, so codegen has to drop it here as well.
(mt/with-dynamic-fn-redefs [schema.common/select-schema-cards
(constantly [{:id 247
:dataset_query {:lib/type :mbql/query
@@ -179,20 +177,9 @@
(is (= [247]
(vec (schema.metric/metric-schemas nil nil))))))
-(deftest table-source-names-filters-unreadable-tables-test
- (with-redefs [perms/prime-table-perms-cache (constantly nil)
- typed-schemas.db/table-names
- (constantly [{:id 10 :name "orders" :display_name "Orders"}
- {:id 20 :name "franchises" :display_name "Franchises"}])
- mi/can-read? (fn [{:keys [id]}] (= id 10))]
- (is (= {10 "orders"}
- (#'schema.metric/table-source-names [10 20])))
- (is (= {10 "Orders"}
- (#'schema.metric/table-key-disambiguators [10 20])))))
-
(deftest metric-schema-keys-dimensions-test
(mt/with-dynamic-fn-redefs [schema.metric/metric-result-column (constantly nil)
- schema.metric/readable-table-source-rows
+ schema.metric/table-source-rows
(constantly [{:id 10 :name "orders" :display_name "Orders"}])
schema.metric/sync-and-fetch-metric-dimensions!
(constantly [{:id "550e8400-e29b-41d4-a716-446655440001"
@@ -228,17 +215,15 @@
(deftest metric-schema-reuses-table-source-rows-test
(let [table-select-count (atom 0)]
- (with-redefs [schema.metric/metric-result-column (constantly nil)
- schema.metric/sync-and-fetch-metric-dimensions!
- (constantly [{:id "orders-dimension"
- :name "orders"
- :table-id 10}])
- mi/can-read? (constantly true)
- perms/prime-table-perms-cache (constantly nil)
- typed-schemas.db/table-names
- (fn [_table-ids]
- (swap! table-select-count inc)
- [{:id 10 :name "orders" :display_name "Orders"}])]
+ (mt/with-dynamic-fn-redefs [schema.metric/metric-result-column (constantly nil)
+ schema.metric/sync-and-fetch-metric-dimensions!
+ (constantly [{:id "orders-dimension"
+ :name "orders"
+ :table-id 10}])
+ typed-schemas.db/table-names
+ (fn [_table-ids]
+ (swap! table-select-count inc)
+ [{:id 10 :name "orders" :display_name "Orders"}])]
(#'schema.metric/metric-schema
{:id 247
:name "Customer Lifetime Value"}
diff --git a/test/metabase/typed_schemas/schema/table_test.clj b/test/metabase/typed_schemas/schema/table_test.clj
index ce20fa4efd1..ab68b93d9ea 100644
--- a/test/metabase/typed_schemas/schema/table_test.clj
+++ b/test/metabase/typed_schemas/schema/table_test.clj
@@ -1,6 +1,8 @@
(ns metabase.typed-schemas.schema.table-test
(:require
[clojure.test :refer :all]
+ [metabase.audit-app.core :as audit]
+ [metabase.config.core :as config]
[metabase.lib-be.core :as lib-be]
[metabase.metabot.core :as metabot]
[metabase.test :as mt]
@@ -140,6 +142,18 @@
(let [tables (schema.table/select-tables nil [open-table-id destination-table-id])]
(is (= [open-table-id] (map :id tables)))))))))
+(deftest the-audit-databases-tables-are-left-out-without-the-audit-feature-test
+ (let [tables [{:id 1 :db_id (mt/id)} {:id 2 :db_id audit/audit-db-id}]]
+ (testing "the table details lookup refuses the audit database's tables while the feature is off, so the schema
+ leaves them out rather than fail an unscoped request"
+ (mt/with-premium-features #{}
+ (is (= [1] (map :id (#'schema.table/without-unavailable-tables tables))))))
+ ;; a premium feature is never on without the EE code, whatever the token says
+ (when config/ee-available?
+ (testing "with the feature on they are listed"
+ (mt/with-premium-features #{:audit-app}
+ (is (= [1 2] (map :id (#'schema.table/without-unavailable-tables tables)))))))))
+
;; Batch measure definitions to avoid N+1 queries.
(deftest table-schema-bulk-loads-measure-definitions-test
(let [measure-select-count (atom 0)
diff --git a/test/metabase/typed_schemas/source_test.clj b/test/metabase/typed_schemas/source_test.clj
index cb02bd051d6..73a24396bee 100644
--- a/test/metabase/typed_schemas/source_test.clj
+++ b/test/metabase/typed_schemas/source_test.clj
@@ -111,7 +111,7 @@
(deftest actions-test
(mt/with-temp [:model/Database {other-db-id :id} {}
- :model/Collection {hidden-coll-id :id} {:name "Hidden actions" :namespace "data-actions"}
+ :model/Collection {collection-id :id} {:name "Actions" :namespace "data-actions"}
:model/Card {model-id :id} {:type :model
:dataset_query (lib/query (mt/metadata-provider)
(lib.metadata/table (mt/metadata-provider)
@@ -120,17 +120,17 @@
:model/QueryAction _ {:action_id standalone, :dataset_query (touch-category-query)}
:model/Action {archived :id} {:type :query, :name "Archived", :archived true}
:model/QueryAction _ {:action_id archived, :dataset_query (touch-category-query)}
- :model/Action {hidden :id} {:type :query, :name "Hidden", :collection_id hidden-coll-id}
- :model/QueryAction _ {:action_id hidden, :dataset_query (touch-category-query)}
+ :model/Action {in-collection :id} {:type :query, :name "In a collection", :collection_id collection-id}
+ :model/QueryAction _ {:action_id in-collection, :dataset_query (touch-category-query)}
:model/Action {on-model :id} {:type :query, :name "On a model", :model_id model-id}
:model/QueryAction _ {:action_id on-model, :dataset_query (touch-category-query)}]
(let [action-ids (fn [database-ids] (into #{} (map :id) (source/actions source/app-db-source database-ids)))
- ours #{standalone archived hidden on-model}]
+ ours #{standalone archived in-collection on-model}]
(mt/with-current-user (mt/user->id :crowberto)
(testing "a database scope returns that database's unarchived actions without a model"
- (is (= #{standalone hidden} (set/intersection ours (action-ids #{(mt/id)})))))
+ (is (= #{standalone in-collection} (set/intersection ours (action-ids #{(mt/id)})))))
(testing "no scope reads every database"
- (is (= #{standalone hidden} (set/intersection ours (action-ids nil)))))
+ (is (= #{standalone in-collection} (set/intersection ours (action-ids nil)))))
(testing "a scope of another database leaves them out"
(is (= #{} (set/intersection ours (action-ids #{other-db-id})))))
(testing "an action renders with its parameters typed from the template tag"
@@ -139,15 +139,4 @@
:id standalone
:type "query"
:parameters [{:slug "id", :jsType "number", :required true}]}]
- (filter #(= standalone (:id %)) (source/actions source/app-db-source #{(mt/id)}))))))
- (testing "an action in a collection the user cannot read is left out"
- (mt/with-non-admin-groups-no-collection-perms hidden-coll-id
- (mt/with-current-user (mt/user->id :rasta)
- (is (not (contains? (action-ids #{(mt/id)}) hidden))))))
- (testing "an action in the data actions root follows that root's permissions, not the default root's"
- (mt/with-current-user (mt/user->id :rasta)
- (mt/with-non-admin-groups-no-root-collection-for-namespace-perms :data-actions
- (is (not (contains? (action-ids #{(mt/id)}) standalone)))
- (mt/with-non-admin-groups-no-root-collection-perms
- (mt/with-all-users-permission "/collection/namespace/data-actions/root/read/"
- (is (contains? (action-ids #{(mt/id)}) standalone))))))))))
+ (filter #(= standalone (:id %)) (source/actions source/app-db-source #{(mt/id)})))))))))
diff --git a/test/metabase/typed_schemas_rest/api_test.clj b/test/metabase/typed_schemas_rest/api_test.clj
index df2bacb9cc4..19886335ed2 100644
--- a/test/metabase/typed_schemas_rest/api_test.clj
+++ b/test/metabase/typed_schemas_rest/api_test.clj
@@ -12,6 +12,12 @@
(use-fixtures :once (fixtures/initialize :db :web-server :test-users))
+(deftest only-a-superuser-generates-the-schema-test
+ (testing "the schema is what an app's author builds from, and only an admin works with an app's repository"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "typed-schemas/v1/typescript")))
+ (is (string? (mt/user-http-request :crowberto :get 200 "typed-schemas/v1/typescript")))))
+
(defn- without-generated-at
[typescript]
(str/replace typescript #"generatedAt: \"[^\"]+\"" "generatedAt: \"<generated-at>\""))
@@ -108,23 +114,6 @@
(mt/with-dynamic-fn-redefs [perms/data-app-collection-ids (constantly #{(:id copies)})]
(is (not (str/includes? (schema :database (mt/id) :include-actions true) "copiedOrder")))))))))
-(deftest actions-in-data-actions-root-test
- (mt/with-actions-enabled
- (mt/with-temp [:model/Action root-action {:name "Discount order", :type :query}
- :model/QueryAction _ {:action_id (:id root-action)
- :dataset_query (lib/native-query (mt/metadata-provider)
- "UPDATE orders SET discount = 0")}]
- (let [rasta-schema #(:body (mt/user-http-request-full-response :rasta :get 200 "typed-schemas/v1/typescript"
- :database (mt/id) :include-actions true))]
- (testing "permissions on the default root do not reveal an action in the data actions root"
- (mt/with-non-admin-groups-no-root-collection-for-namespace-perms :data-actions
- (is (t2/exists? :model/Permissions :group_id (:id (perms/all-users-group)) :object "/collection/root/"))
- (is (not (str/includes? (rasta-schema) "discountOrder")))))
- (testing "permissions on the data actions root reveal it without the default root"
- (mt/with-non-admin-groups-no-root-collection-perms
- (mt/with-all-users-permission "/collection/namespace/data-actions/root/read/"
- (is (str/includes? (rasta-schema) "discountOrder")))))))))
-
(deftest collection-and-database-query-params-are-mutually-exclusive-test
(mt/user-http-request-full-response
:crowberto