Reduce memory and CPU use of the OpenNext workers (#4788)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
conico974
2026-11-16 10:17:23 +01:00
committed by GitHub
parent c85d84fc1d
commit 9fcde5f487
20 changed files with 111 additions and 77 deletions
@@ -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.
+5
View File
@@ -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.
+12
View File
@@ -1,6 +1,7 @@
// @ts-check // @ts-check
import { networkInterfaces } from 'node:os'; 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. // 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 // 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() { async headers() {
return [ return [
{ {
@@ -3,6 +3,7 @@
"name": "gitbook-open-v2", "name": "gitbook-open-v2",
"compatibility_date": "2026-04-02", "compatibility_date": "2026-04-02",
"keep_names": false, "keep_names": false,
"minify": true,
"compatibility_flags": [ "compatibility_flags": [
"nodejs_compat", "nodejs_compat",
"allow_importable_env", "allow_importable_env",
@@ -50,6 +50,7 @@ export async function handleMcpRequest(
streamableHttpEndpoint: context.linker.toPathInSite(endpoint), streamableHttpEndpoint: context.linker.toPathInSite(endpoint),
maxDuration: 60, maxDuration: 60,
verboseLogs: true, verboseLogs: true,
// SSE needs redis, which next.config.mjs stubs out of the server bundle.
disableSse: true, disableSse: true,
} }
); );
+21 -2
View File
@@ -1,5 +1,6 @@
import { jwtDecode } from 'jwt-decode'; import { jwtDecode } from 'jwt-decode';
import { forbidden, notFound } from 'next/navigation'; import { forbidden, notFound } from 'next/navigation';
import { cache } from 'react';
import rison from 'rison'; import rison from 'rison';
import type { SiteAPIToken } from '@gitbook/api'; import type { SiteAPIToken } from '@gitbook/api';
@@ -27,7 +28,17 @@ export type RouteParams = RouteLayoutParams & {
/** /**
* Get the static context when rendering statically a site. * 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 siteURL = getSiteURLFromParams(params);
const siteURLData = getSiteURLDataFromParams(params); const siteURLData = getSiteURLDataFromParams(params);
@@ -57,7 +68,15 @@ export async function getStaticSiteContext(params: RouteLayoutParams) {
* Get the site context when rendering dynamically. * Get the site context when rendering dynamically.
* The context will depend on the request. * 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 siteURL = getSiteURLFromParams(params);
const siteURLData = getSiteURLDataFromParams(params); const siteURLData = getSiteURLDataFromParams(params);
@@ -1,6 +1,6 @@
import type { DocumentBlockHint } from '@gitbook/api'; import type { DocumentBlockHint } from '@gitbook/api';
import { Icon, type IconName } from '@gitbook/icons'; 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 { Block, type BlockProps } from './Block';
import { Blocks } from './Blocks'; import { Blocks } from './Blocks';
@@ -4,7 +4,7 @@ import {
type DocumentBlockPrompt, type DocumentBlockPrompt,
type SiteCustomizationSettings, type SiteCustomizationSettings,
} from '@gitbook/api'; } from '@gitbook/api';
import { validateIconName } from '@gitbook/icons/icons'; import { validateIconName } from '@gitbook/icons/validateIconName';
import type { BlockProps } from '../Block'; import type { BlockProps } from '../Block';
import { CodeBlock } from '../CodeBlock'; import { CodeBlock } from '../CodeBlock';
@@ -1,6 +1,6 @@
import type { DocumentBlockTabs } from '@gitbook/api'; import type { DocumentBlockTabs } from '@gitbook/api';
import type { IconName } from '@gitbook/icons'; import type { IconName } from '@gitbook/icons';
import { validateIconName } from '@gitbook/icons/icons'; import { validateIconName } from '@gitbook/icons/validateIconName';
import type { BlockProps } from '../Block'; import type { BlockProps } from '../Block';
import { Blocks } from '../Blocks'; import { Blocks } from '../Blocks';
+1 -1
View File
@@ -10,9 +10,9 @@ import {
type SiteCustomizationSettings, type SiteCustomizationSettings,
} from '@gitbook/api'; } from '@gitbook/api';
import { getIconStyle } from '@gitbook/icons/getIconStyle'; import { getIconStyle } from '@gitbook/icons/getIconStyle';
import { validateIconName } from '@gitbook/icons/icons';
import { type InlineIconSource, getInlineIconSourceKey } from '@gitbook/icons/IconSources'; import { type InlineIconSource, getInlineIconSourceKey } from '@gitbook/icons/IconSources';
import { type IconName, IconStyle } from '@gitbook/icons/types'; import { type IconName, IconStyle } from '@gitbook/icons/types';
import { validateIconName } from '@gitbook/icons/validateIconName';
import { GITBOOK_ICONS_ASSET_VERSION } from '@gitbook/icons/version'; import { GITBOOK_ICONS_ASSET_VERSION } from '@gitbook/icons/version';
import { getAssetURL } from '@/lib/assets'; import { getAssetURL } from '@/lib/assets';
@@ -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');
}
@@ -17,4 +17,22 @@ describe('#enrichFilesystem', () => {
'<p>Social platform<br>Hello</p>' '<p>Social platform<br>Hello</p>'
); );
}); });
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('<p>constructor</p>');
expect(paths['/b'].get['x-gitbook-description-html']).toBe('<p>constructor</p>');
});
}); });
+12 -9
View File
@@ -30,14 +30,17 @@ export async function enrichFilesystem(filesystem: Filesystem) {
/** /**
* Create a markdown parser that caches the results of parsing. * Create a markdown parser that caches the results of parsing.
*/ */
const createMarkdownParser = () => (input: string) => { const createMarkdownParser = () => {
const cache: Record<string, Promise<string>> = {}; // A Map rather than an object so descriptions like "constructor" don't hit prototype keys.
const existing = cache[input]; const cache = new Map<string, Promise<string>>();
if (existing) { return (input: string) => {
return existing; const existing = cache.get(input);
} if (existing) {
return existing;
}
const result = parseMarkdown(input); const result = parseMarkdown(input);
cache[input] = result; cache.set(input, result);
return result; return result;
};
}; };
+1 -1
View File
@@ -10,7 +10,7 @@ export async function withVerifySignature<T>(
request: Request, request: Request,
fn: (body: T) => Promise<NextResponse> fn: (body: T) => Promise<NextResponse>
) { ) {
// Fail closed when no secret is configured, consistent with force-revalidate. // Fail closed when no secret is configured.
if (!GITBOOK_SECRET) { if (!GITBOOK_SECRET) {
return NextResponse.json({ error: 'Revalidation is disabled' }, { status: 403 }); return NextResponse.json({ error: 'Revalidation is disabled' }, { status: 403 });
} }
@@ -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' });
}
+2
View File
@@ -53,6 +53,8 @@ async function main() {
await Promise.all([ await Promise.all([
writeDataFile('styles-map', JSON.stringify(onlyStyles, null, 2)), writeDataFile('styles-map', JSON.stringify(onlyStyles, null, 2)),
writeDataFile('icons', JSON.stringify(result, 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 // oxlint-disable-next-line no-console
+5
View File
@@ -12,6 +12,11 @@
"development": "./src/icons.ts", "development": "./src/icons.ts",
"default": "./dist/icons.js" "default": "./dist/icons.js"
}, },
"./validateIconName": {
"types": "./dist/validateIconName.d.ts",
"development": "./src/validateIconName.ts",
"default": "./dist/validateIconName.js"
},
"./types": { "./types": {
"types": "./dist/types.d.ts", "types": "./dist/types.d.ts",
"development": "./src/types.ts", "development": "./src/types.ts",
+1 -12
View File
@@ -18,15 +18,4 @@ export interface IconDefinition {
// @ts-ignore // @ts-ignore
export const icons: IconDefinition[] = rawIcons; export const icons: IconDefinition[] = rawIcons;
let iconNamesSet: Set<string> | null = null; export { validateIconName } from './validateIconName';
/**
* 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);
}
+15
View File
@@ -0,0 +1,15 @@
import iconNames from './data/icon-names.json' with { type: 'json' };
import type { IconName } from './types';
let iconNamesSet: Set<string> | 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);
}
+1
View File
@@ -5,6 +5,7 @@ export default defineConfig([
entry: [ entry: [
'src/index.ts', 'src/index.ts',
'src/icons.ts', 'src/icons.ts',
'src/validateIconName.ts',
'src/types.ts', 'src/types.ts',
'src/getIconStyle.ts', 'src/getIconStyle.ts',
'src/IconSources.ts', 'src/IconSources.ts',