Compare commits

..

3 Commits

Author SHA1 Message Date
Aiden Cline 4fa56a8a71 fix(opencode): expand retryable error patterns 2026-08-05 13:13:19 -05:00
Aiden Cline b76df6c359 test(opencode): cover serialized rate limits 2026-08-05 12:31:32 -05:00
Aiden Cline e3366180ae refactor(opencode): simplify retry error matching 2026-08-05 12:30:50 -05:00
4 changed files with 66 additions and 58 deletions
@@ -87,7 +87,24 @@ const createSetupIntent = async (input: { plan: string; workspaceID: string }) =
return { error: formError.alreadySubscribed }
}
const customerID = await Billing.ensureCustomer(email)
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 intent = await Billing.stripe().setupIntents.create({
customer: customerID,
+27 -49
View File
@@ -42,39 +42,6 @@ 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
@@ -264,9 +231,8 @@ export namespace Billing {
}
const email = await User.getAuthEmail(user.properties.userID)
const billing = await Billing.get()
const customerID = await Billing.ensureCustomer(email ?? undefined)
const amountInCents = (amount ?? billing.reloadAmount ?? Billing.RELOAD_AMOUNT) * 100
const customer = await Billing.get()
const amountInCents = (amount ?? customer.reloadAmount ?? Billing.RELOAD_AMOUNT) * 100
const session = await Billing.stripe().checkout.sessions.create({
mode: "payment",
billing_address_collection: "required",
@@ -288,11 +254,18 @@ export namespace Billing {
quantity: 1,
},
],
customer: customerID,
customer_update: {
name: "auto",
address: "auto",
},
...(customer.customerID
? {
customer: customer.customerID,
customer_update: {
name: "auto",
address: "auto",
},
}
: {
customer_email: email!,
customer_creation: "always",
}),
currency: "usd",
invoice_creation: {
enabled: true,
@@ -338,7 +311,6 @@ 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
@@ -363,11 +335,17 @@ export namespace Billing {
Billing.stripe().checkout.sessions.create({
mode: "subscription",
discounts: coupon ? [{ coupon }] : undefined,
customer: customerID,
customer_update: {
name: "auto",
address: "auto",
},
...(billing.customerID
? {
customer: billing.customerID,
customer_update: {
name: "auto",
address: "auto",
},
}
: {
customer_email: email,
}),
...(() => {
if (method === "alipay") {
return {
@@ -433,14 +411,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:'${customerID}'`,
query: `-status:'canceled' AND -status:'processing' AND -status:'succeeded' AND customer:'${billing.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: customerID,
customer: billing.customerID!,
payment_intent: intent.id,
})
+8 -8
View File
@@ -28,6 +28,13 @@ 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)
}
@@ -125,16 +132,9 @@ 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,6 +168,19 @@ 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)