@softure-ai/metering
v0.4.2
Published
SOFTURE AI metering module: a ledger of paid provider calls in any unit (credits, usd, characters, seconds, tokens, requests), budgets per provider and day or month that refuse a call before it spends, reservations under a lock, adapters for llm usage and
Readme
@softure-ai/metering
A ledger of paid provider calls in the provider's own unit, and budgets that refuse a call before it spends.
1. What it provides
metering.charges: every paid call an app makes (speech and audio credits, images, search requests, model dollars), with provider, step, unit, amount, account and the app's attributes.- Budgets per provider and day or month, for the whole provider or per account, in the provider's unit. Their limits
come from the configuration and can be changed at runtime (stored in
metering.budget_limits), without a deploy. reserveSpendbefore a paid call,settleSpendwith the billed amount after it,releaseSpendwhen it failed unbilled. A reservation runs in one transaction under the provider's lock, so two jobs reserving at once cannot both pass the same remaining amount. Amounts compare as Postgresnumeric, so0.1 + 0.2fills a0.3budget exactly.recordChargefor spend reported after the fact,getSpendfor a status tool or page,getSpendBreakdownfor spend per step or per item (any attribute), and an attributefilterfor one item's cost.- Adapters for
@softure-ai/llm'sonUsageand@softure-ai/marketing-kit's footageonCharge, a GDPR contributor and a prune job for@softure-ai/jobs.
2. Installation
npm install @softure-ai/metering@softure-ai/jobs is an optional peer: only the @softure-ai/metering/jobs entry needs it.
3. Configuration
// softure.config.ts
import { metering } from "@softure-ai/metering";
metering({
providers: [
// 100,000 credits a month for the app, 2,000 a day for each account.
{ id: "elevenlabs", unit: "credits", budgets: [{ period: "month", limit: 100_000 }, { period: "day", limit: 2_000, perAccount: true }] },
{ id: "openrouter", unit: "usd", budgets: [{ period: "day", limit: 5 }] },
// Metered, no budget.
{ id: "brave-search", unit: "requests" },
],
reservationTtlSeconds: 3600, // default
});| Option | Default | Meaning |
| --- | --- | --- |
| providers[].id | required | Lower case words joined by ., _ or -, at most 64 characters. |
| providers[].unit | required | credits, usd, characters, seconds, tokens or requests. Every amount of the provider is in it. |
| providers[].budgets[] | [] | { period: "day" \| "month", limit, perAccount = false }; one budget per period and scope. |
| reservationTtlSeconds | 3600 | How long an unsettled reservation holds budget (a call that crashed). Longer than the slowest call. |
Days and months start at midnight in the app's timezone (defineSoftureConfig). Spend counts in the period it was
reserved or recorded in, also when it is settled later.
Using it around a paid call (@softure-ai/metering/server):
const reserved = await reserveSpend(ctx, { provider: "elevenlabs", amount: estimate, step: "isolate", accountId, attributes: { jobId } });
if (!reserved.ok) return reserved; // metering.budget_exceeded, with reserved.budget.remaining and reserved.budget.resetsAt
try {
const result = await callProvider();
await settleSpend(ctx, reserved.value, result.creditsBilled);
return ok(result);
} catch (error) {
await releaseSpend(ctx, reserved.value); // only when the provider did not bill
throw error;
}| Function | Returns |
| --- | --- |
| reserveSpend(ctx, { provider, amount, step?, accountId?, attributes? }) | ok(SpendReservation) or BudgetExceeded (error: "metering.budget_exceeded", budget, requested). |
| settleSpend(ctx, reservation, actual) | ok() or metering.reservation_not_found (settled, released or pruned). An actual above the reservation is recorded as billed. |
| releaseSpend(ctx, reservation) | ok() or metering.reservation_not_found. |
| recordCharge(ctx, { provider, amount, step?, accountId?, attributes?, at? }) | ok({ id }); never refused, the spend already happened. |
| getSpend(ctx, { provider, period, accountId?, filter? }) | ok(SpendSummary): settled, reserved, spent, limit, remaining, from, resetsAt. With accountId: that account's spend and its per-account budget. With filter: { attribute, value }: only the charges with that attribute value; limit and remaining stay the scope's budget. |
| getSpendBreakdown(ctx, { provider, period, accountId?, groupBy, filter? }) | ok(SpendBreakdown): rows of { key, settled, reserved, spent } per step (groupBy: "step") or per attribute value (groupBy: { attribute }), highest spend first. key: null gathers charges without the step or attribute, so the rows add up to getSpend. |
| getChargeRate(ctx, { provider, step, accountId?, latest?, minUnits? }) | ok(ChargeRate): rate (amount / units), amount, units and charges over the latest latest (20 by default, at most 1000) settled charges of the step whose amount the provider reported (attributes reported: "true" and units, as the footage recorder writes them); ok(null) without such charges or when their units add up to 0 or less than minUnits. |
BudgetExceeded.budget names the first budget the amount did not fit: scope ({ kind: "provider" } or
{ kind: "account", accountId }), period, limit, spent, remaining and resetsAt. An undeclared provider, an
amount that is negative, not finite or above 1e15, and a reservation without accountId for a provider with a
per-account budget throw: they are bugs, not expected failures. So does an attribute name that is empty or longer
than 100 characters, and a filter value that is empty or longer than 500.
Budget limits at runtime
The configuration declares which budgets exist and their default limit. An operator can change a limit without a deploy: the stored value applies to every process (app and worker) from the next reservation on, until it is cleared.
import { clearBudgetLimit, getBudgetLimits, setBudgetLimit } from "@softure-ai/metering/server";
// A settings form: each declared budget with its default, the stored value and who changed it.
const limits = await getBudgetLimits(ctx, { provider: "elevenlabs" });
// Save (after the app checked that the session may change budgets).
const saved = await setBudgetLimit(ctx, { provider: "elevenlabs", period: "month", limit: 50_000, updatedBy: session.userId });
if (!saved.ok) return saved; // metering.invalid_budget_limit: negative, not finite or above 1e15
// Back to the configured limit.
await clearBudgetLimit(ctx, { provider: "elevenlabs", period: "month" });| Function | Returns |
| --- | --- |
| getBudgetLimits(ctx, { provider }) | ok(BudgetLimit[]) in configuration order: period, perAccount, configuredLimit, storedLimit (null without one), limit (the one in force), updatedAt, updatedBy. |
| setBudgetLimit(ctx, { provider, period, perAccount?, limit, updatedBy? }) | ok(BudgetLimit) or metering.invalid_budget_limit. A limit may be 0: the provider is stopped (only amounts of 0 fit). |
| clearBudgetLimit(ctx, { provider, period, perAccount? }) | ok(BudgetLimit) with the configured limit in force again. |
reserveSpend reads the stored limits after it takes the provider's lock, and setBudgetLimit / clearBudgetLimit
take the same lock, so a change and a reservation never interleave. BudgetExceeded.budget.limit and
SpendSummary.limit report the limit in force. A budget the configuration does not declare (provider, period and
perAccount) throws: build the form from getBudgetLimits. A stored row of a budget later removed from the
configuration is ignored. The module has no route: the app authorizes who may change budgets.
Spend per step and per item
import { getSpend, getSpendBreakdown } from "@softure-ai/metering/server";
// This month per item (charges recorded with attributes: { jobId }) and per step.
const perItem = await getSpendBreakdown(ctx, { provider: "elevenlabs", period: "month", groupBy: { attribute: "jobId" } });
const perStep = await getSpendBreakdown(ctx, { provider: "elevenlabs", period: "month", groupBy: "step" });
// One item: its total, and its steps.
const item = await getSpend(ctx, { provider: "elevenlabs", period: "month", filter: { attribute: "jobId", value: jobId } });
const itemSteps = await getSpendBreakdown(ctx, { provider: "elevenlabs", period: "month", groupBy: "step", filter: { attribute: "jobId", value: jobId } });The period bounds and the rule for what counts (settled charges and unexpired reservations) are the same as
getSpend's. A filter matches the attribute's value exactly, through attributes @> {attribute: value}, which the
charges_attributes_idx GIN index serves for any attribute name, so one item's spend stays an index lookup on a page
of a few hundred items. Grouping reads one provider's period through the (provider, created_at) index.
4. Mounting
Nothing to mount. A status page or tool reads getSpend and getSpendBreakdown; a settings form reads
getBudgetLimits and writes setBudgetLimit.
5. Migrations and tables
Schema metering, migrations 0001_create_charges.sql, 0002_index_charge_attributes.sql (a GIN index on
attributes for filters) and 0003_create_budget_limits.sql, tables charges and budget_limits.
charges:
| Column | Meaning |
| --- | --- |
| id | uuid |
| provider, unit | the declared provider and its unit |
| step | what the call was for (nullable) |
| amount | numeric(24, 8), at least 0 |
| account_id | the app's account or user id (nullable) |
| attributes | the app's string attributes, a JSON object |
| status | reserved (with expires_at) or settled (with settled_at) |
| created_at | when the spend was reserved or recorded: the period it counts in |
budget_limits (primary key provider, period, per_account):
| Column | Meaning |
| --- | --- |
| provider, period, per_account | the declared budget the row overrides |
| limit | numeric(24, 8), at least 0 |
| updated_at, updated_by | when and by which account id (nullable) the limit was set |
6. Environment variables
None.
7. Switches
None.
8. Appearance
No UI.
9. Copy
src/messages/en.ts holds errors["metering.budget_exceeded"], errors["metering.invalid_budget_limit"] and
errors["metering.reservation_not_found"];
getMeteringErrorMessage(code, messages?) reads them, and an app passes its own dictionary for other languages.
10. Hooks
Adapters (@softure-ai/metering/server) read the other packages' records by shape, so metering depends on neither.
@softure-ai/llm:createLlm({ ..., onUsage: createLlmUsageRecorder(ctx, { provider: "openrouter" }) })records each priced call as ausdcharge (a call withcostUsd: nullrecords nothing). The record'saccountIdattribute becomes the charge's account; the model is the step and an attribute. The provider must be declared with unitusd. A failed write propagates throughonUsage.recordLlmUsage(ctx, record, options)does one record.marketing-kit footage:
onChargeis synchronous, so the recorder runs the writes in the background andflush()reports them:const recorder = createFootageChargeRecorder(ctx, { accountId, attributes: { filmId }, creditsPerSecond: 15 }); await transcribeFootage(film, clips, { ...runOptions, onCharge: recorder.onCharge }); // and the other paid steps await recorder.flush(); // rejects with the first failed writeA provider billed in
secondsrecords the charge's seconds; one billed increditsrecords the reported credits, orcreditsPerSecondtimes the seconds when the provider reports none (without a rate that charge fails). Every charge keeps the attributesitem,units(the seconds billed) andreported("true"when the amount is the provider's reported credits,"false"for acreditsPerSecondfallback or a seconds count); they win over app attributes of the same name.onCharge(charge, attributes?)takes this charge's own attributes, merged over the recorder's, so one recorder serves a whole run. To estimate a step at the rate the provider really bills, read it from the history:const history = await getChargeRate(ctx, { provider: "elevenlabs", step: "isolate", accountId, latest: 20, minUnits: 60 }); const creditsPerSecond = history.value?.rate ?? PUBLISHED_CREDITS_PER_SECOND;Prune job (
@softure-ai/metering/jobs):jobs({ schedules: { ...createMeteringJobSchedules({ keepDays: 400 }) } })andhandlers: { ...meteringJobHandlers }. Daily, it deletes charges older thankeepDays(at least 32, so a month budget never loses its own period) and expired reservations.pruneCharges(ctx, { keepDays })runs it directly.
11. GDPR
The module contributes to @softure-ai/privacy through account_id: an app that meters per user passes the user id
as accountId. The export lists the user's charges (provider, step, unit, amount, status, attributes, time). A
deletion clears account_id and attributes and keeps the amounts, so budgets and spend totals stay true; the
charges are the app's records of what it paid. A budget limit the user set names them in updated_by: the export
lists those limits, and a deletion clears updated_by and keeps the limit. exportMeteringUserData and deleteMeteringUserData take { db } for
an app that runs its own deletion transaction.
12. Limitations
- One lock per provider: reservations of one provider run one at a time (the check is two indexed sums and an insert).
- A reservation that outlives
reservationTtlSecondsstops holding budget, and once pruned it cannot be settled (metering.reservation_not_found); record the late charge withrecordChargethen. - Spend over a budget is possible through
recordChargeand a settle above the reservation: the ledger records what was billed.remainingis then 0. - No currency conversion: a budget is in its provider's unit only, and
usdis the only money unit. - No UI or route: the app builds its own status page on
getSpendandgetSpendBreakdown, and its own settings form ongetBudgetLimitsandsetBudgetLimit, with its own authorization. - Which budgets exist (provider, period, scope) is still configuration: only their limits change at runtime.
Build
npm run build -w modules/metering runs tsc -p tsconfig.build.json. Releasing:
scripts/release/README.md.
