billing.rs

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