| 1 | //! The billing service: what g1t's compute costs, charged to the workspace |
| 2 | //! it ran for at what g1t pays plus 20%. |
| 3 | //! |
| 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. |
| 13 | //! |
| 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 | |
| 20 | mod accounts; |
| 21 | mod ai; |
| 22 | mod budget; |
| 23 | mod cards; |
| 24 | mod closing; |
| 25 | mod compute; |
| 26 | mod costs; |
| 27 | mod margin; |
| 28 | mod pricing; |
| 29 | mod report; |
| 30 | mod details; |
| 31 | mod credits; |
| 32 | mod grants; |
| 33 | mod overages; |
| 34 | mod requests; |
| 35 | mod storage; |
| 36 | mod invoices; |
| 37 | mod sales; |
| 38 | mod statement; |
| 39 | mod webhooks; |
| 40 | mod features; |
| 41 | mod gateway; |
| 42 | mod keeper; |
| 43 | mod limits; |
| 44 | mod rename; |
| 45 | mod reset; |
| 46 | mod retention; |
| 47 | mod stripe; |
| 48 | mod stripe_sync; |
| 49 | mod subscriptions; |
| 50 | mod tax; |
| 51 | mod tokens; |
| 52 | |
| 53 | use g1t_contracts::billing::*; |
| 54 | use g1t_contracts::time::rfc3339; |
| 55 | use g1t_contracts::{FailureCode, Outcome, Role, new_id}; |
| 56 | use g1t_kit::{args, now_ms, reply, rpc_method}; |
| 57 | use serde::Deserialize; |
| 58 | use sha2::{Digest, Sha256}; |
| 59 | use worker::wasm_bindgen::JsValue; |
| 60 | use worker::{Context, D1Database, Env, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event}; |
| 61 | use futures_util::future::{try_join, try_join5}; |
| 62 | |
| 63 | use stripe::Stripe; |
| 64 | |
| 65 | /// Prepaying: $25 at the least; by card up to $10,000 at a time, and by |
| 66 | /// bank transfer from $1,000 to $100,000. |
| 67 | const MIN_TOP_UP_CENTS: u32 = 2_500; |
| 68 | const MAX_TOP_UP_CENTS: u32 = 1_000_000; |
| 69 | const MIN_BANK_TRANSFER_CENTS: u32 = 100_000; |
| 70 | const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000; |
| 71 | const LEDGER_PAGE: u32 = 100; |
| 72 | /// A run's reported cost is believed up to this much. A sandbox cannot |
| 73 | /// spend more in the time it has, so anything above is a fault. |
| 74 | const MAX_RUN_COST_USD: f64 = 100.0; |
| 75 | |
| 76 | /// What a run is charged: its cost plus the margin, rounded up to a whole |
| 77 | /// millionth of a dollar. |
| 78 | pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 { |
| 79 | let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil(); |
| 80 | (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64 |
| 81 | } |
| 82 | |
| 83 | /// What a cost g1t trusts (the price book's, or what AI Gateway priced a |
| 84 | /// run at) is charged at: plus the margin, rounded up to a whole millionth. |
| 85 | /// Unlike `charge_micros`, never capped: only a sandbox's own report is |
| 86 | /// held to `MAX_RUN_COST_USD`, so a run that really cost more is charged |
| 87 | /// for all of it once it is settled. |
| 88 | pub fn margin_on(cost_micros: i64, margin_percent: u32) -> i64 { |
| 89 | let cost = i128::from(cost_micros.max(0)); |
| 90 | let charge = (cost * i128::from(100 + margin_percent) + 99) / 100; |
| 91 | i64::try_from(charge).unwrap_or(i64::MAX) |
| 92 | } |
| 93 | |
| 94 | fn hash(token: &str) -> String { |
| 95 | hex::encode(Sha256::digest(token.as_bytes())) |
| 96 | } |
| 97 | |
| 98 | fn optional(value: Option<&str>) -> JsValue { |
| 99 | value.map_or(JsValue::NULL, JsValue::from) |
| 100 | } |
| 101 | |
| 102 | #[derive(Deserialize)] |
| 103 | struct AccountRow { |
| 104 | balance_micros: i64, |
| 105 | customer_id: Option<String>, |
| 106 | } |
| 107 | |
| 108 | #[derive(Deserialize)] |
| 109 | struct LedgerRow { |
| 110 | id: String, |
| 111 | kind: EntryKind, |
| 112 | amount_micros: i64, |
| 113 | description: String, |
| 114 | repo: Option<String>, |
| 115 | number: Option<u32>, |
| 116 | task: Option<String>, |
| 117 | model: Option<String>, |
| 118 | created_by: Option<String>, |
| 119 | created_at: String, |
| 120 | billed_to: Option<String>, |
| 121 | #[serde(default)] |
| 122 | workspace: Option<String>, |
| 123 | #[serde(default)] |
| 124 | credit_micros: Option<i64>, |
| 125 | #[serde(default)] |
| 126 | trial_micros: Option<i64>, |
| 127 | #[serde(default)] |
| 128 | oss_micros: Option<i64>, |
| 129 | #[serde(default)] |
| 130 | given_micros: Option<i64>, |
| 131 | #[serde(default)] |
| 132 | credit_kind: Option<String>, |
| 133 | #[serde(default)] |
| 134 | discount_micros: Option<i64>, |
| 135 | } |
| 136 | |
| 137 | impl From<LedgerRow> for LedgerEntry { |
| 138 | fn from(row: LedgerRow) -> Self { |
| 139 | LedgerEntry { |
| 140 | id: row.id, |
| 141 | kind: row.kind, |
| 142 | amount_micros: row.amount_micros, |
| 143 | description: row.description, |
| 144 | repo: row.repo, |
| 145 | number: row.number, |
| 146 | task: row.task, |
| 147 | model: row.model, |
| 148 | billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()), |
| 149 | created_by: row.created_by, |
| 150 | created_at: row.created_at, |
| 151 | workspace: row.workspace, |
| 152 | credit_micros: row.credit_micros.unwrap_or(0), |
| 153 | trial_micros: row.trial_micros.unwrap_or(0), |
| 154 | oss_micros: row.oss_micros.unwrap_or(0), |
| 155 | given_micros: row.given_micros.unwrap_or(0), |
| 156 | credit_kind: row.credit_kind.as_deref().and_then(CreditKind::parse), |
| 157 | discount_micros: row.discount_micros.unwrap_or(0), |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | #[derive(Clone, Deserialize)] |
| 163 | struct RunRow { |
| 164 | workspace: String, |
| 165 | repo: String, |
| 166 | number: u32, |
| 167 | task: String, |
| 168 | model: String, |
| 169 | token_hash: String, |
| 170 | billed_to: Option<String>, |
| 171 | } |
| 172 | |
| 173 | impl RunRow { |
| 174 | fn own_provider(&self) -> bool { |
| 175 | self.billed_to.as_deref() == Some("workspace") |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | #[derive(Deserialize)] |
| 180 | struct CheckoutRow { |
| 181 | workspace: String, |
| 182 | created_by: String, |
| 183 | #[serde(default)] |
| 184 | fee_cents: Option<u32>, |
| 185 | } |
| 186 | |
| 187 | /// A payment page started, as `checkouts` keeps it. |
| 188 | pub(crate) struct NewCheckout<'a> { |
| 189 | pub id: &'a str, |
| 190 | pub workspace: &'a str, |
| 191 | /// What it pays for, in cents: the prepayment, the plan's price, the AI |
| 192 | /// credit; 0 for a card check. |
| 193 | pub amount_cents: u32, |
| 194 | /// The card fee on top, for AI credit. |
| 195 | pub fee_cents: u32, |
| 196 | pub created_by: &'a str, |
| 197 | /// None for a prepayment; `plan`, `security`, `card_check` or |
| 198 | /// `ai_credit` otherwise. |
| 199 | pub feature: Option<&'a str>, |
| 200 | } |
| 201 | |
| 202 | /// The one insert every payment page goes through, every column named, so |
| 203 | /// a column added to `checkouts` with no default is caught by |
| 204 | /// `tests::every_checkout_insert_fills_the_table` rather than by a 500. |
| 205 | pub(crate) const CHECKOUT_INSERT: &str = "INSERT INTO checkouts (id, workspace, amount_cents, fee_cents, created_by, created_at, feature, status) |
| 206 | VALUES (?, ?, ?, ?, ?, ?, ?, 'open')"; |
| 207 | |
| 208 | impl Billing { |
| 209 | pub(crate) async fn record_checkout(&self, c: &NewCheckout<'_>) -> Result<()> { |
| 210 | self.db |
| 211 | .prepare(CHECKOUT_INSERT) |
| 212 | .bind(&[ |
| 213 | c.id.into(), |
| 214 | c.workspace.into(), |
| 215 | c.amount_cents.into(), |
| 216 | c.fee_cents.into(), |
| 217 | c.created_by.into(), |
| 218 | rfc3339(now_ms()).into(), |
| 219 | optional(c.feature), |
| 220 | ])? |
| 221 | .run() |
| 222 | .await?; |
| 223 | Ok(()) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// A row an `UPDATE … RETURNING` touched. |
| 228 | #[derive(Deserialize)] |
| 229 | struct Touched { |
| 230 | #[allow(dead_code)] |
| 231 | id: String, |
| 232 | } |
| 233 | |
| 234 | struct Billing { |
| 235 | db: D1Database, |
| 236 | /// Absent when no card processor is configured. |
| 237 | stripe: Option<Stripe>, |
| 238 | /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`); |
| 239 | /// without it no event is believed. |
| 240 | webhook_secret: Option<String>, |
| 241 | margin_percent: u32, |
| 242 | /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`). |
| 243 | free: bool, |
| 244 | /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS` |
| 245 | /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero). |
| 246 | trials_on: bool, |
| 247 | /// The plans' and pools' numbers; see `credits`. |
| 248 | plans: credits::Config, |
| 249 | /// The repos service: which repositories are public, what private ones |
| 250 | /// hold, and their git operations. Absent where it is not bound. |
| 251 | repos: Option<worker::Fetcher>, |
| 252 | /// The packages service: what each workspace's packages hold. |
| 253 | packages: Option<worker::Fetcher>, |
| 254 | /// The identity service, which emails owners. Absent where it is not |
| 255 | /// bound. |
| 256 | identity: Option<worker::Fetcher>, |
| 257 | /// How far unpaid usage may go; see `limits`. |
| 258 | ceilings: limits::Ceilings, |
| 259 | /// `PREPAID_ONLY`: the old rule, that agents need credit first. |
| 260 | prepaid_only: bool, |
| 261 | /// The caps on what g1t pays for itself; see `budget`. |
| 262 | caps: budget::Caps, |
| 263 | /// The worker's bindings, for emailing staff (`EMAIL`). |
| 264 | env: Env, |
| 265 | } |
| 266 | |
| 267 | impl Billing { |
| 268 | fn status(&self) -> Status { |
| 269 | Status { |
| 270 | enabled: self.stripe.is_some(), |
| 271 | live: self.stripe.as_ref().is_some_and(Stripe::live), |
| 272 | free: self.free, |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> { |
| 277 | self.db |
| 278 | .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?") |
| 279 | .bind(&[workspace.into()])? |
| 280 | .first::<AccountRow>(None) |
| 281 | .await |
| 282 | } |
| 283 | |
| 284 | async fn standing(&self, workspace: &str) -> Result<Account> { |
| 285 | // The card as last synced (stripe_sync.rs), not asked of Stripe. |
| 286 | let (row, card) = try_join(self.row(workspace), self.saved_card(workspace)).await?; |
| 287 | Ok(Account { |
| 288 | workspace: workspace.to_owned(), |
| 289 | balance_micros: row.map_or(0, |row| row.balance_micros), |
| 290 | status: self.status(), |
| 291 | margin_percent: self.margin_percent, |
| 292 | card, |
| 293 | }) |
| 294 | } |
| 295 | |
| 296 | /// The workspace's customer at Stripe, made the first time one is needed. |
| 297 | pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> { |
| 298 | let Some(stripe) = &self.stripe else { |
| 299 | return Err(worker::Error::RustError("payments are not set up".into())); |
| 300 | }; |
| 301 | if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) { |
| 302 | return Ok(customer); |
| 303 | } |
| 304 | let customer = stripe.create_customer(workspace).await?; |
| 305 | self.db |
| 306 | .prepare( |
| 307 | "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3) |
| 308 | ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2", |
| 309 | ) |
| 310 | .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])? |
| 311 | .run() |
| 312 | .await?; |
| 313 | Ok(customer) |
| 314 | } |
| 315 | |
| 316 | /// Stripe's hosted billing page for the workspace. Owners only. |
| 317 | async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> { |
| 318 | let workspace = a.workspace.to_lowercase(); |
| 319 | if a.actor.role_in(&workspace) != Some(Role::Owner) { |
| 320 | return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing.")); |
| 321 | } |
| 322 | let Some(stripe) = &self.stripe else { |
| 323 | return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t.")); |
| 324 | }; |
| 325 | let customer = match self.customer_for(&workspace).await { |
| 326 | Ok(customer) => customer, |
| 327 | Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))), |
| 328 | }; |
| 329 | match stripe.portal_session(&customer, &a.return_url).await { |
| 330 | Ok(url) => Ok(Outcome::Ok(Checkout { url })), |
| 331 | Err(error) if stripe::is_missing(&error) => { |
| 332 | // The customer was removed at Stripe: a new one next time. |
| 333 | self.forget_customer(&workspace).await?; |
| 334 | Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again.")) |
| 335 | } |
| 336 | Err(error) => Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))), |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | /// Adds a ledger entry and moves the balance by the same amount, as |
| 341 | /// one write. |
| 342 | #[allow(clippy::too_many_arguments)] |
| 343 | async fn enter( |
| 344 | &self, |
| 345 | workspace: &str, |
| 346 | kind: EntryKind, |
| 347 | amount_micros: i64, |
| 348 | description: &str, |
| 349 | reference: &str, |
| 350 | run: Option<&RunRow>, |
| 351 | cost_micros: Option<i64>, |
| 352 | created_by: Option<&str>, |
| 353 | customer: Option<&str>, |
| 354 | ) -> Result<()> { |
| 355 | let now = now_ms(); |
| 356 | let timestamp = rfc3339(now); |
| 357 | let kind = match kind { |
| 358 | EntryKind::TopUp => "top_up", |
| 359 | EntryKind::Usage => "usage", |
| 360 | }; |
| 361 | self.db |
| 362 | .batch(vec![ |
| 363 | self.db |
| 364 | .prepare( |
| 365 | "INSERT INTO ledger |
| 366 | (id, workspace, kind, amount_micros, description, repo, number, task, |
| 367 | model, cost_micros, reference, created_by, created_at, billed_to) |
| 368 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 369 | ) |
| 370 | .bind(&[ |
| 371 | new_id("led", now).into(), |
| 372 | workspace.into(), |
| 373 | kind.into(), |
| 374 | // D1 takes numbers as doubles, which hold every |
| 375 | // amount this service will see exactly. |
| 376 | (amount_micros as f64).into(), |
| 377 | description.into(), |
| 378 | optional(run.map(|run| run.repo.as_str())), |
| 379 | run.map_or(JsValue::NULL, |run| run.number.into()), |
| 380 | optional(run.map(|run| run.task.as_str())), |
| 381 | optional(run.map(|run| run.model.as_str())), |
| 382 | cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()), |
| 383 | reference.into(), |
| 384 | optional(created_by), |
| 385 | timestamp.as_str().into(), |
| 386 | run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(), |
| 387 | ])?, |
| 388 | self.db |
| 389 | .prepare( |
| 390 | "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) |
| 391 | VALUES (?1, ?2, ?3, ?4) |
| 392 | ON CONFLICT (workspace) DO UPDATE SET |
| 393 | balance_micros = balance_micros + ?2, |
| 394 | customer_id = COALESCE(?3, customer_id)", |
| 395 | ) |
| 396 | .bind(&[ |
| 397 | workspace.into(), |
| 398 | (amount_micros as f64).into(), |
| 399 | optional(customer), |
| 400 | timestamp.as_str().into(), |
| 401 | ])?, |
| 402 | ]) |
| 403 | .await?; |
| 404 | // Money in clears a card declined at the limit. A refund or a lost |
| 405 | // dispute is a top-up of less than nothing: money out, which never |
| 406 | // clears it. |
| 407 | if kind == "top_up" && amount_micros > 0 { |
| 408 | self.db |
| 409 | .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?") |
| 410 | .bind(&[workspace.into()])? |
| 411 | .run() |
| 412 | .await?; |
| 413 | } |
| 414 | Ok(()) |
| 415 | } |
| 416 | |
| 417 | async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> { |
| 418 | let workspace = a.workspace.to_lowercase(); |
| 419 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { |
| 420 | return Ok(members_only()); |
| 421 | } |
| 422 | Ok(Outcome::Ok(self.standing(&workspace).await?)) |
| 423 | } |
| 424 | |
| 425 | async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> { |
| 426 | let workspace = a.workspace.to_lowercase(); |
| 427 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { |
| 428 | return Ok(members_only()); |
| 429 | } |
| 430 | let rows = self |
| 431 | .db |
| 432 | .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?") |
| 433 | .bind(&[workspace.into(), LEDGER_PAGE.into()])? |
| 434 | .all() |
| 435 | .await? |
| 436 | .results::<LedgerRow>()?; |
| 437 | Ok(Outcome::Ok( |
| 438 | rows.into_iter().map(LedgerEntry::from).collect(), |
| 439 | )) |
| 440 | } |
| 441 | |
| 442 | async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> { |
| 443 | let workspace = a.workspace.to_lowercase(); |
| 444 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { |
| 445 | return Ok(members_only()); |
| 446 | } |
| 447 | #[derive(serde::Deserialize)] |
| 448 | struct SliceRow { |
| 449 | key: Option<String>, |
| 450 | micros: Option<i64>, |
| 451 | runs: Option<u32>, |
| 452 | } |
| 453 | // While g1t is free, what was used at cost is what there is to show. |
| 454 | // With a discount, usage at its price, so a 100% discount still |
| 455 | // shows what the workspace would pay. |
| 456 | // Every slice measures usage at price (statement::PRICE_SQL), the one |
| 457 | // figure every page shows as usage, whatever paid for it. |
| 458 | let discount_percent = self.terms_of(&workspace).await?.percent_off(); |
| 459 | let measure = if self.free { "COALESCE(cost_micros, 0)" } else { crate::statement::PRICE_SQL }; |
| 460 | let slices = |key: &str, limit: u32| { |
| 461 | format!( |
| 462 | "SELECT {key} AS key, SUM({measure}) AS micros, COUNT(*) AS runs FROM ledger |
| 463 | WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2 |
| 464 | GROUP BY 1 ORDER BY micros DESC LIMIT {limit}" |
| 465 | ) |
| 466 | }; |
| 467 | let query = |sql: String| { |
| 468 | let db = &self.db; |
| 469 | let workspace = workspace.clone(); |
| 470 | let since = a.since.clone(); |
| 471 | async move { |
| 472 | let rows = db |
| 473 | .prepare(sql) |
| 474 | .bind(&[workspace.into(), since.into()])? |
| 475 | .all() |
| 476 | .await? |
| 477 | .results::<SliceRow>()?; |
| 478 | Ok::<Vec<UsageSlice>, worker::Error>( |
| 479 | rows.into_iter() |
| 480 | .map(|row| UsageSlice { |
| 481 | key: row.key.unwrap_or_else(|| "other".to_owned()), |
| 482 | micros: row.micros.unwrap_or_default(), |
| 483 | runs: row.runs.unwrap_or_default(), |
| 484 | }) |
| 485 | .collect(), |
| 486 | ) |
| 487 | } |
| 488 | }; |
| 489 | #[derive(serde::Deserialize)] |
| 490 | struct Totals { |
| 491 | spent: Option<i64>, |
| 492 | cost: Option<i64>, |
| 493 | provider: Option<i64>, |
| 494 | runs: Option<u32>, |
| 495 | added: Option<i64>, |
| 496 | discount: Option<i64>, |
| 497 | covered: Option<i64>, |
| 498 | price: Option<i64>, |
| 499 | } |
| 500 | let totals = async { |
| 501 | self.db |
| 502 | .prepare(format!( |
| 503 | "SELECT |
| 504 | -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent, |
| 505 | SUM(CASE WHEN kind = 'usage' THEN COALESCE(credit_micros, 0) + COALESCE(trial_micros, 0) |
| 506 | + COALESCE(oss_micros, 0) + COALESCE(given_micros, 0) END) AS covered, |
| 507 | SUM(CASE WHEN kind = 'usage' THEN {price} END) AS price,", |
| 508 | price = crate::statement::PRICE_SQL |
| 509 | ) + " |
| 510 | SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost, |
| 511 | SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider, |
| 512 | SUM(CASE WHEN kind = 'usage' AND " + crate::statement::RUN_SQL + " THEN 1 ELSE 0 END) AS runs, |
| 513 | SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added, |
| 514 | SUM(CASE WHEN kind = 'usage' THEN discount_micros END) AS discount |
| 515 | FROM ledger WHERE workspace = ?1 AND created_at >= ?2", |
| 516 | ) |
| 517 | .bind(&[workspace.as_str().into(), a.since.as_str().into()])? |
| 518 | .first::<Totals>(None) |
| 519 | .await |
| 520 | }; |
| 521 | // The totals and the five slices read the same rows independently, |
| 522 | // so they go to D1 at once: one round trip of waiting, not six. |
| 523 | let (totals, (by_day, by_task, by_repo, by_pull, by_model)) = try_join( |
| 524 | totals, |
| 525 | try_join5( |
| 526 | query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)), |
| 527 | query(slices("task", 20)), |
| 528 | query(slices("repo", 20)), |
| 529 | query(slices("repo || '#' || number", 10)), |
| 530 | query(slices("model", 10)), |
| 531 | ), |
| 532 | ) |
| 533 | .await?; |
| 534 | let totals = totals.unwrap_or(Totals { |
| 535 | spent: None, |
| 536 | cost: None, |
| 537 | provider: None, |
| 538 | runs: None, |
| 539 | added: None, |
| 540 | discount: None, |
| 541 | covered: None, |
| 542 | price: None, |
| 543 | }); |
| 544 | Ok(Outcome::Ok(Usage { |
| 545 | spent_micros: totals.spent.unwrap_or_default(), |
| 546 | // What the included usage, the trial, a pool or g1t paid, as the |
| 547 | // entries record it. |
| 548 | covered_micros: totals.covered.unwrap_or_default(), |
| 549 | price_micros: if self.free { totals.cost.unwrap_or_default() } else { totals.price.unwrap_or_default() }, |
| 550 | cost_micros: totals.cost.unwrap_or_default(), |
| 551 | provider_micros: totals.provider.unwrap_or_default(), |
| 552 | used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(), |
| 553 | free: self.free, |
| 554 | discount_micros: totals.discount.unwrap_or_default(), |
| 555 | discount_percent: (discount_percent > 0).then_some(discount_percent), |
| 556 | runs: totals.runs.unwrap_or_default(), |
| 557 | added_micros: totals.added.unwrap_or_default(), |
| 558 | by_day, |
| 559 | by_task, |
| 560 | by_repo, |
| 561 | by_pull, |
| 562 | by_model, |
| 563 | since: a.since, |
| 564 | })) |
| 565 | } |
| 566 | |
| 567 | /// `checkout`: prepays usage, by card or (from $1,000) bank transfer. |
| 568 | async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> { |
| 569 | let workspace = a.workspace.to_lowercase(); |
| 570 | if a.actor.role_in(&workspace) != Some(Role::Owner) { |
| 571 | return Ok(Outcome::fail( |
| 572 | FailureCode::Forbidden, |
| 573 | "Only an owner can prepay for a workspace.", |
| 574 | )); |
| 575 | } |
| 576 | let Some(stripe) = &self.stripe else { |
| 577 | return Ok(Outcome::fail( |
| 578 | FailureCode::Conflict, |
| 579 | "Payments are not set up on this g1t yet.", |
| 580 | )); |
| 581 | }; |
| 582 | let bank_transfer = a.method.as_deref() == Some("bank_transfer"); |
| 583 | if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) { |
| 584 | return Ok(Outcome::fail(FailureCode::Invalid, why)); |
| 585 | } |
| 586 | // A bank transfer needs a customer for its account details. |
| 587 | let customer = if bank_transfer { |
| 588 | match self.customer_for(&workspace).await { |
| 589 | Ok(customer) => Some(customer), |
| 590 | Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, stripe::friendly(&error))), |
| 591 | } |
| 592 | } else { |
| 593 | self.row(&workspace).await?.and_then(|row| row.customer_id) |
| 594 | }; |
| 595 | // By card, Stripe's fee is its own line; a bank transfer has none. |
| 596 | let fee = if bank_transfer { 0 } else { self.card_fee_on(i64::from(a.amount_cents)).await? as u32 }; |
| 597 | let started = match stripe.start_checkout(&workspace, a.amount_cents, fee, customer.as_deref(), &a.return_url, bank_transfer).await { |
| 598 | // A customer saved under another Stripe account: start afresh. |
| 599 | Err(error) if customer.is_some() && stripe::is_missing(&error) => { |
| 600 | self.forget_customer(&workspace).await?; |
| 601 | let customer = if bank_transfer { self.customer_for(&workspace).await.ok() } else { None }; |
| 602 | stripe.start_checkout(&workspace, a.amount_cents, fee, customer.as_deref(), &a.return_url, bank_transfer).await |
| 603 | } |
| 604 | other => other, |
| 605 | }; |
| 606 | self.page_opened(started, &workspace, a.amount_cents, fee, &a.actor.username, None).await |
| 607 | } |
| 608 | |
| 609 | /// A payment page Stripe started (or refused), recorded in `checkouts` |
| 610 | /// and handed back; any failure as a sentence for the page, never a |
| 611 | /// raw error. |
| 612 | pub(crate) async fn page_opened( |
| 613 | &self, |
| 614 | started: Result<stripe::Session>, |
| 615 | workspace: &str, |
| 616 | amount_cents: u32, |
| 617 | fee_cents: u32, |
| 618 | created_by: &str, |
| 619 | feature: Option<&str>, |
| 620 | ) -> Result<Outcome<Checkout>> { |
| 621 | let session = match started { |
| 622 | Ok(session) => session, |
| 623 | Err(error) => { |
| 624 | worker::console_error!("{workspace}: Stripe refused a payment page ({}): {error}", feature.unwrap_or("prepay")); |
| 625 | return Ok(Outcome::fail(FailureCode::Conflict, stripe::friendly(&error))); |
| 626 | } |
| 627 | }; |
| 628 | let Some(url) = session.url.clone() else { |
| 629 | return Ok(Outcome::fail(FailureCode::Conflict, "Stripe returned no payment page. Try again in a minute.")); |
| 630 | }; |
| 631 | let recorded = self |
| 632 | .record_checkout(&NewCheckout { id: &session.id, workspace, amount_cents, fee_cents, created_by, feature }) |
| 633 | .await; |
| 634 | if let Err(error) = recorded { |
| 635 | worker::console_error!("{workspace}: a payment page could not be recorded: {error}"); |
| 636 | return Ok(Outcome::fail(FailureCode::Conflict, "g1t could not keep track of the payment page. Nothing was charged; try again.")); |
| 637 | } |
| 638 | Ok(Outcome::Ok(Checkout { url })) |
| 639 | } |
| 640 | |
| 641 | /// Credits a payment if the processor says it was made and it has not |
| 642 | /// been credited before. The amount credited is what the processor |
| 643 | /// says was paid, not what anyone here remembers asking for. |
| 644 | async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> { |
| 645 | let workspace = a.workspace.to_lowercase(); |
| 646 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { |
| 647 | return Ok(members_only()); |
| 648 | } |
| 649 | let (Some(stripe), Some(checkout)) = ( |
| 650 | &self.stripe, |
| 651 | self.db |
| 652 | .prepare( |
| 653 | // A prepayment only: a plan's or a card check's page is |
| 654 | // settled where it was started, never credited as money |
| 655 | // paid in advance. |
| 656 | "SELECT workspace, created_by, fee_cents FROM checkouts |
| 657 | WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NULL", |
| 658 | ) |
| 659 | .bind(&[a.session.as_str().into(), workspace.as_str().into()])? |
| 660 | .first::<CheckoutRow>(None) |
| 661 | .await?, |
| 662 | ) else { |
| 663 | // Unknown, someone else's, or already credited: nothing to do. |
| 664 | return Ok(Outcome::Ok(self.standing(&workspace).await?)); |
| 665 | }; |
| 666 | let session = match stripe.session(&a.session).await { |
| 667 | Ok(session) => session, |
| 668 | Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))), |
| 669 | }; |
| 670 | if session.payment_status == "paid" && session.amount_total.is_some() { |
| 671 | // Only whoever flips it from open to paid enters the credit. |
| 672 | let claimed = self |
| 673 | .db |
| 674 | .prepare( |
| 675 | "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open' |
| 676 | RETURNING id", |
| 677 | ) |
| 678 | .bind(&[a.session.as_str().into()])? |
| 679 | .first::<Touched>(None) |
| 680 | .await?; |
| 681 | if claimed.is_some() { |
| 682 | self.credit_prepayment(&checkout.workspace, &session, checkout.fee_cents.unwrap_or(0), &checkout.created_by).await?; |
| 683 | } |
| 684 | } |
| 685 | Ok(Outcome::Ok(self.standing(&workspace).await?)) |
| 686 | } |
| 687 | |
| 688 | /// Enters a paid prepayment page: what its lines came to before tax, |
| 689 | /// less the card fee, as credit; its tax and fee kept apart. Once the |
| 690 | /// page is claimed `open → paid`. The credit in cents. |
| 691 | pub(crate) async fn credit_prepayment(&self, workspace: &str, session: &stripe::Session, fee_cents: u32, by: &str) -> Result<i64> { |
| 692 | let fee = i64::from(fee_cents); |
| 693 | let cents = tax::prepay_credit_cents(session.before_tax_cents(), fee); |
| 694 | let tax_cents = session.tax_cents(); |
| 695 | let description = if tax_cents > 0 || fee > 0 { |
| 696 | format!( |
| 697 | "Paid in advance (tax {} and card fee {} paid with it)", |
| 698 | features::cents(tax_cents * 10_000), |
| 699 | features::cents(fee * 10_000) |
| 700 | ) |
| 701 | } else { |
| 702 | "Paid in advance".to_owned() |
| 703 | }; |
| 704 | self.enter( |
| 705 | workspace, |
| 706 | EntryKind::TopUp, |
| 707 | cents * MICROS_PER_DOLLAR / 100, |
| 708 | &description, |
| 709 | &session.id, |
| 710 | None, |
| 711 | None, |
| 712 | Some(by), |
| 713 | session.customer.as_deref(), |
| 714 | ) |
| 715 | .await?; |
| 716 | self.record_extras(workspace, &session.id, session.payment_intent.as_deref(), tax::Extras { tax_cents, fee_cents: fee }, None) |
| 717 | .await?; |
| 718 | Ok(cents) |
| 719 | } |
| 720 | |
| 721 | /// Drops a saved customer the card processor no longer knows. |
| 722 | pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> { |
| 723 | self.db |
| 724 | .prepare( |
| 725 | "UPDATE accounts SET customer_id = NULL, card_brand = NULL, card_last4 = NULL, card_exp_month = NULL, |
| 726 | card_exp_year = NULL, card_synced_at = NULL WHERE workspace = ?", |
| 727 | ) |
| 728 | .bind(&[workspace.into()])? |
| 729 | .run() |
| 730 | .await?; |
| 731 | Ok(()) |
| 732 | } |
| 733 | |
| 734 | /// A refusal if the workspace has no credit to start an agent with. |
| 735 | async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> { |
| 736 | // Billing is postpaid: usage limits decide whether work starts |
| 737 | // (see `limits`), and credit is a prepayment that lowers what is |
| 738 | // owed. A balance no longer has to be positive to start. |
| 739 | if self.free || !self.prepaid_only { |
| 740 | return Ok(None); |
| 741 | } |
| 742 | let balance = self |
| 743 | .row(workspace) |
| 744 | .await? |
| 745 | .map_or(0, |row| row.balance_micros); |
| 746 | Ok((balance <= 0).then(|| { |
| 747 | Outcome::fail( |
| 748 | FailureCode::PaymentRequired, |
| 749 | format!( |
| 750 | "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page." |
| 751 | ), |
| 752 | ) |
| 753 | })) |
| 754 | } |
| 755 | |
| 756 | async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> { |
| 757 | if self.stripe.is_none() { |
| 758 | return Ok(Outcome::Ok(true)); |
| 759 | } |
| 760 | if let Some(stopped) = self.stopped(&a.workspace).await? { |
| 761 | return Ok(stopped); |
| 762 | } |
| 763 | Ok(self |
| 764 | .out_of_credit(&a.workspace.to_lowercase()) |
| 765 | .await? |
| 766 | .unwrap_or(Outcome::Ok(true))) |
| 767 | } |
| 768 | |
| 769 | async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> { |
| 770 | if self.stripe.is_none() { |
| 771 | return Ok(Outcome::Ok(None)); |
| 772 | } |
| 773 | let workspace = a.workspace.to_lowercase(); |
| 774 | if let Some(stopped) = self.stopped(&workspace).await? { |
| 775 | return Ok(stopped); |
| 776 | } |
| 777 | if let Some(refused) = self.out_of_credit(&workspace).await? { |
| 778 | return Ok(refused); |
| 779 | } |
| 780 | // On g1t's models, a workspace on the plan needs AI credit (or |
| 781 | // included usage) first: g1t never fronts a model's cost (ai.rs). |
| 782 | if a.billed_to != "workspace" |
| 783 | && let Some(why) = self.ai_refusal(&workspace).await? |
| 784 | { |
| 785 | return Ok(Outcome::fail(FailureCode::PaymentRequired, why)); |
| 786 | } |
| 787 | let now = now_ms(); |
| 788 | let run_id = new_id("run", now); |
| 789 | let mut bytes = [0u8; 32]; |
| 790 | getrandom::getrandom(&mut bytes).expect("no source of randomness"); |
| 791 | let token = hex::encode(bytes); |
| 792 | self.db |
| 793 | .prepare( |
| 794 | "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier) |
| 795 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 796 | ) |
| 797 | .bind(&[ |
| 798 | run_id.as_str().into(), |
| 799 | workspace.into(), |
| 800 | format!("{}/{}", a.repo.namespace, a.repo.name).into(), |
| 801 | a.number.into(), |
| 802 | a.task.into(), |
| 803 | a.model.into(), |
| 804 | hash(&token).into(), |
| 805 | rfc3339(now).into(), |
| 806 | if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(), |
| 807 | // On the workspace's own provider too: the proxy counts the |
| 808 | // run's tokens under it, and the agent rate is charged on them. |
| 809 | optional(a.session.as_deref()), |
| 810 | optional(a.tier.as_deref().filter(|tier| tokens::is_tier(tier))), |
| 811 | ])? |
| 812 | .run() |
| 813 | .await?; |
| 814 | Ok(Outcome::Ok(Some(RunTicket { run_id, token }))) |
| 815 | } |
| 816 | |
| 817 | async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> { |
| 818 | let run = self |
| 819 | .db |
| 820 | .prepare( |
| 821 | "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs |
| 822 | WHERE id = ? AND finished_at IS NULL", |
| 823 | ) |
| 824 | .bind(&[a.run_id.as_str().into()])? |
| 825 | .first::<RunRow>(None) |
| 826 | .await?; |
| 827 | let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else { |
| 828 | return Ok(Outcome::fail(FailureCode::NotFound, "Run not found.")); |
| 829 | }; |
| 830 | if !a.cost_usd.is_finite() || a.cost_usd < 0.0 { |
| 831 | return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost.")); |
| 832 | } |
| 833 | // Only whoever closes the run charges for it. |
| 834 | let claimed = self |
| 835 | .db |
| 836 | .prepare( |
| 837 | "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id", |
| 838 | ) |
| 839 | .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])? |
| 840 | .first::<Touched>(None) |
| 841 | .await?; |
| 842 | if claimed.is_none() { |
| 843 | return Ok(Outcome::Ok(false)); |
| 844 | } |
| 845 | // On the workspace's own provider, the model was paid for there and |
| 846 | // the run's sandbox time is recorded on its own: only the agent rate |
| 847 | // is charged, on its own meter. |
| 848 | if run.own_provider() { |
| 849 | self.charge_agent_rate(&a.run_id, &run, a.tokens).await?; |
| 850 | return Ok(Outcome::Ok(true)); |
| 851 | } |
| 852 | // Its cost plus the margin, on the account's terms; then the plan's |
| 853 | // included usage and the trial credit pay what they can, and g1t |
| 854 | // covers a free workspace's overrun (see `credits`). Agents are |
| 855 | // never the open-source pool's. |
| 856 | // The model at the provider's price and the price book's markup on it |
| 857 | // (`agent_models`: none from 2026-10-08); g1t's own part is the agent |
| 858 | // rate, charged on a line of its own below. |
| 859 | let base = charge_micros(a.cost_usd, self.model_markup().await?); |
| 860 | let (charge, terms_note, discount) = self.charged(&run.workspace, base).await?; |
| 861 | let month = credits::month_of(&rfc3339(now_ms())); |
| 862 | let eligible = credits::eligible_for(Some(ComputeKind::Agent), None); |
| 863 | let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?; |
| 864 | let mut description = match run.task.as_str() { |
| 865 | "plan" => format!("Planning for {}", run.repo), |
| 866 | "review" => format!("Review of {}#{}", run.repo, run.number), |
| 867 | "update" => format!("Catching up {}#{}", run.repo, run.number), |
| 868 | _ => format!("Work on {}#{}", run.repo, run.number), |
| 869 | }; |
| 870 | description.push_str(&terms_note); |
| 871 | description.push_str(&drawn.note()); |
| 872 | self.enter( |
| 873 | &run.workspace, |
| 874 | EntryKind::Usage, |
| 875 | -(charge - drawn.total()), |
| 876 | &description, |
| 877 | &a.run_id, |
| 878 | Some(&run), |
| 879 | Some(charge_micros(a.cost_usd, 0)), |
| 880 | None, |
| 881 | None, |
| 882 | ) |
| 883 | .await?; |
| 884 | self.record_drawn(&a.run_id, &drawn).await?; |
| 885 | self.record_discount(&a.run_id, discount).await?; |
| 886 | self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await; |
| 887 | self.charge_agent_rate(&a.run_id, &run, a.tokens).await?; |
| 888 | Ok(Outcome::Ok(true)) |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | impl Billing { |
| 893 | /// Records how long a sandbox ran, with its cost and its charge: every |
| 894 | /// second, from the first, at the price book's price; on its own CPU |
| 895 | /// when it reports it. Settles its reservation, if it names one. |
| 896 | async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> { |
| 897 | // Self-hosted time is recorded wherever g1t runs, for its minutes; |
| 898 | // anything else only where there is a bill to put it on. |
| 899 | if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 { |
| 900 | return Ok(Outcome::Ok(false)); |
| 901 | } |
| 902 | let workspace = a.workspace.to_lowercase(); |
| 903 | let seen = self |
| 904 | .db |
| 905 | .prepare("SELECT id FROM ledger WHERE reference = ?") |
| 906 | .bind(&[a.reference.as_str().into()])? |
| 907 | .first::<Touched>(None) |
| 908 | .await?; |
| 909 | if seen.is_some() { |
| 910 | return Ok(Outcome::Ok(false)); |
| 911 | } |
| 912 | let now = now_ms(); |
| 913 | let timestamp = rfc3339(now); |
| 914 | let seconds = i64::from(a.seconds); |
| 915 | // On the workspace's own machine: its minutes go on usage, at $0, |
| 916 | // and whatever was reserved for it is given back. |
| 917 | if a.self_hosted { |
| 918 | let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds)); |
| 919 | self.db |
| 920 | .prepare( |
| 921 | "INSERT INTO ledger |
| 922 | (id, workspace, kind, amount_micros, description, repo, task, |
| 923 | cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, quantity) |
| 924 | VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0, ?)", |
| 925 | ) |
| 926 | .bind(&[ |
| 927 | new_id("led", now).into(), |
| 928 | workspace.as_str().into(), |
| 929 | description.as_str().into(), |
| 930 | optional(a.repo.as_deref()), |
| 931 | a.reference.as_str().into(), |
| 932 | timestamp.as_str().into(), |
| 933 | (seconds as f64).into(), |
| 934 | ])? |
| 935 | .run() |
| 936 | .await?; |
| 937 | if let Some(reservation) = &a.reservation_id { |
| 938 | self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?; |
| 939 | } |
| 940 | return Ok(Outcome::Ok(true)); |
| 941 | } |
| 942 | // From the price book, which follows what Cloudflare bills g1t. A |
| 943 | // sandbox is the same container as a build, so without a row it is |
| 944 | // a build second's cost plus the margin. |
| 945 | let (cost_per_second, _) = self.price("sandbox_second").await?.unwrap_or_else(|| { |
| 946 | let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64; |
| 947 | (cost, Price::price_for(cost, self.margin_percent)) |
| 948 | }); |
| 949 | // A larger machine (`runs-on: g1t-4core`): its memory and disk |
| 950 | // cost more each second, and without its own CPU it is priced at |
| 951 | // its vCPUs as busy as the standard machine's. |
| 952 | let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named); |
| 953 | let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb)); |
| 954 | let price_scale = instance.map_or(1.0, |i| i.price_scale); |
| 955 | let vcpus = instance.map_or(4.0, |i| i.vcpu.max(4.0)); |
| 956 | // Its own CPU when the sandbox reports it; otherwise the average. |
| 957 | let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) { |
| 958 | Some(cpu) => match (self.price("sandbox_base_second").await?, self.price("sandbox_cpu_second").await?) { |
| 959 | (Some((base, _)), Some((vcpu, _))) => { |
| 960 | Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu)) |
| 961 | } |
| 962 | _ => None, |
| 963 | }, |
| 964 | None => None, |
| 965 | }; |
| 966 | let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64; |
| 967 | let (charge, terms_note, discount) = self.charged(&workspace, credits::with_margin(cost, self.margin_percent)).await?; |
| 968 | let eligible = credits::eligible_for(a.kind, a.repo.as_deref()); |
| 969 | let drawn = self.draw(&workspace, charge, &credits::month_of(×tamp), &eligible).await?; |
| 970 | let charge = charge - drawn.total(); |
| 971 | let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds")); |
| 972 | let description = format!("{}: {} of sandbox time{cpu_note}{terms_note}{}", a.description, duration(seconds), drawn.note()); |
| 973 | // The price versions it was charged at (pricing.rs). |
| 974 | let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] }; |
| 975 | let mut versions = Vec::new(); |
| 976 | for meter in meters { |
| 977 | versions.extend(self.version_now(meter).await?); |
| 978 | } |
| 979 | let price_version = versions.join(","); |
| 980 | self.db |
| 981 | .batch(vec![ |
| 982 | self.db |
| 983 | .prepare( |
| 984 | "INSERT INTO ledger |
| 985 | (id, workspace, kind, amount_micros, description, repo, task, |
| 986 | cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version, quantity, compute) |
| 987 | VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?, ?, ?)", |
| 988 | ) |
| 989 | .bind(&[ |
| 990 | new_id("led", now).into(), |
| 991 | workspace.as_str().into(), |
| 992 | (-(charge as f64)).into(), |
| 993 | description.as_str().into(), |
| 994 | optional(a.repo.as_deref()), |
| 995 | (cost as f64).into(), |
| 996 | a.reference.as_str().into(), |
| 997 | timestamp.as_str().into(), |
| 998 | (drawn.credit as f64).into(), |
| 999 | (drawn.trial as f64).into(), |
| 1000 | (drawn.oss as f64).into(), |
| 1001 | (drawn.given as f64).into(), |
| 1002 | optional(Some(price_version.as_str()).filter(|v| !v.is_empty())), |
| 1003 | (seconds as f64).into(), |
| 1004 | optional(a.kind.map(ComputeKind::as_str)), |
| 1005 | ])?, |
| 1006 | self.db |
| 1007 | .prepare( |
| 1008 | "INSERT INTO accounts (workspace, balance_micros, created_at) |
| 1009 | VALUES (?1, ?2, ?3) |
| 1010 | ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2", |
| 1011 | ) |
| 1012 | .bind(&[ |
| 1013 | workspace.as_str().into(), |
| 1014 | (-(charge as f64)).into(), |
| 1015 | timestamp.as_str().into(), |
| 1016 | ])?, |
| 1017 | ]) |
| 1018 | .await?; |
| 1019 | self.record_discount(&a.reference, discount).await?; |
| 1020 | self.count_spend(&workspace, cost, charge, &drawn).await; |
| 1021 | if let Some(reservation) = &a.reservation_id { |
| 1022 | self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?; |
| 1023 | } |
| 1024 | Ok(Outcome::Ok(true)) |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | /// Whether an amount may be prepaid: $25 at the least by card, and from |
| 1029 | /// $1,000 by bank transfer. |
| 1030 | pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> { |
| 1031 | let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) }; |
| 1032 | if (min..=max).contains(¢s) { |
| 1033 | return Ok(()); |
| 1034 | } |
| 1035 | Err(if bank_transfer { |
| 1036 | format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100)) |
| 1037 | } else { |
| 1038 | format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100)) |
| 1039 | }) |
| 1040 | } |
| 1041 | |
| 1042 | /// `10,000` for 10000. |
| 1043 | fn group(n: u32) -> String { |
| 1044 | let digits = n.to_string(); |
| 1045 | let mut out = String::new(); |
| 1046 | for (i, c) in digits.chars().enumerate() { |
| 1047 | if i > 0 && (digits.len() - i).is_multiple_of(3) { |
| 1048 | out.push(','); |
| 1049 | } |
| 1050 | out.push(c); |
| 1051 | } |
| 1052 | out |
| 1053 | } |
| 1054 | |
| 1055 | #[cfg(test)] |
| 1056 | /// What `seconds` of sandbox time are charged at `price_per_second`, in |
| 1057 | /// millionths of a dollar: every second, rounded up to the next millionth. |
| 1058 | fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 { |
| 1059 | (seconds as f64 * price_per_second).ceil() as i64 |
| 1060 | } |
| 1061 | |
| 1062 | /// `1h 2m`, `3m 12s` or `40s`. |
| 1063 | fn duration(seconds: i64) -> String { |
| 1064 | let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60); |
| 1065 | if h > 0 { |
| 1066 | format!("{h}h {m}m") |
| 1067 | } else if m > 0 { |
| 1068 | format!("{m}m {s}s") |
| 1069 | } else { |
| 1070 | format!("{s}s") |
| 1071 | } |
| 1072 | } |
| 1073 | |
| 1074 | impl Billing { |
| 1075 | /// What a workspace is charged for something that would be `base`: |
| 1076 | /// nothing while g1t is free, or as its account's terms say. With a |
| 1077 | /// note for the statement when it differs. |
| 1078 | /// A charge at cost plus the margin (`base`) on the account's terms: |
| 1079 | /// what is charged, the note for the statement, and what a discount |
| 1080 | /// gave away below `base`. That last is written on the entry |
| 1081 | /// (`record_discount`) so the reconciliation counts it as given, never |
| 1082 | /// as margin lost: a sold charge is worth at least its cost plus the |
| 1083 | /// margin. |
| 1084 | pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String, i64)> { |
| 1085 | if self.free { |
| 1086 | return Ok((0, " (free while g1t is being built out)".to_owned(), 0)); |
| 1087 | } |
| 1088 | let terms = self.terms_of(workspace).await?; |
| 1089 | let (charge, discount) = terms.discounted(base); |
| 1090 | let note = match terms.discount_label() { |
| 1091 | Some(label) if base > 0 => format!(" ({label})"), |
| 1092 | _ => String::new(), |
| 1093 | }; |
| 1094 | Ok((charge, note, discount)) |
| 1095 | } |
| 1096 | |
| 1097 | /// What a discount gave away on an entry, below cost plus the margin |
| 1098 | /// (less than nothing on a correction down). |
| 1099 | pub(crate) async fn record_discount(&self, reference: &str, micros: i64) -> Result<()> { |
| 1100 | if micros == 0 { |
| 1101 | return Ok(()); |
| 1102 | } |
| 1103 | self.db |
| 1104 | .prepare("UPDATE ledger SET discount_micros = ? WHERE reference = ?") |
| 1105 | .bind(&[(micros as f64).into(), reference.into()])? |
| 1106 | .run() |
| 1107 | .await?; |
| 1108 | Ok(()) |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | fn members_only<T>() -> Outcome<T> { |
| 1113 | Outcome::fail( |
| 1114 | FailureCode::Forbidden, |
| 1115 | "Only members can see a workspace's billing.", |
| 1116 | ) |
| 1117 | } |
| 1118 | |
| 1119 | impl Billing { |
| 1120 | fn from_env(env: &Env) -> Result<Self> { |
| 1121 | Ok(Billing { |
| 1122 | db: env.d1("DB")?, |
| 1123 | stripe: env |
| 1124 | .secret("STRIPE_SECRET_KEY") |
| 1125 | .ok() |
| 1126 | .map(|key| key.to_string()) |
| 1127 | .filter(|key| !key.is_empty()) |
| 1128 | .map(Stripe::new), |
| 1129 | webhook_secret: env |
| 1130 | .secret("STRIPE_WEBHOOK_SECRET") |
| 1131 | .ok() |
| 1132 | .map(|secret| secret.to_string().trim().to_owned()) |
| 1133 | .filter(|secret| !secret.is_empty()), |
| 1134 | margin_percent: env |
| 1135 | .var("MARGIN_PERCENT") |
| 1136 | .ok() |
| 1137 | .and_then(|percent| percent.to_string().parse().ok()) |
| 1138 | .unwrap_or(20), |
| 1139 | free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"), |
| 1140 | ceilings: limits::Ceilings::from_env(env), |
| 1141 | prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"), |
| 1142 | trials_on: { |
| 1143 | let plans = credits::Config::from_env(env); |
| 1144 | plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0 |
| 1145 | }, |
| 1146 | plans: credits::Config::from_env(env), |
| 1147 | repos: env.service("REPOS").ok(), |
| 1148 | packages: env.service("PACKAGES").ok(), |
| 1149 | identity: env.service("IDENTITY").ok(), |
| 1150 | caps: budget::Caps::from_env(env), |
| 1151 | env: env.clone(), |
| 1152 | }) |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | #[event(scheduled)] |
| 1157 | async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) { |
| 1158 | let Ok(billing) = Billing::from_env(&env) else { |
| 1159 | return; |
| 1160 | }; |
| 1161 | let keeper = keeper::Keeper::from_env(&env); |
| 1162 | if let Err(error) = billing.settle_runs(&keeper).await { |
| 1163 | worker::console_error!("settling runs failed: {error}"); |
| 1164 | } |
| 1165 | if let Err(error) = billing.settle_own_runs().await { |
| 1166 | worker::console_error!("closing runs on own providers failed: {error}"); |
| 1167 | } |
| 1168 | // Stripe events billing never received, handled now. |
| 1169 | match billing.replay_events().await { |
| 1170 | Ok(done) => worker::console_log!("stripe replay: {done}"), |
| 1171 | Err(error) => worker::console_error!("replaying Stripe events failed: {error}"), |
| 1172 | } |
| 1173 | if let Err(error) = billing.autopay().await { |
| 1174 | worker::console_error!("paying at the limit failed: {error}"); |
| 1175 | } |
| 1176 | // AI credit below a workspace's auto-reload threshold, reloaded (ai.rs). |
| 1177 | match billing.reload_ai_credit().await { |
| 1178 | Ok(0) => {} |
| 1179 | Ok(done) => worker::console_log!("auto-reloaded AI credit for {done} workspaces"), |
| 1180 | Err(error) => worker::console_error!("auto-reloading AI credit failed: {error}"), |
| 1181 | } |
| 1182 | // Last month's metered usage (scans, embeddings, storage) goes on the |
| 1183 | // ledger before the month is closed and invoiced. |
| 1184 | if let Err(error) = billing.charge_pending().await { |
| 1185 | worker::console_error!("charging last month's metered usage failed: {error}"); |
| 1186 | } |
| 1187 | if let Err(error) = billing.close_months().await { |
| 1188 | worker::console_error!("closing the month failed: {error}"); |
| 1189 | } |
| 1190 | if let Err(error) = billing.invoice_enterprises().await { |
| 1191 | worker::console_error!("invoicing enterprises failed: {error}"); |
| 1192 | } |
| 1193 | // Comped budgets' alerts, and a tripped breaker staff were not told of. |
| 1194 | if let Err(error) = billing.watch_spend().await { |
| 1195 | worker::console_error!("watching g1t's own spend failed: {error}"); |
| 1196 | } |
| 1197 | if let Ok(identity) = env.service("IDENTITY") |
| 1198 | && let Err(error) = billing.warn_limits(&identity).await { |
| 1199 | worker::console_error!("warning owners failed: {error}"); |
| 1200 | } |
| 1201 | // Once a day: Stripe's endpoint kept listening to billing's events and |
| 1202 | // enabled, and saved cards and plans not read in a while read again. |
| 1203 | if event.cron() == keeper::DAILY { |
| 1204 | match billing.keep_endpoint("billing").await { |
| 1205 | Ok(done) => worker::console_log!("stripe endpoint: {done}"), |
| 1206 | Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"), |
| 1207 | } |
| 1208 | match billing.refresh_from_stripe().await { |
| 1209 | Ok(done) => worker::console_log!("stripe refresh: {done}"), |
| 1210 | Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"), |
| 1211 | } |
| 1212 | } |
| 1213 | // Once a day, and at once if the costs were never checked: check every |
| 1214 | // cost against what Cloudflare billed. |
| 1215 | if (event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false)) |
| 1216 | && let Err(error) = billing.reconcile(&keeper).await { |
| 1217 | worker::console_error!("checking costs against Cloudflare failed: {error}"); |
| 1218 | } |
| 1219 | // Once a day: credit from g1t past its expiry stops counting |
| 1220 | // (grants.rs), before the day is reconciled. |
| 1221 | if event.cron() == keeper::DAILY { |
| 1222 | match billing.expire_credits().await { |
| 1223 | Ok(closed) => worker::console_log!("credits expired: {closed}"), |
| 1224 | Err(error) => worker::console_error!("expiring credits failed: {error}"), |
| 1225 | } |
| 1226 | } |
| 1227 | // Once a day: what Cloudflare charged, reconciled against what g1t |
| 1228 | // counted and charged; prices whose day has come; margin alerts |
| 1229 | // (margin.rs). After the keeper, so its proposals are in. |
| 1230 | if event.cron() == keeper::DAILY { |
| 1231 | match billing.costs_daily(&env, &keeper).await { |
| 1232 | Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts), |
| 1233 | Err(error) => worker::console_error!("reconciling costs failed: {error}"), |
| 1234 | } |
| 1235 | } |
| 1236 | // Once a day: what each workspace's private repositories hold, its git |
| 1237 | // operations, Deployments plans from before the g1t plan set to end, |
| 1238 | // and old reservations cleared. |
| 1239 | if event.cron() == keeper::DAILY { |
| 1240 | if let Err(error) = billing.measure_packages().await { |
| 1241 | worker::console_error!("measuring package storage failed: {error}"); |
| 1242 | } |
| 1243 | if let Err(error) = billing.measure_storage().await { |
| 1244 | worker::console_error!("measuring storage failed: {error}"); |
| 1245 | } |
| 1246 | if let Err(error) = billing.measure_git().await { |
| 1247 | worker::console_error!("measuring git operations failed: {error}"); |
| 1248 | } |
| 1249 | if let Err(error) = billing.retire_deployments_plans().await { |
| 1250 | worker::console_error!("ending Deployments plans failed: {error}"); |
| 1251 | } |
| 1252 | if let Err(error) = billing.sweep_reservations().await { |
| 1253 | worker::console_error!("clearing reservations failed: {error}"); |
| 1254 | } |
| 1255 | // The AI Gateway's log keeps 30 days (gateway.rs). |
| 1256 | if let Err(error) = billing.forget_gateway_requests().await { |
| 1257 | worker::console_error!("clearing old AI Gateway requests failed: {error}"); |
| 1258 | } |
| 1259 | } |
| 1260 | } |
| 1261 | |
| 1262 | /// Events from the bus, on billing's own queue: only a workspace's rename |
| 1263 | /// matters here (see `rename`). |
| 1264 | #[event(queue)] |
| 1265 | async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> { |
| 1266 | let billing = Billing::from_env(&env)?; |
| 1267 | let identity = env.service("IDENTITY").ok(); |
| 1268 | for message in batch.messages()? { |
| 1269 | // A repository transferred: its share of the open-source pool this |
| 1270 | // month follows it. What it was charged stays with the workspace |
| 1271 | // it was charged to; usage from now on is charged to the new one. |
| 1272 | if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? { |
| 1273 | message.ack(); |
| 1274 | continue; |
| 1275 | } |
| 1276 | billing.on_event(identity.as_ref(), message.body()).await?; |
| 1277 | message.ack(); |
| 1278 | } |
| 1279 | Ok(()) |
| 1280 | } |
| 1281 | |
| 1282 | #[event(fetch)] |
| 1283 | async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> { |
| 1284 | let Some(method) = rpc_method(&request) else { |
| 1285 | return Response::error("Not found", 404); |
| 1286 | }; |
| 1287 | // A replica near the caller when it asks for one (crates/kit/src/d1.rs); |
| 1288 | // what other services call (can_start, start_run) asks for none. |
| 1289 | let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?; |
| 1290 | let body: serde_json::Value = request.json().await?; |
| 1291 | let mut billing = Billing::from_env(&env)?; |
| 1292 | billing.db = db; |
| 1293 | let answered = match method.as_str() { |
| 1294 | "status" => reply(&billing.status()), |
| 1295 | "account" => reply(&billing.account(args(body)?).await?), |
| 1296 | "ledger" => reply(&billing.ledger(args(body)?).await?), |
| 1297 | "credits" => reply(&billing.credits(args(body)?).await?), |
| 1298 | "usage" => reply(&billing.usage(args(body)?).await?), |
| 1299 | "usage_report" => reply(&billing.usage_report(args(body)?).await?), |
| 1300 | "ai_credit" => reply(&billing.ai_credit(args(body)?).await?), |
| 1301 | "buy_ai_credit" => reply(&billing.buy_ai_credit(args(body)?).await?), |
| 1302 | "confirm_ai_credit" => reply(&billing.confirm_ai_credit(args(body)?).await?), |
| 1303 | "set_ai_reload" => reply(&billing.set_ai_reload(args(body)?).await?), |
| 1304 | "set_budget" => reply(&billing.set_budget(args(body)?).await?), |
| 1305 | "billing_details" => reply(&billing.billing_details(args(body)?).await?), |
| 1306 | "set_billing_details" => reply(&billing.set_billing_details(args(body)?).await?), |
| 1307 | "record_tokens" => reply(&billing.record_tokens(args(body)?).await?), |
| 1308 | "token_usage" => reply(&billing.token_usage(args(body)?).await?), |
| 1309 | "gateway_models" => reply(&billing.gateway_models().await?), |
| 1310 | "gateway_admit" => reply(&billing.gateway_admit(args(body)?).await?), |
| 1311 | "record_gateway" => reply(&billing.record_gateway(args(body)?).await?), |
| 1312 | "gateway_requests" => reply(&billing.gateway_requests(args(body)?).await?), |
| 1313 | "checkout" => reply(&billing.checkout(args(body)?).await?), |
| 1314 | "confirm" => reply(&billing.confirm(args(body)?).await?), |
| 1315 | "can_start" => reply(&billing.can_start(args(body)?).await?), |
| 1316 | "trial" => reply(&billing.trial(args(body)?).await?), |
| 1317 | "start_run" => reply(&billing.start_run(args(body)?).await?), |
| 1318 | "finish_run" => reply(&billing.finish_run(args(body)?).await?), |
| 1319 | "features" => reply(&billing.features(args(body)?).await?), |
| 1320 | "subscribe" => reply(&billing.subscribe(args(body)?).await?), |
| 1321 | "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?), |
| 1322 | "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?), |
| 1323 | "close_workspace" => reply(&billing.close_workspace(args(body)?).await?), |
| 1324 | "has_feature" => reply(&billing.has_feature(args(body)?).await?), |
| 1325 | "free_workspaces" => reply(&billing.free_workspaces(args(body)?).await?), |
| 1326 | "charge_feature" => reply(&billing.charge_feature(args(body)?).await?), |
| 1327 | "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?), |
| 1328 | "limit" => reply(&billing.limit(args(body)?).await?), |
| 1329 | "check_limit" => reply(&billing.check_limit(args(body)?).await?), |
| 1330 | "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?), |
| 1331 | "prices" => reply(&billing.prices().await?), |
| 1332 | "billing_portal" => reply(&billing.billing_portal(args(body)?).await?), |
| 1333 | "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?), |
| 1334 | "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?), |
| 1335 | "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?), |
| 1336 | "admin_enterprise_address" => reply(&billing.admin_enterprise_address(args(body)?).await?), |
| 1337 | "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?), |
| 1338 | "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?), |
| 1339 | "invoices" => reply(&billing.invoices(args(body)?).await?), |
| 1340 | "statement" => reply(&billing.statement(args(body)?).await?), |
| 1341 | "statement_entries" => reply(&billing.statement_entries(args(body)?).await?), |
| 1342 | "usage_meters" => reply(&billing.usage_meters(args(body)?).await?), |
| 1343 | "admin_workspace_invoices" => { |
| 1344 | let a: AdminWorkspaceInvoicesArgs = args(body)?; |
| 1345 | reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?) |
| 1346 | } |
| 1347 | "admin_signals" => reply(&billing.admin_signals(args(body)?).await?), |
| 1348 | "admin_overview" => reply(&billing.admin_overview(args(body)?).await?), |
| 1349 | "admin_sales" => reply(&billing.admin_sales(args(body)?).await?), |
| 1350 | "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?), |
| 1351 | "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?), |
| 1352 | "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?), |
| 1353 | "admin_audit" => reply(&billing.admin_audit(args(body)?).await?), |
| 1354 | // A staff change made in another service, for sudo's audit log: |
| 1355 | // identity's restores and purges of deleted workspaces. |
| 1356 | "admin_log" => { |
| 1357 | let a: AdminLogArgs = args(body)?; |
| 1358 | billing |
| 1359 | .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by) |
| 1360 | .await?; |
| 1361 | reply(&true) |
| 1362 | } |
| 1363 | "note_pending" => reply(&billing.note_pending(args(body)?).await?), |
| 1364 | "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?), |
| 1365 | "admin_account" => reply(&billing.admin_account(args(body)?).await?), |
| 1366 | "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?), |
| 1367 | "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?), |
| 1368 | "admin_attach" => reply(&billing.admin_attach(args(body)?).await?), |
| 1369 | "admin_credit" => reply(&billing.admin_credit(args(body)?).await?), |
| 1370 | "admin_credits" => reply(&billing.admin_credits(args(body)?).await?), |
| 1371 | "admin_revoke_credit" => reply(&billing.admin_revoke_credit(args(body)?).await?), |
| 1372 | "admin_reset_billing" => reply(&billing.admin_reset_billing(&env, args(body)?).await?), |
| 1373 | "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?), |
| 1374 | "entitlements" => reply(&billing.entitlements(args(body)?).await?), |
| 1375 | "audit_retention" => reply(&billing.audit_retention(args(body)?).await?), |
| 1376 | "reserve" => reply(&billing.reserve(args(body)?).await?), |
| 1377 | "settle" => reply(&billing.settle_reservation(args(body)?).await?), |
| 1378 | "card_check" => reply(&billing.card_check(args(body)?).await?), |
| 1379 | "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?), |
| 1380 | "request_limit" => reply(&billing.request_limit(args(body)?).await?), |
| 1381 | "limit_requests" => reply(&billing.limit_requests(args(body)?).await?), |
| 1382 | "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?), |
| 1383 | "set_caps" => reply(&billing.set_caps(args(body)?).await?), |
| 1384 | "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?), |
| 1385 | "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?), |
| 1386 | "admin_overages" => reply(&billing.admin_overages(args(body)?).await?), |
| 1387 | "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?), |
| 1388 | "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?), |
| 1389 | "admin_record_payment" => reply(&billing.admin_record_payment(args(body)?).await?), |
| 1390 | "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?), |
| 1391 | "admin_cost_alerts" => reply(&billing.admin_cost_alerts(args(body)?).await?), |
| 1392 | "admin_spend_caps" => reply(&billing.spend_caps().await?), |
| 1393 | "admin_lift_breaker" => reply(&billing.admin_lift_breaker(args(body)?).await?), |
| 1394 | "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?), |
| 1395 | "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?), |
| 1396 | "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?), |
| 1397 | "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?), |
| 1398 | _ => Response::error("Unknown method", 404), |
| 1399 | }; |
| 1400 | served.finish(answered) |
| 1401 | } |
| 1402 | |
| 1403 | #[cfg(test)] |
| 1404 | mod tests { |
| 1405 | use super::*; |
| 1406 | |
| 1407 | #[test] |
| 1408 | fn a_run_is_charged_its_cost_plus_the_margin() { |
| 1409 | // $0.05 at 20% is six cents. |
| 1410 | assert_eq!(charge_micros(0.05, 20), 60_000); |
| 1411 | assert_eq!(charge_micros(1.0, 20), 1_200_000); |
| 1412 | assert_eq!(charge_micros(0.05, 0), 50_000); |
| 1413 | } |
| 1414 | |
| 1415 | #[test] |
| 1416 | fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() { |
| 1417 | assert_eq!(charge_micros(0.000_000_4, 20), 2); |
| 1418 | assert_eq!(charge_micros(0.0, 20), 0); |
| 1419 | assert_eq!(charge_micros(-3.0, 20), 0); |
| 1420 | } |
| 1421 | |
| 1422 | #[test] |
| 1423 | fn sandbox_time_is_charged_from_the_first_second() { |
| 1424 | // 21 millionths a second at cost, plus 20%. |
| 1425 | let price = Price::price_for(21.0, 20); |
| 1426 | assert_eq!(sandbox_charge(1, price), 26); |
| 1427 | assert_eq!(sandbox_charge(60, price), 1_512); |
| 1428 | assert_eq!(sandbox_charge(0, price), 0); |
| 1429 | } |
| 1430 | |
| 1431 | #[test] |
| 1432 | fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() { |
| 1433 | assert!(prepay_amount(2_500, false).is_ok()); |
| 1434 | assert!(prepay_amount(2_499, false).is_err()); |
| 1435 | assert!(prepay_amount(10_000, false).is_ok()); |
| 1436 | assert!(prepay_amount(1_000_000, false).is_ok()); |
| 1437 | 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."); |
| 1438 | assert!(prepay_amount(99_999, true).is_err()); |
| 1439 | assert!(prepay_amount(100_000, true).is_ok()); |
| 1440 | } |
| 1441 | |
| 1442 | #[test] |
| 1443 | fn durations_read_plainly() { |
| 1444 | assert_eq!(duration(40), "40s"); |
| 1445 | assert_eq!(duration(192), "3m 12s"); |
| 1446 | assert_eq!(duration(3720), "1h 2m"); |
| 1447 | } |
| 1448 | |
| 1449 | #[test] |
| 1450 | fn an_absurd_cost_is_capped() { |
| 1451 | assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR); |
| 1452 | } |
| 1453 | |
| 1454 | /// Every migration, in order, as D1 applies them. |
| 1455 | const MIGRATIONS: &[&str] = &[ |
| 1456 | include_str!("../migrations/0001_init.sql"), |
| 1457 | include_str!("../migrations/0002_own_provider.sql"), |
| 1458 | include_str!("../migrations/0003_subscriptions.sql"), |
| 1459 | include_str!("../migrations/0004_sandbox_time.sql"), |
| 1460 | include_str!("../migrations/0005_limits.sql"), |
| 1461 | include_str!("../migrations/0006_prices.sql"), |
| 1462 | include_str!("../migrations/0007_pending_usage.sql"), |
| 1463 | include_str!("../migrations/0008_accounts.sql"), |
| 1464 | include_str!("../migrations/0009_autopay.sql"), |
| 1465 | include_str!("../migrations/0010_month_close.sql"), |
| 1466 | include_str!("../migrations/0011_limit_warnings.sql"), |
| 1467 | include_str!("../migrations/0012_stripe_webhooks.sql"), |
| 1468 | include_str!("../migrations/0013_invoices_trust_sales.sql"), |
| 1469 | include_str!("../migrations/0014_custom_domain_price.sql"), |
| 1470 | include_str!("../migrations/0015_sandbox_at_cost.sql"), |
| 1471 | include_str!("../migrations/0016_plans_and_pools.sql"), |
| 1472 | include_str!("../migrations/0017_flagon_comped.sql"), |
| 1473 | include_str!("../migrations/0018_one_plan.sql"), |
| 1474 | include_str!("../migrations/0019_closed_workspaces.sql"), |
| 1475 | include_str!("../migrations/0020_syntaqx_standard.sql"), |
| 1476 | include_str!("../migrations/0021_no_quotas.sql"), |
| 1477 | include_str!("../migrations/0022_costs_and_margin.sql"), |
| 1478 | include_str!("../migrations/0023_one_operation_mapping.sql"), |
| 1479 | include_str!("../migrations/0024_spend_caps.sql"), |
| 1480 | include_str!("../migrations/0025_run_tier.sql"), |
| 1481 | include_str!("../migrations/0026_ledger_by_workspace_time.sql"), |
| 1482 | include_str!("../migrations/0027_stripe_cache.sql"), |
| 1483 | include_str!("../migrations/0028_drop_stripe_webhooks.sql"), |
| 1484 | include_str!("../migrations/0029_audit_retention.sql"), |
| 1485 | include_str!("../migrations/0030_token_usage.sql"), |
| 1486 | include_str!("../migrations/0031_package_storage.sql"), |
| 1487 | include_str!("../migrations/0032_workspace_value.sql"), |
| 1488 | include_str!("../migrations/0033_given_away.sql"), |
| 1489 | include_str!("../migrations/0034_given_by_why.sql"), |
| 1490 | include_str!("../migrations/0035_cf_subscriptions.sql"), |
| 1491 | include_str!("../migrations/0036_model_costs_in_full.sql"), |
| 1492 | include_str!("../migrations/0037_security_activation.sql"), |
| 1493 | include_str!("../migrations/0038_staff_credits.sql"), |
| 1494 | include_str!("../migrations/0039_discounts_not_comped.sql"), |
| 1495 | include_str!("../migrations/0040_ai_credit.sql"), |
| 1496 | include_str!("../migrations/0041_agent_rate_own_key.sql"), |
| 1497 | include_str!("../migrations/0042_agent_rate_weights.sql"), |
| 1498 | include_str!("../migrations/0043_tax_and_card_fees.sql"), |
| 1499 | include_str!("../migrations/0044_cache_reads_count_a_tenth.sql"), |
| 1500 | include_str!("../migrations/0045_gateway.sql"), |
| 1501 | include_str!("../migrations/0046_reset_costs.sql"), |
| 1502 | include_str!("../migrations/0047_gateway_formats.sql"), |
| 1503 | ]; |
| 1504 | |
| 1505 | /// The columns of `table` after the migrations: each with whether an |
| 1506 | /// insert must give it (NOT NULL, no default). |
| 1507 | fn columns(table: &str) -> Vec<(String, bool)> { |
| 1508 | let mut out = vec![]; |
| 1509 | for sql in MIGRATIONS { |
| 1510 | let sql: String = sql.lines().map(|l| l.split("--").next().unwrap_or("")).collect::<Vec<_>>().join("\n"); |
| 1511 | if let Some(start) = sql.find(&format!("CREATE TABLE {table} (")) { |
| 1512 | let body = &sql[start + format!("CREATE TABLE {table} (").len()..]; |
| 1513 | let body = &body[..body.find(");").unwrap()]; |
| 1514 | for column in body.split(",\n") { |
| 1515 | let column = column.trim(); |
| 1516 | let name = column.split_whitespace().next().unwrap_or("").to_owned(); |
| 1517 | if name.is_empty() || name == "PRIMARY" { |
| 1518 | continue; |
| 1519 | } |
| 1520 | let required = column.contains("NOT NULL") && !column.contains("DEFAULT") && !column.contains("PRIMARY KEY"); |
| 1521 | out.push((name, required || column.contains("PRIMARY KEY"))); |
| 1522 | } |
| 1523 | } |
| 1524 | for statement in sql.split(';') { |
| 1525 | let s = statement.trim(); |
| 1526 | if let Some(rest) = s.strip_prefix(&format!("ALTER TABLE {table} ADD COLUMN ")) { |
| 1527 | let name = rest.split_whitespace().next().unwrap().to_owned(); |
| 1528 | out.push((name, rest.contains("NOT NULL") && !rest.contains("DEFAULT"))); |
| 1529 | } |
| 1530 | } |
| 1531 | } |
| 1532 | out |
| 1533 | } |
| 1534 | |
| 1535 | /// The columns an `INSERT INTO table (…)` names. |
| 1536 | fn inserted(sql: &str, table: &str) -> Vec<String> { |
| 1537 | let start = sql.find(&format!("INSERT INTO {table} (")).unwrap() + format!("INSERT INTO {table} (").len(); |
| 1538 | sql[start..start + sql[start..].find(')').unwrap()].split(',').map(|c| c.trim().to_owned()).collect() |
| 1539 | } |
| 1540 | |
| 1541 | |
| 1542 | #[test] |
| 1543 | fn ai_prices_are_price_book_data_with_dated_versions() { |
| 1544 | let sql = include_str!("../migrations/0040_ai_credit.sql"); |
| 1545 | let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned(); |
| 1546 | // AI Gateway: the provider's price, no markup while in beta. |
| 1547 | assert!(row("('gateway_models', 'AI Gateway models'").contains("1000000, 0, 'list'")); |
| 1548 | // Models lose their markup from 2026-10-08, a fall that applies at once… |
| 1549 | assert!(row("('pv_agent_models_2'").contains("1000000, 0, '2026-10-08")); |
| 1550 | // …and the agent rate is $0.25 a million tokens after 14 days' notice. |
| 1551 | assert!(row("('pv_agent_tokens_2'").contains("250000, 0, '2026-10-22")); |
| 1552 | // The card fee is 2.9% + 30¢, switchable. |
| 1553 | assert!(row("('card_fee_percent'").contains("29000")); |
| 1554 | assert!(row("('card_fee_fixed'").contains("300000")); |
| 1555 | assert!(row("('card_fee', 'on'").contains("'on'")); |
| 1556 | } |
| 1557 | |
| 1558 | #[test] |
| 1559 | fn the_agent_rate_on_an_own_model_key_is_its_own_dated_meter() { |
| 1560 | let sql = include_str!("../migrations/0041_agent_rate_own_key.sql"); |
| 1561 | let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned(); |
| 1562 | // Nothing until the notice has run… |
| 1563 | assert!(row("('pv_agent_tokens_own_1'").contains("0, 0, '2026-10-08")); |
| 1564 | // …then $0.25 a million tokens, as on g1t's models, 14 days after. |
| 1565 | assert!(row("('pv_agent_tokens_own_2'").contains("250000, 0, '2026-10-22")); |
| 1566 | assert!(row("('agent_tokens_own',").contains("'million tokens', 0, 0, 'list'")); |
| 1567 | assert_eq!(ai::agent_rate_meter(true), "agent_tokens_own"); |
| 1568 | } |
| 1569 | |
| 1570 | #[test] |
| 1571 | fn the_agent_rate_counts_every_token_once_until_a_weight_is_decided() { |
| 1572 | let sql = include_str!("../migrations/0042_agent_rate_weights.sql"); |
| 1573 | for kind in ["input", "output", "cache_read", "cache_write"] { |
| 1574 | let meter = format!("('agent_token_weight_{kind}', 'Agent rate weight"); |
| 1575 | let row = sql.lines().find(|l| l.contains(&meter)).unwrap_or_else(|| panic!("no {kind} weight")); |
| 1576 | assert!(row.contains("'weight', 1000000, 0, 'list'"), "{kind}: {row}"); |
| 1577 | let version = format!("('pv_agent_token_weight_{kind}_1', 'agent_token_weight_{kind}', 1, 1000000,"); |
| 1578 | assert!(sql.contains(&version), "{kind} has no applied version"); |
| 1579 | } |
| 1580 | assert_eq!(ai::weight_of(1_000_000.0), 1.0); |
| 1581 | } |
| 1582 | #[test] |
| 1583 | fn every_checkout_insert_fills_the_table() { |
| 1584 | // The plan's, the activation's, a card check's, a prepayment's and |
| 1585 | // AI credit's pages all go through one insert, and it names every |
| 1586 | // column the table needs and none it lacks: a missing NOT NULL |
| 1587 | // column, or one from a migration not yet applied, was a 500. |
| 1588 | let table = columns("checkouts"); |
| 1589 | let names: Vec<&str> = table.iter().map(|(n, _)| n.as_str()).collect(); |
| 1590 | assert_eq!(names, ["id", "workspace", "amount_cents", "created_by", "status", "created_at", "feature", "fee_cents"]); |
| 1591 | let given = inserted(CHECKOUT_INSERT, "checkouts"); |
| 1592 | for column in &given { |
| 1593 | assert!(names.contains(&column.as_str()), "the insert names {column}, which checkouts does not have"); |
| 1594 | } |
| 1595 | for (column, required) in &table { |
| 1596 | assert!(!required || given.contains(column), "checkouts needs {column}, which the insert leaves out"); |
| 1597 | } |
| 1598 | // As many values as columns. |
| 1599 | let values = CHECKOUT_INSERT.split("VALUES").nth(1).unwrap(); |
| 1600 | assert_eq!(values.matches('?').count() + values.matches("'open'").count(), given.len()); |
| 1601 | // And no page writes a row of its own any more. |
| 1602 | for (file, source) in [ |
| 1603 | ("lib.rs", include_str!("lib.rs")), |
| 1604 | ("features.rs", include_str!("features.rs")), |
| 1605 | ("cards.rs", include_str!("cards.rs")), |
| 1606 | ("ai.rs", include_str!("ai.rs")), |
| 1607 | ] { |
| 1608 | let inserts = source.matches(concat!("INSERT INTO ", "checkouts")).count(); |
| 1609 | assert!(inserts <= usize::from(file == "lib.rs"), "{file} inserts into checkouts on its own"); |
| 1610 | } |
| 1611 | } |
| 1612 | |
| 1613 | #[test] |
| 1614 | fn a_new_ledger_column_has_a_default() { |
| 1615 | // The ledger is written from a dozen places; a column without a |
| 1616 | // default would break every one that does not name it. |
| 1617 | for (column, required) in columns("ledger") { |
| 1618 | assert!(!required || ["id", "workspace", "kind", "amount_micros", "description", "reference", "created_at"].contains(&column.as_str()), "{column}"); |
| 1619 | } |
| 1620 | } |
| 1621 | } |