Spaces:
Running
Running
Sync from felladrin/MiniSearch@c75b7b9
Browse filesFiles changed (7)
78 unmodified lines798081828384853 unmodified lines89909192939478 unmodified lines/usr/local/searxng/searxng-venv/bin/pip install --no-build-isolation -e . && \/usr/local/searxng/searxng-venv/bin/pip uninstall -y wheel setuptools && \/usr/local/searxng/searxng-venv/bin/pip uninstall -y pip && \/usr/local/searxng/searxng-venv/bin/python -c "import searx.webapp"# The runtime never pip-installs, and pip itself vendors flagged copies of# msgpack and setuptools (`pip/_vendor/vendor.txt`) that no released pip3 unmodified lines# the `import searx.webapp` build check above proves the package imports# after the removal. The editable install finder is plain importlib.# Create the app directory while still root and hand it to the app user:# the legacy (non-BuildKit) builder creates WORKDIR directories as root even# under USER, which then breaks `npm ci`'s mkdir of node_modules.78 unmodified lines79808182838485863 unmodified lines9091929394959697989910010110210310478 unmodified lines/usr/local/searxng/searxng-venv/bin/pip install --no-build-isolation -e . && \/usr/local/searxng/searxng-venv/bin/pip uninstall -y wheel setuptools && \/usr/local/searxng/searxng-venv/bin/pip uninstall -y pip && \/usr/local/searxng/searxng-venv/bin/python -c "import searx.webapp" && \rm -f /tmp/sxng_cache_*# The runtime never pip-installs, and pip itself vendors flagged copies of# msgpack and setuptools (`pip/_vendor/vendor.txt`) that no released pip3 unmodified lines# the `import searx.webapp` build check above proves the package imports# after the removal. The editable install finder is plain importlib.# That same import also creates SearXNG's SQLite caches in the temp directory,# owned by root because the build runs as root. The container runs as `node`,# and SearXNG wipes and rebuilds those caches whenever `server.secret_key`# differs from the one written above, so shipping them makes an instance with# its own key die at startup with `attempt to write a readonly database`, with# no search and a container that still reports healthy (#2732). Clearing them# lets the running user create its own on first start; the `-shm` and `-wal`# sidecars go with them, or SQLite fails on those instead.# Create the app directory while still root and hand it to the app user:# the legacy (non-BuildKit) builder creates WORKDIR directories as root even# under USER, which then breaks `npm ci`'s mkdir of node_modules.
63 unmodified lines64656667686963 unmodified linesawait expect(getConfig()).rejects.toThrow("Network error");});it("retries after a failure instead of caching it", async () => {const { getConfig } = await importConfigModule();mockFetch.mockRejectedValueOnce(new Error("Network error"));63 unmodified lines64656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811963 unmodified linesawait expect(getConfig()).rejects.toThrow("Network error");});// The search token is per-process, so a restart leaves this page holding one// the server never issued; invalidating is how a loaded page gets the new one.it("refetches after the cache is invalidated", async () => {const { getConfig, invalidateConfig } = await importConfigModule();mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(serverConfig),});await getConfig();const rotatedConfig = { ...serverConfig, searchToken: "b".repeat(64) };mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(rotatedConfig),});invalidateConfig();await expect(getConfig()).resolves.toEqual(rotatedConfig);expect(mockFetch).toHaveBeenCalledTimes(2);});// Otherwise the discarded response lands in the cache a moment after the// invalidation, and the page goes back to hashing the token it just dropped.it("does not let a fetch started before the invalidation repopulate the cache", async () => {const { getConfig, invalidateConfig } = await importConfigModule();let resolveFirstFetch: (config: ServerConfig) => void = () => {};mockFetch.mockReturnValueOnce(new Promise((resolve) => {resolveFirstFetch = (config) =>resolve({ ok: true, json: vi.fn().mockResolvedValue(config) });}),);const firstCall = getConfig();invalidateConfig();resolveFirstFetch(serverConfig);await expect(firstCall).resolves.toEqual(serverConfig);const rotatedConfig = { ...serverConfig, searchToken: "b".repeat(64) };mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(rotatedConfig),});await expect(getConfig()).resolves.toEqual(rotatedConfig);expect(mockFetch).toHaveBeenCalledTimes(2);});it("retries after a failure instead of caching it", async () => {const { getConfig } = await importConfigModule();mockFetch.mockRejectedValueOnce(new Error("Network error"));
37 unmodified lines38394041424319 unmodified lines63646566676869707172737475761 unmodified line78798037 unmodified lineslet cachedConfig: ServerConfig | null = null;let pendingFetch: Promise<ServerConfig> | null = null;async function fetchConfig(): Promise<ServerConfig> {const response = await fetch("/api/config", {19 unmodified linesif (cachedConfig) return cachedConfig;if (!pendingFetch) {pendingFetch = fetchConfig().then((config) => {cachedConfig = config;pendingFetch = null;return config;},(error) => {pendingFetch = null;throw error;},);1 unmodified linereturn pendingFetch;}37 unmodified lines3839404142434419 unmodified lines64656667686970717273747576777879801 unmodified line82838485868788899091929394959697989910010110210337 unmodified lineslet cachedConfig: ServerConfig | null = null;let pendingFetch: Promise<ServerConfig> | null = null;let configGeneration = 0;async function fetchConfig(): Promise<ServerConfig> {const response = await fetch("/api/config", {19 unmodified linesif (cachedConfig) return cachedConfig;if (!pendingFetch) {const generation = configGeneration;pendingFetch = fetchConfig().then((config) => {if (generation === configGeneration) {cachedConfig = config;pendingFetch = null;}return config;},(error) => {if (generation === configGeneration) pendingFetch = null;throw error;},);1 unmodified linereturn pendingFetch;}/*** Drops the cached config so the next `getConfig` call goes back to* /api/config.** Each server process mints its own search token, so a restart leaves an open* page holding a token the server never issued. The 401 handler in* `search.ts` calls this before asking for the token again, which is the only* way a page that is already loaded can find out the token rotated.** A fetch that is already in flight was started against the values this call* discards, so it is left to resolve its own callers without repopulating the* cache behind them.*/export function invalidateConfig(): void {cachedConfig = null;pendingFetch = null;configGeneration += 1;}
1234567891011249 unmodified lines261262263264265266import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { addLogEntry } from "./logEntries";import * as searchModule from "./search";vi.mock("./logEntries", () => ({addLogEntry: vi.fn(),}));vi.mock("./searchTokenHash", () => ({getSearchTokenHash: vi.fn().mockResolvedValue("mock-token-hash"),}));249 unmodified lines});});describe("Update Cache Config Function", () => {it.each([["ttl", 60000],1234567891011121314151617249 unmodified lines267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { invalidateConfig } from "./config";import { addLogEntry } from "./logEntries";import * as searchModule from "./search";import { getSearchTokenHash } from "./searchTokenHash";vi.mock("./logEntries", () => ({addLogEntry: vi.fn(),}));vi.mock("./config", () => ({invalidateConfig: vi.fn(),}));vi.mock("./searchTokenHash", () => ({getSearchTokenHash: vi.fn().mockResolvedValue("mock-token-hash"),}));249 unmodified lines});});// A restart, a second instance or a dev-server reload mints a new search// token, and a tab opened before that keeps hashing the old one. These pin// the recovery: the page takes the token the server is handing out now and// tries again, once.describe("Search Token Rotation", () => {beforeEach(() => {vi.clearAllMocks();mockFetch.mockReset();});afterEach(() => {// The token mock is module-level, so the queued one-shot values have to// go back to the shared default for the describe blocks that follow.vi.mocked(getSearchTokenHash).mockReset();vi.mocked(getSearchTokenHash).mockResolvedValue("mock-token-hash");});it("refetches the config and retries once when the token is rejected", async () => {const mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];vi.mocked(getSearchTokenHash).mockResolvedValueOnce("stale-token-hash").mockResolvedValueOnce("fresh-token-hash");mockFetch.mockResolvedValueOnce({ ok: false, status: 401 }).mockResolvedValueOnce({ok: true,json: vi.fn().mockResolvedValue(mockResults),});await expect(searchModule.searchServiceInstance.performSearch<string[][]>("text","test query",),).resolves.toEqual(mockResults);expect(invalidateConfig).toHaveBeenCalledTimes(1);expect(mockFetch).toHaveBeenCalledTimes(2);expect(mockFetch.mock.calls[0][0] as string).toContain("token=stale-token-hash",);expect(mockFetch.mock.calls[1][0] as string).toContain("token=fresh-token-hash",);});it("reports a second rejection instead of retrying again", async () => {mockFetch.mockResolvedValue({ ok: false, status: 401 });await expect(searchModule.searchServiceInstance.performSearch<string[][]>("text","test query",),).rejects.toThrow("HTTP error! status: 401");expect(mockFetch).toHaveBeenCalledTimes(2);expect(invalidateConfig).toHaveBeenCalledTimes(1);});it("leaves the token alone when the request fails for another reason", async () => {mockFetch.mockResolvedValue({ ok: false, status: 500 });await expect(searchModule.searchServiceInstance.performSearch<string[][]>("text","test query",),).rejects.toThrow("HTTP error! status: 500");expect(mockFetch).toHaveBeenCalledTimes(1);expect(invalidateConfig).not.toHaveBeenCalled();});});describe("Update Cache Config Function", () => {it.each([["ttl", 60000],
12345182 unmodified lines188189190191192193208 unmodified lines4024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334346 unmodified lines441442443444445446447448import Dexie, { type Table } from "dexie";import { sha256 } from "hash-wasm";import { addLogEntry } from "./logEntries";import { getSearchTokenHash } from "./searchTokenHash";import type { ImageSearchResults, TextSearchResults } from "./types";182 unmodified lines}}interface SearchCacheEntry {key: string;timestamp: number;208 unmodified lines);}const searchUrl = new URL(`/search/${endpoint}`, self.location.origin);searchUrl.searchParams.set("q", query);searchUrl.searchParams.set("token", await getSearchTokenHash());if (limit) searchUrl.searchParams.set("limit", limit.toString());const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(),CACHE_CONFIG.REQUEST_TIMEOUT,);try {const response = await fetch(searchUrl.toString(), {signal: controller.signal,});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}try {return await response.json();} catch (parseError) {throw new Error(`JSON parsing error: ${parseError instanceof Error ? parseError.message : String(parseError)}`,);}} catch (error) {if (error instanceof Error) {if (error.name === "AbortError") {6 unmodified lines}}throw error;} finally {clearTimeout(timeoutId);}},123456182 unmodified lines189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245208 unmodified lines4544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834846 unmodified lines491492493494495496import Dexie, { type Table } from "dexie";import { sha256 } from "hash-wasm";import { invalidateConfig } from "./config";import { addLogEntry } from "./logEntries";import { getSearchTokenHash } from "./searchTokenHash";import type { ImageSearchResults, TextSearchResults } from "./types";182 unmodified lines}}/** The status the server answers a search with when the token is not its own. */const UNAUTHORIZED_STATUS = 401;type SearchAttempt<T> =| { ok: true; results: T }| { ok: false; status: number };async function buildSearchUrl(endpoint: "text" | "images",query: string,limit?: number,): Promise<URL> {const searchUrl = new URL(`/search/${endpoint}`, self.location.origin);searchUrl.searchParams.set("q", query);searchUrl.searchParams.set("token", await getSearchTokenHash());if (limit) searchUrl.searchParams.set("limit", limit.toString());return searchUrl;}/*** One request, with the timeout covering the body as well as the response, so* a server that answers and then stalls mid-stream still aborts.*/async function attemptSearch<T>(searchUrl: URL): Promise<SearchAttempt<T>> {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(),CACHE_CONFIG.REQUEST_TIMEOUT,);try {const response = await fetch(searchUrl.toString(), {signal: controller.signal,});if (!response.ok) {return { ok: false, status: response.status };}try {return { ok: true, results: (await response.json()) as T };} catch (parseError) {throw new Error(`JSON parsing error: ${parseError instanceof Error ? parseError.message : String(parseError)}`,);}} finally {clearTimeout(timeoutId);}}interface SearchCacheEntry {key: string;timestamp: number;208 unmodified lines);}try {let attempt = await attemptSearch<T>(await buildSearchUrl(endpoint, query, limit),);// Every server process mints its own search token, so a restart leaves// this page hashing one the server never issued. Drop the cached config,// take the token the server is handing out now, and try once more. The// retry runs once per request: a second rejection is a real one, and is// reported as the failure it is.if (!attempt.ok && attempt.status === UNAUTHORIZED_STATUS) {addLogEntry("Search token was rejected; refreshing it and retrying the search",);invalidateConfig();attempt = await attemptSearch<T>(await buildSearchUrl(endpoint, query, limit),);}if (!attempt.ok) {throw new Error(`HTTP error! status: ${attempt.status}`);}return attempt.results;} catch (error) {if (error instanceof Error) {if (error.name === "AbortError") {6 unmodified lines}}throw error;}},
303 unmodified lines3043053063073083093108 unmodified lines319320321322323324325326327328329330331332333334335336303 unmodified lines```bashdocker run -p 7860:7860 \-e SEARXNG_SETTINGS_PATH=/etc/searxng-custom/settings.yml \-e TMPDIR=/home/node \-v "$(pwd)/my-searxng-settings.yml:/etc/searxng-custom/settings.yml:ro" \ghcr.io/felladrin/minisearch```8 unmodified lines- "7860:7860"environment:- SEARXNG_SETTINGS_PATH=/etc/searxng-custom/settings.yml- TMPDIR=/home/nodevolumes:- ./my-searxng-settings.yml:/etc/searxng-custom/settings.yml:ro```Three things about that command are required, not optional:- **The file must be readable by uid 1000.** The container runs as `node`, and a file readable only by its owner on the host is invisible to it.- **`secret_key` must be set to your own random value.** SearXNG refuses to start on the `ultrasecretkey` placeholder and logs `server.secret_key is not changed. Please use something else instead of ultrasecretkey.` The image's own file never carries the placeholder, because the Dockerfile replaces it at build time, but a file you write has to carry a real key.- **`TMPDIR` must point somewhere `node` can write.** SearXNG keeps its SQLite caches in its temp directory, and the published image ships those files owned by root. Changing `secret_key` makes SearXNG wipe and rebuild them at startup, which fails against a root-owned file: `sqlite3.OperationalError: attempt to write a readonly database`. The app server keeps answering through that failure, so it reads as a broken MiniSearch rather than as a settings problem, and every search returns 502. The wipe follows from your key differing from the one baked into the image, so copying that value out of `/etc/searxng/settings.yml` avoids it, but that means carrying a build-time secret in your own file and redoing it on every image update. This is a property of the current image, tracked in #2732; once the image stops shipping root-owned caches the requirement goes away.The traceback above will not show in `docker logs`. The container's CMD sends SearXNG's output to `/dev/null`, deliberately, so that the app server's log stays clean. To see it, run SearXNG in the foreground inside the container, which is only possible once the original has failed: on a running instance the second process collides with the live one on `127.0.0.1:8888` and reports the address as already in use.```bashdocker exec <container> sh -c 'cd /usr/local/searxng/searxng-src && /usr/local/searxng/searxng-venv/bin/python -m searx.webapp'303 unmodified lines3043053063073083098 unmodified lines318319320321322323324325326327328329330331332333303 unmodified lines```bashdocker run -p 7860:7860 \-e SEARXNG_SETTINGS_PATH=/etc/searxng-custom/settings.yml \-v "$(pwd)/my-searxng-settings.yml:/etc/searxng-custom/settings.yml:ro" \ghcr.io/felladrin/minisearch```8 unmodified lines- "7860:7860"environment:- SEARXNG_SETTINGS_PATH=/etc/searxng-custom/settings.ymlvolumes:- ./my-searxng-settings.yml:/etc/searxng-custom/settings.yml:ro```Two things about that command are required, not optional:- **The file must be readable by uid 1000.** The container runs as `node`, and a file readable only by its owner on the host is invisible to it.- **`secret_key` must be set to your own random value.** SearXNG refuses to start on the `ultrasecretkey` placeholder and logs `server.secret_key is not changed. Please use something else instead of ultrasecretkey.` The image's own file never carries the placeholder, because the Dockerfile replaces it at build time, but a file you write has to carry a real key.A SearXNG startup failure will not show in `docker logs`. The container's CMD sends SearXNG's output to `/dev/null`, deliberately, so that the app server's log stays clean. To see it, run SearXNG in the foreground inside the container, which is only possible once the original has failed: on a running instance the second process collides with the live one on `127.0.0.1:8888` and reports the address as already in use.```bashdocker exec <container> sh -c 'cd /usr/local/searxng/searxng-src && /usr/local/searxng/searxng-venv/bin/python -m searx.webapp'
99 unmodified lines10010110210310410599 unmodified linesor a scoring error also keeps lexical ranking. Errors log a fixed diagnosticwithout query, URL, passage text or model error details.The limit bounds inference work, not elapsed time. On an Apple M2 Pro CPU,ONNX Runtime 1.30.0 took 7.42β7.48 seconds for 256 passages, 15.07β15.20 secondsfor 512, and 22.37β22.94 seconds for 768, with two warm runs per pool using99 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212399 unmodified linesor a scoring error also keeps lexical ranking. Errors log a fixed diagnosticwithout query, URL, passage text or model error details.Dense scoring runs in a worker thread (`server/biEncoderWorker.ts`), not onthe server's main thread. `onnxruntime-node` runs inference synchronously onwhichever JS thread calls it, so the pass used to stop the event loop for itswhole duration and no other request could be served while one page-content readranked its passages. `biEncoderService.ts` keeps its four functions and nowonly ships the query and the passages across, and takes `number[]` scores back;the model and the embeddings stay in the worker. On this host (x86_64, 32logical cores) a 200-passage pass blocked the main thread for 815 ms before themove and 1.5 ms after, for identical scores.The worker caps ONNX Runtime's intra-op threads at half the reportedparallelism. The default sizes that pool from the logical core count and itsthreads spin before yielding, which oversubscribes every core: the same passmeasured 31-38 ms of main-thread delay and 7.1 s of wall time at the defaultagainst 1-4 ms and 2.6 s when capped. The cross-encoder is untouched and stillruns on the main thread, where it keeps its block to about 13 ms by refusing tobatch.The limit bounds inference work, not elapsed time. On an Apple M2 Pro CPU,ONNX Runtime 1.30.0 took 7.42β7.48 seconds for 256 passages, 15.07β15.20 secondsfor 512, and 22.37β22.94 seconds for 768, with two warm runs per pool using
Dockerfile+11-1
client/modules/config.test.ts+50
client/modules/config.ts+26-3
client/modules/search.test.ts+83
client/modules/search.ts+72-24
docs/configuration.md+2-5
docs/page-content.md+18