1087 lines
38 KiB
JavaScript
1087 lines
38 KiB
JavaScript
import { chmod, mkdir } from 'node:fs/promises';
|
|
import { homedir } from 'node:os';
|
|
import { dirname, join, resolve } from 'node:path';
|
|
|
|
/** Host half of the cost/balance footer bundle.
|
|
*
|
|
* Serves the connected third-party operator's wallet balance and the spend
|
|
* counter it reports to the Client half over a same-origin route. The operator
|
|
* API key is resolved here, on the Host, through the credentials seam, so no
|
|
* secret ever reaches the browser.
|
|
*/
|
|
const PROVIDERS = {
|
|
openrusrouter: {
|
|
balanceUrl: 'https://openrusrouter.ru/v1/auth/key',
|
|
apiKeyEnv: 'OPENRUSROUTER_API_KEY',
|
|
/* OpenRusRouter bills this wallet in rubles, whatever currency field the
|
|
* gateway echoes (or omits); the configured symbol is authoritative. */
|
|
symbol: '₽',
|
|
displayName: 'OpenRusRouter',
|
|
},
|
|
};
|
|
|
|
/**
|
|
* Daily central-bank rates, cached in the database.
|
|
*
|
|
* DeepSeek wallets bill in dollars or yuan while the operator wallet and the
|
|
* user's budgets are in rubles, so the statistics need a ruble value for the
|
|
* foreign spend. The Central Bank publishes once per business day; the cache
|
|
* is refreshed at most once a day, and a network failure keeps the last known
|
|
* rates instead of blanking the totals.
|
|
*/
|
|
const FX_URL = 'https://www.cbr-xml-daily.ru/daily_json.js';
|
|
const FX_TTL_MS = 24 * 3_600_000;
|
|
const FX_CODES = ['USD', 'CNY', 'EUR'];
|
|
const FX_TIMEOUT_MS = 10_000;
|
|
|
|
/** One JSON response with no caching. */
|
|
function json(status, body) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
});
|
|
}
|
|
|
|
/** Resolve one credential reference to its secret, or undefined. */
|
|
async function resolveCredential(ctx, name) {
|
|
try {
|
|
const credentials = ctx.get('credentials');
|
|
const hit = await credentials?.resolve(name);
|
|
const value = hit?.value;
|
|
if (typeof value === 'string' && value.length > 0) return value;
|
|
} catch {
|
|
/* fall through to the launch environment */
|
|
}
|
|
const fromEnv = process.env[name];
|
|
return typeof fromEnv === 'string' && fromEnv.length > 0 ? fromEnv : undefined;
|
|
}
|
|
|
|
function numeric(value) {
|
|
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
if (typeof value === 'string' && value.trim() !== '') {
|
|
const parsed = Number(value);
|
|
if (Number.isFinite(parsed)) return parsed;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function atPath(value, path) {
|
|
let current = value;
|
|
for (const key of path.split('.')) {
|
|
if (current === null || typeof current !== 'object') return undefined;
|
|
current = current[key];
|
|
}
|
|
return current;
|
|
}
|
|
|
|
/** First finite number among the given payload paths. */
|
|
function firstNumber(payload, paths) {
|
|
for (const path of paths) {
|
|
const amount = numeric(atPath(payload, path));
|
|
if (amount !== undefined) return amount;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Remainder and spend counters of one balance payload.
|
|
*
|
|
* OpenRouter-compatible gateways (OpenRusRouter among them) answer with every
|
|
* amount as a string and separate three numbers that are easy to mistake for
|
|
* one another:
|
|
*
|
|
* - `account_balance` — the whole wallet. It moves only when money is really
|
|
* spent or added, so it is the remainder a "Balance" reading should show;
|
|
* - `balance` / `limit_remaining` — what the key may still spend, i.e. the
|
|
* minimum of the wallet and the key's remaining limit. Editing the key's
|
|
* limit in the billing cabinet changes it without a single request being
|
|
* billed, which is why measuring spending by its fall booked the limit edit
|
|
* as a purchase;
|
|
* - `usage` — what the key has already spent in the current window, reported
|
|
* as measured. Only billed requests move it.
|
|
*
|
|
* The reading therefore shows the wallet as `amount` and hands `used` plus the
|
|
* identity of its window to the Client half, whose ledger books spending from
|
|
* that counter. Gateways without a wallet field keep the older shapes, and the
|
|
* counter stays absent so the ledger falls back to a whole-balance delta
|
|
* instead of the capped one.
|
|
*/
|
|
function extractReading(payload) {
|
|
const wallet = firstNumber(payload, ['data.account_balance', 'account_balance']);
|
|
const limit = firstNumber(payload, ['data.limit', 'limit']);
|
|
const limitRemaining = firstNumber(payload, ['data.limit_remaining', 'limit_remaining']);
|
|
const usage = firstNumber(payload, ['data.usage', 'usage']);
|
|
|
|
let amount;
|
|
let source;
|
|
if (wallet !== undefined) {
|
|
amount = wallet;
|
|
source = 'account-balance';
|
|
} else if (limitRemaining !== undefined) {
|
|
amount = limitRemaining;
|
|
source = 'limit-remaining';
|
|
} else {
|
|
amount = firstNumber(payload, [
|
|
'data.remaining',
|
|
'remaining',
|
|
'data.total_remaining',
|
|
'data.balance',
|
|
'balance',
|
|
'data.credits_remaining',
|
|
'credits_remaining',
|
|
'data.credits',
|
|
'credits',
|
|
]);
|
|
source = 'balance';
|
|
}
|
|
if (amount === undefined) {
|
|
if (limit === undefined || usage === undefined) return undefined;
|
|
amount = limit - usage;
|
|
source = 'limit-usage';
|
|
}
|
|
|
|
/* `usage` counts money only on a payload that reports money for this key; a
|
|
* bare token counter must not become a spend meter. */
|
|
const moneyShaped = wallet !== undefined || limitRemaining !== undefined || limit !== undefined;
|
|
const window = atPath(payload, 'data.limit_window') ?? atPath(payload, 'limit_window');
|
|
const resetsAt = atPath(payload, 'data.limit_resets_at') ?? atPath(payload, 'limit_resets_at');
|
|
return {
|
|
amount,
|
|
source,
|
|
wallet,
|
|
limit,
|
|
used: moneyShaped ? usage : undefined,
|
|
window: typeof window === 'string' ? window : undefined,
|
|
resetsAt: typeof resetsAt === 'string' ? resetsAt : undefined,
|
|
};
|
|
}
|
|
|
|
/** Currency symbol announced by the payload, else the configured one. */
|
|
function extractSymbol(payload, fallback) {
|
|
const currency =
|
|
atPath(payload, 'data.currency') ??
|
|
atPath(payload, 'currency') ??
|
|
atPath(payload, 'data.wallet.currency');
|
|
if (typeof currency === 'string') {
|
|
const upper = currency.toUpperCase();
|
|
if (upper === 'USD') return '$';
|
|
if (upper === 'CNY') return '¥';
|
|
if (upper === 'RUB') return '₽';
|
|
}
|
|
return fallback;
|
|
}
|
|
|
|
async function handleBalance(ctx, request) {
|
|
const provider = new URL(request.url).searchParams.get('provider') ?? '';
|
|
const target = PROVIDERS[provider];
|
|
if (target === undefined) return json(200, { ok: false, reason: 'unknown-provider' });
|
|
const key = await resolveCredential(ctx, target.apiKeyEnv);
|
|
if (key === undefined) {
|
|
return json(200, { ok: false, reason: 'missing-credential', provider });
|
|
}
|
|
let response;
|
|
try {
|
|
response = await fetch(target.balanceUrl, {
|
|
headers: { authorization: `Bearer ${key}`, accept: 'application/json' },
|
|
signal: AbortSignal.timeout(15000),
|
|
});
|
|
} catch {
|
|
return json(200, { ok: false, reason: 'network', provider });
|
|
}
|
|
if (!response.ok) {
|
|
return json(200, { ok: false, reason: 'http-error', provider, status: response.status });
|
|
}
|
|
let payload;
|
|
try {
|
|
payload = await response.json();
|
|
} catch {
|
|
return json(200, { ok: false, reason: 'bad-payload', provider });
|
|
}
|
|
const extracted = extractReading(payload);
|
|
if (extracted === undefined) {
|
|
const data = payload !== null && typeof payload === 'object' ? payload.data : undefined;
|
|
const fields =
|
|
data !== null && typeof data === 'object'
|
|
? Object.keys(data)
|
|
: payload !== null && typeof payload === 'object'
|
|
? Object.keys(payload)
|
|
: [];
|
|
return json(200, { ok: false, reason: 'unknown-shape', provider, fields });
|
|
}
|
|
return json(200, {
|
|
ok: true,
|
|
provider,
|
|
displayName: target.displayName ?? provider,
|
|
amount: extracted.amount,
|
|
symbol: target.symbol ?? extractSymbol(payload, '$'),
|
|
source: extracted.source,
|
|
/* The spend meter the Client half books from, with the identity of the
|
|
* window it belongs to; all absent for a gateway that reports none. */
|
|
wallet: extracted.wallet,
|
|
used: extracted.used,
|
|
limit: extracted.limit,
|
|
window: extracted.window,
|
|
resetsAt: extracted.resetsAt,
|
|
});
|
|
}
|
|
|
|
/* ------------------------------------------------------------------------- */
|
|
/* Spending history: SQLite */
|
|
/* ------------------------------------------------------------------------- */
|
|
|
|
/**
|
|
* The Client half keeps its spending ledger here instead of the browser's
|
|
* `localStorage`: the history then survives a cache wipe, belongs to the
|
|
* machine rather than to one browser profile, and is shared by every window.
|
|
*
|
|
* The schema is normalized and versioned with `PRAGMA user_version`; the file
|
|
* carries `PRAGMA application_id`, so an unrelated database that happens to sit
|
|
* at the same path is refused instead of adopted.
|
|
*/
|
|
const DB_ENV = 'DSH_COST_BALANCE_DB';
|
|
const DB_FILE_NAME = 'cost-balance.sqlite';
|
|
const DB_APPLICATION_ID = 0x43425350; /* "CBSP" */
|
|
const DB_SCHEMA_VERSION = 4;
|
|
const STATE_VERSION = 1;
|
|
const MAX_HOUR_BUCKETS = 10_000;
|
|
const MAX_SAMPLES = 64;
|
|
const MAX_LIMIT_OWNERS = 8;
|
|
const MAX_TOKEN_MODELS = 16;
|
|
const MAX_BODY_BYTES = 4 * 1024 * 1024;
|
|
const CURRENCY_PATTERN = /^[A-Z]{3}$/;
|
|
/** Limit owners are provider ids: `openrusrouter`, `deepseek`. */
|
|
const LIMIT_OWNER_PATTERN = /^[a-z0-9-]{1,32}$/;
|
|
|
|
const DB_SCHEMA = `
|
|
CREATE TABLE IF NOT EXISTS spend_meta (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS spend_hours (
|
|
hour INTEGER NOT NULL,
|
|
currency TEXT NOT NULL,
|
|
amount REAL NOT NULL,
|
|
PRIMARY KEY (hour, currency)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS spend_samples (
|
|
provider TEXT PRIMARY KEY,
|
|
currency TEXT NOT NULL,
|
|
observed_at INTEGER NOT NULL,
|
|
amount REAL,
|
|
wallet REAL,
|
|
used REAL,
|
|
cap REAL,
|
|
reset_window TEXT,
|
|
reset_at TEXT
|
|
);
|
|
CREATE TABLE IF NOT EXISTS spend_limits (
|
|
owner TEXT PRIMARY KEY,
|
|
currency TEXT NOT NULL,
|
|
day REAL NOT NULL DEFAULT 0,
|
|
week REAL NOT NULL DEFAULT 0,
|
|
month REAL NOT NULL DEFAULT 0
|
|
);
|
|
CREATE TABLE IF NOT EXISTS usage_hours (
|
|
hour INTEGER NOT NULL,
|
|
model TEXT NOT NULL,
|
|
miss REAL NOT NULL DEFAULT 0,
|
|
cache_write REAL NOT NULL DEFAULT 0,
|
|
cache_read REAL NOT NULL DEFAULT 0,
|
|
output REAL NOT NULL DEFAULT 0,
|
|
PRIMARY KEY (hour, model)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS fx_rates (
|
|
code TEXT PRIMARY KEY,
|
|
rate REAL NOT NULL,
|
|
rate_date TEXT NOT NULL,
|
|
fetched_at INTEGER NOT NULL
|
|
);
|
|
`;
|
|
|
|
/** Ledger document shape shared with the Client half. */
|
|
function emptyState() {
|
|
return { version: STATE_VERSION, currency: 'RUB', hours: {}, samples: {}, limits: {}, tokens: {} };
|
|
}
|
|
|
|
/** Token counts are non-negative integers; anything else reads as zero. */
|
|
function tokenCount(value) {
|
|
const parsed = numeric(value);
|
|
return parsed !== undefined && parsed > 0 ? parsed : 0;
|
|
}
|
|
|
|
/**
|
|
* Clamp one ledger document to the shape the database stores.
|
|
*
|
|
* The route is loopback and same-origin, but the Client half is replaceable, so
|
|
* the Host never trusts the document: unknown fields are dropped, sizes are
|
|
* bounded, and only finite numbers reach SQLite.
|
|
*/
|
|
function normalizeState(value) {
|
|
const state = emptyState();
|
|
if (value === null || typeof value !== 'object') return state;
|
|
if (typeof value.currency === 'string' && CURRENCY_PATTERN.test(value.currency)) {
|
|
state.currency = value.currency;
|
|
}
|
|
if (value.hours !== null && typeof value.hours === 'object') {
|
|
let buckets = 0;
|
|
for (const [key, bucket] of Object.entries(value.hours)) {
|
|
if (buckets >= MAX_HOUR_BUCKETS) break;
|
|
const hour = numeric(key);
|
|
if (hour === undefined || !Number.isSafeInteger(hour) || hour < 0) continue;
|
|
if (bucket === null || typeof bucket !== 'object') continue;
|
|
const amounts = {};
|
|
for (const [currency, amount] of Object.entries(bucket)) {
|
|
const parsed = numeric(amount);
|
|
if (!CURRENCY_PATTERN.test(currency) || parsed === undefined || parsed === 0) continue;
|
|
amounts[currency] = parsed;
|
|
}
|
|
if (Object.keys(amounts).length === 0) continue;
|
|
state.hours[String(hour)] = amounts;
|
|
buckets += 1;
|
|
}
|
|
}
|
|
if (value.samples !== null && typeof value.samples === 'object') {
|
|
let count = 0;
|
|
for (const [provider, sample] of Object.entries(value.samples)) {
|
|
if (count >= MAX_SAMPLES) break;
|
|
if (typeof provider !== 'string' || provider === '' || provider.length > 64) continue;
|
|
if (sample === null || typeof sample !== 'object') continue;
|
|
const at = numeric(sample.at);
|
|
if (at === undefined) continue;
|
|
const entry = { currency: state.currency, at };
|
|
if (typeof sample.currency === 'string' && CURRENCY_PATTERN.test(sample.currency)) {
|
|
entry.currency = sample.currency;
|
|
}
|
|
for (const key of ['amount', 'wallet', 'used', 'cap']) {
|
|
const parsed = numeric(sample[key]);
|
|
if (parsed !== undefined) entry[key] = parsed;
|
|
}
|
|
if (typeof sample.window === 'string' && sample.window !== '' && sample.window.length <= 16) {
|
|
entry.window = sample.window;
|
|
}
|
|
if (typeof sample.resetsAt === 'string' && sample.resetsAt !== '' && sample.resetsAt.length <= 64) {
|
|
entry.resetsAt = sample.resetsAt;
|
|
}
|
|
state.samples[provider] = entry;
|
|
count += 1;
|
|
}
|
|
}
|
|
if (value.limits !== null && typeof value.limits === 'object') {
|
|
let owners = 0;
|
|
for (const [key, limits] of Object.entries(value.limits)) {
|
|
if (owners >= MAX_LIMIT_OWNERS) break;
|
|
if (limits === null || typeof limits !== 'object') continue;
|
|
/* Older clients still key limits by wallet currency; map those onto the
|
|
* provider that owns the wallet instead of dropping them. */
|
|
const legacy = CURRENCY_PATTERN.test(key);
|
|
const owner = legacy ? (key === 'RUB' ? 'openrusrouter' : 'deepseek') : key;
|
|
if (!LIMIT_OWNER_PATTERN.test(owner)) continue;
|
|
const read = (raw) => {
|
|
const parsed = numeric(raw);
|
|
return parsed !== undefined && parsed > 0 ? parsed : 0;
|
|
};
|
|
state.limits[owner] = {
|
|
currency:
|
|
typeof limits.currency === 'string' && CURRENCY_PATTERN.test(limits.currency)
|
|
? limits.currency
|
|
: legacy
|
|
? key
|
|
: state.currency,
|
|
day: read(limits.day),
|
|
week: read(limits.week),
|
|
month: read(limits.month),
|
|
};
|
|
owners += 1;
|
|
}
|
|
}
|
|
if (value.tokens !== null && typeof value.tokens === 'object') {
|
|
let buckets = 0;
|
|
for (const [key, models] of Object.entries(value.tokens)) {
|
|
if (buckets >= MAX_HOUR_BUCKETS) break;
|
|
const hour = numeric(key);
|
|
if (hour === undefined || !Number.isSafeInteger(hour) || hour < 0) continue;
|
|
if (models === null || typeof models !== 'object') continue;
|
|
const entries = {};
|
|
let count = 0;
|
|
for (const [model, entry] of Object.entries(models)) {
|
|
if (count >= MAX_TOKEN_MODELS) break;
|
|
if (typeof model !== 'string' || model === '' || model.length > 64) continue;
|
|
if (entry === null || typeof entry !== 'object') continue;
|
|
const miss = tokenCount(entry.miss);
|
|
const write = tokenCount(entry.write);
|
|
const hit = tokenCount(entry.hit);
|
|
const out = tokenCount(entry.out);
|
|
if (miss + write + hit + out <= 0) continue;
|
|
entries[model] = { miss, write, hit, out };
|
|
count += 1;
|
|
}
|
|
if (count === 0) continue;
|
|
state.tokens[String(hour)] = entries;
|
|
buckets += 1;
|
|
}
|
|
}
|
|
return state;
|
|
}
|
|
|
|
/** Whether a ledger document carries no history, samples, or limits. */
|
|
function isEmptyState(state) {
|
|
return (
|
|
Object.keys(state.hours).length === 0 &&
|
|
Object.keys(state.samples).length === 0 &&
|
|
Object.keys(state.limits).length === 0 &&
|
|
Object.keys(state.tokens).length === 0
|
|
);
|
|
}
|
|
|
|
/** Harness home: `$DSH_HOME`, else `~/.dsh` — the rule the harness itself uses. */
|
|
function dshHome() {
|
|
const value = process.env.DSH_HOME;
|
|
if (typeof value === 'string' && value.trim() !== '') {
|
|
const trimmed = value.trim();
|
|
if (trimmed === '~') return homedir();
|
|
if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) return join(homedir(), trimmed.slice(2));
|
|
return resolve(trimmed);
|
|
}
|
|
return join(homedir(), '.dsh');
|
|
}
|
|
|
|
/** Absolute path of the ledger database; `$DSH_COST_BALANCE_DB` overrides it. */
|
|
function databasePath() {
|
|
const override = process.env[DB_ENV];
|
|
if (typeof override === 'string' && override.trim() !== '') return resolve(override.trim());
|
|
return join(dshHome(), 'storages', DB_FILE_NAME);
|
|
}
|
|
|
|
let databasePromise;
|
|
|
|
/** One open handle per process; a failed open is retried by the next request. */
|
|
function database() {
|
|
if (databasePromise === undefined) {
|
|
databasePromise = openDatabase().catch((error) => {
|
|
databasePromise = undefined;
|
|
throw error;
|
|
});
|
|
}
|
|
return databasePromise;
|
|
}
|
|
|
|
/** Open (or create) the ledger database and bring its schema up to date. */
|
|
async function openDatabase() {
|
|
/* `node:sqlite` ships with the runtime, but importing it lazily keeps the
|
|
* balance reading working on a runtime that lacks it. */
|
|
const { DatabaseSync } = await import('node:sqlite');
|
|
const file = databasePath();
|
|
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
const db = new DatabaseSync(file);
|
|
try {
|
|
/* The file may have been created by another tool or a wider umask: the
|
|
* spending history stays owner-only either way. */
|
|
await chmod(file, 0o600).catch(() => undefined);
|
|
db.exec('PRAGMA journal_mode = WAL');
|
|
db.exec('PRAGMA busy_timeout = 5000');
|
|
const applicationId = db.prepare('PRAGMA application_id').get().application_id;
|
|
const version = db.prepare('PRAGMA user_version').get().user_version;
|
|
const tables = db
|
|
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
|
|
.all();
|
|
if (applicationId !== 0 && applicationId !== DB_APPLICATION_ID) {
|
|
throw new Error('cost-balance: the database belongs to another application');
|
|
}
|
|
if (applicationId === 0 && tables.length > 0) {
|
|
throw new Error('cost-balance: the database has an unrecognized schema');
|
|
}
|
|
db.exec(`PRAGMA application_id = ${DB_APPLICATION_ID}`);
|
|
if (version > DB_SCHEMA_VERSION) {
|
|
throw new Error(`cost-balance: unsupported database schema version ${version}`);
|
|
}
|
|
/* Every statement is CREATE TABLE IF NOT EXISTS, so applying the current
|
|
* schema upgrades an older file in place (v1 -> v2 adds usage_hours and
|
|
* keeps the spending history) without a destructive rebuild. */
|
|
db.exec(DB_SCHEMA);
|
|
migrateLimitOwners(db);
|
|
if (version !== DB_SCHEMA_VERSION) {
|
|
db.exec(`PRAGMA user_version = ${DB_SCHEMA_VERSION}`);
|
|
}
|
|
return db;
|
|
} catch (error) {
|
|
db.close();
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* v3: soft limits moved from the wallet currency to the provider that owns
|
|
* the wallet. Rebuild the table in place and remap the legacy rows (ruble
|
|
* limits belong to the operator, the account's own currency to DeepSeek);
|
|
* the yuan row wins when a legacy file carries both account currencies.
|
|
*/
|
|
function migrateLimitOwners(db) {
|
|
const columns = db.prepare("PRAGMA table_info('spend_limits')").all().map((row) => row.name);
|
|
if (columns.includes('owner')) return;
|
|
db.exec('BEGIN IMMEDIATE');
|
|
try {
|
|
db.exec('ALTER TABLE spend_limits RENAME TO spend_limits_legacy');
|
|
db.exec('CREATE TABLE spend_limits (owner TEXT PRIMARY KEY, currency TEXT NOT NULL, day REAL NOT NULL DEFAULT 0, week REAL NOT NULL DEFAULT 0, month REAL NOT NULL DEFAULT 0)');
|
|
db.exec('INSERT OR REPLACE INTO spend_limits (owner, currency, day, week, month) SELECT CASE WHEN currency = \'RUB\' THEN \'openrusrouter\' ELSE \'deepseek\' END, currency, day, week, month FROM spend_limits_legacy ORDER BY CASE WHEN currency = \'CNY\' THEN 1 ELSE 0 END');
|
|
db.exec('DROP TABLE spend_limits_legacy');
|
|
db.exec('COMMIT');
|
|
} catch (error) {
|
|
try {
|
|
db.exec('ROLLBACK');
|
|
} catch {
|
|
/* Ignore a transaction SQLite already ended. */
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Read the whole ledger document out of the database. */
|
|
function readState(db) {
|
|
const state = emptyState();
|
|
const currency = db.prepare("SELECT value FROM spend_meta WHERE key = 'currency'").get();
|
|
if (currency !== undefined && typeof currency.value === 'string' && CURRENCY_PATTERN.test(currency.value)) {
|
|
state.currency = currency.value;
|
|
}
|
|
for (const row of db.prepare('SELECT hour, currency, amount FROM spend_hours').all()) {
|
|
const key = String(row.hour);
|
|
const bucket = state.hours[key] ?? (state.hours[key] = {});
|
|
bucket[row.currency] = row.amount;
|
|
}
|
|
for (const row of db.prepare('SELECT * FROM spend_samples').all()) {
|
|
const sample = { currency: row.currency, at: row.observed_at };
|
|
if (row.amount !== null) sample.amount = row.amount;
|
|
if (row.wallet !== null) sample.wallet = row.wallet;
|
|
if (row.used !== null) sample.used = row.used;
|
|
if (row.cap !== null) sample.cap = row.cap;
|
|
if (row.reset_window !== null) sample.window = row.reset_window;
|
|
if (row.reset_at !== null) sample.resetsAt = row.reset_at;
|
|
state.samples[row.provider] = sample;
|
|
}
|
|
for (const row of db.prepare('SELECT owner, currency, day, week, month FROM spend_limits').all()) {
|
|
state.limits[row.owner] = {
|
|
currency: row.currency,
|
|
day: row.day,
|
|
week: row.week,
|
|
month: row.month,
|
|
};
|
|
}
|
|
for (const row of db.prepare('SELECT hour, model, miss, cache_write, cache_read, output FROM usage_hours').all()) {
|
|
const key = String(row.hour);
|
|
const bucket = state.tokens[key] ?? (state.tokens[key] = {});
|
|
bucket[row.model] = {
|
|
miss: row.miss,
|
|
write: row.cache_write,
|
|
hit: row.cache_read,
|
|
out: row.output,
|
|
};
|
|
}
|
|
return state;
|
|
}
|
|
|
|
/** Replace every row of the ledger with one document; caller owns the transaction. */
|
|
function replaceRows(db, state) {
|
|
db.exec('DELETE FROM spend_hours');
|
|
db.exec('DELETE FROM spend_samples');
|
|
db.exec('DELETE FROM spend_limits');
|
|
db.exec('DELETE FROM usage_hours');
|
|
db.exec("DELETE FROM spend_meta WHERE key = 'currency'");
|
|
db.prepare("INSERT INTO spend_meta (key, value) VALUES ('currency', ?)").run(state.currency);
|
|
const insertHour = db.prepare('INSERT INTO spend_hours (hour, currency, amount) VALUES (?, ?, ?)');
|
|
for (const [key, bucket] of Object.entries(state.hours)) {
|
|
for (const [currency, amount] of Object.entries(bucket)) {
|
|
insertHour.run(Number(key), currency, amount);
|
|
}
|
|
}
|
|
const insertSample = db.prepare(
|
|
'INSERT INTO spend_samples (provider, currency, observed_at, amount, wallet, used, cap, reset_window, reset_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
|
);
|
|
for (const [provider, sample] of Object.entries(state.samples)) {
|
|
insertSample.run(
|
|
provider,
|
|
sample.currency,
|
|
sample.at,
|
|
sample.amount ?? null,
|
|
sample.wallet ?? null,
|
|
sample.used ?? null,
|
|
sample.cap ?? null,
|
|
sample.window ?? null,
|
|
sample.resetsAt ?? null,
|
|
);
|
|
}
|
|
const insertLimits = db.prepare(
|
|
'INSERT INTO spend_limits (owner, currency, day, week, month) VALUES (?, ?, ?, ?, ?)',
|
|
);
|
|
for (const [owner, limits] of Object.entries(state.limits)) {
|
|
insertLimits.run(owner, limits.currency ?? state.currency, limits.day, limits.week, limits.month);
|
|
}
|
|
const insertTokens = db.prepare(
|
|
'INSERT INTO usage_hours (hour, model, miss, cache_write, cache_read, output) VALUES (?, ?, ?, ?, ?, ?)',
|
|
);
|
|
for (const [key, models] of Object.entries(state.tokens)) {
|
|
for (const [model, entry] of Object.entries(models)) {
|
|
insertTokens.run(Number(key), model, entry.miss, entry.write, entry.hit, entry.out);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Replace the ledger atomically. */
|
|
function writeState(db, state) {
|
|
db.exec('BEGIN IMMEDIATE');
|
|
try {
|
|
replaceRows(db, state);
|
|
db.exec('COMMIT');
|
|
} catch (error) {
|
|
try {
|
|
db.exec('ROLLBACK');
|
|
} catch {
|
|
/* The transaction may already have been rolled back by SQLite. */
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Import a legacy document, but only into a database that has no history yet.
|
|
* The emptiness check runs inside the write transaction, so two windows
|
|
* importing at once still produce one copy.
|
|
*/
|
|
function importState(db, state) {
|
|
db.exec('BEGIN IMMEDIATE');
|
|
try {
|
|
const rows = db
|
|
.prepare(
|
|
'SELECT (SELECT COUNT(*) FROM spend_hours) + (SELECT COUNT(*) FROM spend_samples) + (SELECT COUNT(*) FROM spend_limits) + (SELECT COUNT(*) FROM usage_hours) AS total',
|
|
)
|
|
.get();
|
|
if (rows.total > 0) {
|
|
db.exec('ROLLBACK');
|
|
return false;
|
|
}
|
|
replaceRows(db, state);
|
|
db.exec('COMMIT');
|
|
return true;
|
|
} catch (error) {
|
|
try {
|
|
db.exec('ROLLBACK');
|
|
} catch {
|
|
/* Ignore a transaction SQLite already ended. */
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fold one document into the stored one without double counting.
|
|
*
|
|
* Several windows poll the same wallet and observe the same spending, so the
|
|
* larger value per hour (and per model for tokens) wins; samples take the newer
|
|
* reading. Limits are authoritative in the shared ledger: the browser copy only
|
|
* fills owners it does not cover, so a stale window cannot reset a budget.
|
|
*/
|
|
function mergeState(current, incoming) {
|
|
const merged = {
|
|
version: STATE_VERSION,
|
|
currency: incoming.currency ?? current.currency,
|
|
hours: { ...current.hours },
|
|
samples: { ...current.samples },
|
|
limits: { ...current.limits },
|
|
tokens: { ...current.tokens },
|
|
};
|
|
for (const [hour, bucket] of Object.entries(incoming.hours)) {
|
|
const target = merged.hours[hour] ?? (merged.hours[hour] = {});
|
|
for (const [currency, amount] of Object.entries(bucket)) {
|
|
const previous = target[currency];
|
|
if (typeof previous !== 'number' || amount > previous) target[currency] = amount;
|
|
}
|
|
}
|
|
for (const [hour, models] of Object.entries(incoming.tokens)) {
|
|
const target = merged.tokens[hour] ?? (merged.tokens[hour] = {});
|
|
for (const [model, entry] of Object.entries(models)) {
|
|
const previous = target[model];
|
|
if (previous === undefined) {
|
|
target[model] = { ...entry };
|
|
continue;
|
|
}
|
|
target[model] = {
|
|
miss: Math.max(previous.miss, entry.miss),
|
|
write: Math.max(previous.write, entry.write),
|
|
hit: Math.max(previous.hit, entry.hit),
|
|
out: Math.max(previous.out, entry.out),
|
|
};
|
|
}
|
|
}
|
|
for (const [provider, sample] of Object.entries(incoming.samples)) {
|
|
const previous = merged.samples[provider];
|
|
if (previous === undefined || (sample.at ?? 0) > (previous.at ?? 0)) {
|
|
merged.samples[provider] = { ...sample };
|
|
}
|
|
}
|
|
for (const [owner, limits] of Object.entries(incoming.limits)) {
|
|
if (merged.limits[owner] === undefined) merged.limits[owner] = { ...limits };
|
|
}
|
|
return merged;
|
|
}
|
|
|
|
/** Replace every soft limit with the document's, keeping the history. */
|
|
function replaceLimits(db, state) {
|
|
db.exec('BEGIN IMMEDIATE');
|
|
try {
|
|
db.exec('DELETE FROM spend_limits');
|
|
db.exec("DELETE FROM spend_meta WHERE key = 'currency'");
|
|
db.prepare("INSERT INTO spend_meta (key, value) VALUES ('currency', ?)").run(state.currency);
|
|
const insert = db.prepare(
|
|
'INSERT INTO spend_limits (owner, currency, day, week, month) VALUES (?, ?, ?, ?, ?)',
|
|
);
|
|
for (const [owner, limits] of Object.entries(state.limits)) {
|
|
insert.run(owner, limits.currency ?? state.currency, limits.day, limits.week, limits.month);
|
|
}
|
|
db.exec('COMMIT');
|
|
} catch (error) {
|
|
try {
|
|
db.exec('ROLLBACK');
|
|
} catch {
|
|
/* Ignore a transaction SQLite already ended. */
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Drop the recorded spending and tokens; the soft limits stay. */
|
|
function clearHistory(db) {
|
|
db.exec('BEGIN IMMEDIATE');
|
|
try {
|
|
db.exec('DELETE FROM spend_hours');
|
|
db.exec('DELETE FROM spend_samples');
|
|
db.exec('DELETE FROM usage_hours');
|
|
db.exec('COMMIT');
|
|
} catch (error) {
|
|
try {
|
|
db.exec('ROLLBACK');
|
|
} catch {
|
|
/* Ignore a transaction SQLite already ended. */
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Replace one local day's money buckets for one currency. */
|
|
function replaceDay(db, day) {
|
|
db.exec('BEGIN IMMEDIATE');
|
|
try {
|
|
db.prepare('DELETE FROM spend_hours WHERE hour >= ? AND hour < ? AND currency = ?').run(
|
|
day.start,
|
|
day.start + 24 * 3_600_000,
|
|
day.currency,
|
|
);
|
|
const insert = db.prepare(
|
|
'INSERT INTO spend_hours (hour, currency, amount) VALUES (?, ?, ?) ON CONFLICT(hour, currency) DO UPDATE SET amount = excluded.amount',
|
|
);
|
|
for (const [hour, amount] of Object.entries(day.buckets ?? {})) {
|
|
const at = numeric(hour);
|
|
const value = numeric(amount);
|
|
if (at === undefined || value === undefined || value === 0) continue;
|
|
insert.run(at, day.currency, value);
|
|
}
|
|
db.exec('COMMIT');
|
|
} catch (error) {
|
|
try {
|
|
db.exec('ROLLBACK');
|
|
} catch {
|
|
/* Ignore a transaction SQLite already ended. */
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Write one JSON answer to a raw HTTP response. */
|
|
function sendJson(res, status, body, allow) {
|
|
const headers = {
|
|
'content-type': 'application/json; charset=utf-8',
|
|
'cache-control': 'no-store',
|
|
};
|
|
if (allow !== undefined) headers.allow = allow;
|
|
res.writeHead(status, headers);
|
|
res.end(JSON.stringify(body));
|
|
}
|
|
|
|
/** Read a bounded request body from a raw HTTP request. */
|
|
function readRawBody(req) {
|
|
return new Promise((resolve) => {
|
|
let size = 0;
|
|
let settled = false;
|
|
const chunks = [];
|
|
const finish = (value) => {
|
|
if (settled) return;
|
|
settled = true;
|
|
resolve(value);
|
|
};
|
|
req.on('data', (chunk) => {
|
|
if (settled) return;
|
|
size += chunk.length;
|
|
if (size > MAX_BODY_BYTES) {
|
|
finish(undefined);
|
|
req.destroy();
|
|
return;
|
|
}
|
|
chunks.push(chunk);
|
|
});
|
|
req.on('end', () => finish(Buffer.concat(chunks)));
|
|
req.on('error', () => finish(undefined));
|
|
req.on('aborted', () => finish(undefined));
|
|
});
|
|
}
|
|
|
|
/** Parse a bounded JSON request body; undefined when it is missing or invalid. */
|
|
async function readJsonBody(req) {
|
|
const buffer = await readRawBody(req);
|
|
if (buffer === undefined || buffer.length === 0) return undefined;
|
|
try {
|
|
const parsed = JSON.parse(buffer.toString('utf8'));
|
|
return parsed !== null && typeof parsed === 'object' ? parsed : undefined;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* GET returns the ledger, PUT replaces it.
|
|
*
|
|
* Registered as a raw handler rather than a `resource`: the web server answers
|
|
* resource routes for GET/HEAD only and returns 405 for anything else before
|
|
* matching, which silently dropped every save (and the one-time import) while
|
|
* the ledger moved into SQLite. A handler owns the response, so PUT reaches it.
|
|
*/
|
|
async function serveSpend(req, res) {
|
|
if (req.method === 'GET' || req.method === 'HEAD') {
|
|
try {
|
|
sendJson(res, 200, { ok: true, state: readState(await database()) });
|
|
} catch {
|
|
sendJson(res, 500, { ok: false, reason: 'database' });
|
|
}
|
|
return;
|
|
}
|
|
if (req.method === 'PUT') {
|
|
const body = await readJsonBody(req);
|
|
if (body === undefined || body.state === undefined) {
|
|
sendJson(res, 400, { ok: false, reason: 'bad-body' });
|
|
return;
|
|
}
|
|
const mode = typeof body.mode === 'string' ? body.mode : 'merge';
|
|
try {
|
|
const db = await database();
|
|
const incoming = normalizeState(body.state);
|
|
if (mode === 'merge') {
|
|
writeState(db, mergeState(readState(db), incoming));
|
|
} else if (mode === 'replace') {
|
|
writeState(db, incoming);
|
|
} else if (mode === 'limits') {
|
|
replaceLimits(db, incoming);
|
|
} else if (mode === 'clear') {
|
|
clearHistory(db);
|
|
} else if (mode === 'day') {
|
|
const day = body.day;
|
|
if (
|
|
day === null ||
|
|
typeof day !== 'object' ||
|
|
!Number.isSafeInteger(day.start) ||
|
|
typeof day.currency !== 'string' ||
|
|
!CURRENCY_PATTERN.test(day.currency)
|
|
) {
|
|
sendJson(res, 400, { ok: false, reason: 'bad-day' });
|
|
return;
|
|
}
|
|
replaceDay(db, {
|
|
start: day.start,
|
|
currency: day.currency,
|
|
buckets: day.buckets !== null && typeof day.buckets === 'object' ? day.buckets : {},
|
|
});
|
|
} else {
|
|
sendJson(res, 400, { ok: false, reason: 'bad-mode' });
|
|
return;
|
|
}
|
|
sendJson(res, 200, { ok: true });
|
|
} catch {
|
|
sendJson(res, 500, { ok: false, reason: 'database' });
|
|
}
|
|
return;
|
|
}
|
|
sendJson(res, 405, { ok: false, reason: 'method' }, 'GET, HEAD, PUT');
|
|
}
|
|
|
|
/** One-time migration of the browser ledger into an empty database. */
|
|
async function serveSpendImport(req, res) {
|
|
if (req.method !== 'POST') {
|
|
sendJson(res, 405, { ok: false, reason: 'method' }, 'POST');
|
|
return;
|
|
}
|
|
const body = await readJsonBody(req);
|
|
if (body === undefined || body.state === undefined) {
|
|
sendJson(res, 400, { ok: false, reason: 'bad-body' });
|
|
return;
|
|
}
|
|
try {
|
|
const db = await database();
|
|
const imported = importState(db, normalizeState(body.state));
|
|
sendJson(res, 200, { ok: true, imported, state: readState(db) });
|
|
} catch {
|
|
sendJson(res, 500, { ok: false, reason: 'database' });
|
|
}
|
|
}
|
|
|
|
/** Last cached central-bank rates, or undefined when none were stored yet. */
|
|
function readFxRates(db) {
|
|
const rows = db.prepare('SELECT code, rate, rate_date, fetched_at FROM fx_rates').all();
|
|
if (rows.length === 0) return undefined;
|
|
const rates = {};
|
|
let date = '';
|
|
let fetchedAt = 0;
|
|
for (const row of rows) {
|
|
rates[row.code] = row.rate;
|
|
if (row.rate_date > date) date = row.rate_date;
|
|
if (row.fetched_at > fetchedAt) fetchedAt = row.fetched_at;
|
|
}
|
|
return { rates, date, fetchedAt };
|
|
}
|
|
|
|
function writeFxRates(db, rates, date, fetchedAt) {
|
|
db.exec('BEGIN IMMEDIATE');
|
|
try {
|
|
db.exec('DELETE FROM fx_rates');
|
|
const insert = db.prepare('INSERT INTO fx_rates (code, rate, rate_date, fetched_at) VALUES (?, ?, ?, ?)');
|
|
for (const [code, rate] of Object.entries(rates)) insert.run(code, rate, date, fetchedAt);
|
|
db.exec('COMMIT');
|
|
} catch (error) {
|
|
try {
|
|
db.exec('ROLLBACK');
|
|
} catch {
|
|
/* Ignore a transaction SQLite already ended. */
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Rubles per one unit of each quoted currency, from the central-bank payload. */
|
|
function parseFxPayload(payload) {
|
|
const valute = payload !== null && typeof payload === 'object' ? payload.Valute : undefined;
|
|
if (valute === null || typeof valute !== 'object') return undefined;
|
|
const rates = {};
|
|
for (const code of FX_CODES) {
|
|
const entry = valute[code];
|
|
if (entry === null || typeof entry !== 'object') continue;
|
|
const nominal = numeric(entry.Nominal) ?? 1;
|
|
const value = numeric(entry.Value);
|
|
if (value === undefined || !(nominal > 0)) continue;
|
|
rates[code] = value / nominal;
|
|
}
|
|
return Object.keys(rates).length > 0 ? rates : undefined;
|
|
}
|
|
|
|
/**
|
|
* Rates for today: the cached copy while it is fresh, a fresh one otherwise.
|
|
* A failed fetch returns the stale copy rather than losing the conversion.
|
|
*/
|
|
async function currentFxRates(db) {
|
|
const cached = readFxRates(db);
|
|
if (cached !== undefined && Date.now() - cached.fetchedAt < FX_TTL_MS) return cached;
|
|
try {
|
|
const response = await fetch(FX_URL, {
|
|
headers: { accept: 'application/json' },
|
|
signal: AbortSignal.timeout(FX_TIMEOUT_MS),
|
|
});
|
|
if (!response.ok) throw new Error(`http-${response.status}`);
|
|
const payload = await response.json();
|
|
const rates = parseFxPayload(payload);
|
|
if (rates === undefined) throw new Error('bad-payload');
|
|
const date = typeof payload.Date === 'string' ? payload.Date : new Date().toISOString();
|
|
const fetchedAt = Date.now();
|
|
writeFxRates(db, rates, date, fetchedAt);
|
|
return { rates, date, fetchedAt };
|
|
} catch {
|
|
return cached;
|
|
}
|
|
}
|
|
|
|
/** GET the cached daily rates; the Client half converts foreign spend to rubles. */
|
|
async function handleRates() {
|
|
try {
|
|
const result = await currentFxRates(await database());
|
|
if (result === undefined) return json(200, { ok: false, reason: 'unavailable' });
|
|
return json(200, {
|
|
ok: true,
|
|
base: 'RUB',
|
|
date: result.date,
|
|
fetchedAt: result.fetchedAt,
|
|
rates: result.rates,
|
|
});
|
|
} catch {
|
|
return json(200, { ok: false, reason: 'database' });
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Services this Host half needs. Declaring `webServer` here is what makes the
|
|
* route appear: without it the plugin can apply before the web server has
|
|
* provided the service, a one-shot `ctx.get` then returned undefined, and the
|
|
* reading fell back to "Balance —" because the browser called a 404. The order
|
|
* of that race depends on the rest of the composition, so it changed between
|
|
* launches.
|
|
*/
|
|
export const inject = ['webServer'];
|
|
|
|
/**
|
|
* Register the operator-balance route. `ctx.inject` keeps the registration
|
|
* bound to the live service, so a later (re)appearance of `webServer` registers
|
|
* again instead of leaving a stale disposer behind.
|
|
*/
|
|
export function apply(ctx) {
|
|
const mount = (target) => {
|
|
const webServer = target.get('webServer');
|
|
if (webServer === undefined) return;
|
|
target.effect(
|
|
() =>
|
|
webServer.register({
|
|
kind: 'exact',
|
|
path: '/api/cost-balance/operator-balance',
|
|
resource: (request) => handleBalance(ctx, request),
|
|
}),
|
|
'cost-balance: operator balance route',
|
|
);
|
|
target.effect(
|
|
() =>
|
|
webServer.register({
|
|
kind: 'exact',
|
|
path: '/api/cost-balance/rates',
|
|
resource: () => handleRates(),
|
|
}),
|
|
'cost-balance: exchange rates route',
|
|
);
|
|
target.effect(
|
|
() =>
|
|
webServer.register({
|
|
kind: 'exact',
|
|
path: '/api/cost-balance/spend',
|
|
handler: (req, res) => {
|
|
void serveSpend(req, res).catch(() => sendJson(res, 500, { ok: false, reason: 'database' }));
|
|
},
|
|
}),
|
|
'cost-balance: spending ledger route',
|
|
);
|
|
target.effect(
|
|
() =>
|
|
webServer.register({
|
|
kind: 'exact',
|
|
path: '/api/cost-balance/spend/import',
|
|
handler: (req, res) => {
|
|
void serveSpendImport(req, res).catch(() => sendJson(res, 500, { ok: false, reason: 'database' }));
|
|
},
|
|
}),
|
|
'cost-balance: spending ledger import route',
|
|
);
|
|
};
|
|
/* `inject` above already delays apply until the service exists; the injected
|
|
* scope additionally re-mounts the route if the service is ever replaced,
|
|
* and the direct call covers a context without `inject`. */
|
|
if (typeof ctx.inject === 'function') ctx.inject(['webServer'], mount);
|
|
else mount(ctx);
|
|
}
|