g1t/services/billing/src/limits.rs

1,109 lines52,381 bytesCodeBlame
1//! How far a workspace can run up costs g1t has not been paid for, and how
2//! far its owners let it spend.
3//!
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
6//! it. So each workspace has a ceiling on that unpaid usage:
7//!
8//! - **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.
17//! - **Internal**: g1t's own workspaces, with none here: what their work
18//! costs g1t has a monthly budget instead (see `budget`).
19//!
20//! 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
35//! under way finish.
36//!
37//! Usage counts at what it cost g1t or what it is charged, whichever is
38//! more. Test-mode payments are not money, so they do not raise trust.
39
40use g1t_contracts::billing::{
41 CheckLimitArgs, Limit, LimitArgs, LimitState, NotePendingArgs, PlanKind, SetSpendLimitArgs, TermsKind, Trust,
42};
43use g1t_contracts::time::rfc3339;
44use g1t_contracts::{FailureCode, Outcome, Role};
45use g1t_kit::now_ms;
46use serde::Deserialize;
47use worker::wasm_bindgen::JsValue;
48use worker::{Env, Result};
49
50use crate::features::dollars as dollars_plain;
51use crate::{Billing, members_only};
52
53/// The ceilings, from the billing service's variables.
54pub(crate) struct Ceilings {
55 /// `LIMIT_NEW_MICROS`: a free workspace's.
56 pub new: i64,
57 /// `LIMIT_PAID_MIN_MICROS` and `LIMIT_PAID_MAX_MICROS`: the bounds of a
58 /// paid workspace's, from what it has paid.
59 pub paid_min: i64,
60 pub paid_max: i64,
61}
62
63impl Ceilings {
64 pub(crate) fn from_env(env: &Env) -> Self {
65 let number = |name: &str, default: i64| {
66 env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok()).unwrap_or(default)
67 };
68 Ceilings {
69 new: number("LIMIT_NEW_MICROS", 3_000_000),
70 paid_min: number("LIMIT_PAID_MIN_MICROS", 25_000_000),
71 paid_max: number("LIMIT_PAID_MAX_MICROS", 1_000_000_000),
72 }
73 }
74
75 /// The ceiling for a workspace that has paid `paid` in live money.
76 pub(crate) fn for_paid(&self, paid: i64) -> i64 {
77 (paid * 2).clamp(self.paid_min, self.paid_max)
78 }
79}
80
81/// Where a workspace stands against its ceiling.
82pub(crate) fn state(exposure: i64, ceiling: Option<i64>) -> LimitState {
83 match ceiling {
84 Some(ceiling) if exposure >= ceiling => LimitState::Stopped,
85 Some(ceiling) if exposure * 5 >= ceiling * 4 => LimitState::Warning,
86 _ => LimitState::Ok,
87 }
88}
89
90/// The automatic monthly spend limit's floor: $200.
91pub(crate) const DEFAULT_SPEND_MICROS: i64 = 200_000_000;
92/// Established workspaces' ceiling: three times their steady monthly
93/// spend, up to $10,000.
94const ESTABLISHED_FACTOR: i64 = 3;
95const ESTABLISHED_MAX_MICROS: i64 = 10_000_000_000;
96/// A month counts toward Established at this much spend or more.
97const ESTABLISHED_MONTH_MICROS: i64 = 20_000_000;
98/// Payments raise trust once this old: past the time most bad cards are
99/// caught.
100pub(crate) const SETTLE_DAYS: u64 = 7;
101
102/// The automatic spend limit: $200, or twice last month's spend.
103pub(crate) fn automatic_spend_limit(last_month_charged: i64) -> i64 {
104 DEFAULT_SPEND_MICROS.max(last_month_charged * 2)
105}
106
107/// An Established workspace's ceiling, from its last three months'
108/// charges, if each was steady enough.
109pub(crate) fn established_ceiling(months: &[i64]) -> Option<i64> {
110 if months.len() < 3 || months.iter().any(|m| *m < ESTABLISHED_MONTH_MICROS) {
111 return None;
112 }
113 let average = months.iter().sum::<i64>() / months.len() as i64;
114 Some((average * ESTABLISHED_FACTOR).min(ESTABLISHED_MAX_MICROS))
115}
116
117/// Days since 1970-01-01 of a `YYYY-MM-DD…` date, for comparing dates
118/// without a clock (Howard Hinnant's days-from-civil).
119pub(crate) fn days(date: &str) -> i64 {
120 let year: i64 = date.get(..4).and_then(|y| y.parse().ok()).unwrap_or(1970);
121 let month: i64 = date.get(5..7).and_then(|m| m.parse().ok()).unwrap_or(1);
122 let day: i64 = date.get(8..10).and_then(|d| d.parse().ok()).unwrap_or(1);
123 let y = if month <= 2 { year - 1 } else { year };
124 let era = y.div_euclid(400);
125 let yoe = y - era * 400;
126 let mp = (month + 9) % 12;
127 let doy = (153 * mp + 2) / 5 + day - 1;
128 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
129 era * 146_097 + doe - 719_468
130}
131
132/// Whether a plan that started at `started_at` is still in its first
133/// billing cycle: its paid period ends no more than a month after it
134/// started (a renewal moves the end a month on), or, with no period known,
135/// it started within the last 31 days.
136pub(crate) fn in_first_cycle(started_at: &str, period_end: Option<&str>, now: &str) -> bool {
137 match period_end {
138 Some(end) => days(end) - days(started_at) <= 32 && days(now) <= days(end),
139 None => days(now) - days(started_at) <= 31,
140 }
141}
142
143/// g1t's ceiling for a workspace on the plan: the starting one in its
144/// first month; after it, what it has paid (or its Established ceiling),
145/// never less than the starting one.
146pub(crate) fn paid_ceiling(ceilings: &Ceilings, start: i64, first_month: bool, paid: i64, established: Option<i64>) -> i64 {
147 if first_month {
148 return start;
149 }
150 let from_paid = if paid > 0 { ceilings.for_paid(paid) } else { 0 };
151 start.max(from_paid).max(established.unwrap_or(0))
152}
153
154/// What the owners may set their spend limit to without asking, and the
155/// one-time raise if it is still theirs to use: up to the highest ceiling
156/// ever (or the current one, if higher) plus what is prepaid; once, twice
157/// the highest ceiling.
158pub(crate) fn spend_bounds(ceiling: i64, max_ever: i64, prepaid: i64, raised: bool) -> (i64, Option<i64>) {
159 let highest = ceiling.max(max_ever);
160 let available = highest + prepaid.max(0);
161 let once = (!raised).then(|| (highest * 2 + prepaid.max(0)).max(available));
162 (available, once)
163}
164
165/// Whether `requested` is a spend limit the owners may set themselves.
166/// `Ok(true)` when it takes the one-time raise.
167pub(crate) fn self_serve(requested: i64, available: i64, once: Option<i64>, raise_once: bool) -> std::result::Result<bool, String> {
168 if requested < 0 {
169 return Err("A spend limit cannot be negative.".to_owned());
170 }
171 if requested <= available {
172 return Ok(false);
173 }
174 match once {
175 Some(once) if raise_once && requested <= once => Ok(true),
176 Some(once) if raise_once => Err(format!(
177 "The one-time raise goes up to {}. For more, ask g1t with Raise my limit; the answer comes within one business day.",
178 dollars_plain(once)
179 )),
180 Some(once) => Err(format!(
181 "You can set up to {} yourself, or use your one-time raise to go up to {}. For more, ask g1t with Raise my limit.",
182 dollars_plain(available),
183 dollars_plain(once)
184 )),
185 None => Err(format!(
186 "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.",
187 dollars_plain(available)
188 )),
189 }
190}
191
192/// Which alert a measure has reached: 100, 90, 75, 50, or none (0).
193pub(crate) fn alert_level(used: i64, limit: i64) -> u32 {
194 if limit <= 0 || used <= 0 {
195 return 0;
196 }
197 for level in [100u32, 90, 75, 50] {
198 if used * 100 >= limit * i64::from(level) {
199 return level;
200 }
201 }
202 0
203}
204
205/// What is owed and what is prepaid, from this month's usage and payments
206/// and the balance the month started with (positive: paid in advance;
207/// negative: owed from before).
208pub(crate) fn exposure(used: i64, paid_month: i64, balance_before: i64) -> (i64, i64) {
209 let prepaid_in = balance_before.max(0);
210 let carried = (-balance_before).max(0);
211 let net = used - paid_month - prepaid_in;
212 (net.max(0) + carried, (-net).max(0))
213}
214
215#[derive(Deserialize)]
216struct LimitRow {
217 spend_limit_micros: Option<i64>,
218 #[serde(default)]
219 spend_limit_full: Option<i64>,
220 autopay_failed_at: Option<String>,
221 autopay_error: Option<String>,
222 #[serde(default)]
223 max_ceiling_micros: Option<i64>,
224 #[serde(default)]
225 granted_ceiling_micros: Option<i64>,
226 #[serde(default)]
227 raised_at: Option<String>,
228}
229
230#[derive(Deserialize)]
231struct Month {
232 used: Option<i64>,
233 paid: Option<i64>,
234}
235
236#[derive(Deserialize)]
237struct Paid {
238 paid: Option<i64>,
239}
240
241impl Billing {
242 /// The workspace's limit, worked out from the ledger of the account
243 /// that pays for it: its own, or its enterprise's, whose workspaces'
244 /// usage and payments count together.
245 pub(crate) async fn limit_of(&self, workspace: &str) -> Result<Limit> {
246 let workspace = workspace.to_lowercase();
247 let account = self.account_of(&workspace).await?;
248 let row = self
249 .db
250 .prepare(
251 "SELECT spend_limit_micros, spend_limit_full, autopay_failed_at, autopay_error,
252 max_ceiling_micros, granted_ceiling_micros, raised_at
253 FROM limits WHERE workspace = ?",
254 )
255 .bind(&[workspace.as_str().into()])?
256 .first::<LimitRow>(None)
257 .await?;
258 let now = rfc3339(now_ms());
259 let month_start = format!("{}-01", &now[..7]);
260 let marks = vec!["?"; account.workspaces.len().max(1)].join(", ");
261 let members: Vec<JsValue> = if account.workspaces.is_empty() {
262 vec![JsValue::from(workspace.as_str())]
263 } else {
264 account.workspaces.iter().map(|w| JsValue::from(w.as_str())).collect()
265 };
266 let mut with_month = members.clone();
267 with_month.push(month_start.as_str().into());
268 // Each usage entry at its cost to g1t or its charge, whichever is
269 // more; on the workspace's own provider, only what g1t charged.
270 // What the plan's included usage, the trial, the open-source pool
271 // or g1t itself paid for is not unpaid: those are budgets already
272 // paid for.
273 let month = self
274 .db
275 .prepare(format!(
276 "SELECT
277 SUM(CASE WHEN kind = 'usage' THEN
278 CASE WHEN COALESCE(billed_to, 'g1t') = 'g1t'
279 THEN MAX(COALESCE(cost_micros, 0) - COALESCE(credit_micros, 0)
280 - COALESCE(trial_micros, 0) - COALESCE(oss_micros, 0)
281 - COALESCE(given_micros, 0),
282 -amount_micros)
283 ELSE -amount_micros END
284 END) AS used,
285 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS paid
286 FROM ledger WHERE workspace IN ({marks}) AND created_at >= ?"
287 ))
288 .bind(&with_month)?
289 .first::<Month>(None)
290 .await?;
291 let (used, paid_month) = month.map_or((0, 0), |m| (m.used.unwrap_or(0), m.paid.unwrap_or(0)));
292 // And what is metered but not charged until the month closes.
293 let mut pending_args = members.clone();
294 pending_args.push(month_start[..7].into());
295 let pending = self
296 .db
297 .prepare(format!(
298 "SELECT SUM(charge_micros) AS paid FROM pending_usage WHERE workspace IN ({marks}) AND month = ?"
299 ))
300 .bind(&pending_args)?
301 .first::<Paid>(None)
302 .await?
303 .and_then(|row| row.paid)
304 .unwrap_or(0);
305 let used = used + pending;
306 // Test-mode payments are not money: they pay nothing off.
307 let live = self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live);
308 // The balance the month started with: owed from before (so a new
309 // month is not a fresh allowance for an account that never pays),
310 // or paid in advance. Credits g1t gave count; test-mode payments
311 // do not.
312 let mut before = members.clone();
313 before.push(month_start.as_str().into());
314 let balance_before = self
315 .db
316 .prepare(format!(
317 "SELECT SUM(CASE WHEN kind = 'usage' THEN amount_micros
318 WHEN kind = 'top_up' AND ({live} = 1 OR reference LIKE 'crd%') THEN amount_micros
319 ELSE 0 END) AS paid
320 FROM ledger WHERE workspace IN ({marks}) AND created_at < ?",
321 live = u8::from(live)
322 ))
323 .bind(&before)?
324 .first::<Paid>(None)
325 .await?
326 .and_then(|row| row.paid)
327 .unwrap_or(0);
328 let (exposure, prepaid) = exposure(used, if live { paid_month } else { 0 }, balance_before);
329
330 let plan = self.plan_kind(&workspace).await?;
331 let mut first_month = false;
332 let (trust, trust_ceiling) = match account.terms.kind {
333 TermsKind::Comped => (Trust::Internal, None),
334 _ if account.terms.ceiling_micros.is_some() => (Trust::Reviewed, account.terms.ceiling_micros),
335 _ => {
336 let paid = self.live_paid(&members).await?;
337 let established = if paid > 0 { self.established(&members).await? } else { None };
338 if plan == PlanKind::Free {
339 // Nothing on demand: only what a free workspace can owe.
340 (Trust::New, Some(self.ceilings.new))
341 } else {
342 first_month = plan == PlanKind::Paid && self.first_month(&workspace).await?;
343 let ceiling = paid_ceiling(&self.ceilings, self.plans.paid_start_micros, first_month, paid, established);
344 (if established.is_some() { Trust::Established } else { Trust::Paid }, Some(ceiling))
345 }
346 }
347 };
348 // A ceiling g1t granted is a floor under the trust ceiling.
349 let granted = row.as_ref().and_then(|row| row.granted_ceiling_micros);
350 let ceiling = trust_ceiling.map(|c| c.max(granted.unwrap_or(0)));
351 // The highest ceiling ever, kept as it rises.
352 let stored_max = row.as_ref().and_then(|row| row.max_ceiling_micros);
353 let max_ever = match (stored_max, ceiling) {
354 (Some(stored), Some(now)) => Some(stored.max(now)),
355 (stored, now) => stored.or(now),
356 };
357 if let (Some(max), true) = (max_ever, ceiling.is_some() && max_ever != stored_max && plan != PlanKind::Free) {
358 self.db
359 .prepare(
360 "INSERT INTO limits (workspace, max_ceiling_micros, updated_at) VALUES (?1, ?2, ?3)
361 ON CONFLICT (workspace) DO UPDATE SET max_ceiling_micros = MAX(COALESCE(max_ceiling_micros, 0), ?2), updated_at = ?3",
362 )
363 .bind(&[workspace.as_str().into(), (max as f64).into(), now.as_str().into()])?
364 .run()
365 .await?;
366 }
367 // This month's charges, and last month's, for the spend limit.
368 let (spent, last_month) = self.charged_months(&members, &month_start).await?;
369 let spent = spent + pending;
370 let raised_at = row.as_ref().and_then(|row| row.raised_at.clone());
371 let self_serve = matches!(trust, Trust::New | Trust::Paid | Trust::Established) && plan != PlanKind::Free;
372 let (available, raise_once) = match (ceiling, self_serve) {
373 (Some(ceiling), true) => {
374 let (available, once) = spend_bounds(ceiling, max_ever.unwrap_or(ceiling), prepaid, raised_at.is_some());
375 (Some(available), once)
376 }
377 (ceiling, _) => (ceiling, None),
378 };
379 // The owners' own monthly limit: theirs, none, or the automatic one
380 // ($200, or twice last month), which self-serve workspaces start on.
381 let chosen = row.as_ref().and_then(|row| row.spend_limit_micros);
382 let full = row.as_ref().and_then(|row| row.spend_limit_full).unwrap_or(0) == 1;
383 let default_spend_limit = chosen.is_none() && !full && self_serve;
384 let spend_limit = match (chosen, full) {
385 (Some(own), _) => Some(own),
386 (None, true) => None,
387 (None, false) if self_serve => Some(automatic_spend_limit(last_month)),
388 _ => None,
389 };
390 // A card declined when g1t charged it at the limit stops work until
391 // it is paid; any payment clears it.
392 let declined = row.as_ref().and_then(|row| row.autopay_failed_at.clone().map(|at| (at, row.autopay_error.clone())));
393 // Two limits: g1t's on what is unpaid, the owners' on what is spent.
394 let risk = state(exposure, ceiling);
395 let budget = state(spent, spend_limit);
396 let over_budget = budget == LimitState::Stopped;
397 let state = if declined.is_some() && exposure > 0 {
398 LimitState::Stopped
399 } else if risk == LimitState::Stopped || over_budget {
400 LimitState::Stopped
401 } else if risk == LimitState::Warning || budget == LimitState::Warning {
402 LimitState::Warning
403 } else {
404 LimitState::Ok
405 };
406 let who = if account.kind == g1t_contracts::billing::AccountKind::Enterprise {
407 format!("The {} enterprise, which pays for {workspace},", account.name)
408 } else {
409 format!("The {workspace} workspace")
410 };
411 let billing = format!("/{workspace}/-/billing");
412 let message = match state {
413 LimitState::Ok => None,
414 LimitState::Warning if budget == LimitState::Warning => Some(format!(
415 "{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}.",
416 dollars_plain(spent),
417 dollars_plain(spend_limit.unwrap_or_default()),
418 )),
419 LimitState::Warning => Some(format!(
420 "{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.",
421 dollars_plain(exposure),
422 dollars_plain(ceiling.unwrap_or_default()),
423 )),
424 LimitState::Stopped if declined.is_some() => Some(format!(
425 "{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}.",
426 declined.as_ref().and_then(|(_, error)| error.clone()).unwrap_or_else(|| "the card was declined".to_owned()),
427 )),
428 LimitState::Stopped => Some(if over_budget {
429 format!(
430 "{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}.",
431 dollars_plain(spend_limit.unwrap_or_default()),
432 )
433 } else {
434 format!(
435 "{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}.",
436 dollars_plain(ceiling.unwrap_or_default()),
437 )
438 }),
439 };
440 let growth = match trust {
441 Trust::New => Some("Free workspaces have no on-demand usage: the g1t plan starts at a $100 limit.".to_owned()),
442 Trust::Paid if first_month => Some(format!(
443 "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.",
444 dollars_plain(self.plans.paid_start_micros)
445 )),
446 Trust::Paid => Some(format!(
447 "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."
448 )),
449 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()),
450 Trust::Reviewed | Trust::Internal => None,
451 };
452 Ok(Limit {
453 workspace,
454 account: account.id,
455 account_name: account.name,
456 spent_micros: spent,
457 default_spend_limit,
458 available_micros: available,
459 growth,
460 trust,
461 exposure_micros: exposure,
462 ceiling_micros: ceiling,
463 trust_ceiling_micros: trust_ceiling,
464 spend_limit_micros: spend_limit,
465 state,
466 message,
467 prepaid_micros: prepaid,
468 max_ceiling_micros: max_ever.filter(|_| plan != PlanKind::Free),
469 raise_once_micros: raise_once,
470 raised_at,
471 first_month,
472 })
473 }
474
475 /// Whether the workspace's plan is in its first billing cycle.
476 pub(crate) async fn first_month(&self, workspace: &str) -> Result<bool> {
477 Ok(match self.plan_cycle(workspace).await? {
478 Some((started_at, period_end)) => in_first_cycle(&started_at, period_end.as_deref(), &rfc3339(now_ms())),
479 None => false,
480 })
481 }
482
483 /// Real money the workspaces have paid g1t, cleared: usage payments and
484 /// the plan's price. Nothing in test mode, and credits g1t gave are not
485 /// payments.
486 pub(crate) async fn live_paid(&self, members: &[JsValue]) -> Result<i64> {
487 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
488 return Ok(0);
489 }
490 let marks = vec!["?"; members.len().max(1)].join(", ");
491 let settled = rfc3339(now_ms() - SETTLE_DAYS * 24 * 60 * 60 * 1000);
492 Ok(self
493 .db
494 .prepare(format!(
495 "SELECT
496 (SELECT COALESCE(SUM(amount_micros), 0) FROM ledger
497 WHERE workspace IN ({marks}) AND kind = 'top_up' AND reference NOT LIKE 'crd%'
498 AND (amount_micros < 0
499 OR (disputed = 0 AND COALESCE(funding, '') <> 'prepaid'
500 AND created_at <= '{settled}')))
501 + (SELECT COALESCE(SUM(amount_micros), 0) FROM plan_payments
502 WHERE workspace IN ({marks}) AND paid_at <= '{settled}') AS paid"
503 ))
504 .bind(&[members, members].concat())?
505 .first::<Paid>(None)
506 .await?
507 .and_then(|row| row.paid)
508 .unwrap_or(0))
509 }
510
511 /// This month's charges and last month's, across the workspaces.
512 async fn charged_months(&self, members: &[JsValue], month_start: &str) -> Result<(i64, i64)> {
513 #[derive(Deserialize)]
514 struct Charged {
515 this_month: Option<i64>,
516 last_month: Option<i64>,
517 }
518 let last_start = format!("{}-01", previous_month(&month_start[..7]));
519 let marks = vec!["?"; members.len().max(1)].join(", ");
520 let row = self
521 .db
522 .prepare(format!(
523 "SELECT
524 -SUM(CASE WHEN created_at >= '{month_start}' THEN amount_micros END) AS this_month,
525 -SUM(CASE WHEN created_at >= '{last_start}' AND created_at < '{month_start}' THEN amount_micros END) AS last_month
526 FROM ledger WHERE kind = 'usage' AND workspace IN ({marks}) AND created_at >= '{last_start}'"
527 ))
528 .bind(members)?
529 .first::<Charged>(None)
530 .await?;
531 Ok(row.map_or((0, 0), |r| (r.this_month.unwrap_or(0).max(0), r.last_month.unwrap_or(0).max(0))))
532 }
533
534 /// An Established ceiling, if the workspaces have paid steadily: three
535 /// full months of real spend, each invoiced and paid, nothing declined
536 /// in 90 days and nothing ever disputed.
537 async fn established(&self, members: &[JsValue]) -> Result<Option<i64>> {
538 let marks = vec!["?"; members.len().max(1)].join(", ");
539 let now = rfc3339(now_ms());
540 let mut months = vec![];
541 let mut month = previous_month(&now[..7]);
542 for _ in 0..3 {
543 months.push(month.clone());
544 month = previous_month(&month);
545 }
546 #[derive(Deserialize)]
547 struct Count {
548 n: Option<i64>,
549 }
550 let troubled = self
551 .db
552 .prepare(format!(
553 "SELECT (SELECT COUNT(*) FROM ledger WHERE workspace IN ({marks}) AND disputed = 1)
554 + (SELECT COUNT(*) FROM limits WHERE workspace IN ({marks}) AND autopay_failed_at >= '{since}') AS n",
555 since = rfc3339(now_ms() - 90 * 24 * 60 * 60 * 1000)
556 ))
557 .bind(&[members, members].concat())?
558 .first::<Count>(None)
559 .await?
560 .and_then(|c| c.n)
561 .unwrap_or(0);
562 if troubled > 0 {
563 return Ok(None);
564 }
565 let mut charged = vec![];
566 for month in &months {
567 #[derive(Deserialize)]
568 struct Month {
569 charged: Option<i64>,
570 unpaid: Option<i64>,
571 }
572 let next = {
573 let year: i32 = month[..4].parse().unwrap_or(1970);
574 let number: u32 = month[5..7].parse().unwrap_or(1);
575 if number == 12 { format!("{}-01", year + 1) } else { format!("{year}-{:02}", number + 1) }
576 };
577 let row = self
578 .db
579 .prepare(format!(
580 "SELECT
581 (SELECT -SUM(amount_micros) FROM ledger WHERE kind = 'usage' AND workspace IN ({marks})
582 AND created_at >= '{month}-01' AND created_at < '{next}-01') AS charged,
583 (SELECT COUNT(*) FROM workspace_invoices WHERE workspace IN ({marks}) AND reason = 'month'
584 AND period = '{month}' AND status <> 'paid') AS unpaid"
585 ))
586 .bind(&[members, members].concat())?
587 .first::<Month>(None)
588 .await?;
589 let Some(row) = row else { return Ok(None) };
590 if row.unpaid.unwrap_or(0) > 0 {
591 return Ok(None);
592 }
593 charged.push(row.charged.unwrap_or(0));
594 }
595 Ok(established_ceiling(&charged))
596 }
597
598 /// A refusal, with the reason, when the workspace's work is stopped.
599 /// None while billing is off: a g1t without payments has no limits.
600 pub(crate) async fn stopped<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
601 if self.stripe.is_none() {
602 return Ok(None);
603 }
604 let limit = self.limit_of(workspace).await?;
605 Ok((limit.state == LimitState::Stopped).then(|| {
606 Outcome::fail(
607 FailureCode::PaymentRequired,
608 limit.message.unwrap_or_else(|| "This workspace is over its limit.".to_owned()),
609 )
610 }))
611 }
612
613 pub(crate) async fn limit(&self, a: LimitArgs) -> Result<Outcome<Limit>> {
614 let workspace = a.workspace.to_lowercase();
615 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
616 return Ok(members_only());
617 }
618 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
619 }
620
621 /// What a source cost so far this month. `security`, `context`,
622 /// `storage` and `git` are charged by billing once the month is over
623 /// (see `storage`); `deployments` charges its own.
624 pub(crate) async fn note_pending(&self, a: NotePendingArgs) -> Result<bool> {
625 // The actions cache is the plan's to pay for; free workspaces are
626 // held to its quota instead.
627 if crate::storage::PLAN_ONLY.contains(&a.source.as_str()) && !self.has_plan(&a.workspace.to_lowercase()).await? {
628 return Ok(false);
629 }
630 let now = rfc3339(now_ms());
631 let detail = a.detail.as_deref().map(str::trim).filter(|d| !d.is_empty()).map(|d| d.chars().take(200).collect::<String>());
632 self.set_pending(&a.workspace, &a.source, &now[..7], a.cost_micros, detail.as_deref()).await?;
633 Ok(true)
634 }
635
636 /// Charges the saved card of each workspace nearing its limit, for what
637 /// it owes, so that a workspace that pays never has its work stopped.
638 /// Only with live payments: test-mode payments are not money and lower
639 /// nothing. Not for a workspace's own spend limit, which means stop, nor
640 /// for enterprises, which are invoiced. A charge at the limit always
641 /// goes through, whatever the minimum charge.
642 pub(crate) async fn autopay(&self) -> Result<()> {
643 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
644 return Ok(());
645 }
646 #[derive(Deserialize)]
647 struct Candidate {
648 workspace: String,
649 }
650 let month_start = format!("{}-01", &rfc3339(now_ms())[..7]);
651 // With a card, and not already declined: a declined card waits for
652 // the owners, rather than being tried again every few minutes.
653 let candidates = self
654 .db
655 .prepare(
656 "SELECT DISTINCT ledger.workspace AS workspace
657 FROM ledger JOIN accounts ON accounts.workspace = ledger.workspace
658 LEFT JOIN limits ON limits.workspace = ledger.workspace
659 WHERE ledger.kind = 'usage' AND ledger.created_at >= ? AND accounts.customer_id IS NOT NULL
660 AND limits.autopay_failed_at IS NULL",
661 )
662 .bind(&[month_start.as_str().into()])?
663 .all()
664 .await?
665 .results::<Candidate>()?;
666 for candidate in candidates {
667 let limit = self.limit_of(&candidate.workspace).await?;
668 // Near g1t's ceiling on what is unpaid; the spend limit is the
669 // owners' and stops work by itself, but what is owed is still owed.
670 let near = limit.ceiling_micros.is_some_and(|ceiling| limit.exposure_micros * 5 >= ceiling * 4);
671 if !near || limit.trust == Trust::Internal || limit.account.starts_with("ent_") {
672 continue;
673 }
674 let today = rfc3339(now_ms())[..10].to_owned();
675 match self.invoice_workspace(&candidate.workspace, "threshold", &today).await? {
676 Ok(_) => {}
677 Err(why) => worker::console_log!("{}: no threshold invoice: {why}", candidate.workspace),
678 }
679 }
680 Ok(())
681 }
682
683 /// Closes last month for each workspace with a card on file: charges
684 /// what it owed when the month ended. Live payments only, once per
685 /// workspace and month; a declined card stops work until it is paid.
686 /// Comped workspaces owe nothing, and enterprises are invoiced. Only
687 /// here does the minimum charge apply: less carries over.
688 pub(crate) async fn close_months(&self) -> Result<()> {
689 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
690 return Ok(());
691 }
692 let now = rfc3339(now_ms());
693 let month_start = format!("{}-01", &now[..7]);
694 let closing = previous_month(&now[..7]);
695 #[derive(Deserialize)]
696 struct Open {
697 workspace: String,
698 balance: Option<i64>,
699 }
700 let open = self
701 .db
702 .prepare(
703 "SELECT accounts.workspace AS workspace,
704 (SELECT SUM(amount_micros) FROM ledger
705 WHERE ledger.workspace = accounts.workspace AND ledger.created_at < ?1) AS balance
706 FROM accounts
707 WHERE accounts.customer_id IS NOT NULL
708 AND NOT EXISTS (SELECT 1 FROM month_closes
709 WHERE month_closes.workspace = accounts.workspace AND month_closes.month = ?2)
710 LIMIT 20",
711 )
712 .bind(&[month_start.as_str().into(), closing.as_str().into()])?
713 .all()
714 .await?
715 .results::<Open>()?;
716 for account in open {
717 let record = |status: &str, amount: i64, payment: Option<&str>, error: Option<&str>| {
718 self.db
719 .prepare(
720 "INSERT OR IGNORE INTO month_closes (workspace, month, status, amount_micros, payment_id, error, closed_at)
721 VALUES (?, ?, ?, ?, ?, ?, ?)",
722 )
723 .bind(&[
724 account.workspace.as_str().into(),
725 closing.as_str().into(),
726 status.into(),
727 (amount as f64).into(),
728 crate::optional(payment),
729 crate::optional(error),
730 now.as_str().into(),
731 ])
732 };
733 let payer = self.account_of(&account.workspace).await?;
734 if payer.terms.kind == TermsKind::Comped || payer.id.starts_with("ent_") {
735 record("skipped", 0, None, None)?.run().await?;
736 continue;
737 }
738 let owed = (-account.balance.unwrap_or(0)).max(0);
739 if owed == 0 {
740 record("nothing", 0, None, None)?.run().await?;
741 continue;
742 }
743 if !worth_charging(owed, self.plans.min_charge_micros) {
744 // Under the minimum charge: a card payment's fee would be
745 // too much of it. It stays owed and goes on the next
746 // invoice that reaches the minimum.
747 record("carried", owed, None, None)?.run().await?;
748 continue;
749 }
750 match self.invoice_workspace(&account.workspace, "month", &closing).await? {
751 Ok(invoice) if invoice.status == "paid" => {
752 record("paid", invoice.amount_micros, Some(&invoice.invoice_id), None)?.run().await?;
753 }
754 Ok(invoice) => {
755 record("failed", invoice.amount_micros, Some(&invoice.invoice_id), Some("the card was declined"))?.run().await?;
756 }
757 Err(why) => {
758 record("nothing", 0, None, Some(&why))?.run().await?;
759 }
760 }
761 }
762 Ok(())
763 }
764
765 /// Emails a workspace's owners as it passes 50, 75, 90 and 100% of its
766 /// plan's included usage, its spend limit and g1t's ceiling, once each a
767 /// month; when its card was declined; and when a spend spike paused it.
768 /// The same alerts show in the app (`entitlements`).
769 pub(crate) async fn warn_limits(&self, identity: &worker::Fetcher) -> Result<()> {
770 if self.stripe.is_none() {
771 return Ok(());
772 }
773 let now = rfc3339(now_ms());
774 let month = &now[..7];
775 #[derive(Deserialize)]
776 struct Candidate {
777 workspace: String,
778 }
779 let candidates = self
780 .db
781 .prepare(
782 "SELECT DISTINCT workspace FROM ledger WHERE kind = 'usage' AND created_at >= ?1
783 UNION SELECT workspace FROM limits WHERE autopay_failed_at IS NOT NULL",
784 )
785 .bind(&[format!("{month}-01").into()])?
786 .all()
787 .await?
788 .results::<Candidate>()?;
789 #[derive(Deserialize)]
790 struct Told {
791 autopay_failed_at: Option<String>,
792 declined_told_at: Option<String>,
793 }
794 #[derive(Deserialize)]
795 struct Sent {
796 meter: String,
797 level: Option<i64>,
798 }
799 for Candidate { workspace } in candidates {
800 let told = self
801 .db
802 .prepare("SELECT autopay_failed_at, declined_told_at FROM limits WHERE workspace = ?")
803 .bind(&[workspace.as_str().into()])?
804 .first::<Told>(None)
805 .await?;
806 let billing = format!("https://g1t.sh/{workspace}/-/billing");
807
808 // A declined card, once per decline.
809 if let Some(Told { autopay_failed_at: Some(failed), declined_told_at }) = &told {
810 if declined_told_at.as_deref().is_none_or(|at| at < failed.as_str()) {
811 let limit = self.limit_of(&workspace).await?;
812 let sent = notify(
813 identity,
814 &workspace,
815 &format!("g1t: the card for {workspace} was declined"),
816 &limit.message.clone().unwrap_or_else(|| format!("g1t could not charge the card on file for {workspace}.")),
817 "Update the card",
818 &billing,
819 )
820 .await;
821 if sent {
822 self.db
823 .prepare("UPDATE limits SET declined_told_at = ? WHERE workspace = ?")
824 .bind(&[now.as_str().into(), workspace.as_str().into()])?
825 .run()
826 .await?;
827 }
828 }
829 }
830
831 // 50, 75, 90 and 100%, once each a month and meter: only the
832 // highest new level is emailed.
833 let alerts = self.alerts_for(&workspace).await?;
834 if alerts.is_empty() {
835 continue;
836 }
837 let sent: Vec<Sent> = self
838 .db
839 .prepare("SELECT meter, MAX(level) AS level FROM alerts_sent WHERE workspace = ? AND month = ? GROUP BY meter")
840 .bind(&[workspace.as_str().into(), month.into()])?
841 .all()
842 .await?
843 .results::<Sent>()?;
844 for alert in alerts {
845 let already = sent.iter().find(|s| s.meter == alert.meter).and_then(|s| s.level).unwrap_or(0);
846 if i64::from(alert.level) <= already {
847 continue;
848 }
849 let subject = match alert.meter.as_str() {
850 "included" => format!("g1t: {workspace} has used {}% of its included usage", alert.level),
851 "spend_limit" => format!("g1t: {workspace} has used {}% of its spend limit", alert.level),
852 _ => format!("g1t: {workspace} has used {}% of its usage limit", alert.level),
853 };
854 if notify(identity, &workspace, &subject, &alert.message, "Open billing", &billing).await {
855 self.db
856 .prepare(
857 "INSERT OR IGNORE INTO alerts_sent (workspace, month, meter, level, sent_at) VALUES (?1, ?2, ?3, ?4, ?5)",
858 )
859 .bind(&[workspace.as_str().into(), month.into(), alert.meter.as_str().into(), alert.level.into(), now.as_str().into()])?
860 .run()
861 .await?;
862 }
863 }
864 }
865 self.tell_spikes(identity).await?;
866 Ok(())
867 }
868
869 pub(crate) async fn check_limit(&self, a: CheckLimitArgs) -> Result<Outcome<Limit>> {
870 Ok(Outcome::Ok(self.limit_of(&a.workspace).await?))
871 }
872
873 /// The owners' spend limit: anywhere up to what is available without
874 /// asking; once, up to twice the highest ceiling (`raise_once`), which
875 /// also raises g1t's ceiling to match.
876 pub(crate) async fn set_spend_limit(&self, a: SetSpendLimitArgs) -> Result<Outcome<Limit>> {
877 let workspace = a.workspace.to_lowercase();
878 if a.actor.role_in(&workspace) != Some(Role::Owner) {
879 return Ok(Outcome::fail(
880 FailureCode::Forbidden,
881 "Only an owner can set the workspace's spend limit.",
882 ));
883 }
884 let before = self.limit_of(&workspace).await?;
885 let mut raising = false;
886 if let (Some(requested), false) = (a.spend_limit_micros, a.use_full_limit) {
887 match (before.available_micros, matches!(before.trust, Trust::Internal | Trust::Reviewed)) {
888 (_, true) | (None, _) => {
889 if requested < 0 {
890 return Ok(Outcome::fail(FailureCode::Invalid, "A spend limit cannot be negative."));
891 }
892 }
893 (Some(available), false) => match self_serve(requested, available, before.raise_once_micros, a.raise_once) {
894 Ok(uses_raise) => raising = uses_raise,
895 Err(why) => return Ok(Outcome::fail(FailureCode::Invalid, why)),
896 },
897 }
898 }
899 let now = rfc3339(now_ms());
900 let limit = if a.use_full_limit { JsValue::NULL } else { a.spend_limit_micros.map_or(JsValue::NULL, |limit| (limit as f64).into()) };
901 self.db
902 .prepare(
903 "INSERT INTO limits (workspace, spend_limit_micros, spend_limit_full, updated_at) VALUES (?1, ?2, ?3, ?4)
904 ON CONFLICT (workspace) DO UPDATE SET spend_limit_micros = ?2, spend_limit_full = ?3, updated_at = ?4",
905 )
906 .bind(&[workspace.as_str().into(), limit, (if a.use_full_limit { 1 } else { 0 }).into(), now.as_str().into()])?
907 .run()
908 .await?;
909 if raising {
910 let raised = a.spend_limit_micros.unwrap_or_default();
911 // The ceiling rises with it, once.
912 self.db
913 .prepare(
914 "UPDATE limits SET granted_ceiling_micros = MAX(COALESCE(granted_ceiling_micros, 0), ?2),
915 raised_at = ?3, updated_at = ?3 WHERE workspace = ?1 AND raised_at IS NULL",
916 )
917 .bind(&[workspace.as_str().into(), (raised as f64).into(), now.as_str().into()])?
918 .run()
919 .await?;
920 let account = self.account_of(&workspace).await?;
921 self.audit(&account.id, "raise_once", &format!("{workspace} used its one-time raise: {}", dollars_plain(raised)), &a.actor.username)
922 .await?;
923 }
924 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
925 }
926}
927
928/// Whether `owed` is enough to charge a card when a month closes: at least
929/// the minimum charge (`MIN_CHARGE_MICROS`). Less carries over to the next
930/// invoice. Charges at a limit do not ask.
931pub(crate) fn worth_charging(owed: i64, min_charge: i64) -> bool {
932 owed > 0 && owed >= min_charge
933}
934
935/// Emails the workspace's owners through identity. False if nothing was sent.
936pub(crate) async fn notify(identity: &worker::Fetcher, workspace: &str, subject: &str, intro: &str, action: &str, link: &str) -> bool {
937 let args = g1t_contracts::identity::NotifyOwnersArgs {
938 workspace: workspace.to_owned(),
939 subject: subject.to_owned(),
940 intro: intro.to_owned(),
941 action: action.to_owned(),
942 link: link.to_owned(),
943 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(),
944 };
945 match g1t_kit::call::<_, u32>(identity, "notify_owners", &args).await {
946 Ok(sent) => sent > 0,
947 Err(error) => {
948 worker::console_error!("could not tell {workspace}'s owners: {error}");
949 false
950 }
951 }
952}
953
954/// `2026-09` for `2026-10`, and `2025-12` for `2026-01`.
955pub(crate) fn previous_month(month: &str) -> String {
956 let year: i32 = month[..4].parse().unwrap_or(1970);
957 let number: u32 = month[5..7].parse().unwrap_or(1);
958 if number == 1 {
959 format!("{}-12", year - 1)
960 } else {
961 format!("{year}-{:02}", number - 1)
962 }
963}
964
965#[cfg(test)]
966mod tests {
967 use super::*;
968
969 #[test]
970 fn the_automatic_spend_limit_follows_last_month() {
971 assert_eq!(automatic_spend_limit(0), 200_000_000);
972 assert_eq!(automatic_spend_limit(50_000_000), 200_000_000);
973 assert_eq!(automatic_spend_limit(900_000_000), 1_800_000_000);
974 }
975
976 #[test]
977 fn three_steady_months_make_a_workspace_established() {
978 assert_eq!(established_ceiling(&[900_000_000, 850_000_000, 950_000_000]), Some(2_700_000_000));
979 assert_eq!(established_ceiling(&[5_000_000_000, 5_000_000_000, 5_000_000_000]), Some(10_000_000_000));
980 assert_eq!(established_ceiling(&[900_000_000, 10_000_000, 950_000_000]), None);
981 assert_eq!(established_ceiling(&[900_000_000, 900_000_000]), None);
982 }
983
984 #[test]
985 fn alerts_come_at_half_three_quarters_ninety_and_the_limit() {
986 assert_eq!(alert_level(0, 10_000_000), 0);
987 assert_eq!(alert_level(4_999_999, 10_000_000), 0);
988 assert_eq!(alert_level(5_000_000, 10_000_000), 50);
989 assert_eq!(alert_level(7_500_000, 10_000_000), 75);
990 assert_eq!(alert_level(8_999_999, 10_000_000), 75);
991 assert_eq!(alert_level(9_000_000, 10_000_000), 90);
992 assert_eq!(alert_level(10_000_000, 10_000_000), 100);
993 assert_eq!(alert_level(25_000_000, 10_000_000), 100);
994 // Nothing to measure against: no alert.
995 assert_eq!(alert_level(5, 0), 0);
996 }
997
998 #[test]
999 fn amounts_under_the_minimum_carry_over_only_at_the_month_close() {
1000 let min = 5_000_000;
1001 assert!(!worth_charging(0, min));
1002 assert!(!worth_charging(4_990_000, min));
1003 assert!(worth_charging(5_000_000, min));
1004 assert!(worth_charging(12_000_000, min));
1005 // $3 carried from last month and $2.50 this month: charged together.
1006 let carried = 3_000_000;
1007 assert!(!worth_charging(carried, min));
1008 assert!(worth_charging(carried + 2_500_000, min));
1009 }
1010
1011 #[test]
1012 fn the_month_before_wraps_the_year() {
1013 assert_eq!(previous_month("2026-10"), "2026-09");
1014 assert_eq!(previous_month("2026-01"), "2025-12");
1015 }
1016
1017 fn ceilings() -> Ceilings {
1018 Ceilings { new: 3_000_000, paid_min: 25_000_000, paid_max: 1_000_000_000 }
1019 }
1020
1021 #[test]
1022 fn trust_grows_with_what_was_paid_within_bounds() {
1023 assert_eq!(ceilings().for_paid(5_000_000), 25_000_000);
1024 assert_eq!(ceilings().for_paid(100_000_000), 200_000_000);
1025 assert_eq!(ceilings().for_paid(10_000_000_000), 1_000_000_000);
1026 }
1027
1028 #[test]
1029 fn a_new_paid_workspace_starts_at_a_hundred_dollars_and_only_goes_up() {
1030 let start = 100_000_000;
1031 // The first month: the starting ceiling, whatever was paid.
1032 assert_eq!(paid_ceiling(&ceilings(), start, true, 900_000_000, None), start);
1033 // After it, with little paid: never below the start.
1034 assert_eq!(paid_ceiling(&ceilings(), start, false, 20_000_000, None), start);
1035 assert_eq!(paid_ceiling(&ceilings(), start, false, 0, None), start);
1036 // Payments that cleared raise it: twice what was paid.
1037 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, None), 600_000_000);
1038 // Established follows the monthly spend.
1039 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, Some(2_700_000_000)), 2_700_000_000);
1040 }
1041
1042 #[test]
1043 fn the_first_billing_cycle_is_the_first_month() {
1044 // A plan that started on the 5th, paid through the 5th of next month.
1045 assert!(in_first_cycle("2026-10-05T10:00:00Z", Some("2026-11-05T10:00:00Z"), "2026-10-20T00:00:00Z"));
1046 // Renewed: the period now ends two months after the start.
1047 assert!(!in_first_cycle("2026-10-05T10:00:00Z", Some("2026-12-05T10:00:00Z"), "2026-11-20T00:00:00Z"));
1048 // No period known yet: the first 31 days.
1049 assert!(in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-04T00:00:00Z"));
1050 assert!(!in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-10T00:00:00Z"));
1051 // Day counting is exact across months and years.
1052 assert_eq!(days("1970-01-01"), 0);
1053 assert_eq!(days("2026-11-01") - days("2026-10-01"), 31);
1054 assert_eq!(days("2028-03-01") - days("2028-02-28"), 2);
1055 assert_eq!(days("2027-01-01") - days("2026-12-31"), 1);
1056 }
1057
1058 #[test]
1059 fn owners_set_their_limit_up_to_the_highest_ceiling_without_asking() {
1060 // First month at $100; the highest ever is $100.
1061 let (available, once) = spend_bounds(100_000_000, 100_000_000, 0, false);
1062 assert_eq!(available, 100_000_000);
1063 assert_eq!(once, Some(200_000_000));
1064 assert_eq!(self_serve(80_000_000, available, once, false), Ok(false));
1065 assert_eq!(self_serve(100_000_000, available, once, false), Ok(false));
1066 // Above it without the raise: refused, saying what to do.
1067 assert!(self_serve(150_000_000, available, once, false).unwrap_err().contains("one-time raise"));
1068 // With the raise: up to twice the highest ceiling, once.
1069 assert_eq!(self_serve(200_000_000, available, once, true), Ok(true));
1070 assert!(self_serve(200_000_001, available, once, true).unwrap_err().contains("Raise my limit"));
1071 // Once used, it is gone.
1072 let (available, once) = spend_bounds(200_000_000, 200_000_000, 0, true);
1073 assert_eq!(once, None);
1074 assert_eq!(self_serve(200_000_000, available, once, false), Ok(false));
1075 assert!(self_serve(300_000_000, available, once, true).unwrap_err().contains("is used"));
1076 // A ceiling that came down still leaves the highest one available.
1077 let (available, _) = spend_bounds(100_000_000, 400_000_000, 0, true);
1078 assert_eq!(available, 400_000_000);
1079 assert!(self_serve(-1, available, None, false).is_err());
1080 }
1081
1082 #[test]
1083 fn prepaying_raises_what_can_be_used_at_once() {
1084 // $500 prepaid this month, $120 used: nothing owed, $380 left.
1085 assert_eq!(exposure(120_000_000, 500_000_000, 0), (0, 380_000_000));
1086 // Prepaid last month and carried in.
1087 assert_eq!(exposure(120_000_000, 0, 500_000_000), (0, 380_000_000));
1088 // Used past the prepayment: the rest is owed.
1089 assert_eq!(exposure(620_000_000, 500_000_000, 0), (120_000_000, 0));
1090 // Owed from before adds to this month's.
1091 assert_eq!(exposure(10_000_000, 0, -4_000_000), (14_000_000, 0));
1092 // With a $100 ceiling and $500 prepaid, work stops at $600 of use,
1093 // not at $100.
1094 let ceiling = 100_000_000;
1095 assert_eq!(state(exposure(599_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Warning);
1096 assert_eq!(state(exposure(600_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Stopped);
1097 // And the owners may set their spend limit that much higher.
1098 assert_eq!(spend_bounds(ceiling, ceiling, 500_000_000, true).0, 600_000_000);
1099 }
1100
1101 #[test]
1102 fn work_warns_at_eighty_percent_and_stops_at_the_ceiling() {
1103 assert_eq!(state(0, Some(100)), LimitState::Ok);
1104 assert_eq!(state(79, Some(100)), LimitState::Ok);
1105 assert_eq!(state(80, Some(100)), LimitState::Warning);
1106 assert_eq!(state(100, Some(100)), LimitState::Stopped);
1107 assert_eq!(state(1_000_000, None), LimitState::Ok);
1108 }
1109}