g1t/services/billing/src/lib.rs

1,273 lines55,362 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1//! The billing service: what g1t's compute costs, charged to the workspace
2//! it ran for at what g1t pays plus 20%.
Agents as a team: lifecycle, merge queue, billing and a new shell3//!
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look4//! One paid plan, "g1t" (see `features`): $20 a month per workspace, never
5//! per person, with $10 of usage included, deployments, and more private
6//! storage. The forge is free for everyone; compute needs the plan or a
7//! card check (see `compute` and `cards`). Before anything that costs money
8//! starts, the service that starts it reserves its estimate here; when it
9//! is done, what it cost goes on the ledger plus the margin, drawn first
10//! from what the plan includes, a trial or g1t's pools (see `credits`).
11//! Every change is a ledger entry, and a balance is always the sum of its
12//! ledger.
Paid features: a workspace turns on Deployments with a monthly plan13//!
Agents as a team: lifecycle, merge queue, billing and a new shell14//! Without a card processor configured the service says so and charges
15//! nothing, so that g1t still runs where billing has not been set up.
16//!
17//! Reached only through service bindings; see `g1t_contracts::billing` for
18//! the methods and their arguments.
19
Billing accounts, terms and enterprises; g1t is no longer free20mod accounts;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays21mod budget;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look22mod cards;
23mod closing;
24mod compute;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily25mod costs;
26mod margin;
27mod pricing;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put28mod credits;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look29mod overages;
30mod requests;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put31mod storage;
Two limits, real invoices, trust that grows by itself, sales signals32mod invoices;
33mod sales;
The statement is a month at a time, a line per kind of charge34mod statement;
Stripe webhooks, enterprise invoices, and sudo for both35mod webhooks;
Paid features: a workspace turns on Deployments with a monthly plan36mod features;
Prices keep themselves current with what g1t pays37mod keeper;
Usage limits: unpaid usage can only go so far38mod limits;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains39mod rename;
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo40mod retention;
Agents as a team: lifecycle, merge queue, billing and a new shell41mod stripe;
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept42mod stripe_sync;
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix43mod tokens;
Agents as a team: lifecycle, merge queue, billing and a new shell44
45use g1t_contracts::billing::*;
46use g1t_contracts::time::rfc3339;
47use g1t_contracts::{FailureCode, Outcome, Role, new_id};
Billing accounts, terms and enterprises; g1t is no longer free48use g1t_contracts::billing::TermsKind;
Agents as a team: lifecycle, merge queue, billing and a new shell49use g1t_kit::{args, now_ms, reply, rpc_method};
50use serde::Deserialize;
51use sha2::{Digest, Sha256};
52use worker::wasm_bindgen::JsValue;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains53use worker::{Context, D1Database, Env, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index54use futures_util::future::{try_join, try_join5};
Agents as a team: lifecycle, merge queue, billing and a new shell55
56use stripe::Stripe;
57
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look58/// Prepaying: $25 at the least; by card up to $10,000 at a time, and by
59/// bank transfer from $1,000 to $100,000.
60const MIN_TOP_UP_CENTS: u32 = 2_500;
61const MAX_TOP_UP_CENTS: u32 = 1_000_000;
62const MIN_BANK_TRANSFER_CENTS: u32 = 100_000;
63const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000;
Agents as a team: lifecycle, merge queue, billing and a new shell64const LEDGER_PAGE: u32 = 100;
65/// A run's reported cost is believed up to this much. A sandbox cannot
66/// spend more in the time it has, so anything above is a fault.
67const MAX_RUN_COST_USD: f64 = 100.0;
68
69/// What a run is charged: its cost plus the margin, rounded up to a whole
70/// millionth of a dollar.
71pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
72 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
73 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
74}
75
76fn hash(token: &str) -> String {
77 hex::encode(Sha256::digest(token.as_bytes()))
78}
79
80fn optional(value: Option<&str>) -> JsValue {
81 value.map_or(JsValue::NULL, JsValue::from)
82}
83
84#[derive(Deserialize)]
85struct AccountRow {
86 balance_micros: i64,
87 customer_id: Option<String>,
88}
89
90#[derive(Deserialize)]
91struct LedgerRow {
92 id: String,
93 kind: EntryKind,
94 amount_micros: i64,
95 description: String,
96 repo: Option<String>,
97 number: Option<u32>,
98 task: Option<String>,
99 model: Option<String>,
100 created_by: Option<String>,
101 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read102 billed_to: Option<String>,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace103 #[serde(default)]
104 workspace: Option<String>,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put105 #[serde(default)]
106 credit_micros: Option<i64>,
107 #[serde(default)]
108 trial_micros: Option<i64>,
109 #[serde(default)]
110 oss_micros: Option<i64>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look111 #[serde(default)]
112 given_micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell113}
114
115impl From<LedgerRow> for LedgerEntry {
116 fn from(row: LedgerRow) -> Self {
117 LedgerEntry {
118 id: row.id,
119 kind: row.kind,
120 amount_micros: row.amount_micros,
121 description: row.description,
122 repo: row.repo,
123 number: row.number,
124 task: row.task,
125 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read126 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell127 created_by: row.created_by,
128 created_at: row.created_at,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace129 workspace: row.workspace,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put130 credit_micros: row.credit_micros.unwrap_or(0),
131 trial_micros: row.trial_micros.unwrap_or(0),
132 oss_micros: row.oss_micros.unwrap_or(0),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look133 given_micros: row.given_micros.unwrap_or(0),
Agents as a team: lifecycle, merge queue, billing and a new shell134 }
135 }
136}
137
138#[derive(Deserialize)]
139struct RunRow {
140 workspace: String,
141 repo: String,
142 number: u32,
143 task: String,
144 model: String,
145 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read146 billed_to: Option<String>,
147}
148
149impl RunRow {
150 fn own_provider(&self) -> bool {
151 self.billed_to.as_deref() == Some("workspace")
152 }
Agents as a team: lifecycle, merge queue, billing and a new shell153}
154
155#[derive(Deserialize)]
156struct CheckoutRow {
157 workspace: String,
158 created_by: String,
159}
160
161/// A row an `UPDATE … RETURNING` touched.
162#[derive(Deserialize)]
163struct Touched {
164 #[allow(dead_code)]
165 id: String,
166}
167
168struct Billing {
169 db: D1Database,
170 /// Absent when no card processor is configured.
171 stripe: Option<Stripe>,
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard172 /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`);
173 /// without it no event is believed.
174 webhook_secret: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell175 margin_percent: u32,
Free while g1t is being built out; agents can check out their own forks176 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
177 free: bool,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put178 /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS`
179 /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero).
180 trials_on: bool,
181 /// The plans' and pools' numbers; see `credits`.
182 plans: credits::Config,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look183 /// The repos service: which repositories are public, what private ones
184 /// hold, and their git operations. Absent where it is not bound.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put185 repos: Option<worker::Fetcher>,
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member186 /// The packages service: what each workspace's packages hold.
187 packages: Option<worker::Fetcher>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look188 /// The identity service, which emails owners. Absent where it is not
189 /// bound.
190 identity: Option<worker::Fetcher>,
Usage limits: unpaid usage can only go so far191 /// How far unpaid usage may go; see `limits`.
192 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free193 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
194 prepaid_only: bool,
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays195 /// The caps on what g1t pays for itself; see `budget`.
196 caps: budget::Caps,
197 /// The worker's bindings, for emailing staff (`EMAIL`).
198 env: Env,
A free allowance on g1t's models, so anyone can try its agents199}
200
Agents as a team: lifecycle, merge queue, billing and a new shell201impl Billing {
202 fn status(&self) -> Status {
203 Status {
204 enabled: self.stripe.is_some(),
205 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks206 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell207 }
208 }
209
210 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
211 self.db
212 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
213 .bind(&[workspace.into()])?
214 .first::<AccountRow>(None)
215 .await
216 }
217
218 async fn standing(&self, workspace: &str) -> Result<Account> {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept219 // The card as last synced (stripe_sync.rs), not asked of Stripe.
220 let (row, card) = try_join(self.row(workspace), self.saved_card(workspace)).await?;
Agents as a team: lifecycle, merge queue, billing and a new shell221 Ok(Account {
222 workspace: workspace.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace223 balance_micros: row.map_or(0, |row| row.balance_micros),
Agents as a team: lifecycle, merge queue, billing and a new shell224 status: self.status(),
225 margin_percent: self.margin_percent,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace226 card,
Agents as a team: lifecycle, merge queue, billing and a new shell227 })
228 }
229
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace230 /// The workspace's customer at Stripe, made the first time one is needed.
231 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
232 let Some(stripe) = &self.stripe else {
233 return Err(worker::Error::RustError("payments are not set up".into()));
234 };
235 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
236 return Ok(customer);
237 }
238 let customer = stripe.create_customer(workspace).await?;
239 self.db
240 .prepare(
241 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
242 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
243 )
244 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
245 .run()
246 .await?;
247 Ok(customer)
248 }
249
250 /// Stripe's hosted billing page for the workspace. Owners only.
251 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
252 let workspace = a.workspace.to_lowercase();
253 if a.actor.role_in(&workspace) != Some(Role::Owner) {
254 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing."));
255 }
256 let Some(stripe) = &self.stripe else {
257 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
258 };
259 let customer = match self.customer_for(&workspace).await {
260 Ok(customer) => customer,
261 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
262 };
263 match stripe.portal_session(&customer, &a.return_url).await {
264 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
265 Err(error) if stripe::is_missing(&error) => {
266 // The customer was removed at Stripe: a new one next time.
267 self.forget_customer(&workspace).await?;
268 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
269 }
270 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe's billing page could not be opened: {error}"))),
271 }
272 }
273
Agents as a team: lifecycle, merge queue, billing and a new shell274 /// Adds a ledger entry and moves the balance by the same amount, as
275 /// one write.
276 #[allow(clippy::too_many_arguments)]
277 async fn enter(
278 &self,
279 workspace: &str,
280 kind: EntryKind,
281 amount_micros: i64,
282 description: &str,
283 reference: &str,
284 run: Option<&RunRow>,
285 cost_micros: Option<i64>,
286 created_by: Option<&str>,
287 customer: Option<&str>,
288 ) -> Result<()> {
289 let now = now_ms();
290 let timestamp = rfc3339(now);
291 let kind = match kind {
292 EntryKind::TopUp => "top_up",
293 EntryKind::Usage => "usage",
294 };
295 self.db
296 .batch(vec![
297 self.db
298 .prepare(
299 "INSERT INTO ledger
300 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read301 model, cost_micros, reference, created_by, created_at, billed_to)
302 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell303 )
304 .bind(&[
305 new_id("led", now).into(),
306 workspace.into(),
307 kind.into(),
308 // D1 takes numbers as doubles, which hold every
309 // amount this service will see exactly.
310 (amount_micros as f64).into(),
311 description.into(),
312 optional(run.map(|run| run.repo.as_str())),
313 run.map_or(JsValue::NULL, |run| run.number.into()),
314 optional(run.map(|run| run.task.as_str())),
315 optional(run.map(|run| run.model.as_str())),
316 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
317 reference.into(),
318 optional(created_by),
319 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read320 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell321 ])?,
322 self.db
323 .prepare(
324 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
325 VALUES (?1, ?2, ?3, ?4)
326 ON CONFLICT (workspace) DO UPDATE SET
327 balance_micros = balance_micros + ?2,
328 customer_id = COALESCE(?3, customer_id)",
329 )
330 .bind(&[
331 workspace.into(),
332 (amount_micros as f64).into(),
333 optional(customer),
334 timestamp.as_str().into(),
335 ])?,
336 ])
337 .await?;
Billing accounts, terms and enterprises; g1t is no longer free338 // Money in clears a card declined at the limit.
339 if kind == "top_up" {
340 self.db
341 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
342 .bind(&[workspace.into()])?
343 .run()
344 .await?;
345 }
Agents as a team: lifecycle, merge queue, billing and a new shell346 Ok(())
347 }
348
349 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
350 let workspace = a.workspace.to_lowercase();
351 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
352 return Ok(members_only());
353 }
354 Ok(Outcome::Ok(self.standing(&workspace).await?))
355 }
356
357 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
358 let workspace = a.workspace.to_lowercase();
359 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
360 return Ok(members_only());
361 }
362 let rows = self
363 .db
364 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
365 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
366 .all()
367 .await?
368 .results::<LedgerRow>()?;
369 Ok(Outcome::Ok(
370 rows.into_iter().map(LedgerEntry::from).collect(),
371 ))
372 }
373
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request374 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
375 let workspace = a.workspace.to_lowercase();
376 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
377 return Ok(members_only());
378 }
379 #[derive(serde::Deserialize)]
380 struct SliceRow {
381 key: Option<String>,
382 micros: Option<i64>,
383 runs: Option<u32>,
384 }
A comped workspace's usage chart and breakdowns show what runs used at cost, as the free tier's do385 // While nothing is charged (g1t is free, or the workspace is
386 // comped), what was used is what there is to show.
387 #[derive(serde::Deserialize)]
388 struct Comped {
389 n: i64,
390 }
391 let comped = self
392 .db
393 .prepare("SELECT COUNT(*) AS n FROM billing_accounts WHERE kind = 'workspace' AND terms_kind = 'comped' AND substr(id, 4) = ?1")
394 .bind(&[workspace.as_str().into()])?
395 .first::<Comped>(None)
396 .await?
397 .is_some_and(|row| row.n > 0);
398 let measure = if self.free || comped { "COALESCE(cost_micros, 0)" } else { "-amount_micros" };
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request399 let slices = |key: &str, limit: u32| {
400 format!(
Usage while free is shown at cost; agents get rustfmt and clippy401 "SELECT {key} AS key, SUM({measure}) AS micros, COUNT(*) AS runs FROM ledger
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request402 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
403 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
404 )
405 };
406 let query = |sql: String| {
407 let db = &self.db;
408 let workspace = workspace.clone();
409 let since = a.since.clone();
410 async move {
411 let rows = db
412 .prepare(sql)
413 .bind(&[workspace.into(), since.into()])?
414 .all()
415 .await?
416 .results::<SliceRow>()?;
417 Ok::<Vec<UsageSlice>, worker::Error>(
418 rows.into_iter()
419 .map(|row| UsageSlice {
420 key: row.key.unwrap_or_else(|| "other".to_owned()),
421 micros: row.micros.unwrap_or_default(),
422 runs: row.runs.unwrap_or_default(),
423 })
424 .collect(),
425 )
426 }
427 };
428 #[derive(serde::Deserialize)]
429 struct Totals {
430 spent: Option<i64>,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged431 g1t_cost: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request432 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read433 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request434 runs: Option<u32>,
435 added: Option<i64>,
436 }
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index437 let totals = async {
438 self.db
439 .prepare(
440 "SELECT
441 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged442 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS g1t_cost,
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index443 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
444 SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider,
445 SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs,
446 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added
447 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
448 )
449 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
450 .first::<Totals>(None)
451 .await
452 };
453 // The totals and the five slices read the same rows independently,
454 // so they go to D1 at once: one round trip of waiting, not six.
455 let (totals, (by_day, by_task, by_repo, by_pull, by_model)) = try_join(
456 totals,
457 try_join5(
458 query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)),
459 query(slices("task", 20)),
460 query(slices("repo", 20)),
461 query(slices("repo || '#' || number", 10)),
462 query(slices("model", 10)),
463 ),
464 )
465 .await?;
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request466 let totals = totals.unwrap_or(Totals {
467 spent: None,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged468 g1t_cost: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request469 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read470 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request471 runs: None,
472 added: None,
473 });
474 Ok(Outcome::Ok(Usage {
475 spent_micros: totals.spent.unwrap_or_default(),
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged476 // At price, what g1t's usage came to, less what was charged: the
477 // part the included usage, the trial, a pool, or a free period paid.
478 covered_micros: (crate::credits::with_margin(totals.g1t_cost.unwrap_or_default(), self.margin_percent)
479 - totals.spent.unwrap_or_default())
480 .max(0),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request481 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read482 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy483 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
484 free: self.free,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request485 runs: totals.runs.unwrap_or_default(),
486 added_micros: totals.added.unwrap_or_default(),
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index487 by_day,
488 by_task,
489 by_repo,
490 by_pull,
491 by_model,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request492 since: a.since,
493 }))
494 }
495
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look496 /// `checkout`: prepays usage, by card or (from $1,000) bank transfer.
Agents as a team: lifecycle, merge queue, billing and a new shell497 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
498 let workspace = a.workspace.to_lowercase();
499 if a.actor.role_in(&workspace) != Some(Role::Owner) {
500 return Ok(Outcome::fail(
501 FailureCode::Forbidden,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look502 "Only an owner can prepay for a workspace.",
Agents as a team: lifecycle, merge queue, billing and a new shell503 ));
504 }
505 let Some(stripe) = &self.stripe else {
506 return Ok(Outcome::fail(
507 FailureCode::Conflict,
508 "Payments are not set up on this g1t yet.",
509 ));
510 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look511 let bank_transfer = a.method.as_deref() == Some("bank_transfer");
512 if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) {
513 return Ok(Outcome::fail(FailureCode::Invalid, why));
Agents as a team: lifecycle, merge queue, billing and a new shell514 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look515 // A bank transfer needs a customer for its account details.
516 let customer = if bank_transfer {
517 match self.customer_for(&workspace).await {
518 Ok(customer) => Some(customer),
519 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
520 }
521 } else {
522 self.row(&workspace).await?.and_then(|row| row.customer_id)
523 };
Project dependencies: addresses, preview stacks, Affects, and agents who know524 let session = match stripe
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look525 .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url, bank_transfer)
Project dependencies: addresses, preview stacks, Affects, and agents who know526 .await
527 {
528 Ok(session) => session,
529 // A customer saved under another Stripe account: start afresh.
530 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
531 self.forget_customer(&workspace).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look532 let customer = if bank_transfer { Some(self.customer_for(&workspace).await?) } else { None };
533 stripe.start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url, bank_transfer).await?
Project dependencies: addresses, preview stacks, Affects, and agents who know534 }
535 Err(error) => return Err(error),
536 };
Agents as a team: lifecycle, merge queue, billing and a new shell537 let Some(url) = session.url else {
538 return Err(worker::Error::RustError(
539 "the card processor returned no payment page".into(),
540 ));
541 };
542 self.db
543 .prepare(
544 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at)
545 VALUES (?, ?, ?, ?, ?)",
546 )
547 .bind(&[
548 session.id.into(),
549 workspace.into(),
550 a.amount_cents.into(),
551 a.actor.username.into(),
552 rfc3339(now_ms()).into(),
553 ])?
554 .run()
555 .await?;
556 Ok(Outcome::Ok(Checkout { url }))
557 }
558
559 /// Credits a payment if the processor says it was made and it has not
560 /// been credited before. The amount credited is what the processor
561 /// says was paid, not what anyone here remembers asking for.
562 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
563 let workspace = a.workspace.to_lowercase();
564 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
565 return Ok(members_only());
566 }
567 let (Some(stripe), Some(checkout)) = (
568 &self.stripe,
569 self.db
570 .prepare(
571 "SELECT workspace, created_by FROM checkouts
572 WHERE id = ? AND workspace = ? AND status = 'open'",
573 )
574 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
575 .first::<CheckoutRow>(None)
576 .await?,
577 ) else {
578 // Unknown, someone else's, or already credited: nothing to do.
579 return Ok(Outcome::Ok(self.standing(&workspace).await?));
580 };
581 let session = stripe.session(&a.session).await?;
582 let paid = session
583 .amount_total
584 .filter(|_| session.payment_status == "paid");
585 if let Some(cents) = paid {
586 // Only whoever flips it from open to paid enters the credit.
587 let claimed = self
588 .db
589 .prepare(
590 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
591 RETURNING id",
592 )
593 .bind(&[a.session.as_str().into()])?
594 .first::<Touched>(None)
595 .await?;
596 if claimed.is_some() {
597 self.enter(
598 &checkout.workspace,
599 EntryKind::TopUp,
600 i64::from(cents) * MICROS_PER_DOLLAR / 100,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look601 "Paid in advance",
Agents as a team: lifecycle, merge queue, billing and a new shell602 &session.id,
603 None,
604 None,
605 Some(&checkout.created_by),
606 session.customer.as_deref(),
607 )
608 .await?;
609 }
610 }
611 Ok(Outcome::Ok(self.standing(&workspace).await?))
612 }
613
Project dependencies: addresses, preview stacks, Affects, and agents who know614 /// Drops a saved customer the card processor no longer knows.
615 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
616 self.db
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept617 .prepare(
618 "UPDATE accounts SET customer_id = NULL, card_brand = NULL, card_last4 = NULL, card_exp_month = NULL,
619 card_exp_year = NULL, card_synced_at = NULL WHERE workspace = ?",
620 )
Project dependencies: addresses, preview stacks, Affects, and agents who know621 .bind(&[workspace.into()])?
622 .run()
623 .await?;
624 Ok(())
625 }
626
Agents as a team: lifecycle, merge queue, billing and a new shell627 /// A refusal if the workspace has no credit to start an agent with.
628 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free629 // Billing is postpaid: usage limits decide whether work starts
630 // (see `limits`), and credit is a prepayment that lowers what is
631 // owed. A balance no longer has to be positive to start.
632 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks633 return Ok(None);
634 }
Agents as a team: lifecycle, merge queue, billing and a new shell635 let balance = self
636 .row(workspace)
637 .await?
638 .map_or(0, |row| row.balance_micros);
639 Ok((balance <= 0).then(|| {
640 Outcome::fail(
641 FailureCode::PaymentRequired,
642 format!(
643 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
644 ),
645 )
646 }))
Billing accounts, terms and enterprises; g1t is no longer free647 }
648
Agents as a team: lifecycle, merge queue, billing and a new shell649 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
650 if self.stripe.is_none() {
651 return Ok(Outcome::Ok(true));
652 }
Usage limits: unpaid usage can only go so far653 if let Some(stopped) = self.stopped(&a.workspace).await? {
654 return Ok(stopped);
655 }
Agents as a team: lifecycle, merge queue, billing and a new shell656 Ok(self
657 .out_of_credit(&a.workspace.to_lowercase())
658 .await?
659 .unwrap_or(Outcome::Ok(true)))
660 }
661
662 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
663 if self.stripe.is_none() {
664 return Ok(Outcome::Ok(None));
665 }
666 let workspace = a.workspace.to_lowercase();
Usage limits: unpaid usage can only go so far667 if let Some(stopped) = self.stopped(&workspace).await? {
668 return Ok(stopped);
669 }
Agents as a team: lifecycle, merge queue, billing and a new shell670 if let Some(refused) = self.out_of_credit(&workspace).await? {
671 return Ok(refused);
672 }
673 let now = now_ms();
674 let run_id = new_id("run", now);
675 let mut bytes = [0u8; 32];
676 getrandom::getrandom(&mut bytes).expect("no source of randomness");
677 let token = hex::encode(bytes);
678 self.db
679 .prepare(
Auto model routing: the cheapest tier that can do each piece of work, a retry goes up a tier, and each run records its tier680 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier)
681 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell682 )
683 .bind(&[
684 run_id.as_str().into(),
685 workspace.into(),
686 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
687 a.number.into(),
688 a.task.into(),
689 a.model.into(),
690 hash(&token).into(),
691 rfc3339(now).into(),
Integrations: your own model provider, alerts that open issues, tickets agents read692 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Prices keep themselves current with what g1t pays693 optional(a.session.as_deref().filter(|_| a.billed_to != "workspace")),
Auto model routing: the cheapest tier that can do each piece of work, a retry goes up a tier, and each run records its tier694 optional(
695 a.tier
696 .as_deref()
697 .filter(|tier| a.billed_to != "workspace" && matches!(*tier, "small" | "large")),
698 ),
Agents as a team: lifecycle, merge queue, billing and a new shell699 ])?
700 .run()
701 .await?;
702 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
703 }
704
705 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
706 let run = self
707 .db
708 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read709 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell710 WHERE id = ? AND finished_at IS NULL",
711 )
712 .bind(&[a.run_id.as_str().into()])?
713 .first::<RunRow>(None)
714 .await?;
715 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
716 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
717 };
718 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
719 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
720 }
721 // Only whoever closes the run charges for it.
722 let claimed = self
723 .db
724 .prepare(
725 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
726 )
727 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
728 .first::<Touched>(None)
729 .await?;
730 if claimed.is_none() {
731 return Ok(Outcome::Ok(false));
732 }
Prices are what g1t pays plus 20%, from the first second733 // On the workspace's own provider, the model was paid for there,
734 // and the run's sandbox time is recorded on its own: nothing more
735 // to charge.
736 if run.own_provider() {
737 return Ok(Outcome::Ok(true));
738 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look739 // Its cost plus the margin, on the account's terms; then the plan's
740 // included usage and the trial credit pay what they can, and g1t
741 // covers a free workspace's overrun (see `credits`). Agents are
742 // never the open-source pool's.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put743 let base = charge_micros(a.cost_usd, self.margin_percent);
Billing accounts, terms and enterprises; g1t is no longer free744 let (charge, terms_note) = self.charged(&run.workspace, base).await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put745 let month = credits::month_of(&rfc3339(now_ms()));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look746 let eligible = credits::eligible_for(Some(ComputeKind::Agent), None);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put747 let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read748 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell749 "plan" => format!("Planning for {}", run.repo),
750 "review" => format!("Review of {}#{}", run.repo, run.number),
751 "update" => format!("Catching up {}#{}", run.repo, run.number),
752 _ => format!("Work on {}#{}", run.repo, run.number),
753 };
Billing accounts, terms and enterprises; g1t is no longer free754 description.push_str(&terms_note);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put755 description.push_str(&drawn.note());
Agents as a team: lifecycle, merge queue, billing and a new shell756 self.enter(
757 &run.workspace,
758 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put759 -(charge - drawn.total()),
Agents as a team: lifecycle, merge queue, billing and a new shell760 &description,
761 &a.run_id,
762 Some(&run),
763 Some(charge_micros(a.cost_usd, 0)),
764 None,
765 None,
766 )
767 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put768 self.record_drawn(&a.run_id, &drawn).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays769 self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await;
Agents as a team: lifecycle, merge queue, billing and a new shell770 Ok(Outcome::Ok(true))
771 }
772}
773
Every sandbox is metered by the second774impl Billing {
Prices are what g1t pays plus 20%, from the first second775 /// Records how long a sandbox ran, with its cost and its charge: every
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look776 /// second, from the first, at the price book's price; on its own CPU
777 /// when it reports it. Settles its reservation, if it names one.
Every sandbox is metered by the second778 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents779 // Self-hosted time is recorded wherever g1t runs, for its minutes;
780 // anything else only where there is a bill to put it on.
781 if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 {
Every sandbox is metered by the second782 return Ok(Outcome::Ok(false));
783 }
784 let workspace = a.workspace.to_lowercase();
785 let seen = self
786 .db
787 .prepare("SELECT id FROM ledger WHERE reference = ?")
788 .bind(&[a.reference.as_str().into()])?
789 .first::<Touched>(None)
790 .await?;
791 if seen.is_some() {
792 return Ok(Outcome::Ok(false));
793 }
794 let now = now_ms();
795 let timestamp = rfc3339(now);
796 let seconds = i64::from(a.seconds);
Fast pages, required checks on the branch, self-hosted runners, honest incidents797 // On the workspace's own machine: its minutes go on usage, at $0,
798 // and whatever was reserved for it is given back.
799 if a.self_hosted {
800 let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds));
801 self.db
802 .prepare(
803 "INSERT INTO ledger
804 (id, workspace, kind, amount_micros, description, repo, task,
805 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros)
806 VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0)",
807 )
808 .bind(&[
809 new_id("led", now).into(),
810 workspace.as_str().into(),
811 description.as_str().into(),
812 optional(a.repo.as_deref()),
813 a.reference.as_str().into(),
814 timestamp.as_str().into(),
815 ])?
816 .run()
817 .await?;
818 if let Some(reservation) = &a.reservation_id {
819 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?;
820 }
821 return Ok(Outcome::Ok(true));
822 }
Prices are what g1t pays plus 20%, from the first second823 // From the price book, which follows what Cloudflare bills g1t. A
824 // sandbox is the same container as a build, so without a row it is
825 // a build second's cost plus the margin.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look826 let (cost_per_second, _) = self.price("sandbox_second").await?.unwrap_or_else(|| {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas827 let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64;
Prices are what g1t pays plus 20%, from the first second828 (cost, Price::price_for(cost, self.margin_percent))
829 });
Fast pages, required checks on the branch, self-hosted runners, honest incidents830 // A larger machine (`runs-on: g1t-4core`): its memory and disk
831 // cost more each second, and without its own CPU it is priced at
832 // its vCPUs as busy as the standard machine's.
833 let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named);
834 let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb));
835 let price_scale = instance.map_or(1.0, |i| i.price_scale);
836 let vcpus = instance.map_or(4.0, |i| i.vcpu.max(4.0));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look837 // Its own CPU when the sandbox reports it; otherwise the average.
838 let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) {
839 Some(cpu) => match (self.price("sandbox_base_second").await?, self.price("sandbox_cpu_second").await?) {
Fast pages, required checks on the branch, self-hosted runners, honest incidents840 (Some((base, _)), Some((vcpu, _))) => {
841 Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu))
842 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look843 _ => None,
844 },
845 None => None,
846 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents847 let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look848 let (charge, terms_note) = self.charged(&workspace, credits::with_margin(cost, self.margin_percent)).await?;
849 let eligible = credits::eligible_for(a.kind, a.repo.as_deref());
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put850 let drawn = self.draw(&workspace, charge, &credits::month_of(&timestamp), &eligible).await?;
851 let charge = charge - drawn.total();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look852 let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds"));
853 let description = format!("{}: {} of sandbox time{cpu_note}{terms_note}{}", a.description, duration(seconds), drawn.note());
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily854 // The price versions it was charged at (pricing.rs).
855 let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] };
856 let mut versions = Vec::new();
857 for meter in meters {
858 versions.extend(self.version_now(meter).await?);
859 }
860 let price_version = versions.join(",");
Every sandbox is metered by the second861 self.db
862 .batch(vec![
863 self.db
864 .prepare(
865 "INSERT INTO ledger
866 (id, workspace, kind, amount_micros, description, repo, task,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily867 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version)
868 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?)",
Every sandbox is metered by the second869 )
870 .bind(&[
871 new_id("led", now).into(),
872 workspace.as_str().into(),
873 (-(charge as f64)).into(),
874 description.as_str().into(),
875 optional(a.repo.as_deref()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look876 (cost as f64).into(),
Every sandbox is metered by the second877 a.reference.as_str().into(),
878 timestamp.as_str().into(),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put879 (drawn.credit as f64).into(),
880 (drawn.trial as f64).into(),
881 (drawn.oss as f64).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look882 (drawn.given as f64).into(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily883 optional(Some(price_version.as_str()).filter(|v| !v.is_empty())),
Every sandbox is metered by the second884 ])?,
885 self.db
886 .prepare(
887 "INSERT INTO accounts (workspace, balance_micros, created_at)
888 VALUES (?1, ?2, ?3)
889 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
890 )
891 .bind(&[
892 workspace.as_str().into(),
893 (-(charge as f64)).into(),
894 timestamp.as_str().into(),
895 ])?,
896 ])
897 .await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays898 self.count_spend(&workspace, cost, charge, &drawn).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look899 if let Some(reservation) = &a.reservation_id {
900 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?;
901 }
Every sandbox is metered by the second902 Ok(Outcome::Ok(true))
903 }
904}
905
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look906/// Whether an amount may be prepaid: $25 at the least by card, and from
907/// $1,000 by bank transfer.
908pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> {
909 let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) };
910 if (min..=max).contains(&cents) {
911 return Ok(());
912 }
913 Err(if bank_transfer {
914 format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100))
915 } else {
916 format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100))
917 })
918}
919
920/// `10,000` for 10000.
921fn group(n: u32) -> String {
922 let digits = n.to_string();
923 let mut out = String::new();
924 for (i, c) in digits.chars().enumerate() {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept925 if i > 0 && (digits.len() - i).is_multiple_of(3) {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look926 out.push(',');
927 }
928 out.push(c);
929 }
930 out
931}
932
933#[cfg(test)]
Prices are what g1t pays plus 20%, from the first second934/// What `seconds` of sandbox time are charged at `price_per_second`, in
935/// millionths of a dollar: every second, rounded up to the next millionth.
936fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 {
937 (seconds as f64 * price_per_second).ceil() as i64
Every sandbox is metered by the second938}
939
940/// `1h 2m`, `3m 12s` or `40s`.
941fn duration(seconds: i64) -> String {
942 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
943 if h > 0 {
944 format!("{h}h {m}m")
945 } else if m > 0 {
946 format!("{m}m {s}s")
947 } else {
948 format!("{s}s")
949 }
950}
951
Billing accounts, terms and enterprises; g1t is no longer free952impl Billing {
953 /// What a workspace is charged for something that would be `base`:
954 /// nothing while g1t is free, or as its account's terms say. With a
955 /// note for the statement when it differs.
956 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String)> {
957 if self.free {
958 return Ok((0, " (free while g1t is being built out)".to_owned()));
959 }
960 let terms = self.terms_of(workspace).await?;
961 let charge = terms.apply(base);
962 let note = match terms.kind {
963 TermsKind::Comped => " (comped)".to_owned(),
964 TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent),
965 _ => String::new(),
966 };
967 Ok((charge, note))
968 }
969}
970
Agents as a team: lifecycle, merge queue, billing and a new shell971fn members_only<T>() -> Outcome<T> {
972 Outcome::fail(
973 FailureCode::Forbidden,
974 "Only members can see a workspace's billing.",
975 )
976}
977
Prices keep themselves current with what g1t pays978impl Billing {
979 fn from_env(env: &Env) -> Result<Self> {
980 Ok(Billing {
981 db: env.d1("DB")?,
982 stripe: env
983 .secret("STRIPE_SECRET_KEY")
984 .ok()
985 .map(|key| key.to_string())
986 .filter(|key| !key.is_empty())
987 .map(Stripe::new),
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard988 webhook_secret: env
989 .secret("STRIPE_WEBHOOK_SECRET")
990 .ok()
991 .map(|secret| secret.to_string().trim().to_owned())
992 .filter(|secret| !secret.is_empty()),
Prices keep themselves current with what g1t pays993 margin_percent: env
994 .var("MARGIN_PERCENT")
995 .ok()
996 .and_then(|percent| percent.to_string().parse().ok())
997 .unwrap_or(20),
998 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept999 ceilings: limits::Ceilings::from_env(env),
Billing accounts, terms and enterprises; g1t is no longer free1000 prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1001 trials_on: {
1002 let plans = credits::Config::from_env(env);
1003 plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0
Prices keep themselves current with what g1t pays1004 },
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1005 plans: credits::Config::from_env(env),
1006 repos: env.service("REPOS").ok(),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1007 packages: env.service("PACKAGES").ok(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1008 identity: env.service("IDENTITY").ok(),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1009 caps: budget::Caps::from_env(env),
1010 env: env.clone(),
Prices keep themselves current with what g1t pays1011 })
1012 }
1013}
1014
1015#[event(scheduled)]
1016async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
1017 let Ok(billing) = Billing::from_env(&env) else {
1018 return;
1019 };
1020 let keeper = keeper::Keeper::from_env(&env);
1021 if let Err(error) = billing.settle_runs(&keeper).await {
1022 worker::console_error!("settling runs failed: {error}");
1023 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1024 // Stripe events billing never received, handled now.
1025 match billing.replay_events().await {
1026 Ok(done) => worker::console_log!("stripe replay: {done}"),
1027 Err(error) => worker::console_error!("replaying Stripe events failed: {error}"),
1028 }
Billing accounts, terms and enterprises; g1t is no longer free1029 if let Err(error) = billing.autopay().await {
1030 worker::console_error!("paying at the limit failed: {error}");
1031 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1032 // Last month's metered usage (scans, embeddings, storage) goes on the
1033 // ledger before the month is closed and invoiced.
1034 if let Err(error) = billing.charge_pending().await {
1035 worker::console_error!("charging last month's metered usage failed: {error}");
1036 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1037 if let Err(error) = billing.close_months().await {
1038 worker::console_error!("closing the month failed: {error}");
1039 }
Stripe webhooks, enterprise invoices, and sudo for both1040 if let Err(error) = billing.invoice_enterprises().await {
1041 worker::console_error!("invoicing enterprises failed: {error}");
1042 }
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1043 // Comped budgets' alerts, and a tripped breaker staff were not told of.
1044 if let Err(error) = billing.watch_spend().await {
1045 worker::console_error!("watching g1t's own spend failed: {error}");
1046 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1047 if let Ok(identity) = env.service("IDENTITY")
1048 && let Err(error) = billing.warn_limits(&identity).await {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1049 worker::console_error!("warning owners failed: {error}");
1050 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1051 // Once a day: Stripe's endpoint kept listening to billing's events and
1052 // enabled, and saved cards and plans not read in a while read again.
1053 if event.cron() == keeper::DAILY {
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1054 match billing.keep_endpoint("billing").await {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1055 Ok(done) => worker::console_log!("stripe endpoint: {done}"),
1056 Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"),
1057 }
1058 match billing.refresh_from_stripe().await {
1059 Ok(done) => worker::console_log!("stripe refresh: {done}"),
1060 Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"),
1061 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1062 }
The keeper reads Cloudflare as it really answers1063 // Once a day, and at once if the costs were never checked: check every
1064 // cost against what Cloudflare billed.
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1065 if (event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false))
1066 && let Err(error) = billing.reconcile(&keeper).await {
Prices keep themselves current with what g1t pays1067 worker::console_error!("checking costs against Cloudflare failed: {error}");
1068 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1069 // Once a day: what Cloudflare charged, reconciled against what g1t
1070 // counted and charged; prices whose day has come; margin alerts
1071 // (margin.rs). After the keeper, so its proposals are in.
1072 if event.cron() == keeper::DAILY {
1073 match billing.costs_daily(&env, &keeper).await {
1074 Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1075 Err(error) => worker::console_error!("reconciling costs failed: {error}"),
1076 }
1077 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1078 // Once a day: what each workspace's private repositories hold, its git
1079 // operations, Deployments plans from before the g1t plan set to end,
1080 // and old reservations cleared.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1081 if event.cron() == keeper::DAILY {
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1082 if let Err(error) = billing.measure_packages().await {
1083 worker::console_error!("measuring package storage failed: {error}");
1084 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1085 if let Err(error) = billing.measure_storage().await {
1086 worker::console_error!("measuring storage failed: {error}");
1087 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1088 if let Err(error) = billing.measure_git().await {
1089 worker::console_error!("measuring git operations failed: {error}");
1090 }
1091 if let Err(error) = billing.retire_deployments_plans().await {
1092 worker::console_error!("ending Deployments plans failed: {error}");
1093 }
1094 if let Err(error) = billing.sweep_reservations().await {
1095 worker::console_error!("clearing reservations failed: {error}");
1096 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1097 }
Prices keep themselves current with what g1t pays1098}
1099
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1100/// Events from the bus, on billing's own queue: only a workspace's rename
1101/// matters here (see `rename`).
1102#[event(queue)]
1103async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
1104 let billing = Billing::from_env(&env)?;
1105 let identity = env.service("IDENTITY").ok();
1106 for message in batch.messages()? {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1107 // A repository transferred: its share of the open-source pool this
1108 // month follows it. What it was charged stays with the workspace
1109 // it was charged to; usage from now on is charged to the new one.
1110 if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? {
1111 message.ack();
1112 continue;
1113 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1114 billing.on_event(identity.as_ref(), message.body()).await?;
1115 message.ack();
1116 }
1117 Ok(())
1118}
1119
Agents as a team: lifecycle, merge queue, billing and a new shell1120#[event(fetch)]
1121async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1122 let Some(method) = rpc_method(&request) else {
1123 return Response::error("Not found", 404);
1124 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents1125 // A replica near the caller when it asks for one (crates/kit/src/d1.rs);
1126 // what other services call (can_start, start_run) asks for none.
1127 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
Agents as a team: lifecycle, merge queue, billing and a new shell1128 let body: serde_json::Value = request.json().await?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents1129 let mut billing = Billing::from_env(&env)?;
1130 billing.db = db;
1131 let answered = match method.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell1132 "status" => reply(&billing.status()),
1133 "account" => reply(&billing.account(args(body)?).await?),
1134 "ledger" => reply(&billing.ledger(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request1135 "usage" => reply(&billing.usage(args(body)?).await?),
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix1136 "record_tokens" => reply(&billing.record_tokens(args(body)?).await?),
1137 "token_usage" => reply(&billing.token_usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1138 "checkout" => reply(&billing.checkout(args(body)?).await?),
1139 "confirm" => reply(&billing.confirm(args(body)?).await?),
1140 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents1141 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1142 "start_run" => reply(&billing.start_run(args(body)?).await?),
1143 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1144 "features" => reply(&billing.features(args(body)?).await?),
1145 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1146 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1147 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1148 "close_workspace" => reply(&billing.close_workspace(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1149 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
1150 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1151 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1152 "limit" => reply(&billing.limit(args(body)?).await?),
1153 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1154 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1155 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1156 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1157 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1158 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1159 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
1160 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1161 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1162 "invoices" => reply(&billing.invoices(args(body)?).await?),
The statement is a month at a time, a line per kind of charge1163 "statement" => reply(&billing.statement(args(body)?).await?),
1164 "statement_entries" => reply(&billing.statement_entries(args(body)?).await?),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1165 "usage_meters" => reply(&billing.usage_meters(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1166 "admin_workspace_invoices" => {
1167 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1168 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1169 }
1170 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1171 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1172 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1173 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1174 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
Billing lists every invoice and every staff change; signals carry follow-ups1175 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1176 "admin_audit" => reply(&billing.admin_audit(args(body)?).await?),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1177 // A staff change made in another service, for sudo's audit log:
1178 // identity's restores and purges of deleted workspaces.
1179 "admin_log" => {
1180 let a: AdminLogArgs = args(body)?;
1181 billing
1182 .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by)
1183 .await?;
1184 reply(&true)
1185 }
Prices keep themselves current with what g1t pays1186 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1187 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1188 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1189 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1190 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1191 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1192 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1193 "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?),
1194 "entitlements" => reply(&billing.entitlements(args(body)?).await?),
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo1195 "audit_retention" => reply(&billing.audit_retention(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1196 "reserve" => reply(&billing.reserve(args(body)?).await?),
1197 "settle" => reply(&billing.settle_reservation(args(body)?).await?),
1198 "card_check" => reply(&billing.card_check(args(body)?).await?),
1199 "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?),
1200 "request_limit" => reply(&billing.request_limit(args(body)?).await?),
1201 "limit_requests" => reply(&billing.limit_requests(args(body)?).await?),
1202 "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?),
1203 "set_caps" => reply(&billing.set_caps(args(body)?).await?),
1204 "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?),
1205 "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?),
1206 "admin_overages" => reply(&billing.admin_overages(args(body)?).await?),
1207 "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?),
1208 "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?),
1209 "admin_record_payment" => reply(&billing.admin_record_payment(args(body)?).await?),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1210 "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?),
1211 "admin_cost_alerts" => reply(&billing.admin_cost_alerts(args(body)?).await?),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1212 "admin_spend_caps" => reply(&billing.spend_caps().await?),
1213 "admin_lift_breaker" => reply(&billing.admin_lift_breaker(args(body)?).await?),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1214 "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?),
1215 "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?),
1216 "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?),
1217 "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1218 _ => Response::error("Unknown method", 404),
Fast pages, required checks on the branch, self-hosted runners, honest incidents1219 };
1220 served.finish(answered)
Agents as a team: lifecycle, merge queue, billing and a new shell1221}
1222
1223#[cfg(test)]
1224mod tests {
1225 use super::*;
1226
1227 #[test]
1228 fn a_run_is_charged_its_cost_plus_the_margin() {
1229 // $0.05 at 20% is six cents.
1230 assert_eq!(charge_micros(0.05, 20), 60_000);
1231 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1232 assert_eq!(charge_micros(0.05, 0), 50_000);
1233 }
1234
1235 #[test]
1236 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1237 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1238 assert_eq!(charge_micros(0.0, 20), 0);
1239 assert_eq!(charge_micros(-3.0, 20), 0);
1240 }
1241
1242 #[test]
Prices are what g1t pays plus 20%, from the first second1243 fn sandbox_time_is_charged_from_the_first_second() {
1244 // 21 millionths a second at cost, plus 20%.
1245 let price = Price::price_for(21.0, 20);
1246 assert_eq!(sandbox_charge(1, price), 26);
1247 assert_eq!(sandbox_charge(60, price), 1_512);
1248 assert_eq!(sandbox_charge(0, price), 0);
Every sandbox is metered by the second1249 }
1250
1251 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1252 fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() {
1253 assert!(prepay_amount(2_500, false).is_ok());
1254 assert!(prepay_amount(2_499, false).is_err());
1255 assert!(prepay_amount(10_000, false).is_ok());
1256 assert!(prepay_amount(1_000_000, false).is_ok());
1257 assert_eq!(prepay_amount(1_000_001, false).unwrap_err(), "Prepay between $25 and $10,000 by card; from $1,000, a bank transfer works too.");
1258 assert!(prepay_amount(99_999, true).is_err());
1259 assert!(prepay_amount(100_000, true).is_ok());
1260 }
1261
1262 #[test]
Every sandbox is metered by the second1263 fn durations_read_plainly() {
1264 assert_eq!(duration(40), "40s");
1265 assert_eq!(duration(192), "3m 12s");
1266 assert_eq!(duration(3720), "1h 2m");
1267 }
1268
1269 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1270 fn an_absurd_cost_is_capped() {
1271 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1272 }
1273}