billing.rs

  1use std::str::FromStr;
  2use std::sync::Arc;
  3use std::time::Duration;
  4
  5use anyhow::{anyhow, bail, Context};
  6use axum::{
  7    extract::{self, Query},
  8    routing::{get, post},
  9    Extension, Json, Router,
 10};
 11use chrono::{DateTime, SecondsFormat};
 12use reqwest::StatusCode;
 13use sea_orm::ActiveValue;
 14use serde::{Deserialize, Serialize};
 15use stripe::{
 16    BillingPortalSession, CheckoutSession, CreateBillingPortalSession,
 17    CreateBillingPortalSessionFlowData, CreateBillingPortalSessionFlowDataAfterCompletion,
 18    CreateBillingPortalSessionFlowDataAfterCompletionRedirect,
 19    CreateBillingPortalSessionFlowDataType, CreateCheckoutSession, CreateCheckoutSessionLineItems,
 20    CreateCustomer, Customer, CustomerId, EventObject, EventType, Expandable, ListEvents,
 21    Subscription, SubscriptionId, SubscriptionStatus,
 22};
 23use util::ResultExt;
 24
 25use crate::db::billing_subscription::StripeSubscriptionStatus;
 26use crate::db::{
 27    billing_customer, BillingSubscriptionId, CreateBillingCustomerParams,
 28    CreateBillingSubscriptionParams, CreateProcessedStripeEventParams, UpdateBillingCustomerParams,
 29    UpdateBillingSubscriptionParams,
 30};
 31use crate::{AppState, Error, Result};
 32
 33pub fn router() -> Router {
 34    Router::new()
 35        .route(
 36            "/billing/subscriptions",
 37            get(list_billing_subscriptions).post(create_billing_subscription),
 38        )
 39        .route(
 40            "/billing/subscriptions/manage",
 41            post(manage_billing_subscription),
 42        )
 43}
 44
 45#[derive(Debug, Deserialize)]
 46struct ListBillingSubscriptionsParams {
 47    github_user_id: i32,
 48}
 49
 50#[derive(Debug, Serialize)]
 51struct BillingSubscriptionJson {
 52    id: BillingSubscriptionId,
 53    name: String,
 54    status: StripeSubscriptionStatus,
 55    cancel_at: Option<String>,
 56    /// Whether this subscription can be canceled.
 57    is_cancelable: bool,
 58}
 59
 60#[derive(Debug, Serialize)]
 61struct ListBillingSubscriptionsResponse {
 62    subscriptions: Vec<BillingSubscriptionJson>,
 63}
 64
 65async fn list_billing_subscriptions(
 66    Extension(app): Extension<Arc<AppState>>,
 67    Query(params): Query<ListBillingSubscriptionsParams>,
 68) -> Result<Json<ListBillingSubscriptionsResponse>> {
 69    let user = app
 70        .db
 71        .get_user_by_github_user_id(params.github_user_id)
 72        .await?
 73        .ok_or_else(|| anyhow!("user not found"))?;
 74
 75    let subscriptions = app.db.get_billing_subscriptions(user.id).await?;
 76
 77    Ok(Json(ListBillingSubscriptionsResponse {
 78        subscriptions: subscriptions
 79            .into_iter()
 80            .map(|subscription| BillingSubscriptionJson {
 81                id: subscription.id,
 82                name: "Zed Pro".to_string(),
 83                status: subscription.stripe_subscription_status,
 84                cancel_at: subscription.stripe_cancel_at.map(|cancel_at| {
 85                    cancel_at
 86                        .and_utc()
 87                        .to_rfc3339_opts(SecondsFormat::Millis, true)
 88                }),
 89                is_cancelable: subscription.stripe_subscription_status.is_cancelable()
 90                    && subscription.stripe_cancel_at.is_none(),
 91            })
 92            .collect(),
 93    }))
 94}
 95
 96#[derive(Debug, Deserialize)]
 97struct CreateBillingSubscriptionBody {
 98    github_user_id: i32,
 99}
100
101#[derive(Debug, Serialize)]
102struct CreateBillingSubscriptionResponse {
103    checkout_session_url: String,
104}
105
106/// Initiates a Stripe Checkout session for creating a billing subscription.
107async fn create_billing_subscription(
108    Extension(app): Extension<Arc<AppState>>,
109    extract::Json(body): extract::Json<CreateBillingSubscriptionBody>,
110) -> Result<Json<CreateBillingSubscriptionResponse>> {
111    let user = app
112        .db
113        .get_user_by_github_user_id(body.github_user_id)
114        .await?
115        .ok_or_else(|| anyhow!("user not found"))?;
116
117    let Some((stripe_client, stripe_price_id)) = app
118        .stripe_client
119        .clone()
120        .zip(app.config.stripe_price_id.clone())
121    else {
122        log::error!("failed to retrieve Stripe client or price ID");
123        Err(Error::Http(
124            StatusCode::NOT_IMPLEMENTED,
125            "not supported".into(),
126        ))?
127    };
128
129    let customer_id =
130        if let Some(existing_customer) = app.db.get_billing_customer_by_user_id(user.id).await? {
131            CustomerId::from_str(&existing_customer.stripe_customer_id)
132                .context("failed to parse customer ID")?
133        } else {
134            let customer = Customer::create(
135                &stripe_client,
136                CreateCustomer {
137                    email: user.email_address.as_deref(),
138                    ..Default::default()
139                },
140            )
141            .await?;
142
143            customer.id
144        };
145
146    let checkout_session = {
147        let mut params = CreateCheckoutSession::new();
148        params.mode = Some(stripe::CheckoutSessionMode::Subscription);
149        params.customer = Some(customer_id);
150        params.client_reference_id = Some(user.github_login.as_str());
151        params.line_items = Some(vec![CreateCheckoutSessionLineItems {
152            price: Some(stripe_price_id.to_string()),
153            quantity: Some(1),
154            ..Default::default()
155        }]);
156        let success_url = format!("{}/account", app.config.zed_dot_dev_url());
157        params.success_url = Some(&success_url);
158
159        CheckoutSession::create(&stripe_client, params).await?
160    };
161
162    Ok(Json(CreateBillingSubscriptionResponse {
163        checkout_session_url: checkout_session
164            .url
165            .ok_or_else(|| anyhow!("no checkout session URL"))?,
166    }))
167}
168
169#[derive(Debug, PartialEq, Deserialize)]
170#[serde(rename_all = "snake_case")]
171enum ManageSubscriptionIntent {
172    /// The user intends to cancel their subscription.
173    Cancel,
174    /// The user intends to stop the cancellation of their subscription.
175    StopCancellation,
176}
177
178#[derive(Debug, Deserialize)]
179struct ManageBillingSubscriptionBody {
180    github_user_id: i32,
181    intent: ManageSubscriptionIntent,
182    /// The ID of the subscription to manage.
183    subscription_id: BillingSubscriptionId,
184}
185
186#[derive(Debug, Serialize)]
187struct ManageBillingSubscriptionResponse {
188    billing_portal_session_url: Option<String>,
189}
190
191/// Initiates a Stripe customer portal session for managing a billing subscription.
192async fn manage_billing_subscription(
193    Extension(app): Extension<Arc<AppState>>,
194    extract::Json(body): extract::Json<ManageBillingSubscriptionBody>,
195) -> Result<Json<ManageBillingSubscriptionResponse>> {
196    let user = app
197        .db
198        .get_user_by_github_user_id(body.github_user_id)
199        .await?
200        .ok_or_else(|| anyhow!("user not found"))?;
201
202    let Some(stripe_client) = app.stripe_client.clone() else {
203        log::error!("failed to retrieve Stripe client");
204        Err(Error::Http(
205            StatusCode::NOT_IMPLEMENTED,
206            "not supported".into(),
207        ))?
208    };
209
210    let customer = app
211        .db
212        .get_billing_customer_by_user_id(user.id)
213        .await?
214        .ok_or_else(|| anyhow!("billing customer not found"))?;
215    let customer_id = CustomerId::from_str(&customer.stripe_customer_id)
216        .context("failed to parse customer ID")?;
217
218    let subscription = app
219        .db
220        .get_billing_subscription_by_id(body.subscription_id)
221        .await?
222        .ok_or_else(|| anyhow!("subscription not found"))?;
223
224    if body.intent == ManageSubscriptionIntent::StopCancellation {
225        let subscription_id = SubscriptionId::from_str(&subscription.stripe_subscription_id)
226            .context("failed to parse subscription ID")?;
227
228        let updated_stripe_subscription = Subscription::update(
229            &stripe_client,
230            &subscription_id,
231            stripe::UpdateSubscription {
232                cancel_at_period_end: Some(false),
233                ..Default::default()
234            },
235        )
236        .await?;
237
238        app.db
239            .update_billing_subscription(
240                subscription.id,
241                &UpdateBillingSubscriptionParams {
242                    stripe_cancel_at: ActiveValue::set(
243                        updated_stripe_subscription
244                            .cancel_at
245                            .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
246                            .map(|time| time.naive_utc()),
247                    ),
248                    ..Default::default()
249                },
250            )
251            .await?;
252
253        return Ok(Json(ManageBillingSubscriptionResponse {
254            billing_portal_session_url: None,
255        }));
256    }
257
258    let flow = match body.intent {
259        ManageSubscriptionIntent::Cancel => CreateBillingPortalSessionFlowData {
260            type_: CreateBillingPortalSessionFlowDataType::SubscriptionCancel,
261            after_completion: Some(CreateBillingPortalSessionFlowDataAfterCompletion {
262                type_: stripe::CreateBillingPortalSessionFlowDataAfterCompletionType::Redirect,
263                redirect: Some(CreateBillingPortalSessionFlowDataAfterCompletionRedirect {
264                    return_url: format!("{}/account", app.config.zed_dot_dev_url()),
265                }),
266                ..Default::default()
267            }),
268            subscription_cancel: Some(
269                stripe::CreateBillingPortalSessionFlowDataSubscriptionCancel {
270                    subscription: subscription.stripe_subscription_id,
271                    retention: None,
272                },
273            ),
274            ..Default::default()
275        },
276        ManageSubscriptionIntent::StopCancellation => unreachable!(),
277    };
278
279    let mut params = CreateBillingPortalSession::new(customer_id);
280    params.flow_data = Some(flow);
281    let return_url = format!("{}/account", app.config.zed_dot_dev_url());
282    params.return_url = Some(&return_url);
283
284    let session = BillingPortalSession::create(&stripe_client, params).await?;
285
286    Ok(Json(ManageBillingSubscriptionResponse {
287        billing_portal_session_url: Some(session.url),
288    }))
289}
290
291/// The amount of time we wait in between each poll of Stripe events.
292///
293/// This value should strike a balance between:
294///   1. Being short enough that we update quickly when something in Stripe changes
295///   2. Being long enough that we don't eat into our rate limits.
296///
297/// As a point of reference, the Sequin folks say they have this at **500ms**:
298///
299/// > We poll the Stripe /events endpoint every 500ms per account
300/// >
301/// > — https://blog.sequinstream.com/events-not-webhooks/
302const POLL_EVENTS_INTERVAL: Duration = Duration::from_secs(5);
303
304/// The maximum number of events to return per page.
305///
306/// We set this to 100 (the max) so we have to make fewer requests to Stripe.
307///
308/// > Limit can range between 1 and 100, and the default is 10.
309const EVENTS_LIMIT_PER_PAGE: u64 = 100;
310
311/// The number of pages consisting entirely of already-processed events that we
312/// will see before we stop retrieving events.
313///
314/// This is used to prevent over-fetching the Stripe events API for events we've
315/// already seen and processed.
316const NUMBER_OF_ALREADY_PROCESSED_PAGES_BEFORE_WE_STOP: usize = 4;
317
318/// Polls the Stripe events API periodically to reconcile the records in our
319/// database with the data in Stripe.
320pub fn poll_stripe_events_periodically(app: Arc<AppState>) {
321    let Some(stripe_client) = app.stripe_client.clone() else {
322        log::warn!("failed to retrieve Stripe client");
323        return;
324    };
325
326    let executor = app.executor.clone();
327    executor.spawn_detached({
328        let executor = executor.clone();
329        async move {
330            loop {
331                poll_stripe_events(&app, &stripe_client).await.log_err();
332
333                executor.sleep(POLL_EVENTS_INTERVAL).await;
334            }
335        }
336    });
337}
338
339async fn poll_stripe_events(
340    app: &Arc<AppState>,
341    stripe_client: &stripe::Client,
342) -> anyhow::Result<()> {
343    fn event_type_to_string(event_type: EventType) -> String {
344        // Calling `to_string` on `stripe::EventType` members gives us a quoted string,
345        // so we need to unquote it.
346        event_type.to_string().trim_matches('"').to_string()
347    }
348
349    let event_types = [
350        EventType::CustomerCreated,
351        EventType::CustomerUpdated,
352        EventType::CustomerSubscriptionCreated,
353        EventType::CustomerSubscriptionUpdated,
354        EventType::CustomerSubscriptionPaused,
355        EventType::CustomerSubscriptionResumed,
356        EventType::CustomerSubscriptionDeleted,
357    ]
358    .into_iter()
359    .map(event_type_to_string)
360    .collect::<Vec<_>>();
361
362    let mut pages_of_already_processed_events = 0;
363    let mut unprocessed_events = Vec::new();
364
365    loop {
366        if pages_of_already_processed_events >= NUMBER_OF_ALREADY_PROCESSED_PAGES_BEFORE_WE_STOP {
367            log::info!("saw {pages_of_already_processed_events} pages of already-processed events: stopping event retrieval");
368            break;
369        }
370
371        log::info!("retrieving events from Stripe: {}", event_types.join(", "));
372
373        let mut params = ListEvents::new();
374        params.types = Some(event_types.clone());
375        params.limit = Some(EVENTS_LIMIT_PER_PAGE);
376
377        let events = stripe::Event::list(stripe_client, &params).await?;
378
379        let processed_event_ids = {
380            let event_ids = &events
381                .data
382                .iter()
383                .map(|event| event.id.as_str())
384                .collect::<Vec<_>>();
385
386            app.db
387                .get_processed_stripe_events_by_event_ids(event_ids)
388                .await?
389                .into_iter()
390                .map(|event| event.stripe_event_id)
391                .collect::<Vec<_>>()
392        };
393
394        let mut processed_events_in_page = 0;
395        let events_in_page = events.data.len();
396        for event in events.data {
397            if processed_event_ids.contains(&event.id.to_string()) {
398                processed_events_in_page += 1;
399                log::debug!("Stripe event {} already processed: skipping", event.id);
400            } else {
401                unprocessed_events.push(event);
402            }
403        }
404
405        if processed_events_in_page == events_in_page {
406            pages_of_already_processed_events += 1;
407        }
408
409        if !events.has_more {
410            break;
411        }
412    }
413
414    log::info!(
415        "unprocessed events from Stripe: {}",
416        unprocessed_events.len()
417    );
418
419    // Sort all of the unprocessed events in ascending order, so we can handle them in the order they occurred.
420    unprocessed_events.sort_by(|a, b| a.created.cmp(&b.created).then_with(|| a.id.cmp(&b.id)));
421
422    for event in unprocessed_events {
423        let event_id = event.id.clone();
424        let processed_event_params = CreateProcessedStripeEventParams {
425            stripe_event_id: event.id.to_string(),
426            stripe_event_type: event_type_to_string(event.type_),
427            stripe_event_created_timestamp: event.created,
428        };
429
430        let process_result = match event.type_ {
431            EventType::CustomerCreated | EventType::CustomerUpdated => {
432                handle_customer_event(app, stripe_client, event).await
433            }
434            EventType::CustomerSubscriptionCreated
435            | EventType::CustomerSubscriptionUpdated
436            | EventType::CustomerSubscriptionPaused
437            | EventType::CustomerSubscriptionResumed
438            | EventType::CustomerSubscriptionDeleted => {
439                handle_customer_subscription_event(app, stripe_client, event).await
440            }
441            _ => Ok(()),
442        };
443
444        if let Some(()) = process_result
445            .with_context(|| format!("failed to process event {event_id} successfully"))
446            .log_err()
447        {
448            app.db
449                .create_processed_stripe_event(&processed_event_params)
450                .await?;
451        }
452    }
453
454    Ok(())
455}
456
457async fn handle_customer_event(
458    app: &Arc<AppState>,
459    _stripe_client: &stripe::Client,
460    event: stripe::Event,
461) -> anyhow::Result<()> {
462    let EventObject::Customer(customer) = event.data.object else {
463        bail!("unexpected event payload for {}", event.id);
464    };
465
466    log::info!("handling Stripe {} event: {}", event.type_, event.id);
467
468    let Some(email) = customer.email else {
469        log::info!("Stripe customer has no email: skipping");
470        return Ok(());
471    };
472
473    let Some(user) = app.db.get_user_by_email(&email).await? else {
474        log::info!("no user found for email: skipping");
475        return Ok(());
476    };
477
478    if let Some(existing_customer) = app
479        .db
480        .get_billing_customer_by_stripe_customer_id(&customer.id)
481        .await?
482    {
483        app.db
484            .update_billing_customer(
485                existing_customer.id,
486                &UpdateBillingCustomerParams {
487                    // For now we just leave the information as-is, as it is not
488                    // likely to change.
489                    ..Default::default()
490                },
491            )
492            .await?;
493    } else {
494        app.db
495            .create_billing_customer(&CreateBillingCustomerParams {
496                user_id: user.id,
497                stripe_customer_id: customer.id.to_string(),
498            })
499            .await?;
500    }
501
502    Ok(())
503}
504
505async fn handle_customer_subscription_event(
506    app: &Arc<AppState>,
507    stripe_client: &stripe::Client,
508    event: stripe::Event,
509) -> anyhow::Result<()> {
510    let EventObject::Subscription(subscription) = event.data.object else {
511        bail!("unexpected event payload for {}", event.id);
512    };
513
514    log::info!("handling Stripe {} event: {}", event.type_, event.id);
515
516    let billing_customer =
517        find_or_create_billing_customer(app, stripe_client, subscription.customer)
518            .await?
519            .ok_or_else(|| anyhow!("billing customer not found"))?;
520
521    if let Some(existing_subscription) = app
522        .db
523        .get_billing_subscription_by_stripe_subscription_id(&subscription.id)
524        .await?
525    {
526        app.db
527            .update_billing_subscription(
528                existing_subscription.id,
529                &UpdateBillingSubscriptionParams {
530                    billing_customer_id: ActiveValue::set(billing_customer.id),
531                    stripe_subscription_id: ActiveValue::set(subscription.id.to_string()),
532                    stripe_subscription_status: ActiveValue::set(subscription.status.into()),
533                    stripe_cancel_at: ActiveValue::set(
534                        subscription
535                            .cancel_at
536                            .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
537                            .map(|time| time.naive_utc()),
538                    ),
539                },
540            )
541            .await?;
542    } else {
543        app.db
544            .create_billing_subscription(&CreateBillingSubscriptionParams {
545                billing_customer_id: billing_customer.id,
546                stripe_subscription_id: subscription.id.to_string(),
547                stripe_subscription_status: subscription.status.into(),
548            })
549            .await?;
550    }
551
552    Ok(())
553}
554
555impl From<SubscriptionStatus> for StripeSubscriptionStatus {
556    fn from(value: SubscriptionStatus) -> Self {
557        match value {
558            SubscriptionStatus::Incomplete => Self::Incomplete,
559            SubscriptionStatus::IncompleteExpired => Self::IncompleteExpired,
560            SubscriptionStatus::Trialing => Self::Trialing,
561            SubscriptionStatus::Active => Self::Active,
562            SubscriptionStatus::PastDue => Self::PastDue,
563            SubscriptionStatus::Canceled => Self::Canceled,
564            SubscriptionStatus::Unpaid => Self::Unpaid,
565            SubscriptionStatus::Paused => Self::Paused,
566        }
567    }
568}
569
570/// Finds or creates a billing customer using the provided customer.
571async fn find_or_create_billing_customer(
572    app: &Arc<AppState>,
573    stripe_client: &stripe::Client,
574    customer_or_id: Expandable<Customer>,
575) -> anyhow::Result<Option<billing_customer::Model>> {
576    let customer_id = match &customer_or_id {
577        Expandable::Id(id) => id,
578        Expandable::Object(customer) => customer.id.as_ref(),
579    };
580
581    // If we already have a billing customer record associated with the Stripe customer,
582    // there's nothing more we need to do.
583    if let Some(billing_customer) = app
584        .db
585        .get_billing_customer_by_stripe_customer_id(&customer_id)
586        .await?
587    {
588        return Ok(Some(billing_customer));
589    }
590
591    // If all we have is a customer ID, resolve it to a full customer record by
592    // hitting the Stripe API.
593    let customer = match customer_or_id {
594        Expandable::Id(id) => Customer::retrieve(&stripe_client, &id, &[]).await?,
595        Expandable::Object(customer) => *customer,
596    };
597
598    let Some(email) = customer.email else {
599        return Ok(None);
600    };
601
602    let Some(user) = app.db.get_user_by_email(&email).await? else {
603        return Ok(None);
604    };
605
606    let billing_customer = app
607        .db
608        .create_billing_customer(&CreateBillingCustomerParams {
609            user_id: user.id,
610            stripe_customer_id: customer.id.to_string(),
611        })
612        .await?;
613
614    Ok(Some(billing_customer))
615}