Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

fix(payments): isolate catalog retries and expire stale Dodo attempts

Timothy Yin8c884797d11f
diff --git a/packages/platform/migrations/0031_dodo_sync_failures.sql b/packages/platform/migrations/0031_dodo_sync_failures.sql
new file mode 100644
index 00000000..5777f41a
--- /dev/null
+++ b/packages/platform/migrations/0031_dodo_sync_failures.sql
@@ -0,0 +1,12 @@
+CREATE TABLE platform_dodo_sync_failures(
+ provider_key TEXT NOT NULL REFERENCES platform_payment_providers(id),
+ plan_id TEXT NOT NULL REFERENCES platform_plans(id),
+ interval INTEGER NOT NULL CHECK(interval IN(1,3)),
+ plan_revision INTEGER NOT NULL,
+ credential_revision INTEGER NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 1,
+ next_attempt_at INTEGER NOT NULL,
+ error TEXT NOT NULL,
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY(provider_key,plan_id,interval)
+);
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index 04a71281..74cfb90a 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -71,82 +71,126 @@ export async function syncDodoProducts(
const plans = await allRows<any>(
db
.prepare(
- 'SELECT p.*,i.period FROM platform_plans p CROSS JOIN (SELECT 1 AS period UNION ALL SELECT 3) i LEFT JOIN platform_dodo_products d ON d.provider_key=? AND d.plan_id=p.id AND d.interval=i.period WHERE p.active=1 AND p.listed=1 AND CASE WHEN i.period=1 THEN p.monthly_price ELSE p.quarterly_price END>0 AND (d.product_id IS NULL OR d.plan_revision<>p.revision OR d.credential_revision<>?) ORDER BY p.sort_order,p.id,i.period LIMIT ?',
+ 'SELECT p.*,i.period,COALESCE(f.attempts,0) AS sync_attempts FROM platform_plans p CROSS JOIN (SELECT 1 AS period UNION ALL SELECT 3) i LEFT JOIN platform_dodo_products d ON d.provider_key=? AND d.plan_id=p.id AND d.interval=i.period LEFT JOIN platform_dodo_sync_failures f ON f.provider_key=? AND f.plan_id=p.id AND f.interval=i.period AND f.plan_revision=p.revision AND f.credential_revision=? WHERE (f.next_attempt_at IS NULL OR f.next_attempt_at<=?) AND p.active=1 AND p.listed=1 AND CASE WHEN i.period=1 THEN p.monthly_price ELSE p.quarterly_price END>0 AND (d.product_id IS NULL OR d.plan_revision<>p.revision OR d.credential_revision<>?) ORDER BY p.sort_order,p.id,i.period LIMIT ?',
)
- .bind(key, revision, limit),
+ .bind(key, key, revision, now, revision, limit),
)
let processed = 0
for (const plan of plans) {
- const price = Number(
- plan.period === 1 ? plan.monthly_price : plan.quarterly_price,
- )
- const snapshot = paymentProductSnapshot(plan, plan.period)
- const discountBps = Number(
- plan.period === 1
- ? plan.monthly_discount_bps
- : plan.quarterly_discount_bps,
- )
- const effectivePrice = discountedPrice(price, discountBps)!
- if (effectivePrice < 1) fail('payment_price_invalid', 400)
- const body = {
- name: snapshot.product.name,
- description: snapshot.product.description.slice(0, 1000),
- tax_category: 'saas' as const,
- price: {
- type: 'recurring_price' as const,
- currency: plan.currency,
- price,
- payment_frequency_count: plan.period,
- payment_frequency_interval: 'Month' as const,
- subscription_period_count: 20,
- subscription_period_interval: 'Year' as const,
- tax_inclusive: true,
- trial_period_days: 0,
- discount_bps: discountBps,
- purchasing_power_parity: false,
- },
- metadata: {
- chronoframe_plan_id: plan.id,
- chronoframe_interval: String(plan.period),
- chronoframe_profile_id: key,
- chronoframe_plan_revision: String(plan.revision),
- },
- }
- const product = await dodoRequest(() =>
- client.products.create(body, {
- idempotencyKey: `cf-product-${key}-${revision}-${plan.id}-${plan.revision}-${plan.period}`,
- headers: {
- 'Idempotency-Key': `cf-product-${key}-${revision}-${plan.id}-${plan.revision}-${plan.period}`,
- },
- }),
- )
- if (!identifier(product.product_id)) fail('payment_product_invalid', 502)
- await db
- .prepare(
- `INSERT INTO platform_dodo_products(provider_key,plan_id,interval,product_id,price,currency,discount_bps,effective_price,plan_revision,credential_revision,updated_at) SELECT ?,?,?,?,?,?,?,?,?,?,? WHERE ${activeFence} AND EXISTS(SELECT 1 FROM platform_dodo_sync_locks WHERE provider_key=? AND token=? AND expires_at>?) AND EXISTS(SELECT 1 FROM platform_plans WHERE id=? AND revision=?) ON CONFLICT(provider_key,plan_id,interval) DO UPDATE SET product_id=excluded.product_id,price=excluded.price,currency=excluded.currency,discount_bps=excluded.discount_bps,effective_price=excluded.effective_price,plan_revision=excluded.plan_revision,credential_revision=excluded.credential_revision,updated_at=excluded.updated_at`,
+ try {
+ const price = Number(
+ plan.period === 1 ? plan.monthly_price : plan.quarterly_price,
)
- .bind(
- key,
- plan.id,
- plan.period,
- product.product_id,
- price,
- plan.currency,
- discountBps,
- effectivePrice,
- plan.revision,
- revision,
- now,
- key,
- revision,
- key,
- syncToken,
- Date.now(),
- plan.id,
- plan.revision,
+ const snapshot = paymentProductSnapshot(plan, plan.period)
+ const discountBps = Number(
+ plan.period === 1
+ ? plan.monthly_discount_bps
+ : plan.quarterly_discount_bps,
)
- .run()
- processed++
+ const effectivePrice = discountedPrice(price, discountBps)!
+ if (effectivePrice < 1) fail('payment_price_invalid', 400)
+ const body = {
+ name: snapshot.product.name,
+ description: snapshot.product.description.slice(0, 1000),
+ tax_category: 'saas' as const,
+ price: {
+ type: 'recurring_price' as const,
+ currency: plan.currency,
+ price,
+ payment_frequency_count: plan.period,
+ payment_frequency_interval: 'Month' as const,
+ subscription_period_count: 20,
+ subscription_period_interval: 'Year' as const,
+ tax_inclusive: true,
+ trial_period_days: 0,
+ discount_bps: discountBps,
+ purchasing_power_parity: false,
+ },
+ metadata: {
+ chronoframe_plan_id: plan.id,
+ chronoframe_interval: String(plan.period),
+ chronoframe_profile_id: key,
+ chronoframe_plan_revision: String(plan.revision),
+ },
+ }
+ const product = await dodoRequest(() =>
+ client.products.create(body, {
+ idempotencyKey: `cf-product-${key}-${revision}-${plan.id}-${plan.revision}-${plan.period}`,
+ headers: {
+ 'Idempotency-Key': `cf-product-${key}-${revision}-${plan.id}-${plan.revision}-${plan.period}`,
+ },
+ }),
+ )
+ if (!identifier(product.product_id))
+ fail('payment_product_invalid', 502)
+ const published = await db
+ .prepare(
+ `INSERT INTO platform_dodo_products(provider_key,plan_id,interval,product_id,price,currency,discount_bps,effective_price,plan_revision,credential_revision,updated_at) SELECT ?,?,?,?,?,?,?,?,?,?,? WHERE ${activeFence} AND EXISTS(SELECT 1 FROM platform_dodo_sync_locks WHERE provider_key=? AND token=? AND expires_at>?) AND EXISTS(SELECT 1 FROM platform_plans WHERE id=? AND revision=?) ON CONFLICT(provider_key,plan_id,interval) DO UPDATE SET product_id=excluded.product_id,price=excluded.price,currency=excluded.currency,discount_bps=excluded.discount_bps,effective_price=excluded.effective_price,plan_revision=excluded.plan_revision,credential_revision=excluded.credential_revision,updated_at=excluded.updated_at`,
+ )
+ .bind(
+ key,
+ plan.id,
+ plan.period,
+ product.product_id,
+ price,
+ plan.currency,
+ discountBps,
+ effectivePrice,
+ plan.revision,
+ revision,
+ now,
+ key,
+ revision,
+ key,
+ syncToken,
+ Date.now(),
+ plan.id,
+ plan.revision,
+ )
+ .run()
+ if (published.meta.changes) {
+ await db
+ .prepare(
+ 'DELETE FROM platform_dodo_sync_failures WHERE provider_key=? AND plan_id=? AND interval=?',
+ )
+ .bind(key, plan.id, plan.period)
+ .run()
+ processed++
+ }
+ } catch (error) {
+ const code =
+ error instanceof SubscriptionError &&
+ [
+ 'payment_price_invalid',
+ 'payment_product_invalid',
+ 'payment_provider_request_failed',
+ ].includes(error.code)
+ ? error.code
+ : 'payment_product_sync_failed'
+ const attempts = Number(plan.sync_attempts) + 1
+ const nextAttempt =
+ now + Math.min(3600000, 30000 * 2 ** Math.min(attempts - 1, 7))
+ await db
+ .prepare(
+ `INSERT INTO platform_dodo_sync_failures(provider_key,plan_id,interval,plan_revision,credential_revision,attempts,next_attempt_at,error,updated_at) SELECT ?,?,?,?,?,?,?,?,? WHERE ${activeFence} AND EXISTS(SELECT 1 FROM platform_dodo_sync_locks WHERE provider_key=? AND token=?) ON CONFLICT(provider_key,plan_id,interval) DO UPDATE SET plan_revision=excluded.plan_revision,credential_revision=excluded.credential_revision,attempts=excluded.attempts,next_attempt_at=excluded.next_attempt_at,error=excluded.error,updated_at=excluded.updated_at`,
+ )
+ .bind(
+ key,
+ plan.id,
+ plan.period,
+ plan.revision,
+ revision,
+ attempts,
+ nextAttempt,
+ code,
+ now,
+ key,
+ revision,
+ key,
+ syncToken,
+ )
+ .run()
+ }
}
return { processed }
} finally {
@@ -918,6 +962,13 @@ export async function reconcileDodoPayments(
.run()
}
}
+ // The session's 24-hour validity has elapsed. Keep the immutable row for late provider events.
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='expired',error='payment_confirmation_unresolved',updated_at=? WHERE provider='dodo' AND environment=? AND provider_key=? AND state IN('creating','uncertain') AND updated_at<?",
+ )
+ .bind(now, environment, key, now - 86400000)
+ .run()
const pending = await allRows<any>(
db
.prepare(
@@ -982,7 +1033,7 @@ export async function closeDodoAccountPayments(
}
return !(await db
.prepare(
- "SELECT c.id FROM platform_payment_checkouts c JOIN platform_workspaces w ON w.id=c.workspace_id WHERE c.provider='dodo' AND (w.owner_user_id=? OR c.user_id=?) AND c.state IN('creating','open','uncertain') LIMIT 1",
+ "SELECT c.id FROM platform_payment_checkouts c JOIN platform_workspaces w ON w.id=c.workspace_id WHERE c.provider='dodo' AND (w.owner_user_id=? OR c.user_id=?) AND (c.state IN('creating','open','uncertain') OR (c.state='expired' AND c.error='payment_confirmation_unresolved')) LIMIT 1",
)
.bind(userId, userId)
.first())
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index 8a90fc64..72cdd2b4 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -16,6 +16,7 @@ import {
paymentSettings,
paymentStatus,
createPaymentCheckout,
+ closeAccountPayments,
} from '../packages/platform/src/payments.ts'
import {
syncDodoProducts,
@@ -394,7 +395,9 @@ test('official SDK isolates environments, synchronizes prices and creates a sign
)
await syncDodoProducts(f.db, root, f.transport)
assert.ok(
- f.calls.some((c) => c.url.startsWith('https://live.dodopayments.com')),
+ f.calls.some(
+ (c) => new URL(c.url).origin === 'https://live.dodopayments.com',
+ ),
)
assert.equal(
(
@@ -899,3 +902,233 @@ test('multiple named Dodo profiles in one environment isolate callbacks, product
await f.mf.dispose()
}
})
+
+test('product failures persist redacted backoff without starving later plans and reset after edits', async () => {
+ const f = await fixture()
+ try {
+ await f.db
+ .prepare(
+ "INSERT INTO platform_plans(id,name,policy_json,currency,monthly_price,quarterly_price) SELECT 'zzz','Later Plan',policy_json,'USD',2000,5000 FROM platform_plans WHERE id='free'",
+ )
+ .run()
+ let reject = true,
+ rejectedCalls = 0
+ const transport: typeof fetch = async (input, init) => {
+ const body = init?.body ? JSON.parse(String(init.body)) : null
+ if (
+ reject &&
+ body?.metadata?.chronoframe_plan_id === 'pro' &&
+ body.price.payment_frequency_count === 1
+ ) {
+ rejectedCalls++
+ return Response.json(
+ { message: 'private-provider-body-and-api-key' },
+ { status: 422 },
+ )
+ }
+ return f.transport(input, init)
+ }
+ assert.equal(
+ (await syncDodoProducts(f.db, root, transport, f.now)).processed,
+ 1,
+ )
+ let failure = await f.db
+ .prepare("SELECT * FROM platform_dodo_sync_failures WHERE plan_id='pro'")
+ .first<any>()
+ assert.equal(failure.attempts, 1)
+ assert.equal(failure.next_attempt_at, f.now + 30000)
+ assert.equal(failure.error, 'payment_provider_request_failed')
+ assert.ok(!JSON.stringify(failure).includes('private-provider'))
+ assert.equal(
+ (await syncDodoProducts(f.db, root, transport, f.now + 1)).processed,
+ 2,
+ )
+ assert.equal(rejectedCalls, 1)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ "SELECT COUNT(*) AS n FROM platform_dodo_products WHERE plan_id='zzz'",
+ )
+ .first<any>()
+ ).n,
+ 2,
+ )
+ await syncDodoProducts(f.db, root, transport, f.now + 30001)
+ failure = await f.db
+ .prepare("SELECT * FROM platform_dodo_sync_failures WHERE plan_id='pro'")
+ .first<any>()
+ assert.equal(failure.attempts, 2)
+ assert.equal(failure.next_attempt_at, f.now + 90001)
+ reject = false
+ await f.db
+ .prepare("UPDATE platform_plans SET revision=revision+1 WHERE id='pro'")
+ .run()
+ assert.equal(
+ (await syncDodoProducts(f.db, root, transport, f.now + 30002)).processed,
+ 2,
+ )
+ assert.equal(
+ await f.db
+ .prepare(
+ "SELECT * FROM platform_dodo_sync_failures WHERE plan_id='pro'",
+ )
+ .first(),
+ null,
+ )
+ // An invalid local price and an isolated row-publication failure are also per-plan failures.
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET monthly_price=1,monthly_discount_bps=9999,revision=revision+1 WHERE id='pro'",
+ )
+ .run()
+ assert.equal(
+ (await syncDodoProducts(f.db, root, transport, f.now + 30003)).processed,
+ 1,
+ )
+ failure = await f.db
+ .prepare("SELECT * FROM platform_dodo_sync_failures WHERE plan_id='pro'")
+ .first<any>()
+ assert.equal(failure.error, 'payment_price_invalid')
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET monthly_price=1200,monthly_discount_bps=0,revision=revision+1 WHERE id='pro'",
+ )
+ .run()
+ let failWrite = true
+ const db = {
+ prepare(sql: string) {
+ if (failWrite && sql.startsWith('INSERT INTO platform_dodo_products')) {
+ failWrite = false
+ throw Error('private database error')
+ }
+ return f.db.prepare(sql)
+ },
+ batch: (statements: any) => f.db.batch(statements),
+ }
+ assert.equal(
+ (await syncDodoProducts(db, root, transport, f.now + 30004)).processed,
+ 1,
+ )
+ failure = await f.db
+ .prepare("SELECT * FROM platform_dodo_sync_failures WHERE plan_id='pro'")
+ .first<any>()
+ assert.equal(failure.error, 'payment_product_sync_failed')
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('stale Dodo attempts release slots only in the active profile and remain reconcilable by late events', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ 'https://portal.example',
+ f.transport,
+ )
+ const { payment } = await f.paid(checkout),
+ event = await f.sign('payment.succeeded', payment, 'evt_late_payment')
+ const old = f.now - 86400001
+ await f.db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='uncertain',provider_id=NULL,updated_at=? WHERE id=?",
+ )
+ .bind(old, checkout.id)
+ .run()
+ for (const [workspace, id, key, environment, updated] of [
+ [2, 'stale_create', 'dodo_test', 'test', old],
+ [3, 'other_environment', 'dodo_live', 'live', old],
+ [4, 'fresh_create', 'dodo_test', 'test', f.now],
+ ] as const) {
+ if (workspace > 2) {
+ await f.db
+ .prepare(
+ 'INSERT INTO platform_users(id,email,name,email_verified,created_at,updated_at) VALUES(?,?,?,1,?,?)',
+ )
+ .bind(workspace, id + '@example.com', id, f.now, f.now)
+ .run()
+ await f.db
+ .prepare(
+ 'INSERT INTO platform_workspaces(id,name,owner_user_id,created_at) VALUES(?,?,?,?)',
+ )
+ .bind(workspace, id, workspace, f.now)
+ .run()
+ }
+ await f.db
+ .prepare(
+ "INSERT INTO platform_payment_checkouts(id,workspace_id,user_id,request_id,plan_id,interval,product_id,price,currency,assignment_revision,state,created_at,updated_at,provider,environment,provider_key) VALUES(?,?,2,?,'pro',1,'pdt_fixture',1200,'USD',1,'creating',?,?,'dodo',?,?)",
+ )
+ .bind(id, workspace, id, updated, updated, environment, key)
+ .run()
+ }
+ await f.db.prepare('UPDATE platform_payment_settings SET enabled=0').run()
+ await reconcileDodoPayments(f.db, root, f.transport, f.now)
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT state FROM platform_payment_checkouts WHERE id=?')
+ .bind(checkout.id)
+ .first<any>()
+ ).state,
+ 'uncertain',
+ )
+ await f.db.prepare('UPDATE platform_payment_settings SET enabled=1').run()
+ await reconcileDodoPayments(f.db, root, f.transport, f.now)
+ const rows = (
+ await f.db
+ .prepare('SELECT id,state FROM platform_payment_checkouts')
+ .all<any>()
+ ).results
+ const state = (id: string) => rows.find((row: any) => row.id === id)?.state
+ assert.equal(state(checkout.id), 'expired')
+ assert.equal(state('stale_create'), 'expired')
+ assert.equal(state('other_environment'), 'creating')
+ assert.equal(state('fresh_create'), 'creating')
+ // Expiration frees checkout capacity but does not declare unknown billing safe for account erasure.
+ assert.equal(await closeAccountPayments(f.db, root, 1, f.transport), false)
+ const retry = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input('retry_after_expiry'),
+ 'https://portal.example',
+ f.transport,
+ )
+ assert.ok(retry.url)
+ await receiveDodoEvent(
+ f.db,
+ root,
+ 'test',
+ event.body,
+ event.headers,
+ f.transport,
+ )
+ await processDodoEvents(f.db, root, f.transport)
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT state FROM platform_payment_checkouts WHERE id=?')
+ .bind(checkout.id)
+ .first<any>()
+ ).state,
+ 'completed',
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'pro',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})