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