MCPcopy Create free account
hub / github.com/Kilo-Org/cloud / recordExaUsage

Function recordExaUsage

apps/web/src/lib/exa-usage.ts:69–123  ·  view source on GitHub ↗
(params: {
  userId: string;
  organizationId: string | undefined;
  path: string;
  costMicrodollars: number;
  chargedToBalance: boolean;
  freeAllowanceMicrodollars: number;
  featureId?: string;
  type?: string;
})

Source from the content-addressed store, hash-verified

67 */
68 deadlineMs?: number;
69 fromDb?: typeof db;
70};
71
72/** The documented server `statement_timeout`; the caller's remaining budget may only tighten it. */
73const WRITE_ACTIVE_TIMEOUT_MS = 120_000;
74/** A suspended client is idle between statements; this bounds how long its transaction may sit. */
75const WRITE_IDLE_TIMEOUT_MS = 60_000;
76
77/**
78 * Records the source row, monthly counter, and charged owner mutation atomically.
79 * A repeated `id`/`occurredAt` pair is a no-op, so retries cannot double-charge; a
80 * committed record keeps answering `duplicate` even when its payer no longer resolves.
81 * A record whose named payer cannot be resolved resolves to `rejected` and writes
82 * nothing; low-balance notification scheduling happens only after a commit.
83 */
84export async function recordExaUsage(
85 record: ExaUsageRecord,
86 options: ExaUsageWriteOptions = {}
87): Promise<ExaUsageWriteResponse['status']> {
88 const {
89 id,
90 occurredAt,
91 userId,
92 path,
93 costMicrodollars,
94 chargedToBalance,
95 freeAllowanceMicrodollars,
96 featureId,
97 type,
98 } = record;
99 const organizationId = record.organizationId ?? undefined;
100 const chargedAmount = chargedToBalance ? costMicrodollars : 0;
101
102 const outcome = await (options.fromDb ?? db).transaction(async tx => {
103 if (options.deadlineMs !== undefined) {
104 const budgetMs = Math.max(1_000, Math.floor(options.deadlineMs));
105 const activeTimeoutMs = Math.min(budgetMs, WRITE_ACTIVE_TIMEOUT_MS);
106 const idleTimeoutMs = Math.min(budgetMs, WRITE_IDLE_TIMEOUT_MS);
107 // PostgreSQL rejects a parameterized SET; Math.floor above proves these are integers.
108 await tx.execute(sql.raw(`SET LOCAL lock_timeout = '${activeTimeoutMs}'`));
109 await tx.execute(sql.raw(`SET LOCAL statement_timeout = '${activeTimeoutMs}'`));
110 await tx.execute(
111 sql.raw(`SET LOCAL idle_in_transaction_session_timeout = '${idleTimeoutMs}'`)
112 );
113 }
114
115 const rejectionReason = await unresolvablePayer(tx, {
116 userId,
117 organizationId: organizationId ?? null,
118 });
119 if (rejectionReason) {
120 const [committed] = await tx
121 .select({ id: exa_usage_log.id })
122 .from(exa_usage_log)
123 .where(and(eq(exa_usage_log.id, id), eq(exa_usage_log.created_at, occurredAt)))
124 .limit(1);
125 if (committed) {
126 return { status: 'duplicate' as const, organizationUsage: null };

Callers 2

exa-usage.test.tsFile · 0.90
POSTFunction · 0.90

Calls 3

upsertMonthlyCounterFunction · 0.85
deductFromBalanceFunction · 0.85
valuesMethod · 0.65

Tested by

no test coverage detected