Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): usage billing should acrue for users stripe subscription billing period (#7498)
Will Hutchinson41f9fd481e44
diff --git a/Cargo.lock b/Cargo.lockindex f6d4d8594f..81132cfc40 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1983,11 +1983,13 @@ name = "authentication_service_client"version = "0.1.0"dependencies = ["anyhow",+ "chrono","model","reqwest 0.13.4","serde","thiserror 2.0.18","tracing",+ "uuid","workspace-hack",]diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rsindex 8b214a38a3..8b7ad91cdc 100644--- a/crates/ai_billing/src/domain/ledger/test.rs+++ b/crates/ai_billing/src/domain/ledger/test.rs@@ -441,6 +441,79 @@ fn billing_period_falls_back_to_the_calendar_month() {);}+#[test]+fn billing_period_covering_needs_an_anchor_that_contains_now() {+ let start = Utc.with_ymd_and_hms(2026, 4, 10, 0, 0, 0).unwrap();+ let end = Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap();+ let inside = Utc.with_ymd_and_hms(2026, 4, 18, 12, 0, 0).unwrap();++ assert_eq!(+ BillingPeriod::covering(Some((start, end)), inside),+ Some(BillingPeriod { start, end })+ );+ assert_eq!(+ BillingPeriod::covering(Some((start, end)), start),+ Some(BillingPeriod { start, end }),+ "the start is inclusive"+ );+ assert_eq!(BillingPeriod::covering(None, inside), None, "missing");+ assert_eq!(+ BillingPeriod::covering(Some((start, end)), end),+ None,+ "ended: the end is exclusive"+ );+ assert_eq!(+ BillingPeriod::covering(+ Some((start, end)),+ Utc.with_ymd_and_hms(2026, 4, 1, 0, 0, 0).unwrap()+ ),+ None,+ "future"+ );+ assert_eq!(+ BillingPeriod::covering(Some((end, start)), inside),+ None,+ "inverted"+ );+}++#[test]+fn billing_period_adopted_starts_at_the_stored_end_and_contains_now() {+ let subscription = BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 2, 3, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 3, 3, 0, 0, 0).unwrap(),+ };+ let now = Utc.with_ymd_and_hms(2026, 2, 20, 12, 0, 0).unwrap();++ assert_eq!(+ subscription.adopted(None, now),+ Some(BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 2, 3, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 3, 3, 0, 0, 0).unwrap(),+ }),+ "no anchor"+ );+ assert_eq!(+ subscription.adopted(+ Some((+ Utc.with_ymd_and_hms(2026, 1, 15, 0, 0, 0).unwrap(),+ Utc.with_ymd_and_hms(2026, 2, 15, 0, 0, 0).unwrap(),+ )),+ now+ ),+ Some(BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 2, 15, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 3, 3, 0, 0, 0).unwrap(),+ }),+ "overlapping anchor"+ );+ assert_eq!(+ subscription.adopted(None, Utc.with_ymd_and_hms(2026, 3, 10, 0, 0, 0).unwrap()),+ None,+ "ended before now"+ );+}+#[test]fn plan_tier_from_roles_prefers_max() {use roles_and_permissions::domain::model::RoleId;diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rsindex 2b5c9a5e80..0614000a8f 100644--- a/crates/ai_billing/src/domain/models.rs+++ b/crates/ai_billing/src/domain/models.rs@@ -178,6 +178,33 @@ impl BillingPeriod {Self::calendar_month(now)}+ /// The stored anchor when it contains `now`.+ pub fn covering(+ anchor: Option<(DateTime<Utc>, DateTime<Utc>)>,+ now: DateTime<Utc>,+ ) -> Option<Self> {+ let (start, end) = anchor?;+ (start <= now && now < end).then_some(Self { start, end })+ }++ /// The part of this subscription window to store and meter after the+ /// stored anchor.+ ///+ /// The start moves up to the anchor's end because the store refuses a start+ /// that overlaps the stored window. `None` when that part does not contain+ /// `now`, because it is then not a period to meter.+ pub fn adopted(+ self,+ anchor: Option<(DateTime<Utc>, DateTime<Utc>)>,+ now: DateTime<Utc>,+ ) -> Option<Self> {+ let start = match anchor {+ Some((_, stored_end)) => self.start.max(stored_end),+ None => self.start,+ };+ Self::covering(Some((start, self.end)), now)+ }+/// The period immediately before this one, assuming the same length in/// whole months (one month for calendar periods).pub fn previous(&self) -> Self {@@ -382,6 +409,11 @@ impl Entitlement {pub fn is_payer(&self, user: &MacroUserIdStr<'_>) -> bool {self.payer.as_ref() == user.as_ref()}++ /// Paid and finite: usage is metered against a subscription period.+ pub fn is_metered(&self) -> bool {+ self.tier.is_paid() && !self.unlimited+ }}/// The payer's overage settings, Stripe period anchor, and open-seat generation.@@ -393,7 +425,7 @@ pub struct BillingSettings {pub overage_limit_cents: i64,/// Set when an overage charge failed to collect.pub overage_suspended_at: Option<DateTime<Utc>>,- /// The subscription period last synced from Stripe.+ /// The subscription period last observed from Stripe (webhook or read-through).pub period_anchor: Option<(DateTime<Utc>, DateTime<Utc>)>,/// Generation of the payer's open-seat roster. Zero when no account row exists.pub seat_generation: SeatGeneration,diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rsindex 05bce8bf67..95dd378708 100644--- a/crates/ai_billing/src/domain/ports.rs+++ b/crates/ai_billing/src/domain/ports.rs@@ -337,6 +337,17 @@ pub trait PaymentGateway: Send + Sync + 'static {invoice_id: &str,scope: SubscriptionScope,) -> impl Future<Output = Result<bool>> + Send;++ /// The current period of the customer's subscription in `scope`. Active or+ /// trialing subscriptions win over past-due or unpaid ones. `Ok(None)` when+ /// no non-canceled subscription exists or the gateway cannot read+ /// subscriptions. Chosen subscriptions that disagree on the period are a+ /// [`BillingError::Payment`](super::BillingError::Payment).+ fn subscription_period(+ &self,+ customer_id: &str,+ scope: SubscriptionScope,+ ) -> impl Future<Output = Result<Option<BillingPeriod>>> + Send;}/// Asks whoever owns Stripe to settle a payer. Fire-and-forget: services thatdiff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex 63ce667200..a1d4923b99 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -9,7 +9,7 @@ use super::models::{AiUsageBilling, AllowanceDecision, AllowanceStore, BillingError, BillingPeriod,BillingSettings, CREDIT_PACKS_CENTS, Entitlement, OVERAGE_CHARGE_THRESHOLD_CENTS,OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS, OverageChargeStatus, PayerScope,- PeriodAllowance, PlanTier, Result, SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,+ PeriodAllowance, Result, SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,};use super::period::{PeriodSync, SubscriptionPeriod};use super::ports::{@@ -21,9 +21,17 @@ use ai_usage::AiUsageEnforcement;use chrono::{DateTime, Utc};use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use macro_uuid::Uuid;-use std::sync::Arc;+use std::collections::HashMap;+use std::sync::{Arc, Mutex, PoisonError};use teams::domain::open_seat_release::OpenSeatRelease;+/// How long a payer whose subscription period read came back empty, failed,+/// or did not contain `now` meters the fallback period before the next read.+/// A miss stores nothing, so without this every AI request from that payer+/// would read the provider again. One minute bounds that to one read per+/// payer per process while Stripe rolls a period or a provider recovers.+const PERIOD_MISS_BACKOFF: chrono::Duration = chrono::Duration::minutes(1);+/// The billing service over its four ports.#[derive(Clone)]pub struct BillingServiceImpl<E, U, R, P> {@@ -35,6 +43,10 @@ pub struct BillingServiceImpl<E, U, R, P> {enforcement: AiUsageEnforcement,billing: AiUsageBilling,period_sync: Option<Arc<dyn PeriodSync>>,+ /// Payers whose last subscription period read missed, and until when the+ /// read is not repeated. Shared by clones so every holder of this service+ /// in a process backs off together.+ period_misses: Arc<Mutex<HashMap<String, DateTime<Utc>>>>,}impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {@@ -51,6 +63,7 @@ impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {enforcement: AiUsageEnforcement::Disabled,billing: AiUsageBilling::Disabled,period_sync: None,+ period_misses: Arc::default(),}}@@ -130,8 +143,8 @@ whereasync fn position(&self, user: &MacroUserIdStr<'_>, now: DateTime<Utc>) -> Result<Position> {let first = self.entitlements.entitlement(user).await?;let settings = self.repo.settings(&first.payer).await?;- let period = BillingPeriod::current(settings.period_anchor, now);- if !first.tier.is_paid() || first.unlimited {+ let period = self.usage_period(&first, settings.period_anchor, now).await;+ if !first.is_metered() {return Ok(Position {entitlement: first,settings,@@ -168,14 +181,16 @@ whereif entitlement.payer.as_ref() != first.payer.as_ref() {// `settings.seat_generation` was read for `first.payer`.let settings = self.repo.settings(&entitlement.payer).await?;- let period = BillingPeriod::current(settings.period_anchor, now);+ let period = self+ .usage_period(&entitlement, settings.period_anchor, now)+ .await;return Ok(Position {entitlement,settings,period,});}- if !entitlement.tier.is_paid() || entitlement.unlimited {+ if !entitlement.is_metered() {return Ok(Position {entitlement,settings,@@ -202,6 +217,120 @@ where}}+ async fn usage_period(+ &self,+ entitlement: &Entitlement,+ anchor: Option<(DateTime<Utc>, DateTime<Utc>)>,+ now: DateTime<Utc>,+ ) -> BillingPeriod {+ if let Some(period) = BillingPeriod::covering(anchor, now) {+ return period;+ }+ if !entitlement.is_metered() {+ return BillingPeriod::current(anchor, now);+ }+ let payer = &entitlement.payer;+ if self.period_read_missed_recently(payer, now) {+ tracing::debug!(+ "subscription period read missed recently; metering the fallback period"+ );+ return BillingPeriod::current(anchor, now);+ }+ let read = match self.entitlements.stripe_customer_id(payer).await {+ Ok(Some(customer_id)) => {+ self.payments+ .subscription_period(&customer_id, SubscriptionScope::from(&entitlement.scope))+ .await+ }+ Ok(None) => Ok(None),+ Err(e) => Err(e),+ };+ match read {+ Ok(Some(period)) => {+ let Some(adopted) = period.adopted(anchor, now) else {+ tracing::warn!(+ period_start = %period.start,+ period_end = %period.end,+ "subscription period past the stored anchor does not contain now; metering the fallback period"+ );+ self.note_period_miss(payer, now);+ return BillingPeriod::current(anchor, now);+ };+ let _ = self+ .repo+ .set_period(payer, adopted.start, adopted.end)+ .await+ .inspect_err(+ |e| tracing::warn!(error = ?e, "storing the subscription period failed"),+ );+ adopted+ }+ Ok(None) => {+ tracing::debug!("no subscription period to read; metering the fallback period");+ self.note_period_miss(payer, now);+ BillingPeriod::current(anchor, now)+ }+ Err(e) => {+ tracing::warn!(+ error = ?e,+ "reading the subscription period failed; metering the fallback period"+ );+ self.note_period_miss(payer, now);+ BillingPeriod::current(anchor, now)+ }+ }+ }++ fn period_read_missed_recently(&self, payer: &MacroUserIdStr<'_>, now: DateTime<Utc>) -> bool {+ self.period_misses+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .get(payer.as_ref())+ .is_some_and(|until| now < *until)+ }++ fn note_period_miss(&self, payer: &MacroUserIdStr<'_>, now: DateTime<Utc>) {+ let mut misses = self+ .period_misses+ .lock()+ .unwrap_or_else(PoisonError::into_inner);+ misses.retain(|_, until| now < *until);+ misses.insert(payer.as_ref().to_string(), now + PERIOD_MISS_BACKOFF);+ }++ async fn release_at(+ &self,+ team_id: Uuid,+ member: &MacroUserIdStr<'_>,+ now: DateTime<Utc>,+ ) -> Result<()> {+ let Some(payer) = self.entitlements.team_payer(team_id).await? else {+ return Ok(());+ };+ if payer.as_ref() == member.as_ref() {+ return Ok(());+ }+ let settings = self.repo.settings(&payer).await?;+ let anchor = settings.period_anchor;+ let period = match BillingPeriod::covering(anchor, now) {+ Some(period) => period,+ None => match self.entitlements.entitlement(&payer).await {+ Ok(entitlement) => self.usage_period(&entitlement, anchor, now).await,+ Err(e) => {+ tracing::warn!(+ error = ?e,+ "reading the payer entitlement failed; releasing in the fallback period"+ );+ BillingPeriod::current(anchor, now)+ }+ },+ };+ let Some(open) = period.open_start(now) else {+ return Ok(());+ };+ self.repo.release_open_seat(&payer, open, member).await+ }+async fn snapshot_at(&self,user: &MacroUserIdStr<'_>,@@ -474,18 +603,7 @@ where#[tracing::instrument(skip(self), err)]async fn release(&self, team_id: Uuid, member: &MacroUserIdStr<'_>) -> Result<()> {- let Some(payer) = self.entitlements.team_payer(team_id).await? else {- return Ok(());- };- if payer.as_ref() == member.as_ref() {- return Ok(());- }- let settings = self.repo.settings(&payer).await?;- let now = Utc::now();- let Some(open) = BillingPeriod::current(settings.period_anchor, now).open_start(now) else {- return Ok(());- };- self.repo.release_open_seat(&payer, open, member).await+ self.release_at(team_id, member, Utc::now()).await}}@@ -502,7 +620,7 @@ wherereturn Ok(AllowanceDecision::Allow);}let position = self.position(user, Utc::now()).await?;- if position.entitlement.unlimited || position.entitlement.tier == PlanTier::Free {+ if !position.entitlement.is_metered() {return Ok(AllowanceDecision::Allow);}let snapshot = self.snapshot_at(user, &position).await?;@@ -528,7 +646,7 @@ where}let now = Utc::now();let position = self.position(user, now).await?;- if position.entitlement.unlimited || !position.entitlement.tier.is_paid() {+ if !position.entitlement.is_metered() {return Ok(());}// The previous period first, so a tail that ran past the boundary isdiff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex 4024f31977..2e979543a1 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -5,6 +5,7 @@ use crate::domain::models::{PlanTier, SeatGeneration,};use crate::domain::ports::SettlementOutcome;+use chrono::TimeZone;use macro_user_id::cowlike::CowLike;use macro_uuid::Uuid;use std::collections::HashMap;@@ -20,6 +21,7 @@ struct FakeEntitlements {by_user: Arc<Mutex<HashMap<String, Entitlement>>>,customers: Arc<Mutex<HashMap<String, String>>>,payers: Arc<Mutex<HashMap<Uuid, MacroUserIdStr<'static>>>>,+ fail_entitlement: Arc<Mutex<bool>>,}impl FakeEntitlements {@@ -60,6 +62,11 @@ impl FakeEntitlements {impl EntitlementSource for FakeEntitlements {async fn entitlement(&self, user: &MacroUserIdStr<'_>) -> Result<Entitlement> {+ if *self.fail_entitlement.lock().unwrap() {+ return Err(BillingError::Entitlement(anyhow::anyhow!(+ "roles unavailable"+ )));+ }Ok(self.by_user.lock()@@ -157,6 +164,7 @@ struct RepoState {allowances: HashMap<DateTime<Utc>, PeriodAllowance>,releases: Vec<(String, DateTime<Utc>, String)>,activated_seats: Vec<String>,+ period_writes: Vec<(String, DateTime<Utc>, DateTime<Utc>)>,}impl RepoState {@@ -204,6 +212,9 @@ impl FakeRepo {fn releases(&self) -> Vec<(String, DateTime<Utc>, String)> {self.state.lock().unwrap().releases.clone()}+ fn period_writes(&self) -> Vec<(String, DateTime<Utc>, DateTime<Utc>)> {+ self.state.lock().unwrap().period_writes.clone()+ }}impl BillingRepo for FakeRepo {@@ -243,11 +254,25 @@ impl BillingRepo for FakeRepo {}async fn set_period(&self,- _payer: &MacroUserIdStr<'_>,+ payer: &MacroUserIdStr<'_>,start: DateTime<Utc>,end: DateTime<Utc>,) -> Result<()> {- self.state.lock().unwrap().settings.period_anchor = Some((start, end));+ let mut state = self.state.lock().unwrap();+ // Same guard as `PgBillingRepo::set_period`, which returns `Ok` when it refuses a write.+ let applies = match state.settings.period_anchor {+ None => true,+ Some((stored_start, stored_end)) => {+ (start > stored_start && start >= stored_end)+ || (start == stored_start && end > start)+ }+ };+ if applies {+ state.settings.period_anchor = Some((start, end));+ }+ state+ .period_writes+ .push((payer.as_ref().to_string(), start, end));Ok(())}async fn suspend_overage(&self, _payer: &MacroUserIdStr<'_>) -> Result<()> {@@ -453,6 +478,14 @@ enum PayOutcome {Error,}+#[derive(Debug, Clone, Copy, Default)]+enum PeriodReply {+ #[default]+ Missing,+ Found(BillingPeriod),+ Failed,+}+#[derive(Clone, Default)]struct FakePayments {fail_open: Arc<Mutex<bool>>,@@ -460,12 +493,20 @@ struct FakePayments {checkouts: Arc<Mutex<Vec<CreditCheckoutRequest>>>,opened: Arc<Mutex<Vec<OverageChargeRequest>>>,payments: Arc<Mutex<Vec<(Uuid, String)>>>,+ period_reply: Arc<Mutex<PeriodReply>>,+ period_requests: Arc<Mutex<Vec<(String, SubscriptionScope)>>>,}impl FakePayments {fn set_pay(&self, outcome: PayOutcome) {*self.pay_outcome.lock().unwrap() = outcome;}+ fn set_period(&self, reply: PeriodReply) {+ *self.period_reply.lock().unwrap() = reply;+ }+ fn period_requests(&self) -> Vec<(String, SubscriptionScope)> {+ self.period_requests.lock().unwrap().clone()+ }fn opened(&self) -> Vec<OverageChargeRequest> {self.opened.lock().unwrap().clone()}@@ -503,6 +544,23 @@ impl PaymentGateway for FakePayments {PayOutcome::Error => Err(BillingError::Payment(anyhow::anyhow!("card declined"))),}}+ async fn subscription_period(+ &self,+ customer_id: &str,+ scope: SubscriptionScope,+ ) -> Result<Option<BillingPeriod>> {+ self.period_requests+ .lock()+ .unwrap()+ .push((customer_id.to_string(), scope));+ match *self.period_reply.lock().unwrap() {+ PeriodReply::Missing => Ok(None),+ PeriodReply::Found(period) => Ok(Some(period)),+ PeriodReply::Failed => {+ Err(BillingError::Payment(anyhow::anyhow!("stripe unavailable")))+ }+ }+ }}#[derive(Default)]@@ -621,6 +679,48 @@ async fn recorded_new_policy_never_enters_legacy_analytics_settlement() {assert_eq!(repo.state.lock().unwrap().balance, 10_000);}+#[tokio::test]+async fn unlimited_payers_are_never_charged_overage_or_gated() {+ let payer = user("[email protected]");+ let entitlements = FakeEntitlements::default()+ .with(Entitlement {+ unlimited: true,+ ..Entitlement::personal(payer.clone(), PlanTier::Premium)+ })+ .with_customer(&payer, "cus_unlimited");+ let usage = FakeUsage {+ cents: Arc::new(Mutex::new(50_000)),+ entries: Default::default(),+ };+ let repo = FakeRepo::default();+ let payments = FakePayments::default();+ {+ let mut state = repo.state.lock().unwrap();+ state.balance = 10_000;+ state.settings.overage_enabled = true;+ state.settings.overage_limit_cents = 10_000;+ }+ let svc = BillingServiceImpl::new(+ entitlements,+ usage,+ repo.clone(),+ payments.clone(),+ AiPricing::testing(),+ )+ .with_enforcement(AiUsageEnforcement::Enabled)+ .with_billing(AiUsageBilling::Enabled);++ assert_eq!(+ svc.check_allowance(&payer).await.unwrap(),+ AllowanceDecision::Allow+ );+ svc.settle(&payer).await.unwrap();+ assert!(repo.state.lock().unwrap().consumed.is_empty());+ assert!(repo.charges().is_empty());+ assert!(payments.opened().is_empty());+ assert_eq!(repo.state.lock().unwrap().balance, 10_000);+}+#[tokio::test]async fn policy_activation_during_analytics_read_cannot_double_bill() {struct ActivatingUsage(FakeRepo);@@ -1814,3 +1914,576 @@ impl EntitlementSource for ReleaseOnSecondRead {Ok(None)}}++fn d(year: i32, month: u32, day: u32) -> DateTime<Utc> {+ Utc.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap()+}++fn apr_18_noon() -> DateTime<Utc> {+ d(2026, 4, 18) + chrono::Duration::hours(12)+}++fn premium_team(+ owner: &MacroUserIdStr<'static>,+ member: &MacroUserIdStr<'static>,+ team_id: Uuid,+) -> Entitlement {+ Entitlement {+ tier: PlanTier::Premium,+ seat_tiers: vec![PlanTier::Premium, PlanTier::Premium],+ unlimited: false,+ payer: owner.clone(),+ billed_users: vec![owner.clone(), member.clone()],+ scope: PayerScope::TeamOwner { team_id },+ }+}++#[tokio::test]+async fn missing_anchor_reads_the_subscription_period_once_and_stores_it() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }));++ let position = svc.position(&payer, apr_18_noon()).await.unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }+ );+ assert_eq!(+ repo.settings(&payer).await.unwrap().period_anchor,+ Some((d(2026, 4, 10), d(2026, 5, 10)))+ );+ assert_eq!(+ payments.period_requests(),+ vec![("cus_123".to_string(), SubscriptionScope::Personal)]+ );++ let position = svc.position(&payer, apr_18_noon()).await.unwrap();+ assert_eq!(position.period.start, d(2026, 4, 10));+ assert_eq!(+ payments.period_requests(),+ vec![("cus_123".to_string(), SubscriptionScope::Personal)],+ "the stored anchor answers the second read"+ );+}++#[tokio::test]+async fn ended_anchor_is_refreshed_from_the_subscription_before_rolling_forward() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ repo.set_period(&payer, d(2026, 1, 15), d(2026, 2, 15))+ .await+ .unwrap();+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }));++ let position = svc.position(&payer, apr_18_noon()).await.unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ },+ "the subscription window, not the anchor rolled to Apr 15"+ );+ assert_eq!(+ repo.settings(&payer).await.unwrap().period_anchor,+ Some((d(2026, 4, 10), d(2026, 5, 10)))+ );+}++#[tokio::test]+async fn overlapping_subscription_window_starts_at_the_stored_end() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ repo.set_period(&payer, d(2026, 1, 15), d(2026, 2, 15))+ .await+ .unwrap();+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 2, 3),+ end: d(2026, 3, 3),+ }));++ let position = svc+ .position(&payer, d(2026, 2, 20) + chrono::Duration::hours(12))+ .await+ .unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 2, 15),+ end: d(2026, 3, 3),+ }+ );+ assert_eq!(+ repo.period_writes(),+ vec![+ (+ "macro|[email protected]".to_string(),+ d(2026, 1, 15),+ d(2026, 2, 15)+ ),+ (+ "macro|[email protected]".to_string(),+ d(2026, 2, 15),+ d(2026, 3, 3)+ ),+ ]+ );+ assert_eq!(+ repo.settings(&payer).await.unwrap().period_anchor,+ Some((d(2026, 2, 15), d(2026, 3, 3)))+ );++ svc.position(&payer, d(2026, 2, 21)).await.unwrap();+ assert_eq!(+ payments.period_requests(),+ vec![("cus_123".to_string(), SubscriptionScope::Personal)],+ "the stored window answers the second read"+ );+}++#[tokio::test]+async fn unrolled_subscription_window_rolls_the_anchor_and_stores_nothing() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ repo.set_period(&payer, d(2026, 3, 18), d(2026, 4, 18))+ .await+ .unwrap();+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 3, 18),+ end: d(2026, 4, 18),+ }));++ let position = svc+ .position(&payer, d(2026, 4, 18) + chrono::Duration::minutes(30))+ .await+ .unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 18),+ end: d(2026, 5, 18),+ }+ );+ assert_eq!(+ repo.period_writes(),+ vec![(+ "macro|[email protected]".to_string(),+ d(2026, 3, 18),+ d(2026, 4, 18)+ )],+ "only the seeded anchor was written"+ );+ assert_eq!(+ repo.settings(&payer).await.unwrap().period_anchor,+ Some((d(2026, 3, 18), d(2026, 4, 18)))+ );+}++#[tokio::test]+async fn subscription_window_after_now_keeps_the_calendar_month_and_stores_nothing() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 4, 19),+ end: d(2026, 5, 19),+ }));++ let position = svc.position(&payer, apr_18_noon()).await.unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 1),+ end: d(2026, 5, 1),+ }+ );+ assert!(repo.period_writes().is_empty());+}++#[tokio::test]+async fn provider_failure_keeps_the_calendar_month_and_stores_nothing() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_period(PeriodReply::Failed);++ let position = svc.position(&payer, apr_18_noon()).await.unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 1),+ end: d(2026, 5, 1),+ }+ );+ assert_eq!(repo.settings(&payer).await.unwrap().period_anchor, None);+}++#[tokio::test]+async fn provider_failure_rolls_an_ended_anchor_forward() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ repo.set_period(&payer, d(2026, 1, 15), d(2026, 2, 15))+ .await+ .unwrap();+ payments.set_period(PeriodReply::Failed);++ let position = svc.position(&payer, apr_18_noon()).await.unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 15),+ end: d(2026, 5, 15),+ }+ );+ assert_eq!(+ repo.settings(&payer).await.unwrap().period_anchor,+ Some((d(2026, 1, 15), d(2026, 2, 15)))+ );+}++#[tokio::test]+async fn a_failed_read_is_not_repeated_for_a_minute() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_period(PeriodReply::Failed);+ let first = apr_18_noon();++ svc.position(&payer, first).await.unwrap();+ let within = svc+ .position(&payer, first + chrono::Duration::seconds(59))+ .await+ .unwrap();+ assert_eq!(+ within.period,+ BillingPeriod {+ start: d(2026, 4, 1),+ end: d(2026, 5, 1),+ }+ );+ assert_eq!(payments.period_requests().len(), 1);++ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }));+ let after = svc+ .position(&payer, first + chrono::Duration::seconds(60))+ .await+ .unwrap();+ assert_eq!(+ after.period,+ BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }+ );+ assert_eq!(payments.period_requests().len(), 2);+ assert_eq!(+ repo.settings(&payer).await.unwrap().period_anchor,+ Some((d(2026, 4, 10), d(2026, 5, 10)))+ );+}++#[tokio::test]+async fn an_empty_or_unadoptable_read_is_not_repeated_for_a_minute() {+ let future_window = PeriodReply::Found(BillingPeriod {+ start: d(2026, 4, 19),+ end: d(2026, 5, 19),+ });+ for reply in [PeriodReply::Missing, future_window] {+ let (svc, _, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_period(reply);++ svc.position(&payer, apr_18_noon()).await.unwrap();+ let again = svc+ .position(&payer, apr_18_noon() + chrono::Duration::seconds(30))+ .await+ .unwrap();++ assert_eq!(+ again.period,+ BillingPeriod {+ start: d(2026, 4, 1),+ end: d(2026, 5, 1),+ },+ "{reply:?}"+ );+ assert_eq!(payments.period_requests().len(), 1, "{reply:?}");+ }+}++#[tokio::test]+async fn covering_anchor_never_reads_the_provider() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ repo.set_period(&payer, d(2026, 4, 1), d(2026, 5, 1))+ .await+ .unwrap();+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 1, 1),+ end: d(2026, 2, 1),+ }));++ let position = svc.position(&payer, apr_18_noon()).await.unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 1),+ end: d(2026, 5, 1),+ }+ );+ assert_eq!(+ repo.settings(&payer).await.unwrap().period_anchor,+ Some((d(2026, 4, 1), d(2026, 5, 1)))+ );+ assert!(payments.period_requests().is_empty());+}++#[tokio::test]+async fn free_and_unlimited_payers_never_read_the_provider() {+ let free = user("[email protected]");+ let unlimited = user("[email protected]");+ let entitlements = FakeEntitlements::default()+ .with(Entitlement::personal(free.clone(), PlanTier::Free))+ .with(Entitlement {+ unlimited: true,+ ..Entitlement::personal(unlimited.clone(), PlanTier::Premium)+ })+ .with_customer(&free, "cus_free")+ .with_customer(&unlimited, "cus_unlimited");+ let payments = FakePayments::default();+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }));+ let svc = BillingServiceImpl::new(+ entitlements,+ FakeUsage::default(),+ FakeRepo::default(),+ payments.clone(),+ AiPricing::testing(),+ )+ .with_billing(AiUsageBilling::Enabled);++ for payer in [free, unlimited] {+ let position = svc.position(&payer, apr_18_noon()).await.unwrap();+ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 1),+ end: d(2026, 5, 1),+ },+ "{payer}"+ );+ }+ assert!(payments.period_requests().is_empty());+}++#[tokio::test]+async fn payer_without_a_stripe_customer_never_reads_the_provider() {+ let payer = user("[email protected]");+ let payments = FakePayments::default();+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }));+ let svc = BillingServiceImpl::new(+ FakeEntitlements::default().with(Entitlement::personal(payer.clone(), PlanTier::Premium)),+ FakeUsage::default(),+ FakeRepo::default(),+ payments.clone(),+ AiPricing::testing(),+ )+ .with_billing(AiUsageBilling::Enabled);++ let position = svc.position(&payer, apr_18_noon()).await.unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 1),+ end: d(2026, 5, 1),+ }+ );+ assert!(payments.period_requests().is_empty());+}++#[tokio::test]+async fn team_member_reads_the_owner_subscription_in_team_scope() {+ let owner = user("[email protected]");+ let member = user("[email protected]");+ let team_id = Uuid::from_u128(7);+ let repo = FakeRepo::default();+ let payments = FakePayments::default();+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }));+ let svc = BillingServiceImpl::new(+ FakeEntitlements::default()+ .with(premium_team(&owner, &member, team_id))+ .with_customer(&owner, "cus_owner"),+ FakeUsage::default(),+ repo.clone(),+ payments.clone(),+ AiPricing::testing(),+ )+ .with_billing(AiUsageBilling::Enabled);++ let position = svc.position(&member, apr_18_noon()).await.unwrap();++ assert_eq!(+ position.period,+ BillingPeriod {+ start: d(2026, 4, 10),+ end: d(2026, 5, 10),+ }+ );+ assert_eq!(+ payments.period_requests(),+ vec![(+ "cus_owner".to_string(),+ SubscriptionScope::Team {+ team_id: Uuid::from_u128(7)+ }+ )]+ );+ assert_eq!(+ repo.period_writes(),+ vec![(+ "macro|[email protected]".to_string(),+ d(2026, 4, 10),+ d(2026, 5, 10)+ )]+ );+}++#[tokio::test]+async fn release_uses_the_subscription_period() {+ let owner = user("[email protected]");+ let member = user("[email protected]");+ let team_id = Uuid::from_u128(7);+ let repo = FakeRepo::default();+ let payments = FakePayments::default();+ payments.set_period(PeriodReply::Found(BillingPeriod {+ start: d(2026, 3, 20),+ end: d(2026, 4, 20),+ }));+ let svc = BillingServiceImpl::new(+ FakeEntitlements::default()+ .with(premium_team(&owner, &member, team_id))+ .with_customer(&owner, "cus_owner")+ .payer_for_team(team_id, owner.clone()),+ FakeUsage::default(),+ repo.clone(),+ payments,+ AiPricing::testing(),+ )+ .with_billing(AiUsageBilling::Enabled);++ svc.release_at(team_id, &member, apr_18_noon())+ .await+ .unwrap();++ assert_eq!(+ repo.releases(),+ vec![(+ "macro|[email protected]".to_string(),+ d(2026, 3, 20),+ "macro|[email protected]".to_string()+ )]+ );+}++#[tokio::test]+async fn release_with_a_covering_anchor_never_reads_the_entitlement() {+ let owner = user("[email protected]");+ let member = user("[email protected]");+ let team_id = Uuid::from_u128(7);+ let repo = FakeRepo::default();+ repo.set_period(&owner, d(2026, 4, 10), d(2026, 5, 10))+ .await+ .unwrap();+ let payments = FakePayments::default();+ let entitlements = FakeEntitlements::default()+ .with(premium_team(&owner, &member, team_id))+ .with_customer(&owner, "cus_owner")+ .payer_for_team(team_id, owner.clone());+ *entitlements.fail_entitlement.lock().unwrap() = true;+ let svc = BillingServiceImpl::new(+ entitlements,+ FakeUsage::default(),+ repo.clone(),+ payments.clone(),+ AiPricing::testing(),+ )+ .with_billing(AiUsageBilling::Enabled);++ svc.release_at(team_id, &member, apr_18_noon())+ .await+ .unwrap();++ assert_eq!(+ repo.releases(),+ vec![(+ "macro|[email protected]".to_string(),+ d(2026, 4, 10),+ "macro|[email protected]".to_string()+ )]+ );+ assert!(payments.period_requests().is_empty());+}++#[tokio::test]+async fn release_rolls_an_ended_anchor_when_the_entitlement_read_fails() {+ let owner = user("[email protected]");+ let member = user("[email protected]");+ let team_id = Uuid::from_u128(7);+ let repo = FakeRepo::default();+ repo.set_period(&owner, d(2026, 1, 15), d(2026, 2, 15))+ .await+ .unwrap();+ let entitlements = FakeEntitlements::default()+ .with(premium_team(&owner, &member, team_id))+ .with_customer(&owner, "cus_owner")+ .payer_for_team(team_id, owner.clone());+ *entitlements.fail_entitlement.lock().unwrap() = true;+ let svc = BillingServiceImpl::new(+ entitlements,+ FakeUsage::default(),+ repo.clone(),+ FakePayments::default(),+ AiPricing::testing(),+ )+ .with_billing(AiUsageBilling::Enabled);++ svc.release_at(team_id, &member, apr_18_noon())+ .await+ .unwrap();++ assert_eq!(+ repo.releases(),+ vec![(+ "macro|[email protected]".to_string(),+ d(2026, 4, 15),+ "macro|[email protected]".to_string()+ )]+ );+}diff --git a/crates/ai_billing/src/inbound/axum_router.rs b/crates/ai_billing/src/inbound/axum_router.rsindex 979d140273..6b9ec9957d 100644--- a/crates/ai_billing/src/inbound/axum_router.rs+++ b/crates/ai_billing/src/inbound/axum_router.rs@@ -1,26 +1,29 @@//! HTTP API for AI billing: the payer's position, overage settings, credit-//! purchases, the plan catalog, and the internal settle hook.+//! purchases, the plan catalog, and the internal settle and subscription-period+//! hooks.use crate::domain::{AiPricing, BillingError, BillingService, CREDIT_PACKS_CENTS, OVERAGE_LIMIT_MAX_CENTS,- OVERAGE_LIMIT_MIN_CENTS, PlanTier, UsageSnapshot,+ OVERAGE_LIMIT_MIN_CENTS, PaymentGateway, PlanTier, SubscriptionScope, UsageSnapshot,};use axum::{Json, Router,- extract::{FromRef, State},+ extract::{FromRef, Query, State},http::{HeaderMap, StatusCode, Uri, header::ORIGIN},response::{IntoResponse, Response},routing::{get, patch, post},};+use chrono::{DateTime, Utc};use macro_authorization::{InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,UserOrInternal,};use macro_user_id::user_id::MacroUserIdStr;+use macro_uuid::Uuid;use serde::{Deserialize, Serialize};use std::sync::Arc;use teams::domain::model::SeatPlan;-use utoipa::ToSchema;+use utoipa::{IntoParams, ToSchema};/// Error response body.#[derive(Debug, Serialize, ToSchema)]@@ -167,49 +170,82 @@ pub struct SettleRequest {pub user_id: String,}-/// Router state: the billing service, the configured pricing the catalog+/// Query for [`subscription_period_handler`].+#[derive(Debug, Deserialize, IntoParams)]+#[into_params(parameter_in = Query)]+#[serde(rename_all = "camelCase")]+pub struct SubscriptionPeriodQuery {+ /// The payer's Stripe customer.+ pub customer_id: String,+ /// The team whose subscription to read. Absent for the personal subscription.+ pub team_id: Option<Uuid>,+}++/// Response for [`subscription_period_handler`].+#[derive(Debug, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct SubscriptionPeriodResponse {+ /// First instant of the period.+ pub start: DateTime<Utc>,+ /// First instant after the period.+ pub end: DateTime<Utc>,+}++fn scope_from_query(team_id: Option<Uuid>) -> SubscriptionScope {+ match team_id {+ Some(team_id) => SubscriptionScope::Team { team_id },+ None => SubscriptionScope::Personal,+ }+}++/// Router state: the billing service, the payment gateway the internal+/// subscription-period read uses, the configured pricing the catalog/// publishes, and the authorization state the extractors need.-pub struct AiBillingRouterState<B, Auth> {+pub struct AiBillingRouterState<B, P, Auth> {/// The billing service.pub service: Arc<B>,+ /// The payment gateway that answers subscription-period reads.+ pub payments: Arc<P>,/// The pricing the host composed the billing service with.pub pricing: AiPricing,/// Authorization state for the request extractors.pub authorization_state: MacroAuthorizationState<Auth>,}-impl<B, Auth> Clone for AiBillingRouterState<B, Auth> {+impl<B, P, Auth> Clone for AiBillingRouterState<B, P, Auth> {fn clone(&self) -> Self {Self {service: self.service.clone(),+ payments: self.payments.clone(),pricing: self.pricing,authorization_state: self.authorization_state.clone(),}}}-impl<B, Auth> FromRef<AiBillingRouterState<B, Auth>> for AiPricing {- fn from_ref(state: &AiBillingRouterState<B, Auth>) -> Self {+impl<B, P, Auth> FromRef<AiBillingRouterState<B, P, Auth>> for AiPricing {+ fn from_ref(state: &AiBillingRouterState<B, P, Auth>) -> Self {state.pricing}}-impl<B, Auth> FromRef<AiBillingRouterState<B, Auth>> for Arc<B> {- fn from_ref(state: &AiBillingRouterState<B, Auth>) -> Self {+impl<B, P, Auth> FromRef<AiBillingRouterState<B, P, Auth>> for Arc<B> {+ fn from_ref(state: &AiBillingRouterState<B, P, Auth>) -> Self {state.service.clone()}}-impl<B, Auth> FromRef<AiBillingRouterState<B, Auth>> for MacroAuthorizationState<Auth> {- fn from_ref(state: &AiBillingRouterState<B, Auth>) -> Self {+impl<B, P, Auth> FromRef<AiBillingRouterState<B, P, Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &AiBillingRouterState<B, P, Auth>) -> Self {state.authorization_state.clone()}}/// Build the AI billing router.-pub fn ai_billing_router<B, Auth, S>(state: AiBillingRouterState<B, Auth>) -> Router<S>+pub fn ai_billing_router<B, P, Auth, S>(state: AiBillingRouterState<B, P, Auth>) -> Router<S>whereB: BillingService,+ P: PaymentGateway,Auth: MacroAuthorizationService,S: Send + Sync + Clone + 'static,{@@ -228,6 +264,10 @@ where"/internal/ai-billing/settle",post(settle_handler::<B, Auth>),)+ .route(+ "/internal/ai-billing/subscription-period",+ get(subscription_period_handler::<B, P, Auth>),+ ).with_state(state)}@@ -430,5 +470,48 @@ pub async fn settle_handler<B: BillingService, Auth: MacroAuthorizationService>(}}+/// The current period of a Stripe customer's non-canceled subscription in the+/// personal or team scope, preferring an active or trialing one. Internal+/// services only; the document cognition service reads it when a payer's stored+/// period is missing or ended.+#[utoipa::path(+ get,+ path = "/internal/ai-billing/subscription-period",+ operation_id = "get_ai_billing_subscription_period",+ params(SubscriptionPeriodQuery),+ responses(+ (status = 200, description = "Current subscription period", body = SubscriptionPeriodResponse),+ (status = 204, description = "No non-canceled subscription in scope"),+ (status = 401, description = "Unauthorized"),+ (status = 500, description = "Internal server error", body = AiBillingErrorBody),+ ),+ tag = "ai_billing"+)]+#[tracing::instrument(skip(state, _internal))]+pub async fn subscription_period_handler<B, P, Auth>(+ State(state): State<AiBillingRouterState<B, P, Auth>>,+ _internal: MacroAuthorizationExtractor<Auth, InternalOnly>,+ Query(query): Query<SubscriptionPeriodQuery>,+) -> Response+where+ B: BillingService,+ P: PaymentGateway,+ Auth: MacroAuthorizationService,+{+ match state+ .payments+ .subscription_period(&query.customer_id, scope_from_query(query.team_id))+ .await+ {+ Ok(Some(period)) => Json(SubscriptionPeriodResponse {+ start: period.start,+ end: period.end,+ })+ .into_response(),+ Ok(None) => StatusCode::NO_CONTENT.into_response(),+ Err(e) => error_response(e),+ }+}+#[cfg(test)]mod test;diff --git a/crates/ai_billing/src/inbound/axum_router/test.rs b/crates/ai_billing/src/inbound/axum_router/test.rsindex 58f810cf61..047ad1d72a 100644--- a/crates/ai_billing/src/inbound/axum_router/test.rs+++ b/crates/ai_billing/src/inbound/axum_router/test.rs@@ -1,6 +1,10 @@-use super::{ReturnUrlError, get_plans_handler, validate_return_url};-use crate::domain::{AiPricing, PlanTier};-use axum::extract::State;+use super::{+ ReturnUrlError, SettleRequest, SubscriptionPeriodQuery, get_plans_handler, scope_from_query,+ validate_return_url,+};+use crate::domain::{AiPricing, PlanTier, SubscriptionScope};+use axum::extract::{Query, State};+use macro_uuid::Uuid;#[test]fn return_urls_must_be_https_on_the_calling_origin() {@@ -67,3 +71,38 @@ async fn plan_catalog_lists_every_tier_and_marks_the_purchasable_ones() {]);}++#[test]+fn subscription_period_query_selects_the_scope() {+ let Query(team) = Query::<SubscriptionPeriodQuery>::try_from_uri(+ &"/internal/ai-billing/subscription-period?customerId=cus_123&teamId=00000000-0000-0000-0000-000000000007"+ .parse()+ .unwrap(),+ )+ .unwrap();+ assert_eq!(team.customer_id, "cus_123");+ assert_eq!(+ scope_from_query(team.team_id),+ SubscriptionScope::Team {+ team_id: Uuid::from_u128(7)+ }+ );++ let Query(personal) = Query::<SubscriptionPeriodQuery>::try_from_uri(+ &"/internal/ai-billing/subscription-period?customerId=cus_123"+ .parse()+ .unwrap(),+ )+ .unwrap();+ assert_eq!(personal.customer_id, "cus_123");+ assert_eq!(+ scope_from_query(personal.team_id),+ SubscriptionScope::Personal+ );+}++#[test]+fn settle_request_reads_the_camel_case_user_id() {+ let request: SettleRequest = serde_json::from_str(r#"{"userId":"macro|[email protected]"}"#).unwrap();+ assert_eq!(request.user_id, "macro|[email protected]");+}diff --git a/crates/ai_billing/src/outbound.rs b/crates/ai_billing/src/outbound.rsindex 3fcea3d6c7..ca248aa77a 100644--- a/crates/ai_billing/src/outbound.rs+++ b/crates/ai_billing/src/outbound.rs@@ -1,7 +1,9 @@//! Outbound adapters: Postgres, Stripe, the roles + teams entitlement resolver,-//! the internal settlement trigger, and the settling usage recorder.+//! the internal settlement trigger and subscription-period reader, and the+//! settling usage recorder.pub mod entitlement;+pub mod http_payment_gateway;pub mod http_settlement_trigger;pub mod pg_billing_repo;pub mod pg_funding_repo;@@ -10,6 +12,7 @@ pub mod settling_recorder;pub mod stripe_gateway;pub use entitlement::RolesTeamsEntitlementSource;+pub use http_payment_gateway::HttpPaymentGateway;pub use http_settlement_trigger::HttpSettlementTrigger;pub use pg_billing_repo::PgBillingRepo;pub use pg_funding_repo::PgFundingRepo;diff --git a/crates/ai_billing/src/outbound/http_payment_gateway.rs b/crates/ai_billing/src/outbound/http_payment_gateway.rsnew file mode 100644index 0000000000..4ad4943525--- /dev/null+++ b/crates/ai_billing/src/outbound/http_payment_gateway.rs@@ -0,0 +1,82 @@+//! Reads the subscription period through the authentication service, which+//! owns Stripe.++#[cfg(test)]+mod test;++use super::NoOpPaymentGateway;+use crate::domain::{+ BillingError, BillingPeriod, CreditCheckoutRequest, OverageChargeRequest, PaymentGateway,+ Result, SubscriptionScope,+};+use authentication_service_client::AuthServiceClient;+use macro_uuid::Uuid;+use std::sync::Arc;+use std::time::Duration;++/// The read sits on the AI request path and a failed read degrades to the+/// stored anchor, so it gets a third of the client's 15 s default.+const SUBSCRIPTION_PERIOD_TIMEOUT: Duration = Duration::from_secs(5);++/// [`PaymentGateway`] for the document cognition service, which gates AI+/// requests but does not own Stripe. Reads the subscription period through the+/// authentication service and refuses to pay like [`NoOpPaymentGateway`]. The+/// client must present the authentication service's own key, which the other+/// gate hosts do not hold.+#[derive(Clone)]+pub struct HttpPaymentGateway {+ client: Arc<AuthServiceClient>,+}++impl HttpPaymentGateway {+ /// Wrap an internal auth-service client.+ pub fn new(client: Arc<AuthServiceClient>) -> Self {+ Self { client }+ }+}++impl PaymentGateway for HttpPaymentGateway {+ async fn create_credit_checkout(&self, request: CreditCheckoutRequest) -> Result<String> {+ NoOpPaymentGateway.create_credit_checkout(request).await+ }++ async fn open_overage_invoice(&self, request: OverageChargeRequest) -> Result<String> {+ NoOpPaymentGateway.open_overage_invoice(request).await+ }++ async fn pay_overage_invoice(+ &self,+ charge_id: Uuid,+ invoice_id: &str,+ scope: SubscriptionScope,+ ) -> Result<bool> {+ NoOpPaymentGateway+ .pay_overage_invoice(charge_id, invoice_id, scope)+ .await+ }++ async fn subscription_period(+ &self,+ customer_id: &str,+ scope: SubscriptionScope,+ ) -> Result<Option<BillingPeriod>> {+ let team_id = match scope {+ SubscriptionScope::Personal => None,+ SubscriptionScope::Team { team_id } => Some(team_id),+ };+ let period = self+ .client+ .ai_subscription_period(customer_id, team_id, SUBSCRIPTION_PERIOD_TIMEOUT)+ .await+ .map_err(|e| {+ BillingError::Payment(+ anyhow::Error::new(e)+ .context("reading the subscription period from the authentication service"),+ )+ })?;+ Ok(period.map(|period| BillingPeriod {+ start: period.start,+ end: period.end,+ }))+ }+}diff --git a/crates/ai_billing/src/outbound/http_payment_gateway/test.rs b/crates/ai_billing/src/outbound/http_payment_gateway/test.rsnew file mode 100644index 0000000000..44a8c3cdf5--- /dev/null+++ b/crates/ai_billing/src/outbound/http_payment_gateway/test.rs@@ -0,0 +1,134 @@+use super::*;+use crate::inbound::axum_router::SubscriptionPeriodResponse;+use chrono::{DateTime, TimeZone, Utc};+use wiremock::matchers::{header, method, path, query_param, query_param_is_missing};+use wiremock::{Mock, MockServer, ResponseTemplate};++const CUSTOMER_ID: &str = "cus_123";+const TEAM_ID: Uuid = Uuid::from_u128(7);+const PERIOD_PATH: &str = "/internal/ai-billing/subscription-period";++#[tokio::test]+async fn reads_the_period_for_a_team_scope() {+ let start = Utc.with_ymd_and_hms(2026, 3, 18, 8, 0, 0).unwrap();+ let end = Utc.with_ymd_and_hms(2026, 4, 18, 8, 0, 0).unwrap();+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path(PERIOD_PATH))+ .and(query_param("customerId", CUSTOMER_ID))+ .and(query_param(+ "teamId",+ "00000000-0000-0000-0000-000000000007",+ ))+ .and(header("x-internal-auth-key", "key"))+ .respond_with(period_response(start, end))+ .expect(1)+ .mount(&server)+ .await;++ let period = gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Team { team_id: TEAM_ID })+ .await+ .unwrap();++ assert_eq!(period, Some(BillingPeriod { start, end }));+}++#[tokio::test]+async fn reads_the_period_for_the_personal_scope() {+ let start = Utc.with_ymd_and_hms(2026, 4, 10, 0, 0, 0).unwrap();+ let end = Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap();+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path(PERIOD_PATH))+ .and(query_param("customerId", CUSTOMER_ID))+ .and(query_param_is_missing("teamId"))+ .and(header("x-internal-auth-key", "key"))+ .respond_with(period_response(start, end))+ .expect(1)+ .mount(&server)+ .await;++ let period = gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ .unwrap();++ assert_eq!(period, Some(BillingPeriod { start, end }));+}++#[tokio::test]+async fn missing_subscription_is_none() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path(PERIOD_PATH))+ .respond_with(ResponseTemplate::new(204))+ .expect(1)+ .mount(&server)+ .await;++ let period = gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ .unwrap();++ assert_eq!(period, None);+}++#[tokio::test]+async fn provider_errors_are_payment_errors() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path(PERIOD_PATH))+ .respond_with(ResponseTemplate::new(500).set_body_string("stripe is down"))+ .expect(1)+ .mount(&server)+ .await;++ match gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ {+ Err(BillingError::Payment(error)) => assert_eq!(+ format!("{error:#}"),+ "reading the subscription period from the authentication service: internal server error: stripe is down"+ ),+ other => panic!("expected a payment error, got {other:?}"),+ }+}++#[tokio::test]+async fn other_failures_carry_the_response_body() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path(PERIOD_PATH))+ .respond_with(+ ResponseTemplate::new(400)+ .set_body_string("Failed to deserialize query string: missing field `customerId`"),+ )+ .expect(1)+ .mount(&server)+ .await;++ match gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ {+ Err(BillingError::Payment(error)) => assert_eq!(+ format!("{error:#}"),+ "reading the subscription period from the authentication service: Failed to deserialize query string: missing field `customerId`"+ ),+ other => panic!("expected a payment error, got {other:?}"),+ }+}++fn gateway(server: &MockServer) -> HttpPaymentGateway {+ HttpPaymentGateway::new(Arc::new(AuthServiceClient::new(+ "key".to_string(),+ server.uri(),+ )))+}++fn period_response(start: DateTime<Utc>, end: DateTime<Utc>) -> ResponseTemplate {+ ResponseTemplate::new(200).set_body_json(SubscriptionPeriodResponse { start, end })+}diff --git a/crates/ai_billing/src/outbound/http_settlement_trigger.rs b/crates/ai_billing/src/outbound/http_settlement_trigger.rsindex 628ebc4d32..583256e2dc 100644--- a/crates/ai_billing/src/outbound/http_settlement_trigger.rs+++ b/crates/ai_billing/src/outbound/http_settlement_trigger.rs@@ -1,5 +1,8 @@//! Asks the authentication service (which owns Stripe) to settle a payer.+#[cfg(test)]+mod test;+use crate::domain::SettlementTrigger;use authentication_service_client::AuthServiceClient;use macro_user_id::user_id::MacroUserIdStr;diff --git a/crates/ai_billing/src/outbound/http_settlement_trigger/test.rs b/crates/ai_billing/src/outbound/http_settlement_trigger/test.rsnew file mode 100644index 0000000000..4230f7e6e6--- /dev/null+++ b/crates/ai_billing/src/outbound/http_settlement_trigger/test.rs@@ -0,0 +1,21 @@+use authentication_service_client::AuthServiceClient;+use wiremock::matchers::{body_json, header, method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++#[tokio::test]+async fn settle_requests_carry_the_camel_case_user_id() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/internal/ai-billing/settle"))+ .and(header("x-internal-auth-key", "key"))+ .and(body_json(+ serde_json::json!({"userId": "macro|[email protected]"}),+ ))+ .respond_with(ResponseTemplate::new(204))+ .expect(1)+ .mount(&server)+ .await;++ let client = AuthServiceClient::new("key".to_string(), server.uri());+ client.settle_ai_billing("macro|[email protected]").await.unwrap();+}diff --git a/crates/ai_billing/src/outbound/stripe_gateway.rs b/crates/ai_billing/src/outbound/stripe_gateway.rsindex ad74a16533..e50f437f3f 100644--- a/crates/ai_billing/src/outbound/stripe_gateway.rs+++ b/crates/ai_billing/src/outbound/stripe_gateway.rs@@ -1,14 +1,14 @@-//! Stripe adapter: one-off Checkout for credit packs, and immediate invoices-//! for overage chunks.+//! Stripe adapter: one-off Checkout for credit packs, immediate invoices for+//! overage chunks, and the current subscription period.#[cfg(test)]mod test;use crate::domain::{- BillingError, CreditCheckoutRequest, OverageChargeRequest, PaymentGateway, Result,- SubscriptionScope,+ BillingError, BillingPeriod, CreditCheckoutRequest, OverageChargeRequest, PaymentGateway,+ Result, SubscriptionScope,};-use chrono::Utc;+use chrono::{DateTime, Utc};use macro_uuid::Uuid;use serde::Serialize;use std::collections::HashMap;@@ -175,6 +175,50 @@ fn in_scope(subscription: &Subscription, scope: SubscriptionScope) -> bool {}}+fn billable(subscription: &Subscription) -> bool {+ matches!(+ subscription.status,+ SubscriptionStatus::Active | SubscriptionStatus::Trialing+ )+}++/// Billable subscriptions decide the period. Without one, any subscription in+/// scope does, because a payer whose subscription fell past due can still be+/// metered and the webhook stores periods whatever the status.+fn scoped_period(+ subscriptions: &[Subscription],+ scope: SubscriptionScope,+) -> Result<Option<BillingPeriod>> {+ let scoped = || {+ subscriptions+ .iter()+ .filter(move |subscription| in_scope(subscription, scope))+ };+ if let Some(period) = agreed_period(scoped().filter(|subscription| billable(subscription)))? {+ return Ok(Some(period));+ }+ agreed_period(scoped())+}++fn agreed_period<'a>(+ subscriptions: impl Iterator<Item = &'a Subscription>,+) -> Result<Option<BillingPeriod>> {+ let mut periods = subscriptions.filter_map(|subscription| {+ let start = DateTime::from_timestamp(subscription.current_period_start, 0)?;+ let end = DateTime::from_timestamp(subscription.current_period_end, 0)?;+ (start < end).then_some(BillingPeriod { start, end })+ });+ let Some(period) = periods.next() else {+ return Ok(None);+ };+ if periods.any(|other| other != period) {+ return Err(BillingError::Payment(anyhow::anyhow!(+ "subscriptions in scope disagree on the billing period"+ )));+ }+ Ok(Some(period))+}+fn charge_method(fallback: Option<PaymentMethodId>,subscriptions: &[Subscription],@@ -182,11 +226,7 @@ fn charge_method() -> Result<ChargeMethod> {let mut selected = ChargeMethod::NoMatchingSubscription;for subscription in subscriptions {- if !matches!(- subscription.status,- SubscriptionStatus::Active | SubscriptionStatus::Trialing- ) || !in_scope(subscription, scope)- {+ if !billable(subscription) || !in_scope(subscription, scope) {continue;}let candidate = payment_method_id(&subscription.default_payment_method)@@ -471,6 +511,17 @@ impl PaymentGateway for StripePaymentGateway {}}}++ #[tracing::instrument(skip(self), err)]+ async fn subscription_period(+ &self,+ customer_id: &str,+ scope: SubscriptionScope,+ ) -> Result<Option<BillingPeriod>> {+ let customer = parse_customer(customer_id)?;+ let subscriptions = self.non_canceled_subscriptions(&customer).await?;+ scoped_period(&subscriptions, scope)+ }}/// A [`PaymentGateway`] for services that never settle (they only read@@ -501,4 +552,12 @@ impl PaymentGateway for NoOpPaymentGateway {"payments are not configured in this service")))}++ async fn subscription_period(+ &self,+ _customer_id: &str,+ _scope: SubscriptionScope,+ ) -> Result<Option<BillingPeriod>> {+ Ok(None)+ }}diff --git a/crates/ai_billing/src/outbound/stripe_gateway/test.rs b/crates/ai_billing/src/outbound/stripe_gateway/test.rsindex 6d7f002255..8338654c77 100644--- a/crates/ai_billing/src/outbound/stripe_gateway/test.rs+++ b/crates/ai_billing/src/outbound/stripe_gateway/test.rs@@ -1,4 +1,5 @@use super::*;+use chrono::TimeZone;use serde::Serialize;use serde::de::DeserializeOwned;use serde_json::{Value, json};@@ -757,6 +758,216 @@ async fn pay_overage_invoice_returns_when_the_invoice_is_already_paid() {}));}+#[tokio::test]+async fn subscription_period_selects_the_billable_subscription_in_scope() {+ let personal = BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 4, 10, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap(),+ };+ let team = BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 3, 18, 8, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 4, 18, 8, 0, 0).unwrap(),+ };+ let team_id = TEAM_ID.to_string();+ let server = MockServer::start().await;+ mount_subscriptions(+ &server,+ subscription_page(+ vec![+ subscription_in_period(+ "sub_past_due",+ stripe::SubscriptionStatus::PastDue,+ None,+ BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 1, 15, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 2, 15, 0, 0, 0).unwrap(),+ },+ ),+ subscription_in_period(+ "sub_personal",+ stripe::SubscriptionStatus::Active,+ None,+ personal,+ ),+ subscription_in_period(+ "sub_team",+ stripe::SubscriptionStatus::Active,+ Some(&team_id),+ team,+ ),+ ],+ false,+ ),+ )+ .await;+ let gateway = gateway(&server);++ assert_eq!(+ gateway+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ .unwrap(),+ Some(personal)+ );+ assert_eq!(+ gateway+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Team { team_id: TEAM_ID })+ .await+ .unwrap(),+ Some(team)+ );+ assert_eq!(+ gateway+ .subscription_period(+ CUSTOMER_ID,+ SubscriptionScope::Team {+ team_id: Uuid::from_u128(8)+ }+ )+ .await+ .unwrap(),+ None+ );+ let requests = server.received_requests().await.expect("recorded requests");+ assert!(+ requests+ .iter()+ .all(|request| request.url.path() == "/v1/subscriptions"),+ "{requests:?}"+ );+}++#[tokio::test]+async fn subscription_period_rejects_disagreeing_subscriptions() {+ let server = MockServer::start().await;+ mount_subscriptions(+ &server,+ subscription_page(+ vec![+ subscription_in_period(+ "sub_monthly",+ stripe::SubscriptionStatus::Active,+ None,+ BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 4, 10, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap(),+ },+ ),+ subscription_in_period(+ "sub_other",+ stripe::SubscriptionStatus::Active,+ None,+ BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 4, 1, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 5, 1, 0, 0, 0).unwrap(),+ },+ ),+ ],+ false,+ ),+ )+ .await;++ let error = gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ .expect_err("two personal subscriptions on different periods");+ assert!(matches!(error, BillingError::Payment(_)), "{error:?}");+}++#[tokio::test]+async fn subscription_period_reads_a_past_due_subscription_when_none_is_billable() {+ let server = MockServer::start().await;+ mount_subscriptions(+ &server,+ subscription_page(+ vec![subscription_in_period(+ "sub_past_due",+ stripe::SubscriptionStatus::PastDue,+ None,+ BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 4, 10, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap(),+ },+ )],+ false,+ ),+ )+ .await;++ assert_eq!(+ gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ .unwrap(),+ Some(BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 4, 10, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap(),+ })+ );+}++#[tokio::test]+async fn subscription_period_prefers_the_billable_subscription_to_an_unpaid_one() {+ let server = MockServer::start().await;+ mount_subscriptions(+ &server,+ subscription_page(+ vec![+ subscription_in_period(+ "sub_unpaid",+ stripe::SubscriptionStatus::Unpaid,+ None,+ BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 1, 15, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 2, 15, 0, 0, 0).unwrap(),+ },+ ),+ subscription_in_period(+ "sub_active",+ stripe::SubscriptionStatus::Active,+ None,+ BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 4, 10, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap(),+ },+ ),+ ],+ false,+ ),+ )+ .await;++ assert_eq!(+ gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ .unwrap(),+ Some(BillingPeriod {+ start: Utc.with_ymd_and_hms(2026, 4, 10, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 5, 10, 0, 0, 0).unwrap(),+ })+ );+}++#[tokio::test]+async fn subscription_period_reports_provider_errors() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/v1/subscriptions"))+ .respond_with(ResponseTemplate::new(500).set_body_json(json!({+ "error": { "type": "api_error", "message": "stripe is down" }+ })))+ .mount(&server)+ .await;++ let error = gateway(&server)+ .subscription_period(CUSTOMER_ID, SubscriptionScope::Personal)+ .await+ .expect_err("stripe answered 500");+ assert!(matches!(error, BillingError::Payment(_)), "{error:?}");+}+fn customer_with_stale_fallback() -> stripe::Customer {let stale: stripe::PaymentMethodId =STALE_PAYMENT_METHOD.parse().expect("stale payment method");@@ -801,6 +1012,19 @@ fn subscription(}}+fn subscription_in_period(+ id: &str,+ status: stripe::SubscriptionStatus,+ team_id: Option<&str>,+ period: BillingPeriod,+) -> Value {+ stripe_response(&stripe::Subscription {+ current_period_start: period.start.timestamp(),+ current_period_end: period.end.timestamp(),+ ..subscription(id, status, None, team_id)+ })+}+fn open_invoice(default_payment_method: Option<&str>, scope: Option<&str>) -> stripe::Invoice {let method = default_payment_method.map(|method| stripe::Expandable::Id(method.parse().expect("invoice payment method")));@@ -862,6 +1086,10 @@ async fn mount_customer(server: &MockServer) {async fn mount_customer_and_subscriptions(server: &MockServer, subscriptions: Value) {mount_customer(server).await;+ mount_subscriptions(server, subscriptions).await;+}++async fn mount_subscriptions(server: &MockServer, subscriptions: Value) {Mock::given(method("GET")).and(path("/v1/subscriptions")).and(query_param("customer", CUSTOMER_ID))diff --git a/crates/authentication_service_client/Cargo.toml b/crates/authentication_service_client/Cargo.tomlindex bceb52d590..7005aaa96e 100644--- a/crates/authentication_service_client/Cargo.toml+++ b/crates/authentication_service_client/Cargo.toml@@ -6,9 +6,11 @@ version = "0.1.0"[dependencies]anyhow = { workspace = true }+chrono = { workspace = true }model = { path = "../model" }reqwest = { workspace = true }serde = { workspace = true }thiserror = { workspace = true }tracing = { workspace = true }+uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/authentication_service_client/src/ai_billing.rs b/crates/authentication_service_client/src/ai_billing.rsindex 5c8802b64f..450e48cfdf 100644--- a/crates/authentication_service_client/src/ai_billing.rs+++ b/crates/authentication_service_client/src/ai_billing.rs@@ -1,11 +1,32 @@use crate::AuthServiceClient;use crate::error::{AuthServiceClientError, GenericErrorResponse};+use chrono::{DateTime, Utc};+use std::time::Duration;+use uuid::Uuid;#[derive(Debug, serde::Serialize)]+#[serde(rename_all = "camelCase")]struct SettleAiBillingRequest<'a> {user_id: &'a str,}+#[derive(Debug, serde::Serialize)]+#[serde(rename_all = "camelCase")]+struct SubscriptionPeriodQuery<'a> {+ customer_id: &'a str,+ #[serde(skip_serializing_if = "Option::is_none")]+ team_id: Option<Uuid>,+}++/// A Stripe subscription's current billing period, `[start, end)`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]+pub struct AiSubscriptionPeriod {+ /// First instant of the period.+ pub start: DateTime<Utc>,+ /// First instant after the period.+ pub end: DateTime<Utc>,+}+impl AuthServiceClient {/// Ask the authentication service to settle AI billing for `user_id`'s/// payer: apply prepaid credits to usage past the allowance and collect@@ -27,23 +48,63 @@ impl AuthServiceClient {match res.status() {reqwest::StatusCode::OK | reqwest::StatusCode::NO_CONTENT => Ok(()),- reqwest::StatusCode::UNAUTHORIZED => Err(AuthServiceClientError::Unauthorized),- reqwest::StatusCode::FORBIDDEN => Err(AuthServiceClientError::Forbidden),- reqwest::StatusCode::NOT_FOUND => Err(AuthServiceClientError::NotFound),- status => {- let body = res.text().await.map_err(|e| {- AuthServiceClientError::Generic(GenericErrorResponse {- message: e.to_string(),- })- })?;- if status == reqwest::StatusCode::INTERNAL_SERVER_ERROR {- Err(AuthServiceClientError::InternalServerError { details: body })- } else {- Err(AuthServiceClientError::Generic(GenericErrorResponse {- message: body,- }))- }- }+ _ => Err(error_for_status(res).await),+ }+ }++ /// The current Stripe subscription period for `customer_id` in the personal+ /// scope (`team_id` is `None`) or the team scope. `Ok(None)` when no+ /// non-canceled subscription matches. The caller picks `timeout` because it+ /// knows what is waiting on the answer.+ #[tracing::instrument(skip(self), err)]+ pub async fn ai_subscription_period(+ &self,+ customer_id: &str,+ team_id: Option<Uuid>,+ timeout: Duration,+ ) -> Result<Option<AiSubscriptionPeriod>, AuthServiceClientError> {+ let res = self+ .client+ .get(format!(+ "{}/internal/ai-billing/subscription-period",+ self.url+ ))+ .query(&SubscriptionPeriodQuery {+ customer_id,+ team_id,+ })+ .timeout(timeout)+ .send()+ .await+ .map_err(|e| AuthServiceClientError::RequestBuildError {+ details: e.to_string(),+ })?;++ match res.status() {+ reqwest::StatusCode::OK => res.json().await.map(Some).map_err(|e| {+ AuthServiceClientError::Generic(GenericErrorResponse {+ message: e.to_string(),+ })+ }),+ reqwest::StatusCode::NO_CONTENT => Ok(None),+ _ => Err(error_for_status(res).await),}}}++async fn error_for_status(res: reqwest::Response) -> AuthServiceClientError {+ match res.status() {+ reqwest::StatusCode::UNAUTHORIZED => AuthServiceClientError::Unauthorized,+ reqwest::StatusCode::FORBIDDEN => AuthServiceClientError::Forbidden,+ reqwest::StatusCode::NOT_FOUND => AuthServiceClientError::NotFound,+ status => match res.text().await {+ Err(e) => AuthServiceClientError::Generic(GenericErrorResponse {+ message: e.to_string(),+ }),+ Ok(body) if status == reqwest::StatusCode::INTERNAL_SERVER_ERROR => {+ AuthServiceClientError::InternalServerError { details: body }+ }+ Ok(body) => AuthServiceClientError::Generic(GenericErrorResponse { message: body }),+ },+ }+}diff --git a/crates/authentication_service_client/src/error.rs b/crates/authentication_service_client/src/error.rsindex dc5ca61919..522697e42c 100644--- a/crates/authentication_service_client/src/error.rs+++ b/crates/authentication_service_client/src/error.rs@@ -11,7 +11,7 @@ pub enum AuthServiceClientError {InternalServerError { details: String },#[error("unable to build request: {details}")]RequestBuildError { details: String },- #[error("an unknown error occurred")]+ #[error("{}", .0.message)]Generic(GenericErrorResponse),}diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rsindex 893c5aa434..68a7a05a59 100644--- a/services/authentication_service/src/api.rs+++ b/services/authentication_service/src/api.rs@@ -157,6 +157,7 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {.merge(ai_billing::inbound::ai_billing_router(ai_billing::inbound::AiBillingRouterState {service: state.ai_billing_service.clone(),+ payments: state.ai_payment_gateway.clone(),pricing: state.ai_billing_service.pricing(),authorization_state: state.authorization_state.clone(),},diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rsindex 030330c184..4c6ebdf0f9 100644--- a/services/authentication_service/src/api/context.rs+++ b/services/authentication_service/src/api/context.rs@@ -179,6 +179,7 @@ pub(crate) struct ApiContext {pub stripe_prices: crate::api::user::stripe::StripePrices,/// AI allowances, credits, and overagepub ai_billing_service: Arc<AiBillingServiceType>,+ pub ai_payment_gateway: Arc<ai_billing::outbound::StripePaymentGateway>,/// Whether Gmail link consent requests the Google Calendar scope.pub calendar_scope_enabled: bool,}diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rsindex bb94f727ee..64079d8700 100644--- a/services/authentication_service/src/main.rs+++ b/services/authentication_service/src/main.rs@@ -506,6 +506,7 @@ async fn main() -> anyhow::Result<()> {};let stripe_client = Arc::new(stripe_client);+ let ai_payment_gateway = ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone());let ai_pricing = config.ai_pricing();let ai_billing_service = Arc::new(ai_billing::domain::BillingServiceImpl::new(@@ -515,7 +516,7 @@ async fn main() -> anyhow::Result<()> {),ai_billing::outbound::PgUsageReader::new(db.clone()),ai_billing::outbound::PgBillingRepo::new(db.clone(), ai_pricing),- ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone()),+ ai_payment_gateway.clone(),ai_pricing,).with_enforcement(config.enable_ai_usage_enforcement)@@ -611,6 +612,7 @@ async fn main() -> anyhow::Result<()> {analytics_client,stripe_prices,ai_billing_service,+ ai_payment_gateway: Arc::new(ai_payment_gateway),},config.port,)diff --git a/services/document_cognition_service/src/api/context.rs b/services/document_cognition_service/src/api/context.rsindex 6ae52bab01..46b037ab67 100644--- a/services/document_cognition_service/src/api/context.rs+++ b/services/document_cognition_service/src/api/context.rs@@ -47,8 +47,7 @@ pub type DcsUserPermissionsService =>;/// The AI billing gate: reads plan allowances, credits, and overage state.-/// DCS never charges anyone (the payment gateway is a no-op); settlement is-/// requested from the authentication service.+/// DCS never charges anyone.pub type DcsAiBillingService = ai_billing::domain::BillingServiceImpl<ai_billing::outbound::RolesTeamsEntitlementSource<DcsUserPermissionsService,@@ -56,7 +55,7 @@ pub type DcsAiBillingService = ai_billing::domain::BillingServiceImpl<>,ai_billing::outbound::PgUsageReader,ai_billing::outbound::PgBillingRepo,- ai_billing::outbound::NoOpPaymentGateway,+ ai_billing::outbound::HttpPaymentGateway,>;/// Type alias for the chat model entitlement extractor wired to DCS services.diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 0bfa6fbc7d..e4fe01a7ee 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -650,7 +650,12 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar),ai_billing::outbound::PgUsageReader::new(pool.clone()),ai_billing::outbound::PgBillingRepo::new(pool.clone(), pricing),- ai_billing::outbound::NoOpPaymentGateway,+ ai_billing::outbound::HttpPaymentGateway::new(Arc::new(+ authentication_service_client::AuthServiceClient::new(+ "testing".to_string(),+ "http://127.0.0.1:9".to_string(),+ ),+ )),pricing,).with_enforcement(enforcement),diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex 880c6742c6..d836f5c688 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -489,6 +489,13 @@ async fn main() -> anyhow::Result<()> {// collection (Stripe) lives in the authentication service, which the// recorder below asks to settle once a payer runs past their allowance// and ENABLE_AI_USAGE_BILLING is enabled. This instance never settles.+ let auth_service_client = Arc::new(authentication_service_client::AuthServiceClient::new(+ config+ .authentication_service_secret_key+ .as_ref()+ .to_string(),+ AuthServiceUrl::new()?.to_string(),+ ));let ai_pricing = config.ai_pricing();let ai_billing = Arc::new(ai_billing::domain::BillingServiceImpl::new(@@ -498,7 +505,7 @@ async fn main() -> anyhow::Result<()> {),ai_billing::outbound::PgUsageReader::new(db.clone()),ai_billing::outbound::PgBillingRepo::new(db.clone(), ai_pricing),- ai_billing::outbound::NoOpPaymentGateway,+ ai_billing::outbound::HttpPaymentGateway::new(auth_service_client.clone()),ai_pricing,).with_enforcement(config.enable_ai_usage_enforcement),@@ -508,10 +515,6 @@ async fn main() -> anyhow::Result<()> {ai_billing.clone(),config.enable_ai_usage_enforcement,));- let auth_service_client = Arc::new(authentication_service_client::AuthServiceClient::new(- internal_api_key.clone(),- AuthServiceUrl::new()?.to_string(),- ));let recorder: Arc<dyn ai_usage::UsageRecorder> =Arc::new(ai_billing::outbound::SettlingUsageRecorder::new(Arc::new(