Skip to content
1,408 linesCodeBlameRaw
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: the
26//! month's usage at price less the discount, included usage, pools and
27//! credit, with month-end usage counted on the same terms (`charged`, the
28//! one definition the Billing page and Usage share). They may
29//! put it anywhere up to the highest ceiling the workspace has ever had,
30//! plus what is prepaid, without asking anyone; once per workspace they may
31//! raise it to twice that highest ceiling themselves. Past that, they ask
32//! (see `requests`), and g1t answers within one business day.
33//!
34//! Alerts go out at 50, 75, 90 and 100% of the plan's included usage, the
35//! spend limit and the ceiling, in the app and by email. At the ceiling or
36//! the spend limit, new work stops: no new sandboxes, builds or app
37//! requests until it is paid, raised, or the month turns. Runs already
38//! under way finish.
39//!
40//! Usage counts at what it cost g1t or what it is charged, whichever is
41//! more. Test-mode payments are not money, so they do not raise trust.
42
43use std::collections::BTreeSet;
44
45use futures_util::future::{try_join, try_join3, try_join4, try_join_all};
46use g1t_contracts::billing::{
47 BillingAccount, CheckLimitArgs, Limit, LimitArgs, LimitState, NotePendingArgs, PlanKind, SetBudgetArgs, SetSpendLimitArgs, Trust,
48};
49use g1t_contracts::time::rfc3339;
50use g1t_contracts::{FailureCode, Outcome};
51use g1t_kit::now_ms;
52use serde::Deserialize;
53use worker::wasm_bindgen::JsValue;
54use worker::{Env, Result};
55
56use crate::charged::{PendingLine, PendingSplit, month_totals, pending_split};
57use crate::features::dollars as dollars_plain;
58use crate::{Billing, members_only};
59
60/// A month's usage on the ledger, in the parts `charged` is made of.
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
62struct MonthCharges {
63 /// At price.
64 price: i64,
65 /// What the account's discount took off.
66 discount: i64,
67 /// What the plan's included usage, the trial, a pool or g1t paid.
68 covered: i64,
69 /// Last month's charge, as the ledger has it, for the automatic limit.
70 last_month: i64,
71}
72
73/// The ceilings, from the billing service's variables.
74pub(crate) struct Ceilings {
75 /// `LIMIT_NEW_MICROS`: a free workspace's.
76 pub new: i64,
77 /// `LIMIT_PAID_MIN_MICROS` and `LIMIT_PAID_MAX_MICROS`: the bounds of a
78 /// paid workspace's, from what it has paid.
79 pub paid_min: i64,
80 pub paid_max: i64,
81}
82
83impl Ceilings {
84 pub(crate) fn from_env(env: &Env) -> Self {
85 let number = |name: &str, default: i64| {
86 env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok()).unwrap_or(default)
87 };
88 Ceilings {
89 new: number("LIMIT_NEW_MICROS", 3_000_000),
90 paid_min: number("LIMIT_PAID_MIN_MICROS", 25_000_000),
91 paid_max: number("LIMIT_PAID_MAX_MICROS", 1_000_000_000),
92 }
93 }
94
95 /// The ceiling for a workspace that has paid `paid` in live money.
96 pub(crate) fn for_paid(&self, paid: i64) -> i64 {
97 (paid * 2).clamp(self.paid_min, self.paid_max)
98 }
99}
100
101/// Where a workspace stands against its ceiling.
102pub(crate) fn state(exposure: i64, ceiling: Option<i64>) -> LimitState {
103 match ceiling {
104 Some(ceiling) if exposure >= ceiling => LimitState::Stopped,
105 Some(ceiling) if exposure * 5 >= ceiling * 4 => LimitState::Warning,
106 _ => LimitState::Ok,
107 }
108}
109
110/// The automatic monthly spend limit's floor: $200.
111pub(crate) const DEFAULT_SPEND_MICROS: i64 = 200_000_000;
112/// Established workspaces' ceiling: three times their steady monthly
113/// spend, up to $10,000.
114const ESTABLISHED_FACTOR: i64 = 3;
115const ESTABLISHED_MAX_MICROS: i64 = 10_000_000_000;
116/// A month counts toward Established at this much spend or more.
117const ESTABLISHED_MONTH_MICROS: i64 = 20_000_000;
118/// Payments raise trust once this old: past the time most bad cards are
119/// caught.
120pub(crate) const SETTLE_DAYS: u64 = 7;
121
122/// The automatic spend limit: $200, or twice last month's spend.
123pub(crate) fn automatic_spend_limit(last_month_charged: i64) -> i64 {
124 DEFAULT_SPEND_MICROS.max(last_month_charged * 2)
125}
126
127/// An Established workspace's ceiling, from its last three months'
128/// charges, if each was steady enough.
129pub(crate) fn established_ceiling(months: &[i64]) -> Option<i64> {
130 if months.len() < 3 || months.iter().any(|m| *m < ESTABLISHED_MONTH_MICROS) {
131 return None;
132 }
133 let average = months.iter().sum::<i64>() / months.len() as i64;
134 Some((average * ESTABLISHED_FACTOR).min(ESTABLISHED_MAX_MICROS))
135}
136
137/// Days since 1970-01-01 of a `YYYY-MM-DD…` date, for comparing dates
138/// without a clock (Howard Hinnant's days-from-civil).
139pub(crate) fn days(date: &str) -> i64 {
140 let year: i64 = date.get(..4).and_then(|y| y.parse().ok()).unwrap_or(1970);
141 let month: i64 = date.get(5..7).and_then(|m| m.parse().ok()).unwrap_or(1);
142 let day: i64 = date.get(8..10).and_then(|d| d.parse().ok()).unwrap_or(1);
143 let y = if month <= 2 { year - 1 } else { year };
144 let era = y.div_euclid(400);
145 let yoe = y - era * 400;
146 let mp = (month + 9) % 12;
147 let doy = (153 * mp + 2) / 5 + day - 1;
148 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
149 era * 146_097 + doe - 719_468
150}
151
152/// Whether a plan that started at `started_at` is still in its first
153/// billing cycle: its paid period ends no more than a month after it
154/// started (a renewal moves the end a month on), or, with no period known,
155/// it started within the last 31 days.
156pub(crate) fn in_first_cycle(started_at: &str, period_end: Option<&str>, now: &str) -> bool {
157 match period_end {
158 Some(end) => days(end) - days(started_at) <= 32 && days(now) <= days(end),
159 None => days(now) - days(started_at) <= 31,
160 }
161}
162
163/// g1t's ceiling for a workspace on the plan: the starting one in its
164/// first month; after it, what it has paid (or its Established ceiling),
165/// never less than the starting one.
166pub(crate) fn paid_ceiling(ceilings: &Ceilings, start: i64, first_month: bool, paid: i64, established: Option<i64>) -> i64 {
167 if first_month {
168 return start;
169 }
170 let from_paid = if paid > 0 { ceilings.for_paid(paid) } else { 0 };
171 start.max(from_paid).max(established.unwrap_or(0))
172}
173
174/// What the owners may set their spend limit to without asking, and the
175/// one-time raise if it is still theirs to use: up to the highest ceiling
176/// ever (or the current one, if higher) plus what is prepaid; once, twice
177/// the highest ceiling.
178pub(crate) fn spend_bounds(ceiling: i64, max_ever: i64, prepaid: i64, raised: bool) -> (i64, Option<i64>) {
179 let highest = ceiling.max(max_ever);
180 let available = highest + prepaid.max(0);
181 let once = (!raised).then(|| (highest * 2 + prepaid.max(0)).max(available));
182 (available, once)
183}
184
185/// Whether `requested` is a spend limit the owners may set themselves.
186/// `Ok(true)` when it takes the one-time raise.
187pub(crate) fn self_serve(requested: i64, available: i64, once: Option<i64>, raise_once: bool) -> std::result::Result<bool, String> {
188 if requested < 0 {
189 return Err("A spend limit cannot be negative.".to_owned());
190 }
191 if requested <= available {
192 return Ok(false);
193 }
194 match once {
195 Some(once) if raise_once && requested <= once => Ok(true),
196 Some(once) if raise_once => Err(format!(
197 "The one-time raise goes up to {}. For more, ask g1t with Raise my limit; the answer comes within one business day.",
198 dollars_plain(once)
199 )),
200 Some(once) => Err(format!(
201 "You can set up to {} yourself, or use your one-time raise to go up to {}. For more, ask g1t with Raise my limit.",
202 dollars_plain(available),
203 dollars_plain(once)
204 )),
205 None => Err(format!(
206 "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.",
207 dollars_plain(available)
208 )),
209 }
210}
211
212/// Which alert a measure has reached: 100, 90, 75, 50, or none (0).
213pub(crate) fn alert_level(used: i64, limit: i64) -> u32 {
214 alert_level_in(used, limit, &ALERT_LEVELS)
215}
216
217/// Every alert a budget can have, highest first.
218pub(crate) const ALERT_LEVELS: [u32; 4] = [100, 90, 75, 50];
219
220/// The highest of `levels` a measure has reached, or 0.
221pub(crate) fn alert_level_in(used: i64, limit: i64, levels: &[u32]) -> u32 {
222 if limit <= 0 || used <= 0 {
223 return 0;
224 }
225 levels.iter().copied().filter(|level| used * 100 >= limit * i64::from(*level)).max().unwrap_or(0)
226}
227
228/// A budget's alerts as stored (`50,75,100`): every level when none were
229/// chosen, highest first.
230pub(crate) fn alert_levels(stored: Option<&str>) -> Vec<u32> {
231 let Some(stored) = stored else { return ALERT_LEVELS.to_vec() };
232 let mut levels: Vec<u32> = stored.split(',').filter_map(|l| l.trim().parse().ok()).filter(|l| ALERT_LEVELS.contains(l)).collect();
233 levels.sort_by(|a, b| b.cmp(a));
234 levels.dedup();
235 levels
236}
237
238/// Where spending stands against the budget: at 100% it stops work only
239/// when the budget pauses usage; otherwise it is a warning.
240pub(crate) fn budget_state(spent: i64, budget: Option<i64>, pause: bool) -> LimitState {
241 match state(spent, budget) {
242 LimitState::Stopped if !pause => LimitState::Warning,
243 other => other,
244 }
245}
246
247/// Whether a budget webhook is an address g1t will post to: HTTPS, not
248/// g1t's own, at most 500 characters.
249pub(crate) fn webhook_ok(url: &str) -> bool {
250 let url = url.trim();
251 url.len() <= 500
252 && url.starts_with("https://")
253 && url.len() > "https://".len() + 3
254 && !url.contains(char::is_whitespace)
255 && !url["https://".len()..].split('/').next().is_some_and(|host| host == "g1t.sh" || host.ends_with(".g1t.sh") || host.starts_with("localhost") || host.starts_with("127."))
256}
257
258/// What is owed and what is prepaid, from this month's usage and payments
259/// and the balance the month started with (positive: paid in advance;
260/// negative: owed from before).
261pub(crate) fn exposure(used: i64, paid_month: i64, balance_before: i64) -> (i64, i64) {
262 let prepaid_in = balance_before.max(0);
263 let carried = (-balance_before).max(0);
264 let net = used - paid_month - prepaid_in;
265 (net.max(0) + carried, (-net).max(0))
266}
267
268#[derive(Deserialize)]
269struct LimitRow {
270 spend_limit_micros: Option<i64>,
271 #[serde(default)]
272 spend_limit_full: Option<i64>,
273 autopay_failed_at: Option<String>,
274 autopay_error: Option<String>,
275 #[serde(default)]
276 max_ceiling_micros: Option<i64>,
277 #[serde(default)]
278 granted_ceiling_micros: Option<i64>,
279 #[serde(default)]
280 raised_at: Option<String>,
281 #[serde(default)]
282 alert_levels: Option<String>,
283 #[serde(default)]
284 pause_at_limit: Option<i64>,
285 #[serde(default)]
286 budget_webhook: Option<String>,
287}
288
289#[derive(Deserialize)]
290struct Month {
291 used: Option<i64>,
292 paid: Option<i64>,
293}
294
295#[derive(Deserialize)]
296struct Paid {
297 paid: Option<i64>,
298}
299
300impl Billing {
301 /// The workspace's limit, worked out from the ledger of the account
302 /// that pays for it: its own, or its enterprise's, whose workspaces'
303 /// usage and payments count together.
304 pub(crate) async fn limit_of(&self, workspace: &str) -> Result<Limit> {
305 let workspace = workspace.to_lowercase();
306 let account = self.account_of(&workspace).await?;
307 let plan = self.plan_kind_for(&workspace, &account).await?;
308 self.limit_with(&workspace, &account, plan).await
309 }
310
311 /// The workspace's limit, from the account and plan already read for
312 /// it, so a caller that has them does not read them again.
313 pub(crate) async fn limit_with(&self, workspace: &str, account: &BillingAccount, plan: PlanKind) -> Result<Limit> {
314 let workspace = workspace.to_lowercase();
315 let now = rfc3339(now_ms());
316 let month_start = format!("{}-01", &now[..7]);
317 let marks = vec!["?"; account.workspaces.len().max(1)].join(", ");
318 let names: Vec<String> = if account.workspaces.is_empty() { vec![workspace.clone()] } else { account.workspaces.clone() };
319 let members: Vec<JsValue> = names.iter().map(|w| JsValue::from(w.as_str())).collect();
320 let row = async {
321 self.db
322 .prepare(
323 "SELECT spend_limit_micros, spend_limit_full, autopay_failed_at, autopay_error,
324 max_ceiling_micros, granted_ceiling_micros, raised_at, alert_levels, pause_at_limit, budget_webhook
325 FROM limits WHERE workspace = ?",
326 )
327 .bind(&[workspace.as_str().into()])?
328 .first::<LimitRow>(None)
329 .await
330 };
331 let mut with_month = members.clone();
332 with_month.push(month_start.as_str().into());
333 // Each usage entry at its cost to g1t or its charge, whichever is
334 // more; on the workspace's own provider, only what g1t charged.
335 // What the plan's included usage, the trial, the open-source pool
336 // or g1t itself paid for is not unpaid: those are budgets already
337 // paid for.
338 let month = async {
339 self.db
340 .prepare(format!(
341 "SELECT
342 SUM(CASE WHEN kind = 'usage' THEN
343 CASE WHEN COALESCE(billed_to, 'g1t') = 'g1t'
344 THEN MAX(COALESCE(cost_micros, 0) - COALESCE(credit_micros, 0)
345 - COALESCE(trial_micros, 0) - COALESCE(oss_micros, 0)
346 - COALESCE(given_micros, 0),
347 -amount_micros)
348 ELSE -amount_micros END
349 END) AS used,
350 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS paid
351 FROM ledger WHERE workspace IN ({marks}) AND created_at >= ?"
352 ))
353 .bind(&with_month)?
354 .first::<Month>(None)
355 .await
356 };
357 // And what is metered but not charged until the month closes: it
358 // counts toward what is unpaid at its charge, and toward what is
359 // charged on the account's terms (see `charged`).
360 let pending = self.pending_this_month(&members, &month_start[..7]);
361 // What credit (AI credit, credit from g1t) paid this month: charged
362 // to no one, so not against the spend limit. Read only for
363 // workspaces with grants; the rest answer at once.
364 let next_month = crate::credits::next_month_start(&month_start[..7]);
365 let credits = try_join_all(names.iter().map(|name| {
366 let (from, until) = (month_start.as_str(), next_month.as_str());
367 async move { Ok::<i64, worker::Error>(self.credit_paid_between(name, from, until).await?.0) }
368 }));
369 // Test-mode payments are not money: they pay nothing off.
370 let live = self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live);
371 // The balance the month started with: owed from before (so a new
372 // month is not a fresh allowance for an account that never pays),
373 // or paid in advance. Credits g1t gave count; test-mode payments
374 // do not.
375 let mut before = members.clone();
376 before.push(month_start.as_str().into());
377 let balance_before = async {
378 Ok::<i64, worker::Error>(
379 self.db
380 .prepare(format!(
381 "SELECT SUM(CASE WHEN kind = 'usage' THEN amount_micros
382 WHEN kind = 'top_up' AND ({live} = 1 OR reference LIKE 'crd%') THEN amount_micros
383 ELSE 0 END) AS paid
384 FROM ledger WHERE workspace IN ({marks}) AND created_at < ?",
385 live = u8::from(live)
386 ))
387 .bind(&before)?
388 .first::<Paid>(None)
389 .await?
390 .and_then(|row| row.paid)
391 .unwrap_or(0),
392 )
393 };
394 // The trust ceiling, from what has been paid and how steadily. The
395 // first month is asked for beside it, since neither needs the other.
396 let trust = async {
397 Ok::<_, worker::Error>(match account.terms.kind {
398 _ if account.terms.full_discount() => (Trust::Internal, None, false),
399 _ if account.terms.ceiling_micros.is_some() => (Trust::Reviewed, account.terms.ceiling_micros, false),
400 _ => {
401 let standing = async {
402 let paid = self.live_paid(&members).await?;
403 let established = if paid > 0 { self.established(&members).await? } else { None };
404 Ok::<_, worker::Error>((paid, established))
405 };
406 let first = async {
407 if plan == PlanKind::Paid { self.first_month(&workspace).await } else { Ok(false) }
408 };
409 let ((paid, established), first_month) = try_join(standing, first).await?;
410 if plan == PlanKind::Free {
411 // Nothing on demand: only what a free workspace can owe.
412 (Trust::New, Some(self.ceilings.new), false)
413 } else {
414 let ceiling = paid_ceiling(&self.ceilings, self.plans.paid_start_micros, first_month, paid, established);
415 (if established.is_some() { Trust::Established } else { Trust::Paid }, Some(ceiling), first_month)
416 }
417 }
418 })
419 };
420 // This month's charges on the ledger, measured as every page
421 // measures them, and last month's, for the automatic spend limit.
422 let charges = self.month_charges(&members, &month_start);
423 // None of these reads needs another's answer, so they go to D1 at
424 // once: the limit is on every signed-in page.
425 let ((row, month, balance_before, charges), (pending, credits), (trust, trust_ceiling, first_month)) =
426 try_join3(try_join4(row, month, balance_before, charges), try_join(pending, credits), trust).await?;
427 // Charged this month: the one definition (`charged`), so this is
428 // the Billing page's and Usage's figure, to the micro.
429 let percent = account.terms.percent_off();
430 let splits: Vec<PendingSplit> = pending.iter().map(|p| pending_split(p.cost(), p.charge(), self.margin_percent, percent)).collect();
431 let totals = month_totals(charges.price, charges.discount, charges.covered, credits.into_iter().sum(), &splits);
432 let spent = totals.charged_micros;
433 let last_month = charges.last_month;
434 let (used, paid_month) = month.map_or((0, 0), |m| (m.used.unwrap_or(0), m.paid.unwrap_or(0)));
435 let used = used + pending.iter().map(PendingLine::charge).sum::<i64>();
436 let (exposure, prepaid) = exposure(used, if live { paid_month } else { 0 }, balance_before);
437
438 // A ceiling g1t granted is a floor under the trust ceiling.
439 let granted = row.as_ref().and_then(|row| row.granted_ceiling_micros);
440 let ceiling = trust_ceiling.map(|c| c.max(granted.unwrap_or(0)));
441 // The highest ceiling ever, kept as it rises.
442 let stored_max = row.as_ref().and_then(|row| row.max_ceiling_micros);
443 let max_ever = match (stored_max, ceiling) {
444 (Some(stored), Some(now)) => Some(stored.max(now)),
445 (stored, now) => stored.or(now),
446 };
447 if let (Some(max), true) = (max_ever, ceiling.is_some() && max_ever != stored_max && plan != PlanKind::Free) {
448 self.db
449 .prepare(
450 "INSERT INTO limits (workspace, max_ceiling_micros, updated_at) VALUES (?1, ?2, ?3)
451 ON CONFLICT (workspace) DO UPDATE SET max_ceiling_micros = MAX(COALESCE(max_ceiling_micros, 0), ?2), updated_at = ?3",
452 )
453 .bind(&[workspace.as_str().into(), (max as f64).into(), now.as_str().into()])?
454 .run()
455 .await?;
456 }
457 let raised_at = row.as_ref().and_then(|row| row.raised_at.clone());
458 let self_serve = matches!(trust, Trust::New | Trust::Paid | Trust::Established) && plan != PlanKind::Free;
459 let (available, raise_once) = match (ceiling, self_serve) {
460 (Some(ceiling), true) => {
461 let (available, once) = spend_bounds(ceiling, max_ever.unwrap_or(ceiling), prepaid, raised_at.is_some());
462 (Some(available), once)
463 }
464 (ceiling, _) => (ceiling, None),
465 };
466 // The owners' own monthly limit: theirs, none, or the automatic one
467 // ($200, or twice last month), which self-serve workspaces start on.
468 let chosen = row.as_ref().and_then(|row| row.spend_limit_micros);
469 let full = row.as_ref().and_then(|row| row.spend_limit_full).unwrap_or(0) == 1;
470 let default_spend_limit = chosen.is_none() && !full && self_serve;
471 let spend_limit = match (chosen, full) {
472 (Some(own), _) => Some(own),
473 (None, true) => None,
474 (None, false) if self_serve => Some(automatic_spend_limit(last_month)),
475 _ => None,
476 };
477 // A card declined when g1t charged it at the limit stops work until
478 // it is paid; any payment clears it.
479 let declined = row.as_ref().and_then(|row| row.autopay_failed_at.clone().map(|at| (at, row.autopay_error.clone())));
480 // Two limits: g1t's on what is unpaid, the owners' on what is spent.
481 let risk = state(exposure, ceiling);
482 // A budget that does not pause usage only alerts: at 100% it is a
483 // warning, never a stop. g1t's own ceiling still stops work.
484 let pause = row.as_ref().and_then(|row| row.pause_at_limit).unwrap_or(1) != 0;
485 let budget = budget_state(spent, spend_limit, pause);
486 let over_budget = budget == LimitState::Stopped;
487 let state = if (declined.is_some() && exposure > 0) || risk == LimitState::Stopped || over_budget {
488 LimitState::Stopped
489 } else if risk == LimitState::Warning || budget == LimitState::Warning {
490 LimitState::Warning
491 } else {
492 LimitState::Ok
493 };
494 let who = if account.kind == g1t_contracts::billing::AccountKind::Enterprise {
495 format!("The {} enterprise, which pays for {workspace},", account.name)
496 } else {
497 format!("The {workspace} workspace")
498 };
499 let billing = format!("/{workspace}/-/billing");
500 let message = match state {
501 LimitState::Ok => None,
502 LimitState::Warning if budget == LimitState::Warning && !pause => Some(format!(
503 "{who} has spent {} of its {} monthly budget. Usage does not pause at the budget; an owner can change that at {billing}.",
504 dollars_plain(spent),
505 dollars_plain(spend_limit.unwrap_or_default()),
506 )),
507 LimitState::Warning if budget == LimitState::Warning => Some(format!(
508 "{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}.",
509 dollars_plain(spent),
510 dollars_plain(spend_limit.unwrap_or_default()),
511 )),
512 LimitState::Warning => Some(format!(
513 "{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.",
514 dollars_plain(exposure),
515 dollars_plain(ceiling.unwrap_or_default()),
516 )),
517 LimitState::Stopped if declined.is_some() => Some(format!(
518 "{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}.",
519 declined.as_ref().and_then(|(_, error)| error.clone()).unwrap_or_else(|| "the card was declined".to_owned()),
520 )),
521 LimitState::Stopped => Some(if over_budget {
522 format!(
523 "{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}.",
524 dollars_plain(spend_limit.unwrap_or_default()),
525 )
526 } else {
527 format!(
528 "{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}.",
529 dollars_plain(ceiling.unwrap_or_default()),
530 )
531 }),
532 };
533 let growth = match trust {
534 Trust::New => Some("Free workspaces have no on-demand usage: the g1t plan starts at a $100 limit.".to_owned()),
535 Trust::Paid if first_month => Some(format!(
536 "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.",
537 dollars_plain(self.plans.paid_start_micros)
538 )),
539 Trust::Paid => Some(format!(
540 "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."
541 )),
542 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()),
543 Trust::Reviewed | Trust::Internal => None,
544 };
545 Ok(Limit {
546 workspace,
547 account: account.id.clone(),
548 account_name: account.name.clone(),
549 spent_micros: spent,
550 default_spend_limit,
551 available_micros: available,
552 growth,
553 trust,
554 exposure_micros: exposure,
555 ceiling_micros: ceiling,
556 trust_ceiling_micros: trust_ceiling,
557 spend_limit_micros: spend_limit,
558 state,
559 message,
560 prepaid_micros: prepaid,
561 max_ceiling_micros: max_ever.filter(|_| plan != PlanKind::Free),
562 raise_once_micros: raise_once,
563 raised_at,
564 first_month,
565 alert_levels: alert_levels(row.as_ref().and_then(|row| row.alert_levels.as_deref())),
566 pause_at_limit: pause,
567 budget_webhook: row.as_ref().and_then(|row| row.budget_webhook.clone()),
568 })
569 }
570
571 /// Whether the workspace's plan is in its first billing cycle.
572 pub(crate) async fn first_month(&self, workspace: &str) -> Result<bool> {
573 Ok(match self.plan_cycle(workspace).await? {
574 Some((started_at, period_end)) => in_first_cycle(&started_at, period_end.as_deref(), &rfc3339(now_ms())),
575 None => false,
576 })
577 }
578
579 /// Real money the workspaces have paid g1t, cleared: usage payments and
580 /// the plan's price. Nothing in test mode, and credits g1t gave are not
581 /// payments.
582 pub(crate) async fn live_paid(&self, members: &[JsValue]) -> Result<i64> {
583 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
584 return Ok(0);
585 }
586 let marks = vec!["?"; members.len().max(1)].join(", ");
587 let settled = rfc3339(now_ms() - SETTLE_DAYS * 24 * 60 * 60 * 1000);
588 Ok(self
589 .db
590 .prepare(format!(
591 "SELECT
592 (SELECT COALESCE(SUM(amount_micros), 0) FROM ledger
593 WHERE workspace IN ({marks}) AND kind = 'top_up' AND reference NOT LIKE 'crd%'
594 AND (amount_micros < 0
595 OR (disputed = 0 AND COALESCE(funding, '') <> 'prepaid'
596 AND created_at <= '{settled}')))
597 + (SELECT COALESCE(SUM(amount_micros), 0) FROM plan_payments
598 WHERE workspace IN ({marks}) AND paid_at <= '{settled}') AS paid"
599 ))
600 .bind(&[members, members].concat())?
601 .first::<Paid>(None)
602 .await?
603 .and_then(|row| row.paid)
604 .unwrap_or(0))
605 }
606
607 /// This month's usage on the ledger across the workspaces, in the parts
608 /// `charged` is made of (at price, the discount, what included usage,
609 /// the trial, a pool or g1t paid), and last month's charge.
610 async fn month_charges(&self, members: &[JsValue], month_start: &str) -> Result<MonthCharges> {
611 #[derive(Deserialize)]
612 struct Row {
613 price: Option<f64>,
614 discount: Option<f64>,
615 covered: Option<f64>,
616 last_month: Option<f64>,
617 }
618 let last_start = format!("{}-01", previous_month(&month_start[..7]));
619 let marks = vec!["?"; members.len().max(1)].join(", ");
620 let row = self
621 .db
622 .prepare(format!(
623 "SELECT
624 SUM(CASE WHEN created_at >= '{month_start}' THEN {price} END) AS price,
625 SUM(CASE WHEN created_at >= '{month_start}' THEN COALESCE(discount_micros, 0) END) AS discount,
626 SUM(CASE WHEN created_at >= '{month_start}' THEN COALESCE(credit_micros, 0) + COALESCE(trial_micros, 0)
627 + COALESCE(oss_micros, 0) + COALESCE(given_micros, 0) END) AS covered,
628 -SUM(CASE WHEN created_at >= '{last_start}' AND created_at < '{month_start}' THEN amount_micros END) AS last_month
629 FROM ledger WHERE kind = 'usage' AND workspace IN ({marks}) AND created_at >= '{last_start}'",
630 price = crate::statement::PRICE_SQL
631 ))
632 .bind(members)?
633 .first::<Row>(None)
634 .await?;
635 let whole = |n: Option<f64>| n.unwrap_or(0.0).round() as i64;
636 Ok(row.map_or(MonthCharges::default(), |r| MonthCharges {
637 price: whole(r.price),
638 discount: whole(r.discount),
639 covered: whole(r.covered),
640 last_month: whole(r.last_month).max(0),
641 }))
642 }
643
644 /// An Established ceiling, if the workspaces have paid steadily: three
645 /// full months of real spend, each invoiced and paid, nothing declined
646 /// in 90 days and nothing ever disputed.
647 async fn established(&self, members: &[JsValue]) -> Result<Option<i64>> {
648 let marks = vec!["?"; members.len().max(1)].join(", ");
649 let now = rfc3339(now_ms());
650 let mut months = vec![];
651 let mut month = previous_month(&now[..7]);
652 for _ in 0..3 {
653 months.push(month.clone());
654 month = previous_month(&month);
655 }
656 #[derive(Deserialize)]
657 struct Count {
658 n: Option<i64>,
659 }
660 let troubled = async {
661 Ok::<i64, worker::Error>(
662 self.db
663 .prepare(format!(
664 "SELECT (SELECT COUNT(*) FROM ledger WHERE workspace IN ({marks}) AND disputed = 1)
665 + (SELECT COUNT(*) FROM limits WHERE workspace IN ({marks}) AND autopay_failed_at >= '{since}') AS n",
666 since = rfc3339(now_ms() - 90 * 24 * 60 * 60 * 1000)
667 ))
668 .bind(&[members, members].concat())?
669 .first::<Count>(None)
670 .await?
671 .and_then(|c| c.n)
672 .unwrap_or(0),
673 )
674 };
675 #[derive(Deserialize)]
676 struct Month {
677 charged: Option<i64>,
678 unpaid: Option<i64>,
679 }
680 let read_month = |month: &String| {
681 let next = {
682 let year: i32 = month[..4].parse().unwrap_or(1970);
683 let number: u32 = month[5..7].parse().unwrap_or(1);
684 if number == 12 { format!("{}-01", year + 1) } else { format!("{year}-{:02}", number + 1) }
685 };
686 let sql = format!(
687 "SELECT
688 (SELECT -SUM(amount_micros) FROM ledger WHERE kind = 'usage' AND workspace IN ({marks})
689 AND created_at >= '{month}-01' AND created_at < '{next}-01') AS charged,
690 (SELECT COUNT(*) FROM workspace_invoices WHERE workspace IN ({marks}) AND reason = 'month'
691 AND period = '{month}' AND status <> 'paid') AS unpaid"
692 );
693 async move { self.db.prepare(sql).bind(&[members, members].concat())?.first::<Month>(None).await }
694 };
695 // The check for trouble and the three months are read at once; the
696 // answer is the one reading them in turn and stopping early gives.
697 let (troubled, rows) = try_join(troubled, try_join_all(months.iter().map(read_month))).await?;
698 if troubled > 0 {
699 return Ok(None);
700 }
701 let mut charged = vec![];
702 for row in rows {
703 let Some(row) = row else { return Ok(None) };
704 if row.unpaid.unwrap_or(0) > 0 {
705 return Ok(None);
706 }
707 charged.push(row.charged.unwrap_or(0));
708 }
709 Ok(established_ceiling(&charged))
710 }
711
712 pub(crate) async fn limit(&self, a: LimitArgs) -> Result<Outcome<Limit>> {
713 let workspace = a.workspace.to_lowercase();
714 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
715 return Ok(members_only());
716 }
717 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
718 }
719
720 /// What a source cost so far this month. `security`, `context`,
721 /// `storage` and `git` are charged by billing once the month is over
722 /// (see `storage`); `deployments` charges its own.
723 pub(crate) async fn note_pending(&self, a: NotePendingArgs) -> Result<bool> {
724 // The actions cache is the plan's to pay for; free workspaces are
725 // held to its quota instead.
726 if crate::storage::PLAN_ONLY.contains(&a.source.as_str()) && !self.has_plan(&a.workspace.to_lowercase()).await? {
727 return Ok(false);
728 }
729 let now = rfc3339(now_ms());
730 let detail = a.detail.as_deref().map(str::trim).filter(|d| !d.is_empty()).map(|d| d.chars().take(200).collect::<String>());
731 self.set_pending(&a.workspace, &a.source, &now[..7], a.cost_micros, detail.as_deref()).await?;
732 Ok(true)
733 }
734
735 /// The workspaces with usage on the ledger this month: autopay's and
736 /// the limit warnings' candidates, read once a tick for both. Served by
737 /// `ledger_usage_by_time` (migration 0050), not a scan of the ledger.
738 pub(crate) async fn month_users(&self) -> Result<BTreeSet<String>> {
739 #[derive(Deserialize)]
740 struct User {
741 workspace: String,
742 }
743 let month_start = format!("{}-01", &rfc3339(now_ms())[..7]);
744 Ok(self
745 .db
746 .prepare("SELECT DISTINCT workspace FROM ledger WHERE kind = 'usage' AND created_at >= ?")
747 .bind(&[month_start.into()])?
748 .all()
749 .await?
750 .results::<User>()?
751 .into_iter()
752 .map(|user| user.workspace)
753 .collect())
754 }
755
756 /// Charges the saved card of each workspace nearing its limit, for what
757 /// it owes, so that a workspace that pays never has its work stopped.
758 /// Only with live payments: test-mode payments are not money and lower
759 /// nothing. Not for a workspace's own spend limit, which means stop, nor
760 /// for enterprises, which are invoiced. A charge at the limit always
761 /// goes through, whatever the minimum charge.
762 ///
763 /// `users` are the workspaces with usage this month ([`Self::month_users`]).
764 pub(crate) async fn autopay(&self, users: &BTreeSet<String>) -> Result<()> {
765 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
766 return Ok(());
767 }
768 #[derive(Deserialize)]
769 struct Candidate {
770 workspace: String,
771 }
772 // With a card, and not already declined: a declined card waits for
773 // the owners, rather than being tried again every few minutes.
774 let candidates = self
775 .db
776 .prepare(
777 "SELECT accounts.workspace AS workspace
778 FROM accounts LEFT JOIN limits ON limits.workspace = accounts.workspace
779 WHERE accounts.customer_id IS NOT NULL AND limits.autopay_failed_at IS NULL",
780 )
781 .all()
782 .await?
783 .results::<Candidate>()?
784 .into_iter()
785 .filter(|candidate| users.contains(&candidate.workspace));
786 for candidate in candidates {
787 let limit = self.limit_of(&candidate.workspace).await?;
788 // Near g1t's ceiling on what is unpaid; the spend limit is the
789 // owners' and stops work by itself, but what is owed is still owed.
790 let near = limit.ceiling_micros.is_some_and(|ceiling| limit.exposure_micros * 5 >= ceiling * 4);
791 if !near || limit.trust == Trust::Internal || limit.account.starts_with("ent_") {
792 continue;
793 }
794 let today = rfc3339(now_ms())[..10].to_owned();
795 match self.invoice_workspace(&candidate.workspace, "threshold", &today).await? {
796 Ok(_) => {}
797 Err(why) => worker::console_log!("{}: no threshold invoice: {why}", candidate.workspace),
798 }
799 }
800 Ok(())
801 }
802
803 /// Closes last month for each workspace with a card on file: charges
804 /// what it owed when the month ended. Live payments only, once per
805 /// workspace and month; a declined card stops work until it is paid.
806 /// Comped workspaces owe nothing, and enterprises are invoiced. Only
807 /// here does the minimum charge apply: less carries over.
808 pub(crate) async fn close_months(&self) -> Result<()> {
809 if !self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live) {
810 return Ok(());
811 }
812 let now = rfc3339(now_ms());
813 let month_start = format!("{}-01", &now[..7]);
814 let closing = previous_month(&now[..7]);
815 #[derive(Deserialize)]
816 struct Open {
817 workspace: String,
818 balance: Option<i64>,
819 }
820 let open = self
821 .db
822 .prepare(
823 "SELECT accounts.workspace AS workspace,
824 (SELECT SUM(amount_micros) FROM ledger
825 WHERE ledger.workspace = accounts.workspace AND ledger.created_at < ?1) AS balance
826 FROM accounts
827 WHERE accounts.customer_id IS NOT NULL
828 AND NOT EXISTS (SELECT 1 FROM month_closes
829 WHERE month_closes.workspace = accounts.workspace AND month_closes.month = ?2)
830 LIMIT 20",
831 )
832 .bind(&[month_start.as_str().into(), closing.as_str().into()])?
833 .all()
834 .await?
835 .results::<Open>()?;
836 for account in open {
837 let record = |status: &str, amount: i64, payment: Option<&str>, error: Option<&str>| {
838 self.db
839 .prepare(
840 "INSERT OR IGNORE INTO month_closes (workspace, month, status, amount_micros, payment_id, error, closed_at)
841 VALUES (?, ?, ?, ?, ?, ?, ?)",
842 )
843 .bind(&[
844 account.workspace.as_str().into(),
845 closing.as_str().into(),
846 status.into(),
847 (amount as f64).into(),
848 crate::optional(payment),
849 crate::optional(error),
850 now.as_str().into(),
851 ])
852 };
853 let payer = self.account_of(&account.workspace).await?;
854 if payer.terms.full_discount() || payer.id.starts_with("ent_") {
855 record("skipped", 0, None, None)?.run().await?;
856 continue;
857 }
858 // AI credit left at the month's end pays only for models: not
859 // money for anything else that is owed (ai.rs).
860 let ai_left = self.models_left_before(&account.workspace, &month_start).await?;
861 let owed = (ai_left - account.balance.unwrap_or(0)).max(0);
862 if owed == 0 {
863 record("nothing", 0, None, None)?.run().await?;
864 continue;
865 }
866 if !worth_charging(owed, self.plans.min_charge_micros) {
867 // Under the minimum charge: a card payment's fee would be
868 // too much of it. It stays owed and goes on the next
869 // invoice that reaches the minimum.
870 record("carried", owed, None, None)?.run().await?;
871 continue;
872 }
873 match self.invoice_workspace(&account.workspace, "month", &closing).await? {
874 Ok(invoice) if invoice.status == "paid" => {
875 record("paid", invoice.amount_micros, Some(&invoice.invoice_id), None)?.run().await?;
876 }
877 Ok(invoice) => {
878 record("failed", invoice.amount_micros, Some(&invoice.invoice_id), Some("the card was declined"))?.run().await?;
879 }
880 Err(why) => {
881 record("nothing", 0, None, Some(&why))?.run().await?;
882 }
883 }
884 }
885 Ok(())
886 }
887
888 /// Emails a workspace's owners as it passes 50, 75, 90 and 100% of its
889 /// plan's included usage, its spend limit and g1t's ceiling, once each a
890 /// month; when its card was declined; and when a spend spike paused it.
891 /// The same alerts show in the app (`entitlements`).
892 ///
893 /// `users` are the workspaces with usage this month ([`Self::month_users`]).
894 pub(crate) async fn warn_limits(&self, identity: &worker::Fetcher, users: &BTreeSet<String>) -> Result<()> {
895 if self.stripe.is_none() {
896 return Ok(());
897 }
898 let now = rfc3339(now_ms());
899 let month = &now[..7];
900 #[derive(Deserialize)]
901 struct Candidate {
902 workspace: String,
903 }
904 let mut candidates = users.clone();
905 candidates.extend(
906 self.db
907 .prepare("SELECT workspace FROM limits WHERE autopay_failed_at IS NOT NULL")
908 .all()
909 .await?
910 .results::<Candidate>()?
911 .into_iter()
912 .map(|candidate| candidate.workspace),
913 );
914 #[derive(Deserialize)]
915 struct Told {
916 autopay_failed_at: Option<String>,
917 declined_told_at: Option<String>,
918 }
919 #[derive(Deserialize)]
920 struct Sent {
921 meter: String,
922 level: Option<i64>,
923 }
924 for workspace in candidates {
925 let told = self
926 .db
927 .prepare("SELECT autopay_failed_at, declined_told_at FROM limits WHERE workspace = ?")
928 .bind(&[workspace.as_str().into()])?
929 .first::<Told>(None)
930 .await?;
931 let billing = format!("https://g1t.sh/{workspace}/-/billing");
932
933 // A declined card, once per decline.
934 if let Some(Told { autopay_failed_at: Some(failed), declined_told_at }) = &told
935 && declined_told_at.as_deref().is_none_or(|at| at < failed.as_str()) {
936 let limit = self.limit_of(&workspace).await?;
937 let sent = notify(
938 identity,
939 &workspace,
940 &format!("g1t: the card for {workspace} was declined"),
941 &limit.message.clone().unwrap_or_else(|| format!("g1t could not charge the card on file for {workspace}.")),
942 "Update the card",
943 &billing,
944 )
945 .await;
946 if sent {
947 self.db
948 .prepare("UPDATE limits SET declined_told_at = ? WHERE workspace = ?")
949 .bind(&[now.as_str().into(), workspace.as_str().into()])?
950 .run()
951 .await?;
952 }
953 }
954
955 // 50, 75, 90 and 100%, once each a month and meter: only the
956 // highest new level is emailed.
957 let alerts = self.alerts_for(&workspace).await?;
958 if alerts.is_empty() {
959 continue;
960 }
961 let sent: Vec<Sent> = self
962 .db
963 .prepare("SELECT meter, MAX(level) AS level FROM alerts_sent WHERE workspace = ? AND month = ? GROUP BY meter")
964 .bind(&[workspace.as_str().into(), month.into()])?
965 .all()
966 .await?
967 .results::<Sent>()?;
968 for alert in alerts {
969 let already = sent.iter().find(|s| s.meter == alert.meter).and_then(|s| s.level).unwrap_or(0);
970 if i64::from(alert.level) <= already {
971 continue;
972 }
973 let subject = match alert.meter.as_str() {
974 "included" => format!("g1t: {workspace} has used {}% of its included usage", alert.level),
975 "spend_limit" => format!("g1t: {workspace} has used {}% of its spend limit", alert.level),
976 _ => format!("g1t: {workspace} has used {}% of its usage limit", alert.level),
977 };
978 // The budget's webhook hears of its alerts too, once each.
979 if alert.meter == "spend_limit"
980 && let Some(url) = self.budget_webhook_of(&workspace).await?
981 {
982 self.post_budget_webhook(&url, &workspace, alert.level, alert.used_micros, alert.limit_micros).await;
983 }
984 if notify(identity, &workspace, &subject, &alert.message, "Open billing", &billing).await {
985 self.db
986 .prepare(
987 "INSERT OR IGNORE INTO alerts_sent (workspace, month, meter, level, sent_at) VALUES (?1, ?2, ?3, ?4, ?5)",
988 )
989 .bind(&[workspace.as_str().into(), month.into(), alert.meter.as_str().into(), alert.level.into(), now.as_str().into()])?
990 .run()
991 .await?;
992 }
993 }
994 }
995 self.tell_spikes(identity).await?;
996 Ok(())
997 }
998
999 pub(crate) async fn check_limit(&self, a: CheckLimitArgs) -> Result<Outcome<Limit>> {
1000 Ok(Outcome::Ok(self.limit_of(&a.workspace).await?))
1001 }
1002
1003 /// The owners' spend limit: anywhere up to what is available without
1004 /// asking; once, up to twice the highest ceiling (`raise_once`), which
1005 /// also raises g1t's ceiling to match.
1006 pub(crate) async fn set_spend_limit(&self, a: SetSpendLimitArgs) -> Result<Outcome<Limit>> {
1007 let workspace = a.workspace.to_lowercase();
1008 if !a.actor.manages_billing(&workspace) {
1009 return Ok(Outcome::fail(
1010 FailureCode::Forbidden,
1011 "Only an owner or a billing manager can set the workspace's spend limit.",
1012 ));
1013 }
1014 let before = self.limit_of(&workspace).await?;
1015 // A free workspace has no on-demand usage to limit: its ceiling is
1016 // only what it can owe for storage, and no raise applies to it.
1017 if before.trust == Trust::New {
1018 return Ok(Outcome::fail(
1019 FailureCode::Conflict,
1020 format!("{workspace} is not on the g1t plan, so it has no usage to put a spend limit on. The plan starts with a {} limit for its first month.", dollars_plain(self.plans.paid_start_micros)),
1021 ));
1022 }
1023 let mut raising = false;
1024 if let (Some(requested), false) = (a.spend_limit_micros, a.use_full_limit) {
1025 match (before.available_micros, matches!(before.trust, Trust::Internal | Trust::Reviewed)) {
1026 (_, true) | (None, _) => {
1027 if requested < 0 {
1028 return Ok(Outcome::fail(FailureCode::Invalid, "A spend limit cannot be negative."));
1029 }
1030 }
1031 (Some(available), false) => match self_serve(requested, available, before.raise_once_micros, a.raise_once) {
1032 Ok(uses_raise) => raising = uses_raise,
1033 Err(why) => return Ok(Outcome::fail(FailureCode::Invalid, why)),
1034 },
1035 }
1036 }
1037 let now = rfc3339(now_ms());
1038 let limit = if a.use_full_limit { JsValue::NULL } else { a.spend_limit_micros.map_or(JsValue::NULL, |limit| (limit as f64).into()) };
1039 self.db
1040 .prepare(
1041 "INSERT INTO limits (workspace, spend_limit_micros, spend_limit_full, updated_at) VALUES (?1, ?2, ?3, ?4)
1042 ON CONFLICT (workspace) DO UPDATE SET spend_limit_micros = ?2, spend_limit_full = ?3, updated_at = ?4",
1043 )
1044 .bind(&[workspace.as_str().into(), limit, (if a.use_full_limit { 1 } else { 0 }).into(), now.as_str().into()])?
1045 .run()
1046 .await?;
1047 if raising {
1048 let raised = a.spend_limit_micros.unwrap_or_default();
1049 // The ceiling rises with it, once.
1050 self.db
1051 .prepare(
1052 "UPDATE limits SET granted_ceiling_micros = MAX(COALESCE(granted_ceiling_micros, 0), ?2),
1053 raised_at = ?3, updated_at = ?3 WHERE workspace = ?1 AND raised_at IS NULL",
1054 )
1055 .bind(&[workspace.as_str().into(), (raised as f64).into(), now.as_str().into()])?
1056 .run()
1057 .await?;
1058 let account = self.account_of(&workspace).await?;
1059 self.audit(&account.id, "raise_once", &format!("{workspace} used its one-time raise: {}", dollars_plain(raised)), &a.actor.username)
1060 .await?;
1061 }
1062 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
1063 }
1064
1065 /// `set_budget`: the owners' monthly budget on usage after what the
1066 /// plan includes: the spend limit (set as `set_spend_limit` sets it,
1067 /// with the same bounds), which alerts to send, whether usage pauses at
1068 /// 100%, and a webhook told at each alert.
1069 pub(crate) async fn set_budget(&self, a: SetBudgetArgs) -> Result<Outcome<Limit>> {
1070 let workspace = a.workspace.to_lowercase();
1071 if !a.actor.manages_billing(&workspace) {
1072 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner or a billing manager can set the workspace's budget."));
1073 }
1074 if a.alerts.iter().any(|level| !ALERT_LEVELS.contains(level)) {
1075 return Ok(Outcome::fail(FailureCode::Invalid, "Alerts are at 50, 75, 90 or 100% of the budget."));
1076 }
1077 let webhook = a.webhook.as_deref().map(str::trim).filter(|url| !url.is_empty());
1078 if let Some(url) = webhook
1079 && !webhook_ok(url)
1080 {
1081 return Ok(Outcome::fail(FailureCode::Invalid, "The webhook is an https:// address of your own, at most 500 characters."));
1082 }
1083 if !a.keep_limit {
1084 let set = self
1085 .set_spend_limit(SetSpendLimitArgs {
1086 actor: a.actor.clone(),
1087 workspace: workspace.clone(),
1088 spend_limit_micros: a.amount_micros,
1089 use_full_limit: false,
1090 raise_once: false,
1091 })
1092 .await?;
1093 if let Outcome::Fail(failure) = set {
1094 return Ok(Outcome::Fail(failure));
1095 }
1096 } else if self.limit_of(&workspace).await?.trust == Trust::New {
1097 return Ok(Outcome::fail(FailureCode::Conflict, format!("{workspace} is not on the g1t plan, so it has no budget to alert on.")));
1098 } else {
1099 // The row the alerts are kept on, if the workspace has none yet.
1100 self.db
1101 .prepare("INSERT OR IGNORE INTO limits (workspace, updated_at) VALUES (?, ?)")
1102 .bind(&[workspace.as_str().into(), rfc3339(now_ms()).into()])?
1103 .run()
1104 .await?;
1105 }
1106 let mut levels = a.alerts.clone();
1107 levels.sort_by(|x, y| y.cmp(x));
1108 levels.dedup();
1109 let stored = levels.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
1110 self.db
1111 .prepare(
1112 "UPDATE limits SET alert_levels = ?2, pause_at_limit = ?3, budget_webhook = ?4, updated_at = ?5 WHERE workspace = ?1",
1113 )
1114 .bind(&[
1115 workspace.as_str().into(),
1116 stored.as_str().into(),
1117 i32::from(a.pause_at_limit).into(),
1118 crate::optional(webhook),
1119 rfc3339(now_ms()).into(),
1120 ])?
1121 .run()
1122 .await?;
1123 let account = self.account_of(&workspace).await?;
1124 self.audit(
1125 &account.id,
1126 "budget",
1127 &format!(
1128 "{workspace}: budget {}, alerts at {}, {}{}",
1129 a.amount_micros.map_or_else(|| "automatic".to_owned(), dollars_plain),
1130 if stored.is_empty() { "none".to_owned() } else { format!("{stored}%") },
1131 if a.pause_at_limit { "pauses usage at 100%" } else { "alerts only" },
1132 if webhook.is_some() { ", with a webhook" } else { "" }
1133 ),
1134 &a.actor.username,
1135 )
1136 .await?;
1137 Ok(Outcome::Ok(self.limit_of(&workspace).await?))
1138 }
1139
1140
1141 /// The budget's webhook, if the workspace has one.
1142 async fn budget_webhook_of(&self, workspace: &str) -> Result<Option<String>> {
1143 #[derive(Deserialize)]
1144 struct Row {
1145 budget_webhook: Option<String>,
1146 }
1147 Ok(self
1148 .db
1149 .prepare("SELECT budget_webhook FROM limits WHERE workspace = ?")
1150 .bind(&[workspace.into()])?
1151 .first::<Row>(None)
1152 .await?
1153 .and_then(|row| row.budget_webhook)
1154 .filter(|url| webhook_ok(url)))
1155 }
1156 /// Posts a budget alert to the workspace's webhook, if it has one.
1157 /// Never fails the alert: a receiver that does not answer is logged.
1158 pub(crate) async fn post_budget_webhook(&self, url: &str, workspace: &str, level: u32, spent: i64, budget: i64) {
1159 let body = serde_json::json!({
1160 "event": "budget.alert",
1161 "workspace": workspace,
1162 "level_percent": level,
1163 "spent_micros": spent,
1164 "budget_micros": budget,
1165 "sent_at": rfc3339(now_ms()),
1166 });
1167 let headers = worker::Headers::new();
1168 let _ = headers.set("content-type", "application/json");
1169 let _ = headers.set("user-agent", "g1t-billing");
1170 let mut init = worker::RequestInit::new();
1171 init.with_method(worker::Method::Post).with_headers(headers).with_body(Some(body.to_string().into()));
1172 let sent = match worker::Request::new_with_init(url, &init) {
1173 Ok(request) => worker::Fetch::Request(request).send().await.map(|r| r.status_code()),
1174 Err(error) => Err(error),
1175 };
1176 match sent {
1177 Ok(status) if (200..300).contains(&status) => {}
1178 Ok(status) => worker::console_warn!("{workspace}'s budget webhook answered {status}"),
1179 Err(error) => worker::console_warn!("{workspace}'s budget webhook could not be reached: {error}"),
1180 }
1181 }
1182}
1183
1184/// Whether `owed` is enough to charge a card when a month closes: at least
1185/// the minimum charge (`MIN_CHARGE_MICROS`). Less carries over to the next
1186/// invoice. Charges at a limit do not ask.
1187pub(crate) fn worth_charging(owed: i64, min_charge: i64) -> bool {
1188 owed > 0 && owed >= min_charge
1189}
1190
1191/// Emails the workspace's owners through identity. False if nothing was sent.
1192pub(crate) async fn notify(identity: &worker::Fetcher, workspace: &str, subject: &str, intro: &str, action: &str, link: &str) -> bool {
1193 let footer = "You get this because you own this workspace on g1t. Limits and alerts are explained at https://docs.g1t.sh/guides/usage-and-billing/#limits";
1194 notify_with(identity, workspace, subject, intro, action, link, footer).await
1195}
1196
1197/// `notify`, with a footer of its own.
1198pub(crate) async fn notify_with(
1199 identity: &worker::Fetcher,
1200 workspace: &str,
1201 subject: &str,
1202 intro: &str,
1203 action: &str,
1204 link: &str,
1205 footer: &str,
1206) -> bool {
1207 let args = g1t_contracts::identity::NotifyOwnersArgs {
1208 workspace: workspace.to_owned(),
1209 subject: subject.to_owned(),
1210 intro: intro.to_owned(),
1211 action: action.to_owned(),
1212 link: link.to_owned(),
1213 footer: footer.to_owned(),
1214 };
1215 match g1t_kit::call::<_, u32>(identity, "notify_owners", &args).await {
1216 Ok(sent) => sent > 0,
1217 Err(error) => {
1218 worker::console_error!("could not tell {workspace}'s owners: {error}");
1219 false
1220 }
1221 }
1222}
1223
1224/// `2026-09` for `2026-10`, and `2025-12` for `2026-01`.
1225pub(crate) fn previous_month(month: &str) -> String {
1226 let year: i32 = month[..4].parse().unwrap_or(1970);
1227 let number: u32 = month[5..7].parse().unwrap_or(1);
1228 if number == 1 {
1229 format!("{}-12", year - 1)
1230 } else {
1231 format!("{year}-{:02}", number - 1)
1232 }
1233}
1234
1235#[cfg(test)]
1236mod tests {
1237 use super::*;
1238
1239 #[test]
1240 fn a_budget_alerts_at_the_levels_chosen_and_pauses_only_if_asked() {
1241 // Every level when none were chosen; the chosen ones, highest first.
1242 assert_eq!(alert_levels(None), [100, 90, 75, 50]);
1243 assert_eq!(alert_levels(Some("50,100,75")), [100, 75, 50]);
1244 assert_eq!(alert_levels(Some("")), Vec::<u32>::new());
1245 assert_eq!(alert_levels(Some("40, 50")), [50]);
1246 // The highest chosen level reached.
1247 assert_eq!(alert_level_in(80, 100, &[100, 75, 50]), 75);
1248 assert_eq!(alert_level_in(80, 100, &[100, 90]), 0);
1249 assert_eq!(alert_level_in(100, 100, &[100, 75, 50]), 100);
1250 assert_eq!(alert_level_in(10, 0, &[50]), 0);
1251 // At 100%: a stop when the budget pauses usage, else a warning.
1252 assert_eq!(budget_state(100, Some(100), true), LimitState::Stopped);
1253 assert_eq!(budget_state(100, Some(100), false), LimitState::Warning);
1254 assert_eq!(budget_state(10, Some(100), false), LimitState::Ok);
1255 assert_eq!(budget_state(10, None, true), LimitState::Ok);
1256 }
1257
1258 #[test]
1259 fn a_budget_webhook_is_someone_elses_https_address() {
1260 assert!(webhook_ok("https://hooks.acme.test/g1t"));
1261 assert!(!webhook_ok("http://hooks.acme.test/g1t"));
1262 assert!(!webhook_ok("https://g1t.sh/x"));
1263 assert!(!webhook_ok("https://api.g1t.sh/x"));
1264 assert!(!webhook_ok("https://localhost:3000/x"));
1265 assert!(!webhook_ok("https://a b.test/"));
1266 assert!(!webhook_ok(&format!("https://acme.test/{}", "x".repeat(600))));
1267 }
1268 #[test]
1269 fn the_automatic_spend_limit_follows_last_month() {
1270 assert_eq!(automatic_spend_limit(0), 200_000_000);
1271 assert_eq!(automatic_spend_limit(50_000_000), 200_000_000);
1272 assert_eq!(automatic_spend_limit(900_000_000), 1_800_000_000);
1273 }
1274
1275 #[test]
1276 fn three_steady_months_make_a_workspace_established() {
1277 assert_eq!(established_ceiling(&[900_000_000, 850_000_000, 950_000_000]), Some(2_700_000_000));
1278 assert_eq!(established_ceiling(&[5_000_000_000, 5_000_000_000, 5_000_000_000]), Some(10_000_000_000));
1279 assert_eq!(established_ceiling(&[900_000_000, 10_000_000, 950_000_000]), None);
1280 assert_eq!(established_ceiling(&[900_000_000, 900_000_000]), None);
1281 }
1282
1283 #[test]
1284 fn alerts_come_at_half_three_quarters_ninety_and_the_limit() {
1285 assert_eq!(alert_level(0, 10_000_000), 0);
1286 assert_eq!(alert_level(4_999_999, 10_000_000), 0);
1287 assert_eq!(alert_level(5_000_000, 10_000_000), 50);
1288 assert_eq!(alert_level(7_500_000, 10_000_000), 75);
1289 assert_eq!(alert_level(8_999_999, 10_000_000), 75);
1290 assert_eq!(alert_level(9_000_000, 10_000_000), 90);
1291 assert_eq!(alert_level(10_000_000, 10_000_000), 100);
1292 assert_eq!(alert_level(25_000_000, 10_000_000), 100);
1293 // Nothing to measure against: no alert.
1294 assert_eq!(alert_level(5, 0), 0);
1295 }
1296
1297 #[test]
1298 fn amounts_under_the_minimum_carry_over_only_at_the_month_close() {
1299 let min = 5_000_000;
1300 assert!(!worth_charging(0, min));
1301 assert!(!worth_charging(4_990_000, min));
1302 assert!(worth_charging(5_000_000, min));
1303 assert!(worth_charging(12_000_000, min));
1304 // $3 carried from last month and $2.50 this month: charged together.
1305 let carried = 3_000_000;
1306 assert!(!worth_charging(carried, min));
1307 assert!(worth_charging(carried + 2_500_000, min));
1308 }
1309
1310 #[test]
1311 fn the_month_before_wraps_the_year() {
1312 assert_eq!(previous_month("2026-10"), "2026-09");
1313 assert_eq!(previous_month("2026-01"), "2025-12");
1314 }
1315
1316 fn ceilings() -> Ceilings {
1317 Ceilings { new: 3_000_000, paid_min: 25_000_000, paid_max: 1_000_000_000 }
1318 }
1319
1320 #[test]
1321 fn trust_grows_with_what_was_paid_within_bounds() {
1322 assert_eq!(ceilings().for_paid(5_000_000), 25_000_000);
1323 assert_eq!(ceilings().for_paid(100_000_000), 200_000_000);
1324 assert_eq!(ceilings().for_paid(10_000_000_000), 1_000_000_000);
1325 }
1326
1327 #[test]
1328 fn a_new_paid_workspace_starts_at_a_hundred_dollars_and_only_goes_up() {
1329 let start = 100_000_000;
1330 // The first month: the starting ceiling, whatever was paid.
1331 assert_eq!(paid_ceiling(&ceilings(), start, true, 900_000_000, None), start);
1332 // After it, with little paid: never below the start.
1333 assert_eq!(paid_ceiling(&ceilings(), start, false, 20_000_000, None), start);
1334 assert_eq!(paid_ceiling(&ceilings(), start, false, 0, None), start);
1335 // Payments that cleared raise it: twice what was paid.
1336 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, None), 600_000_000);
1337 // Established follows the monthly spend.
1338 assert_eq!(paid_ceiling(&ceilings(), start, false, 300_000_000, Some(2_700_000_000)), 2_700_000_000);
1339 }
1340
1341 #[test]
1342 fn the_first_billing_cycle_is_the_first_month() {
1343 // A plan that started on the 5th, paid through the 5th of next month.
1344 assert!(in_first_cycle("2026-10-05T10:00:00Z", Some("2026-11-05T10:00:00Z"), "2026-10-20T00:00:00Z"));
1345 // Renewed: the period now ends two months after the start.
1346 assert!(!in_first_cycle("2026-10-05T10:00:00Z", Some("2026-12-05T10:00:00Z"), "2026-11-20T00:00:00Z"));
1347 // No period known yet: the first 31 days.
1348 assert!(in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-04T00:00:00Z"));
1349 assert!(!in_first_cycle("2026-10-05T10:00:00Z", None, "2026-11-10T00:00:00Z"));
1350 // Day counting is exact across months and years.
1351 assert_eq!(days("1970-01-01"), 0);
1352 assert_eq!(days("2026-11-01") - days("2026-10-01"), 31);
1353 assert_eq!(days("2028-03-01") - days("2028-02-28"), 2);
1354 assert_eq!(days("2027-01-01") - days("2026-12-31"), 1);
1355 }
1356
1357 #[test]
1358 fn owners_set_their_limit_up_to_the_highest_ceiling_without_asking() {
1359 // First month at $100; the highest ever is $100.
1360 let (available, once) = spend_bounds(100_000_000, 100_000_000, 0, false);
1361 assert_eq!(available, 100_000_000);
1362 assert_eq!(once, Some(200_000_000));
1363 assert_eq!(self_serve(80_000_000, available, once, false), Ok(false));
1364 assert_eq!(self_serve(100_000_000, available, once, false), Ok(false));
1365 // Above it without the raise: refused, saying what to do.
1366 assert!(self_serve(150_000_000, available, once, false).unwrap_err().contains("one-time raise"));
1367 // With the raise: up to twice the highest ceiling, once.
1368 assert_eq!(self_serve(200_000_000, available, once, true), Ok(true));
1369 assert!(self_serve(200_000_001, available, once, true).unwrap_err().contains("Raise my limit"));
1370 // Once used, it is gone.
1371 let (available, once) = spend_bounds(200_000_000, 200_000_000, 0, true);
1372 assert_eq!(once, None);
1373 assert_eq!(self_serve(200_000_000, available, once, false), Ok(false));
1374 assert!(self_serve(300_000_000, available, once, true).unwrap_err().contains("is used"));
1375 // A ceiling that came down still leaves the highest one available.
1376 let (available, _) = spend_bounds(100_000_000, 400_000_000, 0, true);
1377 assert_eq!(available, 400_000_000);
1378 assert!(self_serve(-1, available, None, false).is_err());
1379 }
1380
1381 #[test]
1382 fn prepaying_raises_what_can_be_used_at_once() {
1383 // $500 prepaid this month, $120 used: nothing owed, $380 left.
1384 assert_eq!(exposure(120_000_000, 500_000_000, 0), (0, 380_000_000));
1385 // Prepaid last month and carried in.
1386 assert_eq!(exposure(120_000_000, 0, 500_000_000), (0, 380_000_000));
1387 // Used past the prepayment: the rest is owed.
1388 assert_eq!(exposure(620_000_000, 500_000_000, 0), (120_000_000, 0));
1389 // Owed from before adds to this month's.
1390 assert_eq!(exposure(10_000_000, 0, -4_000_000), (14_000_000, 0));
1391 // With a $100 ceiling and $500 prepaid, work stops at $600 of use,
1392 // not at $100.
1393 let ceiling = 100_000_000;
1394 assert_eq!(state(exposure(599_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Warning);
1395 assert_eq!(state(exposure(600_000_000, 500_000_000, 0).0, Some(ceiling)), LimitState::Stopped);
1396 // And the owners may set their spend limit that much higher.
1397 assert_eq!(spend_bounds(ceiling, ceiling, 500_000_000, true).0, 600_000_000);
1398 }
1399
1400 #[test]
1401 fn work_warns_at_eighty_percent_and_stops_at_the_ceiling() {
1402 assert_eq!(state(0, Some(100)), LimitState::Ok);
1403 assert_eq!(state(79, Some(100)), LimitState::Ok);
1404 assert_eq!(state(80, Some(100)), LimitState::Warning);
1405 assert_eq!(state(100, Some(100)), LimitState::Stopped);
1406 assert_eq!(state(1_000_000, None), LimitState::Ok);
1407 }
1408}