g1t/services/billing/src/features.rs

694 lines30,934 bytesCodeBlame

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
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily108/// `units` at `each` micros a unit, as the pricing page writes it: a
109/// build second's price times 60 is the build minute both quote.
110pub(crate) fn per_units(each: f64, units: f64) -> String {
111 dollars((each * units).round() as i64)
112}
113
Paid features: a workspace turns on Deployments with a monthly plan114impl SubscriptionRow {
115 fn subscription(&self) -> Option<Subscription> {
116 Some(Subscription {
117 feature: Feature::parse(&self.feature)?,
118 status: status_from(&self.status),
119 period_end: self.period_end.clone(),
120 started_by: self.started_by.clone(),
121 started_at: self.started_at.clone(),
122 })
123 }
124}
125
126impl Billing {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily127 /// What the g1t plan costs and includes, as it is sold now, at the
128 /// price book's prices (the same figures as the pricing page's table).
129 pub(crate) async fn plan(&self, _feature: Feature) -> Result<Plan> {
130 let mut book = std::collections::BTreeMap::new();
131 for meter in ["build_second", "app_requests", "app_cpu", "custom_domain_month", "private_storage", "git_operations"] {
132 if let Some((_, price)) = self.price(meter).await? {
133 book.insert(meter, price);
134 }
135 }
136 Ok(self.plan_at(&book))
137 }
138
139 /// The plan at the given prices per unit (micros, after the markup);
140 /// the published costs plus the margin for any not given.
141 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 look142 let p = &self.plans;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily143 let price_of = |meter: &str, cost: i64, units: f64| {
144 per_units(book.get(meter).copied().unwrap_or_else(|| Price::price_for(cost as f64, self.margin_percent)), units)
145 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look146 Plan {
147 feature: Feature::Plan,
148 title: Feature::Plan.title().to_owned(),
149 monthly_cents: p.plan_monthly_cents,
150 includes: vec![
151 format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas152 "{} of usage each month at cost plus {}%, used first",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look153 dollars(p.plan_included_micros),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put154 self.margin_percent
155 ),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas156 "Everyone in the workspace at one price, never per person".to_owned(),
157 "Unlimited projects, previews and repositories".to_owned(),
158 "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 look159 format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas160 "Usage past {} is charged at cost plus {}%, up to your spend limit",
161 dollars(p.plan_included_micros),
162 self.margin_percent
Paid features: a workspace turns on Deployments with a monthly plan163 ),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look164 ],
165 overage: format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas166 "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 look167 self.margin_percent,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily168 price_of("build_second", costs::MICROS_PER_BUILD_SECOND, 60.0),
169 price_of("app_requests", costs::MICROS_PER_MILLION_REQUESTS, 1.0),
170 price_of("app_cpu", costs::MICROS_PER_MILLION_CPU_MS, 1.0),
171 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 quotas172 bytes(p.free_storage_bytes),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily173 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 quotas174 thousands(p.git_included),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily175 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 look176 ),
Paid features: a workspace turns on Deployments with a monthly plan177 }
178 }
179
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look180 /// When the workspace's plan started, and when the period paid for
181 /// ends: its first billing cycle is the first month.
182 pub(crate) async fn plan_cycle(&self, workspace: &str) -> Result<Option<(String, Option<String>)>> {
183 let row = match self.current(workspace, Feature::Plan).await? {
184 Some(row) => Some(row),
185 None => self.current(workspace, Feature::Deployments).await?,
186 };
187 Ok(row
188 .filter(|row| status_from(&row.status).on())
189 .map(|row| (row.started_at, row.period_end)))
190 }
191
Paid features: a workspace turns on Deployments with a monthly plan192 async fn subscription_row(&self, workspace: &str, feature: Feature) -> Result<Option<SubscriptionRow>> {
193 self.db
194 .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 index195 "SELECT feature, subscription_id, status, period_end, started_by, started_at, updated_at
Paid features: a workspace turns on Deployments with a monthly plan196 FROM subscriptions WHERE workspace = ? AND feature = ?",
197 )
198 .bind(&[workspace.into(), feature.as_str().into()])?
199 .first::<SubscriptionRow>(None)
200 .await
201 }
202
203 /// Writes down what the processor says about a plan.
Stripe webhooks, enterprise invoices, and sudo for both204 pub(crate) async fn record(
Paid features: a workspace turns on Deployments with a monthly plan205 &self,
206 workspace: &str,
207 feature: Feature,
208 subscription: &StripeSubscription,
209 started_by: &str,
210 ) -> Result<()> {
211 let now = rfc3339(now_ms());
212 let period_end = subscription.period_end().map(|seconds| rfc3339(seconds.max(0) as u64 * 1000));
213 self.db
214 .prepare(
215 "INSERT INTO subscriptions
216 (workspace, feature, subscription_id, status, period_end, started_by, started_at, updated_at)
217 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)
218 ON CONFLICT (workspace, feature) DO UPDATE SET
219 subscription_id = ?3, status = ?4, period_end = ?5, updated_at = ?7,
220 started_by = CASE WHEN subscription_id = ?3 THEN started_by ELSE ?6 END,
221 started_at = CASE WHEN subscription_id = ?3 THEN started_at ELSE ?7 END",
222 )
223 .bind(&[
224 workspace.into(),
225 feature.as_str().into(),
226 subscription.id.as_str().into(),
227 status_text(status_of(subscription)).into(),
228 optional(period_end.as_deref()),
229 started_by.into(),
230 now.as_str().into(),
231 ])?
232 .run()
233 .await?;
234 Ok(())
235 }
236
237 /// 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 index238 /// the period it last knew of is over, at most once an hour.
Paid features: a workspace turns on Deployments with a monthly plan239 async fn current(&self, workspace: &str, feature: Feature) -> Result<Option<SubscriptionRow>> {
240 let Some(row) = self.subscription_row(workspace, feature).await? else {
241 return Ok(None);
242 };
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 index243 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 plan244 if let (true, Some(stripe)) = (stale, &self.stripe) {
Project dependencies: addresses, preview stacks, Affects, and agents who know245 match stripe.subscription(&row.subscription_id).await {
246 Ok(subscription) => self.record(workspace, feature, &subscription, &row.started_by).await?,
247 // A plan from another Stripe account: it has ended here.
248 Err(error) if is_missing(&error) => {
249 self.db
250 .prepare("UPDATE subscriptions SET status = 'canceled', updated_at = ? WHERE workspace = ? AND feature = ?")
251 .bind(&[rfc3339(now_ms()).into(), workspace.into(), feature.as_str().into()])?
252 .run()
253 .await?;
254 }
255 Err(error) => return Err(error),
256 }
Paid features: a workspace turns on Deployments with a monthly plan257 return self.subscription_row(workspace, feature).await;
258 }
259 Ok(Some(row))
260 }
261
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look262 /// The plan as a workspace sees it. A Deployments subscription from
263 /// before the plan shows as the plan until its period ends.
264 async fn state(&self, workspace: &str, _feature: Feature) -> Result<FeatureState> {
265 let subscription = match self.current(workspace, Feature::Plan).await?.and_then(|row| row.subscription()) {
266 Some(plan) if plan.status.on() => Some(plan),
267 plan => self
268 .current(workspace, Feature::Deployments)
269 .await?
270 .and_then(|row| row.subscription())
271 .filter(|legacy| legacy.status.on())
272 .or(plan),
273 };
274 let included = self.included(workspace).await?;
Paid features: a workspace turns on Deployments with a monthly plan275 Ok(FeatureState {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily276 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 put277 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 plan278 subscription,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put279 included,
Paid features: a workspace turns on Deployments with a monthly plan280 })
281 }
282
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look283 /// Whether the plan is on without its price: comped terms, an
284 /// enterprise's workspaces, or given by g1t staff.
285 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 put286 let account = self.account_of(workspace).await?;
287 Ok(account.terms.kind == g1t_contracts::billing::TermsKind::Comped
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look288 || account.kind == g1t_contracts::billing::AccountKind::Enterprise
289 || account.allowances.plan)
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put290 }
291
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look292 /// Sets every Deployments subscription from before the plan to end
293 /// with its period, once, so no one pays for it and the plan both.
294 /// Until then it counts as the plan.
295 pub(crate) async fn retire_deployments_plans(&self) -> Result<()> {
296 let Some(stripe) = &self.stripe else { return Ok(()) };
297 #[derive(Deserialize)]
298 struct Legacy {
299 workspace: String,
300 subscription_id: String,
301 started_by: String,
302 period_end: Option<String>,
303 }
304 let legacy = self
305 .db
306 .prepare(
307 "SELECT workspace, subscription_id, started_by, period_end FROM subscriptions
308 WHERE feature = 'deployments' AND status = 'active' LIMIT 20",
309 )
310 .all()
311 .await?
312 .results::<Legacy>()?;
313 for plan in legacy {
314 match stripe.cancel_at_period_end(&plan.subscription_id, true).await {
315 Ok(subscription) => {
316 self.record(&plan.workspace, Feature::Deployments, &subscription, &plan.started_by).await?;
317 let account = self.account_of(&plan.workspace).await?;
318 self.audit(
319 &account.id,
320 "migration",
321 &format!(
322 "{}: the Deployments plan ends {} and is not renewed; deployments come with the g1t plan now",
323 plan.workspace,
324 plan.period_end.as_deref().map_or("at the end of its period", |end| &end[..10])
325 ),
326 "billing",
327 )
328 .await?;
329 }
330 Err(error) if is_missing(&error) => {
331 self.db
332 .prepare("UPDATE subscriptions SET status = 'canceled', updated_at = ? WHERE workspace = ? AND feature = 'deployments'")
333 .bind(&[rfc3339(now_ms()).into(), plan.workspace.as_str().into()])?
334 .run()
335 .await?;
336 }
337 Err(error) => worker::console_error!("could not end {}'s Deployments plan: {error}", plan.workspace),
338 }
339 }
340 Ok(())
341 }
342
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put343 /// Whether the workspace's plan for the feature is paid up.
344 pub(crate) async fn plan_on(&self, workspace: &str, feature: Feature) -> Result<bool> {
345 Ok(self
346 .current(workspace, feature)
347 .await?
348 .and_then(|row| row.subscription())
349 .is_some_and(|s| s.status.on()))
350 }
351
Paid features: a workspace turns on Deployments with a monthly plan352 pub(crate) async fn features(&self, a: FeaturesArgs) -> Result<Outcome<Vec<FeatureState>>> {
353 let workspace = a.workspace.to_lowercase();
354 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
355 return Ok(members_only());
356 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look357 Ok(Outcome::Ok(vec![self.state(&workspace, Feature::Plan).await?]))
Paid features: a workspace turns on Deployments with a monthly plan358 }
359
360 pub(crate) async fn subscribe(&self, a: SubscribeArgs) -> Result<Outcome<Checkout>> {
361 let workspace = a.workspace.to_lowercase();
362 if a.actor.role_in(&workspace) != Some(Role::Owner) {
363 return Ok(Outcome::fail(
364 FailureCode::Forbidden,
365 "Only an owner can turn on a paid feature.",
366 ));
367 }
368 let Some(stripe) = &self.stripe else {
369 return Ok(Outcome::fail(
370 FailureCode::Conflict,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look371 "Payments are not set up on this g1t, so the plan is already on.",
Paid features: a workspace turns on Deployments with a monthly plan372 ));
373 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look374 // Deployments come with the plan: asking for them starts the plan.
375 let feature = Feature::Plan;
376 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 put377 if state.included {
378 return Ok(Outcome::fail(
379 FailureCode::Conflict,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look380 format!("The g1t plan 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 put381 ));
382 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look383 if self.plan_on(&workspace, Feature::Plan).await? {
384 return Ok(Outcome::fail(FailureCode::Conflict, format!("The g1t plan is already on for {workspace}.")));
Paid features: a workspace turns on Deployments with a monthly plan385 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily386 let plan = self.plan(feature).await?;
Paid features: a workspace turns on Deployments with a monthly plan387 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 look388 // The card from the card check: the plan starts on it at once, with
389 // no second page. A card that needs the bank's approval again goes
390 // through Stripe's page instead.
391 if let (Some(customer), Some(method)) = (customer.as_deref(), self.checked_card(&workspace).await?) {
392 match stripe
393 .subscribe_with_card(&workspace, feature.as_str(), &plan.title, plan.monthly_cents, customer, &method)
394 .await
395 {
396 Ok(subscription) if matches!(subscription.status.as_str(), "active" | "trialing") => {
397 self.record(&workspace, feature, &subscription, &a.actor.username).await?;
398 let account = self.account_of(&workspace).await?;
399 self.audit(&account.id, "plan", &format!("{workspace}: the g1t plan started on the checked card"), &a.actor.username)
400 .await?;
401 let separator = if a.return_url.contains('?') { '&' } else { '?' };
402 return Ok(Outcome::Ok(Checkout { url: format!("{}{separator}plan=started", a.return_url) }));
403 }
404 Ok(subscription) => {
405 // Incomplete: let it lapse, and use the page.
406 let _ = stripe.cancel_now(&subscription.id).await;
407 }
408 Err(error) => worker::console_log!("{workspace}: the plan could not start on the checked card: {error}"),
409 }
410 }
Project dependencies: addresses, preview stacks, Affects, and agents who know411 let start = |customer: Option<String>| {
412 let plan = &plan;
413 let workspace = &workspace;
414 let return_url = &a.return_url;
415 async move {
416 stripe
417 .start_subscription(
418 workspace,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look419 feature.as_str(),
Project dependencies: addresses, preview stacks, Affects, and agents who know420 &plan.title,
421 plan.monthly_cents,
422 customer.as_deref(),
423 return_url,
424 )
425 .await
426 }
427 };
428 let session = match start(customer.clone()).await {
429 Ok(session) => session,
430 // A customer saved under another Stripe account: start afresh.
431 Err(error) if customer.is_some() && is_missing(&error) => {
432 self.forget_customer(&workspace).await?;
433 start(None).await?
434 }
435 Err(error) => return Err(error),
436 };
Paid features: a workspace turns on Deployments with a monthly plan437 let Some(url) = session.url else {
438 return Err(worker::Error::RustError(
439 "the card processor returned no payment page".into(),
440 ));
441 };
442 self.db
443 .prepare(
444 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at, feature)
445 VALUES (?, ?, ?, ?, ?, ?)",
446 )
447 .bind(&[
448 session.id.into(),
449 workspace.into(),
450 plan.monthly_cents.into(),
451 a.actor.username.into(),
452 rfc3339(now_ms()).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look453 feature.as_str().into(),
Paid features: a workspace turns on Deployments with a monthly plan454 ])?
455 .run()
456 .await?;
457 Ok(Outcome::Ok(Checkout { url }))
458 }
459
460 pub(crate) async fn confirm_subscription(
461 &self,
462 a: ConfirmSubscriptionArgs,
463 ) -> Result<Outcome<FeatureState>> {
464 let workspace = a.workspace.to_lowercase();
465 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
466 return Ok(members_only());
467 }
468 let checkout = self
469 .db
470 .prepare(
471 "SELECT workspace, created_by, feature FROM checkouts
472 WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NOT NULL",
473 )
474 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
475 .first::<PlanCheckoutRow>(None)
476 .await?;
477 let (Some(stripe), Some(checkout)) = (&self.stripe, checkout) else {
478 // 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 look479 return Ok(Outcome::Ok(self.state(&workspace, Feature::Plan).await?));
Paid features: a workspace turns on Deployments with a monthly plan480 };
481 let Some(feature) = Feature::parse(&checkout.feature) else {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look482 return Ok(Outcome::fail(FailureCode::NotFound, "No such plan."));
Paid features: a workspace turns on Deployments with a monthly plan483 };
484 let session = stripe.session(&a.session).await?;
485 if let (Some(subscription_id), true) = (&session.subscription, session.payment_status == "paid") {
486 let claimed = self
487 .db
488 .prepare("UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open' RETURNING id")
489 .bind(&[a.session.as_str().into()])?
490 .first::<Touched>(None)
491 .await?;
492 if claimed.is_some() {
493 let subscription = stripe.subscription(subscription_id).await?;
494 self.record(&checkout.workspace, feature, &subscription, &checkout.created_by)
495 .await?;
496 // Keep the card's customer, so later payments need no retyping.
497 self.db
498 .prepare(
499 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
500 VALUES (?1, 0, ?2, ?3)
501 ON CONFLICT (workspace) DO UPDATE SET customer_id = COALESCE(customer_id, ?2)",
502 )
503 .bind(&[
504 checkout.workspace.as_str().into(),
505 optional(session.customer.as_deref()),
506 rfc3339(now_ms()).into(),
507 ])?
508 .run()
509 .await?;
510 }
511 }
512 Ok(Outcome::Ok(self.state(&workspace, feature).await?))
513 }
514
515 pub(crate) async fn cancel_subscription(
516 &self,
517 a: CancelSubscriptionArgs,
518 ) -> Result<Outcome<FeatureState>> {
519 let workspace = a.workspace.to_lowercase();
520 if a.actor.role_in(&workspace) != Some(Role::Owner) {
521 return Ok(Outcome::fail(
522 FailureCode::Forbidden,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look523 "Only an owner can change the workspace's plan.",
Paid features: a workspace turns on Deployments with a monthly plan524 ));
525 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look526 // The plan, or a Deployments subscription from before it.
527 let row = match self.current(&workspace, Feature::Plan).await? {
528 Some(row) if status_from(&row.status) != SubscriptionStatus::Canceled => Some((Feature::Plan, row)),
529 _ => self.current(&workspace, Feature::Deployments).await?.map(|row| (Feature::Deployments, row)),
530 };
531 let (Some(stripe), Some((feature, row))) = (&self.stripe, row) else {
532 return Ok(Outcome::fail(FailureCode::NotFound, format!("The g1t plan is not on for {workspace}.")));
Paid features: a workspace turns on Deployments with a monthly plan533 };
534 let subscription = stripe
535 .cancel_at_period_end(&row.subscription_id, !a.resume)
536 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look537 self.record(&workspace, feature, &subscription, &row.started_by)
Paid features: a workspace turns on Deployments with a monthly plan538 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look539 Ok(Outcome::Ok(self.state(&workspace, Feature::Plan).await?))
Paid features: a workspace turns on Deployments with a monthly plan540 }
541
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look542 /// Whether the workspace has the plan, which deployments come with.
Paid features: a workspace turns on Deployments with a monthly plan543 pub(crate) async fn has_feature(&self, a: HasFeatureArgs) -> Result<Outcome<bool>> {
544 let workspace = a.workspace.to_lowercase();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look545 if self.has_plan(&workspace).await? {
Paid features: a workspace turns on Deployments with a monthly plan546 return Ok(Outcome::Ok(true));
547 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look548 let what = match a.feature {
549 Feature::Deployments => "Deployments come with the g1t plan",
550 Feature::Plan => "This needs the g1t plan",
551 };
Paid features: a workspace turns on Deployments with a monthly plan552 Ok(Outcome::fail(
553 FailureCode::PaymentRequired,
554 format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look555 "{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 plan556 ),
557 ))
558 }
559
560 pub(crate) async fn charge_feature(&self, a: ChargeFeatureArgs) -> Result<Outcome<bool>> {
561 if self.stripe.is_none() || a.cost_micros <= 0 {
562 return Ok(Outcome::Ok(false));
563 }
564 let workspace = a.workspace.to_lowercase();
565 let seen = self
566 .db
567 .prepare("SELECT id FROM ledger WHERE reference = ?")
568 .bind(&[a.reference.as_str().into()])?
569 .first::<Touched>(None)
570 .await?;
571 if seen.is_some() {
572 return Ok(Outcome::Ok(false));
573 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put574 let timestamp = rfc3339(now_ms());
575 let month = crate::credits::month_of(&timestamp);
576 let mut description = a.description.clone();
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas577 // A build: every second is metered, at the price book's build
578 // second, which the keeper keeps at what Cloudflare bills, rather
579 // than at what the caller worked out. The month's build time is
580 // tallied for the Billing page.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put581 let cost_micros = match a.build_seconds.filter(|s| *s > 0 && a.feature == Feature::Deployments) {
582 Some(seconds) => {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas583 self.tally("build_seconds", &workspace, &month, seconds.into()).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look584 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 quotas585 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 put586 }
587 None => a.cost_micros,
588 };
589 let cost = cost_micros as f64 / MICROS_PER_DOLLAR as f64;
Billing accounts, terms and enterprises; g1t is no longer free590 // 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 look591 // and only the account's terms change it. The plan's included usage
592 // 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 put593 // deployments.
Billing accounts, terms and enterprises; g1t is no longer free594 let charge = self.terms_of(&workspace).await?.apply(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 put595 let drawn = self.draw(&workspace, charge, &month, &crate::credits::Eligible::default()).await?;
596 description.push_str(&drawn.note());
597 self.post_usage(crate::storage::UsageLine {
598 workspace: &workspace,
599 charged: charge - drawn.total(),
600 description: &description,
601 repo: a.repo.as_deref(),
602 task: a.feature.as_str(),
603 cost: cost_micros,
604 reference: &a.reference,
605 created_at: &timestamp,
606 drawn,
607 })
608 .await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays609 self.count_spend(&workspace, cost_micros, charge - drawn.total(), &drawn).await;
Paid features: a workspace turns on Deployments with a monthly plan610 Ok(Outcome::Ok(true))
611 }
612}
Deployments: a preview for every pull request, production on g1t.page613
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas614/// `50,000`: a count as the plan reads it.
615pub(crate) fn thousands(n: u64) -> String {
616 let digits = n.to_string();
617 let mut out = String::new();
618 for (i, c) in digits.chars().enumerate() {
619 if i > 0 && (digits.len() - i).is_multiple_of(3) {
620 out.push(',');
621 }
622 out.push(c);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put623 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas624 out
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put625}
626
Deployments: a preview for every pull request, production on g1t.page627#[cfg(test)]
628mod tests {
629 use super::*;
630
631 #[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 index632 fn an_ended_plan_is_asked_about_at_most_once_an_hour() {
633 let now = 1_791_000_000_000;
634 let at = |ago_ms: u64| rfc3339(now - ago_ms);
635 let ended = at(24 * 60 * 60 * 1000);
636 // Ended, and last written a day ago: ask.
637 assert!(needs_refresh("active", Some(&ended), &ended, now));
638 // Ended, but written ten minutes ago: believe the row.
639 assert!(!needs_refresh("active", Some(&ended), &at(10 * 60 * 1000), now));
640 // An hour on, ask again.
641 assert!(needs_refresh("active", Some(&ended), &at(REFRESH_MS), now));
642 // No period known is the same as ended.
643 assert!(needs_refresh("past_due", None, &ended, now));
644 // A period still running, or a canceled plan, is never asked about.
645 assert!(!needs_refresh("active", Some(&rfc3339(now + 1000)), &ended, now));
646 assert!(!needs_refresh("canceled", Some(&ended), &ended, now));
647 }
648
649 #[test]
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily650 fn the_plan_text_quotes_a_build_minute_as_the_table_does() {
651 // The price book's build second (16.44 millionths at cost, plus
652 // 20%) is 19.73 millionths: a minute is 1,184 millionths, $0.0012,
653 // as the pricing page's table says. The old fixed cost (15) gave
654 // $0.0011.
655 let each = Price::price_for(16.439_893_610_418_67, 20);
656 assert_eq!(per_units(each, 60.0), "$0.0012");
657 assert_eq!(per_units(Price::price_for(15.0, 20), 60.0), "$0.0011");
658 assert_eq!(per_units(Price::price_for(150_000.0, 20), 1.0), "$0.18");
659 }
660
661 #[test]
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas662 fn every_build_second_is_metered_at_cost_plus_the_margin() {
663 // A 5-minute build at 15 millionths a second costs g1t 4,500, and
664 // is charged at cost plus 20%, from the first second: there are no
665 // included build minutes, only the plan's included usage.
666 let cost = 300 * costs::MICROS_PER_BUILD_SECOND;
667 assert_eq!(cost, 4_500);
668 assert_eq!(crate::credits::with_margin(cost, 20), 5_400);
669 }
670
671 #[test]
672 fn counts_read_with_thousands_separators() {
673 assert_eq!(thousands(0), "0");
674 assert_eq!(thousands(999), "999");
675 assert_eq!(thousands(50_000), "50,000");
676 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 put677 }
678
679 #[test]
680 fn storage_reads_in_gigabytes() {
681 assert_eq!(bytes(1_000_000_000), "1 GB");
682 assert_eq!(bytes(50_000_000_000), "50 GB");
683 assert_eq!(bytes(1_500_000_000), "1.5 GB");
684 assert_eq!(bytes(500_000_000), "500 MB");
685 }
686
687 #[test]
Deployments: a preview for every pull request, production on g1t.page688 fn prices_under_a_cent_keep_their_digits() {
689 assert_eq!(dollars(1512), "$0.0015");
690 assert_eq!(dollars(24_000), "$0.024");
691 assert_eq!(dollars(360_000), "$0.36");
692 assert_eq!(dollars(5_000_000), "$5.00");
693 }
694}