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 58 additions and 66 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,
})
+8 -8
View File
@@ -28,13 +28,6 @@ export const RETRY_BACKOFF_FACTOR = 2
export const RETRY_MAX_DELAY_NO_HEADERS = 30_000 // 30 seconds
export const RETRY_MAX_DELAY = 2_147_483_647 // max 32-bit signed integer for setTimeout
const RETRYABLE_MESSAGE = [
/\b(?:server[_\s-]?error|internal[_\s-]?error|service[_\s-]?unavailable|overloaded|too many requests|rate increased too quickly|provider[_\s-]?returned[_\s-]?error)\b|\brate[_\s-]?limit/i,
/\b(?:fetch failed|network error|upstream connect|connection (?:error|refused|lost)|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again)\b|^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed? out)\b/i,
/\b(?:resource[_\s-]?exhausted|please retry your request|you can retry your request|try your request again)\b/i,
/\b(?:429|500|502|503|504|524)\b/,
]
function cap(ms: number) {
return Math.min(ms, RETRY_MAX_DELAY)
}
@@ -132,9 +125,16 @@ export function retryable(error: Err, provider: string) {
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" }
if (RETRYABLE_MESSAGE.some((pattern) => pattern.test(message))) return { message }
return undefined
}
@@ -168,19 +168,6 @@ describe("session.retry.retryable", () => {
expect(SessionRetry.retryable(error, retryProvider)).toEqual({ message: msg })
})
test.each([
"Internal server error",
"Provider returned error",
"fetch failed",
"connection refused",
"EAI_AGAIN",
"response timed out",
"Please retry your request",
"upstream returned status 524",
])("retries matching API error text: %s", (message) => {
expect(SessionRetry.retryable(wrap(message), retryProvider)).toEqual({ message })
})
test("retries transport timeout errors", () => {
const request = MessageV2.fromError(new ProviderError.HeaderTimeoutError(10000), { providerID })
expect(SessionV1.APIError.isInstance(request)).toBe(true)