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 look | 1 | //! 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 shell | 3 | //! |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 4 | //! 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 plan | 13 | //! |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 14 | //! 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 free | 20 | mod accounts; |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 21 | mod budget; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 22 | mod cards; |
| 23 | mod closing; | |
| 24 | mod compute; | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 25 | mod costs; |
| 26 | mod margin; | |
| 27 | mod pricing; | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 28 | mod credits; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 29 | mod overages; |
| 30 | mod requests; | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 31 | mod storage; |
| Two limits, real invoices, trust that grows by itself, sales signals | 32 | mod invoices; |
| 33 | mod sales; | |
| The statement is a month at a time, a line per kind of charge | 34 | mod statement; |
| Stripe webhooks, enterprise invoices, and sudo for both | 35 | mod webhooks; |
| Paid features: a workspace turns on Deployments with a monthly plan | 36 | mod features; |
| Prices keep themselves current with what g1t pays | 37 | mod keeper; |
| Usage limits: unpaid usage can only go so far | 38 | mod limits; |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 39 | mod rename; |
| Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo | 40 | mod retention; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 41 | mod stripe; |
| Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept | 42 | mod stripe_sync; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 43 | |
| 44 | use g1t_contracts::billing::*; | |
| 45 | use g1t_contracts::time::rfc3339; | |
| 46 | use g1t_contracts::{FailureCode, Outcome, Role, new_id}; | |
| Billing accounts, terms and enterprises; g1t is no longer free | 47 | use g1t_contracts::billing::TermsKind; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 48 | use g1t_kit::{args, now_ms, reply, rpc_method}; |
| 49 | use serde::Deserialize; | |
| 50 | use sha2::{Digest, Sha256}; | |
| 51 | use worker::wasm_bindgen::JsValue; | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 52 | use 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 index | 53 | use futures_util::future::{try_join, try_join5}; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 54 | |
| 55 | use stripe::Stripe; | |
| 56 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 57 | /// Prepaying: $25 at the least; by card up to $10,000 at a time, and by |
| 58 | /// bank transfer from $1,000 to $100,000. | |
| 59 | const MIN_TOP_UP_CENTS: u32 = 2_500; | |
| 60 | const MAX_TOP_UP_CENTS: u32 = 1_000_000; | |
| 61 | const MIN_BANK_TRANSFER_CENTS: u32 = 100_000; | |
| 62 | const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 63 | const LEDGER_PAGE: u32 = 100; |
| 64 | /// A run's reported cost is believed up to this much. A sandbox cannot | |
| 65 | /// spend more in the time it has, so anything above is a fault. | |
| 66 | const MAX_RUN_COST_USD: f64 = 100.0; | |
| 67 | ||
| 68 | /// What a run is charged: its cost plus the margin, rounded up to a whole | |
| 69 | /// millionth of a dollar. | |
| 70 | pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 { | |
| 71 | let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil(); | |
| 72 | (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64 | |
| 73 | } | |
| 74 | ||
| 75 | fn hash(token: &str) -> String { | |
| 76 | hex::encode(Sha256::digest(token.as_bytes())) | |
| 77 | } | |
| 78 | ||
| 79 | fn optional(value: Option<&str>) -> JsValue { | |
| 80 | value.map_or(JsValue::NULL, JsValue::from) | |
| 81 | } | |
| 82 | ||
| 83 | #[derive(Deserialize)] | |
| 84 | struct AccountRow { | |
| 85 | balance_micros: i64, | |
| 86 | customer_id: Option<String>, | |
| 87 | } | |
| 88 | ||
| 89 | #[derive(Deserialize)] | |
| 90 | struct LedgerRow { | |
| 91 | id: String, | |
| 92 | kind: EntryKind, | |
| 93 | amount_micros: i64, | |
| 94 | description: String, | |
| 95 | repo: Option<String>, | |
| 96 | number: Option<u32>, | |
| 97 | task: Option<String>, | |
| 98 | model: Option<String>, | |
| 99 | created_by: Option<String>, | |
| 100 | created_at: String, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 101 | billed_to: Option<String>, |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 102 | #[serde(default)] |
| 103 | workspace: Option<String>, | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 104 | #[serde(default)] |
| 105 | credit_micros: Option<i64>, | |
| 106 | #[serde(default)] | |
| 107 | trial_micros: Option<i64>, | |
| 108 | #[serde(default)] | |
| 109 | oss_micros: Option<i64>, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 110 | #[serde(default)] |
| 111 | given_micros: Option<i64>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 112 | } |
| 113 | ||
| 114 | impl From<LedgerRow> for LedgerEntry { | |
| 115 | fn from(row: LedgerRow) -> Self { | |
| 116 | LedgerEntry { | |
| 117 | id: row.id, | |
| 118 | kind: row.kind, | |
| 119 | amount_micros: row.amount_micros, | |
| 120 | description: row.description, | |
| 121 | repo: row.repo, | |
| 122 | number: row.number, | |
| 123 | task: row.task, | |
| 124 | model: row.model, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 125 | billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 126 | created_by: row.created_by, |
| 127 | created_at: row.created_at, | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 128 | workspace: row.workspace, |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 129 | credit_micros: row.credit_micros.unwrap_or(0), |
| 130 | trial_micros: row.trial_micros.unwrap_or(0), | |
| 131 | oss_micros: row.oss_micros.unwrap_or(0), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 132 | given_micros: row.given_micros.unwrap_or(0), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 133 | } |
| 134 | } | |
| 135 | } | |
| 136 | ||
| 137 | #[derive(Deserialize)] | |
| 138 | struct RunRow { | |
| 139 | workspace: String, | |
| 140 | repo: String, | |
| 141 | number: u32, | |
| 142 | task: String, | |
| 143 | model: String, | |
| 144 | token_hash: String, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 145 | billed_to: Option<String>, |
| 146 | } | |
| 147 | ||
| 148 | impl RunRow { | |
| 149 | fn own_provider(&self) -> bool { | |
| 150 | self.billed_to.as_deref() == Some("workspace") | |
| 151 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 152 | } |
| 153 | ||
| 154 | #[derive(Deserialize)] | |
| 155 | struct CheckoutRow { | |
| 156 | workspace: String, | |
| 157 | created_by: String, | |
| 158 | } | |
| 159 | ||
| 160 | /// A row an `UPDATE … RETURNING` touched. | |
| 161 | #[derive(Deserialize)] | |
| 162 | struct Touched { | |
| 163 | #[allow(dead_code)] | |
| 164 | id: String, | |
| 165 | } | |
| 166 | ||
| 167 | struct Billing { | |
| 168 | db: D1Database, | |
| 169 | /// Absent when no card processor is configured. | |
| 170 | stripe: Option<Stripe>, | |
| Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard | 171 | /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`); |
| 172 | /// without it no event is believed. | |
| 173 | webhook_secret: Option<String>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 174 | margin_percent: u32, |
| Free while g1t is being built out; agents can check out their own forks | 175 | /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`). |
| 176 | free: bool, | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 177 | /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS` |
| 178 | /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero). | |
| 179 | trials_on: bool, | |
| 180 | /// The plans' and pools' numbers; see `credits`. | |
| 181 | plans: credits::Config, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 182 | /// The repos service: which repositories are public, what private ones |
| 183 | /// 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 put | 184 | repos: Option<worker::Fetcher>, |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 185 | /// The identity service, which emails owners. Absent where it is not |
| 186 | /// bound. | |
| 187 | identity: Option<worker::Fetcher>, | |
| Usage limits: unpaid usage can only go so far | 188 | /// How far unpaid usage may go; see `limits`. |
| 189 | ceilings: limits::Ceilings, | |
| Billing accounts, terms and enterprises; g1t is no longer free | 190 | /// `PREPAID_ONLY`: the old rule, that agents need credit first. |
| 191 | prepaid_only: bool, | |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 192 | /// The caps on what g1t pays for itself; see `budget`. |
| 193 | caps: budget::Caps, | |
| 194 | /// The worker's bindings, for emailing staff (`EMAIL`). | |
| 195 | env: Env, | |
| A free allowance on g1t's models, so anyone can try its agents | 196 | } |
| 197 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 198 | impl Billing { |
| 199 | fn status(&self) -> Status { | |
| 200 | Status { | |
| 201 | enabled: self.stripe.is_some(), | |
| 202 | live: self.stripe.as_ref().is_some_and(Stripe::live), | |
| Free while g1t is being built out; agents can check out their own forks | 203 | free: self.free, |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 204 | } |
| 205 | } | |
| 206 | ||
| 207 | async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> { | |
| 208 | self.db | |
| 209 | .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?") | |
| 210 | .bind(&[workspace.into()])? | |
| 211 | .first::<AccountRow>(None) | |
| 212 | .await | |
| 213 | } | |
| 214 | ||
| 215 | 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 kept | 216 | // The card as last synced (stripe_sync.rs), not asked of Stripe. |
| 217 | let (row, card) = try_join(self.row(workspace), self.saved_card(workspace)).await?; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 218 | Ok(Account { |
| 219 | workspace: workspace.to_owned(), | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 220 | balance_micros: row.map_or(0, |row| row.balance_micros), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 221 | status: self.status(), |
| 222 | margin_percent: self.margin_percent, | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 223 | card, |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 224 | }) |
| 225 | } | |
| 226 | ||
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 227 | /// The workspace's customer at Stripe, made the first time one is needed. |
| 228 | pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> { | |
| 229 | let Some(stripe) = &self.stripe else { | |
| 230 | return Err(worker::Error::RustError("payments are not set up".into())); | |
| 231 | }; | |
| 232 | if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) { | |
| 233 | return Ok(customer); | |
| 234 | } | |
| 235 | let customer = stripe.create_customer(workspace).await?; | |
| 236 | self.db | |
| 237 | .prepare( | |
| 238 | "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3) | |
| 239 | ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2", | |
| 240 | ) | |
| 241 | .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])? | |
| 242 | .run() | |
| 243 | .await?; | |
| 244 | Ok(customer) | |
| 245 | } | |
| 246 | ||
| 247 | /// Stripe's hosted billing page for the workspace. Owners only. | |
| 248 | async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> { | |
| 249 | let workspace = a.workspace.to_lowercase(); | |
| 250 | if a.actor.role_in(&workspace) != Some(Role::Owner) { | |
| 251 | return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing.")); | |
| 252 | } | |
| 253 | let Some(stripe) = &self.stripe else { | |
| 254 | return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t.")); | |
| 255 | }; | |
| 256 | let customer = match self.customer_for(&workspace).await { | |
| 257 | Ok(customer) => customer, | |
| 258 | Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))), | |
| 259 | }; | |
| 260 | match stripe.portal_session(&customer, &a.return_url).await { | |
| 261 | Ok(url) => Ok(Outcome::Ok(Checkout { url })), | |
| 262 | Err(error) if stripe::is_missing(&error) => { | |
| 263 | // The customer was removed at Stripe: a new one next time. | |
| 264 | self.forget_customer(&workspace).await?; | |
| 265 | Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again.")) | |
| 266 | } | |
| 267 | Err(error) => Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe's billing page could not be opened: {error}"))), | |
| 268 | } | |
| 269 | } | |
| 270 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 271 | /// Adds a ledger entry and moves the balance by the same amount, as |
| 272 | /// one write. | |
| 273 | #[allow(clippy::too_many_arguments)] | |
| 274 | async fn enter( | |
| 275 | &self, | |
| 276 | workspace: &str, | |
| 277 | kind: EntryKind, | |
| 278 | amount_micros: i64, | |
| 279 | description: &str, | |
| 280 | reference: &str, | |
| 281 | run: Option<&RunRow>, | |
| 282 | cost_micros: Option<i64>, | |
| 283 | created_by: Option<&str>, | |
| 284 | customer: Option<&str>, | |
| 285 | ) -> Result<()> { | |
| 286 | let now = now_ms(); | |
| 287 | let timestamp = rfc3339(now); | |
| 288 | let kind = match kind { | |
| 289 | EntryKind::TopUp => "top_up", | |
| 290 | EntryKind::Usage => "usage", | |
| 291 | }; | |
| 292 | self.db | |
| 293 | .batch(vec![ | |
| 294 | self.db | |
| 295 | .prepare( | |
| 296 | "INSERT INTO ledger | |
| 297 | (id, workspace, kind, amount_micros, description, repo, number, task, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 298 | model, cost_micros, reference, created_by, created_at, billed_to) |
| 299 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 300 | ) |
| 301 | .bind(&[ | |
| 302 | new_id("led", now).into(), | |
| 303 | workspace.into(), | |
| 304 | kind.into(), | |
| 305 | // D1 takes numbers as doubles, which hold every | |
| 306 | // amount this service will see exactly. | |
| 307 | (amount_micros as f64).into(), | |
| 308 | description.into(), | |
| 309 | optional(run.map(|run| run.repo.as_str())), | |
| 310 | run.map_or(JsValue::NULL, |run| run.number.into()), | |
| 311 | optional(run.map(|run| run.task.as_str())), | |
| 312 | optional(run.map(|run| run.model.as_str())), | |
| 313 | cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()), | |
| 314 | reference.into(), | |
| 315 | optional(created_by), | |
| 316 | timestamp.as_str().into(), | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 317 | run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 318 | ])?, |
| 319 | self.db | |
| 320 | .prepare( | |
| 321 | "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) | |
| 322 | VALUES (?1, ?2, ?3, ?4) | |
| 323 | ON CONFLICT (workspace) DO UPDATE SET | |
| 324 | balance_micros = balance_micros + ?2, | |
| 325 | customer_id = COALESCE(?3, customer_id)", | |
| 326 | ) | |
| 327 | .bind(&[ | |
| 328 | workspace.into(), | |
| 329 | (amount_micros as f64).into(), | |
| 330 | optional(customer), | |
| 331 | timestamp.as_str().into(), | |
| 332 | ])?, | |
| 333 | ]) | |
| 334 | .await?; | |
| Billing accounts, terms and enterprises; g1t is no longer free | 335 | // Money in clears a card declined at the limit. |
| 336 | if kind == "top_up" { | |
| 337 | self.db | |
| 338 | .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?") | |
| 339 | .bind(&[workspace.into()])? | |
| 340 | .run() | |
| 341 | .await?; | |
| 342 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 343 | Ok(()) |
| 344 | } | |
| 345 | ||
| 346 | async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> { | |
| 347 | let workspace = a.workspace.to_lowercase(); | |
| 348 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { | |
| 349 | return Ok(members_only()); | |
| 350 | } | |
| 351 | Ok(Outcome::Ok(self.standing(&workspace).await?)) | |
| 352 | } | |
| 353 | ||
| 354 | async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> { | |
| 355 | let workspace = a.workspace.to_lowercase(); | |
| 356 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { | |
| 357 | return Ok(members_only()); | |
| 358 | } | |
| 359 | let rows = self | |
| 360 | .db | |
| 361 | .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?") | |
| 362 | .bind(&[workspace.into(), LEDGER_PAGE.into()])? | |
| 363 | .all() | |
| 364 | .await? | |
| 365 | .results::<LedgerRow>()?; | |
| 366 | Ok(Outcome::Ok( | |
| 367 | rows.into_iter().map(LedgerEntry::from).collect(), | |
| 368 | )) | |
| 369 | } | |
| 370 | ||
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 371 | async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> { |
| 372 | let workspace = a.workspace.to_lowercase(); | |
| 373 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { | |
| 374 | return Ok(members_only()); | |
| 375 | } | |
| 376 | #[derive(serde::Deserialize)] | |
| 377 | struct SliceRow { | |
| 378 | key: Option<String>, | |
| 379 | micros: Option<i64>, | |
| 380 | runs: Option<u32>, | |
| 381 | } | |
| Usage while free is shown at cost; agents get rustfmt and clippy | 382 | // While nothing is charged, what was used is what there is to show. |
| 383 | let measure = if self.free { "COALESCE(cost_micros, 0)" } else { "-amount_micros" }; | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 384 | let slices = |key: &str, limit: u32| { |
| 385 | format!( | |
| Usage while free is shown at cost; agents get rustfmt and clippy | 386 | "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 request | 387 | WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2 |
| 388 | GROUP BY 1 ORDER BY micros DESC LIMIT {limit}" | |
| 389 | ) | |
| 390 | }; | |
| 391 | let query = |sql: String| { | |
| 392 | let db = &self.db; | |
| 393 | let workspace = workspace.clone(); | |
| 394 | let since = a.since.clone(); | |
| 395 | async move { | |
| 396 | let rows = db | |
| 397 | .prepare(sql) | |
| 398 | .bind(&[workspace.into(), since.into()])? | |
| 399 | .all() | |
| 400 | .await? | |
| 401 | .results::<SliceRow>()?; | |
| 402 | Ok::<Vec<UsageSlice>, worker::Error>( | |
| 403 | rows.into_iter() | |
| 404 | .map(|row| UsageSlice { | |
| 405 | key: row.key.unwrap_or_else(|| "other".to_owned()), | |
| 406 | micros: row.micros.unwrap_or_default(), | |
| 407 | runs: row.runs.unwrap_or_default(), | |
| 408 | }) | |
| 409 | .collect(), | |
| 410 | ) | |
| 411 | } | |
| 412 | }; | |
| 413 | #[derive(serde::Deserialize)] | |
| 414 | struct Totals { | |
| 415 | spent: Option<i64>, | |
| 416 | cost: Option<i64>, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 417 | provider: Option<i64>, |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 418 | runs: Option<u32>, |
| 419 | added: Option<i64>, | |
| 420 | } | |
| 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 index | 421 | let totals = async { |
| 422 | self.db | |
| 423 | .prepare( | |
| 424 | "SELECT | |
| 425 | -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent, | |
| 426 | SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost, | |
| 427 | SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider, | |
| 428 | SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs, | |
| 429 | SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added | |
| 430 | FROM ledger WHERE workspace = ?1 AND created_at >= ?2", | |
| 431 | ) | |
| 432 | .bind(&[workspace.as_str().into(), a.since.as_str().into()])? | |
| 433 | .first::<Totals>(None) | |
| 434 | .await | |
| 435 | }; | |
| 436 | // The totals and the five slices read the same rows independently, | |
| 437 | // so they go to D1 at once: one round trip of waiting, not six. | |
| 438 | let (totals, (by_day, by_task, by_repo, by_pull, by_model)) = try_join( | |
| 439 | totals, | |
| 440 | try_join5( | |
| 441 | query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)), | |
| 442 | query(slices("task", 20)), | |
| 443 | query(slices("repo", 20)), | |
| 444 | query(slices("repo || '#' || number", 10)), | |
| 445 | query(slices("model", 10)), | |
| 446 | ), | |
| 447 | ) | |
| 448 | .await?; | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 449 | let totals = totals.unwrap_or(Totals { |
| 450 | spent: None, | |
| 451 | cost: None, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 452 | provider: None, |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 453 | runs: None, |
| 454 | added: None, | |
| 455 | }); | |
| 456 | Ok(Outcome::Ok(Usage { | |
| 457 | spent_micros: totals.spent.unwrap_or_default(), | |
| 458 | cost_micros: totals.cost.unwrap_or_default(), | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 459 | provider_micros: totals.provider.unwrap_or_default(), |
| Usage while free is shown at cost; agents get rustfmt and clippy | 460 | used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(), |
| 461 | free: self.free, | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 462 | runs: totals.runs.unwrap_or_default(), |
| 463 | 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 index | 464 | by_day, |
| 465 | by_task, | |
| 466 | by_repo, | |
| 467 | by_pull, | |
| 468 | by_model, | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 469 | since: a.since, |
| 470 | })) | |
| 471 | } | |
| 472 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 473 | /// `checkout`: prepays usage, by card or (from $1,000) bank transfer. |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 474 | async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> { |
| 475 | let workspace = a.workspace.to_lowercase(); | |
| 476 | if a.actor.role_in(&workspace) != Some(Role::Owner) { | |
| 477 | return Ok(Outcome::fail( | |
| 478 | FailureCode::Forbidden, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 479 | "Only an owner can prepay for a workspace.", |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 480 | )); |
| 481 | } | |
| 482 | let Some(stripe) = &self.stripe else { | |
| 483 | return Ok(Outcome::fail( | |
| 484 | FailureCode::Conflict, | |
| 485 | "Payments are not set up on this g1t yet.", | |
| 486 | )); | |
| 487 | }; | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 488 | let bank_transfer = a.method.as_deref() == Some("bank_transfer"); |
| 489 | if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) { | |
| 490 | return Ok(Outcome::fail(FailureCode::Invalid, why)); | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 491 | } |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 492 | // A bank transfer needs a customer for its account details. |
| 493 | let customer = if bank_transfer { | |
| 494 | match self.customer_for(&workspace).await { | |
| 495 | Ok(customer) => Some(customer), | |
| 496 | Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))), | |
| 497 | } | |
| 498 | } else { | |
| 499 | self.row(&workspace).await?.and_then(|row| row.customer_id) | |
| 500 | }; | |
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 501 | let session = match stripe |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 502 | .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url, bank_transfer) |
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 503 | .await |
| 504 | { | |
| 505 | Ok(session) => session, | |
| 506 | // A customer saved under another Stripe account: start afresh. | |
| 507 | Err(error) if customer.is_some() && stripe::is_missing(&error) => { | |
| 508 | self.forget_customer(&workspace).await?; | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 509 | let customer = if bank_transfer { Some(self.customer_for(&workspace).await?) } else { None }; |
| 510 | 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 know | 511 | } |
| 512 | Err(error) => return Err(error), | |
| 513 | }; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 514 | let Some(url) = session.url else { |
| 515 | return Err(worker::Error::RustError( | |
| 516 | "the card processor returned no payment page".into(), | |
| 517 | )); | |
| 518 | }; | |
| 519 | self.db | |
| 520 | .prepare( | |
| 521 | "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at) | |
| 522 | VALUES (?, ?, ?, ?, ?)", | |
| 523 | ) | |
| 524 | .bind(&[ | |
| 525 | session.id.into(), | |
| 526 | workspace.into(), | |
| 527 | a.amount_cents.into(), | |
| 528 | a.actor.username.into(), | |
| 529 | rfc3339(now_ms()).into(), | |
| 530 | ])? | |
| 531 | .run() | |
| 532 | .await?; | |
| 533 | Ok(Outcome::Ok(Checkout { url })) | |
| 534 | } | |
| 535 | ||
| 536 | /// Credits a payment if the processor says it was made and it has not | |
| 537 | /// been credited before. The amount credited is what the processor | |
| 538 | /// says was paid, not what anyone here remembers asking for. | |
| 539 | async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> { | |
| 540 | let workspace = a.workspace.to_lowercase(); | |
| 541 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { | |
| 542 | return Ok(members_only()); | |
| 543 | } | |
| 544 | let (Some(stripe), Some(checkout)) = ( | |
| 545 | &self.stripe, | |
| 546 | self.db | |
| 547 | .prepare( | |
| 548 | "SELECT workspace, created_by FROM checkouts | |
| 549 | WHERE id = ? AND workspace = ? AND status = 'open'", | |
| 550 | ) | |
| 551 | .bind(&[a.session.as_str().into(), workspace.as_str().into()])? | |
| 552 | .first::<CheckoutRow>(None) | |
| 553 | .await?, | |
| 554 | ) else { | |
| 555 | // Unknown, someone else's, or already credited: nothing to do. | |
| 556 | return Ok(Outcome::Ok(self.standing(&workspace).await?)); | |
| 557 | }; | |
| 558 | let session = stripe.session(&a.session).await?; | |
| 559 | let paid = session | |
| 560 | .amount_total | |
| 561 | .filter(|_| session.payment_status == "paid"); | |
| 562 | if let Some(cents) = paid { | |
| 563 | // Only whoever flips it from open to paid enters the credit. | |
| 564 | let claimed = self | |
| 565 | .db | |
| 566 | .prepare( | |
| 567 | "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open' | |
| 568 | RETURNING id", | |
| 569 | ) | |
| 570 | .bind(&[a.session.as_str().into()])? | |
| 571 | .first::<Touched>(None) | |
| 572 | .await?; | |
| 573 | if claimed.is_some() { | |
| 574 | self.enter( | |
| 575 | &checkout.workspace, | |
| 576 | EntryKind::TopUp, | |
| 577 | i64::from(cents) * MICROS_PER_DOLLAR / 100, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 578 | "Paid in advance", |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 579 | &session.id, |
| 580 | None, | |
| 581 | None, | |
| 582 | Some(&checkout.created_by), | |
| 583 | session.customer.as_deref(), | |
| 584 | ) | |
| 585 | .await?; | |
| 586 | } | |
| 587 | } | |
| 588 | Ok(Outcome::Ok(self.standing(&workspace).await?)) | |
| 589 | } | |
| 590 | ||
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 591 | /// Drops a saved customer the card processor no longer knows. |
| 592 | pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> { | |
| 593 | self.db | |
| Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept | 594 | .prepare( |
| 595 | "UPDATE accounts SET customer_id = NULL, card_brand = NULL, card_last4 = NULL, card_exp_month = NULL, | |
| 596 | card_exp_year = NULL, card_synced_at = NULL WHERE workspace = ?", | |
| 597 | ) | |
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 598 | .bind(&[workspace.into()])? |
| 599 | .run() | |
| 600 | .await?; | |
| 601 | Ok(()) | |
| 602 | } | |
| 603 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 604 | /// A refusal if the workspace has no credit to start an agent with. |
| 605 | async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> { | |
| Billing accounts, terms and enterprises; g1t is no longer free | 606 | // Billing is postpaid: usage limits decide whether work starts |
| 607 | // (see `limits`), and credit is a prepayment that lowers what is | |
| 608 | // owed. A balance no longer has to be positive to start. | |
| 609 | if self.free || !self.prepaid_only { | |
| Free while g1t is being built out; agents can check out their own forks | 610 | return Ok(None); |
| 611 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 612 | let balance = self |
| 613 | .row(workspace) | |
| 614 | .await? | |
| 615 | .map_or(0, |row| row.balance_micros); | |
| 616 | Ok((balance <= 0).then(|| { | |
| 617 | Outcome::fail( | |
| 618 | FailureCode::PaymentRequired, | |
| 619 | format!( | |
| 620 | "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page." | |
| 621 | ), | |
| 622 | ) | |
| 623 | })) | |
| Billing accounts, terms and enterprises; g1t is no longer free | 624 | } |
| 625 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 626 | async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> { |
| 627 | if self.stripe.is_none() { | |
| 628 | return Ok(Outcome::Ok(true)); | |
| 629 | } | |
| Usage limits: unpaid usage can only go so far | 630 | if let Some(stopped) = self.stopped(&a.workspace).await? { |
| 631 | return Ok(stopped); | |
| 632 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 633 | Ok(self |
| 634 | .out_of_credit(&a.workspace.to_lowercase()) | |
| 635 | .await? | |
| 636 | .unwrap_or(Outcome::Ok(true))) | |
| 637 | } | |
| 638 | ||
| 639 | async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> { | |
| 640 | if self.stripe.is_none() { | |
| 641 | return Ok(Outcome::Ok(None)); | |
| 642 | } | |
| 643 | let workspace = a.workspace.to_lowercase(); | |
| Usage limits: unpaid usage can only go so far | 644 | if let Some(stopped) = self.stopped(&workspace).await? { |
| 645 | return Ok(stopped); | |
| 646 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 647 | if let Some(refused) = self.out_of_credit(&workspace).await? { |
| 648 | return Ok(refused); | |
| 649 | } | |
| 650 | let now = now_ms(); | |
| 651 | let run_id = new_id("run", now); | |
| 652 | let mut bytes = [0u8; 32]; | |
| 653 | getrandom::getrandom(&mut bytes).expect("no source of randomness"); | |
| 654 | let token = hex::encode(bytes); | |
| 655 | self.db | |
| 656 | .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 tier | 657 | "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier) |
| 658 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 659 | ) |
| 660 | .bind(&[ | |
| 661 | run_id.as_str().into(), | |
| 662 | workspace.into(), | |
| 663 | format!("{}/{}", a.repo.namespace, a.repo.name).into(), | |
| 664 | a.number.into(), | |
| 665 | a.task.into(), | |
| 666 | a.model.into(), | |
| 667 | hash(&token).into(), | |
| 668 | rfc3339(now).into(), | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 669 | if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(), |
| Prices keep themselves current with what g1t pays | 670 | 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 tier | 671 | optional( |
| 672 | a.tier | |
| 673 | .as_deref() | |
| 674 | .filter(|tier| a.billed_to != "workspace" && matches!(*tier, "small" | "large")), | |
| 675 | ), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 676 | ])? |
| 677 | .run() | |
| 678 | .await?; | |
| 679 | Ok(Outcome::Ok(Some(RunTicket { run_id, token }))) | |
| 680 | } | |
| 681 | ||
| 682 | async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> { | |
| 683 | let run = self | |
| 684 | .db | |
| 685 | .prepare( | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 686 | "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 687 | WHERE id = ? AND finished_at IS NULL", |
| 688 | ) | |
| 689 | .bind(&[a.run_id.as_str().into()])? | |
| 690 | .first::<RunRow>(None) | |
| 691 | .await?; | |
| 692 | let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else { | |
| 693 | return Ok(Outcome::fail(FailureCode::NotFound, "Run not found.")); | |
| 694 | }; | |
| 695 | if !a.cost_usd.is_finite() || a.cost_usd < 0.0 { | |
| 696 | return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost.")); | |
| 697 | } | |
| 698 | // Only whoever closes the run charges for it. | |
| 699 | let claimed = self | |
| 700 | .db | |
| 701 | .prepare( | |
| 702 | "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id", | |
| 703 | ) | |
| 704 | .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])? | |
| 705 | .first::<Touched>(None) | |
| 706 | .await?; | |
| 707 | if claimed.is_none() { | |
| 708 | return Ok(Outcome::Ok(false)); | |
| 709 | } | |
| Prices are what g1t pays plus 20%, from the first second | 710 | // On the workspace's own provider, the model was paid for there, |
| 711 | // and the run's sandbox time is recorded on its own: nothing more | |
| 712 | // to charge. | |
| 713 | if run.own_provider() { | |
| 714 | return Ok(Outcome::Ok(true)); | |
| 715 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 716 | // Its cost plus the margin, on the account's terms; then the plan's |
| 717 | // included usage and the trial credit pay what they can, and g1t | |
| 718 | // covers a free workspace's overrun (see `credits`). Agents are | |
| 719 | // 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 put | 720 | let base = charge_micros(a.cost_usd, self.margin_percent); |
| Billing accounts, terms and enterprises; g1t is no longer free | 721 | 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 put | 722 | let month = credits::month_of(&rfc3339(now_ms())); |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 723 | 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 put | 724 | let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?; |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 725 | let mut description = match run.task.as_str() { |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 726 | "plan" => format!("Planning for {}", run.repo), |
| 727 | "review" => format!("Review of {}#{}", run.repo, run.number), | |
| 728 | "update" => format!("Catching up {}#{}", run.repo, run.number), | |
| 729 | _ => format!("Work on {}#{}", run.repo, run.number), | |
| 730 | }; | |
| Billing accounts, terms and enterprises; g1t is no longer free | 731 | description.push_str(&terms_note); |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 732 | description.push_str(&drawn.note()); |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 733 | self.enter( |
| 734 | &run.workspace, | |
| 735 | EntryKind::Usage, | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 736 | -(charge - drawn.total()), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 737 | &description, |
| 738 | &a.run_id, | |
| 739 | Some(&run), | |
| 740 | Some(charge_micros(a.cost_usd, 0)), | |
| 741 | None, | |
| 742 | None, | |
| 743 | ) | |
| 744 | .await?; | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 745 | self.record_drawn(&a.run_id, &drawn).await?; |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 746 | 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 shell | 747 | Ok(Outcome::Ok(true)) |
| 748 | } | |
| 749 | } | |
| 750 | ||
| Every sandbox is metered by the second | 751 | impl Billing { |
| Prices are what g1t pays plus 20%, from the first second | 752 | /// 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 look | 753 | /// second, from the first, at the price book's price; on its own CPU |
| 754 | /// when it reports it. Settles its reservation, if it names one. | |
| Every sandbox is metered by the second | 755 | async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> { |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 756 | // Self-hosted time is recorded wherever g1t runs, for its minutes; |
| 757 | // anything else only where there is a bill to put it on. | |
| 758 | if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 { | |
| Every sandbox is metered by the second | 759 | return Ok(Outcome::Ok(false)); |
| 760 | } | |
| 761 | let workspace = a.workspace.to_lowercase(); | |
| 762 | let seen = self | |
| 763 | .db | |
| 764 | .prepare("SELECT id FROM ledger WHERE reference = ?") | |
| 765 | .bind(&[a.reference.as_str().into()])? | |
| 766 | .first::<Touched>(None) | |
| 767 | .await?; | |
| 768 | if seen.is_some() { | |
| 769 | return Ok(Outcome::Ok(false)); | |
| 770 | } | |
| 771 | let now = now_ms(); | |
| 772 | let timestamp = rfc3339(now); | |
| 773 | let seconds = i64::from(a.seconds); | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 774 | // On the workspace's own machine: its minutes go on usage, at $0, |
| 775 | // and whatever was reserved for it is given back. | |
| 776 | if a.self_hosted { | |
| 777 | let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds)); | |
| 778 | self.db | |
| 779 | .prepare( | |
| 780 | "INSERT INTO ledger | |
| 781 | (id, workspace, kind, amount_micros, description, repo, task, | |
| 782 | cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros) | |
| 783 | VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0)", | |
| 784 | ) | |
| 785 | .bind(&[ | |
| 786 | new_id("led", now).into(), | |
| 787 | workspace.as_str().into(), | |
| 788 | description.as_str().into(), | |
| 789 | optional(a.repo.as_deref()), | |
| 790 | a.reference.as_str().into(), | |
| 791 | timestamp.as_str().into(), | |
| 792 | ])? | |
| 793 | .run() | |
| 794 | .await?; | |
| 795 | if let Some(reservation) = &a.reservation_id { | |
| 796 | self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?; | |
| 797 | } | |
| 798 | return Ok(Outcome::Ok(true)); | |
| 799 | } | |
| Prices are what g1t pays plus 20%, from the first second | 800 | // From the price book, which follows what Cloudflare bills g1t. A |
| 801 | // sandbox is the same container as a build, so without a row it is | |
| 802 | // a build second's cost plus the margin. | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 803 | 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 quotas | 804 | let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64; |
| Prices are what g1t pays plus 20%, from the first second | 805 | (cost, Price::price_for(cost, self.margin_percent)) |
| 806 | }); | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 807 | // A larger machine (`runs-on: g1t-4core`): its memory and disk |
| 808 | // cost more each second, and without its own CPU it is priced at | |
| 809 | // its vCPUs as busy as the standard machine's. | |
| 810 | let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named); | |
| 811 | let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb)); | |
| 812 | let price_scale = instance.map_or(1.0, |i| i.price_scale); | |
| 813 | 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 look | 814 | // Its own CPU when the sandbox reports it; otherwise the average. |
| 815 | let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) { | |
| 816 | 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 incidents | 817 | (Some((base, _)), Some((vcpu, _))) => { |
| 818 | Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu)) | |
| 819 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 820 | _ => None, |
| 821 | }, | |
| 822 | None => None, | |
| 823 | }; | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 824 | 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 look | 825 | let (charge, terms_note) = self.charged(&workspace, credits::with_margin(cost, self.margin_percent)).await?; |
| 826 | 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 put | 827 | let drawn = self.draw(&workspace, charge, &credits::month_of(×tamp), &eligible).await?; |
| 828 | let charge = charge - drawn.total(); | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 829 | let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds")); |
| 830 | 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 daily | 831 | // The price versions it was charged at (pricing.rs). |
| 832 | let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] }; | |
| 833 | let mut versions = Vec::new(); | |
| 834 | for meter in meters { | |
| 835 | versions.extend(self.version_now(meter).await?); | |
| 836 | } | |
| 837 | let price_version = versions.join(","); | |
| Every sandbox is metered by the second | 838 | self.db |
| 839 | .batch(vec![ | |
| 840 | self.db | |
| 841 | .prepare( | |
| 842 | "INSERT INTO ledger | |
| 843 | (id, workspace, kind, amount_micros, description, repo, task, | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 844 | cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version) |
| 845 | VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?)", | |
| Every sandbox is metered by the second | 846 | ) |
| 847 | .bind(&[ | |
| 848 | new_id("led", now).into(), | |
| 849 | workspace.as_str().into(), | |
| 850 | (-(charge as f64)).into(), | |
| 851 | description.as_str().into(), | |
| 852 | optional(a.repo.as_deref()), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 853 | (cost as f64).into(), |
| Every sandbox is metered by the second | 854 | a.reference.as_str().into(), |
| 855 | timestamp.as_str().into(), | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 856 | (drawn.credit as f64).into(), |
| 857 | (drawn.trial as f64).into(), | |
| 858 | (drawn.oss as f64).into(), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 859 | (drawn.given as f64).into(), |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 860 | optional(Some(price_version.as_str()).filter(|v| !v.is_empty())), |
| Every sandbox is metered by the second | 861 | ])?, |
| 862 | self.db | |
| 863 | .prepare( | |
| 864 | "INSERT INTO accounts (workspace, balance_micros, created_at) | |
| 865 | VALUES (?1, ?2, ?3) | |
| 866 | ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2", | |
| 867 | ) | |
| 868 | .bind(&[ | |
| 869 | workspace.as_str().into(), | |
| 870 | (-(charge as f64)).into(), | |
| 871 | timestamp.as_str().into(), | |
| 872 | ])?, | |
| 873 | ]) | |
| 874 | .await?; | |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 875 | self.count_spend(&workspace, cost, charge, &drawn).await; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 876 | if let Some(reservation) = &a.reservation_id { |
| 877 | self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?; | |
| 878 | } | |
| Every sandbox is metered by the second | 879 | Ok(Outcome::Ok(true)) |
| 880 | } | |
| 881 | } | |
| 882 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 883 | /// Whether an amount may be prepaid: $25 at the least by card, and from |
| 884 | /// $1,000 by bank transfer. | |
| 885 | pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> { | |
| 886 | let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) }; | |
| 887 | if (min..=max).contains(¢s) { | |
| 888 | return Ok(()); | |
| 889 | } | |
| 890 | Err(if bank_transfer { | |
| 891 | format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100)) | |
| 892 | } else { | |
| 893 | format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100)) | |
| 894 | }) | |
| 895 | } | |
| 896 | ||
| 897 | /// `10,000` for 10000. | |
| 898 | fn group(n: u32) -> String { | |
| 899 | let digits = n.to_string(); | |
| 900 | let mut out = String::new(); | |
| 901 | 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 kept | 902 | 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 look | 903 | out.push(','); |
| 904 | } | |
| 905 | out.push(c); | |
| 906 | } | |
| 907 | out | |
| 908 | } | |
| 909 | ||
| 910 | #[cfg(test)] | |
| Prices are what g1t pays plus 20%, from the first second | 911 | /// What `seconds` of sandbox time are charged at `price_per_second`, in |
| 912 | /// millionths of a dollar: every second, rounded up to the next millionth. | |
| 913 | fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 { | |
| 914 | (seconds as f64 * price_per_second).ceil() as i64 | |
| Every sandbox is metered by the second | 915 | } |
| 916 | ||
| 917 | /// `1h 2m`, `3m 12s` or `40s`. | |
| 918 | fn duration(seconds: i64) -> String { | |
| 919 | let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60); | |
| 920 | if h > 0 { | |
| 921 | format!("{h}h {m}m") | |
| 922 | } else if m > 0 { | |
| 923 | format!("{m}m {s}s") | |
| 924 | } else { | |
| 925 | format!("{s}s") | |
| 926 | } | |
| 927 | } | |
| 928 | ||
| Billing accounts, terms and enterprises; g1t is no longer free | 929 | impl Billing { |
| 930 | /// What a workspace is charged for something that would be `base`: | |
| 931 | /// nothing while g1t is free, or as its account's terms say. With a | |
| 932 | /// note for the statement when it differs. | |
| 933 | pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String)> { | |
| 934 | if self.free { | |
| 935 | return Ok((0, " (free while g1t is being built out)".to_owned())); | |
| 936 | } | |
| 937 | let terms = self.terms_of(workspace).await?; | |
| 938 | let charge = terms.apply(base); | |
| 939 | let note = match terms.kind { | |
| 940 | TermsKind::Comped => " (comped)".to_owned(), | |
| 941 | TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent), | |
| 942 | _ => String::new(), | |
| 943 | }; | |
| 944 | Ok((charge, note)) | |
| 945 | } | |
| 946 | } | |
| 947 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 948 | fn members_only<T>() -> Outcome<T> { |
| 949 | Outcome::fail( | |
| 950 | FailureCode::Forbidden, | |
| 951 | "Only members can see a workspace's billing.", | |
| 952 | ) | |
| 953 | } | |
| 954 | ||
| Prices keep themselves current with what g1t pays | 955 | impl Billing { |
| 956 | fn from_env(env: &Env) -> Result<Self> { | |
| 957 | Ok(Billing { | |
| 958 | db: env.d1("DB")?, | |
| 959 | stripe: env | |
| 960 | .secret("STRIPE_SECRET_KEY") | |
| 961 | .ok() | |
| 962 | .map(|key| key.to_string()) | |
| 963 | .filter(|key| !key.is_empty()) | |
| 964 | .map(Stripe::new), | |
| Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard | 965 | webhook_secret: env |
| 966 | .secret("STRIPE_WEBHOOK_SECRET") | |
| 967 | .ok() | |
| 968 | .map(|secret| secret.to_string().trim().to_owned()) | |
| 969 | .filter(|secret| !secret.is_empty()), | |
| Prices keep themselves current with what g1t pays | 970 | margin_percent: env |
| 971 | .var("MARGIN_PERCENT") | |
| 972 | .ok() | |
| 973 | .and_then(|percent| percent.to_string().parse().ok()) | |
| 974 | .unwrap_or(20), | |
| 975 | 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 kept | 976 | ceilings: limits::Ceilings::from_env(env), |
| Billing accounts, terms and enterprises; g1t is no longer free | 977 | 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 put | 978 | trials_on: { |
| 979 | let plans = credits::Config::from_env(env); | |
| 980 | plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0 | |
| Prices keep themselves current with what g1t pays | 981 | }, |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 982 | plans: credits::Config::from_env(env), |
| 983 | repos: env.service("REPOS").ok(), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 984 | identity: env.service("IDENTITY").ok(), |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 985 | caps: budget::Caps::from_env(env), |
| 986 | env: env.clone(), | |
| Prices keep themselves current with what g1t pays | 987 | }) |
| 988 | } | |
| 989 | } | |
| 990 | ||
| 991 | #[event(scheduled)] | |
| 992 | async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) { | |
| 993 | let Ok(billing) = Billing::from_env(&env) else { | |
| 994 | return; | |
| 995 | }; | |
| 996 | let keeper = keeper::Keeper::from_env(&env); | |
| 997 | if let Err(error) = billing.settle_runs(&keeper).await { | |
| 998 | worker::console_error!("settling runs failed: {error}"); | |
| 999 | } | |
| Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept | 1000 | // Stripe events billing never received, handled now. |
| 1001 | match billing.replay_events().await { | |
| 1002 | Ok(done) => worker::console_log!("stripe replay: {done}"), | |
| 1003 | Err(error) => worker::console_error!("replaying Stripe events failed: {error}"), | |
| 1004 | } | |
| Billing accounts, terms and enterprises; g1t is no longer free | 1005 | if let Err(error) = billing.autopay().await { |
| 1006 | worker::console_error!("paying at the limit failed: {error}"); | |
| 1007 | } | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 1008 | // Last month's metered usage (scans, embeddings, storage) goes on the |
| 1009 | // ledger before the month is closed and invoiced. | |
| 1010 | if let Err(error) = billing.charge_pending().await { | |
| 1011 | worker::console_error!("charging last month's metered usage failed: {error}"); | |
| 1012 | } | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 1013 | if let Err(error) = billing.close_months().await { |
| 1014 | worker::console_error!("closing the month failed: {error}"); | |
| 1015 | } | |
| Stripe webhooks, enterprise invoices, and sudo for both | 1016 | if let Err(error) = billing.invoice_enterprises().await { |
| 1017 | worker::console_error!("invoicing enterprises failed: {error}"); | |
| 1018 | } | |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 1019 | // Comped budgets' alerts, and a tripped breaker staff were not told of. |
| 1020 | if let Err(error) = billing.watch_spend().await { | |
| 1021 | worker::console_error!("watching g1t's own spend failed: {error}"); | |
| 1022 | } | |
| Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept | 1023 | if let Ok(identity) = env.service("IDENTITY") |
| 1024 | && let Err(error) = billing.warn_limits(&identity).await { | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 1025 | worker::console_error!("warning owners failed: {error}"); |
| 1026 | } | |
| Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept | 1027 | // Once a day: Stripe's endpoint kept listening to billing's events and |
| 1028 | // enabled, and saved cards and plans not read in a while read again. | |
| 1029 | if event.cron() == keeper::DAILY { | |
| Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard | 1030 | 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 kept | 1031 | Ok(done) => worker::console_log!("stripe endpoint: {done}"), |
| 1032 | Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"), | |
| 1033 | } | |
| 1034 | match billing.refresh_from_stripe().await { | |
| 1035 | Ok(done) => worker::console_log!("stripe refresh: {done}"), | |
| 1036 | Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"), | |
| 1037 | } | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 1038 | } |
| The keeper reads Cloudflare as it really answers | 1039 | // Once a day, and at once if the costs were never checked: check every |
| 1040 | // 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 kept | 1041 | if (event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false)) |
| 1042 | && let Err(error) = billing.reconcile(&keeper).await { | |
| Prices keep themselves current with what g1t pays | 1043 | worker::console_error!("checking costs against Cloudflare failed: {error}"); |
| 1044 | } | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 1045 | // Once a day: what Cloudflare charged, reconciled against what g1t |
| 1046 | // counted and charged; prices whose day has come; margin alerts | |
| 1047 | // (margin.rs). After the keeper, so its proposals are in. | |
| 1048 | if event.cron() == keeper::DAILY { | |
| 1049 | match billing.costs_daily(&env, &keeper).await { | |
| 1050 | Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts), | |
| 1051 | Err(error) => worker::console_error!("reconciling costs failed: {error}"), | |
| 1052 | } | |
| 1053 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1054 | // Once a day: what each workspace's private repositories hold, its git |
| 1055 | // operations, Deployments plans from before the g1t plan set to end, | |
| 1056 | // and old reservations cleared. | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 1057 | if event.cron() == keeper::DAILY { |
| 1058 | if let Err(error) = billing.measure_storage().await { | |
| 1059 | worker::console_error!("measuring storage failed: {error}"); | |
| 1060 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1061 | if let Err(error) = billing.measure_git().await { |
| 1062 | worker::console_error!("measuring git operations failed: {error}"); | |
| 1063 | } | |
| 1064 | if let Err(error) = billing.retire_deployments_plans().await { | |
| 1065 | worker::console_error!("ending Deployments plans failed: {error}"); | |
| 1066 | } | |
| 1067 | if let Err(error) = billing.sweep_reservations().await { | |
| 1068 | worker::console_error!("clearing reservations failed: {error}"); | |
| 1069 | } | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 1070 | } |
| Prices keep themselves current with what g1t pays | 1071 | } |
| 1072 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 1073 | /// Events from the bus, on billing's own queue: only a workspace's rename |
| 1074 | /// matters here (see `rename`). | |
| 1075 | #[event(queue)] | |
| 1076 | async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> { | |
| 1077 | let billing = Billing::from_env(&env)?; | |
| 1078 | let identity = env.service("IDENTITY").ok(); | |
| 1079 | for message in batch.messages()? { | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1080 | // A repository transferred: its share of the open-source pool this |
| 1081 | // month follows it. What it was charged stays with the workspace | |
| 1082 | // it was charged to; usage from now on is charged to the new one. | |
| 1083 | if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? { | |
| 1084 | message.ack(); | |
| 1085 | continue; | |
| 1086 | } | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 1087 | billing.on_event(identity.as_ref(), message.body()).await?; |
| 1088 | message.ack(); | |
| 1089 | } | |
| 1090 | Ok(()) | |
| 1091 | } | |
| 1092 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1093 | #[event(fetch)] |
| 1094 | async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> { | |
| 1095 | let Some(method) = rpc_method(&request) else { | |
| 1096 | return Response::error("Not found", 404); | |
| 1097 | }; | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 1098 | // A replica near the caller when it asks for one (crates/kit/src/d1.rs); |
| 1099 | // what other services call (can_start, start_run) asks for none. | |
| 1100 | let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1101 | let body: serde_json::Value = request.json().await?; |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 1102 | let mut billing = Billing::from_env(&env)?; |
| 1103 | billing.db = db; | |
| 1104 | let answered = match method.as_str() { | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1105 | "status" => reply(&billing.status()), |
| 1106 | "account" => reply(&billing.account(args(body)?).await?), | |
| 1107 | "ledger" => reply(&billing.ledger(args(body)?).await?), | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 1108 | "usage" => reply(&billing.usage(args(body)?).await?), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1109 | "checkout" => reply(&billing.checkout(args(body)?).await?), |
| 1110 | "confirm" => reply(&billing.confirm(args(body)?).await?), | |
| 1111 | "can_start" => reply(&billing.can_start(args(body)?).await?), | |
| A free allowance on g1t's models, so anyone can try its agents | 1112 | "trial" => reply(&billing.trial(args(body)?).await?), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1113 | "start_run" => reply(&billing.start_run(args(body)?).await?), |
| 1114 | "finish_run" => reply(&billing.finish_run(args(body)?).await?), | |
| Paid features: a workspace turns on Deployments with a monthly plan | 1115 | "features" => reply(&billing.features(args(body)?).await?), |
| 1116 | "subscribe" => reply(&billing.subscribe(args(body)?).await?), | |
| 1117 | "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?), | |
| 1118 | "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1119 | "close_workspace" => reply(&billing.close_workspace(args(body)?).await?), |
| Paid features: a workspace turns on Deployments with a monthly plan | 1120 | "has_feature" => reply(&billing.has_feature(args(body)?).await?), |
| 1121 | "charge_feature" => reply(&billing.charge_feature(args(body)?).await?), | |
| Every sandbox is metered by the second | 1122 | "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?), |
| Usage limits: unpaid usage can only go so far | 1123 | "limit" => reply(&billing.limit(args(body)?).await?), |
| 1124 | "check_limit" => reply(&billing.check_limit(args(body)?).await?), | |
| 1125 | "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?), | |
| Prices keep themselves current with what g1t pays | 1126 | "prices" => reply(&billing.prices().await?), |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 1127 | "billing_portal" => reply(&billing.billing_portal(args(body)?).await?), |
| 1128 | "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?), | |
| Stripe webhooks, enterprise invoices, and sudo for both | 1129 | "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?), |
| 1130 | "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?), | |
| 1131 | "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?), | |
| 1132 | "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?), | |
| Two limits, real invoices, trust that grows by itself, sales signals | 1133 | "invoices" => reply(&billing.invoices(args(body)?).await?), |
| The statement is a month at a time, a line per kind of charge | 1134 | "statement" => reply(&billing.statement(args(body)?).await?), |
| 1135 | "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 quotas | 1136 | "usage_meters" => reply(&billing.usage_meters(args(body)?).await?), |
| Two limits, real invoices, trust that grows by itself, sales signals | 1137 | "admin_workspace_invoices" => { |
| 1138 | let a: AdminWorkspaceInvoicesArgs = args(body)?; | |
| 1139 | reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?) | |
| 1140 | } | |
| 1141 | "admin_signals" => reply(&billing.admin_signals(args(body)?).await?), | |
| 1142 | "admin_overview" => reply(&billing.admin_overview(args(body)?).await?), | |
| 1143 | "admin_sales" => reply(&billing.admin_sales(args(body)?).await?), | |
| 1144 | "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?), | |
| 1145 | "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?), | |
| Billing lists every invoice and every staff change; signals carry follow-ups | 1146 | "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?), |
| 1147 | "admin_audit" => reply(&billing.admin_audit(args(body)?).await?), | |
| Prices keep themselves current with what g1t pays | 1148 | "note_pending" => reply(&billing.note_pending(args(body)?).await?), |
| Billing accounts, terms and enterprises; g1t is no longer free | 1149 | "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?), |
| 1150 | "admin_account" => reply(&billing.admin_account(args(body)?).await?), | |
| 1151 | "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?), | |
| 1152 | "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?), | |
| 1153 | "admin_attach" => reply(&billing.admin_attach(args(body)?).await?), | |
| 1154 | "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 put | 1155 | "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?), |
| 1156 | "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 sudo | 1157 | "audit_retention" => reply(&billing.audit_retention(args(body)?).await?), |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1158 | "reserve" => reply(&billing.reserve(args(body)?).await?), |
| 1159 | "settle" => reply(&billing.settle_reservation(args(body)?).await?), | |
| 1160 | "card_check" => reply(&billing.card_check(args(body)?).await?), | |
| 1161 | "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?), | |
| 1162 | "request_limit" => reply(&billing.request_limit(args(body)?).await?), | |
| 1163 | "limit_requests" => reply(&billing.limit_requests(args(body)?).await?), | |
| 1164 | "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?), | |
| 1165 | "set_caps" => reply(&billing.set_caps(args(body)?).await?), | |
| 1166 | "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?), | |
| 1167 | "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?), | |
| 1168 | "admin_overages" => reply(&billing.admin_overages(args(body)?).await?), | |
| 1169 | "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?), | |
| 1170 | "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?), | |
| 1171 | "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 daily | 1172 | "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?), |
| 1173 | "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 pays | 1174 | "admin_spend_caps" => reply(&billing.spend_caps().await?), |
| 1175 | "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 daily | 1176 | "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?), |
| 1177 | "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?), | |
| 1178 | "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?), | |
| 1179 | "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1180 | _ => Response::error("Unknown method", 404), |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 1181 | }; |
| 1182 | served.finish(answered) | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1183 | } |
| 1184 | ||
| 1185 | #[cfg(test)] | |
| 1186 | mod tests { | |
| 1187 | use super::*; | |
| 1188 | ||
| 1189 | #[test] | |
| 1190 | fn a_run_is_charged_its_cost_plus_the_margin() { | |
| 1191 | // $0.05 at 20% is six cents. | |
| 1192 | assert_eq!(charge_micros(0.05, 20), 60_000); | |
| 1193 | assert_eq!(charge_micros(1.0, 20), 1_200_000); | |
| 1194 | assert_eq!(charge_micros(0.05, 0), 50_000); | |
| 1195 | } | |
| 1196 | ||
| 1197 | #[test] | |
| 1198 | fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() { | |
| 1199 | assert_eq!(charge_micros(0.000_000_4, 20), 2); | |
| 1200 | assert_eq!(charge_micros(0.0, 20), 0); | |
| 1201 | assert_eq!(charge_micros(-3.0, 20), 0); | |
| 1202 | } | |
| 1203 | ||
| 1204 | #[test] | |
| Prices are what g1t pays plus 20%, from the first second | 1205 | fn sandbox_time_is_charged_from_the_first_second() { |
| 1206 | // 21 millionths a second at cost, plus 20%. | |
| 1207 | let price = Price::price_for(21.0, 20); | |
| 1208 | assert_eq!(sandbox_charge(1, price), 26); | |
| 1209 | assert_eq!(sandbox_charge(60, price), 1_512); | |
| 1210 | assert_eq!(sandbox_charge(0, price), 0); | |
| Every sandbox is metered by the second | 1211 | } |
| 1212 | ||
| 1213 | #[test] | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1214 | fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() { |
| 1215 | assert!(prepay_amount(2_500, false).is_ok()); | |
| 1216 | assert!(prepay_amount(2_499, false).is_err()); | |
| 1217 | assert!(prepay_amount(10_000, false).is_ok()); | |
| 1218 | assert!(prepay_amount(1_000_000, false).is_ok()); | |
| 1219 | 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."); | |
| 1220 | assert!(prepay_amount(99_999, true).is_err()); | |
| 1221 | assert!(prepay_amount(100_000, true).is_ok()); | |
| 1222 | } | |
| 1223 | ||
| 1224 | #[test] | |
| Every sandbox is metered by the second | 1225 | fn durations_read_plainly() { |
| 1226 | assert_eq!(duration(40), "40s"); | |
| 1227 | assert_eq!(duration(192), "3m 12s"); | |
| 1228 | assert_eq!(duration(3720), "1h 2m"); | |
| 1229 | } | |
| 1230 | ||
| 1231 | #[test] | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1232 | fn an_absurd_cost_is_capped() { |
| 1233 | assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR); | |
| 1234 | } | |
| 1235 | } |