@240xu/dsh-websearch 2.8.8 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -28
- package/lib/backends/anthropic-like.js +12 -8
- package/lib/backends/brave.js +8 -4
- package/lib/backends/ddg.js +27 -11
- package/lib/backends/exa.js +5 -2
- package/lib/backends/firecrawl.js +129 -0
- package/lib/backends/mojeek.js +5 -3
- package/lib/backends/openai.js +12 -7
- package/lib/backends/parallel.js +2 -20
- package/lib/backends/searxng.js +36 -8
- package/lib/backends/serper.js +8 -4
- package/lib/backends/tavily.js +5 -3
- package/lib/backends/tinyfish.js +124 -0
- package/lib/breaker.js +25 -4
- package/lib/cache.js +41 -7
- package/lib/client.js +634 -188
- package/lib/health.js +21 -17
- package/lib/history.js +26 -36
- package/lib/index.js +163 -63
- package/lib/prompting.js +18 -6
- package/lib/provider.js +364 -97
- package/lib/rrf.js +9 -4
- package/lib/settings-api.js +48 -30
- package/lib/trust.js +7 -1
- package/lib/util/base-url.js +56 -0
- package/lib/util/egress-fetch.js +197 -18
- package/lib/util/failure-label.js +73 -12
- package/lib/util/log.js +5 -3
- package/lib/util/mcp-client.js +89 -40
- package/lib/util/namespace.js +28 -0
- package/lib/util/rank.js +22 -3
- package/lib/util/redact.js +49 -0
- package/lib/util/web-error.js +49 -0
- package/package.json +2 -2
package/lib/backends/parallel.js
CHANGED
|
@@ -48,7 +48,8 @@ export const parallelBackend = {
|
|
|
48
48
|
|
|
49
49
|
let result;
|
|
50
50
|
try {
|
|
51
|
-
|
|
51
|
+
// The official provider sends a bare tools/call with no session handshake.
|
|
52
|
+
result = await mcpCall(PARALLEL_ENDPOINT, PARALLEL_TOOL, args, {}, signal, { skipInitialize: true });
|
|
52
53
|
} catch (err) {
|
|
53
54
|
if (err instanceof WebError) throw err;
|
|
54
55
|
throw new WebError(
|
|
@@ -59,32 +60,13 @@ export const parallelBackend = {
|
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
if (result?.isError === true) {
|
|
62
|
-
|
|
63
|
-
|
|
64
63
|
const message = String(result.content?.[0]?.text ?? "unknown");
|
|
65
|
-
|
|
66
|
-
|
|
67
64
|
hooks.recordOutcome?.({ status: "error", message });
|
|
68
|
-
|
|
69
|
-
|
|
70
65
|
throw new WebError(`parallel returned an MCP error: ${message}`, "WEB_PROVIDER_ERROR");
|
|
71
|
-
|
|
72
|
-
|
|
73
66
|
}
|
|
74
67
|
|
|
75
|
-
|
|
76
68
|
const sources = parseParallelResult(result, request.maxResults ?? 8);
|
|
77
|
-
|
|
78
|
-
|
|
79
69
|
hooks.recordOutcome?.({ status: "ok", count: sources.length });
|
|
80
|
-
|
|
81
|
-
if (result?.isError === true) {
|
|
82
|
-
throw new WebError(
|
|
83
|
-
`parallel returned an MCP error: ${String(result.content?.[0]?.text ?? "unknown")}`,
|
|
84
|
-
"WEB_PROVIDER_ERROR",
|
|
85
|
-
);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
70
|
return { sources, content: undefined, truncated: false };
|
|
89
71
|
},
|
|
90
72
|
};
|
package/lib/backends/searxng.js
CHANGED
|
@@ -13,10 +13,12 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
16
|
+
import { webErrorFromResponse } from "../util/web-error.js";
|
|
16
17
|
import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
|
|
17
18
|
import { applySearxngFilters, normalizeFilters, safeSearchParams } from "../util/filters.js";
|
|
18
19
|
import { egressFetch } from "../util/egress-fetch.js";
|
|
19
20
|
import { describeError } from "../util/describe-error.js";
|
|
21
|
+
import { invalidBaseURL } from "../util/base-url.js";
|
|
20
22
|
|
|
21
23
|
const DEFAULT_SEARXNG_URL = "https://searx.be";
|
|
22
24
|
|
|
@@ -62,6 +64,14 @@ export const searxngBackend = {
|
|
|
62
64
|
const trimmed = typeof candidate === "string" ? candidate.trim() : "";
|
|
63
65
|
if (trimmed !== "" && !candidates.includes(trimmed)) candidates.push(trimmed);
|
|
64
66
|
}
|
|
67
|
+
// Every candidate receives the configured API key, so every candidate
|
|
68
|
+
// passes the same trust gate as baseURL. This is checked here (not only in
|
|
69
|
+
// the provider) because searxngBaseURLs was the unvalidated path and the
|
|
70
|
+
// backend is also usable directly by embedders.
|
|
71
|
+
const invalid = candidates.map((c) => invalidBaseURL(c)).find((reason) => reason !== undefined);
|
|
72
|
+
if (invalid !== undefined) {
|
|
73
|
+
throw new WebError("SearXNG: invalid instance URL (" + invalid + ")", "WEB_PROVIDER_ERROR");
|
|
74
|
+
}
|
|
65
75
|
|
|
66
76
|
// Single instance (the default): legacy path, unchanged semantics.
|
|
67
77
|
if (candidates.length === 1) {
|
|
@@ -75,11 +85,26 @@ export const searxngBackend = {
|
|
|
75
85
|
const fresh = candidates.filter((u) => (instanceCooldowns.get(u) ?? 0) <= now);
|
|
76
86
|
const order = fresh.length > 0 ? fresh : candidates; // all cooled -> fail-open
|
|
77
87
|
let lastErr = null;
|
|
78
|
-
|
|
88
|
+
// A quota/rate-limit answer is the most actionable failure: it carries
|
|
89
|
+
// Retry-After and drives the breaker's quota cooldown. Taking whichever
|
|
90
|
+
// instance failed LAST would discard it whenever a later instance failed
|
|
91
|
+
// on plain network grounds.
|
|
92
|
+
const severity = (err) => (err?.code === "RATE_LIMIT" || err?.code === "QUOTA" || err?.rateLimited === true ? 2 : 1);
|
|
93
|
+
// Each instance attempt must fit inside what is left of the backend budget:
|
|
94
|
+
// three public instances at 4.5s each would otherwise need 13.5s while the
|
|
95
|
+
// provider abandons the backend at 8s, and the per-instance detail is lost
|
|
96
|
+
// to a generic "timed out after 8000ms".
|
|
97
|
+
const budgetMs = Number(backendOpts?.backendTimeoutMs);
|
|
98
|
+
const deadline = Number.isFinite(budgetMs) && budgetMs > 0 ? Date.now() + budgetMs : Infinity;
|
|
99
|
+
for (const [index, candidate] of order.entries()) {
|
|
79
100
|
throwIfSearchAborted(signal);
|
|
101
|
+
const remaining = deadline - Date.now();
|
|
102
|
+
if (remaining <= 0) break;
|
|
103
|
+
const share = remaining / Math.max(1, order.length - index);
|
|
104
|
+
const attemptMs = Math.max(1000, Math.min(INSTANCE_ATTEMPT_TIMEOUT_MS, share));
|
|
80
105
|
const attemptController = new AbortController();
|
|
81
106
|
const attemptSignal = signal ? AbortSignal.any([signal, attemptController.signal]) : attemptController.signal;
|
|
82
|
-
const timer = setTimeout(() => attemptController.abort(),
|
|
107
|
+
const timer = setTimeout(() => attemptController.abort(), attemptMs);
|
|
83
108
|
try {
|
|
84
109
|
const sources = await queryInstance(candidate, request, attemptSignal, backendOpts, apiKey, hooks);
|
|
85
110
|
instanceCooldowns.delete(candidate);
|
|
@@ -88,23 +113,26 @@ export const searxngBackend = {
|
|
|
88
113
|
if (signal?.aborted === true) throw searchAborted(signal, error);
|
|
89
114
|
instanceCooldowns.set(candidate, Date.now() + INSTANCE_COOLDOWN_MS);
|
|
90
115
|
if (attemptController.signal.aborted && !(signal && signal.aborted)) {
|
|
91
|
-
|
|
92
|
-
`SearXNG instance attempt timed out after ${
|
|
116
|
+
const timedOutErr = new WebError(
|
|
117
|
+
`SearXNG instance attempt timed out after ${attemptMs}ms (${candidate})`,
|
|
93
118
|
"WEB_PROVIDER_ERROR",
|
|
94
119
|
{ cause: error instanceof Error ? error : undefined },
|
|
95
120
|
);
|
|
121
|
+
if (lastErr === null || severity(timedOutErr) > severity(lastErr)) lastErr = timedOutErr;
|
|
96
122
|
} else if (error instanceof WebError && error.code !== "WEB_ABORTED") {
|
|
97
|
-
lastErr = error;
|
|
123
|
+
if (lastErr === null || severity(error) > severity(lastErr)) lastErr = error;
|
|
98
124
|
} else {
|
|
99
|
-
|
|
125
|
+
const netErr = new WebError(
|
|
100
126
|
"SearXNG instance failed (" + candidate + "): " + describeError(error),
|
|
101
127
|
"WEB_PROVIDER_ERROR",
|
|
102
128
|
{ cause: error instanceof Error ? error : undefined },
|
|
103
129
|
);
|
|
130
|
+
if (lastErr === null || severity(netErr) > severity(lastErr)) lastErr = netErr;
|
|
104
131
|
}
|
|
105
132
|
} finally {
|
|
106
133
|
clearTimeout(timer);
|
|
107
134
|
}
|
|
135
|
+
|
|
108
136
|
}
|
|
109
137
|
throw lastErr ?? new WebError("SearXNG: no instance available (all cooling down)", "WEB_PROVIDER_ERROR");
|
|
110
138
|
},
|
|
@@ -163,9 +191,9 @@ async function queryInstance(baseURL, request, signal, backendOpts, apiKey, hook
|
|
|
163
191
|
const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
|
|
164
192
|
hooks?.recordOutcome?.({ status: "error", message: "HTTP " + response.status + ": " + text });
|
|
165
193
|
if (response.status === 429 || response.status >= 500) {
|
|
166
|
-
throw
|
|
194
|
+
throw webErrorFromResponse(response, text + " (instance struggling? point searxngBaseURL at another public instance)", "SearXNG");
|
|
167
195
|
}
|
|
168
|
-
throw
|
|
196
|
+
throw webErrorFromResponse(response, text, "SearXNG");
|
|
169
197
|
}
|
|
170
198
|
|
|
171
199
|
// 200 does not mean JSON (route3: searx.be 200 + HTML anti-bot page). Read
|
package/lib/backends/serper.js
CHANGED
|
@@ -6,9 +6,11 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
9
|
+
import { webErrorFromResponse } from "../util/web-error.js";
|
|
9
10
|
import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
|
|
10
11
|
import { applySerperFilters, normalizeFilters } from "../util/filters.js";
|
|
11
12
|
import { egressFetch } from "../util/egress-fetch.js";
|
|
13
|
+
import { describeError } from "../util/describe-error.js";
|
|
12
14
|
|
|
13
15
|
const SERPER_ENDPOINT = "https://google.serper.dev/search";
|
|
14
16
|
|
|
@@ -27,7 +29,7 @@ export const serperBackend = {
|
|
|
27
29
|
|
|
28
30
|
const apiKey = await backendOpts.resolveApiKey?.();
|
|
29
31
|
if (!apiKey) {
|
|
30
|
-
throw new WebError("Serper: API key not configured", "
|
|
32
|
+
throw new WebError("Serper: API key not configured", "WEB_PROVIDER_CREDENTIAL_MISSING");
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
const baseURL = backendOpts.baseURL ?? SERPER_ENDPOINT;
|
|
@@ -62,13 +64,13 @@ export const serperBackend = {
|
|
|
62
64
|
});
|
|
63
65
|
} catch (error) {
|
|
64
66
|
if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
|
|
65
|
-
throw new WebError("Serper request failed: " + error, "WEB_PROVIDER_ERROR", { cause: error });
|
|
67
|
+
throw new WebError("Serper request failed: " + describeError(error), "WEB_PROVIDER_ERROR", { cause: error });
|
|
66
68
|
}
|
|
67
69
|
|
|
68
70
|
if (!response.ok) {
|
|
69
71
|
const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
|
|
70
72
|
hooks?.recordOutcome?.({ status: "error", message: "HTTP " + response.status + ": " + text });
|
|
71
|
-
throw
|
|
73
|
+
throw webErrorFromResponse(response, text, "Serper");
|
|
72
74
|
}
|
|
73
75
|
|
|
74
76
|
let data;
|
|
@@ -112,7 +114,9 @@ export function parseSerperResult(data, maxResults) {
|
|
|
112
114
|
url: item.link,
|
|
113
115
|
...(item.title ? { title: item.title } : {}),
|
|
114
116
|
...(item.snippet ? { snippet: item.snippet.slice(0, 500) } : {}),
|
|
115
|
-
|
|
117
|
+
// `date` is often relative ("2 days ago"); only ISO-shaped values are
|
|
118
|
+
// valid for the seam's ISO-8601 publishedAt.
|
|
119
|
+
...(typeof item.date === "string" && /^\d{4}-\d{2}-\d{2}/.test(item.date) ? { publishedAt: item.date } : {}),
|
|
116
120
|
});
|
|
117
121
|
}
|
|
118
122
|
|
package/lib/backends/tavily.js
CHANGED
|
@@ -6,9 +6,11 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { WebError } from "@deepseek-ai/dsh-web";
|
|
9
|
+
import { webErrorFromResponse } from "../util/web-error.js";
|
|
9
10
|
import { throwIfSearchAborted, searchAborted, isAbortError } from "../util/abort.js";
|
|
10
11
|
import { applyTavilyFilters, normalizeFilters } from "../util/filters.js";
|
|
11
12
|
import { egressFetch } from "../util/egress-fetch.js";
|
|
13
|
+
import { describeError } from "../util/describe-error.js";
|
|
12
14
|
|
|
13
15
|
const TAVILY_ENDPOINT = "https://api.tavily.com/search";
|
|
14
16
|
|
|
@@ -27,7 +29,7 @@ export const tavilyBackend = {
|
|
|
27
29
|
|
|
28
30
|
const apiKey = await backendOpts.resolveApiKey?.();
|
|
29
31
|
if (!apiKey) {
|
|
30
|
-
throw new WebError("Tavily: API key not configured", "
|
|
32
|
+
throw new WebError("Tavily: API key not configured", "WEB_PROVIDER_CREDENTIAL_MISSING");
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
const baseURL = backendOpts.baseURL ?? TAVILY_ENDPOINT;
|
|
@@ -71,13 +73,13 @@ export const tavilyBackend = {
|
|
|
71
73
|
});
|
|
72
74
|
} catch (error) {
|
|
73
75
|
if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
|
|
74
|
-
throw new WebError(`Tavily request failed: ${error}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
76
|
+
throw new WebError(`Tavily request failed: ${describeError(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
|
|
75
77
|
}
|
|
76
78
|
|
|
77
79
|
if (!response.ok) {
|
|
78
80
|
const text = await response.text().catch(() => "").then((tx) => tx.slice(0, 300));
|
|
79
81
|
hooks?.recordOutcome?.({ status: "error", message: `HTTP ${response.status}: ${text}` });
|
|
80
|
-
throw
|
|
82
|
+
throw webErrorFromResponse(response, text, "Tavily");
|
|
81
83
|
}
|
|
82
84
|
|
|
83
85
|
let data;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// tinyfish.js — TinyFish search backend (streamable-http MCP).
|
|
2
|
+
//
|
|
3
|
+
// Aligned with the OpenCode v2 websearch provider:
|
|
4
|
+
// https://github.com/anomalyco/opencode/blob/v2.2.5/packages/core/src/plugin/websearch/tinyfish.ts
|
|
5
|
+
// The hosted keyless tier needs no credential; an optional API key activates
|
|
6
|
+
// the session handshake and raises limits.
|
|
7
|
+
// Endpoint: https://agent.tinyfish.ai/mcp
|
|
8
|
+
// - keyless: header `X-TinyFish-Access-Mode: keyless`, NO initialize /
|
|
9
|
+
// Mcp-Session-Id handshake. TinyFish v2.2.5 source comment:
|
|
10
|
+
// "Keyed requests are rejected without the Mcp-Session-Id returned by
|
|
11
|
+
// initialize; keyless ones are not."
|
|
12
|
+
// - keyed: header `X-API-Key: <key>` plus the normal 3-step handshake
|
|
13
|
+
// (mcpCall default). Our mcpCall() gained `options.skipInitialize` to
|
|
14
|
+
// express exactly this split without regressing exa/parallel.
|
|
15
|
+
//
|
|
16
|
+
// Keyless limits observed via tools/list: 30 requests/min, 50 searches/UTC
|
|
17
|
+
// day (search only: web + news). The REST pricing page uses different numbers
|
|
18
|
+
// (TinySearch 30 req/min, 500/hour) — that is a different ingress, do not
|
|
19
|
+
// conflate the two. See 05-search-backends.md appendix A.3.
|
|
20
|
+
//
|
|
21
|
+
// Response envelope: content[0].text is a JSON string of
|
|
22
|
+
// { results: [{ url, title, snippet }] }.
|
|
23
|
+
//
|
|
24
|
+
// Registration is opt-in (DEFAULT_ENABLED does not contain this id).
|
|
25
|
+
|
|
26
|
+
import { mcpCall } from "../util/mcp-client.js";
|
|
27
|
+
import { WebError } from "@deepseek-ai/dsh-web";
|
|
28
|
+
|
|
29
|
+
const TINYFISH_ENDPOINT = "https://agent.tinyfish.ai/mcp";
|
|
30
|
+
const TINYFISH_TOOL = "search";
|
|
31
|
+
|
|
32
|
+
export const tinyfishBackend = {
|
|
33
|
+
id: "tinyfish",
|
|
34
|
+
requiresCredential: false,
|
|
35
|
+
|
|
36
|
+
available() {
|
|
37
|
+
// Keyless mode needs no credential.
|
|
38
|
+
return true;
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
async search(request, signal, options, hooks = {}) {
|
|
42
|
+
const args = { query: request.query };
|
|
43
|
+
// resolveOptions() supplies an async resolveApiKey() closure. A literal
|
|
44
|
+
// apiKey is accepted for stubs; a failed resolution degrades to keyless.
|
|
45
|
+
let apiKey = typeof options?.apiKey === "string" ? options.apiKey : "";
|
|
46
|
+
if (!apiKey && typeof options?.resolveApiKey === "function") {
|
|
47
|
+
try { apiKey = (await options.resolveApiKey()) ?? ""; } catch { apiKey = ""; }
|
|
48
|
+
}
|
|
49
|
+
const keyed = apiKey.length > 0;
|
|
50
|
+
|
|
51
|
+
const extraHeaders = keyed
|
|
52
|
+
? { "X-API-Key": apiKey }
|
|
53
|
+
: { "X-TinyFish-Access-Mode": "keyless" };
|
|
54
|
+
// Use the configured baseURL so the provider trust gate and sidecar path apply.
|
|
55
|
+
const endpoint = typeof options?.baseURL === "string" && options.baseURL.length > 0
|
|
56
|
+
? options.baseURL : TINYFISH_ENDPOINT;
|
|
57
|
+
|
|
58
|
+
// Never record the key itself.
|
|
59
|
+
hooks.recordRequest?.({
|
|
60
|
+
endpoint,
|
|
61
|
+
toolName: TINYFISH_TOOL,
|
|
62
|
+
body: args,
|
|
63
|
+
headers: {},
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
let result;
|
|
67
|
+
try {
|
|
68
|
+
result = await mcpCall(
|
|
69
|
+
endpoint,
|
|
70
|
+
TINYFISH_TOOL,
|
|
71
|
+
args,
|
|
72
|
+
extraHeaders,
|
|
73
|
+
signal,
|
|
74
|
+
// Keyless is stateless: skip initialize. Keyed uses the handshake
|
|
75
|
+
// once; the session cache is keyed by URL *and* X-API-Key, so a
|
|
76
|
+
// rotated credential cannot reuse the previous Mcp-Session-Id, and a
|
|
77
|
+
// server-side expiry still triggers the 401/403/404 retry.
|
|
78
|
+
{ skipInitialize: !keyed },
|
|
79
|
+
);
|
|
80
|
+
} catch (err) {
|
|
81
|
+
if (err instanceof WebError) throw err;
|
|
82
|
+
throw new WebError(
|
|
83
|
+
`tinyfish search failed: ${String(err?.message ?? err)}`,
|
|
84
|
+
"WEB_PROVIDER_ERROR",
|
|
85
|
+
{ cause: err },
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (result?.isError === true) {
|
|
90
|
+
const message = String(result.content?.[0]?.text ?? "unknown");
|
|
91
|
+
hooks.recordOutcome?.({ status: "error", message });
|
|
92
|
+
throw new WebError(`tinyfish returned an MCP error: ${message}`, "WEB_PROVIDER_ERROR");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const sources = parseTinyfishResult(result, request.maxResults ?? 8);
|
|
96
|
+
hooks.recordOutcome?.({ status: "ok", count: sources.length });
|
|
97
|
+
return { sources, content: undefined, truncated: false };
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** Parse the JSON string embedded in content[0].text into DSH sources. */
|
|
102
|
+
export function parseTinyfishResult(result, maxResults) {
|
|
103
|
+
const text = result?.content?.[0]?.text;
|
|
104
|
+
if (typeof text !== "string" || text.length === 0) return [];
|
|
105
|
+
let parsed;
|
|
106
|
+
try {
|
|
107
|
+
parsed = JSON.parse(text);
|
|
108
|
+
} catch {
|
|
109
|
+
return [];
|
|
110
|
+
}
|
|
111
|
+
if (!Array.isArray(parsed?.results)) return [];
|
|
112
|
+
const sources = [];
|
|
113
|
+
for (const item of parsed.results) {
|
|
114
|
+
if (typeof item?.url !== "string" || item.url.length === 0) continue;
|
|
115
|
+
const source = { url: item.url };
|
|
116
|
+
if (typeof item.title === "string" && item.title.length > 0) source.title = item.title;
|
|
117
|
+
if (typeof item.snippet === "string" && item.snippet.length > 0) source.snippet = item.snippet;
|
|
118
|
+
sources.push(source);
|
|
119
|
+
if (sources.length >= maxResults) break;
|
|
120
|
+
}
|
|
121
|
+
return sources;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export default tinyfishBackend;
|
package/lib/breaker.js
CHANGED
|
@@ -24,9 +24,11 @@ export const BREAKER_DEFAULTS = {
|
|
|
24
24
|
* @param {boolean} ok did this call succeed?
|
|
25
25
|
* @param {number} nowMs
|
|
26
26
|
* @param {{threshold?: number, cooldownMs?: number}} cfg
|
|
27
|
+
* @param {{rateLimited?: boolean, retryAfterMs?: number}} [opts] - a quota
|
|
28
|
+
* failure cools the backend immediately instead of waiting for threshold.
|
|
27
29
|
* @returns {{ failCount: number, cooledUntil: number }}
|
|
28
30
|
*/
|
|
29
|
-
export function foldBreaker(prev, ok, nowMs, cfg = {}) {
|
|
31
|
+
export function foldBreaker(prev, ok, nowMs, cfg = {}, opts = {}) {
|
|
30
32
|
const threshold = Math.max(1, Math.floor(Number(cfg.threshold) || BREAKER_DEFAULTS.threshold));
|
|
31
33
|
// cooldownMs === 0 explicitly disables the cooldown window (cooledUntil = now
|
|
32
34
|
// expires instantly). Only null/undefined falls back to the default — an
|
|
@@ -35,13 +37,32 @@ export function foldBreaker(prev, ok, nowMs, cfg = {}) {
|
|
|
35
37
|
? Math.max(0, Math.floor(Number(cfg.cooldownMs) || 0))
|
|
36
38
|
: BREAKER_DEFAULTS.cooldownMs;
|
|
37
39
|
if (ok) return { failCount: 0, cooledUntil: 0 };
|
|
38
|
-
|
|
40
|
+
// A cooldown window that has already expired starts a fresh failure streak;
|
|
41
|
+
// otherwise failCount grows monotonically across unrelated outages.
|
|
42
|
+
// cooledUntil === 0 means "never opened", so the streak still accumulates.
|
|
43
|
+
const hadOpenWindow = Number.isFinite(prev?.cooledUntil) && prev.cooledUntil > 0;
|
|
44
|
+
const expired = hadOpenWindow && prev.cooledUntil <= nowMs;
|
|
45
|
+
const baseCount = Number.isFinite(prev?.failCount) ? prev.failCount : 0;
|
|
46
|
+
const failCount = expired ? 1 : baseCount + 1;
|
|
47
|
+
const prevCooledUntil = expired ? 0 : (Number.isFinite(prev?.cooledUntil) ? prev.cooledUntil : 0);
|
|
48
|
+
// A rate-limit/quota response should not be retried twice more just to
|
|
49
|
+
// reach the failure threshold; cool immediately for the retry window.
|
|
50
|
+
if (opts.rateLimited === true) {
|
|
51
|
+
// A quota answer carries its own Retry-After; without one, fall back to
|
|
52
|
+
// the configured cooldown. A zero here means "count only", matching the
|
|
53
|
+
// threshold path above.
|
|
54
|
+
const retryAfterMs = Number.isFinite(opts.retryAfterMs) ? opts.retryAfterMs : cooldownMs;
|
|
55
|
+
return { failCount, cooledUntil: retryAfterMs > 0 ? nowMs + retryAfterMs : 0 };
|
|
56
|
+
}
|
|
39
57
|
if (failCount >= threshold) {
|
|
40
|
-
|
|
58
|
+
// cooldownMs === 0 means "count only, never cool": writing a window of
|
|
59
|
+
// zero length would immediately look expired and reset the streak, so the
|
|
60
|
+
// threshold could never be reached again.
|
|
61
|
+
return { failCount, cooledUntil: cooldownMs > 0 ? nowMs + cooldownMs : 0 };
|
|
41
62
|
}
|
|
42
63
|
// Keep an existing open window if the backend was already open (failure
|
|
43
64
|
// while open extends nothing, but must not silently close it).
|
|
44
|
-
return { failCount, cooledUntil:
|
|
65
|
+
return { failCount, cooledUntil: prevCooledUntil };
|
|
45
66
|
}
|
|
46
67
|
|
|
47
68
|
/**
|
package/lib/cache.js
CHANGED
|
@@ -29,18 +29,27 @@ export const CACHE_DEFAULTS = {
|
|
|
29
29
|
|
|
30
30
|
/**
|
|
31
31
|
* Compute the deterministic cache key for a search.
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
32
|
+
* The key covers the shaped query, filters, the effective maxResults, the
|
|
33
|
+
* enabledBackends set (sorted), the cache mode, and every non-function result
|
|
34
|
+
* option: switching the backend mix or editing a result-affecting setting
|
|
35
|
+
* must never serve a stale result within the TTL (arch-review P1-1).
|
|
36
|
+
* Pure function; exported for tests and host reuse.
|
|
35
37
|
*/
|
|
36
|
-
export function cacheKeyFor({ query, filters, maxResults, backends, mode }) {
|
|
38
|
+
export function cacheKeyFor({ query, filters, maxResults, backends, mode, resultOptions }) {
|
|
37
39
|
const backendSet = Array.isArray(backends) ? [...backends].sort().join(",") : "";
|
|
40
|
+
let shaped = {};
|
|
41
|
+
if (resultOptions && typeof resultOptions === "object") {
|
|
42
|
+
const keys = Object.keys(resultOptions).filter((k) =>
|
|
43
|
+
typeof resultOptions[k] !== "function" && !k.startsWith("resolve"));
|
|
44
|
+
for (const k of keys.sort()) shaped[k] = resultOptions[k] ?? null;
|
|
45
|
+
}
|
|
38
46
|
const canonical = JSON.stringify({
|
|
39
47
|
q: typeof query === "string" ? query : "",
|
|
40
48
|
f: filters ?? {},
|
|
41
49
|
n: Number(maxResults) || 0,
|
|
42
50
|
b: backendSet,
|
|
43
51
|
m: typeof mode === "string" ? mode : "",
|
|
52
|
+
o: shaped,
|
|
44
53
|
});
|
|
45
54
|
return createHash("sha256").update(canonical).digest("hex").slice(0, 32);
|
|
46
55
|
}
|
|
@@ -77,8 +86,14 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
|
|
|
77
86
|
*/
|
|
78
87
|
function atomicWrite(file, data) {
|
|
79
88
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
80
|
-
|
|
81
|
-
|
|
89
|
+
try {
|
|
90
|
+
writeFileSync(tmp, data, "utf8");
|
|
91
|
+
renameSync(tmp, file);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
// A failed rename must not leave an orphan tmp counted outside the cap.
|
|
94
|
+
try { unlinkSync(tmp); } catch { /* already gone */ }
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
82
97
|
}
|
|
83
98
|
|
|
84
99
|
/** List current entries as [{key, file, mtime}] sorted oldest first. */
|
|
@@ -97,9 +112,26 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
|
|
|
97
112
|
return out.sort((a, b) => a.mtime - b.mtime);
|
|
98
113
|
}
|
|
99
114
|
|
|
115
|
+
/** Count entry names without stat()ing them (the common, under-cap path). */
|
|
116
|
+
function countEntries() {
|
|
117
|
+
if (!existsSync(dir)) return 0;
|
|
118
|
+
let n = 0;
|
|
119
|
+
for (const name of readdirSync(dir)) {
|
|
120
|
+
if (name.endsWith(".json") && !name.includes(".tmp")) n += 1;
|
|
121
|
+
}
|
|
122
|
+
return n;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// maxEntries is a hard bound. Checking it costs one readdir of names; only
|
|
126
|
+
// an over-cap write pays the stat() of every entry. Trimming to a low-water
|
|
127
|
+
// mark (10%, at least one) keeps that scan amortized over ~cap/10 writes
|
|
128
|
+
// instead of running synchronously on every single write.
|
|
100
129
|
function evict() {
|
|
130
|
+
if (countEntries() <= cap) return;
|
|
101
131
|
const entries = listEntries();
|
|
102
|
-
|
|
132
|
+
const lowWater = Math.max(1, cap - Math.max(1, Math.ceil(cap * 0.1)));
|
|
133
|
+
const remove = entries.length - lowWater;
|
|
134
|
+
for (let i = 0; i < remove; i++) {
|
|
103
135
|
try { unlinkSync(entries[i].file); } catch { /* raced */ }
|
|
104
136
|
}
|
|
105
137
|
}
|
|
@@ -123,6 +155,8 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
|
|
|
123
155
|
}
|
|
124
156
|
return { value: record.value, age };
|
|
125
157
|
} catch {
|
|
158
|
+
// A corrupt/unreadable entry is re-parsed on every get; drop it.
|
|
159
|
+
try { unlinkSync(fileFor(key)); } catch { /* raced */ }
|
|
126
160
|
return null;
|
|
127
161
|
}
|
|
128
162
|
},
|