tuxevil-rotator 3.0.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/CHANGELOG.md +773 -0
- package/LICENSE +21 -0
- package/README.md +341 -0
- package/bin/pi-antigravity-rotator.js +27 -0
- package/bin/tuxevil-rotator.js +5 -0
- package/package.json +63 -0
- package/src/account-store.ts +542 -0
- package/src/admin-auth.ts +126 -0
- package/src/body-limit.ts +52 -0
- package/src/cli.ts +293 -0
- package/src/compat/cache.ts +38 -0
- package/src/compat/model-specs.ts +82 -0
- package/src/compat/schema-sanitizer.ts +284 -0
- package/src/compat.ts +2357 -0
- package/src/compression/index.ts +92 -0
- package/src/compression/lite.ts +210 -0
- package/src/compression/preservation.ts +183 -0
- package/src/compression/rtk/command-detector.ts +170 -0
- package/src/compression/rtk/deduplicator.ts +39 -0
- package/src/compression/rtk/filter-loader.ts +84 -0
- package/src/compression/rtk/filter-types.ts +25 -0
- package/src/compression/rtk/filters/aws.json +34 -0
- package/src/compression/rtk/filters/biome.json +35 -0
- package/src/compression/rtk/filters/build-eslint.json +37 -0
- package/src/compression/rtk/filters/build-typescript.json +33 -0
- package/src/compression/rtk/filters/build-vite.json +41 -0
- package/src/compression/rtk/filters/build-webpack.json +34 -0
- package/src/compression/rtk/filters/bundle-install.json +35 -0
- package/src/compression/rtk/filters/composer.json +81 -0
- package/src/compression/rtk/filters/curl.json +34 -0
- package/src/compression/rtk/filters/df.json +34 -0
- package/src/compression/rtk/filters/docker-build.json +78 -0
- package/src/compression/rtk/filters/docker-logs.json +42 -0
- package/src/compression/rtk/filters/docker-ps.json +33 -0
- package/src/compression/rtk/filters/dotnet.json +47 -0
- package/src/compression/rtk/filters/du.json +33 -0
- package/src/compression/rtk/filters/error-stacktrace.json +41 -0
- package/src/compression/rtk/filters/gcloud.json +34 -0
- package/src/compression/rtk/filters/generic-output.json +32 -0
- package/src/compression/rtk/filters/gh.json +98 -0
- package/src/compression/rtk/filters/git-branch.json +45 -0
- package/src/compression/rtk/filters/git-diff.json +33 -0
- package/src/compression/rtk/filters/git-log.json +33 -0
- package/src/compression/rtk/filters/git-status.json +40 -0
- package/src/compression/rtk/filters/golangci-lint.json +34 -0
- package/src/compression/rtk/filters/gradle.json +47 -0
- package/src/compression/rtk/filters/json-output.json +40 -0
- package/src/compression/rtk/filters/kubectl.json +99 -0
- package/src/compression/rtk/filters/make.json +38 -0
- package/src/compression/rtk/filters/mypy.json +34 -0
- package/src/compression/rtk/filters/npm-audit.json +43 -0
- package/src/compression/rtk/filters/npm-install.json +41 -0
- package/src/compression/rtk/filters/nx.json +34 -0
- package/src/compression/rtk/filters/pip.json +41 -0
- package/src/compression/rtk/filters/playwright.json +42 -0
- package/src/compression/rtk/filters/poetry-install.json +35 -0
- package/src/compression/rtk/filters/prettier.json +40 -0
- package/src/compression/rtk/filters/ps.json +34 -0
- package/src/compression/rtk/filters/rsync.json +33 -0
- package/src/compression/rtk/filters/rubocop.json +34 -0
- package/src/compression/rtk/filters/ruff.json +40 -0
- package/src/compression/rtk/filters/shell-find.json +33 -0
- package/src/compression/rtk/filters/shell-grep.json +37 -0
- package/src/compression/rtk/filters/shell-ls.json +33 -0
- package/src/compression/rtk/filters/ssh.json +43 -0
- package/src/compression/rtk/filters/systemctl-status.json +43 -0
- package/src/compression/rtk/filters/terraform-plan.json +34 -0
- package/src/compression/rtk/filters/test-cargo.json +42 -0
- package/src/compression/rtk/filters/test-go.json +41 -0
- package/src/compression/rtk/filters/test-jest.json +43 -0
- package/src/compression/rtk/filters/test-pytest.json +41 -0
- package/src/compression/rtk/filters/test-vitest.json +43 -0
- package/src/compression/rtk/filters/tofu-plan.json +34 -0
- package/src/compression/rtk/filters/turbo.json +34 -0
- package/src/compression/rtk/filters/uv-sync.json +35 -0
- package/src/compression/rtk/filters/wget.json +34 -0
- package/src/compression/rtk/index.ts +103 -0
- package/src/compression/rtk/line-filter.ts +124 -0
- package/src/compression/rtk/smart-truncate.ts +71 -0
- package/src/config-defaults.ts +93 -0
- package/src/config-normalize.ts +48 -0
- package/src/config-storage.ts +21 -0
- package/src/dashboard.ts +1169 -0
- package/src/db-store.ts +188 -0
- package/src/doctor.ts +115 -0
- package/src/env.ts +15 -0
- package/src/exposure.ts +17 -0
- package/src/fetch-with-retry.ts +93 -0
- package/src/idempotency.ts +137 -0
- package/src/index.ts +267 -0
- package/src/key-auth.ts +159 -0
- package/src/key-migrations.ts +84 -0
- package/src/logger.ts +92 -0
- package/src/login.ts +48 -0
- package/src/notification-poller.ts +155 -0
- package/src/onboarding.ts +754 -0
- package/src/paths.ts +153 -0
- package/src/providers/adapter.ts +131 -0
- package/src/providers/credential-helpers.ts +72 -0
- package/src/providers/google-antigravity/code-assist.ts +161 -0
- package/src/providers/google-antigravity/credentials.ts +24 -0
- package/src/providers/google-antigravity/forward.ts +424 -0
- package/src/providers/google-antigravity/index.ts +168 -0
- package/src/providers/google-antigravity/login.ts +285 -0
- package/src/providers/google-antigravity/oauth.ts +314 -0
- package/src/providers/google-antigravity/quota.ts +152 -0
- package/src/providers/google-antigravity/translators.ts +1663 -0
- package/src/providers/ollama/api-key-validation.ts +59 -0
- package/src/providers/ollama/credentials.ts +28 -0
- package/src/providers/ollama/forward.ts +306 -0
- package/src/providers/ollama/index.ts +85 -0
- package/src/providers/ollama/login.ts +55 -0
- package/src/providers/ollama/prediction.ts +188 -0
- package/src/providers/ollama/quota-poll-store.ts +160 -0
- package/src/providers/ollama/quota.ts +189 -0
- package/src/providers/ollama/translators.ts +256 -0
- package/src/providers/ollama/usage-windows.ts +48 -0
- package/src/providers/proxy-dispatcher.ts +269 -0
- package/src/providers/registry.ts +70 -0
- package/src/proxy.ts +2446 -0
- package/src/rate-limit-parser.ts +126 -0
- package/src/response-headers.ts +98 -0
- package/src/responses-store.ts +159 -0
- package/src/rotator.ts +3614 -0
- package/src/settings-repository.ts +327 -0
- package/src/spend-logger.ts +696 -0
- package/src/static/dashboard-keys.js +384 -0
- package/src/static/dashboard-logs.js +797 -0
- package/src/static/dashboard.css +2740 -0
- package/src/static/dashboard.js +3177 -0
- package/src/storage.ts +105 -0
- package/src/systemd-env.ts +214 -0
- package/src/telemetry.ts +384 -0
- package/src/token-encryption.ts +199 -0
- package/src/types.ts +897 -0
- package/src/validators.ts +218 -0
- package/src/version-check.ts +225 -0
- package/src/virtual-keys.ts +312 -0
- package/tools/telemetry-receiver/README.md +147 -0
- package/tools/telemetry-receiver/package.json +13 -0
- package/tools/telemetry-receiver/receiver.js +2334 -0
- package/tuxevil-rotator_logo.png +0 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
export type RateLimitReason = "rate-limit" | "quota-exhausted" | "model-capacity" | "server-error" | "unknown";
|
|
2
|
+
|
|
3
|
+
function parseDurationToMs(errorText: string): number | null {
|
|
4
|
+
const durationMatch = errorText.match(/(?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);
|
|
5
|
+
if (!durationMatch) return null;
|
|
6
|
+
const hours = durationMatch[1] ? parseInt(durationMatch[1], 10) : 0;
|
|
7
|
+
const minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0;
|
|
8
|
+
const seconds = parseFloat(durationMatch[3]);
|
|
9
|
+
if (!Number.isFinite(seconds)) return null;
|
|
10
|
+
return Math.ceil(((hours * 60 + minutes) * 60 + seconds) * 1000);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function classifyRateLimitReason(errorText: string, status?: number): RateLimitReason {
|
|
14
|
+
if (status === 503 || status === 529) return "model-capacity";
|
|
15
|
+
if (status === 500) return "server-error";
|
|
16
|
+
|
|
17
|
+
const lower = errorText.toLowerCase();
|
|
18
|
+
if (
|
|
19
|
+
lower.includes("quota_exhausted") ||
|
|
20
|
+
lower.includes("quotaresetdelay") ||
|
|
21
|
+
lower.includes("quotaresettimestamp") ||
|
|
22
|
+
lower.includes("resource_exhausted") ||
|
|
23
|
+
lower.includes("resource exhausted") ||
|
|
24
|
+
lower.includes("daily limit") ||
|
|
25
|
+
lower.includes("quota exceeded")
|
|
26
|
+
) {
|
|
27
|
+
return "quota-exhausted";
|
|
28
|
+
}
|
|
29
|
+
if (
|
|
30
|
+
lower.includes("model_capacity_exhausted") ||
|
|
31
|
+
lower.includes("capacity_exhausted") ||
|
|
32
|
+
lower.includes("currently overloaded") ||
|
|
33
|
+
lower.includes("service temporarily unavailable")
|
|
34
|
+
) {
|
|
35
|
+
return "model-capacity";
|
|
36
|
+
}
|
|
37
|
+
if (
|
|
38
|
+
lower.includes("rate_limit_exceeded") ||
|
|
39
|
+
lower.includes("rate limit") ||
|
|
40
|
+
lower.includes("too many requests") ||
|
|
41
|
+
lower.includes("throttl")
|
|
42
|
+
) {
|
|
43
|
+
return "rate-limit";
|
|
44
|
+
}
|
|
45
|
+
if (
|
|
46
|
+
lower.includes("internal server error") ||
|
|
47
|
+
lower.includes("server error") ||
|
|
48
|
+
lower.includes("bad gateway") ||
|
|
49
|
+
lower.includes("gateway timeout")
|
|
50
|
+
) {
|
|
51
|
+
return "server-error";
|
|
52
|
+
}
|
|
53
|
+
return "unknown";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function parseRetryAfterMs(errorText: string, headers: Headers): number {
|
|
57
|
+
const retryAfter = headers.get("retry-after");
|
|
58
|
+
if (retryAfter) {
|
|
59
|
+
const seconds = Number(retryAfter);
|
|
60
|
+
if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1000 + 1000);
|
|
61
|
+
const retryDate = new Date(retryAfter);
|
|
62
|
+
if (!Number.isNaN(retryDate.getTime())) {
|
|
63
|
+
const delta = retryDate.getTime() - Date.now();
|
|
64
|
+
if (delta > 0) return Math.ceil(delta + 1000);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const resetHeader = headers.get("x-ratelimit-reset");
|
|
69
|
+
if (resetHeader) {
|
|
70
|
+
const resetTs = Number(resetHeader);
|
|
71
|
+
if (Number.isFinite(resetTs) && resetTs > 0) {
|
|
72
|
+
const delta = resetTs * 1000 - Date.now();
|
|
73
|
+
if (delta > 0) return Math.ceil(delta + 1000);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const resetAfter = headers.get("x-ratelimit-reset-after");
|
|
78
|
+
if (resetAfter) {
|
|
79
|
+
const seconds = Number(resetAfter);
|
|
80
|
+
if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1000 + 1000);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const quotaDelayMatch = errorText.match(/quotaResetDelay[:\s"]+(\d+(?:\.\d+)?)(ms|s)/i);
|
|
84
|
+
if (quotaDelayMatch) {
|
|
85
|
+
const value = parseFloat(quotaDelayMatch[1]);
|
|
86
|
+
if (Number.isFinite(value) && value > 0) {
|
|
87
|
+
const ms = quotaDelayMatch[2].toLowerCase() === "s" ? value * 1000 : value;
|
|
88
|
+
return Math.ceil(ms + 1000);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const quotaTimestampMatch = errorText.match(/quotaResetTimeStamp[:\s"]+(\d{4}-\d{2}-\d{2}T[\d:.]+Z?)/i);
|
|
93
|
+
if (quotaTimestampMatch) {
|
|
94
|
+
const resetTime = new Date(quotaTimestampMatch[1]).getTime();
|
|
95
|
+
if (!Number.isNaN(resetTime)) {
|
|
96
|
+
const delta = resetTime - Date.now();
|
|
97
|
+
if (delta > 0) return Math.ceil(delta + 1000);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const retryDelayMatch = errorText.match(/(?:retry[-_]?after[-_]?ms|retryDelay|Please retry in)[:\s"]+([0-9.]+)(ms|s)/i);
|
|
102
|
+
if (retryDelayMatch?.[1]) {
|
|
103
|
+
const value = parseFloat(retryDelayMatch[1]);
|
|
104
|
+
if (Number.isFinite(value) && value > 0) {
|
|
105
|
+
const ms = retryDelayMatch[2].toLowerCase() === "ms" ? value : value * 1000;
|
|
106
|
+
return Math.ceil(ms + 1000);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const naturalRetryMatch = errorText.match(/retry\s+(?:after\s+)?(\d+)\s*(?:sec|secs|seconds|s\b)/i);
|
|
111
|
+
if (naturalRetryMatch?.[1]) {
|
|
112
|
+
const seconds = Number(naturalRetryMatch[1]);
|
|
113
|
+
if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1000 + 1000);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const resetAfterMatch = errorText.match(/reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);
|
|
117
|
+
if (resetAfterMatch) {
|
|
118
|
+
const duration = parseDurationToMs(resetAfterMatch[0]);
|
|
119
|
+
if (duration && duration > 0) return Math.ceil(duration + 1000);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const duration = parseDurationToMs(errorText);
|
|
123
|
+
if (duration && duration > 0) return Math.ceil(duration + 1000);
|
|
124
|
+
|
|
125
|
+
return 60_000;
|
|
126
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { calculateCost } from "./spend-logger.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Masks an account email or label for PII protection in headers.
|
|
5
|
+
* Example: "user@example.com" -> "us***r@example.com"
|
|
6
|
+
* Example: "donated-account" -> "do***nt"
|
|
7
|
+
* Example: "acc" -> "ac***"
|
|
8
|
+
*/
|
|
9
|
+
export function maskAccountLabel(account: string): string {
|
|
10
|
+
if (!account) return "unknown";
|
|
11
|
+
if (account.includes("@")) {
|
|
12
|
+
const [user, domain] = account.split("@");
|
|
13
|
+
if (user.length <= 2) {
|
|
14
|
+
return `${user}***@${domain}`;
|
|
15
|
+
}
|
|
16
|
+
return `${user.slice(0, 2)}***${user.slice(-1)}@${domain}`;
|
|
17
|
+
}
|
|
18
|
+
if (account.length <= 4) return `${account}***`;
|
|
19
|
+
return `${account.slice(0, 2)}***${account.slice(-2)}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface CompressionHeaderOptions {
|
|
23
|
+
mode: string;
|
|
24
|
+
savedChars: number;
|
|
25
|
+
savingsPercent: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface RotatorResponseHeaderOptions {
|
|
29
|
+
accountLabel?: string;
|
|
30
|
+
model?: string;
|
|
31
|
+
latencyMs?: number;
|
|
32
|
+
ttfbMs?: number;
|
|
33
|
+
inputTokens?: number;
|
|
34
|
+
outputTokens?: number;
|
|
35
|
+
healthScore?: number;
|
|
36
|
+
routingPolicy?: string;
|
|
37
|
+
idempotencyHit?: boolean;
|
|
38
|
+
retries?: number;
|
|
39
|
+
compression?: CompressionHeaderOptions;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Builds standard X-Rotator-* response headers for observability.
|
|
44
|
+
*/
|
|
45
|
+
export function buildRotatorResponseHeaders(
|
|
46
|
+
opts: RotatorResponseHeaderOptions,
|
|
47
|
+
): Record<string, string> {
|
|
48
|
+
const headers: Record<string, string> = {};
|
|
49
|
+
|
|
50
|
+
if (opts.idempotencyHit) {
|
|
51
|
+
headers["X-Rotator-Idempotency-Hit"] = "true";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (opts.retries !== undefined && opts.retries > 0) {
|
|
55
|
+
headers["X-Rotator-Retries"] = String(Math.floor(opts.retries));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (opts.accountLabel) {
|
|
59
|
+
headers["X-Rotator-Account"] = maskAccountLabel(opts.accountLabel);
|
|
60
|
+
}
|
|
61
|
+
if (opts.model) {
|
|
62
|
+
headers["X-Rotator-Model"] = opts.model;
|
|
63
|
+
}
|
|
64
|
+
if (opts.latencyMs !== undefined && opts.latencyMs >= 0) {
|
|
65
|
+
headers["X-Rotator-Latency-Ms"] = String(Math.round(opts.latencyMs));
|
|
66
|
+
}
|
|
67
|
+
if (opts.ttfbMs !== undefined && opts.ttfbMs >= 0) {
|
|
68
|
+
headers["X-Rotator-TTFB-Ms"] = String(Math.round(opts.ttfbMs));
|
|
69
|
+
}
|
|
70
|
+
if (opts.inputTokens !== undefined && opts.inputTokens >= 0) {
|
|
71
|
+
headers["X-Rotator-Tokens-Input"] = String(opts.inputTokens);
|
|
72
|
+
}
|
|
73
|
+
if (opts.outputTokens !== undefined && opts.outputTokens >= 0) {
|
|
74
|
+
headers["X-Rotator-Tokens-Output"] = String(opts.outputTokens);
|
|
75
|
+
}
|
|
76
|
+
if (
|
|
77
|
+
(opts.inputTokens !== undefined && opts.inputTokens >= 0) ||
|
|
78
|
+
(opts.outputTokens !== undefined && opts.outputTokens >= 0)
|
|
79
|
+
) {
|
|
80
|
+
const input = opts.inputTokens && opts.inputTokens >= 0 ? opts.inputTokens : 0;
|
|
81
|
+
const output = opts.outputTokens && opts.outputTokens >= 0 ? opts.outputTokens : 0;
|
|
82
|
+
const cost = calculateCost(opts.model || "", input, output);
|
|
83
|
+
headers["X-Rotator-Cost-Usd"] = cost.toFixed(6);
|
|
84
|
+
}
|
|
85
|
+
if (opts.healthScore !== undefined) {
|
|
86
|
+
headers["X-Rotator-Health-Score"] = opts.healthScore.toFixed(2);
|
|
87
|
+
}
|
|
88
|
+
if (opts.routingPolicy) {
|
|
89
|
+
headers["X-Rotator-Routing-Policy"] = opts.routingPolicy;
|
|
90
|
+
}
|
|
91
|
+
if (opts.compression) {
|
|
92
|
+
headers["X-Rotator-Compression-Mode"] = opts.compression.mode;
|
|
93
|
+
headers["X-Rotator-Compression-Saved-Chars"] = String(opts.compression.savedChars);
|
|
94
|
+
headers["X-Rotator-Compression-Savings-Percent"] = String(opts.compression.savingsPercent);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return headers;
|
|
98
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// Persistent in-memory store for OpenAI Responses API (Codex) chain state.
|
|
2
|
+
//
|
|
3
|
+
// The store maps `response_id` to the conversation state needed to continue
|
|
4
|
+
// a previous turn via `previous_response_id`. It is persisted via the
|
|
5
|
+
// settings repository (PostgreSQL or disk files) so a rotator restart does
|
|
6
|
+
// not break active Codex sessions.
|
|
7
|
+
//
|
|
8
|
+
// Writes are debounced to avoid excessive persistence calls under load.
|
|
9
|
+
// The store is flushed asynchronously during graceful shutdown (see index.ts)
|
|
10
|
+
// to minimise data loss without blocking the event loop.
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
getCachedResponsesStore,
|
|
14
|
+
setCachedResponsesStore,
|
|
15
|
+
} from "./db-store.js";
|
|
16
|
+
|
|
17
|
+
export interface StoredResponseEntry {
|
|
18
|
+
response: Record<string, unknown>;
|
|
19
|
+
inputItems: Array<Record<string, unknown>>;
|
|
20
|
+
conversationMessages: Array<Record<string, unknown>>;
|
|
21
|
+
// Maps call_id -> function name. Serialized as plain object on disk
|
|
22
|
+
// because Map cannot be JSON.stringified directly. Convert to Map at use sites.
|
|
23
|
+
callIdToName: Record<string, string>;
|
|
24
|
+
expiresAt: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface PersistedResponsesStore {
|
|
28
|
+
version: 1;
|
|
29
|
+
entries: Array<[string, StoredResponseEntry]>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const FLUSH_DEBOUNCE_MS = 1_500;
|
|
33
|
+
const MAX_ENTRIES = 500;
|
|
34
|
+
const ENTRY_TTL_MS = 6 * 60 * 60 * 1000;
|
|
35
|
+
|
|
36
|
+
function now(): number {
|
|
37
|
+
return Date.now();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Persistent in-memory store for OpenAI Responses API (Codex) chain state.
|
|
42
|
+
*
|
|
43
|
+
* Maps `response_id` to the conversation state needed to continue a previous
|
|
44
|
+
* turn via `previous_response_id`. Persisted via the settings repository.
|
|
45
|
+
* Writes are debounced to 1.5s and coalesced if a flush is already in flight.
|
|
46
|
+
* Stale entries (older than the 6h TTL) and entries over the 500-entry cap
|
|
47
|
+
* are pruned automatically.
|
|
48
|
+
*/
|
|
49
|
+
export class ResponsesStore {
|
|
50
|
+
private cache = new Map<string, StoredResponseEntry>();
|
|
51
|
+
private flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
52
|
+
private flushing: Promise<void> | null = null;
|
|
53
|
+
private pendingFlush = false;
|
|
54
|
+
private dirty = false;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Load the persisted store from the repository. Missing or corrupt data
|
|
58
|
+
* is treated as an empty store. Stale entries (older than TTL) are pruned.
|
|
59
|
+
*/
|
|
60
|
+
async load(): Promise<void> {
|
|
61
|
+
const dbStore = getCachedResponsesStore();
|
|
62
|
+
if (!dbStore || dbStore.version !== 1 || !Array.isArray(dbStore.entries)) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const cutoff = now() - ENTRY_TTL_MS;
|
|
66
|
+
for (const [id, entry] of dbStore.entries) {
|
|
67
|
+
if (!entry || typeof entry !== "object") continue;
|
|
68
|
+
if (typeof entry.expiresAt !== "number" || entry.expiresAt < cutoff)
|
|
69
|
+
continue;
|
|
70
|
+
this.cache.set(id, entry);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
get(id: string): StoredResponseEntry | null {
|
|
75
|
+
const entry = this.cache.get(id);
|
|
76
|
+
if (!entry) return null;
|
|
77
|
+
if (entry.expiresAt <= now()) {
|
|
78
|
+
this.cache.delete(id);
|
|
79
|
+
this.scheduleFlush();
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
return entry;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
set(id: string, entry: StoredResponseEntry): void {
|
|
86
|
+
this.cache.set(id, entry);
|
|
87
|
+
this.pruneIfNeeded();
|
|
88
|
+
this.scheduleFlush();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
delete(id: string): boolean {
|
|
92
|
+
const existed = this.cache.delete(id);
|
|
93
|
+
if (existed) this.scheduleFlush();
|
|
94
|
+
return existed;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
clear(): void {
|
|
98
|
+
this.cache.clear();
|
|
99
|
+
this.scheduleFlush();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
size(): number {
|
|
103
|
+
return this.cache.size;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private pruneIfNeeded(): void {
|
|
107
|
+
const cutoff = now() - ENTRY_TTL_MS;
|
|
108
|
+
for (const [id, entry] of this.cache.entries()) {
|
|
109
|
+
if (entry.expiresAt <= cutoff) this.cache.delete(id);
|
|
110
|
+
}
|
|
111
|
+
while (this.cache.size > MAX_ENTRIES) {
|
|
112
|
+
const oldest = this.cache.keys().next();
|
|
113
|
+
if (oldest.done) break;
|
|
114
|
+
this.cache.delete(oldest.value);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private scheduleFlush(): void {
|
|
119
|
+
this.dirty = true;
|
|
120
|
+
if (this.flushTimer) return;
|
|
121
|
+
this.flushTimer = setTimeout(() => {
|
|
122
|
+
this.flushTimer = null;
|
|
123
|
+
void this.flush();
|
|
124
|
+
}, FLUSH_DEBOUNCE_MS);
|
|
125
|
+
if (this.flushTimer.unref) this.flushTimer.unref();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Flush pending writes to the repository. Safe to call multiple times
|
|
130
|
+
* concurrently; callers will see the same in-flight promise.
|
|
131
|
+
*/
|
|
132
|
+
async flush(): Promise<void> {
|
|
133
|
+
if (this.flushing) {
|
|
134
|
+
this.pendingFlush = true;
|
|
135
|
+
return this.flushing;
|
|
136
|
+
}
|
|
137
|
+
this.flushing = (async () => {
|
|
138
|
+
try {
|
|
139
|
+
if (!this.dirty) return;
|
|
140
|
+
const data: PersistedResponsesStore = {
|
|
141
|
+
version: 1,
|
|
142
|
+
entries: Array.from(this.cache.entries()),
|
|
143
|
+
};
|
|
144
|
+
await setCachedResponsesStore(data);
|
|
145
|
+
this.dirty = false;
|
|
146
|
+
} catch {
|
|
147
|
+
// Best effort — will retry on next schedule.
|
|
148
|
+
} finally {
|
|
149
|
+
this.flushing = null;
|
|
150
|
+
if (this.pendingFlush) {
|
|
151
|
+
this.pendingFlush = false;
|
|
152
|
+
void this.flush();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
})();
|
|
156
|
+
return this.flushing;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
}
|