Skip to content
804 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1//! The g1t plan: one monthly price per workspace, never per person, that
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2//! includes $10 of usage. Everything that costs g1t money is metered from
3//! the first unit at cost plus the margin and drawn from that $10 first;
4//! past it, it is charged, up to the workspace's spend limit. There are no
5//! per-feature quotas: no count of apps, build minutes, requests or
6//! domains ever stops a workspace on the plan. Only its spend limit does
7//! (and g1t's protections against abuse). Projects, previews and
8//! repositories cost g1t next to nothing and are not metered. None of it is
9//! free, whatever `FREE_WHILE_BUILDING` says.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look10//!
11//! Deployments were once a plan of their own. They come with the g1t plan
12//! now: `has_feature(deployments)` answers whether the workspace has the
13//! plan, and a Deployments subscription from before keeps working until
14//! its period ends. Billing sets each one to end then, once
15//! (`retire_deployments_plans`), so no one pays for both.
Paid features: a workspace turns on Deployments with a monthly plan16
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas17use g1t_contracts::billing::deployment_costs as costs;
Paid features: a workspace turns on Deployments with a monthly plan18use g1t_contracts::billing::*;
19use g1t_contracts::time::rfc3339;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put20use g1t_contracts::{FailureCode, Outcome, Role};
Paid features: a workspace turns on Deployments with a monthly plan21use g1t_kit::now_ms;
22use serde::Deserialize;
23use worker::Result;
24
Project dependencies: addresses, preview stacks, Affects, and agents who know25use crate::stripe::{StripeSubscription, is_missing};
Paid features: a workspace turns on Deployments with a monthly plan26use crate::{Billing, Touched, members_only, optional};
27
28#[derive(Deserialize)]
29struct SubscriptionRow {
30 feature: String,
31 subscription_id: String,
32 status: String,
33 period_end: Option<String>,
34 started_by: String,
35 started_at: String,
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index36 updated_at: String,
37}
38
39/// How long a plan's row is believed after it was last written, once its
40/// period is over, before the processor is asked again.
41const REFRESH_MS: u64 = 60 * 60 * 1000;
42
43/// Whether to ask the processor about a plan again: its period is over (or
44/// unknown) and it is not canceled, and it was not written in the last hour.
45/// Without the hour a plan the processor still shows as ended would be
46/// asked about on every page.
47fn needs_refresh(status: &str, period_end: Option<&str>, updated_at: &str, now_ms: u64) -> bool {
48 let now = rfc3339(now_ms);
49 let over = period_end.is_none_or(|end| end <= now.as_str()) && status != "canceled";
50 over && updated_at <= rfc3339(now_ms.saturating_sub(REFRESH_MS)).as_str()
Paid features: a workspace turns on Deployments with a monthly plan51}
52
53#[derive(Deserialize)]
54struct PlanCheckoutRow {
55 workspace: String,
56 created_by: String,
57 feature: String,
58}
59
60fn status_from(text: &str) -> SubscriptionStatus {
61 match text {
62 "active" => SubscriptionStatus::Active,
63 "canceling" => SubscriptionStatus::Canceling,
64 "past_due" => SubscriptionStatus::PastDue,
65 _ => SubscriptionStatus::Canceled,
66 }
67}
68
69fn status_text(status: SubscriptionStatus) -> &'static str {
70 match status {
71 SubscriptionStatus::Active => "active",
72 SubscriptionStatus::Canceling => "canceling",
73 SubscriptionStatus::PastDue => "past_due",
74 SubscriptionStatus::Canceled => "canceled",
75 }
76}
77
78/// What the processor's state for a plan means here.
79fn status_of(subscription: &StripeSubscription) -> SubscriptionStatus {
80 match subscription.status.as_str() {
81 "active" | "trialing" if subscription.cancel_at_period_end => SubscriptionStatus::Canceling,
82 "active" | "trialing" => SubscriptionStatus::Active,
83 "past_due" | "unpaid" | "incomplete" | "paused" => SubscriptionStatus::PastDue,
84 _ => SubscriptionStatus::Canceled,
85 }
86}
87
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put88/// `1 GB`, `50 GB`, or `500 MB`, as storage is priced (powers of ten).
89pub(crate) fn bytes(bytes: i64) -> String {
90 if bytes >= 1_000_000_000 && bytes % 1_000_000_000 == 0 {
91 format!("{} GB", bytes / 1_000_000_000)
92 } else if bytes >= 1_000_000_000 {
93 format!("{:.1} GB", bytes as f64 / 1e9)
94 } else {
95 format!("{} MB", bytes / 1_000_000)
96 }
97}
98
Deployments: a preview for every pull request, production on g1t.page99/// Dollars to the cent, or finer for prices under a cent, so that a
100/// build minute's $0.0015 does not read as nothing.
Usage limits: unpaid usage can only go so far101pub(crate) fn dollars(micros: i64) -> String {
Deployments: a preview for every pull request, production on g1t.page102 let text = format!("{:.4}", micros as f64 / MICROS_PER_DOLLAR as f64);
103 let (whole, fraction) = text.split_once('.').unwrap_or((&text, ""));
104 let fraction = fraction.trim_end_matches('0');
105 format!("${whole}.{fraction:0<2}")
Paid features: a workspace turns on Deployments with a monthly plan106}
107
Money in billing's messages reads to the cent, and the deploy reads migrations again after a failure108/// An amount of money to the cent, as balances and amounts owed read:
109/// `$3.99`, never `$3.987`. Prices use [`dollars`].
110pub(crate) fn cents(micros: i64) -> String {
111 format!("${:.2}", micros as f64 / MICROS_PER_DOLLAR as f64)
112}
113
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily114/// `units` at `each` micros a unit, as the pricing page writes it: a
115/// build second's price times 60 is the build minute both quote.
116pub(crate) fn per_units(each: f64, units: f64) -> String {
117 dollars((each * units).round() as i64)
118}
119
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar120/// The price book's meter for the Security and quality activation.
121pub(crate) const SECURITY_METER: &str = "security_activation";
122/// Its price when the price book cannot be read: $10 a month.
123const SECURITY_FALLBACK_MICROS: f64 = 10_000_000.0;
124
125/// The Security and quality activation at the price book's price.
126pub(crate) fn security_plan_at(book: &std::collections::BTreeMap<&str, f64>) -> Plan {
127 let micros = book.get(SECURITY_METER).copied().unwrap_or(SECURITY_FALLBACK_MICROS);
128 Plan {
129 feature: Feature::Security,
130 title: Feature::Security.title().to_owned(),
131 monthly_cents: (micros / 10_000.0).round().max(0.0) as u32,
132 includes: vec![
133 "For every private repository in the workspace; public repositories have it free".to_owned(),
134 "Custom secret patterns, validity checks with issuers, and delegated push protection bypass".to_owned(),
135 "Code scanning from SARIF, with pull request checks that can block merges".to_owned(),
136 "Dependency review on pull requests, and the workspace's security overview".to_owned(),
137 "Everyone in the workspace at one price, never per person".to_owned(),
138 ],
139 overage: "Fixes by g1t's agent are charged as agent usage, like any other agent run. Secret scanning, push protection, vulnerability alerts and security updates stay free.".to_owned(),
140 }
141}
142
Paid features: a workspace turns on Deployments with a monthly plan143impl SubscriptionRow {
144 fn subscription(&self) -> Option<Subscription> {
145 Some(Subscription {
146 feature: Feature::parse(&self.feature)?,
147 status: status_from(&self.status),
148 period_end: self.period_end.clone(),
149 started_by: self.started_by.clone(),
150 started_at: self.started_at.clone(),
151 })
152 }
153}
154
155impl Billing {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily156 /// What the g1t plan costs and includes, as it is sold now, at the
157 /// price book's prices (the same figures as the pricing page's table).
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar158 pub(crate) async fn plan(&self, feature: Feature) -> Result<Plan> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily159 let mut book = std::collections::BTreeMap::new();
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar160 if feature == Feature::Security {
161 if let Some((_, price)) = self.price(SECURITY_METER).await? {
162 book.insert(SECURITY_METER, price);
163 }
164 return Ok(security_plan_at(&book));
165 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily166 for meter in ["build_second", "app_requests", "app_cpu", "custom_domain_month", "private_storage", "git_operations"] {
167 if let Some((_, price)) = self.price(meter).await? {
168 book.insert(meter, price);
169 }
170 }
171 Ok(self.plan_at(&book))
172 }
173
174 /// The plan at the given prices per unit (micros, after the markup);
175 /// the published costs plus the margin for any not given.
176 pub(crate) fn plan_at(&self, book: &std::collections::BTreeMap<&str, f64>) -> Plan {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look177 let p = &self.plans;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily178 let price_of = |meter: &str, cost: i64, units: f64| {
179 per_units(book.get(meter).copied().unwrap_or_else(|| Price::price_for(cost as f64, self.margin_percent)), units)
180 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look181 Plan {
182 feature: Feature::Plan,
183 title: Feature::Plan.title().to_owned(),
184 monthly_cents: p.plan_monthly_cents,
185 includes: vec![
186 format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas187 "{} of usage each month at cost plus {}%, used first",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look188 dollars(p.plan_included_micros),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put189 self.margin_percent
190 ),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas191 "Everyone in the workspace at one price, never per person".to_owned(),
192 "Unlimited projects, previews and repositories".to_owned(),
193 "Agents, checks, workflows, the merge queue, deployments and semantic search".to_owned(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look194 format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas195 "Usage past {} is charged at cost plus {}%, up to your spend limit",
196 dollars(p.plan_included_micros),
197 self.margin_percent
Paid features: a workspace turns on Deployments with a monthly plan198 ),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look199 ],
200 overage: format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas201 "Everything is metered from the first unit at what it costs g1t plus {}%: sandbox time and deploy builds by the second ({} a build minute), models at what the provider charged, {} per million app requests, {} per million CPU milliseconds, {} a month per custom domain, private storage past the free {} at {} per GB-month, and git operations past the free {} a month at {} per 1,000. Unused included usage does not roll over.",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look202 self.margin_percent,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily203 price_of("build_second", costs::MICROS_PER_BUILD_SECOND, 60.0),
204 price_of("app_requests", costs::MICROS_PER_MILLION_REQUESTS, 1.0),
205 price_of("app_cpu", costs::MICROS_PER_MILLION_CPU_MS, 1.0),
206 price_of("custom_domain_month", costs::MICROS_PER_DOMAIN_MONTH, 1.0),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas207 bytes(p.free_storage_bytes),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily208 price_of("private_storage", crate::storage::STORAGE_MICROS_PER_GB_MONTH, 1.0),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas209 thousands(p.git_included),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily210 price_of("git_operations", crate::storage::GIT_MICROS_PER_THOUSAND, 1.0),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look211 ),
Paid features: a workspace turns on Deployments with a monthly plan212 }
213 }
214
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look215 /// When the workspace's plan started, and when the period paid for
216 /// ends: its first billing cycle is the first month.
217 pub(crate) async fn plan_cycle(&self, workspace: &str) -> Result<Option<(String, Option<String>)>> {
218 let row = match self.current(workspace, Feature::Plan).await? {
219 Some(row) => Some(row),
220 None => self.current(workspace, Feature::Deployments).await?,
221 };
222 Ok(row
223 .filter(|row| status_from(&row.status).on())
224 .map(|row| (row.started_at, row.period_end)))
225 }
226
Paid features: a workspace turns on Deployments with a monthly plan227 async fn subscription_row(&self, workspace: &str, feature: Feature) -> Result<Option<SubscriptionRow>> {
228 self.db
229 .prepare(
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index230 "SELECT feature, subscription_id, status, period_end, started_by, started_at, updated_at
Paid features: a workspace turns on Deployments with a monthly plan231 FROM subscriptions WHERE workspace = ? AND feature = ?",
232 )
233 .bind(&[workspace.into(), feature.as_str().into()])?
234 .first::<SubscriptionRow>(None)
235 .await
236 }
237
238 /// Writes down what the processor says about a plan.
Stripe webhooks, enterprise invoices, and sudo for both239 pub(crate) async fn record(
Paid features: a workspace turns on Deployments with a monthly plan240 &self,
241 workspace: &str,
242 feature: Feature,
243 subscription: &StripeSubscription,
244 started_by: &str,
245 ) -> Result<()> {
246 let now = rfc3339(now_ms());
247 let period_end = subscription.period_end().map(|seconds| rfc3339(seconds.max(0) as u64 * 1000));
248 self.db
249 .prepare(
250 "INSERT INTO subscriptions
251 (workspace, feature, subscription_id, status, period_end, started_by, started_at, updated_at)
252 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)
253 ON CONFLICT (workspace, feature) DO UPDATE SET
254 subscription_id = ?3, status = ?4, period_end = ?5, updated_at = ?7,
255 started_by = CASE WHEN subscription_id = ?3 THEN started_by ELSE ?6 END,
256 started_at = CASE WHEN subscription_id = ?3 THEN started_at ELSE ?7 END",
257 )
258 .bind(&[
259 workspace.into(),
260 feature.as_str().into(),
261 subscription.id.as_str().into(),
262 status_text(status_of(subscription)).into(),
263 optional(period_end.as_deref()),
264 started_by.into(),
265 now.as_str().into(),
266 ])?
267 .run()
268 .await?;
269 Ok(())
270 }
271
272 /// A workspace's plan for a feature, asking the processor again once
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index273 /// the period it last knew of is over, at most once an hour.
Paid features: a workspace turns on Deployments with a monthly plan274 async fn current(&self, workspace: &str, feature: Feature) -> Result<Option<SubscriptionRow>> {
275 let Some(row) = self.subscription_row(workspace, feature).await? else {
276 return Ok(None);
277 };
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index278 let stale = needs_refresh(&row.status, row.period_end.as_deref(), &row.updated_at, now_ms());
Paid features: a workspace turns on Deployments with a monthly plan279 if let (true, Some(stripe)) = (stale, &self.stripe) {
Project dependencies: addresses, preview stacks, Affects, and agents who know280 match stripe.subscription(&row.subscription_id).await {
281 Ok(subscription) => self.record(workspace, feature, &subscription, &row.started_by).await?,
282 // A plan from another Stripe account: it has ended here.
283 Err(error) if is_missing(&error) => {
284 self.db
285 .prepare("UPDATE subscriptions SET status = 'canceled', updated_at = ? WHERE workspace = ? AND feature = ?")
286 .bind(&[rfc3339(now_ms()).into(), workspace.into(), feature.as_str().into()])?
287 .run()
288 .await?;
289 }
290 Err(error) => return Err(error),
291 }
Paid features: a workspace turns on Deployments with a monthly plan292 return self.subscription_row(workspace, feature).await;
293 }
294 Ok(Some(row))
295 }
296
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look297 /// The plan as a workspace sees it. A Deployments subscription from
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar298 /// before the plan shows as the plan until its period ends. The
299 /// Security and quality activation is its own subscription.
300 async fn state(&self, workspace: &str, feature: Feature) -> Result<FeatureState> {
301 if feature == Feature::Security {
302 let subscription = self.current(workspace, Feature::Security).await?.and_then(|row| row.subscription());
303 let included = self.security_included(workspace).await?;
304 return Ok(FeatureState {
305 plan: self.plan(Feature::Security).await?,
306 on: included || self.stripe.is_none() || subscription.as_ref().is_some_and(|s| s.status.on()),
307 subscription,
308 included,
309 });
310 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look311 let subscription = match self.current(workspace, Feature::Plan).await?.and_then(|row| row.subscription()) {
312 Some(plan) if plan.status.on() => Some(plan),
313 plan => self
314 .current(workspace, Feature::Deployments)
315 .await?
316 .and_then(|row| row.subscription())
317 .filter(|legacy| legacy.status.on())
318 .or(plan),
319 };
320 let included = self.included(workspace).await?;
Paid features: a workspace turns on Deployments with a monthly plan321 Ok(FeatureState {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily322 plan: self.plan(Feature::Plan).await?,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put323 on: included || self.stripe.is_none() || subscription.as_ref().is_some_and(|s| s.status.on()),
Paid features: a workspace turns on Deployments with a monthly plan324 subscription,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put325 included,
Paid features: a workspace turns on Deployments with a monthly plan326 })
327 }
328
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look329 /// Whether the plan is on without its price: comped terms, an
330 /// enterprise's workspaces, or given by g1t staff.
331 async fn included(&self, workspace: &str) -> Result<bool> {
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put332 let account = self.account_of(workspace).await?;
333 Ok(account.terms.kind == g1t_contracts::billing::TermsKind::Comped
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look334 || account.kind == g1t_contracts::billing::AccountKind::Enterprise
335 || account.allowances.plan)
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put336 }
337
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar338 /// Whether the Security and quality activation is on without its
339 /// price: comped terms, or an enterprise's workspace. Giving the plan
340 /// as an allowance does not give the activation.
341 async fn security_included(&self, workspace: &str) -> Result<bool> {
342 let account = self.account_of(workspace).await?;
343 Ok(account.terms.kind == g1t_contracts::billing::TermsKind::Comped
344 || account.kind == g1t_contracts::billing::AccountKind::Enterprise)
345 }
346
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look347 /// Sets every Deployments subscription from before the plan to end
348 /// with its period, once, so no one pays for it and the plan both.
349 /// Until then it counts as the plan.
350 pub(crate) async fn retire_deployments_plans(&self) -> Result<()> {
351 let Some(stripe) = &self.stripe else { return Ok(()) };
352 #[derive(Deserialize)]
353 struct Legacy {
354 workspace: String,
355 subscription_id: String,
356 started_by: String,
357 period_end: Option<String>,
358 }
359 let legacy = self
360 .db
361 .prepare(
362 "SELECT workspace, subscription_id, started_by, period_end FROM subscriptions
363 WHERE feature = 'deployments' AND status = 'active' LIMIT 20",
364 )
365 .all()
366 .await?
367 .results::<Legacy>()?;
368 for plan in legacy {
369 match stripe.cancel_at_period_end(&plan.subscription_id, true).await {
370 Ok(subscription) => {
371 self.record(&plan.workspace, Feature::Deployments, &subscription, &plan.started_by).await?;
372 let account = self.account_of(&plan.workspace).await?;
373 self.audit(
374 &account.id,
375 "migration",
376 &format!(
377 "{}: the Deployments plan ends {} and is not renewed; deployments come with the g1t plan now",
378 plan.workspace,
379 plan.period_end.as_deref().map_or("at the end of its period", |end| &end[..10])
380 ),
381 "billing",
382 )
383 .await?;
384 }
385 Err(error) if is_missing(&error) => {
386 self.db
387 .prepare("UPDATE subscriptions SET status = 'canceled', updated_at = ? WHERE workspace = ? AND feature = 'deployments'")
388 .bind(&[rfc3339(now_ms()).into(), plan.workspace.as_str().into()])?
389 .run()
390 .await?;
391 }
392 Err(error) => worker::console_error!("could not end {}'s Deployments plan: {error}", plan.workspace),
393 }
394 }
395 Ok(())
396 }
397
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put398 /// Whether the workspace's plan for the feature is paid up.
399 pub(crate) async fn plan_on(&self, workspace: &str, feature: Feature) -> Result<bool> {
400 Ok(self
401 .current(workspace, feature)
402 .await?
403 .and_then(|row| row.subscription())
404 .is_some_and(|s| s.status.on()))
405 }
406
Paid features: a workspace turns on Deployments with a monthly plan407 pub(crate) async fn features(&self, a: FeaturesArgs) -> Result<Outcome<Vec<FeatureState>>> {
408 let workspace = a.workspace.to_lowercase();
409 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
410 return Ok(members_only());
411 }
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar412 let plan = self.state(&workspace, Feature::Plan).await?;
413 let security = self.state(&workspace, Feature::Security).await?;
414 Ok(Outcome::Ok(vec![plan, security]))
Paid features: a workspace turns on Deployments with a monthly plan415 }
416
417 pub(crate) async fn subscribe(&self, a: SubscribeArgs) -> Result<Outcome<Checkout>> {
418 let workspace = a.workspace.to_lowercase();
419 if a.actor.role_in(&workspace) != Some(Role::Owner) {
420 return Ok(Outcome::fail(
421 FailureCode::Forbidden,
422 "Only an owner can turn on a paid feature.",
423 ));
424 }
425 let Some(stripe) = &self.stripe else {
426 return Ok(Outcome::fail(
427 FailureCode::Conflict,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look428 "Payments are not set up on this g1t, so the plan is already on.",
Paid features: a workspace turns on Deployments with a monthly plan429 ));
430 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look431 // Deployments come with the plan: asking for them starts the plan.
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar432 // The Security and quality activation is its own subscription.
433 let feature = if a.feature == Feature::Security { Feature::Security } else { Feature::Plan };
434 let name = if feature == Feature::Security { "The Security and quality activation" } else { "The g1t plan" };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look435 let state = self.state(&workspace, feature).await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put436 if state.included {
437 return Ok(Outcome::fail(
438 FailureCode::Conflict,
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar439 format!("{name} is included for {workspace} already, at no charge."),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put440 ));
441 }
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar442 if self.plan_on(&workspace, feature).await? {
443 return Ok(Outcome::fail(FailureCode::Conflict, format!("{name} is already on for {workspace}.")));
Paid features: a workspace turns on Deployments with a monthly plan444 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily445 let plan = self.plan(feature).await?;
Paid features: a workspace turns on Deployments with a monthly plan446 let customer = self.row(&workspace).await?.and_then(|row| row.customer_id);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look447 // The card from the card check: the plan starts on it at once, with
448 // no second page. A card that needs the bank's approval again goes
449 // through Stripe's page instead.
450 if let (Some(customer), Some(method)) = (customer.as_deref(), self.checked_card(&workspace).await?) {
451 match stripe
452 .subscribe_with_card(&workspace, feature.as_str(), &plan.title, plan.monthly_cents, customer, &method)
453 .await
454 {
455 Ok(subscription) if matches!(subscription.status.as_str(), "active" | "trialing") => {
456 self.record(&workspace, feature, &subscription, &a.actor.username).await?;
457 let account = self.account_of(&workspace).await?;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar458 self.audit(
459 &account.id,
460 "plan",
461 &format!("{workspace}: {} started on the checked card", name.to_lowercase()),
462 &a.actor.username,
463 )
464 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look465 let separator = if a.return_url.contains('?') { '&' } else { '?' };
466 return Ok(Outcome::Ok(Checkout { url: format!("{}{separator}plan=started", a.return_url) }));
467 }
468 Ok(subscription) => {
469 // Incomplete: let it lapse, and use the page.
470 let _ = stripe.cancel_now(&subscription.id).await;
471 }
472 Err(error) => worker::console_log!("{workspace}: the plan could not start on the checked card: {error}"),
473 }
474 }
Project dependencies: addresses, preview stacks, Affects, and agents who know475 let start = |customer: Option<String>| {
476 let plan = &plan;
477 let workspace = &workspace;
478 let return_url = &a.return_url;
479 async move {
480 stripe
481 .start_subscription(
482 workspace,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look483 feature.as_str(),
Project dependencies: addresses, preview stacks, Affects, and agents who know484 &plan.title,
485 plan.monthly_cents,
486 customer.as_deref(),
487 return_url,
488 )
489 .await
490 }
491 };
492 let session = match start(customer.clone()).await {
493 Ok(session) => session,
494 // A customer saved under another Stripe account: start afresh.
495 Err(error) if customer.is_some() && is_missing(&error) => {
496 self.forget_customer(&workspace).await?;
497 start(None).await?
498 }
499 Err(error) => return Err(error),
500 };
Paid features: a workspace turns on Deployments with a monthly plan501 let Some(url) = session.url else {
502 return Err(worker::Error::RustError(
503 "the card processor returned no payment page".into(),
504 ));
505 };
506 self.db
507 .prepare(
508 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at, feature)
509 VALUES (?, ?, ?, ?, ?, ?)",
510 )
511 .bind(&[
512 session.id.into(),
513 workspace.into(),
514 plan.monthly_cents.into(),
515 a.actor.username.into(),
516 rfc3339(now_ms()).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look517 feature.as_str().into(),
Paid features: a workspace turns on Deployments with a monthly plan518 ])?
519 .run()
520 .await?;
521 Ok(Outcome::Ok(Checkout { url }))
522 }
523
524 pub(crate) async fn confirm_subscription(
525 &self,
526 a: ConfirmSubscriptionArgs,
527 ) -> Result<Outcome<FeatureState>> {
528 let workspace = a.workspace.to_lowercase();
529 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
530 return Ok(members_only());
531 }
532 let checkout = self
533 .db
534 .prepare(
535 "SELECT workspace, created_by, feature FROM checkouts
536 WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NOT NULL",
537 )
538 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
539 .first::<PlanCheckoutRow>(None)
540 .await?;
541 let (Some(stripe), Some(checkout)) = (&self.stripe, checkout) else {
542 // Unknown, someone else's, or already done: show where it stands.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look543 return Ok(Outcome::Ok(self.state(&workspace, Feature::Plan).await?));
Paid features: a workspace turns on Deployments with a monthly plan544 };
545 let Some(feature) = Feature::parse(&checkout.feature) else {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look546 return Ok(Outcome::fail(FailureCode::NotFound, "No such plan."));
Paid features: a workspace turns on Deployments with a monthly plan547 };
548 let session = stripe.session(&a.session).await?;
549 if let (Some(subscription_id), true) = (&session.subscription, session.payment_status == "paid") {
550 let claimed = self
551 .db
552 .prepare("UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open' RETURNING id")
553 .bind(&[a.session.as_str().into()])?
554 .first::<Touched>(None)
555 .await?;
556 if claimed.is_some() {
557 let subscription = stripe.subscription(subscription_id).await?;
558 self.record(&checkout.workspace, feature, &subscription, &checkout.created_by)
559 .await?;
560 // Keep the card's customer, so later payments need no retyping.
561 self.db
562 .prepare(
563 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
564 VALUES (?1, 0, ?2, ?3)
565 ON CONFLICT (workspace) DO UPDATE SET customer_id = COALESCE(customer_id, ?2)",
566 )
567 .bind(&[
568 checkout.workspace.as_str().into(),
569 optional(session.customer.as_deref()),
570 rfc3339(now_ms()).into(),
571 ])?
572 .run()
573 .await?;
574 }
575 }
576 Ok(Outcome::Ok(self.state(&workspace, feature).await?))
577 }
578
579 pub(crate) async fn cancel_subscription(
580 &self,
581 a: CancelSubscriptionArgs,
582 ) -> Result<Outcome<FeatureState>> {
583 let workspace = a.workspace.to_lowercase();
584 if a.actor.role_in(&workspace) != Some(Role::Owner) {
585 return Ok(Outcome::fail(
586 FailureCode::Forbidden,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look587 "Only an owner can change the workspace's plan.",
Paid features: a workspace turns on Deployments with a monthly plan588 ));
589 }
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar590 // The activation; or the plan, or a Deployments subscription from
591 // before it.
592 let row = if a.feature == Feature::Security {
593 self.current(&workspace, Feature::Security).await?.map(|row| (Feature::Security, row))
594 } else {
595 match self.current(&workspace, Feature::Plan).await? {
596 Some(row) if status_from(&row.status) != SubscriptionStatus::Canceled => Some((Feature::Plan, row)),
597 _ => self.current(&workspace, Feature::Deployments).await?.map(|row| (Feature::Deployments, row)),
598 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look599 };
600 let (Some(stripe), Some((feature, row))) = (&self.stripe, row) else {
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar601 let name = if a.feature == Feature::Security { "The Security and quality activation" } else { "The g1t plan" };
602 return Ok(Outcome::fail(FailureCode::NotFound, format!("{name} is not on for {workspace}.")));
Paid features: a workspace turns on Deployments with a monthly plan603 };
604 let subscription = stripe
605 .cancel_at_period_end(&row.subscription_id, !a.resume)
606 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look607 self.record(&workspace, feature, &subscription, &row.started_by)
Paid features: a workspace turns on Deployments with a monthly plan608 .await?;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar609 let shown = if feature == Feature::Security { Feature::Security } else { Feature::Plan };
610 Ok(Outcome::Ok(self.state(&workspace, shown).await?))
Paid features: a workspace turns on Deployments with a monthly plan611 }
612
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar613 /// Whether the workspace has the plan, which deployments come with, or
614 /// the Security and quality activation.
Paid features: a workspace turns on Deployments with a monthly plan615 pub(crate) async fn has_feature(&self, a: HasFeatureArgs) -> Result<Outcome<bool>> {
616 let workspace = a.workspace.to_lowercase();
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar617 if a.feature == Feature::Security {
618 let state = self.state(&workspace, Feature::Security).await?;
619 if state.on {
620 return Ok(Outcome::Ok(true));
621 }
622 return Ok(Outcome::fail(
623 FailureCode::PaymentRequired,
624 format!(
625 "This needs the Security and quality activation ({} a month for the workspace), and {workspace} does not have it. An owner can turn it on at /{workspace}/-/billing.",
626 dollars(i64::from(state.plan.monthly_cents) * 10_000)
627 ),
628 ));
629 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look630 if self.has_plan(&workspace).await? {
Paid features: a workspace turns on Deployments with a monthly plan631 return Ok(Outcome::Ok(true));
632 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look633 let what = match a.feature {
634 Feature::Deployments => "Deployments come with the g1t plan",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar635 Feature::Plan | Feature::Security => "This needs the g1t plan",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look636 };
Paid features: a workspace turns on Deployments with a monthly plan637 Ok(Outcome::fail(
638 FailureCode::PaymentRequired,
639 format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look640 "{what} ($20 a month for the workspace, with $10 of usage included), and {workspace} does not have it. An owner can start it at /{workspace}/-/billing."
Paid features: a workspace turns on Deployments with a monthly plan641 ),
642 ))
643 }
644
645 pub(crate) async fn charge_feature(&self, a: ChargeFeatureArgs) -> Result<Outcome<bool>> {
646 if self.stripe.is_none() || a.cost_micros <= 0 {
647 return Ok(Outcome::Ok(false));
648 }
649 let workspace = a.workspace.to_lowercase();
650 let seen = self
651 .db
652 .prepare("SELECT id FROM ledger WHERE reference = ?")
653 .bind(&[a.reference.as_str().into()])?
654 .first::<Touched>(None)
655 .await?;
656 if seen.is_some() {
657 return Ok(Outcome::Ok(false));
658 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put659 let timestamp = rfc3339(now_ms());
660 let month = crate::credits::month_of(&timestamp);
661 let mut description = a.description.clone();
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas662 // A build: every second is metered, at the price book's build
663 // second, which the keeper keeps at what Cloudflare bills, rather
664 // than at what the caller worked out. The month's build time is
665 // tallied for the Billing page.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put666 let cost_micros = match a.build_seconds.filter(|s| *s > 0 && a.feature == Feature::Deployments) {
667 Some(seconds) => {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas668 self.tally("build_seconds", &workspace, &month, seconds.into()).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look669 let measured = self.price("build_second").await?.map(|(cost, _)| (f64::from(seconds) * cost).ceil() as i64);
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas670 measured.unwrap_or(a.cost_micros)
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put671 }
672 None => a.cost_micros,
673 };
674 let cost = cost_micros as f64 / MICROS_PER_DOLLAR as f64;
Billing accounts, terms and enterprises; g1t is no longer free675 // Never free: the margin applies whatever FREE_WHILE_BUILDING says,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look676 // and only the account's terms change it. The plan's included usage
677 // pays what it can; the trial and the open-source pool never pay for
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put678 // deployments.
Merge branch 'worktree-agent-a633ac0f7f66d419d'679 let (charge, discount) = self.terms_of(&workspace).await?.discounted(crate::charge_micros(cost, self.margin_percent));
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put680 let drawn = self.draw(&workspace, charge, &month, &crate::credits::Eligible::default()).await?;
681 description.push_str(&drawn.note());
682 self.post_usage(crate::storage::UsageLine {
683 workspace: &workspace,
684 charged: charge - drawn.total(),
685 description: &description,
686 repo: a.repo.as_deref(),
687 task: a.feature.as_str(),
688 cost: cost_micros,
689 reference: &a.reference,
690 created_at: &timestamp,
691 drawn,
692 })
693 .await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'694 self.record_discount(&a.reference, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays695 self.count_spend(&workspace, cost_micros, charge - drawn.total(), &drawn).await;
Paid features: a workspace turns on Deployments with a monthly plan696 Ok(Outcome::Ok(true))
697 }
698}
Deployments: a preview for every pull request, production on g1t.page699
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas700/// `50,000`: a count as the plan reads it.
701pub(crate) fn thousands(n: u64) -> String {
702 let digits = n.to_string();
703 let mut out = String::new();
704 for (i, c) in digits.chars().enumerate() {
705 if i > 0 && (digits.len() - i).is_multiple_of(3) {
706 out.push(',');
707 }
708 out.push(c);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put709 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas710 out
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put711}
712
Deployments: a preview for every pull request, production on g1t.page713#[cfg(test)]
714mod tests {
715 use super::*;
716
717 #[test]
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index718 fn an_ended_plan_is_asked_about_at_most_once_an_hour() {
719 let now = 1_791_000_000_000;
720 let at = |ago_ms: u64| rfc3339(now - ago_ms);
721 let ended = at(24 * 60 * 60 * 1000);
722 // Ended, and last written a day ago: ask.
723 assert!(needs_refresh("active", Some(&ended), &ended, now));
724 // Ended, but written ten minutes ago: believe the row.
725 assert!(!needs_refresh("active", Some(&ended), &at(10 * 60 * 1000), now));
726 // An hour on, ask again.
727 assert!(needs_refresh("active", Some(&ended), &at(REFRESH_MS), now));
728 // No period known is the same as ended.
729 assert!(needs_refresh("past_due", None, &ended, now));
730 // A period still running, or a canceled plan, is never asked about.
731 assert!(!needs_refresh("active", Some(&rfc3339(now + 1000)), &ended, now));
732 assert!(!needs_refresh("canceled", Some(&ended), &ended, now));
733 }
734
735 #[test]
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily736 fn the_plan_text_quotes_a_build_minute_as_the_table_does() {
737 // The price book's build second (16.44 millionths at cost, plus
738 // 20%) is 19.73 millionths: a minute is 1,184 millionths, $0.0012,
739 // as the pricing page's table says. The old fixed cost (15) gave
740 // $0.0011.
741 let each = Price::price_for(16.439_893_610_418_67, 20);
742 assert_eq!(per_units(each, 60.0), "$0.0012");
743 assert_eq!(per_units(Price::price_for(15.0, 20), 60.0), "$0.0011");
744 assert_eq!(per_units(Price::price_for(150_000.0, 20), 1.0), "$0.18");
745 }
746
747 #[test]
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas748 fn every_build_second_is_metered_at_cost_plus_the_margin() {
749 // A 5-minute build at 15 millionths a second costs g1t 4,500, and
750 // is charged at cost plus 20%, from the first second: there are no
751 // included build minutes, only the plan's included usage.
752 let cost = 300 * costs::MICROS_PER_BUILD_SECOND;
753 assert_eq!(cost, 4_500);
754 assert_eq!(crate::credits::with_margin(cost, 20), 5_400);
755 }
756
757 #[test]
758 fn counts_read_with_thousands_separators() {
759 assert_eq!(thousands(0), "0");
760 assert_eq!(thousands(999), "999");
761 assert_eq!(thousands(50_000), "50,000");
762 assert_eq!(thousands(1_234_567), "1,234,567");
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put763 }
764
765 #[test]
766 fn storage_reads_in_gigabytes() {
767 assert_eq!(bytes(1_000_000_000), "1 GB");
768 assert_eq!(bytes(50_000_000_000), "50 GB");
769 assert_eq!(bytes(1_500_000_000), "1.5 GB");
770 assert_eq!(bytes(500_000_000), "500 MB");
771 }
772
773 #[test]
Money in billing's messages reads to the cent, and the deploy reads migrations again after a failure774 fn amounts_of_money_read_to_the_cent() {
775 assert_eq!(cents(3_986_990), "$3.99");
776 assert_eq!(cents(5_000_000), "$5.00");
777 assert_eq!(cents(4_000), "$0.00");
778 }
779
780 #[test]
Deployments: a preview for every pull request, production on g1t.page781 fn prices_under_a_cent_keep_their_digits() {
782 assert_eq!(dollars(1512), "$0.0015");
783 assert_eq!(dollars(24_000), "$0.024");
784 assert_eq!(dollars(360_000), "$0.36");
785 assert_eq!(dollars(5_000_000), "$5.00");
786 }
787}
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar788
789#[cfg(test)]
790mod security_activation {
791 use super::*;
792
793 #[test]
794 fn the_activation_is_priced_from_the_price_book() {
795 let book = std::collections::BTreeMap::from([(SECURITY_METER, 12_000_000.0)]);
796 let plan = security_plan_at(&book);
797 assert_eq!((plan.feature, plan.monthly_cents), (Feature::Security, 1200));
798 assert_eq!(plan.title, "Security and quality");
799 // The price book unreadable: $10, as the migration seeds it.
800 assert_eq!(security_plan_at(&std::collections::BTreeMap::new()).monthly_cents, 1000);
801 assert!(plan.includes.iter().any(|line| line.contains("public repositories have it free")));
802 assert!(plan.overage.contains("agent usage"));
803 }
804}

This file's history is long; its oldest lines are credited to the oldest commit read.