release - #2310
Merged
Merged
Conversation
Import eligible Stripe subscriptions and schedules during initial customer creation, coordinate with subscription-created webhooks, and cover idempotency, schedules, and license quantities.
Keep customer-wide Stripe discovery as an internal sync helper, make lock wrappers explicit, and cover creation boundaries with eight integration scenarios.
…on-creation fix(customers): sync stripe billing on customer creation
Contributor
|
Capy auto-review is paused for this organization because the usage-cycle auto-review limit has been reached. Increase the limit or turn it off in billing settings to resume automatic reviews. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary by cubic
Auto-syncs eligible Stripe subscriptions and schedules when creating a customer, and serializes syncs to prevent duplicates and race conditions. This ensures existing Stripe billing is imported once, preserves license quantities, and avoids duplicating paid defaults.
New Features
stripe_idis provided) viaprepareAutoSyncStripeCustomerandautoSyncStripeCustomerWithLock.withStripeSyncCustomerLock); also applied to the subscription-created webhook.canAutoSyncallows; supports schedule phases and keeps seat/license quantities exact.Bug Fixes
Written for commit f60544e. Summary will update on new commits.
Greptile Summary
This PR adds automatic Stripe-to-Autumn synchronisation when a customer is created with an existing
stripe_id: pending subscriptions and schedules are imported under a Redis spin-lock that also serialises concurrentsubscription.createdwebhook deliveries, preventing double-imports.syncCreatedCustomerFromStripestep increateCustomerWithDefaultsfetches all unlinked Stripe subscriptions/schedules and syncs them before attaching paid defaults, guarded by a per-customer Redis lock shared with the webhook handler.autoSyncFromSubscription(webhook path) now re-fetches fresh customer state inside the lock, so a webhook that fires concurrently with a create-sync sees the already-imported subscription and skips it.shouldAttachPaidDefaultsis now gated onhasActivePaidSubscription, preventing a duplicate Stripe subscription from being created when the import already brought in an active one.Confidence Score: 3/5
The customer-creation path now has an unrecoverable sync gap: if the Stripe import throws on first attempt, any subsequent retry returns the existing customer immediately without re-running the sync.
The early-return for existing customers (line 70 of createCustomerWithDefaults) was written before the sync step was introduced. With the new ordering, a transient Stripe error on first creation creates a customer record in the DB and a failed sync; every subsequent retry hits the early-return and silently returns the customer without synced subscriptions. The lock implementation also shares a TTL/deadline value and relies on an unchecked DEL, which could break serialisation under sustained load.
createCustomerWithDefaults.ts and autoSyncStripeCustomer.ts need the most attention — the retry bypass and sequential-failure behaviour interact to permanently strand partially-synced customers.
Important Files Changed
Sequence Diagram
%%{init: {'theme': 'neutral'}}%% sequenceDiagram participant API as customers.create API participant CWD as createCustomerWithDefaults participant SCFS as syncCreatedCustomerFromStripe participant ASWL as autoSyncStripeCustomerWithLock participant Lock as withStripeSyncCustomerLock (Redis) participant PASC as prepareAutoSyncStripeCustomer participant Stripe as Stripe API participant DB as Database (CusService) participant Webhook as Stripe Webhook Handler API->>CWD: create(customerId, stripe_id) CWD->>CWD: Phase 1 — create Autumn customer CWD->>SCFS: syncCreatedCustomerFromStripe(stripe_id) SCFS->>ASWL: autoSyncStripeCustomerWithLock(customerId) ASWL->>Lock: acquire lock:stripe-sync:org:env:customerId Lock-->>ASWL: acquired ASWL->>PASC: prepareAutoSyncStripeCustomer PASC->>Stripe: list subscriptions + schedules PASC->>DB: CusService.getFull (current state) PASC-->>ASWL: syncCandidates (pending only) loop each syncCandidate ASWL->>DB: syncV2(params) end ASWL->>Lock: clearLock Lock-->>ASWL: released SCFS->>DB: CusService.getFull (refreshed) SCFS-->>CWD: updated fullCustomer CWD->>CWD: skip paid defaults if active subscription exists CWD-->>API: FullCustomer%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%% sequenceDiagram participant API as customers.create API participant CWD as createCustomerWithDefaults participant SCFS as syncCreatedCustomerFromStripe participant ASWL as autoSyncStripeCustomerWithLock participant Lock as withStripeSyncCustomerLock (Redis) participant PASC as prepareAutoSyncStripeCustomer participant Stripe as Stripe API participant DB as Database (CusService) participant Webhook as Stripe Webhook Handler API->>CWD: create(customerId, stripe_id) CWD->>CWD: Phase 1 — create Autumn customer CWD->>SCFS: syncCreatedCustomerFromStripe(stripe_id) SCFS->>ASWL: autoSyncStripeCustomerWithLock(customerId) ASWL->>Lock: acquire lock:stripe-sync:org:env:customerId Lock-->>ASWL: acquired ASWL->>PASC: prepareAutoSyncStripeCustomer PASC->>Stripe: list subscriptions + schedules PASC->>DB: CusService.getFull (current state) PASC-->>ASWL: syncCandidates (pending only) loop each syncCandidate ASWL->>DB: syncV2(params) end ASWL->>Lock: clearLock Lock-->>ASWL: released SCFS->>DB: CusService.getFull (refreshed) SCFS-->>CWD: updated fullCustomer CWD->>CWD: skip paid defaults if active subscription exists CWD-->>API: FullCustomerComments Outside Diff (3)
server/src/internal/customers/actions/createWithDefaults/createCustomerWithDefaults.ts, line 70 (link)When
syncCreatedCustomerFromStripethrows on the firstcustomers.create()call (e.g., a transient Stripe API error or lock timeout), the customer record is already committed to the DB (Phase 1 succeeded). On any subsequent retry,autumnResult.type === "existing"causes an early return here — before thetryblock that hosts the sync call is ever reached. The caller receives a200response with the customer, but the Stripe subscriptions are never imported. There is currently no mechanism inside the create path to re-attempt the sync once the customer record already exists.Prompt To Fix With AI
server/src/internal/billing/v2/actions/sync/utils/withStripeSyncCustomerLock.ts, line 242-277 (link)clearLockuses uncheckedDELLOCK_TIMEOUT_MS(30 s) is used both as the Redis key TTL and as the maximum acquisition wait. Ifrun()takes longer than 30 s (e.g., many subscriptions + slow Stripe responses), the key expires in Redis, a waiting process acquires a brand-new lock, and when the original holder finishes and reachesclearLock→redis.del(lockKey), it deletes the new holder's lock without any ownership check. A third waiter can then acquire the lock while the second holder is still running, breaking the serialisation guarantee and potentially causing concurrent syncs for the same customer. Consider setting the key TTL longer than the expected worst-caserun()duration (e.g., 2–3×), keeping the acquisition deadline at 30 s; or, longer term, storing a unique token in the lock value and checking it before deletion.Prompt To Fix With AI
server/src/internal/billing/v2/actions/sync/autoSyncStripeCustomer.ts, line 119-128 (link)The
forloop awaitssyncV2sequentially with no per-iteration error handling. IfsyncV2throws for subscription N, the exception escapes the loop, propagates throughwithStripeSyncCustomerLock, and surfaces as a failure insyncCreatedCustomerFromStripe. Subscriptions N+1, N+2, … are never processed. Because of the early-return issue on retry (line 70 ofcreateCustomerWithDefaults), those subscriptions then stay unsynced indefinitely. Wrapping each iteration in a try/catch to log and continue would make the sync best-effort and resilient to individual failures.Prompt To Fix With AI
Prompt To Fix All With AI
Reviews (1): Last reviewed commit: "Merge pull request #2308 from useautumn/..." | Re-trigger Greptile