diff --git a/superset-frontend/src/dashboard/actions/datasources.test.ts b/superset-frontend/src/dashboard/actions/datasources.test.ts index 15d1b72a3b2b..12aff9b33979 100644 --- a/superset-frontend/src/dashboard/actions/datasources.test.ts +++ b/superset-frontend/src/dashboard/actions/datasources.test.ts @@ -16,9 +16,143 @@ * specific language governing permissions and limitations * under the License. */ -import { SupersetClient } from '@superset-ui/core'; -import type { RootState } from 'src/dashboard/types'; -import { fetchDatasourceMetadata } from './datasources'; +import { JsonObject, SupersetClient } from '@superset-ui/core'; +import type { + Datasource, + DatasourcesState, + RootState, +} from 'src/dashboard/types'; +import { + DatasourcesAction, + fetchDatasourceMetadata, + setDatasource, +} from './datasources'; + +const KEY = '7__table'; + +type ClientResponse = Awaited>; + +// Minimal typed stand-ins so the tests avoid `any` while exercising the thunk. +const datasource = (json: JsonObject = { uid: KEY, main_dttm_col: 'ds' }) => + json as unknown as Datasource; + +const jsonResponse = (json: JsonObject): ClientResponse => + ({ json }) as unknown as ClientResponse; + +const buildGetState = + (datasources: DatasourcesState = {}) => + () => + ({ datasources }) as unknown as RootState; + +afterEach(() => { + jest.restoreAllMocks(); +}); + +test('fetchDatasourceMetadata uses the cached datasource without a network call', () => { + const getSpy = jest.spyOn(SupersetClient, 'get'); + const dispatch = jest.fn(); + const cached = datasource(); + + fetchDatasourceMetadata(KEY)(dispatch, buildGetState({ [KEY]: cached })); + + expect(getSpy).not.toHaveBeenCalled(); + expect(dispatch).toHaveBeenCalledWith(setDatasource(cached, KEY)); +}); + +test('fetchDatasourceMetadata fetches and caches an uncached datasource', async () => { + const json = { uid: KEY, main_dttm_col: 'ds' }; + const getSpy = jest + .spyOn(SupersetClient, 'get') + .mockResolvedValue(jsonResponse(json)); + const dispatch = jest.fn(); + + await fetchDatasourceMetadata(KEY)(dispatch, buildGetState()); + + expect(getSpy).toHaveBeenCalledTimes(1); + expect(dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: DatasourcesAction.SetDatasource, + key: KEY, + datasource: json, + }), + ); +}); + +test('fetchDatasourceMetadata shares one in-flight promise across concurrent callers', async () => { + let resolveGet: (value: ClientResponse) => void = () => {}; + const getSpy = jest.spyOn(SupersetClient, 'get').mockReturnValue( + new Promise(resolve => { + resolveGet = resolve; + }), + ); + const dispatch = jest.fn(); + const getState = buildGetState(); + + // Two filters using the same dataset mount and dispatch before the first + // request resolves and populates the cache. + const first = fetchDatasourceMetadata(KEY)(dispatch, getState); + const second = fetchDatasourceMetadata(KEY)(dispatch, getState); + + // Only one network request fires, and both callers receive the same promise + // so each observes the same completion/rejection. + expect(getSpy).toHaveBeenCalledTimes(1); + expect(second).toBe(first); + + resolveGet(jsonResponse({ uid: KEY, main_dttm_col: 'ds' })); + await Promise.all([first, second]); + + expect(dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: DatasourcesAction.SetDatasource, + key: KEY, + }), + ); +}); + +test('fetchDatasourceMetadata propagates a rejection to all concurrent callers', async () => { + jest.spyOn(SupersetClient, 'get').mockRejectedValue(new Error('boom')); + const dispatch = jest.fn(); + const getState = buildGetState(); + + const first = fetchDatasourceMetadata(KEY)(dispatch, getState); + const second = fetchDatasourceMetadata(KEY)(dispatch, getState); + + expect(second).toBe(first); + await expect(first).rejects.toThrow('boom'); + await expect(second).rejects.toThrow('boom'); +}); + +test('fetchDatasourceMetadata clears the in-flight key after a failed request so it can retry', async () => { + const getSpy = jest + .spyOn(SupersetClient, 'get') + .mockRejectedValueOnce(new Error('boom')) + .mockResolvedValueOnce(jsonResponse({ uid: KEY })); + const dispatch = jest.fn(); + const getState = buildGetState(); + + await expect( + fetchDatasourceMetadata(KEY)(dispatch, getState), + ).rejects.toThrow('boom'); + + // The failed key is no longer in flight, so a subsequent dispatch retries. + await fetchDatasourceMetadata(KEY)(dispatch, getState); + + expect(getSpy).toHaveBeenCalledTimes(2); +}); + +test('fetchDatasourceMetadata fetches when the datasources slice is missing', async () => { + const getSpy = jest + .spyOn(SupersetClient, 'get') + .mockResolvedValue(jsonResponse({ uid: KEY })); + const dispatch = jest.fn(); + + await fetchDatasourceMetadata(KEY)( + dispatch, + () => ({}) as unknown as RootState, + ); + + expect(getSpy).toHaveBeenCalledTimes(1); +}); const sourceKey = '2__semantic_view'; diff --git a/superset-frontend/src/dashboard/actions/datasources.ts b/superset-frontend/src/dashboard/actions/datasources.ts index 92c537831d34..385d00062e2d 100644 --- a/superset-frontend/src/dashboard/actions/datasources.ts +++ b/superset-frontend/src/dashboard/actions/datasources.ts @@ -58,10 +58,12 @@ export function setDatasource(datasource: Datasource, key: string) { }; } +const inFlightDatasourceRequests = new Map>(); + export function fetchDatasourceMetadata(key: string, dashboardId?: number) { return (dispatch: Dispatch, getState: () => RootState) => { const { datasources } = getState(); - const datasource = datasources[key]; + const datasource = datasources?.[key]; const requestId = dashboardId === undefined ? undefined : nanoid(); if (dashboardId !== undefined) { @@ -74,7 +76,19 @@ export function fetchDatasourceMetadata(key: string, dashboardId?: number) { return dispatch(setDatasource(datasource, key)); } - return SupersetClient.get({ + // Plain metadata loads share a single in-flight promise per key across + // concurrent callers, so request deduplication preserves the thunk + // contract: every awaiter (e.g. a Promise.all over multiple dispatches) + // observes the same completion or rejection. Semantic refreshes + // (dashboardId set) track their own request ids and are not shared. + if (dashboardId === undefined) { + const inFlight = inFlightDatasourceRequests.get(key); + if (inFlight) { + return inFlight; + } + } + + const request = SupersetClient.get({ endpoint: `/fetch_datasource_metadata?datasourceKey=${key}`, }) .then(({ json }) => { @@ -99,5 +113,15 @@ export function fetchDatasourceMetadata(key: string, dashboardId?: number) { logging.error('Error fetching semantic datasource metadata:', error); return undefined; }); + + if (dashboardId !== undefined) { + return request; + } + + const sharedRequest = request.finally(() => { + inFlightDatasourceRequests.delete(key); + }); + inFlightDatasourceRequests.set(key, sharedRequest); + return sharedRequest; }; } diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.granularitySqla.test.ts b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.granularitySqla.test.ts new file mode 100644 index 000000000000..61961a1d7344 --- /dev/null +++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.granularitySqla.test.ts @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { resolveGranularitySqla } from './FilterValue'; + +test('resolveGranularitySqla prefers the filter own granularity_sqla', () => { + expect(resolveGranularitySqla('order_date', true, 'main_dttm')).toEqual( + 'order_date', + ); + expect(resolveGranularitySqla('order_date', false, 'main_dttm')).toEqual( + 'order_date', + ); +}); + +test('resolveGranularitySqla falls back to main_dttm_col when a time_range parent cascades', () => { + expect(resolveGranularitySqla(undefined, true, 'main_dttm')).toEqual( + 'main_dttm', + ); +}); + +test('resolveGranularitySqla returns undefined without a time_range dependency', () => { + expect(resolveGranularitySqla(undefined, false, 'main_dttm')).toBeUndefined(); +}); + +test('resolveGranularitySqla returns undefined when the datasource has no main_dttm_col', () => { + expect(resolveGranularitySqla(undefined, true, undefined)).toBeUndefined(); +}); diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.test.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.test.tsx index 2b7125594074..fd12a48fbb28 100644 --- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.test.tsx +++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.test.tsx @@ -28,6 +28,7 @@ import thunk from 'redux-thunk'; import { NativeFilterType, DatasourceType, + SupersetClient, buildQueryObject, } from '@superset-ui/core'; import type { DataMask, Filter } from '@superset-ui/core'; @@ -227,6 +228,73 @@ test('forwards the dashboard async override to the request', async () => { ); }); +test('a time_range parent cascade falls back to the cached main_dttm_col', async () => { + const getSpy = jest.spyOn(SupersetClient, 'get'); + mockUseTransitiveParentIds.mockReturnValue([]); + mockUseFilterDependencies.mockReturnValue({ time_range: 'Last week' }); + mockRequestChartData.mockResolvedValue([{ data: [{ country: 'US' }] }]); + + renderFilterValue( + {}, + { datasources: { '1__table': { uid: '1__table', main_dttm_col: 'ds' } } }, + ); + + await waitFor(() => { + expect(mockRequestChartData).toHaveBeenCalled(); + }); + expect(mockRequestChartData).toHaveBeenLastCalledWith( + expect.objectContaining({ + formData: expect.objectContaining({ + granularity_sqla: 'ds', + extra_form_data: { time_range: 'Last week' }, + }), + }), + ); + // The datasource is already cached, so no metadata request is made. + expect(getSpy).not.toHaveBeenCalled(); + getSpy.mockRestore(); + mockUseFilterDependencies.mockReturnValue({}); +}); + +test('a time_range parent cascade fetches metadata for an uncached filter dataset', async () => { + const getSpy = jest.spyOn(SupersetClient, 'get').mockResolvedValue({ + json: { uid: '1__table', main_dttm_col: 'ds' }, + } as unknown as Awaited>); + mockUseTransitiveParentIds.mockReturnValue([]); + mockUseFilterDependencies.mockReturnValue({ time_range: 'Last week' }); + mockRequestChartData.mockResolvedValue([{ data: [{ country: 'US' }] }]); + + renderFilterValue({}, { datasources: {} }); + + await waitFor(() => { + expect(getSpy).toHaveBeenCalledWith({ + endpoint: '/fetch_datasource_metadata?datasourceKey=1__table', + }); + }); + getSpy.mockRestore(); + mockUseFilterDependencies.mockReturnValue({}); +}); + +test('filters without a time_range parent do not fetch datasource metadata', async () => { + const getSpy = jest.spyOn(SupersetClient, 'get'); + mockUseTransitiveParentIds.mockReturnValue([]); + mockUseFilterDependencies.mockReturnValue({}); + mockRequestChartData.mockResolvedValue([{ data: [{ country: 'US' }] }]); + + renderFilterValue({}, { datasources: {} }); + + await waitFor(() => { + expect(mockRequestChartData).toHaveBeenCalled(); + }); + expect(getSpy).not.toHaveBeenCalled(); + expect(mockRequestChartData).toHaveBeenLastCalledWith( + expect.objectContaining({ + formData: expect.not.objectContaining({ granularity_sqla: 'ds' }), + }), + ); + getSpy.mockRestore(); +}); + const FRIENDLY_MESSAGE = 'Sorry, something went wrong. Try again later.'; const NETWORK_MESSAGE = 'Network error while attempting to fetch resource'; diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.tsx index 101bf7c3084c..5ef95b48bd42 100644 --- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.tsx +++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.tsx @@ -57,6 +57,7 @@ import { onFiltersRefreshSuccess, setDirectPathToChild, } from 'src/dashboard/actions/dashboardState'; +import { fetchDatasourceMetadata } from 'src/dashboard/actions/datasources'; import { setHoveredChartCustomization, unsetHoveredChartCustomization, @@ -101,6 +102,20 @@ const ReselectActionButton = styled(Button)` const queriesDataPlaceholder = [{ data: [{}] }]; +/** + * Resolve the granularity_sqla a filter should send. A filter's own + * granularity_sqla always wins. Otherwise, when a Date Range parent filter is + * cascading a time_range down, fall back to the datasource's main_dttm_col so + * the temporal WHERE clause can be applied. + */ +export const resolveGranularitySqla = ( + granularitySqla: string | undefined, + hasTimeRangeDependency: boolean, + datasourceMainDttmCol: string | undefined, +): string | undefined => + granularitySqla || + (hasTimeRangeDependency ? datasourceMainDttmCol : undefined); + const useShouldFilterRefresh = () => { const isDashboardRefreshing = useSelector( state => state.dashboardState.isRefreshing, @@ -203,6 +218,51 @@ const FilterValue: FC = ({ const [isRefreshing, setIsRefreshing] = useState(false); const dispatch = useDispatch(); + // When a Date Range parent filter is active and the filter has no + // granularity_sqla of its own, the request needs one to apply the temporal + // WHERE clause. Fall back to the dataset's main_dttm_col from the Redux + // datasource cache. + // + // The dashboard datasets API (/api/v1/dashboard/:id/datasets) only returns + // datasets used by chart slices, so native-filter-only datasets are never + // in state.datasources. Fetch their metadata when the fallback is needed + // and it is not already cached. + const hasTimeRangeDependency = Boolean(dependencies.time_range); + const tableDatasourceKey = + datasetId != null && + (datasourceType === undefined || datasourceType === DatasourceType.Table) + ? `${datasetId}__${DatasourceType.Table}` + : undefined; + const datasourceMainDttmCol = useSelector( + state => + tableDatasourceKey + ? state.datasources?.[tableDatasourceKey]?.main_dttm_col + : undefined, + ); + const isDatasourceCached = useSelector(state => + tableDatasourceKey ? !!state.datasources?.[tableDatasourceKey] : false, + ); + const needsDatasourceMetadata = + !!tableDatasourceKey && + !granularitySqla && + hasTimeRangeDependency && + !isDatasourceCached; + + useEffect(() => { + if (!needsDatasourceMetadata || !tableDatasourceKey) { + return; + } + // Best-effort prime of the datasource cache for the granularity_sqla + // fallback. A failure here is non-fatal (the filter still works, just + // without the time-range cascade fallback), so catch both synchronous + // throws and rejections instead of letting them escape the effect. + Promise.resolve() + .then(() => dispatch(fetchDatasourceMetadata(tableDatasourceKey))) + .catch(error => + logging.warn('Failed to fetch filter datasource metadata', error), + ); + }, [needsDatasourceMetadata, tableDatasourceKey, dispatch]); + const { outlinedFilterId, lastUpdated } = useFilterOutlined(); const handleFilterLoadFinish = useCallback(() => { @@ -236,7 +296,11 @@ const FilterValue: FC = ({ groupby, adhoc_filters: adhocFilters, time_range: timeRange, - granularity_sqla: granularitySqla, + granularity_sqla: resolveGranularitySqla( + granularitySqla, + hasTimeRangeDependency, + datasourceMainDttmCol, + ), dashboardId, }); const filterOwnState = filter.dataMask?.ownState || {}; @@ -351,6 +415,7 @@ const FilterValue: FC = ({ dataMaskSelected, setHasDepsFilterValue, transitiveParentIds, + datasourceMainDttmCol, parentDefaultToFirstItem, asyncModeOverride, ]);