g1t/services/billing/src/credits.rs

791 lines34,743 bytesCodeBlame
1//! What pays for usage before the workspace does.
2//!
3//! Every charge is worked out the same way: its cost plus the margin, then
4//! the account's terms. What is left is drawn down, in this order, from:
5//!
6//! 1. **The plan's included usage** (`PLAN_INCLUDED_MICROS` a month, $10),
7//! when the workspace has the g1t plan. Any usage draws on it. Unused
8//! included usage does not roll over.
9//! 2. **The trial credit**: one grant per workspace
10//! (`TRIAL_WORKSPACE_MICROS`, $5), made once its card is checked (see
11//! `cards`), out of a pool for everyone that resets each calendar month
12//! (`TRIAL_MONTHLY_POOL_MICROS`, $100). Never for deployments.
13//! 3. **g1t's open-source pool** (`OSS_POOL_MICROS` a month, $25, at most
14//! `OSS_REPO_MICROS`, $2, for any one repository): checks, workflows and
15//! the merge queue on a public repository.
16//!
17//! Whatever is left is charged: from what was paid in advance first, since
18//! a charge comes off the balance, and then owed. For a free workspace's
19//! compute, what is left past its trial is covered by g1t (`given`): a free
20//! workspace is never charged for compute, and `reserve` keeps that to the
21//! runs already in flight when the trial ran out.
22//!
23//! Each source is a fixed, capped budget that something pays for: the
24//! plan, or g1t. Nothing here is an open-ended allowance per workspace.
25//!
26//! Months are calendar months in UTC, the same as the limits'. Every draw
27//! is one D1 batch, which runs as a transaction, so two charges at once
28//! never take more than a budget holds.
29
30use g1t_contracts::billing::{BillingAccount, ComputeKind, Feature, PlanKind, Pools, TermsKind, Trial, TrialArgs};
31use g1t_contracts::time::rfc3339;
32use g1t_kit::now_ms;
33use serde::Deserialize;
34use worker::{Env, Result};
35
36use crate::Billing;
37use crate::features::dollars;
38
39/// Every number of the plan and the pools, from the billing service's
40/// variables, each with its default.
41#[derive(Clone, Debug)]
42pub(crate) struct Config {
43 /// `PLAN_MONTHLY_CENTS`: the plan's price, per workspace: $20.
44 pub plan_monthly_cents: u32,
45 /// `PLAN_INCLUDED_MICROS`: its included usage each month: $10.
46 pub plan_included_micros: i64,
47 /// `OSS_POOL_MICROS`: g1t's open-source pool each month, in all.
48 pub oss_pool_micros: i64,
49 /// `OSS_REPO_MICROS`: any one public repository's share of it.
50 pub oss_repo_micros: i64,
51 /// `TRIAL_WORKSPACE_MICROS`: each new workspace's trial credit.
52 pub trial_workspace_micros: i64,
53 /// `TRIAL_MONTHLY_POOL_MICROS`: trial grants each month, in all.
54 pub trial_monthly_pool_micros: i64,
55 /// `MIN_CHARGE_MICROS`: a month's close charges no less; smaller
56 /// amounts carry over. Charges at a limit always go through.
57 pub min_charge_micros: i64,
58 /// `FREE_PRIVATE_STORAGE_BYTES`: private repository storage that is
59 /// free for every workspace. Past it, the plan pays at cost plus the
60 /// margin; a free workspace's pushes to private repositories stop.
61 pub free_storage_bytes: i64,
62 /// `PUBLIC_PACKAGES_FREE_BYTES` and `PRIVATE_PACKAGES_FREE_BYTES`: what
63 /// a workspace's public and private packages may hold for free (10 GB
64 /// and 500 MB). Past them a free workspace's pushes are refused (the
65 /// packages service asks); the plan pays at cost plus the margin.
66 pub public_package_free_bytes: i64,
67 pub private_package_free_bytes: i64,
68 /// `FREE_AUDIT_RETENTION_DAYS`: days of audit log a free workspace
69 /// keeps. `AUDIT_RETENTION_DAYS`: the plan's, g1t's own and an
70 /// enterprise's. `AUDIT_MAX_DAYS`: the most staff can set for an
71 /// account; the events service deletes everything older regardless.
72 pub free_audit_days: u32,
73 pub audit_days: u32,
74 pub audit_max_days: u32,
75 /// `RUN_CAP_MICROS` and `ISSUE_CAP_MICROS`: one run's spend cap, and
76 /// agents' spend on one issue in all.
77 pub run_cap_micros: i64,
78 pub issue_cap_micros: i64,
79 /// `LIMIT_PAID_START_MICROS`: a new paid workspace's ceiling in its
80 /// first month.
81 pub paid_start_micros: i64,
82 /// `SPIKE_FACTOR` and `SPIKE_FLOOR_MICROS`: an hour above this many
83 /// times the usual hour, and at least this much, is a spike.
84 pub spike_factor: i64,
85 pub spike_floor_micros: i64,
86 /// `OVERAGE_FORGIVE_COST_MICROS`: the most of an overage's real cost a
87 /// one-click goodwill credit covers.
88 pub forgive_cost_micros: i64,
89 /// `GIT_OPERATIONS_INCLUDED`: git operations a month that are free for
90 /// every workspace. Past it, the plan pays at cost plus the margin and
91 /// is never slowed; a free workspace is slowed down (the repos
92 /// service's `GIT_OPERATIONS_FREE_CAP`, the same number), never charged.
93 pub git_included: u64,
94}
95
96impl Default for Config {
97 fn default() -> Self {
98 Config {
99 plan_monthly_cents: 2_000,
100 plan_included_micros: 10_000_000,
101 oss_pool_micros: 25_000_000,
102 oss_repo_micros: 2_000_000,
103 trial_workspace_micros: 5_000_000,
104 trial_monthly_pool_micros: 100_000_000,
105 min_charge_micros: 5_000_000,
106 free_storage_bytes: 1_000_000_000,
107 public_package_free_bytes: 10_000_000_000,
108 private_package_free_bytes: 500_000_000,
109 free_audit_days: 7,
110 audit_days: 90,
111 audit_max_days: 400,
112 run_cap_micros: g1t_contracts::guardrails::DEFAULT_RUN_CAP_MICROS,
113 issue_cap_micros: 10_000_000,
114 paid_start_micros: 100_000_000,
115 spike_factor: 5,
116 spike_floor_micros: 5_000_000,
117 forgive_cost_micros: 50_000_000,
118 git_included: 50_000,
119 }
120 }
121}
122
123impl Config {
124 pub(crate) fn from_env(env: &Env) -> Self {
125 let d = Config::default();
126 let number = |name: &str, default: i64| -> i64 {
127 env.var(name).ok().and_then(|v| v.to_string().trim().parse::<i64>().ok()).filter(|n| *n >= 0).unwrap_or(default)
128 };
129 Config {
130 plan_monthly_cents: number("PLAN_MONTHLY_CENTS", d.plan_monthly_cents.into()) as u32,
131 plan_included_micros: number("PLAN_INCLUDED_MICROS", d.plan_included_micros),
132 oss_pool_micros: number("OSS_POOL_MICROS", d.oss_pool_micros),
133 oss_repo_micros: number("OSS_REPO_MICROS", d.oss_repo_micros),
134 trial_workspace_micros: number("TRIAL_WORKSPACE_MICROS", d.trial_workspace_micros),
135 trial_monthly_pool_micros: number("TRIAL_MONTHLY_POOL_MICROS", d.trial_monthly_pool_micros),
136 min_charge_micros: number("MIN_CHARGE_MICROS", d.min_charge_micros),
137 free_storage_bytes: number("FREE_PRIVATE_STORAGE_BYTES", d.free_storage_bytes),
138 public_package_free_bytes: number("PUBLIC_PACKAGES_FREE_BYTES", d.public_package_free_bytes),
139 private_package_free_bytes: number("PRIVATE_PACKAGES_FREE_BYTES", d.private_package_free_bytes),
140 free_audit_days: number("FREE_AUDIT_RETENTION_DAYS", d.free_audit_days.into()).max(1) as u32,
141 audit_days: number("AUDIT_RETENTION_DAYS", d.audit_days.into()).max(1) as u32,
142 audit_max_days: number("AUDIT_MAX_DAYS", d.audit_max_days.into()).max(1) as u32,
143 run_cap_micros: number("RUN_CAP_MICROS", d.run_cap_micros),
144 issue_cap_micros: number("ISSUE_CAP_MICROS", d.issue_cap_micros),
145 paid_start_micros: number("LIMIT_PAID_START_MICROS", d.paid_start_micros),
146 spike_factor: number("SPIKE_FACTOR", d.spike_factor).max(1),
147 spike_floor_micros: number("SPIKE_FLOOR_MICROS", d.spike_floor_micros),
148 forgive_cost_micros: number("OVERAGE_FORGIVE_COST_MICROS", d.forgive_cost_micros),
149 git_included: number("GIT_OPERATIONS_INCLUDED", d.git_included as i64) as u64,
150 }
151 }
152}
153
154/// What may pay for a charge besides the plan's included usage, which any
155/// usage may draw on.
156#[derive(Clone, Debug, Default)]
157pub(crate) struct Eligible {
158 /// The trial credit: everything but deployments.
159 pub trial: bool,
160 /// The open-source pool: this repository (`owner/name`), if it is
161 /// public. Only checks, workflows and the merge queue name one.
162 pub repo: Option<String>,
163 /// g1t covers what is left, rather than charging it, when the workspace
164 /// has no plan: a free workspace's compute.
165 pub cover_rest: bool,
166}
167
168/// What paid for a charge before the workspace did.
169#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
170pub(crate) struct Drawn {
171 pub credit: i64,
172 pub trial: i64,
173 pub oss: i64,
174 /// What g1t covered itself.
175 pub given: i64,
176}
177
178impl Drawn {
179 pub fn total(&self) -> i64 {
180 self.credit + self.trial + self.oss + self.given
181 }
182
183 /// For the statement: what paid for the entry, e.g. ` ($0.12 paid by
184 /// g1t's open-source pool)`. Empty when nothing did.
185 pub fn note(&self) -> String {
186 let parts: Vec<String> = [
187 (self.credit, "paid by your plan's included usage"),
188 (self.trial, "paid by your trial credit"),
189 (self.oss, "paid by g1t's open-source pool"),
190 (self.given, "covered by g1t"),
191 ]
192 .iter()
193 .filter(|(micros, _)| *micros > 0)
194 .map(|(micros, by)| format!("{} {by}", dollars(*micros)))
195 .collect();
196 if parts.is_empty() { String::new() } else { format!(" ({})", parts.join(", ")) }
197 }
198}
199
200/// How `gross` is paid for from sources with `available` left each, in
201/// order: each takes what it can of what is still unpaid. The rest is
202/// charged.
203pub(crate) fn split(gross: i64, available: &[i64]) -> Vec<i64> {
204 let mut left = gross.max(0);
205 available
206 .iter()
207 .map(|available| {
208 let take = left.min((*available).max(0));
209 left -= take;
210 take
211 })
212 .collect()
213}
214
215/// What a budget with `cap` and `used` so far has left.
216pub(crate) fn left(cap: i64, used: i64) -> i64 {
217 (cap - used).max(0)
218}
219
220/// `YYYY-MM` of an RFC 3339 time.
221pub(crate) fn month_of(timestamp: &str) -> String {
222 timestamp[..7].to_owned()
223}
224
225/// The first instant of the month after `month`: when this month's pools
226/// reset.
227pub(crate) fn next_month_start(month: &str) -> String {
228 let year: i32 = month[..4].parse().unwrap_or(1970);
229 let number: u32 = month[5..7].parse().unwrap_or(1);
230 if number == 12 {
231 format!("{}-01-01T00:00:00Z", year + 1)
232 } else {
233 format!("{year}-{:02}-01T00:00:00Z", number + 1)
234 }
235}
236
237/// The last second of `month`, for a charge that belongs to a month that
238/// is over.
239pub(crate) fn month_end(month: &str) -> String {
240 let year: i32 = month[..4].parse().unwrap_or(1970);
241 let number: u32 = month[5..7].parse().unwrap_or(1);
242 let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
243 let days = match number {
244 2 if leap => 29,
245 2 => 28,
246 4 | 6 | 9 | 11 => 30,
247 _ => 31,
248 };
249 format!("{month}-{days:02}T23:59:59Z")
250}
251
252/// What a trial grant would be: the account's own amount from sudo, or the
253/// default.
254pub(crate) fn grant_size(config: &Config, staff: Option<i64>) -> i64 {
255 staff.unwrap_or(config.trial_workspace_micros).max(0)
256}
257
258/// Whether this month's pool can still make a grant of `amount`.
259pub(crate) fn pool_has_room(pool: i64, granted_this_month: i64, amount: i64) -> bool {
260 amount > 0 && granted_this_month + amount <= pool
261}
262
263#[derive(Deserialize)]
264struct Used {
265 used: Option<i64>,
266}
267
268#[derive(Deserialize)]
269pub(crate) struct Grant {
270 pub granted_micros: i64,
271 pub used_micros: i64,
272}
273
274impl Billing {
275 /// The workspace's plan: comped terms are internal, an enterprise's
276 /// workspaces are invoiced, and otherwise the plan is paid for (or
277 /// given by staff without its price) or not. A Deployments subscription
278 /// from before the plan counts as the plan until its period ends.
279 /// Without a card processor every workspace has the plan: a g1t that
280 /// does not charge has nothing to gate.
281 pub(crate) async fn plan_kind(&self, workspace: &str) -> Result<PlanKind> {
282 let account = self.account_of(workspace).await?;
283 self.plan_kind_for(workspace, &account).await
284 }
285
286 /// The plan, from the account already read for the workspace.
287 pub(crate) async fn plan_kind_for(&self, workspace: &str, account: &BillingAccount) -> Result<PlanKind> {
288 if account.terms.kind == TermsKind::Comped {
289 return Ok(PlanKind::Internal);
290 }
291 if account.kind == g1t_contracts::billing::AccountKind::Enterprise {
292 return Ok(PlanKind::Enterprise);
293 }
294 if self.stripe.is_none() || account.allowances.plan {
295 return Ok(PlanKind::Paid);
296 }
297 // Both subscriptions are asked for at once; either one is the plan.
298 let (plan, deployments) = futures_util::future::try_join(
299 self.plan_on(workspace, Feature::Plan),
300 self.plan_on(workspace, Feature::Deployments),
301 )
302 .await?;
303 if plan || deployments {
304 return Ok(PlanKind::Paid);
305 }
306 Ok(PlanKind::Free)
307 }
308
309 /// Whether the workspace has the g1t plan now, whoever pays for it.
310 pub(crate) async fn has_plan(&self, workspace: &str) -> Result<bool> {
311 Ok(self.plan_kind(workspace).await? != PlanKind::Free)
312 }
313
314 /// What one monthly allowance has used.
315 pub(crate) async fn allowance_used(&self, kind: &str, scope: &str, month: &str) -> Result<i64> {
316 Ok(self
317 .db
318 .prepare("SELECT used FROM allowance_use WHERE kind = ? AND scope = ? AND month = ?")
319 .bind(&[kind.into(), scope.into(), month.into()])?
320 .first::<Used>(None)
321 .await?
322 .and_then(|u| u.used)
323 .unwrap_or(0))
324 }
325
326 /// Adds `amount` to a monthly count with no cap, such as the month's
327 /// build seconds, which the Billing page shows beside what they cost.
328 pub(crate) async fn tally(&self, kind: &str, scope: &str, month: &str, amount: i64) -> Result<()> {
329 if amount <= 0 {
330 return Ok(());
331 }
332 self.db
333 .prepare(
334 "INSERT INTO allowance_use (kind, scope, month, used) VALUES (?1, ?2, ?3, ?4)
335 ON CONFLICT (kind, scope, month) DO UPDATE SET used = used + ?4",
336 )
337 .bind(&[kind.into(), scope.into(), month.into(), (amount as f64).into()])?
338 .run()
339 .await?;
340 Ok(())
341 }
342
343 /// Takes up to `want` from a monthly allowance with `cap`, as one
344 /// transaction. Returns what it took.
345 pub(crate) async fn draw_allowance(&self, kind: &str, scope: &str, month: &str, want: i64, cap: i64) -> Result<i64> {
346 if want <= 0 || cap <= 0 {
347 return Ok(0);
348 }
349 let key = [kind.into(), scope.into(), month.into()];
350 let results = self
351 .db
352 .batch(vec![
353 self.db
354 .prepare("INSERT OR IGNORE INTO allowance_use (kind, scope, month, used) VALUES (?1, ?2, ?3, 0)")
355 .bind(&key)?,
356 self.db
357 .prepare("SELECT used FROM allowance_use WHERE kind = ?1 AND scope = ?2 AND month = ?3")
358 .bind(&key)?,
359 self.db
360 .prepare(
361 "UPDATE allowance_use SET used = MIN(?4, used + ?5)
362 WHERE kind = ?1 AND scope = ?2 AND month = ?3 AND used < ?4",
363 )
364 .bind(&[kind.into(), scope.into(), month.into(), (cap as f64).into(), (want as f64).into()])?,
365 self.db
366 .prepare("SELECT used FROM allowance_use WHERE kind = ?1 AND scope = ?2 AND month = ?3")
367 .bind(&key)?,
368 ])
369 .await?;
370 let read = |i: usize| -> Result<i64> {
371 Ok(results[i].results::<Used>()?.first().and_then(|u| u.used).unwrap_or(0))
372 };
373 Ok((read(3)? - read(1)?).max(0))
374 }
375
376 /// Gives back what was drawn and not used.
377 async fn return_allowance(&self, kind: &str, scope: &str, month: &str, amount: i64) -> Result<()> {
378 if amount > 0 {
379 self.db
380 .prepare("UPDATE allowance_use SET used = MAX(0, used - ?4) WHERE kind = ?1 AND scope = ?2 AND month = ?3")
381 .bind(&[kind.into(), scope.into(), month.into(), (amount as f64).into()])?
382 .run()
383 .await?;
384 }
385 Ok(())
386 }
387
388 // --- Trials -----------------------------------------------------------
389
390 pub(crate) async fn grant_of(&self, workspace: &str) -> Result<Option<Grant>> {
391 self.db
392 .prepare("SELECT granted_micros, used_micros FROM trial_grants WHERE workspace = ?")
393 .bind(&[workspace.into()])?
394 .first::<Grant>(None)
395 .await
396 }
397
398 /// Trial grants made this month, in all.
399 pub(crate) async fn trial_granted(&self, month: &str) -> Result<(i64, u32)> {
400 #[derive(Deserialize)]
401 struct Row {
402 micros: Option<i64>,
403 n: Option<u32>,
404 }
405 let row = self
406 .db
407 .prepare("SELECT SUM(granted_micros) AS micros, COUNT(*) AS n FROM trial_grants WHERE month = ?")
408 .bind(&[month.into()])?
409 .first::<Row>(None)
410 .await?;
411 Ok(row.map_or((0, 0), |r| (r.micros.unwrap_or(0), r.n.unwrap_or(0))))
412 }
413
414 /// The workspace's grant, made now out of this month's pool if it has
415 /// none and the pool has room. Called once its card is checked, never
416 /// before: the trial needs a card check. A grant g1t staff set comes
417 /// from no pool.
418 pub(crate) async fn ensure_grant(&self, workspace: &str) -> Result<Option<Grant>> {
419 if let Some(grant) = self.grant_of(workspace).await? {
420 return Ok(Some(grant));
421 }
422 if !self.trials_on {
423 return Ok(None);
424 }
425 let staff = self.account_of(workspace).await?.allowances.trial_micros;
426 let amount = grant_size(&self.plans, staff);
427 if amount <= 0 {
428 return Ok(None);
429 }
430 let now = rfc3339(now_ms());
431 let month = if staff.is_some() { "staff".to_owned() } else { month_of(&now) };
432 // One statement: the pool is checked and the grant made together.
433 self.db
434 .prepare(
435 "INSERT INTO trial_grants (workspace, month, granted_micros, used_micros, created_at)
436 SELECT ?1, ?2, ?3, 0, ?4
437 WHERE ?2 = 'staff'
438 OR (SELECT COALESCE(SUM(granted_micros), 0) FROM trial_grants WHERE month = ?2) + ?3 <= ?5
439 ON CONFLICT (workspace) DO NOTHING",
440 )
441 .bind(&[
442 workspace.into(),
443 month.as_str().into(),
444 (amount as f64).into(),
445 now.as_str().into(),
446 (self.plans.trial_monthly_pool_micros as f64).into(),
447 ])?
448 .run()
449 .await?;
450 self.grant_of(workspace).await
451 }
452
453 /// Takes up to `want` from the workspace's trial credit, if it has a
454 /// grant.
455 async fn draw_trial(&self, workspace: &str, want: i64) -> Result<i64> {
456 if want <= 0 || self.grant_of(workspace).await?.is_none() {
457 return Ok(0);
458 }
459 #[derive(Deserialize)]
460 struct Row {
461 used_micros: i64,
462 }
463 let results = self
464 .db
465 .batch(vec![
466 self.db.prepare("SELECT used_micros FROM trial_grants WHERE workspace = ?1").bind(&[workspace.into()])?,
467 self.db
468 .prepare(
469 "UPDATE trial_grants SET used_micros = MIN(granted_micros, used_micros + ?2)
470 WHERE workspace = ?1 AND used_micros < granted_micros",
471 )
472 .bind(&[workspace.into(), (want as f64).into()])?,
473 self.db.prepare("SELECT used_micros FROM trial_grants WHERE workspace = ?1").bind(&[workspace.into()])?,
474 ])
475 .await?;
476 let read = |i: usize| -> Result<i64> { Ok(results[i].results::<Row>()?.first().map_or(0, |r| r.used_micros)) };
477 Ok((read(2)? - read(0)?).max(0))
478 }
479
480 /// `trial`: where the workspace's trial credit stands. Not granted yet,
481 /// it waits for a card check (`verify`), or for next month's pool
482 /// (`pool`).
483 pub(crate) async fn trial(&self, a: TrialArgs) -> Result<Trial> {
484 let workspace = a.workspace.to_lowercase();
485 let closed = |reason: &str| Trial {
486 open: false,
487 used_micros: 0,
488 limit_micros: 0,
489 ends_at: None,
490 reason: Some(reason.to_owned()),
491 granted: false,
492 waits_until: None,
493 };
494 if let Some(grant) = self.grant_of(&workspace).await? {
495 let open = grant.used_micros < grant.granted_micros;
496 return Ok(Trial {
497 open,
498 used_micros: grant.used_micros,
499 limit_micros: grant.granted_micros,
500 ends_at: None,
501 reason: (!open).then(|| "used".to_owned()),
502 granted: true,
503 waits_until: None,
504 });
505 }
506 if !self.trials_on {
507 return Ok(closed("off"));
508 }
509 let staff = self.account_of(&workspace).await?.allowances.trial_micros;
510 let amount = grant_size(&self.plans, staff);
511 if amount <= 0 {
512 return Ok(closed("off"));
513 }
514 let month = month_of(&rfc3339(now_ms()));
515 let (granted, _) = self.trial_granted(&month).await?;
516 let room = staff.is_some() || pool_has_room(self.plans.trial_monthly_pool_micros, granted, amount);
517 Ok(Trial {
518 open: false,
519 used_micros: 0,
520 limit_micros: amount,
521 ends_at: None,
522 reason: Some(if room { "verify" } else { "pool" }.to_owned()),
523 granted: false,
524 waits_until: (!room).then(|| next_month_start(&month)),
525 })
526 }
527
528 // --- The open-source pool ---------------------------------------------
529
530 /// Whether `repo` (`owner/name`) is public, asked of the repos service.
531 /// Unknown counts as private: the pool pays only for what is known to
532 /// be open.
533 pub(crate) async fn is_public(&self, repo: &str) -> bool {
534 let Some(repos) = &self.repos else { return false };
535 let found: Result<Vec<g1t_contracts::repos::RepoVisibility>> = g1t_kit::call(
536 repos,
537 "visibility",
538 &g1t_contracts::repos::VisibilityArgs { paths: vec![repo.to_owned()] },
539 )
540 .await;
541 match found {
542 Ok(list) => list.iter().any(|v| v.path.eq_ignore_ascii_case(repo) && !v.is_private),
543 Err(error) => {
544 worker::console_error!("could not ask whether {repo} is public: {error}");
545 false
546 }
547 }
548 }
549
550 /// A public repository's monthly cap on the pool: its account's own
551 /// from sudo, or `OSS_REPO_MICROS`.
552 pub(crate) async fn oss_repo_cap(&self, workspace: &str) -> Result<i64> {
553 Ok(self.account_of(workspace).await?.allowances.oss_repo_micros.unwrap_or(self.plans.oss_repo_micros))
554 }
555
556 /// What the open-source pool has left this month for `repo`: the
557 /// pool's and the repository's share, whichever is less.
558 pub(crate) async fn oss_left(&self, workspace: &str, repo: &str, month: &str) -> Result<i64> {
559 let pool = left(self.plans.oss_pool_micros, self.allowance_used("oss_pool", "", month).await?);
560 let share = left(self.oss_repo_cap(workspace).await?, self.allowance_used("oss_repo", &repo.to_lowercase(), month).await?);
561 Ok(pool.min(share))
562 }
563
564 /// Takes up to `want` from the open-source pool for `repo`, within the
565 /// pool's cap and the repository's.
566 async fn draw_oss(&self, workspace: &str, repo: &str, month: &str, want: i64) -> Result<i64> {
567 let repo = repo.to_lowercase();
568 let cap = self.oss_repo_cap(workspace).await?;
569 let room = left(cap, self.allowance_used("oss_repo", &repo, month).await?);
570 let from_pool = self.draw_allowance("oss_pool", "", month, want.min(room), self.plans.oss_pool_micros).await?;
571 let for_repo = self.draw_allowance("oss_repo", &repo, month, from_pool, cap).await?;
572 // The repository's cap filled up meanwhile: give the pool back the rest.
573 self.return_allowance("oss_pool", "", month, from_pool - for_repo).await?;
574 Ok(for_repo)
575 }
576
577 // --- Drawing down -----------------------------------------------------
578
579 /// Pays for a `gross` charge from the plan's included usage, the trial
580 /// credit and the open-source pool, in that order, for usage in
581 /// `month`; then, for a free workspace's compute, g1t covers the rest.
582 /// Returns what each paid; the rest is the workspace's to pay.
583 pub(crate) async fn draw(&self, workspace: &str, gross: i64, month: &str, eligible: &Eligible) -> Result<Drawn> {
584 if gross <= 0 {
585 return Ok(Drawn::default());
586 }
587 let plan = self.has_plan(workspace).await?;
588 let credit_left = if plan {
589 left(self.plans.plan_included_micros, self.allowance_used("plan_credit", workspace, month).await?)
590 } else {
591 0
592 };
593 let trial_left = if eligible.trial {
594 self.grant_of(workspace).await?.map_or(0, |grant| left(grant.granted_micros, grant.used_micros))
595 } else {
596 0
597 };
598 // Asked only when the rest has not paid for it all.
599 let public_repo = match &eligible.repo {
600 Some(repo) if gross > credit_left + trial_left && self.is_public(repo).await => Some(repo.clone()),
601 _ => None,
602 };
603 let oss_left = match &public_repo {
604 Some(repo) => self.oss_left(workspace, repo, month).await?,
605 None => 0,
606 };
607 let planned = split(gross, &[credit_left, trial_left, oss_left]);
608 let mut drawn = Drawn {
609 credit: self.draw_allowance("plan_credit", workspace, month, planned[0], self.plans.plan_included_micros).await?,
610 trial: self.draw_trial(workspace, planned[1]).await?,
611 ..Drawn::default()
612 };
613 if let Some(repo) = &public_repo {
614 drawn.oss = self.draw_oss(workspace, repo, month, planned[2]).await?;
615 }
616 if eligible.cover_rest && !plan {
617 drawn.given = (gross - drawn.credit - drawn.trial - drawn.oss).max(0);
618 }
619 Ok(drawn)
620 }
621
622 /// Writes down on a usage entry what paid for it.
623 pub(crate) async fn record_drawn(&self, reference: &str, drawn: &Drawn) -> Result<()> {
624 if drawn.total() == 0 {
625 return Ok(());
626 }
627 self.db
628 .prepare("UPDATE ledger SET credit_micros = ?, trial_micros = ?, oss_micros = ?, given_micros = ? WHERE reference = ?")
629 .bind(&[
630 (drawn.credit as f64).into(),
631 (drawn.trial as f64).into(),
632 (drawn.oss as f64).into(),
633 (drawn.given as f64).into(),
634 reference.into(),
635 ])?
636 .run()
637 .await?;
638 Ok(())
639 }
640
641 /// g1t's pools this month, for sudo.
642 pub(crate) async fn pools(&self) -> Result<Pools> {
643 let month = month_of(&rfc3339(now_ms()));
644 let (granted, grants) = self.trial_granted(&month).await?;
645 Ok(Pools {
646 oss_used_micros: self.allowance_used("oss_pool", "", &month).await?,
647 oss_pool_micros: self.plans.oss_pool_micros,
648 oss_repo_micros: self.plans.oss_repo_micros,
649 trial_granted_micros: granted,
650 trial_pool_micros: self.plans.trial_monthly_pool_micros,
651 trial_grants: grants,
652 month,
653 })
654 }
655}
656
657/// What may pay for compute: the trial (never for deployments), the
658/// open-source pool for checks, workflows and the merge queue on `repo`,
659/// and g1t for a free workspace's overrun. Work whose kind is not known is
660/// taken as an agent's: never the pool.
661pub(crate) fn eligible_for(kind: Option<ComputeKind>, repo: Option<&str>) -> Eligible {
662 let kind = kind.unwrap_or(ComputeKind::Agent);
663 Eligible {
664 trial: kind != ComputeKind::Deploy,
665 repo: repo.filter(|_| kind.open_source_pool()).map(str::to_owned),
666 cover_rest: kind != ComputeKind::Deploy,
667 }
668}
669
670/// A charge in millionths of a dollar for `micros` of cost plus `margin`.
671pub(crate) fn with_margin(cost_micros: i64, margin_percent: u32) -> i64 {
672 crate::margin_on(cost_micros, margin_percent)
673}
674
675#[cfg(test)]
676mod tests {
677 use super::*;
678
679 #[test]
680 fn included_usage_pays_first_then_the_trial_then_the_pool_then_the_workspace() {
681 // $0.50 of usage; $0.20 included, $1 of trial, $1 of pool.
682 assert_eq!(split(500_000, &[200_000, 1_000_000, 1_000_000]), [200_000, 300_000, 0]);
683 // No plan: the trial pays all of it.
684 assert_eq!(split(500_000, &[0, 1_000_000, 1_000_000]), [0, 500_000, 0]);
685 // Trial spent: the pool pays, where it applies.
686 assert_eq!(split(500_000, &[0, 0, 1_000_000]), [0, 0, 500_000]);
687 // Everything spent: the workspace pays all of it.
688 let planned = split(500_000, &[0, 0, 0]);
689 assert_eq!(planned, [0, 0, 0]);
690 assert_eq!(500_000 - planned.iter().sum::<i64>(), 500_000);
691 // Each pays what it can, and the rest is charged.
692 let planned = split(500_000, &[100_000, 150_000, 50_000]);
693 assert_eq!(planned, [100_000, 150_000, 50_000]);
694 assert_eq!(500_000 - planned.iter().sum::<i64>(), 200_000);
695 // Nothing is drawn for nothing, nor from a negative balance.
696 assert_eq!(split(0, &[1, 1, 1]), [0, 0, 0]);
697 assert_eq!(split(100, &[-5, 50, 100]), [0, 50, 50]);
698 }
699
700 #[test]
701 fn a_budget_never_gives_more_than_its_cap() {
702 assert_eq!(left(1_000_000, 400_000), 600_000);
703 assert_eq!(left(1_000_000, 1_000_000), 0);
704 assert_eq!(left(1_000_000, 1_200_000), 0);
705 // The open-source pool: the repository's share and the pool's both bound it.
706 let pool = left(25_000_000, 24_900_000);
707 let repo = left(2_000_000, 300_000);
708 assert_eq!(split(800_000, &[pool.min(repo)]), [100_000]);
709 // A repository past its $2 share gets nothing, however full the pool.
710 assert_eq!(split(800_000, &[left(25_000_000, 0).min(left(2_000_000, 2_000_000))]), [0]);
711 }
712
713 #[test]
714 fn the_open_source_pool_pays_only_for_checks_workflows_and_the_queue() {
715 assert_eq!(eligible_for(Some(ComputeKind::Check), Some("acme/web")).repo.as_deref(), Some("acme/web"));
716 assert_eq!(eligible_for(Some(ComputeKind::Queue), Some("acme/web")).repo.as_deref(), Some("acme/web"));
717 assert_eq!(eligible_for(Some(ComputeKind::Workflow), Some("acme/web")).repo.as_deref(), Some("acme/web"));
718 // An agent on a public repository pays as any agent does.
719 assert!(eligible_for(Some(ComputeKind::Agent), Some("acme/web")).repo.is_none());
720 // Unknown work is never the pool's.
721 assert!(eligible_for(None, Some("acme/web")).repo.is_none());
722 // Deployments are never the trial's, and never covered.
723 let deploy = eligible_for(Some(ComputeKind::Deploy), Some("acme/web"));
724 assert!(!deploy.trial && !deploy.cover_rest && deploy.repo.is_none());
725 assert!(eligible_for(Some(ComputeKind::Agent), None).trial);
726 }
727
728 #[test]
729 fn pools_reset_each_calendar_month() {
730 assert_eq!(month_of("2026-10-31T23:59:59Z"), "2026-10");
731 assert_eq!(month_of("2026-11-01T00:00:00Z"), "2026-11");
732 assert_eq!(next_month_start("2026-10"), "2026-11-01T00:00:00Z");
733 assert_eq!(next_month_start("2026-12"), "2027-01-01T00:00:00Z");
734 // $100 a month in $5 grants: twenty trials, then the next month.
735 assert!(pool_has_room(100_000_000, 95_000_000, 5_000_000));
736 assert!(!pool_has_room(100_000_000, 100_000_000, 5_000_000));
737 assert!(!pool_has_room(100_000_000, 97_500_000, 5_000_000));
738 assert!(pool_has_room(100_000_000, 0, 5_000_000));
739 assert!(!pool_has_room(100_000_000, 0, 0));
740 }
741
742 #[test]
743 fn a_trial_grant_is_the_default_unless_staff_set_one() {
744 let config = Config::default();
745 assert_eq!(grant_size(&config, None), 5_000_000);
746 assert_eq!(grant_size(&config, Some(20_000_000)), 20_000_000);
747 assert_eq!(grant_size(&config, Some(-1)), 0);
748 }
749
750 #[test]
751 fn a_month_ends_on_its_last_day() {
752 assert_eq!(month_end("2026-10"), "2026-10-31T23:59:59Z");
753 assert_eq!(month_end("2026-09"), "2026-09-30T23:59:59Z");
754 assert_eq!(month_end("2028-02"), "2028-02-29T23:59:59Z");
755 assert_eq!(month_end("2027-02"), "2027-02-28T23:59:59Z");
756 }
757
758 #[test]
759 fn what_paid_is_said_on_the_statement() {
760 assert_eq!(Drawn::default().note(), "");
761 let drawn = Drawn { oss: 120_000, ..Drawn::default() };
762 assert_eq!(drawn.note(), " ($0.12 paid by g1t's open-source pool)");
763 let drawn = Drawn { credit: 50_000, trial: 20_000, ..Drawn::default() };
764 assert_eq!(drawn.note(), " ($0.05 paid by your plan's included usage, $0.02 paid by your trial credit)");
765 assert_eq!(drawn.total(), 70_000);
766 let drawn = Drawn { trial: 300_000, given: 40_000, ..Drawn::default() };
767 assert_eq!(drawn.note(), " ($0.30 paid by your trial credit, $0.04 covered by g1t)");
768 assert_eq!(drawn.total(), 340_000);
769 }
770
771 #[test]
772 fn the_defaults_are_the_published_ones() {
773 let c = Config::default();
774 assert_eq!(c.plan_monthly_cents, 2_000);
775 assert_eq!(c.plan_included_micros, 10_000_000);
776 assert_eq!(c.oss_pool_micros, 25_000_000);
777 assert_eq!(c.oss_repo_micros, 2_000_000);
778 assert_eq!(c.trial_workspace_micros, 5_000_000);
779 assert_eq!(c.trial_monthly_pool_micros, 100_000_000);
780 assert_eq!(c.min_charge_micros, 5_000_000);
781 assert_eq!(c.free_storage_bytes, 1_000_000_000);
782 assert_eq!(c.free_audit_days, 7);
783 assert_eq!(c.audit_days, 90);
784 assert_eq!(c.audit_max_days, 400);
785 assert_eq!(c.run_cap_micros, g1t_contracts::guardrails::DEFAULT_RUN_CAP_MICROS);
786 assert_eq!(c.issue_cap_micros, 10_000_000);
787 assert_eq!(c.paid_start_micros, 100_000_000);
788 assert_eq!(c.forgive_cost_micros, 50_000_000);
789 assert_eq!(c.git_included, 50_000);
790 }
791}