From 8d9cd25b4e812cc88342d1b1a7fdd34b26cdbcf8 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 11 Mar 2026 20:25:23 -0400 Subject: [PATCH] perf: Query pagination (#11726) * Add client version header * Include commit sha in x-client-version header Co-Authored-By: Claude Opus 4.6 * perf: Removes count query for client requests --------- Co-authored-by: Claude Opus 4.6 --- app/utils/ApiClient.ts | 3 + server/routes/api/documents/documents.ts | 93 +++++++++++---------- server/routes/api/middlewares/pagination.ts | 56 ++++++++++++- 3 files changed, 107 insertions(+), 45 deletions(-) diff --git a/app/utils/ApiClient.ts b/app/utils/ApiClient.ts index 0f1889c25a..58ac9cf59e 100644 --- a/app/utils/ApiClient.ts +++ b/app/utils/ApiClient.ts @@ -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, }; diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 2355b04230..eb2f5c47b0 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -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) => { 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( + ctx, + (opts) => User.findAll({ where, replacements, ...opts }), + () => + User.count({ + where, + // @ts-expect-error Types are incorrect for count + replacements, + }) as unknown as Promise + ); 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( diff --git a/server/routes/api/middlewares/pagination.ts b/server/routes/api/middlewares/pagination.ts index 49a11ab8f8..8276d56337 100644 --- a/server/routes/api/middlewares/pagination.ts +++ b/server/routes/api/middlewares/pagination.ts @@ -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( + ctx: AppContext, + find: (opts: { offset: number; limit: number }) => Promise, + count: () => Promise +): 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) {