Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
726 linesCodeBlameRaw
1//! Keeps every price current with what g1t actually pays.
2//!
3//! g1t passes its own costs through, so a price is only right while the
4//! cost under it is. One job keeps them right, on the billing service's
5//! daily cron:
6//!
7//! - **Checking costs** (daily). What Cloudflare billed g1t's account, from
8//! its usage API, is measured against how much was used: Containers
9//! against the seconds containers ran, Workers for Platforms per request
10//! and per CPU millisecond. When a measured cost moves, the price book
11//! moves with it, since each price is its cost plus a set markup, and
12//! the change is recorded where anyone can see it. A measurement goes
13//! through `pricing` as a proposal: a small move is applied on its own (a
14//! rise only after customers have had notice), a large or suspect one
15//! waits for staff in sudo, so one odd day of data cannot reprice
16//! everything.
17
18use g1t_contracts::actions::{InstanceType, STANDARD_INSTANCE, runner_minutes};
19use g1t_contracts::billing::{MICROS_PER_DOLLAR, Price, PriceBook, PriceChange};
20
21use g1t_contracts::time::rfc3339;
22use g1t_kit::now_ms;
23use serde::Deserialize;
24use serde_json::{Value, json};
25use worker::{Env, Fetch, Headers, Method, Request, RequestInit, Result};
26
27use crate::Billing;
28
29/// The cron that also checks costs against Cloudflare's bill.
30pub(crate) const DAILY: &str = "17 4 * * *";
31/// The quarter-hourly tick: settling, and once an hour the platform watch.
32pub(crate) const QUARTER_HOURLY: &str = "*/15 * * * *";
33
34/// Where the keeper reads what g1t pays.
35pub(crate) struct Keeper {
36 /// `CLOUDFLARE_USAGE_TOKEN`: Billing and Account Analytics, read only.
37 token: Option<String>,
38 /// What reads the bill for `costs`: `CLOUDFLARE_BILLING_TOKEN`
39 /// (Account: Billing Read and Account Analytics Read), or the usage
40 /// token, which has both.
41 billing_token: Option<String>,
42 account: String,
43}
44
45impl Keeper {
46 pub(crate) fn from_env(env: &Env) -> Self {
47 let var = |name: &str| env.var(name).map(|v| v.to_string()).unwrap_or_default();
48 let secret = |name: &str| env.secret(name).ok().map(|v| v.to_string()).filter(|v| !v.is_empty());
49 let token = secret("CLOUDFLARE_USAGE_TOKEN");
50 Keeper {
51 billing_token: secret("CLOUDFLARE_BILLING_TOKEN").or_else(|| token.clone()),
52 token,
53 account: var("CLOUDFLARE_ACCOUNT_ID"),
54 }
55 }
56
57 async fn send(&self, method: Method, url: &str, body: Option<Value>) -> Result<Value> {
58 let Some(token) = &self.token else {
59 return Err(worker::Error::RustError("no CLOUDFLARE_USAGE_TOKEN".into()));
60 };
61 send_with(token, method, url, body).await
62 }
63
64 /// Whether Cloudflare's bill can be read.
65 pub(crate) fn can_read_bill(&self) -> bool {
66 self.billing_token.is_some() && !self.account.is_empty()
67 }
68
69 fn billing_token(&self) -> Result<&str> {
70 self.billing_token
71 .as_deref()
72 .ok_or_else(|| worker::Error::RustError("no CLOUDFLARE_BILLING_TOKEN or CLOUDFLARE_USAGE_TOKEN".into()))
73 }
74
75 /// Billable usage from `from` to `to` (dates), every page of it, as one
76 /// answer (`result` holds all the rows), and how many pages it took.
77 /// An answer that says it failed is returned as it is.
78 pub(crate) async fn billable_usage_pages(&self, from: &str, to: &str) -> Result<(Value, u32)> {
79 usage_pages(self.billing_token()?, &self.api(&format!("/billable-usage?from={from}&to={to}"))).await
80 }
81
82 /// The account's subscriptions (Workers Paid, add-ons), as Cloudflare
83 /// answers them. Needs Account: Billing Read.
84 pub(crate) async fn subscriptions_body(&self) -> Result<Value> {
85 send_with(self.billing_token()?, Method::Get, &self.api("/subscriptions"), None).await
86 }
87
88 /// A GraphQL Analytics query, as Cloudflare answers it, errors and all.
89 pub(crate) async fn graphql(&self, body: Value) -> Result<Value> {
90 send_with(self.billing_token()?, Method::Post, "https://api.cloudflare.com/client/v4/graphql", Some(body)).await
91 }
92
93 pub(crate) fn account(&self) -> &str {
94 &self.account
95 }
96
97 fn api(&self, path: &str) -> String {
98 format!("https://api.cloudflare.com/client/v4/accounts/{}{path}", self.account)
99 }
100
101 /// The account's billable usage, one row per service per day, as
102 /// Cloudflare reports it.
103 async fn billable_usage(&self, from: &str, to: &str) -> Result<Vec<UsageRow>> {
104 let Some(token) = &self.token else {
105 return Err(worker::Error::RustError("no CLOUDFLARE_USAGE_TOKEN".into()));
106 };
107 let (body, _) = usage_pages(token, &self.api(&format!("/billable-usage?from={from}&to={to}"))).await?;
108 let rows = body["result"].as_array().cloned().unwrap_or_default();
109 Ok(rows.iter().filter_map(UsageRow::from_value).collect())
110 }
111
112 /// What g1t's containers used from `since` to `until` (dates), as
113 /// Cloudflare bills it: memory in byte-seconds, and CPU seconds.
114 async fn container_usage(&self, since: &str, until: &str) -> Result<ContainerUsage> {
115 let query = "query ($account: String!, $since: Date!, $until: Date!) {
116 viewer { accounts(filter: { accountTag: $account }) {
117 containersUsageAdaptiveGroups(limit: 1000, filter: { date_geq: $since, date_leq: $until }) {
118 sum { cpuTimeSec allocatedMemory }
119 }
120 } }
121 }";
122 let body = self
123 .send(
124 Method::Post,
125 "https://api.cloudflare.com/client/v4/graphql",
126 Some(json!({ "query": query, "variables": { "account": self.account, "since": since, "until": until } })),
127 )
128 .await?;
129 let groups = body["data"]["viewer"]["accounts"][0]["containersUsageAdaptiveGroups"]
130 .as_array()
131 .cloned()
132 .unwrap_or_default();
133 Ok(groups.iter().fold(ContainerUsage::default(), |total, g| ContainerUsage {
134 cpu_seconds: total.cpu_seconds + g["sum"]["cpuTimeSec"].as_f64().unwrap_or(0.0),
135 memory_byte_seconds: total.memory_byte_seconds + g["sum"]["allocatedMemory"].as_f64().unwrap_or(0.0),
136 }))
137 }
138}
139
140/// A request to Cloudflare's API with a bearer token; anything but 200 is
141/// an error with what Cloudflare said.
142/// The most pages of billable usage read in one go: far more than a few
143/// months of g1t's meters.
144const MAX_USAGE_PAGES: u32 = 50;
145
146/// Every page of a billable-usage answer, its rows together. Before
147/// 2026-10-09 only the first page was read.
148async fn usage_pages(token: &str, url: &str) -> Result<(Value, u32)> {
149 let mut rows: Vec<Value> = Vec::new();
150 let mut pages = 0;
151 let mut next = url.to_owned();
152 loop {
153 let body = send_with(token, Method::Get, &next, None).await?;
154 if body["success"] == Value::Bool(false) {
155 return Ok((body, pages + 1));
156 }
157 pages += 1;
158 rows.extend(body["result"].as_array().cloned().unwrap_or_default());
159 match crate::costs::next_page(&body, pages).filter(|_| pages < MAX_USAGE_PAGES) {
160 Some(query) => next = format!("{url}&{query}"),
161 None => break,
162 }
163 }
164 Ok((json!({ "success": true, "result": rows }), pages))
165}
166
167async fn send_with(token: &str, method: Method, url: &str, body: Option<Value>) -> Result<Value> {
168 let headers = Headers::new();
169 headers.set("authorization", &format!("Bearer {token}"))?;
170 headers.set("content-type", "application/json")?;
171 let mut init = RequestInit::new();
172 init.with_method(method).with_headers(headers);
173 if let Some(body) = body {
174 init.with_body(Some(body.to_string().into()));
175 }
176 let mut response = Fetch::Request(Request::new_with_init(url, &init)?).send().await?;
177 let status = response.status_code();
178 let value: Value = response.json().await.unwrap_or(Value::Null);
179 if status != 200 {
180 return Err(worker::Error::RustError(format!("Cloudflare answered {status}: {value}")));
181 }
182 Ok(value)
183}
184
185#[derive(Debug, Default, Clone, Copy)]
186pub(crate) struct ContainerUsage {
187 cpu_seconds: f64,
188 memory_byte_seconds: f64,
189}
190
191/// g1t's standard sandbox (`STANDARD_INSTANCE` in the contracts):
192/// Containers' standard-3, 2 vCPU, 8 GiB and 16 GB of disk. Memory and disk
193/// are billed as provisioned for every second it runs, so they are in the
194/// base; CPU only as used.
195const SANDBOX_GIB: f64 = 8.0;
196const SANDBOX_DISK_GB: f64 = 16.0;
197const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
198/// The Durable Object behind each container is billed for as long as the
199/// container runs, at 128 MB.
200const SANDBOX_DO_GB: f64 = 0.125;
201
202/// Cloudflare's published Containers rates, in dollars, used for any rate
203/// the bill does not show yet (while usage is inside the included amount).
204const LIST_MEMORY_GIB_SECOND: f64 = 0.000_002_5;
205const LIST_DISK_GB_SECOND: f64 = 0.000_000_07;
206const LIST_VCPU_SECOND: f64 = 0.000_02;
207/// Durable Objects duration: $12.50 per million GB-seconds.
208const LIST_DO_GB_SECOND: f64 = 0.000_012_5;
209
210/// What one second of a sandbox costs whatever it does, in millionths of a
211/// dollar: its memory and disk, and the Durable Object behind it, for the
212/// whole second. CPU is billed only while busy, on top.
213pub(crate) fn sandbox_base_micros(memory: f64, disk: f64, durable_object: f64) -> f64 {
214 (SANDBOX_GIB * memory + SANDBOX_DISK_GB * disk + SANDBOX_DO_GB * durable_object) * MICROS_PER_DOLLAR as f64
215}
216
217/// What one second of a sandbox costs on average, in millionths of a
218/// dollar: its base, and the CPU sandboxes actually use per second of
219/// running. Runs that report their own CPU are priced on it instead (see
220/// `run_cost`).
221pub(crate) fn sandbox_second_micros(usage: ContainerUsage, memory: f64, disk: f64, vcpu: f64, durable_object: f64) -> Option<f64> {
222 let instance_seconds = usage.memory_byte_seconds / (SANDBOX_GIB * GIB);
223 if instance_seconds < 3600.0 {
224 return None;
225 }
226 let cpu_share = usage.cpu_seconds / instance_seconds;
227 Some(sandbox_base_micros(memory, disk, durable_object) + cpu_share * vcpu * MICROS_PER_DOLLAR as f64)
228}
229
230/// How much more a second of a larger machine's memory and disk (and the
231/// Durable Object behind it) costs than the standard sandbox's, at
232/// Cloudflare's list rates: 1 for the standard machine.
233pub(crate) fn base_scale(memory_gib: f64, disk_gb: f64) -> f64 {
234 let base = |memory: f64, disk: f64| memory * LIST_MEMORY_GIB_SECOND + disk * LIST_DISK_GB_SECOND + SANDBOX_DO_GB * LIST_DO_GB_SECOND;
235 base(memory_gib, disk_gb) / base(SANDBOX_GIB, SANDBOX_DISK_GB)
236}
237
238/// How much more a second of a machine costs g1t than the standard
239/// sandbox's with every vCPU of each as busy, at Cloudflare's list rates: 1
240/// for the standard machine. What a run that did not report its CPU is
241/// costed at, against the measured `sandbox_second`.
242pub(crate) fn busy_scale(instance: &InstanceType) -> f64 {
243 let busy = |i: &InstanceType| {
244 i.memory_gib * LIST_MEMORY_GIB_SECOND + i.disk_gb * LIST_DISK_GB_SECOND + i.vcpu * LIST_VCPU_SECOND + SANDBOX_DO_GB * LIST_DO_GB_SECOND
245 };
246 busy(instance) / busy(&STANDARD_INSTANCE)
247}
248
249/// What a job on g1t's machines is charged before the account's terms:
250/// its minutes, rounded up (`runner_minutes`), at its machine's rate a
251/// minute. The rates cover a machine with every vCPU busy at Cloudflare's
252/// list prices; should what a job cost g1t ever come to more (a dearer
253/// bill), it is charged that cost instead, so g1t never sells a minute
254/// below cost. Returns the minutes and the price.
255pub(crate) fn runner_charge(seconds: i64, instance: &InstanceType, cost: i64) -> (i64, i64) {
256 let minutes = runner_minutes(seconds);
257 (minutes, (minutes * instance.micros_per_minute).max(cost.max(0)))
258}
259
260/// `1 minute`, `12 minutes`.
261pub(crate) fn minutes_text(minutes: i64) -> String {
262 format!("{minutes} minute{}", if minutes == 1 { "" } else { "s" })
263}
264
265/// What a run that reported its own CPU cost g1t: its base for every
266/// second, and its vCPU-seconds at the vCPU rate.
267pub(crate) fn run_cost(seconds: i64, cpu_seconds: f64, base_per_second: f64, per_vcpu_second: f64) -> f64 {
268 seconds.max(0) as f64 * base_per_second + cpu_seconds.max(0.0) * per_vcpu_second
269}
270
271/// A unit's rate from the bill: the median, over the days with a list
272/// cost, of list cost over quantity. Never what was billed: that is net of
273/// the included amounts (nothing while a cycle is inside them, part of a
274/// day's usage on the day it passes one), so over all of the quantity it
275/// reads as a lower price when nothing changed. None without a list cost;
276/// the published rates stand in.
277pub(crate) fn billed_rate(rows: &[&UsageRow]) -> Option<f64> {
278 let mut rates: Vec<f64> = rows
279 .iter()
280 .filter(|r| r.list_cost > 0.0 && r.quantity > 0.0)
281 .map(|r| r.list_cost / r.quantity)
282 .collect();
283 if rates.is_empty() {
284 return None;
285 }
286 rates.sort_by(f64::total_cmp);
287 Some(rates[rates.len() / 2])
288}
289
290/// One line of Cloudflare's billable usage.
291#[derive(Debug, Clone)]
292pub(crate) struct UsageRow {
293 period_start: String,
294 period_end: String,
295 service: String,
296 unit: String,
297 quantity: f64,
298 cost: f64,
299 /// The quantity at list price, before the included amounts.
300 list_cost: f64,
301}
302
303impl UsageRow {
304 /// Read leniently: the API is new, and its field names are FOCUS's.
305 fn from_value(row: &Value) -> Option<Self> {
306 let text = |keys: &[&str]| keys.iter().find_map(|k| row[*k].as_str()).unwrap_or_default().to_owned();
307 let number = |keys: &[&str]| {
308 keys.iter()
309 .find_map(|k| row[*k].as_f64().or_else(|| row[*k].as_str().and_then(|s| s.parse().ok())))
310 .unwrap_or(0.0)
311 };
312 let service = text(&["ServiceName", "service_name", "service"]);
313 if service.is_empty() {
314 return None;
315 }
316 let family = text(&["ServiceFamilyName", "service_family_name"]);
317 Some(UsageRow {
318 period_start: text(&["ChargePeriodStart", "charge_period_start"]),
319 period_end: text(&["ChargePeriodEnd", "charge_period_end"]),
320 service: if family.is_empty() { service } else { format!("{family} / {service}") },
321 unit: text(&["PricingUnit", "ConsumedUnit", "consumed_unit"]),
322 quantity: number(&["PricingQuantity", "ConsumedQuantity", "pricing_quantity"]),
323 // What g1t pays; list price if nothing was contracted.
324 cost: Some(number(&["ContractedCost", "BilledCost", "contracted_cost"]))
325 .filter(|cost| *cost > 0.0)
326 .unwrap_or_else(|| number(&["ListCost", "list_cost"])),
327 list_cost: number(&["ListCost", "list_cost"]),
328 })
329 }
330}
331
332#[derive(Deserialize)]
333struct PriceRow {
334 meter: String,
335 title: String,
336 unit: String,
337 cost_micros: f64,
338 markup_percent: u32,
339 source: String,
340 checked_at: Option<String>,
341 updated_at: String,
342}
343
344#[derive(Deserialize)]
345struct ChangeRow {
346 meter: String,
347 old_cost_micros: f64,
348 new_cost_micros: f64,
349 markup_percent: u32,
350 old_markup_percent: Option<u32>,
351 reason: String,
352 created_at: String,
353}
354
355impl Billing {
356 pub(crate) async fn prices(&self) -> Result<PriceBook> {
357 // Three reads at once; the plans are priced from the rows already
358 // read, not one query per meter (status.g1t.sh times this call).
359 let (prices, changes, coming) = futures_util::future::join3(
360 async { self.db.prepare("SELECT * FROM prices ORDER BY rowid").all().await?.results::<PriceRow>() },
361 async {
362 self.db
363 .prepare("SELECT * FROM price_changes ORDER BY created_at DESC LIMIT 20")
364 .all()
365 .await?
366 .results::<ChangeRow>()
367 },
368 // Changes still to come first, so a rise is seen before it is charged.
369 self.coming_changes(),
370 )
371 .await;
372 let (prices, changes, coming) = (prices?, changes?, coming?);
373 // Agents' and models' meters, from before g1t stopped running
374 // agents, stay in the table but are no longer prices.
375 let prices: Vec<PriceRow> = prices.into_iter().filter(|row| !crate::pricing::retired(&row.meter)).collect();
376 let changes: Vec<ChangeRow> = changes.into_iter().filter(|row| !crate::pricing::retired(&row.meter)).collect();
377 let coming: Vec<PriceChange> = coming.into_iter().filter(|change| !crate::pricing::retired(&change.meter)).collect();
378 let book: std::collections::BTreeMap<&str, f64> = prices
379 .iter()
380 .map(|row| (row.meter.as_str(), Price::price_for(row.cost_micros, row.markup_percent)))
381 .collect();
382 // With the card fee on top of each monthly price, as it is charged.
383 let card_fee = self.card_fee().await?;
384 let plans: Vec<_> = g1t_contracts::billing::Feature::ALL
385 .iter()
386 .map(|feature| {
387 let mut plan = match feature {
388 g1t_contracts::billing::Feature::Security => crate::features::security_plan_at(&book),
389 _ => self.plan_at(&book),
390 };
391 plan.card_fee_cents = crate::tax::fee_for(i64::from(plan.monthly_cents), &card_fee) as u32;
392 plan
393 })
394 .collect();
395 Ok(PriceBook {
396 prices: prices
397 .into_iter()
398 .map(|row| Price {
399 price_micros: Price::price_for(row.cost_micros, row.markup_percent),
400 meter: row.meter,
401 title: row.title,
402 unit: row.unit,
403 cost_micros: row.cost_micros,
404 markup_percent: row.markup_percent,
405 source: row.source,
406 checked_at: row.checked_at,
407 updated_at: row.updated_at,
408 })
409 .collect(),
410 changes: coming
411 .into_iter()
412 .chain(changes.into_iter().map(|row| PriceChange {
413 meter: row.meter,
414 old_cost_micros: row.old_cost_micros,
415 new_cost_micros: row.new_cost_micros,
416 markup_percent: row.markup_percent,
417 old_markup_percent: row.old_markup_percent,
418 reason: row.reason,
419 created_at: row.created_at,
420 effective_at: None,
421 }))
422 .collect(),
423 // Nothing is charged for models any more; kept for readers.
424 model_margin_percent: self.margin_percent,
425 plans,
426 free: Some(g1t_contracts::billing::FreeTier {
427 trial_workspace_micros: if self.trials_on { self.plans.trial_workspace_micros } else { 0 },
428 trial_monthly_pool_micros: if self.trials_on { self.plans.trial_monthly_pool_micros } else { 0 },
429 oss_pool_micros: self.plans.oss_pool_micros,
430 oss_repo_micros: self.plans.oss_repo_micros,
431 free_private_storage_bytes: self.plans.free_storage_bytes,
432 audit_retention_days: self.plans.free_audit_days,
433 plan_audit_retention_days: self.plans.audit_days,
434 min_charge_micros: self.plans.min_charge_micros,
435 git_operations_included: self.plans.git_included,
436 paid_start_ceiling_micros: self.plans.paid_start_micros,
437 overage_forgive_cost_micros: self.plans.forgive_cost_micros,
438 }),
439 })
440 }
441
442 /// Whether the costs have never been checked against Cloudflare's bill.
443 pub(crate) async fn never_checked(&self) -> Result<bool> {
444 Ok(self
445 .db
446 .prepare("SELECT meter FROM prices WHERE checked_at IS NOT NULL LIMIT 1")
447 .first::<Value>(None)
448 .await?
449 .is_none())
450 }
451
452 /// A meter's cost and price per unit, from the book.
453 pub(crate) async fn price(&self, meter: &str) -> Result<Option<(f64, f64)>> {
454 #[derive(Deserialize)]
455 struct Row {
456 cost_micros: f64,
457 markup_percent: u32,
458 }
459 Ok(self
460 .db
461 .prepare("SELECT cost_micros, markup_percent FROM prices WHERE meter = ?")
462 .bind(&[meter.into()])?
463 .first::<Row>(None)
464 .await?
465 .map(|row| (row.cost_micros, Price::price_for(row.cost_micros, row.markup_percent))))
466 }
467
468 pub(crate) async fn reconcile(&self, keeper: &Keeper) -> Result<()> {
469 if keeper.token.is_none() {
470 return Ok(());
471 }
472 let now = rfc3339(now_ms());
473 let today = &now[..10];
474 let since = rfc3339(now_ms() - 30 * 24 * 60 * 60 * 1000);
475 let rows = keeper.billable_usage(&since[..10], today).await?;
476 for row in &rows {
477 self.db
478 .prepare(
479 "INSERT INTO cloudflare_usage (period_start, period_end, service, unit, quantity, cost_usd, fetched_at)
480 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
481 ON CONFLICT (period_start, service, unit) DO UPDATE SET
482 period_end = ?2, quantity = ?5, cost_usd = ?6, fetched_at = ?7",
483 )
484 .bind(&[
485 row.period_start.as_str().into(),
486 row.period_end.as_str().into(),
487 row.service.as_str().into(),
488 row.unit.as_str().into(),
489 row.quantity.into(),
490 row.cost.into(),
491 now.as_str().into(),
492 ])?
493 .run()
494 .await?;
495 }
496
497 let named = |words: &[&str]| -> Vec<&UsageRow> {
498 rows.iter()
499 .filter(|r| {
500 let service = r.service.to_lowercase();
501 words.iter().all(|word| service.contains(word))
502 })
503 .collect()
504 };
505
506 // Containers: each resource at the list cost the bill shows for it
507 // (before the included amounts), or the published rate without one,
508 // over how much CPU g1t's sandboxes really use per second.
509 let memory = billed_rate(&named(&["container memory"]));
510 let disk = billed_rate(&named(&["container disk"]));
511 let vcpu = billed_rate(&named(&["container vcpu"]));
512 let durable_object = billed_rate(&named(&["durable objects", "duration"]));
513 let usage = keeper.container_usage(&since[..10], today).await?;
514 let rates = (
515 memory.unwrap_or(LIST_MEMORY_GIB_SECOND),
516 disk.unwrap_or(LIST_DISK_GB_SECOND),
517 vcpu.unwrap_or(LIST_VCPU_SECOND),
518 durable_object.unwrap_or(LIST_DO_GB_SECOND),
519 );
520 // The parts, for runs that report their own CPU.
521 let parts_reason = "Cloudflare's Containers and Durable Objects rates, as listed on the bill or published";
522 self.measure("sandbox_base_second", sandbox_base_micros(rates.0, rates.1, rates.3), parts_reason).await?;
523 self.measure("sandbox_cpu_second", rates.2 * MICROS_PER_DOLLAR as f64, parts_reason).await?;
524 if let Some(per_second) = sandbox_second_micros(usage, rates.0, rates.1, rates.2, rates.3) {
525 let instance_seconds = usage.memory_byte_seconds / (SANDBOX_GIB * GIB);
526 let billed = [("memory", memory), ("disk", disk), ("vCPU", vcpu), ("Durable Object duration", durable_object)]
527 .iter()
528 .filter(|(_, rate)| rate.is_some())
529 .map(|(name, _)| *name)
530 .collect::<Vec<_>>();
531 let reason = format!(
532 "Sandboxes used {:.2} vCPU per second over {:.0} hours of Cloudflare Containers in the last 30 days, with the Durable Object behind each; {}",
533 usage.cpu_seconds / instance_seconds,
534 instance_seconds / 3600.0,
535 if billed.is_empty() {
536 "rates are Cloudflare's published ones".to_owned()
537 } else {
538 format!("{} at the list cost on Cloudflare's bill", billed.join(", "))
539 },
540 );
541 for meter in ["sandbox_second", "build_second"] {
542 self.measure(meter, per_second, &reason).await?;
543 }
544 }
545 // Apps run as Workers: per million requests and CPU milliseconds,
546 // once the bill shows them charged.
547 // Security scans' CPU follows the same Workers CPU rate.
548 let app_meters: [(&str, &[&str], &str); 3] = [
549 ("app_requests", &["workers", "requests"], "requests"),
550 ("app_cpu", &["workers cpu"], "CPU ms"),
551 ("scan_cpu", &["workers cpu"], "CPU ms"),
552 ];
553 for (meter, words, unit) in app_meters {
554 if let Some(rate) = billed_rate(&named(words)) {
555 let reason = format!("Cloudflare's bill lists Workers {unit} at ${:.2} per million", rate * 1e6);
556 self.measure(meter, rate * 1e6 * MICROS_PER_DOLLAR as f64, &reason).await?;
557 }
558 }
559 self.db
560 .prepare("UPDATE prices SET checked_at = ?")
561 .bind(&[now.as_str().into()])?
562 .run()
563 .await?;
564 Ok(())
565 }
566
567 /// Proposes moving a meter's cost to a measurement (see `pricing`):
568 /// applied on its own when small, after notice when a rise; left for
569 /// staff when large or suspect.
570 async fn measure(&self, meter: &str, measured: f64, reason: &str) -> Result<()> {
571 if let Some(outcome) = self.propose(meter, measured, reason, "keeper").await? {
572 worker::console_log!("{meter}: {outcome}");
573 }
574 Ok(())
575 }
576}
577
578#[cfg(test)]
579mod tests {
580 use super::*;
581
582 #[test]
583 fn a_cost_plus_the_margin_rounds_up_to_a_whole_micro() {
584 assert_eq!(crate::margin_on(140_000_000, 20), 168_000_000);
585 // Exactly cost plus the margin, rounded up, in whole micros, never under it.
586 for cost in [0_i64, 1, 7, 999, 123_457, 99_999_999] {
587 let exact = (cost * 120 + 99) / 100;
588 assert_eq!(crate::margin_on(cost, 20), exact, "{cost}");
589 assert!(crate::margin_on(cost, 20) * 100 >= cost * 120, "{cost}");
590 }
591 }
592
593 #[test]
594 fn a_sandbox_second_is_its_memory_and_disk_and_the_cpu_it_uses() {
595 // An hour of sandboxes that kept a fifth of a vCPU busy.
596 let usage = ContainerUsage { cpu_seconds: 720.0, memory_byte_seconds: 3600.0 * 8.0 * GIB };
597 let micros =
598 sandbox_second_micros(usage, LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_VCPU_SECOND, LIST_DO_GB_SECOND).unwrap();
599 // 8 x 2.5 + 16 x 0.07 + 0.125 x 12.5 + 0.2 x 20 = 26.6825
600 assert!((micros - 26.6825).abs() < 1e-9, "{micros}");
601 // Memory, disk and the Durable Object, billed for every second.
602 let base = sandbox_base_micros(LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_DO_GB_SECOND);
603 assert!((base - 22.6825).abs() < 1e-9);
604 // An hour of sandboxes that used no CPU still costs their base.
605 let idle = ContainerUsage { cpu_seconds: 0.0, memory_byte_seconds: 3600.0 * 8.0 * GIB };
606 let idle = sandbox_second_micros(idle, LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_VCPU_SECOND, LIST_DO_GB_SECOND).unwrap();
607 assert!((idle - base).abs() < 1e-9);
608 // Too little use to say anything.
609 assert!(sandbox_second_micros(ContainerUsage { cpu_seconds: 1.0, memory_byte_seconds: GIB }, 1.0, 1.0, 1.0, 1.0).is_none());
610 }
611
612 #[test]
613 fn a_run_that_reports_its_cpu_is_priced_on_it() {
614 let base = sandbox_base_micros(LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_DO_GB_SECOND);
615 let vcpu = LIST_VCPU_SECOND * MICROS_PER_DOLLAR as f64;
616 // A 10-minute cargo build that kept half a vCPU busy throughout.
617 let heavy = run_cost(600, 300.0, base, vcpu);
618 assert!((heavy - (600.0 * 22.6825 + 300.0 * 20.0)).abs() < 1e-6);
619 // Ten idle minutes cost the memory, disk and Durable Object that
620 // Cloudflare bills for all of them, and are charged that plus the
621 // margin, never less.
622 let idle = run_cost(600, 0.0, base, vcpu);
623 let provisioned = 600.0 * (8.0 * 2.5 + 16.0 * 0.07 + 0.125 * 12.5);
624 assert!((idle - provisioned).abs() < 1e-6, "{idle}");
625 let charged = crate::credits::with_margin(idle.ceil() as i64, 20);
626 assert!(charged as f64 >= provisioned * 1.2, "{charged}");
627 // The same ten minutes, mostly idle, costs less.
628 let light = run_cost(600, 30.0, base, vcpu);
629 assert!(light < heavy);
630 // The average would have under-priced the heavy one.
631 let average = 600.0 * (base + 0.195 * vcpu);
632 assert!(average < heavy && average > light);
633 assert_eq!(run_cost(0, -1.0, base, vcpu), 0.0);
634 // A larger machine's base: its memory and disk, not its CPU.
635 assert!((base_scale(SANDBOX_GIB, SANDBOX_DISK_GB) - 1.0).abs() < 1e-12);
636 assert!((base_scale(12.0, 20.0) - 1.45).abs() < 0.01, "{}", base_scale(12.0, 20.0));
637 // Each machine in the contracts is costed from its own memory and
638 // disk, and with its CPU unknown, at its vCPUs as busy: at least its
639 // base's share, so an idle job's cost still has the memory and disk
640 // it held.
641 for instance in g1t_contracts::actions::INSTANCE_TYPES {
642 let scale = base_scale(instance.memory_gib, instance.disk_gb);
643 assert!(scale >= 1.0 - 1e-12 && scale <= busy_scale(&instance) + 1e-9, "{}: {scale}", instance.label);
644 }
645 assert!((busy_scale(&STANDARD_INSTANCE) - 1.0).abs() < 1e-12);
646 let four = g1t_contracts::actions::machine_named("4-core").unwrap();
647 assert!((busy_scale(&four) - 1.80).abs() < 0.01, "{}", busy_scale(&four));
648 assert_eq!((STANDARD_INSTANCE.memory_gib, STANDARD_INSTANCE.disk_gb), (SANDBOX_GIB, SANDBOX_DISK_GB));
649 }
650
651 #[test]
652 fn a_job_is_charged_its_minutes_rounded_up_at_its_machines_rate() {
653 let four = g1t_contracts::actions::machine_named("4-core").unwrap();
654 // 61 seconds is 2 minutes; a job that ran is at least 1.
655 assert_eq!(runner_charge(61, &STANDARD_INSTANCE, 2_000), (2, 8_000));
656 assert_eq!(runner_charge(1, &STANDARD_INSTANCE, 30), (1, 4_000));
657 assert_eq!(runner_charge(60, &four, 4_000), (1, 7_000));
658 assert_eq!(runner_charge(0, &STANDARD_INSTANCE, 0), (0, 0));
659 // A full hour, every vCPU busy, at list prices: still over cost.
660 for machine in g1t_contracts::actions::machines() {
661 let busy_second = machine.memory_gib * 2.5 + machine.disk_gb * 0.07 + 0.125 * 12.5 + machine.vcpu * 20.0;
662 let cost = (3_600.0 * busy_second).ceil() as i64;
663 let (minutes, price) = runner_charge(3_600, &machine, cost);
664 assert_eq!((minutes, price), (60, 60 * machine.micros_per_minute), "{}", machine.machine);
665 assert!(price > cost, "{}: {price} {cost}", machine.machine);
666 }
667 // Should a job ever cost more than its minutes at the rate (a dearer
668 // Cloudflare bill), it is charged that cost instead.
669 assert_eq!(runner_charge(60, &STANDARD_INSTANCE, 10_000), (1, 10_000));
670 assert_eq!(minutes_text(1), "1 minute");
671 assert_eq!(minutes_text(12), "12 minutes");
672 }
673
674 #[test]
675 fn a_billed_rate_is_the_median_of_the_charged_days() {
676 let row = |quantity: f64, list_cost: f64| UsageRow {
677 period_start: String::new(),
678 period_end: String::new(),
679 service: "Containers / Container Memory".into(),
680 unit: "Count".into(),
681 quantity,
682 cost: list_cost,
683 list_cost,
684 };
685 let rows = [row(100.0, 0.0), row(100.0, 0.0002), row(100.0, 0.00025), row(100.0, 0.00025)];
686 assert_eq!(billed_rate(&rows.iter().collect::<Vec<_>>()), Some(0.000_002_5));
687 assert_eq!(billed_rate(&[&row(5.0, 0.0)]), None);
688 }
689
690 #[test]
691 fn a_rate_is_the_list_price_not_what_was_billed_past_the_included_amount() {
692 // 126,870 GiB-seconds, of which the 36,870 past the included 90,000
693 // were billed: $0.09 billed, $0.32 at list. The rate is the list's.
694 let row = UsageRow {
695 period_start: String::new(),
696 period_end: String::new(),
697 service: "Containers / Container Memory".into(),
698 unit: "GiB-seconds".into(),
699 quantity: 126_870.0,
700 cost: 0.092_175,
701 list_cost: 0.317_175,
702 };
703 assert!((billed_rate(&[&row]).unwrap() - 0.000_002_5).abs() < 1e-15);
704 // Billed with no list cost says nothing about the price.
705 assert_eq!(billed_rate(&[&UsageRow { list_cost: 0.0, ..row }]), None);
706 }
707
708 #[test]
709 fn usage_rows_are_read_by_their_focus_names() {
710 let row = UsageRow::from_value(&json!({
711 "ServiceFamilyName": "Containers",
712 "ServiceName": "Memory",
713 "PricingUnit": "GiB-seconds",
714 "PricingQuantity": "1200.5",
715 "ContractedCost": 0.003,
716 "ListCost": 0.0030,
717 "ChargePeriodStart": "2026-10-01",
718 }))
719 .unwrap();
720 assert_eq!(row.service, "Containers / Memory");
721 assert_eq!(row.quantity, 1200.5);
722 assert_eq!(row.cost, 0.003);
723 assert_eq!(row.list_cost, 0.003);
724 assert!(UsageRow::from_value(&json!({ "nothing": 1 })).is_none());
725 }
726}