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