From ec4770d94a1dcce42077b290329992f78d2fb0df Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Sun, 8 Nov 2026 09:12:43 +0000 Subject: [PATCH 1/3] Read registry responses within a size limit and one timeout apiGet parsed every registry response whole, with no size limit, and cleared its timeout once headers arrived, so a slow body never timed out. Docs pages were fetched with no timeout at all. A package's metadata can carry 10,000 versions with a 128 KB lpmConfig each, which the server parsed to read about ten fields. Bodies are now read up to 10 MB (the CLI's output limit) under one 30 s timeout that covers the request and the body. A larger body is cancelled and returned as an error without a retry. lpm_browse_source lists at most 2,000 paths and reports the total, since a tarball can hold 20,000 entries. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + lib/__tests__/api.test.js | 111 +++++++++++- lib/__tests__/tools/browse-source.test.js | 22 +++ lib/api.js | 209 ++++++++++++++++++---- lib/constants.js | 4 + lib/tools/browse-source.js | 24 ++- lib/tools/docs.js | 29 ++- 7 files changed, 345 insertions(+), 61 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24353ec..7807365 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to this project will be documented in this file. +## [Unreleased] + +### Fixed + +- **Registry and docs responses have a size limit and a full timeout** — Bodies are read up to 10 MB, the CLI's output limit; a larger one is cancelled and the tool returns an error instead of parsing it. The 30-second timeout now runs until the body has been read, so a server that sends headers and then stalls no longer hangs the call. Documentation pages and the docs index use the same limits, and had no timeout before +- **`lpm_browse_source` lists at most 2,000 paths** — A larger tree reports `treeTotal`, `treeTruncated` and a warning to list a directory with `path`, instead of passing up to 20,000 paths to the model + ## [0.3.0] - 2026-11-08 ### Changed diff --git a/lib/__tests__/api.test.js b/lib/__tests__/api.test.js index a8dcd5d..dac625c 100644 --- a/lib/__tests__/api.test.js +++ b/lib/__tests__/api.test.js @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" -import { apiGet, registryGet } from "../api.js" +import { apiGet, registryGet, textGet } from "../api.js" +import { MAX_RESPONSE_BYTES, REQUEST_TIMEOUT_MS } from "../constants.js" const mockFetch = vi.fn() @@ -127,6 +128,114 @@ describe("api", () => { }) }) + describe("response bodies", () => { + function endlessBody(onCancel) { + const chunk = new TextEncoder().encode(`"${"x".repeat(64 * 1024)}",`) + return new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("[")) + }, + pull(controller) { + controller.enqueue(chunk) + }, + cancel: onCancel, + }) + } + + function stalledBody(signal) { + return new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{"versions":{')) + signal.addEventListener("abort", () => + controller.error(signal.reason), + ) + }, + }) + } + + afterEach(() => { + vi.useRealTimers() + }) + + it("stops reading a body past the size limit and reports it without retrying", async () => { + let cancelled = 0 + mockFetch.mockImplementation( + async () => new Response(endlessBody(() => cancelled++)), + ) + + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(mockFetch).toHaveBeenCalledTimes(1) + expect(cancelled).toBe(1) + expect(result.ok).toBe(false) + expect(result.data.error).toMatch(/larger than 10 MB/) + }) + + it("doesn't read a body whose declared size is past the limit", async () => { + let cancelled = 0 + mockFetch.mockImplementation( + async () => + new Response( + endlessBody(() => cancelled++), + { + headers: { "content-length": String(MAX_RESPONSE_BYTES + 1) }, + }, + ), + ) + + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(cancelled).toBe(1) + expect(result.data.error).toMatch(/larger than 10 MB/) + }) + + it("keeps the timeout running until the body has been read", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + mockFetch.mockImplementation( + async (_url, init) => new Response(stalledBody(init.signal)), + ) + + const pending = apiGet("https://lpm.dev/api/test", null) + await vi.advanceTimersByTimeAsync((REQUEST_TIMEOUT_MS + 10_000) * 3) + const result = await pending + + expect(mockFetch).toHaveBeenCalledTimes(3) + expect(result).toEqual({ + ok: false, + status: 0, + data: { error: "Request timed out" }, + }) + }) + + it("reads text bodies within the same limit and timeout", async () => { + mockFetch.mockImplementationOnce( + async () => new Response("# Docs\n", { status: 200 }), + ) + expect(await textGet("https://lpm.dev/api/docs")).toEqual({ + ok: true, + status: 200, + text: "# Docs\n", + }) + + mockFetch.mockImplementationOnce(async () => new Response(endlessBody())) + const oversized = await textGet("https://lpm.dev/api/docs") + expect(oversized.ok).toBe(false) + expect(oversized.error).toMatch(/larger than 10 MB/) + + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + mockFetch.mockImplementationOnce( + async (_url, init) => new Response(stalledBody(init.signal)), + ) + const pending = textGet("https://lpm.dev/api/docs") + await vi.advanceTimersByTimeAsync(REQUEST_TIMEOUT_MS + 1) + expect(await pending).toEqual({ + ok: false, + status: 0, + error: "Request timed out", + }) + }) + }) + describe("registryGet", () => { it("prepends /api/registry to the path", async () => { mockFetch.mockResolvedValueOnce(jsonResponse({ ok: true })) diff --git a/lib/__tests__/tools/browse-source.test.js b/lib/__tests__/tools/browse-source.test.js index 5a9458e..97bc786 100644 --- a/lib/__tests__/tools/browse-source.test.js +++ b/lib/__tests__/tools/browse-source.test.js @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest" import { MemoryCache } from "../../cache.js" +import { MAX_SOURCE_TREE_ENTRIES } from "../../constants.js" import { browseSource } from "../../tools/browse-source.js" vi.mock("../../api.js", () => ({ @@ -61,6 +62,27 @@ describe("browseSource tool", () => { expect(result.content[0].text).toContain("Authentication required") }) + it("lists at most the tree limit and says how many paths there are", async () => { + const tree = Array.from( + { length: 5_000 }, + (_, index) => `src/file-${index}.js`, + ) + registryGet.mockResolvedValueOnce({ + ok: true, + status: 200, + data: { ...MOCK_TREE_RESPONSE, tree }, + }) + + const result = await browseSource({ name: "alice.ui-kit" }, createContext()) + const data = JSON.parse(result.content[0].text) + + expect(data.tree).toHaveLength(MAX_SOURCE_TREE_ENTRIES) + expect(data.tree[0]).toBe("src/file-0.js") + expect(data.treeTotal).toBe(5_000) + expect(data.treeTruncated).toBe(true) + expect(data.warning).toMatch(/first 2000 of 5000 paths/) + }) + it("returns file tree when no path specified", async () => { registryGet.mockResolvedValueOnce({ ok: true, diff --git a/lib/api.js b/lib/api.js index a70b724..8f068ee 100644 --- a/lib/api.js +++ b/lib/api.js @@ -1,6 +1,7 @@ // CRITICAL: Never use console.log() — it corrupts the MCP stdio transport import { + MAX_RESPONSE_BYTES, MAX_RETRIES, REQUEST_TIMEOUT_MS, RETRY_BACKOFF_MULTIPLIER, @@ -33,6 +34,89 @@ function parseRetryAfter(retryAfter) { return RETRY_BASE_DELAY_MS } +class ResponseTooLargeError extends Error { + constructor() { + super(`Response was larger than ${MAX_RESPONSE_BYTES / (1024 * 1024)} MB`) + this.name = "ResponseTooLargeError" + } +} + +async function readStreamWithin(body) { + const reader = body.getReader() + const chunks = [] + let length = 0 + for (;;) { + const { done, value } = await reader.read() + if (done) break + length += value.byteLength + if (length > MAX_RESPONSE_BYTES) { + await reader.cancel().catch(() => {}) + throw new ResponseTooLargeError() + } + chunks.push(value) + } + return Buffer.concat(chunks, length).toString("utf8") +} + +/** + * Reads a body as text, up to MAX_RESPONSE_BYTES. A body past the limit is + * cancelled and rejects with ResponseTooLargeError. + */ +async function readTextWithin(response) { + const declared = Number(response.headers?.get?.("content-length")) + if (declared > MAX_RESPONSE_BYTES) { + await response.body?.cancel?.().catch(() => {}) + throw new ResponseTooLargeError() + } + if (typeof response.body?.getReader === "function") { + return readStreamWithin(response.body) + } + return typeof response.text === "function" ? response.text() : "" +} + +/** Parses a JSON body within the size limit; a malformed body reads as `{}`. */ +async function readJsonWithin(response) { + // A response without a body stream (no content, or a test double). + if ( + typeof response.body?.getReader !== "function" && + typeof response.json === "function" + ) { + return response.json().catch(() => ({})) + } + const text = await readTextWithin(response) + try { + return JSON.parse(text) + } catch { + return {} + } +} + +function discardBody(response) { + response.body?.cancel?.().catch(() => {}) +} + +/** + * Runs `read` on a GET response with one timeout covering both the request + * and the body, so a server that sends headers and then stalls still times + * out. + * + * @template T + * @param {string} url + * @param {RequestInit} init + * @param {(response: Response) => Promise} read + * @returns {Promise} + */ +async function fetchWithin(url, init, read) { + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) + try { + const response = await fetch(url, { ...init, signal: controller.signal }) + return await read(response) + } finally { + clearTimeout(timeoutId) + } +} + /** * Make a GET request with retry, timeout, and rate limit handling. * @@ -49,50 +133,67 @@ export async function apiGet(url, token) { let lastError = null for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - const controller = new AbortController() - const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) - try { - const response = await fetch(url, { - method: "GET", - headers, - signal: controller.signal, - }) - - clearTimeout(timeoutId) - - // No retry on auth errors - if (response.status === 401 || response.status === 403) { - const data = await response.json().catch(() => ({})) - return { ok: false, status: response.status, data } - } + const outcome = await fetchWithin( + url, + { method: "GET", headers }, + async response => { + // No retry on auth errors + if (response.status === 401 || response.status === 403) { + return { + result: { + ok: false, + status: response.status, + data: await readJsonWithin(response), + }, + } + } - // Rate limiting - if (response.status === 429) { - const retryAfter = response.headers.get("Retry-After") - const delayMs = parseRetryAfter(retryAfter) + // Rate limiting + if (response.status === 429) { + discardBody(response) + if (attempt < MAX_RETRIES) { + return { + retryAfterMs: parseRetryAfter( + response.headers.get("Retry-After"), + ), + } + } + return { + result: { + ok: false, + status: 429, + data: { error: "Rate limited" }, + }, + } + } - if (attempt < MAX_RETRIES) { - await sleep(delayMs) - continue - } + // Retryable server errors + if ( + RETRYABLE_STATUS_CODES.includes(response.status) && + attempt < MAX_RETRIES + ) { + discardBody(response) + return { retryAfterMs: getBackoffDelay(attempt) } + } - return { ok: false, status: 429, data: { error: "Rate limited" } } - } - - // Retryable server errors - if ( - RETRYABLE_STATUS_CODES.includes(response.status) && - attempt < MAX_RETRIES - ) { - await sleep(getBackoffDelay(attempt)) - continue - } + return { + result: { + ok: response.ok, + status: response.status, + data: await readJsonWithin(response), + }, + } + }, + ) - const data = await response.json().catch(() => ({})) - return { ok: response.ok, status: response.status, data } + if (outcome.result) return outcome.result + await sleep(outcome.retryAfterMs) } catch (error) { - clearTimeout(timeoutId) + // The same body would be too large again. + if (error instanceof ResponseTooLargeError) { + return { ok: false, status: 0, data: { error: error.message } } + } lastError = error @@ -120,6 +221,38 @@ export async function apiGet(url, token) { } } +/** + * GET a text body once, within the request timeout and size limit. + * + * @param {string} url + * @param {Record} [headers] + * @returns {Promise<{ok: true, status: number, text: string} | {ok: false, status: number, text?: string, error?: string}>} + */ +export async function textGet(url, headers = { Accept: "text/plain" }) { + try { + return await fetchWithin( + url, + { method: "GET", headers }, + async response => { + if (!response.ok) { + discardBody(response) + return { ok: false, status: response.status } + } + return { + ok: true, + status: response.status, + text: await readTextWithin(response), + } + }, + ) + } catch (error) { + if (error.name === "AbortError") { + return { ok: false, status: 0, error: "Request timed out" } + } + return { ok: false, status: 0, error: error.message || "Network error" } + } +} + /** * GET from the registry API (/api/registry prefix). * diff --git a/lib/constants.js b/lib/constants.js index c32959e..89f40dc 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -6,6 +6,10 @@ export const KEYTAR_SERVICE_NAME = "lpm-cli" export const KEYTAR_ACCOUNT_PREFIX = "auth-token" export const REQUEST_TIMEOUT_MS = 30_000 +// Matches the CLI output limit. A registry response is parsed whole on the +// server's only thread, and package documents can grow with every version. +export const MAX_RESPONSE_BYTES = 10 * 1024 * 1024 +export const MAX_SOURCE_TREE_ENTRIES = 2_000 export const MAX_RETRIES = 2 export const RETRY_BASE_DELAY_MS = 1_000 export const RETRY_MAX_DELAY_MS = 10_000 diff --git a/lib/tools/browse-source.js b/lib/tools/browse-source.js index 55a6ba0..2b55324 100644 --- a/lib/tools/browse-source.js +++ b/lib/tools/browse-source.js @@ -1,5 +1,5 @@ import { registryGet } from "../api.js" -import { CACHE_TTL } from "../constants.js" +import { CACHE_TTL, MAX_SOURCE_TREE_ENTRIES } from "../constants.js" import { errorResponse, parseName, textResponse } from "../format.js" /** @@ -85,20 +85,32 @@ export async function browseSource({ name, version, path }, ctx) { ecosystem: data.ecosystem, } - // Always include tree - response.tree = data.tree || [] + // Always include tree, up to the limit: a tarball can hold 20,000 entries. + const tree = Array.isArray(data.tree) ? data.tree : [] + response.tree = tree.slice(0, MAX_SOURCE_TREE_ENTRIES) + if (tree.length > MAX_SOURCE_TREE_ENTRIES) { + response.treeTotal = tree.length + response.treeTruncated = true + } // Include files if present (only when path was requested) if (data.files && data.files.length > 0) { response.files = data.files } - // Include truncation warning + const warnings = [] + if (response.treeTruncated) { + warnings.push( + `The tree lists the first ${MAX_SOURCE_TREE_ENTRIES} of ${tree.length} paths. Use the \`path\` parameter to list a directory.`, + ) + } if (data.truncated) { response.truncated = true - response.warning = - "Response was truncated due to size limits. Use the `path` parameter to request specific files or directories." + warnings.push( + "Response was truncated due to size limits. Use the `path` parameter to request specific files or directories.", + ) } + if (warnings.length) response.warning = warnings.join(" ") // Include package config if present (helps AI understand package structure) if (data.lpmConfig) { diff --git a/lib/tools/docs.js b/lib/tools/docs.js index ca7628d..b7360d5 100644 --- a/lib/tools/docs.js +++ b/lib/tools/docs.js @@ -1,3 +1,4 @@ +import { textGet } from "../api.js" import { CACHE_TTL } from "../constants.js" import { errorResponse, textResponse } from "../format.js" @@ -22,18 +23,19 @@ export async function docs({ page, query }, ctx) { const cached = ctx.cache.get(cacheKey) if (cached) return cached - const response = await fetchText(`${DOCS_BASE_URL}/${slug}`) + const response = await textGet(`${DOCS_BASE_URL}/${slug}`) if (!response.ok) { if (response.status === 404) { return errorResponse( `Documentation page "${slug}" not found. Use this tool without a page parameter to see all available pages.`, ) } - return errorResponse(`Failed to fetch docs (${response.status})`) + return errorResponse( + `Failed to fetch docs (${response.error ?? response.status})`, + ) } - const content = await response.text() - const result = textResponse(content) + const result = textResponse(response.text) ctx.cache.set(cacheKey, result, CACHE_TTL.LONG) return result } @@ -43,11 +45,13 @@ export async function docs({ page, query }, ctx) { let indexText = ctx.cache.get(cacheKey) if (!indexText) { - const response = await fetchText(DOCS_BASE_URL) + const response = await textGet(DOCS_BASE_URL) if (!response.ok) { - return errorResponse(`Failed to fetch docs index (${response.status})`) + return errorResponse( + `Failed to fetch docs index (${response.error ?? response.status})`, + ) } - indexText = await response.text() + indexText = response.text ctx.cache.set(cacheKey, indexText, CACHE_TTL.LONG) } else { // Cache stores the textResponse wrapper, extract the text @@ -78,10 +82,9 @@ export async function docs({ page, query }, ctx) { const results = [] for (const match of matches.slice(0, 3)) { const slug = match.split(" — ")[0].trim() - const response = await fetchText(`${DOCS_BASE_URL}/${slug}`) + const response = await textGet(`${DOCS_BASE_URL}/${slug}`) if (response.ok) { - const content = await response.text() - results.push(`--- ${slug} ---\n${content}`) + results.push(`--- ${slug} ---\n${response.text}`) } } @@ -93,9 +96,3 @@ export async function docs({ page, query }, ctx) { typeof indexText === "string" ? indexText : String(indexText), ) } - -async function fetchText(url) { - return fetch(url, { - headers: { Accept: "text/plain" }, - }) -} From 289eba8385934fe15a73dac42263ff93a0667b08 Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Sun, 8 Nov 2026 12:21:43 +0000 Subject: [PATCH 2/3] Address review: error statuses, BOM, timeouts, tree scoping Findings from independent reviews (Opus 5.5, Sol 6.1) of the first commit: - An auth or not-found response whose body broke off, stalled or was too large lost its status, and auth failures were retried. Error bodies are now read leniently: the status is kept and the body reads as `{}`. - Decoding the bounded bytes with Buffer kept a byte-order mark, so BOM-led JSON parsed as `{}`. TextDecoder drops it, as response.text() does. - The 30 s timeout covered the whole download, so a large body that kept arriving was cut off. Requests now have an idle timeout, restarted by each chunk, and a 2-minute total. The size limit is 50 MB, since a package document can legitimately pass 10 MB with large lpmConfig values. - A Retry-After longer than the backoff allows was slept on, up to hours. The call now returns rate limited instead. - Bodies of fetch replacements without a stream reader were read unbounded; Node streams are now bounded too, and only a body-less response uses json(). - lpm_docs search returned an empty success when every matching page failed; it now returns an error naming them. - The tree cap cut the alphabetically first 2,000 paths, so whole directories could vanish, and `path` didn't help. A truncated tree now has a summary by top-level entry, and with `path` it lists that directory's paths. - The session cache is bounded at 500 entries. - Tests now cover each of these, the cancelled body of a retried response, that a declared oversized body is never read, and lpm_docs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 +- lib/__tests__/api.test.js | 235 +++++++++++++++++++--- lib/__tests__/cache.test.js | 13 ++ lib/__tests__/tools/browse-source.test.js | 73 ++++++- lib/__tests__/tools/docs.test.js | 125 ++++++++++++ lib/api.js | 128 ++++++++---- lib/cache.js | 11 +- lib/constants.js | 11 +- lib/tools/browse-source.js | 46 ++++- lib/tools/docs.js | 8 + 10 files changed, 573 insertions(+), 91 deletions(-) create mode 100644 lib/__tests__/tools/docs.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 7807365..2be13dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,18 @@ All notable changes to this project will be documented in this file. ### Fixed -- **Registry and docs responses have a size limit and a full timeout** — Bodies are read up to 10 MB, the CLI's output limit; a larger one is cancelled and the tool returns an error instead of parsing it. The 30-second timeout now runs until the body has been read, so a server that sends headers and then stalls no longer hangs the call. Documentation pages and the docs index use the same limits, and had no timeout before -- **`lpm_browse_source` lists at most 2,000 paths** — A larger tree reports `treeTotal`, `treeTruncated` and a warning to list a directory with `path`, instead of passing up to 20,000 paths to the model +- **Registry and docs responses are read within a size limit and timeouts.** + - A body over 50 MB is cancelled, and the tool returns an error instead of parsing it. + - A request may wait 30 seconds for headers and 30 seconds between chunks of its body, and take 2 minutes in all. A server that sends headers and then stalls no longer hangs the call, and a slow download that keeps arriving still finishes. + - Documentation pages and the docs index use the same limits; they had no timeout before. +- **Error responses keep their status.** A 401, 403 or 404 whose body breaks off, stalls or is too large is still reported as that status, without a retry. +- **JSON bodies that start with a byte-order mark parse again**, as they did with `response.json()`. +- **A long `Retry-After` is not waited on.** When a server asks to wait longer than the backoff allows (10 seconds), the call returns rate limited instead of sleeping. +- **`lpm_docs` reports a failure when no matching page could be read**, instead of an empty answer. +- **`lpm_browse_source` lists at most 2,000 paths.** + - A larger tree comes with `treeTotal`, `treeTruncated`, and a `treeSummary` counting paths by top-level entry, instead of passing up to 20,000 paths to the model. + - With `path`, a tree too large to list shows the paths under that directory. +- **The session cache holds at most 500 entries**, dropping the least recently used. ## [0.3.0] - 2026-11-08 diff --git a/lib/__tests__/api.test.js b/lib/__tests__/api.test.js index dac625c..588c10e 100644 --- a/lib/__tests__/api.test.js +++ b/lib/__tests__/api.test.js @@ -1,6 +1,12 @@ +import { Readable } from "node:stream" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { apiGet, registryGet, textGet } from "../api.js" -import { MAX_RESPONSE_BYTES, REQUEST_TIMEOUT_MS } from "../constants.js" +import { + MAX_RESPONSE_BYTES, + REQUEST_TIMEOUT_MS, + REQUEST_TOTAL_TIMEOUT_MS, + RETRY_MAX_DELAY_MS, +} from "../constants.js" const mockFetch = vi.fn() @@ -129,23 +135,52 @@ describe("api", () => { }) describe("response bodies", () => { - function endlessBody(onCancel) { - const chunk = new TextEncoder().encode(`"${"x".repeat(64 * 1024)}",`) - return new ReadableStream({ + const encoder = new TextEncoder() + const tooLarge = new RegExp( + `larger than ${MAX_RESPONSE_BYTES / (1024 * 1024)} MB`, + ) + + /** A body that never ends, and counts how often it was read and cancelled. */ + function endlessBody() { + const chunk = encoder.encode(`"${"x".repeat(256 * 1024)}",`) + const stats = { pulls: 0, cancels: 0 } + const body = new ReadableStream({ start(controller) { - controller.enqueue(new TextEncoder().encode("[")) + controller.enqueue(encoder.encode("[")) }, pull(controller) { + stats.pulls++ controller.enqueue(chunk) }, - cancel: onCancel, + cancel() { + stats.cancels++ + }, + }) + return { body, stats } + } + + /** A body that sends `parts`, one every `everyMs`, then ends. */ + function slowBody(parts, everyMs, signal) { + return new ReadableStream({ + async start(controller) { + signal?.addEventListener("abort", () => + controller.error(signal.reason), + ) + for (const part of parts) { + await new Promise(resolve => setTimeout(resolve, everyMs)) + if (signal?.aborted) return + controller.enqueue(encoder.encode(part)) + } + controller.close() + }, }) } - function stalledBody(signal) { + /** A body that sends `part` and then neither ends nor sends more. */ + function stalledBody(part, signal) { return new ReadableStream({ start(controller) { - controller.enqueue(new TextEncoder().encode('{"versions":{')) + controller.enqueue(encoder.encode(part)) signal.addEventListener("abort", () => controller.error(signal.reason), ) @@ -158,41 +193,58 @@ describe("api", () => { }) it("stops reading a body past the size limit and reports it without retrying", async () => { - let cancelled = 0 - mockFetch.mockImplementation( - async () => new Response(endlessBody(() => cancelled++)), - ) + const { body, stats } = endlessBody() + mockFetch.mockImplementation(async () => new Response(body)) const result = await apiGet("https://lpm.dev/api/test", null) expect(mockFetch).toHaveBeenCalledTimes(1) - expect(cancelled).toBe(1) + expect(stats.cancels).toBe(1) expect(result.ok).toBe(false) - expect(result.data.error).toMatch(/larger than 10 MB/) + expect(result.data.error).toMatch(tooLarge) }) it("doesn't read a body whose declared size is past the limit", async () => { - let cancelled = 0 + const { body, stats } = endlessBody() mockFetch.mockImplementation( async () => - new Response( - endlessBody(() => cancelled++), - { - headers: { "content-length": String(MAX_RESPONSE_BYTES + 1) }, - }, - ), + new Response(body, { + headers: { "content-length": String(MAX_RESPONSE_BYTES + 1) }, + }), ) const result = await apiGet("https://lpm.dev/api/test", null) - expect(cancelled).toBe(1) - expect(result.data.error).toMatch(/larger than 10 MB/) + expect(stats.pulls).toBe(0) + expect(stats.cancels).toBe(1) + expect(result.data.error).toMatch(tooLarge) }) - it("keeps the timeout running until the body has been read", async () => { + it("bounds a body without a stream reader, as fetch replacements give", async () => { + function* endless() { + yield Buffer.from("[") + for (;;) yield Buffer.alloc(256 * 1024, 0x20) + } + const body = Readable.from(endless()) + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + body, + headers: { get: () => null }, + json: () => Promise.reject(new Error("must not parse unbounded")), + }) + + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(result.data.error).toMatch(tooLarge) + expect(body.destroyed).toBe(true) + }) + + it("times out a body that stalls after its headers, on each attempt", async () => { vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) mockFetch.mockImplementation( - async (_url, init) => new Response(stalledBody(init.signal)), + async (_url, init) => + new Response(stalledBody('{"versions":{', init.signal)), ) const pending = apiGet("https://lpm.dev/api/test", null) @@ -207,9 +259,130 @@ describe("api", () => { }) }) - it("reads text bodies within the same limit and timeout", async () => { + it("lets a slow download finish while it keeps arriving", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + const gap = REQUEST_TIMEOUT_MS - 5_000 mockFetch.mockImplementationOnce( - async () => new Response("# Docs\n", { status: 200 }), + async (_url, init) => + new Response(slowBody(['{"a":', "1", "}"], gap, init.signal)), + ) + + const pending = apiGet("https://lpm.dev/api/test", null) + await vi.advanceTimersByTimeAsync(gap * 3 + 1_000) + + expect(gap * 3).toBeGreaterThan(REQUEST_TIMEOUT_MS) + expect(await pending).toEqual({ ok: true, status: 200, data: { a: 1 } }) + }) + + it("ends a download that trickles past the total timeout", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + const gap = REQUEST_TIMEOUT_MS - 5_000 + const parts = Array.from( + { length: Math.ceil(REQUEST_TOTAL_TIMEOUT_MS / gap) + 2 }, + () => " ", + ) + mockFetch.mockImplementation( + async (_url, init) => new Response(slowBody(parts, gap, init.signal)), + ) + + const pending = apiGet("https://lpm.dev/api/test", null) + await vi.advanceTimersByTimeAsync((REQUEST_TOTAL_TIMEOUT_MS + 15_000) * 3) + + expect(await pending).toEqual({ + ok: false, + status: 0, + data: { error: "Request timed out" }, + }) + }) + + it("reads a JSON body that starts with a byte-order mark, as fetch does", async () => { + mockFetch.mockImplementationOnce( + async () => new Response('\uFEFF{"name":"valid"}'), + ) + + expect(await apiGet("https://lpm.dev/api/test", null)).toEqual({ + ok: true, + status: 200, + data: { name: "valid" }, + }) + }) + + it("keeps an auth failure's status when its body breaks off or is too large, without retrying", async () => { + const broken = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode('{"err')) + controller.error(new TypeError("terminated")) + }, + }) + mockFetch.mockImplementationOnce( + async () => new Response(broken, { status: 401 }), + ) + expect(await apiGet("https://lpm.dev/api/test", "t")).toEqual({ + ok: false, + status: 401, + data: {}, + }) + expect(mockFetch).toHaveBeenCalledTimes(1) + + mockFetch.mockImplementationOnce( + async () => new Response(endlessBody().body, { status: 403 }), + ) + expect(await apiGet("https://lpm.dev/api/test", "t")).toEqual({ + ok: false, + status: 403, + data: {}, + }) + }) + + it("keeps a not-found status when its body is too large", async () => { + mockFetch.mockImplementationOnce( + async () => new Response(endlessBody().body, { status: 404 }), + ) + + expect(await apiGet("https://lpm.dev/api/test", null)).toEqual({ + ok: false, + status: 404, + data: {}, + }) + }) + + it("cancels the body of a response it retries", async () => { + const { body, stats } = endlessBody() + mockFetch + .mockImplementationOnce(async () => new Response(body, { status: 503 })) + .mockImplementationOnce(async () => new Response('{"ok":true}')) + + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(result).toEqual({ ok: true, status: 200, data: { ok: true } }) + expect(stats.cancels).toBe(1) + }) + + it("answers rate limited at once when the server asks to wait longer than the backoff allows", async () => { + const seconds = Math.ceil(RETRY_MAX_DELAY_MS / 1000) + 1 + mockFetch.mockImplementationOnce( + async () => + new Response("", { + status: 429, + headers: { "Retry-After": String(seconds) }, + }), + ) + + const started = Date.now() + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(result).toEqual({ + ok: false, + status: 429, + data: { error: "Rate limited" }, + }) + expect(mockFetch).toHaveBeenCalledTimes(1) + expect(Date.now() - started).toBeLessThan(1_000) + }) + + it("reads text bodies within the same limit and timeouts", async () => { + mockFetch.mockImplementationOnce( + async () => new Response("\uFEFF# Docs\n", { status: 200 }), ) expect(await textGet("https://lpm.dev/api/docs")).toEqual({ ok: true, @@ -217,14 +390,16 @@ describe("api", () => { text: "# Docs\n", }) - mockFetch.mockImplementationOnce(async () => new Response(endlessBody())) + mockFetch.mockImplementationOnce( + async () => new Response(endlessBody().body), + ) const oversized = await textGet("https://lpm.dev/api/docs") expect(oversized.ok).toBe(false) - expect(oversized.error).toMatch(/larger than 10 MB/) + expect(oversized.error).toMatch(tooLarge) vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) mockFetch.mockImplementationOnce( - async (_url, init) => new Response(stalledBody(init.signal)), + async (_url, init) => new Response(stalledBody("# Do", init.signal)), ) const pending = textGet("https://lpm.dev/api/docs") await vi.advanceTimersByTimeAsync(REQUEST_TIMEOUT_MS + 1) diff --git a/lib/__tests__/cache.test.js b/lib/__tests__/cache.test.js index 3e72e9c..d4d366a 100644 --- a/lib/__tests__/cache.test.js +++ b/lib/__tests__/cache.test.js @@ -70,4 +70,17 @@ describe("MemoryCache", () => { afterEach(() => { vi.useRealTimers() }) + + it("keeps at most maxEntries, dropping the least recently used", () => { + const cache = new MemoryCache({ maxEntries: 2 }) + cache.set("a", 1, 60_000) + cache.set("b", 2, 60_000) + expect(cache.get("a")).toBe(1) + cache.set("c", 3, 60_000) + + expect(cache.get("b")).toBeUndefined() + expect(cache.get("a")).toBe(1) + expect(cache.get("c")).toBe(3) + expect(cache.size).toBe(2) + }) }) diff --git a/lib/__tests__/tools/browse-source.test.js b/lib/__tests__/tools/browse-source.test.js index 97bc786..eccf66c 100644 --- a/lib/__tests__/tools/browse-source.test.js +++ b/lib/__tests__/tools/browse-source.test.js @@ -62,11 +62,14 @@ describe("browseSource tool", () => { expect(result.content[0].text).toContain("Authentication required") }) - it("lists at most the tree limit and says how many paths there are", async () => { - const tree = Array.from( - { length: 5_000 }, - (_, index) => `src/file-${index}.js`, - ) + it("lists at most the tree limit and summarizes the tree by top-level entry", async () => { + const tree = [ + "README.md", + ...Array.from({ length: 2_500 }, (_, index) => `dist/chunk-${index}.js`), + "package.json", + "src/index.js", + "src/button.jsx", + ] registryGet.mockResolvedValueOnce({ ok: true, status: 200, @@ -77,10 +80,64 @@ describe("browseSource tool", () => { const data = JSON.parse(result.content[0].text) expect(data.tree).toHaveLength(MAX_SOURCE_TREE_ENTRIES) - expect(data.tree[0]).toBe("src/file-0.js") - expect(data.treeTotal).toBe(5_000) + expect(data.treeTotal).toBe(tree.length) expect(data.treeTruncated).toBe(true) - expect(data.warning).toMatch(/first 2000 of 5000 paths/) + expect(data.treeSummary).toEqual([ + { path: "dist/", files: 2_500 }, + { path: "src/", files: 2 }, + { path: "README.md", files: 1 }, + { path: "package.json", files: 1 }, + ]) + expect(data.warning).toMatch(/first 2000 of 2504 paths/) + expect(data.warning).toMatch(/Pass a directory as `path`/) + }) + + it("lists the requested directory's paths when the whole tree doesn't fit", async () => { + const tree = [ + ...Array.from({ length: 2_500 }, (_, index) => `dist/chunk-${index}.js`), + "src/index.js", + "src/button.jsx", + ] + registryGet.mockResolvedValueOnce({ + ok: true, + status: 200, + data: { ...MOCK_FILES_RESPONSE, tree }, + }) + + const result = await browseSource( + { name: "alice.ui-kit", path: "/src/" }, + createContext(), + ) + const data = JSON.parse(result.content[0].text) + + expect(data.tree).toEqual(["src/index.js", "src/button.jsx"]) + expect(data.treeTruncated).toBeUndefined() + expect(data.files).toHaveLength(2) + }) + + it("summarizes the requested directory when its paths don't fit either", async () => { + const tree = Array.from( + { length: 2_200 }, + (_, index) => `dist/${index % 2 ? "esm" : "cjs"}/chunk-${index}.js`, + ) + registryGet.mockResolvedValueOnce({ + ok: true, + status: 200, + data: { ...MOCK_TREE_RESPONSE, tree }, + }) + + const result = await browseSource( + { name: "alice.ui-kit", path: "dist" }, + createContext(), + ) + const data = JSON.parse(result.content[0].text) + + expect(data.treeTotal).toBe(2_200) + expect(data.treeSummary).toEqual([ + { path: "dist/cjs/", files: 1_100 }, + { path: "dist/esm/", files: 1_100 }, + ]) + expect(data.warning).toMatch(/under dist; treeSummary/) }) it("returns file tree when no path specified", async () => { diff --git a/lib/__tests__/tools/docs.test.js b/lib/__tests__/tools/docs.test.js new file mode 100644 index 0000000..aacaf9e --- /dev/null +++ b/lib/__tests__/tools/docs.test.js @@ -0,0 +1,125 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" +import { MemoryCache } from "../../cache.js" +import { docs } from "../../tools/docs.js" + +vi.mock("../../api.js", () => ({ + textGet: vi.fn(), +})) + +import { textGet } from "../../api.js" + +const INDEX = [ + "# LPM docs", + "getting-started — Getting started with LPM", + "cli/install — Installing packages", + "cli/publish — Publishing packages", +].join("\n") + +const ok = text => ({ ok: true, status: 200, text }) + +function context() { + return { cache: new MemoryCache() } +} + +describe("docs tool", () => { + beforeEach(() => { + textGet.mockReset() + }) + + it("returns a page and caches it", async () => { + textGet.mockResolvedValueOnce(ok("# Installing")) + const ctx = context() + + const first = await docs({ page: "/cli/install/" }, ctx) + const second = await docs({ page: "cli/install" }, ctx) + + expect(first.content[0].text).toBe("# Installing") + expect(second).toBe(first) + expect(textGet).toHaveBeenCalledTimes(1) + expect(textGet).toHaveBeenCalledWith("https://lpm.dev/api/docs/cli/install") + }) + + it("says a missing page wasn't found, and why another page couldn't be read", async () => { + textGet.mockResolvedValueOnce({ ok: false, status: 404 }) + const missing = await docs({ page: "nope" }, context()) + expect(missing.isError).toBe(true) + expect(missing.content[0].text).toContain('"nope" not found') + + textGet.mockResolvedValueOnce({ + ok: false, + status: 0, + error: "Request timed out", + }) + const timedOut = await docs({ page: "cli/install" }, context()) + expect(timedOut.isError).toBe(true) + expect(timedOut.content[0].text).toContain("Request timed out") + }) + + it("returns the index without a page or query", async () => { + textGet.mockResolvedValueOnce(ok(INDEX)) + + const result = await docs({}, context()) + + expect(result.content[0].text).toBe(INDEX) + }) + + it("returns the pages whose index lines match a query", async () => { + textGet + .mockResolvedValueOnce(ok(INDEX)) + .mockResolvedValueOnce(ok("# Installing")) + .mockResolvedValueOnce(ok("# Publishing")) + + const result = await docs({ query: "packages" }, context()) + + expect(result.content[0].text).toBe( + "--- cli/install ---\n# Installing\n\n--- cli/publish ---\n# Publishing", + ) + }) + + it("keeps the pages it could read when another fails", async () => { + textGet + .mockResolvedValueOnce(ok(INDEX)) + .mockResolvedValueOnce({ + ok: false, + status: 0, + error: "Request timed out", + }) + .mockResolvedValueOnce(ok("# Publishing")) + + const result = await docs({ query: "packages" }, context()) + + expect(result.isError).toBeUndefined() + expect(result.content[0].text).toBe("--- cli/publish ---\n# Publishing") + }) + + it("reports an error, not an empty answer, when no matching page could be read", async () => { + textGet + .mockResolvedValueOnce(ok(INDEX)) + .mockResolvedValueOnce({ + ok: false, + status: 0, + error: "Request timed out", + }) + .mockResolvedValueOnce({ ok: false, status: 503 }) + + const result = await docs({ query: "packages" }, context()) + + expect(result.isError).toBe(true) + expect(result.content[0].text).toContain( + "cli/install: Request timed out, cli/publish: 503", + ) + }) + + it("reports when the index can't be read", async () => { + textGet.mockResolvedValueOnce({ + ok: false, + status: 0, + error: "Response was larger than 50 MB", + }) + + const result = await docs({ query: "x" }, context()) + + expect(result.isError).toBe(true) + expect(result.content[0].text).toContain("larger than 50 MB") + }) +}) diff --git a/lib/api.js b/lib/api.js index 8f068ee..d50922d 100644 --- a/lib/api.js +++ b/lib/api.js @@ -4,6 +4,7 @@ import { MAX_RESPONSE_BYTES, MAX_RETRIES, REQUEST_TIMEOUT_MS, + REQUEST_TOTAL_TIMEOUT_MS, RETRY_BACKOFF_MULTIPLIER, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, @@ -24,7 +25,7 @@ function parseRetryAfter(retryAfter) { if (!retryAfter) return RETRY_BASE_DELAY_MS const seconds = parseInt(retryAfter, 10) - if (!Number.isNaN(seconds)) return seconds * 1000 + if (!Number.isNaN(seconds)) return Math.max(0, seconds * 1000) const date = new Date(retryAfter) if (!Number.isNaN(date.getTime())) { @@ -41,49 +42,64 @@ class ResponseTooLargeError extends Error { } } -async function readStreamWithin(body) { - const reader = body.getReader() +/** + * Reads a body's bytes up to MAX_RESPONSE_BYTES and decodes them as UTF-8, + * dropping a byte-order mark as `response.text()` does. `progress` is called + * for each chunk, so a download that keeps arriving isn't timed out as idle. + */ +async function readBodyWithin(body, progress) { const chunks = [] let length = 0 - for (;;) { - const { done, value } = await reader.read() - if (done) break - length += value.byteLength - if (length > MAX_RESPONSE_BYTES) { + const add = chunk => { + progress() + length += chunk.byteLength + if (length > MAX_RESPONSE_BYTES) throw new ResponseTooLargeError() + chunks.push(chunk) + } + if (typeof body.getReader === "function") { + const reader = body.getReader() + try { + for (;;) { + const { done, value } = await reader.read() + if (done) break + add(value) + } + } catch (error) { await reader.cancel().catch(() => {}) - throw new ResponseTooLargeError() + throw error } - chunks.push(value) + } else { + // A Node stream, as fetch replacements such as node-fetch give. Leaving + // the loop early destroys it. + for await (const chunk of body) add(chunk) } - return Buffer.concat(chunks, length).toString("utf8") + return new TextDecoder().decode(Buffer.concat(chunks, length)) } /** * Reads a body as text, up to MAX_RESPONSE_BYTES. A body past the limit is * cancelled and rejects with ResponseTooLargeError. */ -async function readTextWithin(response) { +async function readTextWithin(response, progress) { const declared = Number(response.headers?.get?.("content-length")) if (declared > MAX_RESPONSE_BYTES) { - await response.body?.cancel?.().catch(() => {}) + discardBody(response) throw new ResponseTooLargeError() } - if (typeof response.body?.getReader === "function") { - return readStreamWithin(response.body) + if (response.body == null) { + return typeof response.text === "function" ? response.text() : "" } - return typeof response.text === "function" ? response.text() : "" + return readBodyWithin(response.body, progress) } /** Parses a JSON body within the size limit; a malformed body reads as `{}`. */ -async function readJsonWithin(response) { - // A response without a body stream (no content, or a test double). - if ( - typeof response.body?.getReader !== "function" && - typeof response.json === "function" - ) { +async function readJsonWithin(response, progress) { + // Without a body there is nothing to bound: fetch gives one for every + // response with content, so this is an empty response or a test double. + if (response.body == null && typeof response.json === "function") { return response.json().catch(() => ({})) } - const text = await readTextWithin(response) + const text = await readTextWithin(response, progress) try { return JSON.parse(text) } catch { @@ -91,29 +107,53 @@ async function readJsonWithin(response) { } } +/** + * The JSON body of an error response, or `{}` when it can't be read: the + * status is what callers act on, and it must not be lost to a body that is + * too large, breaks off or stalls. + */ +async function readErrorBody(response, progress) { + try { + return await readJsonWithin(response, progress) + } catch { + return {} + } +} + function discardBody(response) { - response.body?.cancel?.().catch(() => {}) + const body = response.body + if (typeof body?.cancel === "function") body.cancel().catch(() => {}) + else body?.destroy?.() } /** - * Runs `read` on a GET response with one timeout covering both the request - * and the body, so a server that sends headers and then stalls still times - * out. + * Runs `read` on a GET response. The request and the body have one idle + * timeout, restarted by each chunk, so a server that sends headers and then + * stalls still times out, and a total timeout, so one that trickles can't + * hold a call indefinitely. * * @template T * @param {string} url * @param {RequestInit} init - * @param {(response: Response) => Promise} read + * @param {(response: Response, progress: () => void) => Promise} read * @returns {Promise} */ async function fetchWithin(url, init, read) { const controller = new AbortController() - const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) + const abort = () => controller.abort() + let idle = setTimeout(abort, REQUEST_TIMEOUT_MS) + const total = setTimeout(abort, REQUEST_TOTAL_TIMEOUT_MS) + const progress = () => { + clearTimeout(idle) + idle = setTimeout(abort, REQUEST_TIMEOUT_MS) + } try { const response = await fetch(url, { ...init, signal: controller.signal }) - return await read(response) + progress() + return await read(response, progress) } finally { - clearTimeout(timeoutId) + clearTimeout(idle) + clearTimeout(total) } } @@ -137,27 +177,25 @@ export async function apiGet(url, token) { const outcome = await fetchWithin( url, { method: "GET", headers }, - async response => { + async (response, progress) => { // No retry on auth errors if (response.status === 401 || response.status === 403) { return { result: { ok: false, status: response.status, - data: await readJsonWithin(response), + data: await readErrorBody(response, progress), }, } } - // Rate limiting + // Rate limiting. A server that asks for a longer wait than the + // backoff allows is answered as rate limited rather than waited on. if (response.status === 429) { discardBody(response) - if (attempt < MAX_RETRIES) { - return { - retryAfterMs: parseRetryAfter( - response.headers.get("Retry-After"), - ), - } + const delay = parseRetryAfter(response.headers.get("Retry-After")) + if (attempt < MAX_RETRIES && delay <= RETRY_MAX_DELAY_MS) { + return { retryAfterMs: delay } } return { result: { @@ -181,7 +219,9 @@ export async function apiGet(url, token) { result: { ok: response.ok, status: response.status, - data: await readJsonWithin(response), + data: response.ok + ? await readJsonWithin(response, progress) + : await readErrorBody(response, progress), }, } }, @@ -222,7 +262,7 @@ export async function apiGet(url, token) { } /** - * GET a text body once, within the request timeout and size limit. + * GET a text body once, within the request timeouts and size limit. * * @param {string} url * @param {Record} [headers] @@ -233,7 +273,7 @@ export async function textGet(url, headers = { Accept: "text/plain" }) { return await fetchWithin( url, { method: "GET", headers }, - async response => { + async (response, progress) => { if (!response.ok) { discardBody(response) return { ok: false, status: response.status } @@ -241,7 +281,7 @@ export async function textGet(url, headers = { Accept: "text/plain" }) { return { ok: true, status: response.status, - text: await readTextWithin(response), + text: await readTextWithin(response, progress), } }, ) diff --git a/lib/cache.js b/lib/cache.js index f7cf540..68b0f18 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -1,10 +1,13 @@ /** * Simple in-memory cache with TTL support. * Used to reduce API calls for repeated queries within an MCP session. + * It holds at most `maxEntries`, dropping the least recently used, since a + * long session can ask about any number of packages and paths. */ export class MemoryCache { - constructor() { + constructor({ maxEntries = 500 } = {}) { this._store = new Map() + this._maxEntries = maxEntries } /** @@ -21,6 +24,8 @@ export class MemoryCache { return undefined } + this._store.delete(key) + this._store.set(key, entry) return entry.value } @@ -33,6 +38,10 @@ export class MemoryCache { set(key, value, ttlMs) { if (!ttlMs) return + this._store.delete(key) + while (this._store.size >= this._maxEntries) { + this._store.delete(this._store.keys().next().value) + } this._store.set(key, { value, expiresAt: Date.now() + ttlMs, diff --git a/lib/constants.js b/lib/constants.js index 89f40dc..91e3400 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -5,10 +5,15 @@ export const DEFAULT_REGISTRY_URL = "https://lpm.dev" export const KEYTAR_SERVICE_NAME = "lpm-cli" export const KEYTAR_ACCOUNT_PREFIX = "auth-token" +// How long a request may wait for headers, or between chunks of its body. export const REQUEST_TIMEOUT_MS = 30_000 -// Matches the CLI output limit. A registry response is parsed whole on the -// server's only thread, and package documents can grow with every version. -export const MAX_RESPONSE_BYTES = 10 * 1024 * 1024 +// How long a request may take in all, its body included. +export const REQUEST_TOTAL_TIMEOUT_MS = 120_000 +// A registry response is parsed whole on the server's only thread, so its +// size is bounded. Package documents grow with every version, and each +// version's lpmConfig can be 128 KB, so the limit leaves room for large +// packages: parsing 50 MB takes about 80 ms. +export const MAX_RESPONSE_BYTES = 50 * 1024 * 1024 export const MAX_SOURCE_TREE_ENTRIES = 2_000 export const MAX_RETRIES = 2 export const RETRY_BASE_DELAY_MS = 1_000 diff --git a/lib/tools/browse-source.js b/lib/tools/browse-source.js index 2b55324..8da3465 100644 --- a/lib/tools/browse-source.js +++ b/lib/tools/browse-source.js @@ -85,12 +85,22 @@ export async function browseSource({ name, version, path }, ctx) { ecosystem: data.ecosystem, } - // Always include tree, up to the limit: a tarball can hold 20,000 entries. - const tree = Array.isArray(data.tree) ? data.tree : [] + // The whole tree when it fits. A tarball can hold 20,000 entries, so a + // larger tree lists the paths under the requested directory, if any, up + // to the limit, and says how many there are by top-level entry. + const fullTree = Array.isArray(data.tree) ? data.tree : [] + const directory = path ? path.replace(/^\/+|\/+$/g, "") : "" + const tree = + fullTree.length > MAX_SOURCE_TREE_ENTRIES && directory + ? fullTree.filter( + entry => entry === directory || entry.startsWith(`${directory}/`), + ) + : fullTree response.tree = tree.slice(0, MAX_SOURCE_TREE_ENTRIES) if (tree.length > MAX_SOURCE_TREE_ENTRIES) { response.treeTotal = tree.length response.treeTruncated = true + response.treeSummary = summarizeTree(tree, directory) } // Include files if present (only when path was requested) @@ -101,7 +111,9 @@ export async function browseSource({ name, version, path }, ctx) { const warnings = [] if (response.treeTruncated) { warnings.push( - `The tree lists the first ${MAX_SOURCE_TREE_ENTRIES} of ${tree.length} paths. Use the \`path\` parameter to list a directory.`, + directory + ? `The tree lists the first ${MAX_SOURCE_TREE_ENTRIES} of ${tree.length} paths under ${directory}; treeSummary counts them by entry. Pass a deeper \`path\` to narrow it.` + : `The tree lists the first ${MAX_SOURCE_TREE_ENTRIES} of ${tree.length} paths; treeSummary counts them by top-level entry. Pass a directory as \`path\` to list its files.`, ) } if (data.truncated) { @@ -121,3 +133,31 @@ export async function browseSource({ name, version, path }, ctx) { ctx.cache.set(cacheKey, mcpResponse, CACHE_TTL.SHORT) return mcpResponse } + +const MAX_SUMMARY_ENTRIES = 100 + +/** + * The number of paths under each entry directly below `directory` (the root + * when empty), most first, at most MAX_SUMMARY_ENTRIES of them. + * + * @param {string[]} tree + * @param {string} directory + * @returns {Array<{ path: string, files: number }>} + */ +function summarizeTree(tree, directory) { + const prefix = directory ? `${directory}/` : "" + const counts = new Map() + for (const entry of tree) { + const rest = entry.startsWith(prefix) ? entry.slice(prefix.length) : entry + const slash = rest.indexOf("/") + const key = prefix + (slash === -1 ? rest : rest.slice(0, slash + 1)) + counts.set(key, (counts.get(key) ?? 0) + 1) + } + return [...counts] + .sort( + ([a, countA], [b, countB]) => + countB - countA || (a < b ? -1 : a > b ? 1 : 0), + ) + .slice(0, MAX_SUMMARY_ENTRIES) + .map(([path, files]) => ({ path, files })) +} diff --git a/lib/tools/docs.js b/lib/tools/docs.js index b7360d5..f8d3181 100644 --- a/lib/tools/docs.js +++ b/lib/tools/docs.js @@ -80,14 +80,22 @@ export async function docs({ page, query }, ctx) { // Fetch content of matching pages (up to 3) const results = [] + const failures = [] for (const match of matches.slice(0, 3)) { const slug = match.split(" — ")[0].trim() const response = await textGet(`${DOCS_BASE_URL}/${slug}`) if (response.ok) { results.push(`--- ${slug} ---\n${response.text}`) + } else { + failures.push(`${slug}: ${response.error ?? response.status}`) } } + if (results.length === 0) { + return errorResponse( + `Failed to fetch the matching docs pages (${failures.join(", ")})`, + ) + } return textResponse(results.join("\n\n")) } From c2f6baa754497b185fd6e90b39ca6d2a3fd2bdf9 Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Sun, 8 Nov 2026 12:59:18 +0000 Subject: [PATCH 3/3] Address re-check: tree paging, one deadline, hung reads Findings from re-checks (Opus 5.5, Sol 6.1) of the second commit: - The tree summary stopped at 100 entries without saying so, so a directory could be left out of both the listing and the summary, and a package could hide files from a model browsing it. lpm_browse_source now takes a treeOffset argument and lists a long tree a page at a time, so every path can be reached, and a truncated summary says so. - Scoping a long tree to `path` was silent, and a `path` with no paths under it gave an empty tree. The scope is now named in treeScope, and an unmatched path lists the whole package with a note. Directory entries in the tree aren't counted as files, and slashes are trimmed with a loop instead of a trailing-run pattern. - The 2-minute total timeout applied per attempt, so a trickling server held a call for about 6 minutes. It now spans the retries, and a retry isn't waited out past it. Body reads also race the abort signal, so a fetch replacement whose reads ignore it can't hang a call. - MemoryCache rejected nothing for maxEntries, and 0 looped forever. - lpm_docs names the pages it couldn't read after the ones it could. - The Retry-After test no longer depends on wall-clock time. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 +- lib/__tests__/api.test.js | 58 +++++++- lib/__tests__/cache.test.js | 11 ++ lib/__tests__/tools/browse-source.test.js | 143 +++++++++++++------- lib/__tests__/tools/docs.test.js | 6 +- lib/api.js | 156 ++++++++++++++++------ lib/cache.js | 3 + lib/server.js | 8 ++ lib/tools/browse-source.js | 150 ++++++++++++++++----- lib/tools/docs.js | 3 + 10 files changed, 419 insertions(+), 132 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2be13dd..7252192 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,16 +8,17 @@ All notable changes to this project will be documented in this file. - **Registry and docs responses are read within a size limit and timeouts.** - A body over 50 MB is cancelled, and the tool returns an error instead of parsing it. - - A request may wait 30 seconds for headers and 30 seconds between chunks of its body, and take 2 minutes in all. A server that sends headers and then stalls no longer hangs the call, and a slow download that keeps arriving still finishes. + - A request may wait 30 seconds for headers and 30 seconds between chunks of its body, and a call takes at most 2 minutes, its retries included. A server that sends headers and then stalls no longer hangs the call, and a slow download that keeps arriving still finishes. A body read that ignores the abort signal, as some fetch replacements' do, still ends at the timeout. - Documentation pages and the docs index use the same limits; they had no timeout before. - **Error responses keep their status.** A 401, 403 or 404 whose body breaks off, stalls or is too large is still reported as that status, without a retry. - **JSON bodies that start with a byte-order mark parse again**, as they did with `response.json()`. - **A long `Retry-After` is not waited on.** When a server asks to wait longer than the backoff allows (10 seconds), the call returns rate limited instead of sleeping. -- **`lpm_docs` reports a failure when no matching page could be read**, instead of an empty answer. -- **`lpm_browse_source` lists at most 2,000 paths.** - - A larger tree comes with `treeTotal`, `treeTruncated`, and a `treeSummary` counting paths by top-level entry, instead of passing up to 20,000 paths to the model. - - With `path`, a tree too large to list shows the paths under that directory. -- **The session cache holds at most 500 entries**, dropping the least recently used. +- **`lpm_docs` reports failed pages.** A search where no matching page could be read returns an error instead of an empty answer, and one where some failed names them after the pages it read. +- **`lpm_browse_source` lists a long tree 2,000 paths at a time.** + - A larger tree comes with `treeTotal`, `treeOffset`, `treeTruncated`, and a `treeSummary` counting files by top-level entry; pass the new `treeOffset` argument for the next page, so every path can be reached. A summary of more than 100 entries says so. + - With `path`, a tree too large to list whole is scoped to that directory and names it in `treeScope`. A `path` with no paths under it lists the whole package and says so. + - Before, up to 20,000 paths went to the model at once. +- **The session cache holds at most 500 entries**, dropping the least recently used. Its size must be a positive integer. ## [0.3.0] - 2026-11-08 diff --git a/lib/__tests__/api.test.js b/lib/__tests__/api.test.js index 588c10e..0cbf583 100644 --- a/lib/__tests__/api.test.js +++ b/lib/__tests__/api.test.js @@ -274,7 +274,7 @@ describe("api", () => { expect(await pending).toEqual({ ok: true, status: 200, data: { a: 1 } }) }) - it("ends a download that trickles past the total timeout", async () => { + it("ends a download that trickles past the total timeout, which spans retries", async () => { vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) const gap = REQUEST_TIMEOUT_MS - 5_000 const parts = Array.from( @@ -285,8 +285,31 @@ describe("api", () => { async (_url, init) => new Response(slowBody(parts, gap, init.signal)), ) + let settled = false + const pending = apiGet("https://lpm.dev/api/test", null).finally(() => { + settled = true + }) + await vi.advanceTimersByTimeAsync(REQUEST_TOTAL_TIMEOUT_MS - 1) + expect(settled).toBe(false) + await vi.advanceTimersByTimeAsync(2) + + expect(await pending).toEqual({ + ok: false, + status: 0, + data: { error: "Request timed out" }, + }) + expect(mockFetch).toHaveBeenCalledTimes(1) + }) + + it("doesn't wait out a retry past the total timeout", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + mockFetch.mockImplementation( + async (_url, init) => + new Response(stalledBody("{", init.signal), { status: 200 }), + ) + const pending = apiGet("https://lpm.dev/api/test", null) - await vi.advanceTimersByTimeAsync((REQUEST_TOTAL_TIMEOUT_MS + 15_000) * 3) + await vi.advanceTimersByTimeAsync(REQUEST_TOTAL_TIMEOUT_MS + 1) expect(await pending).toEqual({ ok: false, @@ -295,6 +318,33 @@ describe("api", () => { }) }) + it("times out a body whose reader ignores the abort signal", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + let cancelled = 0 + const reader = { + read: () => new Promise(() => {}), + cancel: async () => { + cancelled++ + }, + } + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + body: { getReader: () => reader }, + headers: { get: () => null }, + }) + + const pending = apiGet("https://lpm.dev/api/test", null) + await vi.advanceTimersByTimeAsync(REQUEST_TOTAL_TIMEOUT_MS + 1) + + expect(await pending).toEqual({ + ok: false, + status: 0, + data: { error: "Request timed out" }, + }) + expect(cancelled).toBeGreaterThan(0) + }) + it("reads a JSON body that starts with a byte-order mark, as fetch does", async () => { mockFetch.mockImplementationOnce( async () => new Response('\uFEFF{"name":"valid"}'), @@ -359,6 +409,7 @@ describe("api", () => { }) it("answers rate limited at once when the server asks to wait longer than the backoff allows", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) const seconds = Math.ceil(RETRY_MAX_DELAY_MS / 1000) + 1 mockFetch.mockImplementationOnce( async () => @@ -368,7 +419,7 @@ describe("api", () => { }), ) - const started = Date.now() + // Resolves without any timer advancing, so nothing waited. const result = await apiGet("https://lpm.dev/api/test", null) expect(result).toEqual({ @@ -377,7 +428,6 @@ describe("api", () => { data: { error: "Rate limited" }, }) expect(mockFetch).toHaveBeenCalledTimes(1) - expect(Date.now() - started).toBeLessThan(1_000) }) it("reads text bodies within the same limit and timeouts", async () => { diff --git a/lib/__tests__/cache.test.js b/lib/__tests__/cache.test.js index d4d366a..d08d166 100644 --- a/lib/__tests__/cache.test.js +++ b/lib/__tests__/cache.test.js @@ -83,4 +83,15 @@ describe("MemoryCache", () => { expect(cache.get("c")).toBe(3) expect(cache.size).toBe(2) }) + + it.each([ + 0, + -1, + 1.5, + Number.POSITIVE_INFINITY, + ])("rejects %s as its size", maxEntries => { + expect(() => new MemoryCache({ maxEntries })).toThrow( + "maxEntries must be a positive integer", + ) + }) }) diff --git a/lib/__tests__/tools/browse-source.test.js b/lib/__tests__/tools/browse-source.test.js index eccf66c..9939a93 100644 --- a/lib/__tests__/tools/browse-source.test.js +++ b/lib/__tests__/tools/browse-source.test.js @@ -62,82 +62,135 @@ describe("browseSource tool", () => { expect(result.content[0].text).toContain("Authentication required") }) - it("lists at most the tree limit and summarizes the tree by top-level entry", async () => { + async function browse(params, tree, base = MOCK_TREE_RESPONSE) { + registryGet.mockResolvedValueOnce({ + ok: true, + status: 200, + data: { ...base, tree }, + }) + const result = await browseSource( + { name: "alice.ui-kit", ...params }, + createContext(), + ) + return JSON.parse(result.content[0].text) + } + + const files = (count, make) => + Array.from({ length: count }, (_, index) => make(index)) + + it("lists a long tree a page at a time, with its total and a summary by top-level entry", async () => { const tree = [ "README.md", - ...Array.from({ length: 2_500 }, (_, index) => `dist/chunk-${index}.js`), + ...files(2_500, index => `dist/chunk-${index}.js`), "package.json", "src/index.js", "src/button.jsx", ] - registryGet.mockResolvedValueOnce({ - ok: true, - status: 200, - data: { ...MOCK_TREE_RESPONSE, tree }, - }) - - const result = await browseSource({ name: "alice.ui-kit" }, createContext()) - const data = JSON.parse(result.content[0].text) - expect(data.tree).toHaveLength(MAX_SOURCE_TREE_ENTRIES) - expect(data.treeTotal).toBe(tree.length) - expect(data.treeTruncated).toBe(true) - expect(data.treeSummary).toEqual([ + const first = await browse({}, tree) + expect(first.tree).toEqual(tree.slice(0, MAX_SOURCE_TREE_ENTRIES)) + expect(first).toMatchObject({ + treeTotal: 2_504, + treeOffset: 0, + treeScope: null, + treeTruncated: true, + }) + expect(first.treeSummary).toEqual([ { path: "dist/", files: 2_500 }, { path: "src/", files: 2 }, { path: "README.md", files: 1 }, { path: "package.json", files: 1 }, ]) - expect(data.warning).toMatch(/first 2000 of 2504 paths/) - expect(data.warning).toMatch(/Pass a directory as `path`/) + expect(first.warning).toMatch(/paths 1–2000 of 2504\. Pass treeOffset 2000/) + + const second = await browse({ treeOffset: 2_000 }, tree) + expect(second.tree).toEqual(tree.slice(2_000)) + expect(second.tree).toContain("src/button.jsx") + expect(second.treeTruncated).toBe(false) + expect(second.warning).toMatch(/paths 2001–2504 of 2504\./) + }) + + it("can list every path, so none hides behind the summary's limit", async () => { + const tree = [ + ...files( + 2_100, + index => + `d${String(Math.floor(index / 21)).padStart(3, "0")}/f${index}.js`, + ), + "z-hidden/index.js", + ] + + const first = await browse({}, tree) + expect(first.treeSummary).toHaveLength(100) + expect(first.treeSummaryTruncated).toBe(true) + expect(first.warning).toMatch( + /100 largest of its 101 entries; page through the tree/, + ) + + const second = await browse({ treeOffset: first.tree.length }, tree) + expect(second.tree).toContain("z-hidden/index.js") }) - it("lists the requested directory's paths when the whole tree doesn't fit", async () => { + it("scopes a long tree to the requested directory, and says so", async () => { const tree = [ - ...Array.from({ length: 2_500 }, (_, index) => `dist/chunk-${index}.js`), + ...files(2_500, index => `dist/chunk-${index}.js`), "src/index.js", "src/button.jsx", ] - registryGet.mockResolvedValueOnce({ - ok: true, - status: 200, - data: { ...MOCK_FILES_RESPONSE, tree }, - }) - const result = await browseSource( - { name: "alice.ui-kit", path: "/src/" }, - createContext(), - ) - const data = JSON.parse(result.content[0].text) + const data = await browse({ path: "/src/" }, tree, MOCK_FILES_RESPONSE) expect(data.tree).toEqual(["src/index.js", "src/button.jsx"]) - expect(data.treeTruncated).toBeUndefined() + expect(data).toMatchObject({ + treeScope: "src", + treeTotal: 2, + treeTruncated: false, + }) expect(data.files).toHaveLength(2) }) - it("summarizes the requested directory when its paths don't fit either", async () => { - const tree = Array.from( - { length: 2_200 }, - (_, index) => `dist/${index % 2 ? "esm" : "cjs"}/chunk-${index}.js`, - ) - registryGet.mockResolvedValueOnce({ - ok: true, - status: 200, - data: { ...MOCK_TREE_RESPONSE, tree }, - }) + it("lists the whole tree when the requested directory has no paths", async () => { + const tree = files(2_500, index => `dist/chunk-${index}.js`) - const result = await browseSource( - { name: "alice.ui-kit", path: "dist" }, - createContext(), + const data = await browse({ path: "./src" }, tree) + + expect(data.treeScope).toBeNull() + expect(data.treeTotal).toBe(2_500) + expect(data.warning).toMatch( + /No paths are under \.\/src; the tree lists the whole package/, ) - const data = JSON.parse(result.content[0].text) + }) - expect(data.treeTotal).toBe(2_200) + it("summarizes the requested directory, counting files, not directory entries", async () => { + const tree = [ + "dist", + "dist/esm", + ...files( + 2_200, + index => `dist/${index % 2 ? "esm" : "cjs"}/chunk-${index}.js`, + ), + ] + + const data = await browse({ path: "dist" }, tree) + + expect(data.treeTotal).toBe(2_202) expect(data.treeSummary).toEqual([ { path: "dist/cjs/", files: 1_100 }, { path: "dist/esm/", files: 1_100 }, ]) - expect(data.warning).toMatch(/under dist; treeSummary/) + expect(data.warning).toMatch(/under dist/) + }) + + it("rejects a negative or fractional treeOffset", async () => { + for (const treeOffset of [-1, 1.5]) { + const result = await browseSource( + { name: "alice.ui-kit", treeOffset }, + createContext(), + ) + expect(result.isError).toBe(true) + expect(result.content[0].text).toContain("treeOffset") + } + expect(registryGet).not.toHaveBeenCalled() }) it("returns file tree when no path specified", async () => { diff --git a/lib/__tests__/tools/docs.test.js b/lib/__tests__/tools/docs.test.js index aacaf9e..a0e1f76 100644 --- a/lib/__tests__/tools/docs.test.js +++ b/lib/__tests__/tools/docs.test.js @@ -76,7 +76,7 @@ describe("docs tool", () => { ) }) - it("keeps the pages it could read when another fails", async () => { + it("keeps the pages it could read, and names the ones it couldn't", async () => { textGet .mockResolvedValueOnce(ok(INDEX)) .mockResolvedValueOnce({ @@ -89,7 +89,9 @@ describe("docs tool", () => { const result = await docs({ query: "packages" }, context()) expect(result.isError).toBeUndefined() - expect(result.content[0].text).toBe("--- cli/publish ---\n# Publishing") + expect(result.content[0].text).toBe( + "--- cli/publish ---\n# Publishing\n\n(Could not read: cli/install: Request timed out)", + ) }) it("reports an error, not an empty answer, when no matching page could be read", async () => { diff --git a/lib/api.js b/lib/api.js index d50922d..761b0fa 100644 --- a/lib/api.js +++ b/lib/api.js @@ -11,8 +11,46 @@ import { RETRYABLE_STATUS_CODES, } from "./constants.js" -function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)) +/** Waits `ms`, or until `signal` aborts. */ +function sleep(ms, signal) { + return new Promise(resolve => { + if (signal?.aborted) return resolve() + const done = () => { + clearTimeout(timer) + signal?.removeEventListener("abort", done) + resolve() + } + const timer = setTimeout(done, ms) + signal?.addEventListener("abort", done, { once: true }) + }) +} + +function abortError() { + return new DOMException("The request was aborted", "AbortError") +} + +/** + * `promise`, or a rejection once `signal` aborts. Built-in fetch ends a body + * read when its signal aborts, but a replacement may not, and the read would + * then hang past every timeout. + */ +function untilAborted(promise, signal) { + if (!signal) return promise + if (signal.aborted) return Promise.reject(abortError()) + return new Promise((resolve, reject) => { + const onAbort = () => reject(abortError()) + signal.addEventListener("abort", onAbort, { once: true }) + promise.then( + value => { + signal.removeEventListener("abort", onAbort) + resolve(value) + }, + error => { + signal.removeEventListener("abort", onAbort) + reject(error) + }, + ) + }) } function getBackoffDelay(attempt) { @@ -47,7 +85,7 @@ class ResponseTooLargeError extends Error { * dropping a byte-order mark as `response.text()` does. `progress` is called * for each chunk, so a download that keeps arriving isn't timed out as idle. */ -async function readBodyWithin(body, progress) { +async function readBodyWithin(body, { progress, signal }) { const chunks = [] let length = 0 const add = chunk => { @@ -56,22 +94,31 @@ async function readBodyWithin(body, progress) { if (length > MAX_RESPONSE_BYTES) throw new ResponseTooLargeError() chunks.push(chunk) } - if (typeof body.getReader === "function") { - const reader = body.getReader() - try { - for (;;) { - const { done, value } = await reader.read() - if (done) break - add(value) - } - } catch (error) { + // A web stream, as fetch gives, or a Node stream, as replacements such as + // node-fetch give. Either is cancelled when the read stops early. + const reader = + typeof body.getReader === "function" + ? body.getReader() + : body[Symbol.asyncIterator]() + const next = () => + untilAborted( + typeof reader.read === "function" ? reader.read() : reader.next(), + signal, + ) + try { + for (;;) { + const { done, value } = await next() + if (done) break + add(value) + } + } catch (error) { + if (typeof reader.cancel === "function") { await reader.cancel().catch(() => {}) - throw error + } else { + await reader.return?.().catch(() => {}) + body.destroy?.() } - } else { - // A Node stream, as fetch replacements such as node-fetch give. Leaving - // the loop early destroys it. - for await (const chunk of body) add(chunk) + throw error } return new TextDecoder().decode(Buffer.concat(chunks, length)) } @@ -80,7 +127,7 @@ async function readBodyWithin(body, progress) { * Reads a body as text, up to MAX_RESPONSE_BYTES. A body past the limit is * cancelled and rejects with ResponseTooLargeError. */ -async function readTextWithin(response, progress) { +async function readTextWithin(response, reading) { const declared = Number(response.headers?.get?.("content-length")) if (declared > MAX_RESPONSE_BYTES) { discardBody(response) @@ -89,17 +136,17 @@ async function readTextWithin(response, progress) { if (response.body == null) { return typeof response.text === "function" ? response.text() : "" } - return readBodyWithin(response.body, progress) + return readBodyWithin(response.body, reading) } /** Parses a JSON body within the size limit; a malformed body reads as `{}`. */ -async function readJsonWithin(response, progress) { +async function readJsonWithin(response, reading) { // Without a body there is nothing to bound: fetch gives one for every // response with content, so this is an empty response or a test double. if (response.body == null && typeof response.json === "function") { return response.json().catch(() => ({})) } - const text = await readTextWithin(response, progress) + const text = await readTextWithin(response, reading) try { return JSON.parse(text) } catch { @@ -112,9 +159,9 @@ async function readJsonWithin(response, progress) { * status is what callers act on, and it must not be lost to a body that is * too large, breaks off or stalls. */ -async function readErrorBody(response, progress) { +async function readErrorBody(response, reading) { try { - return await readJsonWithin(response, progress) + return await readJsonWithin(response, reading) } catch { return {} } @@ -127,36 +174,47 @@ function discardBody(response) { } /** - * Runs `read` on a GET response. The request and the body have one idle + * Runs `read` on a GET response. The request and its body have an idle * timeout, restarted by each chunk, so a server that sends headers and then - * stalls still times out, and a total timeout, so one that trickles can't - * hold a call indefinitely. + * stalls still times out. `deadline` aborts it too: it is the call's total + * timeout, which spans its retries. * * @template T * @param {string} url * @param {RequestInit} init - * @param {(response: Response, progress: () => void) => Promise} read + * @param {AbortSignal} deadline + * @param {(response: Response, reading: { progress: () => void, signal: AbortSignal }) => Promise} read * @returns {Promise} */ -async function fetchWithin(url, init, read) { +async function fetchWithin(url, init, deadline, read) { const controller = new AbortController() const abort = () => controller.abort() let idle = setTimeout(abort, REQUEST_TIMEOUT_MS) - const total = setTimeout(abort, REQUEST_TOTAL_TIMEOUT_MS) + deadline.addEventListener("abort", abort, { once: true }) const progress = () => { clearTimeout(idle) idle = setTimeout(abort, REQUEST_TIMEOUT_MS) } try { + if (deadline.aborted) throw abortError() const response = await fetch(url, { ...init, signal: controller.signal }) progress() - return await read(response, progress) + return await read(response, { progress, signal: controller.signal }) } finally { clearTimeout(idle) - clearTimeout(total) + deadline.removeEventListener("abort", abort) } } +/** A signal that aborts after REQUEST_TOTAL_TIMEOUT_MS, and its cleanup. */ +function totalDeadline() { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), REQUEST_TOTAL_TIMEOUT_MS) + return { signal: controller.signal, clear: () => clearTimeout(timer) } +} + +const TIMED_OUT = { error: "Request timed out" } + /** * Make a GET request with retry, timeout, and rate limit handling. * @@ -170,6 +228,15 @@ export async function apiGet(url, token) { headers.Authorization = `Bearer ${token}` } + const deadline = totalDeadline() + try { + return await apiGetWithin(url, headers, deadline.signal) + } finally { + deadline.clear() + } +} + +async function apiGetWithin(url, headers, deadline) { let lastError = null for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { @@ -177,14 +244,15 @@ export async function apiGet(url, token) { const outcome = await fetchWithin( url, { method: "GET", headers }, - async (response, progress) => { + deadline, + async (response, reading) => { // No retry on auth errors if (response.status === 401 || response.status === 403) { return { result: { ok: false, status: response.status, - data: await readErrorBody(response, progress), + data: await readErrorBody(response, reading), }, } } @@ -220,30 +288,34 @@ export async function apiGet(url, token) { ok: response.ok, status: response.status, data: response.ok - ? await readJsonWithin(response, progress) - : await readErrorBody(response, progress), + ? await readJsonWithin(response, reading) + : await readErrorBody(response, reading), }, } }, ) if (outcome.result) return outcome.result - await sleep(outcome.retryAfterMs) + await sleep(outcome.retryAfterMs, deadline) + if (deadline.aborted) return { ok: false, status: 0, data: TIMED_OUT } } catch (error) { // The same body would be too large again. if (error instanceof ResponseTooLargeError) { return { ok: false, status: 0, data: { error: error.message } } } + // The call's total timeout spans its retries. + if (deadline.aborted) return { ok: false, status: 0, data: TIMED_OUT } lastError = error if (attempt < MAX_RETRIES) { - await sleep(getBackoffDelay(attempt)) + await sleep(getBackoffDelay(attempt), deadline) + if (deadline.aborted) return { ok: false, status: 0, data: TIMED_OUT } continue } if (error.name === "AbortError") { - return { ok: false, status: 0, data: { error: "Request timed out" } } + return { ok: false, status: 0, data: TIMED_OUT } } return { @@ -269,11 +341,13 @@ export async function apiGet(url, token) { * @returns {Promise<{ok: true, status: number, text: string} | {ok: false, status: number, text?: string, error?: string}>} */ export async function textGet(url, headers = { Accept: "text/plain" }) { + const deadline = totalDeadline() try { return await fetchWithin( url, { method: "GET", headers }, - async (response, progress) => { + deadline.signal, + async (response, reading) => { if (!response.ok) { discardBody(response) return { ok: false, status: response.status } @@ -281,7 +355,7 @@ export async function textGet(url, headers = { Accept: "text/plain" }) { return { ok: true, status: response.status, - text: await readTextWithin(response, progress), + text: await readTextWithin(response, reading), } }, ) @@ -290,6 +364,8 @@ export async function textGet(url, headers = { Accept: "text/plain" }) { return { ok: false, status: 0, error: "Request timed out" } } return { ok: false, status: 0, error: error.message || "Network error" } + } finally { + deadline.clear() } } diff --git a/lib/cache.js b/lib/cache.js index 68b0f18..b86b31b 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -6,6 +6,9 @@ */ export class MemoryCache { constructor({ maxEntries = 500 } = {}) { + if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) { + throw new TypeError("maxEntries must be a positive integer") + } this._store = new Map() this._maxEntries = maxEntries } diff --git a/lib/server.js b/lib/server.js index 20d9801..56c7dbb 100644 --- a/lib/server.js +++ b/lib/server.js @@ -286,6 +286,14 @@ If you must use this tool: fetch directory paths (e.g., "src") to get multiple f .describe( 'File or directory path to browse (e.g., "src/index.js" or "src"). Omit to get file tree only. Pass empty string "" to get ALL source files at once.', ), + treeOffset: z + .number() + .int() + .min(0) + .optional() + .describe( + "Index of the first tree path to list. A tree longer than 2,000 paths is listed 2,000 at a time; the response gives the offset of the next page.", + ), }, params => browseSource(params, context), ) diff --git a/lib/tools/browse-source.js b/lib/tools/browse-source.js index 8da3465..7330deb 100644 --- a/lib/tools/browse-source.js +++ b/lib/tools/browse-source.js @@ -10,11 +10,15 @@ import { errorResponse, parseName, textResponse } from "../format.js" * * - Without `path`: returns file tree only (use this first to explore structure) * - With `path`: returns file tree + source contents for matching files/directory + * - With `treeOffset`: lists a long tree from that path onwards * - * @param {{ name: string, version?: string, path?: string }} params + * @param {{ name: string, version?: string, path?: string, treeOffset?: number }} params * @param {{ cache: import('../cache.js').MemoryCache, getToken: () => Promise, getBaseUrl: () => string }} ctx */ -export async function browseSource({ name, version, path }, ctx) { +export async function browseSource( + { name, version, path, treeOffset = 0 }, + ctx, +) { let owner, pkgName try { const parsed = parseName(name) @@ -31,8 +35,12 @@ export async function browseSource({ name, version, path }, ctx) { ) } + if (!Number.isSafeInteger(treeOffset) || treeOffset < 0) { + return errorResponse("treeOffset must be a non-negative integer.") + } + // Build cache key (includes path for content requests) - const cacheKey = `browse-source:${owner}.${pkgName}:${version || "latest"}:${path || ""}` + const cacheKey = `browse-source:${owner}.${pkgName}:${version || "latest"}:${path || ""}:${treeOffset}` const cached = ctx.cache.get(cacheKey) if (cached) return cached @@ -85,37 +93,15 @@ export async function browseSource({ name, version, path }, ctx) { ecosystem: data.ecosystem, } - // The whole tree when it fits. A tarball can hold 20,000 entries, so a - // larger tree lists the paths under the requested directory, if any, up - // to the limit, and says how many there are by top-level entry. - const fullTree = Array.isArray(data.tree) ? data.tree : [] - const directory = path ? path.replace(/^\/+|\/+$/g, "") : "" - const tree = - fullTree.length > MAX_SOURCE_TREE_ENTRIES && directory - ? fullTree.filter( - entry => entry === directory || entry.startsWith(`${directory}/`), - ) - : fullTree - response.tree = tree.slice(0, MAX_SOURCE_TREE_ENTRIES) - if (tree.length > MAX_SOURCE_TREE_ENTRIES) { - response.treeTotal = tree.length - response.treeTruncated = true - response.treeSummary = summarizeTree(tree, directory) - } + Object.assign(response, treeListing(data.tree, path, treeOffset)) // Include files if present (only when path was requested) if (data.files && data.files.length > 0) { response.files = data.files } - const warnings = [] - if (response.treeTruncated) { - warnings.push( - directory - ? `The tree lists the first ${MAX_SOURCE_TREE_ENTRIES} of ${tree.length} paths under ${directory}; treeSummary counts them by entry. Pass a deeper \`path\` to narrow it.` - : `The tree lists the first ${MAX_SOURCE_TREE_ENTRIES} of ${tree.length} paths; treeSummary counts them by top-level entry. Pass a directory as \`path\` to list its files.`, - ) - } + const warnings = response.treeNote ? [response.treeNote] : [] + delete response.treeNote if (data.truncated) { response.truncated = true warnings.push( @@ -137,27 +123,121 @@ export async function browseSource({ name, version, path }, ctx) { const MAX_SUMMARY_ENTRIES = 100 /** - * The number of paths under each entry directly below `directory` (the root - * when empty), most first, at most MAX_SUMMARY_ENTRIES of them. + * The tree, or one page of it. A tree that fits is listed whole, as the + * registry sends it. A tarball can hold 20,000 paths, so a longer one is + * listed MAX_SOURCE_TREE_ENTRIES at a time from `offset`, scoped to `path` + * when that names a directory with paths in it, with its total and a count + * of paths by entry. Every path can be reached by paging, so none can hide + * behind the limit. + * + * @param {unknown} tree + * @param {string | undefined} path + * @param {number} offset + */ +function treeListing(tree, path, offset) { + const fullTree = Array.isArray(tree) ? tree : [] + if (fullTree.length <= MAX_SOURCE_TREE_ENTRIES && offset === 0) { + return { tree: fullTree } + } + + const directory = path ? trimSlashes(path, { leading: true }) : "" + const scoped = directory + ? fullTree.filter( + entry => entry === directory || entry.startsWith(`${directory}/`), + ) + : fullTree + const scope = directory && scoped.length > 0 ? directory : null + const listed = scope ? scoped : fullTree + const page = listed.slice(offset, offset + MAX_SOURCE_TREE_ENTRIES) + const next = offset + page.length + const summary = summarizeTree(listed, scope ?? "") + + const where = scope ? ` under ${scope}` : "" + const notes = [] + if (directory && !scope) { + notes.push( + `No paths are under ${directory}; the tree lists the whole package.`, + ) + } + notes.push( + page.length + ? `The tree lists paths ${offset + 1}–${next} of ${listed.length}${where}.` + : `treeOffset ${offset} is past the ${listed.length} paths${where}.`, + ) + if (next < listed.length) { + notes.push(`Pass treeOffset ${next} for the next paths.`) + } + notes.push( + summary.truncated + ? `treeSummary counts the ${MAX_SUMMARY_ENTRIES} largest of its ${summary.total} entries; page through the tree for the rest.` + : "treeSummary counts its paths by entry.", + ) + + return { + tree: page, + treeTotal: listed.length, + treeOffset: offset, + treeScope: scope, + treeTruncated: next < listed.length, + treeSummary: summary.entries, + ...(summary.truncated ? { treeSummaryTruncated: true } : {}), + treeNote: notes.join(" "), + } +} + +/** + * The number of files under each entry directly below `directory` (the root + * when empty), most first, at most MAX_SUMMARY_ENTRIES of them. A tree can + * list directories as paths of their own; those aren't counted as files. * * @param {string[]} tree * @param {string} directory - * @returns {Array<{ path: string, files: number }>} + * @returns {{ entries: Array<{ path: string, files: number }>, total: number, truncated: boolean }} */ function summarizeTree(tree, directory) { const prefix = directory ? `${directory}/` : "" - const counts = new Map() + const rests = [] + const directories = new Set() for (const entry of tree) { - const rest = entry.startsWith(prefix) ? entry.slice(prefix.length) : entry + if (prefix && !entry.startsWith(prefix)) continue + const rest = trimSlashes(entry.slice(prefix.length)) + if (!rest) continue const slash = rest.indexOf("/") + if (slash !== -1) directories.add(rest.slice(0, slash)) + rests.push(rest) + } + const counts = new Map() + for (const rest of rests) { + const slash = rest.indexOf("/") + if (slash === -1 && directories.has(rest)) continue const key = prefix + (slash === -1 ? rest : rest.slice(0, slash + 1)) counts.set(key, (counts.get(key) ?? 0) + 1) } - return [...counts] + const entries = [...counts] .sort( ([a, countA], [b, countB]) => countB - countA || (a < b ? -1 : a > b ? 1 : 0), ) - .slice(0, MAX_SUMMARY_ENTRIES) .map(([path, files]) => ({ path, files })) + return { + entries: entries.slice(0, MAX_SUMMARY_ENTRIES), + total: entries.length, + truncated: entries.length > MAX_SUMMARY_ENTRIES, + } +} + +/** + * `text` without its trailing slashes, and its leading ones too with + * `leading`. A loop, not /\/+$/: that pattern retries a run of slashes from + * every offset when another character follows, and paths reach 32 KiB. + * + * @param {string} text + * @param {{ leading?: boolean }} [options] + */ +function trimSlashes(text, { leading = false } = {}) { + let start = 0 + let end = text.length + if (leading) while (start < end && text[start] === "/") start++ + while (end > start && text[end - 1] === "/") end-- + return text.slice(start, end) } diff --git a/lib/tools/docs.js b/lib/tools/docs.js index f8d3181..e3fc7bc 100644 --- a/lib/tools/docs.js +++ b/lib/tools/docs.js @@ -96,6 +96,9 @@ export async function docs({ page, query }, ctx) { `Failed to fetch the matching docs pages (${failures.join(", ")})`, ) } + if (failures.length) { + results.push(`(Could not read: ${failures.join(", ")})`) + } return textResponse(results.join("\n\n")) }