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