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