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