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    if let Some(existing_subscription) = app
670        .db
671        .get_billing_subscription_by_stripe_subscription_id(&subscription.id)
672        .await?
673    {
674        app.db
675            .update_billing_subscription(
676                existing_subscription.id,
677                &UpdateBillingSubscriptionParams {
678                    billing_customer_id: ActiveValue::set(billing_customer.id),
679                    stripe_subscription_id: ActiveValue::set(subscription.id.to_string()),
680                    stripe_subscription_status: ActiveValue::set(subscription.status.into()),
681                    stripe_cancel_at: ActiveValue::set(
682                        subscription
683                            .cancel_at
684                            .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
685                            .map(|time| time.naive_utc()),
686                    ),
687                    stripe_cancellation_reason: ActiveValue::set(
688                        subscription
689                            .cancellation_details
690                            .and_then(|details| details.reason)
691                            .map(|reason| reason.into()),
692                    ),
693                },
694            )
695            .await?;
696    } else {
697        // If the user already has an active billing subscription, ignore the
698        // event and return an `Ok` to signal that it was processed
699        // successfully.
700        //
701        // There is the possibility that this could cause us to not create a
702        // subscription in the following scenario:
703        //
704        //   1. User has an active subscription A
705        //   2. User cancels subscription A
706        //   3. User creates a new subscription B
707        //   4. We process the new subscription B before the cancellation of subscription A
708        //   5. User ends up with no subscriptions
709        //
710        // In theory this situation shouldn't arise as we try to process the events in the order they occur.
711        if app
712            .db
713            .has_active_billing_subscription(billing_customer.user_id)
714            .await?
715        {
716            log::info!(
717                "user {user_id} already has an active subscription, skipping creation of subscription {subscription_id}",
718                user_id = billing_customer.user_id,
719                subscription_id = subscription.id
720            );
721            return Ok(());
722        }
723
724        app.db
725            .create_billing_subscription(&CreateBillingSubscriptionParams {
726                billing_customer_id: billing_customer.id,
727                stripe_subscription_id: subscription.id.to_string(),
728                stripe_subscription_status: subscription.status.into(),
729                stripe_cancellation_reason: subscription
730                    .cancellation_details
731                    .and_then(|details| details.reason)
732                    .map(|reason| reason.into()),
733            })
734            .await?;
735    }
736
737    // When the user's subscription changes, we want to refresh their LLM tokens
738    // to either grant/revoke access.
739    rpc_server
740        .refresh_llm_tokens_for_user(billing_customer.user_id)
741        .await;
742
743    Ok(())
744}
745
746#[derive(Debug, Deserialize)]
747struct GetMonthlySpendParams {
748    github_user_id: i32,
749}
750
751#[derive(Debug, Serialize)]
752struct GetMonthlySpendResponse {
753    monthly_free_tier_spend_in_cents: u32,
754    monthly_free_tier_allowance_in_cents: u32,
755    monthly_spend_in_cents: u32,
756}
757
758async fn get_monthly_spend(
759    Extension(app): Extension<Arc<AppState>>,
760    Query(params): Query<GetMonthlySpendParams>,
761) -> Result<Json<GetMonthlySpendResponse>> {
762    let user = app
763        .db
764        .get_user_by_github_user_id(params.github_user_id)
765        .await?
766        .ok_or_else(|| anyhow!("user not found"))?;
767
768    let Some(llm_db) = app.llm_db.clone() else {
769        return Err(Error::http(
770            StatusCode::NOT_IMPLEMENTED,
771            "LLM database not available".into(),
772        ));
773    };
774
775    let free_tier = user
776        .custom_llm_monthly_allowance_in_cents
777        .map(|allowance| Cents(allowance as u32))
778        .unwrap_or(FREE_TIER_MONTHLY_SPENDING_LIMIT);
779
780    let spending_for_month = llm_db
781        .get_user_spending_for_month(user.id, Utc::now())
782        .await?;
783
784    let free_tier_spend = Cents::min(spending_for_month, free_tier);
785    let monthly_spend = spending_for_month.saturating_sub(free_tier);
786
787    Ok(Json(GetMonthlySpendResponse {
788        monthly_free_tier_spend_in_cents: free_tier_spend.0,
789        monthly_free_tier_allowance_in_cents: free_tier.0,
790        monthly_spend_in_cents: monthly_spend.0,
791    }))
792}
793
794impl From<SubscriptionStatus> for StripeSubscriptionStatus {
795    fn from(value: SubscriptionStatus) -> Self {
796        match value {
797            SubscriptionStatus::Incomplete => Self::Incomplete,
798            SubscriptionStatus::IncompleteExpired => Self::IncompleteExpired,
799            SubscriptionStatus::Trialing => Self::Trialing,
800            SubscriptionStatus::Active => Self::Active,
801            SubscriptionStatus::PastDue => Self::PastDue,
802            SubscriptionStatus::Canceled => Self::Canceled,
803            SubscriptionStatus::Unpaid => Self::Unpaid,
804            SubscriptionStatus::Paused => Self::Paused,
805        }
806    }
807}
808
809impl From<CancellationDetailsReason> for StripeCancellationReason {
810    fn from(value: CancellationDetailsReason) -> Self {
811        match value {
812            CancellationDetailsReason::CancellationRequested => Self::CancellationRequested,
813            CancellationDetailsReason::PaymentDisputed => Self::PaymentDisputed,
814            CancellationDetailsReason::PaymentFailed => Self::PaymentFailed,
815        }
816    }
817}
818
819/// Finds or creates a billing customer using the provided customer.
820async fn find_or_create_billing_customer(
821    app: &Arc<AppState>,
822    stripe_client: &stripe::Client,
823    customer_or_id: Expandable<Customer>,
824) -> anyhow::Result<Option<billing_customer::Model>> {
825    let customer_id = match &customer_or_id {
826        Expandable::Id(id) => id,
827        Expandable::Object(customer) => customer.id.as_ref(),
828    };
829
830    // If we already have a billing customer record associated with the Stripe customer,
831    // there's nothing more we need to do.
832    if let Some(billing_customer) = app
833        .db
834        .get_billing_customer_by_stripe_customer_id(customer_id)
835        .await?
836    {
837        return Ok(Some(billing_customer));
838    }
839
840    // If all we have is a customer ID, resolve it to a full customer record by
841    // hitting the Stripe API.
842    let customer = match customer_or_id {
843        Expandable::Id(id) => Customer::retrieve(stripe_client, &id, &[]).await?,
844        Expandable::Object(customer) => *customer,
845    };
846
847    let Some(email) = customer.email else {
848        return Ok(None);
849    };
850
851    let Some(user) = app.db.get_user_by_email(&email).await? else {
852        return Ok(None);
853    };
854
855    let billing_customer = app
856        .db
857        .create_billing_customer(&CreateBillingCustomerParams {
858            user_id: user.id,
859            stripe_customer_id: customer.id.to_string(),
860        })
861        .await?;
862
863    Ok(Some(billing_customer))
864}
865
866const SYNC_LLM_USAGE_WITH_STRIPE_INTERVAL: Duration = Duration::from_secs(60);
867
868pub fn sync_llm_usage_with_stripe_periodically(app: Arc<AppState>) {
869    let Some(stripe_billing) = app.stripe_billing.clone() else {
870        log::warn!("failed to retrieve Stripe billing object");
871        return;
872    };
873    let Some(llm_db) = app.llm_db.clone() else {
874        log::warn!("failed to retrieve LLM database");
875        return;
876    };
877
878    let executor = app.executor.clone();
879    executor.spawn_detached({
880        let executor = executor.clone();
881        async move {
882            loop {
883                sync_with_stripe(&app, &llm_db, &stripe_billing)
884                    .await
885                    .context("failed to sync LLM usage to Stripe")
886                    .trace_err();
887                executor.sleep(SYNC_LLM_USAGE_WITH_STRIPE_INTERVAL).await;
888            }
889        }
890    });
891}
892
893async fn sync_with_stripe(
894    app: &Arc<AppState>,
895    llm_db: &Arc<LlmDatabase>,
896    stripe_billing: &Arc<StripeBilling>,
897) -> anyhow::Result<()> {
898    let events = llm_db.get_billing_events().await?;
899    let user_ids = events
900        .iter()
901        .map(|(event, _)| event.user_id)
902        .collect::<HashSet<UserId>>();
903    let stripe_subscriptions = app.db.get_active_billing_subscriptions(user_ids).await?;
904
905    for (event, model) in events {
906        let Some((stripe_db_customer, stripe_db_subscription)) =
907            stripe_subscriptions.get(&event.user_id)
908        else {
909            tracing::warn!(
910                user_id = event.user_id.0,
911                "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."
912            );
913            continue;
914        };
915        let stripe_subscription_id: stripe::SubscriptionId = stripe_db_subscription
916            .stripe_subscription_id
917            .parse()
918            .context("failed to parse stripe subscription id from db")?;
919        let stripe_customer_id: stripe::CustomerId = stripe_db_customer
920            .stripe_customer_id
921            .parse()
922            .context("failed to parse stripe customer id from db")?;
923
924        let stripe_model = stripe_billing.register_model(&model).await?;
925        stripe_billing
926            .subscribe_to_model(&stripe_subscription_id, &stripe_model)
927            .await?;
928        stripe_billing
929            .bill_model_usage(&stripe_customer_id, &stripe_model, &event)
930            .await?;
931        llm_db.consume_billing_event(event.id).await?;
932    }
933
934    Ok(())
935}