feat: Batch RPC endpoint (#12820)

* batch RPC endpoint

* Clamp batch socket timeout between 15s and 25s

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Tom MoorandClaude Opus 4.8 authored and GitHub committed 2026-06-28 02:39:30 -04:00
1 parent 94babaa273
commit 695042b2af
5 files changed
+539

No files matched your search

+273
View File
@@ -0,0 +1,273 @@
import { RateLimiterRes } from "rate-limiter-flexible";
import env from "@server/env";
import type { Document, User } from "@server/models";
import {
buildAdmin,
buildCollection,
buildDocument,
buildUser,
} from "@server/test/factories";
import { getTestServer } from "@server/test/support";
import RateLimiter from "@server/utils/RateLimiter";
const server = getTestServer();
describe("#batch", () => {
let user: User;
let documentOne: Document;
let documentTwo: Document;
beforeEach(async () => {
user = await buildUser();
[documentOne, documentTwo] = await Promise.all([
buildDocument({ userId: user.id, teamId: user.teamId }),
buildDocument({ userId: user.id, teamId: user.teamId }),
]);
});
it("should require authentication", async () => {
const res = await server.post("/api/batch", {
body: {
requests: [{ method: "documents.info", body: { id: documentOne.id } }],
},
});
expect(res.status).toEqual(401);
});
it("should reject an empty batch", async () => {
const res = await server.post("/api/batch", user, {
body: { requests: [] },
});
expect(res.status).toEqual(400);
});
it("should reject a batch over the maximum size", async () => {
const res = await server.post("/api/batch", user, {
body: {
requests: Array.from({ length: 26 }, () => ({
method: "documents.info",
body: { id: documentOne.id },
})),
},
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toContain("at most 25");
});
it("should dispatch multiple requests and return a response for each", async () => {
const res = await server.post("/api/batch", user, {
body: {
requests: [
{
method: "documents.update",
body: { id: documentOne.id, title: "One" },
},
{
method: "documents.update",
body: { id: documentTwo.id, title: "Two" },
},
],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data).toHaveLength(2);
expect(body.data[0].ok).toBe(true);
expect(body.data[0].status).toEqual(200);
expect(body.data[0].data.id).toEqual(documentOne.id);
expect(body.data[0].data.title).toEqual("One");
expect(body.data[0].policies).toBeTruthy();
expect(body.data[1].ok).toBe(true);
expect(body.data[1].data.title).toEqual("Two");
});
it("should dispatch across multiple resources in one batch", async () => {
const admin = await buildAdmin();
const collection = await buildCollection({
teamId: admin.teamId,
userId: admin.id,
});
const doc = await buildDocument({
teamId: admin.teamId,
userId: admin.id,
collectionId: collection.id,
});
const res = await server.post("/api/batch", admin, {
body: {
requests: [
{ method: "documents.update", body: { id: doc.id, title: "Doc" } },
{
method: "collections.update",
body: { id: collection.id, name: "Coll" },
},
],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data[0].ok).toBe(true);
expect(body.data[0].data.title).toEqual("Doc");
expect(body.data[1].ok).toBe(true);
expect(body.data[1].data.name).toEqual("Coll");
});
it("should isolate failures so the batch succeeds partially", async () => {
const otherDocument = await buildDocument();
const res = await server.post("/api/batch", user, {
body: {
requests: [
{
method: "documents.update",
body: { id: documentOne.id, title: "Updated" },
},
{
method: "documents.update",
body: { id: otherDocument.id, title: "Denied" },
},
],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data[0].ok).toBe(true);
expect(body.data[0].data.title).toEqual("Updated");
expect(body.data[1].ok).toBe(false);
expect([403, 404]).toContain(body.data[1].status);
expect(body.data[1].error).toBeTruthy();
});
it("should reject an unknown method", async () => {
const res = await server.post("/api/batch", user, {
body: {
requests: [
{ method: "stars.create", body: { documentId: documentOne.id } },
],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data[0].ok).toBe(false);
expect(body.data[0].status).toEqual(400);
expect(body.data[0].error).toEqual("invalid_request");
});
it("should reject a known endpoint that is not allowlisted", async () => {
// documents.list is a real route, but reads aren't permitted in a batch.
const res = await server.post("/api/batch", user, {
body: {
requests: [{ method: "documents.list", body: {} }],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data[0].ok).toBe(false);
expect(body.data[0].status).toEqual(400);
expect(body.data[0].error).toEqual("invalid_request");
});
it("should transform errors with parity to top-level routes", async () => {
const res = await server.post("/api/batch", user, {
body: {
requests: [
{
method: "documents.archive",
body: { id: "550e8400-e29b-41d4-a716-446655440000" },
},
],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
// A Sequelize EmptyResultError is transformed to a 404 not_found, matching
// what the same request would return when called directly.
expect(body.data[0].ok).toBe(false);
expect(body.data[0].status).toEqual(404);
expect(body.data[0].error).toEqual("not_found");
});
it("should surface per-request validation errors", async () => {
const res = await server.post("/api/batch", user, {
body: {
requests: [{ method: "documents.update", body: {} }],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data[0].ok).toBe(false);
expect(body.data[0].status).toEqual(400);
});
describe("rate limiting", () => {
const originalEnabled = env.RATE_LIMITER_ENABLED;
afterEach(() => {
env.RATE_LIMITER_ENABLED = originalEnabled;
vi.restoreAllMocks();
});
it("should rate limit each sub-request against its own method", async () => {
env.RATE_LIMITER_ENABLED = true;
const consume = vi.fn().mockResolvedValue(undefined);
const getRateLimiter = vi
.spyOn(RateLimiter, "getRateLimiter")
.mockReturnValue({ consume, points: 100 } as unknown as ReturnType<
typeof RateLimiter.getRateLimiter
>);
const res = await server.post("/api/batch", user, {
body: {
requests: [
{
method: "documents.update",
body: { id: documentOne.id, title: "x" },
},
],
},
});
expect(res.status).toEqual(200);
// The dispatched method is rate limited on its own path, not /batch, so a
// batch can't be used to bypass per-endpoint limits.
expect(getRateLimiter).toHaveBeenCalledWith(
expect.stringContaining("documents.update")
);
expect(consume).toHaveBeenCalled();
});
it("should return a per-item 429 when a sub-request is rate limited", async () => {
env.RATE_LIMITER_ENABLED = true;
// A RateLimiterRes rejection signals the limit was hit (a plain Error
// would instead fail open inside the limiter middleware).
const consume = vi
.fn()
.mockRejectedValue(new RateLimiterRes(0, 60000, 1, false));
vi.spyOn(RateLimiter, "getRateLimiter").mockReturnValue({
consume,
points: 1,
} as unknown as ReturnType<typeof RateLimiter.getRateLimiter>);
const res = await server.post("/api/batch", user, {
body: {
requests: [
{
method: "documents.update",
body: { id: documentOne.id, title: "x" },
},
],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data[0].ok).toBe(false);
expect(body.data[0].status).toEqual(429);
});
});
});
+238
View File
@@ -0,0 +1,238 @@
import { chunk, snakeCase } from "es-toolkit/compat";
import type { Middleware } from "koa";
import compose from "koa-compose";
import Router from "koa-router";
import auth from "@server/middlewares/authentication";
import {
defaultRateLimiter,
rateLimiter,
} from "@server/middlewares/rateLimiter";
import validate from "@server/middlewares/validate";
import type { APIContext, AppContext } from "@server/types";
import { AuthenticationType } from "@server/types";
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
import { toError } from "@shared/utils/error";
import collections from "../collections";
import documents from "../documents";
import apiErrorHandler from "../middlewares/apiErrorHandler";
import * as T from "./schema";
const router = new Router();
/**
* Error transforms applied to each sub-request, mirroring the handler that
* wraps top-level API routes so batched responses have full parity.
*/
const handleErrors = apiErrorHandler();
/**
* Enforces each sub-request against its own method's rate limiter, mirroring the
* global limiter that runs once per top-level request, so that batching cannot
* be used to bypass per-endpoint limits.
*/
const enforceRateLimit = defaultRateLimiter();
/**
* The individual endpoints that may be invoked within a batch. Deliberately
* curated to simple JSON mutations — no reads (pagination), redirects, file
* responses, or endpoints that set response headers.
*/
const allowedMethods = new Set<string>([
"documents.update",
"documents.move",
"documents.archive",
"documents.restore",
"documents.unpublish",
"documents.delete",
"collections.update",
"collections.move",
"collections.archive",
"collections.restore",
"collections.delete",
]);
/** Routers searched for an allowed method's middleware stack. */
const dispatchableRouters: Router[] = [documents, collections];
/** The number of sub-requests dispatched in parallel, to limit pool pressure. */
const BatchConcurrency = 2;
interface HttpError extends Error {
status?: number;
id?: string;
}
interface RouteResponse {
data?: unknown;
policies?: unknown;
}
interface BatchResult {
status: number;
ok: boolean;
data?: unknown;
policies?: unknown;
error?: string;
message?: string;
}
/**
* Locates the middleware stack for an allowlisted method.
*
* @param method The RPC method name, e.g. "documents.update".
* @returns the route's middleware stack, or undefined if not permitted.
*/
function resolveStack(method: string): Middleware[] | undefined {
if (!allowedMethods.has(method)) {
return undefined;
}
for (const resourceRouter of dispatchableRouters) {
for (const layer of resourceRouter.stack) {
// Layer paths are lazily prefixed with "/" once mounted, so accept both.
if (
(layer.path === method || layer.path === `/${method}`) &&
layer.methods.includes("POST")
) {
return layer.stack;
}
}
}
return undefined;
}
/**
* Creates an isolated child context for a single batched request so that its
* request body, state, transaction, and response are independent from sibling
* requests and from the parent. Headers, cookies, and query are inherited.
*
* @param ctx The parent request context.
* @param body The request body for the child.
* @returns the child context and a handle to its captured response.
*/
function createSubContext(
ctx: AppContext,
method: string,
body: Record<string, unknown>
) {
const sub: AppContext = Object.create(ctx);
// A shallow copy so middleware writes (auth, transaction) don't leak between
// concurrent sub-requests or back to the parent.
sub.state = { ...ctx.state };
sub.request = Object.create(ctx.request);
sub.request.body = body;
// Present the sub-request's own path so per-method rate limiting keys on the
// dispatched method rather than the shared /batch path.
Object.defineProperty(sub, "path", {
configurable: true,
get: () => `/${method}`,
});
const captured: { body?: RouteResponse; status: number } = { status: 404 };
Object.defineProperty(sub, "body", {
configurable: true,
get: () => captured.body,
set: (value: RouteResponse) => {
captured.body = value;
if (captured.status === 404) {
captured.status = 200;
}
},
});
Object.defineProperty(sub, "status", {
configurable: true,
get: () => captured.status,
set: (value: number) => {
captured.status = value;
},
});
// Re-bind ctx.context to this child so mutations use the child's transaction
// rather than the parent's (the getter from apiContext closes over its ctx).
Object.defineProperty(sub, "context", {
configurable: true,
get: () => ({
auth: sub.state.auth,
transaction: sub.state.transaction,
ip: sub.request.ip,
}),
});
return { sub, captured };
}
/**
* Dispatches a single sub-request through its real route, reusing that route's
* authentication, validation, transaction, and presenters.
*
* @param ctx The parent request context.
* @param method The RPC method name to invoke.
* @param body The request body for the method.
* @returns the result, shaped like a standard API response envelope.
*/
async function dispatch(
ctx: AppContext,
method: string,
body: Record<string, unknown>
): Promise<BatchResult> {
const stack = resolveStack(method);
if (!stack) {
return {
status: 400,
ok: false,
error: "invalid_request",
message: `Method not permitted in batch: ${method}`,
};
}
const { sub, captured } = createSubContext(ctx, method, body);
try {
await compose([handleErrors, enforceRateLimit, ...stack])(sub);
return {
status: captured.status,
ok: captured.status < 400,
data: captured.body?.data,
policies: captured.body?.policies,
};
} catch (err) {
const error: HttpError = toError(err);
return {
status: typeof error.status === "number" ? error.status : 500,
ok: false,
error: error.id ? snakeCase(error.id) : "internal_error",
message: error.message,
};
}
}
router.post(
"batch",
rateLimiter(RateLimiterStrategy.TwentyFivePerMinute),
auth({ type: AuthenticationType.APP }),
validate(T.BatchSchema),
async (ctx: APIContext<T.BatchReq>) => {
const { requests } = ctx.input.body;
// Allow 1s per sub-request, clamped between a 15s floor and 25s ceiling.
const originalTimeout = ctx.req.socket.timeout || 0;
ctx.req.socket.setTimeout(
Math.min(25000, Math.max(15000, requests.length * 1000))
);
try {
const data: BatchResult[] = [];
// Process in bounded groups so a single batch can't exhaust the pool.
for (const group of chunk(requests, BatchConcurrency)) {
const results = await Promise.all(
group.map((request) =>
dispatch(ctx, request.method, request.body ?? {})
)
);
data.push(...results);
}
ctx.body = { data };
} finally {
ctx.req.socket.setTimeout(originalTimeout);
}
}
);
export default router;
+1
View File
@@ -0,0 +1 @@
export { default } from "./batch";
+25
View File
@@ -0,0 +1,25 @@
import { z } from "zod";
import { BaseSchema } from "../schema";
/** The maximum number of sub-requests permitted in a single batch. */
export const BatchMaxRequests = 25;
export const BatchSchema = BaseSchema.extend({
body: z.object({
requests: z
.array(
z.object({
/** The RPC method to invoke, e.g. "documents.update". */
method: z.string(),
/** The request body passed to the method. */
body: z.record(z.string(), z.unknown()).optional(),
})
)
.min(1)
.max(BatchMaxRequests, {
message: `A batch may contain at most ${BatchMaxRequests} requests`,
}),
}),
});
export type BatchReq = z.infer<typeof BatchSchema>;
+2
View File
@@ -17,6 +17,7 @@ import apiKeys from "./apiKeys";
import attachments from "./attachments";
import auth from "./auth";
import authenticationProviders from "./authenticationProviders";
import batch from "./batch";
import collections from "./collections";
import comments from "./comments/comments";
import cron from "./cron";
@@ -88,6 +89,7 @@ PluginManager.getHooks(Hook.API).forEach((hook) =>
// routes
router.use("/", auth.routes());
router.use("/", authenticationProviders.routes());
router.use("/", batch.routes());
router.use("/", events.routes());
router.use("/", users.routes());
router.use("/", collections.routes());