g1t/services/billing/src/limits.rs

1,142 lines54,530 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::{
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 index42 BillingAccount, CheckLimitArgs, Limit, LimitArgs, LimitState, NotePendingArgs, PlanKind, SetSpendLimitArgs, TermsKind, 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 {
195 if limit <= 0 || used <= 0 {
196 return 0;
197 }
198 for level in [100u32, 90, 75, 50] {
199 if used * 100 >= limit * i64::from(level) {
200 return level;
201 }
202 }
203 0
204}
205
206/// What is owed and what is prepaid, from this month's usage and payments
207/// and the balance the month started with (positive: paid in advance;
208/// negative: owed from before).
209pub(crate) fn exposure(used: i64, paid_month: i64, balance_before: i64) -> (i64, i64) {
210 let prepaid_in = balance_before.max(0);
211 let carried = (-balance_before).max(0);
212 let net = used - paid_month - prepaid_in;
213 (net.max(0) + carried, (-net).max(0))
214}
215
Usage limits: unpaid usage can only go so far216#[derive(Deserialize)]
217struct LimitRow {
218 spend_limit_micros: Option<i64>,
Two limits, real invoices, trust that grows by itself, sales signals219 #[serde(default)]
220 spend_limit_full: Option<i64>,
Billing accounts, terms and enterprises; g1t is no longer free221 autopay_failed_at: Option<String>,
222 autopay_error: Option<String>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look223 #[serde(default)]
224 max_ceiling_micros: Option<i64>,
225 #[serde(default)]
226 granted_ceiling_micros: Option<i64>,
227 #[serde(default)]
228 raised_at: Option<String>,
Usage limits: unpaid usage can only go so far229}
230
231#[derive(Deserialize)]
232struct Month {
233 used: Option<i64>,
234 paid: Option<i64>,
235}
236
237#[derive(Deserialize)]
238struct Paid {
239 paid: Option<i64>,
240}
241
242impl Billing {
Billing accounts, terms and enterprises; g1t is no longer free243 /// The workspace's limit, worked out from the ledger of the account
244 /// that pays for it: its own, or its enterprise's, whose workspaces'
245 /// usage and payments count together.
Usage limits: unpaid usage can only go so far246 pub(crate) async fn limit_of(&self, workspace: &str) -> Result<Limit> {
247 let workspace = workspace.to_lowercase();
Billing accounts, terms and enterprises; g1t is no longer free248 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 index249 let plan = self.plan_kind_for(&workspace, &account).await?;
250 self.limit_with(&workspace, &account, plan).await
251 }
252
253 /// The workspace's limit, from the account and plan already read for
254 /// it, so a caller that has them does not read them again.
255 pub(crate) async fn limit_with(&self, workspace: &str, account: &BillingAccount, plan: PlanKind) -> Result<Limit> {
256 let workspace = workspace.to_lowercase();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look257 let now = rfc3339(now_ms());
258 let month_start = format!("{}-01", &now[..7]);
Billing accounts, terms and enterprises; g1t is no longer free259 let marks = vec!["?"; account.workspaces.len().max(1)].join(", ");
260 let members: Vec<JsValue> = if account.workspaces.is_empty() {
261 vec![JsValue::from(workspace.as_str())]
262 } else {
263 account.workspaces.iter().map(|w| JsValue::from(w.as_str())).collect()
264 };
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 index265 let row = async {
266 self.db
267 .prepare(
268 "SELECT spend_limit_micros, spend_limit_full, autopay_failed_at, autopay_error,
269 max_ceiling_micros, granted_ceiling_micros, raised_at
270 FROM limits WHERE workspace = ?",
271 )
272 .bind(&[workspace.as_str().into()])?
273 .first::<LimitRow>(None)
274 .await
275 };
Billing accounts, terms and enterprises; g1t is no longer free276 let mut with_month = members.clone();
277 with_month.push(month_start.as_str().into());
Usage limits: unpaid usage can only go so far278 // 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 look279 // more; on the workspace's own provider, only what g1t charged.
280 // What the plan's included usage, the trial, the open-source pool
281 // or g1t itself paid for is not unpaid: those are budgets already
282 // 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 index283 let month = async {
284 self.db
285 .prepare(format!(
286 "SELECT
287 SUM(CASE WHEN kind = 'usage' THEN
288 CASE WHEN COALESCE(billed_to, 'g1t') = 'g1t'
289 THEN MAX(COALESCE(cost_micros, 0) - COALESCE(credit_micros, 0)
290 - COALESCE(trial_micros, 0) - COALESCE(oss_micros, 0)
291 - COALESCE(given_micros, 0),
292 -amount_micros)
293 ELSE -amount_micros END
294 END) AS used,
295 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS paid
296 FROM ledger WHERE workspace IN ({marks}) AND created_at >= ?"
297 ))
298 .bind(&with_month)?
299 .first::<Month>(None)
300 .await
301 };
Prices keep themselves current with what g1t pays302 // And what is metered but not charged until the month closes.
Billing accounts, terms and enterprises; g1t is no longer free303 let mut pending_args = members.clone();
304 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 index305 let pending = async {
306 Ok::<i64, worker::Error>(
307 self.db
308 .prepare(format!(
309 "SELECT SUM(charge_micros) AS paid FROM pending_usage WHERE workspace IN ({marks}) AND month = ?"
310 ))
311 .bind(&pending_args)?
312 .first::<Paid>(None)
313 .await?
314 .and_then(|row| row.paid)
315 .unwrap_or(0),
316 )
317 };
Usage limits: unpaid usage can only go so far318 // Test-mode payments are not money: they pay nothing off.
319 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 look320 // The balance the month started with: owed from before (so a new
321 // month is not a fresh allowance for an account that never pays),
322 // or paid in advance. Credits g1t gave count; test-mode payments
323 // do not.
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace324 let mut before = members.clone();
325 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 index326 let balance_before = async {
327 Ok::<i64, worker::Error>(
328 self.db
329 .prepare(format!(
330 "SELECT SUM(CASE WHEN kind = 'usage' THEN amount_micros
331 WHEN kind = 'top_up' AND ({live} = 1 OR reference LIKE 'crd%') THEN amount_micros
332 ELSE 0 END) AS paid
333 FROM ledger WHERE workspace IN ({marks}) AND created_at < ?",
334 live = u8::from(live)
335 ))
336 .bind(&before)?
337 .first::<Paid>(None)
338 .await?
339 .and_then(|row| row.paid)
340 .unwrap_or(0),
341 )
342 };
343 // The trust ceiling, from what has been paid and how steadily. The
344 // first month is asked for beside it, since neither needs the other.
345 let trust = async {
346 Ok::<_, worker::Error>(match account.terms.kind {
347 TermsKind::Comped => (Trust::Internal, None, false),
348 _ if account.terms.ceiling_micros.is_some() => (Trust::Reviewed, account.terms.ceiling_micros, false),
349 _ => {
350 let standing = async {
351 let paid = self.live_paid(&members).await?;
352 let established = if paid > 0 { self.established(&members).await? } else { None };
353 Ok::<_, worker::Error>((paid, established))
354 };
355 let first = async {
356 if plan == PlanKind::Paid { self.first_month(&workspace).await } else { Ok(false) }
357 };
358 let ((paid, established), first_month) = try_join(standing, first).await?;
359 if plan == PlanKind::Free {
360 // Nothing on demand: only what a free workspace can owe.
361 (Trust::New, Some(self.ceilings.new), false)
362 } else {
363 let ceiling = paid_ceiling(&self.ceilings, self.plans.paid_start_micros, first_month, paid, established);
364 (if established.is_some() { Trust::Established } else { Trust::Paid }, Some(ceiling), first_month)
365 }
Billing accounts, terms and enterprises; g1t is no longer free366 }
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 index367 })
Usage limits: unpaid usage can only go so far368 };
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 index369 // This month's charges, and last month's, for the spend limit.
370 let charged = self.charged_months(&members, &month_start);
371 // None of these reads needs another's answer, so they go to D1 at
372 // once: the limit is on every signed-in page.
373 let ((row, month, pending, balance_before, (spent, last_month)), (trust, trust_ceiling, first_month)) =
374 try_join(try_join5(row, month, pending, balance_before, charged), trust).await?;
375 let (used, paid_month) = month.map_or((0, 0), |m| (m.used.unwrap_or(0), m.paid.unwrap_or(0)));
376 let used = used + pending;
377 let (exposure, prepaid) = exposure(used, if live { paid_month } else { 0 }, balance_before);
378
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look379 // A ceiling g1t granted is a floor under the trust ceiling.
380 let granted = row.as_ref().and_then(|row| row.granted_ceiling_micros);
381 let ceiling = trust_ceiling.map(|c| c.max(granted.unwrap_or(0)));
382 // The highest ceiling ever, kept as it rises.
383 let stored_max = row.as_ref().and_then(|row| row.max_ceiling_micros);
384 let max_ever = match (stored_max, ceiling) {
385 (Some(stored), Some(now)) => Some(stored.max(now)),
386 (stored, now) => stored.or(now),
387 };
388 if let (Some(max), true) = (max_ever, ceiling.is_some() && max_ever != stored_max && plan != PlanKind::Free) {
389 self.db
390 .prepare(
391 "INSERT INTO limits (workspace, max_ceiling_micros, updated_at) VALUES (?1, ?2, ?3)
392 ON CONFLICT (workspace) DO UPDATE SET max_ceiling_micros = MAX(COALESCE(max_ceiling_micros, 0), ?2), updated_at = ?3",
393 )
394 .bind(&[workspace.as_str().into(), (max as f64).into(), now.as_str().into()])?
395 .run()
396 .await?;
397 }
Two limits, real invoices, trust that grows by itself, sales signals398 let spent = spent + pending;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look399 let raised_at = row.as_ref().and_then(|row| row.raised_at.clone());
400 let self_serve = matches!(trust, Trust::New | Trust::Paid | Trust::Established) && plan != PlanKind::Free;
401 let (available, raise_once) = match (ceiling, self_serve) {
402 (Some(ceiling), true) => {
403 let (available, once) = spend_bounds(ceiling, max_ever.unwrap_or(ceiling), prepaid, raised_at.is_some());
404 (Some(available), once)
405 }
406 (ceiling, _) => (ceiling, None),
407 };
Two limits, real invoices, trust that grows by itself, sales signals408 // The owners' own monthly limit: theirs, none, or the automatic one
409 // ($200, or twice last month), which self-serve workspaces start on.
410 let chosen = row.as_ref().and_then(|row| row.spend_limit_micros);
411 let full = row.as_ref().and_then(|row| row.spend_limit_full).unwrap_or(0) == 1;
412 let default_spend_limit = chosen.is_none() && !full && self_serve;
413 let spend_limit = match (chosen, full) {
414 (Some(own), _) => Some(own),
415 (None, true) => None,
416 (None, false) if self_serve => Some(automatic_spend_limit(last_month)),
417 _ => None,
418 };
Billing accounts, terms and enterprises; g1t is no longer free419 // A card declined when g1t charged it at the limit stops work until
420 // it is paid; any payment clears it.
421 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 signals422 // Two limits: g1t's on what is unpaid, the owners' on what is spent.
423 let risk = state(exposure, ceiling);
424 let budget = state(spent, spend_limit);
425 let over_budget = budget == LimitState::Stopped;
426 let state = if declined.is_some() && exposure > 0 {
427 LimitState::Stopped
428 } else if risk == LimitState::Stopped || over_budget {
429 LimitState::Stopped
430 } else if risk == LimitState::Warning || budget == LimitState::Warning {
431 LimitState::Warning
432 } else {
433 LimitState::Ok
Usage limits: unpaid usage can only go so far434 };
Billing accounts, terms and enterprises; g1t is no longer free435 let who = if account.kind == g1t_contracts::billing::AccountKind::Enterprise {
436 format!("The {} enterprise, which pays for {workspace},", account.name)
437 } else {
438 format!("The {workspace} workspace")
439 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look440 let billing = format!("/{workspace}/-/billing");
Usage limits: unpaid usage can only go so far441 let message = match state {
442 LimitState::Ok => None,
Two limits, real invoices, trust that grows by itself, sales signals443 LimitState::Warning if budget == LimitState::Warning => Some(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look444 "{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 signals445 dollars_plain(spent),
446 dollars_plain(spend_limit.unwrap_or_default()),
447 )),
Usage limits: unpaid usage can only go so far448 LimitState::Warning => Some(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look449 "{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 far450 dollars_plain(exposure),
451 dollars_plain(ceiling.unwrap_or_default()),
452 )),
Billing accounts, terms and enterprises; g1t is no longer free453 LimitState::Stopped if declined.is_some() => Some(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look454 "{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 free455 declined.as_ref().and_then(|(_, error)| error.clone()).unwrap_or_else(|| "the card was declined".to_owned()),
456 )),
Two limits, real invoices, trust that grows by itself, sales signals457 LimitState::Stopped => Some(if over_budget {
Usage limits: unpaid usage can only go so far458 format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look459 "{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 signals460 dollars_plain(spend_limit.unwrap_or_default()),
Usage limits: unpaid usage can only go so far461 )
462 } else {
463 format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look464 "{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 far465 dollars_plain(ceiling.unwrap_or_default()),
466 )
467 }),
468 };
Two limits, real invoices, trust that grows by itself, sales signals469 let growth = match trust {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look470 Trust::New => Some("Free workspaces have no on-demand usage: the g1t plan starts at a $100 limit.".to_owned()),
471 Trust::Paid if first_month => Some(format!(
472 "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.",
473 dollars_plain(self.plans.paid_start_micros)
474 )),
Two limits, real invoices, trust that grows by itself, sales signals475 Trust::Paid => Some(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look476 "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 signals477 )),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look478 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 signals479 Trust::Reviewed | Trust::Internal => None,
480 };
Usage limits: unpaid usage can only go so far481 Ok(Limit {
482 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 index483 account: account.id.clone(),
484 account_name: account.name.clone(),
Two limits, real invoices, trust that grows by itself, sales signals485 spent_micros: spent,
486 default_spend_limit,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look487 available_micros: available,
Two limits, real invoices, trust that grows by itself, sales signals488 growth,
Usage limits: unpaid usage can only go so far489 trust,
490 exposure_micros: exposure,
491 ceiling_micros: ceiling,
492 trust_ceiling_micros: trust_ceiling,
493 spend_limit_micros: spend_limit,
494 state,
495 message,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look496 prepaid_micros: prepaid,
497 max_ceiling_micros: max_ever.filter(|_| plan != PlanKind::Free),
498 raise_once_micros: raise_once,
499 raised_at,
500 first_month,
501 })
502 }
503
504 /// Whether the workspace's plan is in its first billing cycle.
505 pub(crate) async fn first_month(&self, workspace: &str) -> Result<bool> {
506 Ok(match self.plan_cycle(workspace).await? {
507 Some((started_at, period_end)) => in_first_cycle(&started_at, period_end.as_deref(), &rfc3339(now_ms())),
508 None => false,
Usage limits: unpaid usage can only go so far509 })
510 }
511
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look512 /// Real money the workspaces have paid g1t, cleared: usage payments and
513 /// the plan's price. Nothing in test mode, and credits g1t gave are not
514 /// payments.
515 pub(crate) async fn live_paid(&self, members: &[JsValue]) -> Result<i64> {
Usage limits: unpaid usage can only go so far516 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
517 return Ok(0);
518 }
Billing accounts, terms and enterprises; g1t is no longer free519 let marks = vec!["?"; members.len().max(1)].join(", ");
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look520 let settled = rfc3339(now_ms() - SETTLE_DAYS * 24 * 60 * 60 * 1000);
Usage limits: unpaid usage can only go so far521 Ok(self
522 .db
Billing accounts, terms and enterprises; g1t is no longer free523 .prepare(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look524 "SELECT
525 (SELECT COALESCE(SUM(amount_micros), 0) FROM ledger
526 WHERE workspace IN ({marks}) AND kind = 'top_up' AND reference NOT LIKE 'crd%'
527 AND (amount_micros < 0
528 OR (disputed = 0 AND COALESCE(funding, '') <> 'prepaid'
529 AND created_at <= '{settled}')))
530 + (SELECT COALESCE(SUM(amount_micros), 0) FROM plan_payments
531 WHERE workspace IN ({marks}) AND paid_at <= '{settled}') AS paid"
Billing accounts, terms and enterprises; g1t is no longer free532 ))
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look533 .bind(&[members, members].concat())?
Usage limits: unpaid usage can only go so far534 .first::<Paid>(None)
535 .await?
536 .and_then(|row| row.paid)
537 .unwrap_or(0))
538 }
539
Two limits, real invoices, trust that grows by itself, sales signals540 /// This month's charges and last month's, across the workspaces.
541 async fn charged_months(&self, members: &[JsValue], month_start: &str) -> Result<(i64, i64)> {
542 #[derive(Deserialize)]
543 struct Charged {
544 this_month: Option<i64>,
545 last_month: Option<i64>,
546 }
547 let last_start = format!("{}-01", previous_month(&month_start[..7]));
548 let marks = vec!["?"; members.len().max(1)].join(", ");
549 let row = self
550 .db
551 .prepare(format!(
552 "SELECT
553 -SUM(CASE WHEN created_at >= '{month_start}' THEN amount_micros END) AS this_month,
554 -SUM(CASE WHEN created_at >= '{last_start}' AND created_at < '{month_start}' THEN amount_micros END) AS last_month
555 FROM ledger WHERE kind = 'usage' AND workspace IN ({marks}) AND created_at >= '{last_start}'"
556 ))
557 .bind(members)?
558 .first::<Charged>(None)
559 .await?;
560 Ok(row.map_or((0, 0), |r| (r.this_month.unwrap_or(0).max(0), r.last_month.unwrap_or(0).max(0))))
561 }
562
563 /// An Established ceiling, if the workspaces have paid steadily: three
564 /// full months of real spend, each invoiced and paid, nothing declined
565 /// in 90 days and nothing ever disputed.
566 async fn established(&self, members: &[JsValue]) -> Result<Option<i64>> {
567 let marks = vec!["?"; members.len().max(1)].join(", ");
568 let now = rfc3339(now_ms());
569 let mut months = vec![];
570 let mut month = previous_month(&now[..7]);
571 for _ in 0..3 {
572 months.push(month.clone());
573 month = previous_month(&month);
574 }
575 #[derive(Deserialize)]
576 struct Count {
577 n: Option<i64>,
578 }
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 index579 let troubled = async {
580 Ok::<i64, worker::Error>(
581 self.db
582 .prepare(format!(
583 "SELECT (SELECT COUNT(*) FROM ledger WHERE workspace IN ({marks}) AND disputed = 1)
584 + (SELECT COUNT(*) FROM limits WHERE workspace IN ({marks}) AND autopay_failed_at >= '{since}') AS n",
585 since = rfc3339(now_ms() - 90 * 24 * 60 * 60 * 1000)
586 ))
587 .bind(&[members, members].concat())?
588 .first::<Count>(None)
589 .await?
590 .and_then(|c| c.n)
591 .unwrap_or(0),
592 )
593 };
594 #[derive(Deserialize)]
595 struct Month {
596 charged: Option<i64>,
597 unpaid: Option<i64>,
Two limits, real invoices, trust that grows by itself, sales signals598 }
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 index599 let read_month = |month: &String| {
Two limits, real invoices, trust that grows by itself, sales signals600 let next = {
601 let year: i32 = month[..4].parse().unwrap_or(1970);
602 let number: u32 = month[5..7].parse().unwrap_or(1);
603 if number == 12 { format!("{}-01", year + 1) } else { format!("{year}-{:02}", number + 1) }
604 };
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 index605 let sql = format!(
606 "SELECT
607 (SELECT -SUM(amount_micros) FROM ledger WHERE kind = 'usage' AND workspace IN ({marks})
608 AND created_at >= '{month}-01' AND created_at < '{next}-01') AS charged,
609 (SELECT COUNT(*) FROM workspace_invoices WHERE workspace IN ({marks}) AND reason = 'month'
610 AND period = '{month}' AND status <> 'paid') AS unpaid"
611 );
612 async move { self.db.prepare(sql).bind(&[members, members].concat())?.first::<Month>(None).await }
613 };
614 // The check for trouble and the three months are read at once; the
615 // answer is the one reading them in turn and stopping early gives.
616 let (troubled, rows) = try_join(troubled, try_join_all(months.iter().map(read_month))).await?;
617 if troubled > 0 {
618 return Ok(None);
619 }
620 let mut charged = vec![];
621 for row in rows {
Two limits, real invoices, trust that grows by itself, sales signals622 let Some(row) = row else { return Ok(None) };
623 if row.unpaid.unwrap_or(0) > 0 {
624 return Ok(None);
625 }
626 charged.push(row.charged.unwrap_or(0));
627 }
628 Ok(established_ceiling(&charged))
629 }
630
Usage limits: unpaid usage can only go so far631 /// A refusal, with the reason, when the workspace's work is stopped.
632 /// None while billing is off: a g1t without payments has no limits.
633 pub(crate) async fn stopped<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
634 if self.stripe.is_none() {
635 return Ok(None);
636 }
637 let limit = self.limit_of(workspace).await?;
638 Ok((limit.state == LimitState::Stopped).then(|| {
639 Outcome::fail(
640 FailureCode::PaymentRequired,
641 limit.message.unwrap_or_else(|| "This workspace is over its limit.".to_owned()),
642 )
643 }))
644 }
645
646 pub(crate) async fn limit(&self, a: LimitArgs) -> Result<Outcome<Limit>> {
647 let workspace = a.workspace.to_lowercase();
648 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
649 return Ok(members_only());
650 }
651 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
652 }
653
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look654 /// What a source cost so far this month. `security`, `context`,
655 /// `storage` and `git` are charged by billing once the month is over
656 /// (see `storage`); `deployments` charges its own.
Prices keep themselves current with what g1t pays657 pub(crate) async fn note_pending(&self, a: NotePendingArgs) -> Result<bool> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents658 // The actions cache is the plan's to pay for; free workspaces are
659 // held to its quota instead.
660 if crate::storage::PLAN_ONLY.contains(&a.source.as_str()) && !self.has_plan(&a.workspace.to_lowercase()).await? {
661 return Ok(false);
662 }
Prices keep themselves current with what g1t pays663 let now = rfc3339(now_ms());
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas664 let detail = a.detail.as_deref().map(str::trim).filter(|d| !d.is_empty()).map(|d| d.chars().take(200).collect::<String>());
665 self.set_pending(&a.workspace, &a.source, &now[..7], a.cost_micros, detail.as_deref()).await?;
Prices keep themselves current with what g1t pays666 Ok(true)
667 }
668
Billing accounts, terms and enterprises; g1t is no longer free669 /// Charges the saved card of each workspace nearing its limit, for what
670 /// it owes, so that a workspace that pays never has its work stopped.
671 /// Only with live payments: test-mode payments are not money and lower
672 /// 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 look673 /// for enterprises, which are invoiced. A charge at the limit always
674 /// goes through, whatever the minimum charge.
Billing accounts, terms and enterprises; g1t is no longer free675 pub(crate) async fn autopay(&self) -> Result<()> {
Two limits, real invoices, trust that grows by itself, sales signals676 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
Billing accounts, terms and enterprises; g1t is no longer free677 return Ok(());
Two limits, real invoices, trust that grows by itself, sales signals678 }
Billing accounts, terms and enterprises; g1t is no longer free679 #[derive(Deserialize)]
680 struct Candidate {
681 workspace: String,
682 }
683 let month_start = format!("{}-01", &rfc3339(now_ms())[..7]);
Two limits, real invoices, trust that grows by itself, sales signals684 // With a card, and not already declined: a declined card waits for
685 // the owners, rather than being tried again every few minutes.
Billing accounts, terms and enterprises; g1t is no longer free686 let candidates = self
687 .db
688 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals689 "SELECT DISTINCT ledger.workspace AS workspace
Billing accounts, terms and enterprises; g1t is no longer free690 FROM ledger JOIN accounts ON accounts.workspace = ledger.workspace
Two limits, real invoices, trust that grows by itself, sales signals691 LEFT JOIN limits ON limits.workspace = ledger.workspace
692 WHERE ledger.kind = 'usage' AND ledger.created_at >= ? AND accounts.customer_id IS NOT NULL
693 AND limits.autopay_failed_at IS NULL",
Billing accounts, terms and enterprises; g1t is no longer free694 )
695 .bind(&[month_start.as_str().into()])?
696 .all()
697 .await?
698 .results::<Candidate>()?;
699 for candidate in candidates {
700 let limit = self.limit_of(&candidate.workspace).await?;
Two limits, real invoices, trust that grows by itself, sales signals701 // Near g1t's ceiling on what is unpaid; the spend limit is the
702 // owners' and stops work by itself, but what is owed is still owed.
703 let near = limit.ceiling_micros.is_some_and(|ceiling| limit.exposure_micros * 5 >= ceiling * 4);
704 if !near || limit.trust == Trust::Internal || limit.account.starts_with("ent_") {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace705 continue;
706 }
Two limits, real invoices, trust that grows by itself, sales signals707 let today = rfc3339(now_ms())[..10].to_owned();
708 match self.invoice_workspace(&candidate.workspace, "threshold", &today).await? {
709 Ok(_) => {}
710 Err(why) => worker::console_log!("{}: no threshold invoice: {why}", candidate.workspace),
Billing accounts, terms and enterprises; g1t is no longer free711 }
712 }
713 Ok(())
714 }
715
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace716 /// Closes last month for each workspace with a card on file: charges
717 /// what it owed when the month ended. Live payments only, once per
718 /// 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 look719 /// Comped workspaces owe nothing, and enterprises are invoiced. Only
720 /// here does the minimum charge apply: less carries over.
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace721 pub(crate) async fn close_months(&self) -> Result<()> {
Two limits, real invoices, trust that grows by itself, sales signals722 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace723 return Ok(());
Two limits, real invoices, trust that grows by itself, sales signals724 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace725 let now = rfc3339(now_ms());
726 let month_start = format!("{}-01", &now[..7]);
727 let closing = previous_month(&now[..7]);
728 #[derive(Deserialize)]
729 struct Open {
730 workspace: String,
731 balance: Option<i64>,
732 }
733 let open = self
734 .db
735 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals736 "SELECT accounts.workspace AS workspace,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace737 (SELECT SUM(amount_micros) FROM ledger
738 WHERE ledger.workspace = accounts.workspace AND ledger.created_at < ?1) AS balance
739 FROM accounts
740 WHERE accounts.customer_id IS NOT NULL
741 AND NOT EXISTS (SELECT 1 FROM month_closes
742 WHERE month_closes.workspace = accounts.workspace AND month_closes.month = ?2)
743 LIMIT 20",
744 )
745 .bind(&[month_start.as_str().into(), closing.as_str().into()])?
746 .all()
747 .await?
748 .results::<Open>()?;
749 for account in open {
750 let record = |status: &str, amount: i64, payment: Option<&str>, error: Option<&str>| {
751 self.db
752 .prepare(
753 "INSERT OR IGNORE INTO month_closes (workspace, month, status, amount_micros, payment_id, error, closed_at)
754 VALUES (?, ?, ?, ?, ?, ?, ?)",
755 )
756 .bind(&[
757 account.workspace.as_str().into(),
758 closing.as_str().into(),
759 status.into(),
760 (amount as f64).into(),
761 crate::optional(payment),
762 crate::optional(error),
763 now.as_str().into(),
764 ])
765 };
766 let payer = self.account_of(&account.workspace).await?;
767 if payer.terms.kind == TermsKind::Comped || payer.id.starts_with("ent_") {
768 record("skipped", 0, None, None)?.run().await?;
769 continue;
770 }
771 let owed = (-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 put772 if owed == 0 {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace773 record("nothing", 0, None, None)?.run().await?;
774 continue;
775 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put776 if !worth_charging(owed, self.plans.min_charge_micros) {
777 // Under the minimum charge: a card payment's fee would be
778 // too much of it. It stays owed and goes on the next
779 // invoice that reaches the minimum.
780 record("carried", owed, None, None)?.run().await?;
781 continue;
782 }
Two limits, real invoices, trust that grows by itself, sales signals783 match self.invoice_workspace(&account.workspace, "month", &closing).await? {
784 Ok(invoice) if invoice.status == "paid" => {
785 record("paid", invoice.amount_micros, Some(&invoice.invoice_id), None)?.run().await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace786 }
Two limits, real invoices, trust that grows by itself, sales signals787 Ok(invoice) => {
788 record("failed", invoice.amount_micros, Some(&invoice.invoice_id), Some("the card was declined"))?.run().await?;
789 }
790 Err(why) => {
791 record("nothing", 0, None, Some(&why))?.run().await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace792 }
793 }
794 }
795 Ok(())
796 }
797
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look798 /// Emails a workspace's owners as it passes 50, 75, 90 and 100% of its
799 /// plan's included usage, its spend limit and g1t's ceiling, once each a
800 /// month; when its card was declined; and when a spend spike paused it.
801 /// The same alerts show in the app (`entitlements`).
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace802 pub(crate) async fn warn_limits(&self, identity: &worker::Fetcher) -> Result<()> {
803 if self.stripe.is_none() {
804 return Ok(());
805 }
806 let now = rfc3339(now_ms());
807 let month = &now[..7];
808 #[derive(Deserialize)]
809 struct Candidate {
810 workspace: String,
811 }
812 let candidates = self
813 .db
814 .prepare(
815 "SELECT DISTINCT workspace FROM ledger WHERE kind = 'usage' AND created_at >= ?1
816 UNION SELECT workspace FROM limits WHERE autopay_failed_at IS NOT NULL",
817 )
818 .bind(&[format!("{month}-01").into()])?
819 .all()
820 .await?
821 .results::<Candidate>()?;
822 #[derive(Deserialize)]
823 struct Told {
824 autopay_failed_at: Option<String>,
825 declined_told_at: Option<String>,
826 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look827 #[derive(Deserialize)]
828 struct Sent {
829 meter: String,
830 level: Option<i64>,
831 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace832 for Candidate { workspace } in candidates {
833 let told = self
834 .db
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look835 .prepare("SELECT autopay_failed_at, declined_told_at FROM limits WHERE workspace = ?")
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace836 .bind(&[workspace.as_str().into()])?
837 .first::<Told>(None)
838 .await?;
839 let billing = format!("https://g1t.sh/{workspace}/-/billing");
840
841 // A declined card, once per decline.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look842 if let Some(Told { autopay_failed_at: Some(failed), declined_told_at }) = &told {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace843 if 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 look844 let limit = self.limit_of(&workspace).await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace845 let sent = notify(
846 identity,
847 &workspace,
848 &format!("g1t: the card for {workspace} was declined"),
849 &limit.message.clone().unwrap_or_else(|| format!("g1t could not charge the card on file for {workspace}.")),
850 "Update the card",
851 &billing,
852 )
853 .await;
854 if sent {
855 self.db
856 .prepare("UPDATE limits SET declined_told_at = ? WHERE workspace = ?")
857 .bind(&[now.as_str().into(), workspace.as_str().into()])?
858 .run()
859 .await?;
860 }
861 }
862 }
863
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look864 // 50, 75, 90 and 100%, once each a month and meter: only the
865 // highest new level is emailed.
866 let alerts = self.alerts_for(&workspace).await?;
867 if alerts.is_empty() {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace868 continue;
869 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look870 let sent: Vec<Sent> = self
871 .db
872 .prepare("SELECT meter, MAX(level) AS level FROM alerts_sent WHERE workspace = ? AND month = ? GROUP BY meter")
873 .bind(&[workspace.as_str().into(), month.into()])?
874 .all()
875 .await?
876 .results::<Sent>()?;
877 for alert in alerts {
878 let already = sent.iter().find(|s| s.meter == alert.meter).and_then(|s| s.level).unwrap_or(0);
879 if i64::from(alert.level) <= already {
880 continue;
881 }
882 let subject = match alert.meter.as_str() {
883 "included" => format!("g1t: {workspace} has used {}% of its included usage", alert.level),
884 "spend_limit" => format!("g1t: {workspace} has used {}% of its spend limit", alert.level),
885 _ => format!("g1t: {workspace} has used {}% of its usage limit", alert.level),
886 };
887 if notify(identity, &workspace, &subject, &alert.message, "Open billing", &billing).await {
888 self.db
889 .prepare(
890 "INSERT OR IGNORE INTO alerts_sent (workspace, month, meter, level, sent_at) VALUES (?1, ?2, ?3, ?4, ?5)",
891 )
892 .bind(&[workspace.as_str().into(), month.into(), alert.meter.as_str().into(), alert.level.into(), now.as_str().into()])?
893 .run()
894 .await?;
895 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace896 }
897 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look898 self.tell_spikes(identity).await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace899 Ok(())
900 }
901
Usage limits: unpaid usage can only go so far902 pub(crate) async fn check_limit(&self, a: CheckLimitArgs) -> Result<Outcome<Limit>> {
903 Ok(Outcome::Ok(self.limit_of(&a.workspace).await?))
904 }
905
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look906 /// The owners' spend limit: anywhere up to what is available without
907 /// asking; once, up to twice the highest ceiling (`raise_once`), which
908 /// also raises g1t's ceiling to match.
Usage limits: unpaid usage can only go so far909 pub(crate) async fn set_spend_limit(&self, a: SetSpendLimitArgs) -> Result<Outcome<Limit>> {
910 let workspace = a.workspace.to_lowercase();
911 if a.actor.role_in(&workspace) != Some(Role::Owner) {
912 return Ok(Outcome::fail(
913 FailureCode::Forbidden,
914 "Only an owner can set the workspace's spend limit.",
915 ));
916 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look917 let before = self.limit_of(&workspace).await?;
918 let mut raising = false;
919 if let (Some(requested), false) = (a.spend_limit_micros, a.use_full_limit) {
920 match (before.available_micros, matches!(before.trust, Trust::Internal | Trust::Reviewed)) {
921 (_, true) | (None, _) => {
922 if requested < 0 {
923 return Ok(Outcome::fail(FailureCode::Invalid, "A spend limit cannot be negative."));
924 }
925 }
926 (Some(available), false) => match self_serve(requested, available, before.raise_once_micros, a.raise_once) {
927 Ok(uses_raise) => raising = uses_raise,
928 Err(why) => return Ok(Outcome::fail(FailureCode::Invalid, why)),
929 },
930 }
Usage limits: unpaid usage can only go so far931 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look932 let now = rfc3339(now_ms());
Two limits, real invoices, trust that grows by itself, sales signals933 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 far934 self.db
935 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals936 "INSERT INTO limits (workspace, spend_limit_micros, spend_limit_full, updated_at) VALUES (?1, ?2, ?3, ?4)
937 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 far938 )
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look939 .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 far940 .run()
941 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look942 if raising {
943 let raised = a.spend_limit_micros.unwrap_or_default();
944 // The ceiling rises with it, once.
945 self.db
946 .prepare(
947 "UPDATE limits SET granted_ceiling_micros = MAX(COALESCE(granted_ceiling_micros, 0), ?2),
948 raised_at = ?3, updated_at = ?3 WHERE workspace = ?1 AND raised_at IS NULL",
949 )
950 .bind(&[workspace.as_str().into(), (raised as f64).into(), now.as_str().into()])?
951 .run()
952 .await?;
953 let account = self.account_of(&workspace).await?;
954 self.audit(&account.id, "raise_once", &format!("{workspace} used its one-time raise: {}", dollars_plain(raised)), &a.actor.username)
955 .await?;
956 }
Usage limits: unpaid usage can only go so far957 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
958 }
959}
960
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look961/// Whether `owed` is enough to charge a card when a month closes: at least
962/// the minimum charge (`MIN_CHARGE_MICROS`). Less carries over to the next
963/// 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 put964pub(crate) fn worth_charging(owed: i64, min_charge: i64) -> bool {
965 owed > 0 && owed >= min_charge
966}
967
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace968/// 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 look969pub(crate) async fn notify(identity: &worker::Fetcher, workspace: &str, subject: &str, intro: &str, action: &str, link: &str) -> bool {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace970 let args = g1t_contracts::identity::NotifyOwnersArgs {
971 workspace: workspace.to_owned(),
972 subject: subject.to_owned(),
973 intro: intro.to_owned(),
974 action: action.to_owned(),
975 link: link.to_owned(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look976 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".to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace977 };
978 match g1t_kit::call::<_, u32>(identity, "notify_owners", &args).await {
979 Ok(sent) => sent > 0,
980 Err(error) => {
981 worker::console_error!("could not tell {workspace}'s owners: {error}");
982 false
983 }
984 }
985}
986
987/// `2026-09` for `2026-10`, and `2025-12` for `2026-01`.
988pub(crate) fn previous_month(month: &str) -> String {
989 let year: i32 = month[..4].parse().unwrap_or(1970);
990 let number: u32 = month[5..7].parse().unwrap_or(1);
991 if number == 1 {
992 format!("{}-12", year - 1)
993 } else {
994 format!("{year}-{:02}", number - 1)
995 }
996}
997
Usage limits: unpaid usage can only go so far998#[cfg(test)]
999mod tests {
1000 use super::*;
1001
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1002 #[test]
Two limits, real invoices, trust that grows by itself, sales signals1003 fn the_automatic_spend_limit_follows_last_month() {
1004 assert_eq!(automatic_spend_limit(0), 200_000_000);
1005 assert_eq!(automatic_spend_limit(50_000_000), 200_000_000);
1006 assert_eq!(automatic_spend_limit(900_000_000), 1_800_000_000);
1007 }
1008
1009 #[test]
1010 fn three_steady_months_make_a_workspace_established() {
1011 assert_eq!(established_ceiling(&[900_000_000, 850_000_000, 950_000_000]), Some(2_700_000_000));
1012 assert_eq!(established_ceiling(&[5_000_000_000, 5_000_000_000, 5_000_000_000]), Some(10_000_000_000));
1013 assert_eq!(established_ceiling(&[900_000_000, 10_000_000, 950_000_000]), None);
1014 assert_eq!(established_ceiling(&[900_000_000, 900_000_000]), None);
1015 }
1016
1017 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1018 fn alerts_come_at_half_three_quarters_ninety_and_the_limit() {
1019 assert_eq!(alert_level(0, 10_000_000), 0);
1020 assert_eq!(alert_level(4_999_999, 10_000_000), 0);
1021 assert_eq!(alert_level(5_000_000, 10_000_000), 50);
1022 assert_eq!(alert_level(7_500_000, 10_000_000), 75);
1023 assert_eq!(alert_level(8_999_999, 10_000_000), 75);
1024 assert_eq!(alert_level(9_000_000, 10_000_000), 90);
1025 assert_eq!(alert_level(10_000_000, 10_000_000), 100);
1026 assert_eq!(alert_level(25_000_000, 10_000_000), 100);
1027 // Nothing to measure against: no alert.
1028 assert_eq!(alert_level(5, 0), 0);
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1029 }
1030
1031 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1032 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 put1033 let min = 5_000_000;
1034 assert!(!worth_charging(0, min));
1035 assert!(!worth_charging(4_990_000, min));
1036 assert!(worth_charging(5_000_000, min));
1037 assert!(worth_charging(12_000_000, min));
1038 // $3 carried from last month and $2.50 this month: charged together.
1039 let carried = 3_000_000;
1040 assert!(!worth_charging(carried, min));
1041 assert!(worth_charging(carried + 2_500_000, min));
1042 }
1043
1044 #[test]
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1045 fn the_month_before_wraps_the_year() {
1046 assert_eq!(previous_month("2026-10"), "2026-09");
1047 assert_eq!(previous_month("2026-01"), "2025-12");
1048 }
1049
Usage limits: unpaid usage can only go so far1050 fn ceilings() -> Ceilings {
Billing accounts, terms and enterprises; g1t is no longer free1051 Ceilings { new: 3_000_000, paid_min: 25_000_000, paid_max: 1_000_000_000 }
Usage limits: unpaid usage can only go so far1052 }
1053
1054 #[test]
1055 fn trust_grows_with_what_was_paid_within_bounds() {
1056 assert_eq!(ceilings().for_paid(5_000_000), 25_000_000);
1057 assert_eq!(ceilings().for_paid(100_000_000), 200_000_000);
1058 assert_eq!(ceilings().for_paid(10_000_000_000), 1_000_000_000);
1059 }
1060
1061 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1062 fn a_new_paid_workspace_starts_at_a_hundred_dollars_and_only_goes_up() {
1063 let start = 100_000_000;
1064 // The first month: the starting ceiling, whatever was paid.
1065 assert_eq!(paid_ceiling(&ceilings(), start, true, 900_000_000, None), start);
1066 // After it, with little paid: never below the start.
1067 assert_eq!(paid_ceiling(&ceilings(), start, false, 20_000_000, None), start);
1068 assert_eq!(paid_ceiling(&ceilings(), start, false, 0, None), start);
1069 // Payments that cleared raise it: twice what was paid.
1070 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, None), 600_000_000);
1071 // Established follows the monthly spend.
1072 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, Some(2_700_000_000)), 2_700_000_000);
1073 }
1074
1075 #[test]
1076 fn the_first_billing_cycle_is_the_first_month() {
1077 // A plan that started on the 5th, paid through the 5th of next month.
1078 assert!(in_first_cycle("2026-10-05T10:00:00Z", Some("2026-11-05T10:00:00Z"), "2026-10-20T00:00:00Z"));
1079 // Renewed: the period now ends two months after the start.
1080 assert!(!in_first_cycle("2026-10-05T10:00:00Z", Some("2026-12-05T10:00:00Z"), "2026-11-20T00:00:00Z"));
1081 // No period known yet: the first 31 days.
1082 assert!(in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-04T00:00:00Z"));
1083 assert!(!in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-10T00:00:00Z"));
1084 // Day counting is exact across months and years.
1085 assert_eq!(days("1970-01-01"), 0);
1086 assert_eq!(days("2026-11-01") - days("2026-10-01"), 31);
1087 assert_eq!(days("2028-03-01") - days("2028-02-28"), 2);
1088 assert_eq!(days("2027-01-01") - days("2026-12-31"), 1);
1089 }
1090
1091 #[test]
1092 fn owners_set_their_limit_up_to_the_highest_ceiling_without_asking() {
1093 // First month at $100; the highest ever is $100.
1094 let (available, once) = spend_bounds(100_000_000, 100_000_000, 0, false);
1095 assert_eq!(available, 100_000_000);
1096 assert_eq!(once, Some(200_000_000));
1097 assert_eq!(self_serve(80_000_000, available, once, false), Ok(false));
1098 assert_eq!(self_serve(100_000_000, available, once, false), Ok(false));
1099 // Above it without the raise: refused, saying what to do.
1100 assert!(self_serve(150_000_000, available, once, false).unwrap_err().contains("one-time raise"));
1101 // With the raise: up to twice the highest ceiling, once.
1102 assert_eq!(self_serve(200_000_000, available, once, true), Ok(true));
1103 assert!(self_serve(200_000_001, available, once, true).unwrap_err().contains("Raise my limit"));
1104 // Once used, it is gone.
1105 let (available, once) = spend_bounds(200_000_000, 200_000_000, 0, true);
1106 assert_eq!(once, None);
1107 assert_eq!(self_serve(200_000_000, available, once, false), Ok(false));
1108 assert!(self_serve(300_000_000, available, once, true).unwrap_err().contains("is used"));
1109 // A ceiling that came down still leaves the highest one available.
1110 let (available, _) = spend_bounds(100_000_000, 400_000_000, 0, true);
1111 assert_eq!(available, 400_000_000);
1112 assert!(self_serve(-1, available, None, false).is_err());
1113 }
1114
1115 #[test]
1116 fn prepaying_raises_what_can_be_used_at_once() {
1117 // $500 prepaid this month, $120 used: nothing owed, $380 left.
1118 assert_eq!(exposure(120_000_000, 500_000_000, 0), (0, 380_000_000));
1119 // Prepaid last month and carried in.
1120 assert_eq!(exposure(120_000_000, 0, 500_000_000), (0, 380_000_000));
1121 // Used past the prepayment: the rest is owed.
1122 assert_eq!(exposure(620_000_000, 500_000_000, 0), (120_000_000, 0));
1123 // Owed from before adds to this month's.
1124 assert_eq!(exposure(10_000_000, 0, -4_000_000), (14_000_000, 0));
1125 // With a $100 ceiling and $500 prepaid, work stops at $600 of use,
1126 // not at $100.
1127 let ceiling = 100_000_000;
1128 assert_eq!(state(exposure(599_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Warning);
1129 assert_eq!(state(exposure(600_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Stopped);
1130 // And the owners may set their spend limit that much higher.
1131 assert_eq!(spend_bounds(ceiling, ceiling, 500_000_000, true).0, 600_000_000);
1132 }
1133
1134 #[test]
Usage limits: unpaid usage can only go so far1135 fn work_warns_at_eighty_percent_and_stops_at_the_ceiling() {
1136 assert_eq!(state(0, Some(100)), LimitState::Ok);
1137 assert_eq!(state(79, Some(100)), LimitState::Ok);
1138 assert_eq!(state(80, Some(100)), LimitState::Warning);
1139 assert_eq!(state(100, Some(100)), LimitState::Stopped);
1140 assert_eq!(state(1_000_000, None), LimitState::Ok);
1141 }
1142}