Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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