g1t/services/billing/src/lib.rs

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