g1t/services/billing/src/lib.rs

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