@jeffusion/bungee-core 6.16.1 → 6.17.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/dist/main.js +5700 -2198
- package/dist/observability-worker.js +3245 -1495
- package/dist/plugins/anthropic-request-sanitizer/index.js.map +2 -2
- package/dist/plugins/anthropic-tool-name-transformer/index.js.map +2 -2
- package/dist/plugins/chatgpt-oauth/index.js +37 -15
- package/dist/plugins/chatgpt-oauth/index.js.map +5 -5
- package/dist/plugins/codex-router/index.js +21 -3
- package/dist/plugins/codex-router/index.js.map +5 -5
- package/dist/plugins/deepseek-reasoning-fix/index.js.map +2 -2
- package/dist/plugins/key-access/index.js +1 -1
- package/dist/plugins/key-access/index.js.map +4 -4
- package/dist/plugins/key-access/ingress.js +1 -1
- package/dist/plugins/key-access/ingress.js.map +3 -3
- package/dist/plugins/key-rate-limit/index.js.map +2 -2
- package/dist/plugins/llm-protocol-adapter/control.js +1 -1
- package/dist/plugins/llm-protocol-adapter/control.js.map +3 -3
- package/dist/plugins/llm-protocol-adapter/index.js +1 -1
- package/dist/plugins/llm-protocol-adapter/index.js.map +5 -5
- package/dist/plugins/llm-tps/index.js.map +2 -2
- package/dist/plugins/model-mapping/index.js +1 -1
- package/dist/plugins/model-mapping/index.js.map +4 -4
- package/dist/plugins/models-dev/index.js.map +2 -2
- package/dist/plugins/request-logs/index.js +505 -118
- package/dist/plugins/request-logs/index.js.map +11 -10
- package/dist/plugins/request-logs/ingress.js +3 -23
- package/dist/plugins/request-logs/ingress.js.map +3 -3
- package/dist/plugins/request-logs/ui/RequestLogsPage.svelte +215 -130
- package/dist/plugins/signature-repair/index.js.map +2 -2
- package/dist/plugins/token-budget/index.js.map +2 -2
- package/dist/plugins/token-metering/index.js.map +2 -2
- package/dist/plugins/token-stats/control.js +257 -61
- package/dist/plugins/token-stats/control.js.map +7 -6
- package/dist/plugins/token-stats/index.js +271 -127
- package/dist/plugins/token-stats/index.js.map +8 -8
- package/dist/plugins/token-stats/manifest.json +2 -2
- package/dist/plugins/user-auth/index.js.map +2 -2
- package/package.json +3 -2
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
+
// plugins/token-stats/server/control.ts
|
|
3
|
+
import { SQLiteError } from "bun:sqlite";
|
|
4
|
+
|
|
2
5
|
// plugins/models-dev/contract.ts
|
|
3
6
|
var MODELS_DEV_SOURCE_URL = "https://models.dev/api.json";
|
|
4
7
|
var MODELS_DEV_CATALOG_SERVICE_ID = "models-dev.catalog.v1";
|
|
@@ -199,6 +202,40 @@ function tokenStatsWindow(range, asOfMs, timeZone = "UTC") {
|
|
|
199
202
|
const bucketStarts = Array.from({ length: days }, (_, i) => midnight(firstDay + i * 24 * HOUR));
|
|
200
203
|
return { startMs: bucketStarts[0], endMs: asOfMs, bucketMs: 24 * HOUR, bucketStarts, bucketEndMs: midnight(nextPeriod) };
|
|
201
204
|
}
|
|
205
|
+
// plugins/token-stats/server/pricing.ts
|
|
206
|
+
var TOKENS_PER_UNIT = 1e6;
|
|
207
|
+
function isNonNegativeInteger(value) {
|
|
208
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
209
|
+
}
|
|
210
|
+
function costOf(match, input) {
|
|
211
|
+
const inputTokens = input.inputTokens;
|
|
212
|
+
const outputTokens = input.outputTokens;
|
|
213
|
+
if (!isNonNegativeInteger(inputTokens) || !isNonNegativeInteger(outputTokens))
|
|
214
|
+
return null;
|
|
215
|
+
const cacheReads = input.cacheReadTokens ?? 0;
|
|
216
|
+
const cacheWrites = input.cacheWriteTokens ?? 0;
|
|
217
|
+
if (!isNonNegativeInteger(cacheReads) || !isNonNegativeInteger(cacheWrites) || cacheReads + cacheWrites > inputTokens)
|
|
218
|
+
return null;
|
|
219
|
+
let rates = match;
|
|
220
|
+
for (const tier of match.contextTiers ?? []) {
|
|
221
|
+
if (inputTokens < tier.minimumInputTokens)
|
|
222
|
+
break;
|
|
223
|
+
rates = tier;
|
|
224
|
+
}
|
|
225
|
+
const cacheRead = rates.cacheRead ?? match.cacheRead ?? rates.input;
|
|
226
|
+
const cacheWrite = rates.cacheWrite ?? match.cacheWrite ?? rates.input;
|
|
227
|
+
const baseInput = inputTokens - cacheReads - cacheWrites;
|
|
228
|
+
const total = baseInput * rates.input + outputTokens * rates.output + cacheReads * cacheRead + cacheWrites * cacheWrite;
|
|
229
|
+
const cost = total / TOKENS_PER_UNIT;
|
|
230
|
+
return Number.isFinite(cost) && cost >= 0 ? cost : null;
|
|
231
|
+
}
|
|
232
|
+
function costNanoUsdOf(cost) {
|
|
233
|
+
if (cost === null || !Number.isFinite(cost) || cost < 0)
|
|
234
|
+
return null;
|
|
235
|
+
const nano = Math.round(cost * 1e9);
|
|
236
|
+
return Number.isSafeInteger(nano) ? nano : null;
|
|
237
|
+
}
|
|
238
|
+
|
|
202
239
|
// plugins/token-stats/server/storage.ts
|
|
203
240
|
var TOKEN_STATS_METRICS = [
|
|
204
241
|
"inputTokens",
|
|
@@ -227,47 +264,122 @@ var TOKEN_STATS_METRICS = [
|
|
|
227
264
|
var TOKEN_STATS_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000;
|
|
228
265
|
var TOKEN_STATS_BUSY_TIMEOUT_MS = 5;
|
|
229
266
|
var EMPTY_METRICS = Object.fromEntries(TOKEN_STATS_METRICS.map((name) => [name, 0]));
|
|
267
|
+
var PRICEABLE_USAGE = `cost_usd IS NULL AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL AND model <> 'unknown'`;
|
|
230
268
|
|
|
231
269
|
class SQLiteTokenStatsMetering {
|
|
232
270
|
observation;
|
|
233
271
|
constructor(observation) {
|
|
234
272
|
this.observation = observation;
|
|
235
273
|
}
|
|
236
|
-
async recordAttempt(row) {
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
274
|
+
async recordAttempt(row, deadlineAt) {
|
|
275
|
+
row = { ...row };
|
|
276
|
+
let remainingMs;
|
|
277
|
+
if (deadlineAt === undefined) {
|
|
278
|
+
const directDeadline = performance.now() + 50;
|
|
279
|
+
remainingMs = () => directDeadline - performance.now();
|
|
280
|
+
} else {
|
|
281
|
+
if (!Number.isSafeInteger(deadlineAt))
|
|
282
|
+
throw new Error("invalid token-stats write deadline");
|
|
283
|
+
const budget = this.observation.writeBudgetMs?.(deadlineAt);
|
|
284
|
+
if (!budget)
|
|
285
|
+
throw new Error("token-stats write deadline clock unavailable");
|
|
286
|
+
remainingMs = budget;
|
|
287
|
+
}
|
|
288
|
+
const requireWriteBudget = () => {
|
|
289
|
+
if (remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS)
|
|
290
|
+
throw new Error("token-stats write deadline expired");
|
|
291
|
+
};
|
|
292
|
+
requireWriteBudget();
|
|
293
|
+
const maxAttempts = deadlineAt === undefined ? 8 : Infinity;
|
|
294
|
+
for (let attempt = 1;; attempt++) {
|
|
295
|
+
const busy = await this.observation.withDatabase((db) => {
|
|
296
|
+
validateTokenStatsAttempt(row);
|
|
297
|
+
const transaction = db.transaction(() => {
|
|
298
|
+
if (deadlineAt !== undefined)
|
|
299
|
+
requireWriteBudget();
|
|
300
|
+
db.query(`
|
|
301
|
+
INSERT OR IGNORE INTO token_stats_attempts (
|
|
302
|
+
attempt_id, request_id, finished_at_ms, route_id, upstream_id, provider, outcome, model, key_id,
|
|
303
|
+
input_tokens, output_tokens, input_source, output_source,
|
|
304
|
+
cache_read_tokens, cache_write_tokens, cost_usd, observation_incomplete
|
|
305
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
306
|
+
`).run(row.attempt_id, row.request_id, row.finished_at_ms, row.route_id, row.upstream_id, row.provider, row.outcome, row.model, row.key_id ?? null, row.input_tokens, row.output_tokens, row.input_source, row.output_source, row.cache_read_tokens, row.cache_write_tokens, row.cost_usd, row.observation_incomplete ? 1 : 0);
|
|
307
|
+
db.query(`
|
|
308
|
+
DELETE FROM token_stats_attempts WHERE attempt_id IN (
|
|
309
|
+
SELECT attempt_id FROM token_stats_attempts INDEXED BY idx_token_stats_attempts_finished
|
|
310
|
+
WHERE finished_at_ms < ? ORDER BY finished_at_ms LIMIT 500
|
|
311
|
+
)
|
|
312
|
+
`).run(Date.now() - TOKEN_STATS_RETENTION_MS);
|
|
313
|
+
if (deadlineAt !== undefined)
|
|
314
|
+
requireWriteBudget();
|
|
315
|
+
});
|
|
316
|
+
return withReportingWriteTimeout(db, () => {
|
|
317
|
+
try {
|
|
318
|
+
transaction.immediate();
|
|
319
|
+
} catch (error) {
|
|
320
|
+
if (error instanceof Error && error.name === "SQLiteError" && "code" in error && error.code === "SQLITE_BUSY" && db.inTransaction === false)
|
|
321
|
+
return error;
|
|
322
|
+
throw error;
|
|
323
|
+
}
|
|
324
|
+
});
|
|
253
325
|
});
|
|
254
|
-
|
|
255
|
-
|
|
326
|
+
if (!busy)
|
|
327
|
+
return;
|
|
328
|
+
if (attempt === maxAttempts || remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS)
|
|
329
|
+
throw busy;
|
|
330
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
331
|
+
if (remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS)
|
|
332
|
+
throw busy;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
async queryPricingModels(input) {
|
|
336
|
+
const window = queryBounds(input);
|
|
337
|
+
return this.observation.withDatabase((db) => db.transaction(() => {
|
|
338
|
+
const { throughRow } = db.query("SELECT COALESCE(MAX(rowid), 0) AS throughRow FROM token_stats_attempts").get();
|
|
339
|
+
const { index, where, params } = attemptWindow({ ...window, throughRow });
|
|
340
|
+
const rows = db.query(`
|
|
341
|
+
SELECT DISTINCT model FROM token_stats_attempts INDEXED BY ${index}
|
|
342
|
+
WHERE ${where} AND ${PRICEABLE_USAGE}
|
|
343
|
+
`).all(...params);
|
|
344
|
+
return { models: rows.map((row) => row.model), throughRow };
|
|
345
|
+
}).deferred());
|
|
256
346
|
}
|
|
257
347
|
async queryWindowSnapshot(input) {
|
|
348
|
+
const window = queryBounds(input);
|
|
349
|
+
const { bucketMs, bucketStarts, bucketEndMs } = window;
|
|
350
|
+
const pricing = input.pricing;
|
|
351
|
+
const { sql, params, missingSql } = buildTokenStatsWindowSnapshotQuery({ ...window, throughRow: pricing?.throughRow });
|
|
258
352
|
return this.observation.withDatabase((db) => {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
353
|
+
const read = () => {
|
|
354
|
+
const rows = db.query(sql).all(...params);
|
|
355
|
+
if (!pricing?.prices.length)
|
|
356
|
+
return rows;
|
|
357
|
+
const prices = new Map(pricing.prices);
|
|
358
|
+
const missing = db.query(missingSql).iterate(...params, JSON.stringify([...prices.keys()]));
|
|
359
|
+
const byGroup = new Map;
|
|
360
|
+
let total;
|
|
361
|
+
for (const row of missing) {
|
|
362
|
+
const nano = costNanoUsdOf(costOf(prices.get(row.model), {
|
|
363
|
+
inputTokens: row.input_tokens ?? undefined,
|
|
364
|
+
outputTokens: row.output_tokens ?? undefined,
|
|
365
|
+
cacheReadTokens: row.cache_read_tokens ?? undefined,
|
|
366
|
+
cacheWriteTokens: row.cache_write_tokens ?? undefined
|
|
367
|
+
}));
|
|
368
|
+
if (nano === null)
|
|
369
|
+
continue;
|
|
370
|
+
const cost = nano / 1e9;
|
|
371
|
+
total = (total ?? 0) + cost;
|
|
372
|
+
const key = JSON.stringify([row.model, row.bucketStartMs]);
|
|
373
|
+
byGroup.set(key, (byGroup.get(key) ?? 0) + cost);
|
|
374
|
+
}
|
|
375
|
+
for (const row of rows) {
|
|
376
|
+
const extra = row.kind === "all" ? total : byGroup.get(JSON.stringify([row.dimension, row.bucketStartMs]));
|
|
377
|
+
if (extra !== undefined)
|
|
378
|
+
row.estimatedCostUsd = Number(row.estimatedCostUsd ?? 0) + extra;
|
|
379
|
+
}
|
|
380
|
+
return rows;
|
|
381
|
+
};
|
|
382
|
+
const rows = pricing?.prices.length ? db.transaction(read).deferred() : read();
|
|
271
383
|
const allRow = rows.find((row) => row.kind === "all");
|
|
272
384
|
const dataRows = rows.filter((row) => row.kind === "data");
|
|
273
385
|
const metrics = (row) => {
|
|
@@ -313,6 +425,36 @@ class SQLiteTokenStatsMetering {
|
|
|
313
425
|
});
|
|
314
426
|
}
|
|
315
427
|
}
|
|
428
|
+
function queryBounds(input) {
|
|
429
|
+
validateTokenStatsTimestamp(input.asOfMs, "asOfMs");
|
|
430
|
+
if (!TOKEN_STATS_RANGES.includes(input.range))
|
|
431
|
+
throw new Error("invalid token-stats range");
|
|
432
|
+
if (!["model", "time"].includes(input.groupBy))
|
|
433
|
+
throw new Error("invalid token-stats groupBy");
|
|
434
|
+
const window = tokenStatsWindow(input.range, input.asOfMs, input.timeZone);
|
|
435
|
+
return {
|
|
436
|
+
...window,
|
|
437
|
+
startMs: Math.max(window.startMs, Date.now() - TOKEN_STATS_RETENTION_MS),
|
|
438
|
+
groupBy: input.groupBy,
|
|
439
|
+
bucketMs: input.groupBy === "time" ? window.bucketMs : undefined,
|
|
440
|
+
bucketStarts: input.groupBy === "time" ? window.bucketStarts : undefined,
|
|
441
|
+
bucketEndMs: input.groupBy === "time" ? window.bucketEndMs : undefined,
|
|
442
|
+
keyId: input.keyId
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
function attemptWindow(input) {
|
|
446
|
+
const { startMs, endMs, keyId, throughRow } = input;
|
|
447
|
+
if (keyId !== undefined && (typeof keyId !== "string" || !keyId || keyId.length > 128))
|
|
448
|
+
throw new Error("invalid token-stats keyId");
|
|
449
|
+
if (throughRow !== undefined && (!Number.isSafeInteger(throughRow) || throughRow < 0))
|
|
450
|
+
throw new Error("invalid token-stats row boundary");
|
|
451
|
+
const keyFilter = keyId === undefined ? "" : keyId === "__unattributed__" ? " AND key_id IS NULL" : " AND key_id = ?";
|
|
452
|
+
return {
|
|
453
|
+
index: keyId === undefined ? "idx_token_stats_attempts_finished" : "idx_token_stats_attempts_key_finished",
|
|
454
|
+
where: `finished_at_ms >= ? AND finished_at_ms < ?${keyFilter}${throughRow === undefined ? "" : " AND rowid <= ?"}`,
|
|
455
|
+
params: [startMs, endMs, ...keyId !== undefined && keyId !== "__unattributed__" ? [keyId] : [], ...throughRow === undefined ? [] : [throughRow]]
|
|
456
|
+
};
|
|
457
|
+
}
|
|
316
458
|
function buildTokenStatsWindowSnapshotQuery(input) {
|
|
317
459
|
const metrics = (alias) => `
|
|
318
460
|
COALESCE(SUM(CASE WHEN ${alias}.input_source = 'usage' THEN ${alias}.input_tokens ELSE 0 END), 0) AS officialInputTokens,
|
|
@@ -340,10 +482,7 @@ function buildTokenStatsWindowSnapshotQuery(input) {
|
|
|
340
482
|
if (input.bucketStarts && (!input.bucketStarts.length || input.bucketStarts.length > 31 || input.bucketStarts.some((start, i, starts) => !Number.isSafeInteger(start) || start < 0 || i > 0 && start <= starts[i - 1]))) {
|
|
341
483
|
throw new Error("invalid token-stats bucketStarts");
|
|
342
484
|
}
|
|
343
|
-
|
|
344
|
-
throw new Error("invalid token-stats keyId");
|
|
345
|
-
const keyFilter = input.keyId === undefined ? "" : input.keyId === "__unattributed__" ? " AND key_id IS NULL" : " AND key_id = ?";
|
|
346
|
-
const index = input.keyId === undefined ? "idx_token_stats_attempts_finished" : "idx_token_stats_attempts_key_finished";
|
|
485
|
+
const { index, where, params } = attemptWindow(input);
|
|
347
486
|
const origin = input.bucketStarts?.[0] ?? 0;
|
|
348
487
|
const uniform = !input.bucketStarts || input.bucketStarts.every((start, i) => start === origin + i * input.bucketMs);
|
|
349
488
|
const bucketStart = input.groupBy !== "time" ? "NULL" : uniform ? `CAST((attempt.finished_at_ms - ${origin}) / ${input.bucketMs} AS INTEGER) * ${input.bucketMs} + ${origin}` : `CASE ${[...input.bucketStarts].reverse().map((start) => `WHEN attempt.finished_at_ms >= ${start} THEN ${start}`).join(" ")} END`;
|
|
@@ -356,14 +495,19 @@ function buildTokenStatsWindowSnapshotQuery(input) {
|
|
|
356
495
|
sql: `
|
|
357
496
|
WITH window_rows AS MATERIALIZED (
|
|
358
497
|
SELECT * FROM token_stats_attempts INDEXED BY ${index}
|
|
359
|
-
WHERE
|
|
498
|
+
WHERE ${where}
|
|
360
499
|
)
|
|
361
500
|
SELECT 'all' AS kind, 'all' AS dimension, NULL AS bucketStartMs, ${metrics("attempt")}, (COUNT(*) > 0) AS present
|
|
362
501
|
FROM window_rows AS attempt
|
|
363
502
|
${grouped}
|
|
364
503
|
ORDER BY kind, bucketStartMs, dimension
|
|
365
504
|
`,
|
|
366
|
-
|
|
505
|
+
missingSql: `
|
|
506
|
+
SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, ${bucketStart} AS bucketStartMs
|
|
507
|
+
FROM token_stats_attempts AS attempt INDEXED BY ${index}
|
|
508
|
+
WHERE ${where} AND ${PRICEABLE_USAGE} AND model IN (SELECT value FROM json_each(?))
|
|
509
|
+
`,
|
|
510
|
+
params
|
|
367
511
|
};
|
|
368
512
|
}
|
|
369
513
|
function validateTokenStatsAttempt(row) {
|
|
@@ -472,13 +616,29 @@ var pendingCount = 0;
|
|
|
472
616
|
var drainTimer;
|
|
473
617
|
var draining = false;
|
|
474
618
|
var lastDropLogAt = 0;
|
|
475
|
-
var lastFailureLogAt =
|
|
476
|
-
function
|
|
619
|
+
var lastFailureLogAt = new Map;
|
|
620
|
+
function failureCode(error) {
|
|
621
|
+
if (error instanceof DOMException && error.name === "TimeoutError")
|
|
622
|
+
return "rpc_timeout";
|
|
623
|
+
if (error instanceof Error && error.name === "DataAdmissionError" && "code" in error) {
|
|
624
|
+
switch (error.code) {
|
|
625
|
+
case "invalid_worker_rpc":
|
|
626
|
+
case "worker_not_admitted":
|
|
627
|
+
case "rpc_busy":
|
|
628
|
+
case "rpc_capacity":
|
|
629
|
+
return error.code;
|
|
630
|
+
default:
|
|
631
|
+
return "rpc_rejected";
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return "unclassified";
|
|
635
|
+
}
|
|
636
|
+
function logRateLimited(logger, stage, error) {
|
|
477
637
|
try {
|
|
478
638
|
logger.onFailure?.();
|
|
479
639
|
} catch {}
|
|
480
640
|
const now = Date.now();
|
|
481
|
-
if (
|
|
641
|
+
if (stage === "drop") {
|
|
482
642
|
if (now - lastDropLogAt < LOG_INTERVAL_MS)
|
|
483
643
|
return;
|
|
484
644
|
lastDropLogAt = now;
|
|
@@ -487,13 +647,12 @@ function logRateLimited(logger, kind, error) {
|
|
|
487
647
|
} catch {}
|
|
488
648
|
return;
|
|
489
649
|
}
|
|
490
|
-
if (now - lastFailureLogAt < LOG_INTERVAL_MS)
|
|
491
|
-
return;
|
|
492
|
-
lastFailureLogAt = now;
|
|
493
650
|
try {
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
651
|
+
const failure = `${stage}/${failureCode(error)}`;
|
|
652
|
+
if (now - (lastFailureLogAt.get(failure) ?? 0) < LOG_INTERVAL_MS)
|
|
653
|
+
return;
|
|
654
|
+
lastFailureLogAt.set(failure, now);
|
|
655
|
+
logger.error(`Token stats attempt processing failed; dropping metering row [${failure}]`);
|
|
497
656
|
} catch {}
|
|
498
657
|
}
|
|
499
658
|
function scheduleDrain() {
|
|
@@ -511,17 +670,15 @@ async function drainOneAttempt() {
|
|
|
511
670
|
if (!item)
|
|
512
671
|
return;
|
|
513
672
|
draining = true;
|
|
673
|
+
let stage = "prepare";
|
|
514
674
|
try {
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
} catch (error) {
|
|
523
|
-
logRateLimited(item.logger, "failure", error);
|
|
524
|
-
}
|
|
675
|
+
const row = await item.task();
|
|
676
|
+
if (row === undefined)
|
|
677
|
+
return logRateLimited(item.logger, "missing_row");
|
|
678
|
+
stage = "write";
|
|
679
|
+
await item.metering.recordAttempt(row);
|
|
680
|
+
} catch (error) {
|
|
681
|
+
logRateLimited(item.logger, stage, error);
|
|
525
682
|
} finally {
|
|
526
683
|
pendingCount--;
|
|
527
684
|
draining = false;
|
|
@@ -575,7 +732,7 @@ class TokenStatsRepository {
|
|
|
575
732
|
scheduleDrain();
|
|
576
733
|
return true;
|
|
577
734
|
}
|
|
578
|
-
async query(range, groupBy, asOfMs = Date.now(), timeZone, keyId) {
|
|
735
|
+
async query(range, groupBy, asOfMs = Date.now(), timeZone, keyId, catalog) {
|
|
579
736
|
if (!TOKEN_STATS_RANGES.includes(range))
|
|
580
737
|
throw new TokenStatsRepositoryError("invalid token-stats range");
|
|
581
738
|
if (groupBy !== "model" && groupBy !== "time") {
|
|
@@ -583,7 +740,26 @@ class TokenStatsRepository {
|
|
|
583
740
|
}
|
|
584
741
|
if (!Number.isSafeInteger(asOfMs) || asOfMs < 0)
|
|
585
742
|
throw new TokenStatsRepositoryError("invalid token-stats asOfMs");
|
|
586
|
-
const
|
|
743
|
+
const window = { asOfMs, range, groupBy, timeZone, keyId };
|
|
744
|
+
let input = window;
|
|
745
|
+
if (catalog && this.metering.queryPricingModels) {
|
|
746
|
+
const mappings = await this.mappings().catch(() => {
|
|
747
|
+
return;
|
|
748
|
+
});
|
|
749
|
+
if (mappings) {
|
|
750
|
+
const { models, throughRow } = await this.metering.queryPricingModels(window);
|
|
751
|
+
const bySource = new Map(mappings.map((mapping) => [mapping.source, mapping]));
|
|
752
|
+
const prices = [];
|
|
753
|
+
for (const model of models) {
|
|
754
|
+
const mapped = bySource.get(model);
|
|
755
|
+
const price = catalog.resolveModel(mapped ? { model: mapped.model, pricingProvider: mapped.provider } : { model });
|
|
756
|
+
if (price !== null)
|
|
757
|
+
prices.push([model, price]);
|
|
758
|
+
}
|
|
759
|
+
input = { ...window, pricing: { throughRow, prices } };
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
const snapshot = await this.metering.queryWindowSnapshot(input);
|
|
587
763
|
const total = metricsToDto(snapshot.all);
|
|
588
764
|
const { inputTokens, outputTokens, ...summary } = total;
|
|
589
765
|
return {
|
|
@@ -815,7 +991,11 @@ class TokenStatsControl {
|
|
|
815
991
|
}
|
|
816
992
|
const range = rawRange ?? "24h";
|
|
817
993
|
const groupBy = rawGroupBy ?? "model";
|
|
818
|
-
|
|
994
|
+
let catalog;
|
|
995
|
+
try {
|
|
996
|
+
catalog = this.catalogService();
|
|
997
|
+
} catch {}
|
|
998
|
+
const payload = await abortable(this.repository.query(range, groupBy, Date.now(), timeZone, keyId, catalog), context.requestSignal, context.signal);
|
|
819
999
|
this.assertAlive(context.requestSignal);
|
|
820
1000
|
const maxBytes = ["1h", "12h", "24h"].includes(range) ? MAX_RESPONSE_BYTES : MAX_PAGE_STATS_RESPONSE_BYTES;
|
|
821
1001
|
return jsonResponse(payload, 200, maxBytes);
|
|
@@ -910,9 +1090,25 @@ function createControl(context) {
|
|
|
910
1090
|
var control_default = { supportsOnlinePreparation: true, createControl };
|
|
911
1091
|
function createObservationAdapter(observation) {
|
|
912
1092
|
const leaf = new SQLiteTokenStatsMetering(observation);
|
|
1093
|
+
let nextWriteFailureLogAt = 0;
|
|
913
1094
|
return Object.freeze({
|
|
914
|
-
|
|
1095
|
+
async recordAttempt(row, deadlineAt) {
|
|
1096
|
+
try {
|
|
1097
|
+
await leaf.recordAttempt(row, deadlineAt);
|
|
1098
|
+
} catch (error) {
|
|
1099
|
+
const now = Date.now();
|
|
1100
|
+
if (now >= nextWriteFailureLogAt) {
|
|
1101
|
+
nextWriteFailureLogAt = now + 60000;
|
|
1102
|
+
try {
|
|
1103
|
+
const requestId = typeof row?.request_id === "string" && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(row.request_id) ? row.request_id : undefined;
|
|
1104
|
+
logger.error({ requestId, sqliteErrno: error instanceof SQLiteError ? error.errno : undefined }, "Token stats observation write failed");
|
|
1105
|
+
} catch {}
|
|
1106
|
+
}
|
|
1107
|
+
throw error;
|
|
1108
|
+
}
|
|
1109
|
+
},
|
|
915
1110
|
queryWindowSnapshot: leaf.queryWindowSnapshot.bind(leaf),
|
|
1111
|
+
queryPricingModels: leaf.queryPricingModels.bind(leaf),
|
|
916
1112
|
listClientModels: leaf.listClientModels.bind(leaf)
|
|
917
1113
|
});
|
|
918
1114
|
}
|
|
@@ -922,4 +1118,4 @@ export {
|
|
|
922
1118
|
control_default as default
|
|
923
1119
|
};
|
|
924
1120
|
|
|
925
|
-
//# debugId=
|
|
1121
|
+
//# debugId=EA92F7EB842DE65764756E2164756E21
|