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