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