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.

860 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/// Draw from each source using what the preceding source actually gave,
194/// not a balance read before concurrent charges consumed it. On failure,
195/// return the partial allocation so the caller can return it.
196async fn draw_in_order<F, Fut>(gross: i64, mut take: F) -> std::result::Result<Drawn, (worker::Error, Drawn)>
197where
198 F: FnMut(usize, i64) -> Fut,
199 Fut: std::future::Future<Output = Result<i64>>,
200{
201 let mut drawn = Drawn::default();
202 for source in 0..3 {
203 let remaining = (gross - drawn.total()).max(0);
204 if remaining == 0 {
205 break;
206 }
207 let amount = match take(source, remaining).await {
208 Ok(amount) => amount,
209 Err(error) => return Err((error, drawn)),
210 };
211 match source {
212 0 => drawn.credit = amount,
213 1 => drawn.trial = amount,
214 _ => drawn.oss = amount,
215 }
216 }
217 Ok(drawn)
218}
219
220/// What a budget with `cap` and `used` so far has left.
221pub(crate) fn left(cap: i64, used: i64) -> i64 {
222 (cap - used).max(0)
223}
224
225/// `YYYY-MM` of an RFC 3339 time.
226pub(crate) fn month_of(timestamp: &str) -> String {
227 timestamp[..7].to_owned()
228}
229
230/// The first instant of the month after `month`: when this month's pools
231/// reset.
232pub(crate) fn next_month_start(month: &str) -> String {
233 let year: i32 = month[..4].parse().unwrap_or(1970);
234 let number: u32 = month[5..7].parse().unwrap_or(1);
235 if number == 12 {
236 format!("{}-01-01T00:00:00Z", year + 1)
237 } else {
238 format!("{year}-{:02}-01T00:00:00Z", number + 1)
239 }
240}
241
242/// The last second of `month`, for a charge that belongs to a month that
243/// is over.
244pub(crate) fn month_end(month: &str) -> String {
245 format!("{month}-{:02}T23:59:59Z", days_in(month))
246}
247
248/// How many days `month` (`YYYY-MM`) has.
249pub(crate) fn days_in(month: &str) -> u32 {
250 let year: i32 = month.get(..4).and_then(|y| y.parse().ok()).unwrap_or(1970);
251 let number: u32 = month.get(5..7).and_then(|m| m.parse().ok()).unwrap_or(1);
252 let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
253 match number {
254 2 if leap => 29,
255 2 => 28,
256 4 | 6 | 9 | 11 => 30,
257 _ => 31,
258 }
259}
260
261/// What a trial grant would be: the account's own amount from sudo, or the
262/// default.
263pub(crate) fn grant_size(config: &Config, staff: Option<i64>) -> i64 {
264 staff.unwrap_or(config.trial_workspace_micros).max(0)
265}
266
267/// Whether this month's pool can still make a grant of `amount`.
268pub(crate) fn pool_has_room(pool: i64, granted_this_month: i64, amount: i64) -> bool {
269 amount > 0 && granted_this_month + amount <= pool
270}
271
272#[derive(Deserialize)]
273struct Used {
274 used: Option<i64>,
275}
276
277#[derive(Deserialize)]
278pub(crate) struct Grant {
279 pub granted_micros: i64,
280 pub used_micros: i64,
281}
282
283impl Billing {
284 /// The workspace's plan: comped terms are internal, an enterprise's
285 /// workspaces are invoiced, and otherwise the plan is paid for (or
286 /// given by staff without its price) or not. A Deployments subscription
287 /// from before the plan counts as the plan until its period ends.
288 /// Without a card processor every workspace has the plan: a g1t that
289 /// does not charge has nothing to gate.
290 pub(crate) async fn plan_kind(&self, workspace: &str) -> Result<PlanKind> {
291 let account = self.account_of(workspace).await?;
292 self.plan_kind_for(workspace, &account).await
293 }
294
295 /// The plan, from the account already read for the workspace.
296 pub(crate) async fn plan_kind_for(&self, workspace: &str, account: &BillingAccount) -> Result<PlanKind> {
297 if account.terms.full_discount() {
298 return Ok(PlanKind::Internal);
299 }
300 if account.kind == g1t_contracts::billing::AccountKind::Enterprise {
301 return Ok(PlanKind::Enterprise);
302 }
303 if !self.charging || account.allowances.plan {
304 return Ok(PlanKind::Paid);
305 }
306 // Both subscriptions are asked for at once; either one is the plan.
307 let (plan, deployments) = futures_util::future::try_join(
308 self.plan_on(workspace, Feature::Plan),
309 self.plan_on(workspace, Feature::Deployments),
310 )
311 .await?;
312 if plan || deployments {
313 return Ok(PlanKind::Paid);
314 }
315 Ok(PlanKind::Free)
316 }
317
318 /// Whether the workspace has the g1t plan now, whoever pays for it.
319 pub(crate) async fn has_plan(&self, workspace: &str) -> Result<bool> {
320 Ok(self.plan_kind(workspace).await? != PlanKind::Free)
321 }
322
323 /// `free_workspaces`: those of the workspaces on no paid plan. With no
324 /// card processor nothing is free (`plan_kind_for` says paid), so a
325 /// g1t without payments limits no one.
326 pub(crate) async fn free_workspaces(&self, a: g1t_contracts::billing::FreeWorkspacesArgs) -> Result<Vec<String>> {
327 let mut free = vec![];
328 // A person belongs to a bounded number of workspaces; this caps the
329 // reads all the same.
330 for workspace in a.workspaces.iter().take(100) {
331 let workspace = workspace.trim().to_lowercase();
332 if workspace.is_empty() || free.contains(&workspace) {
333 continue;
334 }
335 if self.plan_kind(&workspace).await? == PlanKind::Free {
336 free.push(workspace);
337 }
338 }
339 Ok(free)
340 }
341
342 /// What one monthly allowance has used.
343 pub(crate) async fn allowance_used(&self, kind: &str, scope: &str, month: &str) -> Result<i64> {
344 Ok(self
345 .db
346 .prepare("SELECT used FROM allowance_use WHERE kind = ? AND scope = ? AND month = ?")
347 .bind(&[kind.into(), scope.into(), month.into()])?
348 .first::<Used>(None)
349 .await?
350 .and_then(|u| u.used)
351 .unwrap_or(0))
352 }
353
354 /// Adds `amount` to a monthly count with no cap, such as the month's
355 /// build seconds, which the Billing page shows beside what they cost.
356 pub(crate) async fn tally(&self, kind: &str, scope: &str, month: &str, amount: i64) -> Result<()> {
357 if amount <= 0 {
358 return Ok(());
359 }
360 self.db
361 .prepare(
362 "INSERT INTO allowance_use (kind, scope, month, used) VALUES (?1, ?2, ?3, ?4)
363 ON CONFLICT (kind, scope, month) DO UPDATE SET used = used + ?4",
364 )
365 .bind(&[kind.into(), scope.into(), month.into(), (amount as f64).into()])?
366 .run()
367 .await?;
368 Ok(())
369 }
370
371 /// Takes up to `want` from a monthly allowance with `cap`, as one
372 /// transaction. Returns what it took.
373 pub(crate) async fn draw_allowance(&self, kind: &str, scope: &str, month: &str, want: i64, cap: i64) -> Result<i64> {
374 if want <= 0 || cap <= 0 {
375 return Ok(0);
376 }
377 let key = [kind.into(), scope.into(), month.into()];
378 let results = self
379 .db
380 .batch(vec![
381 self.db
382 .prepare("INSERT OR IGNORE INTO allowance_use (kind, scope, month, used) VALUES (?1, ?2, ?3, 0)")
383 .bind(&key)?,
384 self.db
385 .prepare("SELECT used FROM allowance_use WHERE kind = ?1 AND scope = ?2 AND month = ?3")
386 .bind(&key)?,
387 self.db
388 .prepare(
389 "UPDATE allowance_use SET used = MIN(?4, used + ?5)
390 WHERE kind = ?1 AND scope = ?2 AND month = ?3 AND used < ?4",
391 )
392 .bind(&[kind.into(), scope.into(), month.into(), (cap as f64).into(), (want as f64).into()])?,
393 self.db
394 .prepare("SELECT used FROM allowance_use WHERE kind = ?1 AND scope = ?2 AND month = ?3")
395 .bind(&key)?,
396 ])
397 .await?;
398 let read = |i: usize| -> Result<i64> {
399 Ok(results[i].results::<Used>()?.first().and_then(|u| u.used).unwrap_or(0))
400 };
401 Ok((read(3)? - read(1)?).max(0))
402 }
403
404 /// Gives back what was drawn and not used.
405 async fn return_allowance(&self, kind: &str, scope: &str, month: &str, amount: i64) -> Result<()> {
406 if amount > 0 {
407 self.db
408 .prepare("UPDATE allowance_use SET used = MAX(0, used - ?4) WHERE kind = ?1 AND scope = ?2 AND month = ?3")
409 .bind(&[kind.into(), scope.into(), month.into(), (amount as f64).into()])?
410 .run()
411 .await?;
412 }
413 Ok(())
414 }
415
416 // --- Trials -----------------------------------------------------------
417
418 pub(crate) async fn grant_of(&self, workspace: &str) -> Result<Option<Grant>> {
419 self.db
420 .prepare("SELECT granted_micros, used_micros FROM trial_grants WHERE workspace = ?")
421 .bind(&[workspace.into()])?
422 .first::<Grant>(None)
423 .await
424 }
425
426 /// Trial grants made this month, in all.
427 pub(crate) async fn trial_granted(&self, month: &str) -> Result<(i64, u32)> {
428 #[derive(Deserialize)]
429 struct Row {
430 micros: Option<i64>,
431 n: Option<u32>,
432 }
433 let row = self
434 .db
435 .prepare("SELECT SUM(granted_micros) AS micros, COUNT(*) AS n FROM trial_grants WHERE month = ?")
436 .bind(&[month.into()])?
437 .first::<Row>(None)
438 .await?;
439 Ok(row.map_or((0, 0), |r| (r.micros.unwrap_or(0), r.n.unwrap_or(0))))
440 }
441
442 /// The workspace's grant, made now out of this month's pool if it has
443 /// none and the pool has room. Called once its card is checked, never
444 /// before: the trial needs a card check. A grant g1t staff set comes
445 /// from no pool.
446 pub(crate) async fn ensure_grant(&self, workspace: &str) -> Result<Option<Grant>> {
447 if let Some(grant) = self.grant_of(workspace).await? {
448 return Ok(Some(grant));
449 }
450 if !self.trials_on {
451 return Ok(None);
452 }
453 let staff = self.account_of(workspace).await?.allowances.trial_micros;
454 let amount = grant_size(&self.plans, staff);
455 if amount <= 0 {
456 return Ok(None);
457 }
458 let now = rfc3339(now_ms());
459 let month = if staff.is_some() { "staff".to_owned() } else { month_of(&now) };
460 // One statement: the pool is checked and the grant made together.
461 self.db
462 .prepare(
463 "INSERT INTO trial_grants (workspace, month, granted_micros, used_micros, created_at)
464 SELECT ?1, ?2, ?3, 0, ?4
465 WHERE ?2 = 'staff'
466 OR (SELECT COALESCE(SUM(granted_micros), 0) FROM trial_grants WHERE month = ?2) + ?3 <= ?5
467 ON CONFLICT (workspace) DO NOTHING",
468 )
469 .bind(&[
470 workspace.into(),
471 month.as_str().into(),
472 (amount as f64).into(),
473 now.as_str().into(),
474 (self.plans.trial_monthly_pool_micros as f64).into(),
475 ])?
476 .run()
477 .await?;
478 self.grant_of(workspace).await
479 }
480
481 /// Takes up to `want` from the workspace's trial credit, if it has a
482 /// grant.
483 async fn draw_trial(&self, workspace: &str, want: i64) -> Result<i64> {
484 if want <= 0 || self.grant_of(workspace).await?.is_none() {
485 return Ok(0);
486 }
487 #[derive(Deserialize)]
488 struct Row {
489 used_micros: i64,
490 }
491 let results = self
492 .db
493 .batch(vec![
494 self.db.prepare("SELECT used_micros FROM trial_grants WHERE workspace = ?1").bind(&[workspace.into()])?,
495 self.db
496 .prepare(
497 "UPDATE trial_grants SET used_micros = MIN(granted_micros, used_micros + ?2)
498 WHERE workspace = ?1 AND used_micros < granted_micros",
499 )
500 .bind(&[workspace.into(), (want as f64).into()])?,
501 self.db.prepare("SELECT used_micros FROM trial_grants WHERE workspace = ?1").bind(&[workspace.into()])?,
502 ])
503 .await?;
504 let read = |i: usize| -> Result<i64> { Ok(results[i].results::<Row>()?.first().map_or(0, |r| r.used_micros)) };
505 Ok((read(2)? - read(0)?).max(0))
506 }
507
508 /// `trial`: where the workspace's trial credit stands. Not granted yet,
509 /// it waits for a card check (`verify`), or for next month's pool
510 /// (`pool`).
511 pub(crate) async fn trial(&self, a: TrialArgs) -> Result<Trial> {
512 let workspace = a.workspace.to_lowercase();
513 let closed = |reason: &str| Trial {
514 open: false,
515 used_micros: 0,
516 limit_micros: 0,
517 ends_at: None,
518 reason: Some(reason.to_owned()),
519 granted: false,
520 waits_until: None,
521 };
522 if let Some(grant) = self.grant_of(&workspace).await? {
523 let open = grant.used_micros < grant.granted_micros;
524 return Ok(Trial {
525 open,
526 used_micros: grant.used_micros,
527 limit_micros: grant.granted_micros,
528 ends_at: None,
529 reason: (!open).then(|| "used".to_owned()),
530 granted: true,
531 waits_until: None,
532 });
533 }
534 if !self.trials_on {
535 return Ok(closed("off"));
536 }
537 let staff = self.account_of(&workspace).await?.allowances.trial_micros;
538 let amount = grant_size(&self.plans, staff);
539 if amount <= 0 {
540 return Ok(closed("off"));
541 }
542 let month = month_of(&rfc3339(now_ms()));
543 let (granted, _) = self.trial_granted(&month).await?;
544 let room = staff.is_some() || pool_has_room(self.plans.trial_monthly_pool_micros, granted, amount);
545 Ok(Trial {
546 open: false,
547 used_micros: 0,
548 limit_micros: amount,
549 ends_at: None,
550 reason: Some(if room { "verify" } else { "pool" }.to_owned()),
551 granted: false,
552 waits_until: (!room).then(|| next_month_start(&month)),
553 })
554 }
555
556 // --- The open-source pool ---------------------------------------------
557
558 /// Whether `repo` (`owner/name`) is public, asked of the repos service.
559 /// Unknown counts as private: the pool pays only for what is known to
560 /// be open.
561 pub(crate) async fn is_public(&self, repo: &str) -> bool {
562 let Some(repos) = &self.repos else { return false };
563 let found: Result<Vec<g1t_contracts::repos::RepoVisibility>> = g1t_kit::call(
564 repos,
565 "visibility",
566 &g1t_contracts::repos::VisibilityArgs { paths: vec![repo.to_owned()] },
567 )
568 .await;
569 match found {
570 Ok(list) => list.iter().any(|v| v.path.eq_ignore_ascii_case(repo) && !v.is_private),
571 Err(error) => {
572 worker::console_error!("could not ask whether {repo} is public: {error}");
573 false
574 }
575 }
576 }
577
578 /// A public repository's monthly cap on the pool: its account's own
579 /// from sudo, or `OSS_REPO_MICROS`.
580 pub(crate) async fn oss_repo_cap(&self, workspace: &str) -> Result<i64> {
581 Ok(self.account_of(workspace).await?.allowances.oss_repo_micros.unwrap_or(self.plans.oss_repo_micros))
582 }
583
584 /// What the open-source pool has left this month for `repo`: the
585 /// pool's and the repository's share, whichever is less.
586 pub(crate) async fn oss_left(&self, workspace: &str, repo: &str, month: &str) -> Result<i64> {
587 let pool = left(self.plans.oss_pool_micros, self.allowance_used("oss_pool", "", month).await?);
588 let share = left(self.oss_repo_cap(workspace).await?, self.allowance_used("oss_repo", &repo.to_lowercase(), month).await?);
589 Ok(pool.min(share))
590 }
591
592 /// Takes up to `want` from the open-source pool for `repo`, within the
593 /// pool's cap and the repository's.
594 async fn draw_oss(&self, workspace: &str, repo: &str, month: &str, want: i64) -> Result<i64> {
595 let repo = repo.to_lowercase();
596 let cap = self.oss_repo_cap(workspace).await?;
597 let room = left(cap, self.allowance_used("oss_repo", &repo, month).await?);
598 let from_pool = self.draw_allowance("oss_pool", "", month, want.min(room), self.plans.oss_pool_micros).await?;
599 // The repository's share failing to draw gives the pool back what it
600 // gave: the caller only knows to return what this hands back.
601 let for_repo = match self.draw_allowance("oss_repo", &repo, month, from_pool, cap).await {
602 Ok(for_repo) => for_repo,
603 Err(error) => {
604 if let Err(undo) = self.return_allowance("oss_pool", "", month, from_pool).await {
605 worker::console_error!("{workspace}: {from_pool} drawn from the open-source pool for {repo} was not given back: {undo}");
606 }
607 return Err(error);
608 }
609 };
610 // The repository's cap filled up meanwhile: give the pool back the rest.
611 self.return_allowance("oss_pool", "", month, from_pool - for_repo).await?;
612 Ok(for_repo)
613 }
614
615 // --- Drawing down -----------------------------------------------------
616
617 /// Pays for a `gross` charge from the plan's included usage, the trial
618 /// credit and the open-source pool, in that order, for usage in
619 /// `month`; then, for a free workspace's compute, g1t covers the rest.
620 /// Returns what each paid; the rest is the workspace's to pay.
621 pub(crate) async fn draw(&self, workspace: &str, gross: i64, month: &str, eligible: &Eligible) -> Result<Drawn> {
622 if gross <= 0 {
623 return Ok(Drawn::default());
624 }
625 let plan = self.has_plan(workspace).await?;
626 self.draw_as(workspace, gross, month, eligible, plan).await
627 }
628
629 /// `draw`, for a workspace that had the plan (`plan`) or not in
630 /// `month`: a month that is over is paid for as it was then.
631 pub(crate) async fn draw_as(&self, workspace: &str, gross: i64, month: &str, eligible: &Eligible, plan: bool) -> Result<Drawn> {
632 if gross <= 0 {
633 return Ok(Drawn::default());
634 }
635 let allocation = draw_in_order(gross, |source, want| async move {
636 match source {
637 0 if plan => self.draw_allowance("plan_credit", workspace, month, want, self.plans.plan_included_micros).await,
638 1 if eligible.trial => self.draw_trial(workspace, want).await,
639 2 => match &eligible.repo {
640 Some(repo) if self.is_public(repo).await => self.draw_oss(workspace, repo, month, want).await,
641 _ => Ok(0),
642 },
643 _ => Ok(0),
644 }
645 }).await;
646 let mut drawn = match allocation {
647 Ok(drawn) => drawn,
648 Err((error, partial)) => {
649 self.undraw(workspace, month, &partial, eligible.repo.as_deref()).await?;
650 return Err(error);
651 }
652 };
653 if eligible.cover_rest && !plan {
654 drawn.given = (gross - drawn.credit - drawn.trial - drawn.oss).max(0);
655 }
656 Ok(drawn)
657 }
658
659 /// Gives back what `draw` took for an entry that was not written: a
660 /// duplicate delivery of usage already on the ledger, or a write that
661 /// failed. `repo` is the eligible repository the open-source pool paid
662 /// for, if any. What g1t covered was never taken from anything.
663 pub(crate) async fn undraw(&self, workspace: &str, month: &str, drawn: &Drawn, repo: Option<&str>) -> Result<()> {
664 self.return_allowance("plan_credit", workspace, month, drawn.credit).await?;
665 if drawn.trial > 0 {
666 self.db
667 .prepare("UPDATE trial_grants SET used_micros = MAX(0, used_micros - ?2) WHERE workspace = ?1")
668 .bind(&[workspace.into(), (drawn.trial as f64).into()])?
669 .run()
670 .await?;
671 }
672 if let (true, Some(repo)) = (drawn.oss > 0, repo) {
673 self.return_allowance("oss_pool", "", month, drawn.oss).await?;
674 self.return_allowance("oss_repo", &repo.to_lowercase(), month, drawn.oss).await?;
675 }
676 Ok(())
677 }
678
679 /// g1t's pools this month, for sudo.
680 pub(crate) async fn pools(&self) -> Result<Pools> {
681 let month = month_of(&rfc3339(now_ms()));
682 let (granted, grants) = self.trial_granted(&month).await?;
683 Ok(Pools {
684 oss_used_micros: self.allowance_used("oss_pool", "", &month).await?,
685 oss_pool_micros: self.plans.oss_pool_micros,
686 oss_repo_micros: self.plans.oss_repo_micros,
687 trial_granted_micros: granted,
688 trial_pool_micros: self.plans.trial_monthly_pool_micros,
689 trial_grants: grants,
690 month,
691 })
692 }
693}
694
695/// What may pay for compute: the trial (never for deployments), the
696/// open-source pool for checks, workflows and the merge queue on `repo`,
697/// and g1t for a free workspace's overrun. Work whose kind is not known is
698/// taken as an agent's: never the pool.
699pub(crate) fn eligible_for(kind: Option<ComputeKind>, repo: Option<&str>) -> Eligible {
700 let kind = kind.unwrap_or(ComputeKind::Agent);
701 Eligible {
702 trial: kind != ComputeKind::Deploy,
703 repo: repo.filter(|_| kind.open_source_pool()).map(str::to_owned),
704 cover_rest: kind != ComputeKind::Deploy,
705 }
706}
707
708/// A charge in millionths of a dollar for `micros` of cost plus `margin`.
709pub(crate) fn with_margin(cost_micros: i64, margin_percent: u32) -> i64 {
710 crate::margin_on(cost_micros, margin_percent)
711}
712
713#[cfg(test)]
714mod tests {
715 use super::*;
716 use futures_util::FutureExt;
717
718 fn split(gross: i64, available: &[i64]) -> Vec<i64> {
719 let drawn = draw_in_order(gross, |source, want| {
720 std::future::ready(Ok(want.min(available.get(source).copied().unwrap_or(0).max(0))))
721 }).now_or_never().unwrap().unwrap();
722 [drawn.credit, drawn.trial, drawn.oss][..available.len()].to_vec()
723 }
724
725 #[test]
726 fn concurrent_consumption_of_included_usage_falls_through_to_trial() {
727 let mut requested = Vec::new();
728 let drawn = draw_in_order(500_000, |source, want| {
729 requested.push((source, want));
730 // Another charge has already taken the included balance that
731 // an earlier read would have said could pay for all of this.
732 std::future::ready(Ok(if source == 0 { 0 } else { want }))
733 }).now_or_never().unwrap().unwrap();
734 assert_eq!(requested, [(0, 500_000), (1, 500_000)]);
735 assert_eq!(drawn.credit, 0);
736 assert_eq!(drawn.trial, 500_000);
737 assert_eq!(drawn.total(), 500_000);
738 }
739
740 #[test]
741 fn a_failed_source_returns_the_actual_prior_draw_for_compensation() {
742 let failed = draw_in_order(500_000, |source, _| {
743 std::future::ready(if source == 0 { Ok(200_000) } else { Err(worker::Error::RustError("unavailable".into())) })
744 }).now_or_never().unwrap().unwrap_err();
745 assert_eq!(failed.1.credit, 200_000);
746 assert_eq!(failed.1.trial, 0);
747 assert_eq!(failed.1.total(), 200_000);
748 }
749
750 #[test]
751 fn included_usage_pays_first_then_the_trial_then_the_pool_then_the_workspace() {
752 // $0.50 of usage; $0.20 included, $1 of trial, $1 of pool.
753 assert_eq!(split(500_000, &[200_000, 1_000_000, 1_000_000]), [200_000, 300_000, 0]);
754 // No plan: the trial pays all of it.
755 assert_eq!(split(500_000, &[0, 1_000_000, 1_000_000]), [0, 500_000, 0]);
756 // Trial spent: the pool pays, where it applies.
757 assert_eq!(split(500_000, &[0, 0, 1_000_000]), [0, 0, 500_000]);
758 // Everything spent: the workspace pays all of it.
759 let planned = split(500_000, &[0, 0, 0]);
760 assert_eq!(planned, [0, 0, 0]);
761 assert_eq!(500_000 - planned.iter().sum::<i64>(), 500_000);
762 // Each pays what it can, and the rest is charged.
763 let planned = split(500_000, &[100_000, 150_000, 50_000]);
764 assert_eq!(planned, [100_000, 150_000, 50_000]);
765 assert_eq!(500_000 - planned.iter().sum::<i64>(), 200_000);
766 // Nothing is drawn for nothing, nor from a negative balance.
767 assert_eq!(split(0, &[1, 1, 1]), [0, 0, 0]);
768 assert_eq!(split(100, &[-5, 50, 100]), [0, 50, 50]);
769 }
770
771 #[test]
772 fn a_budget_never_gives_more_than_its_cap() {
773 assert_eq!(left(1_000_000, 400_000), 600_000);
774 assert_eq!(left(1_000_000, 1_000_000), 0);
775 assert_eq!(left(1_000_000, 1_200_000), 0);
776 // The open-source pool: the repository's share and the pool's both bound it.
777 let pool = left(25_000_000, 24_900_000);
778 let repo = left(2_000_000, 300_000);
779 assert_eq!(split(800_000, &[pool.min(repo)]), [100_000]);
780 // A repository past its $2 share gets nothing, however full the pool.
781 assert_eq!(split(800_000, &[left(25_000_000, 0).min(left(2_000_000, 2_000_000))]), [0]);
782 }
783
784 #[test]
785 fn the_open_source_pool_pays_only_for_checks_workflows_and_the_queue() {
786 assert_eq!(eligible_for(Some(ComputeKind::Check), Some("acme/web")).repo.as_deref(), Some("acme/web"));
787 assert_eq!(eligible_for(Some(ComputeKind::Queue), Some("acme/web")).repo.as_deref(), Some("acme/web"));
788 assert_eq!(eligible_for(Some(ComputeKind::Workflow), Some("acme/web")).repo.as_deref(), Some("acme/web"));
789 // An agent on a public repository pays as any agent does.
790 assert!(eligible_for(Some(ComputeKind::Agent), Some("acme/web")).repo.is_none());
791 // Unknown work is never the pool's.
792 assert!(eligible_for(None, Some("acme/web")).repo.is_none());
793 // Deployments are never the trial's, and never covered.
794 let deploy = eligible_for(Some(ComputeKind::Deploy), Some("acme/web"));
795 assert!(!deploy.trial && !deploy.cover_rest && deploy.repo.is_none());
796 assert!(eligible_for(Some(ComputeKind::Agent), None).trial);
797 }
798
799 #[test]
800 fn pools_reset_each_calendar_month() {
801 assert_eq!(month_of("2026-10-31T23:59:59Z"), "2026-10");
802 assert_eq!(month_of("2026-11-01T00:00:00Z"), "2026-11");
803 assert_eq!(next_month_start("2026-10"), "2026-11-01T00:00:00Z");
804 assert_eq!(next_month_start("2026-12"), "2027-01-01T00:00:00Z");
805 // $100 a month in $5 grants: twenty trials, then the next month.
806 assert!(pool_has_room(100_000_000, 95_000_000, 5_000_000));
807 assert!(!pool_has_room(100_000_000, 100_000_000, 5_000_000));
808 assert!(!pool_has_room(100_000_000, 97_500_000, 5_000_000));
809 assert!(pool_has_room(100_000_000, 0, 5_000_000));
810 assert!(!pool_has_room(100_000_000, 0, 0));
811 }
812
813 #[test]
814 fn a_trial_grant_is_the_default_unless_staff_set_one() {
815 let config = Config::default();
816 assert_eq!(grant_size(&config, None), 5_000_000);
817 assert_eq!(grant_size(&config, Some(20_000_000)), 20_000_000);
818 assert_eq!(grant_size(&config, Some(-1)), 0);
819 }
820
821 #[test]
822 fn a_month_ends_on_its_last_day() {
823 assert_eq!(month_end("2026-10"), "2026-10-31T23:59:59Z");
824 assert_eq!(month_end("2026-09"), "2026-09-30T23:59:59Z");
825 assert_eq!(month_end("2028-02"), "2028-02-29T23:59:59Z");
826 assert_eq!(month_end("2027-02"), "2027-02-28T23:59:59Z");
827 }
828
829 #[test]
830 fn what_paid_is_said_on_the_statement() {
831 assert_eq!(Drawn::default().note(), "");
832 let drawn = Drawn { oss: 120_000, ..Drawn::default() };
833 assert_eq!(drawn.note(), " ($0.12 paid by g1t's open-source pool)");
834 let drawn = Drawn { credit: 50_000, trial: 20_000, ..Drawn::default() };
835 assert_eq!(drawn.note(), " ($0.05 paid by your plan's included usage, $0.02 paid by your trial credit)");
836 assert_eq!(drawn.total(), 70_000);
837 let drawn = Drawn { trial: 300_000, given: 40_000, ..Drawn::default() };
838 assert_eq!(drawn.note(), " ($0.30 paid by your trial credit, $0.04 covered by g1t)");
839 assert_eq!(drawn.total(), 340_000);
840 }
841
842 #[test]
843 fn the_defaults_are_the_published_ones() {
844 let c = Config::default();
845 assert_eq!(c.plan_monthly_cents, 2_100);
846 assert_eq!(c.plan_included_micros, 10_000_000);
847 assert_eq!(c.oss_pool_micros, 25_000_000);
848 assert_eq!(c.oss_repo_micros, 2_000_000);
849 assert_eq!(c.trial_workspace_micros, 5_000_000);
850 assert_eq!(c.trial_monthly_pool_micros, 100_000_000);
851 assert_eq!(c.min_charge_micros, 5_000_000);
852 assert_eq!(c.free_storage_bytes, 1_000_000_000);
853 assert_eq!(c.free_audit_days, 7);
854 assert_eq!(c.audit_days, 90);
855 assert_eq!(c.audit_max_days, 400);
856 assert_eq!(c.paid_start_micros, 100_000_000);
857 assert_eq!(c.forgive_cost_micros, 50_000_000);
858 assert_eq!(c.git_included, 50_000);
859 }
860}