Skip to content

g1t/services/billing/src/lib.rs

1,632 lines75,307 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 ai;
22mod budget;
23mod catalogue;
24mod cards;
25mod closing;
26mod compute;
27mod costs;
28mod margin;
29mod pricing;
30mod report;
31mod details;
32mod credits;
33mod grants;
34mod overages;
35mod requests;
36mod storage;
37mod invoices;
38mod sales;
39mod statement;
40mod webhooks;
41mod features;
42mod gateway;
43mod keeper;
44mod limits;
45mod rename;
46mod reset;
47mod retention;
48mod stripe;
49mod stripe_sync;
50mod subscriptions;
51mod tax;
52mod tokens;
53
54use g1t_contracts::billing::*;
55use g1t_contracts::time::rfc3339;
56use g1t_contracts::{FailureCode, Outcome, Role, new_id};
57use g1t_kit::{args, now_ms, reply, rpc_method};
58use serde::Deserialize;
59use sha2::{Digest, Sha256};
60use worker::wasm_bindgen::JsValue;
61use worker::{Context, D1Database, Env, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
62use futures_util::future::{try_join, try_join5};
63
64use stripe::Stripe;
65
66/// Prepaying: $25 at the least; by card up to $10,000 at a time, and by
67/// bank transfer from $1,000 to $100,000.
68const MIN_TOP_UP_CENTS: u32 = 2_500;
69const MAX_TOP_UP_CENTS: u32 = 1_000_000;
70const MIN_BANK_TRANSFER_CENTS: u32 = 100_000;
71const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000;
72const LEDGER_PAGE: u32 = 100;
73/// A run's reported cost is believed up to this much. A sandbox cannot
74/// spend more in the time it has, so anything above is a fault.
75const MAX_RUN_COST_USD: f64 = 100.0;
76
77/// What a run is charged: its cost plus the margin, rounded up to a whole
78/// millionth of a dollar.
79pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
80 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
81 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
82}
83
84/// What a cost g1t trusts (the price book's, or what AI Gateway priced a
85/// run at) is charged at: plus the margin, rounded up to a whole millionth.
86/// Unlike `charge_micros`, never capped: only a sandbox's own report is
87/// held to `MAX_RUN_COST_USD`, so a run that really cost more is charged
88/// for all of it once it is settled.
89pub fn margin_on(cost_micros: i64, margin_percent: u32) -> i64 {
90 let cost = i128::from(cost_micros.max(0));
91 let charge = (cost * i128::from(100 + margin_percent) + 99) / 100;
92 i64::try_from(charge).unwrap_or(i64::MAX)
93}
94
95fn hash(token: &str) -> String {
96 hex::encode(Sha256::digest(token.as_bytes()))
97}
98
99fn optional(value: Option<&str>) -> JsValue {
100 value.map_or(JsValue::NULL, JsValue::from)
101}
102
103#[derive(Deserialize)]
104struct AccountRow {
105 balance_micros: i64,
106 customer_id: Option<String>,
107}
108
109#[derive(Deserialize)]
110struct LedgerRow {
111 id: String,
112 kind: EntryKind,
113 amount_micros: i64,
114 description: String,
115 repo: Option<String>,
116 number: Option<u32>,
117 task: Option<String>,
118 model: Option<String>,
119 created_by: Option<String>,
120 created_at: String,
121 billed_to: Option<String>,
122 #[serde(default)]
123 workspace: Option<String>,
124 #[serde(default)]
125 credit_micros: Option<i64>,
126 #[serde(default)]
127 trial_micros: Option<i64>,
128 #[serde(default)]
129 oss_micros: Option<i64>,
130 #[serde(default)]
131 given_micros: Option<i64>,
132 #[serde(default)]
133 credit_kind: Option<String>,
134 #[serde(default)]
135 discount_micros: Option<i64>,
136}
137
138impl From<LedgerRow> for LedgerEntry {
139 fn from(row: LedgerRow) -> Self {
140 LedgerEntry {
141 id: row.id,
142 kind: row.kind,
143 amount_micros: row.amount_micros,
144 description: row.description,
145 repo: row.repo,
146 number: row.number,
147 task: row.task,
148 model: row.model,
149 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
150 created_by: row.created_by,
151 created_at: row.created_at,
152 workspace: row.workspace,
153 credit_micros: row.credit_micros.unwrap_or(0),
154 trial_micros: row.trial_micros.unwrap_or(0),
155 oss_micros: row.oss_micros.unwrap_or(0),
156 given_micros: row.given_micros.unwrap_or(0),
157 credit_kind: row.credit_kind.as_deref().and_then(CreditKind::parse),
158 discount_micros: row.discount_micros.unwrap_or(0),
159 }
160 }
161}
162
163#[derive(Clone, Deserialize)]
164struct RunRow {
165 workspace: String,
166 repo: String,
167 number: u32,
168 task: String,
169 model: String,
170 token_hash: String,
171 billed_to: Option<String>,
172}
173
174impl RunRow {
175 fn own_provider(&self) -> bool {
176 self.billed_to.as_deref() == Some("workspace")
177 }
178}
179
180#[derive(Deserialize)]
181struct CheckoutRow {
182 workspace: String,
183 created_by: String,
184 #[serde(default)]
185 fee_cents: Option<u32>,
186}
187
188/// A payment page started, as `checkouts` keeps it.
189pub(crate) struct NewCheckout<'a> {
190 pub id: &'a str,
191 pub workspace: &'a str,
192 /// What it pays for, in cents: the prepayment, the plan's price, the AI
193 /// credit; 0 for a card check.
194 pub amount_cents: u32,
195 /// The card fee on top, for AI credit.
196 pub fee_cents: u32,
197 pub created_by: &'a str,
198 /// None for a prepayment; `plan`, `security`, `card_check` or
199 /// `ai_credit` otherwise.
200 pub feature: Option<&'a str>,
201}
202
203/// The one insert every payment page goes through, every column named, so
204/// a column added to `checkouts` with no default is caught by
205/// `tests::every_checkout_insert_fills_the_table` rather than by a 500.
206pub(crate) const CHECKOUT_INSERT: &str = "INSERT INTO checkouts (id, workspace, amount_cents, fee_cents, created_by, created_at, feature, status)
207 VALUES (?, ?, ?, ?, ?, ?, ?, 'open')";
208
209impl Billing {
210 pub(crate) async fn record_checkout(&self, c: &NewCheckout<'_>) -> Result<()> {
211 self.db
212 .prepare(CHECKOUT_INSERT)
213 .bind(&[
214 c.id.into(),
215 c.workspace.into(),
216 c.amount_cents.into(),
217 c.fee_cents.into(),
218 c.created_by.into(),
219 rfc3339(now_ms()).into(),
220 optional(c.feature),
221 ])?
222 .run()
223 .await?;
224 Ok(())
225 }
226}
227
228/// A row an `UPDATE … RETURNING` touched.
229#[derive(Deserialize)]
230struct Touched {
231 #[allow(dead_code)]
232 id: String,
233}
234
235struct Billing {
236 db: D1Database,
237 /// Absent when no card processor is configured.
238 stripe: Option<Stripe>,
239 /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`);
240 /// without it no event is believed.
241 webhook_secret: Option<String>,
242 margin_percent: u32,
243 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
244 free: bool,
245 /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS`
246 /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero).
247 trials_on: bool,
248 /// The plans' and pools' numbers; see `credits`.
249 plans: credits::Config,
250 /// The repos service: which repositories are public, what private ones
251 /// hold, and their git operations. Absent where it is not bound.
252 repos: Option<worker::Fetcher>,
253 /// The packages service: what each workspace's packages hold.
254 packages: Option<worker::Fetcher>,
255 /// The identity service, which emails owners. Absent where it is not
256 /// bound.
257 identity: Option<worker::Fetcher>,
258 /// How far unpaid usage may go; see `limits`.
259 ceilings: limits::Ceilings,
260 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
261 prepaid_only: bool,
262 /// The caps on what g1t pays for itself; see `budget`.
263 caps: budget::Caps,
264 /// The worker's bindings, for emailing staff (`EMAIL`).
265 env: Env,
266}
267
268impl Billing {
269 fn status(&self) -> Status {
270 Status {
271 enabled: self.stripe.is_some(),
272 live: self.stripe.as_ref().is_some_and(Stripe::live),
273 free: self.free,
274 }
275 }
276
277 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
278 self.db
279 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
280 .bind(&[workspace.into()])?
281 .first::<AccountRow>(None)
282 .await
283 }
284
285 async fn standing(&self, workspace: &str) -> Result<Account> {
286 // The card as last synced (stripe_sync.rs), not asked of Stripe.
287 let (row, card) = try_join(self.row(workspace), self.saved_card(workspace)).await?;
288 Ok(Account {
289 workspace: workspace.to_owned(),
290 balance_micros: row.map_or(0, |row| row.balance_micros),
291 status: self.status(),
292 margin_percent: self.margin_percent,
293 card,
294 })
295 }
296
297 /// The workspace's customer at Stripe, made the first time one is needed.
298 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
299 let Some(stripe) = &self.stripe else {
300 return Err(worker::Error::RustError("payments are not set up".into()));
301 };
302 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
303 return Ok(customer);
304 }
305 let customer = stripe.create_customer(workspace).await?;
306 self.db
307 .prepare(
308 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
309 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
310 )
311 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
312 .run()
313 .await?;
314 Ok(customer)
315 }
316
317 /// Stripe's hosted billing page for the workspace. Owners only.
318 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
319 let workspace = a.workspace.to_lowercase();
320 if a.actor.role_in(&workspace) != Some(Role::Owner) {
321 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing."));
322 }
323 let Some(stripe) = &self.stripe else {
324 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
325 };
326 let customer = match self.customer_for(&workspace).await {
327 Ok(customer) => customer,
328 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
329 };
330 match stripe.portal_session(&customer, &a.return_url).await {
331 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
332 Err(error) if stripe::is_missing(&error) => {
333 // The customer was removed at Stripe: a new one next time.
334 self.forget_customer(&workspace).await?;
335 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
336 }
337 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
338 }
339 }
340
341 /// Adds a ledger entry and moves the balance by the same amount, as
342 /// one write.
343 #[allow(clippy::too_many_arguments)]
344 async fn enter(
345 &self,
346 workspace: &str,
347 kind: EntryKind,
348 amount_micros: i64,
349 description: &str,
350 reference: &str,
351 run: Option<&RunRow>,
352 cost_micros: Option<i64>,
353 created_by: Option<&str>,
354 customer: Option<&str>,
355 ) -> Result<()> {
356 let now = now_ms();
357 let timestamp = rfc3339(now);
358 let kind = match kind {
359 EntryKind::TopUp => "top_up",
360 EntryKind::Usage => "usage",
361 };
362 self.db
363 .batch(vec![
364 self.db
365 .prepare(
366 "INSERT INTO ledger
367 (id, workspace, kind, amount_micros, description, repo, number, task,
368 model, cost_micros, reference, created_by, created_at, billed_to)
369 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
370 )
371 .bind(&[
372 new_id("led", now).into(),
373 workspace.into(),
374 kind.into(),
375 // D1 takes numbers as doubles, which hold every
376 // amount this service will see exactly.
377 (amount_micros as f64).into(),
378 description.into(),
379 optional(run.map(|run| run.repo.as_str())),
380 run.map_or(JsValue::NULL, |run| run.number.into()),
381 optional(run.map(|run| run.task.as_str())),
382 optional(run.map(|run| run.model.as_str())),
383 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
384 reference.into(),
385 optional(created_by),
386 timestamp.as_str().into(),
387 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
388 ])?,
389 self.db
390 .prepare(
391 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
392 VALUES (?1, ?2, ?3, ?4)
393 ON CONFLICT (workspace) DO UPDATE SET
394 balance_micros = balance_micros + ?2,
395 customer_id = COALESCE(?3, customer_id)",
396 )
397 .bind(&[
398 workspace.into(),
399 (amount_micros as f64).into(),
400 optional(customer),
401 timestamp.as_str().into(),
402 ])?,
403 ])
404 .await?;
405 // Money in clears a card declined at the limit. A refund or a lost
406 // dispute is a top-up of less than nothing: money out, which never
407 // clears it.
408 if kind == "top_up" && amount_micros > 0 {
409 self.db
410 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
411 .bind(&[workspace.into()])?
412 .run()
413 .await?;
414 }
415 Ok(())
416 }
417
418 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
419 let workspace = a.workspace.to_lowercase();
420 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
421 return Ok(members_only());
422 }
423 Ok(Outcome::Ok(self.standing(&workspace).await?))
424 }
425
426 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
427 let workspace = a.workspace.to_lowercase();
428 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
429 return Ok(members_only());
430 }
431 let rows = self
432 .db
433 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
434 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
435 .all()
436 .await?
437 .results::<LedgerRow>()?;
438 Ok(Outcome::Ok(
439 rows.into_iter().map(LedgerEntry::from).collect(),
440 ))
441 }
442
443 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
444 let workspace = a.workspace.to_lowercase();
445 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
446 return Ok(members_only());
447 }
448 #[derive(serde::Deserialize)]
449 struct SliceRow {
450 key: Option<String>,
451 micros: Option<i64>,
452 runs: Option<u32>,
453 }
454 // While g1t is free, what was used at cost is what there is to show.
455 // With a discount, usage at its price, so a 100% discount still
456 // shows what the workspace would pay.
457 // Every slice measures usage at price (statement::PRICE_SQL), the one
458 // figure every page shows as usage, whatever paid for it.
459 let discount_percent = self.terms_of(&workspace).await?.percent_off();
460 let measure = if self.free { "COALESCE(cost_micros, 0)" } else { crate::statement::PRICE_SQL };
461 let slices = |key: &str, limit: u32| {
462 format!(
463 "SELECT {key} AS key, SUM({measure}) AS micros, COUNT(*) AS runs FROM ledger
464 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
465 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
466 )
467 };
468 let query = |sql: String| {
469 let db = &self.db;
470 let workspace = workspace.clone();
471 let since = a.since.clone();
472 async move {
473 let rows = db
474 .prepare(sql)
475 .bind(&[workspace.into(), since.into()])?
476 .all()
477 .await?
478 .results::<SliceRow>()?;
479 Ok::<Vec<UsageSlice>, worker::Error>(
480 rows.into_iter()
481 .map(|row| UsageSlice {
482 key: row.key.unwrap_or_else(|| "other".to_owned()),
483 micros: row.micros.unwrap_or_default(),
484 runs: row.runs.unwrap_or_default(),
485 })
486 .collect(),
487 )
488 }
489 };
490 #[derive(serde::Deserialize)]
491 struct Totals {
492 spent: Option<i64>,
493 cost: Option<i64>,
494 provider: Option<i64>,
495 runs: Option<u32>,
496 added: Option<i64>,
497 discount: Option<i64>,
498 covered: Option<i64>,
499 price: Option<i64>,
500 }
501 let totals = async {
502 self.db
503 .prepare(format!(
504 "SELECT
505 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
506 SUM(CASE WHEN kind = 'usage' THEN COALESCE(credit_micros, 0) + COALESCE(trial_micros, 0)
507 + COALESCE(oss_micros, 0) + COALESCE(given_micros, 0) END) AS covered,
508 SUM(CASE WHEN kind = 'usage' THEN {price} END) AS price,",
509 price = crate::statement::PRICE_SQL
510 ) + "
511 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
512 SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider,
513 SUM(CASE WHEN kind = 'usage' AND " + crate::statement::RUN_SQL + " THEN 1 ELSE 0 END) AS runs,
514 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added,
515 SUM(CASE WHEN kind = 'usage' THEN discount_micros END) AS discount
516 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
517 )
518 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
519 .first::<Totals>(None)
520 .await
521 };
522 // The totals and the five slices read the same rows independently,
523 // so they go to D1 at once: one round trip of waiting, not six.
524 let (totals, (by_day, by_task, by_repo, by_pull, by_model)) = try_join(
525 totals,
526 try_join5(
527 query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)),
528 query(slices("task", 20)),
529 query(slices("repo", 20)),
530 query(slices("repo || '#' || number", 10)),
531 query(slices("model", 10)),
532 ),
533 )
534 .await?;
535 let totals = totals.unwrap_or(Totals {
536 spent: None,
537 cost: None,
538 provider: None,
539 runs: None,
540 added: None,
541 discount: None,
542 covered: None,
543 price: None,
544 });
545 Ok(Outcome::Ok(Usage {
546 spent_micros: totals.spent.unwrap_or_default(),
547 // What the included usage, the trial, a pool or g1t paid, as the
548 // entries record it.
549 covered_micros: totals.covered.unwrap_or_default(),
550 price_micros: if self.free { totals.cost.unwrap_or_default() } else { totals.price.unwrap_or_default() },
551 cost_micros: totals.cost.unwrap_or_default(),
552 provider_micros: totals.provider.unwrap_or_default(),
553 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
554 free: self.free,
555 discount_micros: totals.discount.unwrap_or_default(),
556 discount_percent: (discount_percent > 0).then_some(discount_percent),
557 runs: totals.runs.unwrap_or_default(),
558 added_micros: totals.added.unwrap_or_default(),
559 by_day,
560 by_task,
561 by_repo,
562 by_pull,
563 by_model,
564 since: a.since,
565 }))
566 }
567
568 /// `checkout`: prepays usage, by card or (from $1,000) bank transfer.
569 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
570 let workspace = a.workspace.to_lowercase();
571 if a.actor.role_in(&workspace) != Some(Role::Owner) {
572 return Ok(Outcome::fail(
573 FailureCode::Forbidden,
574 "Only an owner can prepay for a workspace.",
575 ));
576 }
577 let Some(stripe) = &self.stripe else {
578 return Ok(Outcome::fail(
579 FailureCode::Conflict,
580 "Payments are not set up on this g1t yet.",
581 ));
582 };
583 let bank_transfer = a.method.as_deref() == Some("bank_transfer");
584 if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) {
585 return Ok(Outcome::fail(FailureCode::Invalid, why));
586 }
587 // A bank transfer needs a customer for its account details.
588 let customer = if bank_transfer {
589 match self.customer_for(&workspace).await {
590 Ok(customer) => Some(customer),
591 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, stripe::friendly(&error))),
592 }
593 } else {
594 self.row(&workspace).await?.and_then(|row| row.customer_id)
595 };
596 // By card, Stripe's fee is its own line; a bank transfer has none.
597 let fee = if bank_transfer { 0 } else { self.card_fee_on(i64::from(a.amount_cents)).await? as u32 };
598 let started = match stripe.start_checkout(&workspace, a.amount_cents, fee, customer.as_deref(), &a.return_url, bank_transfer).await {
599 // A customer saved under another Stripe account: start afresh.
600 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
601 self.forget_customer(&workspace).await?;
602 let customer = if bank_transfer { self.customer_for(&workspace).await.ok() } else { None };
603 stripe.start_checkout(&workspace, a.amount_cents, fee, customer.as_deref(), &a.return_url, bank_transfer).await
604 }
605 other => other,
606 };
607 self.page_opened(started, &workspace, a.amount_cents, fee, &a.actor.username, None).await
608 }
609
610 /// A payment page Stripe started (or refused), recorded in `checkouts`
611 /// and handed back; any failure as a sentence for the page, never a
612 /// raw error.
613 pub(crate) async fn page_opened(
614 &self,
615 started: Result<stripe::Session>,
616 workspace: &str,
617 amount_cents: u32,
618 fee_cents: u32,
619 created_by: &str,
620 feature: Option<&str>,
621 ) -> Result<Outcome<Checkout>> {
622 let session = match started {
623 Ok(session) => session,
624 Err(error) => {
625 worker::console_error!("{workspace}: Stripe refused a payment page ({}): {error}", feature.unwrap_or("prepay"));
626 return Ok(Outcome::fail(FailureCode::Conflict, stripe::friendly(&error)));
627 }
628 };
629 let Some(url) = session.url.clone() else {
630 return Ok(Outcome::fail(FailureCode::Conflict, "Stripe returned no payment page. Try again in a minute."));
631 };
632 let recorded = self
633 .record_checkout(&NewCheckout { id: &session.id, workspace, amount_cents, fee_cents, created_by, feature })
634 .await;
635 if let Err(error) = recorded {
636 worker::console_error!("{workspace}: a payment page could not be recorded: {error}");
637 return Ok(Outcome::fail(FailureCode::Conflict, "g1t could not keep track of the payment page. Nothing was charged; try again."));
638 }
639 Ok(Outcome::Ok(Checkout { url }))
640 }
641
642 /// Credits a payment if the processor says it was made and it has not
643 /// been credited before. The amount credited is what the processor
644 /// says was paid, not what anyone here remembers asking for.
645 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
646 let workspace = a.workspace.to_lowercase();
647 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
648 return Ok(members_only());
649 }
650 let (Some(stripe), Some(checkout)) = (
651 &self.stripe,
652 self.db
653 .prepare(
654 // A prepayment only: a plan's or a card check's page is
655 // settled where it was started, never credited as money
656 // paid in advance.
657 "SELECT workspace, created_by, fee_cents FROM checkouts
658 WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NULL",
659 )
660 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
661 .first::<CheckoutRow>(None)
662 .await?,
663 ) else {
664 // Unknown, someone else's, or already credited: nothing to do.
665 return Ok(Outcome::Ok(self.standing(&workspace).await?));
666 };
667 let session = match stripe.session(&a.session).await {
668 Ok(session) => session,
669 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
670 };
671 if session.payment_status == "paid" && session.amount_total.is_some() {
672 // Only whoever flips it from open to paid enters the credit.
673 let claimed = self
674 .db
675 .prepare(
676 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
677 RETURNING id",
678 )
679 .bind(&[a.session.as_str().into()])?
680 .first::<Touched>(None)
681 .await?;
682 if claimed.is_some() {
683 self.credit_prepayment(&checkout.workspace, &session, checkout.fee_cents.unwrap_or(0), &checkout.created_by).await?;
684 }
685 }
686 Ok(Outcome::Ok(self.standing(&workspace).await?))
687 }
688
689 /// Enters a paid prepayment page: what its lines came to before tax,
690 /// less the card fee, as credit; its tax and fee kept apart. Once the
691 /// page is claimed `open → paid`. The credit in cents.
692 pub(crate) async fn credit_prepayment(&self, workspace: &str, session: &stripe::Session, fee_cents: u32, by: &str) -> Result<i64> {
693 let fee = i64::from(fee_cents);
694 let cents = tax::prepay_credit_cents(session.before_tax_cents(), fee);
695 let tax_cents = session.tax_cents();
696 let description = if tax_cents > 0 || fee > 0 {
697 format!(
698 "Paid in advance (tax {} and card fee {} paid with it)",
699 features::cents(tax_cents * 10_000),
700 features::cents(fee * 10_000)
701 )
702 } else {
703 "Paid in advance".to_owned()
704 };
705 self.enter(
706 workspace,
707 EntryKind::TopUp,
708 cents * MICROS_PER_DOLLAR / 100,
709 &description,
710 &session.id,
711 None,
712 None,
713 Some(by),
714 session.customer.as_deref(),
715 )
716 .await?;
717 self.record_extras(workspace, &session.id, session.payment_intent.as_deref(), tax::Extras { tax_cents, fee_cents: fee }, None)
718 .await?;
719 Ok(cents)
720 }
721
722 /// Drops a saved customer the card processor no longer knows.
723 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
724 self.db
725 .prepare(
726 "UPDATE accounts SET customer_id = NULL, card_brand = NULL, card_last4 = NULL, card_exp_month = NULL,
727 card_exp_year = NULL, card_synced_at = NULL WHERE workspace = ?",
728 )
729 .bind(&[workspace.into()])?
730 .run()
731 .await?;
732 Ok(())
733 }
734
735 /// A refusal if the workspace has no credit to start an agent with.
736 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
737 // Billing is postpaid: usage limits decide whether work starts
738 // (see `limits`), and credit is a prepayment that lowers what is
739 // owed. A balance no longer has to be positive to start.
740 if self.free || !self.prepaid_only {
741 return Ok(None);
742 }
743 let balance = self
744 .row(workspace)
745 .await?
746 .map_or(0, |row| row.balance_micros);
747 Ok((balance <= 0).then(|| {
748 Outcome::fail(
749 FailureCode::PaymentRequired,
750 format!(
751 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
752 ),
753 )
754 }))
755 }
756
757 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
758 if self.stripe.is_none() {
759 return Ok(Outcome::Ok(true));
760 }
761 if let Some(stopped) = self.stopped(&a.workspace).await? {
762 return Ok(stopped);
763 }
764 Ok(self
765 .out_of_credit(&a.workspace.to_lowercase())
766 .await?
767 .unwrap_or(Outcome::Ok(true)))
768 }
769
770 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
771 if self.stripe.is_none() {
772 return Ok(Outcome::Ok(None));
773 }
774 let workspace = a.workspace.to_lowercase();
775 if let Some(stopped) = self.stopped(&workspace).await? {
776 return Ok(stopped);
777 }
778 if let Some(refused) = self.out_of_credit(&workspace).await? {
779 return Ok(refused);
780 }
781 // On g1t's models, a workspace on the plan needs AI credit (or
782 // included usage) first: g1t never fronts a model's cost (ai.rs).
783 if a.billed_to != "workspace"
784 && let Some(why) = self.ai_refusal(&workspace).await?
785 {
786 return Ok(Outcome::fail(FailureCode::PaymentRequired, why));
787 }
788 let now = now_ms();
789 let run_id = new_id("run", now);
790 let mut bytes = [0u8; 32];
791 getrandom::getrandom(&mut bytes).expect("no source of randomness");
792 let token = hex::encode(bytes);
793 self.db
794 .prepare(
795 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier)
796 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
797 )
798 .bind(&[
799 run_id.as_str().into(),
800 workspace.into(),
801 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
802 a.number.into(),
803 a.task.into(),
804 a.model.into(),
805 hash(&token).into(),
806 rfc3339(now).into(),
807 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
808 // On the workspace's own provider too: the proxy counts the
809 // run's tokens under it, and the agent rate is charged on them.
810 optional(a.session.as_deref()),
811 optional(a.tier.as_deref().filter(|tier| tokens::is_tier(tier))),
812 ])?
813 .run()
814 .await?;
815 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
816 }
817
818 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
819 let run = self
820 .db
821 .prepare(
822 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
823 WHERE id = ? AND finished_at IS NULL",
824 )
825 .bind(&[a.run_id.as_str().into()])?
826 .first::<RunRow>(None)
827 .await?;
828 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
829 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
830 };
831 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
832 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
833 }
834 // Only whoever closes the run charges for it.
835 let claimed = self
836 .db
837 .prepare(
838 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
839 )
840 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
841 .first::<Touched>(None)
842 .await?;
843 if claimed.is_none() {
844 return Ok(Outcome::Ok(false));
845 }
846 // On the workspace's own provider, the model was paid for there and
847 // the run's sandbox time is recorded on its own: only the agent rate
848 // is charged, on its own meter.
849 if run.own_provider() {
850 self.charge_agent_rate(&a.run_id, &run, a.tokens).await?;
851 return Ok(Outcome::Ok(true));
852 }
853 // Its cost plus the margin, on the account's terms; then the plan's
854 // included usage and the trial credit pay what they can, and g1t
855 // covers a free workspace's overrun (see `credits`). Agents are
856 // never the open-source pool's.
857 // The model at the provider's price and the price book's markup on it
858 // (`agent_models`: none from 2026-10-08); g1t's own part is the agent
859 // rate, charged on a line of its own below.
860 let base = charge_micros(a.cost_usd, self.model_markup().await?);
861 let (charge, terms_note, discount) = self.charged(&run.workspace, base).await?;
862 let month = credits::month_of(&rfc3339(now_ms()));
863 let eligible = credits::eligible_for(Some(ComputeKind::Agent), None);
864 let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?;
865 let mut description = match run.task.as_str() {
866 "plan" => format!("Planning for {}", run.repo),
867 "review" => format!("Review of {}#{}", run.repo, run.number),
868 "update" => format!("Catching up {}#{}", run.repo, run.number),
869 _ => format!("Work on {}#{}", run.repo, run.number),
870 };
871 description.push_str(&terms_note);
872 description.push_str(&drawn.note());
873 self.enter(
874 &run.workspace,
875 EntryKind::Usage,
876 -(charge - drawn.total()),
877 &description,
878 &a.run_id,
879 Some(&run),
880 Some(charge_micros(a.cost_usd, 0)),
881 None,
882 None,
883 )
884 .await?;
885 self.record_drawn(&a.run_id, &drawn).await?;
886 self.record_discount(&a.run_id, discount).await?;
887 self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await;
888 self.charge_agent_rate(&a.run_id, &run, a.tokens).await?;
889 Ok(Outcome::Ok(true))
890 }
891}
892
893impl Billing {
894 /// Records how long a sandbox ran, with its cost and its charge: every
895 /// second, from the first, at the price book's price; on its own CPU
896 /// when it reports it. Settles its reservation, if it names one.
897 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
898 // Self-hosted time is recorded wherever g1t runs, for its minutes;
899 // anything else only where there is a bill to put it on.
900 if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 {
901 return Ok(Outcome::Ok(false));
902 }
903 let workspace = a.workspace.to_lowercase();
904 let seen = self
905 .db
906 .prepare("SELECT id FROM ledger WHERE reference = ?")
907 .bind(&[a.reference.as_str().into()])?
908 .first::<Touched>(None)
909 .await?;
910 if seen.is_some() {
911 return Ok(Outcome::Ok(false));
912 }
913 let now = now_ms();
914 let timestamp = rfc3339(now);
915 let seconds = i64::from(a.seconds);
916 // On the workspace's own machine: its minutes go on usage, at $0,
917 // and whatever was reserved for it is given back.
918 if a.self_hosted {
919 let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds));
920 self.db
921 .prepare(
922 "INSERT INTO ledger
923 (id, workspace, kind, amount_micros, description, repo, task,
924 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, quantity)
925 VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0, ?)",
926 )
927 .bind(&[
928 new_id("led", now).into(),
929 workspace.as_str().into(),
930 description.as_str().into(),
931 optional(a.repo.as_deref()),
932 a.reference.as_str().into(),
933 timestamp.as_str().into(),
934 (seconds as f64).into(),
935 ])?
936 .run()
937 .await?;
938 if let Some(reservation) = &a.reservation_id {
939 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?;
940 }
941 return Ok(Outcome::Ok(true));
942 }
943 // From the price book, which follows what Cloudflare bills g1t. A
944 // sandbox is the same container as a build, so without a row it is
945 // a build second's cost plus the margin.
946 let (cost_per_second, _) = self.price("sandbox_second").await?.unwrap_or_else(|| {
947 let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64;
948 (cost, Price::price_for(cost, self.margin_percent))
949 });
950 // A larger machine (`runs-on: g1t-4core`): its memory and disk
951 // cost more each second, and without its own CPU it is priced at
952 // its vCPUs as busy as the standard machine's.
953 let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named);
954 let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb));
955 let price_scale = instance.map_or(1.0, |i| i.price_scale);
956 let vcpus = instance.map_or(4.0, |i| i.vcpu.max(4.0));
957 // Its own CPU when the sandbox reports it; otherwise the average.
958 let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) {
959 Some(cpu) => match (self.price("sandbox_base_second").await?, self.price("sandbox_cpu_second").await?) {
960 (Some((base, _)), Some((vcpu, _))) => {
961 Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu))
962 }
963 _ => None,
964 },
965 None => None,
966 };
967 let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64;
968 let (charge, terms_note, discount) = self.charged(&workspace, credits::with_margin(cost, self.margin_percent)).await?;
969 let eligible = credits::eligible_for(a.kind, a.repo.as_deref());
970 let drawn = self.draw(&workspace, charge, &credits::month_of(&timestamp), &eligible).await?;
971 let charge = charge - drawn.total();
972 let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds"));
973 let description = format!("{}: {} of sandbox time{cpu_note}{terms_note}{}", a.description, duration(seconds), drawn.note());
974 // The price versions it was charged at (pricing.rs).
975 let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] };
976 let mut versions = Vec::new();
977 for meter in meters {
978 versions.extend(self.version_now(meter).await?);
979 }
980 let price_version = versions.join(",");
981 self.db
982 .batch(vec![
983 self.db
984 .prepare(
985 "INSERT INTO ledger
986 (id, workspace, kind, amount_micros, description, repo, task,
987 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version, quantity, compute)
988 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?, ?, ?)",
989 )
990 .bind(&[
991 new_id("led", now).into(),
992 workspace.as_str().into(),
993 (-(charge as f64)).into(),
994 description.as_str().into(),
995 optional(a.repo.as_deref()),
996 (cost as f64).into(),
997 a.reference.as_str().into(),
998 timestamp.as_str().into(),
999 (drawn.credit as f64).into(),
1000 (drawn.trial as f64).into(),
1001 (drawn.oss as f64).into(),
1002 (drawn.given as f64).into(),
1003 optional(Some(price_version.as_str()).filter(|v| !v.is_empty())),
1004 (seconds as f64).into(),
1005 optional(a.kind.map(ComputeKind::as_str)),
1006 ])?,
1007 self.db
1008 .prepare(
1009 "INSERT INTO accounts (workspace, balance_micros, created_at)
1010 VALUES (?1, ?2, ?3)
1011 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
1012 )
1013 .bind(&[
1014 workspace.as_str().into(),
1015 (-(charge as f64)).into(),
1016 timestamp.as_str().into(),
1017 ])?,
1018 ])
1019 .await?;
1020 self.record_discount(&a.reference, discount).await?;
1021 self.count_spend(&workspace, cost, charge, &drawn).await;
1022 if let Some(reservation) = &a.reservation_id {
1023 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?;
1024 }
1025 Ok(Outcome::Ok(true))
1026 }
1027}
1028
1029/// Whether an amount may be prepaid: $25 at the least by card, and from
1030/// $1,000 by bank transfer.
1031pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> {
1032 let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) };
1033 if (min..=max).contains(&cents) {
1034 return Ok(());
1035 }
1036 Err(if bank_transfer {
1037 format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100))
1038 } else {
1039 format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100))
1040 })
1041}
1042
1043/// `10,000` for 10000.
1044fn group(n: u32) -> String {
1045 let digits = n.to_string();
1046 let mut out = String::new();
1047 for (i, c) in digits.chars().enumerate() {
1048 if i > 0 && (digits.len() - i).is_multiple_of(3) {
1049 out.push(',');
1050 }
1051 out.push(c);
1052 }
1053 out
1054}
1055
1056#[cfg(test)]
1057/// What `seconds` of sandbox time are charged at `price_per_second`, in
1058/// millionths of a dollar: every second, rounded up to the next millionth.
1059fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 {
1060 (seconds as f64 * price_per_second).ceil() as i64
1061}
1062
1063/// `1h 2m`, `3m 12s` or `40s`.
1064fn duration(seconds: i64) -> String {
1065 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
1066 if h > 0 {
1067 format!("{h}h {m}m")
1068 } else if m > 0 {
1069 format!("{m}m {s}s")
1070 } else {
1071 format!("{s}s")
1072 }
1073}
1074
1075impl Billing {
1076 /// What a workspace is charged for something that would be `base`:
1077 /// nothing while g1t is free, or as its account's terms say. With a
1078 /// note for the statement when it differs.
1079 /// A charge at cost plus the margin (`base`) on the account's terms:
1080 /// what is charged, the note for the statement, and what a discount
1081 /// gave away below `base`. That last is written on the entry
1082 /// (`record_discount`) so the reconciliation counts it as given, never
1083 /// as margin lost: a sold charge is worth at least its cost plus the
1084 /// margin.
1085 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String, i64)> {
1086 if self.free {
1087 return Ok((0, " (free while g1t is being built out)".to_owned(), 0));
1088 }
1089 let terms = self.terms_of(workspace).await?;
1090 let (charge, discount) = terms.discounted(base);
1091 let note = match terms.discount_label() {
1092 Some(label) if base > 0 => format!(" ({label})"),
1093 _ => String::new(),
1094 };
1095 Ok((charge, note, discount))
1096 }
1097
1098 /// What a discount gave away on an entry, below cost plus the margin
1099 /// (less than nothing on a correction down).
1100 pub(crate) async fn record_discount(&self, reference: &str, micros: i64) -> Result<()> {
1101 if micros == 0 {
1102 return Ok(());
1103 }
1104 self.db
1105 .prepare("UPDATE ledger SET discount_micros = ? WHERE reference = ?")
1106 .bind(&[(micros as f64).into(), reference.into()])?
1107 .run()
1108 .await?;
1109 Ok(())
1110 }
1111}
1112
1113fn members_only<T>() -> Outcome<T> {
1114 Outcome::fail(
1115 FailureCode::Forbidden,
1116 "Only members can see a workspace's billing.",
1117 )
1118}
1119
1120impl Billing {
1121 fn from_env(env: &Env) -> Result<Self> {
1122 Ok(Billing {
1123 db: env.d1("DB")?,
1124 stripe: env
1125 .secret("STRIPE_SECRET_KEY")
1126 .ok()
1127 .map(|key| key.to_string())
1128 .filter(|key| !key.is_empty())
1129 .map(Stripe::new),
1130 webhook_secret: env
1131 .secret("STRIPE_WEBHOOK_SECRET")
1132 .ok()
1133 .map(|secret| secret.to_string().trim().to_owned())
1134 .filter(|secret| !secret.is_empty()),
1135 margin_percent: env
1136 .var("MARGIN_PERCENT")
1137 .ok()
1138 .and_then(|percent| percent.to_string().parse().ok())
1139 .unwrap_or(20),
1140 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
1141 ceilings: limits::Ceilings::from_env(env),
1142 prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"),
1143 trials_on: {
1144 let plans = credits::Config::from_env(env);
1145 plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0
1146 },
1147 plans: credits::Config::from_env(env),
1148 repos: env.service("REPOS").ok(),
1149 packages: env.service("PACKAGES").ok(),
1150 identity: env.service("IDENTITY").ok(),
1151 caps: budget::Caps::from_env(env),
1152 env: env.clone(),
1153 })
1154 }
1155}
1156
1157#[event(scheduled)]
1158async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
1159 let Ok(billing) = Billing::from_env(&env) else {
1160 return;
1161 };
1162 let keeper = keeper::Keeper::from_env(&env);
1163 if let Err(error) = billing.settle_runs(&keeper).await {
1164 worker::console_error!("settling runs failed: {error}");
1165 }
1166 if let Err(error) = billing.settle_own_runs().await {
1167 worker::console_error!("closing runs on own providers failed: {error}");
1168 }
1169 // Stripe events billing never received, handled now.
1170 match billing.replay_events().await {
1171 Ok(done) => worker::console_log!("stripe replay: {done}"),
1172 Err(error) => worker::console_error!("replaying Stripe events failed: {error}"),
1173 }
1174 if let Err(error) = billing.autopay().await {
1175 worker::console_error!("paying at the limit failed: {error}");
1176 }
1177 // AI credit below a workspace's auto-reload threshold, reloaded (ai.rs).
1178 match billing.reload_ai_credit().await {
1179 Ok(0) => {}
1180 Ok(done) => worker::console_log!("auto-reloaded AI credit for {done} workspaces"),
1181 Err(error) => worker::console_error!("auto-reloading AI credit failed: {error}"),
1182 }
1183 // Last month's metered usage (scans, embeddings, storage) goes on the
1184 // ledger before the month is closed and invoiced.
1185 if let Err(error) = billing.charge_pending().await {
1186 worker::console_error!("charging last month's metered usage failed: {error}");
1187 }
1188 if let Err(error) = billing.close_months().await {
1189 worker::console_error!("closing the month failed: {error}");
1190 }
1191 if let Err(error) = billing.invoice_enterprises().await {
1192 worker::console_error!("invoicing enterprises failed: {error}");
1193 }
1194 // Comped budgets' alerts, and a tripped breaker staff were not told of.
1195 if let Err(error) = billing.watch_spend().await {
1196 worker::console_error!("watching g1t's own spend failed: {error}");
1197 }
1198 if let Ok(identity) = env.service("IDENTITY")
1199 && let Err(error) = billing.warn_limits(&identity).await {
1200 worker::console_error!("warning owners failed: {error}");
1201 }
1202 // Once a day: Stripe's endpoint kept listening to billing's events and
1203 // enabled, and saved cards and plans not read in a while read again.
1204 if event.cron() == keeper::DAILY {
1205 match billing.keep_endpoint("billing").await {
1206 Ok(done) => worker::console_log!("stripe endpoint: {done}"),
1207 Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"),
1208 }
1209 match billing.refresh_from_stripe().await {
1210 Ok(done) => worker::console_log!("stripe refresh: {done}"),
1211 Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"),
1212 }
1213 }
1214 // Once a day, and at once if the costs were never checked: check every
1215 // cost against what Cloudflare billed.
1216 if (event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false))
1217 && let Err(error) = billing.reconcile(&keeper).await {
1218 worker::console_error!("checking costs against Cloudflare failed: {error}");
1219 }
1220 // Once a day: credit from g1t past its expiry stops counting
1221 // (grants.rs), before the day is reconciled.
1222 if event.cron() == keeper::DAILY {
1223 match billing.expire_credits().await {
1224 Ok(closed) => worker::console_log!("credits expired: {closed}"),
1225 Err(error) => worker::console_error!("expiring credits failed: {error}"),
1226 }
1227 }
1228 // Once a day: what Cloudflare charged, reconciled against what g1t
1229 // counted and charged; prices whose day has come; margin alerts
1230 // (margin.rs). After the keeper, so its proposals are in.
1231 if event.cron() == keeper::DAILY {
1232 match billing.costs_daily(&env, &keeper).await {
1233 Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1234 Err(error) => worker::console_error!("reconciling costs failed: {error}"),
1235 }
1236 }
1237 // Once a day: what each workspace's private repositories hold, its git
1238 // operations, Deployments plans from before the g1t plan set to end,
1239 // and old reservations cleared.
1240 if event.cron() == keeper::DAILY {
1241 if let Err(error) = billing.measure_packages().await {
1242 worker::console_error!("measuring package storage failed: {error}");
1243 }
1244 if let Err(error) = billing.measure_storage().await {
1245 worker::console_error!("measuring storage failed: {error}");
1246 }
1247 if let Err(error) = billing.measure_git().await {
1248 worker::console_error!("measuring git operations failed: {error}");
1249 }
1250 if let Err(error) = billing.retire_deployments_plans().await {
1251 worker::console_error!("ending Deployments plans failed: {error}");
1252 }
1253 if let Err(error) = billing.sweep_reservations().await {
1254 worker::console_error!("clearing reservations failed: {error}");
1255 }
1256 // The AI Gateway's log keeps 30 days (gateway.rs).
1257 if let Err(error) = billing.forget_gateway_requests().await {
1258 worker::console_error!("clearing old AI Gateway requests failed: {error}");
1259 }
1260 // Checks of the providers' model lists keep 90 days (catalogue.rs).
1261 if let Err(error) = billing.forget_model_checks().await {
1262 worker::console_error!("clearing old model checks failed: {error}");
1263 }
1264 }
1265}
1266
1267/// Events from the bus, on billing's own queue: only a workspace's rename
1268/// matters here (see `rename`).
1269#[event(queue)]
1270async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
1271 let billing = Billing::from_env(&env)?;
1272 let identity = env.service("IDENTITY").ok();
1273 for message in batch.messages()? {
1274 // A repository transferred: its share of the open-source pool this
1275 // month follows it. What it was charged stays with the workspace
1276 // it was charged to; usage from now on is charged to the new one.
1277 if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? {
1278 message.ack();
1279 continue;
1280 }
1281 billing.on_event(identity.as_ref(), message.body()).await?;
1282 message.ack();
1283 }
1284 Ok(())
1285}
1286
1287#[event(fetch)]
1288async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1289 let Some(method) = rpc_method(&request) else {
1290 return Response::error("Not found", 404);
1291 };
1292 // A replica near the caller when it asks for one (crates/kit/src/d1.rs);
1293 // what other services call (can_start, start_run) asks for none.
1294 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
1295 let body: serde_json::Value = request.json().await?;
1296 let mut billing = Billing::from_env(&env)?;
1297 billing.db = db;
1298 let answered = match method.as_str() {
1299 "status" => reply(&billing.status()),
1300 "account" => reply(&billing.account(args(body)?).await?),
1301 "ledger" => reply(&billing.ledger(args(body)?).await?),
1302 "credits" => reply(&billing.credits(args(body)?).await?),
1303 "usage" => reply(&billing.usage(args(body)?).await?),
1304 "usage_report" => reply(&billing.usage_report(args(body)?).await?),
1305 "ai_credit" => reply(&billing.ai_credit(args(body)?).await?),
1306 "buy_ai_credit" => reply(&billing.buy_ai_credit(args(body)?).await?),
1307 "confirm_ai_credit" => reply(&billing.confirm_ai_credit(args(body)?).await?),
1308 "set_ai_reload" => reply(&billing.set_ai_reload(args(body)?).await?),
1309 "set_budget" => reply(&billing.set_budget(args(body)?).await?),
1310 "billing_details" => reply(&billing.billing_details(args(body)?).await?),
1311 "set_billing_details" => reply(&billing.set_billing_details(args(body)?).await?),
1312 "record_tokens" => reply(&billing.record_tokens(args(body)?).await?),
1313 "token_usage" => reply(&billing.token_usage(args(body)?).await?),
1314 "gateway_models" => reply(&billing.gateway_models().await?),
1315 "model_defaults" => reply(&billing.model_defaults().await?),
1316 "record_discovery" => reply(&billing.record_discovery(args(body)?).await?),
1317 "admin_models" => reply(&billing.admin_models().await?),
1318 "admin_decide_model" => reply(&billing.admin_decide_model(args(body)?).await?),
1319 "admin_set_model_default" => reply(&billing.admin_set_model_default(args(body)?).await?),
1320 "gateway_admit" => reply(&billing.gateway_admit(args(body)?).await?),
1321 "record_gateway" => reply(&billing.record_gateway(args(body)?).await?),
1322 "gateway_requests" => reply(&billing.gateway_requests(args(body)?).await?),
1323 "checkout" => reply(&billing.checkout(args(body)?).await?),
1324 "confirm" => reply(&billing.confirm(args(body)?).await?),
1325 "can_start" => reply(&billing.can_start(args(body)?).await?),
1326 "trial" => reply(&billing.trial(args(body)?).await?),
1327 "start_run" => reply(&billing.start_run(args(body)?).await?),
1328 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
1329 "features" => reply(&billing.features(args(body)?).await?),
1330 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1331 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1332 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
1333 "close_workspace" => reply(&billing.close_workspace(args(body)?).await?),
1334 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
1335 "free_workspaces" => reply(&billing.free_workspaces(args(body)?).await?),
1336 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
1337 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
1338 "limit" => reply(&billing.limit(args(body)?).await?),
1339 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1340 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
1341 "prices" => reply(&billing.prices().await?),
1342 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1343 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
1344 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1345 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
1346 "admin_enterprise_address" => reply(&billing.admin_enterprise_address(args(body)?).await?),
1347 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1348 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
1349 "invoices" => reply(&billing.invoices(args(body)?).await?),
1350 "statement" => reply(&billing.statement(args(body)?).await?),
1351 "statement_entries" => reply(&billing.statement_entries(args(body)?).await?),
1352 "usage_meters" => reply(&billing.usage_meters(args(body)?).await?),
1353 "admin_workspace_invoices" => {
1354 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1355 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1356 }
1357 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1358 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1359 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1360 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1361 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
1362 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1363 "admin_audit" => reply(&billing.admin_audit(args(body)?).await?),
1364 // A staff change made in another service, for sudo's audit log:
1365 // identity's restores and purges of deleted workspaces.
1366 "admin_log" => {
1367 let a: AdminLogArgs = args(body)?;
1368 billing
1369 .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by)
1370 .await?;
1371 reply(&true)
1372 }
1373 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
1374 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1375 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1376 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1377 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1378 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1379 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
1380 "admin_credits" => reply(&billing.admin_credits(args(body)?).await?),
1381 "admin_revoke_credit" => reply(&billing.admin_revoke_credit(args(body)?).await?),
1382 "admin_reset_billing" => reply(&billing.admin_reset_billing(&env, args(body)?).await?),
1383 "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?),
1384 "entitlements" => reply(&billing.entitlements(args(body)?).await?),
1385 "audit_retention" => reply(&billing.audit_retention(args(body)?).await?),
1386 "reserve" => reply(&billing.reserve(args(body)?).await?),
1387 "settle" => reply(&billing.settle_reservation(args(body)?).await?),
1388 "card_check" => reply(&billing.card_check(args(body)?).await?),
1389 "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?),
1390 "request_limit" => reply(&billing.request_limit(args(body)?).await?),
1391 "limit_requests" => reply(&billing.limit_requests(args(body)?).await?),
1392 "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?),
1393 "set_caps" => reply(&billing.set_caps(args(body)?).await?),
1394 "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?),
1395 "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?),
1396 "admin_overages" => reply(&billing.admin_overages(args(body)?).await?),
1397 "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?),
1398 "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?),
1399 "admin_record_payment" => reply(&billing.admin_record_payment(args(body)?).await?),
1400 "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?),
1401 "admin_cost_alerts" => reply(&billing.admin_cost_alerts(args(body)?).await?),
1402 "admin_spend_caps" => reply(&billing.spend_caps().await?),
1403 "admin_lift_breaker" => reply(&billing.admin_lift_breaker(args(body)?).await?),
1404 "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?),
1405 "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?),
1406 "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?),
1407 "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?),
1408 _ => Response::error("Unknown method", 404),
1409 };
1410 served.finish(answered)
1411}
1412
1413#[cfg(test)]
1414mod tests {
1415 use super::*;
1416
1417 #[test]
1418 fn a_run_is_charged_its_cost_plus_the_margin() {
1419 // $0.05 at 20% is six cents.
1420 assert_eq!(charge_micros(0.05, 20), 60_000);
1421 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1422 assert_eq!(charge_micros(0.05, 0), 50_000);
1423 }
1424
1425 #[test]
1426 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1427 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1428 assert_eq!(charge_micros(0.0, 20), 0);
1429 assert_eq!(charge_micros(-3.0, 20), 0);
1430 }
1431
1432 #[test]
1433 fn sandbox_time_is_charged_from_the_first_second() {
1434 // 21 millionths a second at cost, plus 20%.
1435 let price = Price::price_for(21.0, 20);
1436 assert_eq!(sandbox_charge(1, price), 26);
1437 assert_eq!(sandbox_charge(60, price), 1_512);
1438 assert_eq!(sandbox_charge(0, price), 0);
1439 }
1440
1441 #[test]
1442 fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() {
1443 assert!(prepay_amount(2_500, false).is_ok());
1444 assert!(prepay_amount(2_499, false).is_err());
1445 assert!(prepay_amount(10_000, false).is_ok());
1446 assert!(prepay_amount(1_000_000, false).is_ok());
1447 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.");
1448 assert!(prepay_amount(99_999, true).is_err());
1449 assert!(prepay_amount(100_000, true).is_ok());
1450 }
1451
1452 #[test]
1453 fn durations_read_plainly() {
1454 assert_eq!(duration(40), "40s");
1455 assert_eq!(duration(192), "3m 12s");
1456 assert_eq!(duration(3720), "1h 2m");
1457 }
1458
1459 #[test]
1460 fn an_absurd_cost_is_capped() {
1461 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1462 }
1463
1464 /// Every migration, in order, as D1 applies them.
1465 const MIGRATIONS: &[&str] = &[
1466 include_str!("../migrations/0001_init.sql"),
1467 include_str!("../migrations/0002_own_provider.sql"),
1468 include_str!("../migrations/0003_subscriptions.sql"),
1469 include_str!("../migrations/0004_sandbox_time.sql"),
1470 include_str!("../migrations/0005_limits.sql"),
1471 include_str!("../migrations/0006_prices.sql"),
1472 include_str!("../migrations/0007_pending_usage.sql"),
1473 include_str!("../migrations/0008_accounts.sql"),
1474 include_str!("../migrations/0009_autopay.sql"),
1475 include_str!("../migrations/0010_month_close.sql"),
1476 include_str!("../migrations/0011_limit_warnings.sql"),
1477 include_str!("../migrations/0012_stripe_webhooks.sql"),
1478 include_str!("../migrations/0013_invoices_trust_sales.sql"),
1479 include_str!("../migrations/0014_custom_domain_price.sql"),
1480 include_str!("../migrations/0015_sandbox_at_cost.sql"),
1481 include_str!("../migrations/0016_plans_and_pools.sql"),
1482 include_str!("../migrations/0017_flagon_comped.sql"),
1483 include_str!("../migrations/0018_one_plan.sql"),
1484 include_str!("../migrations/0019_closed_workspaces.sql"),
1485 include_str!("../migrations/0020_syntaqx_standard.sql"),
1486 include_str!("../migrations/0021_no_quotas.sql"),
1487 include_str!("../migrations/0022_costs_and_margin.sql"),
1488 include_str!("../migrations/0023_one_operation_mapping.sql"),
1489 include_str!("../migrations/0024_spend_caps.sql"),
1490 include_str!("../migrations/0025_run_tier.sql"),
1491 include_str!("../migrations/0026_ledger_by_workspace_time.sql"),
1492 include_str!("../migrations/0027_stripe_cache.sql"),
1493 include_str!("../migrations/0028_drop_stripe_webhooks.sql"),
1494 include_str!("../migrations/0029_audit_retention.sql"),
1495 include_str!("../migrations/0030_token_usage.sql"),
1496 include_str!("../migrations/0031_package_storage.sql"),
1497 include_str!("../migrations/0032_workspace_value.sql"),
1498 include_str!("../migrations/0033_given_away.sql"),
1499 include_str!("../migrations/0034_given_by_why.sql"),
1500 include_str!("../migrations/0035_cf_subscriptions.sql"),
1501 include_str!("../migrations/0036_model_costs_in_full.sql"),
1502 include_str!("../migrations/0037_security_activation.sql"),
1503 include_str!("../migrations/0038_staff_credits.sql"),
1504 include_str!("../migrations/0039_discounts_not_comped.sql"),
1505 include_str!("../migrations/0040_ai_credit.sql"),
1506 include_str!("../migrations/0041_agent_rate_own_key.sql"),
1507 include_str!("../migrations/0042_agent_rate_weights.sql"),
1508 include_str!("../migrations/0043_tax_and_card_fees.sql"),
1509 include_str!("../migrations/0044_cache_reads_count_a_tenth.sql"),
1510 include_str!("../migrations/0045_gateway.sql"),
1511 include_str!("../migrations/0046_reset_costs.sql"),
1512 include_str!("../migrations/0047_gateway_formats.sql"),
1513 include_str!("../migrations/0048_model_catalogue.sql"),
1514 ];
1515
1516 /// The columns of `table` after the migrations: each with whether an
1517 /// insert must give it (NOT NULL, no default).
1518 fn columns(table: &str) -> Vec<(String, bool)> {
1519 let mut out = vec![];
1520 for sql in MIGRATIONS {
1521 let sql: String = sql.lines().map(|l| l.split("--").next().unwrap_or("")).collect::<Vec<_>>().join("\n");
1522 if let Some(start) = sql.find(&format!("CREATE TABLE {table} (")) {
1523 let body = &sql[start + format!("CREATE TABLE {table} (").len()..];
1524 let body = &body[..body.find(");").unwrap()];
1525 for column in body.split(",\n") {
1526 let column = column.trim();
1527 let name = column.split_whitespace().next().unwrap_or("").to_owned();
1528 if name.is_empty() || name == "PRIMARY" {
1529 continue;
1530 }
1531 let required = column.contains("NOT NULL") && !column.contains("DEFAULT") && !column.contains("PRIMARY KEY");
1532 out.push((name, required || column.contains("PRIMARY KEY")));
1533 }
1534 }
1535 for statement in sql.split(';') {
1536 let s = statement.trim();
1537 if let Some(rest) = s.strip_prefix(&format!("ALTER TABLE {table} ADD COLUMN ")) {
1538 let name = rest.split_whitespace().next().unwrap().to_owned();
1539 out.push((name, rest.contains("NOT NULL") && !rest.contains("DEFAULT")));
1540 }
1541 }
1542 }
1543 out
1544 }
1545
1546 /// The columns an `INSERT INTO table (…)` names.
1547 fn inserted(sql: &str, table: &str) -> Vec<String> {
1548 let start = sql.find(&format!("INSERT INTO {table} (")).unwrap() + format!("INSERT INTO {table} (").len();
1549 sql[start..start + sql[start..].find(')').unwrap()].split(',').map(|c| c.trim().to_owned()).collect()
1550 }
1551
1552
1553 #[test]
1554 fn ai_prices_are_price_book_data_with_dated_versions() {
1555 let sql = include_str!("../migrations/0040_ai_credit.sql");
1556 let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned();
1557 // AI Gateway: the provider's price, no markup while in beta.
1558 assert!(row("('gateway_models', 'AI Gateway models'").contains("1000000, 0, 'list'"));
1559 // Models lose their markup from 2026-10-08, a fall that applies at once…
1560 assert!(row("('pv_agent_models_2'").contains("1000000, 0, '2026-10-08"));
1561 // …and the agent rate is $0.25 a million tokens after 14 days' notice.
1562 assert!(row("('pv_agent_tokens_2'").contains("250000, 0, '2026-10-22"));
1563 // The card fee is 2.9% + 30¢, switchable.
1564 assert!(row("('card_fee_percent'").contains("29000"));
1565 assert!(row("('card_fee_fixed'").contains("300000"));
1566 assert!(row("('card_fee', 'on'").contains("'on'"));
1567 }
1568
1569 #[test]
1570 fn the_agent_rate_on_an_own_model_key_is_its_own_dated_meter() {
1571 let sql = include_str!("../migrations/0041_agent_rate_own_key.sql");
1572 let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned();
1573 // Nothing until the notice has run…
1574 assert!(row("('pv_agent_tokens_own_1'").contains("0, 0, '2026-10-08"));
1575 // …then $0.25 a million tokens, as on g1t's models, 14 days after.
1576 assert!(row("('pv_agent_tokens_own_2'").contains("250000, 0, '2026-10-22"));
1577 assert!(row("('agent_tokens_own',").contains("'million tokens', 0, 0, 'list'"));
1578 assert_eq!(ai::agent_rate_meter(true), "agent_tokens_own");
1579 }
1580
1581 #[test]
1582 fn the_agent_rate_counts_every_token_once_until_a_weight_is_decided() {
1583 let sql = include_str!("../migrations/0042_agent_rate_weights.sql");
1584 for kind in ["input", "output", "cache_read", "cache_write"] {
1585 let meter = format!("('agent_token_weight_{kind}', 'Agent rate weight");
1586 let row = sql.lines().find(|l| l.contains(&meter)).unwrap_or_else(|| panic!("no {kind} weight"));
1587 assert!(row.contains("'weight', 1000000, 0, 'list'"), "{kind}: {row}");
1588 let version = format!("('pv_agent_token_weight_{kind}_1', 'agent_token_weight_{kind}', 1, 1000000,");
1589 assert!(sql.contains(&version), "{kind} has no applied version");
1590 }
1591 assert_eq!(ai::weight_of(1_000_000.0), 1.0);
1592 }
1593 #[test]
1594 fn every_checkout_insert_fills_the_table() {
1595 // The plan's, the activation's, a card check's, a prepayment's and
1596 // AI credit's pages all go through one insert, and it names every
1597 // column the table needs and none it lacks: a missing NOT NULL
1598 // column, or one from a migration not yet applied, was a 500.
1599 let table = columns("checkouts");
1600 let names: Vec<&str> = table.iter().map(|(n, _)| n.as_str()).collect();
1601 assert_eq!(names, ["id", "workspace", "amount_cents", "created_by", "status", "created_at", "feature", "fee_cents"]);
1602 let given = inserted(CHECKOUT_INSERT, "checkouts");
1603 for column in &given {
1604 assert!(names.contains(&column.as_str()), "the insert names {column}, which checkouts does not have");
1605 }
1606 for (column, required) in &table {
1607 assert!(!required || given.contains(column), "checkouts needs {column}, which the insert leaves out");
1608 }
1609 // As many values as columns.
1610 let values = CHECKOUT_INSERT.split("VALUES").nth(1).unwrap();
1611 assert_eq!(values.matches('?').count() + values.matches("'open'").count(), given.len());
1612 // And no page writes a row of its own any more.
1613 for (file, source) in [
1614 ("lib.rs", include_str!("lib.rs")),
1615 ("features.rs", include_str!("features.rs")),
1616 ("cards.rs", include_str!("cards.rs")),
1617 ("ai.rs", include_str!("ai.rs")),
1618 ] {
1619 let inserts = source.matches(concat!("INSERT INTO ", "checkouts")).count();
1620 assert!(inserts <= usize::from(file == "lib.rs"), "{file} inserts into checkouts on its own");
1621 }
1622 }
1623
1624 #[test]
1625 fn a_new_ledger_column_has_a_default() {
1626 // The ledger is written from a dozen places; a column without a
1627 // default would break every one that does not name it.
1628 for (column, required) in columns("ledger") {
1629 assert!(!required || ["id", "workspace", "kind", "amount_micros", "description", "reference", "created_at"].contains(&column.as_str()), "{column}");
1630 }
1631 }
1632}