Bring your own backend (DataSource)
Every component reads data through one interface, DataSource. If you already have a query API, write an adapter for it and install no data-layer package: no engine, no dev server, no Connect client. This recipe adapts a plain HTTP API that answers with Arrow, and adds a small wrapper that limits which sources a page can reach.
What your server has to do:
- Take the
ViewQueryand apply it: filters, sorts, column selection, grouping, aggregates, buckets, samples and the page. Components send a newViewQuerywhenever a person sorts, filters or scrolls, and expect back only that window of rows. The adapter never sorts or filters in the browser; it forwards the request and decodes the reply. - Bind filter values as parameters. They arrive as typed values in
Filter.values, never as SQL text. - Treat the base SQL as untrusted and run it read-only.
- Answer a failed query with a JSON body. A
messageis enough;code,lineandcolumnletSqlEditormark the place.
The wire format here is a choice, not a rule:
| Call | Request | Reply |
|---|---|---|
POST /query | the ExecuteRequest as protobuf JSON | an Arrow IPC stream; x-truncated: true when rows were left out, x-executed-sql (percent-encoded) for "show SQL" |
POST /count, /sources, /catalogs, /schemas, /tables, /describe | the request as protobuf JSON | the response as protobuf JSON |
| any failure | a non-2xx status with { message, code?, line?, column? } |
Protobuf JSON is what toJson and fromJson from @bufbuild/protobuf write and read. Enums are written as names ("SORT_DIRECTION_DESC") and 64-bit integers as strings ("offset": "200"), so any server language can read it without the generated code.
The adapter:
httpDataSource.ts:
import { type DescMessage, type MessageInitShape, type MessageShape, create, fromJson, toJson } from "@bufbuild/protobuf";
import { type CallOptions, type DataSource, QueryError, encodeTable } from "@surfaces-ui/data";
import {
CancelResponseSchema,
CountRequestSchema,
CountResponseSchema,
DescribeTableRequestSchema,
DescribeTableResponseSchema,
ExecuteRequestSchema,
ExecuteResponseSchema,
ListCatalogsRequestSchema,
ListCatalogsResponseSchema,
ListSchemasRequestSchema,
ListSchemasResponseSchema,
ListSnapshotsResponseSchema,
ListSourcesRequestSchema,
ListSourcesResponseSchema,
ListTablesRequestSchema,
ListTablesResponseSchema,
} from "@surfaces-ui/proto";
import { tableFromIPC } from "apache-arrow";
export interface HttpDataSourceOptions {
/** Where your API lives, e.g. "https://api.example.com/analytics". */
baseUrl: string;
/** Headers for every call, such as a session token. Called each time, so a refreshed token is used. */
headers?: () => HeadersInit | Promise<HeadersInit>;
/** Defaults to the global `fetch`. */
fetch?: typeof fetch;
}
/**
* A DataSource over your own HTTP API.
*
* - `POST /query` takes the ExecuteRequest as protobuf JSON and answers with
* an Arrow IPC stream holding only the requested window of rows. Your
* server applies the filters, sorts, grouping and page in the ViewQuery;
* nothing is sorted or filtered here.
* - `POST /count`, `/sources`, `/catalogs`, `/schemas`, `/tables` and
* `/describe` take and return protobuf JSON.
* - The query reply may name what ran in `x-executed-sql` (percent-encoded)
* and say `x-truncated: true` when rows were left out.
* - A failure is a non-2xx reply with `{ message, code?, line?, column? }`.
*/
export function httpDataSource(options: HttpDataSourceOptions): DataSource {
const base = options.baseUrl.replace(/\/$/, "");
const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
const post = async (path: string, body: unknown, signal?: AbortSignal): Promise<Response> => {
const headers = new Headers(await options.headers?.());
headers.set("content-type", "application/json");
let reply: Response;
try {
reply = await doFetch(`${base}${path}`, { method: "POST", headers, body: JSON.stringify(body), signal });
} catch (error) {
if (signal?.aborted) throw error;
throw new Error(`Could not reach the data service: ${error instanceof Error ? error.message : String(error)}`);
}
if (!reply.ok) throw await readError(reply);
return reply;
};
const unary =
<Req extends DescMessage, Res extends DescMessage>(path: string, requestSchema: Req, responseSchema: Res) =>
async (init: MessageInitShape<Req>, callOptions?: CallOptions): Promise<MessageShape<Res>> => {
const reply = await post(path, toJson(requestSchema, create(requestSchema, init)), callOptions?.signal);
return fromJson(responseSchema, await reply.json(), { ignoreUnknownFields: true });
};
return {
async *execute(init, callOptions) {
const started = Date.now();
const request = create(ExecuteRequestSchema, init);
if (request.timeTravel) throw new Error("This data service has no time travel.");
const reply = await post("/query", toJson(ExecuteRequestSchema, request), callOptions?.signal);
const table = tableFromIPC(new Uint8Array(await reply.arrayBuffer()));
// Re-frame the reply as the header, batch and footer parts components read.
const encoded = encodeTable(table, request.batchRows);
yield create(ExecuteResponseSchema, {
part: {
case: "header",
value: {
arrowSchema: encoded.schema,
// What the server ran, percent-encoded because a header cannot hold new lines.
executedSql: decodeURIComponent(reply.headers.get("x-executed-sql") ?? "") || (request.query?.baseSql ?? ""),
queryId: request.queryId,
columns: table.schema.fields.map((f) => ({ name: f.name, nativeType: String(f.type), sortable: true, filterable: true })),
},
},
});
for (const batch of encoded.batches) {
yield create(ExecuteResponseSchema, { part: { case: "batch", value: { arrowBatch: batch.bytes, rowCount: BigInt(batch.rows) } } });
}
yield create(ExecuteResponseSchema, {
part: {
case: "footer",
value: { totalRowsReturned: BigInt(table.numRows), truncated: reply.headers.get("x-truncated") === "true", elapsedMs: BigInt(Date.now() - started) },
},
});
},
count: unary("/count", CountRequestSchema, CountResponseSchema),
listSources: unary("/sources", ListSourcesRequestSchema, ListSourcesResponseSchema),
listCatalogs: unary("/catalogs", ListCatalogsRequestSchema, ListCatalogsResponseSchema),
listSchemas: unary("/schemas", ListSchemasRequestSchema, ListSchemasResponseSchema),
listTables: unary("/tables", ListTablesRequestSchema, ListTablesResponseSchema),
describeTable: unary("/describe", DescribeTableRequestSchema, DescribeTableResponseSchema),
// What this API does not offer, said plainly rather than faked.
async explain() {
throw new Error("This data service does not explain queries.");
},
// Aborting the signal passed to execute stops the request; there is no separate cancel call.
async cancel() {
return create(CancelResponseSchema, { cancelled: false });
},
// No time travel, so no snapshots.
async listSnapshots() {
return create(ListSnapshotsResponseSchema, {});
},
};
}
/** Turns a failed reply into an error a person can read, with its place in the SQL when the server says. */
async function readError(reply: Response): Promise<Error> {
const text = await reply.text();
try {
const body = JSON.parse(text) as { message?: unknown; code?: unknown; line?: unknown; column?: unknown };
if (typeof body.message === "string" && body.message !== "") {
const number = (v: unknown) => (typeof v === "number" ? v : undefined);
return new QueryError(body.message, { code: typeof body.code === "string" ? body.code : undefined, line: number(body.line), column: number(body.column) });
}
} catch {
// Not JSON: fall through to the status.
}
return new Error(`The data service answered ${reply.status}${reply.statusText ? ` ${reply.statusText}` : ""}.`);
}execute reads the Arrow reply whole and then hands it to components as the header, batch and footer parts they expect, using encodeTable from @surfaces-ui/data. Since the server sends only one window at a time, that is a few hundred rows, not the whole result. If your server streams large replies, read the body as it arrives instead and yield each batch as it is decoded.
What it does not do, and says so: it has no query plan (explain throws a readable error, which QueryPlan shows), no time travel (a request for it is refused), no snapshots, and no separate cancel call. Aborting the signal a component passes to execute stops the request. testSource is left out, which the interface allows.
A wrapper can sit in front of any DataSource. This one refuses calls for sources a page should not reach and leaves them out of listSources. It is a convenience, not security: your server still decides what each user may read.
allowList.ts:
import { create } from "@bufbuild/protobuf";
import type { DataSource } from "@surfaces-ui/data";
import { ListSourcesResponseSchema } from "@surfaces-ui/proto";
/**
* Wraps any DataSource so only some sources can be reached through it. Every
* call that names a source is checked; `listSources` leaves the rest out.
* This is a convenience for one page, not security: your server must still
* decide what each user may read.
*/
export function withSourceAllowList(dataSource: DataSource, allowed: string[]): DataSource {
const ok = new Set(allowed);
const check = (sourceId: string | undefined) => {
if (!ok.has(sourceId ?? "")) throw new Error(`The source "${sourceId ?? ""}" is not available here.`);
};
return {
...dataSource,
async *execute(request, options) {
check(request.sourceId);
yield* dataSource.execute(request, options);
},
count: async (request, options) => (check(request.sourceId), dataSource.count(request, options)),
explain: async (request, options) => (check(request.sourceId), dataSource.explain(request, options)),
listCatalogs: async (request, options) => (check(request.sourceId), dataSource.listCatalogs(request, options)),
listSchemas: async (request, options) => (check(request.sourceId), dataSource.listSchemas(request, options)),
listTables: async (request, options) => (check(request.sourceId), dataSource.listTables(request, options)),
describeTable: async (request, options) => (check(request.sourceId), dataSource.describeTable(request, options)),
listSnapshots: async (request, options) => (check(request.sourceId), dataSource.listSnapshots(request, options)),
async listSources(request, options) {
const reply = await dataSource.listSources(request, options);
return create(ListSourcesResponseSchema, { sources: reply.sources.filter((s) => ok.has(s.id)) });
},
testSource: dataSource.testSource && (async (request, options) => {
// Only a check of a named source is allowed; a test of a new, unsaved source is refused.
if (request.target?.case !== "id") throw new Error("Only saved sources can be tested here.");
check(request.target.value);
return dataSource.testSource!(request, options);
}),
};
}Use it like any other backend:
const data = withSourceAllowList(
httpDataSource({ baseUrl: "/api/analytics", headers: async () => ({ authorization: `Bearer ${await session.token()}` }) }),
["shop"],
);
<DataSourceProvider dataSource={data}>
<QueryResult sourceId="shop" sql="SELECT * FROM orders" />
</DataSourceProvider>The test plays the server with a stand-in fetch that runs each request on memoryDataSource and answers in the format above. It checks that the filters, sorts and page reach the server in the request body, that only the requested rows come back, that a real DataGrid works through the adapter, and that each kind of failure reads as a plain message. It has not been run against a real HTTP server.
httpDataSource.test.tsx:
// @vitest-environment jsdom
import { type DescMessage, fromJson, toJson } from "@bufbuild/protobuf";
import { DataGrid } from "@surfaces-ui/components";
import { type DataSource, QueryError, collect, memoryDataSource, queryErrorInfo, toRows } from "@surfaces-ui/data";
import {
CountRequestSchema,
CountResponseSchema,
DescribeTableRequestSchema,
DescribeTableResponseSchema,
ExecuteRequestSchema,
FilterOperator,
ListSourcesRequestSchema,
ListSourcesResponseSchema,
ListTablesRequestSchema,
ListTablesResponseSchema,
SortDirection,
} from "@surfaces-ui/proto";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import { tableToIPC } from "apache-arrow";
import { afterEach, describe, expect, it } from "vitest";
import { withSourceAllowList } from "./allowList.js";
import { httpDataSource } from "./httpDataSource.js";
afterEach(cleanup);
const orders = Array.from({ length: 30 }, (_, i) => ({ order_id: i + 1, region: i % 2 ? "Europe" : "Americas", amount: (i * 37) % 100 }));
/**
* Plays your server: it reads the request, runs it on an in-memory backend
* and answers in the wire format the adapter expects. Every body it receives
* is kept, so the test can see what the browser sent.
*/
function fakeServer() {
const backend = memoryDataSource({ sourceId: "shop", tables: { orders } });
const bodies: { path: string; body: any; auth: string | null }[] = [];
const unary: Record<string, [DescMessage, DescMessage, (request: any) => Promise<any>]> = {
"/count": [CountRequestSchema, CountResponseSchema, (r) => backend.count(r)],
"/sources": [ListSourcesRequestSchema, ListSourcesResponseSchema, (r) => backend.listSources(r)],
"/tables": [ListTablesRequestSchema, ListTablesResponseSchema, (r) => backend.listTables(r)],
"/describe": [DescribeTableRequestSchema, DescribeTableResponseSchema, (r) => backend.describeTable(r)],
};
const fetch: typeof globalThis.fetch = async (input, init) => {
const path = new URL(String(input)).pathname.replace(/^\/api/, "");
const body = JSON.parse(String(init?.body));
bodies.push({ path, body, auth: new Headers(init?.headers).get("authorization") });
try {
if (path === "/query") {
const request = fromJson(ExecuteRequestSchema, body);
if (/\bFORM\b/.test(request.query?.baseSql ?? "")) {
return Response.json({ message: 'Syntax error near "FORM"', code: "SYNTAX", line: 1, column: 10 }, { status: 400 });
}
const result = await collect(backend.execute(request));
return new Response(new Uint8Array(tableToIPC(result.table, "stream")), {
headers: { "content-type": "application/vnd.apache.arrow.stream", "x-truncated": String(result.footer.truncated), "x-executed-sql": encodeURIComponent(result.header.executedSql) },
});
}
const [requestSchema, responseSchema, handle] = unary[path]!;
return Response.json(toJson(responseSchema, await handle(fromJson(requestSchema, body))));
} catch (error) {
return Response.json({ message: (error as Error).message }, { status: 400 });
}
};
return { fetch, bodies };
}
describe("a DataSource over your own HTTP API", () => {
it("sends the whole ViewQuery to the server and reads back only that window", async () => {
const server = fakeServer();
const data = httpDataSource({ baseUrl: "https://example.test/api", fetch: server.fetch, headers: () => ({ authorization: "Bearer test-session" }) });
const result = await collect(
data.execute({
sourceId: "shop",
query: {
baseSql: "SELECT * FROM orders",
filters: [{ column: "region", operator: FilterOperator.EQ, values: [{ kind: { case: "stringValue", value: "Europe" } }] }],
sorts: [{ column: "amount", direction: SortDirection.DESC }],
page: { limit: 3, offset: 2n },
},
}),
);
// The server did the work: the browser got three rows, already filtered, sorted and paged.
const europe = orders.filter((o) => o.region === "Europe").sort((a, b) => b.amount - a.amount);
expect(toRows(result.table).map((r) => r.order_id)).toEqual(europe.slice(2, 5).map((o) => o.order_id));
expect(result.footer.truncated).toBe(true);
expect(result.header.executedSql).toBe("SELECT * FROM orders");
const sent = server.bodies[0]!;
expect(sent.path).toBe("/query");
expect(sent.auth).toBe("Bearer test-session");
expect(sent.body.query.filters).toEqual([{ column: "region", operator: "FILTER_OPERATOR_EQ", values: [{ stringValue: "Europe" }] }]);
expect(sent.body.query.sorts).toEqual([{ column: "amount", direction: "SORT_DIRECTION_DESC" }]);
expect(sent.body.query.page).toEqual({ limit: 3, offset: "2" });
});
it("drives a real DataGrid, which asks the server for a sorted page", async () => {
const server = fakeServer();
const data = httpDataSource({ baseUrl: "https://example.test/api", fetch: server.fetch });
render(<DataGrid dataSource={data} sourceId="shop" sql="SELECT * FROM orders" sorts={[{ column: "amount", desc: true }]} height={300} rowHeight={20} />);
await waitFor(() => expect(document.querySelectorAll(".sf-grid-row").length).toBeGreaterThan(0));
const top = Math.max(...orders.map((o) => o.amount));
expect(document.querySelector(".sf-grid-row")!.textContent).toContain(String(top));
const query = server.bodies.find((b) => b.path === "/query")!.body.query;
expect(query.sorts).toEqual([{ column: "amount", direction: "SORT_DIRECTION_DESC" }]);
expect(query.page.limit).toBeGreaterThan(0);
});
it("answers catalog calls from JSON endpoints", async () => {
const server = fakeServer();
const data = httpDataSource({ baseUrl: "https://example.test/api", fetch: server.fetch });
expect((await data.listSources({})).sources.map((s) => s.id)).toEqual(["shop"]);
expect((await data.listTables({ sourceId: "shop" })).tables.map((t) => t.ref?.table)).toEqual(["orders"]);
const detail = await data.describeTable({ sourceId: "shop", ref: { table: "orders" } });
expect(detail.table?.columns.map((c) => c.name)).toEqual(["order_id", "region", "amount"]);
expect((await data.count({ sourceId: "shop", query: { baseSql: "SELECT * FROM orders" } })).rowCount).toBe(30n);
});
it("turns failures into messages a person can read", async () => {
const server = fakeServer();
const data = httpDataSource({ baseUrl: "https://example.test/api", fetch: server.fetch });
const syntax = await collect(data.execute({ sourceId: "shop", query: { baseSql: "SELECT * FORM orders" } })).catch((e: unknown) => e);
expect(syntax).toBeInstanceOf(QueryError);
expect(queryErrorInfo(syntax)).toEqual({ message: 'Syntax error near "FORM"', code: "SYNTAX", line: 1, column: 10 });
const missing = await collect(data.execute({ sourceId: "shop", query: { baseSql: "SELECT * FROM nope" } })).catch((e: unknown) => e);
expect(queryErrorInfo(missing).message).toBe("Table not found: nope");
const down = httpDataSource({ baseUrl: "https://example.test/api", fetch: async () => new Response("<html>Bad gateway</html>", { status: 502, statusText: "Bad Gateway" }) });
await expect(down.listSources({})).rejects.toThrow("The data service answered 502 Bad Gateway.");
const unreachable = httpDataSource({ baseUrl: "https://example.test/api", fetch: async () => Promise.reject(new TypeError("fetch failed")) });
await expect(unreachable.listSources({})).rejects.toThrow("Could not reach the data service: fetch failed");
await expect(data.explain({ sourceId: "shop", query: { baseSql: "SELECT * FROM orders" } })).rejects.toThrow("does not explain queries");
});
});
describe("withSourceAllowList", () => {
it("refuses other sources and hides them from the list", async () => {
const backend: DataSource = memoryDataSource({ sourceId: "shop", tables: { orders } });
const onlyShop = withSourceAllowList(backend, ["shop"]);
expect((await collect(onlyShop.execute({ sourceId: "shop", query: { baseSql: "SELECT * FROM orders" } }))).table.numRows).toBe(30);
await expect(collect(onlyShop.execute({ sourceId: "hr", query: { baseSql: "SELECT * FROM people" } }))).rejects.toThrow('The source "hr" is not available here.');
await expect(onlyShop.listTables({ sourceId: "hr" })).rejects.toThrow("not available here");
expect((await withSourceAllowList(backend, ["hr"]).listSources({})).sources).toEqual([]);
});
});Source and test: apps/recipes/src/own-datasource