Files
outline/server/routes/api/batch/batch.ts
T
Tom MoorandClaude Opus 5.5 00b124d03c chore: Rename APIContext to Context and flatten its fields (#14684)
* chore: Rename APIContext to Context and flatten its fields

Auth and transaction now live directly on the context instead of in
ctx.state and a nested ctx.context, and model helpers read them directly.
APIContext remains as a deprecated alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove deprecated APIContext alias

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* fix: Read auth from context in OAuth provider callbacks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Add withUser and withTransaction context helpers

Replaces manual createContext rebuilds that copy fields from an existing context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove arbitrary property access from Koa context types

AppContext and Context no longer inherit the any index signature from
Koa's DefaultContext, custom fields are declared explicitly, and importing
Koa's loose Context type is disallowed by lint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-23 23:17:06 -05:00

306 lines
9.0 KiB
TypeScript

import { omit, snakeCase } from "es-toolkit/compat";
import type { Middleware } from "koa";
import compose from "koa-compose";
import Router from "@koa/router";
import {
addTags,
getRootSpanFromRequestContext,
setError,
} from "@server/logging/tracer";
import { traceFunction } from "@server/logging/tracing";
import auth from "@server/middlewares/authentication";
import {
defaultRateLimiter,
rateLimiter,
} from "@server/middlewares/rateLimiter";
import validate from "@server/middlewares/validate";
import type { Context, AppContext } from "@server/types";
import { AuthenticationType } from "@server/types";
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
import { BatchableApiMethods } from "@shared/constants";
import { toError } from "@shared/utils/error";
import collections from "../collections";
import documents from "../documents";
import apiErrorHandler from "../middlewares/apiErrorHandler";
import pins from "../pins";
import stars from "../stars";
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>(BatchableApiMethods);
/** Routers searched for an allowed method's middleware stack. */
const dispatchableRouters: Router[] = [documents, collections, stars, pins];
/** The number of sub-requests dispatched in parallel, to limit pool pressure. */
const BatchConcurrency = 2;
/** Methods that run alone, so that their effects apply in request order. */
const sequentialMethods = new Set<string>(["documents.move"]);
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: T.BatchRequestBody
) {
const sub: AppContext = Object.create(ctx);
// Own copies so middleware writes don't leak between concurrent sub-requests
// or back to the parent.
sub.state = { ...ctx.state };
sub.auth = ctx.auth;
sub.transaction = ctx.transaction;
sub.request = Object.create(ctx.request);
// The parent's credential is the actor for every sub-request, so a token in
// the sub-request body must not re-authenticate it as a different one.
sub.request.body = omit(body, ["token"]);
// 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}`,
});
// Credential scope is enforced against originalUrl, so it must also name the
// dispatched method rather than the parent /api/batch path.
Object.defineProperty(sub, "originalUrl", {
configurable: true,
get: () => `/api/${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;
},
});
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: T.BatchRequestBody
): 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);
setError(error);
return {
status: typeof error.status === "number" ? error.status : 500,
ok: false,
error: error.id ? snakeCase(error.id) : "internal_error",
message: error.message,
};
}
}
/**
* Dispatches a single sub-request in its own APM span, named for the method.
*
* @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.
*/
function tracedDispatch(
ctx: AppContext,
method: string,
body: T.BatchRequestBody
): Promise<BatchResult> {
return traceFunction({ spanName: "batch.request", resourceName: method })(
async () => {
const result = await dispatch(ctx, method, body);
addTags({ "http.status_code": result.status });
return result;
}
)();
}
/**
* Splits requests into groups that are dispatched in parallel, bounded so that
* a single batch can't exhaust the pool. Sequential methods get a group each.
*
* @param requests The batched requests, in order.
* @returns the groups to dispatch one after another.
*/
function groupRequests(
requests: T.BatchReq["body"]["requests"]
): T.BatchReq["body"]["requests"][] {
const groups: T.BatchReq["body"]["requests"][] = [];
let group: T.BatchReq["body"]["requests"] = [];
for (const request of requests) {
if (sequentialMethods.has(request.method)) {
if (group.length) {
groups.push(group);
group = [];
}
groups.push([request]);
continue;
}
group.push(request);
if (group.length === BatchConcurrency) {
groups.push(group);
group = [];
}
}
if (group.length) {
groups.push(group);
}
return groups;
}
router.post(
"batch",
rateLimiter(RateLimiterStrategy.TwentyFivePerMinute),
auth({ type: AuthenticationType.APP }),
validate(T.BatchSchema),
async (ctx: Context<T.BatchReq>) => {
const { requests } = ctx.input.body;
// Sub-request routes would otherwise be appended to the APM route name.
addTags(
{
"resource.name": "POST /batch",
"batch.methods": requests.map((request) => request.method).join(","),
},
getRootSpanFromRequestContext(ctx)
);
// 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[] = [];
for (const group of groupRequests(requests)) {
const results = await Promise.all(
group.map((request) =>
tracedDispatch(ctx, request.method, request.body ?? {})
)
);
data.push(...results);
}
ctx.body = { data };
} finally {
ctx.req.socket.setTimeout(originalTimeout);
}
}
);
export default router;