Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: batch the same url requests to avoid additional download / parsing (#2999)

Myles Scolnick1befc03e3f2d
diff --git a/frontend/src/components/data-table/column-summary.tsx b/frontend/src/components/data-table/column-summary.tsx
index 4aec7fed0a..0bf1997b6b 100644
--- a/frontend/src/components/data-table/column-summary.tsx
+++ b/frontend/src/components/data-table/column-summary.tsx
@@ -8,6 +8,7 @@ import { DelayMount } from "../utils/delay-mount";
import { ChartSkeleton } from "../charts/chart-skeleton";
import { logNever } from "@/utils/assertNever";
import { DatePopover } from "./date-popover";
+import { createBatchedLoader } from "@/plugins/impl/vega/batched";
export const ColumnChartContext = React.createContext<
ColumnChartSpecModel<unknown>
@@ -21,6 +22,10 @@ const LazyVegaLite = React.lazy(() =>
import("react-vega").then((m) => ({ default: m.VegaLite })),
);
+// We batch multiple calls to the same URL returning the same promise
+// for all calls with the same key.
+const batchedLoader = createBatchedLoader();
+
export const TableColumnSummary = <TData, TValue>({
columnId,
}: Props<TData, TValue>) => {
@@ -40,6 +45,8 @@ export const TableColumnSummary = <TData, TValue>({
spec={spec}
width={120}
height={50}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ loader={batchedLoader as any}
style={{ minWidth: "unset", maxHeight: "60px" }}
actions={false}
theme={theme === "dark" ? "dark" : "vox"}
diff --git a/frontend/src/core/static/files.ts b/frontend/src/core/static/files.ts
index e47e6a7534..8e7dee95b2 100644
--- a/frontend/src/core/static/files.ts
+++ b/frontend/src/core/static/files.ts
@@ -46,7 +46,6 @@ export function patchVegaLoader(
},
files: StaticVirtualFiles = getStaticVirtualFiles(),
) {
- // const originalHttp = loader.http.bind(loader);
const originalHttp = loader.http.bind(loader);
loader.http = async (url: string) => {
diff --git a/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts b/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts
index a3678a6c9b..ad15302357 100644
--- a/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts
@@ -1,4 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/unbound-method */
import { afterEach, describe, expect, it, vi } from "vitest";
import { vegaLoader } from "../loader";
import { resolveVegaSpecData } from "../resolve-data";
diff --git a/frontend/src/plugins/impl/vega/batched.ts b/frontend/src/plugins/impl/vega/batched.ts
new file mode 100644
index 0000000000..6b88924f25
--- /dev/null
+++ b/frontend/src/plugins/impl/vega/batched.ts
@@ -0,0 +1,15 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { batch } from "@/utils/batch-requests";
+import { createLoader, type Loader } from "./vega-loader";
+
+export function createBatchedLoader(): Loader {
+ const loader = createLoader();
+ const toKey = (request: unknown) => JSON.stringify(request);
+ return {
+ load: batch(loader.load.bind(loader) as any, toKey),
+ sanitize: batch(loader.sanitize.bind(loader) as any, toKey),
+ http: batch(loader.http.bind(loader) as any, toKey),
+ file: batch(loader.file.bind(loader), toKey),
+ };
+}
diff --git a/frontend/src/plugins/impl/vega/vega-loader.ts b/frontend/src/plugins/impl/vega/vega-loader.ts
index 5a94576ccc..7159266cba 100644
--- a/frontend/src/plugins/impl/vega/vega-loader.ts
+++ b/frontend/src/plugins/impl/vega/vega-loader.ts
@@ -23,14 +23,17 @@ export function read<T = object>(
return vl.read(data, format);
}
-export function createLoader(): {
- load: (
- url: string,
- ) => Promise<
- string | Record<string, unknown> | Array<Record<string, unknown>>
- >;
- http: (url: string) => Promise<string>;
-} {
+export interface Loader {
+ load(
+ uri: string,
+ options?: unknown,
+ ): Promise<string | Record<string, unknown> | Array<Record<string, unknown>>>;
+ sanitize(uri: string, options?: unknown): Promise<{ href: string }>;
+ http(uri: string, options?: unknown): Promise<string>;
+ file(filename: string): Promise<string>;
+}
+
+export function createLoader(): Loader {
return vl.loader();
}
diff --git a/frontend/src/utils/__tests__/batch-requests.test.ts b/frontend/src/utils/__tests__/batch-requests.test.ts
new file mode 100644
index 0000000000..da96b5bf54
--- /dev/null
+++ b/frontend/src/utils/__tests__/batch-requests.test.ts
@@ -0,0 +1,60 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect, vi } from "vitest";
+import { batch } from "../batch-requests";
+
+async function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+describe("batch", () => {
+ it("should return the same promise for calls with the same key", async () => {
+ const loader = vi.fn().mockImplementation(async (arg) => {
+ await sleep(10);
+ return "response";
+ });
+ const batchedLoader = batch(loader, JSON.stringify);
+
+ const promise1 = batchedLoader("arg1");
+ const promise2 = batchedLoader("arg1");
+
+ expect(promise1).toBe(promise2);
+ expect(loader).toHaveBeenCalledTimes(1);
+
+ const result = await promise1;
+ expect(result).toBe("response");
+ });
+
+ it("should call loader again after the first promise resolves", async () => {
+ const loader = vi.fn().mockImplementation(async (arg) => {
+ await sleep(10);
+ return "response";
+ });
+ const batchedLoader = batch(loader, JSON.stringify);
+
+ const promise1 = batchedLoader("arg1");
+ await promise1;
+
+ const promise2 = batchedLoader("arg1");
+ expect(promise1).not.toBe(promise2);
+ expect(loader).toHaveBeenCalledTimes(2);
+ });
+
+ it("should handle different keys separately", async () => {
+ const loader = vi.fn().mockImplementation(async (arg) => {
+ await sleep(10);
+ return "response";
+ });
+ const batchedLoader = batch(loader, JSON.stringify);
+
+ const promise1 = batchedLoader("arg1");
+ const promise2 = batchedLoader("arg2");
+
+ expect(promise1).not.toBe(promise2);
+ expect(loader).toHaveBeenCalledTimes(2);
+
+ const result1 = await promise1;
+ const result2 = await promise2;
+ expect(result1).toBe("response");
+ expect(result2).toBe("response");
+ });
+});
diff --git a/frontend/src/utils/batch-requests.ts b/frontend/src/utils/batch-requests.ts
new file mode 100644
index 0000000000..85ed9a4d38
--- /dev/null
+++ b/frontend/src/utils/batch-requests.ts
@@ -0,0 +1,28 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+/**
+ * Debounces multiple calls to a loader function, returning the same promise for
+ * all calls with the same key.
+ */
+export function batch<T, REQ extends unknown[]>(
+ loader: (...args: REQ) => Promise<T>,
+ toKey: (...args: REQ) => string,
+) {
+ const requestCache = new Map<string, Promise<T>>();
+
+ return (...args: REQ): Promise<T> => {
+ const key = toKey(...args);
+ if (requestCache.has(key)) {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ return requestCache.get(key)!;
+ }
+
+ const requestPromise = loader(...args).finally(() => {
+ requestCache.delete(key);
+ });
+
+ requestCache.set(key, requestPromise);
+ return requestPromise;
+ };
+}