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
UXW-4973 Correctly show cache durations (#79499)
Denis Berezineebccaad10c0
diff --git a/docs/configuring-metabase/caching.md b/docs/configuring-metabase/caching.mdindex 1f42059a6d0..1700186a814 100644--- a/docs/configuring-metabase/caching.md+++ b/docs/configuring-metabase/caching.md@@ -38,7 +38,7 @@ These policies determine how long cached results will remain valid.{% include plans-blockquote.html feature="Duration caching policy" %}-Invalidate and clear the cache after a certain number of hours. When someone runs a query, Metabase will first check whether it has cached the results, and whether those results are still valid. If not, Metabase runs the query against the database and caches the results. These cached results will remain valid for the duration you've set.+Invalidate and clear the cache after a certain amount of time (seconds, minutes, hours, or days). When someone runs a query, Metabase will first check whether it has cached the results, and whether those results are still valid. If not, Metabase runs the query against the database and caches the results. These cached results will remain valid for the duration you've set.### Schedule caching policydiff --git a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts b/e2e/test/scenarios/admin/performance/caching.cy.spec.tsindex d865b86652d..1e101b1710c 100644--- a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts+++ b/e2e/test/scenarios/admin/performance/caching.cy.spec.ts@@ -209,7 +209,7 @@ describe("scenarios > admin > performance > caching", () => {H.visitQuestion(ORDERS_QUESTION_ID);openSidebarCacheStrategyForm("question");H.selectCacheStrategy(/Duration/);- cy.findByLabelText(/Cache duration/).type("99");+ cy.findByRole("spinbutton", { name: /Cache duration/ }).type("99");saveCacheStrategyForm();cy.log("Configure Orders, Count with Adaptive");@@ -227,7 +227,10 @@ describe("scenarios > admin > performance > caching", () => {cy.log("Clicking Duration: 99h opens its form with duration selected");cy.findByTestId("cache-config-table").contains("Duration: 99h").click();H.cacheStrategySelect().should("have.value", "Duration");- cy.findByLabelText(/Cache duration/).should("have.value", "99");+ cy.findByRole("spinbutton", { name: /Cache duration/ }).should(+ "have.value",+ "99",+ );cy.log("Close the sidesheet via ESC");cy.get("body").type("{esc}");diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsxindex e6615ff597a..a3b406013a3 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx@@ -1,4 +1,5 @@import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";import { act, screen, within } from "__support__/ui";import type { SetupOpts } from "metabase/admin/performance/components/test-utils";@@ -16,7 +17,10 @@ import {type DurationStrategy,type ScheduleStrategy,} from "metabase-types/api";-import { createMockTokenFeatures } from "metabase-types/api/mocks";+import {+ createMockCacheConfig,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";function setup(opts: SetupOpts = {}) {baseSetup({@@ -98,7 +102,7 @@ describe("StrategyEditorForDatabases", () => {expect((await screen.findAllByRole("spinbutton")).length).toBe(1);- await changeInput(/Cache duration/, 24, 48);+ await changeInput(/Cache duration/, 0, 48);await userEvent.click(await screen.findByTestId("strategy-form-submit-button"),@@ -169,7 +173,11 @@ describe("StrategyEditorForDatabases", () => {expect((await screen.findAllByRole("spinbutton")).length).toBe(1);- await changeInput(/Cache duration/, 24, 48);+ expect(await screen.findByTestId("duration-unit-select")).toHaveValue(+ "hours",+ );++ await changeInput(/Cache duration/, 0, 48);await userEvent.click(await screen.findByTestId("strategy-form-submit-button"),@@ -250,15 +258,118 @@ describe("StrategyEditorForDatabases", () => {expect(result).toBe("Scheduled: hourly");});- it("can abbreviate a 'Duration' strategy", () => {+ it.each([+ [CacheDurationUnit.Hours, "Duration: 5h"],+ [CacheDurationUnit.Minutes, "Duration: 5m"],+ [CacheDurationUnit.Seconds, "Duration: 5s"],+ [CacheDurationUnit.Days, "Duration: 5d"],+ ])("can abbreviate a 'Duration' strategy with unit %s", (unit, expected) => {const strategy: DurationStrategy = {type: "duration",duration: 5,- unit: CacheDurationUnit.Hours,+ unit,refresh_automatically: false,};- const result = getShortStrategyLabel(strategy);- expect(result).toBe("Duration: 5h");+ expect(getShortStrategyLabel(strategy)).toBe(expected);+ });++ it("does not allow saving an empty cache duration", async () => {+ await userEvent.click(+ await screen.findByLabelText(+ "Edit default policy (currently: Duration: 1h)",+ ),+ );++ const input = await screen.findByRole("spinbutton", {+ name: /Cache duration/,+ });+ await userEvent.clear(input);+ await userEvent.click(+ await screen.findByTestId("strategy-form-submit-button"),+ );++ expect(+ await screen.findByText("Enter a positive number."),+ ).toBeInTheDocument();+ expect(+ fetchMock.callHistory.calls("path:/api/cache", { method: "PUT" }),+ ).toHaveLength(0);+ });++ it("pluralizes the unit options with the entered duration", async () => {+ await userEvent.click(+ await screen.findByLabelText(+ "Edit default policy (currently: Duration: 1h)",+ ),+ );++ expect(await screen.findByTestId("duration-unit-select")).toHaveValue(+ "hour",+ );++ await changeInput(/Cache duration/, 0, 2);++ expect(await screen.findByTestId("duration-unit-select")).toHaveValue(+ "hours",+ );+ });++ it("lets user change the duration unit", async () => {+ await userEvent.click(+ await screen.findByLabelText(+ "Edit default policy (currently: Duration: 1h)",+ ),+ );++ await userEvent.click(await screen.findByTestId("duration-unit-select"));+ await userEvent.click(+ await screen.findByRole("option", { name: "minute" }),+ );++ await userEvent.click(+ await screen.findByTestId("strategy-form-submit-button"),+ );++ expect(+ await screen.findByLabelText(+ "Edit default policy (currently: Duration: 1m)",+ ),+ ).toBeInTheDocument();+ });+});++describe("StrategyEditorForDatabases (sub-hour duration policy)", () => {+ beforeEach(() => {+ setup({+ cacheConfigs: [+ createMockCacheConfig({+ model: "root",+ model_id: 0,+ strategy: {+ type: "duration",+ duration: 30,+ unit: CacheDurationUnit.Minutes,+ refresh_automatically: false,+ },+ }),+ ],+ });+ });++ it("shows a policy stored with a sub-hour unit faithfully", async () => {+ await userEvent.click(+ await screen.findByLabelText(+ "Edit default policy (currently: Duration: 30m)",+ ),+ );++ expect(await getCacheStrategySelect()).toHaveValue("Duration");+ expect(+ await screen.findByRole("spinbutton", { name: /Cache duration/ }),+ ).toHaveValue(30);+ expect(await screen.findByTestId("duration-unit-select")).toHaveValue(+ "minutes",+ );});});diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsxindex 757c2644146..e0a55db6d7d 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx@@ -14,7 +14,6 @@ import type { ColumnItem } from "metabase/common/components/Table/types";import { usePagination } from "metabase/common/hooks/use-pagination";import { Center, Flex, Repeat, Skeleton, Stack } from "metabase/ui";import type { CacheSortColumn, CacheableModel } from "metabase-types/api";-import { CacheDurationUnit } from "metabase-types/api";import type { SortDirection } from "metabase-types/api/sorting";import type { CacheableItem, UpdateTarget } from "../types";@@ -100,16 +99,7 @@ export const StrategyEditorForQuestionsAndDashboards = () => {}): undefined;- const savedStrategy = useMemo(() => {- const strategy = targetConfig?.strategy;- if (!strategy) {- return undefined;- }- if (strategy.type === "duration") {- return { ...strategy, unit: CacheDurationUnit.Hours };- }- return { ...strategy };- }, [targetConfig?.strategy]);+ const savedStrategy = targetConfig?.strategy;const targetName = useMemo(() => {if (targetId === null || targetModel === null) {diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/utils.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/utils.tsxindex 3139b9d15b9..d15b2a77463 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/utils.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/utils.tsx@@ -3,24 +3,29 @@ import _ from "underscore";import { getShortStrategyLabel } from "metabase/admin/performance/utils";import { getCollectionPathAsString } from "metabase/common/collections/utils";+import { CacheDurationUnit } from "metabase-types/api";import type { CacheableItem } from "../types";+const DURATION_UNIT_SECONDS: Record<CacheDurationUnit, number> = {+ [CacheDurationUnit.Seconds]: 1,+ [CacheDurationUnit.Minutes]: 60,+ [CacheDurationUnit.Hours]: 3600,+ [CacheDurationUnit.Days]: 86400,+};+export const formatValueForSorting = (row: CacheableItem,columnName: string,) => {if (columnName === "policy") {- const label = getShortStrategyLabel(row.strategy, row.model);if (row.strategy.type === "duration") {// Sort durations in ascending order of length- return label?.replace(/(\d+)h/, (_, num) => {- const paddedNumber = num.padStart(5, "0");- return `${t`Duration`} ${paddedNumber}`;- });- } else {- return label;+ const seconds =+ row.strategy.duration * DURATION_UNIT_SECONDS[row.strategy.unit];+ return `${t`Duration`} ${String(seconds).padStart(12, "0")}`;}+ return getShortStrategyLabel(row.strategy, row.model);}if (columnName === "collection") {return row.collection ? getCollectionPathAsString(row.collection) : "";diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/utils.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/utils.unit.spec.tsxindex 102651dc29f..2f5d0cd5334 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/utils.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/utils.unit.spec.tsx@@ -170,6 +170,42 @@ describe("StrategyEditorForQuestionsAndDashboards utilities", () => {]);});+ it("sorts durations with mixed units by real length", () => {+ const durationRow = (+ id: number,+ duration: number,+ unit: CacheDurationUnit,+ ): CacheableItem => ({+ model: "question",+ id,+ strategy: {+ type: "duration",+ duration,+ unit,+ refresh_automatically: false,+ },+ });+ const rows = [+ durationRow(0, 1, CacheDurationUnit.Days),+ durationRow(1, 100, CacheDurationUnit.Minutes),+ durationRow(2, 90, CacheDurationUnit.Seconds),+ durationRow(3, 10, CacheDurationUnit.Hours),+ durationRow(4, 30, CacheDurationUnit.Seconds),+ ];+ const sorted = rows.sort((rowA, rowB) => {+ const a = formatValueForSorting(rowA, "policy");+ const b = formatValueForSorting(rowB, "policy");+ return String(a).localeCompare(String(b));+ });+ expect(sorted.map((row) => getShortStrategyLabel(row.strategy))).toEqual([+ "Duration: 30s",+ "Duration: 90s",+ "Duration: 100m",+ "Duration: 10h",+ "Duration: 1d",+ ]);+ });+it("sorts by collection correctly", () => {const sorted = unsortedRows.sort((rowA, rowB) => {// Unjustified type cast. FIXMEdiff --git a/enterprise/frontend/src/metabase-enterprise/caching/constants.ts b/enterprise/frontend/src/metabase-enterprise/caching/constants.tsindex ec9b4269d90..17486a7c959 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/caching/constants.ts@@ -28,11 +28,13 @@ const getDurationStrategyValidationSchema = () =>Yup.object({type: Yup.string().equals(["duration"]),duration: getPositiveIntegerSchema().default(24),- unit: Yup.string().test(- "is-duration-unit",- "${path} is not a valid duration",- (value) => !!value && durationUnits.has(value),- ),+ unit: Yup.string()+ .test(+ "is-duration-unit",+ "${path} is not a valid duration",+ (value) => !!value && durationUnits.has(value),+ )+ .default(CacheDurationUnit.Hours),refresh_automatically: Yup.boolean().nullable().default(false),});@@ -47,7 +49,7 @@ export const enterpriseOnlyCachingStrategies: Record<string, StrategyData> = {},duration: {label: () => t`Duration`,- description: () => t`Keep the cache for a number of hours`,+ description: () => t`Keep the cache for a set duration`,validationSchema: getDurationStrategyValidationSchema,shortLabel: () => t`Duration`,},diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsxindex 16f2872dafc..e5cd5257469 100644--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx@@ -11,7 +11,6 @@ import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/Loadinimport { PLUGIN_CACHING } from "metabase/plugins";import { Box, Flex } from "metabase/ui";import type { CacheableModel } from "metabase-types/api";-import { CacheDurationUnit } from "metabase-types/api";import { rootId } from "../constants/simple";import { useCacheConfigs } from "../hooks/useCacheConfigs";@@ -78,16 +77,7 @@ export const StrategyEditorForDatabases: React.FC = () => {model_id: targetId ?? undefined,});- const savedStrategy = useMemo(() => {- const strategy = targetConfig?.strategy;- if (!strategy) {- return undefined;- }- if (strategy.type === "duration") {- return { ...strategy, unit: CacheDurationUnit.Hours };- }- return { ...strategy };- }, [targetConfig?.strategy]);+ const savedStrategy = targetConfig?.strategy;const {askBeforeDiscardingChanges,diff --git a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx b/frontend/src/metabase/admin/performance/components/StrategyForm.tsxindex fe3fc3bdb64..e1231b602a5 100644--- a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx+++ b/frontend/src/metabase/admin/performance/components/StrategyForm.tsx@@ -2,7 +2,7 @@ import cx from "classnames";import { useFormikContext } from "formik";import type { ReactNode } from "react";import { useCallback, useEffect, useMemo, useState } from "react";-import { c, t } from "ttag";+import { c, msgid, t } from "ttag";import _ from "underscore";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";@@ -12,6 +12,7 @@ import type { FormTextInputProps } from "metabase/forms";import {Form,FormProvider,+ FormSelect,FormSubmitButton,FormTextInput,useFormContext,@@ -198,12 +199,6 @@ const StrategyFormBody = ({}}, [dirty, wasDirty, setIsDirty, setStatus]);- useEffect(() => {- if (selectedStrategyType === "duration") {- setFieldValue("unit", CacheDurationUnit.Hours);- }- }, [selectedStrategyType, values, setFieldValue]);-const headingId = "strategy-form-heading";const handleSwitchToggle = useCallback(() => {@@ -619,33 +614,82 @@ const MultiplierFieldSubtitle = () => (</Text>);+const getDurationUnitOptions = (duration: number) => {+ const count = Number.isFinite(duration) ? duration : 2;+ return [+ {+ value: CacheDurationUnit.Seconds,+ label: c("Cache duration unit").ngettext(msgid`second`, `seconds`, count),+ },+ {+ value: CacheDurationUnit.Minutes,+ label: c("Cache duration unit").ngettext(msgid`minute`, `minutes`, count),+ },+ {+ value: CacheDurationUnit.Hours,+ label: c("Cache duration unit").ngettext(msgid`hour`, `hours`, count),+ },+ {+ value: CacheDurationUnit.Days,+ label: c("Cache duration unit").ngettext(msgid`day`, `days`, count),+ },+ ];+};+const DurationStrategyFormFields = ({targetModel,onSwitchToggle,}: {targetModel: CacheableModel;onSwitchToggle: () => void;-}) => (- <>- <StrategyFormField- title={t`Cache duration`}- subtitle={- <Text fz="md" lh="1.25rem" c="text-secondary">- {t`Cached results are refreshed after this period.`}- </Text>- }- unit={c("Unit suffix shown after the cache duration input").t`hours`}- >- <PositiveNumberInput strategyType="duration" name="duration" />- </StrategyFormField>- <input type="hidden" name="unit" />- {["question", "dashboard"].includes(targetModel) && (- <PLUGIN_CACHING.PreemptiveCachingSwitch- handleSwitchToggle={onSwitchToggle}- />- )}- </>-);+}) => {+ const { values, setFieldValue } = useFormikContext<CacheStrategy>();+ const unit = values.type === "duration" ? values.unit : undefined;+ const duration =+ values.type === "duration" ? Number(values.duration) : Number.NaN;++ useEffect(() => {+ if (!unit) {+ setFieldValue("unit", CacheDurationUnit.Hours);+ }+ }, [unit, setFieldValue]);++ return (+ <>+ <StrategyFormField+ title={t`Cache duration`}+ subtitle={+ <Text fz="md" lh="1.25rem" c="text-secondary">+ {t`Cached results are refreshed after this period.`}+ </Text>+ }+ >+ <Flex align="flex-start" gap="sm">+ <PositiveNumberInput+ strategyType="duration"+ name="duration"+ placeholder="0"+ />+ <FormSelect+ name="unit"+ data={getDurationUnitOptions(duration)}+ w="8rem"+ allowDeselect={false}+ aria-label={t`Cache duration unit`}+ data-testid="duration-unit-select"+ />+ </Flex>+ </StrategyFormField>+ {["question", "dashboard"].includes(targetModel) && (+ <PLUGIN_CACHING.PreemptiveCachingSwitch+ handleSwitchToggle={onSwitchToggle}+ />+ )}+ </>+ );+};++const NUMBER_INPUT_WIDTH = "4.5rem";export const PositiveNumberInput = ({strategyType,@@ -657,12 +701,19 @@ export const PositiveNumberInput = ({<FormTextInputtype="number"name={props.name ?? ""}+ // Store cleared fields as null: Formik turns "" into undefined before validation+ nullablemin={1}styles={{input: {// This is like `text-align: right` but it's RTL-friendlytextAlign: "end",- maxWidth: "4.5rem",+ maxWidth: NUMBER_INPUT_WIDTH,+ },+ error: {+ width: NUMBER_INPUT_WIDTH,+ overflow: "visible",+ whiteSpace: "nowrap",},}}autoComplete="off"diff --git a/frontend/src/metabase/admin/performance/components/test-utils.tsx b/frontend/src/metabase/admin/performance/components/test-utils.tsxindex d6288f46962..854468dd14a 100644--- a/frontend/src/metabase/admin/performance/components/test-utils.tsx+++ b/frontend/src/metabase/admin/performance/components/test-utils.tsx@@ -14,7 +14,7 @@ import { createMockEntitiesState } from "__support__/store";import { act, fireEvent, renderWithProviders, screen } from "__support__/ui";import { createMockState } from "metabase/redux/store/mocks";import { Route } from "metabase/router";-import type { TokenFeatures } from "metabase-types/api";+import type { CacheConfig, TokenFeatures } from "metabase-types/api";import { CacheDurationUnit } from "metabase-types/api";import {createMockCacheConfig,@@ -31,11 +31,29 @@ import { StrategyEditorForDatabases } from "./StrategyEditorForDatabases";export interface SetupOpts {enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][] | "*";tokenFeatures?: Partial<TokenFeatures>;+ cacheConfigs?: CacheConfig[];}+const getDefaultCacheConfigs = (): CacheConfig[] => [+ createMockCacheConfigWithMultiplierStrategy({ model_id: 1 }),+ createMockCacheConfigWithDoNotCacheStrategy({ model_id: 2 }),+ createMockCacheConfigWithDurationStrategy({ model_id: 3 }),+ createMockCacheConfig({+ model: "root",+ model_id: 0,+ strategy: {+ type: "duration",+ duration: 1,+ unit: CacheDurationUnit.Hours,+ refresh_automatically: false,+ },+ }),+];+export const setupStrategyEditorForDatabases = ({enterprisePlugins,tokenFeatures = {},+ cacheConfigs = getDefaultCacheConfigs(),}: SetupOpts = {}) => {const storeInitialState = createMockState({entities: createMockEntitiesState({}),@@ -55,21 +73,6 @@ export const setupStrategyEditorForDatabases = ({}setupTokenStatusEndpoint({ valid: !!enterprisePlugins });- const cacheConfigs = [- createMockCacheConfigWithMultiplierStrategy({ model_id: 1 }),- createMockCacheConfigWithDoNotCacheStrategy({ model_id: 2 }),- createMockCacheConfigWithDurationStrategy({ model_id: 3 }),- createMockCacheConfig({- model: "root",- model_id: 0,- strategy: {- type: "duration",- duration: 1,- unit: CacheDurationUnit.Hours,- refresh_automatically: false,- },- }),- ];setupPerformanceEndpoints(cacheConfigs);const databases = Array.from({ length: 4 }, (_, i) =>diff --git a/frontend/src/metabase/admin/performance/utils.tsx b/frontend/src/metabase/admin/performance/utils.tsxindex 248c666d074..27195802871 100644--- a/frontend/src/metabase/admin/performance/utils.tsx+++ b/frontend/src/metabase/admin/performance/utils.tsx@@ -11,7 +11,6 @@ import {type StrategyData,type StrategyLabel,defaultMinDurationMs,- strategies,} from "metabase/plugins";import { isNullOrUndefined } from "metabase/utils/types";import type {@@ -21,6 +20,7 @@ import type {CacheStrategyType,CacheableModel,} from "metabase-types/api";+import { CacheDurationUnit } from "metabase-types/api";import { isObject } from "metabase-types/guards";import { rootId } from "./constants/simple";@@ -81,12 +81,35 @@ export const getShortStrategyLabel = (.with({ type: "schedule" }, (strategy) =>getFrequencyFromCron(strategy.schedule),)- .with(- { type: "duration" },- (strategy) =>- c(- "{0} is a number. Indicates a number of hours (the length of a cache)",- ).t`${strategy.duration}h`,+ .with({ type: "duration" }, ({ duration, unit }) =>+ match(unit)+ .with(+ CacheDurationUnit.Minutes,+ () =>+ c(+ "{0} is a number. Abbreviation of {0} minutes (the length of a cache)",+ ).t`${duration}m`,+ )+ .with(+ CacheDurationUnit.Seconds,+ () =>+ c(+ "{0} is a number. Abbreviation of {0} seconds (the length of a cache)",+ ).t`${duration}s`,+ )+ .with(+ CacheDurationUnit.Days,+ () =>+ c(+ "{0} is a number. Abbreviation of {0} days (the length of a cache)",+ ).t`${duration}d`,+ )+ .otherwise(+ () =>+ c(+ "{0} is a number. Abbreviation of {0} hours (the length of a cache)",+ ).t`${duration}h`,+ ),).otherwise(() => null);if (subLabel) {@@ -124,7 +147,7 @@ export const strategyValidationSchema = Yup.object().test(path: "type",});}- const schema = getStrategyValidationSchema(strategies[type]);+ const schema = getStrategyValidationSchema(PLUGIN_CACHING.strategies[type]);try {schema.validateSync(value);return true;diff --git a/frontend/src/metabase/plugins/oss/caching.ts b/frontend/src/metabase/plugins/oss/caching.tsindex afef88d0c31..b3cacacaa34 100644--- a/frontend/src/metabase/plugins/oss/caching.ts+++ b/frontend/src/metabase/plugins/oss/caching.ts@@ -83,6 +83,7 @@ export const defaultMinDurationMs = 1000;/** Rather than a constant defined in the module scope, this is a function. This way, ttag.t runs *after* the locale is set */export const getPositiveIntegerSchema = () =>Yup.number()+ .typeError(t`Enter a positive number.`).positive(t`Enter a positive number.`).integer(t`Enter an integer.`);