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