Spaces:
Running
Running
Download server/biEncoderService.ts from Felladrin/MiniSearch: direct link, hf CLI and curl.
- Browser
- Download file 5.63 kB
-
https://huggingface.co/spaces/Felladrin/MiniSearch/resolve/main/server/biEncoderService.ts
- Command line
-
hf download hf://spaces/Felladrin/MiniSearch/server/biEncoderService.ts
-
curl -L -o biEncoderService.ts https://huggingface.co/spaces/Felladrin/MiniSearch/resolve/main/server/biEncoderService.ts
5.63 kB
| /** | |
| * The main thread's side of the bi-encoder. It owns no model and runs no | |
| * inference: it spawns `biEncoderWorker.ts`, forwards scoring requests to it | |
| * and matches the replies back to their callers. | |
| * | |
| * Inference stays off the main thread because a scoring pass run inline stops | |
| * the event loop: a 200-passage pool blocks it for ~815 ms, against under 20 ms | |
| * through the worker (see docs/page-content.md). | |
| */ | |
| import path from "node:path"; | |
| import { Worker } from "node:worker_threads"; | |
| import type { | |
| BiEncoderRequest, | |
| BiEncoderResponse, | |
| } from "./biEncoderWorkerProtocol.ts"; | |
| import { createModelLogger } from "./utils/onnxModelLoader.ts"; | |
| const printMessage = createModelLogger(path.basename(import.meta.url)); | |
| let worker: Worker | null = null; | |
| let isReady = false; | |
| let nextRequestId = 0; | |
| /** | |
| * How long a scoring request may wait for the worker before it is answered | |
| * with empty scores, so a worker that is alive but stuck degrades ranking to | |
| * lexical instead of holding every page-content read. Sized from the budget | |
| * the client already enforces: its 20 s `/page-content` abort, minus the 6 s | |
| * page-read deadline, minus margin for the rest of the request. | |
| */ | |
| export const SCORE_TIMEOUT_MS = 10_000; | |
| interface PendingScore { | |
| resolve: (scores: number[]) => void; | |
| timer: ReturnType<typeof setTimeout>; | |
| } | |
| const pendingScores = new Map<number, PendingScore>(); | |
| /** | |
| * Answers every in-flight request with empty scores. Empty is the signal | |
| * `pageContentService` already reads as "dense scoring is unavailable, rank | |
| * lexically", so a worker that dies degrades the ranking instead of leaving | |
| * page-content reads waiting for a reply that is never coming. | |
| */ | |
| function resolvePendingEmpty() { | |
| for (const { resolve, timer } of pendingScores.values()) { | |
| clearTimeout(timer); | |
| resolve([]); | |
| } | |
| pendingScores.clear(); | |
| } | |
| /** | |
| * Drops a worker that died. Guarded on identity because a terminated worker's | |
| * `exit` still arrives after `startBiEncoderService` has installed its | |
| * replacement, and that late event must not mark the new one dead. | |
| */ | |
| function forgetWorker(deadWorker: Worker) { | |
| if (worker !== deadWorker) return; | |
| worker = null; | |
| isReady = false; | |
| resolvePendingEmpty(); | |
| } | |
| export async function startBiEncoderService() { | |
| if (worker) await stopBiEncoderService(); | |
| const biEncoderWorker = new Worker( | |
| new URL("./biEncoderWorker.ts", import.meta.url), | |
| ); | |
| worker = biEncoderWorker; | |
| biEncoderWorker.on("message", (message: BiEncoderResponse) => { | |
| if (message.type === "ready") return; | |
| const pending = pendingScores.get(message.id); | |
| if (!pending) return; | |
| pendingScores.delete(message.id); | |
| clearTimeout(pending.timer); | |
| const { resolve } = pending; | |
| if (message.type === "failed") { | |
| printMessage(`Bi-encoder scoring failed: ${message.message}`); | |
| resolve([]); | |
| return; | |
| } | |
| resolve(message.scores); | |
| }); | |
| biEncoderWorker.on("error", (error: Error) => { | |
| printMessage(`Bi-encoder worker failed: ${error.message}`); | |
| forgetWorker(biEncoderWorker); | |
| }); | |
| biEncoderWorker.on("exit", () => forgetWorker(biEncoderWorker)); | |
| await new Promise<void>((resolve, reject) => { | |
| const stopListening = () => { | |
| biEncoderWorker.off("message", onMessage); | |
| biEncoderWorker.off("error", onError); | |
| biEncoderWorker.off("exit", onExit); | |
| }; | |
| const onMessage = (message: BiEncoderResponse) => { | |
| if (message.type !== "ready") return; | |
| stopListening(); | |
| resolve(); | |
| }; | |
| const onError = (error: Error) => { | |
| stopListening(); | |
| reject(error); | |
| }; | |
| const onExit = (code: number) => { | |
| stopListening(); | |
| reject( | |
| new Error( | |
| `The bi-encoder worker exited with code ${code} before it was ready`, | |
| ), | |
| ); | |
| }; | |
| biEncoderWorker.on("message", onMessage); | |
| biEncoderWorker.on("error", onError); | |
| biEncoderWorker.on("exit", onExit); | |
| }); | |
| isReady = true; | |
| printMessage("Bi-encoder service ready!"); | |
| } | |
| export async function stopBiEncoderService() { | |
| const runningWorker = worker; | |
| isReady = false; | |
| worker = null; | |
| resolvePendingEmpty(); | |
| await runningWorker?.terminate(); | |
| } | |
| export async function getBiEncoderStatus() { | |
| return isReady; | |
| } | |
| export async function scorePassages( | |
| query: string, | |
| passages: string[], | |
| ): Promise<number[]> { | |
| const runningWorker = worker; | |
| if (!runningWorker || !isReady || passages.length === 0) { | |
| return []; | |
| } | |
| // Ids are per-process and monotonic because the service can have several | |
| // scoring passes in flight at once: two concurrent page-content reads each | |
| // send their own request, and the replies can come back in either order. | |
| const id = nextRequestId++; | |
| return new Promise<number[]>((resolve) => { | |
| // A late reply after the timeout finds no entry and is ignored. | |
| const timer = setTimeout(() => { | |
| pendingScores.delete(id); | |
| printMessage( | |
| `Bi-encoder scoring did not answer within ${SCORE_TIMEOUT_MS} ms; falling back to lexical ranking.`, | |
| ); | |
| resolve([]); | |
| }, SCORE_TIMEOUT_MS); | |
| timer.unref(); | |
| pendingScores.set(id, { resolve, timer }); | |
| const request: BiEncoderRequest = { type: "score", id, query, passages }; | |
| try { | |
| runningWorker.postMessage(request); | |
| } catch (error) { | |
| // The worker was terminated between the check above and this send. | |
| pendingScores.delete(id); | |
| clearTimeout(timer); | |
| printMessage( | |
| `Could not reach the bi-encoder worker: ${error instanceof Error ? error.message : String(error)}`, | |
| ); | |
| resolve([]); | |
| } | |
| }); | |
| } | |