g1t/services/billing/src/credits.rs

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