From 9fcde5f487a06c7cb461bccce74ea914a4494435 Mon Sep 17 00:00:00 2001 From: conico974 Date: Mon, 16 Nov 2026 10:17:23 +0100 Subject: [PATCH] Reduce memory and CPU use of the OpenNext workers (#4788) Co-authored-by: Claude Opus 5.5 --- .changeset/icons-validate-icon-name-entry.md | 5 ++ .changeset/lighter-opennext-workers.md | 5 ++ packages/gitbook/next.config.mjs | 12 +++++ .../customWorkers/middlewareWrangler.jsonc | 1 + .../[siteData]/~gitbook/mcp/handler.ts | 1 + packages/gitbook/src/app/utils.ts | 23 ++++++++- .../src/components/DocumentView/Hint.tsx | 2 +- .../components/DocumentView/Prompt/Prompt.tsx | 2 +- .../src/components/DocumentView/Tabs/Tabs.tsx | 2 +- packages/gitbook/src/lib/icons/inline.ts | 2 +- packages/gitbook/src/lib/mcp/redis-stub.ts | 7 +++ .../gitbook/src/lib/openapi/enrich.test.ts | 18 +++++++ packages/gitbook/src/lib/openapi/enrich.ts | 21 ++++---- packages/gitbook/src/lib/routes.ts | 2 +- .../pages/api/~gitbook/force-revalidate.ts | 49 ------------------- packages/icons/bin/gen-list.js | 2 + packages/icons/package.json | 5 ++ packages/icons/src/icons.ts | 13 +---- packages/icons/src/validateIconName.ts | 15 ++++++ packages/icons/tsdown.config.ts | 1 + 20 files changed, 111 insertions(+), 77 deletions(-) create mode 100644 .changeset/icons-validate-icon-name-entry.md create mode 100644 .changeset/lighter-opennext-workers.md create mode 100644 packages/gitbook/src/lib/mcp/redis-stub.ts delete mode 100644 packages/gitbook/src/pages/api/~gitbook/force-revalidate.ts create mode 100644 packages/icons/src/validateIconName.ts diff --git a/.changeset/icons-validate-icon-name-entry.md b/.changeset/icons-validate-icon-name-entry.md new file mode 100644 index 000000000..bcc919d40 --- /dev/null +++ b/.changeset/icons-validate-icon-name-entry.md @@ -0,0 +1,5 @@ +--- +"@gitbook/icons": minor +--- + +Add a `@gitbook/icons/validateIconName` entry that validates icon names without loading the icon labels and search terms. diff --git a/.changeset/lighter-opennext-workers.md b/.changeset/lighter-opennext-workers.md new file mode 100644 index 000000000..e77b87d24 --- /dev/null +++ b/.changeset/lighter-opennext-workers.md @@ -0,0 +1,5 @@ +--- +"gitbook": patch +--- + +Reduce memory and CPU use of the OpenNext workers: minify the middleware, resolve the site context once per request, cache parsed OpenAPI descriptions across a spec, drop the redis client and the unused force-revalidate route from the server bundle. diff --git a/packages/gitbook/next.config.mjs b/packages/gitbook/next.config.mjs index ce1c0113b..7b8fd7524 100644 --- a/packages/gitbook/next.config.mjs +++ b/packages/gitbook/next.config.mjs @@ -1,6 +1,7 @@ // @ts-check import { networkInterfaces } from 'node:os'; +import { fileURLToPath } from 'node:url'; // Next blocks its dev client and HMR when a physical device opens the server over a LAN address. // Needed to hydrate the dev client on physical phones/tablets over the internal network @@ -119,6 +120,17 @@ const nextConfig = { ], }, + webpack(config, { isServer }) { + if (isServer) { + // mcp-handler only needs redis for SSE, which we disable: keep the client out of the server bundle. + config.resolve.alias = { + ...config.resolve.alias, + redis$: fileURLToPath(new URL('./src/lib/mcp/redis-stub.ts', import.meta.url)), + }; + } + return config; + }, + async headers() { return [ { diff --git a/packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc b/packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc index 9e08e264d..63dea1b92 100644 --- a/packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc +++ b/packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc @@ -3,6 +3,7 @@ "name": "gitbook-open-v2", "compatibility_date": "2026-04-02", "keep_names": false, + "minify": true, "compatibility_flags": [ "nodejs_compat", "allow_importable_env", diff --git a/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/mcp/handler.ts b/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/mcp/handler.ts index 97c234b0c..c3645c08e 100644 --- a/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/mcp/handler.ts +++ b/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/mcp/handler.ts @@ -50,6 +50,7 @@ export async function handleMcpRequest( streamableHttpEndpoint: context.linker.toPathInSite(endpoint), maxDuration: 60, verboseLogs: true, + // SSE needs redis, which next.config.mjs stubs out of the server bundle. disableSse: true, } ); diff --git a/packages/gitbook/src/app/utils.ts b/packages/gitbook/src/app/utils.ts index 727105cd7..2655e28ba 100644 --- a/packages/gitbook/src/app/utils.ts +++ b/packages/gitbook/src/app/utils.ts @@ -1,5 +1,6 @@ import { jwtDecode } from 'jwt-decode'; import { forbidden, notFound } from 'next/navigation'; +import { cache } from 'react'; import rison from 'rison'; import type { SiteAPIToken } from '@gitbook/api'; @@ -27,7 +28,17 @@ export type RouteParams = RouteLayoutParams & { /** * Get the static context when rendering statically a site. */ -export async function getStaticSiteContext(params: RouteLayoutParams) { +export function getStaticSiteContext(params: RouteLayoutParams) { + return getStaticSiteContextCached(params.mode, params.siteURL, params.siteData); +} + +// Layouts, pages and their metadata functions each resolve the context: share it per request. +// Keyed on the raw strings as `params` objects aren't guaranteed to be the same reference. +const getStaticSiteContextCached = cache((mode: string, siteURL: string, siteData: string) => + resolveStaticSiteContext({ mode, siteURL, siteData }) +); + +async function resolveStaticSiteContext(params: RouteLayoutParams) { const siteURL = getSiteURLFromParams(params); const siteURLData = getSiteURLDataFromParams(params); @@ -57,7 +68,15 @@ export async function getStaticSiteContext(params: RouteLayoutParams) { * Get the site context when rendering dynamically. * The context will depend on the request. */ -export async function getDynamicSiteContext(params: RouteLayoutParams) { +export function getDynamicSiteContext(params: RouteLayoutParams) { + return getDynamicSiteContextCached(params.mode, params.siteURL, params.siteData); +} + +const getDynamicSiteContextCached = cache((mode: string, siteURL: string, siteData: string) => + resolveDynamicSiteContext({ mode, siteURL, siteData }) +); + +async function resolveDynamicSiteContext(params: RouteLayoutParams) { const siteURL = getSiteURLFromParams(params); const siteURLData = getSiteURLDataFromParams(params); diff --git a/packages/gitbook/src/components/DocumentView/Hint.tsx b/packages/gitbook/src/components/DocumentView/Hint.tsx index 4e043272a..e54dbb70d 100644 --- a/packages/gitbook/src/components/DocumentView/Hint.tsx +++ b/packages/gitbook/src/components/DocumentView/Hint.tsx @@ -1,6 +1,6 @@ import type { DocumentBlockHint } from '@gitbook/api'; import { Icon, type IconName } from '@gitbook/icons'; -import { validateIconName } from '@gitbook/icons/icons'; +import { validateIconName } from '@gitbook/icons/validateIconName'; import { Block, type BlockProps } from './Block'; import { Blocks } from './Blocks'; diff --git a/packages/gitbook/src/components/DocumentView/Prompt/Prompt.tsx b/packages/gitbook/src/components/DocumentView/Prompt/Prompt.tsx index 27610eb34..7a6fc3a8d 100644 --- a/packages/gitbook/src/components/DocumentView/Prompt/Prompt.tsx +++ b/packages/gitbook/src/components/DocumentView/Prompt/Prompt.tsx @@ -4,7 +4,7 @@ import { type DocumentBlockPrompt, type SiteCustomizationSettings, } from '@gitbook/api'; -import { validateIconName } from '@gitbook/icons/icons'; +import { validateIconName } from '@gitbook/icons/validateIconName'; import type { BlockProps } from '../Block'; import { CodeBlock } from '../CodeBlock'; diff --git a/packages/gitbook/src/components/DocumentView/Tabs/Tabs.tsx b/packages/gitbook/src/components/DocumentView/Tabs/Tabs.tsx index 76daf3a30..4c85f0a4a 100644 --- a/packages/gitbook/src/components/DocumentView/Tabs/Tabs.tsx +++ b/packages/gitbook/src/components/DocumentView/Tabs/Tabs.tsx @@ -1,6 +1,6 @@ import type { DocumentBlockTabs } from '@gitbook/api'; import type { IconName } from '@gitbook/icons'; -import { validateIconName } from '@gitbook/icons/icons'; +import { validateIconName } from '@gitbook/icons/validateIconName'; import type { BlockProps } from '../Block'; import { Blocks } from '../Blocks'; diff --git a/packages/gitbook/src/lib/icons/inline.ts b/packages/gitbook/src/lib/icons/inline.ts index c4f925e47..b424dd8b4 100644 --- a/packages/gitbook/src/lib/icons/inline.ts +++ b/packages/gitbook/src/lib/icons/inline.ts @@ -10,9 +10,9 @@ import { type SiteCustomizationSettings, } from '@gitbook/api'; import { getIconStyle } from '@gitbook/icons/getIconStyle'; -import { validateIconName } from '@gitbook/icons/icons'; import { type InlineIconSource, getInlineIconSourceKey } from '@gitbook/icons/IconSources'; import { type IconName, IconStyle } from '@gitbook/icons/types'; +import { validateIconName } from '@gitbook/icons/validateIconName'; import { GITBOOK_ICONS_ASSET_VERSION } from '@gitbook/icons/version'; import { getAssetURL } from '@/lib/assets'; diff --git a/packages/gitbook/src/lib/mcp/redis-stub.ts b/packages/gitbook/src/lib/mcp/redis-stub.ts new file mode 100644 index 000000000..a510648dc --- /dev/null +++ b/packages/gitbook/src/lib/mcp/redis-stub.ts @@ -0,0 +1,7 @@ +/** + * Replaces `redis` in the server bundle (see next.config.mjs). mcp-handler imports it statically + * but only uses it for SSE transport, which we disable. + */ +export function createClient(): never { + throw new Error('redis is not available: SSE transport is disabled for the MCP handler'); +} diff --git a/packages/gitbook/src/lib/openapi/enrich.test.ts b/packages/gitbook/src/lib/openapi/enrich.test.ts index c0524de7d..171f7563f 100644 --- a/packages/gitbook/src/lib/openapi/enrich.test.ts +++ b/packages/gitbook/src/lib/openapi/enrich.test.ts @@ -17,4 +17,22 @@ describe('#enrichFilesystem', () => { '

Social platform
Hello

' ); }); + + it('parses descriptions that collide with Object.prototype keys', async () => { + const { filesystem } = await parseOpenAPI({ + value: JSON.stringify({ + openapi: '3.0.0', + info: { title: 'Test', version: '1.0.0' }, + paths: { + '/a': { get: { description: 'constructor', responses: {} } }, + '/b': { get: { description: 'constructor', responses: {} } }, + }, + }), + rootURL: null, + }); + const enriched = await enrichFilesystem(filesystem); + const paths = enriched[0]?.specification.paths; + expect(paths['/a'].get['x-gitbook-description-html']).toBe('

constructor

'); + expect(paths['/b'].get['x-gitbook-description-html']).toBe('

constructor

'); + }); }); diff --git a/packages/gitbook/src/lib/openapi/enrich.ts b/packages/gitbook/src/lib/openapi/enrich.ts index 570fc6ce2..527230938 100644 --- a/packages/gitbook/src/lib/openapi/enrich.ts +++ b/packages/gitbook/src/lib/openapi/enrich.ts @@ -30,14 +30,17 @@ export async function enrichFilesystem(filesystem: Filesystem) { /** * Create a markdown parser that caches the results of parsing. */ -const createMarkdownParser = () => (input: string) => { - const cache: Record> = {}; - const existing = cache[input]; - if (existing) { - return existing; - } +const createMarkdownParser = () => { + // A Map rather than an object so descriptions like "constructor" don't hit prototype keys. + const cache = new Map>(); + return (input: string) => { + const existing = cache.get(input); + if (existing) { + return existing; + } - const result = parseMarkdown(input); - cache[input] = result; - return result; + const result = parseMarkdown(input); + cache.set(input, result); + return result; + }; }; diff --git a/packages/gitbook/src/lib/routes.ts b/packages/gitbook/src/lib/routes.ts index 4b4e56b9b..e8ba234c6 100644 --- a/packages/gitbook/src/lib/routes.ts +++ b/packages/gitbook/src/lib/routes.ts @@ -10,7 +10,7 @@ export async function withVerifySignature( request: Request, fn: (body: T) => Promise ) { - // Fail closed when no secret is configured, consistent with force-revalidate. + // Fail closed when no secret is configured. if (!GITBOOK_SECRET) { return NextResponse.json({ error: 'Revalidation is disabled' }, { status: 403 }); } diff --git a/packages/gitbook/src/pages/api/~gitbook/force-revalidate.ts b/packages/gitbook/src/pages/api/~gitbook/force-revalidate.ts deleted file mode 100644 index 7a2255ef3..000000000 --- a/packages/gitbook/src/pages/api/~gitbook/force-revalidate.ts +++ /dev/null @@ -1,49 +0,0 @@ -import type { NextApiRequest, NextApiResponse } from 'next'; -import crypto from 'node:crypto'; - -interface JsonBody { - // The paths need to be the rewritten one, `res.revalidate` call don't go through the middleware - paths: string[]; -} - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - // Only allow POST requests - if (req.method !== 'POST') { - return res.status(405).json({ error: 'Method not allowed' }); - } - const signatureHeader = req.headers['x-gitbook-signature'] as string | undefined; - if (!signatureHeader) { - return res.status(400).json({ error: 'Missing signature header' }); - } - // We cannot use env from `@/v2/lib/env` here as it make it crash because of the import "server-only" in the file. - if (process.env.GITBOOK_SECRET) { - try { - const computedSignature = crypto - .createHmac('sha256', process.env.GITBOOK_SECRET) - .update(JSON.stringify(req.body)) - .digest('hex'); - - if (computedSignature === signatureHeader) { - const results = await Promise.allSettled( - (req.body as JsonBody).paths.map((path) => { - // oxlint-disable-next-line no-console - console.log(`Revalidating path: ${path}`); - return res.revalidate(path); - }) - ); - return res.status(200).json({ - success: results.every((result) => result.status === 'fulfilled'), - errors: results - .filter((result) => result.status === 'rejected') - .map((result) => (result as PromiseRejectedResult).reason), - }); - } - return res.status(401).json({ error: 'Invalid signature' }); - } catch (error) { - console.error('Error during revalidation:', error); - return res.status(400).json({ error: 'Invalid request or unable to parse JSON' }); - } - } - // If no secret is set, we do not allow revalidation - return res.status(403).json({ error: 'Revalidation is disabled' }); -} diff --git a/packages/icons/bin/gen-list.js b/packages/icons/bin/gen-list.js index a687c005e..eb1a58f47 100644 --- a/packages/icons/bin/gen-list.js +++ b/packages/icons/bin/gen-list.js @@ -53,6 +53,8 @@ async function main() { await Promise.all([ writeDataFile('styles-map', JSON.stringify(onlyStyles, null, 2)), writeDataFile('icons', JSON.stringify(result, null, 2)), + // Names only, so validating an icon name doesn't load every label and search term. + writeDataFile('icon-names', JSON.stringify(result.map((entry) => entry.icon))), ]); // oxlint-disable-next-line no-console diff --git a/packages/icons/package.json b/packages/icons/package.json index 34b874053..f712a02d4 100644 --- a/packages/icons/package.json +++ b/packages/icons/package.json @@ -12,6 +12,11 @@ "development": "./src/icons.ts", "default": "./dist/icons.js" }, + "./validateIconName": { + "types": "./dist/validateIconName.d.ts", + "development": "./src/validateIconName.ts", + "default": "./dist/validateIconName.js" + }, "./types": { "types": "./dist/types.d.ts", "development": "./src/types.ts", diff --git a/packages/icons/src/icons.ts b/packages/icons/src/icons.ts index 25dd06c0c..3db46b58b 100644 --- a/packages/icons/src/icons.ts +++ b/packages/icons/src/icons.ts @@ -18,15 +18,4 @@ export interface IconDefinition { // @ts-ignore export const icons: IconDefinition[] = rawIcons; -let iconNamesSet: Set | null = null; - -/** - * Validate that the icon name is valid. - */ -export function validateIconName(icon: IconName | string): icon is IconName { - if (!iconNamesSet) { - iconNamesSet = new Set(icons.map((icon) => icon.icon)); - } - - return iconNamesSet.has(icon); -} +export { validateIconName } from './validateIconName'; diff --git a/packages/icons/src/validateIconName.ts b/packages/icons/src/validateIconName.ts new file mode 100644 index 000000000..14293a814 --- /dev/null +++ b/packages/icons/src/validateIconName.ts @@ -0,0 +1,15 @@ +import iconNames from './data/icon-names.json' with { type: 'json' }; +import type { IconName } from './types'; + +let iconNamesSet: Set | null = null; + +/** + * Validate that the icon name is valid. + */ +export function validateIconName(icon: IconName | string): icon is IconName { + if (!iconNamesSet) { + iconNamesSet = new Set(iconNames); + } + + return iconNamesSet.has(icon); +} diff --git a/packages/icons/tsdown.config.ts b/packages/icons/tsdown.config.ts index c772c7e8b..ec0119855 100644 --- a/packages/icons/tsdown.config.ts +++ b/packages/icons/tsdown.config.ts @@ -5,6 +5,7 @@ export default defineConfig([ entry: [ 'src/index.ts', 'src/icons.ts', + 'src/validateIconName.ts', 'src/types.ts', 'src/getIconStyle.ts', 'src/IconSources.ts',