Spaces:
Running
Running
Sync from felladrin/MiniSearch@fd8be33 (part 2)
Browse filesFiles changed (6)
7 unmodified lines89101112131415161765 unmodified lines8384858687882 unmodified lines919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142142 unmodified lines28528628728828929043 unmodified lines3343353363373383393408 unmodified lines3493503513523533543556 unmodified lines3623633643653663673682 unmodified lines371372373374375376236 unmodified lines61361461561661761817 unmodified lines63663763863964064164264364464564664764824 unmodified lines67367467567667767867926 unmodified lines70670770870971071171240 unmodified lines75375475575675775875937 unmodified lines79779879980080180280328 unmodified lines8328338348357 unmodified linestype MockedFunction,vi,} from "vitest";import {fetchFallbackTextResults,isSearchFallbackEnabled,} from "./fallbackSearchService";function createMockResponse(body: string,65 unmodified linesreturn toolReply({ search_id: "search-1", results });}const EXCERPT ="The opening sentence of a very long excerpt that has to survive the filter. alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec";2 unmodified lineslet originalFetch: typeof fetch;let fetchMock: MockedFunction<typeof fetch>;const originalEnabled = process.env.SEARCH_FALLBACK_ENABLED;const originalApiKey = process.env.SEARCH_FALLBACK_API_KEY;beforeEach(() => {delete process.env.SEARCH_FALLBACK_ENABLED;delete process.env.SEARCH_FALLBACK_API_KEY;originalFetch = global.fetch;fetchMock = vi.fn() as unknown as MockedFunction<typeof fetch>;global.fetch = fetchMock;});afterEach(() => {global.fetch = originalFetch;if (originalEnabled === undefined) delete process.env.SEARCH_FALLBACK_ENABLED;else process.env.SEARCH_FALLBACK_ENABLED = originalEnabled;if (originalApiKey === undefined) delete process.env.SEARCH_FALLBACK_API_KEY;else process.env.SEARCH_FALLBACK_API_KEY = originalApiKey;vi.restoreAllMocks();});/** Answers the three requests in order with the given tool-call reply. */function mockExchange(toolBody: string,{initializeBody = INITIALIZE_REPLY,initializeContentType = "application/json",toolContentType = "application/json",}: {initializeBody?: string;initializeContentType?: string;toolContentType?: string;} = {},) {fetchMock.mockResolvedValueOnce(createMockResponse(initializeBody, {contentType: initializeContentType,headers: { "mcp-session-id": SESSION_ID },}),).mockResolvedValueOnce(createMockResponse(NOTIFICATION_ACCEPTED, { status: 202 }),).mockResolvedValueOnce(createMockResponse(toolBody, { contentType: toolContentType }),);}function requestBody(index: number): {142 unmodified linesit("hands the exchange the caller's budget, capped at its own", async () => {mockExchange(documentWith([]));mockExchange(documentWith([]));const timeoutSpy = vi.spyOn(AbortSignal, "timeout");await fetchFallbackTextResults(QUERY, 10, 3_000);43 unmodified linesawait expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("did not open a session (status 500)");expect(cancelInitialize).toHaveBeenCalledTimes(1);});8 unmodified lines});it("sends the Bearer header on every request when a key is configured", async () => {process.env.SEARCH_FALLBACK_API_KEY = "sk-fallback-key";mockExchange(documentWith([]));await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);6 unmodified lines});it("treats a whitespace-only key as no key", async () => {process.env.SEARCH_FALLBACK_API_KEY = " ";mockExchange(documentWith([]));await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);2 unmodified lines});});describe("reading the reply", () => {it("parses an application/json reply", async () => {mockExchange(236 unmodified lines});describe("failures", () => {it("throws when the tool call is not 2xx", async () => {const cancel = vi.fn(async () => undefined);fetchMock.mockResolvedValueOnce(17 unmodified linesexpect(cancel).toHaveBeenCalledTimes(1);});it("throws when initialize does not open a session", async () => {fetchMock.mockResolvedValueOnce(createMockResponse(INITIALIZE_REPLY));await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("did not open a session (status 200)");expect(fetchMock).toHaveBeenCalledTimes(1);});it("throws on a JSON-RPC error and keeps the endpoint's message out of it", async () => {24 unmodified lines// free-form text from a third party and must not travel any further.expect(rejection).toBeInstanceOf(Error);expect((rejection as Error).message).toBe("The fallback search endpoint returned a JSON-RPC error (code -32601)",);expect(String(rejection)).not.toContain("SECRET UPSTREAM TEXT");});26 unmodified lines// carried into the thrown error.expect(rejection).toBeInstanceOf(Error);expect((rejection as Error).message).toBe("The fallback search endpoint returned a JSON-RPC error",);expect(String(rejection)).not.toContain("SECRET");});40 unmodified lines// A raw SyntaxError quotes the offending body, which would put the// upstream response into the thrown error and then into the log.expect((rejection as Error).message).toBe("The fallback search endpoint sent a reply that is not JSON",);expect(String(rejection)).not.toContain("<html>");});37 unmodified lines});it("never writes the query, the API key or the response text to the log", async () => {process.env.SEARCH_FALLBACK_API_KEY = "sk-fallback-key";mockExchange(documentWith([{28 unmodified lines}expect(logLines.length).toBeGreaterThan(0);});});7 unmodified lines891011121365 unmodified lines79808182838485868788899091929394959697982 unmodified lines101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187142 unmodified lines33033133233333433533633743 unmodified lines3813823833843853863878 unmodified lines3963973983994004014026 unmodified lines4094104114124134144152 unmodified lines418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739236 unmodified lines97697797897998098198298398498598698798898999099199299399499599699799817 unmodified lines101610171018101910201021102210231024102510261027102810291030103124 unmodified lines105610571058105910601061106226 unmodified lines108910901091109210931094109540 unmodified lines113611371138113911401141114237 unmodified lines118011811182118311841185118628 unmodified lines12151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118727 unmodified linestype MockedFunction,vi,} from "vitest";function createMockResponse(body: string,65 unmodified linesreturn toolReply({ search_id: "search-1", results });}// You.com's reply wraps its web results one level deeper, under// `results.web`, and each result carries a description and, when the query// matched the page, query-relevant highlights.function youcomDocumentWith(web: unknown[]): string {return toolReply({ results: { web } });}const PARALLEL_URL = "https://search.parallel.ai/mcp";const YOUCOM_KEYLESS_URL = "https://api.you.com/mcp?profile=free";const YOUCOM_AUTHENTICATED_URL = "https://api.you.com/mcp";const DESCRIPTION ="A plain description that You.com returns for a page that matched the query, long enough to read as a summary.";const EXCERPT ="The opening sentence of a very long excerpt that has to survive the filter. alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec";2 unmodified lineslet originalFetch: typeof fetch;let fetchMock: MockedFunction<typeof fetch>;type FallbackModule = typeof import("./fallbackSearchService");let fetchFallbackTextResults: FallbackModule["fetchFallbackTextResults"];let isSearchFallbackEnabled: FallbackModule["isSearchFallbackEnabled"];let assertSearchFallbackConfiguration: FallbackModule["assertSearchFallbackConfiguration"];let getFallbackProviderStats: FallbackModule["getFallbackProviderStats"];const FALLBACK_VARIABLES = ["SEARCH_FALLBACK_ENABLED","SEARCH_FALLBACK_PROVIDERS","SEARCH_FALLBACK_PARALLEL_API_KEY","SEARCH_FALLBACK_YOUCOM_API_KEY","SEARCH_FALLBACK_PROVIDER","SEARCH_FALLBACK_API_KEY",] as const;const originalVariables = Object.fromEntries(FALLBACK_VARIABLES.map((name) => [name, process.env[name]]),);beforeEach(async () => {for (const name of FALLBACK_VARIABLES) delete process.env[name];// Pinned to one provider so the tests below that are about one exchange// run it alone, without the shuffle; the cascade tests clear it.process.env.SEARCH_FALLBACK_PROVIDERS = "parallel";originalFetch = global.fetch;fetchMock = vi.fn() as unknown as MockedFunction<typeof fetch>;global.fetch = fetchMock;// A fresh module per test: pauses and counters are process state, and one// test's 429 must not leave a provider boxed for the next.vi.resetModules();({fetchFallbackTextResults,isSearchFallbackEnabled,assertSearchFallbackConfiguration,getFallbackProviderStats,} = await import("./fallbackSearchService"));});afterEach(() => {global.fetch = originalFetch;for (const name of FALLBACK_VARIABLES) {const original = originalVariables[name];if (original === undefined) delete process.env[name];else process.env[name] = original;}vi.useRealTimers();vi.restoreAllMocks();});/** Answers the requests in order with the given tool-call reply. */function mockExchange(toolBody: string,{initializeBody = INITIALIZE_REPLY,initializeContentType = "application/json",toolContentType = "application/json",initializeSession = SESSION_ID,}: {initializeBody?: string;initializeContentType?: string;toolContentType?: string;initializeSession?: string | null;} = {},) {fetchMock.mockResolvedValueOnce(createMockResponse(initializeBody, {contentType: initializeContentType,headers: initializeSession ? { "mcp-session-id": initializeSession } : {},}),);// A stateless initialize answers no session, so the initialized// notification never goes out and the tool call follows at once.if (initializeSession) {fetchMock.mockResolvedValueOnce(createMockResponse(NOTIFICATION_ACCEPTED, { status: 202 }),);}fetchMock.mockResolvedValueOnce(createMockResponse(toolBody, { contentType: toolContentType }),);}function requestBody(index: number): {142 unmodified linesit("hands the exchange the caller's budget, capped at its own", async () => {mockExchange(documentWith([]));mockExchange(documentWith([]));// A frozen clock, so the remaining budget is exactly what was passed in.vi.useFakeTimers({ toFake: ["Date"] });const timeoutSpy = vi.spyOn(AbortSignal, "timeout");await fetchFallbackTextResults(QUERY, 10, 3_000);43 unmodified linesawait expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("did not answer the initialize request (status 500)");expect(cancelInitialize).toHaveBeenCalledTimes(1);});8 unmodified lines});it("sends the Bearer header on every request when a key is configured", async () => {process.env.SEARCH_FALLBACK_PARALLEL_API_KEY = "sk-fallback-key";mockExchange(documentWith([]));await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);6 unmodified lines});it("treats a whitespace-only key as no key", async () => {process.env.SEARCH_FALLBACK_PARALLEL_API_KEY = " ";mockExchange(documentWith([]));await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);2 unmodified lines});});describe("choosing the provider", () => {it("runs the Parallel exchange by default", async () => {mockExchange(documentWith([]));await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(fetchMock).toHaveBeenCalledTimes(3);for (const [requestUrl] of fetchMock.mock.calls) {expect(String(requestUrl)).toBe(PARALLEL_URL);}expect(requestBody(2).params?.name).toBe("web_search");});it("runs the You.com exchange when SEARCH_FALLBACK_PROVIDERS lists youcom", async () => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";mockExchange(youcomDocumentWith([]), { initializeSession: null });await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(fetchMock).toHaveBeenCalledTimes(2);for (const [requestUrl] of fetchMock.mock.calls) {expect(String(requestUrl)).toBe(YOUCOM_KEYLESS_URL);}expect(requestBody(1).params?.name).toBe("you-search");expect(requestBody(1).params?.arguments).toEqual({query: QUERY,count: 10,});});it("sends the protocol version but no session id when You.com opens no session", async () => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";mockExchange(youcomDocumentWith([]), { initializeSession: null });await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(fetchMock).toHaveBeenCalledTimes(2);expect(requestBody(1).method).toBe("tools/call");for (const index of [0, 1]) {expect(requestHeaders(index)["Mcp-Session-Id"]).toBeUndefined();}expect(requestHeaders(0)["MCP-Protocol-Version"]).toBeUndefined();expect(requestHeaders(1)["MCP-Protocol-Version"]).toBe("2025-06-18");});it("acknowledges a session and carries it when You.com opens one", async () => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";mockExchange(youcomDocumentWith([]));await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(fetchMock).toHaveBeenCalledTimes(3);expect(requestBody(1).method).toBe("notifications/initialized");for (const index of [1, 2]) {expect(requestHeaders(index)["Mcp-Session-Id"]).toBe(SESSION_ID);}});it("uses You.com's authenticated endpoint and the Bearer key when a key is set", async () => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";process.env.SEARCH_FALLBACK_YOUCOM_API_KEY = "***";mockExchange(youcomDocumentWith([]), { initializeSession: null });await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);for (const [requestUrl] of fetchMock.mock.calls) {expect(String(requestUrl)).toBe(YOUCOM_AUTHENTICATED_URL);}for (const index of [0, 1]) {expect(requestHeaders(index).Authorization).toBe("Bearer ***");}});});describe("mapping You.com results", () => {const runYoucom = async (web: unknown[], limit = 10) => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";mockExchange(youcomDocumentWith(web), { initializeSession: null });return fetchFallbackTextResults(QUERY, limit, FULL_BUDGET_MS);};it("uses the description as the snippet, collapsed to one line", async () => {const results = await runYoucom([{url: "https://example.com/described",title: "Described",description: "A description with\n\nnewlines and extra spaces in it.",},]);expect(results).toEqual([["Described","A description with newlines and extra spaces in it.","https://example.com/described",],]);});it("truncates a long description at a word boundary", async () => {const description = `${EXCERPT} ${LONG_EXCERPT}`;expect(description.length).toBeGreaterThan(400);const results = await runYoucom([{url: "https://example.com/long",title: "Long",description,},]);const snippet = results[0][1];expect(snippet.endsWith("โฆ")).toBe(true);expect(snippet.length).toBeLessThanOrEqual(400);const kept = snippet.slice(0, -1);// The kept text is a prefix of the collapsed source, and the source// continues with a space, so the cut landed between two words rather// than inside one.expect(description.startsWith(kept)).toBe(true);expect(description[kept.length]).toBe(" ");});it("keeps a short description that the excerpt length filter would drop", async () => {const results = await runYoucom([{url: "https://example.com/terse",title: "Terse",description: "Terse.",},]);expect(results).toEqual([["Terse", "Terse.", "https://example.com/terse"]]);});it("falls back to the highlights when the description is empty or null", async () => {const results = await runYoucom([{url: "https://example.com/empty",title: "Empty",description: "",contents: { highlights: ["Skip to main content", EXCERPT] },},{url: "https://example.com/null",title: "Null",description: null,contents: { highlights: [EXCERPT] },},]);expect(results).toEqual([["Empty", EXCERPT, "https://example.com/empty"],["Null", EXCERPT, "https://example.com/null"],]);});it("drops a result with no url, a null or empty title, or no snippet", async () => {const results = await runYoucom([{ title: "No url", description: DESCRIPTION },{url: "https://example.com/null-title",title: null,description: DESCRIPTION,},{url: "https://example.com/empty-title",title: " ",description: DESCRIPTION,},{url: "https://example.com/no-snippet",title: "No snippet",description: "",},{url: "https://example.com/crumb-only",title: "Crumb only",description: "",contents: { highlights: ["Skip to main content"] },},{url: "https://example.com/kept",title: "Kept",description: DESCRIPTION,},]);expect(results).toEqual([["Kept", DESCRIPTION, "https://example.com/kept"],]);});it("drops a result whose url or title is not a string", async () => {const results = await runYoucom([{ url: 42, title: "Number url", description: DESCRIPTION },{ url: null, title: "Null url", description: DESCRIPTION },{url: "https://example.com/number-title",title: 7,description: DESCRIPTION,},null,{url: "https://example.com/kept",title: "Kept",description: DESCRIPTION,},]);// One malformed entry must not take the rest of the search down with it.expect(results).toEqual([["Kept", DESCRIPTION, "https://example.com/kept"],]);});it("drops duplicate urls in the endpoint's order", async () => {const results = await runYoucom([{url: "https://example.com/dup",title: "First",description: DESCRIPTION,},{url: "https://example.com/other",title: "Second",description: DESCRIPTION,},{url: "https://example.com/dup",title: "Third",description: DESCRIPTION,},]);expect(results.map(([title]) => title)).toEqual(["First", "Second"]);});it("keeps the endpoint's relevance order and applies the limit", async () => {const results = await runYoucom([{url: "https://example.com/1",title: "One",description: DESCRIPTION,},{url: "https://example.com/2",title: "Two",description: DESCRIPTION,},{url: "https://example.com/3",title: "Three",description: DESCRIPTION,},],2,);expect(results.map(([title]) => title)).toEqual(["One", "Two"]);});it("throws when the document has no web results array", async () => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";mockExchange(toolReply({ results: {} }), { initializeSession: null });await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("without a web results array");});it("reads the id-matched reply out of an SSE stream that carries a notification first", async () => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";mockExchange(`${sseReply(JSON.stringify({jsonrpc: "2.0",method: "notifications/message",params: {level: "info",data: `Search successful for query: ${QUERY} - 20 web results`,},}),)}${sseReply(JSON.stringify({jsonrpc: "2.0",id: 2,result: {content: [{type: "text",text: JSON.stringify({results: {web: [{url: "https://example.com/sse",title: "SSE",description: DESCRIPTION,},],},}),},],},}),)}`,{ initializeSession: null, toolContentType: "text/event-stream" },);const results = await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(results).toEqual([["SSE", DESCRIPTION, "https://example.com/sse"]]);});});describe("reading the reply", () => {it("parses an application/json reply", async () => {mockExchange(236 unmodified lines});describe("failures", () => {it("throws when the You.com initialize request fails", async () => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";const cancel = vi.fn(async () => undefined);fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 500, unreadBody: { cancel } }),);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("did not answer the initialize request (status 500)");// An unread body keeps undici's socket out of the pool until it is// garbage-collected, so the non-2xx path has to discard it; dropping// that line fails here.expect(cancel).toHaveBeenCalledTimes(1);expect(fetchMock).toHaveBeenCalledTimes(1);});it("throws when the tool call is not 2xx", async () => {const cancel = vi.fn(async () => undefined);fetchMock.mockResolvedValueOnce(17 unmodified linesexpect(cancel).toHaveBeenCalledTimes(1);});it("skips the notification when Parallel opens no session", async () => {mockExchange(documentWith([]), { initializeSession: null });await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);// The session is optional for every provider: with none opened, the tool// call follows initialize directly and carries no session headers.expect(fetchMock).toHaveBeenCalledTimes(2);expect(requestBody(1).method).toBe("tools/call");expect(requestHeaders(1)["Mcp-Session-Id"]).toBeUndefined();});it("throws on a JSON-RPC error and keeps the endpoint's message out of it", async () => {24 unmodified lines// free-form text from a third party and must not travel any further.expect(rejection).toBeInstanceOf(Error);expect((rejection as Error).message).toBe("Every fallback search provider failed (parallel: The fallback search endpoint returned a JSON-RPC error (code -32601))",);expect(String(rejection)).not.toContain("SECRET UPSTREAM TEXT");});26 unmodified lines// carried into the thrown error.expect(rejection).toBeInstanceOf(Error);expect((rejection as Error).message).toBe("Every fallback search provider failed (parallel: The fallback search endpoint returned a JSON-RPC error)",);expect(String(rejection)).not.toContain("SECRET");});40 unmodified lines// A raw SyntaxError quotes the offending body, which would put the// upstream response into the thrown error and then into the log.expect((rejection as Error).message).toBe("Every fallback search provider failed (parallel: The fallback search endpoint sent a reply that is not JSON)",);expect(String(rejection)).not.toContain("<html>");});37 unmodified lines});it("never writes the query, the API key or the response text to the log", async () => {process.env.SEARCH_FALLBACK_PARALLEL_API_KEY = "sk-fallback-key";mockExchange(documentWith([{28 unmodified lines}expect(logLines.length).toBeGreaterThan(0);});it("never writes the You.com query, the API key or the response text to the log", async () => {process.env.SEARCH_FALLBACK_PROVIDERS = "youcom";process.env.SEARCH_FALLBACK_YOUCOM_API_KEY = "youcom-fallback-key";mockExchange(youcomDocumentWith([{url: "https://example.com/private",title: "PRIVATE RESPONSE TITLE",description: "PRIVATE RESPONSE DESCRIPTION",},]),{ initializeSession: null },);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);// The stream the endpoint answers with carries the query inside a// notification before the reply, so this also covers that path: none of// it may reach the log, only the counts do.const output = logLines.join("\n");for (const form of [QUERY,"PRIVATE RESPONSE TITLE","PRIVATE RESPONSE DESCRIPTION","youcom-fallback-key",]) {expect(output).not.toContain(form);}expect(logLines.length).toBeGreaterThan(0);});});// Indexed by name rather than dotted, so each variable is spelled once.const PROVIDERS_VARIABLE = "SEARCH_FALLBACK_PROVIDERS";const PARALLEL_KEY_VARIABLE = "SEARCH_FALLBACK_PARALLEL_API_KEY";const YOUCOM_KEY_VARIABLE = "SEARCH_FALLBACK_YOUCOM_API_KEY";const LEGACY_PROVIDER_VARIABLE = "SEARCH_FALLBACK_PROVIDER";const LEGACY_KEY_VARIABLE = "SEARCH_FALLBACK_API_KEY";function listProviders(value: string | undefined) {if (value === undefined) delete process.env[PROVIDERS_VARIABLE];else process.env[PROVIDERS_VARIABLE] = value;}// Fisher-Yates over the two built-in providers draws once: 0 swaps them,// anything near 1 keeps the table's order.function orderYoucomFirst() {return vi.spyOn(Math, "random").mockReturnValue(0);}function orderParallelFirst() {return vi.spyOn(Math, "random").mockReturnValue(0.99);}function mockYoucom(web: unknown[]) {mockExchange(youcomDocumentWith(web), { initializeSession: null });}function requestUrls(): string[] {return fetchMock.mock.calls.map(([requestUrl]) => String(requestUrl));}function rateLimited(headers: Record<string, string> = {}) {return createMockResponse("", { status: 429, headers });}const SERVED_RESULT = {url: "https://example.com/served",title: "Served",description: DESCRIPTION,};describe("configuration", () => {it("tries every built-in provider when the list is unset", async () => {listProviders(undefined);orderParallelFirst();mockExchange(documentWith([]));mockYoucom([]);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(new Set(requestUrls())).toEqual(new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL]),);});it("tries only the listed providers, trimmed, lowercased and without empty items", async () => {listProviders(" YouCom ,, ");mockYoucom([]);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(requestUrls()).toEqual([YOUCOM_KEYLESS_URL, YOUCOM_KEYLESS_URL]);expect(() => assertSearchFallbackConfiguration()).not.toThrow();});it("throws on an unknown provider name, naming it and the valid ones", async () => {listProviders("parallel, Bing");expect(() => assertSearchFallbackConfiguration()).toThrow("SEARCH_FALLBACK_PROVIDERS has unknown provider names: bing; valid names: parallel, youcom.",);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("unknown provider names: bing");expect(fetchMock).not.toHaveBeenCalled();});it("throws on a list with no names in it", () => {listProviders(",");expect(() => assertSearchFallbackConfiguration()).toThrow("SEARCH_FALLBACK_PROVIDERS lists no provider",);});it("throws when the removed SEARCH_FALLBACK_PROVIDER is set, naming its replacement", () => {process.env[LEGACY_PROVIDER_VARIABLE] = "youcom";expect(() => assertSearchFallbackConfiguration()).toThrow("SEARCH_FALLBACK_PROVIDER is no longer read; set SEARCH_FALLBACK_PROVIDERS instead.",);});it("throws when the removed SEARCH_FALLBACK_API_KEY is set, naming both replacements and not the key", async () => {process.env[LEGACY_KEY_VARIABLE] = "legacy-test-value";const error = (() => {try {assertSearchFallbackConfiguration();} catch (thrown) {return thrown as Error;}})();expect(error?.message).toBe("SEARCH_FALLBACK_API_KEY is no longer read; set SEARCH_FALLBACK_PARALLEL_API_KEY or SEARCH_FALLBACK_YOUCOM_API_KEY instead.",);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("SEARCH_FALLBACK_API_KEY is no longer read");expect(fetchMock).not.toHaveBeenCalled();});it("throws on a key with a control character inside, naming the variable and not the key", async () => {process.env[YOUCOM_KEY_VARIABLE] = "youcom-test\nvalue";expect(() => assertSearchFallbackConfiguration()).toThrow("SEARCH_FALLBACK_YOUCOM_API_KEY contains a control character; set it to the key alone.",);const error = (await fetchFallbackTextResults(QUERY,10,FULL_BUDGET_MS,).catch((thrown: unknown) => thrown)) as Error;expect(error.message).not.toContain("youcom-test");expect(fetchMock).not.toHaveBeenCalled();});it("ignores a removed variable that is set to blank", () => {process.env[LEGACY_PROVIDER_VARIABLE] = " ";process.env[LEGACY_KEY_VARIABLE] = "";expect(() => assertSearchFallbackConfiguration()).not.toThrow();});it("gives each provider its own key, endpoint and Bearer header", async () => {listProviders(undefined);process.env[PARALLEL_KEY_VARIABLE] = "parallel-test-value";orderParallelFirst();mockExchange(documentWith([]));mockYoucom([]);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);// Parallel's three requests carry its key; You.com, with no key of its// own, stays on the keyless profile and is never sent Parallel's.expect(requestUrls()).toEqual([PARALLEL_URL,PARALLEL_URL,PARALLEL_URL,YOUCOM_KEYLESS_URL,YOUCOM_KEYLESS_URL,]);for (const index of [0, 1, 2]) {expect(requestHeaders(index).Authorization).toBe("Bearer parallel-test-value",);}for (const index of [3, 4]) {expect(requestHeaders(index).Authorization).toBeUndefined();}});it("switches You.com to its authenticated endpoint with its own key only", async () => {listProviders(undefined);process.env[YOUCOM_KEY_VARIABLE] = "youcom-test-value";orderYoucomFirst();mockYoucom([]);mockExchange(documentWith([]));await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(requestUrls().slice(0, 2)).toEqual([YOUCOM_AUTHENTICATED_URL,YOUCOM_AUTHENTICATED_URL,]);expect(requestHeaders(0).Authorization).toBe("Bearer youcom-test-value");expect(requestHeaders(2).Authorization).toBeUndefined();});});describe("the cascade", () => {beforeEach(() => {listProviders(undefined);});it("tries the providers in the order the shuffle draws", async () => {const random = orderYoucomFirst();mockYoucom([SERVED_RESULT]);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(random).toHaveBeenCalled();expect(requestUrls()).toEqual([YOUCOM_KEYLESS_URL, YOUCOM_KEYLESS_URL]);fetchMock.mockReset();random.mockReturnValue(0.99);mockExchange(documentWith([{ url: "https://example.com/p", title: "P", excerpts: [EXCERPT] },]),);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(requestUrls()[0]).toBe(PARALLEL_URL);});it("moves on to the next provider when the first throws", async () => {orderParallelFirst();fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 500 }));mockYoucom([SERVED_RESULT]);const results = await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(results).toEqual([["Served", DESCRIPTION, "https://example.com/served"],]);expect(getFallbackProviderStats()).toMatchObject({parallel: { served: 0, empty: 0, failed: 1 },youcom: { served: 1, empty: 0, failed: 0 },});});it("moves on to the next provider when the first answers empty", async () => {orderParallelFirst();mockExchange(documentWith([]));mockYoucom([SERVED_RESULT]);const results = await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(results).toHaveLength(1);expect(getFallbackProviderStats()).toMatchObject({parallel: { served: 0, empty: 1, failed: 0 },youcom: { served: 1, empty: 0, failed: 0 },});});it("stops at the first provider that serves", async () => {orderYoucomFirst();mockYoucom([SERVED_RESULT]);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);expect(requestUrls()).not.toContain(PARALLEL_URL);});it("throws one error naming every provider when all of them fail, without the query", async () => {orderParallelFirst();fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 500 }));fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 503 }));const error = (await fetchFallbackTextResults(QUERY,10,FULL_BUDGET_MS,).catch((thrown: unknown) => thrown)) as Error;expect(error.message).toBe("Every fallback search provider failed (parallel: The fallback search endpoint did not answer the initialize request (status 500); youcom: The fallback search endpoint did not answer the initialize request (status 503))",);expect(error.message).not.toContain(QUERY);});it("returns an empty array when one answered empty and the other failed", async () => {orderParallelFirst();mockExchange(documentWith([]));fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 500 }));await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).resolves.toEqual([]);});it("returns an empty array when one failed and the other answered empty", async () => {orderParallelFirst();fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 500 }));mockYoucom([]);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).resolves.toEqual([]);});it("returns an empty array when every provider answers empty", async () => {orderParallelFirst();mockExchange(documentWith([]));mockYoucom([]);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).resolves.toEqual([]);expect(getFallbackProviderStats()).toMatchObject({parallel: { empty: 1 },youcom: { empty: 1 },});});it("gives each attempt an equal share of what is left of the budget", async () => {vi.useFakeTimers({ toFake: ["Date"] });vi.setSystemTime(1_000_000);orderParallelFirst();const timeoutSpy = vi.spyOn(AbortSignal, "timeout");// The first provider spends a second before it fails, so the second one// gets what is left, not a share computed at the start.fetchMock.mockImplementationOnce(async () => {vi.setSystemTime(1_001_000);throw new Error("Network failure");});mockYoucom([SERVED_RESULT]);await fetchFallbackTextResults(QUERY, 10, 3_000);expect(timeoutSpy.mock.calls).toEqual([[1_500], [2_000]]);});it("splits the module's own cap when the caller offers more", async () => {vi.useFakeTimers({ toFake: ["Date"] });orderParallelFirst();const timeoutSpy = vi.spyOn(AbortSignal, "timeout");mockExchange(documentWith([{ url: "https://example.com/p", title: "P", excerpts: [EXCERPT] },]),);await fetchFallbackTextResults(QUERY, 10, 60_000);expect(timeoutSpy.mock.calls).toEqual([[7_500]]);});it("does not start a provider once the budget is spent", async () => {vi.useFakeTimers({ toFake: ["Date"] });vi.setSystemTime(1_000_000);orderParallelFirst();fetchMock.mockImplementationOnce(async () => {vi.setSystemTime(1_005_000);throw new Error("Network failure");});await expect(fetchFallbackTextResults(QUERY, 10, 3_000)).rejects.toThrow("No fallback search provider served the search (parallel: Network failure; not tried, the time budget ran out: youcom)",);expect(fetchMock).toHaveBeenCalledTimes(1);});});describe("pausing a rate-limited provider", () => {beforeEach(() => {vi.useFakeTimers({ toFake: ["Date"] });// On a whole second, so an HTTP-date Retry-After lands on an exact delta.vi.setSystemTime(Date.UTC(2026, 0, 1, 12, 0, 0));});async function hitRateLimit(headers: Record<string, string> = {}) {fetchMock.mockResolvedValueOnce(rateLimited(headers));await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("rate-limited the request (status 429)");}it("pauses for the seconds Retry-After asks, skips without a request, and tries again after", async () => {await hitRateLimit({ "retry-after": "120" });expect(getFallbackProviderStats().parallel).toMatchObject({failed: 1,rateLimited: 1,pausedForMs: 120_000,});fetchMock.mockClear();vi.setSystemTime(Date.now() + 119_000);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("No fallback search provider could be tried");expect(fetchMock).not.toHaveBeenCalled();expect(getFallbackProviderStats().parallel).toMatchObject({skippedWhilePaused: 1,pausedForMs: 1_000,});vi.setSystemTime(Date.now() + 1_000);mockExchange(documentWith([{ url: "https://example.com/p", title: "P", excerpts: [EXCERPT] },]),);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).resolves.toHaveLength(1);expect(getFallbackProviderStats().parallel.pausedForMs).toBe(0);});it("reads an HTTP-date Retry-After on the tool call", async () => {fetchMock.mockResolvedValueOnce(createMockResponse(INITIALIZE_REPLY, {headers: { "mcp-session-id": SESSION_ID },}),);fetchMock.mockResolvedValueOnce(createMockResponse(NOTIFICATION_ACCEPTED, { status: 202 }),);const cancel = vi.fn(async () => undefined);fetchMock.mockResolvedValueOnce(createMockResponse("", {status: 429,headers: {"retry-after": new Date(Date.now() + 300_000).toUTCString(),},unreadBody: { cancel },}),);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("status 429");expect(cancel).toHaveBeenCalledTimes(1);expect(getFallbackProviderStats().parallel.pausedForMs).toBe(300_000);});it("pauses for a minute when Retry-After is missing or unreadable", async () => {await hitRateLimit();expect(getFallbackProviderStats().parallel.pausedForMs).toBe(60_000);vi.setSystemTime(Date.now() + 60_000);await hitRateLimit({ "retry-after": "soon" });expect(getFallbackProviderStats().parallel.pausedForMs).toBe(60_000);});it("pauses for a minute when Retry-After is a string Date.parse would read as a past date", async () => {for (const value of ["1.5", "-1", "abc 5"]) {await hitRateLimit({ "retry-after": value });expect(getFallbackProviderStats().parallel.pausedForMs).toBe(60_000);vi.setSystemTime(Date.now() + 60_000);}});it("clamps a past HTTP-date and gives an obsolete date format the default", async () => {await hitRateLimit({"retry-after": new Date(Date.now() - 60_000).toUTCString(),});expect(getFallbackProviderStats().parallel.pausedForMs).toBe(1_000);vi.setSystemTime(Date.now() + 1_000);await hitRateLimit({ "retry-after": "Thursday, 01-Jan-26 12:05:00 GMT" });expect(getFallbackProviderStats().parallel.pausedForMs).toBe(60_000);});it("pauses on a 429 to the initialized notification and discards its body", async () => {fetchMock.mockResolvedValueOnce(createMockResponse(INITIALIZE_REPLY, {headers: { "mcp-session-id": SESSION_ID },}),);const cancel = vi.fn(async () => undefined);fetchMock.mockResolvedValueOnce(createMockResponse("", {status: 429,headers: { "retry-after": "45" },unreadBody: { cancel },}),);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("status 429");expect(cancel).toHaveBeenCalledTimes(1);expect(getFallbackProviderStats().parallel).toMatchObject({rateLimited: 1,pausedForMs: 45_000,});});it("skips a provider that a concurrent search paused while this one was waiting", async () => {listProviders(undefined);orderParallelFirst();// Parallel's attempt is still in flight when another search, pinned to// You.com, gets a 429 there and pauses it.fetchMock.mockImplementationOnce(async () => {listProviders("youcom");await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS).catch(() => undefined,);throw new Error("Network failure");});fetchMock.mockResolvedValueOnce(rateLimited({ "retry-after": "3600" }));await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("Every fallback search provider failed (parallel: Network failure)",);expect(fetchMock).toHaveBeenCalledTimes(2);expect(getFallbackProviderStats().youcom).toMatchObject({rateLimited: 1,skippedWhilePaused: 1,pausedForMs: 3_600_000,});});it("never shortens a longer pause that a concurrent search set", async () => {// The first search's request is in flight when a second one gets a 429// asking for an hour; the first then gets its own 429 asking for a second.fetchMock.mockImplementationOnce(async () => {await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS).catch(() => undefined,);return rateLimited({ "retry-after": "1" });});fetchMock.mockResolvedValueOnce(rateLimited({ "retry-after": "3600" }));await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("status 429");expect(getFallbackProviderStats().parallel.pausedForMs).toBe(3_600_000);});it("splits the budget only among the providers that are not paused", async () => {listProviders("youcom");await hitRateLimit();listProviders(undefined);orderParallelFirst();const timeoutSpy = vi.spyOn(AbortSignal, "timeout");mockExchange(documentWith([{ url: "https://example.com/p", title: "P", excerpts: [EXCERPT] },]),);await fetchFallbackTextResults(QUERY, 10, 3_000);expect(timeoutSpy.mock.calls).toEqual([[3_000]]);});it("clamps the pause to an hour at most and a second at least", async () => {await hitRateLimit({ "retry-after": "86400" });expect(getFallbackProviderStats().parallel.pausedForMs).toBe(3_600_000);vi.setSystemTime(Date.now() + 3_600_000);await hitRateLimit({ "retry-after": "0" });expect(getFallbackProviderStats().parallel.pausedForMs).toBe(1_000);});it("skips only the paused provider and goes straight to the next", async () => {listProviders(undefined);orderParallelFirst();fetchMock.mockResolvedValueOnce(rateLimited({ "retry-after": "30" }));mockYoucom([SERVED_RESULT]);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);fetchMock.mockClear();mockYoucom([SERVED_RESULT]);await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).resolves.toHaveLength(1);expect(requestUrls()).toEqual([YOUCOM_KEYLESS_URL, YOUCOM_KEYLESS_URL]);expect(getFallbackProviderStats()).toMatchObject({parallel: { failed: 1, rateLimited: 1, skippedWhilePaused: 1 },youcom: { served: 2 },});});it("does not count a paused provider as skipped once the budget is spent", async () => {listProviders(undefined);const random = orderYoucomFirst();fetchMock.mockResolvedValueOnce(rateLimited({ "retry-after": "600" }));mockExchange(documentWith([{ url: "https://example.com/p", title: "P", excerpts: [EXCERPT] },]),);await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);random.mockReturnValue(0.99);fetchMock.mockImplementationOnce(async () => {vi.setSystemTime(Date.now() + FULL_BUDGET_MS);throw new Error("Network failure");});await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("not tried, the time budget ran out: youcom");expect(getFallbackProviderStats().youcom.skippedWhilePaused).toBe(0);});it("throws without a request when every provider is paused", async () => {listProviders(undefined);orderParallelFirst();fetchMock.mockResolvedValueOnce(rateLimited());fetchMock.mockResolvedValueOnce(rateLimited());await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("Every fallback search provider failed");fetchMock.mockClear();await expect(fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),).rejects.toThrow("No fallback search provider could be tried");expect(fetchMock).not.toHaveBeenCalled();});});describe("getFallbackProviderStats", () => {it("starts every built-in provider at zero", () => {const zero = {served: 0,empty: 0,failed: 0,rateLimited: 0,skippedWhilePaused: 0,pausedForMs: 0,};expect(getFallbackProviderStats()).toEqual({parallel: zero,youcom: zero,});});});
5 unmodified lines67891011121314151617181920212223247 unmodified lines323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182831 unmodified line858687888990918 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591 unmodified line1611621631641651661671681691701711722 unmodified lines17517617717817918018118218318436 unmodified lines22122222322422522622743 unmodified lines27127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631710 unmodified lines3283293303313323333343353363375 unmodified linesconst printMessage = debug(fileName);printMessage.enabled = true;const ENDPOINT_URL = "https://search.parallel.ai/mcp";const MCP_PROTOCOL_VERSION = "2025-06-18";// Bounds the whole three-request exchange, not each request: a fallback that// hangs longer than this keeps the 502 the operator already gets from SearXNG// waiting for a second source that is only there to soften the outage.const FALLBACK_TIMEOUT_MS = 15_000;const MAX_SNIPPET_LENGTH = 400;// Excerpts arrive with navigation crumbs ("Skip to main content", menu items)// that are sentences of their own; a real excerpt paragraph never runs this// short, so length is the cheapest way to drop them without a stoplist.const MIN_SNIPPET_LINE_LENGTH = 40;// One per server process: the endpoint uses it for free-tier rate limiting and// one MiniSearch instance is one client, so a fresh one per request would shed// the rate limit instead of sharing it.const SESSION_ID = randomUUID();7 unmodified lines};}interface FallbackSearchResult {url?: string;title?: string | null;publish_date?: string | null;excerpts?: string[];}interface FallbackSearchDocument {results?: FallbackSearchResult[];}type TextualResult = [title: string, content: string, url: string];/*** Whether the operator opted into the second text-search source. Off unless* `SEARCH_FALLBACK_ENABLED` is `true` or `1`, read at call time so tests can* toggle it.*/export function isSearchFallbackEnabled(): boolean {const value = process.env.SEARCH_FALLBACK_ENABLED?.trim().toLowerCase();return value === "true" || value === "1";}/*** Runs a text search against the fallback endpoint when SearXNG has already* failed, and returns the same `[title, snippet, url]` tuples the SearXNG path* produces, so the caller can rank and render them unchanged.** `timeoutMs` is the time the caller can still afford, measured from its own* start: the exchange is bounded by this and by the module's own cap, whichever* is shorter, so a search that has already spent most of its budget on SearXNG* cannot hang on here past the point where the client has given up.** Throws on any failure rather than returning what it managed to collect: the* caller has to decide between a degraded answer and the 502 it would have sent* anyway, and it has to be able to count the decision. An empty array is the* one non-throwing outcome that means the endpoint answered and nothing usable* came back.*/export async function fetchFallbackTextResults(query: string,limit: number,timeoutMs: number,): Promise<TextualResult[]> {const apiKey = process.env.SEARCH_FALLBACK_API_KEY?.trim();const signal = AbortSignal.timeout(Math.min(FALLBACK_TIMEOUT_MS, timeoutMs));const headers: Record<string, string> = {"Content-Type": "application/json",1 unmodified line...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),};const initializeResponse = await fetch(ENDPOINT_URL, {method: "POST",headers,body: JSON.stringify({8 unmodified lines}),signal,});const sessionId = initializeResponse.headers.get("mcp-session-id");// An unread body keeps undici's socket out of the pool until it is GC'd, so// both outcomes have to discard it before they part ways with the response.await initializeResponse.body?.cancel();if (!initializeResponse.ok || !sessionId) {throw new Error(`The fallback search endpoint did not open a session (status ${initializeResponse.status})`,);}const sessionHeaders = {"Mcp-Session-Id": sessionId,"MCP-Protocol-Version": MCP_PROTOCOL_VERSION,};// A notification, so there is no reply body to read: the session is only// usable once the endpoint has acknowledged it, and `ok` is the whole// acknowledgement.const initializedResponse = await fetch(ENDPOINT_URL, {method: "POST",headers: { ...headers, ...sessionHeaders },body: JSON.stringify({jsonrpc: "2.0",method: "notifications/initialized",}),signal,});await initializedResponse.body?.cancel();if (!initializedResponse.ok) {throw new Error(`The fallback search endpoint rejected the initialized notification (status ${initializedResponse.status})`,);}const callResponse = await fetch(ENDPOINT_URL, {method: "POST",headers: { ...headers, ...sessionHeaders },body: JSON.stringify({jsonrpc: "2.0",id: 2,method: "tools/call",params: {name: "web_search",// No `model_name`: this is a search, not a completion, and the tool// does not need a client that claims to be a model.arguments: {objective: query,search_queries: [query],session_id: SESSION_ID,},},}),signal,});if (!callResponse.ok) {await callResponse.body?.cancel();throw new Error(1 unmodified line);}const document = await readSearchDocument(callResponse, 2);const textualResults = mapResults(document, limit);printMessage(`Fallback search usable text results: ${textualResults.length} of ${document.results?.length ?? 0}.`,);return textualResults;}/**2 unmodified lines* request is decided by the id, not by position: the stream can carry* notifications the client never asked for.*/async function readSearchDocument(response: Response,requestId: number,): Promise<FallbackSearchDocument> {const contentType = response.headers.get("content-type") ?? "";const body = await response.text();36 unmodified linesif (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {throw new Error();}return parsed as FallbackSearchDocument;} catch {throw new Error("The fallback search endpoint returned tool output that is not JSON",43 unmodified lines});}function mapResults(document: FallbackSearchDocument,limit: number,): TextualResult[] {if (!Array.isArray(document.results)) {throw new Error("The fallback search endpoint returned a document without a results array",);}const seenUrls = new Set<string>();const mapped: TextualResult[] = [];for (const result of document.results) {if (mapped.length >= limit) break;// Upstream data, so one malformed entry must not fail the whole search: a// result that is not an object, or whose url or title is not a string, is// skipped rather than left to throw on `.trim()`.if (!result ||typeof result !== "object" ||typeof result.url !== "string" ||!result.url ||seenUrls.has(result.url)) {continue;}const title = typeof result.title === "string" ? result.title.trim() : "";if (!title) continue;const snippet = buildSnippet(result.excerpts);if (!snippet) continue;seenUrls.add(result.url);mapped.push([title, snippet, result.url]);}return mapped;}/*** Turns the endpoint's markdown excerpts into the plain, single-line snippet* the SearXNG path hands to ranking.10 unmodified lines.replace(/\s+/g, " ").trim();if (snippet.length <= MAX_SNIPPET_LENGTH) return snippet;// Cut at a word boundary: a mid-word stump reads as a rendering bug, and the// ellipsis is what tells the reader the sentence was cut, not finished.const cut = snippet.slice(0, MAX_SNIPPET_LENGTH);const lastSpace = cut.lastIndexOf(" ");return `${(lastSpace > 0 ? cut.slice(0, lastSpace) : cut).trimEnd()}โฆ`;5 unmodified lines67891011121314151617181920212223242526272829307 unmodified lines38394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404411 unmodified line4434444454464474484498 unmodified lines4584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145151 unmodified line5175185195205215225235245255265275282 unmodified lines53153253353453553653753853954036 unmodified lines57757857958058158258343 unmodified lines62762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372410 unmodified lines7357367377387397407417427437447457467477487497507515 unmodified linesconst printMessage = debug(fileName);printMessage.enabled = true;const MCP_PROTOCOL_VERSION = "2025-06-18";// Bounds the whole cascade, not each request: a fallback that hangs longer// than this keeps the 502 the operator already gets from SearXNG waiting for// a second source that is only there to soften the outage.const FALLBACK_TIMEOUT_MS = 15_000;const MAX_SNIPPET_LENGTH = 400;// Excerpts arrive with navigation crumbs ("Skip to main content", menu items)// that are sentences of their own; a real excerpt paragraph never runs this// short, so length is the cheapest way to drop them without a stoplist.const MIN_SNIPPET_LINE_LENGTH = 40;// You.com's acceptable use policy can suspend a client that keeps calling// through 429s, so a provider that sends one is left alone for the time it// asks for. A missing or unreadable Retry-After gets a minute, and no answer// may box a provider for longer than an hour or shorter than a second.const DEFAULT_RATE_LIMIT_PAUSE_MS = 60_000;const MAX_RATE_LIMIT_PAUSE_MS = 3_600_000;const MIN_RATE_LIMIT_PAUSE_MS = 1_000;// One per server process: Parallel uses it for free-tier rate limiting and// one MiniSearch instance is one client, so a fresh one per request would shed// the rate limit instead of sharing it.const SESSION_ID = randomUUID();7 unmodified lines};}interface ParallelSearchResult {url?: string;title?: string | null;publish_date?: string | null;excerpts?: string[];}interface ParallelSearchDocument {results?: ParallelSearchResult[];}// You.com's tool output: the web results sit one level deeper, under// `results.web`, and each result carries a plain description plus, when the// query matched the page, query-relevant highlights.interface YoucomWebResult {url?: string;title?: string | null;description?: string | null;contents?: { highlights?: string[] } | null;}interface YoucomSearchDocument {results?: { web?: YoucomWebResult[] };}type TextualResult = [title: string, content: string, url: string];type ProviderName = "parallel" | "youcom";interface MappedResults {results: TextualResult[];received: number;}interface FallbackProvider {name: ProviderName;apiKeyVariable: string;endpointUrl: (apiKey: string) => string;toolCall: (query: string,limit: number,) => { name: string; arguments: Record<string, unknown> };mapResults: (document: object, limit: number) => MappedResults;}const PROVIDERS: readonly FallbackProvider[] = [{name: "parallel",apiKeyVariable: "SEARCH_FALLBACK_PARALLEL_API_KEY",endpointUrl: () => "https://search.parallel.ai/mcp",// No `model_name`: this is a search, not a completion, and the tool does// not need a client that claims to be a model.toolCall: (query) => ({name: "web_search",arguments: {objective: query,search_queries: [query],session_id: SESSION_ID,},}),mapResults: (document, limit) =>mapParallelResults(document as ParallelSearchDocument, limit),},{name: "youcom",apiKeyVariable: "SEARCH_FALLBACK_YOUCOM_API_KEY",// The free profile needs no key at all, and the key, when present,// selects the authenticated endpoint instead.endpointUrl: (apiKey) =>apiKey? "https://api.you.com/mcp": "https://api.you.com/mcp?profile=free",toolCall: (query, limit) => ({name: "you-search",arguments: { query, count: limit },}),mapResults: (document, limit) =>mapYoucomResults(document as YoucomSearchDocument, limit),},];const PROVIDER_NAMES = PROVIDERS.map((provider) => provider.name);// Each removed variable and what replaced it: an operator upgrading with the// old names set would otherwise lose the key without a word and fall back to// the keyless tiers.const REMOVED_VARIABLES: readonly [variable: string, replacement: string][] = [["SEARCH_FALLBACK_PROVIDER", "SEARCH_FALLBACK_PROVIDERS"],["SEARCH_FALLBACK_API_KEY","SEARCH_FALLBACK_PARALLEL_API_KEY or SEARCH_FALLBACK_YOUCOM_API_KEY",],];interface ProviderCounters {served: number;empty: number;failed: number;rateLimited: number;skippedWhilePaused: number;}const providerCounters = new Map<ProviderName, ProviderCounters>(PROVIDER_NAMES.map((name) => [name,{ served: 0, empty: 0, failed: 0, rateLimited: 0, skippedWhilePaused: 0 },]),);const pausedUntil = new Map<ProviderName, number>();class RateLimitedError extends Error {readonly retryAfter: string | null;constructor(retryAfter: string | null) {super("The fallback search endpoint rate-limited the request (status 429)");this.retryAfter = retryAfter;}}/*** Whether the operator opted into the second text-search source. Off unless* `SEARCH_FALLBACK_ENABLED` is `true` or `1`, read at call time so tests can* toggle it.*/export function isSearchFallbackEnabled(): boolean {const value = (process.env.SEARCH_FALLBACK_ENABLED ?? "").trim().toLowerCase();return value === "true" || value === "1";}/*** Checks the fallback configuration and throws on the first thing wrong with* it: a removed variable that is still set, an unknown provider name, a* provider list with no names in it, or a key with a control character in it.* Meant for server start, so a bad value stops the server instead of failing* every search that reaches the fallback.*/export function assertSearchFallbackConfiguration(): void {readConfiguredProviders();}/*** The providers the operator listed in `SEARCH_FALLBACK_PROVIDERS`, or every* built-in provider when it is unset or blank, as a fresh array the caller may* reorder. The listed order carries no meaning, since every call shuffles it.* Read at call time so tests can switch it.*/function readConfiguredProviders(): FallbackProvider[] {const stillSet = REMOVED_VARIABLES.filter(([variable]) => (process.env[variable] ?? "").trim() !== "",);if (stillSet.length > 0) {throw new Error(stillSet.map(([variable, replacement]) =>`${variable} is no longer read; set ${replacement} instead.`,).join(" "),);}// undici quotes an invalid header value in full in its error, so a key with// a line break inside it would reach the log as `Bearer <key>`. Refused// here, by variable name only, so it fails at start instead.const keyWithControlCharacter = PROVIDERS.find(({ apiKeyVariable }) =>// biome-ignore lint/suspicious/noControlCharactersInRegex: matching them is the point./[\u0000-\u001f\u007f]/.test((process.env[apiKeyVariable] ?? "").trim()),);if (keyWithControlCharacter) {throw new Error(`${keyWithControlCharacter.apiKeyVariable} contains a control character; set it to the key alone.`,);}const value = process.env.SEARCH_FALLBACK_PROVIDERS ?? "";if (value.trim() === "") return [...PROVIDERS];const names = value.split(",").map((name) => name.trim().toLowerCase()).filter((name) => name !== "");if (names.length === 0) {throw new Error(`SEARCH_FALLBACK_PROVIDERS lists no provider; valid names: ${PROVIDER_NAMES.join(", ")}.`,);}const unknown = names.filter((name) => !PROVIDER_NAMES.includes(name as ProviderName),);if (unknown.length > 0) {throw new Error(`SEARCH_FALLBACK_PROVIDERS has unknown provider names: ${unknown.join(", ")}; valid names: ${PROVIDER_NAMES.join(", ")}.`,);}return PROVIDERS.filter((provider) => names.includes(provider.name));}/*** Per-provider counters since the last restart, for `/status`, and how much* longer each provider stays paused after a 429 (0 when it is not paused).* `rateLimited` is a subset of `failed`. Provider names are configured* infrastructure rather than anything a search supplied, so they are safe to* publish.*/export function getFallbackProviderStats(): Record<string,ProviderCounters & { pausedForMs: number }> {const now = Date.now();return Object.fromEntries(PROVIDER_NAMES.map((name) => [name,{...(providerCounters.get(name) as ProviderCounters),pausedForMs: Math.max(0, (pausedUntil.get(name) ?? 0) - now),},]),);}/*** Runs a text search against the fallback providers when SearXNG has already* failed, and returns the same `[title, snippet, url]` tuples the SearXNG path* produces, so the caller can rank and render them unchanged.** Every configured provider is a candidate, tried one at a time in a fresh* random order on each call, so the load spreads across them and no single* provider's outage or rate limit decides the outcome. A provider paused by* an earlier 429 is skipped without a request. The first non-empty answer* wins; an empty answer or an error moves on to the next provider.** `timeoutMs` is the time the caller can still afford, measured from its own* start: the cascade is bounded by this and by the module's own cap, whichever* is shorter, and each attempt gets an equal share of what is left, so a* provider that hangs cannot spend the time the next one needs.** Returns an empty array when at least one provider answered and none had* anything usable. Throws when every provider that was tried failed, with* each one's name and error, or when none could be tried at all: the caller* has to decide between a degraded answer and the 502 it would have sent* anyway, and it has to be able to count the decision.*/export async function fetchFallbackTextResults(query: string,limit: number,timeoutMs: number,): Promise<TextualResult[]> {const deadline = Date.now() + Math.min(FALLBACK_TIMEOUT_MS, timeoutMs);const candidates = shuffle(readConfiguredProviders());const failures: string[] = [];const notTried: string[] = [];let answered = false;for (const [index, provider] of candidates.entries()) {const remainingMs = deadline - Date.now();if (remainingMs <= 0) {notTried.push(...candidates.slice(index).map(({ name }) => name));break;}// Checked again before every attempt, not once up front: another search// can pause a provider while this one waits on an earlier attempt, and a// paused provider must not get a new exchange. An exchange already under// way runs to its end, which costs at most two more requests.if (isPaused(provider.name)) {countFor(provider.name).skippedWhilePaused++;printMessage(`Fallback provider ${provider.name} skipped while paused.`);continue;}const eligibleCount = candidates.slice(index).filter((candidate) => !isPaused(candidate.name)).length;const attemptMs = Math.ceil(remainingMs / eligibleCount);try {const results = await searchWithProvider(provider,query,limit,AbortSignal.timeout(attemptMs),);answered = true;if (results.length > 0) {countFor(provider.name).served++;printMessage(`Fallback search served by ${provider.name}.`);return results;}countFor(provider.name).empty++;} catch (error) {const message = error instanceof Error ? error.message : String(error);countFor(provider.name).failed++;if (error instanceof RateLimitedError) {countFor(provider.name).rateLimited++;const pauseMs = rateLimitPauseMs(error.retryAfter);// Never shortens a pause already in place: a concurrent search may// have been told to stay away for longer.pausedUntil.set(provider.name,Math.max(pausedUntil.get(provider.name) ?? 0, Date.now() + pauseMs),);printMessage(`Fallback provider ${provider.name} paused for ${pauseMs} ms after a 429.`,);}printMessage(`Fallback provider ${provider.name} failed: ${message}`);failures.push(`${provider.name}: ${message}`);}}if (answered) return [];if (failures.length > 0) {// A provider the budget ran out before is named as such, so the log does// not read as if it had been asked and failed.throw new Error(notTried.length > 0? `No fallback search provider served the search (${failures.join("; ")}; not tried, the time budget ran out: ${notTried.join(", ")})`: `Every fallback search provider failed (${failures.join("; ")})`,);}throw new Error("No fallback search provider could be tried: all are paused after a rate limit, or the time budget ran out",);}function isPaused(name: ProviderName): boolean {return (pausedUntil.get(name) ?? 0) > Date.now();}function countFor(name: ProviderName): ProviderCounters {return providerCounters.get(name) as ProviderCounters;}function shuffle<Item>(items: Item[]): Item[] {for (let index = items.length - 1; index > 0; index--) {const swapIndex = Math.floor(Math.random() * (index + 1));[items[index], items[swapIndex]] = [items[swapIndex], items[index]];}return items;}// RFC 9110's IMF-fixdate. Date.parse alone is too lenient: V8 turns strings// such as "1.5" or "-1" into dates in 2001, which would clamp to the minimum// pause instead of the default an unreadable value gets. The two obsolete// HTTP-date formats also fall to the default, which is the cautious side.const IMF_FIXDATE =/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/;/*** Reads Retry-After as delta-seconds or an IMF-fixdate HTTP-date, and clamps* the result to the bounds the module allows.*/function rateLimitPauseMs(retryAfter: string | null): number {const value = retryAfter?.trim() ?? "";let pauseMs = DEFAULT_RATE_LIMIT_PAUSE_MS;if (/^\d+$/.test(value)) {pauseMs = Number(value) * 1000;} else if (IMF_FIXDATE.test(value)) {const retryAt = Date.parse(value);if (!Number.isNaN(retryAt)) pauseMs = retryAt - Date.now();}return Math.min(MAX_RATE_LIMIT_PAUSE_MS,Math.max(MIN_RATE_LIMIT_PAUSE_MS, pauseMs),);}/*** Throws the error the cascade pauses a provider on. Checked on every request* of the exchange, since any of them can be the one the limit lands on.*/async function rejectIfRateLimited(response: Response): Promise<void> {if (response.status !== 429) return;await response.body?.cancel();throw new RateLimitedError(response.headers.get("retry-after"));}/*** Runs one provider's MCP exchange: initialize, the initialized notification* when the endpoint opened a session, and the tool call. The session is* optional: with no session id on the initialize reply the endpoint is* stateless, so the notification and the session id are skipped, since there* is no session to acknowledge. The protocol version still goes on every* request after initialize.*/async function searchWithProvider(provider: FallbackProvider,query: string,limit: number,signal: AbortSignal,): Promise<TextualResult[]> {const apiKey = (process.env[provider.apiKeyVariable] ?? "").trim();const endpointUrl = provider.endpointUrl(apiKey);const headers: Record<string, string> = {"Content-Type": "application/json",1 unmodified line...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),};const initializeResponse = await fetch(endpointUrl, {method: "POST",headers,body: JSON.stringify({8 unmodified lines}),signal,});await rejectIfRateLimited(initializeResponse);const sessionId = initializeResponse.headers.get("mcp-session-id");// An unread body keeps undici's socket out of the pool until it is GC'd, so// both outcomes have to discard it before they part ways with the response.await initializeResponse.body?.cancel();if (!initializeResponse.ok) {throw new Error(`The fallback search endpoint did not answer the initialize request (status ${initializeResponse.status})`,);}// The MCP transport spec requires the version header on every request after// initialize, with or without a session; only the session id is optional.const postInitializeHeaders = {"MCP-Protocol-Version": MCP_PROTOCOL_VERSION,...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),};if (sessionId) {// A notification, so there is no reply body to read: the session is only// usable once the endpoint has acknowledged it, and `ok` is the whole// acknowledgement.const initializedResponse = await fetch(endpointUrl, {method: "POST",headers: { ...headers, ...postInitializeHeaders },body: JSON.stringify({jsonrpc: "2.0",method: "notifications/initialized",}),signal,});await rejectIfRateLimited(initializedResponse);await initializedResponse.body?.cancel();if (!initializedResponse.ok) {throw new Error(`The fallback search endpoint rejected the initialized notification (status ${initializedResponse.status})`,);}}const callResponse = await fetch(endpointUrl, {method: "POST",headers: { ...headers, ...postInitializeHeaders },body: JSON.stringify({jsonrpc: "2.0",id: 2,method: "tools/call",params: provider.toolCall(query, limit),}),signal,});await rejectIfRateLimited(callResponse);if (!callResponse.ok) {await callResponse.body?.cancel();throw new Error(1 unmodified line);}const document = await readSearchDocument<object>(callResponse, 2);const { results, received } = provider.mapResults(document, limit);printMessage(`Fallback search usable text results from ${provider.name}: ${results.length} of ${received}.`,);return results;}/**2 unmodified lines* request is decided by the id, not by position: the stream can carry* notifications the client never asked for.*/async function readSearchDocument<SearchDocument>(response: Response,requestId: number,): Promise<SearchDocument> {const contentType = response.headers.get("content-type") ?? "";const body = await response.text();36 unmodified linesif (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {throw new Error();}return parsed as SearchDocument;} catch {throw new Error("The fallback search endpoint returned tool output that is not JSON",43 unmodified lines});}function mapParallelResults(document: ParallelSearchDocument,limit: number,): MappedResults {if (!Array.isArray(document.results)) {throw new Error("The fallback search endpoint returned a document without a results array",);}return {results: mapEntries(document.results, limit, (result) =>buildSnippet(result.excerpts),),received: document.results.length,};}/*** Maps You.com's `results.web` array by the same rules the Parallel path* follows, so the tuples reach ranking and rendering unchanged.*/function mapYoucomResults(document: YoucomSearchDocument,limit: number,): MappedResults {if (!Array.isArray(document.results?.web)) {throw new Error("The fallback search endpoint returned a document without a web results array",);}return {results: mapEntries(document.results.web, limit, buildYoucomSnippet),received: document.results.web.length,};}function mapEntries<Entry extends { url?: string; title?: string | null }>(entries: Entry[],limit: number,snippetOf: (entry: Entry) => string,): TextualResult[] {const seenUrls = new Set<string>();const mapped: TextualResult[] = [];for (const entry of entries) {if (mapped.length >= limit) break;// Upstream data, so one malformed entry must not fail the whole search: a// result that is not an object, or whose url or title is not a string, is// skipped rather than left to throw on `.trim()`.if (!entry ||typeof entry !== "object" ||typeof entry.url !== "string" ||!entry.url ||seenUrls.has(entry.url)) {continue;}const title = typeof entry.title === "string" ? entry.title.trim() : "";if (!title) continue;const snippet = snippetOf(entry);if (!snippet) continue;seenUrls.add(entry.url);mapped.push([title, snippet, entry.url]);}return mapped;}/*** You.com returns a plain description for every result, and, when the query* matched the page, query-relevant highlights as well. The description is the* curated summary, so it is used as-is โ it is not passed through the excerpt* length filter, which would drop a short but complete sentence โ and the* highlights take over only when the description is empty, through the same* filter the Parallel path applies to its excerpts.*/function buildYoucomSnippet(result: YoucomWebResult): string {const description =typeof result.description === "string"? result.description.replace(/\s+/g, " ").trim(): "";if (description) return truncateSnippet(description);return buildSnippet(result.contents?.highlights);}/*** Turns the endpoint's markdown excerpts into the plain, single-line snippet* the SearXNG path hands to ranking.10 unmodified lines.replace(/\s+/g, " ").trim();return truncateSnippet(snippet);}/*** Caps a finished snippet at the length the ranking path expects. Cuts at a* word boundary: a mid-word stump reads as a rendering bug, and the ellipsis* is what tells the reader the sentence was cut, not finished.*/function truncateSnippet(snippet: string): string {if (snippet.length <= MAX_SNIPPET_LENGTH) return snippet;const cut = snippet.slice(0, MAX_SNIPPET_LENGTH);const lastSpace = cut.lastIndexOf(" ");return `${(lastSpace > 0 ? cut.slice(0, lastSpace) : cut).trimEnd()}โฆ`;
1 unmodified line23456723 unmodified lines31323334353658 unmodified lines95969798991001 unmodified lineimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";vi.mock("./fallbackSearchService", () => ({fetchFallbackTextResults: vi.fn(),isSearchFallbackEnabled: vi.fn(),}));23 unmodified lines}));import {fetchFallbackTextResults,isSearchFallbackEnabled,} from "./fallbackSearchService";58 unmodified linesvi.mocked(fetchFallbackTextResults).mockResolvedValue([]);});it("passes through requests that aren't under /search/", async () => {const handler = getRegisteredHandler();const next = vi.fn();1 unmodified line234567823 unmodified lines3233343536373858 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241 unmodified lineimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";vi.mock("./fallbackSearchService", () => ({assertSearchFallbackConfiguration: vi.fn(),fetchFallbackTextResults: vi.fn(),isSearchFallbackEnabled: vi.fn(),}));23 unmodified lines}));import {assertSearchFallbackConfiguration,fetchFallbackTextResults,isSearchFallbackEnabled,} from "./fallbackSearchService";58 unmodified linesvi.mocked(fetchFallbackTextResults).mockResolvedValue([]);});it("checks the fallback configuration at registration only when the fallback is on", () => {getRegisteredHandler();expect(assertSearchFallbackConfiguration).not.toHaveBeenCalled();vi.mocked(isSearchFallbackEnabled).mockReturnValue(true);getRegisteredHandler();expect(assertSearchFallbackConfiguration).toHaveBeenCalledTimes(1);});it("refuses to register when the fallback configuration is invalid", () => {vi.mocked(isSearchFallbackEnabled).mockReturnValue(true);vi.mocked(assertSearchFallbackConfiguration).mockImplementationOnce(() => {throw new Error("SEARCH_FALLBACK_PROVIDERS lists no provider");});// Thrown out of the hook itself, so the server stops at start rather// than answering 502 during the next SearXNG outage.expect(() => getRegisteredHandler()).toThrow("SEARCH_FALLBACK_PROVIDERS lists no provider",);});it("passes through requests that aren't under /search/", async () => {const handler = getRegisteredHandler();const next = vi.fn();
12345693 unmodified lines10010110210310410535 unmodified lines141142143144145146147import type { PreviewServer, ViteDevServer } from "vite";import { z } from "zod";import {fetchFallbackTextResults,isSearchFallbackEnabled,} from "./fallbackSearchService.ts";93 unmodified linesexport function searchEndpointServerHook<T extends ViteDevServer | PreviewServer,>(server: T) {server.middlewares.use(async (request, response, next) => {if (!request.url?.startsWith("/search/")) return next();35 unmodified lines} catch {// SearXNG is unreachable. The operator may have switched on a second// text source, which is consulted only here, after SearXNG has failed,// and never for images: Parallel has no image search.searchResults = null;if (isTextSearch && isSearchFallbackEnabled()) {123456793 unmodified lines10110210310410510610710810911035 unmodified lines146147148149150151152import type { PreviewServer, ViteDevServer } from "vite";import { z } from "zod";import {assertSearchFallbackConfiguration,fetchFallbackTextResults,isSearchFallbackEnabled,} from "./fallbackSearchService.ts";93 unmodified linesexport function searchEndpointServerHook<T extends ViteDevServer | PreviewServer,>(server: T) {// At registration rather than per search: a misconfigured fallback has to// stop the server at start, not surface as a 502 during the next outage.if (isSearchFallbackEnabled()) assertSearchFallbackConfiguration();server.middlewares.use(async (request, response, next) => {if (!request.url?.startsWith("/search/")) return next();35 unmodified lines} catch {// SearXNG is unreachable. The operator may have switched on a second// text source, which is consulted only here, after SearXNG has failed,// and never for images: no fallback provider has image search.searchResults = null;if (isTextSearch && isSearchFallbackEnabled()) {
1234585 unmodified lines919293949596import type { IncomingMessage, ServerResponse } from "node:http";import { describe, expect, it, vi } from "vitest";import {incrementSearchesFailedOnFallback,incrementSearchesServedByFallback,85 unmodified lines);});it("publishes the page-read circuit count beside the outcome counters", async () => {const status = await callStatus();12345685 unmodified lines9293949596979899100101102103104105106107108109110import type { IncomingMessage, ServerResponse } from "node:http";import { describe, expect, it, vi } from "vitest";import { getFallbackProviderStats } from "./fallbackSearchService.ts";import {incrementSearchesFailedOnFallback,incrementSearchesServedByFallback,85 unmodified lines);});it("publishes the per-provider fallback counters under searches", async () => {const status = await callStatus();expect(status.searches).toMatchObject({fallbackProviders: getFallbackProviderStats(),});expect(Object.keys((status.searches as { fallbackProviders: object }).fallbackProviders,),).toEqual(["parallel", "youcom"]);});it("publishes the page-read circuit count beside the outcome counters", async () => {const status = await callStatus();
1 unmodified line23456794 unmodified lines1021031041051061071 unmodified lineimport type { PreviewServer, ViteDevServer } from "vite";import { getAuthorizationStats } from "./authorizationSinceLastRestart.ts";import { getBiEncoderStatus } from "./biEncoderService.ts";import { getInferenceStats } from "./inferencesSinceLastRestart.ts";import { getPageReadCircuitStats } from "./pageReadHostBreaker.ts";import { getPageReadStats } from "./pageReadsSinceLastRestart.ts";94 unmodified lines...getSearchCircuitStats(),degradedSearchTypes: getDegradedSearchTypes(),unresponsiveEngines: getUnresponsiveEngineStats(),},reranker: getRerankingStats(),thumbnails: getThumbnailStats(),1 unmodified line234567894 unmodified lines1031041051061071081091 unmodified lineimport type { PreviewServer, ViteDevServer } from "vite";import { getAuthorizationStats } from "./authorizationSinceLastRestart.ts";import { getBiEncoderStatus } from "./biEncoderService.ts";import { getFallbackProviderStats } from "./fallbackSearchService.ts";import { getInferenceStats } from "./inferencesSinceLastRestart.ts";import { getPageReadCircuitStats } from "./pageReadHostBreaker.ts";import { getPageReadStats } from "./pageReadsSinceLastRestart.ts";94 unmodified lines...getSearchCircuitStats(),degradedSearchTypes: getDegradedSearchTypes(),unresponsiveEngines: getUnresponsiveEngineStats(),fallbackProviders: getFallbackProviderStats(),},reranker: getRerankingStats(),thumbnails: getThumbnailStats(),
server/fallbackSearchService.test.ts+1076-39
server/fallbackSearchService.ts+491-77
server/searchEndpointServerHook.test.ts+24
server/searchEndpointServerHook.ts+6-1
server/statusEndpointServerHook.test.ts+14
server/statusEndpointServerHook.ts+2