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.
Files changed (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
@@ -0,0 +1,188 @@
1
+ // Convenience façade over the settings repository.
2
+ //
3
+ // Maintains full backward compatibility with the previous module API while
4
+ // delegating all persistence to an ISettingsRepository implementation.
5
+ // Both PostgresSettingsRepository and FileSettingsRepository are fully
6
+ // self-contained — callers no longer need to branch on isDbConfigured().
7
+
8
+ import type { Config, PersistedState, TokenUsageTiered } from "./types.js";
9
+ import type { PersistedResponsesStore } from "./responses-store.js";
10
+ import { validateConfig } from "./validators.js";
11
+ import { rotatorEnv } from "./env.js";
12
+ import { applyConfigDefaults } from "./config-defaults.js";
13
+ import {
14
+ decryptAccountsInConfig,
15
+ encryptAccountsInConfig,
16
+ } from "./token-encryption.js";
17
+ import {
18
+ type ISettingsRepository,
19
+ PostgresSettingsRepository,
20
+ FileSettingsRepository,
21
+ } from "./settings-repository.js";
22
+
23
+ export type { PersistedResponsesStore } from "./responses-store.js";
24
+
25
+ // ----- Repository strategy -----
26
+
27
+ function createRepository(): ISettingsRepository {
28
+ if (rotatorEnv("DATABASE_URL") || process.env.DATABASE_URL) {
29
+ return new PostgresSettingsRepository();
30
+ }
31
+ return new FileSettingsRepository();
32
+ }
33
+
34
+ const repository: ISettingsRepository = createRepository();
35
+
36
+ let initialized = false;
37
+
38
+ function assertInitialized(): void {
39
+ if (!initialized) {
40
+ throw new Error(
41
+ "db-store: repository not initialized. Call initDb() before accessing settings.",
42
+ );
43
+ }
44
+ }
45
+
46
+ // ----- Backward-compatible public API -----
47
+
48
+ /**
49
+ * Whether persistence is backed by PostgreSQL (true) or disk files (false).
50
+ * Callers that need to know the storage backend (e.g. for diagnostics or
51
+ * doctor output) can use this, but most callers should NOT need to branch
52
+ * on this — both repositories handle their own I/O.
53
+ */
54
+ export function isDbConfigured(): boolean {
55
+ return !!(rotatorEnv("DATABASE_URL") || process.env.DATABASE_URL);
56
+ }
57
+
58
+ export async function initDb(): Promise<void> {
59
+ await repository.init();
60
+ initialized = true;
61
+ }
62
+
63
+ export function getDbPool() {
64
+ if (repository instanceof PostgresSettingsRepository) {
65
+ return repository.getPool();
66
+ }
67
+ return null;
68
+ }
69
+
70
+ export async function queryDb<R extends import("pg").QueryResultRow = import("pg").QueryResultRow>(
71
+ text: string,
72
+ params?: unknown[],
73
+ ): Promise<import("pg").QueryResult<R>> {
74
+ assertInitialized();
75
+ if (repository instanceof PostgresSettingsRepository) {
76
+ return repository.query<R>(text, params);
77
+ }
78
+ throw new Error("PostgreSQL database is not configured");
79
+ }
80
+
81
+ export async function closeDb(): Promise<void> {
82
+ await repository.close();
83
+ initialized = false;
84
+ }
85
+
86
+ // --- Accounts config ---
87
+
88
+ export function getCachedConfig(): Config | null {
89
+ assertInitialized();
90
+ const raw = repository.get("accounts_json");
91
+ if (!raw) return null;
92
+ try {
93
+ const parsed = JSON.parse(raw);
94
+ const validation = validateConfig(parsed);
95
+ if (validation.ok && validation.value) {
96
+ const withDefaults = applyConfigDefaults(validation.value);
97
+ const { config: decryptedConfig, migrated } = decryptAccountsInConfig(withDefaults);
98
+ if (migrated) {
99
+ void setCachedConfig(decryptedConfig).catch((err) => {
100
+ console.error(`Failed to persist migrated accounts config: ${err}`);
101
+ });
102
+ }
103
+ return decryptedConfig;
104
+ }
105
+ } catch (err) {
106
+ console.error(`Failed to parse accounts config from repository: ${err}`);
107
+ }
108
+ return null;
109
+ }
110
+
111
+ export async function setCachedConfig(config: Config): Promise<void> {
112
+ assertInitialized();
113
+ const withDefaults = applyConfigDefaults(config);
114
+ const encryptedConfig = encryptAccountsInConfig(withDefaults);
115
+ await repository.set("accounts_json", JSON.stringify(encryptedConfig, null, 2));
116
+ }
117
+
118
+ // --- Admin token ---
119
+
120
+ export function getCachedAdminToken(): string | null {
121
+ assertInitialized();
122
+ const raw = repository.get("admin_token");
123
+ return raw ? raw.trim() : null;
124
+ }
125
+
126
+ export async function setCachedAdminToken(token: string): Promise<void> {
127
+ assertInitialized();
128
+ await repository.set("admin_token", token.trim());
129
+ }
130
+
131
+ // --- Rotator state ---
132
+
133
+ export function getCachedState(): PersistedState | null {
134
+ assertInitialized();
135
+ const raw = repository.get("rotator_state");
136
+ if (!raw) return null;
137
+ try {
138
+ return JSON.parse(raw) as PersistedState;
139
+ } catch (err) {
140
+ console.error(`Failed to parse rotator state from repository: ${err}`);
141
+ return null;
142
+ }
143
+ }
144
+
145
+ export async function setCachedState(state: PersistedState): Promise<void> {
146
+ assertInitialized();
147
+ await repository.set("rotator_state", JSON.stringify(state));
148
+ }
149
+
150
+ // --- Token usage ---
151
+
152
+ export function getCachedTokenUsage(): TokenUsageTiered | null {
153
+ assertInitialized();
154
+ const raw = repository.get("token_usage");
155
+ if (!raw) return null;
156
+ try {
157
+ return JSON.parse(raw) as TokenUsageTiered;
158
+ } catch (err) {
159
+ console.error(`Failed to parse token usage from repository: ${err}`);
160
+ return null;
161
+ }
162
+ }
163
+
164
+ export async function setCachedTokenUsage(usage: TokenUsageTiered): Promise<void> {
165
+ assertInitialized();
166
+ await repository.set("token_usage", JSON.stringify(usage));
167
+ }
168
+
169
+ // --- Responses store ---
170
+
171
+ export function getCachedResponsesStore(): PersistedResponsesStore | null {
172
+ assertInitialized();
173
+ const raw = repository.get("responses_store");
174
+ if (!raw) return null;
175
+ try {
176
+ return JSON.parse(raw) as PersistedResponsesStore;
177
+ } catch (err) {
178
+ console.error(`Failed to parse responses store from repository: ${err}`);
179
+ return null;
180
+ }
181
+ }
182
+
183
+ export async function setCachedResponsesStore(
184
+ store: PersistedResponsesStore,
185
+ ): Promise<void> {
186
+ assertInitialized();
187
+ await repository.set("responses_store", JSON.stringify(store));
188
+ }
package/src/doctor.ts ADDED
@@ -0,0 +1,115 @@
1
+ import { accessSync, constants, existsSync } from "node:fs";
2
+ import { getConfiguredAdminToken } from "./admin-auth.js";
3
+ import { getConfigDir } from "./paths.js";
4
+ import { listBackups } from "./storage.js";
5
+ import {
6
+ isDbConfigured,
7
+ getCachedConfig,
8
+ getCachedState,
9
+ getCachedTokenUsage,
10
+ } from "./db-store.js";
11
+
12
+ function checkWritable(path: string): boolean {
13
+ try {
14
+ accessSync(path, constants.R_OK | constants.W_OK);
15
+ return true;
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+
21
+ export interface DoctorResult {
22
+ ok: boolean;
23
+ warnings: string[];
24
+ errors: string[];
25
+ info: Record<string, unknown>;
26
+ }
27
+
28
+ export async function runDoctor(
29
+ env: NodeJS.ProcessEnv = process.env,
30
+ ): Promise<DoctorResult> {
31
+ const warnings: string[] = [];
32
+ const errors: string[] = [];
33
+ const configDir = getConfigDir();
34
+
35
+ if (!getConfiguredAdminToken(env)) {
36
+ warnings.push(
37
+ "TUXEVIL_ROTATOR_ADMIN_TOKEN is not configured; dashboard and /api/* remain open on the bound interface.",
38
+ );
39
+ }
40
+
41
+ const dbConfigured = isDbConfigured();
42
+
43
+ if (dbConfigured) {
44
+ // When using PostgreSQL, configDir is not required for data persistence
45
+ if (!existsSync(configDir)) {
46
+ warnings.push(
47
+ `Config directory does not exist (${configDir}), but storage backend is PostgreSQL — this is expected in containerised environments.`,
48
+ );
49
+ }
50
+ } else {
51
+ if (!existsSync(configDir)) {
52
+ errors.push(`Config directory missing: ${configDir}`);
53
+ } else if (!checkWritable(configDir)) {
54
+ errors.push(`Config directory is not writable: ${configDir}`);
55
+ }
56
+ }
57
+
58
+ // Validate config — read from repository (handles both DB and file)
59
+ const cfg = getCachedConfig();
60
+ if (!cfg) {
61
+ warnings.push(
62
+ "No accounts config found. Run 'tuxevil-rotator login' to add your first account.",
63
+ );
64
+ }
65
+
66
+ // Validate state
67
+ const state = getCachedState();
68
+ if (state && typeof state !== "object") {
69
+ warnings.push("Rotator state data is corrupted.");
70
+ }
71
+
72
+ // Validate token usage
73
+ const usage = getCachedTokenUsage();
74
+ if (usage && typeof usage !== "object") {
75
+ warnings.push("Token usage data is corrupted.");
76
+ }
77
+
78
+ const backups = dbConfigured ? [] : await listBackups();
79
+
80
+ return {
81
+ ok: errors.length === 0,
82
+ warnings,
83
+ errors,
84
+ info: {
85
+ configDir,
86
+ backupCount: backups.length,
87
+ firstBackup: backups[0] ?? null,
88
+ adminTokenConfigured: !!getConfiguredAdminToken(env),
89
+ bindHost: env.TUXEVIL_ROTATOR_BIND_HOST ?? env.PI_ROTATOR_BIND_HOST ?? null,
90
+ storageBackend: dbConfigured ? "postgresql" : "file",
91
+ },
92
+ };
93
+ }
94
+
95
+ export function printDoctorReport(result: DoctorResult): void {
96
+ console.log("Tuxevil Rotator Doctor");
97
+ console.log();
98
+ console.log(`Status: ${result.ok ? "OK" : "ERROR"}`);
99
+ console.log();
100
+ for (const [key, value] of Object.entries(result.info)) {
101
+ console.log(
102
+ `${key}: ${typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null ? value : JSON.stringify(value)}`,
103
+ );
104
+ }
105
+ if (result.warnings.length > 0) {
106
+ console.log();
107
+ console.log("Warnings:");
108
+ for (const warning of result.warnings) console.log(`- ${warning}`);
109
+ }
110
+ if (result.errors.length > 0) {
111
+ console.log();
112
+ console.log("Errors:");
113
+ for (const error of result.errors) console.log(`- ${error}`);
114
+ }
115
+ }
package/src/env.ts ADDED
@@ -0,0 +1,15 @@
1
+ // Environment variable resolution with legacy fallback.
2
+ //
3
+ // The service is branded "tuxevil-rotator": all configuration env vars use
4
+ // the TUXEVIL_ROTATOR_ prefix. For backward compatibility with existing
5
+ // deployments, every read falls back to the legacy PI_ROTATOR_ prefix.
6
+
7
+ export function rotatorEnv(name: string): string | undefined {
8
+ const value = process.env[`TUXEVIL_ROTATOR_${name}`];
9
+ if (value !== undefined) return value;
10
+ return process.env[`PI_ROTATOR_${name}`];
11
+ }
12
+
13
+ export function rotatorEnvOr(name: string, fallback: string): string {
14
+ return rotatorEnv(name) ?? fallback;
15
+ }
@@ -0,0 +1,17 @@
1
+ import type { Config } from "./types.js";
2
+
3
+ type ExposureConfig = Pick<Config, "bindHost" | "proxyPort">;
4
+
5
+ export function isLoopbackBindHost(bindHost?: string | null): boolean {
6
+ const host = (bindHost || "0.0.0.0").trim().toLowerCase();
7
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
8
+ }
9
+
10
+ export function getProxyExposureWarning(config: ExposureConfig): string | null {
11
+ const bindHost = config.bindHost || "0.0.0.0";
12
+ if (isLoopbackBindHost(bindHost)) return null;
13
+ return (
14
+ `Native and /v1 compatibility proxy routes are unauthenticated by design and are listening on ${bindHost}:${config.proxyPort}. ` +
15
+ "Restrict this port to localhost/LAN, a firewall, or a trusted reverse proxy, or set bindHost to 127.0.0.1 for local-only use."
16
+ );
17
+ }
@@ -0,0 +1,93 @@
1
+ import type { Dispatcher } from "undici";
2
+
3
+ export interface FetchWithRetryOptions extends RequestInit {
4
+ retries?: number;
5
+ timeoutMs?: number;
6
+ baseDelayMs?: number;
7
+ maxDelayMs?: number;
8
+ retryStatuses?: number[];
9
+ fetchImpl?: typeof fetch;
10
+ sleepImpl?: (ms: number) => Promise<void>;
11
+ /** Node/Undici dispatcher selected from the account's provider config. */
12
+ dispatcher?: Dispatcher;
13
+ }
14
+
15
+ export type RequestInitWithDispatcher = RequestInit & { dispatcher?: Dispatcher };
16
+
17
+ export const DEFAULT_RETRY_STATUSES = [408, 429, 500, 502, 503, 504] as const;
18
+
19
+ export function isRetryableStatus(status: number, retryStatuses: readonly number[] = DEFAULT_RETRY_STATUSES): boolean {
20
+ return retryStatuses.includes(status);
21
+ }
22
+
23
+ export function isRetryableFetchError(error: unknown): boolean {
24
+ if (error instanceof DOMException && error.name === "AbortError") return true;
25
+ return error instanceof TypeError;
26
+ }
27
+
28
+ export function calculateBackoffMs(
29
+ attempt: number,
30
+ baseDelayMs = 250,
31
+ maxDelayMs = 5_000,
32
+ random = Math.random,
33
+ ): number {
34
+ const exponential = baseDelayMs * 2 ** Math.max(0, attempt);
35
+ const jitter = exponential * 0.2 * random();
36
+ return Math.min(maxDelayMs, Math.round(exponential + jitter));
37
+ }
38
+
39
+ function sleep(ms: number): Promise<void> {
40
+ return new Promise((resolve) => setTimeout(resolve, ms));
41
+ }
42
+
43
+ function createTimeoutSignal(timeoutMs: number | undefined, inputSignal: AbortSignal | null | undefined): AbortSignal | undefined {
44
+ if (!timeoutMs || timeoutMs <= 0) return inputSignal ?? undefined;
45
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
46
+ if (!inputSignal) return timeoutSignal;
47
+ return AbortSignal.any([inputSignal, timeoutSignal]);
48
+ }
49
+
50
+ /**
51
+ * Fetch wrapper for non-streaming calls. Retries only transport failures and explicit retryable statuses.
52
+ * Do not use for streaming responses: retrying streams can duplicate upstream work.
53
+ */
54
+ export async function fetchWithRetry(input: RequestInfo | URL, options: FetchWithRetryOptions = {}): Promise<Response> {
55
+ const {
56
+ retries = 2,
57
+ timeoutMs = 10_000,
58
+ baseDelayMs = 250,
59
+ maxDelayMs = 5_000,
60
+ retryStatuses = [...DEFAULT_RETRY_STATUSES],
61
+ fetchImpl = fetch,
62
+ sleepImpl = sleep,
63
+ dispatcher,
64
+ ...init
65
+ } = options;
66
+
67
+ let lastError: unknown;
68
+ for (let attempt = 0; attempt <= retries; attempt++) {
69
+ try {
70
+ const requestInit: RequestInitWithDispatcher = {
71
+ ...init,
72
+ dispatcher,
73
+ signal: createTimeoutSignal(timeoutMs, init.signal),
74
+ };
75
+ const response = await fetchImpl(input, requestInit);
76
+
77
+ if (!isRetryableStatus(response.status, retryStatuses) || attempt === retries) {
78
+ return response;
79
+ }
80
+
81
+ await response.body?.cancel().catch(() => undefined);
82
+ } catch (err) {
83
+ lastError = err;
84
+ if (!isRetryableFetchError(err) || attempt === retries) {
85
+ throw err;
86
+ }
87
+ }
88
+
89
+ await sleepImpl(calculateBackoffMs(attempt, baseDelayMs, maxDelayMs));
90
+ }
91
+
92
+ throw lastError instanceof Error ? lastError : new Error(String(lastError ?? "fetch failed"));
93
+ }
@@ -0,0 +1,137 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { IncomingMessage } from "node:http";
3
+
4
+ export interface IdempotencyOptions {
5
+ enabled?: boolean;
6
+ windowMs?: number;
7
+ }
8
+
9
+ interface InFlightEntry<T> {
10
+ promise: Promise<T>;
11
+ timestamp: number;
12
+ }
13
+
14
+ export class IdempotencyManager {
15
+ private inFlight = new Map<string, InFlightEntry<unknown>>();
16
+
17
+ /**
18
+ * Compute fingerprint for a request body and optional client idempotency key.
19
+ */
20
+ computeKey(model: string, body: unknown, clientKey?: string | null): string {
21
+ if (clientKey && clientKey.trim().length > 0) {
22
+ return createHash("sha256")
23
+ .update(`idkey:${clientKey.trim()}`)
24
+ .digest("hex");
25
+ }
26
+ const raw = typeof body === "string" ? body : JSON.stringify(body);
27
+ return createHash("sha256")
28
+ .update(`body:${model}:${raw}`)
29
+ .digest("hex");
30
+ }
31
+
32
+ /**
33
+ * Check if a request has opt-out headers.
34
+ */
35
+ isOptedOut(req: IncomingMessage): boolean {
36
+ const headers = req.headers;
37
+ const noDedup =
38
+ headers["x-rotator-no-deduplicate"] ||
39
+ headers["x-no-deduplicate"] ||
40
+ headers["x-no-cache"];
41
+ return Boolean(
42
+ noDedup &&
43
+ noDedup !== "false" &&
44
+ noDedup !== "0" &&
45
+ Array.isArray(noDedup) === false,
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Extract client-provided idempotency key from request headers.
51
+ */
52
+ extractClientKey(req: IncomingMessage): string | null {
53
+ const key =
54
+ req.headers["idempotency-key"] ||
55
+ req.headers["x-idempotency-key"] ||
56
+ req.headers["x-rotator-idempotency-key"];
57
+ if (typeof key === "string" && key.trim().length > 0) {
58
+ return key.trim();
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /**
64
+ * Execute an operation idempotently. If an identical operation is currently
65
+ * in-flight or completed within windowMs, await the in-flight promise.
66
+ */
67
+ async execute<T>(
68
+ key: string,
69
+ windowMs: number,
70
+ fn: () => Promise<T>,
71
+ ): Promise<{ result: T; isDeduplicated: boolean }> {
72
+ if (windowMs <= 0) {
73
+ const result = await fn();
74
+ return { result, isDeduplicated: false };
75
+ }
76
+
77
+ this.cleanup(windowMs);
78
+
79
+ const existing = this.inFlight.get(key);
80
+ if (existing) {
81
+ try {
82
+ const result = (await existing.promise) as T;
83
+ return { result, isDeduplicated: true };
84
+ } catch {
85
+ // If the original failed, remove and proceed with fresh execution
86
+ this.inFlight.delete(key);
87
+ }
88
+ }
89
+
90
+ const promise = fn();
91
+ const entry: InFlightEntry<T> = {
92
+ promise,
93
+ timestamp: Date.now(),
94
+ };
95
+
96
+ this.inFlight.set(key, entry as InFlightEntry<unknown>);
97
+
98
+ try {
99
+ const result = await promise;
100
+ // Schedule removal after windowMs
101
+ const timer = setTimeout(() => {
102
+ if (this.inFlight.get(key) === entry) {
103
+ this.inFlight.delete(key);
104
+ }
105
+ }, windowMs);
106
+ if (timer && typeof timer.unref === "function") {
107
+ timer.unref();
108
+ }
109
+ return { result, isDeduplicated: false };
110
+ } catch (err) {
111
+ // Remove immediately on error so retries can proceed
112
+ this.inFlight.delete(key);
113
+ throw err;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Evict stale entries.
119
+ */
120
+ private cleanup(windowMs: number): void {
121
+ const now = Date.now();
122
+ for (const [k, v] of this.inFlight.entries()) {
123
+ if (now - v.timestamp > windowMs * 2) {
124
+ this.inFlight.delete(k);
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Reset all in-flight entries (for testing).
131
+ */
132
+ clear(): void {
133
+ this.inFlight.clear();
134
+ }
135
+ }
136
+
137
+ export const idempotencyManager = new IdempotencyManager();