g1t/services/billing/src/lib.rs

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