Compare commits

...

2 Commits

Author SHA1 Message Date
Jack Jiang c4219eb9a7 fix(console): reuse workspace Stripe customers 2026-08-05 18:15:26 +00:00
Aiden Cline f929f8f100 refactor(opencode): simplify retry error matching (#40694) 2026-08-05 13:05:19 -05:00
4 changed files with 69 additions and 72 deletions
@@ -87,24 +87,7 @@ const createSetupIntent = async (input: { plan: string; workspaceID: string }) =
return { error: formError.alreadySubscribed }
}
let customerID = customer?.customerID
if (!customerID) {
const customer = await Billing.stripe().customers.create({
email,
metadata: {
workspaceID,
},
})
customerID = customer.id
await Database.use((tx) =>
tx
.update(BillingTable)
.set({
customerID,
})
.where(eq(BillingTable.workspaceID, workspaceID)),
)
}
const customerID = await Billing.ensureCustomer(email)
const intent = await Billing.stripe().setupIntents.create({
customer: customerID,
+49 -27
View File
@@ -42,6 +42,39 @@ export namespace Billing {
)
}
export const ensureCustomer = async (email?: string) => {
const billing = await get()
if (billing?.customerID) return billing.customerID
const workspaceID = Actor.workspace()
const stripe = Billing.stripe()
const created = await stripe.customers.create(
{
metadata: {
workspaceID,
},
},
{
idempotencyKey: `opencode-workspace-customer:${workspaceID}`,
},
)
await Database.use((tx) =>
tx
.update(BillingTable)
.set({
customerID: created.id,
})
.where(and(eq(BillingTable.workspaceID, workspaceID), isNull(BillingTable.customerID))),
)
const customerID = (await get())?.customerID
if (!customerID) throw new Error(`Workspace with ID ${workspaceID} not found`)
if (customerID === created.id && email) {
await stripe.customers.update(customerID, { email })
}
return customerID
}
export const payments = async () => {
return await Database.use((tx) =>
tx
@@ -231,8 +264,9 @@ export namespace Billing {
}
const email = await User.getAuthEmail(user.properties.userID)
const customer = await Billing.get()
const amountInCents = (amount ?? customer.reloadAmount ?? Billing.RELOAD_AMOUNT) * 100
const billing = await Billing.get()
const customerID = await Billing.ensureCustomer(email ?? undefined)
const amountInCents = (amount ?? billing.reloadAmount ?? Billing.RELOAD_AMOUNT) * 100
const session = await Billing.stripe().checkout.sessions.create({
mode: "payment",
billing_address_collection: "required",
@@ -254,18 +288,11 @@ export namespace Billing {
quantity: 1,
},
],
...(customer.customerID
? {
customer: customer.customerID,
customer_update: {
name: "auto",
address: "auto",
},
}
: {
customer_email: email!,
customer_creation: "always",
}),
customer: customerID,
customer_update: {
name: "auto",
address: "auto",
},
currency: "usd",
invoice_creation: {
enabled: true,
@@ -311,6 +338,7 @@ export namespace Billing {
if (billing.subscriptionID) throw new Error("Already subscribed to Black")
if (billing.liteSubscriptionID) throw new Error("Already subscribed to Lite")
const customerID = await Billing.ensureCustomer(email)
const coupons = await Database.use((tx) =>
tx
@@ -335,17 +363,11 @@ export namespace Billing {
Billing.stripe().checkout.sessions.create({
mode: "subscription",
discounts: coupon ? [{ coupon }] : undefined,
...(billing.customerID
? {
customer: billing.customerID,
customer_update: {
name: "auto",
address: "auto",
},
}
: {
customer_email: email,
}),
customer: customerID,
customer_update: {
name: "auto",
address: "auto",
},
...(() => {
if (method === "alipay") {
return {
@@ -411,14 +433,14 @@ export namespace Billing {
// get pending payment intent
const intents = await Billing.stripe().paymentIntents.search({
query: `-status:'canceled' AND -status:'processing' AND -status:'succeeded' AND customer:'${billing.customerID}'`,
query: `-status:'canceled' AND -status:'processing' AND -status:'succeeded' AND customer:'${customerID}'`,
})
if (intents.data.length === 0) throw e
for (const intent of intents.data) {
// get checkout session
const sessions = await Billing.stripe().checkout.sessions.list({
customer: billing.customerID!,
customer: customerID,
payment_intent: intent.id,
})
+12 -25
View File
@@ -122,32 +122,19 @@ export function retryable(error: Err, provider: string) {
return { message: error.data.message.includes("Overloaded") ? "Provider is overloaded" : error.data.message }
}
// Check for rate limit patterns in plain text error messages
const msg = isRecord(error.data) ? error.data.message : undefined
if (typeof msg === "string") {
const lower = msg.toLowerCase()
if (
lower.includes("rate increased too quickly") ||
lower.includes("rate limit") ||
lower.includes("too many requests")
) {
return { message: msg }
}
}
const json = parseJSON(msg)
if (!json || typeof json !== "object") return undefined
const code = typeof json.code === "string" ? json.code : ""
if (json.type === "error" && json.error?.type === "too_many_requests") {
return { message: "Too Many Requests" }
}
if (code.includes("exhausted") || code.includes("unavailable")) {
return { message: "Provider is overloaded" }
}
if (json.type === "error" && typeof json.error?.code === "string" && json.error.code.includes("rate_limit")) {
return { message: "Rate Limited" }
const message = isRecord(error.data) ? error.data.message : undefined
if (typeof message !== "string") return undefined
const lower = message.toLowerCase()
if (
lower.includes("rate increased too quickly") ||
lower.includes("rate limit") ||
lower.includes("rate_limit") ||
lower.includes("too many requests")
) {
return { message }
}
if (lower.includes("too_many_requests")) return { message: "Too Many Requests" }
if (lower.includes("exhausted") || lower.includes("unavailable")) return { message: "Provider is overloaded" }
return undefined
}
+7 -2
View File
@@ -118,16 +118,21 @@ describe("session.retry.delay", () => {
})
describe("session.retry.retryable", () => {
test("maps too_many_requests json messages", () => {
test("retries serialized too_many_requests messages", () => {
const error = wrap(JSON.stringify({ type: "error", error: { type: "too_many_requests" } }))
expect(SessionRetry.retryable(error, retryProvider)).toEqual({ message: "Too Many Requests" })
})
test("maps overloaded provider codes", () => {
test("retries serialized overloaded provider codes", () => {
const error = wrap(JSON.stringify({ code: "resource_exhausted" }))
expect(SessionRetry.retryable(error, retryProvider)).toEqual({ message: "Provider is overloaded" })
})
test("retries serialized rate_limit messages", () => {
const message = JSON.stringify({ type: "error", error: { code: "rate_limit_exceeded" } })
expect(SessionRetry.retryable(wrap(message), retryProvider)).toEqual({ message })
})
test("does not retry unknown json messages", () => {
const error = wrap(JSON.stringify({ error: { message: "no_kv_space" } }))
expect(SessionRetry.retryable(error, retryProvider)).toBeUndefined()