Skip to content

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

Fetch the registered pages once the tab is idle (#82628)

Romeo Van Snick7ba547bdf728
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx
index 855b75a5392..7423e2c7ce7 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx
@@ -2,16 +2,23 @@ import { PLUGIN_AI_CONTROLS } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
import { getAiControlsNavItems, getAiControlsUpsellNavItems } from "./nav";
-import { getAiControlsRoutes, getAiControlsUpsellRoutes } from "./routes";
+import {
+ getAiControlsRoutes,
+ getAiControlsUpsellRoutes,
+ registerAiControlsPagePrefetch,
+ registerAiControlsUpsellPagePrefetch,
+} from "./routes";
export function initializePlugin() {
if (hasPremiumFeature("ai_controls")) {
PLUGIN_AI_CONTROLS.isEnabled = true;
PLUGIN_AI_CONTROLS.getAiControlsRoutes = getAiControlsRoutes;
PLUGIN_AI_CONTROLS.getAiControlsNavItems = getAiControlsNavItems;
+ registerAiControlsPagePrefetch();
} else {
PLUGIN_AI_CONTROLS.isEnabled = false;
PLUGIN_AI_CONTROLS.getAiControlsRoutes = getAiControlsUpsellRoutes;
PLUGIN_AI_CONTROLS.getAiControlsNavItems = getAiControlsUpsellNavItems;
+ registerAiControlsUpsellPagePrefetch();
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx
index 40e22a8bd53..35e0c2268b3 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx
@@ -97,28 +97,44 @@ const adminAiPath = (path: string) => `${Urls.adminAiSettings()}/${path}`;
* Hovering an AI settings tab starts its fetch, so the chunk is usually in hand
* by the time the click lands.
*
- * The pages that differ only by license come from one module, so a registration
- * covers both. The three system prompt tabs are one module too, which is why the
- * prefix they share is registered once.
+ * Called from the licensed branch of `initializePlugin`, so only the pages this
+ * instance mounts are registered. A registration is also what the background pass
+ * reads, and fetching a page nobody can reach would spend a download on nothing.
+ *
+ * The three system prompt tabs are one module, which is why the prefix they share
+ * is registered once.
*/
-registerPagePrefetch(
- adminAiPath(PATHS.featureAccess),
- metabotFeatureAccessPage,
-);
-registerPagePrefetch(
- adminAiPath(PATHS.featureAccess),
- metabotFeatureAccessUpsellPage,
-);
-registerPagePrefetch(adminAiPath(PATHS.usageLimits), metabotUsageLimitsPage);
-registerPagePrefetch(
- adminAiPath(PATHS.customization),
- metabotCustomizationPage,
-);
-registerPagePrefetch(
- adminAiPath(PATHS.customization),
- metabotCustomizationUpsellPage,
-);
-registerPagePrefetch(adminAiPath(PATHS.systemPrompts), metabotChatPromptPage);
+export function registerAiControlsPagePrefetch(): void {
+ registerPagePrefetch(
+ adminAiPath(PATHS.featureAccess),
+ metabotFeatureAccessPage,
+ );
+ registerPagePrefetch(adminAiPath(PATHS.usageLimits), metabotUsageLimitsPage);
+ registerPagePrefetch(
+ adminAiPath(PATHS.customization),
+ metabotCustomizationPage,
+ );
+ registerPagePrefetch(adminAiPath(PATHS.systemPrompts), metabotChatPromptPage);
+}
+
+/**
+ * The tabs an instance without the license mounts. There is no usage limits tab
+ * among them, so nothing registers that path here.
+ */
+export function registerAiControlsUpsellPagePrefetch(): void {
+ registerPagePrefetch(
+ adminAiPath(PATHS.featureAccess),
+ metabotFeatureAccessUpsellPage,
+ );
+ registerPagePrefetch(
+ adminAiPath(PATHS.customization),
+ metabotCustomizationUpsellPage,
+ );
+ registerPagePrefetch(
+ adminAiPath(PATHS.systemPrompts),
+ metabotSystemPromptsUpsellPage,
+ );
+}
export function getAiControlsRoutes() {
return (
diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/index.ts b/enterprise/frontend/src/metabase-enterprise/application_permissions/index.ts
index 6d361c4f28a..fb78d3b5516 100644
--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/application_permissions/index.ts
@@ -9,7 +9,9 @@ import {
import { hasPremiumFeature } from "metabase-enterprise/settings";
import applicationPermissionsReducer from "./reducer";
-import getRoutes from "./routes";
+import getRoutes, {
+ registerApplicationPermissionsPagePrefetch,
+} from "./routes";
import { canAccessSettings, canManageSubscriptions } from "./selectors";
import {
monitoringPermissionAllowedPathGetter,
@@ -37,5 +39,7 @@ export function initializePlugin() {
canManageSubscriptions;
PLUGIN_REDUCERS.applicationPermissionsPlugin =
applicationPermissionsReducer;
+
+ registerApplicationPermissionsPagePrefetch();
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/routes.tsx b/enterprise/frontend/src/metabase-enterprise/application_permissions/routes.tsx
index f24caffcb50..196d69342b6 100644
--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/application_permissions/routes.tsx
@@ -9,7 +9,17 @@ const applicationPermissionsPage = () =>
Component: module.default,
}));
-registerPagePrefetch(APPLICATION_PERMISSIONS_PATH, applicationPermissionsPage);
+/**
+ * Called from the licensed branch of `initializePlugin`, so only a page this
+ * instance mounts is registered. The background pass reads the registrations too,
+ * and fetching a page nobody can reach would spend a download on nothing.
+ */
+export function registerApplicationPermissionsPagePrefetch(): void {
+ registerPagePrefetch(
+ APPLICATION_PERMISSIONS_PATH,
+ applicationPermissionsPage,
+ );
+}
const getRoutes = () => (
<Route path="application" lazy={applicationPermissionsPage} />
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/index.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/index.tsx
index 2f9f459a02d..b92b0c3c179 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/index.tsx
@@ -13,6 +13,8 @@ import { handleMetabotSlashCommand } from "metabase-enterprise/monitor/ai-auditi
import {
getAiAuditingRoutes,
getAiAuditingUpsellRoutes,
+ registerAiAuditingPagePrefetch,
+ registerAiAuditingUpsellPagePrefetch,
} from "metabase-enterprise/monitor/ai-auditing/routes";
import { hasPremiumFeature } from "metabase-enterprise/settings";
import type { User } from "metabase-types/api";
@@ -52,9 +54,13 @@ export function initializePlugin() {
PLUGIN_AUDIT.AnalyticsExportStatus = AnalyticsExportStatus;
PLUGIN_AUDIT.CollectionExportAnalytics = CollectionExportAnalytics;
PLUGIN_AUDIT.isAiAuditingEnabled = true;
- PLUGIN_AUDIT.getAiAuditingRoutes = hasPremiumFeature("ai_controls")
- ? getAiAuditingRoutes
- : getAiAuditingUpsellRoutes;
+ if (hasPremiumFeature("ai_controls")) {
+ PLUGIN_AUDIT.getAiAuditingRoutes = getAiAuditingRoutes;
+ registerAiAuditingPagePrefetch();
+ } else {
+ PLUGIN_AUDIT.getAiAuditingRoutes = getAiAuditingUpsellRoutes;
+ registerAiAuditingUpsellPagePrefetch();
+ }
PLUGIN_METABOT_SLASH_COMMANDS.handleSlashCommand =
handleMetabotSlashCommand;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx
index b46c5d0b6c9..d028fd9dcee 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx
@@ -4,7 +4,7 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { ManageDataAppUsersPage } from "./admin/ManageDataAppUsersPage";
import { ManageDataAppsPage } from "./admin/ManageDataAppsPage";
import { DataAppsNavbarSection } from "./navbar/DataAppsNavbarSection";
-import { getRoutes } from "./routes";
+import { getRoutes, registerDataAppsPagePrefetch } from "./routes";
/**
* Initialize data-apps plugin features.
@@ -20,5 +20,6 @@ export function initializePlugin() {
PLUGIN_DATA_APPS.ManageDataAppsPage = ManageDataAppsPage;
PLUGIN_DATA_APPS.ManageDataAppUsersPage = ManageDataAppUsersPage;
PLUGIN_DATA_APPS.MainNavbarSection = DataAppsNavbarSection;
+ registerDataAppsPagePrefetch();
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx
index 220e7f787c3..83a3d877ad6 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx
@@ -21,8 +21,15 @@ const dataAppView = () =>
Component: DataAppView,
}));
-registerPagePrefetch(`${Urls.DATA_APP_ROOT_URL}/`, dataAppLayout);
-registerPagePrefetch(`${Urls.DATA_APP_ROOT_URL}/`, dataAppView);
+/**
+ * Called from the licensed branch of `initializePlugin`, so only the pages this
+ * instance mounts are registered. The background pass reads the registrations too,
+ * and fetching a page nobody can reach would spend a download on nothing.
+ */
+export function registerDataAppsPagePrefetch(): void {
+ registerPagePrefetch(`${Urls.DATA_APP_ROOT_URL}/`, dataAppLayout);
+ registerPagePrefetch(`${Urls.DATA_APP_ROOT_URL}/`, dataAppView);
+}
/**
* Data-app host routes. Open to any signed-in user.
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.tsx
index e2acfd9068c..009c4066b9b 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.tsx
@@ -82,16 +82,35 @@ const cliCallsPage = () =>
* Hovering a Monitor sidebar link starts the fetch, so the chunk is usually in
* hand by the time the click lands. These pages share a chunk, so the first
* hover covers the whole section.
+ *
+ * Called from the branch of `initializePlugin` that mounts these routes, so only
+ * the pages this instance can reach are registered. The background pass reads the
+ * registrations too, and fetching a page nobody can reach would spend a download
+ * on nothing.
*/
-registerPagePrefetch(Urls.monitorAiAuditingUsage(), conversationStatsPage);
-registerPagePrefetch(Urls.monitorAiAuditingUsage(), metabotAnalyticsUpsellPage);
-registerPagePrefetch(Urls.monitorAiAuditingConversations(), conversationsPage);
-registerPagePrefetch(
- `${Urls.monitorAiAuditingConversations()}/`,
- conversationDetailPage,
-);
-registerPagePrefetch(Urls.monitorAiAuditingMcp(), mcpAnalyticsSectionLayout);
-registerPagePrefetch(Urls.monitorAiAuditingCli(), cliAnalyticsSectionLayout);
+export function registerAiAuditingPagePrefetch(): void {
+ registerPagePrefetch(Urls.monitorAiAuditingUsage(), conversationStatsPage);
+ registerPagePrefetch(
+ Urls.monitorAiAuditingConversations(),
+ conversationsPage,
+ );
+ registerPagePrefetch(
+ `${Urls.monitorAiAuditingConversations()}/`,
+ conversationDetailPage,
+ );
+ registerPagePrefetch(Urls.monitorAiAuditingMcp(), mcpAnalyticsSectionLayout);
+ registerPagePrefetch(Urls.monitorAiAuditingCli(), cliAnalyticsSectionLayout);
+}
+
+/** The section as an instance without the license mounts it: usage upsells. */
+export function registerAiAuditingUpsellPagePrefetch(): void {
+ registerPagePrefetch(
+ Urls.monitorAiAuditingUsage(),
+ metabotAnalyticsUpsellPage,
+ );
+ registerPagePrefetch(Urls.monitorAiAuditingMcp(), mcpAnalyticsSectionLayout);
+ registerPagePrefetch(Urls.monitorAiAuditingCli(), cliAnalyticsSectionLayout);
+}
function getMcpAnalyticsRoutes() {
return (
diff --git a/enterprise/frontend/src/metabase-enterprise/replacement/index.ts b/enterprise/frontend/src/metabase-enterprise/replacement/index.ts
index 4d0e08a3f19..4e075fe3f91 100644
--- a/enterprise/frontend/src/metabase-enterprise/replacement/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/replacement/index.ts
@@ -6,7 +6,10 @@ import { SourceReplacementButton } from "./components/SourceReplacementButton";
import { SourceReplacementModal } from "./components/SourceReplacementModal";
import { SourceReplacementStatus } from "./components/SourceReplacementStatus";
import { TransformToolsMenu } from "./components/TransformToolsMenu";
-import { getTransformToolsRoutes } from "./routes";
+import {
+ getTransformToolsRoutes,
+ registerReplacementPagePrefetch,
+} from "./routes";
export function initializePlugin() {
if (hasPremiumFeature("dependencies")) {
@@ -17,5 +20,6 @@ export function initializePlugin() {
PLUGIN_REPLACEMENT.SourceReplacementModal = SourceReplacementModal;
PLUGIN_REPLACEMENT.SourceReplacementStatus = SourceReplacementStatus;
PLUGIN_REPLACEMENT.TransformToolsMenu = TransformToolsMenu;
+ registerReplacementPagePrefetch();
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/replacement/routes.tsx b/enterprise/frontend/src/metabase-enterprise/replacement/routes.tsx
index 950d44fbe3c..5f7feb3794a 100644
--- a/enterprise/frontend/src/metabase-enterprise/replacement/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/replacement/routes.tsx
@@ -8,7 +8,14 @@ const migrateModelsPage = () =>
Component: MigrateModelsPage,
}));
-registerPagePrefetch(Urls.transformMigrateModels(), migrateModelsPage);
+/**
+ * Called from the licensed branch of `initializePlugin`, so only a page this
+ * instance mounts is registered. The background pass reads the registrations too,
+ * and fetching a page nobody can reach would spend a download on nothing.
+ */
+export function registerReplacementPagePrefetch(): void {
+ registerPagePrefetch(Urls.transformMigrateModels(), migrateModelsPage);
+}
export function getTransformToolsRoutes() {
return (
diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/index.ts
index 3de896543d3..1006d64d406 100644
--- a/enterprise/frontend/src/metabase-enterprise/schema_viewer/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/index.ts
@@ -1,12 +1,16 @@
import { PLUGIN_SCHEMA_VIEWER } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
-import { getDataStudioSchemaViewerRoutes } from "./routes";
+import {
+ getDataStudioSchemaViewerRoutes,
+ registerSchemaViewerPagePrefetch,
+} from "./routes";
export function initializePlugin() {
if (hasPremiumFeature("schema-viewer")) {
PLUGIN_SCHEMA_VIEWER.isEnabled = true;
PLUGIN_SCHEMA_VIEWER.getDataStudioSchemaViewerRoutes =
getDataStudioSchemaViewerRoutes;
+ registerSchemaViewerPagePrefetch();
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/routes.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/routes.tsx
index c71543f9151..c6b74835dbb 100644
--- a/enterprise/frontend/src/metabase-enterprise/schema_viewer/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/routes.tsx
@@ -8,7 +8,14 @@ const schemaViewerPage = () =>
Component: SchemaViewerPage,
}));
-registerPagePrefetch(Urls.dataStudioSchemaViewer(), schemaViewerPage);
+/**
+ * Called from the licensed branch of `initializePlugin`, so only a page this
+ * instance mounts is registered. The background pass reads the registrations too,
+ * and fetching a page nobody can reach would spend a download on nothing.
+ */
+export function registerSchemaViewerPagePrefetch(): void {
+ registerPagePrefetch(Urls.dataStudioSchemaViewer(), schemaViewerPage);
+}
export function getDataStudioSchemaViewerRoutes() {
return <Route index lazy={schemaViewerPage} />;
diff --git a/frontend/src/metabase/app-main.ts b/frontend/src/metabase/app-main.ts
index 130f9c7fa8c..bda009a9074 100644
--- a/frontend/src/metabase/app-main.ts
+++ b/frontend/src/metabase/app-main.ts
@@ -9,7 +9,7 @@ import { getUser, loadCurrentUser } from "metabase/current-user";
import { setRequestClientHeaders } from "metabase/embedding/lib/auth/set-request-client-headers";
import { mainReducers } from "metabase/reducers-main";
import { setErrorPage } from "metabase/redux/app";
-import { navigate } from "metabase/router";
+import { navigate, prefetchRegisteredPages } from "metabase/router";
import { getRoutes } from "metabase/routes";
import { getSetting } from "metabase/settings";
import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";
@@ -77,4 +77,13 @@ init(mainReducers, getRoutes, (store) => {
store.dispatch(setErrorPage({ status: 403 }));
}
});
+
+ // This entry serves full-app embedding too, and inside a customer's page
+ // background downloads are not ours to spend. The public and embed entries
+ // never get here at all.
+ if (IFRAMED_IN_SELF || !isWithinIframe()) {
+ prefetchRegisteredPages({
+ shouldStart: () => getUser(store.getState()) != null,
+ });
+ }
});
diff --git a/frontend/src/metabase/router/prefetch-background.unit.spec.ts b/frontend/src/metabase/router/prefetch-background.unit.spec.ts
new file mode 100644
index 00000000000..fe08dff8bf0
--- /dev/null
+++ b/frontend/src/metabase/router/prefetch-background.unit.spec.ts
@@ -0,0 +1,275 @@
+import type * as prefetchModule from "./prefetch";
+
+// Its own file, so the module-level registry holds only what these tests put in
+// it. `prefetchRegisteredPages` reaches every registration, so a registry shared
+// with the other prefetch tests would drag their pages into these assertions.
+//
+// The registry is module state, so each test takes a fresh copy of the module. A
+// test that declines leaves its pages unstarted, and a shared registry would hand
+// them to whichever test ran next.
+let prefetch: typeof prefetchModule;
+
+type Deferred = {
+ promise: Promise<unknown>;
+ resolve: () => void;
+ reject: () => void;
+};
+
+function deferred(): Deferred {
+ let resolve!: () => void;
+ let reject!: () => void;
+ const promise = new Promise<unknown>((res, rej) => {
+ resolve = () => res(undefined);
+ reject = () => rej(new Error("failed"));
+ });
+ return { promise, resolve, reject };
+}
+
+function setConnection(connection: unknown) {
+ Object.defineProperty(window.navigator, "connection", {
+ value: connection,
+ configurable: true,
+ });
+}
+
+const IDLE_DEADLINE: IdleDeadline = {
+ didTimeout: false,
+ timeRemaining: () => 50,
+};
+
+let idleCallbacks: IdleRequestCallback[];
+
+beforeEach(async () => {
+ idleCallbacks = [];
+ setConnection(undefined);
+ // jsdom has no idle callback. Collect them so a test decides when the tab
+ // goes idle, one turn at a time.
+ window.requestIdleCallback = (run) => {
+ idleCallbacks.push(run);
+ return 1;
+ };
+
+ jest.resetModules();
+ prefetch = await import("./prefetch");
+});
+
+/**
+ * Let everything pending settle, however many turns it takes.
+ *
+ * A macrotask, so it drains the whole microtask queue. Counting `then` hops
+ * instead would tie the tests to how many `await`s the queue happens to use
+ * between an idle callback firing and the next one being asked for.
+ */
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+/** One turn of the tab being idle. */
+async function idleOnce(): Promise<void> {
+ await flush();
+ const pending = idleCallbacks;
+ idleCallbacks = [];
+ pending.forEach((run) => run(IDLE_DEADLINE));
+ await flush();
+}
+
+// Enough turns for every page a test registers, plus the turns the queue spends
+// asking whether it is wanted. It is also what stops a test where `shouldStart`
+// never says yes: that queue keeps asking on every idle turn, so there is no
+// settled state to wait for.
+const MAX_IDLE_TURNS = 20;
+
+/** Idle until nothing is waiting on it, or `MAX_IDLE_TURNS` have passed. */
+async function idleUntilSettled(): Promise<void> {
+ for (let turn = 0; turn < MAX_IDLE_TURNS; turn++) {
+ await idleOnce();
+ if (idleCallbacks.length === 0) {
+ return;
+ }
+ }
+}
+
+describe("prefetchRegisteredPages", () => {
+ it("fetches every registered page once the tab is idle", async () => {
+ const dashboard = jest.fn().mockResolvedValue(undefined);
+ const collection = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/dashboard", dashboard);
+ prefetch.registerPagePrefetch("/collection", collection);
+
+ prefetch.prefetchRegisteredPages();
+ expect(dashboard).not.toHaveBeenCalled();
+
+ await idleUntilSettled();
+
+ expect(dashboard).toHaveBeenCalledTimes(1);
+ expect(collection).toHaveBeenCalledTimes(1);
+ });
+
+ // A chunk runs on the main thread as it arrives, so a queue that ran straight
+ // through would compete with whatever the user started doing meanwhile.
+ it("waits for the tab to be idle again between pages", async () => {
+ const first = jest.fn().mockResolvedValue(undefined);
+ const second = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/first", first);
+ prefetch.registerPagePrefetch("/second", second);
+
+ prefetch.prefetchRegisteredPages();
+
+ await idleOnce();
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(second).not.toHaveBeenCalled();
+
+ await idleOnce();
+ expect(second).toHaveBeenCalledTimes(1);
+ });
+
+ // A page the user asks for while this runs should compete with one background
+ // request, not with all of them.
+ it("fetches one page at a time", async () => {
+ const held = deferred();
+ const slow = jest.fn().mockReturnValue(held.promise);
+ const next = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/slow", slow);
+ prefetch.registerPagePrefetch("/next", next);
+
+ prefetch.prefetchRegisteredPages();
+
+ await idleOnce();
+ expect(slow).toHaveBeenCalledTimes(1);
+
+ // The tab is idle again, but the page in flight has not landed.
+ await idleOnce();
+ expect(next).not.toHaveBeenCalled();
+
+ held.resolve();
+ await idleOnce();
+ expect(next).toHaveBeenCalledTimes(1);
+ });
+
+ // Read when the tab goes idle, so the app can decline on what it knows by
+ // then rather than on what it knew at startup.
+ it("asks shouldStart when the tab goes idle, not when called", async () => {
+ const load = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/late", load);
+
+ let signedIn = false;
+ prefetch.prefetchRegisteredPages({ shouldStart: () => signedIn });
+ signedIn = true;
+
+ await idleUntilSettled();
+
+ expect(load).toHaveBeenCalledTimes(1);
+ });
+
+ // The current user arrives from a request, and someone on the login page signs
+ // in without the tab reloading. A no on the first idle turn is not an answer
+ // for the rest of the session.
+ it("keeps asking shouldStart after it has declined", async () => {
+ const load = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/signs-in-later", load);
+
+ let signedIn = false;
+ prefetch.prefetchRegisteredPages({ shouldStart: () => signedIn });
+
+ await idleOnce();
+ expect(load).not.toHaveBeenCalled();
+
+ signedIn = true;
+ await idleOnce();
+
+ expect(load).toHaveBeenCalledTimes(1);
+ });
+
+ it("fetches nothing while shouldStart declines", async () => {
+ const load = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/declined", load);
+
+ prefetch.prefetchRegisteredPages({ shouldStart: () => false });
+ await idleUntilSettled();
+
+ expect(load).not.toHaveBeenCalled();
+ });
+
+ // No link points at a modal, so hovering is never a signal that one is wanted.
+ it("fetches a background-only page that a link never would", async () => {
+ const modal = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerBackgroundPagePrefetch(modal);
+
+ prefetch.prefetchPage("/page/1");
+ expect(modal).not.toHaveBeenCalled();
+
+ prefetch.prefetchRegisteredPages();
+ await idleUntilSettled();
+
+ expect(modal).toHaveBeenCalledTimes(1);
+ });
+
+ it("carries on when a page fails to load", async () => {
+ const failing = jest.fn().mockRejectedValue(new Error("failed"));
+ const next = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/failing", failing);
+ prefetch.registerPagePrefetch("/next", next);
+
+ prefetch.prefetchRegisteredPages();
+ await idleUntilSettled();
+
+ expect(failing).toHaveBeenCalledTimes(1);
+ expect(next).toHaveBeenCalledTimes(1);
+ });
+
+ // A failed fetch is forgotten, so the navigation that asks for the page can
+ // show the error where the user is looking.
+ it("leaves a page that failed in the background open to a later hover", async () => {
+ const failing = jest.fn().mockRejectedValue(new Error("failed"));
+ prefetch.registerPagePrefetch("/retried", failing);
+
+ prefetch.prefetchRegisteredPages();
+ await idleUntilSettled();
+ expect(failing).toHaveBeenCalledTimes(1);
+
+ prefetch.prefetchPage("/retried");
+
+ expect(failing).toHaveBeenCalledTimes(2);
+ });
+
+ it("fetches nothing on a metered connection", async () => {
+ const load = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/metered", load);
+ setConnection({ saveData: true });
+
+ prefetch.prefetchRegisteredPages();
+ await idleUntilSettled();
+
+ expect(load).not.toHaveBeenCalled();
+ });
+
+ it("fetches nothing on a 2g connection", async () => {
+ const load = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/slow-2g", load);
+ setConnection({ effectiveType: "slow-2g" });
+
+ prefetch.prefetchRegisteredPages();
+ await idleUntilSettled();
+
+ expect(load).not.toHaveBeenCalled();
+ });
+
+ // Read again for each page, so a connection that turns metered part way
+ // through stops the pass instead of being a decision made at startup.
+ it("stops when the connection turns metered part way through", async () => {
+ const held = deferred();
+ const first = jest.fn().mockReturnValue(held.promise);
+ const second = jest.fn().mockResolvedValue(undefined);
+ prefetch.registerPagePrefetch("/first", first);
+ prefetch.registerPagePrefetch("/second", second);
+
+ prefetch.prefetchRegisteredPages();
+
+ await idleOnce();
+ expect(first).toHaveBeenCalledTimes(1);
+
+ setConnection({ saveData: true });
+ held.resolve();
+ await idleUntilSettled();
+
+ expect(second).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/router/prefetch.ts b/frontend/src/metabase/router/prefetch.ts
index 82bfd0dd3d7..31f3bef1d4b 100644
--- a/frontend/src/metabase/router/prefetch.ts
+++ b/frontend/src/metabase/router/prefetch.ts
@@ -1,7 +1,11 @@
type LoadPage = () => Promise<unknown>;
type Registration = {
- path: string;
+ /**
+ * The link prefix that starts this page's fetch, or `null` for a page that
+ * only the background pass reaches.
+ */
+ path: string | null;
load: LoadPage;
isExact: boolean;
isStarted: boolean;
@@ -32,6 +36,18 @@ export function registerPagePrefetch(
registrations.push({ path, load, isExact: exact, isStarted: false });
}
+/**
+ * Ask for a page that no link points at to be fetched in the background.
+ *
+ * Hovering is never a signal that such a page is wanted, so it takes no path and
+ * `prefetchPage` never reaches it. A modal that a menu on the page opens is the
+ * case this exists for. The point of fetching it at all is that a tab which
+ * outlives a deploy can still open it.
+ */
+export function registerBackgroundPagePrefetch(load: LoadPage): void {
+ registrations.push({ path: null, load, isExact: false, isStarted: false });
+}
+
/**
* Start fetching whatever `path` needs, if anything registered for it.
*
@@ -42,11 +58,15 @@ export function registerPagePrefetch(
*/
export function prefetchPage(path: string): void {
for (const registration of registrations) {
+ if (registration.isStarted || registration.path === null) {
+ continue;
+ }
+
const matches = registration.isExact
? path === registration.path
: path.startsWith(registration.path);
- if (registration.isStarted || !matches) {
+ if (!matches) {
continue;
}
@@ -66,15 +86,23 @@ function getConnection(): NetworkInformation | undefined {
.connection;
}
+/**
+ * Whether the connection is one worth spending a guess on.
+ *
+ * Not a metered or slow one, where guessing wrong is most expensive and the
+ * pages being guessed at are the largest chunks the app has.
+ */
+function isConnectionWorthGuessingOn(): boolean {
+ const connection = getConnection();
+ return !connection?.saveData && !/2g/.test(connection?.effectiveType ?? "");
+}
+
/**
* Whether a link coming into view should start its fetch.
*
* Only where hovering cannot: a device with a pointer already prefetches on
* hover, which is a far better signal of intent than a link merely being on
* screen. This covers the touch devices that never fire one.
- *
- * Not on a metered or slow connection, where guessing wrong is most expensive
- * and the pages being guessed at are the largest chunks the app has.
*/
function shouldPrefetchOnVisible(): boolean {
if (typeof window === "undefined" || !("IntersectionObserver" in window)) {
@@ -85,8 +113,102 @@ function shouldPrefetchOnVisible(): boolean {
return false;
}
- const connection = getConnection();
- return !connection?.saveData && !/2g/.test(connection?.effectiveType ?? "");
+ return isConnectionWorthGuessingOn();
+}
+
+// Long enough that the callback runs after the app has settled, short enough
+// that a tab which is never idle still gets its pages.
+const IDLE_TIMEOUT_MS = 10_000;
+const NO_IDLE_CALLBACK_DELAY_MS = 3_000;
+
+function nextIdle(): Promise<void> {
+ return new Promise((resolve) => {
+ const run = () => resolve();
+ if (typeof window.requestIdleCallback === "function") {
+ window.requestIdleCallback(run, { timeout: IDLE_TIMEOUT_MS });
+ return;
+ }
+ window.setTimeout(run, NO_IDLE_CALLBACK_DELAY_MS);
+ });
+}
+
+/**
+ * Wait for the tab to be idle, and for the caller to still want this.
+ *
+ * The caller's answer changes while the app loads. The current user arrives from
+ * a request, and someone on the login page signs in without the tab ever
+ * reloading, so a single no at the first idle turn says nothing about the rest of
+ * the session. This keeps asking instead. A tab that nobody signs into runs one
+ * boolean check per idle turn and fetches nothing.
+ */
+async function waitUntilWanted(shouldStart?: () => boolean): Promise<void> {
+ do {
+ await nextIdle();
+ } while (shouldStart && !shouldStart());
+}
+
+/**
+ * One page at a time, and only while the tab has nothing else to do.
+ *
+ * The browser runs a chunk as it arrives, so the cost of a page is main thread
+ * time and not only a request. Waiting for the tab to be idle again between
+ * pages is what keeps that off the moment the user starts doing something. One
+ * at a time also means a page the user asks for competes with a single
+ * background request rather than with all of them.
+ */
+async function startPendingRegistrationsInTurn(
+ shouldStart?: () => boolean,
+): Promise<void> {
+ for (const registration of registrations) {
+ if (registration.isStarted) {
+ continue;
+ }
+
+ await waitUntilWanted(shouldStart);
+
+ // Read again for each page. A connection that turns metered or drops to 2g
+ // part way through is a reason to stop rather than to carry on.
+ if (!isConnectionWorthGuessingOn()) {
+ return;
+ }
+
+ registration.isStarted = true;
+ try {
+ await registration.load();
+ } catch {
+ registration.isStarted = false;
+ }
+ }
+}
+
+/**
+ * Fetch every registered page once the tab is idle.
+ *
+ * Each file the app serves is named after its contents, so a deploy replaces all
+ * of them. A tab open from before the deploy asks for names nobody serves any
+ * more, and the page it asks for cannot be opened. A page fetched before that
+ * deploy is held by the bundler for the life of the tab, so it stays available
+ * however long the tab stays open.
+ *
+ * This lowers how often that happens. It does not remove it. A page nobody
+ * registered still has to be fetched when the user asks for it, and so does a
+ * chunk that a registered page asks for in turn.
+ *
+ * `shouldStart` is asked on every idle turn rather than once, so a caller can
+ * answer on what it knows by then and change its answer later. The app uses it to
+ * fetch nothing for a visitor sitting on the login page, and to start as soon as
+ * that visitor signs in.
+ */
+export function prefetchRegisteredPages({
+ shouldStart,
+}: {
+ shouldStart?: () => boolean;
+} = {}): void {
+ if (typeof window === "undefined" || !isConnectionWorthGuessingOn()) {
+ return;
+ }
+
+ void startPendingRegistrationsInTurn(shouldStart);
}
const observedPaths = new WeakMap<Element, string>();
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 42a7e792629..2e6d98f9ec8 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -50,6 +50,7 @@ import {
Navigate,
type RouteObject,
redirect,
+ registerBackgroundPagePrefetch,
registerPagePrefetch,
toRouteObjects,
useParams,
@@ -202,6 +203,23 @@ const commentsSidesheet = () =>
/* webpackChunkName: "comments-sidesheet" */ "metabase/documents/components/CommentsSidesheet"
).then(({ CommentsSidesheet }) => CommentsSidesheet);
+const dashboardMoveModal = () =>
+ import(
+ /* webpackChunkName: "dashboard-move-modal" */ "metabase/dashboard/components/DashboardMoveModal"
+ ).then(({ DashboardMoveModalConnected }) => DashboardMoveModalConnected);
+
+const dashboardCopyModal = () =>
+ import(
+ /* webpackChunkName: "dashboard-copy-modal" */ "metabase/dashboard/components/DashboardCopyModal"
+ ).then(({ DashboardCopyModalConnected }) => DashboardCopyModalConnected);
+
+const dashboardArchiveModal = () =>
+ import(
+ /* webpackChunkName: "dashboard-archive-modal" */ "metabase/dashboard/containers/ArchiveDashboardModal"
+ ).then(
+ ({ ArchiveDashboardModalConnected }) => ArchiveDashboardModalConnected,
+ );
+
/**
* Hovering a link into one of these chunks starts the fetch, so it is usually in
* hand by the time the click lands. The router still awaits `lazy` and still
@@ -233,6 +251,13 @@ registerPagePrefetch("/collection/", collectionLanding);
registerPagePrefetch("/trash", trashCollectionLanding);
registerPagePrefetch("/browse", browsePage("BrowseModels"));
+// No link points at a modal, so hovering never says one is wanted. These are
+// fetched only in the background, where the point is that a tab which outlives a
+// deploy can still open them.
+registerBackgroundPagePrefetch(dashboardMoveModal);
+registerBackgroundPagePrefetch(dashboardCopyModal);
+registerBackgroundPagePrefetch(dashboardArchiveModal);
+
export const getRoutes = (store: AppStore): RouteObject[] => [
{
element: <App />,
@@ -392,39 +417,15 @@ export const getRoutes = (store: AppStore): RouteObject[] => [
path: "dashboard/:slug",
lazy: dashboardApp,
children: [
- lazyModalRoute(
- "move",
- () =>
- import(
- /* webpackChunkName: "dashboard-move-modal" */ "metabase/dashboard/components/DashboardMoveModal"
- ).then(
- ({ DashboardMoveModalConnected }) =>
- DashboardMoveModalConnected,
- ),
- { noWrap: true },
- ),
- lazyModalRoute(
- "copy",
- () =>
- import(
- /* webpackChunkName: "dashboard-copy-modal" */ "metabase/dashboard/components/DashboardCopyModal"
- ).then(
- ({ DashboardCopyModalConnected }) =>
- DashboardCopyModalConnected,
- ),
- { noWrap: true },
- ),
- lazyModalRoute(
- "archive",
- () =>
- import(
- /* webpackChunkName: "dashboard-archive-modal" */ "metabase/dashboard/containers/ArchiveDashboardModal"
- ).then(
- ({ ArchiveDashboardModalConnected }) =>
- ArchiveDashboardModalConnected,
- ),
- { noWrap: true },
- ),
+ lazyModalRoute("move", dashboardMoveModal, {
+ noWrap: true,
+ }),
+ lazyModalRoute("copy", dashboardCopyModal, {
+ noWrap: true,
+ }),
+ lazyModalRoute("archive", dashboardArchiveModal, {
+ noWrap: true,
+ }),
],
},