1use anyhow::{Context as _, 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, CustomerId, EventObject, EventType, ListEvents,
21 PaymentMethod, 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::db::subscription_usage_meter::CompletionMode;
30use crate::llm::{AGENT_EXTENDED_TRIAL_FEATURE_FLAG, DEFAULT_MAX_MONTHLY_SPEND};
31use crate::rpc::{ResultExt as _, Server};
32use crate::stripe_client::{
33 StripeCancellationDetailsReason, StripeClient, StripeCustomerId, StripeSubscription,
34 StripeSubscriptionId,
35};
36use crate::{AppState, Error, Result};
37use crate::{db::UserId, llm::db::LlmDatabase};
38use crate::{
39 db::{
40 BillingSubscriptionId, CreateBillingCustomerParams, CreateBillingSubscriptionParams,
41 CreateProcessedStripeEventParams, UpdateBillingCustomerParams,
42 UpdateBillingPreferencesParams, UpdateBillingSubscriptionParams, billing_customer,
43 },
44 stripe_billing::StripeBilling,
45};
46
47pub fn router() -> Router {
48 Router::new()
49 .route(
50 "/billing/preferences",
51 get(get_billing_preferences).put(update_billing_preferences),
52 )
53 .route(
54 "/billing/subscriptions",
55 get(list_billing_subscriptions).post(create_billing_subscription),
56 )
57 .route(
58 "/billing/subscriptions/manage",
59 post(manage_billing_subscription),
60 )
61 .route(
62 "/billing/subscriptions/migrate",
63 post(migrate_to_new_billing),
64 )
65 .route(
66 "/billing/subscriptions/sync",
67 post(sync_billing_subscription),
68 )
69 .route("/billing/usage", get(get_current_usage))
70}
71
72#[derive(Debug, Deserialize)]
73struct GetBillingPreferencesParams {
74 github_user_id: i32,
75}
76
77#[derive(Debug, Serialize)]
78struct BillingPreferencesResponse {
79 trial_started_at: Option<String>,
80 max_monthly_llm_usage_spending_in_cents: i32,
81 model_request_overages_enabled: bool,
82 model_request_overages_spend_limit_in_cents: i32,
83}
84
85async fn get_billing_preferences(
86 Extension(app): Extension<Arc<AppState>>,
87 Query(params): Query<GetBillingPreferencesParams>,
88) -> Result<Json<BillingPreferencesResponse>> {
89 let user = app
90 .db
91 .get_user_by_github_user_id(params.github_user_id)
92 .await?
93 .context("user not found")?;
94
95 let billing_customer = app.db.get_billing_customer_by_user_id(user.id).await?;
96 let preferences = app.db.get_billing_preferences(user.id).await?;
97
98 Ok(Json(BillingPreferencesResponse {
99 trial_started_at: billing_customer
100 .and_then(|billing_customer| billing_customer.trial_started_at)
101 .map(|trial_started_at| {
102 trial_started_at
103 .and_utc()
104 .to_rfc3339_opts(SecondsFormat::Millis, true)
105 }),
106 max_monthly_llm_usage_spending_in_cents: preferences
107 .as_ref()
108 .map_or(DEFAULT_MAX_MONTHLY_SPEND.0 as i32, |preferences| {
109 preferences.max_monthly_llm_usage_spending_in_cents
110 }),
111 model_request_overages_enabled: preferences.as_ref().map_or(false, |preferences| {
112 preferences.model_request_overages_enabled
113 }),
114 model_request_overages_spend_limit_in_cents: preferences
115 .as_ref()
116 .map_or(0, |preferences| {
117 preferences.model_request_overages_spend_limit_in_cents
118 }),
119 }))
120}
121
122#[derive(Debug, Deserialize)]
123struct UpdateBillingPreferencesBody {
124 github_user_id: i32,
125 #[serde(default)]
126 max_monthly_llm_usage_spending_in_cents: i32,
127 #[serde(default)]
128 model_request_overages_enabled: bool,
129 #[serde(default)]
130 model_request_overages_spend_limit_in_cents: i32,
131}
132
133async fn update_billing_preferences(
134 Extension(app): Extension<Arc<AppState>>,
135 Extension(rpc_server): Extension<Arc<crate::rpc::Server>>,
136 extract::Json(body): extract::Json<UpdateBillingPreferencesBody>,
137) -> Result<Json<BillingPreferencesResponse>> {
138 let user = app
139 .db
140 .get_user_by_github_user_id(body.github_user_id)
141 .await?
142 .context("user not found")?;
143
144 let billing_customer = app.db.get_billing_customer_by_user_id(user.id).await?;
145
146 let max_monthly_llm_usage_spending_in_cents =
147 body.max_monthly_llm_usage_spending_in_cents.max(0);
148 let model_request_overages_spend_limit_in_cents =
149 body.model_request_overages_spend_limit_in_cents.max(0);
150
151 let billing_preferences =
152 if let Some(_billing_preferences) = app.db.get_billing_preferences(user.id).await? {
153 app.db
154 .update_billing_preferences(
155 user.id,
156 &UpdateBillingPreferencesParams {
157 max_monthly_llm_usage_spending_in_cents: ActiveValue::set(
158 max_monthly_llm_usage_spending_in_cents,
159 ),
160 model_request_overages_enabled: ActiveValue::set(
161 body.model_request_overages_enabled,
162 ),
163 model_request_overages_spend_limit_in_cents: ActiveValue::set(
164 model_request_overages_spend_limit_in_cents,
165 ),
166 },
167 )
168 .await?
169 } else {
170 app.db
171 .create_billing_preferences(
172 user.id,
173 &crate::db::CreateBillingPreferencesParams {
174 max_monthly_llm_usage_spending_in_cents,
175 model_request_overages_enabled: body.model_request_overages_enabled,
176 model_request_overages_spend_limit_in_cents,
177 },
178 )
179 .await?
180 };
181
182 SnowflakeRow::new(
183 "Billing Preferences Updated",
184 Some(user.metrics_id),
185 user.admin,
186 None,
187 json!({
188 "user_id": user.id,
189 "model_request_overages_enabled": billing_preferences.model_request_overages_enabled,
190 "model_request_overages_spend_limit_in_cents": billing_preferences.model_request_overages_spend_limit_in_cents,
191 "max_monthly_llm_usage_spending_in_cents": billing_preferences.max_monthly_llm_usage_spending_in_cents,
192 }),
193 )
194 .write(&app.kinesis_client, &app.config.kinesis_stream)
195 .await
196 .log_err();
197
198 rpc_server.refresh_llm_tokens_for_user(user.id).await;
199
200 Ok(Json(BillingPreferencesResponse {
201 trial_started_at: billing_customer
202 .and_then(|billing_customer| billing_customer.trial_started_at)
203 .map(|trial_started_at| {
204 trial_started_at
205 .and_utc()
206 .to_rfc3339_opts(SecondsFormat::Millis, true)
207 }),
208 max_monthly_llm_usage_spending_in_cents: billing_preferences
209 .max_monthly_llm_usage_spending_in_cents,
210 model_request_overages_enabled: billing_preferences.model_request_overages_enabled,
211 model_request_overages_spend_limit_in_cents: billing_preferences
212 .model_request_overages_spend_limit_in_cents,
213 }))
214}
215
216#[derive(Debug, Deserialize)]
217struct ListBillingSubscriptionsParams {
218 github_user_id: i32,
219}
220
221#[derive(Debug, Serialize)]
222struct BillingSubscriptionJson {
223 id: BillingSubscriptionId,
224 name: String,
225 status: StripeSubscriptionStatus,
226 trial_end_at: Option<String>,
227 cancel_at: Option<String>,
228 /// Whether this subscription can be canceled.
229 is_cancelable: bool,
230}
231
232#[derive(Debug, Serialize)]
233struct ListBillingSubscriptionsResponse {
234 subscriptions: Vec<BillingSubscriptionJson>,
235}
236
237async fn list_billing_subscriptions(
238 Extension(app): Extension<Arc<AppState>>,
239 Query(params): Query<ListBillingSubscriptionsParams>,
240) -> Result<Json<ListBillingSubscriptionsResponse>> {
241 let user = app
242 .db
243 .get_user_by_github_user_id(params.github_user_id)
244 .await?
245 .context("user not found")?;
246
247 let subscriptions = app.db.get_billing_subscriptions(user.id).await?;
248
249 Ok(Json(ListBillingSubscriptionsResponse {
250 subscriptions: subscriptions
251 .into_iter()
252 .map(|subscription| BillingSubscriptionJson {
253 id: subscription.id,
254 name: match subscription.kind {
255 Some(SubscriptionKind::ZedPro) => "Zed Pro".to_string(),
256 Some(SubscriptionKind::ZedProTrial) => "Zed Pro (Trial)".to_string(),
257 Some(SubscriptionKind::ZedFree) => "Zed Free".to_string(),
258 None => "Zed LLM Usage".to_string(),
259 },
260 status: subscription.stripe_subscription_status,
261 trial_end_at: if subscription.kind == Some(SubscriptionKind::ZedProTrial) {
262 maybe!({
263 let end_at = subscription.stripe_current_period_end?;
264 let end_at = DateTime::from_timestamp(end_at, 0)?;
265
266 Some(end_at.to_rfc3339_opts(SecondsFormat::Millis, true))
267 })
268 } else {
269 None
270 },
271 cancel_at: subscription.stripe_cancel_at.map(|cancel_at| {
272 cancel_at
273 .and_utc()
274 .to_rfc3339_opts(SecondsFormat::Millis, true)
275 }),
276 is_cancelable: subscription.kind != Some(SubscriptionKind::ZedFree)
277 && subscription.stripe_subscription_status.is_cancelable()
278 && subscription.stripe_cancel_at.is_none(),
279 })
280 .collect(),
281 }))
282}
283
284#[derive(Debug, PartialEq, Clone, Copy, Deserialize)]
285#[serde(rename_all = "snake_case")]
286enum ProductCode {
287 ZedPro,
288 ZedProTrial,
289}
290
291#[derive(Debug, Deserialize)]
292struct CreateBillingSubscriptionBody {
293 github_user_id: i32,
294 product: ProductCode,
295}
296
297#[derive(Debug, Serialize)]
298struct CreateBillingSubscriptionResponse {
299 checkout_session_url: String,
300}
301
302/// Initiates a Stripe Checkout session for creating a billing subscription.
303async fn create_billing_subscription(
304 Extension(app): Extension<Arc<AppState>>,
305 extract::Json(body): extract::Json<CreateBillingSubscriptionBody>,
306) -> Result<Json<CreateBillingSubscriptionResponse>> {
307 let user = app
308 .db
309 .get_user_by_github_user_id(body.github_user_id)
310 .await?
311 .context("user not found")?;
312
313 let Some(stripe_billing) = app.stripe_billing.clone() else {
314 log::error!("failed to retrieve Stripe billing object");
315 Err(Error::http(
316 StatusCode::NOT_IMPLEMENTED,
317 "not supported".into(),
318 ))?
319 };
320
321 if let Some(existing_subscription) = app.db.get_active_billing_subscription(user.id).await? {
322 let is_checkout_allowed = body.product == ProductCode::ZedProTrial
323 && existing_subscription.kind == Some(SubscriptionKind::ZedFree);
324
325 if !is_checkout_allowed {
326 return Err(Error::http(
327 StatusCode::CONFLICT,
328 "user already has an active subscription".into(),
329 ));
330 }
331 }
332
333 let existing_billing_customer = app.db.get_billing_customer_by_user_id(user.id).await?;
334 if let Some(existing_billing_customer) = &existing_billing_customer {
335 if existing_billing_customer.has_overdue_invoices {
336 return Err(Error::http(
337 StatusCode::PAYMENT_REQUIRED,
338 "user has overdue invoices".into(),
339 ));
340 }
341 }
342
343 let customer_id = if let Some(existing_customer) = &existing_billing_customer {
344 StripeCustomerId(existing_customer.stripe_customer_id.clone().into())
345 } else {
346 stripe_billing
347 .find_or_create_customer_by_email(user.email_address.as_deref())
348 .await?
349 };
350
351 let success_url = format!(
352 "{}/account?checkout_complete=1",
353 app.config.zed_dot_dev_url()
354 );
355
356 let checkout_session_url = match body.product {
357 ProductCode::ZedPro => {
358 stripe_billing
359 .checkout_with_zed_pro(&customer_id, &user.github_login, &success_url)
360 .await?
361 }
362 ProductCode::ZedProTrial => {
363 if let Some(existing_billing_customer) = &existing_billing_customer {
364 if existing_billing_customer.trial_started_at.is_some() {
365 return Err(Error::http(
366 StatusCode::FORBIDDEN,
367 "user already used free trial".into(),
368 ));
369 }
370 }
371
372 let feature_flags = app.db.get_user_flags(user.id).await?;
373
374 stripe_billing
375 .checkout_with_zed_pro_trial(
376 &customer_id,
377 &user.github_login,
378 feature_flags,
379 &success_url,
380 )
381 .await?
382 }
383 };
384
385 Ok(Json(CreateBillingSubscriptionResponse {
386 checkout_session_url,
387 }))
388}
389
390#[derive(Debug, PartialEq, Deserialize)]
391#[serde(rename_all = "snake_case")]
392enum ManageSubscriptionIntent {
393 /// The user intends to manage their subscription.
394 ///
395 /// This will open the Stripe billing portal without putting the user in a specific flow.
396 ManageSubscription,
397 /// The user intends to update their payment method.
398 UpdatePaymentMethod,
399 /// The user intends to upgrade to Zed Pro.
400 UpgradeToPro,
401 /// The user intends to cancel their subscription.
402 Cancel,
403 /// The user intends to stop the cancellation of their subscription.
404 StopCancellation,
405}
406
407#[derive(Debug, Deserialize)]
408struct ManageBillingSubscriptionBody {
409 github_user_id: i32,
410 intent: ManageSubscriptionIntent,
411 /// The ID of the subscription to manage.
412 subscription_id: BillingSubscriptionId,
413 redirect_to: Option<String>,
414}
415
416#[derive(Debug, Serialize)]
417struct ManageBillingSubscriptionResponse {
418 billing_portal_session_url: Option<String>,
419}
420
421/// Initiates a Stripe customer portal session for managing a billing subscription.
422async fn manage_billing_subscription(
423 Extension(app): Extension<Arc<AppState>>,
424 extract::Json(body): extract::Json<ManageBillingSubscriptionBody>,
425) -> Result<Json<ManageBillingSubscriptionResponse>> {
426 let user = app
427 .db
428 .get_user_by_github_user_id(body.github_user_id)
429 .await?
430 .context("user not found")?;
431
432 let Some(stripe_client) = app.real_stripe_client.clone() else {
433 log::error!("failed to retrieve Stripe client");
434 Err(Error::http(
435 StatusCode::NOT_IMPLEMENTED,
436 "not supported".into(),
437 ))?
438 };
439
440 let Some(stripe_billing) = app.stripe_billing.clone() else {
441 log::error!("failed to retrieve Stripe billing object");
442 Err(Error::http(
443 StatusCode::NOT_IMPLEMENTED,
444 "not supported".into(),
445 ))?
446 };
447
448 let customer = app
449 .db
450 .get_billing_customer_by_user_id(user.id)
451 .await?
452 .context("billing customer not found")?;
453 let customer_id = CustomerId::from_str(&customer.stripe_customer_id)
454 .context("failed to parse customer ID")?;
455
456 let subscription = app
457 .db
458 .get_billing_subscription_by_id(body.subscription_id)
459 .await?
460 .context("subscription not found")?;
461 let subscription_id = SubscriptionId::from_str(&subscription.stripe_subscription_id)
462 .context("failed to parse subscription ID")?;
463
464 if body.intent == ManageSubscriptionIntent::StopCancellation {
465 let updated_stripe_subscription = Subscription::update(
466 &stripe_client,
467 &subscription_id,
468 stripe::UpdateSubscription {
469 cancel_at_period_end: Some(false),
470 ..Default::default()
471 },
472 )
473 .await?;
474
475 app.db
476 .update_billing_subscription(
477 subscription.id,
478 &UpdateBillingSubscriptionParams {
479 stripe_cancel_at: ActiveValue::set(
480 updated_stripe_subscription
481 .cancel_at
482 .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
483 .map(|time| time.naive_utc()),
484 ),
485 ..Default::default()
486 },
487 )
488 .await?;
489
490 return Ok(Json(ManageBillingSubscriptionResponse {
491 billing_portal_session_url: None,
492 }));
493 }
494
495 let flow = match body.intent {
496 ManageSubscriptionIntent::ManageSubscription => None,
497 ManageSubscriptionIntent::UpgradeToPro => {
498 let zed_pro_price_id: stripe::PriceId =
499 stripe_billing.zed_pro_price_id().await?.try_into()?;
500 let zed_free_price_id: stripe::PriceId =
501 stripe_billing.zed_free_price_id().await?.try_into()?;
502
503 let stripe_subscription =
504 Subscription::retrieve(&stripe_client, &subscription_id, &[]).await?;
505
506 let is_on_zed_pro_trial = stripe_subscription.status == SubscriptionStatus::Trialing
507 && stripe_subscription.items.data.iter().any(|item| {
508 item.price
509 .as_ref()
510 .map_or(false, |price| price.id == zed_pro_price_id)
511 });
512 if is_on_zed_pro_trial {
513 let payment_methods = PaymentMethod::list(
514 &stripe_client,
515 &stripe::ListPaymentMethods {
516 customer: Some(stripe_subscription.customer.id()),
517 ..Default::default()
518 },
519 )
520 .await?;
521
522 let has_payment_method = !payment_methods.data.is_empty();
523 if !has_payment_method {
524 return Err(Error::http(
525 StatusCode::BAD_REQUEST,
526 "missing payment method".into(),
527 ));
528 }
529
530 // If the user is already on a Zed Pro trial and wants to upgrade to Pro, we just need to end their trial early.
531 Subscription::update(
532 &stripe_client,
533 &stripe_subscription.id,
534 stripe::UpdateSubscription {
535 trial_end: Some(stripe::Scheduled::now()),
536 ..Default::default()
537 },
538 )
539 .await?;
540
541 return Ok(Json(ManageBillingSubscriptionResponse {
542 billing_portal_session_url: None,
543 }));
544 }
545
546 let subscription_item_to_update = stripe_subscription
547 .items
548 .data
549 .iter()
550 .find_map(|item| {
551 let price = item.price.as_ref()?;
552
553 if price.id == zed_free_price_id {
554 Some(item.id.clone())
555 } else {
556 None
557 }
558 })
559 .context("No subscription item to update")?;
560
561 Some(CreateBillingPortalSessionFlowData {
562 type_: CreateBillingPortalSessionFlowDataType::SubscriptionUpdateConfirm,
563 subscription_update_confirm: Some(
564 CreateBillingPortalSessionFlowDataSubscriptionUpdateConfirm {
565 subscription: subscription.stripe_subscription_id,
566 items: vec![
567 CreateBillingPortalSessionFlowDataSubscriptionUpdateConfirmItems {
568 id: subscription_item_to_update.to_string(),
569 price: Some(zed_pro_price_id.to_string()),
570 quantity: Some(1),
571 },
572 ],
573 discounts: None,
574 },
575 ),
576 ..Default::default()
577 })
578 }
579 ManageSubscriptionIntent::UpdatePaymentMethod => Some(CreateBillingPortalSessionFlowData {
580 type_: CreateBillingPortalSessionFlowDataType::PaymentMethodUpdate,
581 after_completion: Some(CreateBillingPortalSessionFlowDataAfterCompletion {
582 type_: stripe::CreateBillingPortalSessionFlowDataAfterCompletionType::Redirect,
583 redirect: Some(CreateBillingPortalSessionFlowDataAfterCompletionRedirect {
584 return_url: format!(
585 "{}{path}",
586 app.config.zed_dot_dev_url(),
587 path = body.redirect_to.unwrap_or_else(|| "/account".to_string())
588 ),
589 }),
590 ..Default::default()
591 }),
592 ..Default::default()
593 }),
594 ManageSubscriptionIntent::Cancel => {
595 if subscription.kind == Some(SubscriptionKind::ZedFree) {
596 return Err(Error::http(
597 StatusCode::BAD_REQUEST,
598 "free subscription cannot be canceled".into(),
599 ));
600 }
601
602 Some(CreateBillingPortalSessionFlowData {
603 type_: CreateBillingPortalSessionFlowDataType::SubscriptionCancel,
604 after_completion: Some(CreateBillingPortalSessionFlowDataAfterCompletion {
605 type_: stripe::CreateBillingPortalSessionFlowDataAfterCompletionType::Redirect,
606 redirect: Some(CreateBillingPortalSessionFlowDataAfterCompletionRedirect {
607 return_url: format!("{}/account", app.config.zed_dot_dev_url()),
608 }),
609 ..Default::default()
610 }),
611 subscription_cancel: Some(
612 stripe::CreateBillingPortalSessionFlowDataSubscriptionCancel {
613 subscription: subscription.stripe_subscription_id,
614 retention: None,
615 },
616 ),
617 ..Default::default()
618 })
619 }
620 ManageSubscriptionIntent::StopCancellation => unreachable!(),
621 };
622
623 let mut params = CreateBillingPortalSession::new(customer_id);
624 params.flow_data = flow;
625 let return_url = format!("{}/account", app.config.zed_dot_dev_url());
626 params.return_url = Some(&return_url);
627
628 let session = BillingPortalSession::create(&stripe_client, params).await?;
629
630 Ok(Json(ManageBillingSubscriptionResponse {
631 billing_portal_session_url: Some(session.url),
632 }))
633}
634
635#[derive(Debug, Deserialize)]
636struct MigrateToNewBillingBody {
637 github_user_id: i32,
638}
639
640#[derive(Debug, Serialize)]
641struct MigrateToNewBillingResponse {
642 /// The ID of the subscription that was canceled.
643 canceled_subscription_id: Option<String>,
644}
645
646async fn migrate_to_new_billing(
647 Extension(app): Extension<Arc<AppState>>,
648 extract::Json(body): extract::Json<MigrateToNewBillingBody>,
649) -> Result<Json<MigrateToNewBillingResponse>> {
650 let Some(stripe_client) = app.real_stripe_client.clone() else {
651 log::error!("failed to retrieve Stripe client");
652 Err(Error::http(
653 StatusCode::NOT_IMPLEMENTED,
654 "not supported".into(),
655 ))?
656 };
657
658 let user = app
659 .db
660 .get_user_by_github_user_id(body.github_user_id)
661 .await?
662 .context("user not found")?;
663
664 let old_billing_subscriptions_by_user = app
665 .db
666 .get_active_billing_subscriptions(HashSet::from_iter([user.id]))
667 .await?;
668
669 let canceled_subscription_id = if let Some((_billing_customer, billing_subscription)) =
670 old_billing_subscriptions_by_user.get(&user.id)
671 {
672 let stripe_subscription_id = billing_subscription
673 .stripe_subscription_id
674 .parse::<stripe::SubscriptionId>()
675 .context("failed to parse Stripe subscription ID from database")?;
676
677 Subscription::cancel(
678 &stripe_client,
679 &stripe_subscription_id,
680 stripe::CancelSubscription {
681 invoice_now: Some(true),
682 ..Default::default()
683 },
684 )
685 .await?;
686
687 Some(stripe_subscription_id)
688 } else {
689 None
690 };
691
692 let all_feature_flags = app.db.list_feature_flags().await?;
693 let user_feature_flags = app.db.get_user_flags(user.id).await?;
694
695 for feature_flag in ["new-billing", "assistant2"] {
696 let already_in_feature_flag = user_feature_flags.iter().any(|flag| flag == feature_flag);
697 if already_in_feature_flag {
698 continue;
699 }
700
701 let feature_flag = all_feature_flags
702 .iter()
703 .find(|flag| flag.flag == feature_flag)
704 .context("failed to find feature flag: {feature_flag:?}")?;
705
706 app.db.add_user_flag(user.id, feature_flag.id).await?;
707 }
708
709 Ok(Json(MigrateToNewBillingResponse {
710 canceled_subscription_id: canceled_subscription_id
711 .map(|subscription_id| subscription_id.to_string()),
712 }))
713}
714
715#[derive(Debug, Deserialize)]
716struct SyncBillingSubscriptionBody {
717 github_user_id: i32,
718}
719
720#[derive(Debug, Serialize)]
721struct SyncBillingSubscriptionResponse {
722 stripe_customer_id: String,
723}
724
725async fn sync_billing_subscription(
726 Extension(app): Extension<Arc<AppState>>,
727 extract::Json(body): extract::Json<SyncBillingSubscriptionBody>,
728) -> Result<Json<SyncBillingSubscriptionResponse>> {
729 let Some(stripe_client) = app.stripe_client.clone() else {
730 log::error!("failed to retrieve Stripe client");
731 Err(Error::http(
732 StatusCode::NOT_IMPLEMENTED,
733 "not supported".into(),
734 ))?
735 };
736
737 let user = app
738 .db
739 .get_user_by_github_user_id(body.github_user_id)
740 .await?
741 .context("user not found")?;
742
743 let billing_customer = app
744 .db
745 .get_billing_customer_by_user_id(user.id)
746 .await?
747 .context("billing customer not found")?;
748 let stripe_customer_id = StripeCustomerId(billing_customer.stripe_customer_id.clone().into());
749
750 let subscriptions = stripe_client
751 .list_subscriptions_for_customer(&stripe_customer_id)
752 .await?;
753
754 for subscription in subscriptions {
755 let subscription_id = subscription.id.clone();
756
757 sync_subscription(&app, &stripe_client, subscription)
758 .await
759 .with_context(|| {
760 format!(
761 "failed to sync subscription {subscription_id} for user {}",
762 user.id,
763 )
764 })?;
765 }
766
767 Ok(Json(SyncBillingSubscriptionResponse {
768 stripe_customer_id: billing_customer.stripe_customer_id.clone(),
769 }))
770}
771
772/// The amount of time we wait in between each poll of Stripe events.
773///
774/// This value should strike a balance between:
775/// 1. Being short enough that we update quickly when something in Stripe changes
776/// 2. Being long enough that we don't eat into our rate limits.
777///
778/// As a point of reference, the Sequin folks say they have this at **500ms**:
779///
780/// > We poll the Stripe /events endpoint every 500ms per account
781/// >
782/// > — https://blog.sequinstream.com/events-not-webhooks/
783const POLL_EVENTS_INTERVAL: Duration = Duration::from_secs(5);
784
785/// The maximum number of events to return per page.
786///
787/// We set this to 100 (the max) so we have to make fewer requests to Stripe.
788///
789/// > Limit can range between 1 and 100, and the default is 10.
790const EVENTS_LIMIT_PER_PAGE: u64 = 100;
791
792/// The number of pages consisting entirely of already-processed events that we
793/// will see before we stop retrieving events.
794///
795/// This is used to prevent over-fetching the Stripe events API for events we've
796/// already seen and processed.
797const NUMBER_OF_ALREADY_PROCESSED_PAGES_BEFORE_WE_STOP: usize = 4;
798
799/// Polls the Stripe events API periodically to reconcile the records in our
800/// database with the data in Stripe.
801pub fn poll_stripe_events_periodically(app: Arc<AppState>, rpc_server: Arc<Server>) {
802 let Some(real_stripe_client) = app.real_stripe_client.clone() else {
803 log::warn!("failed to retrieve Stripe client");
804 return;
805 };
806 let Some(stripe_client) = app.stripe_client.clone() else {
807 log::warn!("failed to retrieve Stripe client");
808 return;
809 };
810
811 let executor = app.executor.clone();
812 executor.spawn_detached({
813 let executor = executor.clone();
814 async move {
815 loop {
816 poll_stripe_events(&app, &rpc_server, &stripe_client, &real_stripe_client)
817 .await
818 .log_err();
819
820 executor.sleep(POLL_EVENTS_INTERVAL).await;
821 }
822 }
823 });
824}
825
826async fn poll_stripe_events(
827 app: &Arc<AppState>,
828 rpc_server: &Arc<Server>,
829 stripe_client: &Arc<dyn StripeClient>,
830 real_stripe_client: &stripe::Client,
831) -> anyhow::Result<()> {
832 fn event_type_to_string(event_type: EventType) -> String {
833 // Calling `to_string` on `stripe::EventType` members gives us a quoted string,
834 // so we need to unquote it.
835 event_type.to_string().trim_matches('"').to_string()
836 }
837
838 let event_types = [
839 EventType::CustomerCreated,
840 EventType::CustomerUpdated,
841 EventType::CustomerSubscriptionCreated,
842 EventType::CustomerSubscriptionUpdated,
843 EventType::CustomerSubscriptionPaused,
844 EventType::CustomerSubscriptionResumed,
845 EventType::CustomerSubscriptionDeleted,
846 ]
847 .into_iter()
848 .map(event_type_to_string)
849 .collect::<Vec<_>>();
850
851 let mut pages_of_already_processed_events = 0;
852 let mut unprocessed_events = Vec::new();
853
854 log::info!(
855 "Stripe events: starting retrieval for {}",
856 event_types.join(", ")
857 );
858 let mut params = ListEvents::new();
859 params.types = Some(event_types.clone());
860 params.limit = Some(EVENTS_LIMIT_PER_PAGE);
861
862 let mut event_pages = stripe::Event::list(&real_stripe_client, ¶ms)
863 .await?
864 .paginate(params);
865
866 loop {
867 let processed_event_ids = {
868 let event_ids = event_pages
869 .page
870 .data
871 .iter()
872 .map(|event| event.id.as_str())
873 .collect::<Vec<_>>();
874 app.db
875 .get_processed_stripe_events_by_event_ids(&event_ids)
876 .await?
877 .into_iter()
878 .map(|event| event.stripe_event_id)
879 .collect::<Vec<_>>()
880 };
881
882 let mut processed_events_in_page = 0;
883 let events_in_page = event_pages.page.data.len();
884 for event in &event_pages.page.data {
885 if processed_event_ids.contains(&event.id.to_string()) {
886 processed_events_in_page += 1;
887 log::debug!("Stripe events: already processed '{}', skipping", event.id);
888 } else {
889 unprocessed_events.push(event.clone());
890 }
891 }
892
893 if processed_events_in_page == events_in_page {
894 pages_of_already_processed_events += 1;
895 }
896
897 if event_pages.page.has_more {
898 if pages_of_already_processed_events >= NUMBER_OF_ALREADY_PROCESSED_PAGES_BEFORE_WE_STOP
899 {
900 log::info!(
901 "Stripe events: stopping, saw {pages_of_already_processed_events} pages of already-processed events"
902 );
903 break;
904 } else {
905 log::info!("Stripe events: retrieving next page");
906 event_pages = event_pages.next(&real_stripe_client).await?;
907 }
908 } else {
909 break;
910 }
911 }
912
913 log::info!("Stripe events: unprocessed {}", unprocessed_events.len());
914
915 // Sort all of the unprocessed events in ascending order, so we can handle them in the order they occurred.
916 unprocessed_events.sort_by(|a, b| a.created.cmp(&b.created).then_with(|| a.id.cmp(&b.id)));
917
918 for event in unprocessed_events {
919 let event_id = event.id.clone();
920 let processed_event_params = CreateProcessedStripeEventParams {
921 stripe_event_id: event.id.to_string(),
922 stripe_event_type: event_type_to_string(event.type_),
923 stripe_event_created_timestamp: event.created,
924 };
925
926 // If the event has happened too far in the past, we don't want to
927 // process it and risk overwriting other more-recent updates.
928 //
929 // 1 day was chosen arbitrarily. This could be made longer or shorter.
930 let one_day = Duration::from_secs(24 * 60 * 60);
931 let a_day_ago = Utc::now() - one_day;
932 if a_day_ago.timestamp() > event.created {
933 log::info!(
934 "Stripe events: event '{}' is more than {one_day:?} old, marking as processed",
935 event_id
936 );
937 app.db
938 .create_processed_stripe_event(&processed_event_params)
939 .await?;
940
941 continue;
942 }
943
944 let process_result = match event.type_ {
945 EventType::CustomerCreated | EventType::CustomerUpdated => {
946 handle_customer_event(app, real_stripe_client, event).await
947 }
948 EventType::CustomerSubscriptionCreated
949 | EventType::CustomerSubscriptionUpdated
950 | EventType::CustomerSubscriptionPaused
951 | EventType::CustomerSubscriptionResumed
952 | EventType::CustomerSubscriptionDeleted => {
953 handle_customer_subscription_event(app, rpc_server, stripe_client, event).await
954 }
955 _ => Ok(()),
956 };
957
958 if let Some(()) = process_result
959 .with_context(|| format!("failed to process event {event_id} successfully"))
960 .log_err()
961 {
962 app.db
963 .create_processed_stripe_event(&processed_event_params)
964 .await?;
965 }
966 }
967
968 Ok(())
969}
970
971async fn handle_customer_event(
972 app: &Arc<AppState>,
973 _stripe_client: &stripe::Client,
974 event: stripe::Event,
975) -> anyhow::Result<()> {
976 let EventObject::Customer(customer) = event.data.object else {
977 bail!("unexpected event payload for {}", event.id);
978 };
979
980 log::info!("handling Stripe {} event: {}", event.type_, event.id);
981
982 let Some(email) = customer.email else {
983 log::info!("Stripe customer has no email: skipping");
984 return Ok(());
985 };
986
987 let Some(user) = app.db.get_user_by_email(&email).await? else {
988 log::info!("no user found for email: skipping");
989 return Ok(());
990 };
991
992 if let Some(existing_customer) = app
993 .db
994 .get_billing_customer_by_stripe_customer_id(&customer.id)
995 .await?
996 {
997 app.db
998 .update_billing_customer(
999 existing_customer.id,
1000 &UpdateBillingCustomerParams {
1001 // For now we just leave the information as-is, as it is not
1002 // likely to change.
1003 ..Default::default()
1004 },
1005 )
1006 .await?;
1007 } else {
1008 app.db
1009 .create_billing_customer(&CreateBillingCustomerParams {
1010 user_id: user.id,
1011 stripe_customer_id: customer.id.to_string(),
1012 })
1013 .await?;
1014 }
1015
1016 Ok(())
1017}
1018
1019async fn sync_subscription(
1020 app: &Arc<AppState>,
1021 stripe_client: &Arc<dyn StripeClient>,
1022 subscription: StripeSubscription,
1023) -> anyhow::Result<billing_customer::Model> {
1024 let subscription_kind = if let Some(stripe_billing) = &app.stripe_billing {
1025 stripe_billing
1026 .determine_subscription_kind(&subscription)
1027 .await
1028 } else {
1029 None
1030 };
1031
1032 let billing_customer =
1033 find_or_create_billing_customer(app, stripe_client.as_ref(), &subscription.customer)
1034 .await?
1035 .context("billing customer not found")?;
1036
1037 if let Some(SubscriptionKind::ZedProTrial) = subscription_kind {
1038 if subscription.status == SubscriptionStatus::Trialing {
1039 let current_period_start =
1040 DateTime::from_timestamp(subscription.current_period_start, 0)
1041 .context("No trial subscription period start")?;
1042
1043 app.db
1044 .update_billing_customer(
1045 billing_customer.id,
1046 &UpdateBillingCustomerParams {
1047 trial_started_at: ActiveValue::set(Some(current_period_start.naive_utc())),
1048 ..Default::default()
1049 },
1050 )
1051 .await?;
1052 }
1053 }
1054
1055 let was_canceled_due_to_payment_failure = subscription.status == SubscriptionStatus::Canceled
1056 && subscription
1057 .cancellation_details
1058 .as_ref()
1059 .and_then(|details| details.reason)
1060 .map_or(false, |reason| {
1061 reason == StripeCancellationDetailsReason::PaymentFailed
1062 });
1063
1064 if was_canceled_due_to_payment_failure {
1065 app.db
1066 .update_billing_customer(
1067 billing_customer.id,
1068 &UpdateBillingCustomerParams {
1069 has_overdue_invoices: ActiveValue::set(true),
1070 ..Default::default()
1071 },
1072 )
1073 .await?;
1074 }
1075
1076 if let Some(existing_subscription) = app
1077 .db
1078 .get_billing_subscription_by_stripe_subscription_id(subscription.id.0.as_ref())
1079 .await?
1080 {
1081 app.db
1082 .update_billing_subscription(
1083 existing_subscription.id,
1084 &UpdateBillingSubscriptionParams {
1085 billing_customer_id: ActiveValue::set(billing_customer.id),
1086 kind: ActiveValue::set(subscription_kind),
1087 stripe_subscription_id: ActiveValue::set(subscription.id.to_string()),
1088 stripe_subscription_status: ActiveValue::set(subscription.status.into()),
1089 stripe_cancel_at: ActiveValue::set(
1090 subscription
1091 .cancel_at
1092 .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
1093 .map(|time| time.naive_utc()),
1094 ),
1095 stripe_cancellation_reason: ActiveValue::set(
1096 subscription
1097 .cancellation_details
1098 .and_then(|details| details.reason)
1099 .map(|reason| reason.into()),
1100 ),
1101 stripe_current_period_start: ActiveValue::set(Some(
1102 subscription.current_period_start,
1103 )),
1104 stripe_current_period_end: ActiveValue::set(Some(
1105 subscription.current_period_end,
1106 )),
1107 },
1108 )
1109 .await?;
1110 } else {
1111 if let Some(existing_subscription) = app
1112 .db
1113 .get_active_billing_subscription(billing_customer.user_id)
1114 .await?
1115 {
1116 if existing_subscription.kind == Some(SubscriptionKind::ZedFree)
1117 && subscription_kind == Some(SubscriptionKind::ZedProTrial)
1118 {
1119 let stripe_subscription_id = StripeSubscriptionId(
1120 existing_subscription.stripe_subscription_id.clone().into(),
1121 );
1122
1123 stripe_client
1124 .cancel_subscription(&stripe_subscription_id)
1125 .await?;
1126 } else {
1127 // If the user already has an active billing subscription, ignore the
1128 // event and return an `Ok` to signal that it was processed
1129 // successfully.
1130 //
1131 // There is the possibility that this could cause us to not create a
1132 // subscription in the following scenario:
1133 //
1134 // 1. User has an active subscription A
1135 // 2. User cancels subscription A
1136 // 3. User creates a new subscription B
1137 // 4. We process the new subscription B before the cancellation of subscription A
1138 // 5. User ends up with no subscriptions
1139 //
1140 // In theory this situation shouldn't arise as we try to process the events in the order they occur.
1141
1142 log::info!(
1143 "user {user_id} already has an active subscription, skipping creation of subscription {subscription_id}",
1144 user_id = billing_customer.user_id,
1145 subscription_id = subscription.id
1146 );
1147 return Ok(billing_customer);
1148 }
1149 }
1150
1151 app.db
1152 .create_billing_subscription(&CreateBillingSubscriptionParams {
1153 billing_customer_id: billing_customer.id,
1154 kind: subscription_kind,
1155 stripe_subscription_id: subscription.id.to_string(),
1156 stripe_subscription_status: subscription.status.into(),
1157 stripe_cancellation_reason: subscription
1158 .cancellation_details
1159 .and_then(|details| details.reason)
1160 .map(|reason| reason.into()),
1161 stripe_current_period_start: Some(subscription.current_period_start),
1162 stripe_current_period_end: Some(subscription.current_period_end),
1163 })
1164 .await?;
1165 }
1166
1167 if let Some(stripe_billing) = app.stripe_billing.as_ref() {
1168 if subscription.status == SubscriptionStatus::Canceled
1169 || subscription.status == SubscriptionStatus::Paused
1170 {
1171 let already_has_active_billing_subscription = app
1172 .db
1173 .has_active_billing_subscription(billing_customer.user_id)
1174 .await?;
1175 if !already_has_active_billing_subscription {
1176 let stripe_customer_id =
1177 StripeCustomerId(billing_customer.stripe_customer_id.clone().into());
1178
1179 stripe_billing
1180 .subscribe_to_zed_free(stripe_customer_id)
1181 .await?;
1182 }
1183 }
1184 }
1185
1186 Ok(billing_customer)
1187}
1188
1189async fn handle_customer_subscription_event(
1190 app: &Arc<AppState>,
1191 rpc_server: &Arc<Server>,
1192 stripe_client: &Arc<dyn StripeClient>,
1193 event: stripe::Event,
1194) -> anyhow::Result<()> {
1195 let EventObject::Subscription(subscription) = event.data.object else {
1196 bail!("unexpected event payload for {}", event.id);
1197 };
1198
1199 log::info!("handling Stripe {} event: {}", event.type_, event.id);
1200
1201 let billing_customer = sync_subscription(app, stripe_client, subscription.into()).await?;
1202
1203 // When the user's subscription changes, push down any changes to their plan.
1204 rpc_server
1205 .update_plan_for_user(billing_customer.user_id)
1206 .await
1207 .trace_err();
1208
1209 // When the user's subscription changes, we want to refresh their LLM tokens
1210 // to either grant/revoke access.
1211 rpc_server
1212 .refresh_llm_tokens_for_user(billing_customer.user_id)
1213 .await;
1214
1215 Ok(())
1216}
1217
1218#[derive(Debug, Deserialize)]
1219struct GetCurrentUsageParams {
1220 github_user_id: i32,
1221}
1222
1223#[derive(Debug, Serialize)]
1224struct UsageCounts {
1225 pub used: i32,
1226 pub limit: Option<i32>,
1227 pub remaining: Option<i32>,
1228}
1229
1230#[derive(Debug, Serialize)]
1231struct ModelRequestUsage {
1232 pub model: String,
1233 pub mode: CompletionMode,
1234 pub requests: i32,
1235}
1236
1237#[derive(Debug, Serialize)]
1238struct CurrentUsage {
1239 pub model_requests: UsageCounts,
1240 pub model_request_usage: Vec<ModelRequestUsage>,
1241 pub edit_predictions: UsageCounts,
1242}
1243
1244#[derive(Debug, Default, Serialize)]
1245struct GetCurrentUsageResponse {
1246 pub plan: String,
1247 pub current_usage: Option<CurrentUsage>,
1248}
1249
1250async fn get_current_usage(
1251 Extension(app): Extension<Arc<AppState>>,
1252 Query(params): Query<GetCurrentUsageParams>,
1253) -> Result<Json<GetCurrentUsageResponse>> {
1254 let user = app
1255 .db
1256 .get_user_by_github_user_id(params.github_user_id)
1257 .await?
1258 .context("user not found")?;
1259
1260 let feature_flags = app.db.get_user_flags(user.id).await?;
1261 let has_extended_trial = feature_flags
1262 .iter()
1263 .any(|flag| flag == AGENT_EXTENDED_TRIAL_FEATURE_FLAG);
1264
1265 let Some(llm_db) = app.llm_db.clone() else {
1266 return Err(Error::http(
1267 StatusCode::NOT_IMPLEMENTED,
1268 "LLM database not available".into(),
1269 ));
1270 };
1271
1272 let Some(subscription) = app.db.get_active_billing_subscription(user.id).await? else {
1273 return Ok(Json(GetCurrentUsageResponse::default()));
1274 };
1275
1276 let subscription_period = maybe!({
1277 let period_start_at = subscription.current_period_start_at()?;
1278 let period_end_at = subscription.current_period_end_at()?;
1279
1280 Some((period_start_at, period_end_at))
1281 });
1282
1283 let Some((period_start_at, period_end_at)) = subscription_period else {
1284 return Ok(Json(GetCurrentUsageResponse::default()));
1285 };
1286
1287 let usage = llm_db
1288 .get_subscription_usage_for_period(user.id, period_start_at, period_end_at)
1289 .await?;
1290
1291 let plan = subscription
1292 .kind
1293 .map(Into::into)
1294 .unwrap_or(zed_llm_client::Plan::ZedFree);
1295
1296 let model_requests_limit = match plan.model_requests_limit() {
1297 zed_llm_client::UsageLimit::Limited(limit) => {
1298 let limit = if plan == zed_llm_client::Plan::ZedProTrial && has_extended_trial {
1299 1_000
1300 } else {
1301 limit
1302 };
1303
1304 Some(limit)
1305 }
1306 zed_llm_client::UsageLimit::Unlimited => None,
1307 };
1308
1309 let edit_predictions_limit = match plan.edit_predictions_limit() {
1310 zed_llm_client::UsageLimit::Limited(limit) => Some(limit),
1311 zed_llm_client::UsageLimit::Unlimited => None,
1312 };
1313
1314 let Some(usage) = usage else {
1315 return Ok(Json(GetCurrentUsageResponse {
1316 plan: plan.as_str().to_string(),
1317 current_usage: Some(CurrentUsage {
1318 model_requests: UsageCounts {
1319 used: 0,
1320 limit: model_requests_limit,
1321 remaining: model_requests_limit,
1322 },
1323 model_request_usage: Vec::new(),
1324 edit_predictions: UsageCounts {
1325 used: 0,
1326 limit: edit_predictions_limit,
1327 remaining: edit_predictions_limit,
1328 },
1329 }),
1330 }));
1331 };
1332
1333 let subscription_usage_meters = llm_db
1334 .get_current_subscription_usage_meters_for_user(user.id, Utc::now())
1335 .await?;
1336
1337 let model_request_usage = subscription_usage_meters
1338 .into_iter()
1339 .filter_map(|(usage_meter, _usage)| {
1340 let model = llm_db.model_by_id(usage_meter.model_id).ok()?;
1341
1342 Some(ModelRequestUsage {
1343 model: model.name.clone(),
1344 mode: usage_meter.mode,
1345 requests: usage_meter.requests,
1346 })
1347 })
1348 .collect::<Vec<_>>();
1349
1350 Ok(Json(GetCurrentUsageResponse {
1351 plan: plan.as_str().to_string(),
1352 current_usage: Some(CurrentUsage {
1353 model_requests: UsageCounts {
1354 used: usage.model_requests,
1355 limit: model_requests_limit,
1356 remaining: model_requests_limit.map(|limit| (limit - usage.model_requests).max(0)),
1357 },
1358 model_request_usage,
1359 edit_predictions: UsageCounts {
1360 used: usage.edit_predictions,
1361 limit: edit_predictions_limit,
1362 remaining: edit_predictions_limit
1363 .map(|limit| (limit - usage.edit_predictions).max(0)),
1364 },
1365 }),
1366 }))
1367}
1368
1369impl From<SubscriptionStatus> for StripeSubscriptionStatus {
1370 fn from(value: SubscriptionStatus) -> Self {
1371 match value {
1372 SubscriptionStatus::Incomplete => Self::Incomplete,
1373 SubscriptionStatus::IncompleteExpired => Self::IncompleteExpired,
1374 SubscriptionStatus::Trialing => Self::Trialing,
1375 SubscriptionStatus::Active => Self::Active,
1376 SubscriptionStatus::PastDue => Self::PastDue,
1377 SubscriptionStatus::Canceled => Self::Canceled,
1378 SubscriptionStatus::Unpaid => Self::Unpaid,
1379 SubscriptionStatus::Paused => Self::Paused,
1380 }
1381 }
1382}
1383
1384impl From<CancellationDetailsReason> for StripeCancellationReason {
1385 fn from(value: CancellationDetailsReason) -> Self {
1386 match value {
1387 CancellationDetailsReason::CancellationRequested => Self::CancellationRequested,
1388 CancellationDetailsReason::PaymentDisputed => Self::PaymentDisputed,
1389 CancellationDetailsReason::PaymentFailed => Self::PaymentFailed,
1390 }
1391 }
1392}
1393
1394/// Finds or creates a billing customer using the provided customer.
1395pub async fn find_or_create_billing_customer(
1396 app: &Arc<AppState>,
1397 stripe_client: &dyn StripeClient,
1398 customer_id: &StripeCustomerId,
1399) -> anyhow::Result<Option<billing_customer::Model>> {
1400 // If we already have a billing customer record associated with the Stripe customer,
1401 // there's nothing more we need to do.
1402 if let Some(billing_customer) = app
1403 .db
1404 .get_billing_customer_by_stripe_customer_id(customer_id.0.as_ref())
1405 .await?
1406 {
1407 return Ok(Some(billing_customer));
1408 }
1409
1410 let customer = stripe_client.get_customer(customer_id).await?;
1411
1412 let Some(email) = customer.email else {
1413 return Ok(None);
1414 };
1415
1416 let Some(user) = app.db.get_user_by_email(&email).await? else {
1417 return Ok(None);
1418 };
1419
1420 let billing_customer = app
1421 .db
1422 .create_billing_customer(&CreateBillingCustomerParams {
1423 user_id: user.id,
1424 stripe_customer_id: customer.id.to_string(),
1425 })
1426 .await?;
1427
1428 Ok(Some(billing_customer))
1429}
1430
1431const SYNC_LLM_REQUEST_USAGE_WITH_STRIPE_INTERVAL: Duration = Duration::from_secs(60);
1432
1433pub fn sync_llm_request_usage_with_stripe_periodically(app: Arc<AppState>) {
1434 let Some(stripe_billing) = app.stripe_billing.clone() else {
1435 log::warn!("failed to retrieve Stripe billing object");
1436 return;
1437 };
1438 let Some(llm_db) = app.llm_db.clone() else {
1439 log::warn!("failed to retrieve LLM database");
1440 return;
1441 };
1442
1443 let executor = app.executor.clone();
1444 executor.spawn_detached({
1445 let executor = executor.clone();
1446 async move {
1447 loop {
1448 sync_model_request_usage_with_stripe(&app, &llm_db, &stripe_billing)
1449 .await
1450 .context("failed to sync LLM request usage to Stripe")
1451 .trace_err();
1452 executor
1453 .sleep(SYNC_LLM_REQUEST_USAGE_WITH_STRIPE_INTERVAL)
1454 .await;
1455 }
1456 }
1457 });
1458}
1459
1460async fn sync_model_request_usage_with_stripe(
1461 app: &Arc<AppState>,
1462 llm_db: &Arc<LlmDatabase>,
1463 stripe_billing: &Arc<StripeBilling>,
1464) -> anyhow::Result<()> {
1465 let staff_users = app.db.get_staff_users().await?;
1466 let staff_user_ids = staff_users
1467 .iter()
1468 .map(|user| user.id)
1469 .collect::<HashSet<UserId>>();
1470
1471 let usage_meters = llm_db
1472 .get_current_subscription_usage_meters(Utc::now())
1473 .await?;
1474 let usage_meters = usage_meters
1475 .into_iter()
1476 .filter(|(_, usage)| !staff_user_ids.contains(&usage.user_id))
1477 .collect::<Vec<_>>();
1478 let user_ids = usage_meters
1479 .iter()
1480 .map(|(_, usage)| usage.user_id)
1481 .collect::<HashSet<UserId>>();
1482 let billing_subscriptions = app
1483 .db
1484 .get_active_zed_pro_billing_subscriptions(user_ids)
1485 .await?;
1486
1487 let claude_sonnet_4 = stripe_billing
1488 .find_price_by_lookup_key("claude-sonnet-4-requests")
1489 .await?;
1490 let claude_sonnet_4_max = stripe_billing
1491 .find_price_by_lookup_key("claude-sonnet-4-requests-max")
1492 .await?;
1493 let claude_opus_4 = stripe_billing
1494 .find_price_by_lookup_key("claude-opus-4-requests")
1495 .await?;
1496 let claude_opus_4_max = stripe_billing
1497 .find_price_by_lookup_key("claude-opus-4-requests-max")
1498 .await?;
1499 let claude_3_5_sonnet = stripe_billing
1500 .find_price_by_lookup_key("claude-3-5-sonnet-requests")
1501 .await?;
1502 let claude_3_7_sonnet = stripe_billing
1503 .find_price_by_lookup_key("claude-3-7-sonnet-requests")
1504 .await?;
1505 let claude_3_7_sonnet_max = stripe_billing
1506 .find_price_by_lookup_key("claude-3-7-sonnet-requests-max")
1507 .await?;
1508
1509 for (usage_meter, usage) in usage_meters {
1510 maybe!(async {
1511 let Some((billing_customer, billing_subscription)) =
1512 billing_subscriptions.get(&usage.user_id)
1513 else {
1514 bail!(
1515 "Attempted to sync usage meter for user who is not a Stripe customer: {}",
1516 usage.user_id
1517 );
1518 };
1519
1520 let stripe_customer_id =
1521 StripeCustomerId(billing_customer.stripe_customer_id.clone().into());
1522 let stripe_subscription_id =
1523 StripeSubscriptionId(billing_subscription.stripe_subscription_id.clone().into());
1524
1525 let model = llm_db.model_by_id(usage_meter.model_id)?;
1526
1527 let (price, meter_event_name) = match model.name.as_str() {
1528 "claude-opus-4" => match usage_meter.mode {
1529 CompletionMode::Normal => (&claude_opus_4, "claude_opus_4/requests"),
1530 CompletionMode::Max => (&claude_opus_4_max, "claude_opus_4/requests/max"),
1531 },
1532 "claude-sonnet-4" => match usage_meter.mode {
1533 CompletionMode::Normal => (&claude_sonnet_4, "claude_sonnet_4/requests"),
1534 CompletionMode::Max => (&claude_sonnet_4_max, "claude_sonnet_4/requests/max"),
1535 },
1536 "claude-3-5-sonnet" => (&claude_3_5_sonnet, "claude_3_5_sonnet/requests"),
1537 "claude-3-7-sonnet" => match usage_meter.mode {
1538 CompletionMode::Normal => (&claude_3_7_sonnet, "claude_3_7_sonnet/requests"),
1539 CompletionMode::Max => {
1540 (&claude_3_7_sonnet_max, "claude_3_7_sonnet/requests/max")
1541 }
1542 },
1543 model_name => {
1544 bail!("Attempted to sync usage meter for unsupported model: {model_name:?}")
1545 }
1546 };
1547
1548 stripe_billing
1549 .subscribe_to_price(&stripe_subscription_id, price)
1550 .await?;
1551 stripe_billing
1552 .bill_model_request_usage(
1553 &stripe_customer_id,
1554 meter_event_name,
1555 usage_meter.requests,
1556 )
1557 .await?;
1558
1559 Ok(())
1560 })
1561 .await
1562 .log_err();
1563 }
1564
1565 Ok(())
1566}