Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

perf(broker): keep catalog pages and reuse a checked Session on connector routes (#6720)

Milind Soni71ada2b579cc
diff --git a/cloudflare/composio-broker/src/index.test.ts b/cloudflare/composio-broker/src/index.test.ts
index 5c449bdc47..e35b85e557 100644
--- a/cloudflare/composio-broker/src/index.test.ts
+++ b/cloudflare/composio-broker/src/index.test.ts
@@ -457,13 +457,106 @@ describe("connected-apps broker boundaries", () => {
await catalog(catalogEnv, new URL("https://broker.test/v1/catalog?cursor=eyJwYWdlIjoyfQ=="));
await catalog(catalogEnv, new URL("https://broker.test/v1/catalog?cursor=%20%26limit%3D1"));
+ // A malformed cursor asks for the first page, which is kept from the first request.
expect(fetchCalls.map((call) => new URL(call.url).searchParams.get("cursor"))).toEqual([
null,
"eyJwYWdlIjoyfQ==",
- null,
]);
});
+ describe("kept catalog pages", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ async function catalogHarness(page: () => Response = () => Response.json({ items: [{ slug: "deepgram" }], next_cursor: "Mi01MDA=" })) {
+ vi.resetModules();
+ const { catalog: read } = await import("./index");
+ const upstream: string[] = [];
+ const { env } = testEnv([]);
+ vi.stubGlobal("fetch", async (input: string | URL | Request) => {
+ upstream.push(new URL(String(input)).searchParams.get("cursor") ?? "");
+ return page();
+ });
+ const background: Array<Promise<unknown>> = [];
+ const ctx = { waitUntil: (promise: Promise<unknown>) => void background.push(promise) };
+ const catalogEnv = { ...env, COMPOSIO_TOOLKIT_BASE: "https://backend.composio.dev/api/v3" } as never;
+ const get = (cursor?: string) => read(catalogEnv, new URL(`https://broker.test/v1/catalog${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`), ctx);
+ return { get, upstream, settled: () => Promise.all(background) };
+ }
+
+ it("answers a page it has from memory, each cursor its own page, for thirty minutes", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-11-20T12:00:00Z"));
+ const { get, upstream } = await catalogHarness();
+ const first = await get();
+ const again = await get();
+ expect(upstream).toEqual([""]);
+ expect(await again.json()).toEqual(await first.json());
+ expect(again.headers.get("cache-control")).toBe("private, max-age=600");
+ expect(again.headers.get("content-type")).toContain("application/json");
+
+ await get("Mi01MDA=");
+ await get("Mi01MDA=");
+ expect(upstream).toEqual(["", "Mi01MDA="]);
+
+ vi.setSystemTime(new Date("2026-11-20T12:29:59Z"));
+ await get();
+ expect(upstream).toHaveLength(2);
+ vi.setSystemTime(new Date("2026-11-20T12:30:01Z"));
+ await get();
+ expect(upstream).toEqual(["", "Mi01MDA=", ""]);
+ });
+
+ it.each([
+ ["an upstream error", () => Response.json({ error: "down" }, { status: 500 }), 502],
+ ["a page with no toolkits", () => Response.json({ items: [] }), 200],
+ ["a page that is not a catalog", () => new Response("<html>", { headers: { "content-type": "text/html" } }), 200],
+ ])("never keeps %s", async (_name, page, status) => {
+ const { get, upstream } = await catalogHarness(page);
+ expect((await get()).status).toBe(status);
+ expect((await get()).status).toBe(status);
+ expect(upstream).toHaveLength(2);
+ });
+
+ it("stores a page in the data center's cache under its cursor alone, and another isolate answers from there", async () => {
+ const stored = new Map<string, { body: string; headers: Headers }>();
+ const edge = {
+ match: async (key: string) => {
+ const hit = stored.get(key);
+ return hit ? new Response(hit.body, { headers: hit.headers }) : undefined;
+ },
+ put: async (key: string, response: Response) => void stored.set(key, { body: await response.text(), headers: response.headers }),
+ };
+ const first = await catalogHarness();
+ vi.stubGlobal("caches", { default: edge });
+ await first.get();
+ await first.get("Mi01MDA=");
+ await first.settled();
+ expect([...stored.keys()]).toEqual(["https://catalog.invalid/v1/catalog?cursor=", "https://catalog.invalid/v1/catalog?cursor=Mi01MDA%3D"]);
+ expect(stored.get("https://catalog.invalid/v1/catalog?cursor=")!.headers.get("cache-control")).toBe("public, max-age=1800");
+
+ const second = await catalogHarness();
+ vi.stubGlobal("caches", { default: edge });
+ const answer = await second.get();
+ expect(await answer.json()).toEqual({ items: [{ slug: "deepgram" }], next_cursor: "Mi01MDA=" });
+ expect(answer.headers.get("cache-control")).toBe("private, max-age=600");
+ await second.get();
+ expect(second.upstream).toEqual([]);
+ });
+
+ it("still answers when the data center's cache fails", async () => {
+ const { get, upstream, settled } = await catalogHarness();
+ vi.stubGlobal("caches", { default: { match: async () => { throw new Error("cache down"); }, put: async () => { throw new Error("cache down"); } } });
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect((await get()).status).toBe(200);
+ await settled();
+ expect(upstream).toEqual([""]);
+ warn.mockRestore();
+ });
+ });
+
it("passes catalog pagination metadata through untouched", async () => {
const fetchCalls: Array<{ url: string; init?: RequestInit }> = [];
const { env } = testEnv(fetchCalls);
@@ -598,6 +691,8 @@ describe("MCP relay Session reuse", () => {
// Read once per isolate and cached, so it is not part of a request's call sequence.
if (path === "/auth_configs") return Response.json({ items: [] });
calls.push(`${method} ${path}`);
+ const under = path.match(/^\/tool_router\/session\/([^/]+)\//)?.[1];
+ if (under && gone.has(under)) return Response.json({ error: "session not found" }, { status: 404 });
const lookup = path.match(/^\/tool_router\/session\/([^/]+)$/)?.[1];
if (method === "GET" && lookup) {
return gone.has(lookup) ? Response.json({ error: "not found" }, { status: 404 }) : Response.json(session(lookup, "omb_relay"));
@@ -737,22 +832,53 @@ describe("MCP relay Session reuse", () => {
expect(idle.lastSeenWrites).toHaveLength(1);
});
- it("keeps checking the Session on every connector-management route", async () => {
+ const MANAGEMENT_ROUTES = [
+ ["/v1/connectors/connected", {}],
+ ["/v1/connectors?services=gmail", {}],
+ ["/v1/connectors/gmail/authorize", { method: "POST", body: JSON.stringify({ alias: "second" }) }],
+ ["/v1/connectors/gmail", { method: "DELETE" }],
+ ["/v1/connectors/gmail/accounts/ca_relay", { method: "DELETE" }],
+ ] as const;
+
+ it("checks the Session once for the connector-management routes that follow within five minutes", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-11-20T12:00:00Z"));
const relay = relayHarness("trs_connectors");
- await relay.mcp();
const lookup = "GET /tool_router/session/trs_connectors";
+ const first = await relay.send("/v1/connectors/connected");
+ expect(first.calls[0]).toBe(lookup);
- for (const [path, init] of [
- ["/v1/connectors/connected", {}],
- ["/v1/connectors?services=gmail", {}],
- ["/v1/connectors/gmail/authorize", { method: "POST", body: JSON.stringify({ alias: "second" }) }],
- ["/v1/connectors/gmail", { method: "DELETE" }],
- ["/v1/connectors/gmail/accounts/ca_relay", { method: "DELETE" }],
- ] as const) {
+ for (const [path, init] of MANAGEMENT_ROUTES) {
const result = await relay.send(path, init);
expect(result.response.status, path).toBe(200);
- expect(result.calls[0], path).toBe(lookup);
+ expect(result.calls, path).not.toContain(lookup);
}
+ expect((await relay.mcp()).calls).toEqual(["MCP trs_connectors"]);
+
+ vi.setSystemTime(new Date("2026-11-20T12:05:01Z"));
+ expect((await relay.send("/v1/connectors/connected")).calls[0]).toBe(lookup);
+ });
+
+ it.each(MANAGEMENT_ROUTES.slice(0, 4))("looks a dropped Session up again and sends %s once more", async (path, init) => {
+ const id = `trs_dropped_${MANAGEMENT_ROUTES.findIndex(([route]) => route === path)}`;
+ const relay = relayHarness(id);
+ await relay.send("/v1/connectors/connected");
+ relay.gone.add(id);
+
+ const result = await relay.send(path, init);
+ expect(result.response.status).toBe(200);
+ expect(result.calls).toContain(`GET /tool_router/session/${id}`);
+ expect(result.calls).toContain("POST /tool_router/session");
+ expect(result.calls.filter((call) => call.includes(`/tool_router/session/${id}_new/`))).toHaveLength(1);
+ expect(relay.row.session_id).toBe(`${id}_new`);
+ expect(result.calls.filter((call) => call.endsWith("/link"))).toHaveLength(path.endsWith("/authorize") ? 2 : 0);
+ });
+
+ it("looks the Session up again when D1 points the installation at another one", async () => {
+ const relay = relayHarness("trs_before_adoption");
+ await relay.send("/v1/connectors/connected");
+ relay.row.session_id = "trs_after_adoption";
+ expect((await relay.send("/v1/connectors/connected")).calls[0]).toBe("GET /tool_router/session/trs_after_adoption");
});
});
diff --git a/cloudflare/composio-broker/src/index.ts b/cloudflare/composio-broker/src/index.ts
index 6eaa9a9f39..1c019b2a48 100644
--- a/cloudflare/composio-broker/src/index.ts
+++ b/cloudflare/composio-broker/src/index.ts
@@ -343,9 +343,49 @@ async function limitSessionRequests(installation: InstallationRow, env: Env) {
}
}
-async function ensureSession(installation: InstallationRow, env: Env, ctx: ExecutionContext) {
+interface HeldSession {
+ session: ComposioSession;
+ /** True while the Session is one an earlier request checked, not one Composio confirmed for this request. */
+ reused: boolean;
+}
+
+/** The installation's Session. One this isolate checked in the last five minutes is used as it is, when it still covers
+ * the project's auth configs: the row is this request's own read, so its Session id and user are current. */
+async function heldSession(installation: InstallationRow, env: Env, ctx: ExecutionContext): Promise<HeldSession> {
await limitSessionRequests(installation, env);
- return verifySession(installation, env, ctx);
+ const reused = verifiedSession(installation);
+ if (reused && sessionReady(reused, await projectAuthConfigs(env))) {
+ touchLastSeen(installation, env, ctx);
+ return { session: reused, reused: true };
+ }
+ return { session: await verifySession(installation, env, ctx), reused: false };
+}
+
+async function ensureSession(installation: InstallationRow, env: Env, ctx: ExecutionContext) {
+ return (await heldSession(installation, env, ctx)).session;
+}
+
+/** A request under the installation's Session. Composio answers 404 or 410 for a Session it dropped, having done nothing:
+ * a reused Session is then looked up again and the request sent once more. Any failure has the next request look the
+ * Session up again. */
+async function sessionRequest(
+ held: HeldSession,
+ installation: InstallationRow,
+ env: Env,
+ ctx: ExecutionContext,
+ path: (sessionId: string) => string,
+ init?: RequestInit,
+) {
+ let response = await composioRequest(env, path(held.session.sessionId), init);
+ if (held.reused && (response.status === 404 || response.status === 410)) {
+ forgetSession(held.session.sessionId);
+ await response.body?.cancel();
+ held.session = await verifySession(installation, env, ctx);
+ held.reused = false;
+ response = await composioRequest(env, path(held.session.sessionId), init);
+ }
+ if (!response.ok) forgetSession(held.session.sessionId);
+ return response;
}
async function currentInstallation(env: Env, id: string) {
@@ -458,24 +498,77 @@ async function proxyMcp(request: Request, installation: InstallationRow, env: En
return new Response(response.body, { status: response.status, headers });
}
-async function catalog(env: Env, url: URL) {
+/** The catalog is the same for every installation and changes rarely, so a page is kept: in this isolate, and in the
+ * data center's cache where the Worker's hostname has one. The key is the cursor alone, never anything of the caller's. */
+const CATALOG_KEEP_SECONDS = 30 * 60;
+const CATALOG_PAGES_KEPT = 8;
+const catalogPages = new Map<string, { at: number; body: string; contentType: string }>();
+
+function catalogResponse(body: string, contentType: string) {
+ return new Response(body, { headers: { "content-type": contentType, "cache-control": "private, max-age=600" } });
+}
+
+function keepCatalogPage(cursor: string, body: string, contentType: string, at = Date.now()) {
+ catalogPages.delete(cursor);
+ catalogPages.set(cursor, { at, body, contentType });
+ for (const oldest of catalogPages.keys()) {
+ if (catalogPages.size <= CATALOG_PAGES_KEPT) break;
+ catalogPages.delete(oldest);
+ }
+}
+
+/** Cloudflare's per-data-center cache; absent outside Workers. */
+function edgeCache(): Cache | undefined {
+ return typeof caches === "undefined" ? undefined : (caches as unknown as { default?: Cache }).default;
+}
+
+function hasToolkits(body: string) {
+ try {
+ const page = JSON.parse(body) as { items?: unknown; data?: unknown };
+ const items = page.items ?? page.data;
+ return Array.isArray(items) && items.length > 0;
+ } catch {
+ return false;
+ }
+}
+
+async function catalog(env: Env, url: URL, ctx?: Pick<ExecutionContext, "waitUntil">) {
// The catalog runs past a thousand toolkits, so pass the caller's cursor through.
const params = new URLSearchParams({ limit: "500", sort_by: "usage" });
- const cursor = url.searchParams.get("cursor");
- if (cursor && CATALOG_CURSOR.test(cursor)) params.set("cursor", cursor);
+ const asked = url.searchParams.get("cursor");
+ const cursor = asked && CATALOG_CURSOR.test(asked) ? asked : "";
+ if (cursor) params.set("cursor", cursor);
+ const kept = catalogPages.get(cursor);
+ if (kept && Date.now() - kept.at < CATALOG_KEEP_SECONDS * 1_000) return catalogResponse(kept.body, kept.contentType);
+ const edge = edgeCache();
+ const edgeKey = `https://catalog.invalid/v1/catalog?${new URLSearchParams({ cursor })}`;
+ const stored = await edge?.match(edgeKey).catch(() => undefined);
+ if (stored) {
+ const body = await stored.text();
+ const contentType = stored.headers.get("content-type") ?? "application/json";
+ const age = Number(stored.headers.get("age"));
+ keepCatalogPage(cursor, body, contentType, Date.now() - (Number.isFinite(age) ? age * 1_000 : 0));
+ return catalogResponse(body, contentType);
+ }
const response = await fetch(`${env.COMPOSIO_TOOLKIT_BASE}/toolkits?${params}`, {
headers: { accept: "application/json", "x-api-key": env.COMPOSIO_API_KEY },
signal: AbortSignal.timeout(20_000),
});
if (!response.ok) return json({ error: await upstreamError(response, "Catalog unavailable") }, 502);
- return new Response(response.body, {
- headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "private, max-age=600" },
- });
+ const body = await response.text();
+ const contentType = response.headers.get("content-type") ?? "application/json";
+ // A page with no toolkits is an upstream hiccup or the walk's end past the last page: never kept.
+ if (hasToolkits(body)) {
+ keepCatalogPage(cursor, body, contentType);
+ const put = edge?.put(edgeKey, new Response(body, { headers: { "content-type": contentType, "cache-control": `public, max-age=${CATALOG_KEEP_SECONDS}` } }))
+ .catch((error: unknown) => console.warn(JSON.stringify({ message: "catalog page not cached", error: error instanceof Error ? error.message : String(error) })));
+ if (put) ctx?.waitUntil(put);
+ }
+ return catalogResponse(body, contentType);
}
async function listSessionToolkits(
- env: Env,
- sessionId: string,
+ request: (path: (sessionId: string) => string) => Promise<Response>,
): Promise<ToolkitItem[]> {
const toolkits: ToolkitItem[] = [];
const seenCursors = new Set<string>();
@@ -485,10 +578,7 @@ async function listSessionToolkits(
// Composio supports a server-side connected-only filter on this route.
const params = new URLSearchParams({ limit: "50", is_connected: "true" });
if (cursor) params.set("cursor", cursor);
- const response = await composioRequest(
- env,
- `/tool_router/session/${encodeURIComponent(sessionId)}/toolkits?${params}`,
- );
+ const response = await request((sessionId) => `/tool_router/session/${encodeURIComponent(sessionId)}/toolkits?${params}`);
if (!response.ok) throw new Error(await upstreamError(response, "Toolkit inventory unavailable"));
const body = toolkitPageSchema.parse(await response.json());
toolkits.push(...(body.items ?? []));
@@ -573,9 +663,9 @@ async function connectedServices(
env: Env,
ctx: ExecutionContext,
) {
- const session = await ensureSession(installation, env, ctx);
+ const held = await heldSession(installation, env, ctx);
const [toolkits, accounts] = await Promise.all([
- listSessionToolkits(env, session.sessionId),
+ listSessionToolkits((path) => sessionRequest(held, installation, env, ctx, path)),
listConnectedAccounts(env, actingUser(installation), []).catch(() => []),
]);
return json({
@@ -586,12 +676,10 @@ async function connectedServices(
async function connectionStatus(url: URL, installation: InstallationRow, env: Env, ctx: ExecutionContext) {
const slugs = [...new Set((url.searchParams.get("services") ?? "").split(",").map((slug) => slug.toLowerCase()).filter(Boolean))].slice(0, 50);
- const session = await ensureSession(installation, env, ctx);
+ const held = await heldSession(installation, env, ctx);
const [response, accounts] = await Promise.all([
- composioRequest(
- env,
- `/tool_router/session/${encodeURIComponent(session.sessionId)}/toolkits?${new URLSearchParams({ limit: "50", toolkits: slugs.join(",") })}`,
- ),
+ sessionRequest(held, installation, env, ctx,
+ (sessionId) => `/tool_router/session/${encodeURIComponent(sessionId)}/toolkits?${new URLSearchParams({ limit: "50", toolkits: slugs.join(",") })}`),
listConnectedAccounts(env, actingUser(installation), slugs).catch(() => []),
]);
if (!response.ok) return json({ error: await upstreamError(response, "Connection status unavailable") }, 502);
@@ -619,7 +707,7 @@ async function authorize(
env: Env,
ctx: ExecutionContext,
) {
- const session = await ensureSession(installation, env, ctx);
+ const held = await heldSession(installation, env, ctx);
// Listing can be denied to the broker's key scope; authorize must still
// work, with the alias guardrails degrading to first-account behavior.
const accounts = await listConnectedAccounts(env, actingUser(installation), [slug]).catch(() => []);
@@ -636,10 +724,10 @@ async function authorize(
const removed = await composioRequest(env, `/connected_accounts/${encodeURIComponent(id)}?revoke_on_delete=true`, { method: "DELETE" });
if (!removed.ok) return json({ error: await upstreamError(removed, "Removing the earlier sign-in failed") }, 502);
}
- await raiseAccountCap(session, env);
+ await raiseAccountCap(held.session, env);
const linkRequest: AccountLinkRequest = { toolkit: slug };
if (plan.alias) linkRequest.alias = plan.alias;
- const response = await composioRequest(env, `/tool_router/session/${encodeURIComponent(session.sessionId)}/link`, {
+ const response = await sessionRequest(held, installation, env, ctx, (sessionId) => `/tool_router/session/${encodeURIComponent(sessionId)}/link`, {
method: "POST",
body: JSON.stringify(linkRequest),
});
@@ -654,11 +742,9 @@ async function authorize(
}
async function disconnect(slug: string, installation: InstallationRow, env: Env, ctx: ExecutionContext) {
- const session = await ensureSession(installation, env, ctx);
- const list = await composioRequest(
- env,
- `/tool_router/session/${encodeURIComponent(session.sessionId)}/toolkits?${new URLSearchParams({ limit: "50", toolkits: slug })}`,
- );
+ const held = await heldSession(installation, env, ctx);
+ const list = await sessionRequest(held, installation, env, ctx,
+ (sessionId) => `/tool_router/session/${encodeURIComponent(sessionId)}/toolkits?${new URLSearchParams({ limit: "50", toolkits: slug })}`);
if (!list.ok) return json({ error: await upstreamError(list, "Connection lookup unavailable") }, 502);
const body = toolkitPageSchema.parse(await list.json());
const id = body.items?.find((item) => item.slug?.toLowerCase() === slug)?.connected_account?.id;
@@ -768,7 +854,7 @@ async function route(request: Request, env: Env, ctx: ExecutionContext) {
await limitSessionRequests(installation, env);
return requestFileUpload(request, installation, env);
}
- if (request.method === "GET" && url.pathname === "/v1/catalog") return catalog(env, url);
+ if (request.method === "GET" && url.pathname === "/v1/catalog") return catalog(env, url, ctx);
if (request.method === "GET" && url.pathname === "/v1/connectors/connected") return connectedServices(installation, env, ctx);
if (request.method === "GET" && url.pathname === "/v1/connectors") return connectionStatus(url, installation, env, ctx);
const accountMatch = url.pathname.match(/^\/v1\/connectors\/([a-z0-9_][a-z0-9_-]{0,80})\/accounts\/([A-Za-z0-9][A-Za-z0-9_-]{0,127})$/);
diff --git a/cloudflare/composio-broker/src/session-identity.test.ts b/cloudflare/composio-broker/src/session-identity.test.ts
index 655087eab7..cbb6c2e247 100644
--- a/cloudflare/composio-broker/src/session-identity.test.ts
+++ b/cloudflare/composio-broker/src/session-identity.test.ts
@@ -2,7 +2,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { brokerHarness, Installation } from "./test-harness";
-afterEach(() => vi.unstubAllGlobals());
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
const sendEmail = (h: ReturnType<typeof brokerHarness>, owner: Installation) => h.call(owner, "/v1/mcp", {
method: "POST",
@@ -40,7 +43,12 @@ async function sharingFixture() {
describe("Composio session identity across account adoption", () => {
it.each(["creation", "lookup"])("retries a session %s that finishes after adoption", async (operation) => {
const { h, desktop, cloud, gmail, adopt } = await sharingFixture();
- if (operation === "lookup") await emailResult(await sendEmail(h, cloud));
+ if (operation === "lookup") {
+ await emailResult(await sendEmail(h, cloud));
+ // Past the five minutes a checked Session is reused for, so the request below looks it up.
+ const checkedAt = Date.now();
+ vi.spyOn(Date, "now").mockImplementation(() => checkedAt + 5 * 60_000 + 1_000);
+ }
const started = Promise.withResolvers<void>();
const release = Promise.withResolvers<void>();
let held = false;