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