perf: Query pagination (#11726)

* Add client version header

* Include commit sha in x-client-version header

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* perf: Removes count query for client requests

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Tom MoorandClaude Opus 4.6 authored and GitHub committed 2026-03-11 20:25:23 -04:00
1 parent 16a4b8417e
commit 8d9cd25b4e
3 files changed
+107 -45

No files matched your search

+3
View File
@@ -4,6 +4,8 @@ import queryString from "query-string";
import EDITOR_VERSION from "@shared/editor/version";
import type { JSONObject } from "@shared/types";
import { Scope } from "@shared/types";
import { version } from "../../package.json";
import env from "~/env";
import stores from "~/stores";
import Logger from "./Logger";
import download from "./download";
@@ -109,6 +111,7 @@ class ApiClient {
"cache-control": "no-cache",
"x-editor-version": EDITOR_VERSION,
"x-api-version": "4",
"x-client-version": env.VERSION ? `${version}-${env.VERSION}` : version,
pragma: "no-cache",
...options?.headers,
};
+49 -44
View File
@@ -88,7 +88,7 @@ import ZipHelper from "@server/utils/ZipHelper";
import { convertBareUrlsToEmbedMarkdown } from "@server/utils/embeds";
import { getTeamFromContext } from "@server/utils/passport";
import { assertPresent } from "@server/validation";
import pagination from "../middlewares/pagination";
import pagination, { paginateQuery } from "../middlewares/pagination";
import * as T from "./schema";
import {
loadPublicShare,
@@ -295,24 +295,26 @@ router.post(
// When sorting by index, pagination is already handled by slicing documentIds,
// so we skip the SQL-level offset to avoid double-pagination
const [documents, total] = await Promise.all([
Document.withMembershipScope(user.id).findAll({
where,
order: orderClause as Order,
offset: sort === "index" ? 0 : ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
replacements: {
documentIds,
},
}),
Document.count({ where }),
]);
const { results: documents, pagination } = await paginateQuery(
ctx,
({ offset: queryOffset, limit: queryLimit }) =>
Document.withMembershipScope(user.id).findAll({
where,
order: orderClause as Order,
offset: sort === "index" ? 0 : queryOffset,
limit: queryLimit,
replacements: {
documentIds,
},
}),
() => Document.count({ where })
);
const data = await presentDocuments(ctx, documents);
const policies = presentPolicies(user, documents);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
pagination,
data,
policies,
};
@@ -627,7 +629,6 @@ router.post(
async (ctx: APIContext<T.DocumentsUsersReq>) => {
const { id, userId, query } = ctx.input.body;
const actor = ctx.state.auth.user;
const { offset, limit } = ctx.state.pagination;
const document = await Document.findByPk(id, {
userId: actor.id,
});
@@ -686,17 +687,19 @@ router.post(
const replacements = { query: `%${query}%` };
const [users, total] = await Promise.all([
User.findAll({ where, replacements, offset, limit }),
User.count({
where,
// @ts-expect-error Types are incorrect for count
replacements,
}),
]);
const { results: users, pagination } = await paginateQuery<User>(
ctx,
(opts) => User.findAll({ where, replacements, ...opts }),
() =>
User.count({
where,
// @ts-expect-error Types are incorrect for count
replacements,
}) as unknown as Promise<number>
);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
pagination,
data: users.map((user) => presentUser(user)),
policies: presentPolicies(actor, users),
};
@@ -1991,18 +1994,19 @@ router.post(
],
};
const [total, memberships] = await Promise.all([
UserMembership.count(options),
UserMembership.findAll({
...options,
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
]);
const { results: memberships, pagination } = await paginateQuery(
ctx,
(opts) =>
UserMembership.findAll({
...options,
order: [["createdAt", "DESC"]],
...opts,
}),
() => UserMembership.count(options)
);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
pagination,
data: {
memberships: memberships.map(presentMembership),
users: memberships.map((membership) => presentUser(membership.user)),
@@ -2052,20 +2056,21 @@ router.post(
],
};
const [total, memberships] = await Promise.all([
GroupMembership.count(options),
GroupMembership.findAll({
...options,
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
]);
const { results: memberships, pagination } = await paginateQuery(
ctx,
(opts) =>
GroupMembership.findAll({
...options,
order: [["createdAt", "DESC"]],
...opts,
}),
() => GroupMembership.count(options)
);
const groupMemberships = memberships.map(presentGroupMembership);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
pagination,
data: {
groupMemberships,
groups: await Promise.all(
+55 -1
View File
@@ -2,7 +2,61 @@ import querystring from "node:querystring";
import type { Next } from "koa";
import { Pagination } from "@shared/constants";
import { InvalidRequestError } from "@server/errors";
import type { AppContext } from "@server/types";
import type { AppContext, Pagination as PaginationType } from "@server/types";
/**
* Execute a paginated query, skipping the COUNT query for client requests by
* fetching one extra row to determine if a next page exists.
*
* For client requests (identified by x-client-version header), the find
* function receives `limit + 1` so it can detect the presence of a next page
* without a separate COUNT query. For non-client requests, find and count run
* in parallel and the exact total is returned.
*
* @param ctx - the Koa application context.
* @param find - function that fetches rows given offset and limit.
* @param count - function that returns the total count. Only called for non-client requests.
* @returns the rows for the current page and pagination metadata with total.
*/
export async function paginateQuery<T>(
ctx: AppContext,
find: (opts: { offset: number; limit: number }) => Promise<T[]>,
count: () => Promise<number>
): Promise<{
results: T[];
pagination: PaginationType & { total: number };
}> {
const { offset, limit } = ctx.state.pagination;
const isClientRequest = !!ctx.headers["x-client-version"];
if (isClientRequest) {
const results = await find({ offset, limit: limit + 1 });
const hasNextPage = results.length > limit;
if (hasNextPage) {
results.pop();
}
return {
results,
pagination: {
...ctx.state.pagination,
total: hasNextPage ? offset + limit + 1 : offset + results.length,
},
};
}
const [results, total] = await Promise.all([
find({ offset, limit }),
count(),
]);
return {
results,
pagination: { ...ctx.state.pagination, total },
};
}
export default function pagination() {
return async function paginationMiddleware(ctx: AppContext, next: Next) {