Skip to content

Open source CapCut alternative.

TypeScript

fix(site): retry credit grant and expire transactions on write conflict

David Lecd15d3ee3afb
diff --git a/site/scripts/backfill-signup-credit.ts b/site/scripts/backfill-signup-credit.ts
new file mode 100644
index 00000000..a5082720
--- /dev/null
+++ b/site/scripts/backfill-signup-credit.ts
@@ -0,0 +1,34 @@
+#!/usr/bin/env bun
+/**
+ * One-off: re-grant the signup app credit to accounts whose provisioning lost
+ * the write-conflict race at signup (P2034) before grantCredits retried on
+ * conflict. Idempotent — grantCredits dedupes on (source, sourceId, userId) —
+ * so re-running or listing an already-granted user is a no-op.
+ *
+ * Run from site/ with production credentials in the environment:
+ * bun run scripts/backfill-signup-credit.ts <userId> [<userId> ...]
+ */
+
+import { creditStringToMicros } from "../src/lib/credits/amounts";
+import { grantCredits } from "../src/lib/credits/inference";
+import { signupAppCredits } from "../src/lib/onboarding/sequence";
+import { prisma } from "../src/lib/prisma";
+
+const userIds = process.argv.slice(2);
+if (userIds.length === 0) {
+ console.error("usage: bun run scripts/backfill-signup-credit.ts <userId> [<userId> ...]");
+ process.exit(1);
+}
+
+for (const userId of userIds) {
+ const grant = await grantCredits({
+ amountMicros: creditStringToMicros(signupAppCredits),
+ description: "Signup bonus credits",
+ source: "signup",
+ sourceId: `signup-app-credit:${userId}`,
+ userId,
+ });
+ console.log(`${userId}: grant ${grant.id} (${grant.originalAmountMicros} micros)`);
+}
+
+await prisma.$disconnect();
diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.ts
index 9f4f05b2..d9f099d0 100644
--- a/site/src/lib/credits/inference.ts
+++ b/site/src/lib/credits/inference.ts
@@ -175,7 +175,7 @@ export async function grantCredits(input: {
}
try {
- return await prisma.$transaction(
+ return await withWriteConflictRetry(() => prisma.$transaction(
async (tx) => {
const account = await ensureCreditAccountRecord(tx, input.userId);
// An account already carrying an overdraft — one that predates the
@@ -239,7 +239,7 @@ export async function grantCredits(input: {
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
},
- );
+ ));
} catch (error) {
if (
input.sourceId &&
@@ -264,7 +264,7 @@ export async function grantCredits(input: {
}
export async function expireCredits(userId: string, now = new Date()) {
- await prisma.$transaction(
+ await withWriteConflictRetry(() => prisma.$transaction(
async (tx) => {
const account = await ensureCreditAccountRecord(tx, userId);
await expireCreditsForAccount(tx, account.id, userId, account.balanceMicros, now);
@@ -272,7 +272,7 @@ export async function expireCredits(userId: string, now = new Date()) {
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
},
- );
+ ));
}
export async function assertCanUseInference(input: CreditPreflightInput) {
@@ -348,9 +348,10 @@ export async function requireInferenceCredits(input: CreditPreflightInput) {
// Prisma raises P2034 when a transaction is aborted by a write conflict or
// deadlock. A Serializable transaction rolls back entirely on conflict, so
// nothing partially committed and the whole body is safe to re-run. Concurrent
-// charges against the same credit account (e.g. two generations at once)
-// routinely collide here; retrying transparently avoids surfacing a billing
-// race as a user-facing generation failure.
+// writers against the same credit account routinely collide here — two
+// generations at once, the parallel signup grants, simultaneous Stripe webhook
+// deliveries for one checkout — so every credit transaction retries
+// transparently instead of surfacing the race to its caller.
async function withWriteConflictRetry<T>(run: () => Promise<T>): Promise<T> {
const maxAttempts = 5;
for (let attempt = 1; ; attempt += 1) {