g1t/services/billing/src/lib.rs

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