tuxevil-rotator 3.2.1 → 3.2.3
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 +28 -0
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/compat/model-specs.ts +31 -28
- package/src/compat.ts +2 -2
- package/src/providers/google-antigravity/catalog.ts +99 -0
- package/src/providers/google-antigravity/index.ts +5 -0
- package/src/providers/ollama/context-window.ts +117 -0
- package/src/providers/ollama/index.ts +1 -0
- package/src/providers/openai-codex/catalog.ts +8 -2
- package/src/providers/opencode-zen/catalog.ts +13 -1
- package/src/proxy.ts +42 -37
- package/src/rotator.ts +340 -55
- package/src/spend-logger.ts +75 -38
- package/src/virtual-keys.ts +28 -4
package/src/spend-logger.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { rotatorEnv } from "./env.js";
|
|
|
5
5
|
|
|
6
6
|
const FLUSH_INTERVAL_MS = 5_000;
|
|
7
7
|
const MAX_QUEUE_SIZE = 50;
|
|
8
|
+
const MAX_QUEUE_CAP = 100;
|
|
8
9
|
const DEFAULT_KEY_HASH_LABEL = "unauthenticated";
|
|
9
10
|
|
|
10
11
|
const storeMessagesConfig =
|
|
@@ -19,6 +20,27 @@ let queue: SpendLog[] = [];
|
|
|
19
20
|
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
20
21
|
let isFlushing = false;
|
|
21
22
|
|
|
23
|
+
export function getSpendQueueSizeForTests(): number {
|
|
24
|
+
return queue.length;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function getSpendQueueItemsForTests(): SpendLog[] {
|
|
28
|
+
return [...queue];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function setSpendQueueForTests(items: SpendLog[]): void {
|
|
32
|
+
queue = [...items];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function resetSpendLoggerForTests(): void {
|
|
36
|
+
queue = [];
|
|
37
|
+
if (flushTimer) {
|
|
38
|
+
clearTimeout(flushTimer);
|
|
39
|
+
flushTimer = null;
|
|
40
|
+
}
|
|
41
|
+
isFlushing = false;
|
|
42
|
+
}
|
|
43
|
+
|
|
22
44
|
export function generateRequestId(): string {
|
|
23
45
|
return `req_${Date.now().toString(36)}_${randomBytes.randomBytes(8).toString("hex")}`;
|
|
24
46
|
}
|
|
@@ -32,6 +54,11 @@ export function logSpend(
|
|
|
32
54
|
totalTokens?: number;
|
|
33
55
|
},
|
|
34
56
|
): void {
|
|
57
|
+
if (!isDbConfigured()) {
|
|
58
|
+
if (queue.length > 0) queue = [];
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
|
|
35
62
|
const pricing = MODEL_PRICING[log.model] || { inputPer1M: 0, outputPer1M: 0 };
|
|
36
63
|
const promptTokens = Math.max(0, log.promptTokens || 0);
|
|
37
64
|
const completionTokens = Math.max(0, log.completionTokens || 0);
|
|
@@ -71,6 +98,9 @@ export function logSpend(
|
|
|
71
98
|
createdAt: new Date().toISOString(),
|
|
72
99
|
};
|
|
73
100
|
|
|
101
|
+
if (queue.length >= MAX_QUEUE_CAP) {
|
|
102
|
+
queue.splice(0, queue.length - MAX_QUEUE_CAP + 1);
|
|
103
|
+
}
|
|
74
104
|
queue.push(fullLog);
|
|
75
105
|
|
|
76
106
|
if (queue.length >= MAX_QUEUE_SIZE) {
|
|
@@ -137,23 +167,52 @@ function cleanValue(val: unknown, depth = 0): unknown {
|
|
|
137
167
|
* Flush accumulated spend logs to database.
|
|
138
168
|
*/
|
|
139
169
|
export async function flushSpendLogs(): Promise<void> {
|
|
140
|
-
if (
|
|
170
|
+
if (!isDbConfigured()) {
|
|
171
|
+
queue = [];
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (isFlushing || queue.length === 0) return;
|
|
141
175
|
isFlushing = true;
|
|
142
176
|
|
|
143
177
|
const logsToFlush = queue;
|
|
144
178
|
queue = [];
|
|
145
179
|
|
|
180
|
+
let lastProcessedIndex = -1;
|
|
146
181
|
try {
|
|
147
|
-
for (
|
|
148
|
-
|
|
182
|
+
for (let i = 0; i < logsToFlush.length; i++) {
|
|
183
|
+
const log = logsToFlush[i];
|
|
184
|
+
const dateStr = log.startTime.slice(0, 10); // YYYY-MM-DD
|
|
185
|
+
const keyHashForDaily = log.apiKeyHash || DEFAULT_KEY_HASH_LABEL;
|
|
186
|
+
const isSuccess = log.status === "success" ? 1 : 0;
|
|
187
|
+
const isFail = log.status === "failure" ? 1 : 0;
|
|
188
|
+
|
|
189
|
+
// Atomic insert: detailed log + daily aggregation in a single query CTE.
|
|
190
|
+
// If the request_id was already inserted, ins_log yields 0 rows, making
|
|
191
|
+
// the daily aggregation update completely idempotent against retries.
|
|
149
192
|
await queryDb(
|
|
150
|
-
`
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
193
|
+
`WITH ins_log AS (
|
|
194
|
+
INSERT INTO rotator_spend_logs (
|
|
195
|
+
request_id, api_key_hash, model, account_email, call_type, status,
|
|
196
|
+
prompt_tokens, completion_tokens, total_tokens, start_time, end_time,
|
|
197
|
+
ttfb_ms, duration_ms, request_messages, response_content, metadata,
|
|
198
|
+
requester_ip, created_at
|
|
199
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
|
|
200
|
+
ON CONFLICT (request_id) DO NOTHING
|
|
201
|
+
RETURNING request_id
|
|
202
|
+
)
|
|
203
|
+
INSERT INTO rotator_daily_spend (
|
|
204
|
+
api_key_hash, model, date, prompt_tokens, completion_tokens,
|
|
205
|
+
total_requests, successful_requests, failed_requests, total_duration_ms
|
|
206
|
+
)
|
|
207
|
+
SELECT $19, $3, $20::date, $7, $8, 1, $21, $22, $13
|
|
208
|
+
FROM ins_log
|
|
209
|
+
ON CONFLICT (api_key_hash, model, date) DO UPDATE SET
|
|
210
|
+
prompt_tokens = rotator_daily_spend.prompt_tokens + EXCLUDED.prompt_tokens,
|
|
211
|
+
completion_tokens = rotator_daily_spend.completion_tokens + EXCLUDED.completion_tokens,
|
|
212
|
+
total_requests = rotator_daily_spend.total_requests + 1,
|
|
213
|
+
successful_requests = rotator_daily_spend.successful_requests + EXCLUDED.successful_requests,
|
|
214
|
+
failed_requests = rotator_daily_spend.failed_requests + EXCLUDED.failed_requests,
|
|
215
|
+
total_duration_ms = rotator_daily_spend.total_duration_ms + EXCLUDED.total_duration_ms`,
|
|
157
216
|
[
|
|
158
217
|
log.requestId,
|
|
159
218
|
log.apiKeyHash,
|
|
@@ -173,43 +232,21 @@ export async function flushSpendLogs(): Promise<void> {
|
|
|
173
232
|
JSON.stringify(log.metadata || {}),
|
|
174
233
|
log.requesterIp,
|
|
175
234
|
log.createdAt || new Date().toISOString(),
|
|
176
|
-
],
|
|
177
|
-
);
|
|
178
|
-
|
|
179
|
-
// 2. Upsert daily aggregation
|
|
180
|
-
const dateStr = log.startTime.slice(0, 10); // YYYY-MM-DD
|
|
181
|
-
const keyHashForDaily = log.apiKeyHash || DEFAULT_KEY_HASH_LABEL;
|
|
182
|
-
const isSuccess = log.status === "success" ? 1 : 0;
|
|
183
|
-
const isFail = log.status === "failure" ? 1 : 0;
|
|
184
|
-
|
|
185
|
-
await queryDb(
|
|
186
|
-
`INSERT INTO rotator_daily_spend (
|
|
187
|
-
api_key_hash, model, date, prompt_tokens, completion_tokens,
|
|
188
|
-
total_requests, successful_requests, failed_requests, total_duration_ms
|
|
189
|
-
) VALUES ($1, $2, $3, $4, $5, 1, $6, $7, $8)
|
|
190
|
-
ON CONFLICT (api_key_hash, model, date) DO UPDATE SET
|
|
191
|
-
prompt_tokens = rotator_daily_spend.prompt_tokens + EXCLUDED.prompt_tokens,
|
|
192
|
-
completion_tokens = rotator_daily_spend.completion_tokens + EXCLUDED.completion_tokens,
|
|
193
|
-
total_requests = rotator_daily_spend.total_requests + 1,
|
|
194
|
-
successful_requests = rotator_daily_spend.successful_requests + EXCLUDED.successful_requests,
|
|
195
|
-
failed_requests = rotator_daily_spend.failed_requests + EXCLUDED.failed_requests,
|
|
196
|
-
total_duration_ms = rotator_daily_spend.total_duration_ms + EXCLUDED.total_duration_ms`,
|
|
197
|
-
[
|
|
198
235
|
keyHashForDaily,
|
|
199
|
-
log.model,
|
|
200
236
|
dateStr,
|
|
201
|
-
log.promptTokens,
|
|
202
|
-
log.completionTokens,
|
|
203
237
|
isSuccess,
|
|
204
238
|
isFail,
|
|
205
|
-
log.durationMs,
|
|
206
239
|
],
|
|
207
240
|
);
|
|
241
|
+
|
|
242
|
+
lastProcessedIndex = i;
|
|
208
243
|
}
|
|
209
244
|
} catch (err) {
|
|
210
245
|
console.error("Failed to flush spend logs to database:", err);
|
|
211
|
-
// Put
|
|
212
|
-
|
|
246
|
+
// Put only uncommitted items back in queue and consistently enforce FIFO (keep newest, drop oldest)
|
|
247
|
+
const uncommitted = logsToFlush.slice(lastProcessedIndex + 1);
|
|
248
|
+
const combined = [...uncommitted, ...queue];
|
|
249
|
+
queue = combined.length > MAX_QUEUE_CAP ? combined.slice(-MAX_QUEUE_CAP) : combined;
|
|
213
250
|
} finally {
|
|
214
251
|
isFlushing = false;
|
|
215
252
|
}
|
package/src/virtual-keys.ts
CHANGED
|
@@ -15,9 +15,33 @@ interface CachedKey {
|
|
|
15
15
|
fetchedAt: number;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
const KEY_CACHE_MAX = 500;
|
|
18
19
|
const keyCache = new Map<string, CachedKey>(); // tokenHash -> CachedKey
|
|
19
20
|
let hasKeysCache: { value: boolean; fetchedAt: number } | null = null;
|
|
20
21
|
|
|
22
|
+
export function getKeyCacheSizeForTests(): number {
|
|
23
|
+
return keyCache.size;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function setCachedKey(tokenHash: string, entry: CachedKey): void {
|
|
27
|
+
const now = Date.now();
|
|
28
|
+
if (keyCache.size >= KEY_CACHE_MAX) {
|
|
29
|
+
// Prune expired entries first
|
|
30
|
+
for (const [k, v] of keyCache.entries()) {
|
|
31
|
+
if (now - v.fetchedAt >= CACHE_TTL_MS) {
|
|
32
|
+
keyCache.delete(k);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// If still at capacity, drop oldest entries (FIFO)
|
|
36
|
+
while (keyCache.size >= KEY_CACHE_MAX) {
|
|
37
|
+
const oldest = keyCache.keys().next();
|
|
38
|
+
if (oldest.done) break;
|
|
39
|
+
keyCache.delete(oldest.value);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
keyCache.set(tokenHash, entry);
|
|
43
|
+
}
|
|
44
|
+
|
|
21
45
|
// Debounced last_active updates to prevent DB write spam
|
|
22
46
|
const pendingLastActive = new Set<string>();
|
|
23
47
|
let lastActiveFlushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
@@ -130,7 +154,7 @@ export async function generateVirtualKey(params: {
|
|
|
130
154
|
);
|
|
131
155
|
|
|
132
156
|
const key = mapRowToVirtualKey(res.rows[0]);
|
|
133
|
-
|
|
157
|
+
setCachedKey(tokenHash, { key, fetchedAt: Date.now() });
|
|
134
158
|
hasKeysCache = { value: true, fetchedAt: Date.now() };
|
|
135
159
|
|
|
136
160
|
return { rawKey, key };
|
|
@@ -161,12 +185,12 @@ export async function lookupVirtualKey(
|
|
|
161
185
|
);
|
|
162
186
|
|
|
163
187
|
if (res.rows.length === 0) {
|
|
164
|
-
|
|
188
|
+
setCachedKey(tokenHash, { key: null, fetchedAt: now });
|
|
165
189
|
return null;
|
|
166
190
|
}
|
|
167
191
|
|
|
168
192
|
const key = mapRowToVirtualKey(res.rows[0]);
|
|
169
|
-
|
|
193
|
+
setCachedKey(tokenHash, { key, fetchedAt: now });
|
|
170
194
|
return key;
|
|
171
195
|
} catch (err) {
|
|
172
196
|
console.error("Failed to lookup virtual key:", err);
|
|
@@ -250,7 +274,7 @@ export async function updateVirtualKey(
|
|
|
250
274
|
if (res.rows.length === 0) return null;
|
|
251
275
|
|
|
252
276
|
const updated = mapRowToVirtualKey(res.rows[0]);
|
|
253
|
-
|
|
277
|
+
setCachedKey(tokenHash, { key: updated, fetchedAt: Date.now() });
|
|
254
278
|
return updated;
|
|
255
279
|
} catch (err) {
|
|
256
280
|
console.error("Failed to update virtual key:", err);
|