Open source CapCut alternative.
TypeScript
feat(site): add vision-call grant ledger on UserCreditGrant
David Le2a4513b26082
diff --git a/site/prisma/Credits.prisma b/site/prisma/Credits.prismaindex 1c4fee4f..96935910 100644--- a/site/prisma/Credits.prisma+++ b/site/prisma/Credits.prisma@@ -22,6 +22,11 @@ model UserCreditGrant {user User @relation(fields: [userId], references: [id], onDelete: Cascade)source StringsourceId String?+ // What the amounts below are denominated in. "credit" = USD micros that feed+ // UserCreditAccount.balanceMicros. "vision_call" = a raw integer count of+ // Vision API calls that lives off-balance (never touches balanceMicros and is+ // consumed by the Vision API quota path, not by dollar inference).+ unit String @default("credit")originalAmountMicros BigIntremainingAmountMicros BigIntexpiresAt DateTime?@@ -34,10 +39,9 @@ model UserCreditGrant {updatedAt DateTime @updatedAtledgerEntries UserCreditLedgerEntry[]- @@unique([userId, source, sourceId])+ @@unique([userId, unit, source, sourceId])@@index([accountId])- @@index([userId, expiresAt])- @@index([userId, status])+ @@index([userId, unit, status])@@map("user_credit_grant")}diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.tsindex 7f687b9b..2d8f344a 100644--- a/site/src/lib/credits/inference.ts+++ b/site/src/lib/credits/inference.ts@@ -14,6 +14,13 @@ import {import { isJsonObject, toJsonValue } from "@/lib/inference/json";import type { JsonObject, JsonValue } from "@/lib/inference/providers";+// UserCreditGrant.unit values. Dollar grants ("credit") feed the account+// balance and pay for hosted inference; vision-call grants ("vision_call") are+// an off-balance integer count consumed only by the Vision API quota path.+export const creditGrantUnit = "credit";+export const visionCallGrantUnit = "vision_call";+export type CreditGrantUnit = typeof creditGrantUnit | typeof visionCallGrantUnit;+export const inferenceUsageRoutes = {assets: "/api/inference/assets/",assetsRefresh: "/api/inference/assets/refresh/",@@ -100,19 +107,9 @@ export class CreditLimitExceededError extends Error {}export async function ensureCreditAccount(userId: string) {- const account = await ensureCreditAccountRecord(prisma, userId);- const initialGrantMicros = initialFreeCreditMicros();- if (initialGrantMicros > zeroCreditMicros) {- await grantCredits({- userId,- amountMicros: initialGrantMicros,- source: "free",- sourceId: `first-use:${userId}`,- description: "Initial free credits",- });- }-- return account;+ // Signup grants are provisioned once at user creation (see+ // provisionSignupGrants); this only guarantees the account row exists.+ return ensureCreditAccountRecord(prisma, userId);}export async function grantCredits(input: {@@ -120,6 +117,7 @@ export async function grantCredits(input: {amountMicros: bigint;source: string;sourceId?: string;+ unit?: CreditGrantUnit;expiresAt?: Date;periodStart?: Date;periodEnd?: Date;@@ -130,11 +128,18 @@ export async function grantCredits(input: {throw new Error("Credit grants must be positive.");}+ const unit = input.unit ?? creditGrantUnit;+ // Only dollar grants move the account balance and write a balance-tracking+ // ledger entry. Vision-call grants are an off-balance count, so they create+ // just the grant row.+ const affectsBalance = unit === creditGrantUnit;+if (input.sourceId) {const existing = await prisma.userCreditGrant.findFirst({where: {source: input.source,sourceId: input.sourceId,+ unit,userId: input.userId,},});@@ -147,19 +152,21 @@ export async function grantCredits(input: {return await prisma.$transaction(async (tx) => {const account = await ensureCreditAccountRecord(tx, input.userId);- const updatedAccount = await tx.userCreditAccount.update({- data: {- balanceMicros: {- increment: input.amountMicros,- },- lifetimeGrantedMicros: {- increment: input.amountMicros,- },- },- where: {- id: account.id,- },- });+ const updatedAccount = affectsBalance+ ? await tx.userCreditAccount.update({+ data: {+ balanceMicros: {+ increment: input.amountMicros,+ },+ lifetimeGrantedMicros: {+ increment: input.amountMicros,+ },+ },+ where: {+ id: account.id,+ },+ })+ : account;const grant = await tx.userCreditGrant.create({data: {@@ -173,24 +180,27 @@ export async function grantCredits(input: {remainingAmountMicros: input.amountMicros,source: input.source,sourceId: input.sourceId,+ unit,userId: input.userId,},});- await tx.userCreditLedgerEntry.create({- data: {- accountId: account.id,- amountMicros: input.amountMicros,- balanceAfterMicros: updatedAccount.balanceMicros,- description: input.description,- grantId: grant.id,- metadata: prismaJson(input.metadata),- source: input.source,- sourceId: input.sourceId,- type: "grant",- userId: input.userId,- },- });+ if (affectsBalance) {+ await tx.userCreditLedgerEntry.create({+ data: {+ accountId: account.id,+ amountMicros: input.amountMicros,+ balanceAfterMicros: updatedAccount.balanceMicros,+ description: input.description,+ grantId: grant.id,+ metadata: prismaJson(input.metadata),+ source: input.source,+ sourceId: input.sourceId,+ type: "grant",+ userId: input.userId,+ },+ });+ }return grant;},@@ -208,6 +218,7 @@ export async function grantCredits(input: {where: {source: input.source,sourceId: input.sourceId,+ unit,userId: input.userId,},});@@ -421,6 +432,9 @@ export async function getCreditBalance(userId: string) {gt: zeroCreditMicros,},status: "active",+ // The dollar balance view lists dollar grants only; vision-call grants+ // are surfaced through the Vision API quota path.+ unit: creditGrantUnit,userId,OR: [{@@ -593,6 +607,9 @@ async function expireCreditsForAccount(gt: zeroCreditMicros,},status: "active",+ // Dollar grants only — vision-call grants are off-balance and expire via+ // their own path, so they must never decrement balanceMicros here.+ unit: creditGrantUnit,},});@@ -659,6 +676,9 @@ async function debitGrants(gt: zeroCreditMicros,},status: "active",+ // Dollar inference only spends dollar grants — vision-call grants are a+ // separate denomination and must never be debited here.+ unit: creditGrantUnit,},});@@ -1229,10 +1249,6 @@ function billingStatusFor(status: InferenceUsageStatus, creditCostMicros: bigintreturn creditCostMicros > zeroCreditMicros ? "charged" : "zero_cost";}-function initialFreeCreditMicros() {- return creditStringToMicros(process.env.DONKEY_INITIAL_FREE_CREDITS);-}-function prismaJson(value: JsonValue | undefined): Prisma.InputJsonValue | undefined {if (value === undefined || value === null) {return undefined;diff --git a/site/src/lib/credits/vision-grants.ts b/site/src/lib/credits/vision-grants.tsnew file mode 100644index 00000000..b89414a5--- /dev/null+++ b/site/src/lib/credits/vision-grants.ts@@ -0,0 +1,137 @@+import { Prisma } from "@/generated/prisma/client";++import { zeroCreditMicros } from "@/lib/credits/amounts";+import { grantCredits, visionCallGrantUnit } from "@/lib/credits/inference";+import { prisma } from "@/lib/prisma";++// Vision-call grants live in UserCreditGrant under unit="vision_call": an+// off-balance integer count (stored in remainingAmountMicros) that the dollar+// credit engine never touches. Consumption here is the *only* path that reads+// these rows, so the two denominations can never cross.++const oneCall = BigInt(1);+const maxReserveAttempts = 5;++function activeVisionGrantWhere(+ userId: string,+ now: Date,+): Prisma.UserCreditGrantWhereInput {+ return {+ remainingAmountMicros: { gt: zeroCreditMicros },+ status: "active",+ unit: visionCallGrantUnit,+ userId,+ OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],+ };+}++// Grant a one-time allotment of Vision API calls (signup bonus, promo, support+// comp). Idempotent via (userId, unit, source, sourceId); optionally expiring.+export async function grantVisionCalls(input: {+ userId: string;+ calls: number;+ source: string;+ sourceId?: string;+ expiresAt?: Date;+ description?: string;+}) {+ if (!Number.isInteger(input.calls) || input.calls <= 0) {+ throw new Error("Vision call grants must be a positive integer.");+ }++ return grantCredits({+ amountMicros: BigInt(input.calls),+ description: input.description,+ expiresAt: input.expiresAt,+ source: input.source,+ sourceId: input.sourceId,+ unit: visionCallGrantUnit,+ userId: input.userId,+ });+}++// Flip expired vision-call grants to "expired". These grants never moved the+// dollar balance, so a plain status update is the whole story (unlike dollar+// expiry, which must also decrement balanceMicros).+export async function expireVisionCallGrants(userId: string, now = new Date()) {+ await prisma.userCreditGrant.updateMany({+ data: { status: "expired" },+ where: {+ expiresAt: { lte: now },+ remainingAmountMicros: { gt: zeroCreditMicros },+ status: "active",+ unit: visionCallGrantUnit,+ userId,+ },+ });+}++// Total Vision API calls left across a user's active, unexpired grants.+export async function visionCallGrantRemaining(userId: string): Promise<bigint> {+ const now = new Date();+ await expireVisionCallGrants(userId, now);+ const aggregate = await prisma.userCreditGrant.aggregate({+ _sum: { remainingAmountMicros: true },+ where: activeVisionGrantWhere(userId, now),+ });++ return aggregate._sum.remainingAmountMicros ?? zeroCreditMicros;+}++// Atomically consume one call from the user's grants, oldest-expiring first.+// Mirrors the subscription quota reservation: a conditional decrement keyed to a+// specific grant row, so concurrent calls can't double-spend, retried against+// the next grant if a race empties the chosen one. Returns the debited grant id+// so a failed request can hand the call back.+export async function reserveVisionCallGrant(+ userId: string,+): Promise<{ ok: true; grantId: string; remaining: bigint } | { ok: false }> {+ const now = new Date();+ await expireVisionCallGrants(userId, now);++ for (let attempt = 0; attempt < maxReserveAttempts; attempt += 1) {+ const grant = await prisma.userCreditGrant.findFirst({+ orderBy: [+ { expiresAt: { sort: "asc", nulls: "last" } },+ { createdAt: "asc" },+ ],+ where: activeVisionGrantWhere(userId, now),+ });+ if (!grant) {+ return { ok: false };+ }++ const debited = await prisma.userCreditGrant.updateMany({+ data: { remainingAmountMicros: { decrement: oneCall } },+ where: {+ id: grant.id,+ remainingAmountMicros: { gt: zeroCreditMicros },+ status: "active",+ },+ });+ if (debited.count === 0) {+ // Another request emptied this grant first; try the next candidate.+ continue;+ }++ // Drop the grant out of future selection once it reaches zero.+ await prisma.userCreditGrant.updateMany({+ data: { status: "exhausted" },+ where: { id: grant.id, remainingAmountMicros: { lte: zeroCreditMicros } },+ });++ return { grantId: grant.id, ok: true, remaining: await visionCallGrantRemaining(userId) };+ }++ return { ok: false };+}++// Hand a reserved call back to its grant when the request ultimately fails, so a+// failed parse doesn't burn the allotment. Re-activates a grant the reservation+// had just exhausted (but never resurrects an expired one).+export async function releaseVisionCallGrant(grantId: string) {+ await prisma.userCreditGrant.updateMany({+ data: { remainingAmountMicros: { increment: oneCall }, status: "active" },+ where: { id: grantId, status: { not: "expired" } },+ });+}