diff --git a/src/__tests__/__snapshots__/server.helpers.test.ts.snap b/src/__tests__/__snapshots__/server.helpers.test.ts.snap index 8bb32916..529604f7 100644 --- a/src/__tests__/__snapshots__/server.helpers.test.ts.snap +++ b/src/__tests__/__snapshots__/server.helpers.test.ts.snap @@ -20,6 +20,10 @@ exports[`generateHash should generate a consistent hash, error 1`] = `"231aa2757 exports[`generateHash should generate a consistent hash, function 1`] = `"adf4394f45bb2dee237a9c9dadc2883a31ae7b18"`; +exports[`generateHash should generate a consistent hash, headers, different values 1`] = `"5e34c28950714843dc081f5d4a34ba9f75db47d3"`; + +exports[`generateHash should generate a consistent hash, headers, same entries 1`] = `"d20ffc85b564e5db59b176f2576b145d9983a384"`; + exports[`generateHash should generate a consistent hash, map of objects, reversed order 1`] = `"d7534cc9388daa961fe01876d91a001b9d02bf1d"`; exports[`generateHash should generate a consistent hash, map of objects, same order 1`] = `"d7534cc9388daa961fe01876d91a001b9d02bf1d"`; diff --git a/src/__tests__/index.test.ts b/src/__tests__/index.test.ts index 60ca569a..0dea9371 100644 --- a/src/__tests__/index.test.ts +++ b/src/__tests__/index.test.ts @@ -8,7 +8,12 @@ import { runServer } from '../server'; // Mock dependencies jest.mock('../options'); jest.mock('../options.parser'); -jest.mock('../options.context'); +jest.mock('../options.context', () => ({ + ...jest.requireActual('../options.context'), + getSessionOptions: jest.fn(), + runWithSession: jest.fn(), + setOptions: jest.fn() +})); jest.mock('../server'); jest.mock('../server.tools'); diff --git a/src/__tests__/server.fetch.test.ts b/src/__tests__/server.fetch.test.ts index 0dcdd844..313fcd1c 100644 --- a/src/__tests__/server.fetch.test.ts +++ b/src/__tests__/server.fetch.test.ts @@ -9,9 +9,11 @@ import { parsePayload, preflight, setFetch, - FetchError + FetchError, + setFetchMemo } from '../server.fetch'; import { getOptions } from '../options.context'; +import * as serverCaching from '../server.caching'; import { log } from '../logger'; describe('MIME helpers', () => { @@ -224,6 +226,17 @@ describe('setFetch', () => { jest.restoreAllMocks(); }); + it('should expose get, cancel, and status functions', () => { + const res = setFetch(); + + expect(res).toHaveProperty('get'); + expect(typeof res.get).toBe('function'); + expect(res).toHaveProperty('cancel'); + expect(typeof res.cancel).toBe('function'); + expect(res).toHaveProperty('status'); + expect(typeof res.status).toBe('function'); + }); + it('should fetch and parse text', async () => { const mockResponse = { ok: true, @@ -498,23 +511,49 @@ describe('setFetch', () => { }); }); - it('should de-duplicate concurrent requests to the same URL', async () => { + it('should reject concurrent requests while one fetch is in-flight', async () => { (global.fetch as jest.Mock).mockReturnValue(new Promise(() => {})); // Hang const { get } = setFetch(); - const p1 = get('https://patternfly.org/data'); - const p2 = get('https://patternfly.org/data'); + get('https://patternfly.org/a', { headers: { 'Accept-Language': 'en' } }); + + await expect(get('https://patternfly.org/b')).rejects.toThrow('Fetch already in progress'); + await expect(get('https://patternfly.org/a', { headers: { 'Accept-Language': 'en' } })).rejects.toThrow( + 'Fetch already in progress' + ); + await expect( + get('https://patternfly.org/a', { headers: { 'Accept-Language': 'fr' } }) + ).rejects.toThrow('Fetch already in progress'); + await expect( + get('https://patternfly.org/a', { headers: new Headers({ 'Accept-Language': 'fr' }) }) + ).rejects.toThrow('Fetch already in progress'); - expect(p1).toBe(p2); expect(global.fetch).toHaveBeenCalledTimes(1); }); - it('should reject concurrent requests to different URLs', async () => { - (global.fetch as jest.Mock).mockReturnValue(new Promise(() => {})); // Hang + it('should allow retry after failure and reject concurrent requests while retry is in-flight', async () => { + let rejectFirst: (err: unknown) => void = () => {}; + + (global.fetch as jest.Mock) + .mockImplementationOnce(() => new Promise((_, reject) => { + rejectFirst = reject; + })) + .mockImplementationOnce(() => new Promise(() => {})); // Second attempt hangs in-flight + const { get } = setFetch(); - get('https://patternfly.org/a'); - await expect(get('https://patternfly.org/b')).rejects.toThrow('Fetch already in progress'); + const firstAttempt = get('https://patternfly.org/retry'); + + rejectFirst(new Error('network failure')); + + await expect(firstAttempt).rejects.toThrow('network failure'); + + const retryAttempt = get('https://patternfly.org/retry'); + + await expect(get('https://patternfly.org/other')).rejects.toThrow('Fetch already in progress'); + await expect(get('https://patternfly.org/retry')).rejects.toThrow('Fetch already in progress'); + expect(global.fetch).toHaveBeenCalledTimes(2); + expect(retryAttempt).toBeDefined(); }); it('should handle cancel properly', async () => { @@ -711,3 +750,64 @@ describe('setFetch', () => { }); }); }); + +describe('setFetchMemo', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('should memoize a fetch function with default options and forward args', async () => { + const memoSpy = jest.spyOn(serverCaching, 'memo'); + const options = getOptions(); + const mockFetchFn = jest.fn(async (url: string, settings?: RequestInit) => ({ + url, + headers: settings?.headers + })); + + const memoized = setFetchMemo('fetch_get', mockFetchFn, options); + + expect(memoSpy).toHaveBeenCalledWith( + mockFetchFn, + options.resourceMemoOptions.fetchUrl + ); + + const resultA = await memoized('https://patternfly.org/memo.txt', { + headers: { 'X-Custom': '1' } + }); + const resultB = await memoized('https://patternfly.org/memo.txt', { + headers: { 'X-Custom': '1' } + }); + + expect(mockFetchFn).toHaveBeenCalledTimes(1); + expect(mockFetchFn).toHaveBeenCalledWith( + 'https://patternfly.org/memo.txt', + { headers: { 'X-Custom': '1' } } + ); + expect(resultA).toBe(resultB); + }); + + it('should minimally differentiate native Headers instances in the memoized response', async () => { + const mockFetchFn = jest.fn(async (_url: string, init?: RequestInit) => { + const headers = new Headers(init?.headers); + + return `lang:${headers.get('accept-language') ?? 'unknown'}`; + }); + + const memoized = setFetchMemo('fetch_get', mockFetchFn); + + const enResult = await memoized('https://patternfly.org/i18n', { + headers: new Headers({ 'Accept-Language': 'en' }) + }); + const frResult = await memoized('https://patternfly.org/i18n', { + headers: new Headers({ 'Accept-Language': 'fr' }) + }); + + expect(enResult).toBe('lang:en'); + expect(frResult).toBe('lang:fr'); + expect(mockFetchFn).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/__tests__/server.fetchGet.test.ts b/src/__tests__/server.fetchGet.test.ts new file mode 100644 index 00000000..8fc5a91b --- /dev/null +++ b/src/__tests__/server.fetchGet.test.ts @@ -0,0 +1,96 @@ +import { ReadableStream } from 'node:stream/web'; +import { fetchGet } from '../server.fetchGet'; +import { FetchError } from '../server.fetch'; +import { getOptions } from '../options.context'; + +describe('fetchGet', () => { + beforeEach(() => { + jest.clearAllMocks(); + global.fetch = jest.fn(); + }); + + it('should attempt to fetch a URL', async () => { + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + headers: { + get: (name: string) => { + if (name === 'content-type') { + return 'text/plain'; + } + + return null; + } + }, + body: new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('fetched content')); + controller.close(); + } + }) + }; + + (global.fetch as jest.Mock).mockResolvedValue(mockResponse); + + const result = await fetchGet('https://patternfly.org/doc.md'); + + expect(global.fetch).toHaveBeenCalledWith( + 'https://patternfly.org/doc.md', + expect.objectContaining({ + method: 'GET' + }) + ); + expect(result).toMatchObject({ data: 'fetched content' }); + }); + + it('should handle non-OK responses', async () => { + const mockResponse = { + ok: false, + status: 404, + statusText: 'Not Found', + headers: { + get: () => null + } + }; + + (global.fetch as jest.Mock).mockResolvedValue(mockResponse); + + await expect(fetchGet('https://patternfly.org/missing.md')) + .rejects + .toThrow('404 Not Found'); + }); + + it('should throw a FetchError when response type is binary', async () => { + (global.fetch as jest.Mock).mockResolvedValue({ + ok: true, + status: 200, + statusText: 'OK', + headers: { + get: (name: string) => (name === 'content-type' ? 'image/png' : null) + }, + body: new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([0x89, 0x50, 0x4e, 0x47])); + controller.close(); + } + }) + }); + + const options = getOptions(); + + await expect( + fetchGet('https://patternfly.org/image.png', undefined, { + ...options, + xhrFetch: { + ...options.xhrFetch, + allowBinary: true + } + }) + ).rejects.toThrow(new FetchError({ message: 'Cannot return binary content (https://patternfly.org/image.png).' })); + }); + + it('should have memo property', () => { + expect(fetchGet.memo).toBeDefined(); + }); +}); diff --git a/src/__tests__/server.getResources.test.ts b/src/__tests__/server.getResources.test.ts index dd6388cf..dd5b01bd 100644 --- a/src/__tests__/server.getResources.test.ts +++ b/src/__tests__/server.getResources.test.ts @@ -1,16 +1,15 @@ import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; -import { ReadableStream } from 'node:stream/web'; import { matchPackageVersion, findNearestPackageJson, readLocalFileFunction, - fetchUrlFunction, processDocsFunction, promiseQueue, loadFileFetch, resolveLocalPathFunction } from '../server.getResources'; +import { fetchGet } from '../server.fetchGet'; import { runWithOptions } from '../options.context'; import { DEFAULT_OPTIONS } from '../options.defaults'; @@ -175,69 +174,6 @@ describe('readLocalFileFunction', () => { }); }); -describe('fetchUrlFunction', () => { - beforeEach(() => { - jest.clearAllMocks(); - global.fetch = jest.fn(); - }); - - it('should attempt to fetch a URL', async () => { - const mockResponse = { - ok: true, - status: 200, - statusText: 'OK', - headers: { - get: (name: string) => { - if (name === 'content-type') { - return 'text/plain'; - } - - return null; - } - }, - body: new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode('fetched content')); - controller.close(); - } - }) - }; - - (global.fetch as jest.Mock).mockResolvedValue(mockResponse); - - const result = await fetchUrlFunction('https://patternfly.org/doc.md'); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://patternfly.org/doc.md', - expect.objectContaining({ - method: 'GET' - }) - ); - expect(result).toBe('fetched content'); - }); - - it('should handle non-OK responses', async () => { - const mockResponse = { - ok: false, - status: 404, - statusText: 'Not Found', - headers: { - get: () => null - } - }; - - (global.fetch as jest.Mock).mockResolvedValue(mockResponse); - - await expect(fetchUrlFunction('https://patternfly.org/missing.md')) - .rejects - .toThrow('404 Not Found'); - }); - - it('should have memo property', () => { - expect(fetchUrlFunction.memo).toBeDefined(); - }); -}); - describe('resolveLocalPathFunction', () => { it.each([ { @@ -318,11 +254,11 @@ describe('loadFileFetch', () => { expectedIsFetch: false } ])('should attempt to load a file or fetch, $description', async ({ pathUrl, expectedIsFetch }) => { - const mockFetchCall = jest.fn().mockResolvedValue('content') as any; + const mockFetchCall = jest.fn().mockResolvedValue({ text: 'content' }) as any; const mockReadCall = jest.fn().mockResolvedValue('content') as any; readLocalFileFunction.memo = mockReadCall; - fetchUrlFunction.memo = mockFetchCall; + fetchGet.memo = mockFetchCall; const result = await runWithOptions({ ...DEFAULT_OPTIONS, docsPaths: ['/app/project/documentation'], contextPath: '/app/project' }, () => loadFileFetch(pathUrl)); @@ -343,7 +279,7 @@ describe('promiseQueue', () => { it('should execute promises in order', async () => { readLocalFileFunction.memo = jest.fn().mockImplementation(path => Promise.resolve(path)) as any; - fetchUrlFunction.memo = jest.fn().mockImplementation(url => Promise.reject(url)) as any; + fetchGet.memo = jest.fn().mockImplementation(url => Promise.reject(url)) as any; const pathUrlQueue = ['dolor-sit.md', 'https://example.com/remote.md', 'lorem-ipsum.md']; @@ -406,13 +342,13 @@ describe('processDocsFunction', () => { } ])('should process local and remote inputs, $description', async ({ inputs, fileMemoHits = 0, fetchMemoHits = 0 }) => { readLocalFileFunction.memo = jest.fn().mockResolvedValue('local file content') as any; - fetchUrlFunction.memo = jest.fn().mockResolvedValue('fetched content') as any; + fetchGet.memo = jest.fn().mockResolvedValue({ text: 'fetched content' }) as any; const result = await processDocsFunction(inputs, { loadLimit: 10 }); expect(result).toMatchSnapshot(); expect(readLocalFileFunction.memo).toHaveBeenCalledTimes(fileMemoHits); - expect(fetchUrlFunction.memo).toHaveBeenCalledTimes(fetchMemoHits); + expect(fetchGet.memo).toHaveBeenCalledTimes(fetchMemoHits); }); it('should handle errors gracefully', async () => { @@ -420,7 +356,7 @@ describe('processDocsFunction', () => { readLocalFileFunction.memo = jest.fn() .mockResolvedValueOnce('success content') .mockRejectedValueOnce(new Error('File not found')) as any; - fetchUrlFunction.memo = jest.fn().mockResolvedValue('fetched content') as any; + fetchGet.memo = jest.fn().mockResolvedValue({ text: 'fetched content' }) as any; const inputs = [ 'good-file.md', @@ -463,7 +399,7 @@ describe('processDocsFunction', () => { } ])('should handle custom settings: $description', async ({ inputs, settings, expectedCount, expectedPaths }) => { readLocalFileFunction.memo = jest.fn().mockImplementation(async (path: string) => `content of ${path}`) as any; - fetchUrlFunction.memo = jest.fn().mockImplementation(async (url: string) => `content of ${url}`) as any; + fetchGet.memo = jest.fn().mockImplementation(async (url: string) => ({ text: `content of ${url}` })) as any; const result = await processDocsFunction(inputs, settings); diff --git a/src/__tests__/server.helpers.test.ts b/src/__tests__/server.helpers.test.ts index e8969638..07069489 100644 --- a/src/__tests__/server.helpers.test.ts +++ b/src/__tests__/server.helpers.test.ts @@ -342,6 +342,20 @@ describe('generateHash', () => { expectedComparison: false, expectedUndefined: false }, + { + description: 'headers, same entries', + value: new Headers({ 'Accept-Language': 'en', 'X-Custom': '1' }), + comparisonValue: new Headers({ 'X-Custom': '1', 'accept-language': 'en' }), + expectedComparison: true, + expectedUndefined: false + }, + { + description: 'headers, different values', + value: new Headers({ 'Accept-Language': 'en' }), + comparisonValue: new Headers({ 'Accept-Language': 'fr' }), + expectedComparison: false, + expectedUndefined: false + }, { description: 'map, same order', value: new Map([['lorem', 1], ['ipsum', 2]]), diff --git a/src/collection.patternFlyApi.ts b/src/collection.patternFlyApi.ts index a5a656df..6dd4c2bb 100644 --- a/src/collection.patternFlyApi.ts +++ b/src/collection.patternFlyApi.ts @@ -7,7 +7,7 @@ import { import { formatUnknownError, log } from './logger'; import { processDocsFunction } from './server.getResources'; import { memo } from './server.caching'; -import { setFetch } from './server.fetch'; +import { fetchGet } from './server.fetchGet'; import { deferTask } from './server.task'; import { isPlainObject, joinUrl, timeoutFunction } from './server.helpers'; import { @@ -207,31 +207,30 @@ const DEFERRED_API_CATEGORIES = new Set([ const MIN_API_QUALITY_THRESHOLD = 0.95; /** - * Majority confirmation, is the API live and healthy? + * Best-effort majority confirmation, is the API live and healthy? + * + * @note Behavior: + * - Timing has been chosen to help with initial collection loading + * - Once `probeHealth()` returns, any delayed responses cannot change + * the confirmation. * * @param options - Global options. * @returns `true` if 2 of 3 probes INCLUDING the last attempt confirms the API is live and healthy, otherwise `false`. */ const probeHealth = async (options = getOptions()): Promise => { const { base } = options.patternflyOptions.api; - const { get } = setFetch(); let successCount = 0; - let isLastSuccess = false; + let isLastSuccess = true; log.debug('Checking PatternFly API heartbeat.'); const check = async () => { - isLastSuccess = false; - - try { - const response = await get(base, { method: 'HEAD' }); + const response = await fetchGet(base, { method: 'HEAD' }); - if (response.status < 400) { - successCount += 1; - isLastSuccess = true; - } - } catch { - isLastSuccess = false; + if (response.status < 400) { + successCount += 1; + } else { + throw new Error(`API returned status ${response.status}`); } }; @@ -244,7 +243,7 @@ const probeHealth = async (options = getOptions()): Promise => { try { await task.start(); } catch { - // Handled by continueOnError + isLastSuccess = false; } return successCount >= 2 && isLastSuccess; diff --git a/src/server.fetch.ts b/src/server.fetch.ts index 9701eff2..2b9907fb 100644 --- a/src/server.fetch.ts +++ b/src/server.fetch.ts @@ -3,10 +3,11 @@ import { type ReadableStream } from 'node:stream/web'; import { getOptions } from './options.context'; import { formatUnknownError, log } from './logger'; import { sanitizeMessage } from './logger.helpers'; -import { memo } from './server.caching'; +import { memo, type MemoReturn } from './server.caching'; import { assertInputUrlWhiteListed } from './server.assertions'; import { isUrl } from './server.helpers'; import { type WhitelistUrl } from './options.defaults'; +import { type GlobalOptions } from './options'; /** * Decoded payload. Can either be textual or binary data. @@ -91,11 +92,13 @@ interface FetchResponse { /** * Set a fetch request. * + * @interface SetFetchInstance + * * @property get - Function to perform a GET request. * @property cancel - Function to cancel the fetch request. * @property status - Function to get the status of the fetch request. */ -interface SetFetch { +interface SetFetchInstance { get: (url: string, settings?: RequestInit) => Promise; // post: (url: string, data: unknown) => Promise; cancel: () => void; @@ -440,10 +443,9 @@ const preflight = async ( * * @note * **Single-flight by design.** Each `setFetch()` call returns an isolated instance - * with its own in-flight tracking (`inflight` is closure state, not module state). + * with its own in-flight tracking (`controller` is closure state, not module state). * A given instance will service **one active request at a time**: - * - A second `get(sameUrl)` while one is in-flight returns the same promise (de-dup). - * - A second `get(otherUrl)` while one is in-flight rejects with `FetchError` + * - Any second `get` while one is in-flight rejects with `FetchError` * ("Fetch already in progress. Create a new setFetch."). * Callers that need parallelism should instantiate a new `setFetch()` per request. * @@ -463,13 +465,13 @@ const preflight = async ( * This policy keeps tests deterministic and prevents accidental calls to external networks during * testing. * - * @param {GlobalOptions} [options=getOptions()] - Configuration options for the fetch operation. - * @returns {SetFetch} Fetch operations: + * @param {GlobalOptions} [options] - Configuration options for the fetch operation. + * @returns {SetFetchInstance} Fetch operations: * - `get`: GET request callback to the specified URL. * - `cancel`: Cancel callback for the fetch operation. * - `status`: Callback for returning state or registering a state listener. */ -const setFetch = (options = getOptions()): SetFetch => { +const setFetch = (options = getOptions()): SetFetchInstance => { const { mode, modeOptions, whitelist, xhrFetch } = options; const fixtureUrl = mode === 'test' ? modeOptions?.test?.baseUrl : undefined; @@ -480,7 +482,6 @@ const setFetch = (options = getOptions()): SetFetch => { let controller: AbortController | undefined; let stream: Readable | undefined; let timeoutId: ReturnType | undefined; - let inflight: { key: string; promise: Promise } | undefined; let updatedWhitelist = whitelist.urls; let isTestModeFetchBlocked = false; @@ -511,37 +512,6 @@ const setFetch = (options = getOptions()): SetFetch => { }); }; - /** - * Prevent duplicating async tasks for the same key. - * - * @param {string} key - A unique identifier associated with the operation. - * @param {() => Promise} startFetch - Start the async operation and return a promise. - * @returns {Promise} Promise that resolves to the result of the async operation. - * - * @throws {FetchError} If an operation with the specified key is already in progress and a new - * task is attempted. - */ - const checkInflight = (key: string, startFetch: () => Promise): Promise => { - if (inflight) { - if (inflight.key === key) { - return inflight.promise; - } - - return Promise.reject(new FetchError({ - message: 'Fetch already in progress. Create a new setFetch.', - sanitize: xhrFetch.sanitizeMessages - })); - } - - const promise = startFetch().finally(() => { - inflight = undefined; - }); - - inflight = { key, promise }; - - return promise; - }; - /** * Execute a fetch request with the given URL and settings. * @@ -699,9 +669,16 @@ const setFetch = (options = getOptions()): SetFetch => { return { get: (url: string, settings: RequestInit = {}) => { const updatedSettings = { method: 'GET', ...(settings || {}) }; - const key = `${updatedSettings.method}:${url}`; - return checkInflight(key, () => executeFetch(url, updatedSettings)); + // Controller is defined for the lifetime of a request, then undefined. + if (controller) { + return Promise.reject(new FetchError({ + message: 'Fetch already in progress. Create a new setFetch.', + sanitize: xhrFetch.sanitizeMessages + })); + } + + return executeFetch(url, updatedSettings); }, cancel: () => { if (state.phase !== 'loading') { @@ -729,6 +706,23 @@ const setFetch = (options = getOptions()): SetFetch => { }; }; +/** + * Set a memoized version of a fetch function and route cacheDb activation. + * + * @param _cacheNamespace - Future namespace for cacheDb + * @param fn - Fetch function to memoize. + * @param options - Global options. + */ +const setFetchMemo = ( + _cacheNamespace: string, + fn: (url: string, settings?: RequestInit, options?: GlobalOptions) => Promise, + options = getOptions() +): MemoReturn<[url: string, settings?: RequestInit, options?: GlobalOptions], Promise> => { + const { resourceMemoOptions } = options; + + return memo(fn, resourceMemoOptions.fetchUrl); +}; + export { decodeStream, isBinaryMime, @@ -738,10 +732,11 @@ export { parsePayload, preflight, setFetch, + setFetchMemo, FetchError, type DecodedPayload, type DecodedStreamResult, type FetchState, type FetchResponse, - type SetFetch + type SetFetchInstance }; diff --git a/src/server.fetchGet.ts b/src/server.fetchGet.ts new file mode 100644 index 00000000..37f28034 --- /dev/null +++ b/src/server.fetchGet.ts @@ -0,0 +1,47 @@ +import { FetchError, type FetchResponse, setFetch, setFetchMemo } from './server.fetch'; +import { getOptions } from './options.context'; + +/** + * Generic GET request. Creates a fresh single-flight `setFetch` instance per call. + * + * @note Minor guard against unexpected binary content. Currently, binary content + * is unsupported. See {@link XhrFetchOptions} + * + * @param url - URL to fetch. + * @param [settings] - Optional fetch RequestInit settings. + * @param [options] - Configuration options. + * @returns Resolves with the full FetchResponse. + */ +const fetchGet = async ( + url: string, + settings?: RequestInit, + options = getOptions() +): Promise => { + const { type, data, ...response } = await setFetch(options).get(url, settings); + + if (type === 'binary') { + throw new FetchError({ message: `Cannot return binary content (${url}).` }); + } + + const parseText = () => + (typeof data === 'string' ? data : JSON.stringify(data)); + + return { + ...response, + type, + data, + text: parseText() + }; +}; + +/** + * Memoized generic GET request. + * + * @note Calling `setFetchMemo` at module load works because `index.ts` calls `setOptions()` + * before dynamically importing `./server`, ensuring `getOptions()` already has runtime options. + */ +fetchGet.memo = setFetchMemo('fetch_get', fetchGet); + +export { + fetchGet +}; diff --git a/src/server.getResources.ts b/src/server.getResources.ts index eab786bc..409ac7d3 100644 --- a/src/server.getResources.ts +++ b/src/server.getResources.ts @@ -7,7 +7,7 @@ import { DEFAULT_OPTIONS } from './options.defaults'; import { memo } from './server.caching'; import { normalizeString } from './server.search'; import { isUrl, isPath, createError } from './server.helpers'; -import { FetchError, setFetch } from './server.fetch'; +import { fetchGet } from './server.fetchGet'; import { delay } from './server.task'; import { log, formatUnknownError } from './logger'; import { sanitizeMessage } from './logger.helpers'; @@ -139,31 +139,6 @@ const readLocalFileFunction = async (filePath: string) => await readFile(filePat */ readLocalFileFunction.memo = memo(readLocalFileFunction, DEFAULT_OPTIONS.resourceMemoOptions.readFile); -/** - * Fetch content from a URL with timeout and error handling - * - * @note Minor guard against unexpected binary content. Currently, binary content - * is unsupported. See {@link XhrFetchOptions} - * - * @param url - URL to fetch - * @returns The fetched content as a string. - */ -const fetchUrlFunction = async (url: string): Promise => { - const { get } = setFetch(); - const { data, type } = await get(url); // throws FetchError on any failure - - if (type === 'binary') { - throw new FetchError({ message: `Cannot return binary content (${url}).` }); - } - - return typeof data === 'string' ? data : JSON.stringify(data); -}; - -/** - * Memoized version of fetchUrlFunction. Use default memo options. - */ -fetchUrlFunction.memo = memo(fetchUrlFunction, DEFAULT_OPTIONS.resourceMemoOptions.fetchUrl); - /** * Resolve a local path against a base directory. * Ensures the resolved path stays within the intended base for security. @@ -237,7 +212,9 @@ const mockPathOrUrlFunction = async (pathOrUrl: string, options = getOptions()) } // In test mode, everything is treated as a fetchable resource to allow mocking - return fetchUrlFunction.memo(updatedPathOrUrl); + const { text } = await fetchGet.memo(updatedPathOrUrl); + + return text; }; /** @@ -263,7 +240,7 @@ const loadFileFetch = async (pathOrUrl: string, options = getOptions()) => { let content; if (isUrl(updatedPathOrUrl)) { - content = await fetchUrlFunction.memo(updatedPathOrUrl); + ({ text: content } = await fetchGet.memo(updatedPathOrUrl)); } else { content = await readLocalFileFunction.memo(updatedPathOrUrl); } @@ -411,7 +388,6 @@ const processDocsFunction = async = Record { return { $regexp: value.toString() }; } + if (typeof Headers !== 'undefined' && value instanceof Headers) { + const entries = Array.from(value.entries()) + .map(([key, val]) => [hashNormalizeValue(key), hashNormalizeValue(val)]) + .sort(([a], [b]) => normalizeSort(JSON.stringify(a), JSON.stringify(b))); + + return { $headers: entries }; + } + if (value instanceof Map) { const entries = Array.from(value.entries()) .map(([key, val]) => [hashNormalizeValue(key), hashNormalizeValue(val)]) diff --git a/tests/e2e/__snapshots__/stdioTransport.test.ts.snap b/tests/e2e/__snapshots__/stdioTransport.test.ts.snap index 7c2d935b..cd1da095 100644 --- a/tests/e2e/__snapshots__/stdioTransport.test.ts.snap +++ b/tests/e2e/__snapshots__/stdioTransport.test.ts.snap @@ -175,126 +175,8 @@ exports[`Builtin tools, STDIO should return expected markdown structure for sear - Use a search all ("*") to find all available resources." `; -exports[`Logging should allow server debug logs: debug log 1`] = ` -[ - "[DEBUG]: Server memo: { -", - " "type": "memo promise", -", - " "cache": [ -", - " [ -", - " "[REDACTED]", -", - " {} -", - " ] -", - " ] -", - "} -", - "[DEBUG]: Reviewing registration for 4 collections. -", - "[DEBUG]: Running collection "patternfly-docs" -", - "[DEBUG]: Running collection "patternfly-component-schemas" -", - "[DEBUG]: Running collection "patternfly-api" -", - "[DEBUG]: PatternFly API crawler is disabled, using baseline records. -", - "[DEBUG]: Running collection "ai-handbook" -", - "[DEBUG]: Merging collection patternfly-component-schemas records. (XXX) -", - "[DEBUG]: Failed to load https://raw.githubusercontent.com/rh-uxd/ai-handbook/refs/heads/main/docs.json from processing: Access denied: "setFetch URL" must be within the whitelisted URLs. -", - "[DEBUG]: Storing server collection patternfly-component-schemas records. (XXX) -", - "[DEBUG]: Merging collection patternfly-docs records. (XXX) -", - "[DEBUG]: Merging collection patternfly-api records. (XXX) -", - "[DEBUG]: Storing server collection patternfly-docs records. (XXX) -", - "[DEBUG]: Storing server collection patternfly-api records. (XXX) -", - "[DEBUG]: Merging collection ai-handbook records. (XXX) -", - "[DEBUG]: Storing server collection ai-handbook records. (XXX) -", - "[DEBUG]: Settled collection: patternfly-docs -", - "[DEBUG]: Settled collection: patternfly-component-schemas -", - "[DEBUG]: Settled collection: patternfly-api -", - "[DEBUG]: Settled collection: ai-handbook -", - "[DEBUG]: Skipping tool registration: searchPatternFly -", -] -`; - exports[`Logging should allow setting logging options, default 1`] = `[]`; -exports[`Logging should allow setting logging options, stderr 1`] = ` -[ - "[INFO]: Server logging enabled. -", - "[INFO]: Server stats enabled. -", - "[INFO]: No external resources loaded. -", - "[INFO]: No external tools loaded. -", - "[INFO]: Registered collection: patternfly-docs -", - "[INFO]: Registered collection: patternfly-component-schemas -", - "[INFO]: Registered collection: patternfly-api -", - "[INFO]: Registered collection: ai-handbook -", - "[WARN]: Network access blocked for https://raw.githubusercontent.com/rh-uxd/ai-handbook/refs/heads/main/docs.json: server is in 'test' mode and 'modeOptions.test.baseUrl' is not configured. :Configure 'modeOptions.test.baseUrl' to allow outbound fetches. -", - "[INFO]: Update collection: patternfly-component-schemas -", - "[INFO]: Update collection: patternfly-docs -", - "[INFO]: Update collection: patternfly-api -", - "[INFO]: Update collection: ai-handbook -", - "[INFO]: Registered resource: patternfly-context -", - "[INFO]: Registered resource: patternfly-components-index-meta -", - "[INFO]: Registered resource: patternfly-components-index -", - "[INFO]: Registered resource: patternfly-docs-index-meta -", - "[INFO]: Registered resource: patternfly-docs-index -", - "[INFO]: Registered resource: patternfly-docs-template -", - "[INFO]: Registered resource: patternfly-schemas-index-meta -", - "[INFO]: Registered resource: patternfly-schemas-index -", - "[INFO]: Registered resource: patternfly-schemas-template -", - "[INFO]: Registered tool: usePatternFlyDocs -", - "[INFO]: Registered tool: searchPatternFlyDocs -", - "[INFO]: @patternfly/patternfly-mcp server running on stdio transport -", -] -`; - exports[`Logging should allow setting logging options, with experimental flag set 1`] = `[]`; exports[`Logging should allow setting logging options, with log level filtering 1`] = `[]`; diff --git a/tests/e2e/stdioTransport.test.ts b/tests/e2e/stdioTransport.test.ts index 6613eb3e..3c41cf4a 100644 --- a/tests/e2e/stdioTransport.test.ts +++ b/tests/e2e/stdioTransport.test.ts @@ -497,10 +497,6 @@ describe('Logging', () => { description: 'default', args: [] }, - { - description: 'stderr', - args: ['--log-stderr'] - }, { description: 'with log level filtering', args: ['--log-level', 'warn'] @@ -521,20 +517,81 @@ describe('Logging', () => { await CLIENT.stop(); }); +}); + +describe('Debug logging timeline', () => { + let CLIENT: StdioTransportClient; + let logs: string[] = []; - it('should allow server debug logs', async () => { - const CLIENT = await startServer({ + beforeAll(async () => { + CLIENT = await startServer({ args: ['--log-stderr', '--log-level', 'debug'] }); + logs = CLIENT.logs(); + }); - const logs = CLIENT.logs(); - const memoLog = logs - .filter(line => line.startsWith('[DEBUG]:') || line.startsWith(' ') || line.trim() === '}') - .map(line => (line.includes('collection') ? line.replace(/\(([\d]*)\)/g, '(XXX)') : line)); + afterAll(async () => { + if (CLIENT) { + await CLIENT.stop(); + } + }); - expect(memoLog).toMatchSnapshot('debug log'); + it.each([ + { + name: 'server lifecycle', + sequence: [ + 'Server memo:', + 'Reviewing registration for 4 collections.', + 'Skipping tool registration:' + ] + }, + { + name: 'patternfly-docs collection', + sequence: [ + 'Running collection "patternfly-docs"', + 'Merging collection patternfly-docs records.', + 'Storing server collection patternfly-docs records.', + 'Settled collection: patternfly-docs' + ] + }, + { + name: 'patternfly-component-schemas collection', + sequence: [ + 'Running collection "patternfly-component-schemas"', + 'Merging collection patternfly-component-schemas records.', + 'Storing server collection patternfly-component-schemas records.', + 'Settled collection: patternfly-component-schemas' + ] + }, + { + name: 'patternfly-api collection', + sequence: [ + 'Running collection "patternfly-api"', + 'Merging collection patternfly-api records.', + 'Storing server collection patternfly-api records.', + 'Settled collection: patternfly-api' + ] + }, + { + name: 'ai-handbook collection', + sequence: [ + 'Running collection "ai-handbook"', + 'Failed to load https://raw.githubusercontent.com', + 'Merging collection ai-handbook records.', + 'Storing server collection ai-handbook records.', + 'Settled collection: ai-handbook' + ] + } + ])('should follow sequence: $name', ({ sequence }) => { + let lastIndex = -1; - await CLIENT.stop(); + for (const item of sequence) { + const nextIndex = logs.findIndex((log, index) => + index > lastIndex && log.includes(item)); + + expect(nextIndex).toBeGreaterThan(lastIndex); + lastIndex = nextIndex; + } }); });