Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

billing.ts

118 lines4.4 KB

1import type { TokenUsage } from '@tanstack/ai'
2​
3/**
4 * Response header fal sets on a queue *result* fetch carrying the real billed
5 * quantity for the generation, denominated in the endpoint's priced unit.
6 */
7const FAL_BILLABLE_UNITS_HEADER = 'x-fal-billable-units'
8​
9/**
10 * Response header fal sets carrying the request id. The fal client surfaces this
11 * same value as `Result.requestId`, so keying captured billable units by it
12 * guarantees the adapter's lookup matches the fetch the units came from — no URL
13 * parsing or global correlation registry of our own design needed.
14 */
15const FAL_REQUEST_ID_HEADER = 'x-fal-request-id'
16​
17/**
18 * Upper bound on retained, not-yet-consumed billable-unit entries. Each
19 * successful generation reads-and-deletes its entry (see {@link takeBillableUnits}),
20 * so this only guards against an unbounded leak when a result fetch records units
21 * but the adapter never resolves (e.g. it throws before reading). When the cap is
22 * exceeded the oldest entry is evicted (Map preserves insertion order).
23 */
24const MAX_PENDING_ENTRIES = 256
25​
26const billableUnitsByRequestId = new Map<string, number>()
27​
28/**
29 * Parse the `x-fal-billable-units` header value into a finite number. Returns
30 * `undefined` for a missing or non-numeric value so callers can skip attaching
31 * usage rather than surfacing `NaN`.
32 */
33export function parseBillableUnits(value: string | null): number | undefined {
34 if (value == null || value === '') return undefined
35 const parsed = Number(value)
36 return Number.isFinite(parsed) ? parsed : undefined
38​
39/**
40 * Record the billable units carried by a fal result response, keyed by the
41 * request id from the same response. Reading headers does not consume the body,
42 * so the response can be returned to the fal client untouched.
43 */
44export function recordBillableUnitsFromResponse(response: Response): void {
45 const units = parseBillableUnits(
46 response.headers.get(FAL_BILLABLE_UNITS_HEADER),
47 )
48 if (units == null) return
49 const requestId = response.headers.get(FAL_REQUEST_ID_HEADER)
50 if (!requestId) return
51 if (
52 billableUnitsByRequestId.size >= MAX_PENDING_ENTRIES &&
53 !billableUnitsByRequestId.has(requestId)
54 ) {
55 const oldest = billableUnitsByRequestId.keys().next().value
56 if (oldest !== undefined) billableUnitsByRequestId.delete(oldest)
57 }
58 billableUnitsByRequestId.set(requestId, units)
60​
61/**
62 * Read and remove the billable units recorded for a request id. Removing on read
63 * keeps the registry from growing across the lifetime of the process.
64 */
65export function takeBillableUnits(
66 requestId: string | undefined,
67): number | undefined {
68 if (!requestId) return undefined
69 const units = billableUnitsByRequestId.get(requestId)
70 if (units !== undefined) billableUnitsByRequestId.delete(requestId)
71 return units
73​
74/**
75 * Build a {@link TokenUsage} carrying fal's billed quantity. Media generation has
76 * no tokens, so the token fields are zero and the real billing signal rides on
77 * `billed`, denominated in `'units'` — fal's priced unit is endpoint-defined
78 * (its pricing page maps each endpoint to a unit price), so the count is opaque
79 * by design. Returns `undefined` when no units were captured so callers can
80 * omit `usage` entirely.
81 */
82export function buildFalUsage(
83 unitsBilled: number | undefined,
84): TokenUsage | undefined {
85 if (unitsBilled == null) return undefined
86 return {
87 promptTokens: 0,
88 completionTokens: 0,
89 totalTokens: 0,
90 billed: { quantity: unitsBilled, unit: 'units' },
91 }
93​
94/**
95 * Wrap a fetch so every fal request's response is inspected for the
96 * `x-fal-billable-units` header before being returned untouched. Installed as
97 * fal's `config.fetch`, which (unlike a global `responseHandler`) is honoured for
98 * every request — the fal client forces `resultResponseHandler` per queue
99 * operation, clobbering any configured response handler.
100 *
101 * `baseFetch` is the underlying implementation to delegate to (defaults to the
102 * global `fetch`). Injecting it keeps usage capture working when a caller
103 * supplies a custom fetch — a proxy, instrumentation, or a test mock — without
104 * mutating any global.
105 */
106export function createBillingFetch(
107 baseFetch: typeof fetch = globalThis.fetch,
108): typeof fetch {
109 return async (input, init) => {
110 const response = await baseFetch(input, init)
111 try {
112 recordBillableUnitsFromResponse(response)
113 } catch {
114 // Capturing usage must never break the underlying request.
115 }
116 return response
117 }