Skip to content

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

Track page load times on every master merge (#80978)

Romeo Van Snicka22958cee3f2
diff --git a/.github/scripts/upload-bundle-load-stats.ts b/.github/scripts/upload-bundle-load-stats.ts
new file mode 100644
index 00000000000..24ddea72fa5
--- /dev/null
+++ b/.github/scripts/upload-bundle-load-stats.ts
@@ -0,0 +1,97 @@
+// Appends the measured load times to the "Bundle Load Times" table in
+// eng-stats-importer. Reads ROWS (the JSON matrix.js prints) and API_KEY from
+// env, and stamps each row with the commit it came from.
+
+import { readFileSync } from "node:fs";
+
+import { importStats } from "./stats-import";
+
+/** One condition, as `frontend/test/bench/matrix.ts` reports it. */
+interface Condition {
+ network: string;
+ networkMbps: number;
+ latencyMs: number;
+ cpu: string;
+ cpuThrottle: number;
+ coldMs: number;
+ warmMs: number;
+ steadyMs: number;
+ coldSpreadPercent: number;
+ coldTtfbMs: number;
+ coldFirstPaintMs: number;
+ coldAppMountedMs: number;
+ coldLargestPaintMs: number;
+ coldPageReadyMs: number;
+ warmPageReadyMs: number;
+ scripts: number;
+ scriptKb: number;
+ runs: number;
+}
+
+interface CommitStamp {
+ sha: string;
+ subject: string;
+}
+
+type LoadTimeRow = Record<string, string | number>;
+
+function buildRows(
+ conditions: Condition[],
+ { sha, subject }: CommitStamp,
+): LoadTimeRow[] {
+ return conditions.map((condition) => ({
+ Date: new Date().toISOString().slice(0, 10),
+ // Truncated the same way the bundle-size table does, so the two join.
+ Commit: sha.slice(0, 12),
+ // The stats table carries a free-text Description column. Populate it with
+ // the commit subject so the chart's points are self-describing.
+ Description: subject.split("\n")[0],
+ Network: condition.network,
+ "Network mbps": condition.networkMbps,
+ "Latency ms": condition.latencyMs,
+ CPU: condition.cpu,
+ "CPU throttle": condition.cpuThrottle,
+ "Cold ms": condition.coldMs,
+ "Warm ms": condition.warmMs,
+ "Steady ms": condition.steadyMs,
+ "Cold spread %": condition.coldSpreadPercent,
+ // The cold load broken up. A zero means the browser or the route never
+ // reported that one, rather than that it happened at time zero.
+ "Cold ttfb ms": condition.coldTtfbMs,
+ "Cold first paint ms": condition.coldFirstPaintMs,
+ "Cold app mounted ms": condition.coldAppMountedMs,
+ "Cold largest paint ms": condition.coldLargestPaintMs,
+ "Cold page ready ms": condition.coldPageReadyMs,
+ "Warm page ready ms": condition.warmPageReadyMs,
+ Scripts: condition.scripts,
+ "Script kb": condition.scriptKb,
+ Runs: condition.runs,
+ }));
+}
+
+async function main() {
+ const path = process.env.ROWS || "artifacts/load-times.json";
+ // matrix.js wrote this file, and Condition is the shape it prints.
+ const conditions = JSON.parse(readFileSync(path, "utf8")) as Condition[];
+
+ const rows = buildRows(conditions, {
+ sha: process.env.HEAD_SHA || "",
+ subject: process.env.COMMIT_MESSAGE || "",
+ });
+
+ console.table(rows);
+
+ try {
+ await importStats({ table: "bundle_load_times", rows });
+ console.log("Load times uploaded successfully");
+ } catch (error) {
+ // Stats logging is best-effort. A point lost to an unreachable importer is
+ // worth less than a red build on master, and the next commit plots another.
+ const message = error instanceof Error ? error.message : String(error);
+ console.log(
+ `::warning::Load-time upload failed after retries; leaving run green: ${message}`,
+ );
+ }
+}
+
+main();
diff --git a/.github/workflows/test.bundle-load-stats.yml b/.github/workflows/test.bundle-load-stats.yml
new file mode 100644
index 00000000000..49f0bea2a86
--- /dev/null
+++ b/.github/workflows/test.bundle-load-stats.yml
@@ -0,0 +1,107 @@
+name: Bundle Load Stats
+
+# Reuses the uberjar built on every master merge: boots it, signs in, loads the
+# app in a throttled headless Chrome across four network and CPU conditions, and
+# appends the times to eng-stats-importer.
+#
+# The instance is blank on purpose. `index.html` is built from settings and the
+# signed-in user alone, so seeding content would not change a single byte of the
+# document this measures.
+
+on:
+ workflow_run:
+ workflows: ["Build Uberjar"]
+ types: [completed]
+ # Master only: a release forms a non-linear line whose times cannot be
+ # compared against the commit before it.
+ branches: [master]
+ # A `workflow_run` workflow always runs the copy on the default branch, so a
+ # change here cannot be tried out before it merges. The call lets a PR run
+ # this branch's copy against the uberjar CI already built. A called run
+ # measures and reports; it does not write rows to Stats.
+ workflow_call:
+ inputs:
+ commit:
+ description: "Commit SHA to measure."
+ type: string
+ required: false
+ default: ""
+
+concurrency:
+ group: bundle-load-stats-${{ inputs.commit || github.event.workflow_run.head_sha }}
+ cancel-in-progress: true
+
+jobs:
+ bundle-load-stats:
+ if: ${{ github.repository == 'metabase/metabase' && (inputs.commit != '' || github.event.workflow_run.conclusion == 'success') }}
+ runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
+ timeout-minutes: 10
+ env:
+ HEAD_SHA: ${{ inputs.commit || github.event.workflow_run.head_sha }}
+ MB_JETTY_PORT: "4000"
+ SITE: http://localhost:4000
+ # Loads per condition. The first is the cold reading and the rest give the
+ # median, so this trades run time for a steadier number.
+ RUNS: "8"
+ steps:
+ - name: Check out the code
+ uses: actions/checkout@v6
+ with:
+ ref: ${{ env.HEAD_SHA }}
+ - uses: ./.github/actions/prepare-node-bun
+ - name: Prepare JDK 25
+ uses: actions/[email protected]
+ with:
+ java-version: "25"
+ distribution: "temurin"
+ - name: Install Chrome v144
+ uses: browser-actions/setup-chrome@2e1d749697dd1612b833dba4a722266286fbefcd # v2.1.2
+ with:
+ chrome-version: 144
+ id: setup-chrome
+ - name: Download EE uberjar
+ uses: ./.github/actions/fetch-artifact
+ with:
+ commit: ${{ env.HEAD_SHA }}
+ edition: ee
+ extract-path: temp/uberjar
+ - name: Start Metabase
+ run: |
+ mkdir -p artifacts
+ # --add-opens matches how the jar is launched everywhere else
+ # (uberjar.yml, pre-release.yml, bin/docker/run_metabase.sh), so the
+ # benchmark runs the app under the JVM configuration we ship.
+ MB_DB_FILE="${RUNNER_TEMP}/bench.db" \
+ nohup java --add-opens java.base/java.nio=ALL-UNNAMED \
+ -jar temp/uberjar/metabase.jar > artifacts/metabase.log 2>&1 &
+ - name: Sign in
+ run: |
+ # Waits for the instance to migrate and come up, then creates the
+ # first user. Masked because the token authenticates as that user.
+ session=$(bun frontend/test/bench/sign-in.ts "$SITE")
+ echo "::add-mask::$session"
+ echo "SESSION_COOKIE=$session" >> "$GITHUB_ENV"
+ - name: Warm the backend
+ run: |
+ # The first document a fresh JVM renders pays for its own JIT. Spend
+ # that here rather than inside the first condition measured.
+ for _ in 1 2 3 4 5; do curl -sS -o /dev/null "$SITE/"; done
+ - name: Measure load times
+ env:
+ CHROME_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
+ run: |
+ bun frontend/test/bench/matrix.ts "$SITE/" "$RUNS" \
+ | tee artifacts/load-times.json
+ - name: Show the Metabase log if something went wrong
+ if: failure()
+ run: tail -100 artifacts/metabase.log || true
+ - name: Import load times into Stats
+ if: ${{ inputs.commit == '' }}
+ env:
+ ROWS: artifacts/load-times.json
+ # Passed via env (not interpolated into the shell) so the commit
+ # message can't inject commands; the script keeps only the subject.
+ COMMIT_MESSAGE: ${{ github.event.workflow_run.head_commit.message }}
+ ENG_STATS_URL: ${{ secrets.ENG_STATS_URL }}
+ API_KEY: ${{ secrets.ENG_STATS_API_KEY }}
+ run: bun .github/scripts/upload-bundle-load-stats.ts
diff --git a/eslint.config.mjs b/eslint.config.mjs
index fcba2392316..d0d5bc7554f 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -1192,6 +1192,7 @@ const configs = [
"bin/**/*.js",
".github/scripts/**/*.js",
".github/scripts/**/*.mjs",
+ ".github/scripts/**/*.ts",
],
languageOptions: {
globals: {
diff --git a/frontend/src/metabase/app.tsx b/frontend/src/metabase/app.tsx
index 2a4bb513d51..2599682efa9 100644
--- a/frontend/src/metabase/app.tsx
+++ b/frontend/src/metabase/app.tsx
@@ -21,6 +21,7 @@ import "metabase/auth/plugins";
import "metabase/utils/csp-setup";
import { type Middleware, isAction } from "@reduxjs/toolkit";
+import { useLayoutEffect } from "react";
import { DragDropContextProvider } from "react-dnd";
import { createPortal } from "react-dom";
import { createRoot } from "react-dom/client";
@@ -52,6 +53,7 @@ import { setBasename } from "metabase/utils/basename";
import { captureConsoleErrors } from "metabase/utils/errors";
import { initMetaplow } from "metabase/utils/metaplow";
import { initTracing, rotateTraceId } from "metabase/utils/otel";
+import { PERFORMANCE_MARKS, markOnce } from "metabase/utils/performance-marks";
import MetabaseSettings from "metabase/utils/settings";
import { registerVisualizations } from "metabase/visualizations/register";
@@ -64,6 +66,18 @@ initializePlugins();
type Store = ReturnType<typeof getStore>;
+/**
+ * Marks the commit of the app shell. A layout effect runs after React has
+ * committed, so this is the first moment the app is on screen, and it sits
+ * inside the tree so every entry records it.
+ */
+function AppMountedMark() {
+ useLayoutEffect(() => {
+ markOnce(PERFORMANCE_MARKS.appMounted);
+ }, []);
+ return null;
+}
+
function isLocationChangeAction(
action: unknown,
): action is { type: typeof LOCATION_CHANGE; payload?: Location } {
@@ -115,6 +129,7 @@ function _init(
root.render(
<MetabaseReduxProvider store={store}>
+ <AppMountedMark />
<EmotionCacheProvider>
<DragDropContextProvider backend={ModifiedBackend} context={{ window }}>
<OverlayStackProvider>
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.ts
index 806c2c898cd..22dea10e5dd 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts
@@ -49,6 +49,7 @@ import {
isQuestionDashCard,
isVirtualDashCard,
} from "metabase/utils/dashboard";
+import { PERFORMANCE_MARKS, markOnce } from "metabase/utils/performance-marks";
import { uuid } from "metabase/utils/uuid";
import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";
import type {
@@ -150,6 +151,8 @@ export const setShowLoadingCompleteFavicon = createAction<boolean>(
const loadingComplete = createThunkAction(
SET_LOADING_DASHCARDS_COMPLETE,
() => (dispatch, getState) => {
+ // Every card has its data, so the dashboard is as rendered as it gets.
+ markOnce(PERFORMANCE_MARKS.pageReady);
dispatch(setShowLoadingCompleteFavicon(true));
if (!document.hidden) {
diff --git a/frontend/src/metabase/home/components/HomeContent/HomeContent.tsx b/frontend/src/metabase/home/components/HomeContent/HomeContent.tsx
index d9cae0d74ba..9eafc493a88 100644
--- a/frontend/src/metabase/home/components/HomeContent/HomeContent.tsx
+++ b/frontend/src/metabase/home/components/HomeContent/HomeContent.tsx
@@ -9,6 +9,7 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErr
import { getUser } from "metabase/current-user";
import { useSelector } from "metabase/redux";
import { useSetting } from "metabase/settings";
+import { useMarkPageReady } from "metabase/utils/performance-marks";
import { isSyncCompleted } from "metabase/utils/syncing";
import type {
Database,
@@ -44,11 +45,21 @@ export const HomeContent = (): JSX.Element | null => {
[recentItemsRaw],
);
+ const isContentReady = Boolean(
+ !error && user && !isLoading(user, databases, recentItems, popularItems),
+ );
+
+ // The home page is what the load benchmark measures, so it reports when its
+ // own content is in hand rather than leaving the reading to the shell.
+ useMarkPageReady(isContentReady);
+
if (error) {
return <LoadingAndErrorWrapper error={error} />;
}
- if (!user || isLoading(user, databases, recentItems, popularItems)) {
+ // `!user` is implied by `!isContentReady`, and repeating it narrows the
+ // type for everything below.
+ if (!isContentReady || !user) {
return <LoadingAndErrorWrapper loading />;
}
diff --git a/frontend/src/metabase/utils/performance-marks.ts b/frontend/src/metabase/utils/performance-marks.ts
new file mode 100644
index 00000000000..02474f3c626
--- /dev/null
+++ b/frontend/src/metabase/utils/performance-marks.ts
@@ -0,0 +1,69 @@
+import { useEffect } from "react";
+
+/**
+ * The moments in a page load that only the app knows.
+ *
+ * Navigation timing already reports everything up to `loadEventEnd`, and the
+ * paint entries report when the browser first drew something. What neither can
+ * say is when the page the user asked for actually has its data. These marks
+ * fill that gap, and a benchmark reads them back with
+ * `performance.getEntriesByName`.
+ *
+ * Marks are cheap and carry no payload, so they are recorded in every build
+ * rather than behind a flag.
+ */
+export const PERFORMANCE_MARKS = {
+ /**
+ * React has committed the app shell. The entry bundle has downloaded, parsed
+ * and run by this point, but no route content is on screen yet.
+ */
+ appMounted: "mb:app-mounted",
+
+ /**
+ * Everything the route needs has arrived, so no loading state is left on
+ * screen. Routes opt in, because only the route knows when it is done.
+ */
+ pageReady: "mb:page-ready",
+} as const;
+
+export type PerformanceMark =
+ (typeof PERFORMANCE_MARKS)[keyof typeof PERFORMANCE_MARKS];
+
+const recorded = new Set<PerformanceMark>();
+
+/**
+ * Records a mark the first time it is asked for and ignores every later call.
+ *
+ * A component that remounts, a dashboard that auto-refreshes, or a second
+ * navigation would otherwise move a reading that is meant to describe the
+ * first load.
+ */
+export function markOnce(name: PerformanceMark): void {
+ // static-viz renders in GraalJS, which has no Performance API.
+ if (typeof performance === "undefined" || !performance.mark) {
+ return;
+ }
+ if (recorded.has(name)) {
+ return;
+ }
+ recorded.add(name);
+ performance.mark(name);
+}
+
+/** Test seam: forgets which marks have been recorded. */
+export function resetPerformanceMarks(): void {
+ recorded.clear();
+}
+
+/**
+ * Records `page-ready` the first time a route reports that its content has
+ * arrived. Routes opt in, because only the route knows what "arrived" means for
+ * it.
+ */
+export function useMarkPageReady(isReady: boolean): void {
+ useEffect(() => {
+ if (isReady) {
+ markOnce(PERFORMANCE_MARKS.pageReady);
+ }
+ }, [isReady]);
+}
diff --git a/frontend/src/metabase/utils/performance-marks.unit.spec.ts b/frontend/src/metabase/utils/performance-marks.unit.spec.ts
new file mode 100644
index 00000000000..6065dc1a229
--- /dev/null
+++ b/frontend/src/metabase/utils/performance-marks.unit.spec.ts
@@ -0,0 +1,59 @@
+import {
+ PERFORMANCE_MARKS,
+ markOnce,
+ resetPerformanceMarks,
+} from "./performance-marks";
+
+// jsdom implements `performance.now` and nothing else, so the API this module
+// guards against being absent is absent here too. Stub the one method it uses.
+function stubPerformanceMark() {
+ const mark = jest.fn();
+ Object.defineProperty(performance, "mark", {
+ value: mark,
+ configurable: true,
+ writable: true,
+ });
+ return mark;
+}
+
+describe("markOnce", () => {
+ beforeEach(() => {
+ resetPerformanceMarks();
+ // Unjustified type cast. FIXME
+ delete (performance as unknown as Record<string, unknown>).mark;
+ });
+
+ it("records the mark", () => {
+ const mark = stubPerformanceMark();
+
+ markOnce(PERFORMANCE_MARKS.appMounted);
+
+ expect(mark).toHaveBeenCalledWith(PERFORMANCE_MARKS.appMounted);
+ });
+
+ it("ignores every call after the first, so a remount cannot move the reading", () => {
+ const mark = stubPerformanceMark();
+
+ markOnce(PERFORMANCE_MARKS.pageReady);
+ markOnce(PERFORMANCE_MARKS.pageReady);
+ markOnce(PERFORMANCE_MARKS.pageReady);
+
+ expect(mark).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the marks apart", () => {
+ const mark = stubPerformanceMark();
+
+ markOnce(PERFORMANCE_MARKS.appMounted);
+ markOnce(PERFORMANCE_MARKS.pageReady);
+
+ expect(mark.mock.calls.flat()).toEqual([
+ PERFORMANCE_MARKS.appMounted,
+ PERFORMANCE_MARKS.pageReady,
+ ]);
+ });
+
+ it("does nothing where the Performance API is absent, as in static-viz", () => {
+ expect(() => markOnce(PERFORMANCE_MARKS.appMounted)).not.toThrow();
+ });
+});
diff --git a/frontend/test/bench/README.md b/frontend/test/bench/README.md
new file mode 100644
index 00000000000..d5ff05d6912
--- /dev/null
+++ b/frontend/test/bench/README.md
@@ -0,0 +1,149 @@
+# Bundle load benchmark
+
+Measures how long the initial bundle takes to download, parse and run, so a
+change to the chunk layout can be judged on time rather than on bytes alone.
+
+Bytes and time disagree. A layout that ships fewer bytes can be slower to
+execute, and one that splits work across files can compile faster while
+transferring more. This harness reports the number that settles it.
+
+## What it measures
+
+`domContentLoadedEventEnd`. A `defer` script is guaranteed to have downloaded,
+parsed and executed before DOMContentLoaded fires, so it brackets exactly the
+work a chunk layout can move around.
+
+Three states are reported, because a layout can help one and hurt another:
+
+- **cold**, the first visit, with an empty cache,
+- **warm**, the second visit, served from the HTTP cache but still compiled,
+- **steady**, the visits after that, once V8 has cached the compiled code.
+
+DOMContentLoaded is not the whole story, so the harness also reads the rest of
+the load.
+
+| Reading | Where it comes from | What it says |
+| ------------------------ | -------------------------- | --------------------------------------------- |
+| `ttfb` | `responseStart` | The server started answering. |
+| `firstContentfulPaint` | paint entry | The browser drew something. |
+| `domContentLoaded` | `domContentLoadedEventEnd` | The entry scripts downloaded, parsed and ran. |
+| `appMounted` | `mb:app-mounted` mark | React committed the app shell. |
+| `largestContentfulPaint` | LCP entry | The biggest element was drawn. |
+| `pageReady` | `mb:page-ready` mark | The route has all its data. |
+| `load` | `loadEventEnd` | Everything the document referenced arrived. |
+
+A jar built before these marks existed reports `0` for both, and still produces
+every other reading. The marks never gate a measurement.
+
+`largestContentfulPaint` needs a `PerformanceObserver`, because these entries
+never reach the performance timeline that every other reading comes from. The
+harness installs one before the document runs. The browser keeps revising the
+value until the user interacts, and the harness reads it once the page reports
+ready, so it is a lower bound rather than the final figure.
+
+The two marks come from the app, in
+`frontend/src/metabase/utils/performance-marks.ts`. `mb:app-mounted` is recorded
+in a layout effect inside the render tree, so every entry reports it.
+`mb:page-ready` is opt-in per route, because only the route knows when it is
+done: the dashboard records it from `loadingComplete`, where its last card
+lands. A route that does not record it reports `0`, so a zero means "not
+reported" rather than "instant".
+
+Reading DOMContentLoaded alone understates a route in its own chunk, which is
+requested only after the reading is taken. `pageReady` is the one that covers
+it.
+
+### One load per state
+
+Each state reports the readings of a single load. It does not take a separate
+median for each reading.
+
+For cold and steady, the harness runs the page several times and then picks the
+run whose DOMContentLoaded is the median of that series. Every reading in the
+state comes from that one run. The second visit happens once per browser
+profile, so that state is the run itself.
+
+A separate median per reading describes a load that never happened. It can also
+put the readings out of order, and print a page-ready that precedes the TTFB
+beside it.
+
+`Cold spread %` still comes from all the cold runs, because a spread is a
+property of the series rather than of one load.
+
+## Running it against a real Metabase
+
+This is what CI does, and it is the accurate option. The document is 136 kb, most
+of it the inline settings JSON that precedes the script tags, and only a real
+backend produces it.
+
+Start a build, sign in, and measure:
+
+```
+MB_DB_FILE=/tmp/bench.db MB_JETTY_PORT=4000 java -jar target/uberjar/metabase.jar &
+SESSION_COOKIE=$(bun frontend/test/bench/sign-in.ts http://localhost:4000) \
+ bun frontend/test/bench/matrix.ts http://localhost:4000/ 8
+```
+
+`sign-in.js` creates the first user on a blank instance and signs that user in on
+a later run, so it is safe to run again while the backend is up. It seeds no
+content, because `index.html` is built from settings and the user alone.
+
+## Running it against a built tree
+
+Use this to compare two chunk layouts without booting a backend. It understates
+the cold reading, because the stub document is 2.7 kb rather than 136 kb.
+
+```
+bun run build-release:js
+cp -R resources/frontend_client /tmp/bench-before
+bun frontend/test/bench/serve.ts /tmp/bench-before 8099 &
+bun frontend/test/bench/matrix.ts http://127.0.0.1:8099/ 8
+```
+
+`serve.js` fills in the index template, serves a `.br` beside a file when the
+client accepts it, and answers every API call with `{}`. The app fails to render
+on that, which does not matter: the measurement is finished before the first API
+response would have been used.
+
+To measure one condition rather than the four, call `measure.js` directly:
+
+```
+WARM=1 CPU_THROTTLE=4 bun frontend/test/bench/measure.ts http://127.0.0.1:8099/ 8
+```
+
+## Options
+
+`matrix.js` sets the first four itself, one condition at a time. Pass them to
+`measure.js` when you call it directly.
+
+| variable | default | what it does |
+| ----------------- | ------------ | -------------------------------------------------------- |
+| `CPU_THROTTLE` | `4` | CPU slowdown, so a laptop stands in for a slower machine |
+| `NETWORK_MBPS` | `10` | throughput, `0` to leave the network alone |
+| `NETWORK_LATENCY` | `40` | added latency in ms |
+| `WARM` | unset | keep the cache between runs, to measure a returning user |
+| `SESSION_COOKIE` | unset | `metabase.SESSION`, to load the page signed in |
+| `PORT_OFFSET` | `0` | added to the debugging port `9222` |
+| `CHROME_PATH` | macOS Chrome | the browser binary |
+
+## What CI records
+
+`.github/workflows/test.bundle-load-stats.yml` runs the matrix on every master
+merge and appends one row per condition to the `bundle_load_times` table.
+
+That table has to exist in eng-stats-importer before the first run. The importer
+does not create one on demand, and a push to a table it does not know returns a
+4xx. The upload treats any failure as a warning and leaves the run green, so a
+missing table shows up as an empty chart rather than a red build.
+
+The conditions are a fast and a slow network crossed with a fast and a slow CPU.
+The split matters: a slow network dominates the cold reading, because that is
+bytes on the wire, and a slow CPU dominates the warm one, because that is parse
+and execute. A change that trades bytes for execution moves one and not the
+other.
+
+Times are relative to the machine that runs them. A CI runner is slower than a
+laptop, so read a number against the same runner's history and not against a
+number from anywhere else. Each row carries `Cold spread %`, the interquartile
+spread of its cold runs, which is what tells a real regression from a busy
+runner.
diff --git a/frontend/test/bench/matrix.ts b/frontend/test/bench/matrix.ts
new file mode 100644
index 00000000000..d7ec1916b54
--- /dev/null
+++ b/frontend/test/bench/matrix.ts
@@ -0,0 +1,204 @@
+/* eslint-env node */
+
+/**
+ * Runs the load benchmark across the conditions CI tracks, and prints one row
+ * per condition.
+ *
+ * Each condition is measured twice. A series with the cache off gives the cold
+ * load, where every run is a first visit. A series with the cache kept gives the
+ * two loads that follow: the second visit, which reads the files from the HTTP
+ * cache but still compiles them, and the steady state after V8 has cached the
+ * compiled code.
+ *
+ * Times are relative to the machine that runs them. A CI runner is slower than a
+ * laptop, so compare a number against the same machine's history, not against a
+ * number from somewhere else.
+ *
+ * Point this at a real Metabase, which is what CI does, or at `serve.js` to
+ * measure a built tree without a backend. Set SESSION_COOKIE to load the page
+ * signed in.
+ */
+import { spawn } from "node:child_process";
+import path from "node:path";
+
+/** One reading, as `timings` in `measure.ts` builds it. */
+interface Timings {
+ ttfbMs: number;
+ firstContentfulPaintMs: number;
+ domContentLoadedMs: number;
+ appMountedMs: number;
+ largestContentfulPaintMs: number;
+ pageReadyMs: number;
+}
+
+/** What one `measure.ts` series prints. */
+interface Series {
+ runs: number;
+ scripts: number;
+ scriptKb: number;
+ median: Timings;
+ secondLoad: Timings | null;
+ steady: Timings | null;
+ everyRunMs: number[];
+}
+
+interface Conditions {
+ mbps: number;
+ latency: number;
+ throttle: number;
+ warm: boolean;
+ offset: number;
+}
+
+const url = process.argv[2];
+const runs = Number(process.argv[3] || 8);
+
+if (!url) {
+ console.error("usage: bun matrix.ts <url> [runs]");
+ console.error("env: SESSION_COOKIE");
+ process.exit(1);
+}
+
+// The cache-kept series spends its first run filling an empty cache, its second
+// on the second visit, and the rest on the steady state.
+if (runs < 3) {
+ console.error("matrix.ts needs at least 3 runs per condition");
+ process.exit(1);
+}
+
+/** Throughput in Mbps and added latency in ms. */
+const NETWORKS = {
+ fast: { mbps: 40, latency: 20 },
+ slow: { mbps: 5, latency: 150 },
+};
+
+/** CPU slowdown, where 1 leaves the runner at its own speed. */
+const CPUS = { fast: 1, slow: 4 };
+
+function measure({
+ mbps,
+ latency,
+ throttle,
+ warm,
+ offset,
+}: Conditions): Promise<Series> {
+ return new Promise<Series>((resolve, reject) => {
+ const child = spawn(
+ process.execPath,
+ [path.join(import.meta.dirname, "measure.ts"), url, String(runs)],
+ {
+ stdio: ["ignore", "pipe", "inherit"],
+ env: {
+ ...process.env,
+ NETWORK_MBPS: String(mbps),
+ NETWORK_LATENCY: String(latency),
+ CPU_THROTTLE: String(throttle),
+ // Each series gets its own debugging port, so a Chrome that is slow
+ // to release the last one cannot be mistaken for the new one.
+ PORT_OFFSET: String(offset),
+ WARM: warm ? "1" : "",
+ },
+ },
+ );
+
+ let output = "";
+ child.stdout.on("data", (chunk) => (output += chunk));
+ child.on("exit", (code) =>
+ code === 0
+ ? resolve(JSON.parse(output))
+ : reject(new Error(`measure.ts exited with ${code}`)),
+ );
+ });
+}
+
+/**
+ * How far the middle half of the cold runs spread, as a percent of the median.
+ *
+ * Cold is the number a reader watches, and on a shared runner it is the number
+ * noise moves. Recording the spread beside it is what tells a real change from
+ * a busy machine.
+ */
+/**
+ * `measure.ts` leaves these empty for a series too short to hold them, which the
+ * run count above rules out. Fail loudly rather than report a zero if it ever
+ * stops filling one in.
+ */
+function required(timings: Timings | null, name: string): Timings {
+ if (!timings) {
+ throw new Error(`measure.ts reported no ${name}`);
+ }
+ return timings;
+}
+
+function spreadPercent(values: number[]) {
+ const sorted = [...values].sort((a, b) => a - b);
+ const at = (fraction: number) => sorted[Math.floor(sorted.length * fraction)];
+ const middle = sorted[Math.floor(sorted.length / 2)];
+ return Number((((at(0.75) - at(0.25)) / middle) * 100).toFixed(1));
+}
+
+(async () => {
+ const rows = [];
+ let offset = 0;
+
+ // Object.keys widens to string, and these two objects are the only source of
+ // condition names.
+ for (const cpu of Object.keys(CPUS) as (keyof typeof CPUS)[]) {
+ // Object.keys widens to string, as above.
+ for (const network of Object.keys(NETWORKS) as (keyof typeof NETWORKS)[]) {
+ const { mbps, latency } = NETWORKS[network];
+ const throttle = CPUS[cpu];
+
+ const cold = await measure({
+ mbps,
+ latency,
+ throttle,
+ warm: false,
+ offset: offset++,
+ });
+ const warm = await measure({
+ mbps,
+ latency,
+ throttle,
+ warm: true,
+ offset: offset++,
+ });
+
+ // Every cold reading in the row comes from `cold.median`, and every warm
+ // reading from `warm.secondLoad`. Each is one load, so the readings in a
+ // row stay in order with each other. A row assembled from a separate
+ // median per reading describes a load that never happened.
+ rows.push({
+ network,
+ networkMbps: mbps,
+ latencyMs: latency,
+ cpu,
+ cpuThrottle: throttle,
+ coldMs: cold.median.domContentLoadedMs,
+ warmMs: required(warm.secondLoad, "secondLoad").domContentLoadedMs,
+ steadyMs: required(warm.steady, "steady").domContentLoadedMs,
+ coldSpreadPercent: spreadPercent(cold.everyRunMs),
+ // The cold load broken up, in the order a user meets it: bytes start
+ // arriving, something is drawn, the shell commits, the page has its
+ // data.
+ coldTtfbMs: cold.median.ttfbMs,
+ coldFirstPaintMs: cold.median.firstContentfulPaintMs,
+ coldAppMountedMs: cold.median.appMountedMs,
+ coldLargestPaintMs: cold.median.largestContentfulPaintMs,
+ coldPageReadyMs: cold.median.pageReadyMs,
+ warmPageReadyMs: required(warm.secondLoad, "secondLoad").pageReadyMs,
+ scripts: cold.scripts,
+ scriptKb: cold.scriptKb,
+ runs: cold.runs,
+ });
+
+ console.error(`measured ${cpu} cpu on a ${network} network`);
+ }
+ }
+
+ // Written with a callback rather than console.log so the process cannot exit
+ // with the JSON still buffered in a pipe.
+ process.stdout.write(JSON.stringify(rows, null, 2) + "\n", () =>
+ process.exit(0),
+ );
+})();
diff --git a/frontend/test/bench/measure.ts b/frontend/test/bench/measure.ts
new file mode 100644
index 00000000000..7641ca120f3
--- /dev/null
+++ b/frontend/test/bench/measure.ts
@@ -0,0 +1,353 @@
+/* eslint-env node */
+
+/**
+ * Loads a page repeatedly in a throttled headless Chrome and reports how long
+ * the initial bundle takes to download, parse and run.
+ *
+ * `domContentLoadedEventEnd` is the number to read. A `defer` script is
+ * guaranteed to have downloaded, parsed and executed before DOMContentLoaded
+ * fires, so it brackets exactly the work a chunk layout can move around. It also
+ * survives the app erroring against the stub API, which a paint metric does not.
+ *
+ * The first load fills the HTTP cache, the second fills V8's code cache, and the
+ * loads after that are the steady state a returning user sees. Both are
+ * reported, because a chunk layout can help one and hurt the other.
+ */
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import http from "node:http";
+
+const CHROME =
+ process.env.CHROME_PATH ||
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
+
+const url = process.argv[2];
+const runs = Number(process.argv[3] || 8);
+const cpuThrottle = Number(process.env.CPU_THROTTLE || 4);
+const mbps = Number(process.env.NETWORK_MBPS || 10);
+const latency = Number(process.env.NETWORK_LATENCY || 40);
+const keepCache = Boolean(process.env.WARM);
+// Signs the load in, so the document carries what a real user's does: their
+// locale and, once the build writes them, the route's preload hints.
+const sessionCookie = process.env.SESSION_COOKIE || "";
+const port = 9222 + Number(process.env.PORT_OFFSET || 0);
+
+if (!url) {
+ console.error("usage: bun measure.ts <url> [runs]");
+ console.error(
+ "env: CPU_THROTTLE NETWORK_MBPS NETWORK_LATENCY WARM PORT_OFFSET SESSION_COOKIE",
+ );
+ process.exit(1);
+}
+
+/** What READ_METRICS evaluates to in the page. */
+interface Run {
+ href: string;
+ ttfb: number;
+ domContentLoaded: number;
+ load: number;
+ firstPaint: number;
+ firstContentfulPaint: number;
+ largestContentfulPaint: number;
+ appMounted: number;
+ pageReady: number;
+ lastScriptEnd: number;
+ scriptCount: number;
+ scriptBytes: number;
+}
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// Cleared by the first load that shows the build records no performance
+// marks, so the rest of the series skips waiting for them.
+let buildRecordsMarks = true;
+
+function devtools(path: string, method = "GET"): Promise<any> {
+ return new Promise((resolve, reject) => {
+ http
+ .request({ host: "127.0.0.1", port, path, method }, (res) => {
+ let body = "";
+ res.on("data", (chunk) => (body += chunk));
+ res.on("end", () => {
+ try {
+ resolve(body ? JSON.parse(body) : {});
+ } catch {
+ resolve({});
+ }
+ });
+ })
+ .on("error", reject)
+ .end();
+ });
+}
+
+/** The slice of the DevTools protocol this needs, over the native WebSocket. */
+class Session {
+ socket: WebSocket;
+ lastId: number;
+ pending: Map<number, (result: any) => void>;
+
+ constructor(socket: WebSocket) {
+ this.socket = socket;
+ this.lastId = 0;
+ this.pending = new Map();
+
+ socket.addEventListener("message", (event: MessageEvent) => {
+ const message = JSON.parse(event.data);
+ const resolve = this.pending.get(message.id);
+ if (resolve) {
+ this.pending.delete(message.id);
+ resolve(message.result);
+ }
+ });
+ }
+
+ send(method: string, params: Record<string, unknown> = {}): Promise<any> {
+ const id = ++this.lastId;
+ this.socket.send(JSON.stringify({ id, method, params }));
+ return new Promise((resolve) => this.pending.set(id, resolve));
+ }
+}
+
+// Everything up to `load` comes from navigation timing, and the paint entries
+// say when the browser first drew. `mb:app-mounted` and `mb:page-ready` are the
+// two the app records itself, because only it knows when the shell committed
+// and when the page has its data. See metabase/utils/performance-marks.ts.
+const READ_METRICS = `JSON.stringify((() => {
+ const nav = performance.getEntriesByType("navigation")[0];
+ const scripts = performance
+ .getEntriesByType("resource")
+ .filter((entry) => entry.name.endsWith(".js"));
+ const paint = (name) => {
+ const entry = performance.getEntriesByName(name)[0];
+ return entry ? entry.startTime : 0;
+ };
+ return {
+ href: location.href,
+ ttfb: nav ? nav.responseStart : 0,
+ domContentLoaded: nav ? nav.domContentLoadedEventEnd : 0,
+ load: nav ? nav.loadEventEnd : 0,
+ firstPaint: paint("first-paint"),
+ firstContentfulPaint: paint("first-contentful-paint"),
+ largestContentfulPaint: window.__benchLargestPaint || 0,
+ appMounted: paint("mb:app-mounted"),
+ pageReady: paint("mb:page-ready"),
+ lastScriptEnd: Math.max(0, ...scripts.map((entry) => entry.responseEnd)),
+ scriptCount: scripts.length,
+ scriptBytes: scripts.reduce((total, entry) => total + entry.encodedBodySize, 0),
+ };
+})())`;
+
+// Records the last largest-contentful-paint the page reports. The entries arrive
+// in increasing order, so the latest one is the largest so far. `buffered` covers
+// a paint that lands before the observer is registered.
+//
+// The browser keeps revising this until the user interacts, and the reading is
+// taken once the page reports ready. It is therefore a lower bound rather than
+// the final figure, which is what makes it comparable between commits.
+const OBSERVE_LARGEST_PAINT = `
+ window.__benchLargestPaint = 0;
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ window.__benchLargestPaint = entry.startTime;
+ }
+ }).observe({ type: "largest-contentful-paint", buffered: true });
+`;
+
+async function launchChrome() {
+ const chrome = spawn(CHROME, [
+ "--headless=new",
+ // The harness only ever loads its own server on localhost, and a Chrome
+ // installed by CI has no SUID sandbox binary to use.
+ "--no-sandbox",
+ `--remote-debugging-port=${port}`,
+ `--user-data-dir=${fs.mkdtempSync("/tmp/metabase-bench-")}`,
+ "--no-first-run",
+ "--disable-extensions",
+ "--disable-background-networking",
+ "--window-size=1280,900",
+ ]);
+ chrome.stderr.on("data", () => {});
+
+ for (let attempt = 0; attempt < 60; attempt++) {
+ try {
+ await devtools("/json/version");
+ return chrome;
+ } catch {
+ await sleep(250);
+ }
+ }
+ throw new Error(`Chrome did not open a debugging port on ${port}`);
+}
+
+async function loadOnce() {
+ const target = await devtools("/json/new?about:blank", "PUT");
+ const socket = new WebSocket(target.webSocketDebuggerUrl);
+ await new Promise((resolve) => socket.addEventListener("open", resolve));
+ const session = new Session(socket);
+
+ await session.send("Page.enable");
+ await session.send("Network.enable");
+ await session.send("Network.setCacheDisabled", { cacheDisabled: !keepCache });
+ await session.send("Emulation.setCPUThrottlingRate", { rate: cpuThrottle });
+
+ if (mbps > 0) {
+ await session.send("Network.emulateNetworkConditions", {
+ offline: false,
+ latency,
+ downloadThroughput: (mbps * 1024 * 1024) / 8,
+ uploadThroughput: (mbps * 1024 * 1024) / 8,
+ });
+ }
+
+ if (sessionCookie) {
+ await session.send("Network.setCookie", {
+ name: "metabase.SESSION",
+ value: sessionCookie,
+ url,
+ });
+ }
+
+ // Largest-contentful-paint entries never reach the performance timeline, so
+ // `getEntriesByType` cannot see them. An observer is the only way to read one,
+ // and it has to exist before the paint. Paint entries are buffered, which is
+ // why first-contentful-paint needs none of this.
+ await session.send("Page.addScriptToEvaluateOnNewDocument", {
+ source: OBSERVE_LARGEST_PAINT,
+ });
+
+ await session.send("Page.navigate", { url });
+
+ const read = async () => {
+ const { result } = await session.send("Runtime.evaluate", {
+ expression: READ_METRICS,
+ returnByValue: true,
+ });
+ return result && result.value ? JSON.parse(result.value) : null;
+ };
+
+ // Polled rather than waiting on a lifecycle event, because the app errors
+ // against the stub API and a failed boot must still produce a reading. The
+ // href check keeps the blank page the tab opens on out of the results.
+ let metrics = null;
+ for (let attempt = 0; attempt < 300; attempt++) {
+ const parsed = await read();
+ if (
+ parsed &&
+ parsed.domContentLoaded > 0 &&
+ parsed.scriptCount > 0 &&
+ parsed.href.startsWith(url)
+ ) {
+ metrics = parsed;
+ break;
+ }
+ await sleep(150);
+ }
+
+ // The marks land after the entry scripts, `mb:page-ready` only on a route that
+ // records it, and the largest paint later still. Wait a bounded while rather
+ // than missing them.
+ //
+ // They must not gate the reading itself. A jar built before the marks existed
+ // never fires either one, and waiting on them there would turn each load into
+ // a 45s timeout and then report no reading at all. One load settles it for the
+ // whole series, so the rest do not pay the wait again.
+ for (
+ let attempt = 0;
+ buildRecordsMarks &&
+ metrics &&
+ (!metrics.pageReady || !metrics.largestContentfulPaint) &&
+ attempt < 40;
+ attempt++
+ ) {
+ await sleep(150);
+ metrics = (await read()) || metrics;
+ }
+ if (metrics && !metrics.appMounted) {
+ buildRecordsMarks = false;
+ }
+
+ socket.close();
+ await devtools(`/json/close/${target.id}`);
+ return metrics;
+}
+
+/**
+ * The run that stands for a series: the one whose DOMContentLoaded is the
+ * median.
+ *
+ * A whole run, not a median of each reading on its own. Medianing the readings
+ * separately describes a load that never happened, and lets one reading land
+ * before a reading that must precede it, such as a page-ready earlier than the
+ * TTFB printed beside it.
+ */
+function representative(results: Run[], from = 0): Run {
+ const sorted = [...results.slice(from)].sort(
+ (a, b) => a.domContentLoaded - b.domContentLoaded,
+ );
+ return sorted[Math.floor(sorted.length / 2)];
+}
+
+/** The readings one load produced, in the order a user meets them. */
+function timings(run: Run) {
+ const ms = (value: number) => Number(value.toFixed(1));
+ return {
+ ttfbMs: ms(run.ttfb),
+ firstContentfulPaintMs: ms(run.firstContentfulPaint),
+ domContentLoadedMs: ms(run.domContentLoaded),
+ appMountedMs: ms(run.appMounted),
+ largestContentfulPaintMs: ms(run.largestContentfulPaint),
+ pageReadyMs: ms(run.pageReady),
+ loadMs: ms(run.load),
+ };
+}
+
+(async () => {
+ const chrome = await launchChrome();
+ const results = [];
+
+ for (let run = 0; run < runs; run++) {
+ const metrics = await loadOnce();
+ if (metrics) {
+ results.push(metrics);
+ }
+ }
+
+ chrome.kill();
+
+ if (results.length === 0) {
+ console.error("no runs produced a reading");
+ process.exit(1);
+ }
+
+ // Written with a callback rather than console.log so the process cannot exit
+ // with the JSON still buffered in a pipe.
+ process.stdout.write(
+ JSON.stringify(
+ {
+ url,
+ runs: results.length,
+ cpuThrottle,
+ network: mbps > 0 ? `${mbps} Mbps` : "unthrottled",
+ cache: keepCache ? "kept between runs" : "disabled",
+ scripts: results[0].scriptCount,
+ scriptKb: Number((results[0].scriptBytes / 1024).toFixed(1)),
+ // Each of the three is one load. A zero in a reading means the browser
+ // or the route never reported that one.
+ median: timings(representative(results)),
+ // The second visit happens once per browser profile, so it is the one
+ // run itself rather than a run chosen out of several.
+ secondLoad: results.length > 1 ? timings(results[1]) : null,
+ // The first load of a cache-kept series still fills an empty cache, so
+ // the steady state starts at the third.
+ steady: results.length > 2 ? timings(representative(results, 2)) : null,
+ everyRunMs: results.map((result) =>
+ Math.round(result.domContentLoaded),
+ ),
+ },
+ null,
+ 2,
+ ) + "\n",
+ () => process.exit(0),
+ );
+})();
diff --git a/frontend/test/bench/serve.ts b/frontend/test/bench/serve.ts
new file mode 100644
index 00000000000..194042cd17a
--- /dev/null
+++ b/frontend/test/bench/serve.ts
@@ -0,0 +1,122 @@
+/* eslint-env node */
+/* eslint-disable no-console -- printing the result is what this script is for */
+
+/**
+ * Serves a built `resources/frontend_client` tree the way the backend does, so
+ * a bundle can be loaded in a browser without running Metabase.
+ *
+ * The index template's placeholders are filled in, hashed assets are immutable
+ * so a second visit reuses them, and a `.br` beside a file is served when the
+ * client accepts it. API calls answer `{}`. The app fails to render on that, and
+ * that is fine: every number this harness reports lands before the first API
+ * response matters.
+ */
+import fs from "node:fs";
+import http, { type ServerResponse } from "node:http";
+import path from "node:path";
+
+const root = process.argv[2];
+const port = Number(process.argv[3] || 8099);
+
+if (!root) {
+ console.error("usage: bun serve.ts <resources/frontend_client dir> [port]");
+ process.exit(1);
+}
+
+const BOOTSTRAP = JSON.stringify({
+ "site-locale": "en",
+ "available-locales": [["en", "English"]],
+ "token-features": {},
+ version: { tag: "bench" },
+});
+
+const TEMPLATE_VALUES = {
+ language: "en",
+ baseHref: "/",
+ uri: "/",
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- the template wants the default app name
+ applicationName: "Metabase",
+ favicon: "app/assets/img/favicon.ico",
+ embedCode: "",
+ routePreloads: "",
+ bootstrapJSON: BOOTSTRAP,
+ userLocalizationJSON: "{}",
+ siteLocalizationJSON: "{}",
+ userColorScheme: '"light"',
+ nonceJSON: '""',
+ bootstrapJS: "",
+ assetOnErrorJS: "",
+};
+
+const CONTENT_TYPES = {
+ ".css": "text/css",
+ ".html": "text/html",
+ ".js": "application/javascript",
+ ".json": "application/json",
+ ".svg": "image/svg+xml",
+};
+
+const IMMUTABLE = "public, max-age=31536000, immutable";
+
+function serveTemplate(file: string, res: ServerResponse) {
+ const html = Object.entries(TEMPLATE_VALUES).reduce(
+ (result, [key, value]) => result.replaceAll(`{{{${key}}}}`, value),
+ fs.readFileSync(file, "utf8"),
+ );
+
+ res.writeHead(200, {
+ "content-type": "text/html",
+ "cache-control": "no-store",
+ });
+ res.end(html);
+}
+
+http
+ .createServer((req, res) => {
+ const url = (req.url ?? "/").split("?")[0];
+
+ if (url.startsWith("/api/")) {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end("{}");
+ return;
+ }
+
+ const relative = url === "/" ? "/index.html" : url;
+ const file = path.join(root, relative);
+
+ if (relative === "/index.html") {
+ serveTemplate(file, res);
+ return;
+ }
+
+ const contentType =
+ // An unknown extension falls through to the default below.
+ CONTENT_TYPES[path.extname(relative) as keyof typeof CONTENT_TYPES] ||
+ "application/octet-stream";
+ const acceptsBrotli = (req.headers["accept-encoding"] || "").includes("br");
+
+ if (acceptsBrotli && fs.existsSync(`${file}.br`)) {
+ res.writeHead(200, {
+ "content-type": contentType,
+ "content-encoding": "br",
+ "cache-control": IMMUTABLE,
+ });
+ res.end(fs.readFileSync(`${file}.br`));
+ return;
+ }
+
+ if (!fs.existsSync(file)) {
+ res.writeHead(404);
+ res.end();
+ return;
+ }
+
+ res.writeHead(200, {
+ "content-type": contentType,
+ "cache-control": IMMUTABLE,
+ });
+ res.end(fs.readFileSync(file));
+ })
+ .listen(port, () =>
+ console.log(`serving ${root} on http://127.0.0.1:${port}`),
+ );
diff --git a/frontend/test/bench/sign-in.ts b/frontend/test/bench/sign-in.ts
new file mode 100644
index 00000000000..b9f2cf74292
--- /dev/null
+++ b/frontend/test/bench/sign-in.ts
@@ -0,0 +1,81 @@
+/* eslint-env node */
+
+/**
+ * Waits for a Metabase to come up, signs in, and prints the session token.
+ *
+ * A blank instance has no user, so the first run creates one from the setup
+ * token. A later run against the same instance signs that user in instead,
+ * which is what makes this safe to run again while a backend is still up.
+ *
+ * The benchmark needs a signed-in document, not content. Nothing here creates a
+ * dashboard or a question, because `index.html` is built from settings and the
+ * user alone. See `template-parameters` in `metabase.server.routes.index`.
+ */
+
+const url = process.argv[2] || "http://localhost:4000";
+
+const EMAIL = "[email protected]";
+// The setup endpoint rejects a password that is short or common.
+const PASSWORD = "Benchmark-Passw0rd!";
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+async function waitUntilReady() {
+ for (let attempt = 0; attempt < 300; attempt++) {
+ try {
+ const response = await fetch(`${url}/api/health`);
+ const { status } = await response.json();
+ if (status === "ok") {
+ return;
+ }
+ } catch {
+ // Not listening yet.
+ }
+ await sleep(1000);
+ }
+ throw new Error(`No instance came up on ${url}`);
+}
+
+async function post(path: string, body: unknown) {
+ const response = await fetch(`${url}${path}`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!response.ok) {
+ throw new Error(
+ `POST ${path} failed: ${response.status} ${await response.text()}`,
+ );
+ }
+ return response.json();
+}
+
+(async () => {
+ await waitUntilReady();
+
+ const response = await fetch(`${url}/api/session/properties`);
+ const properties = await response.json();
+ // `setup-token` outlives the setup that used it, so it cannot say whether
+ // this instance is blank. `has-user-setup` can.
+ const isBlank = !properties["has-user-setup"];
+
+ // Both endpoints answer `{id: <session-key>}`.
+ const { id } = isBlank
+ ? await post("/api/setup", {
+ token: properties["setup-token"],
+ user: {
+ email: EMAIL,
+ password: PASSWORD,
+ first_name: "Bench",
+ last_name: "Mark",
+ },
+ prefs: { site_name: "Bench" },
+ })
+ : await post("/api/session", { username: EMAIL, password: PASSWORD });
+
+ console.error(isBlank ? "created the first user" : "signed the user in");
+ process.stdout.write(`${id}\n`);
+})().catch((error) => {
+ console.error(error.message);
+ process.exit(1);
+});