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
Use AbortError to signal request cancellation (#75001)
Romeo Van Snick8562bc7d9f49
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.tsindex c82345c5f8a..e1ac68c7f7c 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts@@ -16,11 +16,11 @@ import type {SdkQuestionState,SqlParameterValues,} from "embedding-sdk-bundle/types/question";+import { isAbortError } from "metabase/api/legacy-client";import { isStaticEmbeddingEntityLoadingError } from "metabase/utils/errors/is-static-embedding-entity-loading-error";import type Question from "metabase-lib/v1/Question";import type { ParameterValuesMap } from "metabase-types/api";import type { EntityToken } from "metabase-types/api/entity";-import { isObject } from "metabase-types/guards";type LoadQuestionResult = Promise<SdkQuestionState & { originalQuestion?: Question }@@ -153,7 +153,7 @@ export function useLoadQuestion({// controlled `sqlParameters` push cancels the in-flight load query via the// shared `controllerRef`). React simulates unmounting on strict mode,// therefore "Question not found" will be shown without this.- if (isCancelledRequestError(err)) {+ if (isAbortError(err)) {setIsQuestionLoading(false);return {};}@@ -352,6 +352,3 @@ export const getParameterDependencyKey = (.sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, value]) => `${key}=${value}`).join(":");--const isCancelledRequestError = (error: unknown) =>- isObject(error) && "isCancelled" in error && error.isCancelled === true;diff --git a/frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.unit.spec.tsxindex 3dd3af0f9ce..ed354b38885 100644--- a/frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.unit.spec.tsx@@ -188,7 +188,6 @@ describe("BaseSMTPConnectionForm", () => {"email-smtp-port": "Wrong host or port",},},- isCancelled: false,}),});diff --git a/frontend/src/metabase/api/legacy-client.ts b/frontend/src/metabase/api/legacy-client.tsindex 09ce17ce538..a1f9d172bce 100644--- a/frontend/src/metabase/api/legacy-client.ts+++ b/frontend/src/metabase/api/legacy-client.ts@@ -91,6 +91,27 @@ export class NetworkError extends Error {}}+/**+ * The standard web-platform shape for a cancelled request: an `Error` whose+ * `name` is `"AbortError"`. `fetch()` rejects with a `DOMException` of this+ * shape on abort, and we throw the same from the XHR path so both transports+ * line up. Use `isAbortError` to narrow.+ */+export type AbortError = Error & { name: "AbortError" };++/**+ * Type guard for the standard `AbortError` that `fetch()` (and+ * `XMLHttpRequest.abort()`-driven rejections) surface when the request is+ * cancelled. Replaces the legacy `error.isCancelled` flag.+ */+export function isAbortError(error: unknown): error is AbortError {+ return (+ typeof error === "object" &&+ error !== null &&+ (error as { name?: unknown }).name === "AbortError"+ );+}+type ResponseErrorInfo = {body: unknown;status: number;@@ -291,7 +312,7 @@ export class LegacyApi extends EventEmitter<EventMap> {) {await delay(retryDelays.pop() ?? 0, options.signal);if (options.signal?.aborted) {- throw { isCancelled: true };+ throw new DOMException("Aborted", "AbortError");}} else {throw e;@@ -381,6 +402,15 @@ export class LegacyApi extends EventEmitter<EventMap> {status = responseBody._status as number;}+ if (isCancelled) {+ // Surface aborts as the standard `DOMException` AbortError so+ // callers can `isAbortError`-check the same shape both transports+ // (and `fetch` itself) emit. Skip the responseError/status events+ // since the request was cancelled — there's no real response.+ reject(new DOMException("Aborted", "AbortError"));+ return;+ }+if (status >= 200 && status <= 299) {if (options.transformResponse) {responseBody = options.transformResponse({@@ -399,7 +429,6 @@ export class LegacyApi extends EventEmitter<EventMap> {reject({status: status,data: responseBody,- isCancelled: isCancelled,});}if (!options.noEvent) {@@ -510,8 +539,11 @@ export class LegacyApi extends EventEmitter<EventMap> {});}).catch((error: unknown) => {+ // When the request is aborted, `fetch` rejects with the standard+ // `DOMException` AbortError. Let it propagate untouched so callers+ // can `isAbortError`-check the standard web shape.if (options.signal?.aborted) {- throw { isCancelled: true };+ throw error;}// A raw `fetch` rejection (e.g. the server dropped the connection)// surfaces as a plain Error here, indistinguishable from JSdiff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.tsindex 5f78f563d49..bfa577bdfeb 100644--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts@@ -5,6 +5,7 @@ import { t } from "ttag";import _ from "underscore";import { automagicDashboardsApi, cardApi, dashboardApi } from "metabase/api";+import { isAbortError } from "metabase/api/legacy-client";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { applyParameters } from "metabase/common/utils/card";import { showAutoApplyFiltersToast } from "metabase/dashboard/actions/parameters";@@ -858,7 +859,7 @@ export const fetchDashboard = createAsyncThunk(preserveParameters,};} catch (error) {- if (!(error as { isCancelled: boolean }).isCancelled) {+ if (!isAbortError(error)) {console.error(error);}return rejectWithValue(error);diff --git a/frontend/src/metabase/dashboard/context/context.tsx b/frontend/src/metabase/dashboard/context/context.tsxindex 93165cf206d..df3e85b8bcf 100644--- a/frontend/src/metabase/dashboard/context/context.tsx+++ b/frontend/src/metabase/dashboard/context/context.tsx@@ -11,8 +11,9 @@ import {useState,} from "react";import { usePrevious, useUnmount } from "react-use";-import { isEqual, isObject, noop } from "underscore";+import { isEqual, noop } from "underscore";+import { isAbortError } from "metabase/api/legacy-client";import { useEmbeddingEntityContext } from "metabase/embedding/context";import { getTabHiddenParameterSlugs } from "metabase/embedding/lib/tab-parameters";import type {@@ -484,7 +485,5 @@ export function useDashboardContext() {export function isFailedFetchDashboardResult(result: FetchDashboardResult,): result is FailedFetchDashboardResult {- return (- isObject(result.payload) && !result.payload.isCancelled && "error" in result- );+ return !isAbortError(result.payload) && "error" in result;}diff --git a/frontend/src/metabase/dashboard/types/fetch-dashboard-result.ts b/frontend/src/metabase/dashboard/types/fetch-dashboard-result.tsindex bac15dac1a3..23c739c862d 100644--- a/frontend/src/metabase/dashboard/types/fetch-dashboard-result.ts+++ b/frontend/src/metabase/dashboard/types/fetch-dashboard-result.ts@@ -1,11 +1,15 @@+import type { AbortError } from "metabase/api/legacy-client";import type { Dashboard } from "metabase-types/api";type SuccessfulFetchDashboardResult = {payload: { dashboard: Dashboard };};+// A cancelled fetch surfaces as an `AbortError` payload. It also satisfies+// `FailedFetchDashboardResult` shape-wise, so consumers use+// `isAbortError(result.payload)` to distinguish.type CancelledFetchDashboardResult = {- payload: { isCancelled: true };+ payload: AbortError;};export type FailedFetchDashboardResult = { error: unknown; payload: unknown };diff --git a/frontend/src/metabase/query_builder/actions/querying.ts b/frontend/src/metabase/query_builder/actions/querying.tsindex 71eabc4dc38..ee459a37d44 100644--- a/frontend/src/metabase/query_builder/actions/querying.ts+++ b/frontend/src/metabase/query_builder/actions/querying.ts@@ -1,6 +1,7 @@import { createAction } from "redux-actions";import { t } from "ttag";+import { isAbortError } from "metabase/api/legacy-client";import { syncVizSettingsWithSeries } from "metabase/querying/viz-settings/utils/sync-viz-settings";import { createThunkAction } from "metabase/redux";import {@@ -249,7 +250,7 @@ export const queryErrored = createThunkAction(QUERY_ERRORED_TYPE,(startTime, error) => {return async (dispatch) => {- if (error && error.isCancelled) {+ if (isAbortError(error)) {return null;} else {dispatch(loadErrorUIControls());diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.jsindex b77b821e496..497a335b654 100644--- a/frontend/src/metabase/services.js+++ b/frontend/src/metabase/services.js@@ -101,9 +101,9 @@ export function maybeUsePivotEndpoint(api, card, metadata) {}// Dispatches the RTK `datasetApi` ad-hoc query endpoint (pivot or non-pivot)-// and wires the `signal` to RTK Query's `.abort()`. Translates aborts-// into the `{ isCancelled: true }` shape that the legacy fetch helper threw,-// so existing error-handling code (e.g. queryErrored) keeps working.+// and wires the `signal` to RTK Query's `.abort()`. On abort it surfaces the+// standard `DOMException` AbortError so existing error-handling code keeps+// working via `isAbortError(error)`.let adhocDatasetQueryCounter = 0;export async function runAdhocDatasetQuery(dispatch,@@ -155,7 +155,7 @@ export async function runAdhocDatasetQuery(.unwrap().catch((error) => {if (isCancelled) {- throw { isCancelled: true };+ throw signal?.reason ?? new DOMException("Aborted", "AbortError");}throw error;})diff --git a/frontend/src/metabase/services.unit.spec.ts b/frontend/src/metabase/services.unit.spec.tsindex 6320efd9d3f..e41c9369ce4 100644--- a/frontend/src/metabase/services.unit.spec.ts+++ b/frontend/src/metabase/services.unit.spec.ts@@ -278,11 +278,11 @@ describe("metabase/services > runQuestionQuery", () => {});});- it("rejects with { isCancelled: true } when cancelDeferred resolves (ad-hoc question)", async () => {- // Guards the RTK Query cancellation path: resolving `cancelDeferred`- // must abort the underlying `/api/dataset` request and reject with- // the legacy `{ isCancelled: true }` shape that `queryErrored` and- // other callers rely on.+ it("rejects with AbortError when the signal aborts (ad-hoc question)", async () => {+ // Guards the RTK Query cancellation path: aborting the signal must+ // abort the underlying `/api/dataset` request and reject with the+ // standard `DOMException` AbortError that `queryErrored` and other+ // callers identify via `isAbortError`.const question = createMockAdHocQuestion();fetchMock.post(getQueryEndpointPath(question),@@ -297,7 +297,7 @@ describe("metabase/services > runQuestionQuery", () => {controller.abort();- await expect(runPromise).rejects.toEqual({ isCancelled: true });+ await expect(runPromise).rejects.toMatchObject({ name: "AbortError" });});it("normalizes plain-text 4xx error bodies into a structured error result (EMB-1659)", async () => {