billing.rs

   1use anyhow::{Context, anyhow, bail};
   2use axum::{
   3    Extension, Json, Router,
   4    extract::{self, Query},
   5    routing::{get, post},
   6};
   7use chrono::{DateTime, SecondsFormat, Utc};
   8use collections::HashSet;
   9use reqwest::StatusCode;
  10use sea_orm::ActiveValue;
  11use serde::{Deserialize, Serialize};
  12use serde_json::json;
  13use std::{str::FromStr, sync::Arc, time::Duration};
  14use stripe::{
  15    BillingPortalSession, CancellationDetailsReason, CreateBillingPortalSession,
  16    CreateBillingPortalSessionFlowData, CreateBillingPortalSessionFlowDataAfterCompletion,
  17    CreateBillingPortalSessionFlowDataAfterCompletionRedirect,
  18    CreateBillingPortalSessionFlowDataSubscriptionUpdateConfirm,
  19    CreateBillingPortalSessionFlowDataSubscriptionUpdateConfirmItems,
  20    CreateBillingPortalSessionFlowDataType, CreateCustomer, Customer, CustomerId, EventObject,
  21    EventType, Expandable, ListEvents, Subscription, SubscriptionId, SubscriptionStatus,
  22};
  23use util::{ResultExt, maybe};
  24
  25use crate::api::events::SnowflakeRow;
  26use crate::db::billing_subscription::{
  27    StripeCancellationReason, StripeSubscriptionStatus, SubscriptionKind,
  28};
  29use crate::llm::{DEFAULT_MAX_MONTHLY_SPEND, FREE_TIER_MONTHLY_SPENDING_LIMIT};
  30use crate::rpc::{ResultExt as _, Server};
  31use crate::{AppState, Cents, Error, Result};
  32use crate::{db::UserId, llm::db::LlmDatabase};
  33use crate::{
  34    db::{
  35        BillingSubscriptionId, CreateBillingCustomerParams, CreateBillingSubscriptionParams,
  36        CreateProcessedStripeEventParams, UpdateBillingCustomerParams,
  37        UpdateBillingPreferencesParams, UpdateBillingSubscriptionParams, billing_customer,
  38    },
  39    stripe_billing::StripeBilling,
  40};
  41
  42pub fn router() -> Router {
  43    Router::new()
  44        .route(
  45            "/billing/preferences",
  46            get(get_billing_preferences).put(update_billing_preferences),
  47        )
  48        .route(
  49            "/billing/subscriptions",
  50            get(list_billing_subscriptions).post(create_billing_subscription),
  51        )
  52        .route(
  53            "/billing/subscriptions/manage",
  54            post(manage_billing_subscription),
  55        )
  56        .route("/billing/monthly_spend", get(get_monthly_spend))
  57        .route("/billing/usage", get(get_current_usage))
  58}
  59
  60#[derive(Debug, Deserialize)]
  61struct GetBillingPreferencesParams {
  62    github_user_id: i32,
  63}
  64
  65#[derive(Debug, Serialize)]
  66struct BillingPreferencesResponse {
  67    max_monthly_llm_usage_spending_in_cents: i32,
  68}
  69
  70async fn get_billing_preferences(
  71    Extension(app): Extension<Arc<AppState>>,
  72    Query(params): Query<GetBillingPreferencesParams>,
  73) -> Result<Json<BillingPreferencesResponse>> {
  74    let user = app
  75        .db
  76        .get_user_by_github_user_id(params.github_user_id)
  77        .await?
  78        .ok_or_else(|| anyhow!("user not found"))?;
  79
  80    let preferences = app.db.get_billing_preferences(user.id).await?;
  81
  82    Ok(Json(BillingPreferencesResponse {
  83        max_monthly_llm_usage_spending_in_cents: preferences
  84            .map_or(DEFAULT_MAX_MONTHLY_SPEND.0 as i32, |preferences| {
  85                preferences.max_monthly_llm_usage_spending_in_cents
  86            }),
  87    }))
  88}
  89
  90#[derive(Debug, Deserialize)]
  91struct UpdateBillingPreferencesBody {
  92    github_user_id: i32,
  93    max_monthly_llm_usage_spending_in_cents: i32,
  94}
  95
  96async fn update_billing_preferences(
  97    Extension(app): Extension<Arc<AppState>>,
  98    Extension(rpc_server): Extension<Arc<crate::rpc::Server>>,
  99    extract::Json(body): extract::Json<UpdateBillingPreferencesBody>,
 100) -> Result<Json<BillingPreferencesResponse>> {
 101    let user = app
 102        .db
 103        .get_user_by_github_user_id(body.github_user_id)
 104        .await?
 105        .ok_or_else(|| anyhow!("user not found"))?;
 106
 107    let max_monthly_llm_usage_spending_in_cents =
 108        body.max_monthly_llm_usage_spending_in_cents.max(0);
 109
 110    let billing_preferences =
 111        if let Some(_billing_preferences) = app.db.get_billing_preferences(user.id).await? {
 112            app.db
 113                .update_billing_preferences(
 114                    user.id,
 115                    &UpdateBillingPreferencesParams {
 116                        max_monthly_llm_usage_spending_in_cents: ActiveValue::set(
 117                            max_monthly_llm_usage_spending_in_cents,
 118                        ),
 119                    },
 120                )
 121                .await?
 122        } else {
 123            app.db
 124                .create_billing_preferences(
 125                    user.id,
 126                    &crate::db::CreateBillingPreferencesParams {
 127                        max_monthly_llm_usage_spending_in_cents,
 128                    },
 129                )
 130                .await?
 131        };
 132
 133    SnowflakeRow::new(
 134        "Spend Limit Updated",
 135        Some(user.metrics_id),
 136        user.admin,
 137        None,
 138        json!({
 139            "user_id": user.id,
 140            "max_monthly_llm_usage_spending_in_cents": billing_preferences.max_monthly_llm_usage_spending_in_cents,
 141        }),
 142    )
 143    .write(&app.kinesis_client, &app.config.kinesis_stream)
 144    .await
 145    .log_err();
 146
 147    rpc_server.refresh_llm_tokens_for_user(user.id).await;
 148
 149    Ok(Json(BillingPreferencesResponse {
 150        max_monthly_llm_usage_spending_in_cents: billing_preferences
 151            .max_monthly_llm_usage_spending_in_cents,
 152    }))
 153}
 154
 155#[derive(Debug, Deserialize)]
 156struct ListBillingSubscriptionsParams {
 157    github_user_id: i32,
 158}
 159
 160#[derive(Debug, Serialize)]
 161struct BillingSubscriptionJson {
 162    id: BillingSubscriptionId,
 163    name: String,
 164    status: StripeSubscriptionStatus,
 165    trial_end_at: Option<String>,
 166    cancel_at: Option<String>,
 167    /// Whether this subscription can be canceled.
 168    is_cancelable: bool,
 169}
 170
 171#[derive(Debug, Serialize)]
 172struct ListBillingSubscriptionsResponse {
 173    subscriptions: Vec<BillingSubscriptionJson>,
 174}
 175
 176async fn list_billing_subscriptions(
 177    Extension(app): Extension<Arc<AppState>>,
 178    Query(params): Query<ListBillingSubscriptionsParams>,
 179) -> Result<Json<ListBillingSubscriptionsResponse>> {
 180    let user = app
 181        .db
 182        .get_user_by_github_user_id(params.github_user_id)
 183        .await?
 184        .ok_or_else(|| anyhow!("user not found"))?;
 185
 186    let subscriptions = app.db.get_billing_subscriptions(user.id).await?;
 187
 188    Ok(Json(ListBillingSubscriptionsResponse {
 189        subscriptions: subscriptions
 190            .into_iter()
 191            .map(|subscription| BillingSubscriptionJson {
 192                id: subscription.id,
 193                name: match subscription.kind {
 194                    Some(SubscriptionKind::ZedPro) => "Zed Pro".to_string(),
 195                    Some(SubscriptionKind::ZedProTrial) => "Zed Pro (Trial)".to_string(),
 196                    Some(SubscriptionKind::ZedFree) => "Zed Free".to_string(),
 197                    None => "Zed LLM Usage".to_string(),
 198                },
 199                status: subscription.stripe_subscription_status,
 200                trial_end_at: if subscription.kind == Some(SubscriptionKind::ZedProTrial) {
 201                    maybe!({
 202                        let end_at = subscription.stripe_current_period_end?;
 203                        let end_at = DateTime::from_timestamp(end_at, 0)?;
 204
 205                        Some(end_at.to_rfc3339_opts(SecondsFormat::Millis, true))
 206                    })
 207                } else {
 208                    None
 209                },
 210                cancel_at: subscription.stripe_cancel_at.map(|cancel_at| {
 211                    cancel_at
 212                        .and_utc()
 213                        .to_rfc3339_opts(SecondsFormat::Millis, true)
 214                }),
 215                is_cancelable: subscription.stripe_subscription_status.is_cancelable()
 216                    && subscription.stripe_cancel_at.is_none(),
 217            })
 218            .collect(),
 219    }))
 220}
 221
 222#[derive(Debug, Clone, Copy, Deserialize)]
 223#[serde(rename_all = "snake_case")]
 224enum ProductCode {
 225    ZedPro,
 226    ZedProTrial,
 227}
 228
 229#[derive(Debug, Deserialize)]
 230struct CreateBillingSubscriptionBody {
 231    github_user_id: i32,
 232    product: Option<ProductCode>,
 233}
 234
 235#[derive(Debug, Serialize)]
 236struct CreateBillingSubscriptionResponse {
 237    checkout_session_url: String,
 238}
 239
 240/// Initiates a Stripe Checkout session for creating a billing subscription.
 241async fn create_billing_subscription(
 242    Extension(app): Extension<Arc<AppState>>,
 243    extract::Json(body): extract::Json<CreateBillingSubscriptionBody>,
 244) -> Result<Json<CreateBillingSubscriptionResponse>> {
 245    let user = app
 246        .db
 247        .get_user_by_github_user_id(body.github_user_id)
 248        .await?
 249        .ok_or_else(|| anyhow!("user not found"))?;
 250
 251    let Some(stripe_client) = app.stripe_client.clone() else {
 252        log::error!("failed to retrieve Stripe client");
 253        Err(Error::http(
 254            StatusCode::NOT_IMPLEMENTED,
 255            "not supported".into(),
 256        ))?
 257    };
 258    let Some(stripe_billing) = app.stripe_billing.clone() else {
 259        log::error!("failed to retrieve Stripe billing object");
 260        Err(Error::http(
 261            StatusCode::NOT_IMPLEMENTED,
 262            "not supported".into(),
 263        ))?
 264    };
 265    let Some(llm_db) = app.llm_db.clone() else {
 266        log::error!("failed to retrieve LLM database");
 267        Err(Error::http(
 268            StatusCode::NOT_IMPLEMENTED,
 269            "not supported".into(),
 270        ))?
 271    };
 272
 273    if app.db.has_active_billing_subscription(user.id).await? {
 274        return Err(Error::http(
 275            StatusCode::CONFLICT,
 276            "user already has an active subscription".into(),
 277        ));
 278    }
 279
 280    let existing_billing_customer = app.db.get_billing_customer_by_user_id(user.id).await?;
 281    if let Some(existing_billing_customer) = &existing_billing_customer {
 282        if existing_billing_customer.has_overdue_invoices {
 283            return Err(Error::http(
 284                StatusCode::PAYMENT_REQUIRED,
 285                "user has overdue invoices".into(),
 286            ));
 287        }
 288    }
 289
 290    let customer_id = if let Some(existing_customer) = existing_billing_customer {
 291        CustomerId::from_str(&existing_customer.stripe_customer_id)
 292            .context("failed to parse customer ID")?
 293    } else {
 294        let customer = Customer::create(
 295            &stripe_client,
 296            CreateCustomer {
 297                email: user.email_address.as_deref(),
 298                ..Default::default()
 299            },
 300        )
 301        .await?;
 302
 303        customer.id
 304    };
 305
 306    let success_url = format!(
 307        "{}/account?checkout_complete=1",
 308        app.config.zed_dot_dev_url()
 309    );
 310
 311    let checkout_session_url = match body.product {
 312        Some(ProductCode::ZedPro) => {
 313            stripe_billing
 314                .checkout_with_price(
 315                    app.config.zed_pro_price_id()?,
 316                    customer_id,
 317                    &user.github_login,
 318                    &success_url,
 319                )
 320                .await?
 321        }
 322        Some(ProductCode::ZedProTrial) => {
 323            stripe_billing
 324                .checkout_with_price(
 325                    app.config.zed_pro_trial_price_id()?,
 326                    customer_id,
 327                    &user.github_login,
 328                    &success_url,
 329                )
 330                .await?
 331        }
 332        None => {
 333            let default_model = llm_db.model(
 334                zed_llm_client::LanguageModelProvider::Anthropic,
 335                "claude-3-7-sonnet",
 336            )?;
 337            let stripe_model = stripe_billing.register_model(default_model).await?;
 338            stripe_billing
 339                .checkout(customer_id, &user.github_login, &stripe_model, &success_url)
 340                .await?
 341        }
 342    };
 343
 344    Ok(Json(CreateBillingSubscriptionResponse {
 345        checkout_session_url,
 346    }))
 347}
 348
 349#[derive(Debug, PartialEq, Deserialize)]
 350#[serde(rename_all = "snake_case")]
 351enum ManageSubscriptionIntent {
 352    /// The user intends to manage their subscription.
 353    ///
 354    /// This will open the Stripe billing portal without putting the user in a specific flow.
 355    ManageSubscription,
 356    /// The user intends to upgrade to Zed Pro.
 357    UpgradeToPro,
 358    /// The user intends to cancel their subscription.
 359    Cancel,
 360    /// The user intends to stop the cancellation of their subscription.
 361    StopCancellation,
 362}
 363
 364#[derive(Debug, Deserialize)]
 365struct ManageBillingSubscriptionBody {
 366    github_user_id: i32,
 367    intent: ManageSubscriptionIntent,
 368    /// The ID of the subscription to manage.
 369    subscription_id: BillingSubscriptionId,
 370}
 371
 372#[derive(Debug, Serialize)]
 373struct ManageBillingSubscriptionResponse {
 374    billing_portal_session_url: Option<String>,
 375}
 376
 377/// Initiates a Stripe customer portal session for managing a billing subscription.
 378async fn manage_billing_subscription(
 379    Extension(app): Extension<Arc<AppState>>,
 380    extract::Json(body): extract::Json<ManageBillingSubscriptionBody>,
 381) -> Result<Json<ManageBillingSubscriptionResponse>> {
 382    let user = app
 383        .db
 384        .get_user_by_github_user_id(body.github_user_id)
 385        .await?
 386        .ok_or_else(|| anyhow!("user not found"))?;
 387
 388    let Some(stripe_client) = app.stripe_client.clone() else {
 389        log::error!("failed to retrieve Stripe client");
 390        Err(Error::http(
 391            StatusCode::NOT_IMPLEMENTED,
 392            "not supported".into(),
 393        ))?
 394    };
 395
 396    let customer = app
 397        .db
 398        .get_billing_customer_by_user_id(user.id)
 399        .await?
 400        .ok_or_else(|| anyhow!("billing customer not found"))?;
 401    let customer_id = CustomerId::from_str(&customer.stripe_customer_id)
 402        .context("failed to parse customer ID")?;
 403
 404    let subscription = app
 405        .db
 406        .get_billing_subscription_by_id(body.subscription_id)
 407        .await?
 408        .ok_or_else(|| anyhow!("subscription not found"))?;
 409    let subscription_id = SubscriptionId::from_str(&subscription.stripe_subscription_id)
 410        .context("failed to parse subscription ID")?;
 411
 412    if body.intent == ManageSubscriptionIntent::StopCancellation {
 413        let updated_stripe_subscription = Subscription::update(
 414            &stripe_client,
 415            &subscription_id,
 416            stripe::UpdateSubscription {
 417                cancel_at_period_end: Some(false),
 418                ..Default::default()
 419            },
 420        )
 421        .await?;
 422
 423        app.db
 424            .update_billing_subscription(
 425                subscription.id,
 426                &UpdateBillingSubscriptionParams {
 427                    stripe_cancel_at: ActiveValue::set(
 428                        updated_stripe_subscription
 429                            .cancel_at
 430                            .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
 431                            .map(|time| time.naive_utc()),
 432                    ),
 433                    ..Default::default()
 434                },
 435            )
 436            .await?;
 437
 438        return Ok(Json(ManageBillingSubscriptionResponse {
 439            billing_portal_session_url: None,
 440        }));
 441    }
 442
 443    let flow = match body.intent {
 444        ManageSubscriptionIntent::ManageSubscription => None,
 445        ManageSubscriptionIntent::UpgradeToPro => {
 446            let zed_pro_price_id = app.config.zed_pro_price_id()?;
 447            let zed_pro_trial_price_id = app.config.zed_pro_trial_price_id()?;
 448            let zed_free_price_id = app.config.zed_free_price_id()?;
 449
 450            let stripe_subscription =
 451                Subscription::retrieve(&stripe_client, &subscription_id, &[]).await?;
 452
 453            let subscription_item_to_update = stripe_subscription
 454                .items
 455                .data
 456                .iter()
 457                .find_map(|item| {
 458                    let price = item.price.as_ref()?;
 459
 460                    if price.id == zed_free_price_id || price.id == zed_pro_trial_price_id {
 461                        Some(item.id.clone())
 462                    } else {
 463                        None
 464                    }
 465                })
 466                .ok_or_else(|| anyhow!("No subscription item to update"))?;
 467
 468            Some(CreateBillingPortalSessionFlowData {
 469                type_: CreateBillingPortalSessionFlowDataType::SubscriptionUpdateConfirm,
 470                subscription_update_confirm: Some(
 471                    CreateBillingPortalSessionFlowDataSubscriptionUpdateConfirm {
 472                        subscription: subscription.stripe_subscription_id,
 473                        items: vec![
 474                            CreateBillingPortalSessionFlowDataSubscriptionUpdateConfirmItems {
 475                                id: subscription_item_to_update.to_string(),
 476                                price: Some(zed_pro_price_id.to_string()),
 477                                quantity: Some(1),
 478                            },
 479                        ],
 480                        discounts: None,
 481                    },
 482                ),
 483                ..Default::default()
 484            })
 485        }
 486        ManageSubscriptionIntent::Cancel => Some(CreateBillingPortalSessionFlowData {
 487            type_: CreateBillingPortalSessionFlowDataType::SubscriptionCancel,
 488            after_completion: Some(CreateBillingPortalSessionFlowDataAfterCompletion {
 489                type_: stripe::CreateBillingPortalSessionFlowDataAfterCompletionType::Redirect,
 490                redirect: Some(CreateBillingPortalSessionFlowDataAfterCompletionRedirect {
 491                    return_url: format!("{}/account", app.config.zed_dot_dev_url()),
 492                }),
 493                ..Default::default()
 494            }),
 495            subscription_cancel: Some(
 496                stripe::CreateBillingPortalSessionFlowDataSubscriptionCancel {
 497                    subscription: subscription.stripe_subscription_id,
 498                    retention: None,
 499                },
 500            ),
 501            ..Default::default()
 502        }),
 503        ManageSubscriptionIntent::StopCancellation => unreachable!(),
 504    };
 505
 506    let mut params = CreateBillingPortalSession::new(customer_id);
 507    params.flow_data = flow;
 508    let return_url = format!("{}/account", app.config.zed_dot_dev_url());
 509    params.return_url = Some(&return_url);
 510
 511    let session = BillingPortalSession::create(&stripe_client, params).await?;
 512
 513    Ok(Json(ManageBillingSubscriptionResponse {
 514        billing_portal_session_url: Some(session.url),
 515    }))
 516}
 517
 518/// The amount of time we wait in between each poll of Stripe events.
 519///
 520/// This value should strike a balance between:
 521///   1. Being short enough that we update quickly when something in Stripe changes
 522///   2. Being long enough that we don't eat into our rate limits.
 523///
 524/// As a point of reference, the Sequin folks say they have this at **500ms**:
 525///
 526/// > We poll the Stripe /events endpoint every 500ms per account
 527/// >
 528/// > — https://blog.sequinstream.com/events-not-webhooks/
 529const POLL_EVENTS_INTERVAL: Duration = Duration::from_secs(5);
 530
 531/// The maximum number of events to return per page.
 532///
 533/// We set this to 100 (the max) so we have to make fewer requests to Stripe.
 534///
 535/// > Limit can range between 1 and 100, and the default is 10.
 536const EVENTS_LIMIT_PER_PAGE: u64 = 100;
 537
 538/// The number of pages consisting entirely of already-processed events that we
 539/// will see before we stop retrieving events.
 540///
 541/// This is used to prevent over-fetching the Stripe events API for events we've
 542/// already seen and processed.
 543const NUMBER_OF_ALREADY_PROCESSED_PAGES_BEFORE_WE_STOP: usize = 4;
 544
 545/// Polls the Stripe events API periodically to reconcile the records in our
 546/// database with the data in Stripe.
 547pub fn poll_stripe_events_periodically(app: Arc<AppState>, rpc_server: Arc<Server>) {
 548    let Some(stripe_client) = app.stripe_client.clone() else {
 549        log::warn!("failed to retrieve Stripe client");
 550        return;
 551    };
 552
 553    let executor = app.executor.clone();
 554    executor.spawn_detached({
 555        let executor = executor.clone();
 556        async move {
 557            loop {
 558                poll_stripe_events(&app, &rpc_server, &stripe_client)
 559                    .await
 560                    .log_err();
 561
 562                executor.sleep(POLL_EVENTS_INTERVAL).await;
 563            }
 564        }
 565    });
 566}
 567
 568async fn poll_stripe_events(
 569    app: &Arc<AppState>,
 570    rpc_server: &Arc<Server>,
 571    stripe_client: &stripe::Client,
 572) -> anyhow::Result<()> {
 573    fn event_type_to_string(event_type: EventType) -> String {
 574        // Calling `to_string` on `stripe::EventType` members gives us a quoted string,
 575        // so we need to unquote it.
 576        event_type.to_string().trim_matches('"').to_string()
 577    }
 578
 579    let event_types = [
 580        EventType::CustomerCreated,
 581        EventType::CustomerUpdated,
 582        EventType::CustomerSubscriptionCreated,
 583        EventType::CustomerSubscriptionUpdated,
 584        EventType::CustomerSubscriptionPaused,
 585        EventType::CustomerSubscriptionResumed,
 586        EventType::CustomerSubscriptionDeleted,
 587    ]
 588    .into_iter()
 589    .map(event_type_to_string)
 590    .collect::<Vec<_>>();
 591
 592    let mut pages_of_already_processed_events = 0;
 593    let mut unprocessed_events = Vec::new();
 594
 595    log::info!(
 596        "Stripe events: starting retrieval for {}",
 597        event_types.join(", ")
 598    );
 599    let mut params = ListEvents::new();
 600    params.types = Some(event_types.clone());
 601    params.limit = Some(EVENTS_LIMIT_PER_PAGE);
 602
 603    let mut event_pages = stripe::Event::list(&stripe_client, &params)
 604        .await?
 605        .paginate(params);
 606
 607    loop {
 608        let processed_event_ids = {
 609            let event_ids = event_pages
 610                .page
 611                .data
 612                .iter()
 613                .map(|event| event.id.as_str())
 614                .collect::<Vec<_>>();
 615            app.db
 616                .get_processed_stripe_events_by_event_ids(&event_ids)
 617                .await?
 618                .into_iter()
 619                .map(|event| event.stripe_event_id)
 620                .collect::<Vec<_>>()
 621        };
 622
 623        let mut processed_events_in_page = 0;
 624        let events_in_page = event_pages.page.data.len();
 625        for event in &event_pages.page.data {
 626            if processed_event_ids.contains(&event.id.to_string()) {
 627                processed_events_in_page += 1;
 628                log::debug!("Stripe events: already processed '{}', skipping", event.id);
 629            } else {
 630                unprocessed_events.push(event.clone());
 631            }
 632        }
 633
 634        if processed_events_in_page == events_in_page {
 635            pages_of_already_processed_events += 1;
 636        }
 637
 638        if event_pages.page.has_more {
 639            if pages_of_already_processed_events >= NUMBER_OF_ALREADY_PROCESSED_PAGES_BEFORE_WE_STOP
 640            {
 641                log::info!(
 642                    "Stripe events: stopping, saw {pages_of_already_processed_events} pages of already-processed events"
 643                );
 644                break;
 645            } else {
 646                log::info!("Stripe events: retrieving next page");
 647                event_pages = event_pages.next(&stripe_client).await?;
 648            }
 649        } else {
 650            break;
 651        }
 652    }
 653
 654    log::info!("Stripe events: unprocessed {}", unprocessed_events.len());
 655
 656    // Sort all of the unprocessed events in ascending order, so we can handle them in the order they occurred.
 657    unprocessed_events.sort_by(|a, b| a.created.cmp(&b.created).then_with(|| a.id.cmp(&b.id)));
 658
 659    for event in unprocessed_events {
 660        let event_id = event.id.clone();
 661        let processed_event_params = CreateProcessedStripeEventParams {
 662            stripe_event_id: event.id.to_string(),
 663            stripe_event_type: event_type_to_string(event.type_),
 664            stripe_event_created_timestamp: event.created,
 665        };
 666
 667        // If the event has happened too far in the past, we don't want to
 668        // process it and risk overwriting other more-recent updates.
 669        //
 670        // 1 day was chosen arbitrarily. This could be made longer or shorter.
 671        let one_day = Duration::from_secs(24 * 60 * 60);
 672        let a_day_ago = Utc::now() - one_day;
 673        if a_day_ago.timestamp() > event.created {
 674            log::info!(
 675                "Stripe events: event '{}' is more than {one_day:?} old, marking as processed",
 676                event_id
 677            );
 678            app.db
 679                .create_processed_stripe_event(&processed_event_params)
 680                .await?;
 681
 682            return Ok(());
 683        }
 684
 685        let process_result = match event.type_ {
 686            EventType::CustomerCreated | EventType::CustomerUpdated => {
 687                handle_customer_event(app, stripe_client, event).await
 688            }
 689            EventType::CustomerSubscriptionCreated
 690            | EventType::CustomerSubscriptionUpdated
 691            | EventType::CustomerSubscriptionPaused
 692            | EventType::CustomerSubscriptionResumed
 693            | EventType::CustomerSubscriptionDeleted => {
 694                handle_customer_subscription_event(app, rpc_server, stripe_client, event).await
 695            }
 696            _ => Ok(()),
 697        };
 698
 699        if let Some(()) = process_result
 700            .with_context(|| format!("failed to process event {event_id} successfully"))
 701            .log_err()
 702        {
 703            app.db
 704                .create_processed_stripe_event(&processed_event_params)
 705                .await?;
 706        }
 707    }
 708
 709    Ok(())
 710}
 711
 712async fn handle_customer_event(
 713    app: &Arc<AppState>,
 714    _stripe_client: &stripe::Client,
 715    event: stripe::Event,
 716) -> anyhow::Result<()> {
 717    let EventObject::Customer(customer) = event.data.object else {
 718        bail!("unexpected event payload for {}", event.id);
 719    };
 720
 721    log::info!("handling Stripe {} event: {}", event.type_, event.id);
 722
 723    let Some(email) = customer.email else {
 724        log::info!("Stripe customer has no email: skipping");
 725        return Ok(());
 726    };
 727
 728    let Some(user) = app.db.get_user_by_email(&email).await? else {
 729        log::info!("no user found for email: skipping");
 730        return Ok(());
 731    };
 732
 733    if let Some(existing_customer) = app
 734        .db
 735        .get_billing_customer_by_stripe_customer_id(&customer.id)
 736        .await?
 737    {
 738        app.db
 739            .update_billing_customer(
 740                existing_customer.id,
 741                &UpdateBillingCustomerParams {
 742                    // For now we just leave the information as-is, as it is not
 743                    // likely to change.
 744                    ..Default::default()
 745                },
 746            )
 747            .await?;
 748    } else {
 749        app.db
 750            .create_billing_customer(&CreateBillingCustomerParams {
 751                user_id: user.id,
 752                stripe_customer_id: customer.id.to_string(),
 753            })
 754            .await?;
 755    }
 756
 757    Ok(())
 758}
 759
 760async fn handle_customer_subscription_event(
 761    app: &Arc<AppState>,
 762    rpc_server: &Arc<Server>,
 763    stripe_client: &stripe::Client,
 764    event: stripe::Event,
 765) -> anyhow::Result<()> {
 766    let EventObject::Subscription(subscription) = event.data.object else {
 767        bail!("unexpected event payload for {}", event.id);
 768    };
 769
 770    log::info!("handling Stripe {} event: {}", event.type_, event.id);
 771
 772    let subscription_kind = maybe!({
 773        let zed_pro_price_id = app.config.zed_pro_price_id().ok()?;
 774        let zed_pro_trial_price_id = app.config.zed_pro_trial_price_id().ok()?;
 775        let zed_free_price_id = app.config.zed_free_price_id().ok()?;
 776
 777        subscription.items.data.iter().find_map(|item| {
 778            let price = item.price.as_ref()?;
 779
 780            if price.id == zed_pro_price_id {
 781                Some(SubscriptionKind::ZedPro)
 782            } else if price.id == zed_pro_trial_price_id {
 783                Some(SubscriptionKind::ZedProTrial)
 784            } else if price.id == zed_free_price_id {
 785                Some(SubscriptionKind::ZedFree)
 786            } else {
 787                None
 788            }
 789        })
 790    });
 791
 792    let billing_customer =
 793        find_or_create_billing_customer(app, stripe_client, subscription.customer)
 794            .await?
 795            .ok_or_else(|| anyhow!("billing customer not found"))?;
 796
 797    let was_canceled_due_to_payment_failure = subscription.status == SubscriptionStatus::Canceled
 798        && subscription
 799            .cancellation_details
 800            .as_ref()
 801            .and_then(|details| details.reason)
 802            .map_or(false, |reason| {
 803                reason == CancellationDetailsReason::PaymentFailed
 804            });
 805
 806    if was_canceled_due_to_payment_failure {
 807        app.db
 808            .update_billing_customer(
 809                billing_customer.id,
 810                &UpdateBillingCustomerParams {
 811                    has_overdue_invoices: ActiveValue::set(true),
 812                    ..Default::default()
 813                },
 814            )
 815            .await?;
 816    }
 817
 818    if let Some(existing_subscription) = app
 819        .db
 820        .get_billing_subscription_by_stripe_subscription_id(&subscription.id)
 821        .await?
 822    {
 823        app.db
 824            .update_billing_subscription(
 825                existing_subscription.id,
 826                &UpdateBillingSubscriptionParams {
 827                    billing_customer_id: ActiveValue::set(billing_customer.id),
 828                    kind: ActiveValue::set(subscription_kind),
 829                    stripe_subscription_id: ActiveValue::set(subscription.id.to_string()),
 830                    stripe_subscription_status: ActiveValue::set(subscription.status.into()),
 831                    stripe_cancel_at: ActiveValue::set(
 832                        subscription
 833                            .cancel_at
 834                            .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
 835                            .map(|time| time.naive_utc()),
 836                    ),
 837                    stripe_cancellation_reason: ActiveValue::set(
 838                        subscription
 839                            .cancellation_details
 840                            .and_then(|details| details.reason)
 841                            .map(|reason| reason.into()),
 842                    ),
 843                    stripe_current_period_start: ActiveValue::set(Some(
 844                        subscription.current_period_start,
 845                    )),
 846                    stripe_current_period_end: ActiveValue::set(Some(
 847                        subscription.current_period_end,
 848                    )),
 849                },
 850            )
 851            .await?;
 852    } else {
 853        // If the user already has an active billing subscription, ignore the
 854        // event and return an `Ok` to signal that it was processed
 855        // successfully.
 856        //
 857        // There is the possibility that this could cause us to not create a
 858        // subscription in the following scenario:
 859        //
 860        //   1. User has an active subscription A
 861        //   2. User cancels subscription A
 862        //   3. User creates a new subscription B
 863        //   4. We process the new subscription B before the cancellation of subscription A
 864        //   5. User ends up with no subscriptions
 865        //
 866        // In theory this situation shouldn't arise as we try to process the events in the order they occur.
 867        if app
 868            .db
 869            .has_active_billing_subscription(billing_customer.user_id)
 870            .await?
 871        {
 872            log::info!(
 873                "user {user_id} already has an active subscription, skipping creation of subscription {subscription_id}",
 874                user_id = billing_customer.user_id,
 875                subscription_id = subscription.id
 876            );
 877            return Ok(());
 878        }
 879
 880        app.db
 881            .create_billing_subscription(&CreateBillingSubscriptionParams {
 882                billing_customer_id: billing_customer.id,
 883                kind: subscription_kind,
 884                stripe_subscription_id: subscription.id.to_string(),
 885                stripe_subscription_status: subscription.status.into(),
 886                stripe_cancellation_reason: subscription
 887                    .cancellation_details
 888                    .and_then(|details| details.reason)
 889                    .map(|reason| reason.into()),
 890                stripe_current_period_start: Some(subscription.current_period_start),
 891                stripe_current_period_end: Some(subscription.current_period_end),
 892            })
 893            .await?;
 894    }
 895
 896    // When the user's subscription changes, we want to refresh their LLM tokens
 897    // to either grant/revoke access.
 898    rpc_server
 899        .refresh_llm_tokens_for_user(billing_customer.user_id)
 900        .await;
 901
 902    Ok(())
 903}
 904
 905#[derive(Debug, Deserialize)]
 906struct GetMonthlySpendParams {
 907    github_user_id: i32,
 908}
 909
 910#[derive(Debug, Serialize)]
 911struct GetMonthlySpendResponse {
 912    monthly_free_tier_spend_in_cents: u32,
 913    monthly_free_tier_allowance_in_cents: u32,
 914    monthly_spend_in_cents: u32,
 915}
 916
 917async fn get_monthly_spend(
 918    Extension(app): Extension<Arc<AppState>>,
 919    Query(params): Query<GetMonthlySpendParams>,
 920) -> Result<Json<GetMonthlySpendResponse>> {
 921    let user = app
 922        .db
 923        .get_user_by_github_user_id(params.github_user_id)
 924        .await?
 925        .ok_or_else(|| anyhow!("user not found"))?;
 926
 927    let Some(llm_db) = app.llm_db.clone() else {
 928        return Err(Error::http(
 929            StatusCode::NOT_IMPLEMENTED,
 930            "LLM database not available".into(),
 931        ));
 932    };
 933
 934    let free_tier = user
 935        .custom_llm_monthly_allowance_in_cents
 936        .map(|allowance| Cents(allowance as u32))
 937        .unwrap_or(FREE_TIER_MONTHLY_SPENDING_LIMIT);
 938
 939    let spending_for_month = llm_db
 940        .get_user_spending_for_month(user.id, Utc::now())
 941        .await?;
 942
 943    let free_tier_spend = Cents::min(spending_for_month, free_tier);
 944    let monthly_spend = spending_for_month.saturating_sub(free_tier);
 945
 946    Ok(Json(GetMonthlySpendResponse {
 947        monthly_free_tier_spend_in_cents: free_tier_spend.0,
 948        monthly_free_tier_allowance_in_cents: free_tier.0,
 949        monthly_spend_in_cents: monthly_spend.0,
 950    }))
 951}
 952
 953#[derive(Debug, Deserialize)]
 954struct GetCurrentUsageParams {
 955    github_user_id: i32,
 956}
 957
 958#[derive(Debug, Serialize)]
 959struct UsageCounts {
 960    pub used: i32,
 961    pub limit: Option<i32>,
 962    pub remaining: Option<i32>,
 963}
 964
 965#[derive(Debug, Serialize)]
 966struct GetCurrentUsageResponse {
 967    pub model_requests: UsageCounts,
 968    pub edit_predictions: UsageCounts,
 969}
 970
 971async fn get_current_usage(
 972    Extension(app): Extension<Arc<AppState>>,
 973    Query(params): Query<GetCurrentUsageParams>,
 974) -> Result<Json<GetCurrentUsageResponse>> {
 975    let user = app
 976        .db
 977        .get_user_by_github_user_id(params.github_user_id)
 978        .await?
 979        .ok_or_else(|| anyhow!("user not found"))?;
 980
 981    let Some(llm_db) = app.llm_db.clone() else {
 982        return Err(Error::http(
 983            StatusCode::NOT_IMPLEMENTED,
 984            "LLM database not available".into(),
 985        ));
 986    };
 987
 988    let empty_usage = GetCurrentUsageResponse {
 989        model_requests: UsageCounts {
 990            used: 0,
 991            limit: Some(0),
 992            remaining: Some(0),
 993        },
 994        edit_predictions: UsageCounts {
 995            used: 0,
 996            limit: Some(0),
 997            remaining: Some(0),
 998        },
 999    };
1000
1001    let Some(subscription) = app.db.get_active_billing_subscription(user.id).await? else {
1002        return Ok(Json(empty_usage));
1003    };
1004
1005    let subscription_period = maybe!({
1006        let period_start_at = subscription.current_period_start_at()?;
1007        let period_end_at = subscription.current_period_end_at()?;
1008
1009        Some((period_start_at, period_end_at))
1010    });
1011
1012    let Some((period_start_at, period_end_at)) = subscription_period else {
1013        return Ok(Json(empty_usage));
1014    };
1015
1016    let usage = llm_db
1017        .get_subscription_usage_for_period(user.id, period_start_at, period_end_at)
1018        .await?;
1019    let Some(usage) = usage else {
1020        return Ok(Json(empty_usage));
1021    };
1022
1023    let plan = match usage.plan {
1024        SubscriptionKind::ZedPro => zed_llm_client::Plan::ZedPro,
1025        SubscriptionKind::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1026        SubscriptionKind::ZedFree => zed_llm_client::Plan::Free,
1027    };
1028
1029    let model_requests_limit = match plan.model_requests_limit() {
1030        zed_llm_client::UsageLimit::Limited(limit) => Some(limit),
1031        zed_llm_client::UsageLimit::Unlimited => None,
1032    };
1033    let edit_prediction_limit = match plan.edit_predictions_limit() {
1034        zed_llm_client::UsageLimit::Limited(limit) => Some(limit),
1035        zed_llm_client::UsageLimit::Unlimited => None,
1036    };
1037
1038    Ok(Json(GetCurrentUsageResponse {
1039        model_requests: UsageCounts {
1040            used: usage.model_requests,
1041            limit: model_requests_limit,
1042            remaining: model_requests_limit.map(|limit| (limit - usage.model_requests).max(0)),
1043        },
1044        edit_predictions: UsageCounts {
1045            used: usage.edit_predictions,
1046            limit: edit_prediction_limit,
1047            remaining: edit_prediction_limit.map(|limit| (limit - usage.edit_predictions).max(0)),
1048        },
1049    }))
1050}
1051
1052impl From<SubscriptionStatus> for StripeSubscriptionStatus {
1053    fn from(value: SubscriptionStatus) -> Self {
1054        match value {
1055            SubscriptionStatus::Incomplete => Self::Incomplete,
1056            SubscriptionStatus::IncompleteExpired => Self::IncompleteExpired,
1057            SubscriptionStatus::Trialing => Self::Trialing,
1058            SubscriptionStatus::Active => Self::Active,
1059            SubscriptionStatus::PastDue => Self::PastDue,
1060            SubscriptionStatus::Canceled => Self::Canceled,
1061            SubscriptionStatus::Unpaid => Self::Unpaid,
1062            SubscriptionStatus::Paused => Self::Paused,
1063        }
1064    }
1065}
1066
1067impl From<CancellationDetailsReason> for StripeCancellationReason {
1068    fn from(value: CancellationDetailsReason) -> Self {
1069        match value {
1070            CancellationDetailsReason::CancellationRequested => Self::CancellationRequested,
1071            CancellationDetailsReason::PaymentDisputed => Self::PaymentDisputed,
1072            CancellationDetailsReason::PaymentFailed => Self::PaymentFailed,
1073        }
1074    }
1075}
1076
1077/// Finds or creates a billing customer using the provided customer.
1078async fn find_or_create_billing_customer(
1079    app: &Arc<AppState>,
1080    stripe_client: &stripe::Client,
1081    customer_or_id: Expandable<Customer>,
1082) -> anyhow::Result<Option<billing_customer::Model>> {
1083    let customer_id = match &customer_or_id {
1084        Expandable::Id(id) => id,
1085        Expandable::Object(customer) => customer.id.as_ref(),
1086    };
1087
1088    // If we already have a billing customer record associated with the Stripe customer,
1089    // there's nothing more we need to do.
1090    if let Some(billing_customer) = app
1091        .db
1092        .get_billing_customer_by_stripe_customer_id(customer_id)
1093        .await?
1094    {
1095        return Ok(Some(billing_customer));
1096    }
1097
1098    // If all we have is a customer ID, resolve it to a full customer record by
1099    // hitting the Stripe API.
1100    let customer = match customer_or_id {
1101        Expandable::Id(id) => Customer::retrieve(stripe_client, &id, &[]).await?,
1102        Expandable::Object(customer) => *customer,
1103    };
1104
1105    let Some(email) = customer.email else {
1106        return Ok(None);
1107    };
1108
1109    let Some(user) = app.db.get_user_by_email(&email).await? else {
1110        return Ok(None);
1111    };
1112
1113    let billing_customer = app
1114        .db
1115        .create_billing_customer(&CreateBillingCustomerParams {
1116            user_id: user.id,
1117            stripe_customer_id: customer.id.to_string(),
1118        })
1119        .await?;
1120
1121    Ok(Some(billing_customer))
1122}
1123
1124const SYNC_LLM_USAGE_WITH_STRIPE_INTERVAL: Duration = Duration::from_secs(60);
1125
1126pub fn sync_llm_usage_with_stripe_periodically(app: Arc<AppState>) {
1127    let Some(stripe_billing) = app.stripe_billing.clone() else {
1128        log::warn!("failed to retrieve Stripe billing object");
1129        return;
1130    };
1131    let Some(llm_db) = app.llm_db.clone() else {
1132        log::warn!("failed to retrieve LLM database");
1133        return;
1134    };
1135
1136    let executor = app.executor.clone();
1137    executor.spawn_detached({
1138        let executor = executor.clone();
1139        async move {
1140            loop {
1141                sync_with_stripe(&app, &llm_db, &stripe_billing)
1142                    .await
1143                    .context("failed to sync LLM usage to Stripe")
1144                    .trace_err();
1145                executor.sleep(SYNC_LLM_USAGE_WITH_STRIPE_INTERVAL).await;
1146            }
1147        }
1148    });
1149}
1150
1151async fn sync_with_stripe(
1152    app: &Arc<AppState>,
1153    llm_db: &Arc<LlmDatabase>,
1154    stripe_billing: &Arc<StripeBilling>,
1155) -> anyhow::Result<()> {
1156    let events = llm_db.get_billing_events().await?;
1157    let user_ids = events
1158        .iter()
1159        .map(|(event, _)| event.user_id)
1160        .collect::<HashSet<UserId>>();
1161    let stripe_subscriptions = app.db.get_active_billing_subscriptions(user_ids).await?;
1162
1163    for (event, model) in events {
1164        let Some((stripe_db_customer, stripe_db_subscription)) =
1165            stripe_subscriptions.get(&event.user_id)
1166        else {
1167            tracing::warn!(
1168                user_id = event.user_id.0,
1169                "Registered billing event for user who is not a Stripe customer. Billing events should only be created for users who are Stripe customers, so this is a mistake on our side."
1170            );
1171            continue;
1172        };
1173        let stripe_subscription_id: stripe::SubscriptionId = stripe_db_subscription
1174            .stripe_subscription_id
1175            .parse()
1176            .context("failed to parse stripe subscription id from db")?;
1177        let stripe_customer_id: stripe::CustomerId = stripe_db_customer
1178            .stripe_customer_id
1179            .parse()
1180            .context("failed to parse stripe customer id from db")?;
1181
1182        let stripe_model = stripe_billing.register_model(&model).await?;
1183        stripe_billing
1184            .subscribe_to_model(&stripe_subscription_id, &stripe_model)
1185            .await?;
1186        stripe_billing
1187            .bill_model_usage(&stripe_customer_id, &stripe_model, &event)
1188            .await?;
1189        llm_db.consume_billing_event(event.id).await?;
1190    }
1191
1192    Ok(())
1193}