The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat: Pg Replication Preview modal (#61522)
Filipe Silvabfd69205ef62
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 46a1456592b..d5a852c1934 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1653,6 +1653,7 @@metabase-enterprise.database-replication.init}:uses #{analyticsapi+ driverpremium-featuressettingsutildiff --git a/.github/workflows/uberjar-containerize-labeled.yml b/.github/workflows/uberjar-containerize-labeled.ymlindex f99fbdcc2a3..5b1291da266 100644--- a/.github/workflows/uberjar-containerize-labeled.yml+++ b/.github/workflows/uberjar-containerize-labeled.yml@@ -2,7 +2,7 @@ name: Uberjar Containerize labeledon:pull_request:- types: [ labeled ]+ types: [ labeled, opened, synchronize, reopened ]concurrency:group: ${{ github.workflow }}-${{ github.ref }}@@ -10,12 +10,12 @@ concurrency:jobs:uberjar:- if: ${{ github.event.label.name == 'build-docker-uberjar' }}+ if: ${{ contains(github.event.pull_request.labels.*.name, 'build-docker-uberjar') || github.event.label.name == 'build-docker-uberjar' }}uses: ./.github/workflows/uberjar.ymlsecrets: inheritcontainerize:needs: [uberjar]- if: ${{ github.event.label.name == 'build-docker-uberjar' }}+ if: ${{ contains(github.event.pull_request.labels.*.name, 'build-docker-uberjar') || github.event.label.name == 'build-docker-uberjar' }}uses: ./.github/workflows/containerize-uberjar.ymlsecrets: inheritdiff --git a/CLAUDE.md b/CLAUDE.mdindex a714aedaa8d..e15da3fe685 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -14,8 +14,7 @@### JavaScript/TypeScript- **Lint:** `yarn lint-eslint-pure`-- **Test:** `yarn test-unit path/to/file.unit.spec.js` or `yarn test-unit -t "pattern"`-- **Watch:** `yarn test-unit-watch path/to/file.unit.spec.js`+- **Test:** `yarn test-unit-keep-cljs path/to/file.unit.spec.js` or `yarn test-unit-keep-cljs -t "pattern"`- **Format:** `yarn prettier`- **Type Check:** `yarn type-check-pure`diff --git a/enterprise/backend/src/metabase_enterprise/database_replication/api.clj b/enterprise/backend/src/metabase_enterprise/database_replication/api.cljindex f80a5ade16e..5eda9ef4e12 100644--- a/enterprise/backend/src/metabase_enterprise/database_replication/api.clj+++ b/enterprise/backend/src/metabase_enterprise/database_replication/api.clj@@ -1,13 +1,21 @@(ns metabase-enterprise.database-replication.api(:require+ [clojure.core.memoize :as memoize]+ [clojure.set :as set][medley.core :as m][metabase-enterprise.database-replication.settings :as database-replication.settings][metabase-enterprise.harbormaster.client :as hm.client][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]+ [metabase.driver.sync :as driver.s]+ [metabase.premium-features.core :as premium-features]+ [metabase.util :as u]+ [metabase.util.log :as log][metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [toucan2.core :as t2])+ (:import+ (java.util.regex PatternSyntaxException)))(set! *warn-on-reflection* true)@@ -28,28 +36,144 @@(defn- database-id->connection-id [conns database-id](->> database-id kw-id (get conns) :connection-id))+(defn- schema-filter->fn [{:keys [type patterns]}]+ (if (= type "all")+ (constantly true)+ (let [pat (driver.s/schema-pattern->re-pattern patterns)+ f (case type+ "include" some?+ "exclude" nil?)]+ (fn [table-schema]+ (f (re-matches pat table-schema))))))++(defn- schema-filters->fn [schema-filters]+ (if (seq schema-filters)+ (fn [table-schema]+ (->> schema-filters+ (map schema-filter->fn)+ (every? #(% table-schema))))+ (constantly true)))++(defn- hm-preview [secret]+ (hm.client/call :preview-connection, :connection-id "preview", :type "pg_replication", :secret secret))++(def ^:private hm-preview-memo+ (memoize/ttl hm-preview :ttl/threshold (u/minutes->ms 5)))++(defn- preview-tables+ [secret & replication-schema-filters]+ (try+ ;; realize this lazy seq here to catch the regex error, if any+ (doall+ (->> secret+ ;; memo the slow preview call without replication-schema-filters, then+ ;; apply filter over the memoized result for snappy UI+ hm-preview-memo+ :tables+ (filter (comp (schema-filters->fn replication-schema-filters) :table_schema))))+ (catch PatternSyntaxException _+ {:error "Invalid schema pattern"})))++(defn- get-free-quota [quotas]+ (or+ (some->> (m/find-first (comp #{"clickhouse-dwh"} :hosting-feature) quotas)+ ((juxt :soft-limit :usage))+ (apply -))+ -1))++(defn preview-replication+ "Predicate that signals if replication looks right from the quota perspective.++ This predicate checks that the quotas we got from the latest tokencheck have enough space for the database to be+ replicated."+ [quotas tables]+ (let [tables-error (:error tables)+ tables (if tables-error [] tables)+ free-quota (get-free-quota quotas)+ replicated-tables (->> tables+ (filter :has_pkey)+ (filter :has_ownership))+ tables-without-pk (filter (comp not :has_pkey) tables)+ tables-without-owner-match (filter (comp not :has_ownership) tables)+ total-estimated-row-count (or+ (some->>+ replicated-tables+ (map :estimated_row_count)+ (remove nil?)+ (reduce +))+ 0)+ errors {:no-tables (empty? replicated-tables)+ :no-quota (> total-estimated-row-count free-quota)+ :invalid-schema-filters-pattern (boolean tables-error)}]+ (log/infof "Quota left: %s. Estimate db row count: %s" free-quota total-estimated-row-count)+ {:free-quota free-quota+ :total-estimated-row-count total-estimated-row-count+ :errors errors+ :can-set-replication (not (some second errors))+ :replicated-tables replicated-tables+ :tables-without-pk tables-without-pk+ :tables-without-owner-match tables-without-owner-match}))++(defn- m->schema-filter [m]+ (-> m+ (select-keys [:schema-filters-type :schema-filters-patterns])+ (set/rename-keys {:schema-filters-type :type, :schema-filters-patterns :patterns})))++(defn- ->secret [{:keys [details]} & {:as replication-schema-filters}]+ (let [dbname (or (:dbname details) (:db details))+ credentials (-> details+ (select-keys [:host :user :password :port])+ (update :port #(or % 5432)) ;; port is required in the API, but optional in MB+ (merge {:dbname dbname+ :dbtype "postgresql"}))+ schema-filters (->> [(m->schema-filter details)+ (m->schema-filter replication-schema-filters)]+ (filterv not-empty))]+ {:credentials credentials+ :schema-filters schema-filters}))++(def ^:private body-schema+ [:map+ [:replicationSchemaFilters+ {:optional true}+ [:map+ [:schema-filters-type [:enum "include" "exclude" "all"]]+ [:schema-filters-patterns :string]]]])++(api.macros/defendpoint :post "/connection/:database-id/preview"+ "Return info about pg-replication connection that is about to be created."+ [{:keys [database-id]} :- [:map [:database-id ms/PositiveInt]] _ {:keys [replicationSchemaFilters]} :- body-schema]+ (let [database (t2/select-one :model/Database :id database-id)+ secret (->secret database)+ replication-schema-filters (m->schema-filter replicationSchemaFilters)]+ (u/recursive-map-keys u/->camelCaseEn (preview-replication (premium-features/quotas) (preview-tables secret replication-schema-filters)))))+(api.macros/defendpoint :post "/connection/:database-id""Create a new PG replication connection for the specified database."- [{:keys [database-id]} :- [:map [:database-id ms/PositiveInt]]]+ [{:keys [database-id]} :- [:map [:database-id ms/PositiveInt]] _ {:keys [replicationSchemaFilters]} :- body-schema](api/check-400 (database-replication.settings/database-replication-enabled) "PG replication integration is not enabled.")- (let [database (t2/select-one :model/Database :id database-id)]+ (let [database (t2/select-one :model/Database :id database-id)+ db-details (:details database)](api/check-404 database)(api/check-400 (= :postgres (:engine database)) "PG replication is only supported for PostgreSQL databases.")+ (api/check-400 (not (:tunnel-enabled db-details)) "PG replication is not supported with SSH Tunnel.")+ (api/check-400 (not (or (:ssl-client-cert db-details) (:ssl-root-cert db-details)))+ "PG replication is not supported with root or client certificates.")(let [conns (pruned-database-replication-connections)](api/check-400 (not (database-id->connection-id conns database-id)) "Database already has an active replication connection.")- (let [credentials (-> (:details database)- (select-keys [:dbname :host :user :password :port])- (update :port #(or % 5432))) ;; port is required in the API, but optional in MB- {:keys [schema-filters-type schema-filters-patterns]} (:details database)- schemas (when-some [k ({"inclusion" :include, "exclusion" :exclude} schema-filters-type)]- (when schema-filters-patterns- {:schemas {k schema-filters-patterns}}))- secret (merge {:credentials (merge {:dbtype "postgresql"} credentials)}- schemas)- {:keys [id]} (hm.client/call :create-connection, :type "pg_replication", :secret secret)- conn {:connection-id id}]- (database-replication.settings/database-replication-connections! (assoc conns (kw-id database-id) conn))- conn))))+ (let [secret (->secret database replicationSchemaFilters)]+ (if (:can-set-replication (preview-replication (premium-features/quotas) (preview-tables secret)))+ (let [{:keys [id]} (try+ (hm.client/call :create-connection, :type "pg_replication", :secret secret)+ (catch Exception e+ (let [{:keys [error error-detail]} (ex-data e)]+ (when (not= "incorrect" error)+ (throw e))+ (api/check-400 false error-detail))))+ conn {:connection-id id}]+ (database-replication.settings/database-replication-connections! (assoc conns (kw-id database-id) conn))+ conn)+ (api/check-400 false "Not enough quota"))))))(api.macros/defendpoint :delete "/connection/:database-id""Delete PG replication connection for the specified database."diff --git a/enterprise/backend/src/metabase_enterprise/harbormaster/client.clj b/enterprise/backend/src/metabase_enterprise/harbormaster/client.cljindex 80462fe8d3b..5ef30c3507b 100644--- a/enterprise/backend/src/metabase_enterprise/harbormaster/client.clj+++ b/enterprise/backend/src/metabase_enterprise/harbormaster/client.clj@@ -156,8 +156,14 @@[& args](apply martian/explore (client) args))+(defn- maybe-decode [x]+ (try+ (json/decode+kw x)+ (catch Exception _+ x)))+(defn call- "Call the API, using Martian. Will throw on non 2xx.+ "Call the API, using Martian. Will throw on non 2xx, and you can get the failure body (if any) using ex-data.e.g.;; call the :foo endpoint with {:some-id id};; use (explore :list-connections) for params, if any, and pass them in a map@@ -166,8 +172,10 @@(try(:body (martian/response-for (client) operation-id args))(catch Exception e- (log/errorf e "Error on Harbormaster operation call %s" operation-id)- (throw e))))+ (let [resp-body (some-> e ex-data :body maybe-decode)+ msg (format "Error on Harbormaster operation call %s" operation-id)]+ (log/error msg (or resp-body e))+ (throw (ex-info msg (if (map? resp-body) resp-body {})))))))(defn request"Same as call, but return the request that will be performed.diff --git a/enterprise/backend/test/metabase_enterprise/database_replication/api_test.clj b/enterprise/backend/test/metabase_enterprise/database_replication/api_test.cljindex a2f8ed6b7f5..ea49f869f23 100644--- a/enterprise/backend/test/metabase_enterprise/database_replication/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/database_replication/api_test.clj@@ -1,8 +1,10 @@(ns metabase-enterprise.database-replication.api-test(:require[clojure.test :refer [deftest is testing]]+ [metabase-enterprise.database-replication.api :as api][metabase-enterprise.database-replication.settings :as database-replication.settings][metabase-enterprise.harbormaster.client :as hm.client]+ [metabase.premium-features.token-check :as token-check][metabase.test :as mt][metabase.util :as u]))@@ -62,29 +64,144 @@(deftest lifecycle-test(let [hm-state (atom [])- db-details {:dbname "dbname", :host "host", :user "user", :password "password"}]- (with-redefs [hm.client/call+ db-details {:dbname "dbname", :host "host", :user "user", :password "password"}+ tables [{:table_schema "public",+ :table_name "t1",+ :estimated_row_count 9+ :has_pkey true,+ :has_ownership true}+ {:table_schema "not_public",+ :table_name "no_schema",+ :estimated_row_count 11+ :has_pkey false,+ :has_ownership true}+ {:table_schema "public",+ :table_name "no_pkey",+ :estimated_row_count 11+ :has_pkey false,+ :has_ownership true}+ {:table_schema "public",+ :table_name "no_ownership",+ :estimated_row_count 11+ :has_pkey true,+ :has_ownership false}]]+ (with-redefs [token-check/quotas+ (constantly [{:usage 499990, :locked false, :updated-at "2025-08-05T08:48:11Z", :quota-type "rows", :hosting-feature "clickhouse-dwh", :soft-limit 500000}])++ api/hm-preview-memo+ #'api/hm-preview++ hm.client/call(fn [op-id & {:as m}](case op-id:list-connections @hm-state+ :preview-connection {:tables tables}:create-connection (u/prog1 (into {:id (str (random-uuid))} m) (swap! hm-state conj <>)):delete-connection (swap! hm-state (fn [state] (vec (remove #(-> % :id (= (:connection-id m))) state))))))](mt/with-premium-features #{:attached-dwh :etl-connections :etl-connections-pg :hosting}(mt/with-temporary-setting-values [is-hosted? true, store-api-url "foo", api-key "foo", database-replication-connections {}](mt/with-temp [:model/Database db {:engine :postgres :details db-details}]- (let [url (str "ee/database-replication/connection/" (:id db))]+ (let [url (str "ee/database-replication/connection/" (:id db))+ body {:replicationSchemaFilters {:schema-filters-type "exclude"+ :schema-filters-patterns "not_pub*"}}]+ (testing "previews"+ (let [resp (mt/user-http-request :crowberto :post 200 (str url "/preview") body)]+ (is (= {:freeQuota 10,+ :totalEstimatedRowCount 9,+ :canSetReplication true,++ :replicatedTables+ [{:tableSchema "public", :tableName "t1", :estimatedRowCount 9, :hasPkey true, :hasOwnership true}],++ :tablesWithoutPk+ [{:tableSchema "public", :tableName "no_pkey", :estimatedRowCount 11, :hasPkey false, :hasOwnership true}],++ :tablesWithoutOwnerMatch+ [{:tableSchema "public", :tableName "no_ownership", :estimatedRowCount 11, :hasPkey true, :hasOwnership false}]++ :errors+ {:noTables false, :noQuota false, :invalidSchemaFiltersPattern false}}+ resp))))(testing "creates"(is (= {} (database-replication.settings/database-replication-connections)))- (mt/user-http-request :crowberto :post 200 url)+ (mt/user-http-request :crowberto :post 200 url body)(is (= 1 (count @hm-state)))(let [hm-conn (first @hm-state)](is (= {(-> db :id str keyword) {:connection-id (str (:id hm-conn))}}(database-replication.settings/database-replication-connections)))(is (= (dissoc hm-conn :id)- {:type "pg_replication", :secret {:credentials (assoc db-details :port 5432 :dbtype "postgresql")}}))))+ {:type "pg_replication",+ :secret {:credentials (assoc db-details :port 5432 :dbtype "postgresql")+ :schema-filters [{:type "exclude", :patterns "not_pub*"}]}}))))(testing "deletes"(mt/user-http-request :crowberto :delete 204 url)(is (= 0 (count @hm-state)))(is (= {} (database-replication.settings/database-replication-connections))))(testing "idempotent delete"(mt/user-http-request :crowberto :delete 204 url)))))))))++(deftest preview-replication-test+ (let [quotas [{:usage 100000, :locked false, :updated-at "2025-08-05T08:48:11Z", :quota-type "rows", :hosting-feature "clickhouse-dwh", :soft-limit 500000}]+ valid-table {:table_schema "public", :table_name "valid_table", :estimated_row_count 1000, :has_pkey true, :has_ownership true}+ no-pk-table {:table_schema "public", :table_name "no_pk_table", :estimated_row_count 2000, :has_pkey false, :has_ownership true}+ no-ownership-table {:table_schema "public", :table_name "no_ownership_table", :estimated_row_count 3000, :has_pkey true, :has_ownership false}+ base-response {:free-quota 400000+ :total-estimated-row-count 0+ :errors {:no-tables false, :no-quota false, :invalid-schema-filters-pattern false}+ :can-set-replication true+ :replicated-tables []+ :tables-without-pk []+ :tables-without-owner-match []}]++ (testing "successful case with valid tables and quota"+ (is (= (merge base-response+ {:total-estimated-row-count 1000+ :replicated-tables [valid-table]})+ (api/preview-replication quotas [valid-table]))))++ (testing "no-tables error condition"+ (is (= (merge base-response+ {:errors {:no-tables true, :no-quota false, :invalid-schema-filters-pattern false}+ :can-set-replication false+ :tables-without-pk [no-pk-table]+ :tables-without-owner-match [no-ownership-table]})+ (api/preview-replication quotas [no-pk-table no-ownership-table]))))++ (testing "no-quota error condition"+ (let [high-row-table {:table_schema "public", :table_name "high_row_table", :estimated_row_count 500000, :has_pkey true, :has_ownership true}]+ (is (= (merge base-response+ {:total-estimated-row-count 500000+ :errors {:no-tables false, :no-quota true, :invalid-schema-filters-pattern false}+ :can-set-replication false+ :replicated-tables [high-row-table]})+ (api/preview-replication quotas [high-row-table])))))++ (testing "invalid-schema-filters-pattern error condition"+ (is (= (merge base-response+ {:errors {:no-tables true, :no-quota false, :invalid-schema-filters-pattern true}+ :can-set-replication false})+ (api/preview-replication quotas {:error "Invalid schema pattern"}))))++ (testing "mixed tables with various conditions"+ (is (= (merge base-response+ {:total-estimated-row-count 1000+ :replicated-tables [valid-table]+ :tables-without-pk [no-pk-table]+ :tables-without-owner-match [no-ownership-table]})+ (api/preview-replication quotas [valid-table no-pk-table no-ownership-table]))))++ (testing "no quota available"+ (let [no-quota-quotas [{:usage 500000, :locked false, :updated-at "2025-08-05T08:48:11Z", :quota-type "rows", :hosting-feature "clickhouse-dwh", :soft-limit 500000}]]+ (is (= (merge base-response+ {:free-quota 0+ :total-estimated-row-count 1000+ :errors {:no-tables false, :no-quota true, :invalid-schema-filters-pattern false}+ :can-set-replication false+ :replicated-tables [valid-table]})+ (api/preview-replication no-quota-quotas [valid-table])))))++ (testing "empty tables list"+ (is (= (merge base-response+ {:errors {:no-tables true, :no-quota false, :invalid-schema-filters-pattern false}+ :can-set-replication false})+ (api/preview-replication quotas []))))))diff --git a/enterprise/frontend/src/metabase-enterprise/api/database-replication.ts b/enterprise/frontend/src/metabase-enterprise/api/database-replication.tsindex 90845b76dd5..e2b2e4db0b1 100644--- a/enterprise/frontend/src/metabase-enterprise/api/database-replication.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/database-replication.ts@@ -3,12 +3,65 @@ import type { DatabaseId } from "metabase-types/api";import { EnterpriseApi } from "./api";+export interface GetDatabaseReplicationResponse {+ connectionId: number;+ status: "initializing" | "active" | "error" | "paused";+ statusReason: string;+ error: "internal" | "not-found";+ errorDetail: string;+ type: string;+}++export interface TableInfo {+ tableName: string;+ tableSchema: string;+}++export interface PreviewDatabaseReplicationResponse {+ canSetReplication: boolean;+ freeQuota: number;+ replicatedTables: TableInfo[];+ tablesWithoutPk: TableInfo[];+ tablesWithoutOwnerMatch: TableInfo[];+ totalEstimatedRowCount: number;+ errors?: {+ noTables?: boolean;+ noQuota?: boolean;+ invalidSchemaFiltersPattern?: boolean;+ };+}++export interface ReplicationSchemaFilters {+ "schema-filters-type": "include" | "exclude" | "all";+ "schema-filters-patterns": string;+}+export const DatabaseReplicationApi = EnterpriseApi.injectEndpoints({endpoints: (builder) => ({- createDatabaseReplication: builder.mutation<void, DatabaseId>({- query: (databaseId) => ({+ previewDatabaseReplication: builder.mutation<+ PreviewDatabaseReplicationResponse,+ {+ databaseId: DatabaseId;+ replicationSchemaFilters: ReplicationSchemaFilters;+ }+ >({+ query: ({ databaseId, ...body }) => ({+ method: "POST",+ url: `/api/ee/database-replication/connection/${databaseId}/preview`,+ body,+ }),+ }),+ createDatabaseReplication: builder.mutation<+ void,+ {+ databaseId: DatabaseId;+ replicationSchemaFilters: ReplicationSchemaFilters;+ }+ >({+ query: ({ databaseId, ...body }) => ({method: "POST",url: `/api/ee/database-replication/connection/${databaseId}`,+ body,}),invalidatesTags: (_, error) =>invalidateTags(error, [tag("session-properties")]),@@ -25,6 +78,7 @@ export const DatabaseReplicationApi = EnterpriseApi.injectEndpoints({});export const {+ usePreviewDatabaseReplicationMutation,useCreateDatabaseReplicationMutation,useDeleteDatabaseReplicationMutation,} = DatabaseReplicationApi;diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationButton.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationButton.tsxdeleted file mode 100644index 0181246ed91..00000000000--- a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationButton.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { t } from "ttag";--import ActionButton from "metabase/common/components/ActionButton";-import { useSetting } from "metabase/common/hooks";-import {- useCreateDatabaseReplicationMutation,- useDeleteDatabaseReplicationMutation,-} from "metabase-enterprise/api/database-replication";-import type { DatabaseId } from "metabase-types/api";--export function DatabaseReplicationButton({- databaseId,-}: {- databaseId: DatabaseId;-}) {- const showDatabaseReplication = useSetting("database-replication-enabled");- const connections = useSetting("database-replication-connections");-- const [createDatabaseReplication] = useCreateDatabaseReplicationMutation();- const [deleteDatabaseReplication] = useDeleteDatabaseReplicationMutation();-- const hasConnection = connections?.[databaseId] != null;-- if (!showDatabaseReplication) {- return null;- }-- const handleCreateReplication = () => {- return createDatabaseReplication(databaseId).unwrap();- };-- const handleDeleteReplication = () => {- return deleteDatabaseReplication(databaseId).unwrap();- };-- // Note: the api call will invalidate the session, which updates the setting, which swaps the buttons.- // When the button is swapped midway, it will use the other button's success text.- // So both buttons have the same innocuous success text.- if (hasConnection) {- return (- <ActionButton- actionFn={handleDeleteReplication}- normalText={t`Stop replicating to Data Warehouse`}- activeText={t`Stopping…`}- failedText={t`Failed to stop replication`}- successText={t`Done!`}- />- );- }-- return (- <ActionButton- actionFn={handleCreateReplication}- normalText={t`Replicate to Data Warehouse`}- activeText={t`Starting…`}- failedText={t`Failed to replicate`}- successText={t`Done!`}- />- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationButton.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationButton.unit.spec.tsxdeleted file mode 100644index 8f4257a7aaf..00000000000--- a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationButton.unit.spec.tsx+++ /dev/null@@ -1,132 +0,0 @@-import { waitFor } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { findRequests } from "__support__/server-mocks";-import { renderWithProviders, screen } from "__support__/ui";-import {- createMockSettingsState,- createMockState,-} from "metabase-types/store/mocks";--import { DatabaseReplicationButton } from "./DatabaseReplicationButton";--const setup = ({ databaseId = 1, settings = {} }) => {- const storeInitialState = createMockState({- settings: createMockSettingsState({- "database-replication-enabled": true,- "database-replication-connections": {},- ...settings,- }),- });-- fetchMock.post(- "express:/api/ee/database-replication/connection/:databaseId",- 200,- );- fetchMock.delete(- "express:/api/ee/database-replication/connection/:databaseId",- 200,- );-- return renderWithProviders(- <DatabaseReplicationButton databaseId={databaseId} />,- {- storeInitialState,- },- );-};--describe("DatabaseReplicationButton", () => {- describe("when database-replication-enabled is false", () => {- it("should not render button", () => {- setup({ settings: { "database-replication-enabled": false } });-- expect(screen.queryByRole("button")).not.toBeInTheDocument();- });- });-- describe("when database-replication-enabled is true", () => {- describe("and database has no replication connection", () => {- it("should render 'Replicate to Data Warehouse' button", () => {- setup({- databaseId: 1,- settings: { "database-replication-connections": {} },- });-- expect(- screen.getByRole("button", { name: "Replicate to Data Warehouse" }),- ).toBeInTheDocument();- });-- it("should call create API when clicked", async () => {- const view = userEvent.setup();- setup({- databaseId: 1,- settings: { "database-replication-connections": {} },- });-- await view.click(- screen.getByRole("button", { name: "Replicate to Data Warehouse" }),- );-- await waitFor(async () => {- const requests = await findRequests("POST");- expect(requests).toHaveLength(1);- });-- const requests = await findRequests("POST");- expect(requests[0].url).toMatch(- /\/api\/ee\/database-replication\/connection\/1$/,- );- });- });-- describe("and database has replication connection", () => {- it("should render 'Stop replicating to Data Warehouse' button", () => {- setup({- databaseId: 1,- settings: {- "database-replication-connections": {- 1: { connection_id: "conn_123" },- },- },- });-- expect(- screen.getByRole("button", {- name: "Stop replicating to Data Warehouse",- }),- ).toBeInTheDocument();- });-- it("should call delete API when clicked", async () => {- const view = userEvent.setup();- setup({- databaseId: 1,- settings: {- "database-replication-connections": {- 1: { connection_id: "conn_123" },- },- },- });-- await view.click(- screen.getByRole("button", {- name: "Stop replicating to Data Warehouse",- }),- );-- await waitFor(async () => {- const requests = await findRequests("DELETE");- expect(requests).toHaveLength(1);- });-- const requests = await findRequests("DELETE");- expect(requests[0].url).toMatch(- /\/api\/ee\/database-replication\/connection\/1$/,- );- });- });- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationError.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationError.tsxnew file mode 100644index 00000000000..142352827ee--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationError.tsx@@ -0,0 +1,45 @@+import { t } from "ttag";++import ExternalLink from "metabase/common/components/ExternalLink";+import { useSelector } from "metabase/lib/redux";+import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";+import { Button, Flex, Group, Icon, Stack, Text } from "metabase/ui";++export const DatabaseReplicationError = ({+ error,+ onClose,+}: {+ error?: string;+ onClose: () => void;+}) => {+ const showMetabaseLinks = useSelector(getShowMetabaseLinks);++ return (+ <Stack gap="xl" mt="xl">+ <Text c="text-secondary" fz="md" lh="1.25rem">+ {error || "Unknown error"}+ </Text>++ <Flex justify="end">+ <Group align="center">+ {showMetabaseLinks && (+ <Button+ component={ExternalLink}+ variant="outline"+ rightSection={<Icon name="external" />}+ size="md"+ role="link"+ href="https://www.metabase.com/docs/latest/"+ >+ {t`Read the docs`}+ </Button>+ )}++ <Button variant="filled" size="md" onClick={onClose}>+ {t`Close`}+ </Button>+ </Group>+ </Flex>+ </Stack>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationForm.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationForm.tsxnew file mode 100644index 00000000000..385ce23afd0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationForm.tsx@@ -0,0 +1,464 @@+import { useEffect, useState } from "react";+import { c, t } from "ttag";+import * as Yup from "yup";++import ExternalLink from "metabase/common/components/ExternalLink";+import { useStoreUrl } from "metabase/common/hooks";+import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";+import {+ Form,+ FormProvider,+ FormSelect,+ FormSubmitButton,+ FormTextarea,+} from "metabase/forms";+import { colors } from "metabase/lib/colors";+import { SEARCH_DEBOUNCE_DURATION } from "metabase/lib/constants";+import {+ Box,+ Card,+ Divider,+ Flex,+ Group,+ Icon,+ List,+ Loader,+ Progress,+ Skeleton,+ Stack,+ Text,+ UnstyledButton,+} from "metabase/ui";+import type {+ PreviewDatabaseReplicationResponse,+ TableInfo,+} from "metabase-enterprise/api/database-replication";+import type { Database, DatabaseId } from "metabase-types/api";++export interface DatabaseReplicationFormFields {+ databaseId: DatabaseId;+ schemaFiltersType: "all" | "include" | "exclude";+ schemaFiltersPatterns: string;+}++const validationSchema = Yup.object({+ schemaFiltersType: Yup.string().oneOf(["all", "include", "exclude"]),+ schemaFiltersPatterns: Yup.string(),+});++const compactEnglishNumberFormat = new Intl.NumberFormat("en", {+ notation: "compact",+ maximumFractionDigits: 1,+});++// JavaScript 2024 `Set.union` does not appear to be available?+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/union+const unionInPlace = <T,>(set: T[], values?: T[]) => {+ values?.forEach((v) => {+ if (!set.includes(v)) {+ set.push(v);+ }+ });+};++const calculateStorageUtilizationPercent = (+ previewResponse: PreviewDatabaseReplicationResponse | undefined,+): number | undefined => {+ return typeof previewResponse?.totalEstimatedRowCount === "number" &&+ typeof previewResponse?.freeQuota === "number" &&+ previewResponse.freeQuota > 0+ ? (previewResponse.totalEstimatedRowCount / previewResponse.freeQuota) * 100+ : undefined;+};++export const DatabaseReplicationForm = ({+ database,+ onSubmit,+ preview,+ initialValues,+}: {+ database: Database;+ onSubmit: (_: DatabaseReplicationFormFields) => void;+ preview: (+ fields: DatabaseReplicationFormFields,+ handleResponse: (_: PreviewDatabaseReplicationResponse) => void,+ handleError: (error: unknown) => void,+ ) => void;+ initialValues: DatabaseReplicationFormFields;+}) => {+ const storeUrl = useStoreUrl("account/storage");++ const [schemaFiltersType, setSchemaFiltersType] = useState(+ initialValues.schemaFiltersType,+ );+ const [schemaFiltersPatterns, setSchemaFiltersPatterns] = useState("");+ const debouncedSchemaFiltersPatterns = useDebouncedValue(+ schemaFiltersPatterns,+ SEARCH_DEBOUNCE_DURATION,+ );+ const isValidSchemaFiltersPatterns = !!debouncedSchemaFiltersPatterns.length;+ const [showNoSyncTables, setShowNoSyncTables] = useState(false);+ const [showReplicatedTables, setShowReplicatedTables] = useState(false);++ const [previewResponseLoading, setPreviewResponseLoading] = useState(false);+ const [previewResponse, setPreviewResponse] =+ useState<PreviewDatabaseReplicationResponse>();+ useEffect(() => {+ setPreviewResponseLoading(true);+ preview(+ {+ databaseId: database.id,+ schemaFiltersType,+ schemaFiltersPatterns: debouncedSchemaFiltersPatterns,+ },+ (res) => {+ setPreviewResponse(res);+ setPreviewResponseLoading(false);+ },+ () => setPreviewResponseLoading(false),+ );+ }, [preview, database.id, debouncedSchemaFiltersPatterns, schemaFiltersType]);++ const storageUtilizationPercent =+ calculateStorageUtilizationPercent(previewResponse);++ const noSyncTables: TableInfo[] = [];+ unionInPlace(noSyncTables, previewResponse?.tablesWithoutPk);+ unionInPlace(noSyncTables, previewResponse?.tablesWithoutOwnerMatch);++ const replicatedTables = previewResponse?.replicatedTables ?? [];++ const hasNoPk = (table: TableInfo) =>+ previewResponse?.tablesWithoutPk?.includes(table) ?? false;+ const hasOwnerMismatch = (table: TableInfo) =>+ previewResponse?.tablesWithoutOwnerMatch?.includes(table) ?? false;+ const noSyncReason = (table: TableInfo) =>+ hasNoPk(table)+ ? t`(no primary key)`+ : hasOwnerMismatch(table)+ ? t`(owner mismatch)`+ : undefined;++ const errorSection =+ previewResponse && !previewResponse.canSetReplication ? (+ <>+ <Divider />+ {previewResponse.errors?.noTables ? (+ <Text>{t`Nothing to replicate. Please select schemas containing at least one table to be replicated.`}</Text>+ ) : previewResponse.errors?.noQuota ? (+ <>+ <Text>{t`Not enough storage. Please upgrade your plan or modify the replication scope by excluding schemas.`}</Text>+ <ExternalLink href={storeUrl}>{t`Get more storage`}</ExternalLink>+ </>+ ) : null}+ </>+ ) : null;++ return (+ <Stack>+ <FormProvider+ initialValues={initialValues}+ onSubmit={onSubmit}+ validationSchema={validationSchema}+ >+ {({ values }) => (+ <Form>+ <Stack>+ <FormSelect+ name="schemaFiltersType"+ label={t`Select schemas to replicate`}+ onChange={(value) =>+ setSchemaFiltersType(+ value as typeof initialValues.schemaFiltersType,+ )+ }+ data={[+ { value: "all", label: t`All` },+ { value: "include", label: t`Only these…` },+ { value: "exclude", label: t`All except…` },+ ]}+ />++ {values.schemaFiltersType !== "all" && (+ <Box>+ <Text c="text-secondary" fz="sm">{c(+ "{0} is either NOT or empty string",+ )+ .t`Comma separated names of schemas that should ${values.schemaFiltersType === "exclude" ? "NOT " : ""}be replicated`}</Text>+ <FormTextarea+ name="schemaFiltersPatterns"+ placeholder={t`e.g. public, auth`}+ maxRows={5}+ minRows={2}+ onChange={({ target: { value } }) =>+ setSchemaFiltersPatterns(value)+ }+ />+ {previewResponse?.errors?.invalidSchemaFiltersPattern && (+ <Text c="error" fz="sm" mt="xs">+ {t`Invalid schema filters pattern`}+ </Text>+ )}+ </Box>+ )}++ <Card+ radius="md"+ bg="var(--mb-color-bg-light)"+ p={0}+ shadow="none"+ >+ <Flex+ align="flex-start"+ direction="row"+ gap="sm"+ justify="flex-start"+ wrap="nowrap"+ p="md"+ >+ <Icon name="info_outline" size={16} mt="1px" />+ <Box>+ <Text fz="md" lh="1rem">+ {t`Tables without primary key or with owner mismatch`}{" "}+ <strong>{t`will not be replicated`}</strong>.+ </Text>+ <UnstyledButton+ variant="subtle"+ size="xs"+ onClick={() => setShowNoSyncTables(!showNoSyncTables)}+ c="brand"+ fz="md"+ h="auto"+ mt="xs"+ p={0}+ w="auto"+ >+ <Flex+ align="center"+ direction="row"+ gap="xs"+ justify="flex-start"+ wrap="nowrap"+ >+ <Text span c="brand">+ {showNoSyncTables+ ? t`Hide tables (${noSyncTables.length})`+ : t`Show tables (${noSyncTables.length})`}+ </Text>+ <Icon+ name={showNoSyncTables ? "chevronup" : "chevrondown"}+ size={12}+ />+ </Flex>+ </UnstyledButton>+ </Box>+ </Flex>++ {showNoSyncTables && (+ <>+ <Divider />+ <Box+ mah={180}+ px="md"+ style={{+ overflowY: "auto",+ }}+ >+ <List spacing="xs" size="sm" fz="md" ml="sm" my="md">+ {noSyncTables.map((table) => (+ <List.Item+ key={`${table.tableSchema}.${table.tableName}`}+ fz="md"+ >+ <Text fz="md">+ <Text+ span+ c="text-dark"+ display="inline"+ fw="500"+ >+ {table.tableSchema}+ </Text>+ <Text span c="text-medium" display="inline">+ .{table.tableName}+ </Text>{" "}+ <Text span c="text-light" display="inline">+ {noSyncReason(table)}+ </Text>+ </Text>+ </List.Item>+ ))}+ </List>+ </Box>+ </>+ )}+ </Card>++ <Card+ radius="md"+ bg="var(--mb-color-bg-light)"+ p={0}+ shadow="none"+ >+ <Flex+ align="flex-start"+ direction="row"+ gap="sm"+ justify="flex-start"+ wrap="nowrap"+ p="md"+ >+ <Icon name="check" size={16} mt="1px" />+ <Box>+ <Text fz="md" lh="1rem">+ {t`The following tables will be replicated.`}+ </Text>+ <UnstyledButton+ variant="subtle"+ size="xs"+ onClick={() =>+ setShowReplicatedTables(!showReplicatedTables)+ }+ c="brand"+ fz="md"+ h="auto"+ mt="xs"+ p={0}+ w="auto"+ >+ <Flex+ align="center"+ direction="row"+ gap="xs"+ justify="flex-start"+ wrap="nowrap"+ >+ <Text span c="brand">+ {showReplicatedTables+ ? t`Hide tables (${replicatedTables.length})`+ : t`Show tables (${replicatedTables.length})`}+ </Text>+ <Icon+ name={+ showReplicatedTables ? "chevronup" : "chevrondown"+ }+ size={12}+ />+ </Flex>+ </UnstyledButton>+ </Box>+ </Flex>++ {showReplicatedTables && (+ <>+ <Divider />+ <Box+ mah={180}+ px="md"+ style={{+ overflowY: "auto",+ }}+ >+ <List spacing="xs" size="sm" fz="md" ml="sm" my="md">+ {replicatedTables.map((table) => (+ <List.Item+ key={`${table.tableSchema}.${table.tableName}`}+ fz="md"+ >+ <Text fz="md">+ <Text+ span+ c="text-dark"+ display="inline"+ fw="500"+ >+ {table.tableSchema}+ </Text>+ <Text span c="text-medium" display="inline">+ .{table.tableName}+ </Text>+ </Text>+ </List.Item>+ ))}+ </List>+ </Box>+ </>+ )}+ </Card>++ <Card+ radius="md"+ bg="var(--mb-color-bg-light)"+ p="md"+ my="sm"+ shadow="none"+ >+ <Stack>+ <Group justify="space-between">+ <Box ta="left">+ <Text c="text-light">{database.name}</Text>+ {!previewResponseLoading &&+ typeof previewResponse?.totalEstimatedRowCount ===+ "number" ? (+ <Text fw="bold">+ {t`${compactEnglishNumberFormat.format(previewResponse.totalEstimatedRowCount)} rows`}+ </Text>+ ) : (+ <Skeleton height="1.5em" width="10em" />+ )}+ </Box>++ {previewResponseLoading && <Loader />}++ <Box ta="right">+ <Text c="text-light">{t`Available Cloud Storage`}</Text>+ {!previewResponseLoading &&+ typeof previewResponse?.freeQuota === "number" ? (+ <Text fw="bold" w="100%">+ {t`${compactEnglishNumberFormat.format(previewResponse.freeQuota)} rows`}+ </Text>+ ) : (+ <Skeleton height="1.5em" width="10em" />+ )}+ </Box>+ </Group>++ {!previewResponseLoading &&+ typeof storageUtilizationPercent === "number" ? (+ <Progress+ value={storageUtilizationPercent}+ color={+ previewResponse?.canSetReplication+ ? colors.success+ : colors.error+ }+ />+ ) : (+ <Skeleton height="1em" width="100%" />+ )}++ {errorSection}+ </Stack>+ </Card>++ <Flex justify="end">+ <Group align="center" gap="sm">+ <FormSubmitButton+ disabled={+ (isValidSchemaFiltersPatterns &&+ previewResponseLoading) ||+ !previewResponse?.canSetReplication+ }+ label={t`Start replication`}+ variant="filled"+ mt="xs"+ />+ </Group>+ </Flex>+ </Stack>+ </Form>+ )}+ </FormProvider>+ </Stack>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationModal.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationModal.tsxnew file mode 100644index 00000000000..f7fbb49b144--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationModal.tsx@@ -0,0 +1,142 @@+import { useCallback, useState } from "react";+import { t } from "ttag";++import { Modal, type ModalProps } from "metabase/ui";+import {+ type PreviewDatabaseReplicationResponse,+ useCreateDatabaseReplicationMutation,+ usePreviewDatabaseReplicationMutation,+} from "metabase-enterprise/api/database-replication";+import type { Database } from "metabase-types/api";++import { DatabaseReplicationError } from "./DatabaseReplicationError";+import {+ DatabaseReplicationForm,+ type DatabaseReplicationFormFields,+} from "./DatabaseReplicationForm";+import { DatabaseReplicationSettingUp } from "./DatabaseReplicationSettingUp";+import { DatabaseReplicationSuccess } from "./DatabaseReplicationSuccess";++interface IRTKQueryError {+ status: unknown;+ data: unknown;+}++// https://redux-toolkit.js.org/rtk-query/usage/error-handling+const isRTKQueryError = (error: unknown): error is IRTKQueryError =>+ error instanceof Object && "status" in error && "data" in error;++const transformSchemaFilters = (+ schemaFiltersType: DatabaseReplicationFormFields["schemaFiltersType"],+ schemaFiltersPatterns: DatabaseReplicationFormFields["schemaFiltersPatterns"],+) => ({+ "schema-filters-type": schemaFiltersType,+ "schema-filters-patterns": schemaFiltersPatterns,+});++export const DatabaseReplicationModal = ({+ opened,+ onClose,+ database,+}: Pick<ModalProps, "opened" | "onClose"> & {+ database: Database;+}) => {+ const [setupStep, setSetupStep] = useState<+ "form" | "setting-up" | "success" | "error"+ >("form");+ const [error, setError] = useState<string>();+ const handleError = (error: unknown) => {+ setSetupStep("error");+ isRTKQueryError(error) &&+ typeof error.data === "string" &&+ setError(error.data);+ };+ const onModalClose = () => {+ setSetupStep("form");+ onClose();+ };++ const [createDatabaseReplication] = useCreateDatabaseReplicationMutation();+ const [previewDatabaseReplication] = usePreviewDatabaseReplicationMutation();+ const preview = useCallback(+ (+ {+ schemaFiltersType,+ schemaFiltersPatterns,+ }: DatabaseReplicationFormFields,+ handleResponse: (response: PreviewDatabaseReplicationResponse) => void,+ ) => {+ previewDatabaseReplication({+ databaseId: database.id,+ replicationSchemaFilters: transformSchemaFilters(+ schemaFiltersType,+ schemaFiltersPatterns,+ ),+ })+ .unwrap()+ .then(handleResponse)+ .catch(handleError);+ },+ [previewDatabaseReplication, database.id],+ );++ async function onSubmit({+ schemaFiltersType,+ schemaFiltersPatterns,+ }: DatabaseReplicationFormFields) {+ setSetupStep("setting-up");+ createDatabaseReplication({+ databaseId: database.id,+ replicationSchemaFilters: transformSchemaFilters(+ schemaFiltersType,+ schemaFiltersPatterns,+ ),+ })+ .unwrap()+ .then(() => setSetupStep("success"))+ .catch(handleError);+ }++ const isProgressStep = setupStep === "setting-up" || setupStep === "success";+ const isErrorStep = setupStep === "error";++ const canCloseModal = !isProgressStep && !isErrorStep;++ return (+ <Modal+ opened={isProgressStep || opened}+ onClose={onModalClose}+ closeOnClickOutside={canCloseModal}+ closeOnEscape={canCloseModal}+ withCloseButton={canCloseModal}+ padding="2.5rem"+ title={+ isProgressStep+ ? undefined+ : isErrorStep+ ? t`Couldn't replicate database`+ : t`Set up database replication`+ }+ mah="80%"+ >+ {setupStep === "form" ? (+ <DatabaseReplicationForm+ database={database}+ onSubmit={onSubmit}+ preview={preview}+ initialValues={{+ databaseId: database.id,+ schemaFiltersType: "all",+ schemaFiltersPatterns: "",+ }}+ />+ ) : setupStep === "setting-up" ? (+ <DatabaseReplicationSettingUp />+ ) : setupStep === "success" ? (+ <DatabaseReplicationSuccess onClose={onModalClose} />+ ) : setupStep === "error" ? (+ <DatabaseReplicationError error={error} onClose={onModalClose} />+ ) : undefined}+ </Modal>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationModal.unit.spec.tsxnew file mode 100644index 00000000000..7bef74d4f7a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationModal.unit.spec.tsx@@ -0,0 +1,285 @@+import userEvent from "@testing-library/user-event";+import type { RouteResponse } from "fetch-mock";+import fetchMock from "fetch-mock";++import { renderWithProviders, screen, waitFor } from "__support__/ui";+import type { PreviewDatabaseReplicationResponse } from "metabase-enterprise/api/database-replication";+import { createMockDatabase } from "metabase-types/api/mocks";++import { DatabaseReplicationModal } from "./DatabaseReplicationModal";++const mockPreviewResponse: PreviewDatabaseReplicationResponse = {+ canSetReplication: true,+ freeQuota: 1000000,+ replicatedTables: [+ { tableName: "users", tableSchema: "public" },+ { tableName: "orders", tableSchema: "public" },+ ],+ tablesWithoutPk: [{ tableName: "logs", tableSchema: "public" }],+ tablesWithoutOwnerMatch: [{ tableName: "temp_data", tableSchema: "staging" }],+ totalEstimatedRowCount: 500000,+};++const setup = async ({+ previewResponse = mockPreviewResponse as RouteResponse,+ createResponse = {} as RouteResponse,+} = {}) => {+ const database = createMockDatabase({ id: 1, name: "Test Database" });++ fetchMock.post(+ `path:/api/ee/database-replication/connection/${database.id}`,+ createResponse,+ );+ fetchMock.post(+ `path:/api/ee/database-replication/connection/${database.id}/preview`,+ previewResponse,+ );++ const view = renderWithProviders(+ <DatabaseReplicationModal+ opened={true}+ onClose={jest.fn()}+ database={database}+ />,+ );++ await waitFor(() => {+ expect(+ fetchMock.callHistory.called(+ `path:/api/ee/database-replication/connection/1/preview`,+ {+ method: "POST",+ body: {+ replicationSchemaFilters: {+ "schema-filters-type": "all",+ "schema-filters-patterns": "",+ },+ },+ },+ ),+ ).toBeTruthy();+ });++ return {+ user: userEvent.setup(),+ view,+ };+};++describe("DatabaseReplicationForm", () => {+ it("renders schema selection options", async () => {+ await setup();++ expect(+ screen.getByLabelText("Select schemas to replicate"),+ ).toBeInTheDocument();+ expect(screen.getByDisplayValue("All")).toBeInTheDocument();+ });++ it("shows textarea only when schema selection is not 'all'", async () => {+ const { user } = await setup();++ // Initially should not show textarea+ expect(+ screen.queryByPlaceholderText("e.g. public, auth"),+ ).not.toBeInTheDocument();++ // Change to "include"+ const select = screen.getByLabelText("Select schemas to replicate");+ await user.click(select);+ await user.click(screen.getByText("Only these…"));++ // Now should show textarea+ expect(+ screen.getByPlaceholderText("e.g. public, auth"),+ ).toBeInTheDocument();+ expect(+ screen.getByText(+ "Comma separated names of schemas that should be replicated",+ ),+ ).toBeInTheDocument();+ });++ it("shows correct text for exclude option", async () => {+ const { user } = await setup();++ const select = screen.getByLabelText("Select schemas to replicate");+ await user.click(select);+ await user.click(screen.getByText("All except…"));++ expect(+ screen.getByText(+ "Comma separated names of schemas that should NOT be replicated",+ ),+ ).toBeInTheDocument();+ });++ it("calls preview with debounced parameters when filters change", async () => {+ const { user } = await setup();++ // Change schema type+ const select = screen.getByLabelText("Select schemas to replicate");+ await user.click(select);+ await user.click(screen.getByText("Only these…"));++ // Type in textarea with debouncing+ const textarea = screen.getByPlaceholderText("e.g. public, auth");+ await user.type(textarea, "public");++ // Should make new API call with updated parameters after debounce+ await waitFor(() => {+ expect(+ fetchMock.callHistory.called(+ `path:/api/ee/database-replication/connection/1/preview`,+ {+ method: "POST",+ body: {+ replicationSchemaFilters: {+ "schema-filters-type": "include",+ "schema-filters-patterns": "public",+ },+ },+ },+ ),+ ).toBeTruthy();+ });+ });++ it("displays table information cards", async () => {+ await setup();++ expect(+ screen.getByText(/Tables without primary key or with owner mismatch/),+ ).toBeInTheDocument();+ expect(+ screen.getByText(/The following tables will be replicated/),+ ).toBeInTheDocument();+ });++ it("shows storage utilization information", async () => {+ await setup();++ expect(screen.getByText("Test Database")).toBeInTheDocument();+ expect(screen.getByText("Available Cloud Storage")).toBeInTheDocument();+ });++ it("renders DatabaseReplicationError when preview fails", async () => {+ setup({ previewResponse: { status: 500 } });++ await waitFor(() => {+ expect(+ screen.getByText("Couldn't replicate database"),+ ).toBeInTheDocument();+ });++ expect(screen.getByText("Unknown error")).toBeInTheDocument();+ });++ it("renders DatabaseReplicationError when submit fails", async () => {+ const { user } = await setup({+ createResponse: { status: 400, body: "Replication setup failed" },+ });++ await waitFor(() => {+ expect(+ screen.getByRole("button", { name: "Start replication" }),+ ).toBeInTheDocument();+ });++ const submitButton = screen.getByRole("button", {+ name: "Start replication",+ });+ await user.click(submitButton);++ await waitFor(() => {+ expect(+ screen.getByText("Couldn't replicate database"),+ ).toBeInTheDocument();+ });++ expect(screen.getByText("Replication setup failed")).toBeInTheDocument();+ });++ it("shows invalid schema filters pattern error message", async () => {+ const previewResponseWithError = {+ ...mockPreviewResponse,+ canSetReplication: false,+ errors: {+ invalidSchemaFiltersPattern: true,+ },+ };++ const { user } = await setup({ previewResponse: previewResponseWithError });++ // Change to "include" to show textarea+ const select = screen.getByLabelText("Select schemas to replicate");+ await user.click(select);+ await user.click(screen.getByText("Only these…"));++ // Wait for error message to appear+ await waitFor(() => {+ expect(+ screen.getByText("Invalid schema filters pattern"),+ ).toBeInTheDocument();+ });++ const submitButton = screen.getByRole("button", {+ name: "Start replication",+ });+ expect(submitButton).toBeDisabled();+ });++ it("shows nothing to replicate error message", async () => {+ const previewResponseWithError = {+ ...mockPreviewResponse,+ canSetReplication: false,+ errors: {+ noTables: true,+ },+ };++ await setup({ previewResponse: previewResponseWithError });++ await waitFor(() => {+ expect(+ screen.getByText(+ "Nothing to replicate. Please select schemas containing at least one table to be replicated.",+ ),+ ).toBeInTheDocument();+ });++ const submitButton = screen.getByRole("button", {+ name: "Start replication",+ });+ expect(submitButton).toBeDisabled();+ });++ it("shows not enough storage error message", async () => {+ const previewResponseWithError = {+ ...mockPreviewResponse,+ canSetReplication: false,+ errors: {+ noQuota: true,+ },+ };++ await setup({ previewResponse: previewResponseWithError });++ await waitFor(() => {+ expect(+ screen.getByText(+ "Not enough storage. Please upgrade your plan or modify the replication scope by excluding schemas.",+ ),+ ).toBeInTheDocument();+ });++ await waitFor(() => {+ expect(screen.getByText("Get more storage")).toBeInTheDocument();+ });++ const submitButton = screen.getByRole("button", {+ name: "Start replication",+ });+ expect(submitButton).toBeDisabled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationPostgresInfo.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationPostgresInfo.tsxindex 1581ce121de..300ea971c39 100644--- a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationPostgresInfo.tsx+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationPostgresInfo.tsx@@ -14,7 +14,7 @@ export function DatabaseReplicationPostgresInfo() {);return (- <Text size="sm" c="text-medium">+ <Text size="md" c="text-medium">{jt`Note: You may need to ${link} in the source database. The process might also require a database restart.`}</Text>);diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSection.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSection.tsxindex 41163b727a6..72f9ceb9133 100644--- a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSection.tsx+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSection.tsx@@ -1,3 +1,4 @@+import { useState } from "react";import { t } from "ttag";import {@@ -5,10 +6,11 @@ import {DatabaseInfoSectionDivider,} from "metabase/admin/databases/components/DatabaseInfoSection";import { useSetting } from "metabase/common/hooks";-import { Flex } from "metabase/ui";+import { Button, Flex, Icon } from "metabase/ui";+import { useDeleteDatabaseReplicationMutation } from "metabase-enterprise/api/database-replication";import type { Database } from "metabase-types/api";-import { DatabaseReplicationButton } from "./DatabaseReplicationButton";+import { DatabaseReplicationModal } from "./DatabaseReplicationModal";import { DatabaseReplicationPostgresInfo } from "./DatabaseReplicationPostgresInfo";import { DatabaseReplicationStatusInfo } from "./DatabaseReplicationStatusInfo";@@ -26,7 +28,12 @@ export function DatabaseReplicationSection({}: {database: Database;}) {+ const [showDWHReplicationModal, setShowDWHReplicationModal] =+ useState<boolean>(false);+ const connections = useSetting("database-replication-connections");const databaseReplicationEnabled = useSetting("database-replication-enabled");+ const [deleteDatabaseReplication, { isLoading: isDeleting }] =+ useDeleteDatabaseReplicationMutation();const databaseSupportsReplication = database.features?.includes("database-replication",);@@ -36,6 +43,10 @@ export function DatabaseReplicationSection({}const engineInfo = getEngineInfo(database.engine);+ const hasConnection = connections?.[database.id] != null;+ const onDelete = async () => {+ await deleteDatabaseReplication(database.id).unwrap();+ };return (<DatabaseInfoSection@@ -46,7 +57,23 @@ export function DatabaseReplicationSection({><Flex align="center" justify="space-between" gap="lg"><DatabaseReplicationStatusInfo databaseId={database.id} />- <DatabaseReplicationButton databaseId={database.id} />+ {hasConnection ? (+ <Button+ onClick={onDelete}+ loaderProps={{ children: t`Stopping…` }}+ loading={isDeleting}+ leftSection={<Icon name="trash" />}+ >{t`Stop replicating to Data Warehouse`}</Button>+ ) : (+ <Button+ onClick={() => setShowDWHReplicationModal(true)}+ >{t`Set up replication`}</Button>+ )}+ <DatabaseReplicationModal+ database={database}+ opened={showDWHReplicationModal}+ onClose={() => setShowDWHReplicationModal(false)}+ /></Flex>{engineInfo && (diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSettingUp.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSettingUp.tsxnew file mode 100644index 00000000000..51d6dcaba69--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSettingUp.tsx@@ -0,0 +1,42 @@+import { t } from "ttag";++import MetabotCloudIcon from "assets/img/metabot-cloud-96x96.svg";+import { Box, Flex, Loader, Stack, Text, Title } from "metabase/ui";++export const DatabaseReplicationSettingUp = () => (+ <Stack align="center" gap="lg" my="4.5rem">+ <Box h={96} pos="relative" w={96}>+ <img src={MetabotCloudIcon} alt={t`Metabot Cloud`} />++ <Flex+ bottom={0}+ align="center"+ direction="row"+ gap={0}+ justify="center"+ pos="absolute"+ right={0}+ wrap="nowrap"+ bg="white"+ fz={0}+ p="sm"+ ta="center"+ style={{+ borderRadius: "100%",+ boxShadow: `0 1px 6px 0 var(--mb-color-shadow)`,+ }}+ >+ <Loader size="xs" ml={1} mt={1} />+ </Flex>+ </Box>++ <Box ta="center">+ <Title c="text-primary" fz="lg">{t`Setting up, please wait`}</Title>+ <Text+ c="text-secondary"+ fz="md"+ lh="1.25rem"+ >{t`This will take just a minute or so`}</Text>+ </Box>+ </Stack>+);diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationStatusInfo.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationStatusInfo.tsxindex 7ab041103fd..eb3432a1a96 100644--- a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationStatusInfo.tsx+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationStatusInfo.tsx@@ -1,4 +1,4 @@-import { useMemo } from "react";+import { memo } from "react";import { t } from "ttag";import { useSetting } from "metabase/common/hooks";@@ -9,28 +9,27 @@ interface DatabaseReplicationStatusInfoProps extends FlexProps {databaseId: DatabaseId;}-export const DatabaseReplicationStatusInfo = ({- databaseId,- ...props-}: DatabaseReplicationStatusInfoProps) => {- const connections = useSetting("database-replication-connections");-- const status = useMemo(() => {+export const DatabaseReplicationStatusInfo = memo(+ function DatabaseReplicationStatusInfo({+ databaseId,+ ...flexProps+ }: DatabaseReplicationStatusInfoProps) {+ const connections = useSetting("database-replication-connections");const hasConnection = connections?.[databaseId] != null;+ const message = hasConnection+ ? // eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins.+ t`Replicating to Metabase Cloud Storage`+ : // eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins.+ t`Not replicating to Metabase Cloud Storage`;+ const color = hasConnection ? "success" : "text-light";- if (hasConnection) {- return { message: t`Replicating`, color: "success" } as const;- } else {- return { message: t`Not replicating`, color: "text-light" } as const;- }- }, [connections, databaseId]);-- return (- <Flex align="center" gap="sm" {...props}>- <Tooltip label={status.message}>- <Badge size="12" circle bg={status.color} style={{ flexShrink: 0 }} />- </Tooltip>- <Text lh="1.4">{status.message}</Text>- </Flex>- );-};+ return (+ <Flex align="center" gap="sm" {...flexProps}>+ <Tooltip label={message}>+ <Badge size="12" circle bg={color} style={{ flexShrink: 0 }} />+ </Tooltip>+ <Text lh="1.25rem">{message}</Text>+ </Flex>+ );+ },+);diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationStatusInfo.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationStatusInfo.unit.spec.tsxindex 7548e206c47..0c318c794e4 100644--- a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationStatusInfo.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationStatusInfo.unit.spec.tsx@@ -26,7 +26,9 @@ describe("DatabaseReplicationStatusInfo", () => {it("should show 'Not replicating' status", () => {setup({ databaseId: 1 });- expect(screen.getByText("Not replicating")).toBeInTheDocument();+ expect(+ screen.getByText("Not replicating to Metabase Cloud Storage"),+ ).toBeInTheDocument();});it("should show 'Not replicating' status when database ID is not in connections", () => {@@ -39,7 +41,9 @@ describe("DatabaseReplicationStatusInfo", () => {},});- expect(screen.getByText("Not replicating")).toBeInTheDocument();+ expect(+ screen.getByText("Not replicating to Metabase Cloud Storage"),+ ).toBeInTheDocument();});});@@ -54,7 +58,9 @@ describe("DatabaseReplicationStatusInfo", () => {},});- expect(screen.getByText("Replicating")).toBeInTheDocument();+ expect(+ screen.getByText("Replicating to Metabase Cloud Storage"),+ ).toBeInTheDocument();});it("should render a badge/indicator element", () => {@@ -78,7 +84,9 @@ describe("DatabaseReplicationStatusInfo", () => {},});- expect(screen.getByText("Replicating")).toBeInTheDocument();+ expect(+ screen.getByText("Replicating to Metabase Cloud Storage"),+ ).toBeInTheDocument();});});});diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSuccess.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSuccess.tsxnew file mode 100644index 00000000000..97b0ce90052--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationSuccess.tsx@@ -0,0 +1,29 @@+import { t } from "ttag";++import MetabotCloudIcon from "assets/img/metabot-cloud-96x96.svg";+import { Box, Button, Stack, Text, Title } from "metabase/ui";++export const DatabaseReplicationSuccess = ({+ onClose,+}: {+ onClose: () => void;+}) => {+ return (+ <Stack align="center" gap="lg" my="4.5rem">+ <Box h={96} w={96}>+ <img src={MetabotCloudIcon} alt={t`Metabot Cloud`} />+ </Box>++ <Box ta="center">+ <Title c="text-primary" fz="lg">{t`Replication in progress`}</Title>+ <Text c="text-secondary" fz="md" lh="1.25rem">+ {t`The process runs in the background. Depending on the database size, this can take up to several hours. You will get an email once your data is ready to use.`}+ </Text>+ </Box>++ <Button onClick={onClose} size="md" variant="filled" miw="30%">+ {t`Done`}+ </Button>+ </Stack>+ );+};diff --git a/frontend/src/metabase/admin/databases/components/DatabaseInfoSection.tsx b/frontend/src/metabase/admin/databases/components/DatabaseInfoSection.tsxindex f995c43336b..edd02955b08 100644--- a/frontend/src/metabase/admin/databases/components/DatabaseInfoSection.tsx+++ b/frontend/src/metabase/admin/databases/components/DatabaseInfoSection.tsx@@ -1,3 +1,5 @@+import type { PropsWithChildren } from "react";+import Markdown from "metabase/common/components/Markdown";import {Box,@@ -12,7 +14,6 @@ import {interface DatabaseInfoSectionProps extends FlexProps {name: string;description: string;- children: React.ReactNode;condensed?: boolean;}@@ -22,7 +23,7 @@ export const DatabaseInfoSection = ({children,condensed = false,...props-}: DatabaseInfoSectionProps) => (+}: PropsWithChildren<DatabaseInfoSectionProps>) => (<Flex gap="lg" w="100%" direction={{ sm: "row", base: "column" }} {...props}><Stack w="100%" maw={{ sm: "16rem" }} mt="md" style={{ flexShrink: 0 }}><Text size="lg" fw="700" mb="xs" lh={1.4}>@@ -36,7 +37,7 @@ export const DatabaseInfoSection = ({bg="accent-gray-light"shadow="none"style={{ flexGrow: 0 }}- px="1.5rem"+ px="lg"py={condensed ? "1.125rem" : "1.875rem"}>{children}@@ -53,10 +54,6 @@ export const DatabaseInfoSectionDivider = ({condensed?: boolean;}) => {return (- <Divider- w="calc(100% + 3rem)"- ml="-1.5rem"- my={condensed ? "1rem" : "1.5rem"}- />+ <Divider w="calc(100% + 3rem)" ml="-1.5rem" my={condensed ? "md" : "lg"} />);};diff --git a/src/metabase/driver/sync.clj b/src/metabase/driver/sync.cljindex e52d5902464..271d34ce58d 100644--- a/src/metabase/driver/sync.clj+++ b/src/metabase/driver/sync.clj@@ -8,7 +8,7 @@(set! *warn-on-reflection* true)-(defn- schema-pattern->re-pattern+(defn schema-pattern->re-pattern"Converts a schema pattern, as entered in the UI, into regex pattern suitable to be passed into [[re-pattern]]. Theconversion that happens is from commas into pipes (disjunction), and wildcard characters (`*`) into greedy wildcardmatchers (`.*`). These only occur if those characters are not preceded by a backslash, which serves as an escapediff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.cljindex 1cf975af314..2e965d304f9 100644--- a/src/metabase/premium_features/core.clj+++ b/src/metabase/premium_features/core.clj@@ -28,6 +28,7 @@log-enabled?max-users-allowedplan-alias+ quotasTokenStatusclear-cache]diff --git a/src/metabase/premium_features/token_check.clj b/src/metabase/premium_features/token_check.cljindex 453e4912e09..29a76440d33 100644--- a/src/metabase/premium_features/token_check.clj+++ b/src/metabase/premium_features/token_check.clj@@ -131,7 +131,8 @@[:max-users {:optional true} pos-int?][:company {:optional true} [:string {:min 1}]][:store-users {:optional true} [:maybe [:sequential [:map- [:email :string]]]]]])+ [:email :string]]]]]+ [:quotas {:optional true} [:sequential [:map]]]])(def ^:private ^:const token-status-cache-ttl"Amount of time in ms to cache the status of a valid enterprise token before forcing a re-check."@@ -349,6 +350,14 @@fetch-token-status:plan-alias))+(mu/defn quotas :- [:maybe [:sequential [:map]]]+ "Returns a vector of maps for each quota of the subscription."+ []+ (memoize/memo-clear! fetch-token-and-parse-body*)+ (some-> (premium-features.settings/premium-embedding-token)+ fetch-token-status+ :quotas))+(defn has-any-features?"True if we have a valid premium features token with ANY features."[]