Skip to content

g1t/services/billing/src/limits.rs

1,367 lines65,527 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1//! How far a workspace can run up costs g1t has not been paid for, and how
2//! far its owners let it spend.
Usage limits: unpaid usage can only go so far3//!
4//! Every sandbox second, build, app request and model token costs g1t
5//! money at Cloudflare or a model provider before the workspace pays for
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look6//! it. So each workspace has a ceiling on that unpaid usage:
Usage limits: unpaid usage can only go so far7//!
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look8//! - **Free**: a few dollars (`LIMIT_NEW_MICROS`), for what a free
9//! workspace can owe at all (private storage past 1 GB). Free workspaces
10//! have no on-demand compute: the trial and g1t's pools pay for it.
11//! - **Paid, first month**: `LIMIT_PAID_START_MICROS` ($100) while the plan
12//! is in its first billing cycle.
13//! - **Paid, after**: twice what it has paid g1t once payments clear
14//! (`SETTLE_DAYS`), never less than the starting ceiling; after three
15//! steady months it follows the monthly spend, up to $10,000.
16//! - **Reviewed**: a ceiling g1t staff set by hand.
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays17//! - **Internal**: g1t's own workspaces, with none here: what their work
18//! costs g1t has a monthly budget instead (see `budget`).
Usage limits: unpaid usage can only go so far19//!
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look20//! A ceiling g1t granted (an approved request, or the owners' one-time
21//! raise) is a floor under the trust ceiling. Money paid in advance raises
22//! what can be used before work stops by the same amount, at once: it comes
23//! off what is owed before anything counts against the ceiling.
24//!
25//! Owners also set a monthly **spend limit** on what is charged. They may
26//! put it anywhere up to the highest ceiling the workspace has ever had,
27//! plus what is prepaid, without asking anyone; once per workspace they may
28//! raise it to twice that highest ceiling themselves. Past that, they ask
29//! (see `requests`), and g1t answers within one business day.
30//!
31//! Alerts go out at 50, 75, 90 and 100% of the plan's included usage, the
32//! spend limit and the ceiling, in the app and by email. At the ceiling or
33//! the spend limit, new work stops: no new sandboxes, builds or app
34//! requests until it is paid, raised, or the month turns. Runs already
Usage limits: unpaid usage can only go so far35//! under way finish.
36//!
37//! Usage counts at what it cost g1t or what it is charged, whichever is
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look38//! more. Test-mode payments are not money, so they do not raise trust.
Usage limits: unpaid usage can only go so far39
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index40use futures_util::future::{try_join, try_join5, try_join_all};
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look41use g1t_contracts::billing::{
Usage, Billing settings and prepaid AI credit; fixes from the UX audit42 BillingAccount, CheckLimitArgs, Limit, LimitArgs, LimitState, NotePendingArgs, PlanKind, SetBudgetArgs, SetSpendLimitArgs, Trust,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look43};
Usage limits: unpaid usage can only go so far44use g1t_contracts::time::rfc3339;
45use g1t_contracts::{FailureCode, Outcome, Role};
46use g1t_kit::now_ms;
47use serde::Deserialize;
48use worker::wasm_bindgen::JsValue;
49use worker::{Env, Result};
50
51use crate::features::dollars as dollars_plain;
52use crate::{Billing, members_only};
53
54/// The ceilings, from the billing service's variables.
55pub(crate) struct Ceilings {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look56 /// `LIMIT_NEW_MICROS`: a free workspace's.
Usage limits: unpaid usage can only go so far57 pub new: i64,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look58 /// `LIMIT_PAID_MIN_MICROS` and `LIMIT_PAID_MAX_MICROS`: the bounds of a
59 /// paid workspace's, from what it has paid.
Usage limits: unpaid usage can only go so far60 pub paid_min: i64,
61 pub paid_max: i64,
62}
63
64impl Ceilings {
65 pub(crate) fn from_env(env: &Env) -> Self {
66 let number = |name: &str, default: i64| {
67 env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok()).unwrap_or(default)
68 };
69 Ceilings {
70 new: number("LIMIT_NEW_MICROS", 3_000_000),
71 paid_min: number("LIMIT_PAID_MIN_MICROS", 25_000_000),
72 paid_max: number("LIMIT_PAID_MAX_MICROS", 1_000_000_000),
73 }
74 }
75
76 /// The ceiling for a workspace that has paid `paid` in live money.
77 pub(crate) fn for_paid(&self, paid: i64) -> i64 {
78 (paid * 2).clamp(self.paid_min, self.paid_max)
79 }
80}
81
82/// Where a workspace stands against its ceiling.
83pub(crate) fn state(exposure: i64, ceiling: Option<i64>) -> LimitState {
84 match ceiling {
85 Some(ceiling) if exposure >= ceiling => LimitState::Stopped,
86 Some(ceiling) if exposure * 5 >= ceiling * 4 => LimitState::Warning,
87 _ => LimitState::Ok,
88 }
89}
90
Two limits, real invoices, trust that grows by itself, sales signals91/// The automatic monthly spend limit's floor: $200.
92pub(crate) const DEFAULT_SPEND_MICROS: i64 = 200_000_000;
93/// Established workspaces' ceiling: three times their steady monthly
94/// spend, up to $10,000.
95const ESTABLISHED_FACTOR: i64 = 3;
96const ESTABLISHED_MAX_MICROS: i64 = 10_000_000_000;
97/// A month counts toward Established at this much spend or more.
98const ESTABLISHED_MONTH_MICROS: i64 = 20_000_000;
99/// Payments raise trust once this old: past the time most bad cards are
100/// caught.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look101pub(crate) const SETTLE_DAYS: u64 = 7;
Two limits, real invoices, trust that grows by itself, sales signals102
103/// The automatic spend limit: $200, or twice last month's spend.
104pub(crate) fn automatic_spend_limit(last_month_charged: i64) -> i64 {
105 DEFAULT_SPEND_MICROS.max(last_month_charged * 2)
106}
Billing accounts, terms and enterprises; g1t is no longer free107
Two limits, real invoices, trust that grows by itself, sales signals108/// An Established workspace's ceiling, from its last three months'
109/// charges, if each was steady enough.
110pub(crate) fn established_ceiling(months: &[i64]) -> Option<i64> {
111 if months.len() < 3 || months.iter().any(|m| *m < ESTABLISHED_MONTH_MICROS) {
112 return None;
113 }
114 let average = months.iter().sum::<i64>() / months.len() as i64;
115 Some((average * ESTABLISHED_FACTOR).min(ESTABLISHED_MAX_MICROS))
116}
117
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look118/// Days since 1970-01-01 of a `YYYY-MM-DD…` date, for comparing dates
119/// without a clock (Howard Hinnant's days-from-civil).
120pub(crate) fn days(date: &str) -> i64 {
121 let year: i64 = date.get(..4).and_then(|y| y.parse().ok()).unwrap_or(1970);
122 let month: i64 = date.get(5..7).and_then(|m| m.parse().ok()).unwrap_or(1);
123 let day: i64 = date.get(8..10).and_then(|d| d.parse().ok()).unwrap_or(1);
124 let y = if month <= 2 { year - 1 } else { year };
125 let era = y.div_euclid(400);
126 let yoe = y - era * 400;
127 let mp = (month + 9) % 12;
128 let doy = (153 * mp + 2) / 5 + day - 1;
129 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
130 era * 146_097 + doe - 719_468
131}
132
133/// Whether a plan that started at `started_at` is still in its first
134/// billing cycle: its paid period ends no more than a month after it
135/// started (a renewal moves the end a month on), or, with no period known,
136/// it started within the last 31 days.
137pub(crate) fn in_first_cycle(started_at: &str, period_end: Option<&str>, now: &str) -> bool {
138 match period_end {
139 Some(end) => days(end) - days(started_at) <= 32 && days(now) <= days(end),
140 None => days(now) - days(started_at) <= 31,
141 }
142}
143
144/// g1t's ceiling for a workspace on the plan: the starting one in its
145/// first month; after it, what it has paid (or its Established ceiling),
146/// never less than the starting one.
147pub(crate) fn paid_ceiling(ceilings: &Ceilings, start: i64, first_month: bool, paid: i64, established: Option<i64>) -> i64 {
148 if first_month {
149 return start;
150 }
151 let from_paid = if paid > 0 { ceilings.for_paid(paid) } else { 0 };
152 start.max(from_paid).max(established.unwrap_or(0))
153}
154
155/// What the owners may set their spend limit to without asking, and the
156/// one-time raise if it is still theirs to use: up to the highest ceiling
157/// ever (or the current one, if higher) plus what is prepaid; once, twice
158/// the highest ceiling.
159pub(crate) fn spend_bounds(ceiling: i64, max_ever: i64, prepaid: i64, raised: bool) -> (i64, Option<i64>) {
160 let highest = ceiling.max(max_ever);
161 let available = highest + prepaid.max(0);
162 let once = (!raised).then(|| (highest * 2 + prepaid.max(0)).max(available));
163 (available, once)
164}
165
166/// Whether `requested` is a spend limit the owners may set themselves.
167/// `Ok(true)` when it takes the one-time raise.
168pub(crate) fn self_serve(requested: i64, available: i64, once: Option<i64>, raise_once: bool) -> std::result::Result<bool, String> {
169 if requested < 0 {
170 return Err("A spend limit cannot be negative.".to_owned());
171 }
172 if requested <= available {
173 return Ok(false);
174 }
175 match once {
176 Some(once) if raise_once && requested <= once => Ok(true),
177 Some(once) if raise_once => Err(format!(
178 "The one-time raise goes up to {}. For more, ask g1t with Raise my limit; the answer comes within one business day.",
179 dollars_plain(once)
180 )),
181 Some(once) => Err(format!(
182 "You can set up to {} yourself, or use your one-time raise to go up to {}. For more, ask g1t with Raise my limit.",
183 dollars_plain(available),
184 dollars_plain(once)
185 )),
186 None => Err(format!(
187 "You can set up to {} yourself, and the one-time raise is used. For more, ask g1t with Raise my limit; the answer comes within one business day.",
188 dollars_plain(available)
189 )),
190 }
191}
192
193/// Which alert a measure has reached: 100, 90, 75, 50, or none (0).
194pub(crate) fn alert_level(used: i64, limit: i64) -> u32 {
Usage, Billing settings and prepaid AI credit; fixes from the UX audit195 alert_level_in(used, limit, &ALERT_LEVELS)
196}
197
198/// Every alert a budget can have, highest first.
199pub(crate) const ALERT_LEVELS: [u32; 4] = [100, 90, 75, 50];
200
201/// The highest of `levels` a measure has reached, or 0.
202pub(crate) fn alert_level_in(used: i64, limit: i64, levels: &[u32]) -> u32 {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look203 if limit <= 0 || used <= 0 {
204 return 0;
205 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit206 levels.iter().copied().filter(|level| used * 100 >= limit * i64::from(*level)).max().unwrap_or(0)
207}
208
209/// A budget's alerts as stored (`50,75,100`): every level when none were
210/// chosen, highest first.
211pub(crate) fn alert_levels(stored: Option<&str>) -> Vec<u32> {
212 let Some(stored) = stored else { return ALERT_LEVELS.to_vec() };
213 let mut levels: Vec<u32> = stored.split(',').filter_map(|l| l.trim().parse().ok()).filter(|l| ALERT_LEVELS.contains(l)).collect();
214 levels.sort_by(|a, b| b.cmp(a));
215 levels.dedup();
216 levels
217}
218
219/// Where spending stands against the budget: at 100% it stops work only
220/// when the budget pauses usage; otherwise it is a warning.
221pub(crate) fn budget_state(spent: i64, budget: Option<i64>, pause: bool) -> LimitState {
222 match state(spent, budget) {
223 LimitState::Stopped if !pause => LimitState::Warning,
224 other => other,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look225 }
226}
227
Usage, Billing settings and prepaid AI credit; fixes from the UX audit228/// Whether a budget webhook is an address g1t will post to: HTTPS, not
229/// g1t's own, at most 500 characters.
230pub(crate) fn webhook_ok(url: &str) -> bool {
231 let url = url.trim();
232 url.len() <= 500
233 && url.starts_with("https://")
234 && url.len() > "https://".len() + 3
235 && !url.contains(char::is_whitespace)
236 && !url["https://".len()..].split('/').next().is_some_and(|host| host == "g1t.sh" || host.ends_with(".g1t.sh") || host.starts_with("localhost") || host.starts_with("127."))
237}
238
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look239/// What is owed and what is prepaid, from this month's usage and payments
240/// and the balance the month started with (positive: paid in advance;
241/// negative: owed from before).
242pub(crate) fn exposure(used: i64, paid_month: i64, balance_before: i64) -> (i64, i64) {
243 let prepaid_in = balance_before.max(0);
244 let carried = (-balance_before).max(0);
245 let net = used - paid_month - prepaid_in;
246 (net.max(0) + carried, (-net).max(0))
247}
248
Usage limits: unpaid usage can only go so far249#[derive(Deserialize)]
250struct LimitRow {
251 spend_limit_micros: Option<i64>,
Two limits, real invoices, trust that grows by itself, sales signals252 #[serde(default)]
253 spend_limit_full: Option<i64>,
Billing accounts, terms and enterprises; g1t is no longer free254 autopay_failed_at: Option<String>,
255 autopay_error: Option<String>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look256 #[serde(default)]
257 max_ceiling_micros: Option<i64>,
258 #[serde(default)]
259 granted_ceiling_micros: Option<i64>,
260 #[serde(default)]
261 raised_at: Option<String>,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit262 #[serde(default)]
263 alert_levels: Option<String>,
264 #[serde(default)]
265 pause_at_limit: Option<i64>,
266 #[serde(default)]
267 budget_webhook: Option<String>,
Usage limits: unpaid usage can only go so far268}
269
270#[derive(Deserialize)]
271struct Month {
272 used: Option<i64>,
273 paid: Option<i64>,
274}
275
276#[derive(Deserialize)]
277struct Paid {
278 paid: Option<i64>,
279}
280
281impl Billing {
Billing accounts, terms and enterprises; g1t is no longer free282 /// The workspace's limit, worked out from the ledger of the account
283 /// that pays for it: its own, or its enterprise's, whose workspaces'
284 /// usage and payments count together.
Usage limits: unpaid usage can only go so far285 pub(crate) async fn limit_of(&self, workspace: &str) -> Result<Limit> {
286 let workspace = workspace.to_lowercase();
Billing accounts, terms and enterprises; g1t is no longer free287 let account = self.account_of(&workspace).await?;
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index288 let plan = self.plan_kind_for(&workspace, &account).await?;
289 self.limit_with(&workspace, &account, plan).await
290 }
291
292 /// The workspace's limit, from the account and plan already read for
293 /// it, so a caller that has them does not read them again.
294 pub(crate) async fn limit_with(&self, workspace: &str, account: &BillingAccount, plan: PlanKind) -> Result<Limit> {
295 let workspace = workspace.to_lowercase();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look296 let now = rfc3339(now_ms());
297 let month_start = format!("{}-01", &now[..7]);
Billing accounts, terms and enterprises; g1t is no longer free298 let marks = vec!["?"; account.workspaces.len().max(1)].join(", ");
299 let members: Vec<JsValue> = if account.workspaces.is_empty() {
300 vec![JsValue::from(workspace.as_str())]
301 } else {
302 account.workspaces.iter().map(|w| JsValue::from(w.as_str())).collect()
303 };
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index304 let row = async {
305 self.db
306 .prepare(
307 "SELECT spend_limit_micros, spend_limit_full, autopay_failed_at, autopay_error,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit308 max_ceiling_micros, granted_ceiling_micros, raised_at, alert_levels, pause_at_limit, budget_webhook
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index309 FROM limits WHERE workspace = ?",
310 )
311 .bind(&[workspace.as_str().into()])?
312 .first::<LimitRow>(None)
313 .await
314 };
Billing accounts, terms and enterprises; g1t is no longer free315 let mut with_month = members.clone();
316 with_month.push(month_start.as_str().into());
Usage limits: unpaid usage can only go so far317 // Each usage entry at its cost to g1t or its charge, whichever is
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look318 // more; on the workspace's own provider, only what g1t charged.
319 // What the plan's included usage, the trial, the open-source pool
320 // or g1t itself paid for is not unpaid: those are budgets already
321 // paid for.
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index322 let month = async {
323 self.db
324 .prepare(format!(
325 "SELECT
326 SUM(CASE WHEN kind = 'usage' THEN
327 CASE WHEN COALESCE(billed_to, 'g1t') = 'g1t'
328 THEN MAX(COALESCE(cost_micros, 0) - COALESCE(credit_micros, 0)
329 - COALESCE(trial_micros, 0) - COALESCE(oss_micros, 0)
330 - COALESCE(given_micros, 0),
331 -amount_micros)
332 ELSE -amount_micros END
333 END) AS used,
334 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS paid
335 FROM ledger WHERE workspace IN ({marks}) AND created_at >= ?"
336 ))
337 .bind(&with_month)?
338 .first::<Month>(None)
339 .await
340 };
Prices keep themselves current with what g1t pays341 // And what is metered but not charged until the month closes.
Billing accounts, terms and enterprises; g1t is no longer free342 let mut pending_args = members.clone();
343 pending_args.push(month_start[..7].into());
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index344 let pending = async {
345 Ok::<i64, worker::Error>(
346 self.db
347 .prepare(format!(
348 "SELECT SUM(charge_micros) AS paid FROM pending_usage WHERE workspace IN ({marks}) AND month = ?"
349 ))
350 .bind(&pending_args)?
351 .first::<Paid>(None)
352 .await?
353 .and_then(|row| row.paid)
354 .unwrap_or(0),
355 )
356 };
Usage limits: unpaid usage can only go so far357 // Test-mode payments are not money: they pay nothing off.
358 let live = self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look359 // The balance the month started with: owed from before (so a new
360 // month is not a fresh allowance for an account that never pays),
361 // or paid in advance. Credits g1t gave count; test-mode payments
362 // do not.
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace363 let mut before = members.clone();
364 before.push(month_start.as_str().into());
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index365 let balance_before = async {
366 Ok::<i64, worker::Error>(
367 self.db
368 .prepare(format!(
369 "SELECT SUM(CASE WHEN kind = 'usage' THEN amount_micros
370 WHEN kind = 'top_up' AND ({live} = 1 OR reference LIKE 'crd%') THEN amount_micros
371 ELSE 0 END) AS paid
372 FROM ledger WHERE workspace IN ({marks}) AND created_at < ?",
373 live = u8::from(live)
374 ))
375 .bind(&before)?
376 .first::<Paid>(None)
377 .await?
378 .and_then(|row| row.paid)
379 .unwrap_or(0),
380 )
381 };
382 // The trust ceiling, from what has been paid and how steadily. The
383 // first month is asked for beside it, since neither needs the other.
384 let trust = async {
385 Ok::<_, worker::Error>(match account.terms.kind {
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging386 _ if account.terms.full_discount() => (Trust::Internal, None, false),
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index387 _ if account.terms.ceiling_micros.is_some() => (Trust::Reviewed, account.terms.ceiling_micros, false),
388 _ => {
389 let standing = async {
390 let paid = self.live_paid(&members).await?;
391 let established = if paid > 0 { self.established(&members).await? } else { None };
392 Ok::<_, worker::Error>((paid, established))
393 };
394 let first = async {
395 if plan == PlanKind::Paid { self.first_month(&workspace).await } else { Ok(false) }
396 };
397 let ((paid, established), first_month) = try_join(standing, first).await?;
398 if plan == PlanKind::Free {
399 // Nothing on demand: only what a free workspace can owe.
400 (Trust::New, Some(self.ceilings.new), false)
401 } else {
402 let ceiling = paid_ceiling(&self.ceilings, self.plans.paid_start_micros, first_month, paid, established);
403 (if established.is_some() { Trust::Established } else { Trust::Paid }, Some(ceiling), first_month)
404 }
Billing accounts, terms and enterprises; g1t is no longer free405 }
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index406 })
Usage limits: unpaid usage can only go so far407 };
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index408 // This month's charges, and last month's, for the spend limit.
409 let charged = self.charged_months(&members, &month_start);
410 // None of these reads needs another's answer, so they go to D1 at
411 // once: the limit is on every signed-in page.
412 let ((row, month, pending, balance_before, (spent, last_month)), (trust, trust_ceiling, first_month)) =
413 try_join(try_join5(row, month, pending, balance_before, charged), trust).await?;
414 let (used, paid_month) = month.map_or((0, 0), |m| (m.used.unwrap_or(0), m.paid.unwrap_or(0)));
415 let used = used + pending;
416 let (exposure, prepaid) = exposure(used, if live { paid_month } else { 0 }, balance_before);
417
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look418 // A ceiling g1t granted is a floor under the trust ceiling.
419 let granted = row.as_ref().and_then(|row| row.granted_ceiling_micros);
420 let ceiling = trust_ceiling.map(|c| c.max(granted.unwrap_or(0)));
421 // The highest ceiling ever, kept as it rises.
422 let stored_max = row.as_ref().and_then(|row| row.max_ceiling_micros);
423 let max_ever = match (stored_max, ceiling) {
424 (Some(stored), Some(now)) => Some(stored.max(now)),
425 (stored, now) => stored.or(now),
426 };
427 if let (Some(max), true) = (max_ever, ceiling.is_some() && max_ever != stored_max && plan != PlanKind::Free) {
428 self.db
429 .prepare(
430 "INSERT INTO limits (workspace, max_ceiling_micros, updated_at) VALUES (?1, ?2, ?3)
431 ON CONFLICT (workspace) DO UPDATE SET max_ceiling_micros = MAX(COALESCE(max_ceiling_micros, 0), ?2), updated_at = ?3",
432 )
433 .bind(&[workspace.as_str().into(), (max as f64).into(), now.as_str().into()])?
434 .run()
435 .await?;
436 }
Two limits, real invoices, trust that grows by itself, sales signals437 let spent = spent + pending;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look438 let raised_at = row.as_ref().and_then(|row| row.raised_at.clone());
439 let self_serve = matches!(trust, Trust::New | Trust::Paid | Trust::Established) && plan != PlanKind::Free;
440 let (available, raise_once) = match (ceiling, self_serve) {
441 (Some(ceiling), true) => {
442 let (available, once) = spend_bounds(ceiling, max_ever.unwrap_or(ceiling), prepaid, raised_at.is_some());
443 (Some(available), once)
444 }
445 (ceiling, _) => (ceiling, None),
446 };
Two limits, real invoices, trust that grows by itself, sales signals447 // The owners' own monthly limit: theirs, none, or the automatic one
448 // ($200, or twice last month), which self-serve workspaces start on.
449 let chosen = row.as_ref().and_then(|row| row.spend_limit_micros);
450 let full = row.as_ref().and_then(|row| row.spend_limit_full).unwrap_or(0) == 1;
451 let default_spend_limit = chosen.is_none() && !full && self_serve;
452 let spend_limit = match (chosen, full) {
453 (Some(own), _) => Some(own),
454 (None, true) => None,
455 (None, false) if self_serve => Some(automatic_spend_limit(last_month)),
456 _ => None,
457 };
Billing accounts, terms and enterprises; g1t is no longer free458 // A card declined when g1t charged it at the limit stops work until
459 // it is paid; any payment clears it.
460 let declined = row.as_ref().and_then(|row| row.autopay_failed_at.clone().map(|at| (at, row.autopay_error.clone())));
Two limits, real invoices, trust that grows by itself, sales signals461 // Two limits: g1t's on what is unpaid, the owners' on what is spent.
462 let risk = state(exposure, ceiling);
Usage, Billing settings and prepaid AI credit; fixes from the UX audit463 // A budget that does not pause usage only alerts: at 100% it is a
464 // warning, never a stop. g1t's own ceiling still stops work.
465 let pause = row.as_ref().and_then(|row| row.pause_at_limit).unwrap_or(1) != 0;
466 let budget = budget_state(spent, spend_limit, pause);
Two limits, real invoices, trust that grows by itself, sales signals467 let over_budget = budget == LimitState::Stopped;
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept468 let state = if (declined.is_some() && exposure > 0) || risk == LimitState::Stopped || over_budget {
Two limits, real invoices, trust that grows by itself, sales signals469 LimitState::Stopped
470 } else if risk == LimitState::Warning || budget == LimitState::Warning {
471 LimitState::Warning
472 } else {
473 LimitState::Ok
Usage limits: unpaid usage can only go so far474 };
Billing accounts, terms and enterprises; g1t is no longer free475 let who = if account.kind == g1t_contracts::billing::AccountKind::Enterprise {
476 format!("The {} enterprise, which pays for {workspace},", account.name)
477 } else {
478 format!("The {workspace} workspace")
479 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look480 let billing = format!("/{workspace}/-/billing");
Usage limits: unpaid usage can only go so far481 let message = match state {
482 LimitState::Ok => None,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit483 LimitState::Warning if budget == LimitState::Warning && !pause => Some(format!(
484 "{who} has spent {} of its {} monthly budget. Usage does not pause at the budget; an owner can change that at {billing}.",
485 dollars_plain(spent),
486 dollars_plain(spend_limit.unwrap_or_default()),
487 )),
Two limits, real invoices, trust that grows by itself, sales signals488 LimitState::Warning if budget == LimitState::Warning => Some(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look489 "{who} has spent {} of its {} monthly spend limit. At the limit, its sandboxes, builds and apps stop until the month turns or an owner raises it at {billing}.",
Two limits, real invoices, trust that grows by itself, sales signals490 dollars_plain(spent),
491 dollars_plain(spend_limit.unwrap_or_default()),
492 )),
Usage limits: unpaid usage can only go so far493 LimitState::Warning => Some(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look494 "{who} has {} of usage not yet paid for, of the {} g1t allows. With a card on file g1t charges it now; prepaying at {billing} raises what it can use at once.",
Usage limits: unpaid usage can only go so far495 dollars_plain(exposure),
496 dollars_plain(ceiling.unwrap_or_default()),
497 )),
Billing accounts, terms and enterprises; g1t is no longer free498 LimitState::Stopped if declined.is_some() => Some(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look499 "{who} could not be charged for its usage ({}), so its sandboxes, builds and apps are stopped. An owner can pay with another card at {billing}.",
Billing accounts, terms and enterprises; g1t is no longer free500 declined.as_ref().and_then(|(_, error)| error.clone()).unwrap_or_else(|| "the card was declined".to_owned()),
501 )),
Two limits, real invoices, trust that grows by itself, sales signals502 LimitState::Stopped => Some(if over_budget {
Usage limits: unpaid usage can only go so far503 format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look504 "{who} reached its {} monthly spend limit, so its sandboxes, builds and apps are stopped until the month turns. An owner can raise it at {billing}.",
Two limits, real invoices, trust that grows by itself, sales signals505 dollars_plain(spend_limit.unwrap_or_default()),
Usage limits: unpaid usage can only go so far506 )
507 } else {
508 format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look509 "{who} reached its {} limit for usage not yet paid for, so its sandboxes, builds and apps are stopped. An owner can pay or prepay, or ask for a higher limit, at {billing}.",
Usage limits: unpaid usage can only go so far510 dollars_plain(ceiling.unwrap_or_default()),
511 )
512 }),
513 };
Two limits, real invoices, trust that grows by itself, sales signals514 let growth = match trust {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look515 Trust::New => Some("Free workspaces have no on-demand usage: the g1t plan starts at a $100 limit.".to_owned()),
516 Trust::Paid if first_month => Some(format!(
517 "Your first month's limit is {}. After it, the limit grows to twice what you have paid as payments clear ({SETTLE_DAYS} days), up to $1,000. Prepaying raises it at once, and you can ask for more.",
518 dollars_plain(self.plans.paid_start_micros)
519 )),
Two limits, real invoices, trust that grows by itself, sales signals520 Trust::Paid => Some(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look521 "Grows to twice what you have paid, as payments clear ({SETTLE_DAYS} days), up to $1,000. After three steady months it follows your monthly spend, up to $10,000, by itself. Prepaying raises it at once."
Two limits, real invoices, trust that grows by itself, sales signals522 )),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look523 Trust::Established => Some("Follows your monthly spend, up to $10,000, by itself. Prepaying raises it at once, and you can ask for more.".to_owned()),
Two limits, real invoices, trust that grows by itself, sales signals524 Trust::Reviewed | Trust::Internal => None,
525 };
Usage limits: unpaid usage can only go so far526 Ok(Limit {
527 workspace,
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index528 account: account.id.clone(),
529 account_name: account.name.clone(),
Two limits, real invoices, trust that grows by itself, sales signals530 spent_micros: spent,
531 default_spend_limit,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look532 available_micros: available,
Two limits, real invoices, trust that grows by itself, sales signals533 growth,
Usage limits: unpaid usage can only go so far534 trust,
535 exposure_micros: exposure,
536 ceiling_micros: ceiling,
537 trust_ceiling_micros: trust_ceiling,
538 spend_limit_micros: spend_limit,
539 state,
540 message,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look541 prepaid_micros: prepaid,
542 max_ceiling_micros: max_ever.filter(|_| plan != PlanKind::Free),
543 raise_once_micros: raise_once,
544 raised_at,
545 first_month,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit546 alert_levels: alert_levels(row.as_ref().and_then(|row| row.alert_levels.as_deref())),
547 pause_at_limit: pause,
548 budget_webhook: row.as_ref().and_then(|row| row.budget_webhook.clone()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look549 })
550 }
551
552 /// Whether the workspace's plan is in its first billing cycle.
553 pub(crate) async fn first_month(&self, workspace: &str) -> Result<bool> {
554 Ok(match self.plan_cycle(workspace).await? {
555 Some((started_at, period_end)) => in_first_cycle(&started_at, period_end.as_deref(), &rfc3339(now_ms())),
556 None => false,
Usage limits: unpaid usage can only go so far557 })
558 }
559
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look560 /// Real money the workspaces have paid g1t, cleared: usage payments and
561 /// the plan's price. Nothing in test mode, and credits g1t gave are not
562 /// payments.
563 pub(crate) async fn live_paid(&self, members: &[JsValue]) -> Result<i64> {
Usage limits: unpaid usage can only go so far564 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
565 return Ok(0);
566 }
Billing accounts, terms and enterprises; g1t is no longer free567 let marks = vec!["?"; members.len().max(1)].join(", ");
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look568 let settled = rfc3339(now_ms() - SETTLE_DAYS * 24 * 60 * 60 * 1000);
Usage limits: unpaid usage can only go so far569 Ok(self
570 .db
Billing accounts, terms and enterprises; g1t is no longer free571 .prepare(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look572 "SELECT
573 (SELECT COALESCE(SUM(amount_micros), 0) FROM ledger
574 WHERE workspace IN ({marks}) AND kind = 'top_up' AND reference NOT LIKE 'crd%'
575 AND (amount_micros < 0
576 OR (disputed = 0 AND COALESCE(funding, '') <> 'prepaid'
577 AND created_at <= '{settled}')))
578 + (SELECT COALESCE(SUM(amount_micros), 0) FROM plan_payments
579 WHERE workspace IN ({marks}) AND paid_at <= '{settled}') AS paid"
Billing accounts, terms and enterprises; g1t is no longer free580 ))
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look581 .bind(&[members, members].concat())?
Usage limits: unpaid usage can only go so far582 .first::<Paid>(None)
583 .await?
584 .and_then(|row| row.paid)
585 .unwrap_or(0))
586 }
587
Two limits, real invoices, trust that grows by itself, sales signals588 /// This month's charges and last month's, across the workspaces.
589 async fn charged_months(&self, members: &[JsValue], month_start: &str) -> Result<(i64, i64)> {
590 #[derive(Deserialize)]
591 struct Charged {
592 this_month: Option<i64>,
593 last_month: Option<i64>,
594 }
595 let last_start = format!("{}-01", previous_month(&month_start[..7]));
596 let marks = vec!["?"; members.len().max(1)].join(", ");
597 let row = self
598 .db
599 .prepare(format!(
600 "SELECT
601 -SUM(CASE WHEN created_at >= '{month_start}' THEN amount_micros END) AS this_month,
602 -SUM(CASE WHEN created_at >= '{last_start}' AND created_at < '{month_start}' THEN amount_micros END) AS last_month
603 FROM ledger WHERE kind = 'usage' AND workspace IN ({marks}) AND created_at >= '{last_start}'"
604 ))
605 .bind(members)?
606 .first::<Charged>(None)
607 .await?;
608 Ok(row.map_or((0, 0), |r| (r.this_month.unwrap_or(0).max(0), r.last_month.unwrap_or(0).max(0))))
609 }
610
611 /// An Established ceiling, if the workspaces have paid steadily: three
612 /// full months of real spend, each invoiced and paid, nothing declined
613 /// in 90 days and nothing ever disputed.
614 async fn established(&self, members: &[JsValue]) -> Result<Option<i64>> {
615 let marks = vec!["?"; members.len().max(1)].join(", ");
616 let now = rfc3339(now_ms());
617 let mut months = vec![];
618 let mut month = previous_month(&now[..7]);
619 for _ in 0..3 {
620 months.push(month.clone());
621 month = previous_month(&month);
622 }
623 #[derive(Deserialize)]
624 struct Count {
625 n: Option<i64>,
626 }
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index627 let troubled = async {
628 Ok::<i64, worker::Error>(
629 self.db
630 .prepare(format!(
631 "SELECT (SELECT COUNT(*) FROM ledger WHERE workspace IN ({marks}) AND disputed = 1)
632 + (SELECT COUNT(*) FROM limits WHERE workspace IN ({marks}) AND autopay_failed_at >= '{since}') AS n",
633 since = rfc3339(now_ms() - 90 * 24 * 60 * 60 * 1000)
634 ))
635 .bind(&[members, members].concat())?
636 .first::<Count>(None)
637 .await?
638 .and_then(|c| c.n)
639 .unwrap_or(0),
640 )
641 };
642 #[derive(Deserialize)]
643 struct Month {
644 charged: Option<i64>,
645 unpaid: Option<i64>,
Two limits, real invoices, trust that grows by itself, sales signals646 }
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index647 let read_month = |month: &String| {
Two limits, real invoices, trust that grows by itself, sales signals648 let next = {
649 let year: i32 = month[..4].parse().unwrap_or(1970);
650 let number: u32 = month[5..7].parse().unwrap_or(1);
651 if number == 12 { format!("{}-01", year + 1) } else { format!("{year}-{:02}", number + 1) }
652 };
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index653 let sql = format!(
654 "SELECT
655 (SELECT -SUM(amount_micros) FROM ledger WHERE kind = 'usage' AND workspace IN ({marks})
656 AND created_at >= '{month}-01' AND created_at < '{next}-01') AS charged,
657 (SELECT COUNT(*) FROM workspace_invoices WHERE workspace IN ({marks}) AND reason = 'month'
658 AND period = '{month}' AND status <> 'paid') AS unpaid"
659 );
660 async move { self.db.prepare(sql).bind(&[members, members].concat())?.first::<Month>(None).await }
661 };
662 // The check for trouble and the three months are read at once; the
663 // answer is the one reading them in turn and stopping early gives.
664 let (troubled, rows) = try_join(troubled, try_join_all(months.iter().map(read_month))).await?;
665 if troubled > 0 {
666 return Ok(None);
667 }
668 let mut charged = vec![];
669 for row in rows {
Two limits, real invoices, trust that grows by itself, sales signals670 let Some(row) = row else { return Ok(None) };
671 if row.unpaid.unwrap_or(0) > 0 {
672 return Ok(None);
673 }
674 charged.push(row.charged.unwrap_or(0));
675 }
676 Ok(established_ceiling(&charged))
677 }
678
Usage limits: unpaid usage can only go so far679 /// A refusal, with the reason, when the workspace's work is stopped.
680 /// None while billing is off: a g1t without payments has no limits.
681 pub(crate) async fn stopped<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
682 if self.stripe.is_none() {
683 return Ok(None);
684 }
685 let limit = self.limit_of(workspace).await?;
686 Ok((limit.state == LimitState::Stopped).then(|| {
687 Outcome::fail(
688 FailureCode::PaymentRequired,
689 limit.message.unwrap_or_else(|| "This workspace is over its limit.".to_owned()),
690 )
691 }))
692 }
693
694 pub(crate) async fn limit(&self, a: LimitArgs) -> Result<Outcome<Limit>> {
695 let workspace = a.workspace.to_lowercase();
696 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
697 return Ok(members_only());
698 }
699 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
700 }
701
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look702 /// What a source cost so far this month. `security`, `context`,
703 /// `storage` and `git` are charged by billing once the month is over
704 /// (see `storage`); `deployments` charges its own.
Prices keep themselves current with what g1t pays705 pub(crate) async fn note_pending(&self, a: NotePendingArgs) -> Result<bool> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents706 // The actions cache is the plan's to pay for; free workspaces are
707 // held to its quota instead.
708 if crate::storage::PLAN_ONLY.contains(&a.source.as_str()) && !self.has_plan(&a.workspace.to_lowercase()).await? {
709 return Ok(false);
710 }
Prices keep themselves current with what g1t pays711 let now = rfc3339(now_ms());
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas712 let detail = a.detail.as_deref().map(str::trim).filter(|d| !d.is_empty()).map(|d| d.chars().take(200).collect::<String>());
713 self.set_pending(&a.workspace, &a.source, &now[..7], a.cost_micros, detail.as_deref()).await?;
Prices keep themselves current with what g1t pays714 Ok(true)
715 }
716
Billing accounts, terms and enterprises; g1t is no longer free717 /// Charges the saved card of each workspace nearing its limit, for what
718 /// it owes, so that a workspace that pays never has its work stopped.
719 /// Only with live payments: test-mode payments are not money and lower
720 /// nothing. Not for a workspace's own spend limit, which means stop, nor
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look721 /// for enterprises, which are invoiced. A charge at the limit always
722 /// goes through, whatever the minimum charge.
Billing accounts, terms and enterprises; g1t is no longer free723 pub(crate) async fn autopay(&self) -> Result<()> {
Two limits, real invoices, trust that grows by itself, sales signals724 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
Billing accounts, terms and enterprises; g1t is no longer free725 return Ok(());
Two limits, real invoices, trust that grows by itself, sales signals726 }
Billing accounts, terms and enterprises; g1t is no longer free727 #[derive(Deserialize)]
728 struct Candidate {
729 workspace: String,
730 }
731 let month_start = format!("{}-01", &rfc3339(now_ms())[..7]);
Two limits, real invoices, trust that grows by itself, sales signals732 // With a card, and not already declined: a declined card waits for
733 // the owners, rather than being tried again every few minutes.
Billing accounts, terms and enterprises; g1t is no longer free734 let candidates = self
735 .db
736 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals737 "SELECT DISTINCT ledger.workspace AS workspace
Billing accounts, terms and enterprises; g1t is no longer free738 FROM ledger JOIN accounts ON accounts.workspace = ledger.workspace
Two limits, real invoices, trust that grows by itself, sales signals739 LEFT JOIN limits ON limits.workspace = ledger.workspace
740 WHERE ledger.kind = 'usage' AND ledger.created_at >= ? AND accounts.customer_id IS NOT NULL
741 AND limits.autopay_failed_at IS NULL",
Billing accounts, terms and enterprises; g1t is no longer free742 )
743 .bind(&[month_start.as_str().into()])?
744 .all()
745 .await?
746 .results::<Candidate>()?;
747 for candidate in candidates {
748 let limit = self.limit_of(&candidate.workspace).await?;
Two limits, real invoices, trust that grows by itself, sales signals749 // Near g1t's ceiling on what is unpaid; the spend limit is the
750 // owners' and stops work by itself, but what is owed is still owed.
751 let near = limit.ceiling_micros.is_some_and(|ceiling| limit.exposure_micros * 5 >= ceiling * 4);
752 if !near || limit.trust == Trust::Internal || limit.account.starts_with("ent_") {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace753 continue;
754 }
Two limits, real invoices, trust that grows by itself, sales signals755 let today = rfc3339(now_ms())[..10].to_owned();
756 match self.invoice_workspace(&candidate.workspace, "threshold", &today).await? {
757 Ok(_) => {}
758 Err(why) => worker::console_log!("{}: no threshold invoice: {why}", candidate.workspace),
Billing accounts, terms and enterprises; g1t is no longer free759 }
760 }
761 Ok(())
762 }
763
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace764 /// Closes last month for each workspace with a card on file: charges
765 /// what it owed when the month ended. Live payments only, once per
766 /// workspace and month; a declined card stops work until it is paid.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look767 /// Comped workspaces owe nothing, and enterprises are invoiced. Only
768 /// here does the minimum charge apply: less carries over.
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace769 pub(crate) async fn close_months(&self) -> Result<()> {
Two limits, real invoices, trust that grows by itself, sales signals770 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace771 return Ok(());
Two limits, real invoices, trust that grows by itself, sales signals772 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace773 let now = rfc3339(now_ms());
774 let month_start = format!("{}-01", &now[..7]);
775 let closing = previous_month(&now[..7]);
776 #[derive(Deserialize)]
777 struct Open {
778 workspace: String,
779 balance: Option<i64>,
780 }
781 let open = self
782 .db
783 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals784 "SELECT accounts.workspace AS workspace,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace785 (SELECT SUM(amount_micros) FROM ledger
786 WHERE ledger.workspace = accounts.workspace AND ledger.created_at < ?1) AS balance
787 FROM accounts
788 WHERE accounts.customer_id IS NOT NULL
789 AND NOT EXISTS (SELECT 1 FROM month_closes
790 WHERE month_closes.workspace = accounts.workspace AND month_closes.month = ?2)
791 LIMIT 20",
792 )
793 .bind(&[month_start.as_str().into(), closing.as_str().into()])?
794 .all()
795 .await?
796 .results::<Open>()?;
797 for account in open {
798 let record = |status: &str, amount: i64, payment: Option<&str>, error: Option<&str>| {
799 self.db
800 .prepare(
801 "INSERT OR IGNORE INTO month_closes (workspace, month, status, amount_micros, payment_id, error, closed_at)
802 VALUES (?, ?, ?, ?, ?, ?, ?)",
803 )
804 .bind(&[
805 account.workspace.as_str().into(),
806 closing.as_str().into(),
807 status.into(),
808 (amount as f64).into(),
809 crate::optional(payment),
810 crate::optional(error),
811 now.as_str().into(),
812 ])
813 };
814 let payer = self.account_of(&account.workspace).await?;
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging815 if payer.terms.full_discount() || payer.id.starts_with("ent_") {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace816 record("skipped", 0, None, None)?.run().await?;
817 continue;
818 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit819 // AI credit left at the month's end pays only for models: not
820 // money for anything else that is owed (ai.rs).
821 let ai_left = self.models_left_before(&account.workspace, &month_start).await?;
822 let owed = (ai_left - account.balance.unwrap_or(0)).max(0);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put823 if owed == 0 {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace824 record("nothing", 0, None, None)?.run().await?;
825 continue;
826 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put827 if !worth_charging(owed, self.plans.min_charge_micros) {
828 // Under the minimum charge: a card payment's fee would be
829 // too much of it. It stays owed and goes on the next
830 // invoice that reaches the minimum.
831 record("carried", owed, None, None)?.run().await?;
832 continue;
833 }
Two limits, real invoices, trust that grows by itself, sales signals834 match self.invoice_workspace(&account.workspace, "month", &closing).await? {
835 Ok(invoice) if invoice.status == "paid" => {
836 record("paid", invoice.amount_micros, Some(&invoice.invoice_id), None)?.run().await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace837 }
Two limits, real invoices, trust that grows by itself, sales signals838 Ok(invoice) => {
839 record("failed", invoice.amount_micros, Some(&invoice.invoice_id), Some("the card was declined"))?.run().await?;
840 }
841 Err(why) => {
842 record("nothing", 0, None, Some(&why))?.run().await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace843 }
844 }
845 }
846 Ok(())
847 }
848
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look849 /// Emails a workspace's owners as it passes 50, 75, 90 and 100% of its
850 /// plan's included usage, its spend limit and g1t's ceiling, once each a
851 /// month; when its card was declined; and when a spend spike paused it.
852 /// The same alerts show in the app (`entitlements`).
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace853 pub(crate) async fn warn_limits(&self, identity: &worker::Fetcher) -> Result<()> {
854 if self.stripe.is_none() {
855 return Ok(());
856 }
857 let now = rfc3339(now_ms());
858 let month = &now[..7];
859 #[derive(Deserialize)]
860 struct Candidate {
861 workspace: String,
862 }
863 let candidates = self
864 .db
865 .prepare(
866 "SELECT DISTINCT workspace FROM ledger WHERE kind = 'usage' AND created_at >= ?1
867 UNION SELECT workspace FROM limits WHERE autopay_failed_at IS NOT NULL",
868 )
869 .bind(&[format!("{month}-01").into()])?
870 .all()
871 .await?
872 .results::<Candidate>()?;
873 #[derive(Deserialize)]
874 struct Told {
875 autopay_failed_at: Option<String>,
876 declined_told_at: Option<String>,
877 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look878 #[derive(Deserialize)]
879 struct Sent {
880 meter: String,
881 level: Option<i64>,
882 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace883 for Candidate { workspace } in candidates {
884 let told = self
885 .db
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look886 .prepare("SELECT autopay_failed_at, declined_told_at FROM limits WHERE workspace = ?")
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace887 .bind(&[workspace.as_str().into()])?
888 .first::<Told>(None)
889 .await?;
890 let billing = format!("https://g1t.sh/{workspace}/-/billing");
891
892 // A declined card, once per decline.
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept893 if let Some(Told { autopay_failed_at: Some(failed), declined_told_at }) = &told
894 && declined_told_at.as_deref().is_none_or(|at| at < failed.as_str()) {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look895 let limit = self.limit_of(&workspace).await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace896 let sent = notify(
897 identity,
898 &workspace,
899 &format!("g1t: the card for {workspace} was declined"),
900 &limit.message.clone().unwrap_or_else(|| format!("g1t could not charge the card on file for {workspace}.")),
901 "Update the card",
902 &billing,
903 )
904 .await;
905 if sent {
906 self.db
907 .prepare("UPDATE limits SET declined_told_at = ? WHERE workspace = ?")
908 .bind(&[now.as_str().into(), workspace.as_str().into()])?
909 .run()
910 .await?;
911 }
912 }
913
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look914 // 50, 75, 90 and 100%, once each a month and meter: only the
915 // highest new level is emailed.
916 let alerts = self.alerts_for(&workspace).await?;
917 if alerts.is_empty() {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace918 continue;
919 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look920 let sent: Vec<Sent> = self
921 .db
922 .prepare("SELECT meter, MAX(level) AS level FROM alerts_sent WHERE workspace = ? AND month = ? GROUP BY meter")
923 .bind(&[workspace.as_str().into(), month.into()])?
924 .all()
925 .await?
926 .results::<Sent>()?;
927 for alert in alerts {
928 let already = sent.iter().find(|s| s.meter == alert.meter).and_then(|s| s.level).unwrap_or(0);
929 if i64::from(alert.level) <= already {
930 continue;
931 }
932 let subject = match alert.meter.as_str() {
933 "included" => format!("g1t: {workspace} has used {}% of its included usage", alert.level),
934 "spend_limit" => format!("g1t: {workspace} has used {}% of its spend limit", alert.level),
935 _ => format!("g1t: {workspace} has used {}% of its usage limit", alert.level),
936 };
Usage, Billing settings and prepaid AI credit; fixes from the UX audit937 // The budget's webhook hears of its alerts too, once each.
938 if alert.meter == "spend_limit"
939 && let Some(url) = self.budget_webhook_of(&workspace).await?
940 {
941 self.post_budget_webhook(&url, &workspace, alert.level, alert.used_micros, alert.limit_micros).await;
942 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look943 if notify(identity, &workspace, &subject, &alert.message, "Open billing", &billing).await {
944 self.db
945 .prepare(
946 "INSERT OR IGNORE INTO alerts_sent (workspace, month, meter, level, sent_at) VALUES (?1, ?2, ?3, ?4, ?5)",
947 )
948 .bind(&[workspace.as_str().into(), month.into(), alert.meter.as_str().into(), alert.level.into(), now.as_str().into()])?
949 .run()
950 .await?;
951 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace952 }
953 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look954 self.tell_spikes(identity).await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace955 Ok(())
956 }
957
Usage limits: unpaid usage can only go so far958 pub(crate) async fn check_limit(&self, a: CheckLimitArgs) -> Result<Outcome<Limit>> {
959 Ok(Outcome::Ok(self.limit_of(&a.workspace).await?))
960 }
961
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look962 /// The owners' spend limit: anywhere up to what is available without
963 /// asking; once, up to twice the highest ceiling (`raise_once`), which
964 /// also raises g1t's ceiling to match.
Usage limits: unpaid usage can only go so far965 pub(crate) async fn set_spend_limit(&self, a: SetSpendLimitArgs) -> Result<Outcome<Limit>> {
966 let workspace = a.workspace.to_lowercase();
967 if a.actor.role_in(&workspace) != Some(Role::Owner) {
968 return Ok(Outcome::fail(
969 FailureCode::Forbidden,
970 "Only an owner can set the workspace's spend limit.",
971 ));
972 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look973 let before = self.limit_of(&workspace).await?;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit974 // A free workspace has no on-demand usage to limit: its ceiling is
975 // only what it can owe for storage, and no raise applies to it.
976 if before.trust == Trust::New {
977 return Ok(Outcome::fail(
978 FailureCode::Conflict,
979 format!("{workspace} is not on the g1t plan, so it has no usage to put a spend limit on. The plan starts with a {} limit for its first month.", dollars_plain(self.plans.paid_start_micros)),
980 ));
981 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look982 let mut raising = false;
983 if let (Some(requested), false) = (a.spend_limit_micros, a.use_full_limit) {
984 match (before.available_micros, matches!(before.trust, Trust::Internal | Trust::Reviewed)) {
985 (_, true) | (None, _) => {
986 if requested < 0 {
987 return Ok(Outcome::fail(FailureCode::Invalid, "A spend limit cannot be negative."));
988 }
989 }
990 (Some(available), false) => match self_serve(requested, available, before.raise_once_micros, a.raise_once) {
991 Ok(uses_raise) => raising = uses_raise,
992 Err(why) => return Ok(Outcome::fail(FailureCode::Invalid, why)),
993 },
994 }
Usage limits: unpaid usage can only go so far995 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look996 let now = rfc3339(now_ms());
Two limits, real invoices, trust that grows by itself, sales signals997 let limit = if a.use_full_limit { JsValue::NULL } else { a.spend_limit_micros.map_or(JsValue::NULL, |limit| (limit as f64).into()) };
Usage limits: unpaid usage can only go so far998 self.db
999 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals1000 "INSERT INTO limits (workspace, spend_limit_micros, spend_limit_full, updated_at) VALUES (?1, ?2, ?3, ?4)
1001 ON CONFLICT (workspace) DO UPDATE SET spend_limit_micros = ?2, spend_limit_full = ?3, updated_at = ?4",
Usage limits: unpaid usage can only go so far1002 )
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1003 .bind(&[workspace.as_str().into(), limit, (if a.use_full_limit { 1 } else { 0 }).into(), now.as_str().into()])?
Usage limits: unpaid usage can only go so far1004 .run()
1005 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1006 if raising {
1007 let raised = a.spend_limit_micros.unwrap_or_default();
1008 // The ceiling rises with it, once.
1009 self.db
1010 .prepare(
1011 "UPDATE limits SET granted_ceiling_micros = MAX(COALESCE(granted_ceiling_micros, 0), ?2),
1012 raised_at = ?3, updated_at = ?3 WHERE workspace = ?1 AND raised_at IS NULL",
1013 )
1014 .bind(&[workspace.as_str().into(), (raised as f64).into(), now.as_str().into()])?
1015 .run()
1016 .await?;
1017 let account = self.account_of(&workspace).await?;
1018 self.audit(&account.id, "raise_once", &format!("{workspace} used its one-time raise: {}", dollars_plain(raised)), &a.actor.username)
1019 .await?;
1020 }
Usage limits: unpaid usage can only go so far1021 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
1022 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1023
1024 /// `set_budget`: the owners' monthly budget on usage after what the
1025 /// plan includes: the spend limit (set as `set_spend_limit` sets it,
1026 /// with the same bounds), which alerts to send, whether usage pauses at
1027 /// 100%, and a webhook told at each alert.
1028 pub(crate) async fn set_budget(&self, a: SetBudgetArgs) -> Result<Outcome<Limit>> {
1029 let workspace = a.workspace.to_lowercase();
1030 if a.actor.role_in(&workspace) != Some(Role::Owner) {
1031 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can set the workspace's budget."));
1032 }
1033 if a.alerts.iter().any(|level| !ALERT_LEVELS.contains(level)) {
1034 return Ok(Outcome::fail(FailureCode::Invalid, "Alerts are at 50, 75, 90 or 100% of the budget."));
1035 }
1036 let webhook = a.webhook.as_deref().map(str::trim).filter(|url| !url.is_empty());
1037 if let Some(url) = webhook
1038 && !webhook_ok(url)
1039 {
1040 return Ok(Outcome::fail(FailureCode::Invalid, "The webhook is an https:// address of your own, at most 500 characters."));
1041 }
1042 if !a.keep_limit {
1043 let set = self
1044 .set_spend_limit(SetSpendLimitArgs {
1045 actor: a.actor.clone(),
1046 workspace: workspace.clone(),
1047 spend_limit_micros: a.amount_micros,
1048 use_full_limit: false,
1049 raise_once: false,
1050 })
1051 .await?;
1052 if let Outcome::Fail(failure) = set {
1053 return Ok(Outcome::Fail(failure));
1054 }
1055 } else if self.limit_of(&workspace).await?.trust == Trust::New {
1056 return Ok(Outcome::fail(FailureCode::Conflict, format!("{workspace} is not on the g1t plan, so it has no budget to alert on.")));
1057 } else {
1058 // The row the alerts are kept on, if the workspace has none yet.
1059 self.db
1060 .prepare("INSERT OR IGNORE INTO limits (workspace, updated_at) VALUES (?, ?)")
1061 .bind(&[workspace.as_str().into(), rfc3339(now_ms()).into()])?
1062 .run()
1063 .await?;
1064 }
1065 let mut levels = a.alerts.clone();
1066 levels.sort_by(|x, y| y.cmp(x));
1067 levels.dedup();
1068 let stored = levels.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
1069 self.db
1070 .prepare(
1071 "UPDATE limits SET alert_levels = ?2, pause_at_limit = ?3, budget_webhook = ?4, updated_at = ?5 WHERE workspace = ?1",
1072 )
1073 .bind(&[
1074 workspace.as_str().into(),
1075 stored.as_str().into(),
1076 i32::from(a.pause_at_limit).into(),
1077 crate::optional(webhook),
1078 rfc3339(now_ms()).into(),
1079 ])?
1080 .run()
1081 .await?;
1082 let account = self.account_of(&workspace).await?;
1083 self.audit(
1084 &account.id,
1085 "budget",
1086 &format!(
1087 "{workspace}: budget {}, alerts at {}, {}{}",
1088 a.amount_micros.map_or_else(|| "automatic".to_owned(), dollars_plain),
1089 if stored.is_empty() { "none".to_owned() } else { format!("{stored}%") },
1090 if a.pause_at_limit { "pauses usage at 100%" } else { "alerts only" },
1091 if webhook.is_some() { ", with a webhook" } else { "" }
1092 ),
1093 &a.actor.username,
1094 )
1095 .await?;
1096 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
1097 }
1098
1099
1100 /// The budget's webhook, if the workspace has one.
1101 async fn budget_webhook_of(&self, workspace: &str) -> Result<Option<String>> {
1102 #[derive(Deserialize)]
1103 struct Row {
1104 budget_webhook: Option<String>,
1105 }
1106 Ok(self
1107 .db
1108 .prepare("SELECT budget_webhook FROM limits WHERE workspace = ?")
1109 .bind(&[workspace.into()])?
1110 .first::<Row>(None)
1111 .await?
1112 .and_then(|row| row.budget_webhook)
1113 .filter(|url| webhook_ok(url)))
1114 }
1115 /// Posts a budget alert to the workspace's webhook, if it has one.
1116 /// Never fails the alert: a receiver that does not answer is logged.
1117 pub(crate) async fn post_budget_webhook(&self, url: &str, workspace: &str, level: u32, spent: i64, budget: i64) {
1118 let body = serde_json::json!({
1119 "event": "budget.alert",
1120 "workspace": workspace,
1121 "level_percent": level,
1122 "spent_micros": spent,
1123 "budget_micros": budget,
1124 "sent_at": rfc3339(now_ms()),
1125 });
1126 let headers = worker::Headers::new();
1127 let _ = headers.set("content-type", "application/json");
1128 let _ = headers.set("user-agent", "g1t-billing");
1129 let mut init = worker::RequestInit::new();
1130 init.with_method(worker::Method::Post).with_headers(headers).with_body(Some(body.to_string().into()));
1131 let sent = match worker::Request::new_with_init(url, &init) {
1132 Ok(request) => worker::Fetch::Request(request).send().await.map(|r| r.status_code()),
1133 Err(error) => Err(error),
1134 };
1135 match sent {
1136 Ok(status) if (200..300).contains(&status) => {}
1137 Ok(status) => worker::console_warn!("{workspace}'s budget webhook answered {status}"),
1138 Err(error) => worker::console_warn!("{workspace}'s budget webhook could not be reached: {error}"),
1139 }
1140 }
Usage limits: unpaid usage can only go so far1141}
1142
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1143/// Whether `owed` is enough to charge a card when a month closes: at least
1144/// the minimum charge (`MIN_CHARGE_MICROS`). Less carries over to the next
1145/// invoice. Charges at a limit do not ask.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1146pub(crate) fn worth_charging(owed: i64, min_charge: i64) -> bool {
1147 owed > 0 && owed >= min_charge
1148}
1149
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1150/// Emails the workspace's owners through identity. False if nothing was sent.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1151pub(crate) async fn notify(identity: &worker::Fetcher, workspace: &str, subject: &str, intro: &str, action: &str, link: &str) -> bool {
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1152 let footer = "You get this because you own this workspace on g1t. Limits and alerts are explained at https://docs.g1t.sh/guides/usage-and-billing/#limits";
1153 notify_with(identity, workspace, subject, intro, action, link, footer).await
1154}
1155
1156/// `notify`, with a footer of its own.
1157pub(crate) async fn notify_with(
1158 identity: &worker::Fetcher,
1159 workspace: &str,
1160 subject: &str,
1161 intro: &str,
1162 action: &str,
1163 link: &str,
1164 footer: &str,
1165) -> bool {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1166 let args = g1t_contracts::identity::NotifyOwnersArgs {
1167 workspace: workspace.to_owned(),
1168 subject: subject.to_owned(),
1169 intro: intro.to_owned(),
1170 action: action.to_owned(),
1171 link: link.to_owned(),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1172 footer: footer.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1173 };
1174 match g1t_kit::call::<_, u32>(identity, "notify_owners", &args).await {
1175 Ok(sent) => sent > 0,
1176 Err(error) => {
1177 worker::console_error!("could not tell {workspace}'s owners: {error}");
1178 false
1179 }
1180 }
1181}
1182
1183/// `2026-09` for `2026-10`, and `2025-12` for `2026-01`.
1184pub(crate) fn previous_month(month: &str) -> String {
1185 let year: i32 = month[..4].parse().unwrap_or(1970);
1186 let number: u32 = month[5..7].parse().unwrap_or(1);
1187 if number == 1 {
1188 format!("{}-12", year - 1)
1189 } else {
1190 format!("{year}-{:02}", number - 1)
1191 }
1192}
1193
Usage limits: unpaid usage can only go so far1194#[cfg(test)]
1195mod tests {
1196 use super::*;
1197
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1198 #[test]
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1199 fn a_budget_alerts_at_the_levels_chosen_and_pauses_only_if_asked() {
1200 // Every level when none were chosen; the chosen ones, highest first.
1201 assert_eq!(alert_levels(None), [100, 90, 75, 50]);
1202 assert_eq!(alert_levels(Some("50,100,75")), [100, 75, 50]);
1203 assert_eq!(alert_levels(Some("")), Vec::<u32>::new());
1204 assert_eq!(alert_levels(Some("40, 50")), [50]);
1205 // The highest chosen level reached.
1206 assert_eq!(alert_level_in(80, 100, &[100, 75, 50]), 75);
1207 assert_eq!(alert_level_in(80, 100, &[100, 90]), 0);
1208 assert_eq!(alert_level_in(100, 100, &[100, 75, 50]), 100);
1209 assert_eq!(alert_level_in(10, 0, &[50]), 0);
1210 // At 100%: a stop when the budget pauses usage, else a warning.
1211 assert_eq!(budget_state(100, Some(100), true), LimitState::Stopped);
1212 assert_eq!(budget_state(100, Some(100), false), LimitState::Warning);
1213 assert_eq!(budget_state(10, Some(100), false), LimitState::Ok);
1214 assert_eq!(budget_state(10, None, true), LimitState::Ok);
1215 }
1216
1217 #[test]
1218 fn a_budget_webhook_is_someone_elses_https_address() {
1219 assert!(webhook_ok("https://hooks.acme.test/g1t"));
1220 assert!(!webhook_ok("http://hooks.acme.test/g1t"));
1221 assert!(!webhook_ok("https://g1t.sh/x"));
1222 assert!(!webhook_ok("https://api.g1t.sh/x"));
1223 assert!(!webhook_ok("https://localhost:3000/x"));
1224 assert!(!webhook_ok("https://a b.test/"));
1225 assert!(!webhook_ok(&format!("https://acme.test/{}", "x".repeat(600))));
1226 }
1227 #[test]
Two limits, real invoices, trust that grows by itself, sales signals1228 fn the_automatic_spend_limit_follows_last_month() {
1229 assert_eq!(automatic_spend_limit(0), 200_000_000);
1230 assert_eq!(automatic_spend_limit(50_000_000), 200_000_000);
1231 assert_eq!(automatic_spend_limit(900_000_000), 1_800_000_000);
1232 }
1233
1234 #[test]
1235 fn three_steady_months_make_a_workspace_established() {
1236 assert_eq!(established_ceiling(&[900_000_000, 850_000_000, 950_000_000]), Some(2_700_000_000));
1237 assert_eq!(established_ceiling(&[5_000_000_000, 5_000_000_000, 5_000_000_000]), Some(10_000_000_000));
1238 assert_eq!(established_ceiling(&[900_000_000, 10_000_000, 950_000_000]), None);
1239 assert_eq!(established_ceiling(&[900_000_000, 900_000_000]), None);
1240 }
1241
1242 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1243 fn alerts_come_at_half_three_quarters_ninety_and_the_limit() {
1244 assert_eq!(alert_level(0, 10_000_000), 0);
1245 assert_eq!(alert_level(4_999_999, 10_000_000), 0);
1246 assert_eq!(alert_level(5_000_000, 10_000_000), 50);
1247 assert_eq!(alert_level(7_500_000, 10_000_000), 75);
1248 assert_eq!(alert_level(8_999_999, 10_000_000), 75);
1249 assert_eq!(alert_level(9_000_000, 10_000_000), 90);
1250 assert_eq!(alert_level(10_000_000, 10_000_000), 100);
1251 assert_eq!(alert_level(25_000_000, 10_000_000), 100);
1252 // Nothing to measure against: no alert.
1253 assert_eq!(alert_level(5, 0), 0);
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1254 }
1255
1256 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1257 fn amounts_under_the_minimum_carry_over_only_at_the_month_close() {
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1258 let min = 5_000_000;
1259 assert!(!worth_charging(0, min));
1260 assert!(!worth_charging(4_990_000, min));
1261 assert!(worth_charging(5_000_000, min));
1262 assert!(worth_charging(12_000_000, min));
1263 // $3 carried from last month and $2.50 this month: charged together.
1264 let carried = 3_000_000;
1265 assert!(!worth_charging(carried, min));
1266 assert!(worth_charging(carried + 2_500_000, min));
1267 }
1268
1269 #[test]
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1270 fn the_month_before_wraps_the_year() {
1271 assert_eq!(previous_month("2026-10"), "2026-09");
1272 assert_eq!(previous_month("2026-01"), "2025-12");
1273 }
1274
Usage limits: unpaid usage can only go so far1275 fn ceilings() -> Ceilings {
Billing accounts, terms and enterprises; g1t is no longer free1276 Ceilings { new: 3_000_000, paid_min: 25_000_000, paid_max: 1_000_000_000 }
Usage limits: unpaid usage can only go so far1277 }
1278
1279 #[test]
1280 fn trust_grows_with_what_was_paid_within_bounds() {
1281 assert_eq!(ceilings().for_paid(5_000_000), 25_000_000);
1282 assert_eq!(ceilings().for_paid(100_000_000), 200_000_000);
1283 assert_eq!(ceilings().for_paid(10_000_000_000), 1_000_000_000);
1284 }
1285
1286 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1287 fn a_new_paid_workspace_starts_at_a_hundred_dollars_and_only_goes_up() {
1288 let start = 100_000_000;
1289 // The first month: the starting ceiling, whatever was paid.
1290 assert_eq!(paid_ceiling(&ceilings(), start, true, 900_000_000, None), start);
1291 // After it, with little paid: never below the start.
1292 assert_eq!(paid_ceiling(&ceilings(), start, false, 20_000_000, None), start);
1293 assert_eq!(paid_ceiling(&ceilings(), start, false, 0, None), start);
1294 // Payments that cleared raise it: twice what was paid.
1295 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, None), 600_000_000);
1296 // Established follows the monthly spend.
1297 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, Some(2_700_000_000)), 2_700_000_000);
1298 }
1299
1300 #[test]
1301 fn the_first_billing_cycle_is_the_first_month() {
1302 // A plan that started on the 5th, paid through the 5th of next month.
1303 assert!(in_first_cycle("2026-10-05T10:00:00Z", Some("2026-11-05T10:00:00Z"), "2026-10-20T00:00:00Z"));
1304 // Renewed: the period now ends two months after the start.
1305 assert!(!in_first_cycle("2026-10-05T10:00:00Z", Some("2026-12-05T10:00:00Z"), "2026-11-20T00:00:00Z"));
1306 // No period known yet: the first 31 days.
1307 assert!(in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-04T00:00:00Z"));
1308 assert!(!in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-10T00:00:00Z"));
1309 // Day counting is exact across months and years.
1310 assert_eq!(days("1970-01-01"), 0);
1311 assert_eq!(days("2026-11-01") - days("2026-10-01"), 31);
1312 assert_eq!(days("2028-03-01") - days("2028-02-28"), 2);
1313 assert_eq!(days("2027-01-01") - days("2026-12-31"), 1);
1314 }
1315
1316 #[test]
1317 fn owners_set_their_limit_up_to_the_highest_ceiling_without_asking() {
1318 // First month at $100; the highest ever is $100.
1319 let (available, once) = spend_bounds(100_000_000, 100_000_000, 0, false);
1320 assert_eq!(available, 100_000_000);
1321 assert_eq!(once, Some(200_000_000));
1322 assert_eq!(self_serve(80_000_000, available, once, false), Ok(false));
1323 assert_eq!(self_serve(100_000_000, available, once, false), Ok(false));
1324 // Above it without the raise: refused, saying what to do.
1325 assert!(self_serve(150_000_000, available, once, false).unwrap_err().contains("one-time raise"));
1326 // With the raise: up to twice the highest ceiling, once.
1327 assert_eq!(self_serve(200_000_000, available, once, true), Ok(true));
1328 assert!(self_serve(200_000_001, available, once, true).unwrap_err().contains("Raise my limit"));
1329 // Once used, it is gone.
1330 let (available, once) = spend_bounds(200_000_000, 200_000_000, 0, true);
1331 assert_eq!(once, None);
1332 assert_eq!(self_serve(200_000_000, available, once, false), Ok(false));
1333 assert!(self_serve(300_000_000, available, once, true).unwrap_err().contains("is used"));
1334 // A ceiling that came down still leaves the highest one available.
1335 let (available, _) = spend_bounds(100_000_000, 400_000_000, 0, true);
1336 assert_eq!(available, 400_000_000);
1337 assert!(self_serve(-1, available, None, false).is_err());
1338 }
1339
1340 #[test]
1341 fn prepaying_raises_what_can_be_used_at_once() {
1342 // $500 prepaid this month, $120 used: nothing owed, $380 left.
1343 assert_eq!(exposure(120_000_000, 500_000_000, 0), (0, 380_000_000));
1344 // Prepaid last month and carried in.
1345 assert_eq!(exposure(120_000_000, 0, 500_000_000), (0, 380_000_000));
1346 // Used past the prepayment: the rest is owed.
1347 assert_eq!(exposure(620_000_000, 500_000_000, 0), (120_000_000, 0));
1348 // Owed from before adds to this month's.
1349 assert_eq!(exposure(10_000_000, 0, -4_000_000), (14_000_000, 0));
1350 // With a $100 ceiling and $500 prepaid, work stops at $600 of use,
1351 // not at $100.
1352 let ceiling = 100_000_000;
1353 assert_eq!(state(exposure(599_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Warning);
1354 assert_eq!(state(exposure(600_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Stopped);
1355 // And the owners may set their spend limit that much higher.
1356 assert_eq!(spend_bounds(ceiling, ceiling, 500_000_000, true).0, 600_000_000);
1357 }
1358
1359 #[test]
Usage limits: unpaid usage can only go so far1360 fn work_warns_at_eighty_percent_and_stops_at_the_ceiling() {
1361 assert_eq!(state(0, Some(100)), LimitState::Ok);
1362 assert_eq!(state(79, Some(100)), LimitState::Ok);
1363 assert_eq!(state(80, Some(100)), LimitState::Warning);
1364 assert_eq!(state(100, Some(100)), LimitState::Stopped);
1365 assert_eq!(state(1_000_000, None), LimitState::Ok);
1366 }
1367}