Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Stop inspect_urls calls dying when their isolate runs out of memory (#1048)
Ben Senescu8a8cf8971c2c
diff --git a/src/server/features/gsc/services/GscService.ts b/src/server/features/gsc/services/GscService.tsindex c70c382d..8af33159 100644--- a/src/server/features/gsc/services/GscService.ts+++ b/src/server/features/gsc/services/GscService.ts@@ -243,9 +243,12 @@ type GscInspectUrlsResult = {};/** Inspect 1–N URLs against a project's connected property. Resolves the- * connection once, then inspects each URL; per-URL failures are captured- * inline so one bad URL doesn't fail the batch. Token/grant failures- * propagate so the caller can prompt a reconnect. */+ * connection once, then inspects every URL at once: Google answers each+ * inspection in ~6 s, so a serial batch of ten held the request open for a+ * minute and made it the usual casualty whenever its isolate ran out of+ * memory. Per-URL failures are captured inline so one bad URL doesn't fail+ * the batch. Token/grant failures propagate so the caller can prompt a+ * reconnect. */async function inspectUrls(input: {projectId: string;urls: string[];@@ -261,24 +264,25 @@ async function inspectUrls(input: {userId: connection.connectedByUserId,gscAccountId: connection.gscAccountId ?? undefined,});- const results: GscUrlInspection[] = [];- for (const url of input.urls) {- try {- const result = await client.inspectUrl(- connection.siteUrl,- url,- input.languageCode,- );- results.push({ url, result });- } catch (error) {- if (error instanceof GscTokenError) throw error;- results.push({- url,- result: null,- error: error instanceof Error ? error.message : "Inspection failed",- });- }- }+ const results = await Promise.all(+ input.urls.map(async (url): Promise<GscUrlInspection> => {+ try {+ const result = await client.inspectUrl(+ connection.siteUrl,+ url,+ input.languageCode,+ );+ return { url, result };+ } catch (error) {+ if (error instanceof GscTokenError) throw error;+ return {+ url,+ result: null,+ error: error instanceof Error ? error.message : "Inspection failed",+ };+ }+ }),+ );return {siteUrl: connection.siteUrl,connectedBy: connection.connectedAccountEmail,diff --git a/src/server/lib/gscClient.test.ts b/src/server/lib/gscClient.test.tsindex 19eb3c00..612135eb 100644--- a/src/server/lib/gscClient.test.ts+++ b/src/server/lib/gscClient.test.ts@@ -151,6 +151,20 @@ describe("gscClient", () => {).rejects.toMatchObject({ status: 429 });});+ it("mints the access token once for concurrent requests on one client", async () => {+ mocks.fetch.mockImplementation(async () =>+ jsonResponse({ inspectionResult: {} }),+ );+ const client = createGscClient({ userId: "u1" });++ await Promise.all([+ client.inspectUrl("sc-domain:example.com", "https://example.com/a"),+ client.inspectUrl("sc-domain:example.com", "https://example.com/b"),+ ]);++ expect(mocks.getAccessToken).toHaveBeenCalledTimes(1);+ });+it("throws GscTokenError when no access token can be minted", async () => {mocks.getAccessToken.mockRejectedValue(new Error("revoked"));await expect(diff --git a/src/server/lib/gscClient.ts b/src/server/lib/gscClient.tsindex 8ae94df5..d24349af 100644--- a/src/server/lib/gscClient.ts+++ b/src/server/lib/gscClient.ts@@ -84,19 +84,22 @@ export function createGscClient(opts: {userId: string;gscAccountId?: string;}) {- async function getToken(): Promise<string> {- try {- return await getGoogleAccessToken({- providerId: GSC_OAUTH_PROVIDER_ID,- userId: opts.userId,- accountId: opts.gscAccountId,- });- } catch (error) {+ // One mint per client: a client lives for a single service call, and+ // concurrent requests (inspectUrls fans out) must not race the refresh.+ let tokenPromise: Promise<string> | undefined;+ function getToken(): Promise<string> {+ tokenPromise ??= getGoogleAccessToken({+ providerId: GSC_OAUTH_PROVIDER_ID,+ userId: opts.userId,+ accountId: opts.gscAccountId,+ }).catch((error: unknown) => {+ tokenPromise = undefined;throw new GscTokenError("Could not mint a Search Console access token (grant revoked or expired).",error,);- }+ });+ return tokenPromise;}async function request<T>(diff --git a/vite-plugin-lean-worker-bundle.ts b/vite-plugin-lean-worker-bundle.tsindex 95d502c2..ada44edd 100644--- a/vite-plugin-lean-worker-bundle.ts+++ b/vite-plugin-lean-worker-bundle.ts@@ -93,6 +93,12 @@ const CLIENT_ENTRY_DENYLIST: Array<{ pattern: RegExp; expected: string }> = [* reachable — turning "we verified the chunk by grepping a sourcemap once"* into a permanent regression test. The client build gets the same check* against CLIENT_ENTRY_DENYLIST.+ * 4. An ASCII-only guarantee for the worker chunks. V8 keeps each module's+ * source text alive for the life of the isolate, and one character outside+ * Latin-1 makes it store the whole file at two bytes per character (the+ * 7.8 MB main chunk occupied 15.5 MB of the 128 MB heap). esbuild escapes+ * code (`esbuild.charset` in vite.config.ts) but keeps JSDoc comments+ * verbatim, so `generateBundle` escapes what is left in them.*/export function leanWorkerBundle(): Plugin {return {@@ -152,6 +158,20 @@ export function leanWorkerBundle(): Plugin {return output?.type === "chunk" ? output : undefined;};+ if (environment !== "client") {+ for (const output of Object.values(bundle)) {+ if (output.type !== "chunk") continue;+ // Code is already escaped by esbuild; only comment text remains, and+ // a \uXXXX sequence reads the same there (and stays valid in a+ // string should one slip through). Per UTF-16 unit on purpose, so an+ // astral character becomes its surrogate pair.+ output.code = output.code.replace(+ /[\u0080-\uffff]/g,+ (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,+ );+ }+ }+// Static-import closure from the entry chunks: everything here is// evaluated at isolate startup. Dynamic imports are excluded — landing// there is the point of the lazy boundaries.diff --git a/vite.config.ts b/vite.config.tsindex e8bebce1..7b0f7f2a 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -70,6 +70,29 @@ export default defineConfig(({ mode, command }) => {sourcemap: emitSourcemaps,outDir: emitSourcemaps ? "dist-sourcemaps" : "dist",},+ esbuild: {+ // Emit every chunk as pure ASCII: esbuild rewrites each non-ASCII+ // character in string, regex, and identifier tokens as a \uXXXX escape+ // (Vite's default is raw UTF-8). The parser decodes the escape, so+ // "S\u00e3o Paulo" and "São Paulo" are the same string at runtime and+ // nothing changes behaviour.+ //+ // Why: V8 keeps each module's source text alive for the life of the+ // isolate, and a single character outside Latin-1 (a location name, a+ // typographic dash in a tool description) makes it store the whole file+ // at two bytes per character. The 7.8 MB main worker chunk occupied+ // 15.5 MB of the 128 MB heap; escaped, it occupies 7.8 MB.+ //+ // Trade-offs: each escaped character costs six bytes instead of one to+ // three, a few KB across the bundle and well compressed on the client.+ // Built output shows \u2014 where a comment had an em dash, which only+ // matters to someone reading dist/ directly. esbuild leaves comments+ // verbatim, and one surviving character is enough to lose the whole+ // saving, so vite-plugin-lean-worker-bundle.ts escapes the comment text+ // of the worker chunks after this pass. Nothing fails if either step+ // stops working; the isolate just quietly uses more memory.+ charset: "ascii",+ },plugins: [mcpWidgets(),leanWorkerBundle(),