Skip to content

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

Use eng stats api for data uploads (#79929)

Ryan Laurie9b71465b85e8
diff --git a/.github/scripts/bundle-size-stats-prepare.js b/.github/scripts/bundle-size-stats-prepare.js
deleted file mode 100644
index 9389b156ec9..00000000000
--- a/.github/scripts/bundle-size-stats-prepare.js
+++ /dev/null
@@ -1,152 +0,0 @@
-/* eslint-disable import/no-commonjs */
-// Prepares the rows the bundle-size stats logger uploads to stats.metabase.com.
-//
-// For each measured (bundle, kind) it computes the delta — raw, gzipped and
-// brotli (as-served) bytes plus percent — against the previously *plotted* data
-// point (restored from a rolling cache), so the deltas can be charted directly.
-// It also decides whether this commit is worth recording at all: a point is kept
-// when the as-served size moved by at least MIN_DELTA_PERCENT, or when a new
-// bundle/kind appears. Only master builds run through here — releases form
-// non-linear lines whose deltas are meaningless, so they're not recorded (their
-// historical sizes are backfilled separately).
-//
-// buildStatsRows is pure (data in, data out) so it can be unit-tested; main()
-// is the thin I/O wrapper that reads env/files and writes the rows, cache and
-// step outputs.
-const fs = require("fs");
-const path = require("path");
-
-const deltaPercent = (current, base) =>
- base ? Math.round(((current - base) * 10000) / base) / 100 : "";
-
-/**
- * Turn the current measurements + the last plotted point into upload rows, the
- * slim cache rows for the next diff, and the keep/skip decision.
- *
- * The significance threshold tracks the as-served size: brotli where the build
- * ships a precompressed .br, otherwise gzip. Current measurements always carry
- * brotliBytes (estimated when no .br shipped), but a cached base point recorded
- * before brotli logging may not, so the delta still falls back to gzip per row.
- */
-function buildStatsRows({ measurements, previous, threshold, date, commit, commitMessage, version }) {
- const previousOf = (bundle, kind) => previous.find(row => row.bundle === bundle && row.kind === kind);
-
- let maxServedDeltaPercent = 0;
- let hasNewSeries = false;
-
- const rows = measurements.map(measurement => {
- const base = previousOf(measurement.bundle, measurement.kind);
- const hasBrotli = measurement.brotliBytes != null && base?.brotliBytes != null;
- const gzipDeltaPercent = deltaPercent(measurement.gzipBytes, base?.gzipBytes);
- const brotliDeltaPercent = hasBrotli ? deltaPercent(measurement.brotliBytes, base.brotliBytes) : "";
- if (!base) {
- hasNewSeries = true;
- } else {
- const servedDeltaPercent = hasBrotli ? brotliDeltaPercent : gzipDeltaPercent;
- maxServedDeltaPercent = Math.max(maxServedDeltaPercent, Math.abs(servedDeltaPercent));
- }
- return {
- "Date": date,
- "Version": version,
- "Commit": commit,
- "Bundle": measurement.bundle,
- "Kind": measurement.kind, // "initial" or "total"
- // The stats table carries a free-text Description column; append-csv
- // requires every table column to be present. Populate it with the commit
- // subject so the chart's points are self-describing.
- "Description": commitMessage,
- "Raw bytes": measurement.rawBytes,
- "Gzip bytes": measurement.gzipBytes,
- "Brotli bytes": measurement.brotliBytes, // as-served (shipped .br, else estimated)
- "File count": measurement.fileCount,
- "Raw bytes delta": base ? measurement.rawBytes - base.rawBytes : "",
- "Gzip bytes delta": base ? measurement.gzipBytes - base.gzipBytes : "",
- "Brotli bytes delta": hasBrotli ? measurement.brotliBytes - base.brotliBytes : "",
- "Raw delta %": deltaPercent(measurement.rawBytes, base?.rawBytes),
- "Gzip delta %": gzipDeltaPercent,
- "Brotli delta %": brotliDeltaPercent,
- };
- });
-
- const firstPoint = previous.length === 0;
- const significant = firstPoint || hasNewSeries || maxServedDeltaPercent >= threshold;
-
- // Slim rows the next run diffs against. The workflow only persists this to the
- // cache when we actually push, so the cached reference always stays the last
- // *plotted* point (cumulative drift is caught).
- const cacheRows = measurements.map(({ bundle, kind, rawBytes, gzipBytes, brotliBytes }) => ({
- bundle,
- kind,
- rawBytes,
- gzipBytes,
- brotliBytes,
- }));
-
- const reason = firstPoint
- ? "first point"
- : hasNewSeries
- ? "new bundle/kind series"
- : `max served Δ ${maxServedDeltaPercent.toFixed(2)}% (threshold ${threshold}%)`;
-
- return { rows, cacheRows, significant, reason, maxServedDeltaPercent, firstPoint, hasNewSeries };
-}
-
-module.exports = { buildStatsRows };
-
-const readJson = filePath => (filePath && fs.existsSync(filePath) ? JSON.parse(fs.readFileSync(filePath, "utf8")) : null);
-const writeJson = (filePath, value) => {
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(value));
-};
-const setOutput = (env, name, value) => {
- if (env.GITHUB_OUTPUT) {
- fs.appendFileSync(env.GITHUB_OUTPUT, `${name}=${value}\n`);
- }
-};
-
-// version.properties (extracted from the uberjar) carries the build's tag.
-// Non-release (master) builds report tag=vUNKNOWN, so leave Version empty there.
-function readVersion(versionPropsPath) {
- const raw =
- versionPropsPath && fs.existsSync(versionPropsPath)
- ? (fs.readFileSync(versionPropsPath, "utf8").match(/^tag=(.*)$/m)?.[1]?.trim() ?? "")
- : "";
- return raw === "vUNKNOWN" ? "" : raw;
-}
-
-function main() {
- const env = process.env;
-
- const measurements = readJson(env.CURRENT);
- if (!Array.isArray(measurements) || measurements.length === 0) {
- console.error(`::error::No bundle measurements found at ${env.CURRENT}`);
- process.exit(1);
- }
-
- const result = buildStatsRows({
- measurements,
- // The last plotted point, as slim rows: [{ bundle, kind, rawBytes, gzipBytes, brotliBytes }].
- previous: readJson(env.LAST) || [],
- threshold: Number(env.MIN_DELTA_PERCENT ?? 1),
- date: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
- commit: (env.HEAD_SHA || "").slice(0, 12),
- commitMessage: (env.COMMIT_MESSAGE || "").split("\n")[0], // subject line only
- version: readVersion(env.VERSION_PROPS),
- });
-
- writeJson(env.ROWS_OUT, result.rows);
- writeJson(env.CACHE_OUT, result.cacheRows);
-
- console.log(`${result.significant ? "RECORD" : "SKIP"} — ${result.reason}`);
-
- setOutput(env, "significant", result.significant ? "true" : "false");
- setOutput(
- env,
- "max_delta_percent",
- result.firstPoint || result.hasNewSeries ? "" : result.maxServedDeltaPercent.toFixed(2),
- );
-}
-
-if (require.main === module) {
- main();
-}
diff --git a/.github/scripts/bundle-size-stats-prepare.ts b/.github/scripts/bundle-size-stats-prepare.ts
new file mode 100644
index 00000000000..8d28b6f1419
--- /dev/null
+++ b/.github/scripts/bundle-size-stats-prepare.ts
@@ -0,0 +1,225 @@
+// Prepares the rows the bundle-size stats logger imports into eng-stats-importer.
+//
+// For each measured (bundle, kind) it computes the delta — raw, gzipped and
+// brotli (as-served) bytes plus percent — against the previously *plotted* data
+// point (restored from a rolling cache), so the deltas can be charted directly.
+// It also decides whether this commit is worth recording at all: a point is kept
+// when the as-served size moved by at least MIN_DELTA_PERCENT, or when a new
+// bundle/kind appears. Only master builds run through here — releases form
+// non-linear lines whose deltas are meaningless, so they're not recorded (their
+// historical sizes are backfilled separately).
+//
+// buildStatsRows is pure (data in, data out) so it can be unit-tested; main()
+// is the thin I/O wrapper that reads env/files and writes the rows, cache and
+// step outputs.
+import {
+ appendFileSync,
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ writeFileSync,
+} from "node:fs";
+import { dirname } from "node:path";
+
+/** One measurement emitted by measure-bundle-sizes. */
+export interface Measurement {
+ bundle: string;
+ kind: "initial" | "total";
+ rawBytes: number;
+ gzipBytes: number;
+ brotliBytes: number;
+ fileCount: number;
+}
+
+/**
+ * The slim row cached between runs, holding the last *plotted* point.
+ * `brotliBytes` is optional because a point cached before brotli logging
+ * landed does not carry it — see buildStatsRows' per-row gzip fallback.
+ */
+export type CacheRow = Pick<Measurement, "bundle" | "kind" | "rawBytes" | "gzipBytes"> & {
+ brotliBytes?: number;
+};
+
+export interface BuildStatsRowsInput {
+ measurements: Measurement[];
+ previous: CacheRow[];
+ threshold: number;
+ date: string;
+ commit: string;
+ commitMessage: string;
+ version: string;
+}
+
+/** An upload row, keyed by the importer's column display names. */
+export type StatsRow = Record<string, string | number | null>;
+
+export interface BuildStatsRowsResult {
+ rows: StatsRow[];
+ cacheRows: CacheRow[];
+ significant: boolean;
+ reason: string;
+ maxServedDeltaPercent: number;
+ firstPoint: boolean;
+ hasNewSeries: boolean;
+}
+
+// null, not "", for an absent delta: the stats importer coerces values
+// strictly and rejects "" for a numeric column.
+const deltaPercent = (current: number, base: number | undefined | null): number | null =>
+ base ? Math.round(((current - base) * 10000) / base) / 100 : null;
+
+/**
+ * Turn the current measurements + the last plotted point into upload rows, the
+ * slim cache rows for the next diff, and the keep/skip decision.
+ *
+ * The significance threshold tracks the as-served size: brotli where the build
+ * ships a precompressed .br, otherwise gzip. Current measurements always carry
+ * brotliBytes (estimated when no .br shipped), but a cached base point recorded
+ * before brotli logging may not, so the delta still falls back to gzip per row.
+ */
+export function buildStatsRows({
+ measurements,
+ previous,
+ threshold,
+ date,
+ commit,
+ commitMessage,
+ version,
+}: BuildStatsRowsInput): BuildStatsRowsResult {
+ const previousOf = (bundle: string, kind: string) =>
+ previous.find((row) => row.bundle === bundle && row.kind === kind);
+
+ let maxServedDeltaPercent = 0;
+ let hasNewSeries = false;
+
+ const rows = measurements.map((measurement): StatsRow => {
+ const base = previousOf(measurement.bundle, measurement.kind);
+ // Non-null only when BOTH sides carry brotli: a point cached before brotli
+ // logging landed has none, and that row falls back to the gzip delta.
+ const baseBrotli =
+ measurement.brotliBytes != null && base?.brotliBytes != null ? base.brotliBytes : null;
+ const gzipDeltaPercent = deltaPercent(measurement.gzipBytes, base?.gzipBytes);
+ const brotliDeltaPercent =
+ baseBrotli != null ? deltaPercent(measurement.brotliBytes, baseBrotli) : null;
+ if (!base) {
+ hasNewSeries = true;
+ } else {
+ const servedDeltaPercent = baseBrotli != null ? brotliDeltaPercent : gzipDeltaPercent;
+ maxServedDeltaPercent = Math.max(maxServedDeltaPercent, Math.abs(servedDeltaPercent ?? 0));
+ }
+ return {
+ Date: date,
+ Version: version,
+ Commit: commit,
+ Bundle: measurement.bundle,
+ Kind: measurement.kind, // "initial" or "total"
+ // The stats table carries a free-text Description column. Populate it
+ // with the commit subject so the chart's points are self-describing.
+ Description: commitMessage,
+ "Raw bytes": measurement.rawBytes,
+ "Gzip bytes": measurement.gzipBytes,
+ "Brotli bytes": measurement.brotliBytes, // as-served (shipped .br, else estimated)
+ "File count": measurement.fileCount,
+ "Raw bytes delta": base ? measurement.rawBytes - base.rawBytes : null,
+ "Gzip bytes delta": base ? measurement.gzipBytes - base.gzipBytes : null,
+ "Brotli bytes delta": baseBrotli != null ? measurement.brotliBytes - baseBrotli : null,
+ "Raw delta %": deltaPercent(measurement.rawBytes, base?.rawBytes),
+ "Gzip delta %": gzipDeltaPercent,
+ "Brotli delta %": brotliDeltaPercent,
+ };
+ });
+
+ const firstPoint = previous.length === 0;
+ const significant = firstPoint || hasNewSeries || maxServedDeltaPercent >= threshold;
+
+ // Slim rows the next run diffs against. The workflow only persists this to the
+ // cache when we actually push, so the cached reference always stays the last
+ // *plotted* point (cumulative drift is caught).
+ const cacheRows = measurements.map(
+ ({ bundle, kind, rawBytes, gzipBytes, brotliBytes }): CacheRow => ({
+ bundle,
+ kind,
+ rawBytes,
+ gzipBytes,
+ brotliBytes,
+ }),
+ );
+
+ const reason = firstPoint
+ ? "first point"
+ : hasNewSeries
+ ? "new bundle/kind series"
+ : `max served Δ ${maxServedDeltaPercent.toFixed(2)}% (threshold ${threshold}%)`;
+
+ return {
+ rows,
+ cacheRows,
+ significant,
+ reason,
+ maxServedDeltaPercent,
+ firstPoint,
+ hasNewSeries,
+ };
+}
+
+const readJson = <T,>(filePath: string | undefined): T | null =>
+ filePath && existsSync(filePath) ? (JSON.parse(readFileSync(filePath, "utf8")) as T) : null;
+
+const writeJson = (filePath: string, value: unknown) => {
+ mkdirSync(dirname(filePath), { recursive: true });
+ writeFileSync(filePath, JSON.stringify(value));
+};
+
+const setOutput = (name: string, value: string) => {
+ if (process.env.GITHUB_OUTPUT) {
+ appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`);
+ }
+};
+
+// version.properties (extracted from the uberjar) carries the build's tag.
+// Non-release (master) builds report tag=vUNKNOWN, so leave Version empty there.
+function readVersion(versionPropsPath: string | undefined): string {
+ const raw =
+ versionPropsPath && existsSync(versionPropsPath)
+ ? (readFileSync(versionPropsPath, "utf8").match(/^tag=(.*)$/m)?.[1]?.trim() ?? "")
+ : "";
+ return raw === "vUNKNOWN" ? "" : raw;
+}
+
+export function main() {
+ const env = process.env;
+
+ const measurements = readJson<Measurement[]>(env.CURRENT);
+ if (!Array.isArray(measurements) || measurements.length === 0) {
+ console.error(`::error::No bundle measurements found at ${env.CURRENT}`);
+ process.exit(1);
+ }
+
+ const result = buildStatsRows({
+ measurements,
+ // The last plotted point, as slim rows: [{ bundle, kind, rawBytes, gzipBytes, brotliBytes }].
+ previous: readJson<CacheRow[]>(env.LAST) || [],
+ threshold: Number(env.MIN_DELTA_PERCENT ?? 1),
+ date: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
+ commit: (env.HEAD_SHA || "").slice(0, 12),
+ commitMessage: (env.COMMIT_MESSAGE || "").split("\n")[0], // subject line only
+ version: readVersion(env.VERSION_PROPS),
+ });
+
+ writeJson(env.ROWS_OUT!, result.rows);
+ writeJson(env.CACHE_OUT!, result.cacheRows);
+
+ console.log(`${result.significant ? "RECORD" : "SKIP"} — ${result.reason}`);
+
+ setOutput("significant", result.significant ? "true" : "false");
+ setOutput(
+ "max_delta_percent",
+ result.firstPoint || result.hasNewSeries ? "" : result.maxServedDeltaPercent.toFixed(2),
+ );
+}
+
+// Only run the I/O wrapper when invoked directly, so importing buildStatsRows
+// (from the spec) has no side effects.
+if ((import.meta as ImportMeta & { main?: boolean }).main) {
+ main();
+}
diff --git a/.github/scripts/bundle-size-stats-prepare.unit.spec.js b/.github/scripts/bundle-size-stats-prepare.unit.spec.ts
similarity index 76%
rename from .github/scripts/bundle-size-stats-prepare.unit.spec.js
rename to .github/scripts/bundle-size-stats-prepare.unit.spec.ts
index 72162476439..0ed112aab44 100644
--- a/.github/scripts/bundle-size-stats-prepare.unit.spec.js
+++ b/.github/scripts/bundle-size-stats-prepare.unit.spec.ts
@@ -1,7 +1,16 @@
-const { buildStatsRows } = require("./bundle-size-stats-prepare");
+import {
+ buildStatsRows,
+ type CacheRow,
+ type Measurement,
+} from "./bundle-size-stats-prepare";
-const meta = { date: "2026-06-30", commit: "abc123", commitMessage: "Fix the thing (#123)", version: "" };
-const measurement = (over = {}) => ({
+const meta = {
+ date: "2026-06-30",
+ commit: "abc123",
+ commitMessage: "Fix the thing (#123)",
+ version: "",
+};
+const measurement = (over: Partial<Measurement> = {}): Measurement => ({
bundle: "embedding-sdk-chunked",
kind: "total",
rawBytes: 1000,
@@ -23,8 +32,8 @@ describe("buildStatsRows", () => {
expect(result.firstPoint).toBe(true);
expect(result.significant).toBe(true);
expect(result.reason).toBe("first point");
- expect(result.rows[0]["Gzip bytes delta"]).toBe("");
- expect(result.rows[0]["Brotli delta %"]).toBe("");
+ expect(result.rows[0]["Gzip bytes delta"]).toBeNull();
+ expect(result.rows[0]["Brotli delta %"]).toBeNull();
expect(result.rows[0]["Description"]).toBe("Fix the thing (#123)");
expect(result.cacheRows[0]).toEqual({
bundle: "embedding-sdk-chunked",
@@ -49,7 +58,15 @@ describe("buildStatsRows", () => {
});
it("gates significance on the brotli (as-served) delta when both sides have it", () => {
- const previous = [{ bundle: "embedding-sdk-chunked", kind: "total", rawBytes: 1000, gzipBytes: 400, brotliBytes: 300 }];
+ const previous: CacheRow[] = [
+ {
+ bundle: "embedding-sdk-chunked",
+ kind: "total",
+ rawBytes: 1000,
+ gzipBytes: 400,
+ brotliBytes: 300,
+ },
+ ];
const big = buildStatsRows({
...meta,
@@ -75,13 +92,14 @@ describe("buildStatsRows", () => {
const result = buildStatsRows({
...meta,
measurements: [measurement({ gzipBytes: 440, brotliBytes: 300 })], // gzip +10%
+ // No brotliBytes: this point was cached before brotli logging landed.
previous: [{ bundle: "embedding-sdk-chunked", kind: "total", rawBytes: 1000, gzipBytes: 400 }],
threshold: 1,
});
expect(result.maxServedDeltaPercent).toBeCloseTo(10);
expect(result.significant).toBe(true);
- expect(result.rows[0]["Brotli bytes delta"]).toBe(""); // no base brotli to diff against
+ expect(result.rows[0]["Brotli bytes delta"]).toBeNull(); // no base brotli to diff against
expect(result.rows[0]["Gzip delta %"]).toBeCloseTo(10);
});
});
diff --git a/.github/scripts/csv-to-mb.js b/.github/scripts/csv-to-mb.js
deleted file mode 100644
index a9f024db823..00000000000
--- a/.github/scripts/csv-to-mb.js
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * jsonData must be in the format:
- * [
- * { column1: value1, column2: value2, ... },
- * { column1: value3, column2: value4, ... },
- * ...
- * ]
- */
-function jsonToCsvFormData(jsonData) {
- const formData = new FormData();
- const csvHeader = Object.keys(jsonData[0]).join(',') + '\n';
- const csvContent = jsonData.map(row =>
- Object.values(row).map(value => `"${String(value).replace(/"/g, '""')}"`).join(',')
- ).join('\n');
-
- const blob = new Blob([csvHeader + csvContent], { type: 'text/csv' });
- formData.append('file', blob, 'data.csv');
-
- return formData;
-}
-
-// Transient failures worth retrying: throttling and server-side errors. A 4xx
-// (bad request, auth) won't succeed on retry, so those fail fast.
-const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
-
-class UploadError extends Error {
- constructor(message, { retryable }) {
- super(message);
- this.retryable = retryable;
- }
-}
-
-async function attemptUpload(url, jsonData, timeoutMs) {
- let response;
- try {
- response = await fetch(url, {
- method: 'POST',
- headers: {
- "x-api-key": process.env.API_KEY
- },
- // Rebuilt per attempt: a consumed request body can't be reused.
- body: jsonToCsvFormData(jsonData),
- // Without this the request can hang indefinitely on a stalled server,
- // eating the whole job timeout. An abort surfaces below as a retryable
- // network error, so it retries with backoff instead.
- signal: AbortSignal.timeout(timeoutMs)
- });
- } catch (networkError) {
- throw new UploadError(networkError.message, { retryable: true });
- }
-
- if (response.ok) {
- return;
- }
-
- const body = await response.text().catch(() => '');
- throw new UploadError(
- `Upload failed: ${response.status} ${response.statusText} ${body}`.trim(),
- { retryable: RETRYABLE_STATUS.has(response.status) }
- );
-}
-
-const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
-
-/**
- * Uploads jsonData as CSV, retrying transient API errors with exponential
- * backoff. `retries` is the number of extra attempts after the first (so the
- * default 2 means up to 3 tries). `timeoutMs` is a per-attempt total deadline
- * (default 60s) that aborts a stalled request. Throws the last error once
- * attempts are exhausted or the error is non-retryable.
- */
-async function uploadCsvToMb({ baseUrl, tableId, jsonData, mode = 'append', retries = 2, retryDelayMs = 1000, timeoutMs = 60_000 }) {
- const operation = mode === 'replace' ? 'replace-csv' : 'append-csv';
- const url = `${baseUrl}/api/table/${tableId}/${operation}`;
-
- for (let attempt = 0; ; attempt++) {
- try {
- await attemptUpload(url, jsonData, timeoutMs);
- return { success: true };
- } catch (error) {
- if (!error.retryable || attempt >= retries) {
- throw error;
- }
- const delay = retryDelayMs * 2 ** attempt;
- console.warn(`Upload attempt ${attempt + 1} failed (${error.message}); retrying in ${delay}ms`);
- await sleep(delay);
- }
- }
-}
-
-module.exports = { uploadCsvToMb };
diff --git a/.github/scripts/csv-to-mb.unit.spec.js b/.github/scripts/csv-to-mb.unit.spec.js
deleted file mode 100644
index 28ebf81913a..00000000000
--- a/.github/scripts/csv-to-mb.unit.spec.js
+++ /dev/null
@@ -1,50 +0,0 @@
-const { uploadCsvToMb } = require("./csv-to-mb");
-
-const ok = () => ({ ok: true });
-const fail = status => ({ ok: false, status, statusText: "err", text: async () => "" });
-
-const upload = (over = {}) =>
- uploadCsvToMb({
- baseUrl: "https://stats.example.com",
- tableId: 1,
- jsonData: [{ a: 1 }],
- retryDelayMs: 1,
- ...over,
- });
-
-describe("uploadCsvToMb retries", () => {
- afterEach(() => {
- delete global.fetch;
- });
-
- it("retries transient server errors then succeeds", async () => {
- global.fetch = jest.fn().mockResolvedValueOnce(fail(503)).mockResolvedValueOnce(fail(500)).mockResolvedValueOnce(ok());
-
- await expect(upload({ retries: 2 })).resolves.toEqual({ success: true });
- expect(global.fetch).toHaveBeenCalledTimes(3);
- });
-
- it("retries network errors", async () => {
- global.fetch = jest
- .fn()
- .mockRejectedValueOnce(new Error("ECONNRESET"))
- .mockResolvedValueOnce(ok());
-
- await expect(upload({ retries: 2 })).resolves.toEqual({ success: true });
- expect(global.fetch).toHaveBeenCalledTimes(2);
- });
-
- it("gives up after exhausting retries and throws the last error", async () => {
- global.fetch = jest.fn().mockResolvedValue(fail(500));
-
- await expect(upload({ retries: 2 })).rejects.toThrow("Upload failed: 500");
- expect(global.fetch).toHaveBeenCalledTimes(3); // 1 initial + 2 retries
- });
-
- it("does not retry a non-transient 4xx", async () => {
- global.fetch = jest.fn().mockResolvedValue(fail(400));
-
- await expect(upload({ retries: 2 })).rejects.toThrow("Upload failed: 400");
- expect(global.fetch).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/.github/scripts/stats-import.ts b/.github/scripts/stats-import.ts
new file mode 100644
index 00000000000..9cb37ff70f3
--- /dev/null
+++ b/.github/scripts/stats-import.ts
@@ -0,0 +1,140 @@
+// Pushes stats rows to eng-stats-importer, which writes them to Postgres.
+//
+// The importer's origin comes from ENG_STATS_URL and its key from API_KEY, both
+// repository secrets — this repo is public, so neither is hardcoded here. Visit
+// the importer to see the tables and mint keys.
+
+// Transient failures worth retrying: throttling and server-side errors. A 4xx
+// (bad request, auth, unknown table) won't succeed on retry, so those fail fast.
+const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
+
+/**
+ * One row, keyed by column. Values are `unknown` rather than a scalar union
+ * because a `json` column takes arbitrary nested data.
+ */
+export type StatsRow = Record<string, unknown>;
+
+export interface ImportStatsOptions {
+ /** Table name as it appears in `/api/import/{table}`, e.g. `emotion_files`. */
+ table: string;
+ rows: StatsRow[];
+ /** Importer origin. Defaults to ENG_STATS_URL. */
+ baseUrl?: string;
+ /** Extra attempts after the first, so the default 2 means up to 3 tries. */
+ retries?: number;
+ retryDelayMs?: number;
+ /** Per-attempt total deadline; aborts a stalled request. */
+ timeoutMs?: number;
+}
+
+export interface ImportStatsResult {
+ success: true;
+ inserted?: number;
+ /** Payload keys with no matching column, when `ignoreUnknown` is in play. */
+ ignoredKeys?: string[];
+}
+
+class ImportError extends Error {
+ retryable: boolean;
+
+ constructor(message: string, { retryable }: { retryable: boolean }) {
+ super(message);
+ this.retryable = retryable;
+ }
+}
+
+async function attemptImport(
+ url: string,
+ rows: StatsRow[],
+ timeoutMs: number,
+): Promise<ImportStatsResult> {
+ let response: Response;
+ try {
+ response = await fetch(url, {
+ method: "PUT",
+ headers: {
+ "x-api-key": process.env.API_KEY ?? "",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(rows),
+ // Without this the request can hang indefinitely on a stalled server,
+ // eating the whole job timeout. An abort surfaces below as a retryable
+ // network error, so it retries with backoff instead.
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ } catch (networkError) {
+ const message =
+ networkError instanceof Error ? networkError.message : String(networkError);
+ throw new ImportError(message, { retryable: true });
+ }
+
+ if (!response.ok) {
+ // Failures carry an `{ error }` body naming the offending row and column,
+ // which is the only way to tell a type mismatch from a typo'd key.
+ const body = await response.text().catch(() => "");
+ throw new ImportError(
+ `Import failed: ${response.status} ${response.statusText} ${body}`.trim(),
+ { retryable: RETRYABLE_STATUS.has(response.status) },
+ );
+ }
+
+ // Best-effort: the row count is for logging, so a body that doesn't parse
+ // shouldn't turn a successful import into a failure.
+ const result = (await response.json().catch(() => ({}))) as {
+ inserted?: number;
+ ignoredKeys?: string[];
+ };
+ return { success: true, inserted: result.inserted, ignoredKeys: result.ignoredKeys };
+}
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Imports `rows` into the `table` table, retrying transient API errors with
+ * exponential backoff.
+ *
+ * Keys are matched leniently against the table's columns -- `Emotion Files`,
+ * `emotionFiles` and `emotion_files` all land in `emotion_files` -- but values
+ * are matched strictly, and a key matching no column is an error rather than a
+ * silent drop. Rows are appended; the importer has no replace mode.
+ *
+ * Throws the last error once attempts are exhausted or the error is
+ * non-retryable.
+ */
+export async function importStats({
+ table,
+ rows,
+ baseUrl = process.env.ENG_STATS_URL,
+ retries = 2,
+ retryDelayMs = 1000,
+ timeoutMs = 60_000,
+}: ImportStatsOptions): Promise<ImportStatsResult> {
+ // The importer accepts an empty payload, but there's no point spending a
+ // request (and a rate-limit slot) to insert nothing.
+ if (rows.length === 0) {
+ return { success: true, inserted: 0 };
+ }
+
+ if (!baseUrl) {
+ throw new Error("ENG_STATS_URL is not set, so there is no importer to push to");
+ }
+
+ // Tolerate a trailing slash: the origin comes from a hand-entered secret.
+ const url = `${baseUrl.replace(/\/+$/, "")}/api/import/${table}`;
+
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await attemptImport(url, rows, timeoutMs);
+ } catch (error) {
+ const importError = error as ImportError;
+ if (!importError.retryable || attempt >= retries) {
+ throw error;
+ }
+ const delay = retryDelayMs * 2 ** attempt;
+ console.warn(
+ `Import attempt ${attempt + 1} failed (${importError.message}); retrying in ${delay}ms`,
+ );
+ await sleep(delay);
+ }
+ }
+}
diff --git a/.github/scripts/stats-import.unit.spec.ts b/.github/scripts/stats-import.unit.spec.ts
new file mode 100644
index 00000000000..5bef73ad531
--- /dev/null
+++ b/.github/scripts/stats-import.unit.spec.ts
@@ -0,0 +1,160 @@
+import { importStats } from "./stats-import";
+
+const ok = (body: unknown = { inserted: 1 }) => ({ ok: true, json: async () => body });
+const fail = (status: number) => ({
+ ok: false,
+ status,
+ statusText: "err",
+ text: async () => "",
+});
+
+const load = (over: Record<string, unknown> = {}) =>
+ importStats({
+ baseUrl: "https://stats.example.com",
+ table: "emotion_files",
+ rows: [{ a: 1 }],
+ retryDelayMs: 1,
+ ...over,
+ });
+
+describe("importStats requests", () => {
+ afterEach(() => {
+ // @ts-expect-error -- removing the stub the tests installed
+ delete global.fetch;
+ delete process.env.API_KEY;
+ delete process.env.ENG_STATS_URL;
+ });
+
+ it("defaults the origin to ENG_STATS_URL", async () => {
+ const fetchMock = jest.fn().mockResolvedValue(ok());
+ global.fetch = fetchMock;
+ process.env.ENG_STATS_URL = "https://importer.example.com";
+
+ await load({ baseUrl: undefined });
+
+ expect(fetchMock.mock.calls[0][0]).toBe(
+ "https://importer.example.com/api/import/emotion_files",
+ );
+ });
+
+ it("tolerates a trailing slash on the origin", async () => {
+ const fetchMock = jest.fn().mockResolvedValue(ok());
+ global.fetch = fetchMock;
+
+ await load({ baseUrl: "https://importer.example.com/" });
+
+ expect(fetchMock.mock.calls[0][0]).toBe(
+ "https://importer.example.com/api/import/emotion_files",
+ );
+ });
+
+ it("fails loudly when no origin is configured", async () => {
+ const fetchMock = jest.fn();
+ global.fetch = fetchMock;
+
+ await expect(load({ baseUrl: undefined })).rejects.toThrow("ENG_STATS_URL is not set");
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("PUTs the rows as JSON to the table's import endpoint", async () => {
+ const fetchMock = jest.fn().mockResolvedValue(ok());
+ global.fetch = fetchMock;
+ process.env.API_KEY = "secret";
+
+ await expect(load({ rows: [{ a: 1 }, { a: 2 }] })).resolves.toEqual({
+ success: true,
+ inserted: 1,
+ ignoredKeys: undefined,
+ });
+
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe("https://stats.example.com/api/import/emotion_files");
+ expect(options.method).toBe("PUT");
+ expect(options.headers).toMatchObject({
+ "x-api-key": "secret",
+ "content-type": "application/json",
+ });
+ expect(JSON.parse(options.body)).toEqual([{ a: 1 }, { a: 2 }]);
+ });
+
+ it("skips the request entirely when there are no rows", async () => {
+ const fetchMock = jest.fn();
+ global.fetch = fetchMock;
+
+ await expect(load({ rows: [] })).resolves.toEqual({ success: true, inserted: 0 });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("succeeds even if the response body does not parse", async () => {
+ global.fetch = jest.fn().mockResolvedValue({
+ ok: true,
+ json: async () => {
+ throw new Error("not json");
+ },
+ });
+
+ await expect(load()).resolves.toMatchObject({ success: true });
+ });
+});
+
+describe("importStats retries", () => {
+ afterEach(() => {
+ // @ts-expect-error -- removing the stub the tests installed
+ delete global.fetch;
+ });
+
+ it("retries transient server errors then succeeds", async () => {
+ const fetchMock = jest
+ .fn()
+ .mockResolvedValueOnce(fail(503))
+ .mockResolvedValueOnce(fail(500))
+ .mockResolvedValueOnce(ok());
+ global.fetch = fetchMock;
+
+ await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it("retries throttling", async () => {
+ const fetchMock = jest.fn().mockResolvedValueOnce(fail(429)).mockResolvedValueOnce(ok());
+ global.fetch = fetchMock;
+
+ await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("retries network errors", async () => {
+ const fetchMock = jest
+ .fn()
+ .mockRejectedValueOnce(new Error("ECONNRESET"))
+ .mockResolvedValueOnce(ok());
+ global.fetch = fetchMock;
+
+ await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("gives up after exhausting retries and throws the last error", async () => {
+ const fetchMock = jest.fn().mockResolvedValue(fail(500));
+ global.fetch = fetchMock;
+
+ await expect(load({ retries: 2 })).rejects.toThrow("Import failed: 500");
+ expect(fetchMock).toHaveBeenCalledTimes(3); // 1 initial + 2 retries
+ });
+
+ it("does not retry a non-transient 4xx", async () => {
+ const fetchMock = jest.fn().mockResolvedValue(fail(400));
+ global.fetch = fetchMock;
+
+ await expect(load({ retries: 2 })).rejects.toThrow("Import failed: 400");
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not retry an unknown table", async () => {
+ const fetchMock = jest.fn().mockResolvedValue(fail(404));
+ global.fetch = fetchMock;
+
+ await expect(load({ retries: 2 })).rejects.toThrow("Import failed: 404");
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/.github/scripts/upload-affected-tests-stats.js b/.github/scripts/upload-affected-tests-stats.ts
similarity index 71%
rename from .github/scripts/upload-affected-tests-stats.js
rename to .github/scripts/upload-affected-tests-stats.ts
index c062dcde3ae..1b276023c59 100644
--- a/.github/scripts/upload-affected-tests-stats.js
+++ b/.github/scripts/upload-affected-tests-stats.ts
@@ -1,11 +1,11 @@
// Appends the test-plan stats row produced by create-test-plan.ts to the
-// "FE Affected Tests" table on stats.metabase.com.
-// Reads STATS_JSON, PR_NUMBER, HEAD_SHA, BASE_SHA, API_KEY from env.
+// "FE Affected Tests" table in eng-stats-importer.
+// Reads STATS_JSON, TRIGGERED_BY, PR_NUMBER, HEAD_SHA, BASE_SHA, API_KEY from env.
-const { uploadCsvToMb } = require("./csv-to-mb.js");
+import type { TestPlanStats } from "./affected-tests";
+import { importStats } from "./stats-import";
-// "FE Affected Tests" uploaded table on stats.metabase.com.
-const TABLE_ID = 81818;
+const TABLE = "fe_affected_tests";
async function main() {
// create-test-plan doesn't always produce stats (e.g. on release branches
@@ -16,7 +16,7 @@ async function main() {
return;
}
- const s = JSON.parse(raw);
+ const s = JSON.parse(raw) as TestPlanStats;
console.log("stats", s);
const row = {
@@ -43,17 +43,15 @@ async function main() {
"Loki Stories All": s.loki_stories_all,
"Loki Stories To Run (Rules)": s.loki_stories_to_run_rules,
"Loki Stories To Run (Usage)": s.loki_stories_to_run_usage,
- "E2E Specs All": s.e2e_specs_all,
- "E2E Specs To Run (Rules)": s.e2e_specs_to_run_rules,
- "E2E Specs To Run (Usage)": s.e2e_specs_to_run_usage,
+ // Spelled as the column name rather than a display name: the importer
+ // splits a digit-then-capital run, so "E2E Specs All" would normalize to
+ // `e2_e_specs_all` instead of `e2e_specs_all`.
+ e2e_specs_all: s.e2e_specs_all,
+ e2e_specs_to_run_rules: s.e2e_specs_to_run_rules,
+ e2e_specs_to_run_usage: s.e2e_specs_to_run_usage,
};
- await uploadCsvToMb({
- baseUrl: "https://stats.metabase.com",
- tableId: TABLE_ID,
- jsonData: [row],
- mode: "append",
- });
+ await importStats({ table: TABLE, rows: [row] });
console.log("Data uploaded successfully");
}
diff --git a/.github/scripts/upload-bundle-size-stats.ts b/.github/scripts/upload-bundle-size-stats.ts
new file mode 100644
index 00000000000..47cec1ef15a
--- /dev/null
+++ b/.github/scripts/upload-bundle-size-stats.ts
@@ -0,0 +1,38 @@
+// Appends the measured bundle sizes (with deltas) to the "Bundle Sizes" table
+// in eng-stats-importer. Reads ROWS (a JSON file of rows) and API_KEY from env,
+// and reports whether the import landed via the `uploaded` step output.
+
+import { appendFileSync, readFileSync } from "node:fs";
+
+import { importStats, type StatsRow } from "./stats-import";
+
+/** `core.setOutput` without the github-script runtime. */
+function setOutput(name: string, value: string) {
+ const file = process.env.GITHUB_OUTPUT;
+ if (file) {
+ appendFileSync(file, `${name}=${value}\n`);
+ }
+}
+
+async function main() {
+ const rowsPath = process.env.ROWS || "artifacts/upload-rows.json";
+ const rows = JSON.parse(readFileSync(rowsPath, "utf8")) as StatsRow[];
+
+ console.table(rows);
+
+ try {
+ await importStats({ table: "bundle_sizes", rows });
+ console.log("Bundle sizes uploaded successfully");
+ setOutput("uploaded", "true");
+ } catch (error) {
+ // Stats logging is best-effort: if the importer is still unreachable after
+ // the client's retries, keep the run green. The last-plotted cache is only
+ // saved on a successful upload, so this point is re-attempted on the next
+ // master build and nothing is silently dropped.
+ const message = error instanceof Error ? error.message : String(error);
+ console.log(`::warning::Bundle-size upload failed after retries; leaving run green: ${message}`);
+ setOutput("uploaded", "false");
+ }
+}
+
+main();
diff --git a/.github/scripts/upload-emotion-stats.ts b/.github/scripts/upload-emotion-stats.ts
new file mode 100644
index 00000000000..94e8bb41443
--- /dev/null
+++ b/.github/scripts/upload-emotion-stats.ts
@@ -0,0 +1,25 @@
+// Appends the weekly @emotion/* importer count to the "Emotion Files" table in
+// eng-stats-importer. Reads EMOTION_FILES and API_KEY from env.
+
+import { importStats } from "./stats-import";
+
+async function main() {
+ console.log("EMOTION_FILES", Number(process.env.EMOTION_FILES));
+
+ // Keys must match the target table's columns (the importer normalizes both
+ // sides, so casing/spacing is forgiving).
+ const rows = [
+ {
+ Date: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
+ "Emotion Files": Number(process.env.EMOTION_FILES),
+ },
+ ];
+
+ await importStats({ table: "emotion_stats", rows });
+ console.log("Data uploaded successfully");
+}
+
+main().catch((error) => {
+ console.error("Error uploading data:", error);
+ process.exit(1);
+});
diff --git a/.github/scripts/upload-module-boundaries-stats.ts b/.github/scripts/upload-module-boundaries-stats.ts
new file mode 100644
index 00000000000..c865c6f8bf7
--- /dev/null
+++ b/.github/scripts/upload-module-boundaries-stats.ts
@@ -0,0 +1,30 @@
+// Appends the weekly module-boundary counts to the "Module Boundaries" table in
+// eng-stats-importer. Reads NAMED_MODULES, ENFORCED_MODULES, UNMODULED,
+// VIOLATIONS and API_KEY from env.
+
+import { importStats } from "./stats-import";
+
+async function main() {
+ console.log("NAMED_MODULES", Number(process.env.NAMED_MODULES));
+ console.log("ENFORCED_MODULES", Number(process.env.ENFORCED_MODULES));
+ console.log("UNMODULED", Number(process.env.UNMODULED));
+ console.log("VIOLATIONS", Number(process.env.VIOLATIONS));
+
+ const rows = [
+ {
+ Date: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
+ Modules: Number(process.env.NAMED_MODULES),
+ "Enforced modules": Number(process.env.ENFORCED_MODULES),
+ "Unmoduled folders": Number(process.env.UNMODULED),
+ Violations: Number(process.env.VIOLATIONS),
+ },
+ ];
+
+ await importStats({ table: "module_boundaries", rows });
+ console.log("Data uploaded successfully");
+}
+
+main().catch((error) => {
+ console.error("Error uploading data:", error);
+ process.exit(1);
+});
diff --git a/.github/workflows/bundle-size-stats.yml b/.github/workflows/bundle-size-stats.yml
index b247e842f60..56ab968f3bd 100644
--- a/.github/workflows/bundle-size-stats.yml
+++ b/.github/workflows/bundle-size-stats.yml
@@ -2,7 +2,7 @@ name: Bundle Size Stats
# Reuses the uberjar built on every master merge: downloads the jar (for the
# emitted JS) plus the bundle-stats and embedding-sdk artifacts, measures
-# initial/total bundle sizes, and appends them to stats.metabase.com.
+# initial/total bundle sizes, and appends them to eng-stats-importer.
on:
workflow_run:
@@ -32,6 +32,7 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ github.event.workflow_run.head_sha }}
+ - uses: ./.github/actions/prepare-node-bun
- name: Download EE uberjar
uses: ./.github/actions/fetch-artifact
with:
@@ -104,42 +105,15 @@ jobs:
# 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 }}
- run: node ./.github/scripts/bundle-size-stats-prepare.js
- - name: Upload sizes (with deltas) to Stats
+ run: bun ./.github/scripts/bundle-size-stats-prepare.ts
+ - name: Import sizes (with deltas) into Stats
id: upload
if: steps.prepare.outputs.significant == 'true'
- uses: actions/github-script@v9
env:
- API_KEY: ${{ secrets.STATS_API_KEY }}
- with:
- script: | # js
- const fs = require("fs");
- const { uploadCsvToMb } = require("${{ github.workspace }}/.github/scripts/csv-to-mb.js");
-
- const data = JSON.parse(
- fs.readFileSync("${{ github.workspace }}/artifacts/upload-rows.json", "utf8"),
- );
-
- console.table(data);
-
- try {
- await uploadCsvToMb({
- baseUrl: "https://stats.metabase.com",
- tableId: 79702,
- jsonData: data,
- mode: "append",
- });
- console.log("Bundle sizes uploaded successfully");
- core.setOutput("uploaded", "true");
- } catch (error) {
- // Stats logging is best-effort: if stats.metabase.com is still
- // unreachable after the client's retries, keep the run green. The
- // last-plotted cache is only saved on a successful upload (below),
- // so this point is re-attempted on the next master build and
- // nothing is silently dropped.
- core.warning(`Bundle-size upload failed after retries; leaving run green: ${error.message}`);
- core.setOutput("uploaded", "false");
- }
+ ROWS: artifacts/upload-rows.json
+ ENG_STATS_URL: ${{ secrets.ENG_STATS_URL }}
+ API_KEY: ${{ secrets.ENG_STATS_API_KEY }}
+ run: bun .github/scripts/upload-bundle-size-stats.ts
- name: Remember this as the last plotted point
if: steps.upload.outputs.uploaded == 'true'
uses: actions/cache/save@v4
diff --git a/.github/workflows/emotion-stats-update.yml b/.github/workflows/emotion-stats-update.yml
index 3116a9ca44b..f12c2888760 100644
--- a/.github/workflows/emotion-stats-update.yml
+++ b/.github/workflows/emotion-stats-update.yml
@@ -1,4 +1,4 @@
-# Weekly count of files importing @emotion/*, uploaded to stats.metabase.com.
+# Weekly count of files importing @emotion/*, imported into eng-stats-importer.
# Feeds the "Emotion CSS Elimination Progress" chart tracking the migration
# off Emotion onto Mantine (+ CSS modules as a fallback).
name: Emotion Stats Update
@@ -15,6 +15,7 @@ jobs:
timeout-minutes: 5
steps:
- uses: actions/checkout@v6
+ - uses: ./.github/actions/prepare-node-bun
- name: Get Emotion file count
id: get-emotion-file-count
run: |
@@ -44,35 +45,8 @@ jobs:
echo "EMOTION_FILES=$((oss + ee))" >> "$GITHUB_OUTPUT"
- name: Upload count to Stats
- uses: actions/github-script@v9
env:
EMOTION_FILES: ${{ steps.get-emotion-file-count.outputs.EMOTION_FILES }}
- API_KEY: ${{ secrets.STATS_API_KEY }}
- with:
- script: | # js
- const { uploadCsvToMb } = require('${{ github.workspace }}/.github/scripts/csv-to-mb.js');
-
- console.log("EMOTION_FILES", Number(process.env.EMOTION_FILES));
-
- // Keys become CSV headers and must match the target table's columns
- // (Metabase slugifies both sides, so casing/spacing is forgiving).
- const data = [
- {
- 'Date': new Date().toISOString().slice(0, 10), // YYYY-MM-DD
- 'Emotion Files': Number(process.env.EMOTION_FILES),
- }
- ];
-
- // tableId 76283 = "Emotion Files" table on stats.metabase.com.
- // Auth via x-api-key, sourced from STATS_API_KEY (see env block above).
- uploadCsvToMb({
- baseUrl: 'https://stats.metabase.com',
- tableId: 76283,
- jsonData: data,
- mode: 'append',
- }).then(() => {
- console.log('Data uploaded successfully');
- }).catch((error) => {
- console.error('Error uploading data:', error);
- process.exit(1);
- });
+ ENG_STATS_URL: ${{ secrets.ENG_STATS_URL }}
+ API_KEY: ${{ secrets.ENG_STATS_API_KEY }}
+ run: bun .github/scripts/upload-emotion-stats.ts
diff --git a/.github/workflows/js-stats-update.yml b/.github/workflows/js-stats-update.yml
deleted file mode 100644
index 09148b3cfea..00000000000
--- a/.github/workflows/js-stats-update.yml
+++ /dev/null
@@ -1,52 +0,0 @@
-name: JS Stats Update
-
-on:
- workflow_dispatch:
- schedule:
- - cron: 40 1 * * 4 # every Thursday at 1:40
-
-jobs:
- js-stats:
- if: ${{ github.event_name != 'schedule' || github.repository == 'metabase/metabase' }}
- runs-on: ${{ vars.SLIM_RUNNER_KEY }}
- timeout-minutes: 5
- steps:
- - uses: actions/checkout@v6
- - name: get JS file count
- id: get-js-file-count
- run: |
- oss=$(find ./frontend/src/metabase -type f -name "*.js" -o -name "*.jsx" | wc -l)
- ee=$(find ./enterprise/frontend/src/metabase-enterprise -type f -name "*.js" -o -name "*.jsx" | wc -l)
-
- echo $((oss + ee)) javascript files
-
- echo "JS_FILES=$((oss + ee))" >> "$GITHUB_OUTPUT"
- - name: Upload count to Stats
- uses: actions/github-script@v9
- env:
- JS_FILES: ${{ steps.get-js-file-count.outputs.JS_FILES }}
- API_KEY: ${{ secrets.STATS_API_KEY }}
- with:
- script: | # js
- const { uploadCsvToMb } = require('${{ github.workspace }}/.github/scripts/csv-to-mb.js');
-
- console.log("JS_FILES", Number(process.env.JS_FILES));
-
- const data = [
- {
- 'Date': new Date().toISOString().slice(0, 10), // YYYY-MM-DD
- 'Js files': Number(process.env.JS_FILES),
- }
- ];
-
- uploadCsvToMb({
- baseUrl: 'https://stats.metabase.com',
- tableId: 73270,
- jsonData: data,
- mode: 'append',
- }).then(() => {
- console.log('Data uploaded successfully');
- }).catch((error) => {
- console.error('Error uploading data:', error);
- process.exit(1);
- });
diff --git a/.github/workflows/module-boundaries-stats.yml b/.github/workflows/module-boundaries-stats.yml
index 0e08de4ff81..8b1d8577b94 100644
--- a/.github/workflows/module-boundaries-stats.yml
+++ b/.github/workflows/module-boundaries-stats.yml
@@ -21,40 +21,11 @@ jobs:
id: get-stats
run: node frontend/lint/module-boundaries-stats.mjs | tee -a "$GITHUB_OUTPUT"
- name: Upload stats
- uses: actions/github-script@v9
env:
NAMED_MODULES: ${{ steps.get-stats.outputs.NAMED_MODULES }}
ENFORCED_MODULES: ${{ steps.get-stats.outputs.ENFORCED_MODULES }}
UNMODULED: ${{ steps.get-stats.outputs.UNMODULED }}
VIOLATIONS: ${{ steps.get-stats.outputs.VIOLATIONS }}
- API_KEY: ${{ secrets.STATS_API_KEY }}
- with:
- script: | # js
- const { uploadCsvToMb } = require('${{ github.workspace }}/.github/scripts/csv-to-mb.js');
-
- console.log("NAMED_MODULES", Number(process.env.NAMED_MODULES));
- console.log("ENFORCED_MODULES", Number(process.env.ENFORCED_MODULES));
- console.log("UNMODULED", Number(process.env.UNMODULED));
- console.log("VIOLATIONS", Number(process.env.VIOLATIONS));
-
- const data = [
- {
- 'Date': new Date().toISOString().slice(0, 10), // YYYY-MM-DD
- 'Modules': Number(process.env.NAMED_MODULES),
- 'Enforced modules': Number(process.env.ENFORCED_MODULES),
- 'Unmoduled folders': Number(process.env.UNMODULED),
- 'Violations': Number(process.env.VIOLATIONS),
- }
- ];
-
- uploadCsvToMb({
- baseUrl: 'https://stats.metabase.com',
- tableId: 75146,
- jsonData: data,
- mode: 'append',
- }).then(() => {
- console.log('Data uploaded successfully');
- }).catch((error) => {
- console.error('Error uploading data:', error);
- process.exit(1);
- });
+ ENG_STATS_URL: ${{ secrets.ENG_STATS_URL }}
+ API_KEY: ${{ secrets.ENG_STATS_API_KEY }}
+ run: bun .github/scripts/upload-module-boundaries-stats.ts
diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml
index 35ff8b3f299..1f086c1285a 100644
--- a/.github/workflows/run-tests.yml
+++ b/.github/workflows/run-tests.yml
@@ -106,14 +106,17 @@ jobs:
timeout-minutes: 3
steps:
- uses: actions/checkout@v6
+ - uses: ./.github/actions/prepare-node-bun
- name: Upload affected tests stats
env:
STATS_JSON: ${{ needs.create-test-plan.outputs.stats }}
- PR_NUMBER: ${{ github.event.pull_request.number }}
- HEAD_SHA: ${{ github.event.pull_request.head.sha }}
- BASE_SHA: ${{ github.event.pull_request.base.sha }}
- API_KEY: ${{ secrets.STATS_API_KEY }}
- run: node .github/scripts/upload-affected-tests-stats.js
+ TRIGGERED_BY: ${{ github.event_name == 'pull_request' && 'pr_update' || 'merge_to_master' }}
+ PR_NUMBER: ${{ github.event_name == 'pull_request' && github.event.pull_request.number || 0 }}
+ HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
+ BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
+ ENG_STATS_URL: ${{ secrets.ENG_STATS_URL }}
+ API_KEY: ${{ secrets.ENG_STATS_API_KEY }}
+ run: bun .github/scripts/upload-affected-tests-stats.ts
uberjar:
needs: [should-run, create-test-plan]