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