g1t/services/billing/src/limits.rs

1,139 lines54,467 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 futures_util::future::{try_join, try_join5, try_join_all};
41use g1t_contracts::billing::{
42 BillingAccount, CheckLimitArgs, Limit, LimitArgs, LimitState, NotePendingArgs, PlanKind, SetSpendLimitArgs, TermsKind, Trust,
43};
44use 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 {
56 /// `LIMIT_NEW_MICROS`: a free workspace's.
57 pub new: i64,
58 /// `LIMIT_PAID_MIN_MICROS` and `LIMIT_PAID_MAX_MICROS`: the bounds of a
59 /// paid workspace's, from what it has paid.
60 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
91/// 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.
101pub(crate) const SETTLE_DAYS: u64 = 7;
102
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}
107
108/// 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
118/// 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
216#[derive(Deserialize)]
217struct LimitRow {
218 spend_limit_micros: Option<i64>,
219 #[serde(default)]
220 spend_limit_full: Option<i64>,
221 autopay_failed_at: Option<String>,
222 autopay_error: Option<String>,
223 #[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>,
229}
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 {
243 /// 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.
246 pub(crate) async fn limit_of(&self, workspace: &str) -> Result<Limit> {
247 let workspace = workspace.to_lowercase();
248 let account = self.account_of(&workspace).await?;
249 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();
257 let now = rfc3339(now_ms());
258 let month_start = format!("{}-01", &now[..7]);
259 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 };
265 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 };
276 let mut with_month = members.clone();
277 with_month.push(month_start.as_str().into());
278 // Each usage entry at its cost to g1t or its charge, whichever is
279 // 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.
283 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 };
302 // And what is metered but not charged until the month closes.
303 let mut pending_args = members.clone();
304 pending_args.push(month_start[..7].into());
305 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 };
318 // Test-mode payments are not money: they pay nothing off.
319 let live = self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live);
320 // 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.
324 let mut before = members.clone();
325 before.push(month_start.as_str().into());
326 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 }
366 }
367 })
368 };
369 // 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
379 // 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 }
398 let spent = spent + pending;
399 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 };
408 // 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 };
419 // 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())));
422 // 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) || risk == LimitState::Stopped || over_budget {
427 LimitState::Stopped
428 } else if risk == LimitState::Warning || budget == LimitState::Warning {
429 LimitState::Warning
430 } else {
431 LimitState::Ok
432 };
433 let who = if account.kind == g1t_contracts::billing::AccountKind::Enterprise {
434 format!("The {} enterprise, which pays for {workspace},", account.name)
435 } else {
436 format!("The {workspace} workspace")
437 };
438 let billing = format!("/{workspace}/-/billing");
439 let message = match state {
440 LimitState::Ok => None,
441 LimitState::Warning if budget == LimitState::Warning => Some(format!(
442 "{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}.",
443 dollars_plain(spent),
444 dollars_plain(spend_limit.unwrap_or_default()),
445 )),
446 LimitState::Warning => Some(format!(
447 "{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.",
448 dollars_plain(exposure),
449 dollars_plain(ceiling.unwrap_or_default()),
450 )),
451 LimitState::Stopped if declined.is_some() => Some(format!(
452 "{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}.",
453 declined.as_ref().and_then(|(_, error)| error.clone()).unwrap_or_else(|| "the card was declined".to_owned()),
454 )),
455 LimitState::Stopped => Some(if over_budget {
456 format!(
457 "{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}.",
458 dollars_plain(spend_limit.unwrap_or_default()),
459 )
460 } else {
461 format!(
462 "{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}.",
463 dollars_plain(ceiling.unwrap_or_default()),
464 )
465 }),
466 };
467 let growth = match trust {
468 Trust::New => Some("Free workspaces have no on-demand usage: the g1t plan starts at a $100 limit.".to_owned()),
469 Trust::Paid if first_month => Some(format!(
470 "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.",
471 dollars_plain(self.plans.paid_start_micros)
472 )),
473 Trust::Paid => Some(format!(
474 "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."
475 )),
476 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()),
477 Trust::Reviewed | Trust::Internal => None,
478 };
479 Ok(Limit {
480 workspace,
481 account: account.id.clone(),
482 account_name: account.name.clone(),
483 spent_micros: spent,
484 default_spend_limit,
485 available_micros: available,
486 growth,
487 trust,
488 exposure_micros: exposure,
489 ceiling_micros: ceiling,
490 trust_ceiling_micros: trust_ceiling,
491 spend_limit_micros: spend_limit,
492 state,
493 message,
494 prepaid_micros: prepaid,
495 max_ceiling_micros: max_ever.filter(|_| plan != PlanKind::Free),
496 raise_once_micros: raise_once,
497 raised_at,
498 first_month,
499 })
500 }
501
502 /// Whether the workspace's plan is in its first billing cycle.
503 pub(crate) async fn first_month(&self, workspace: &str) -> Result<bool> {
504 Ok(match self.plan_cycle(workspace).await? {
505 Some((started_at, period_end)) => in_first_cycle(&started_at, period_end.as_deref(), &rfc3339(now_ms())),
506 None => false,
507 })
508 }
509
510 /// Real money the workspaces have paid g1t, cleared: usage payments and
511 /// the plan's price. Nothing in test mode, and credits g1t gave are not
512 /// payments.
513 pub(crate) async fn live_paid(&self, members: &[JsValue]) -> Result<i64> {
514 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
515 return Ok(0);
516 }
517 let marks = vec!["?"; members.len().max(1)].join(", ");
518 let settled = rfc3339(now_ms() - SETTLE_DAYS * 24 * 60 * 60 * 1000);
519 Ok(self
520 .db
521 .prepare(format!(
522 "SELECT
523 (SELECT COALESCE(SUM(amount_micros), 0) FROM ledger
524 WHERE workspace IN ({marks}) AND kind = 'top_up' AND reference NOT LIKE 'crd%'
525 AND (amount_micros < 0
526 OR (disputed = 0 AND COALESCE(funding, '') <> 'prepaid'
527 AND created_at <= '{settled}')))
528 + (SELECT COALESCE(SUM(amount_micros), 0) FROM plan_payments
529 WHERE workspace IN ({marks}) AND paid_at <= '{settled}') AS paid"
530 ))
531 .bind(&[members, members].concat())?
532 .first::<Paid>(None)
533 .await?
534 .and_then(|row| row.paid)
535 .unwrap_or(0))
536 }
537
538 /// This month's charges and last month's, across the workspaces.
539 async fn charged_months(&self, members: &[JsValue], month_start: &str) -> Result<(i64, i64)> {
540 #[derive(Deserialize)]
541 struct Charged {
542 this_month: Option<i64>,
543 last_month: Option<i64>,
544 }
545 let last_start = format!("{}-01", previous_month(&month_start[..7]));
546 let marks = vec!["?"; members.len().max(1)].join(", ");
547 let row = self
548 .db
549 .prepare(format!(
550 "SELECT
551 -SUM(CASE WHEN created_at >= '{month_start}' THEN amount_micros END) AS this_month,
552 -SUM(CASE WHEN created_at >= '{last_start}' AND created_at < '{month_start}' THEN amount_micros END) AS last_month
553 FROM ledger WHERE kind = 'usage' AND workspace IN ({marks}) AND created_at >= '{last_start}'"
554 ))
555 .bind(members)?
556 .first::<Charged>(None)
557 .await?;
558 Ok(row.map_or((0, 0), |r| (r.this_month.unwrap_or(0).max(0), r.last_month.unwrap_or(0).max(0))))
559 }
560
561 /// An Established ceiling, if the workspaces have paid steadily: three
562 /// full months of real spend, each invoiced and paid, nothing declined
563 /// in 90 days and nothing ever disputed.
564 async fn established(&self, members: &[JsValue]) -> Result<Option<i64>> {
565 let marks = vec!["?"; members.len().max(1)].join(", ");
566 let now = rfc3339(now_ms());
567 let mut months = vec![];
568 let mut month = previous_month(&now[..7]);
569 for _ in 0..3 {
570 months.push(month.clone());
571 month = previous_month(&month);
572 }
573 #[derive(Deserialize)]
574 struct Count {
575 n: Option<i64>,
576 }
577 let troubled = async {
578 Ok::<i64, worker::Error>(
579 self.db
580 .prepare(format!(
581 "SELECT (SELECT COUNT(*) FROM ledger WHERE workspace IN ({marks}) AND disputed = 1)
582 + (SELECT COUNT(*) FROM limits WHERE workspace IN ({marks}) AND autopay_failed_at >= '{since}') AS n",
583 since = rfc3339(now_ms() - 90 * 24 * 60 * 60 * 1000)
584 ))
585 .bind(&[members, members].concat())?
586 .first::<Count>(None)
587 .await?
588 .and_then(|c| c.n)
589 .unwrap_or(0),
590 )
591 };
592 #[derive(Deserialize)]
593 struct Month {
594 charged: Option<i64>,
595 unpaid: Option<i64>,
596 }
597 let read_month = |month: &String| {
598 let next = {
599 let year: i32 = month[..4].parse().unwrap_or(1970);
600 let number: u32 = month[5..7].parse().unwrap_or(1);
601 if number == 12 { format!("{}-01", year + 1) } else { format!("{year}-{:02}", number + 1) }
602 };
603 let sql = format!(
604 "SELECT
605 (SELECT -SUM(amount_micros) FROM ledger WHERE kind = 'usage' AND workspace IN ({marks})
606 AND created_at >= '{month}-01' AND created_at < '{next}-01') AS charged,
607 (SELECT COUNT(*) FROM workspace_invoices WHERE workspace IN ({marks}) AND reason = 'month'
608 AND period = '{month}' AND status <> 'paid') AS unpaid"
609 );
610 async move { self.db.prepare(sql).bind(&[members, members].concat())?.first::<Month>(None).await }
611 };
612 // The check for trouble and the three months are read at once; the
613 // answer is the one reading them in turn and stopping early gives.
614 let (troubled, rows) = try_join(troubled, try_join_all(months.iter().map(read_month))).await?;
615 if troubled > 0 {
616 return Ok(None);
617 }
618 let mut charged = vec![];
619 for row in rows {
620 let Some(row) = row else { return Ok(None) };
621 if row.unpaid.unwrap_or(0) > 0 {
622 return Ok(None);
623 }
624 charged.push(row.charged.unwrap_or(0));
625 }
626 Ok(established_ceiling(&charged))
627 }
628
629 /// A refusal, with the reason, when the workspace's work is stopped.
630 /// None while billing is off: a g1t without payments has no limits.
631 pub(crate) async fn stopped<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
632 if self.stripe.is_none() {
633 return Ok(None);
634 }
635 let limit = self.limit_of(workspace).await?;
636 Ok((limit.state == LimitState::Stopped).then(|| {
637 Outcome::fail(
638 FailureCode::PaymentRequired,
639 limit.message.unwrap_or_else(|| "This workspace is over its limit.".to_owned()),
640 )
641 }))
642 }
643
644 pub(crate) async fn limit(&self, a: LimitArgs) -> Result<Outcome<Limit>> {
645 let workspace = a.workspace.to_lowercase();
646 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
647 return Ok(members_only());
648 }
649 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
650 }
651
652 /// What a source cost so far this month. `security`, `context`,
653 /// `storage` and `git` are charged by billing once the month is over
654 /// (see `storage`); `deployments` charges its own.
655 pub(crate) async fn note_pending(&self, a: NotePendingArgs) -> Result<bool> {
656 // The actions cache is the plan's to pay for; free workspaces are
657 // held to its quota instead.
658 if crate::storage::PLAN_ONLY.contains(&a.source.as_str()) && !self.has_plan(&a.workspace.to_lowercase()).await? {
659 return Ok(false);
660 }
661 let now = rfc3339(now_ms());
662 let detail = a.detail.as_deref().map(str::trim).filter(|d| !d.is_empty()).map(|d| d.chars().take(200).collect::<String>());
663 self.set_pending(&a.workspace, &a.source, &now[..7], a.cost_micros, detail.as_deref()).await?;
664 Ok(true)
665 }
666
667 /// Charges the saved card of each workspace nearing its limit, for what
668 /// it owes, so that a workspace that pays never has its work stopped.
669 /// Only with live payments: test-mode payments are not money and lower
670 /// nothing. Not for a workspace's own spend limit, which means stop, nor
671 /// for enterprises, which are invoiced. A charge at the limit always
672 /// goes through, whatever the minimum charge.
673 pub(crate) async fn autopay(&self) -> Result<()> {
674 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
675 return Ok(());
676 }
677 #[derive(Deserialize)]
678 struct Candidate {
679 workspace: String,
680 }
681 let month_start = format!("{}-01", &rfc3339(now_ms())[..7]);
682 // With a card, and not already declined: a declined card waits for
683 // the owners, rather than being tried again every few minutes.
684 let candidates = self
685 .db
686 .prepare(
687 "SELECT DISTINCT ledger.workspace AS workspace
688 FROM ledger JOIN accounts ON accounts.workspace = ledger.workspace
689 LEFT JOIN limits ON limits.workspace = ledger.workspace
690 WHERE ledger.kind = 'usage' AND ledger.created_at >= ? AND accounts.customer_id IS NOT NULL
691 AND limits.autopay_failed_at IS NULL",
692 )
693 .bind(&[month_start.as_str().into()])?
694 .all()
695 .await?
696 .results::<Candidate>()?;
697 for candidate in candidates {
698 let limit = self.limit_of(&candidate.workspace).await?;
699 // Near g1t's ceiling on what is unpaid; the spend limit is the
700 // owners' and stops work by itself, but what is owed is still owed.
701 let near = limit.ceiling_micros.is_some_and(|ceiling| limit.exposure_micros * 5 >= ceiling * 4);
702 if !near || limit.trust == Trust::Internal || limit.account.starts_with("ent_") {
703 continue;
704 }
705 let today = rfc3339(now_ms())[..10].to_owned();
706 match self.invoice_workspace(&candidate.workspace, "threshold", &today).await? {
707 Ok(_) => {}
708 Err(why) => worker::console_log!("{}: no threshold invoice: {why}", candidate.workspace),
709 }
710 }
711 Ok(())
712 }
713
714 /// Closes last month for each workspace with a card on file: charges
715 /// what it owed when the month ended. Live payments only, once per
716 /// workspace and month; a declined card stops work until it is paid.
717 /// Comped workspaces owe nothing, and enterprises are invoiced. Only
718 /// here does the minimum charge apply: less carries over.
719 pub(crate) async fn close_months(&self) -> Result<()> {
720 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
721 return Ok(());
722 }
723 let now = rfc3339(now_ms());
724 let month_start = format!("{}-01", &now[..7]);
725 let closing = previous_month(&now[..7]);
726 #[derive(Deserialize)]
727 struct Open {
728 workspace: String,
729 balance: Option<i64>,
730 }
731 let open = self
732 .db
733 .prepare(
734 "SELECT accounts.workspace AS workspace,
735 (SELECT SUM(amount_micros) FROM ledger
736 WHERE ledger.workspace = accounts.workspace AND ledger.created_at < ?1) AS balance
737 FROM accounts
738 WHERE accounts.customer_id IS NOT NULL
739 AND NOT EXISTS (SELECT 1 FROM month_closes
740 WHERE month_closes.workspace = accounts.workspace AND month_closes.month = ?2)
741 LIMIT 20",
742 )
743 .bind(&[month_start.as_str().into(), closing.as_str().into()])?
744 .all()
745 .await?
746 .results::<Open>()?;
747 for account in open {
748 let record = |status: &str, amount: i64, payment: Option<&str>, error: Option<&str>| {
749 self.db
750 .prepare(
751 "INSERT OR IGNORE INTO month_closes (workspace, month, status, amount_micros, payment_id, error, closed_at)
752 VALUES (?, ?, ?, ?, ?, ?, ?)",
753 )
754 .bind(&[
755 account.workspace.as_str().into(),
756 closing.as_str().into(),
757 status.into(),
758 (amount as f64).into(),
759 crate::optional(payment),
760 crate::optional(error),
761 now.as_str().into(),
762 ])
763 };
764 let payer = self.account_of(&account.workspace).await?;
765 if payer.terms.kind == TermsKind::Comped || payer.id.starts_with("ent_") {
766 record("skipped", 0, None, None)?.run().await?;
767 continue;
768 }
769 let owed = (-account.balance.unwrap_or(0)).max(0);
770 if owed == 0 {
771 record("nothing", 0, None, None)?.run().await?;
772 continue;
773 }
774 if !worth_charging(owed, self.plans.min_charge_micros) {
775 // Under the minimum charge: a card payment's fee would be
776 // too much of it. It stays owed and goes on the next
777 // invoice that reaches the minimum.
778 record("carried", owed, None, None)?.run().await?;
779 continue;
780 }
781 match self.invoice_workspace(&account.workspace, "month", &closing).await? {
782 Ok(invoice) if invoice.status == "paid" => {
783 record("paid", invoice.amount_micros, Some(&invoice.invoice_id), None)?.run().await?;
784 }
785 Ok(invoice) => {
786 record("failed", invoice.amount_micros, Some(&invoice.invoice_id), Some("the card was declined"))?.run().await?;
787 }
788 Err(why) => {
789 record("nothing", 0, None, Some(&why))?.run().await?;
790 }
791 }
792 }
793 Ok(())
794 }
795
796 /// Emails a workspace's owners as it passes 50, 75, 90 and 100% of its
797 /// plan's included usage, its spend limit and g1t's ceiling, once each a
798 /// month; when its card was declined; and when a spend spike paused it.
799 /// The same alerts show in the app (`entitlements`).
800 pub(crate) async fn warn_limits(&self, identity: &worker::Fetcher) -> Result<()> {
801 if self.stripe.is_none() {
802 return Ok(());
803 }
804 let now = rfc3339(now_ms());
805 let month = &now[..7];
806 #[derive(Deserialize)]
807 struct Candidate {
808 workspace: String,
809 }
810 let candidates = self
811 .db
812 .prepare(
813 "SELECT DISTINCT workspace FROM ledger WHERE kind = 'usage' AND created_at >= ?1
814 UNION SELECT workspace FROM limits WHERE autopay_failed_at IS NOT NULL",
815 )
816 .bind(&[format!("{month}-01").into()])?
817 .all()
818 .await?
819 .results::<Candidate>()?;
820 #[derive(Deserialize)]
821 struct Told {
822 autopay_failed_at: Option<String>,
823 declined_told_at: Option<String>,
824 }
825 #[derive(Deserialize)]
826 struct Sent {
827 meter: String,
828 level: Option<i64>,
829 }
830 for Candidate { workspace } in candidates {
831 let told = self
832 .db
833 .prepare("SELECT autopay_failed_at, declined_told_at FROM limits WHERE workspace = ?")
834 .bind(&[workspace.as_str().into()])?
835 .first::<Told>(None)
836 .await?;
837 let billing = format!("https://g1t.sh/{workspace}/-/billing");
838
839 // A declined card, once per decline.
840 if let Some(Told { autopay_failed_at: Some(failed), declined_told_at }) = &told
841 && declined_told_at.as_deref().is_none_or(|at| at < failed.as_str()) {
842 let limit = self.limit_of(&workspace).await?;
843 let sent = notify(
844 identity,
845 &workspace,
846 &format!("g1t: the card for {workspace} was declined"),
847 &limit.message.clone().unwrap_or_else(|| format!("g1t could not charge the card on file for {workspace}.")),
848 "Update the card",
849 &billing,
850 )
851 .await;
852 if sent {
853 self.db
854 .prepare("UPDATE limits SET declined_told_at = ? WHERE workspace = ?")
855 .bind(&[now.as_str().into(), workspace.as_str().into()])?
856 .run()
857 .await?;
858 }
859 }
860
861 // 50, 75, 90 and 100%, once each a month and meter: only the
862 // highest new level is emailed.
863 let alerts = self.alerts_for(&workspace).await?;
864 if alerts.is_empty() {
865 continue;
866 }
867 let sent: Vec<Sent> = self
868 .db
869 .prepare("SELECT meter, MAX(level) AS level FROM alerts_sent WHERE workspace = ? AND month = ? GROUP BY meter")
870 .bind(&[workspace.as_str().into(), month.into()])?
871 .all()
872 .await?
873 .results::<Sent>()?;
874 for alert in alerts {
875 let already = sent.iter().find(|s| s.meter == alert.meter).and_then(|s| s.level).unwrap_or(0);
876 if i64::from(alert.level) <= already {
877 continue;
878 }
879 let subject = match alert.meter.as_str() {
880 "included" => format!("g1t: {workspace} has used {}% of its included usage", alert.level),
881 "spend_limit" => format!("g1t: {workspace} has used {}% of its spend limit", alert.level),
882 _ => format!("g1t: {workspace} has used {}% of its usage limit", alert.level),
883 };
884 if notify(identity, &workspace, &subject, &alert.message, "Open billing", &billing).await {
885 self.db
886 .prepare(
887 "INSERT OR IGNORE INTO alerts_sent (workspace, month, meter, level, sent_at) VALUES (?1, ?2, ?3, ?4, ?5)",
888 )
889 .bind(&[workspace.as_str().into(), month.into(), alert.meter.as_str().into(), alert.level.into(), now.as_str().into()])?
890 .run()
891 .await?;
892 }
893 }
894 }
895 self.tell_spikes(identity).await?;
896 Ok(())
897 }
898
899 pub(crate) async fn check_limit(&self, a: CheckLimitArgs) -> Result<Outcome<Limit>> {
900 Ok(Outcome::Ok(self.limit_of(&a.workspace).await?))
901 }
902
903 /// The owners' spend limit: anywhere up to what is available without
904 /// asking; once, up to twice the highest ceiling (`raise_once`), which
905 /// also raises g1t's ceiling to match.
906 pub(crate) async fn set_spend_limit(&self, a: SetSpendLimitArgs) -> Result<Outcome<Limit>> {
907 let workspace = a.workspace.to_lowercase();
908 if a.actor.role_in(&workspace) != Some(Role::Owner) {
909 return Ok(Outcome::fail(
910 FailureCode::Forbidden,
911 "Only an owner can set the workspace's spend limit.",
912 ));
913 }
914 let before = self.limit_of(&workspace).await?;
915 let mut raising = false;
916 if let (Some(requested), false) = (a.spend_limit_micros, a.use_full_limit) {
917 match (before.available_micros, matches!(before.trust, Trust::Internal | Trust::Reviewed)) {
918 (_, true) | (None, _) => {
919 if requested < 0 {
920 return Ok(Outcome::fail(FailureCode::Invalid, "A spend limit cannot be negative."));
921 }
922 }
923 (Some(available), false) => match self_serve(requested, available, before.raise_once_micros, a.raise_once) {
924 Ok(uses_raise) => raising = uses_raise,
925 Err(why) => return Ok(Outcome::fail(FailureCode::Invalid, why)),
926 },
927 }
928 }
929 let now = rfc3339(now_ms());
930 let limit = if a.use_full_limit { JsValue::NULL } else { a.spend_limit_micros.map_or(JsValue::NULL, |limit| (limit as f64).into()) };
931 self.db
932 .prepare(
933 "INSERT INTO limits (workspace, spend_limit_micros, spend_limit_full, updated_at) VALUES (?1, ?2, ?3, ?4)
934 ON CONFLICT (workspace) DO UPDATE SET spend_limit_micros = ?2, spend_limit_full = ?3, updated_at = ?4",
935 )
936 .bind(&[workspace.as_str().into(), limit, (if a.use_full_limit { 1 } else { 0 }).into(), now.as_str().into()])?
937 .run()
938 .await?;
939 if raising {
940 let raised = a.spend_limit_micros.unwrap_or_default();
941 // The ceiling rises with it, once.
942 self.db
943 .prepare(
944 "UPDATE limits SET granted_ceiling_micros = MAX(COALESCE(granted_ceiling_micros, 0), ?2),
945 raised_at = ?3, updated_at = ?3 WHERE workspace = ?1 AND raised_at IS NULL",
946 )
947 .bind(&[workspace.as_str().into(), (raised as f64).into(), now.as_str().into()])?
948 .run()
949 .await?;
950 let account = self.account_of(&workspace).await?;
951 self.audit(&account.id, "raise_once", &format!("{workspace} used its one-time raise: {}", dollars_plain(raised)), &a.actor.username)
952 .await?;
953 }
954 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
955 }
956}
957
958/// Whether `owed` is enough to charge a card when a month closes: at least
959/// the minimum charge (`MIN_CHARGE_MICROS`). Less carries over to the next
960/// invoice. Charges at a limit do not ask.
961pub(crate) fn worth_charging(owed: i64, min_charge: i64) -> bool {
962 owed > 0 && owed >= min_charge
963}
964
965/// Emails the workspace's owners through identity. False if nothing was sent.
966pub(crate) async fn notify(identity: &worker::Fetcher, workspace: &str, subject: &str, intro: &str, action: &str, link: &str) -> bool {
967 let args = g1t_contracts::identity::NotifyOwnersArgs {
968 workspace: workspace.to_owned(),
969 subject: subject.to_owned(),
970 intro: intro.to_owned(),
971 action: action.to_owned(),
972 link: link.to_owned(),
973 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(),
974 };
975 match g1t_kit::call::<_, u32>(identity, "notify_owners", &args).await {
976 Ok(sent) => sent > 0,
977 Err(error) => {
978 worker::console_error!("could not tell {workspace}'s owners: {error}");
979 false
980 }
981 }
982}
983
984/// `2026-09` for `2026-10`, and `2025-12` for `2026-01`.
985pub(crate) fn previous_month(month: &str) -> String {
986 let year: i32 = month[..4].parse().unwrap_or(1970);
987 let number: u32 = month[5..7].parse().unwrap_or(1);
988 if number == 1 {
989 format!("{}-12", year - 1)
990 } else {
991 format!("{year}-{:02}", number - 1)
992 }
993}
994
995#[cfg(test)]
996mod tests {
997 use super::*;
998
999 #[test]
1000 fn the_automatic_spend_limit_follows_last_month() {
1001 assert_eq!(automatic_spend_limit(0), 200_000_000);
1002 assert_eq!(automatic_spend_limit(50_000_000), 200_000_000);
1003 assert_eq!(automatic_spend_limit(900_000_000), 1_800_000_000);
1004 }
1005
1006 #[test]
1007 fn three_steady_months_make_a_workspace_established() {
1008 assert_eq!(established_ceiling(&[900_000_000, 850_000_000, 950_000_000]), Some(2_700_000_000));
1009 assert_eq!(established_ceiling(&[5_000_000_000, 5_000_000_000, 5_000_000_000]), Some(10_000_000_000));
1010 assert_eq!(established_ceiling(&[900_000_000, 10_000_000, 950_000_000]), None);
1011 assert_eq!(established_ceiling(&[900_000_000, 900_000_000]), None);
1012 }
1013
1014 #[test]
1015 fn alerts_come_at_half_three_quarters_ninety_and_the_limit() {
1016 assert_eq!(alert_level(0, 10_000_000), 0);
1017 assert_eq!(alert_level(4_999_999, 10_000_000), 0);
1018 assert_eq!(alert_level(5_000_000, 10_000_000), 50);
1019 assert_eq!(alert_level(7_500_000, 10_000_000), 75);
1020 assert_eq!(alert_level(8_999_999, 10_000_000), 75);
1021 assert_eq!(alert_level(9_000_000, 10_000_000), 90);
1022 assert_eq!(alert_level(10_000_000, 10_000_000), 100);
1023 assert_eq!(alert_level(25_000_000, 10_000_000), 100);
1024 // Nothing to measure against: no alert.
1025 assert_eq!(alert_level(5, 0), 0);
1026 }
1027
1028 #[test]
1029 fn amounts_under_the_minimum_carry_over_only_at_the_month_close() {
1030 let min = 5_000_000;
1031 assert!(!worth_charging(0, min));
1032 assert!(!worth_charging(4_990_000, min));
1033 assert!(worth_charging(5_000_000, min));
1034 assert!(worth_charging(12_000_000, min));
1035 // $3 carried from last month and $2.50 this month: charged together.
1036 let carried = 3_000_000;
1037 assert!(!worth_charging(carried, min));
1038 assert!(worth_charging(carried + 2_500_000, min));
1039 }
1040
1041 #[test]
1042 fn the_month_before_wraps_the_year() {
1043 assert_eq!(previous_month("2026-10"), "2026-09");
1044 assert_eq!(previous_month("2026-01"), "2025-12");
1045 }
1046
1047 fn ceilings() -> Ceilings {
1048 Ceilings { new: 3_000_000, paid_min: 25_000_000, paid_max: 1_000_000_000 }
1049 }
1050
1051 #[test]
1052 fn trust_grows_with_what_was_paid_within_bounds() {
1053 assert_eq!(ceilings().for_paid(5_000_000), 25_000_000);
1054 assert_eq!(ceilings().for_paid(100_000_000), 200_000_000);
1055 assert_eq!(ceilings().for_paid(10_000_000_000), 1_000_000_000);
1056 }
1057
1058 #[test]
1059 fn a_new_paid_workspace_starts_at_a_hundred_dollars_and_only_goes_up() {
1060 let start = 100_000_000;
1061 // The first month: the starting ceiling, whatever was paid.
1062 assert_eq!(paid_ceiling(&ceilings(), start, true, 900_000_000, None), start);
1063 // After it, with little paid: never below the start.
1064 assert_eq!(paid_ceiling(&ceilings(), start, false, 20_000_000, None), start);
1065 assert_eq!(paid_ceiling(&ceilings(), start, false, 0, None), start);
1066 // Payments that cleared raise it: twice what was paid.
1067 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, None), 600_000_000);
1068 // Established follows the monthly spend.
1069 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, Some(2_700_000_000)), 2_700_000_000);
1070 }
1071
1072 #[test]
1073 fn the_first_billing_cycle_is_the_first_month() {
1074 // A plan that started on the 5th, paid through the 5th of next month.
1075 assert!(in_first_cycle("2026-10-05T10:00:00Z", Some("2026-11-05T10:00:00Z"), "2026-10-20T00:00:00Z"));
1076 // Renewed: the period now ends two months after the start.
1077 assert!(!in_first_cycle("2026-10-05T10:00:00Z", Some("2026-12-05T10:00:00Z"), "2026-11-20T00:00:00Z"));
1078 // No period known yet: the first 31 days.
1079 assert!(in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-04T00:00:00Z"));
1080 assert!(!in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-10T00:00:00Z"));
1081 // Day counting is exact across months and years.
1082 assert_eq!(days("1970-01-01"), 0);
1083 assert_eq!(days("2026-11-01") - days("2026-10-01"), 31);
1084 assert_eq!(days("2028-03-01") - days("2028-02-28"), 2);
1085 assert_eq!(days("2027-01-01") - days("2026-12-31"), 1);
1086 }
1087
1088 #[test]
1089 fn owners_set_their_limit_up_to_the_highest_ceiling_without_asking() {
1090 // First month at $100; the highest ever is $100.
1091 let (available, once) = spend_bounds(100_000_000, 100_000_000, 0, false);
1092 assert_eq!(available, 100_000_000);
1093 assert_eq!(once, Some(200_000_000));
1094 assert_eq!(self_serve(80_000_000, available, once, false), Ok(false));
1095 assert_eq!(self_serve(100_000_000, available, once, false), Ok(false));
1096 // Above it without the raise: refused, saying what to do.
1097 assert!(self_serve(150_000_000, available, once, false).unwrap_err().contains("one-time raise"));
1098 // With the raise: up to twice the highest ceiling, once.
1099 assert_eq!(self_serve(200_000_000, available, once, true), Ok(true));
1100 assert!(self_serve(200_000_001, available, once, true).unwrap_err().contains("Raise my limit"));
1101 // Once used, it is gone.
1102 let (available, once) = spend_bounds(200_000_000, 200_000_000, 0, true);
1103 assert_eq!(once, None);
1104 assert_eq!(self_serve(200_000_000, available, once, false), Ok(false));
1105 assert!(self_serve(300_000_000, available, once, true).unwrap_err().contains("is used"));
1106 // A ceiling that came down still leaves the highest one available.
1107 let (available, _) = spend_bounds(100_000_000, 400_000_000, 0, true);
1108 assert_eq!(available, 400_000_000);
1109 assert!(self_serve(-1, available, None, false).is_err());
1110 }
1111
1112 #[test]
1113 fn prepaying_raises_what_can_be_used_at_once() {
1114 // $500 prepaid this month, $120 used: nothing owed, $380 left.
1115 assert_eq!(exposure(120_000_000, 500_000_000, 0), (0, 380_000_000));
1116 // Prepaid last month and carried in.
1117 assert_eq!(exposure(120_000_000, 0, 500_000_000), (0, 380_000_000));
1118 // Used past the prepayment: the rest is owed.
1119 assert_eq!(exposure(620_000_000, 500_000_000, 0), (120_000_000, 0));
1120 // Owed from before adds to this month's.
1121 assert_eq!(exposure(10_000_000, 0, -4_000_000), (14_000_000, 0));
1122 // With a $100 ceiling and $500 prepaid, work stops at $600 of use,
1123 // not at $100.
1124 let ceiling = 100_000_000;
1125 assert_eq!(state(exposure(599_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Warning);
1126 assert_eq!(state(exposure(600_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Stopped);
1127 // And the owners may set their spend limit that much higher.
1128 assert_eq!(spend_bounds(ceiling, ceiling, 500_000_000, true).0, 600_000_000);
1129 }
1130
1131 #[test]
1132 fn work_warns_at_eighty_percent_and_stops_at_the_ceiling() {
1133 assert_eq!(state(0, Some(100)), LimitState::Ok);
1134 assert_eq!(state(79, Some(100)), LimitState::Ok);
1135 assert_eq!(state(80, Some(100)), LimitState::Warning);
1136 assert_eq!(state(100, Some(100)), LimitState::Stopped);
1137 assert_eq!(state(1_000_000, None), LimitState::Ok);
1138 }
1139}