Open source CapCut alternative.
TypeScript
perf(site): read the credit balance without writing
David Lec1b961d8128c
diff --git a/site/src/lib/credits/inference.test.ts b/site/src/lib/credits/inference.test.tsindex 5ab9927d..720589db 100644--- a/site/src/lib/credits/inference.test.ts+++ b/site/src/lib/credits/inference.test.ts@@ -10,6 +10,9 @@ import { stubModule } from "@/lib/testing/stubModule";const recorded = { creditCostMicros: BigInt(0), remainingBalanceMicros: BigInt(0), usageEventId: "event" };let failures: Error[] = [];let attempts = 0;+let upserts = 0;+let account: { balanceMicros: bigint; lifetimeChargedMicros: bigint; lifetimeGrantedMicros: bigint } | null = null;+let lapsedMicros: bigint | null = null;const prisma = {$transaction: async () => {attempts += 1;@@ -19,10 +22,24 @@ const prisma = {}return recorded;},+ userCreditAccount: {+ findUnique: async () => account,+ findUniqueOrThrow: async () => account,+ upsert: async () => {+ upserts += 1;+ return account;+ },+ },+ userCreditGrant: {+ aggregate: async () => ({ _sum: { remainingAmountMicros: lapsedMicros } }),+ findMany: async () => [],+ },+ userCreditLimit: { findMany: async () => [] },+ inferenceUsageEvent: { findMany: async () => [] },};await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, { prisma: prisma as never });-const { recordInferenceUsage } = await import("./inference");+const { getCreditBalance, recordInferenceUsage } = await import("./inference");const usage = {clientId: null,@@ -67,3 +84,27 @@ describe("recording usage under concurrent charges", () => {expect(attempts).toBe(1);});});++// The balance is polled by every open editor, so the read never writes: credit+// past its expiry is netted out here and retired by the next charge.+describe("reading the balance", () => {+ test("nets out lapsed grants without writing", async () => {+ account = { balanceMicros: BigInt(5_000_000), lifetimeChargedMicros: BigInt(0), lifetimeGrantedMicros: BigInt(5_000_000) };+ lapsedMicros = BigInt(2_000_000);+ attempts = 0;+ upserts = 0;+ const balance = await getCreditBalance("user");+ expect(balance.balanceMicros).toBe("3000000");+ expect(attempts).toBe(0);+ expect(upserts).toBe(0);+ });++ test("an account without a row reads as empty", async () => {+ account = null;+ lapsedMicros = null;+ upserts = 0;+ const balance = await getCreditBalance("user");+ expect(balance.balanceMicros).toBe("0");+ expect(upserts).toBe(0);+ });+});diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.tsindex 875c2370..05533e85 100644--- a/site/src/lib/credits/inference.ts+++ b/site/src/lib/credits/inference.ts@@ -540,18 +540,33 @@ export async function recordFailedInferenceUsage(input: {}}+// Every open editor polls the balance, so the read stays one parallel round of+// selects. Credit past its expiry is netted out of the stored balance here;+// the next charge retires it in its own transaction (expireCreditsForAccount).export async function getCreditBalance(userId: string) {- await ensureCreditAccount(userId);- await expireCredits(userId);-- const account = await prisma.userCreditAccount.findUniqueOrThrow({- where: {- userId,- },- });const now = new Date();const recentSince = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);- const [grants, limits, recentUsageEvents] = await Promise.all([+ const [account, lapsed, grants, limits, recentUsageEvents] = await Promise.all([+ prisma.userCreditAccount.findUnique({+ where: {+ userId,+ },+ }),+ prisma.userCreditGrant.aggregate({+ _sum: {+ remainingAmountMicros: true,+ },+ where: {+ expiresAt: {+ lte: now,+ },+ remainingAmountMicros: {+ gt: zeroCreditMicros,+ },+ status: "active",+ userId,+ },+ }),prisma.userCreditGrant.findMany({orderBy: [{@@ -637,11 +652,14 @@ export async function getCreditBalance(userId: string) {}),]);+ // An account with no row yet has nothing granted or charged.+ const balanceMicros = (account?.balanceMicros ?? zeroCreditMicros) - (lapsed._sum.remainingAmountMicros ?? zeroCreditMicros);+return {- balance: creditMicrosToString(account.balanceMicros),- balanceMicros: account.balanceMicros.toString(),- lifetimeCharged: creditMicrosToString(account.lifetimeChargedMicros),- lifetimeGranted: creditMicrosToString(account.lifetimeGrantedMicros),+ balance: creditMicrosToString(balanceMicros),+ balanceMicros: balanceMicros.toString(),+ lifetimeCharged: creditMicrosToString(account?.lifetimeChargedMicros ?? zeroCreditMicros),+ lifetimeGranted: creditMicrosToString(account?.lifetimeGrantedMicros ?? zeroCreditMicros),activeGrants: grants.map((grant) => ({id: grant.id,source: grant.source,