| 1 | //! The billing service: what agents cost, charged to the workspace they |
| 2 | //! worked for. |
| 3 | //! |
| 4 | //! A workspace buys credit with a card. Before the runner starts an agent |
| 5 | //! it asks here, and is refused if the workspace has none. When the |
| 6 | //! agent's sandbox finishes it reports what the model cost, and that plus |
| 7 | //! g1t's margin comes off the balance. Every change is a ledger entry, and |
| 8 | //! a balance is always the sum of its ledger. |
| 9 | //! |
| 10 | //! Paid features (deployments) are bought separately, as monthly plans; |
| 11 | //! see `features`. They are never free. |
| 12 | //! |
| 13 | //! Without a card processor configured the service says so and charges |
| 14 | //! nothing, so that g1t still runs where billing has not been set up. |
| 15 | //! |
| 16 | //! Reached only through service bindings; see `g1t_contracts::billing` for |
| 17 | //! the methods and their arguments. |
| 18 | |
| 19 | mod accounts; |
| 20 | mod invoices; |
| 21 | mod sales; |
| 22 | mod statement; |
| 23 | mod webhooks; |
| 24 | mod features; |
| 25 | mod keeper; |
| 26 | mod limits; |
| 27 | mod rename; |
| 28 | mod stripe; |
| 29 | |
| 30 | use g1t_contracts::billing::*; |
| 31 | use g1t_contracts::time::rfc3339; |
| 32 | use g1t_contracts::{FailureCode, Outcome, Role, new_id}; |
| 33 | use g1t_contracts::billing::TermsKind; |
| 34 | use g1t_kit::{args, now_ms, reply, rpc_method}; |
| 35 | use serde::Deserialize; |
| 36 | use sha2::{Digest, Sha256}; |
| 37 | use worker::wasm_bindgen::JsValue; |
| 38 | use worker::{Context, D1Database, Env, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event}; |
| 39 | |
| 40 | use stripe::Stripe; |
| 41 | |
| 42 | const MIN_TOP_UP_CENTS: u32 = 500; |
| 43 | const MAX_TOP_UP_CENTS: u32 = 50_000; |
| 44 | const LEDGER_PAGE: u32 = 100; |
| 45 | /// A run's reported cost is believed up to this much. A sandbox cannot |
| 46 | /// spend more in the time it has, so anything above is a fault. |
| 47 | const MAX_RUN_COST_USD: f64 = 100.0; |
| 48 | |
| 49 | /// What a run is charged: its cost plus the margin, rounded up to a whole |
| 50 | /// millionth of a dollar. |
| 51 | pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 { |
| 52 | let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil(); |
| 53 | (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64 |
| 54 | } |
| 55 | |
| 56 | fn hash(token: &str) -> String { |
| 57 | hex::encode(Sha256::digest(token.as_bytes())) |
| 58 | } |
| 59 | |
| 60 | fn optional(value: Option<&str>) -> JsValue { |
| 61 | value.map_or(JsValue::NULL, JsValue::from) |
| 62 | } |
| 63 | |
| 64 | #[derive(Deserialize)] |
| 65 | struct AccountRow { |
| 66 | balance_micros: i64, |
| 67 | customer_id: Option<String>, |
| 68 | } |
| 69 | |
| 70 | #[derive(Deserialize)] |
| 71 | struct LedgerRow { |
| 72 | id: String, |
| 73 | kind: EntryKind, |
| 74 | amount_micros: i64, |
| 75 | description: String, |
| 76 | repo: Option<String>, |
| 77 | number: Option<u32>, |
| 78 | task: Option<String>, |
| 79 | model: Option<String>, |
| 80 | created_by: Option<String>, |
| 81 | created_at: String, |
| 82 | billed_to: Option<String>, |
| 83 | #[serde(default)] |
| 84 | workspace: Option<String>, |
| 85 | } |
| 86 | |
| 87 | impl From<LedgerRow> for LedgerEntry { |
| 88 | fn from(row: LedgerRow) -> Self { |
| 89 | LedgerEntry { |
| 90 | id: row.id, |
| 91 | kind: row.kind, |
| 92 | amount_micros: row.amount_micros, |
| 93 | description: row.description, |
| 94 | repo: row.repo, |
| 95 | number: row.number, |
| 96 | task: row.task, |
| 97 | model: row.model, |
| 98 | billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()), |
| 99 | created_by: row.created_by, |
| 100 | created_at: row.created_at, |
| 101 | workspace: row.workspace, |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | #[derive(Deserialize)] |
| 107 | struct RunRow { |
| 108 | workspace: String, |
| 109 | repo: String, |
| 110 | number: u32, |
| 111 | task: String, |
| 112 | model: String, |
| 113 | token_hash: String, |
| 114 | billed_to: Option<String>, |
| 115 | } |
| 116 | |
| 117 | impl RunRow { |
| 118 | fn own_provider(&self) -> bool { |
| 119 | self.billed_to.as_deref() == Some("workspace") |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | #[derive(Deserialize)] |
| 124 | struct CheckoutRow { |
| 125 | workspace: String, |
| 126 | created_by: String, |
| 127 | } |
| 128 | |
| 129 | /// A row an `UPDATE … RETURNING` touched. |
| 130 | #[derive(Deserialize)] |
| 131 | struct Touched { |
| 132 | #[allow(dead_code)] |
| 133 | id: String, |
| 134 | } |
| 135 | |
| 136 | struct Billing { |
| 137 | db: D1Database, |
| 138 | /// Absent when no card processor is configured. |
| 139 | stripe: Option<Stripe>, |
| 140 | margin_percent: u32, |
| 141 | /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`). |
| 142 | free: bool, |
| 143 | /// The free allowance on g1t's hosted models, when there is one. |
| 144 | trial: Option<TrialConfig>, |
| 145 | /// The Deployments plan's monthly price (`DEPLOYMENTS_MONTHLY_CENTS`). |
| 146 | deployments_monthly_cents: u32, |
| 147 | /// How far unpaid usage may go; see `limits`. |
| 148 | ceilings: limits::Ceilings, |
| 149 | /// `PREPAID_ONLY`: the old rule, that agents need credit first. |
| 150 | prepaid_only: bool, |
| 151 | } |
| 152 | |
| 153 | /// `TRIAL_WORKSPACE_MICROS`, `TRIAL_TOTAL_MICROS` and `TRIAL_UNTIL`. |
| 154 | struct TrialConfig { |
| 155 | per_workspace_micros: i64, |
| 156 | total_micros: i64, |
| 157 | /// RFC 3339, in UTC. |
| 158 | until: String, |
| 159 | } |
| 160 | |
| 161 | #[derive(serde::Deserialize)] |
| 162 | struct Sum { |
| 163 | micros: Option<i64>, |
| 164 | } |
| 165 | |
| 166 | impl Billing { |
| 167 | fn status(&self) -> Status { |
| 168 | Status { |
| 169 | enabled: self.stripe.is_some(), |
| 170 | live: self.stripe.as_ref().is_some_and(Stripe::live), |
| 171 | free: self.free, |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> { |
| 176 | self.db |
| 177 | .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?") |
| 178 | .bind(&[workspace.into()])? |
| 179 | .first::<AccountRow>(None) |
| 180 | .await |
| 181 | } |
| 182 | |
| 183 | async fn standing(&self, workspace: &str) -> Result<Account> { |
| 184 | let row = self.row(workspace).await?; |
| 185 | let card = match (&self.stripe, row.as_ref().and_then(|row| row.customer_id.as_deref())) { |
| 186 | (Some(stripe), Some(customer)) => stripe.card(customer).await.ok().flatten().map(|card| Card { |
| 187 | brand: card.brand, |
| 188 | last4: card.last4, |
| 189 | exp_month: card.exp_month, |
| 190 | exp_year: card.exp_year, |
| 191 | }), |
| 192 | _ => None, |
| 193 | }; |
| 194 | Ok(Account { |
| 195 | workspace: workspace.to_owned(), |
| 196 | balance_micros: row.map_or(0, |row| row.balance_micros), |
| 197 | status: self.status(), |
| 198 | margin_percent: self.margin_percent, |
| 199 | card, |
| 200 | }) |
| 201 | } |
| 202 | |
| 203 | /// The workspace's customer at Stripe, made the first time one is needed. |
| 204 | pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> { |
| 205 | let Some(stripe) = &self.stripe else { |
| 206 | return Err(worker::Error::RustError("payments are not set up".into())); |
| 207 | }; |
| 208 | if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) { |
| 209 | return Ok(customer); |
| 210 | } |
| 211 | let customer = stripe.create_customer(workspace).await?; |
| 212 | self.db |
| 213 | .prepare( |
| 214 | "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3) |
| 215 | ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2", |
| 216 | ) |
| 217 | .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])? |
| 218 | .run() |
| 219 | .await?; |
| 220 | Ok(customer) |
| 221 | } |
| 222 | |
| 223 | /// Stripe's hosted billing page for the workspace. Owners only. |
| 224 | async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> { |
| 225 | let workspace = a.workspace.to_lowercase(); |
| 226 | if a.actor.role_in(&workspace) != Some(Role::Owner) { |
| 227 | return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing.")); |
| 228 | } |
| 229 | let Some(stripe) = &self.stripe else { |
| 230 | return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t.")); |
| 231 | }; |
| 232 | let customer = match self.customer_for(&workspace).await { |
| 233 | Ok(customer) => customer, |
| 234 | Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))), |
| 235 | }; |
| 236 | match stripe.portal_session(&customer, &a.return_url).await { |
| 237 | Ok(url) => Ok(Outcome::Ok(Checkout { url })), |
| 238 | Err(error) if stripe::is_missing(&error) => { |
| 239 | // The customer was removed at Stripe: a new one next time. |
| 240 | self.forget_customer(&workspace).await?; |
| 241 | Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again.")) |
| 242 | } |
| 243 | Err(error) => Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe's billing page could not be opened: {error}"))), |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | /// Adds a ledger entry and moves the balance by the same amount, as |
| 248 | /// one write. |
| 249 | #[allow(clippy::too_many_arguments)] |
| 250 | async fn enter( |
| 251 | &self, |
| 252 | workspace: &str, |
| 253 | kind: EntryKind, |
| 254 | amount_micros: i64, |
| 255 | description: &str, |
| 256 | reference: &str, |
| 257 | run: Option<&RunRow>, |
| 258 | cost_micros: Option<i64>, |
| 259 | created_by: Option<&str>, |
| 260 | customer: Option<&str>, |
| 261 | ) -> Result<()> { |
| 262 | let now = now_ms(); |
| 263 | let timestamp = rfc3339(now); |
| 264 | let kind = match kind { |
| 265 | EntryKind::TopUp => "top_up", |
| 266 | EntryKind::Usage => "usage", |
| 267 | }; |
| 268 | self.db |
| 269 | .batch(vec![ |
| 270 | self.db |
| 271 | .prepare( |
| 272 | "INSERT INTO ledger |
| 273 | (id, workspace, kind, amount_micros, description, repo, number, task, |
| 274 | model, cost_micros, reference, created_by, created_at, billed_to) |
| 275 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 276 | ) |
| 277 | .bind(&[ |
| 278 | new_id("led", now).into(), |
| 279 | workspace.into(), |
| 280 | kind.into(), |
| 281 | // D1 takes numbers as doubles, which hold every |
| 282 | // amount this service will see exactly. |
| 283 | (amount_micros as f64).into(), |
| 284 | description.into(), |
| 285 | optional(run.map(|run| run.repo.as_str())), |
| 286 | run.map_or(JsValue::NULL, |run| run.number.into()), |
| 287 | optional(run.map(|run| run.task.as_str())), |
| 288 | optional(run.map(|run| run.model.as_str())), |
| 289 | cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()), |
| 290 | reference.into(), |
| 291 | optional(created_by), |
| 292 | timestamp.as_str().into(), |
| 293 | run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(), |
| 294 | ])?, |
| 295 | self.db |
| 296 | .prepare( |
| 297 | "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) |
| 298 | VALUES (?1, ?2, ?3, ?4) |
| 299 | ON CONFLICT (workspace) DO UPDATE SET |
| 300 | balance_micros = balance_micros + ?2, |
| 301 | customer_id = COALESCE(?3, customer_id)", |
| 302 | ) |
| 303 | .bind(&[ |
| 304 | workspace.into(), |
| 305 | (amount_micros as f64).into(), |
| 306 | optional(customer), |
| 307 | timestamp.as_str().into(), |
| 308 | ])?, |
| 309 | ]) |
| 310 | .await?; |
| 311 | // Money in clears a card declined at the limit. |
| 312 | if kind == "top_up" { |
| 313 | self.db |
| 314 | .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?") |
| 315 | .bind(&[workspace.into()])? |
| 316 | .run() |
| 317 | .await?; |
| 318 | } |
| 319 | Ok(()) |
| 320 | } |
| 321 | |
| 322 | async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> { |
| 323 | let workspace = a.workspace.to_lowercase(); |
| 324 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { |
| 325 | return Ok(members_only()); |
| 326 | } |
| 327 | Ok(Outcome::Ok(self.standing(&workspace).await?)) |
| 328 | } |
| 329 | |
| 330 | async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> { |
| 331 | let workspace = a.workspace.to_lowercase(); |
| 332 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { |
| 333 | return Ok(members_only()); |
| 334 | } |
| 335 | let rows = self |
| 336 | .db |
| 337 | .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?") |
| 338 | .bind(&[workspace.into(), LEDGER_PAGE.into()])? |
| 339 | .all() |
| 340 | .await? |
| 341 | .results::<LedgerRow>()?; |
| 342 | Ok(Outcome::Ok( |
| 343 | rows.into_iter().map(LedgerEntry::from).collect(), |
| 344 | )) |
| 345 | } |
| 346 | |
| 347 | async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> { |
| 348 | let workspace = a.workspace.to_lowercase(); |
| 349 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { |
| 350 | return Ok(members_only()); |
| 351 | } |
| 352 | #[derive(serde::Deserialize)] |
| 353 | struct SliceRow { |
| 354 | key: Option<String>, |
| 355 | micros: Option<i64>, |
| 356 | runs: Option<u32>, |
| 357 | } |
| 358 | // While nothing is charged, what was used is what there is to show. |
| 359 | let measure = if self.free { "COALESCE(cost_micros, 0)" } else { "-amount_micros" }; |
| 360 | let slices = |key: &str, limit: u32| { |
| 361 | format!( |
| 362 | "SELECT {key} AS key, SUM({measure}) AS micros, COUNT(*) AS runs FROM ledger |
| 363 | WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2 |
| 364 | GROUP BY 1 ORDER BY micros DESC LIMIT {limit}" |
| 365 | ) |
| 366 | }; |
| 367 | let query = |sql: String| { |
| 368 | let db = &self.db; |
| 369 | let workspace = workspace.clone(); |
| 370 | let since = a.since.clone(); |
| 371 | async move { |
| 372 | let rows = db |
| 373 | .prepare(sql) |
| 374 | .bind(&[workspace.into(), since.into()])? |
| 375 | .all() |
| 376 | .await? |
| 377 | .results::<SliceRow>()?; |
| 378 | Ok::<Vec<UsageSlice>, worker::Error>( |
| 379 | rows.into_iter() |
| 380 | .map(|row| UsageSlice { |
| 381 | key: row.key.unwrap_or_else(|| "other".to_owned()), |
| 382 | micros: row.micros.unwrap_or_default(), |
| 383 | runs: row.runs.unwrap_or_default(), |
| 384 | }) |
| 385 | .collect(), |
| 386 | ) |
| 387 | } |
| 388 | }; |
| 389 | #[derive(serde::Deserialize)] |
| 390 | struct Totals { |
| 391 | spent: Option<i64>, |
| 392 | cost: Option<i64>, |
| 393 | provider: Option<i64>, |
| 394 | runs: Option<u32>, |
| 395 | added: Option<i64>, |
| 396 | } |
| 397 | let totals = self |
| 398 | .db |
| 399 | .prepare( |
| 400 | "SELECT |
| 401 | -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent, |
| 402 | SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost, |
| 403 | SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider, |
| 404 | SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs, |
| 405 | SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added |
| 406 | FROM ledger WHERE workspace = ?1 AND created_at >= ?2", |
| 407 | ) |
| 408 | .bind(&[workspace.as_str().into(), a.since.as_str().into()])? |
| 409 | .first::<Totals>(None) |
| 410 | .await?; |
| 411 | let totals = totals.unwrap_or(Totals { |
| 412 | spent: None, |
| 413 | cost: None, |
| 414 | provider: None, |
| 415 | runs: None, |
| 416 | added: None, |
| 417 | }); |
| 418 | Ok(Outcome::Ok(Usage { |
| 419 | spent_micros: totals.spent.unwrap_or_default(), |
| 420 | cost_micros: totals.cost.unwrap_or_default(), |
| 421 | provider_micros: totals.provider.unwrap_or_default(), |
| 422 | used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(), |
| 423 | free: self.free, |
| 424 | runs: totals.runs.unwrap_or_default(), |
| 425 | added_micros: totals.added.unwrap_or_default(), |
| 426 | by_day: query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)).await?, |
| 427 | by_task: query(slices("task", 20)).await?, |
| 428 | by_repo: query(slices("repo", 20)).await?, |
| 429 | by_pull: query(slices("repo || '#' || number", 10)).await?, |
| 430 | by_model: query(slices("model", 10)).await?, |
| 431 | since: a.since, |
| 432 | })) |
| 433 | } |
| 434 | |
| 435 | async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> { |
| 436 | let workspace = a.workspace.to_lowercase(); |
| 437 | if a.actor.role_in(&workspace) != Some(Role::Owner) { |
| 438 | return Ok(Outcome::fail( |
| 439 | FailureCode::Forbidden, |
| 440 | "Only an owner can add credit to a workspace.", |
| 441 | )); |
| 442 | } |
| 443 | let Some(stripe) = &self.stripe else { |
| 444 | return Ok(Outcome::fail( |
| 445 | FailureCode::Conflict, |
| 446 | "Payments are not set up on this g1t yet.", |
| 447 | )); |
| 448 | }; |
| 449 | if !(MIN_TOP_UP_CENTS..=MAX_TOP_UP_CENTS).contains(&a.amount_cents) { |
| 450 | return Ok(Outcome::fail( |
| 451 | FailureCode::Invalid, |
| 452 | format!( |
| 453 | "Add between ${} and ${} at a time.", |
| 454 | MIN_TOP_UP_CENTS / 100, |
| 455 | MAX_TOP_UP_CENTS / 100 |
| 456 | ), |
| 457 | )); |
| 458 | } |
| 459 | let customer = self.row(&workspace).await?.and_then(|row| row.customer_id); |
| 460 | let session = match stripe |
| 461 | .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url) |
| 462 | .await |
| 463 | { |
| 464 | Ok(session) => session, |
| 465 | // A customer saved under another Stripe account: start afresh. |
| 466 | Err(error) if customer.is_some() && stripe::is_missing(&error) => { |
| 467 | self.forget_customer(&workspace).await?; |
| 468 | stripe.start_checkout(&workspace, a.amount_cents, None, &a.return_url).await? |
| 469 | } |
| 470 | Err(error) => return Err(error), |
| 471 | }; |
| 472 | let Some(url) = session.url else { |
| 473 | return Err(worker::Error::RustError( |
| 474 | "the card processor returned no payment page".into(), |
| 475 | )); |
| 476 | }; |
| 477 | self.db |
| 478 | .prepare( |
| 479 | "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at) |
| 480 | VALUES (?, ?, ?, ?, ?)", |
| 481 | ) |
| 482 | .bind(&[ |
| 483 | session.id.into(), |
| 484 | workspace.into(), |
| 485 | a.amount_cents.into(), |
| 486 | a.actor.username.into(), |
| 487 | rfc3339(now_ms()).into(), |
| 488 | ])? |
| 489 | .run() |
| 490 | .await?; |
| 491 | Ok(Outcome::Ok(Checkout { url })) |
| 492 | } |
| 493 | |
| 494 | /// Credits a payment if the processor says it was made and it has not |
| 495 | /// been credited before. The amount credited is what the processor |
| 496 | /// says was paid, not what anyone here remembers asking for. |
| 497 | async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> { |
| 498 | let workspace = a.workspace.to_lowercase(); |
| 499 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { |
| 500 | return Ok(members_only()); |
| 501 | } |
| 502 | let (Some(stripe), Some(checkout)) = ( |
| 503 | &self.stripe, |
| 504 | self.db |
| 505 | .prepare( |
| 506 | "SELECT workspace, created_by FROM checkouts |
| 507 | WHERE id = ? AND workspace = ? AND status = 'open'", |
| 508 | ) |
| 509 | .bind(&[a.session.as_str().into(), workspace.as_str().into()])? |
| 510 | .first::<CheckoutRow>(None) |
| 511 | .await?, |
| 512 | ) else { |
| 513 | // Unknown, someone else's, or already credited: nothing to do. |
| 514 | return Ok(Outcome::Ok(self.standing(&workspace).await?)); |
| 515 | }; |
| 516 | let session = stripe.session(&a.session).await?; |
| 517 | let paid = session |
| 518 | .amount_total |
| 519 | .filter(|_| session.payment_status == "paid"); |
| 520 | if let Some(cents) = paid { |
| 521 | // Only whoever flips it from open to paid enters the credit. |
| 522 | let claimed = self |
| 523 | .db |
| 524 | .prepare( |
| 525 | "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open' |
| 526 | RETURNING id", |
| 527 | ) |
| 528 | .bind(&[a.session.as_str().into()])? |
| 529 | .first::<Touched>(None) |
| 530 | .await?; |
| 531 | if claimed.is_some() { |
| 532 | self.enter( |
| 533 | &checkout.workspace, |
| 534 | EntryKind::TopUp, |
| 535 | i64::from(cents) * MICROS_PER_DOLLAR / 100, |
| 536 | "Credit added by card", |
| 537 | &session.id, |
| 538 | None, |
| 539 | None, |
| 540 | Some(&checkout.created_by), |
| 541 | session.customer.as_deref(), |
| 542 | ) |
| 543 | .await?; |
| 544 | } |
| 545 | } |
| 546 | Ok(Outcome::Ok(self.standing(&workspace).await?)) |
| 547 | } |
| 548 | |
| 549 | /// Drops a saved customer the card processor no longer knows. |
| 550 | pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> { |
| 551 | self.db |
| 552 | .prepare("UPDATE accounts SET customer_id = NULL WHERE workspace = ?") |
| 553 | .bind(&[workspace.into()])? |
| 554 | .run() |
| 555 | .await?; |
| 556 | Ok(()) |
| 557 | } |
| 558 | |
| 559 | /// A refusal if the workspace has no credit to start an agent with. |
| 560 | async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> { |
| 561 | // Billing is postpaid: usage limits decide whether work starts |
| 562 | // (see `limits`), and credit is a prepayment that lowers what is |
| 563 | // owed. A balance no longer has to be positive to start. |
| 564 | if self.free || !self.prepaid_only { |
| 565 | return Ok(None); |
| 566 | } |
| 567 | let balance = self |
| 568 | .row(workspace) |
| 569 | .await? |
| 570 | .map_or(0, |row| row.balance_micros); |
| 571 | Ok((balance <= 0).then(|| { |
| 572 | Outcome::fail( |
| 573 | FailureCode::PaymentRequired, |
| 574 | format!( |
| 575 | "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page." |
| 576 | ), |
| 577 | ) |
| 578 | })) |
| 579 | } |
| 580 | |
| 581 | /// A workspace's free allowance on g1t's hosted models: what its runs |
| 582 | /// there have cost against its share, and the pool everyone draws on. |
| 583 | /// How much of a hosted model run's cost the workspace's free allowance |
| 584 | /// covers, if it is still open. |
| 585 | async fn trial_covers(&self, workspace: &str, cost_micros: i64) -> Result<i64> { |
| 586 | let trial = self.trial(TrialArgs { workspace: workspace.to_owned(), exempt: vec![] }).await?; |
| 587 | if !trial.open { |
| 588 | return Ok(0); |
| 589 | } |
| 590 | Ok(cost_micros.min((trial.limit_micros - trial.used_micros).max(0))) |
| 591 | } |
| 592 | |
| 593 | async fn trial(&self, a: TrialArgs) -> Result<Trial> { |
| 594 | let workspace = a.workspace.to_lowercase(); |
| 595 | let Some(config) = &self.trial else { |
| 596 | return Ok(Trial { |
| 597 | open: false, |
| 598 | used_micros: 0, |
| 599 | limit_micros: 0, |
| 600 | ends_at: None, |
| 601 | reason: Some("off".to_owned()), |
| 602 | }); |
| 603 | }; |
| 604 | let used = self |
| 605 | .db |
| 606 | .prepare( |
| 607 | "SELECT SUM(cost_micros) AS micros FROM ledger |
| 608 | WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND COALESCE(task, '') NOT IN ('sandbox', 'deployments') AND workspace = ?", |
| 609 | ) |
| 610 | .bind(&[workspace.as_str().into()])? |
| 611 | .first::<Sum>(None) |
| 612 | .await? |
| 613 | .and_then(|sum| sum.micros) |
| 614 | .unwrap_or_default(); |
| 615 | // Everyone's, but for the workspaces open to hosted models anyway. |
| 616 | let exempt: Vec<String> = a.exempt.iter().map(|name| name.trim().to_lowercase()).collect(); |
| 617 | let marks = vec!["?"; exempt.len().max(1)].join(", "); |
| 618 | let mut values: Vec<JsValue> = exempt.iter().map(|name| JsValue::from(name.as_str())).collect(); |
| 619 | if values.is_empty() { |
| 620 | values.push(JsValue::from("")); |
| 621 | } |
| 622 | let pooled = self |
| 623 | .db |
| 624 | .prepare(format!( |
| 625 | "SELECT SUM(cost_micros) AS micros FROM ledger |
| 626 | WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND COALESCE(task, '') NOT IN ('sandbox', 'deployments') AND workspace NOT IN ({marks})" |
| 627 | )) |
| 628 | .bind(&values)? |
| 629 | .first::<Sum>(None) |
| 630 | .await? |
| 631 | .and_then(|sum| sum.micros) |
| 632 | .unwrap_or_default(); |
| 633 | let reason = if rfc3339(now_ms()) >= config.until { |
| 634 | Some("ended") |
| 635 | } else if used >= config.per_workspace_micros { |
| 636 | Some("used") |
| 637 | } else if pooled >= config.total_micros { |
| 638 | Some("pool") |
| 639 | } else { |
| 640 | None |
| 641 | }; |
| 642 | Ok(Trial { |
| 643 | open: reason.is_none(), |
| 644 | used_micros: used, |
| 645 | limit_micros: config.per_workspace_micros, |
| 646 | ends_at: Some(config.until.clone()), |
| 647 | reason: reason.map(str::to_owned), |
| 648 | }) |
| 649 | } |
| 650 | |
| 651 | async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> { |
| 652 | if self.stripe.is_none() { |
| 653 | return Ok(Outcome::Ok(true)); |
| 654 | } |
| 655 | if let Some(stopped) = self.stopped(&a.workspace).await? { |
| 656 | return Ok(stopped); |
| 657 | } |
| 658 | Ok(self |
| 659 | .out_of_credit(&a.workspace.to_lowercase()) |
| 660 | .await? |
| 661 | .unwrap_or(Outcome::Ok(true))) |
| 662 | } |
| 663 | |
| 664 | async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> { |
| 665 | if self.stripe.is_none() { |
| 666 | return Ok(Outcome::Ok(None)); |
| 667 | } |
| 668 | let workspace = a.workspace.to_lowercase(); |
| 669 | if let Some(stopped) = self.stopped(&workspace).await? { |
| 670 | return Ok(stopped); |
| 671 | } |
| 672 | if let Some(refused) = self.out_of_credit(&workspace).await? { |
| 673 | return Ok(refused); |
| 674 | } |
| 675 | let now = now_ms(); |
| 676 | let run_id = new_id("run", now); |
| 677 | let mut bytes = [0u8; 32]; |
| 678 | getrandom::getrandom(&mut bytes).expect("no source of randomness"); |
| 679 | let token = hex::encode(bytes); |
| 680 | self.db |
| 681 | .prepare( |
| 682 | "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id) |
| 683 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 684 | ) |
| 685 | .bind(&[ |
| 686 | run_id.as_str().into(), |
| 687 | workspace.into(), |
| 688 | format!("{}/{}", a.repo.namespace, a.repo.name).into(), |
| 689 | a.number.into(), |
| 690 | a.task.into(), |
| 691 | a.model.into(), |
| 692 | hash(&token).into(), |
| 693 | rfc3339(now).into(), |
| 694 | if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(), |
| 695 | optional(a.session.as_deref().filter(|_| a.billed_to != "workspace")), |
| 696 | ])? |
| 697 | .run() |
| 698 | .await?; |
| 699 | Ok(Outcome::Ok(Some(RunTicket { run_id, token }))) |
| 700 | } |
| 701 | |
| 702 | async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> { |
| 703 | let run = self |
| 704 | .db |
| 705 | .prepare( |
| 706 | "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs |
| 707 | WHERE id = ? AND finished_at IS NULL", |
| 708 | ) |
| 709 | .bind(&[a.run_id.as_str().into()])? |
| 710 | .first::<RunRow>(None) |
| 711 | .await?; |
| 712 | let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else { |
| 713 | return Ok(Outcome::fail(FailureCode::NotFound, "Run not found.")); |
| 714 | }; |
| 715 | if !a.cost_usd.is_finite() || a.cost_usd < 0.0 { |
| 716 | return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost.")); |
| 717 | } |
| 718 | // Only whoever closes the run charges for it. |
| 719 | let claimed = self |
| 720 | .db |
| 721 | .prepare( |
| 722 | "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id", |
| 723 | ) |
| 724 | .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])? |
| 725 | .first::<Touched>(None) |
| 726 | .await?; |
| 727 | if claimed.is_none() { |
| 728 | return Ok(Outcome::Ok(false)); |
| 729 | } |
| 730 | // On the workspace's own provider, the model was paid for there, |
| 731 | // and the run's sandbox time is recorded on its own: nothing more |
| 732 | // to charge. |
| 733 | if run.own_provider() { |
| 734 | return Ok(Outcome::Ok(true)); |
| 735 | } |
| 736 | // The free allowance on g1t's models covers what it can. |
| 737 | let cost = charge_micros(a.cost_usd, 0); |
| 738 | let covered = self.trial_covers(&run.workspace, cost).await?; |
| 739 | let base = charge_micros((cost - covered) as f64 / MICROS_PER_DOLLAR as f64, self.margin_percent); |
| 740 | let (charge, terms_note) = self.charged(&run.workspace, base).await?; |
| 741 | let mut description = match run.task.as_str() { |
| 742 | "plan" => format!("Planning for {}", run.repo), |
| 743 | "review" => format!("Review of {}#{}", run.repo, run.number), |
| 744 | "update" => format!("Catching up {}#{}", run.repo, run.number), |
| 745 | _ => format!("Work on {}#{}", run.repo, run.number), |
| 746 | }; |
| 747 | description.push_str(&terms_note); |
| 748 | self.enter( |
| 749 | &run.workspace, |
| 750 | EntryKind::Usage, |
| 751 | -charge, |
| 752 | &description, |
| 753 | &a.run_id, |
| 754 | Some(&run), |
| 755 | Some(charge_micros(a.cost_usd, 0)), |
| 756 | None, |
| 757 | None, |
| 758 | ) |
| 759 | .await?; |
| 760 | Ok(Outcome::Ok(true)) |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | impl Billing { |
| 765 | /// Records how long a sandbox ran, with its cost and its charge: every |
| 766 | /// second, from the first, at the price book's price. |
| 767 | async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> { |
| 768 | if self.stripe.is_none() || a.seconds == 0 { |
| 769 | return Ok(Outcome::Ok(false)); |
| 770 | } |
| 771 | let workspace = a.workspace.to_lowercase(); |
| 772 | let seen = self |
| 773 | .db |
| 774 | .prepare("SELECT id FROM ledger WHERE reference = ?") |
| 775 | .bind(&[a.reference.as_str().into()])? |
| 776 | .first::<Touched>(None) |
| 777 | .await?; |
| 778 | if seen.is_some() { |
| 779 | return Ok(Outcome::Ok(false)); |
| 780 | } |
| 781 | let now = now_ms(); |
| 782 | let timestamp = rfc3339(now); |
| 783 | let seconds = i64::from(a.seconds); |
| 784 | // From the price book, which follows what Cloudflare bills g1t. A |
| 785 | // sandbox is the same container as a build, so without a row it is |
| 786 | // a build second's cost plus the margin. |
| 787 | let (cost_per_second, price_per_second) = self.price("sandbox_second").await?.unwrap_or_else(|| { |
| 788 | let cost = deployments_allowance::MICROS_PER_BUILD_SECOND as f64; |
| 789 | (cost, Price::price_for(cost, self.margin_percent)) |
| 790 | }); |
| 791 | let (charge, terms_note) = self.charged(&workspace, sandbox_charge(seconds, price_per_second)).await?; |
| 792 | let description = format!("{}: {} of sandbox time{terms_note}", a.description, duration(seconds)); |
| 793 | self.db |
| 794 | .batch(vec![ |
| 795 | self.db |
| 796 | .prepare( |
| 797 | "INSERT INTO ledger |
| 798 | (id, workspace, kind, amount_micros, description, repo, task, |
| 799 | cost_micros, reference, created_at, billed_to) |
| 800 | VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t')", |
| 801 | ) |
| 802 | .bind(&[ |
| 803 | new_id("led", now).into(), |
| 804 | workspace.as_str().into(), |
| 805 | (-(charge as f64)).into(), |
| 806 | description.as_str().into(), |
| 807 | optional(a.repo.as_deref()), |
| 808 | (seconds as f64 * cost_per_second).ceil().into(), |
| 809 | a.reference.as_str().into(), |
| 810 | timestamp.as_str().into(), |
| 811 | ])?, |
| 812 | self.db |
| 813 | .prepare( |
| 814 | "INSERT INTO accounts (workspace, balance_micros, created_at) |
| 815 | VALUES (?1, ?2, ?3) |
| 816 | ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2", |
| 817 | ) |
| 818 | .bind(&[ |
| 819 | workspace.as_str().into(), |
| 820 | (-(charge as f64)).into(), |
| 821 | timestamp.as_str().into(), |
| 822 | ])?, |
| 823 | ]) |
| 824 | .await?; |
| 825 | Ok(Outcome::Ok(true)) |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | /// What `seconds` of sandbox time are charged at `price_per_second`, in |
| 830 | /// millionths of a dollar: every second, rounded up to the next millionth. |
| 831 | fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 { |
| 832 | (seconds as f64 * price_per_second).ceil() as i64 |
| 833 | } |
| 834 | |
| 835 | /// `1h 2m`, `3m 12s` or `40s`. |
| 836 | fn duration(seconds: i64) -> String { |
| 837 | let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60); |
| 838 | if h > 0 { |
| 839 | format!("{h}h {m}m") |
| 840 | } else if m > 0 { |
| 841 | format!("{m}m {s}s") |
| 842 | } else { |
| 843 | format!("{s}s") |
| 844 | } |
| 845 | } |
| 846 | |
| 847 | impl Billing { |
| 848 | /// What a workspace is charged for something that would be `base`: |
| 849 | /// nothing while g1t is free, or as its account's terms say. With a |
| 850 | /// note for the statement when it differs. |
| 851 | pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String)> { |
| 852 | if self.free { |
| 853 | return Ok((0, " (free while g1t is being built out)".to_owned())); |
| 854 | } |
| 855 | let terms = self.terms_of(workspace).await?; |
| 856 | let charge = terms.apply(base); |
| 857 | let note = match terms.kind { |
| 858 | TermsKind::Comped => " (comped)".to_owned(), |
| 859 | TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent), |
| 860 | _ => String::new(), |
| 861 | }; |
| 862 | Ok((charge, note)) |
| 863 | } |
| 864 | } |
| 865 | |
| 866 | fn members_only<T>() -> Outcome<T> { |
| 867 | Outcome::fail( |
| 868 | FailureCode::Forbidden, |
| 869 | "Only members can see a workspace's billing.", |
| 870 | ) |
| 871 | } |
| 872 | |
| 873 | impl Billing { |
| 874 | fn from_env(env: &Env) -> Result<Self> { |
| 875 | Ok(Billing { |
| 876 | db: env.d1("DB")?, |
| 877 | stripe: env |
| 878 | .secret("STRIPE_SECRET_KEY") |
| 879 | .ok() |
| 880 | .map(|key| key.to_string()) |
| 881 | .filter(|key| !key.is_empty()) |
| 882 | .map(Stripe::new), |
| 883 | margin_percent: env |
| 884 | .var("MARGIN_PERCENT") |
| 885 | .ok() |
| 886 | .and_then(|percent| percent.to_string().parse().ok()) |
| 887 | .unwrap_or(20), |
| 888 | free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"), |
| 889 | ceilings: limits::Ceilings::from_env(&env), |
| 890 | prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"), |
| 891 | deployments_monthly_cents: env |
| 892 | .var("DEPLOYMENTS_MONTHLY_CENTS") |
| 893 | .ok() |
| 894 | .and_then(|cents| cents.to_string().parse().ok()) |
| 895 | .unwrap_or(500), |
| 896 | trial: { |
| 897 | let number = |name: &str| env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok()); |
| 898 | match ( |
| 899 | number("TRIAL_WORKSPACE_MICROS"), |
| 900 | number("TRIAL_TOTAL_MICROS"), |
| 901 | env.var("TRIAL_UNTIL").ok().map(|v| v.to_string()), |
| 902 | ) { |
| 903 | (Some(per_workspace_micros), Some(total_micros), Some(until)) |
| 904 | if per_workspace_micros > 0 && !until.is_empty() => |
| 905 | { |
| 906 | Some(TrialConfig { |
| 907 | per_workspace_micros, |
| 908 | total_micros, |
| 909 | until, |
| 910 | }) |
| 911 | } |
| 912 | _ => None, |
| 913 | } |
| 914 | }, |
| 915 | }) |
| 916 | } |
| 917 | } |
| 918 | |
| 919 | #[event(scheduled)] |
| 920 | async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) { |
| 921 | let Ok(billing) = Billing::from_env(&env) else { |
| 922 | return; |
| 923 | }; |
| 924 | let keeper = keeper::Keeper::from_env(&env); |
| 925 | if let Err(error) = billing.settle_runs(&keeper).await { |
| 926 | worker::console_error!("settling runs failed: {error}"); |
| 927 | } |
| 928 | if let Err(error) = billing.autopay().await { |
| 929 | worker::console_error!("paying at the limit failed: {error}"); |
| 930 | } |
| 931 | if let Err(error) = billing.close_months().await { |
| 932 | worker::console_error!("closing the month failed: {error}"); |
| 933 | } |
| 934 | if let Err(error) = billing.invoice_enterprises().await { |
| 935 | worker::console_error!("invoicing enterprises failed: {error}"); |
| 936 | } |
| 937 | if let Ok(identity) = env.service("IDENTITY") { |
| 938 | if let Err(error) = billing.warn_limits(&identity).await { |
| 939 | worker::console_error!("warning owners failed: {error}"); |
| 940 | } |
| 941 | } |
| 942 | // Once a day, and at once if the costs were never checked: check every |
| 943 | // cost against what Cloudflare billed. |
| 944 | if event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false) { |
| 945 | if let Err(error) = billing.reconcile(&keeper).await { |
| 946 | worker::console_error!("checking costs against Cloudflare failed: {error}"); |
| 947 | } |
| 948 | } |
| 949 | } |
| 950 | |
| 951 | /// Events from the bus, on billing's own queue: only a workspace's rename |
| 952 | /// matters here (see `rename`). |
| 953 | #[event(queue)] |
| 954 | async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> { |
| 955 | let billing = Billing::from_env(&env)?; |
| 956 | let identity = env.service("IDENTITY").ok(); |
| 957 | for message in batch.messages()? { |
| 958 | billing.on_event(identity.as_ref(), message.body()).await?; |
| 959 | message.ack(); |
| 960 | } |
| 961 | Ok(()) |
| 962 | } |
| 963 | |
| 964 | #[event(fetch)] |
| 965 | async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> { |
| 966 | let Some(method) = rpc_method(&request) else { |
| 967 | return Response::error("Not found", 404); |
| 968 | }; |
| 969 | let body: serde_json::Value = request.json().await?; |
| 970 | let billing = Billing::from_env(&env)?; |
| 971 | match method.as_str() { |
| 972 | "status" => reply(&billing.status()), |
| 973 | "account" => reply(&billing.account(args(body)?).await?), |
| 974 | "ledger" => reply(&billing.ledger(args(body)?).await?), |
| 975 | "usage" => reply(&billing.usage(args(body)?).await?), |
| 976 | "checkout" => reply(&billing.checkout(args(body)?).await?), |
| 977 | "confirm" => reply(&billing.confirm(args(body)?).await?), |
| 978 | "can_start" => reply(&billing.can_start(args(body)?).await?), |
| 979 | "trial" => reply(&billing.trial(args(body)?).await?), |
| 980 | "start_run" => reply(&billing.start_run(args(body)?).await?), |
| 981 | "finish_run" => reply(&billing.finish_run(args(body)?).await?), |
| 982 | "features" => reply(&billing.features(args(body)?).await?), |
| 983 | "subscribe" => reply(&billing.subscribe(args(body)?).await?), |
| 984 | "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?), |
| 985 | "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?), |
| 986 | "has_feature" => reply(&billing.has_feature(args(body)?).await?), |
| 987 | "charge_feature" => reply(&billing.charge_feature(args(body)?).await?), |
| 988 | "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?), |
| 989 | "limit" => reply(&billing.limit(args(body)?).await?), |
| 990 | "check_limit" => reply(&billing.check_limit(args(body)?).await?), |
| 991 | "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?), |
| 992 | "prices" => reply(&billing.prices().await?), |
| 993 | "billing_portal" => reply(&billing.billing_portal(args(body)?).await?), |
| 994 | "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?), |
| 995 | "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?), |
| 996 | "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?), |
| 997 | "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?), |
| 998 | "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?), |
| 999 | "invoices" => reply(&billing.invoices(args(body)?).await?), |
| 1000 | "statement" => reply(&billing.statement(args(body)?).await?), |
| 1001 | "statement_entries" => reply(&billing.statement_entries(args(body)?).await?), |
| 1002 | "admin_workspace_invoices" => { |
| 1003 | let a: AdminWorkspaceInvoicesArgs = args(body)?; |
| 1004 | reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?) |
| 1005 | } |
| 1006 | "admin_signals" => reply(&billing.admin_signals(args(body)?).await?), |
| 1007 | "admin_overview" => reply(&billing.admin_overview(args(body)?).await?), |
| 1008 | "admin_sales" => reply(&billing.admin_sales(args(body)?).await?), |
| 1009 | "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?), |
| 1010 | "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?), |
| 1011 | "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?), |
| 1012 | "admin_audit" => reply(&billing.admin_audit(args(body)?).await?), |
| 1013 | "note_pending" => reply(&billing.note_pending(args(body)?).await?), |
| 1014 | "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?), |
| 1015 | "admin_account" => reply(&billing.admin_account(args(body)?).await?), |
| 1016 | "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?), |
| 1017 | "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?), |
| 1018 | "admin_attach" => reply(&billing.admin_attach(args(body)?).await?), |
| 1019 | "admin_credit" => reply(&billing.admin_credit(args(body)?).await?), |
| 1020 | _ => Response::error("Unknown method", 404), |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | #[cfg(test)] |
| 1025 | mod tests { |
| 1026 | use super::*; |
| 1027 | |
| 1028 | #[test] |
| 1029 | fn a_run_is_charged_its_cost_plus_the_margin() { |
| 1030 | // $0.05 at 20% is six cents. |
| 1031 | assert_eq!(charge_micros(0.05, 20), 60_000); |
| 1032 | assert_eq!(charge_micros(1.0, 20), 1_200_000); |
| 1033 | assert_eq!(charge_micros(0.05, 0), 50_000); |
| 1034 | } |
| 1035 | |
| 1036 | #[test] |
| 1037 | fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() { |
| 1038 | assert_eq!(charge_micros(0.000_000_4, 20), 2); |
| 1039 | assert_eq!(charge_micros(0.0, 20), 0); |
| 1040 | assert_eq!(charge_micros(-3.0, 20), 0); |
| 1041 | } |
| 1042 | |
| 1043 | #[test] |
| 1044 | fn sandbox_time_is_charged_from_the_first_second() { |
| 1045 | // 21 millionths a second at cost, plus 20%. |
| 1046 | let price = Price::price_for(21.0, 20); |
| 1047 | assert_eq!(sandbox_charge(1, price), 26); |
| 1048 | assert_eq!(sandbox_charge(60, price), 1_512); |
| 1049 | assert_eq!(sandbox_charge(0, price), 0); |
| 1050 | } |
| 1051 | |
| 1052 | #[test] |
| 1053 | fn durations_read_plainly() { |
| 1054 | assert_eq!(duration(40), "40s"); |
| 1055 | assert_eq!(duration(192), "3m 12s"); |
| 1056 | assert_eq!(duration(3720), "1h 2m"); |
| 1057 | } |
| 1058 | |
| 1059 | #[test] |
| 1060 | fn an_absurd_cost_is_capped() { |
| 1061 | assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR); |
| 1062 | } |
| 1063 | } |