Repository navigation
Conversation
subscription.created and subscription.updated
a60b927 to
0c08ac6
Compare
0c08ac6 to
78dffd9
Compare
…ooks-handlers # Conflicts: # lib/plausible/billing/paddle_billing/webhook_signature.ex
|
Merged #6909 here, diff against |
RobertJoonas
left a comment
There was a problem hiding this comment.
Neat! Thanks for a detailed description and a well built-up PR! Kudos for the test coverage too! 🙌
Left a few comments inline. Since I'm not fully sure whether any of them are blocking, I'll leave it up to you decide. Approved ✅
|
|
||
| # Paddle doesn't guarantee delivery order. An event is stale when another event | ||
| # of the same subscription, with a later `occurred_at`, is already stored. | ||
| defp stale?(billing_subscription_id, event_id, occurred_at) do |
There was a problem hiding this comment.
I wonder if we should also account for two different webhook events for the same subscription arriving very close to each other? I.e. we end up processing them at the same time, the first transaction isn't committed yet before the second one starts, neither stale?/3 call sees the other event and the older one can overwrite the newer state.
I'm not sure how likely that is to happen, but we might want to consider an advisory lock on the subscription ID.
There was a problem hiding this comment.
I was thinking we could solve that with row-level locks and upserts, but it gets pretty complex pretty fast (if not impossible). Your idea about using advisory locks seems to be a better option. I'd even opt for creating a lock on team ID so that we can more straightforwardly resolve issues like two created events coming in for the same team but for 2 different subscriptions (highly unlikely, but still theoretically possible).
There was a problem hiding this comment.
That's a good start! I'd consider simplifying at least part of upserts into inserts/updates. Another thing would be detecting situations like attempting insertion of a new subscription with existing one active, for instance.
| existing = Repo.get_by(Subscription, billing_subscription_id: billing_subscription_id) | ||
|
|
||
| case {kind, existing} do | ||
| {:updated, nil} -> {:error, :subscription_not_found} |
There was a problem hiding this comment.
The subscription.updated webhook returning 400 for this reason can keep Paddle retrying until exhaustion. I wonder if we should prevent that to avoid noise in the logs and webhook_failures? The following scenario is quite realistic I think:
- A team schedules their subscription to be cancelled in 20 days
- After 10 days, the team creates a new subscription which overwrites the existing one (only one billing subscription can exist at a time)
- After 20 days, when a
subscription.updatedwithstatus: canceledfinally arrives, a subscription with this ID is not found - Paddle will keep retrying up to 60 times, during ~2 days
I understand we can't just return 200 for any unknown subscription because we still need to let Paddle retry when subscription.updated of a subscription that was just created, arrives before subscription.created. But we could perhaps use billing_subscription_events to tell these two cases apart? If there are existing events for this subscription ID, we know that it has been replaced by a new one. WDYT?
There was a problem hiding this comment.
oof I think your comment uncovers that I had forgotten to implement "only one active subscription" can exist for Billing. IIRC we were planning for this with Adrian, let me get back to this
There was a problem hiding this comment.
We have normalised billing_subscription_id (along with all the other fields) in SubscriptionEvent schema. We could fall back on looking up the most recent entry in the events table and treat that as a "stale" event insertion. However, we should still ensure it doesn't do something unexpected, like changing the canceled subscription back to active (unlikely, but still). Then it should legit crash.
IMHO it would be better to avoid relaxing the one-team-one-billing-subscription constraint, if possible.
| end | ||
|
|
||
| defp process(kind, %{"event_id" => event_id, "data" => %{} = data} = event) do | ||
| with :ok <- check_not_seen(event_id), |
There was a problem hiding this comment.
I wonder if it would make sense to attempt inserting event "stub" first, basically with event_id only, to ensure any process running in parallel with the same event_id sees it? A failed insert (or rather upsert via on_conflict) at this stage would abort the transaction as a duplicate early as well. The stub could be updated in record_event.
| end | ||
|
|
||
| defp find_existing(kind, billing_subscription_id) do | ||
| existing = Repo.get_by(Subscription, billing_subscription_id: billing_subscription_id) |
There was a problem hiding this comment.
I'd consider setting a row-level lock via FOR UPDATE to avoid working with a stale subscription due to two different events being processed in parallel for the same subscription.
| existing = Repo.get_by(Subscription, billing_subscription_id: billing_subscription_id) | ||
|
|
||
| case {kind, existing} do | ||
| {:updated, nil} -> {:error, :subscription_not_found} |
There was a problem hiding this comment.
We have normalised billing_subscription_id (along with all the other fields) in SubscriptionEvent schema. We could fall back on looking up the most recent entry in the events table and treat that as a "stale" event insertion. However, we should still ensure it doesn't do something unexpected, like changing the canceled subscription back to active (unlikely, but still). Then it should legit crash.
IMHO it would be better to avoid relaxing the one-team-one-billing-subscription constraint, if possible.
This PR adds the webhook endpoint that creates and updates Paddle Billing subscriptions. Until now the app could read Billing subscriptions (#6879), but nothing wrote them.
Builds on #6909 (webhook signature verification) and #6898 (migration already applied). The diff will be smaller once #6909 is merged, plus majority of diffstat is tests, the logic is relatively small and self-contained. Reading commit by commit is the best way forward.
@RobertJoonas if you find yourself overwhelmed already, you can also start with these three diffs to get a grasp of core changes:
Deets:
POST /api/paddle-billing/webhookhitsPaddleBillingController. The Classic endpoint is unchanged.WebhookSignaturegains Plug capabilities. A failing request gets a 400 and an error log with the reason.PlausibleWeb.RawBodyReaderis introduced, keeping the raw body for this one route. Configured per plug docs recommendation. Other routes don't copy the body.PADDLE_BILLING_WEBHOOK_SECRET. With no secret configured, every request is rejected..envrc.localis loaded in dev mode only to simplify sandbox experiments. The secret env var will be provisioned on prod in a follow-up.The newly introduced controller only handles
subscription.createdandsubscription.updated.subscription.importedwill be done in a follow-up.Both events carry the whole subscription, so they share one code path.
billing_subscription_events. A repeatedevent_idis a duplicate and results with HTTP 200.createdfinds the team from custom_data (team_id, or user_id for a new personal team) and setsteams.billing_customer_id, which makes theall_subscriptionsview return the appropriate Billing row.updatedfinds the subscription by ID. An unknown ID is an error.:deletedwithnext_bill_dateset to when it takes effect, as with Classic. The cancellation email is sent once for :deleted (SubscriptionState.notify_cancellation/1is now public).billing_intervalcomes from the price's billing cycle. Only monthly and yearly are accepted.SubscriptionState.apply_subscription_state/1, so site locking, grace period, deletion schedules and enterprise API limits provide Classic parity.billing_webhook_failuresfor inspection.Additionally, the usage notification crashed when the pageview limit is :unlimited (for example, for a plan we can't resolve - easy to reach on dev env). Fixed, with a test.