g1t/services/billing/src/limits.rs

818 lines36,752 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.

Usage limits: unpaid usage can only go so far1//! How far a workspace can run up costs g1t has not been paid for.
2//!
3//! Every sandbox second, build, app request and model token costs g1t
4//! money at Cloudflare or a model provider before the workspace pays for
5//! it. So, like Fly or Cloudflare with new accounts, each workspace has a
6//! ceiling on that unpaid usage, set by how much it has paid g1t before:
7//!
8//! - **New**: no live payment yet. A few dollars, enough for the free
9//! allowances and a little more.
10//! - **Paid**: twice what it has paid g1t, within bounds.
11//! - **Reviewed**: a ceiling g1t set by hand.
12//! - **Internal**: g1t's own workspaces, with none.
13//!
14//! An owner can set a lower spend limit of their own. Past 80% the
15//! workspace is warned; at the ceiling its work stops: no new sandboxes,
16//! builds or app requests, until it pays or the month turns. Runs already
17//! under way finish.
18//!
19//! Usage counts at what it cost g1t or what it is charged, whichever is
20//! more, so it counts while g1t is free too: free is a price, not an
21//! exemption from the ceiling. Test-mode payments are not money, so they
22//! do not raise trust.
23
Billing accounts, terms and enterprises; g1t is no longer free24use g1t_contracts::billing::{CheckLimitArgs, Limit, LimitArgs, NotePendingArgs, TermsKind, LimitState, SetSpendLimitArgs, Trust};
Usage limits: unpaid usage can only go so far25use g1t_contracts::time::rfc3339;
26use g1t_contracts::{FailureCode, Outcome, Role};
27use g1t_kit::now_ms;
28use serde::Deserialize;
29use worker::wasm_bindgen::JsValue;
30use worker::{Env, Result};
31
32use crate::features::dollars as dollars_plain;
33use crate::{Billing, members_only};
34
35/// The ceilings, from the billing service's variables.
36pub(crate) struct Ceilings {
37 /// `LIMIT_NEW_MICROS`.
38 pub new: i64,
39 /// `LIMIT_PAID_MIN_MICROS` and `LIMIT_PAID_MAX_MICROS`.
40 pub paid_min: i64,
41 pub paid_max: i64,
42}
43
44impl Ceilings {
45 pub(crate) fn from_env(env: &Env) -> Self {
46 let number = |name: &str, default: i64| {
47 env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok()).unwrap_or(default)
48 };
49 Ceilings {
50 new: number("LIMIT_NEW_MICROS", 3_000_000),
51 paid_min: number("LIMIT_PAID_MIN_MICROS", 25_000_000),
52 paid_max: number("LIMIT_PAID_MAX_MICROS", 1_000_000_000),
53 }
54 }
55
56 /// The ceiling for a workspace that has paid `paid` in live money.
57 pub(crate) fn for_paid(&self, paid: i64) -> i64 {
58 (paid * 2).clamp(self.paid_min, self.paid_max)
59 }
60}
61
62/// Where a workspace stands against its ceiling.
63pub(crate) fn state(exposure: i64, ceiling: Option<i64>) -> LimitState {
64 match ceiling {
65 Some(ceiling) if exposure >= ceiling => LimitState::Stopped,
66 Some(ceiling) if exposure * 5 >= ceiling * 4 => LimitState::Warning,
67 _ => LimitState::Ok,
68 }
69}
70
Two limits, real invoices, trust that grows by itself, sales signals71/// The automatic monthly spend limit's floor: $200.
72pub(crate) const DEFAULT_SPEND_MICROS: i64 = 200_000_000;
73/// Established workspaces' ceiling: three times their steady monthly
74/// spend, up to $10,000.
75const ESTABLISHED_FACTOR: i64 = 3;
76const ESTABLISHED_MAX_MICROS: i64 = 10_000_000_000;
77/// A month counts toward Established at this much spend or more.
78const ESTABLISHED_MONTH_MICROS: i64 = 20_000_000;
79/// Payments raise trust once this old: past the time most bad cards are
80/// caught.
81const SETTLE_DAYS: u64 = 7;
82
83/// The automatic spend limit: $200, or twice last month's spend.
84pub(crate) fn automatic_spend_limit(last_month_charged: i64) -> i64 {
85 DEFAULT_SPEND_MICROS.max(last_month_charged * 2)
86}
Billing accounts, terms and enterprises; g1t is no longer free87
Two limits, real invoices, trust that grows by itself, sales signals88/// An Established workspace's ceiling, from its last three months'
89/// charges, if each was steady enough.
90pub(crate) fn established_ceiling(months: &[i64]) -> Option<i64> {
91 if months.len() < 3 || months.iter().any(|m| *m < ESTABLISHED_MONTH_MICROS) {
92 return None;
93 }
94 let average = months.iter().sum::<i64>() / months.len() as i64;
95 Some((average * ESTABLISHED_FACTOR).min(ESTABLISHED_MAX_MICROS))
96}
97
Usage limits: unpaid usage can only go so far98#[derive(Deserialize)]
99struct LimitRow {
100 spend_limit_micros: Option<i64>,
Two limits, real invoices, trust that grows by itself, sales signals101 #[serde(default)]
102 spend_limit_full: Option<i64>,
Billing accounts, terms and enterprises; g1t is no longer free103 autopay_failed_at: Option<String>,
104 autopay_error: Option<String>,
Usage limits: unpaid usage can only go so far105}
106
107#[derive(Deserialize)]
108struct Month {
109 used: Option<i64>,
110 paid: Option<i64>,
111}
112
113#[derive(Deserialize)]
114struct Paid {
115 paid: Option<i64>,
116}
117
118impl Billing {
Billing accounts, terms and enterprises; g1t is no longer free119 /// The workspace's limit, worked out from the ledger of the account
120 /// that pays for it: its own, or its enterprise's, whose workspaces'
121 /// usage and payments count together.
Usage limits: unpaid usage can only go so far122 pub(crate) async fn limit_of(&self, workspace: &str) -> Result<Limit> {
123 let workspace = workspace.to_lowercase();
Billing accounts, terms and enterprises; g1t is no longer free124 let account = self.account_of(&workspace).await?;
Usage limits: unpaid usage can only go so far125 let row = self
126 .db
Two limits, real invoices, trust that grows by itself, sales signals127 .prepare("SELECT spend_limit_micros, spend_limit_full, autopay_failed_at, autopay_error FROM limits WHERE workspace = ?")
Usage limits: unpaid usage can only go so far128 .bind(&[workspace.as_str().into()])?
129 .first::<LimitRow>(None)
130 .await?;
131 let month_start = format!("{}-01", &rfc3339(now_ms())[..7]);
Billing accounts, terms and enterprises; g1t is no longer free132 let marks = vec!["?"; account.workspaces.len().max(1)].join(", ");
133 let members: Vec<JsValue> = if account.workspaces.is_empty() {
134 vec![JsValue::from(workspace.as_str())]
135 } else {
136 account.workspaces.iter().map(|w| JsValue::from(w.as_str())).collect()
137 };
138 let mut with_month = members.clone();
139 with_month.push(month_start.as_str().into());
Usage limits: unpaid usage can only go so far140 // Each usage entry at its cost to g1t or its charge, whichever is
141 // more; on the workspace's own provider, only g1t's fee is g1t's.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put142 // What a plan's credit, the trial or the open-source pool paid for
143 // is not unpaid: those are capped budgets already paid for.
Usage limits: unpaid usage can only go so far144 let month = self
145 .db
Billing accounts, terms and enterprises; g1t is no longer free146 .prepare(format!(
Usage limits: unpaid usage can only go so far147 "SELECT
148 SUM(CASE WHEN kind = 'usage' THEN
149 CASE WHEN COALESCE(billed_to, 'g1t') = 'g1t'
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put150 THEN MAX(COALESCE(cost_micros, 0) - COALESCE(credit_micros, 0)
151 - COALESCE(trial_micros, 0) - COALESCE(oss_micros, 0),
152 -amount_micros)
Usage limits: unpaid usage can only go so far153 ELSE -amount_micros END
154 END) AS used,
155 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS paid
Billing accounts, terms and enterprises; g1t is no longer free156 FROM ledger WHERE workspace IN ({marks}) AND created_at >= ?"
157 ))
158 .bind(&with_month)?
Usage limits: unpaid usage can only go so far159 .first::<Month>(None)
160 .await?;
161 let (used, paid_month) = month.map_or((0, 0), |m| (m.used.unwrap_or(0), m.paid.unwrap_or(0)));
Prices keep themselves current with what g1t pays162 // And what is metered but not charged until the month closes.
Billing accounts, terms and enterprises; g1t is no longer free163 let mut pending_args = members.clone();
164 pending_args.push(month_start[..7].into());
Prices keep themselves current with what g1t pays165 let pending = self
166 .db
Billing accounts, terms and enterprises; g1t is no longer free167 .prepare(format!(
168 "SELECT SUM(charge_micros) AS paid FROM pending_usage WHERE workspace IN ({marks}) AND month = ?"
169 ))
170 .bind(&pending_args)?
Prices keep themselves current with what g1t pays171 .first::<Paid>(None)
172 .await?
173 .and_then(|row| row.paid)
174 .unwrap_or(0);
175 let used = used + pending;
Usage limits: unpaid usage can only go so far176 // Test-mode payments are not money: they pay nothing off.
177 let live = self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live);
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace178 // Charges from earlier months still unpaid carry over, so a new
179 // month is not a fresh allowance for an account that never pays.
180 // Credits g1t gave count as paid; test-mode payments do not.
181 let mut before = members.clone();
182 before.push(month_start.as_str().into());
183 let carried = self
184 .db
185 .prepare(format!(
186 "SELECT SUM(CASE WHEN kind = 'usage' THEN amount_micros
187 WHEN kind = 'top_up' AND ({live} = 1 OR reference LIKE 'crd%') THEN amount_micros
188 ELSE 0 END) AS paid
189 FROM ledger WHERE workspace IN ({marks}) AND created_at < ?",
190 live = u8::from(live)
191 ))
192 .bind(&before)?
193 .first::<Paid>(None)
194 .await?
195 .and_then(|row| row.paid)
196 .map_or(0, |balance| (-balance).max(0));
197 let exposure = (used - if live { paid_month } else { 0 }).max(0) + carried;
Usage limits: unpaid usage can only go so far198
Billing accounts, terms and enterprises; g1t is no longer free199 let (trust, trust_ceiling) = match account.terms.kind {
200 TermsKind::Comped => (Trust::Internal, None),
201 _ if account.terms.ceiling_micros.is_some() => (Trust::Reviewed, account.terms.ceiling_micros),
202 _ => {
203 let paid = self.live_paid(&members).await?;
Two limits, real invoices, trust that grows by itself, sales signals204 let established = if paid > 0 { self.established(&members).await? } else { None };
205 match established {
206 Some(ceiling) => (Trust::Established, Some(ceiling.max(self.ceilings.for_paid(paid)))),
207 None if paid > 0 => (Trust::Paid, Some(self.ceilings.for_paid(paid))),
208 None => (Trust::New, Some(self.ceilings.new)),
Billing accounts, terms and enterprises; g1t is no longer free209 }
Usage limits: unpaid usage can only go so far210 }
211 };
Two limits, real invoices, trust that grows by itself, sales signals212 // This month's charges, and last month's, for the spend limit.
213 let (spent, last_month) = self.charged_months(&members, &month_start).await?;
214 let spent = spent + pending;
215 // The owners' own monthly limit: theirs, none, or the automatic one
216 // ($200, or twice last month), which self-serve workspaces start on.
217 let chosen = row.as_ref().and_then(|row| row.spend_limit_micros);
218 let full = row.as_ref().and_then(|row| row.spend_limit_full).unwrap_or(0) == 1;
219 let self_serve = matches!(trust, Trust::New | Trust::Paid | Trust::Established);
220 let default_spend_limit = chosen.is_none() && !full && self_serve;
221 let spend_limit = match (chosen, full) {
222 (Some(own), _) => Some(own),
223 (None, true) => None,
224 (None, false) if self_serve => Some(automatic_spend_limit(last_month)),
225 _ => None,
226 };
Billing accounts, terms and enterprises; g1t is no longer free227 // A card declined when g1t charged it at the limit stops work until
228 // it is paid; any payment clears it.
229 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 signals230 // Two limits: g1t's on what is unpaid, the owners' on what is spent.
231 let ceiling = trust_ceiling;
232 let risk = state(exposure, ceiling);
233 let budget = state(spent, spend_limit);
234 let over_budget = budget == LimitState::Stopped;
235 let state = if declined.is_some() && exposure > 0 {
236 LimitState::Stopped
237 } else if risk == LimitState::Stopped || over_budget {
238 LimitState::Stopped
239 } else if risk == LimitState::Warning || budget == LimitState::Warning {
240 LimitState::Warning
241 } else {
242 LimitState::Ok
Usage limits: unpaid usage can only go so far243 };
Billing accounts, terms and enterprises; g1t is no longer free244 let who = if account.kind == g1t_contracts::billing::AccountKind::Enterprise {
245 format!("The {} enterprise, which pays for {workspace},", account.name)
246 } else {
247 format!("The {workspace} workspace")
248 };
Usage limits: unpaid usage can only go so far249 let message = match state {
250 LimitState::Ok => None,
Two limits, real invoices, trust that grows by itself, sales signals251 LimitState::Warning if budget == LimitState::Warning => Some(format!(
252 "{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 under Billing.",
253 dollars_plain(spent),
254 dollars_plain(spend_limit.unwrap_or_default()),
255 )),
Usage limits: unpaid usage can only go so far256 LimitState::Warning => Some(format!(
Two limits, real invoices, trust that grows by itself, sales signals257 "{who} has {} of usage not yet paid for, of the {} g1t allows. With a card on file g1t charges it now; without one, at the limit its sandboxes, builds and apps stop until it pays.",
Usage limits: unpaid usage can only go so far258 dollars_plain(exposure),
259 dollars_plain(ceiling.unwrap_or_default()),
260 )),
Billing accounts, terms and enterprises; g1t is no longer free261 LimitState::Stopped if declined.is_some() => Some(format!(
262 "{who} could not be charged for its usage ({}), so its sandboxes, builds and apps are stopped. An owner can pay under Billing with another card.",
263 declined.as_ref().and_then(|(_, error)| error.clone()).unwrap_or_else(|| "the card was declined".to_owned()),
264 )),
Two limits, real invoices, trust that grows by itself, sales signals265 LimitState::Stopped => Some(if over_budget {
Usage limits: unpaid usage can only go so far266 format!(
Two limits, real invoices, trust that grows by itself, sales signals267 "{who} reached its {} monthly spend limit, so its sandboxes, builds and apps are stopped until the month turns. An owner can raise it under Billing.",
268 dollars_plain(spend_limit.unwrap_or_default()),
Usage limits: unpaid usage can only go so far269 )
270 } else {
271 format!(
Billing accounts, terms and enterprises; g1t is no longer free272 "{who} reached its {} limit for usage not yet paid for, so its sandboxes, builds and apps are stopped. The limit grows as a workspace pays g1t; an owner can pay under Billing, or write to support to have it raised.",
Usage limits: unpaid usage can only go so far273 dollars_plain(ceiling.unwrap_or_default()),
274 )
275 }),
276 };
Two limits, real invoices, trust that grows by itself, sales signals277 let growth = match trust {
278 Trust::New => Some("Pay g1t once, by card or credit, and this grows to $25; after that it grows with every payment.".to_owned()),
279 Trust::Paid => Some(format!(
280 "Grows to twice what you have paid, as payments clear (after {SETTLE_DAYS} days), up to $1,000. After three steady months it follows your monthly spend, up to $10,000, by itself."
281 )),
282 Trust::Established => Some("Follows your monthly spend, up to $10,000, by itself. For more, contact us.".to_owned()),
283 Trust::Reviewed | Trust::Internal => None,
284 };
Usage limits: unpaid usage can only go so far285 Ok(Limit {
286 workspace,
Billing accounts, terms and enterprises; g1t is no longer free287 account: account.id,
288 account_name: account.name,
Two limits, real invoices, trust that grows by itself, sales signals289 spent_micros: spent,
290 default_spend_limit,
291 available_micros: trust_ceiling,
292 growth,
Usage limits: unpaid usage can only go so far293 trust,
294 exposure_micros: exposure,
295 ceiling_micros: ceiling,
296 trust_ceiling_micros: trust_ceiling,
297 spend_limit_micros: spend_limit,
298 state,
299 message,
300 })
301 }
302
Billing accounts, terms and enterprises; g1t is no longer free303 /// Real money the workspaces have paid g1t. Nothing in test mode, and
304 /// credits g1t gave are not payments.
305 async fn live_paid(&self, members: &[JsValue]) -> Result<i64> {
Usage limits: unpaid usage can only go so far306 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
307 return Ok(0);
308 }
Billing accounts, terms and enterprises; g1t is no longer free309 let marks = vec!["?"; members.len().max(1)].join(", ");
Usage limits: unpaid usage can only go so far310 Ok(self
311 .db
Billing accounts, terms and enterprises; g1t is no longer free312 .prepare(format!(
313 "SELECT SUM(amount_micros) AS paid FROM ledger
Two limits, real invoices, trust that grows by itself, sales signals314 WHERE workspace IN ({marks}) AND kind = 'top_up' AND reference NOT LIKE 'crd%'
315 AND (amount_micros < 0
316 OR (disputed = 0 AND COALESCE(funding, '') <> 'prepaid'
317 AND created_at <= '{settled}'))",
318 settled = rfc3339(now_ms() - SETTLE_DAYS * 24 * 60 * 60 * 1000)
Billing accounts, terms and enterprises; g1t is no longer free319 ))
320 .bind(members)?
Usage limits: unpaid usage can only go so far321 .first::<Paid>(None)
322 .await?
323 .and_then(|row| row.paid)
324 .unwrap_or(0))
325 }
326
Two limits, real invoices, trust that grows by itself, sales signals327 /// This month's charges and last month's, across the workspaces.
328 async fn charged_months(&self, members: &[JsValue], month_start: &str) -> Result<(i64, i64)> {
329 #[derive(Deserialize)]
330 struct Charged {
331 this_month: Option<i64>,
332 last_month: Option<i64>,
333 }
334 let last_start = format!("{}-01", previous_month(&month_start[..7]));
335 let marks = vec!["?"; members.len().max(1)].join(", ");
336 let row = self
337 .db
338 .prepare(format!(
339 "SELECT
340 -SUM(CASE WHEN created_at >= '{month_start}' THEN amount_micros END) AS this_month,
341 -SUM(CASE WHEN created_at >= '{last_start}' AND created_at < '{month_start}' THEN amount_micros END) AS last_month
342 FROM ledger WHERE kind = 'usage' AND workspace IN ({marks}) AND created_at >= '{last_start}'"
343 ))
344 .bind(members)?
345 .first::<Charged>(None)
346 .await?;
347 Ok(row.map_or((0, 0), |r| (r.this_month.unwrap_or(0).max(0), r.last_month.unwrap_or(0).max(0))))
348 }
349
350 /// An Established ceiling, if the workspaces have paid steadily: three
351 /// full months of real spend, each invoiced and paid, nothing declined
352 /// in 90 days and nothing ever disputed.
353 async fn established(&self, members: &[JsValue]) -> Result<Option<i64>> {
354 let marks = vec!["?"; members.len().max(1)].join(", ");
355 let now = rfc3339(now_ms());
356 let mut months = vec![];
357 let mut month = previous_month(&now[..7]);
358 for _ in 0..3 {
359 months.push(month.clone());
360 month = previous_month(&month);
361 }
362 #[derive(Deserialize)]
363 struct Count {
364 n: Option<i64>,
365 }
366 let troubled = self
367 .db
368 .prepare(format!(
369 "SELECT (SELECT COUNT(*) FROM ledger WHERE workspace IN ({marks}) AND disputed = 1)
370 + (SELECT COUNT(*) FROM limits WHERE workspace IN ({marks}) AND autopay_failed_at >= '{since}') AS n",
371 since = rfc3339(now_ms() - 90 * 24 * 60 * 60 * 1000)
372 ))
373 .bind(&[members, members].concat())?
374 .first::<Count>(None)
375 .await?
376 .and_then(|c| c.n)
377 .unwrap_or(0);
378 if troubled > 0 {
379 return Ok(None);
380 }
381 let mut charged = vec![];
382 for month in &months {
383 #[derive(Deserialize)]
384 struct Month {
385 charged: Option<i64>,
386 unpaid: Option<i64>,
387 }
388 let next = {
389 let year: i32 = month[..4].parse().unwrap_or(1970);
390 let number: u32 = month[5..7].parse().unwrap_or(1);
391 if number == 12 { format!("{}-01", year + 1) } else { format!("{year}-{:02}", number + 1) }
392 };
393 let row = self
394 .db
395 .prepare(format!(
396 "SELECT
397 (SELECT -SUM(amount_micros) FROM ledger WHERE kind = 'usage' AND workspace IN ({marks})
398 AND created_at >= '{month}-01' AND created_at < '{next}-01') AS charged,
399 (SELECT COUNT(*) FROM workspace_invoices WHERE workspace IN ({marks}) AND reason = 'month'
400 AND period = '{month}' AND status <> 'paid') AS unpaid"
401 ))
402 .bind(&[members, members].concat())?
403 .first::<Month>(None)
404 .await?;
405 let Some(row) = row else { return Ok(None) };
406 if row.unpaid.unwrap_or(0) > 0 {
407 return Ok(None);
408 }
409 charged.push(row.charged.unwrap_or(0));
410 }
411 Ok(established_ceiling(&charged))
412 }
413
Usage limits: unpaid usage can only go so far414 /// A refusal, with the reason, when the workspace's work is stopped.
415 /// None while billing is off: a g1t without payments has no limits.
416 pub(crate) async fn stopped<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
417 if self.stripe.is_none() {
418 return Ok(None);
419 }
420 let limit = self.limit_of(workspace).await?;
421 Ok((limit.state == LimitState::Stopped).then(|| {
422 Outcome::fail(
423 FailureCode::PaymentRequired,
424 limit.message.unwrap_or_else(|| "This workspace is over its limit.".to_owned()),
425 )
426 }))
427 }
428
429 pub(crate) async fn limit(&self, a: LimitArgs) -> Result<Outcome<Limit>> {
430 let workspace = a.workspace.to_lowercase();
431 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
432 return Ok(members_only());
433 }
434 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
435 }
436
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put437 /// What a source cost so far this month. `security`, `context` and
438 /// `storage` are charged by billing once the month is over (see
439 /// `storage`); `deployments` charges its own.
Prices keep themselves current with what g1t pays440 pub(crate) async fn note_pending(&self, a: NotePendingArgs) -> Result<bool> {
441 let now = rfc3339(now_ms());
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put442 self.set_pending(&a.workspace, &a.source, &now[..7], a.cost_micros).await?;
Prices keep themselves current with what g1t pays443 Ok(true)
444 }
445
Billing accounts, terms and enterprises; g1t is no longer free446 /// Charges the saved card of each workspace nearing its limit, for what
447 /// it owes, so that a workspace that pays never has its work stopped.
448 /// Only with live payments: test-mode payments are not money and lower
449 /// nothing. Not for a workspace's own spend limit, which means stop, nor
450 /// for enterprises, which are invoiced.
451 pub(crate) async fn autopay(&self) -> Result<()> {
Two limits, real invoices, trust that grows by itself, sales signals452 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
Billing accounts, terms and enterprises; g1t is no longer free453 return Ok(());
Two limits, real invoices, trust that grows by itself, sales signals454 }
Billing accounts, terms and enterprises; g1t is no longer free455 #[derive(Deserialize)]
456 struct Candidate {
457 workspace: String,
458 }
459 let month_start = format!("{}-01", &rfc3339(now_ms())[..7]);
Two limits, real invoices, trust that grows by itself, sales signals460 // With a card, and not already declined: a declined card waits for
461 // the owners, rather than being tried again every few minutes.
Billing accounts, terms and enterprises; g1t is no longer free462 let candidates = self
463 .db
464 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals465 "SELECT DISTINCT ledger.workspace AS workspace
Billing accounts, terms and enterprises; g1t is no longer free466 FROM ledger JOIN accounts ON accounts.workspace = ledger.workspace
Two limits, real invoices, trust that grows by itself, sales signals467 LEFT JOIN limits ON limits.workspace = ledger.workspace
468 WHERE ledger.kind = 'usage' AND ledger.created_at >= ? AND accounts.customer_id IS NOT NULL
469 AND limits.autopay_failed_at IS NULL",
Billing accounts, terms and enterprises; g1t is no longer free470 )
471 .bind(&[month_start.as_str().into()])?
472 .all()
473 .await?
474 .results::<Candidate>()?;
475 for candidate in candidates {
476 let limit = self.limit_of(&candidate.workspace).await?;
Two limits, real invoices, trust that grows by itself, sales signals477 // Near g1t's ceiling on what is unpaid; the spend limit is the
478 // owners' and stops work by itself, but what is owed is still owed.
479 let near = limit.ceiling_micros.is_some_and(|ceiling| limit.exposure_micros * 5 >= ceiling * 4);
480 if !near || limit.trust == Trust::Internal || limit.account.starts_with("ent_") {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace481 continue;
482 }
Two limits, real invoices, trust that grows by itself, sales signals483 // An invoice for what it owes, charged to its card now: never
484 // the cost of what was free to it.
485 let today = rfc3339(now_ms())[..10].to_owned();
486 match self.invoice_workspace(&candidate.workspace, "threshold", &today).await? {
487 Ok(_) => {}
488 Err(why) => worker::console_log!("{}: no threshold invoice: {why}", candidate.workspace),
Billing accounts, terms and enterprises; g1t is no longer free489 }
490 }
491 Ok(())
492 }
493
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace494 /// Closes last month for each workspace with a card on file: charges
495 /// what it owed when the month ended. Live payments only, once per
496 /// workspace and month; a declined card stops work until it is paid.
497 /// Comped workspaces owe nothing, and enterprises are invoiced.
498 pub(crate) async fn close_months(&self) -> Result<()> {
Two limits, real invoices, trust that grows by itself, sales signals499 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace500 return Ok(());
Two limits, real invoices, trust that grows by itself, sales signals501 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace502 let now = rfc3339(now_ms());
503 let month_start = format!("{}-01", &now[..7]);
504 let closing = previous_month(&now[..7]);
505 #[derive(Deserialize)]
506 struct Open {
507 workspace: String,
508 balance: Option<i64>,
509 }
510 let open = self
511 .db
512 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals513 "SELECT accounts.workspace AS workspace,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace514 (SELECT SUM(amount_micros) FROM ledger
515 WHERE ledger.workspace = accounts.workspace AND ledger.created_at < ?1) AS balance
516 FROM accounts
517 WHERE accounts.customer_id IS NOT NULL
518 AND NOT EXISTS (SELECT 1 FROM month_closes
519 WHERE month_closes.workspace = accounts.workspace AND month_closes.month = ?2)
520 LIMIT 20",
521 )
522 .bind(&[month_start.as_str().into(), closing.as_str().into()])?
523 .all()
524 .await?
525 .results::<Open>()?;
526 for account in open {
527 let record = |status: &str, amount: i64, payment: Option<&str>, error: Option<&str>| {
528 self.db
529 .prepare(
530 "INSERT OR IGNORE INTO month_closes (workspace, month, status, amount_micros, payment_id, error, closed_at)
531 VALUES (?, ?, ?, ?, ?, ?, ?)",
532 )
533 .bind(&[
534 account.workspace.as_str().into(),
535 closing.as_str().into(),
536 status.into(),
537 (amount as f64).into(),
538 crate::optional(payment),
539 crate::optional(error),
540 now.as_str().into(),
541 ])
542 };
543 let payer = self.account_of(&account.workspace).await?;
544 if payer.terms.kind == TermsKind::Comped || payer.id.starts_with("ent_") {
545 record("skipped", 0, None, None)?.run().await?;
546 continue;
547 }
548 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 put549 if owed == 0 {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace550 record("nothing", 0, None, None)?.run().await?;
551 continue;
552 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put553 if !worth_charging(owed, self.plans.min_charge_micros) {
554 // Under the minimum charge: a card payment's fee would be
555 // too much of it. It stays owed and goes on the next
556 // invoice that reaches the minimum.
557 record("carried", owed, None, None)?.run().await?;
558 continue;
559 }
Two limits, real invoices, trust that grows by itself, sales signals560 match self.invoice_workspace(&account.workspace, "month", &closing).await? {
561 Ok(invoice) if invoice.status == "paid" => {
562 record("paid", invoice.amount_micros, Some(&invoice.invoice_id), None)?.run().await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace563 }
Two limits, real invoices, trust that grows by itself, sales signals564 Ok(invoice) => {
565 record("failed", invoice.amount_micros, Some(&invoice.invoice_id), Some("the card was declined"))?.run().await?;
566 }
567 Err(why) => {
568 record("nothing", 0, None, Some(&why))?.run().await?;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace569 }
570 }
571 }
572 Ok(())
573 }
574
575 /// Emails a workspace's owners as it passes 50%, 80% and 100% of its
576 /// limit, once each a month, and when its card was declined, so that
577 /// work never stops without warning.
578 pub(crate) async fn warn_limits(&self, identity: &worker::Fetcher) -> Result<()> {
579 if self.stripe.is_none() {
580 return Ok(());
581 }
582 let now = rfc3339(now_ms());
583 let month = &now[..7];
584 #[derive(Deserialize)]
585 struct Candidate {
586 workspace: String,
587 }
588 let candidates = self
589 .db
590 .prepare(
591 "SELECT DISTINCT workspace FROM ledger WHERE kind = 'usage' AND created_at >= ?1
592 UNION SELECT workspace FROM limits WHERE autopay_failed_at IS NOT NULL",
593 )
594 .bind(&[format!("{month}-01").into()])?
595 .all()
596 .await?
597 .results::<Candidate>()?;
598 #[derive(Deserialize)]
599 struct Told {
600 warned_month: Option<String>,
601 warned_level: Option<i64>,
602 autopay_failed_at: Option<String>,
603 declined_told_at: Option<String>,
604 }
605 for Candidate { workspace } in candidates {
606 let limit = self.limit_of(&workspace).await?;
607 let told = self
608 .db
609 .prepare("SELECT warned_month, warned_level, autopay_failed_at, declined_told_at FROM limits WHERE workspace = ?")
610 .bind(&[workspace.as_str().into()])?
611 .first::<Told>(None)
612 .await?;
613 let billing = format!("https://g1t.sh/{workspace}/-/billing");
614
615 // A declined card, once per decline.
616 if let Some(Told { autopay_failed_at: Some(failed), declined_told_at, .. }) = &told {
617 if declined_told_at.as_deref().is_none_or(|at| at < failed.as_str()) {
618 let sent = notify(
619 identity,
620 &workspace,
621 &format!("g1t: the card for {workspace} was declined"),
622 &limit.message.clone().unwrap_or_else(|| format!("g1t could not charge the card on file for {workspace}.")),
623 "Update the card",
624 &billing,
625 )
626 .await;
627 if sent {
628 self.db
629 .prepare("UPDATE limits SET declined_told_at = ? WHERE workspace = ?")
630 .bind(&[now.as_str().into(), workspace.as_str().into()])?
631 .run()
632 .await?;
633 }
634 }
635 }
636
637 let Some(ceiling) = limit.ceiling_micros.filter(|c| *c > 0) else { continue };
638 let level = warning_level(limit.exposure_micros, ceiling);
639 let already = told
640 .as_ref()
641 .filter(|t| t.warned_month.as_deref() == Some(month))
642 .and_then(|t| t.warned_level)
643 .unwrap_or(0);
644 if level <= already {
645 continue;
646 }
647 let (subject, intro) = match level {
648 100 => (
649 format!("g1t: {workspace} reached its usage limit"),
650 limit.message.clone().unwrap_or_else(|| format!("{workspace} reached its usage limit.")),
651 ),
652 _ => (
653 format!("g1t: {workspace} has used {level}% of its usage limit"),
654 format!(
655 "{workspace} has used {} of its {} usage limit this month. At the limit its sandboxes, builds and apps stop until it pays or the month turns. With a card on file, g1t charges it as the limit nears, so work keeps going.",
656 dollars_plain(limit.exposure_micros),
657 dollars_plain(ceiling),
658 ),
659 ),
660 };
661 if notify(identity, &workspace, &subject, &intro, "Open billing", &billing).await {
662 self.db
663 .prepare(
664 "INSERT INTO limits (workspace, warned_month, warned_level, updated_at) VALUES (?1, ?2, ?3, ?4)
665 ON CONFLICT (workspace) DO UPDATE SET warned_month = ?2, warned_level = ?3, updated_at = ?4",
666 )
667 .bind(&[workspace.as_str().into(), month.into(), (level as f64).into(), now.as_str().into()])?
668 .run()
669 .await?;
670 }
671 }
672 Ok(())
673 }
674
Usage limits: unpaid usage can only go so far675 pub(crate) async fn check_limit(&self, a: CheckLimitArgs) -> Result<Outcome<Limit>> {
676 Ok(Outcome::Ok(self.limit_of(&a.workspace).await?))
677 }
678
679 pub(crate) async fn set_spend_limit(&self, a: SetSpendLimitArgs) -> Result<Outcome<Limit>> {
680 let workspace = a.workspace.to_lowercase();
681 if a.actor.role_in(&workspace) != Some(Role::Owner) {
682 return Ok(Outcome::fail(
683 FailureCode::Forbidden,
684 "Only an owner can set the workspace's spend limit.",
685 ));
686 }
687 if a.spend_limit_micros.is_some_and(|limit| limit < 0) {
688 return Ok(Outcome::fail(FailureCode::Invalid, "A spend limit cannot be negative."));
689 }
Two limits, real invoices, trust that grows by itself, sales signals690 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 far691 self.db
692 .prepare(
Two limits, real invoices, trust that grows by itself, sales signals693 "INSERT INTO limits (workspace, spend_limit_micros, spend_limit_full, updated_at) VALUES (?1, ?2, ?3, ?4)
694 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 far695 )
Two limits, real invoices, trust that grows by itself, sales signals696 .bind(&[workspace.as_str().into(), limit, (if a.use_full_limit { 1 } else { 0 }).into(), rfc3339(now_ms()).into()])?
Usage limits: unpaid usage can only go so far697 .run()
698 .await?;
699 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
700 }
701}
702
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put703/// Whether `owed` is enough to charge a card: at least the minimum charge
704/// (`MIN_CHARGE_MICROS`). Less carries over to the next invoice.
705pub(crate) fn worth_charging(owed: i64, min_charge: i64) -> bool {
706 owed > 0 && owed >= min_charge
707}
708
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace709/// Which warning a workspace has reached: 100, 80, 50 or none (0).
710pub(crate) fn warning_level(exposure: i64, ceiling: i64) -> i64 {
711 if exposure >= ceiling {
712 100
713 } else if exposure * 5 >= ceiling * 4 {
714 80
715 } else if exposure * 2 >= ceiling {
716 50
717 } else {
718 0
719 }
720}
721
722/// Emails the workspace's owners through identity. False if nothing was sent.
723async fn notify(identity: &worker::Fetcher, workspace: &str, subject: &str, intro: &str, action: &str, link: &str) -> bool {
724 let args = g1t_contracts::identity::NotifyOwnersArgs {
725 workspace: workspace.to_owned(),
726 subject: subject.to_owned(),
727 intro: intro.to_owned(),
728 action: action.to_owned(),
729 link: link.to_owned(),
730 footer: "You get this because you own this workspace on g1t. Usage limits are explained at https://docs.g1t.sh/guides/usage-and-billing/#usage-limits".to_owned(),
731 };
732 match g1t_kit::call::<_, u32>(identity, "notify_owners", &args).await {
733 Ok(sent) => sent > 0,
734 Err(error) => {
735 worker::console_error!("could not tell {workspace}'s owners: {error}");
736 false
737 }
738 }
739}
740
741/// `2026-09` for `2026-10`, and `2025-12` for `2026-01`.
742pub(crate) fn previous_month(month: &str) -> String {
743 let year: i32 = month[..4].parse().unwrap_or(1970);
744 let number: u32 = month[5..7].parse().unwrap_or(1);
745 if number == 1 {
746 format!("{}-12", year - 1)
747 } else {
748 format!("{year}-{:02}", number - 1)
749 }
750}
751
Usage limits: unpaid usage can only go so far752#[cfg(test)]
753mod tests {
754 use super::*;
755
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace756 #[test]
Two limits, real invoices, trust that grows by itself, sales signals757 fn the_automatic_spend_limit_follows_last_month() {
758 assert_eq!(automatic_spend_limit(0), 200_000_000);
759 assert_eq!(automatic_spend_limit(50_000_000), 200_000_000);
760 assert_eq!(automatic_spend_limit(900_000_000), 1_800_000_000);
761 }
762
763 #[test]
764 fn three_steady_months_make_a_workspace_established() {
765 assert_eq!(established_ceiling(&[900_000_000, 850_000_000, 950_000_000]), Some(2_700_000_000));
766 assert_eq!(established_ceiling(&[5_000_000_000, 5_000_000_000, 5_000_000_000]), Some(10_000_000_000));
767 assert_eq!(established_ceiling(&[900_000_000, 10_000_000, 950_000_000]), None);
768 assert_eq!(established_ceiling(&[900_000_000, 900_000_000]), None);
769 }
770
771 #[test]
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace772 fn warnings_come_at_half_four_fifths_and_the_limit() {
773 assert_eq!(warning_level(0, 300), 0);
774 assert_eq!(warning_level(149, 300), 0);
775 assert_eq!(warning_level(150, 300), 50);
776 assert_eq!(warning_level(240, 300), 80);
777 assert_eq!(warning_level(300, 300), 100);
778 }
779
780 #[test]
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put781 fn amounts_under_the_minimum_carry_over() {
782 let min = 5_000_000;
783 assert!(!worth_charging(0, min));
784 assert!(!worth_charging(4_990_000, min));
785 assert!(worth_charging(5_000_000, min));
786 assert!(worth_charging(12_000_000, min));
787 // $3 carried from last month and $2.50 this month: charged together.
788 let carried = 3_000_000;
789 assert!(!worth_charging(carried, min));
790 assert!(worth_charging(carried + 2_500_000, min));
791 }
792
793 #[test]
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace794 fn the_month_before_wraps_the_year() {
795 assert_eq!(previous_month("2026-10"), "2026-09");
796 assert_eq!(previous_month("2026-01"), "2025-12");
797 }
798
Usage limits: unpaid usage can only go so far799 fn ceilings() -> Ceilings {
Billing accounts, terms and enterprises; g1t is no longer free800 Ceilings { new: 3_000_000, paid_min: 25_000_000, paid_max: 1_000_000_000 }
Usage limits: unpaid usage can only go so far801 }
802
803 #[test]
804 fn trust_grows_with_what_was_paid_within_bounds() {
805 assert_eq!(ceilings().for_paid(5_000_000), 25_000_000);
806 assert_eq!(ceilings().for_paid(100_000_000), 200_000_000);
807 assert_eq!(ceilings().for_paid(10_000_000_000), 1_000_000_000);
808 }
809
810 #[test]
811 fn work_warns_at_eighty_percent_and_stops_at_the_ceiling() {
812 assert_eq!(state(0, Some(100)), LimitState::Ok);
813 assert_eq!(state(79, Some(100)), LimitState::Ok);
814 assert_eq!(state(80, Some(100)), LimitState::Warning);
815 assert_eq!(state(100, Some(100)), LimitState::Stopped);
816 assert_eq!(state(1_000_000, None), LimitState::Ok);
817 }
818}