g1t/services/billing/src/lib.rs

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