g1t/services/billing/src/features.rs

662 lines29,245 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,
36}
37
38#[derive(Deserialize)]
39struct PlanCheckoutRow {
40 workspace: String,
41 created_by: String,
42 feature: String,
43}
44
45fn status_from(text: &str) -> SubscriptionStatus {
46 match text {
47 "active" => SubscriptionStatus::Active,
48 "canceling" => SubscriptionStatus::Canceling,
49 "past_due" => SubscriptionStatus::PastDue,
50 _ => SubscriptionStatus::Canceled,
51 }
52}
53
54fn status_text(status: SubscriptionStatus) -> &'static str {
55 match status {
56 SubscriptionStatus::Active => "active",
57 SubscriptionStatus::Canceling => "canceling",
58 SubscriptionStatus::PastDue => "past_due",
59 SubscriptionStatus::Canceled => "canceled",
60 }
61}
62
63/// What the processor's state for a plan means here.
64fn status_of(subscription: &StripeSubscription) -> SubscriptionStatus {
65 match subscription.status.as_str() {
66 "active" | "trialing" if subscription.cancel_at_period_end => SubscriptionStatus::Canceling,
67 "active" | "trialing" => SubscriptionStatus::Active,
68 "past_due" | "unpaid" | "incomplete" | "paused" => SubscriptionStatus::PastDue,
69 _ => SubscriptionStatus::Canceled,
70 }
71}
72
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put73/// `1 GB`, `50 GB`, or `500 MB`, as storage is priced (powers of ten).
74pub(crate) fn bytes(bytes: i64) -> String {
75 if bytes >= 1_000_000_000 && bytes % 1_000_000_000 == 0 {
76 format!("{} GB", bytes / 1_000_000_000)
77 } else if bytes >= 1_000_000_000 {
78 format!("{:.1} GB", bytes as f64 / 1e9)
79 } else {
80 format!("{} MB", bytes / 1_000_000)
81 }
82}
83
Deployments: a preview for every pull request, production on g1t.page84/// Dollars to the cent, or finer for prices under a cent, so that a
85/// build minute's $0.0015 does not read as nothing.
Usage limits: unpaid usage can only go so far86pub(crate) fn dollars(micros: i64) -> String {
Deployments: a preview for every pull request, production on g1t.page87 let text = format!("{:.4}", micros as f64 / MICROS_PER_DOLLAR as f64);
88 let (whole, fraction) = text.split_once('.').unwrap_or((&text, ""));
89 let fraction = fraction.trim_end_matches('0');
90 format!("${whole}.{fraction:0<2}")
Paid features: a workspace turns on Deployments with a monthly plan91}
92
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily93/// `units` at `each` micros a unit, as the pricing page writes it: a
94/// build second's price times 60 is the build minute both quote.
95pub(crate) fn per_units(each: f64, units: f64) -> String {
96 dollars((each * units).round() as i64)
97}
98
Paid features: a workspace turns on Deployments with a monthly plan99impl SubscriptionRow {
100 fn subscription(&self) -> Option<Subscription> {
101 Some(Subscription {
102 feature: Feature::parse(&self.feature)?,
103 status: status_from(&self.status),
104 period_end: self.period_end.clone(),
105 started_by: self.started_by.clone(),
106 started_at: self.started_at.clone(),
107 })
108 }
109}
110
111impl Billing {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily112 /// What the g1t plan costs and includes, as it is sold now, at the
113 /// price book's prices (the same figures as the pricing page's table).
114 pub(crate) async fn plan(&self, _feature: Feature) -> Result<Plan> {
115 let mut book = std::collections::BTreeMap::new();
116 for meter in ["build_second", "app_requests", "app_cpu", "custom_domain_month", "private_storage", "git_operations"] {
117 if let Some((_, price)) = self.price(meter).await? {
118 book.insert(meter, price);
119 }
120 }
121 Ok(self.plan_at(&book))
122 }
123
124 /// The plan at the given prices per unit (micros, after the markup);
125 /// the published costs plus the margin for any not given.
126 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 look127 let p = &self.plans;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily128 let price_of = |meter: &str, cost: i64, units: f64| {
129 per_units(book.get(meter).copied().unwrap_or_else(|| Price::price_for(cost as f64, self.margin_percent)), units)
130 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look131 Plan {
132 feature: Feature::Plan,
133 title: Feature::Plan.title().to_owned(),
134 monthly_cents: p.plan_monthly_cents,
135 includes: vec![
136 format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas137 "{} of usage each month at cost plus {}%, used first",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look138 dollars(p.plan_included_micros),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put139 self.margin_percent
140 ),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas141 "Everyone in the workspace at one price, never per person".to_owned(),
142 "Unlimited projects, previews and repositories".to_owned(),
143 "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 look144 format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas145 "Usage past {} is charged at cost plus {}%, up to your spend limit",
146 dollars(p.plan_included_micros),
147 self.margin_percent
Paid features: a workspace turns on Deployments with a monthly plan148 ),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look149 ],
150 overage: format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas151 "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 look152 self.margin_percent,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily153 price_of("build_second", costs::MICROS_PER_BUILD_SECOND, 60.0),
154 price_of("app_requests", costs::MICROS_PER_MILLION_REQUESTS, 1.0),
155 price_of("app_cpu", costs::MICROS_PER_MILLION_CPU_MS, 1.0),
156 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 quotas157 bytes(p.free_storage_bytes),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily158 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 quotas159 thousands(p.git_included),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily160 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 look161 ),
Paid features: a workspace turns on Deployments with a monthly plan162 }
163 }
164
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look165 /// When the workspace's plan started, and when the period paid for
166 /// ends: its first billing cycle is the first month.
167 pub(crate) async fn plan_cycle(&self, workspace: &str) -> Result<Option<(String, Option<String>)>> {
168 let row = match self.current(workspace, Feature::Plan).await? {
169 Some(row) => Some(row),
170 None => self.current(workspace, Feature::Deployments).await?,
171 };
172 Ok(row
173 .filter(|row| status_from(&row.status).on())
174 .map(|row| (row.started_at, row.period_end)))
175 }
176
Paid features: a workspace turns on Deployments with a monthly plan177 async fn subscription_row(&self, workspace: &str, feature: Feature) -> Result<Option<SubscriptionRow>> {
178 self.db
179 .prepare(
180 "SELECT feature, subscription_id, status, period_end, started_by, started_at
181 FROM subscriptions WHERE workspace = ? AND feature = ?",
182 )
183 .bind(&[workspace.into(), feature.as_str().into()])?
184 .first::<SubscriptionRow>(None)
185 .await
186 }
187
188 /// Writes down what the processor says about a plan.
Stripe webhooks, enterprise invoices, and sudo for both189 pub(crate) async fn record(
Paid features: a workspace turns on Deployments with a monthly plan190 &self,
191 workspace: &str,
192 feature: Feature,
193 subscription: &StripeSubscription,
194 started_by: &str,
195 ) -> Result<()> {
196 let now = rfc3339(now_ms());
197 let period_end = subscription.period_end().map(|seconds| rfc3339(seconds.max(0) as u64 * 1000));
198 self.db
199 .prepare(
200 "INSERT INTO subscriptions
201 (workspace, feature, subscription_id, status, period_end, started_by, started_at, updated_at)
202 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)
203 ON CONFLICT (workspace, feature) DO UPDATE SET
204 subscription_id = ?3, status = ?4, period_end = ?5, updated_at = ?7,
205 started_by = CASE WHEN subscription_id = ?3 THEN started_by ELSE ?6 END,
206 started_at = CASE WHEN subscription_id = ?3 THEN started_at ELSE ?7 END",
207 )
208 .bind(&[
209 workspace.into(),
210 feature.as_str().into(),
211 subscription.id.as_str().into(),
212 status_text(status_of(subscription)).into(),
213 optional(period_end.as_deref()),
214 started_by.into(),
215 now.as_str().into(),
216 ])?
217 .run()
218 .await?;
219 Ok(())
220 }
221
222 /// A workspace's plan for a feature, asking the processor again once
223 /// the period it last knew of is over.
224 async fn current(&self, workspace: &str, feature: Feature) -> Result<Option<SubscriptionRow>> {
225 let Some(row) = self.subscription_row(workspace, feature).await? else {
226 return Ok(None);
227 };
228 let stale = row.period_end.as_deref().is_none_or(|end| end <= rfc3339(now_ms()).as_str())
229 && row.status != "canceled";
230 if let (true, Some(stripe)) = (stale, &self.stripe) {
Project dependencies: addresses, preview stacks, Affects, and agents who know231 match stripe.subscription(&row.subscription_id).await {
232 Ok(subscription) => self.record(workspace, feature, &subscription, &row.started_by).await?,
233 // A plan from another Stripe account: it has ended here.
234 Err(error) if is_missing(&error) => {
235 self.db
236 .prepare("UPDATE subscriptions SET status = 'canceled', updated_at = ? WHERE workspace = ? AND feature = ?")
237 .bind(&[rfc3339(now_ms()).into(), workspace.into(), feature.as_str().into()])?
238 .run()
239 .await?;
240 }
241 Err(error) => return Err(error),
242 }
Paid features: a workspace turns on Deployments with a monthly plan243 return self.subscription_row(workspace, feature).await;
244 }
245 Ok(Some(row))
246 }
247
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look248 /// The plan as a workspace sees it. A Deployments subscription from
249 /// before the plan shows as the plan until its period ends.
250 async fn state(&self, workspace: &str, _feature: Feature) -> Result<FeatureState> {
251 let subscription = match self.current(workspace, Feature::Plan).await?.and_then(|row| row.subscription()) {
252 Some(plan) if plan.status.on() => Some(plan),
253 plan => self
254 .current(workspace, Feature::Deployments)
255 .await?
256 .and_then(|row| row.subscription())
257 .filter(|legacy| legacy.status.on())
258 .or(plan),
259 };
260 let included = self.included(workspace).await?;
Paid features: a workspace turns on Deployments with a monthly plan261 Ok(FeatureState {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily262 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 put263 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 plan264 subscription,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put265 included,
Paid features: a workspace turns on Deployments with a monthly plan266 })
267 }
268
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look269 /// Whether the plan is on without its price: comped terms, an
270 /// enterprise's workspaces, or given by g1t staff.
271 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 put272 let account = self.account_of(workspace).await?;
273 Ok(account.terms.kind == g1t_contracts::billing::TermsKind::Comped
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look274 || account.kind == g1t_contracts::billing::AccountKind::Enterprise
275 || account.allowances.plan)
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put276 }
277
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look278 /// Sets every Deployments subscription from before the plan to end
279 /// with its period, once, so no one pays for it and the plan both.
280 /// Until then it counts as the plan.
281 pub(crate) async fn retire_deployments_plans(&self) -> Result<()> {
282 let Some(stripe) = &self.stripe else { return Ok(()) };
283 #[derive(Deserialize)]
284 struct Legacy {
285 workspace: String,
286 subscription_id: String,
287 started_by: String,
288 period_end: Option<String>,
289 }
290 let legacy = self
291 .db
292 .prepare(
293 "SELECT workspace, subscription_id, started_by, period_end FROM subscriptions
294 WHERE feature = 'deployments' AND status = 'active' LIMIT 20",
295 )
296 .all()
297 .await?
298 .results::<Legacy>()?;
299 for plan in legacy {
300 match stripe.cancel_at_period_end(&plan.subscription_id, true).await {
301 Ok(subscription) => {
302 self.record(&plan.workspace, Feature::Deployments, &subscription, &plan.started_by).await?;
303 let account = self.account_of(&plan.workspace).await?;
304 self.audit(
305 &account.id,
306 "migration",
307 &format!(
308 "{}: the Deployments plan ends {} and is not renewed; deployments come with the g1t plan now",
309 plan.workspace,
310 plan.period_end.as_deref().map_or("at the end of its period", |end| &end[..10])
311 ),
312 "billing",
313 )
314 .await?;
315 }
316 Err(error) if is_missing(&error) => {
317 self.db
318 .prepare("UPDATE subscriptions SET status = 'canceled', updated_at = ? WHERE workspace = ? AND feature = 'deployments'")
319 .bind(&[rfc3339(now_ms()).into(), plan.workspace.as_str().into()])?
320 .run()
321 .await?;
322 }
323 Err(error) => worker::console_error!("could not end {}'s Deployments plan: {error}", plan.workspace),
324 }
325 }
326 Ok(())
327 }
328
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put329 /// Whether the workspace's plan for the feature is paid up.
330 pub(crate) async fn plan_on(&self, workspace: &str, feature: Feature) -> Result<bool> {
331 Ok(self
332 .current(workspace, feature)
333 .await?
334 .and_then(|row| row.subscription())
335 .is_some_and(|s| s.status.on()))
336 }
337
Paid features: a workspace turns on Deployments with a monthly plan338 pub(crate) async fn features(&self, a: FeaturesArgs) -> Result<Outcome<Vec<FeatureState>>> {
339 let workspace = a.workspace.to_lowercase();
340 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
341 return Ok(members_only());
342 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look343 Ok(Outcome::Ok(vec![self.state(&workspace, Feature::Plan).await?]))
Paid features: a workspace turns on Deployments with a monthly plan344 }
345
346 pub(crate) async fn subscribe(&self, a: SubscribeArgs) -> Result<Outcome<Checkout>> {
347 let workspace = a.workspace.to_lowercase();
348 if a.actor.role_in(&workspace) != Some(Role::Owner) {
349 return Ok(Outcome::fail(
350 FailureCode::Forbidden,
351 "Only an owner can turn on a paid feature.",
352 ));
353 }
354 let Some(stripe) = &self.stripe else {
355 return Ok(Outcome::fail(
356 FailureCode::Conflict,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look357 "Payments are not set up on this g1t, so the plan is already on.",
Paid features: a workspace turns on Deployments with a monthly plan358 ));
359 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look360 // Deployments come with the plan: asking for them starts the plan.
361 let feature = Feature::Plan;
362 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 put363 if state.included {
364 return Ok(Outcome::fail(
365 FailureCode::Conflict,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look366 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 put367 ));
368 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look369 if self.plan_on(&workspace, Feature::Plan).await? {
370 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 plan371 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily372 let plan = self.plan(feature).await?;
Paid features: a workspace turns on Deployments with a monthly plan373 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 look374 // The card from the card check: the plan starts on it at once, with
375 // no second page. A card that needs the bank's approval again goes
376 // through Stripe's page instead.
377 if let (Some(customer), Some(method)) = (customer.as_deref(), self.checked_card(&workspace).await?) {
378 match stripe
379 .subscribe_with_card(&workspace, feature.as_str(), &plan.title, plan.monthly_cents, customer, &method)
380 .await
381 {
382 Ok(subscription) if matches!(subscription.status.as_str(), "active" | "trialing") => {
383 self.record(&workspace, feature, &subscription, &a.actor.username).await?;
384 let account = self.account_of(&workspace).await?;
385 self.audit(&account.id, "plan", &format!("{workspace}: the g1t plan started on the checked card"), &a.actor.username)
386 .await?;
387 let separator = if a.return_url.contains('?') { '&' } else { '?' };
388 return Ok(Outcome::Ok(Checkout { url: format!("{}{separator}plan=started", a.return_url) }));
389 }
390 Ok(subscription) => {
391 // Incomplete: let it lapse, and use the page.
392 let _ = stripe.cancel_now(&subscription.id).await;
393 }
394 Err(error) => worker::console_log!("{workspace}: the plan could not start on the checked card: {error}"),
395 }
396 }
Project dependencies: addresses, preview stacks, Affects, and agents who know397 let start = |customer: Option<String>| {
398 let plan = &plan;
399 let workspace = &workspace;
400 let return_url = &a.return_url;
401 async move {
402 stripe
403 .start_subscription(
404 workspace,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look405 feature.as_str(),
Project dependencies: addresses, preview stacks, Affects, and agents who know406 &plan.title,
407 plan.monthly_cents,
408 customer.as_deref(),
409 return_url,
410 )
411 .await
412 }
413 };
414 let session = match start(customer.clone()).await {
415 Ok(session) => session,
416 // A customer saved under another Stripe account: start afresh.
417 Err(error) if customer.is_some() && is_missing(&error) => {
418 self.forget_customer(&workspace).await?;
419 start(None).await?
420 }
421 Err(error) => return Err(error),
422 };
Paid features: a workspace turns on Deployments with a monthly plan423 let Some(url) = session.url else {
424 return Err(worker::Error::RustError(
425 "the card processor returned no payment page".into(),
426 ));
427 };
428 self.db
429 .prepare(
430 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at, feature)
431 VALUES (?, ?, ?, ?, ?, ?)",
432 )
433 .bind(&[
434 session.id.into(),
435 workspace.into(),
436 plan.monthly_cents.into(),
437 a.actor.username.into(),
438 rfc3339(now_ms()).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look439 feature.as_str().into(),
Paid features: a workspace turns on Deployments with a monthly plan440 ])?
441 .run()
442 .await?;
443 Ok(Outcome::Ok(Checkout { url }))
444 }
445
446 pub(crate) async fn confirm_subscription(
447 &self,
448 a: ConfirmSubscriptionArgs,
449 ) -> Result<Outcome<FeatureState>> {
450 let workspace = a.workspace.to_lowercase();
451 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
452 return Ok(members_only());
453 }
454 let checkout = self
455 .db
456 .prepare(
457 "SELECT workspace, created_by, feature FROM checkouts
458 WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NOT NULL",
459 )
460 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
461 .first::<PlanCheckoutRow>(None)
462 .await?;
463 let (Some(stripe), Some(checkout)) = (&self.stripe, checkout) else {
464 // 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 look465 return Ok(Outcome::Ok(self.state(&workspace, Feature::Plan).await?));
Paid features: a workspace turns on Deployments with a monthly plan466 };
467 let Some(feature) = Feature::parse(&checkout.feature) else {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look468 return Ok(Outcome::fail(FailureCode::NotFound, "No such plan."));
Paid features: a workspace turns on Deployments with a monthly plan469 };
470 let session = stripe.session(&a.session).await?;
471 if let (Some(subscription_id), true) = (&session.subscription, session.payment_status == "paid") {
472 let claimed = self
473 .db
474 .prepare("UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open' RETURNING id")
475 .bind(&[a.session.as_str().into()])?
476 .first::<Touched>(None)
477 .await?;
478 if claimed.is_some() {
479 let subscription = stripe.subscription(subscription_id).await?;
480 self.record(&checkout.workspace, feature, &subscription, &checkout.created_by)
481 .await?;
482 // Keep the card's customer, so later payments need no retyping.
483 self.db
484 .prepare(
485 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
486 VALUES (?1, 0, ?2, ?3)
487 ON CONFLICT (workspace) DO UPDATE SET customer_id = COALESCE(customer_id, ?2)",
488 )
489 .bind(&[
490 checkout.workspace.as_str().into(),
491 optional(session.customer.as_deref()),
492 rfc3339(now_ms()).into(),
493 ])?
494 .run()
495 .await?;
496 }
497 }
498 Ok(Outcome::Ok(self.state(&workspace, feature).await?))
499 }
500
501 pub(crate) async fn cancel_subscription(
502 &self,
503 a: CancelSubscriptionArgs,
504 ) -> Result<Outcome<FeatureState>> {
505 let workspace = a.workspace.to_lowercase();
506 if a.actor.role_in(&workspace) != Some(Role::Owner) {
507 return Ok(Outcome::fail(
508 FailureCode::Forbidden,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look509 "Only an owner can change the workspace's plan.",
Paid features: a workspace turns on Deployments with a monthly plan510 ));
511 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look512 // The plan, or a Deployments subscription from before it.
513 let row = match self.current(&workspace, Feature::Plan).await? {
514 Some(row) if status_from(&row.status) != SubscriptionStatus::Canceled => Some((Feature::Plan, row)),
515 _ => self.current(&workspace, Feature::Deployments).await?.map(|row| (Feature::Deployments, row)),
516 };
517 let (Some(stripe), Some((feature, row))) = (&self.stripe, row) else {
518 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 plan519 };
520 let subscription = stripe
521 .cancel_at_period_end(&row.subscription_id, !a.resume)
522 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look523 self.record(&workspace, feature, &subscription, &row.started_by)
Paid features: a workspace turns on Deployments with a monthly plan524 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look525 Ok(Outcome::Ok(self.state(&workspace, Feature::Plan).await?))
Paid features: a workspace turns on Deployments with a monthly plan526 }
527
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look528 /// Whether the workspace has the plan, which deployments come with.
Paid features: a workspace turns on Deployments with a monthly plan529 pub(crate) async fn has_feature(&self, a: HasFeatureArgs) -> Result<Outcome<bool>> {
530 let workspace = a.workspace.to_lowercase();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look531 if self.has_plan(&workspace).await? {
Paid features: a workspace turns on Deployments with a monthly plan532 return Ok(Outcome::Ok(true));
533 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look534 let what = match a.feature {
535 Feature::Deployments => "Deployments come with the g1t plan",
536 Feature::Plan => "This needs the g1t plan",
537 };
Paid features: a workspace turns on Deployments with a monthly plan538 Ok(Outcome::fail(
539 FailureCode::PaymentRequired,
540 format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look541 "{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 plan542 ),
543 ))
544 }
545
546 pub(crate) async fn charge_feature(&self, a: ChargeFeatureArgs) -> Result<Outcome<bool>> {
547 if self.stripe.is_none() || a.cost_micros <= 0 {
548 return Ok(Outcome::Ok(false));
549 }
550 let workspace = a.workspace.to_lowercase();
551 let seen = self
552 .db
553 .prepare("SELECT id FROM ledger WHERE reference = ?")
554 .bind(&[a.reference.as_str().into()])?
555 .first::<Touched>(None)
556 .await?;
557 if seen.is_some() {
558 return Ok(Outcome::Ok(false));
559 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put560 let timestamp = rfc3339(now_ms());
561 let month = crate::credits::month_of(&timestamp);
562 let mut description = a.description.clone();
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas563 // A build: every second is metered, at the price book's build
564 // second, which the keeper keeps at what Cloudflare bills, rather
565 // than at what the caller worked out. The month's build time is
566 // tallied for the Billing page.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put567 let cost_micros = match a.build_seconds.filter(|s| *s > 0 && a.feature == Feature::Deployments) {
568 Some(seconds) => {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas569 self.tally("build_seconds", &workspace, &month, seconds.into()).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look570 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 quotas571 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 put572 }
573 None => a.cost_micros,
574 };
575 let cost = cost_micros as f64 / MICROS_PER_DOLLAR as f64;
Billing accounts, terms and enterprises; g1t is no longer free576 // 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 look577 // and only the account's terms change it. The plan's included usage
578 // 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 put579 // deployments.
Billing accounts, terms and enterprises; g1t is no longer free580 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 put581 let drawn = self.draw(&workspace, charge, &month, &crate::credits::Eligible::default()).await?;
582 description.push_str(&drawn.note());
583 self.post_usage(crate::storage::UsageLine {
584 workspace: &workspace,
585 charged: charge - drawn.total(),
586 description: &description,
587 repo: a.repo.as_deref(),
588 task: a.feature.as_str(),
589 cost: cost_micros,
590 reference: &a.reference,
591 created_at: &timestamp,
592 drawn,
593 })
594 .await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays595 self.count_spend(&workspace, cost_micros, charge - drawn.total(), &drawn).await;
Paid features: a workspace turns on Deployments with a monthly plan596 Ok(Outcome::Ok(true))
597 }
598}
Deployments: a preview for every pull request, production on g1t.page599
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas600/// `50,000`: a count as the plan reads it.
601pub(crate) fn thousands(n: u64) -> String {
602 let digits = n.to_string();
603 let mut out = String::new();
604 for (i, c) in digits.chars().enumerate() {
605 if i > 0 && (digits.len() - i).is_multiple_of(3) {
606 out.push(',');
607 }
608 out.push(c);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put609 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas610 out
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put611}
612
Deployments: a preview for every pull request, production on g1t.page613#[cfg(test)]
614mod tests {
615 use super::*;
616
617 #[test]
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily618 fn the_plan_text_quotes_a_build_minute_as_the_table_does() {
619 // The price book's build second (16.44 millionths at cost, plus
620 // 20%) is 19.73 millionths: a minute is 1,184 millionths, $0.0012,
621 // as the pricing page's table says. The old fixed cost (15) gave
622 // $0.0011.
623 let each = Price::price_for(16.439_893_610_418_67, 20);
624 assert_eq!(per_units(each, 60.0), "$0.0012");
625 assert_eq!(per_units(Price::price_for(15.0, 20), 60.0), "$0.0011");
626 assert_eq!(per_units(Price::price_for(150_000.0, 20), 1.0), "$0.18");
627 }
628
629 #[test]
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas630 fn every_build_second_is_metered_at_cost_plus_the_margin() {
631 // A 5-minute build at 15 millionths a second costs g1t 4,500, and
632 // is charged at cost plus 20%, from the first second: there are no
633 // included build minutes, only the plan's included usage.
634 let cost = 300 * costs::MICROS_PER_BUILD_SECOND;
635 assert_eq!(cost, 4_500);
636 assert_eq!(crate::credits::with_margin(cost, 20), 5_400);
637 }
638
639 #[test]
640 fn counts_read_with_thousands_separators() {
641 assert_eq!(thousands(0), "0");
642 assert_eq!(thousands(999), "999");
643 assert_eq!(thousands(50_000), "50,000");
644 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 put645 }
646
647 #[test]
648 fn storage_reads_in_gigabytes() {
649 assert_eq!(bytes(1_000_000_000), "1 GB");
650 assert_eq!(bytes(50_000_000_000), "50 GB");
651 assert_eq!(bytes(1_500_000_000), "1.5 GB");
652 assert_eq!(bytes(500_000_000), "500 MB");
653 }
654
655 #[test]
Deployments: a preview for every pull request, production on g1t.page656 fn prices_under_a_cent_keep_their_digits() {
657 assert_eq!(dollars(1512), "$0.0015");
658 assert_eq!(dollars(24_000), "$0.024");
659 assert_eq!(dollars(360_000), "$0.36");
660 assert_eq!(dollars(5_000_000), "$5.00");
661 }
662}