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 look | 1 | //! 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 quotas | 2 | //! 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 look | 10 | //! |
| 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 plan | 16 | |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 17 | use g1t_contracts::billing::deployment_costs as costs; |
| Paid features: a workspace turns on Deployments with a monthly plan | 18 | use g1t_contracts::billing::*; |
| 19 | use g1t_contracts::time::rfc3339; | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 20 | use g1t_contracts::{FailureCode, Outcome, Role}; |
| Paid features: a workspace turns on Deployments with a monthly plan | 21 | use g1t_kit::now_ms; |
| 22 | use serde::Deserialize; | |
| 23 | use worker::Result; | |
| 24 | ||
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 25 | use crate::stripe::{StripeSubscription, is_missing}; |
| Paid features: a workspace turns on Deployments with a monthly plan | 26 | use crate::{Billing, Touched, members_only, optional}; |
| 27 | ||
| 28 | #[derive(Deserialize)] | |
| 29 | struct 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)] | |
| 39 | struct PlanCheckoutRow { | |
| 40 | workspace: String, | |
| 41 | created_by: String, | |
| 42 | feature: String, | |
| 43 | } | |
| 44 | ||
| 45 | fn 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 | ||
| 54 | fn 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. | |
| 64 | fn 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 put | 73 | /// `1 GB`, `50 GB`, or `500 MB`, as storage is priced (powers of ten). |
| 74 | pub(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.page | 84 | /// 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 far | 86 | pub(crate) fn dollars(micros: i64) -> String { |
| Deployments: a preview for every pull request, production on g1t.page | 87 | 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 plan | 91 | } |
| 92 | ||
| 93 | impl SubscriptionRow { | |
| 94 | fn subscription(&self) -> Option<Subscription> { | |
| 95 | Some(Subscription { | |
| 96 | feature: Feature::parse(&self.feature)?, | |
| 97 | status: status_from(&self.status), | |
| 98 | period_end: self.period_end.clone(), | |
| 99 | started_by: self.started_by.clone(), | |
| 100 | started_at: self.started_at.clone(), | |
| 101 | }) | |
| 102 | } | |
| 103 | } | |
| 104 | ||
| 105 | impl Billing { | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 106 | /// What the g1t plan costs and includes, as it is sold now. |
| 107 | pub(crate) fn plan(&self, _feature: Feature) -> Plan { | |
| 108 | let p = &self.plans; | |
| 109 | let price = |cost: i64| dollars(crate::charge_micros(cost as f64 / MICROS_PER_DOLLAR as f64, self.margin_percent)); | |
| 110 | Plan { | |
| 111 | feature: Feature::Plan, | |
| 112 | title: Feature::Plan.title().to_owned(), | |
| 113 | monthly_cents: p.plan_monthly_cents, | |
| 114 | includes: vec![ | |
| 115 | format!( | |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 116 | "{} of usage each month at cost plus {}%, used first", |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 117 | dollars(p.plan_included_micros), |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 118 | self.margin_percent |
| 119 | ), | |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 120 | "Everyone in the workspace at one price, never per person".to_owned(), |
| 121 | "Unlimited projects, previews and repositories".to_owned(), | |
| 122 | "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 look | 123 | format!( |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 124 | "Usage past {} is charged at cost plus {}%, up to your spend limit", |
| 125 | dollars(p.plan_included_micros), | |
| 126 | self.margin_percent | |
| Paid features: a workspace turns on Deployments with a monthly plan | 127 | ), |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 128 | ], |
| 129 | overage: format!( | |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 130 | "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 look | 131 | self.margin_percent, |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 132 | price(costs::MICROS_PER_BUILD_SECOND * 60), |
| 133 | price(costs::MICROS_PER_MILLION_REQUESTS), | |
| 134 | price(costs::MICROS_PER_MILLION_CPU_MS), | |
| 135 | price(costs::MICROS_PER_DOMAIN_MONTH), | |
| 136 | bytes(p.free_storage_bytes), | |
| 137 | price(crate::storage::STORAGE_MICROS_PER_GB_MONTH), | |
| 138 | thousands(p.git_included), | |
| 139 | price(crate::storage::GIT_MICROS_PER_THOUSAND), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 140 | ), |
| Paid features: a workspace turns on Deployments with a monthly plan | 141 | } |
| 142 | } | |
| 143 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 144 | /// When the workspace's plan started, and when the period paid for |
| 145 | /// ends: its first billing cycle is the first month. | |
| 146 | pub(crate) async fn plan_cycle(&self, workspace: &str) -> Result<Option<(String, Option<String>)>> { | |
| 147 | let row = match self.current(workspace, Feature::Plan).await? { | |
| 148 | Some(row) => Some(row), | |
| 149 | None => self.current(workspace, Feature::Deployments).await?, | |
| 150 | }; | |
| 151 | Ok(row | |
| 152 | .filter(|row| status_from(&row.status).on()) | |
| 153 | .map(|row| (row.started_at, row.period_end))) | |
| 154 | } | |
| 155 | ||
| Paid features: a workspace turns on Deployments with a monthly plan | 156 | async fn subscription_row(&self, workspace: &str, feature: Feature) -> Result<Option<SubscriptionRow>> { |
| 157 | self.db | |
| 158 | .prepare( | |
| 159 | "SELECT feature, subscription_id, status, period_end, started_by, started_at | |
| 160 | FROM subscriptions WHERE workspace = ? AND feature = ?", | |
| 161 | ) | |
| 162 | .bind(&[workspace.into(), feature.as_str().into()])? | |
| 163 | .first::<SubscriptionRow>(None) | |
| 164 | .await | |
| 165 | } | |
| 166 | ||
| 167 | /// Writes down what the processor says about a plan. | |
| Stripe webhooks, enterprise invoices, and sudo for both | 168 | pub(crate) async fn record( |
| Paid features: a workspace turns on Deployments with a monthly plan | 169 | &self, |
| 170 | workspace: &str, | |
| 171 | feature: Feature, | |
| 172 | subscription: &StripeSubscription, | |
| 173 | started_by: &str, | |
| 174 | ) -> Result<()> { | |
| 175 | let now = rfc3339(now_ms()); | |
| 176 | let period_end = subscription.period_end().map(|seconds| rfc3339(seconds.max(0) as u64 * 1000)); | |
| 177 | self.db | |
| 178 | .prepare( | |
| 179 | "INSERT INTO subscriptions | |
| 180 | (workspace, feature, subscription_id, status, period_end, started_by, started_at, updated_at) | |
| 181 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7) | |
| 182 | ON CONFLICT (workspace, feature) DO UPDATE SET | |
| 183 | subscription_id = ?3, status = ?4, period_end = ?5, updated_at = ?7, | |
| 184 | started_by = CASE WHEN subscription_id = ?3 THEN started_by ELSE ?6 END, | |
| 185 | started_at = CASE WHEN subscription_id = ?3 THEN started_at ELSE ?7 END", | |
| 186 | ) | |
| 187 | .bind(&[ | |
| 188 | workspace.into(), | |
| 189 | feature.as_str().into(), | |
| 190 | subscription.id.as_str().into(), | |
| 191 | status_text(status_of(subscription)).into(), | |
| 192 | optional(period_end.as_deref()), | |
| 193 | started_by.into(), | |
| 194 | now.as_str().into(), | |
| 195 | ])? | |
| 196 | .run() | |
| 197 | .await?; | |
| 198 | Ok(()) | |
| 199 | } | |
| 200 | ||
| 201 | /// A workspace's plan for a feature, asking the processor again once | |
| 202 | /// the period it last knew of is over. | |
| 203 | async fn current(&self, workspace: &str, feature: Feature) -> Result<Option<SubscriptionRow>> { | |
| 204 | let Some(row) = self.subscription_row(workspace, feature).await? else { | |
| 205 | return Ok(None); | |
| 206 | }; | |
| 207 | let stale = row.period_end.as_deref().is_none_or(|end| end <= rfc3339(now_ms()).as_str()) | |
| 208 | && row.status != "canceled"; | |
| 209 | if let (true, Some(stripe)) = (stale, &self.stripe) { | |
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 210 | match stripe.subscription(&row.subscription_id).await { |
| 211 | Ok(subscription) => self.record(workspace, feature, &subscription, &row.started_by).await?, | |
| 212 | // A plan from another Stripe account: it has ended here. | |
| 213 | Err(error) if is_missing(&error) => { | |
| 214 | self.db | |
| 215 | .prepare("UPDATE subscriptions SET status = 'canceled', updated_at = ? WHERE workspace = ? AND feature = ?") | |
| 216 | .bind(&[rfc3339(now_ms()).into(), workspace.into(), feature.as_str().into()])? | |
| 217 | .run() | |
| 218 | .await?; | |
| 219 | } | |
| 220 | Err(error) => return Err(error), | |
| 221 | } | |
| Paid features: a workspace turns on Deployments with a monthly plan | 222 | return self.subscription_row(workspace, feature).await; |
| 223 | } | |
| 224 | Ok(Some(row)) | |
| 225 | } | |
| 226 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 227 | /// The plan as a workspace sees it. A Deployments subscription from |
| 228 | /// before the plan shows as the plan until its period ends. | |
| 229 | async fn state(&self, workspace: &str, _feature: Feature) -> Result<FeatureState> { | |
| 230 | let subscription = match self.current(workspace, Feature::Plan).await?.and_then(|row| row.subscription()) { | |
| 231 | Some(plan) if plan.status.on() => Some(plan), | |
| 232 | plan => self | |
| 233 | .current(workspace, Feature::Deployments) | |
| 234 | .await? | |
| 235 | .and_then(|row| row.subscription()) | |
| 236 | .filter(|legacy| legacy.status.on()) | |
| 237 | .or(plan), | |
| 238 | }; | |
| 239 | let included = self.included(workspace).await?; | |
| Paid features: a workspace turns on Deployments with a monthly plan | 240 | Ok(FeatureState { |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 241 | plan: self.plan(Feature::Plan), |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 242 | 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 plan | 243 | subscription, |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 244 | included, |
| Paid features: a workspace turns on Deployments with a monthly plan | 245 | }) |
| 246 | } | |
| 247 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 248 | /// Whether the plan is on without its price: comped terms, an |
| 249 | /// enterprise's workspaces, or given by g1t staff. | |
| 250 | 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 put | 251 | let account = self.account_of(workspace).await?; |
| 252 | Ok(account.terms.kind == g1t_contracts::billing::TermsKind::Comped | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 253 | || account.kind == g1t_contracts::billing::AccountKind::Enterprise |
| 254 | || account.allowances.plan) | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 255 | } |
| 256 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 257 | /// Sets every Deployments subscription from before the plan to end |
| 258 | /// with its period, once, so no one pays for it and the plan both. | |
| 259 | /// Until then it counts as the plan. | |
| 260 | pub(crate) async fn retire_deployments_plans(&self) -> Result<()> { | |
| 261 | let Some(stripe) = &self.stripe else { return Ok(()) }; | |
| 262 | #[derive(Deserialize)] | |
| 263 | struct Legacy { | |
| 264 | workspace: String, | |
| 265 | subscription_id: String, | |
| 266 | started_by: String, | |
| 267 | period_end: Option<String>, | |
| 268 | } | |
| 269 | let legacy = self | |
| 270 | .db | |
| 271 | .prepare( | |
| 272 | "SELECT workspace, subscription_id, started_by, period_end FROM subscriptions | |
| 273 | WHERE feature = 'deployments' AND status = 'active' LIMIT 20", | |
| 274 | ) | |
| 275 | .all() | |
| 276 | .await? | |
| 277 | .results::<Legacy>()?; | |
| 278 | for plan in legacy { | |
| 279 | match stripe.cancel_at_period_end(&plan.subscription_id, true).await { | |
| 280 | Ok(subscription) => { | |
| 281 | self.record(&plan.workspace, Feature::Deployments, &subscription, &plan.started_by).await?; | |
| 282 | let account = self.account_of(&plan.workspace).await?; | |
| 283 | self.audit( | |
| 284 | &account.id, | |
| 285 | "migration", | |
| 286 | &format!( | |
| 287 | "{}: the Deployments plan ends {} and is not renewed; deployments come with the g1t plan now", | |
| 288 | plan.workspace, | |
| 289 | plan.period_end.as_deref().map_or("at the end of its period", |end| &end[..10]) | |
| 290 | ), | |
| 291 | "billing", | |
| 292 | ) | |
| 293 | .await?; | |
| 294 | } | |
| 295 | Err(error) if is_missing(&error) => { | |
| 296 | self.db | |
| 297 | .prepare("UPDATE subscriptions SET status = 'canceled', updated_at = ? WHERE workspace = ? AND feature = 'deployments'") | |
| 298 | .bind(&[rfc3339(now_ms()).into(), plan.workspace.as_str().into()])? | |
| 299 | .run() | |
| 300 | .await?; | |
| 301 | } | |
| 302 | Err(error) => worker::console_error!("could not end {}'s Deployments plan: {error}", plan.workspace), | |
| 303 | } | |
| 304 | } | |
| 305 | Ok(()) | |
| 306 | } | |
| 307 | ||
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 308 | /// Whether the workspace's plan for the feature is paid up. |
| 309 | pub(crate) async fn plan_on(&self, workspace: &str, feature: Feature) -> Result<bool> { | |
| 310 | Ok(self | |
| 311 | .current(workspace, feature) | |
| 312 | .await? | |
| 313 | .and_then(|row| row.subscription()) | |
| 314 | .is_some_and(|s| s.status.on())) | |
| 315 | } | |
| 316 | ||
| Paid features: a workspace turns on Deployments with a monthly plan | 317 | pub(crate) async fn features(&self, a: FeaturesArgs) -> Result<Outcome<Vec<FeatureState>>> { |
| 318 | let workspace = a.workspace.to_lowercase(); | |
| 319 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { | |
| 320 | return Ok(members_only()); | |
| 321 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 322 | Ok(Outcome::Ok(vec![self.state(&workspace, Feature::Plan).await?])) |
| Paid features: a workspace turns on Deployments with a monthly plan | 323 | } |
| 324 | ||
| 325 | pub(crate) async fn subscribe(&self, a: SubscribeArgs) -> Result<Outcome<Checkout>> { | |
| 326 | let workspace = a.workspace.to_lowercase(); | |
| 327 | if a.actor.role_in(&workspace) != Some(Role::Owner) { | |
| 328 | return Ok(Outcome::fail( | |
| 329 | FailureCode::Forbidden, | |
| 330 | "Only an owner can turn on a paid feature.", | |
| 331 | )); | |
| 332 | } | |
| 333 | let Some(stripe) = &self.stripe else { | |
| 334 | return Ok(Outcome::fail( | |
| 335 | FailureCode::Conflict, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 336 | "Payments are not set up on this g1t, so the plan is already on.", |
| Paid features: a workspace turns on Deployments with a monthly plan | 337 | )); |
| 338 | }; | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 339 | // Deployments come with the plan: asking for them starts the plan. |
| 340 | let feature = Feature::Plan; | |
| 341 | 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 put | 342 | if state.included { |
| 343 | return Ok(Outcome::fail( | |
| 344 | FailureCode::Conflict, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 345 | 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 put | 346 | )); |
| 347 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 348 | if self.plan_on(&workspace, Feature::Plan).await? { |
| 349 | 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 plan | 350 | } |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 351 | let plan = self.plan(feature); |
| Paid features: a workspace turns on Deployments with a monthly plan | 352 | 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 look | 353 | // The card from the card check: the plan starts on it at once, with |
| 354 | // no second page. A card that needs the bank's approval again goes | |
| 355 | // through Stripe's page instead. | |
| 356 | if let (Some(customer), Some(method)) = (customer.as_deref(), self.checked_card(&workspace).await?) { | |
| 357 | match stripe | |
| 358 | .subscribe_with_card(&workspace, feature.as_str(), &plan.title, plan.monthly_cents, customer, &method) | |
| 359 | .await | |
| 360 | { | |
| 361 | Ok(subscription) if matches!(subscription.status.as_str(), "active" | "trialing") => { | |
| 362 | self.record(&workspace, feature, &subscription, &a.actor.username).await?; | |
| 363 | let account = self.account_of(&workspace).await?; | |
| 364 | self.audit(&account.id, "plan", &format!("{workspace}: the g1t plan started on the checked card"), &a.actor.username) | |
| 365 | .await?; | |
| 366 | let separator = if a.return_url.contains('?') { '&' } else { '?' }; | |
| 367 | return Ok(Outcome::Ok(Checkout { url: format!("{}{separator}plan=started", a.return_url) })); | |
| 368 | } | |
| 369 | Ok(subscription) => { | |
| 370 | // Incomplete: let it lapse, and use the page. | |
| 371 | let _ = stripe.cancel_now(&subscription.id).await; | |
| 372 | } | |
| 373 | Err(error) => worker::console_log!("{workspace}: the plan could not start on the checked card: {error}"), | |
| 374 | } | |
| 375 | } | |
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 376 | let start = |customer: Option<String>| { |
| 377 | let plan = &plan; | |
| 378 | let workspace = &workspace; | |
| 379 | let return_url = &a.return_url; | |
| 380 | async move { | |
| 381 | stripe | |
| 382 | .start_subscription( | |
| 383 | workspace, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 384 | feature.as_str(), |
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 385 | &plan.title, |
| 386 | plan.monthly_cents, | |
| 387 | customer.as_deref(), | |
| 388 | return_url, | |
| 389 | ) | |
| 390 | .await | |
| 391 | } | |
| 392 | }; | |
| 393 | let session = match start(customer.clone()).await { | |
| 394 | Ok(session) => session, | |
| 395 | // A customer saved under another Stripe account: start afresh. | |
| 396 | Err(error) if customer.is_some() && is_missing(&error) => { | |
| 397 | self.forget_customer(&workspace).await?; | |
| 398 | start(None).await? | |
| 399 | } | |
| 400 | Err(error) => return Err(error), | |
| 401 | }; | |
| Paid features: a workspace turns on Deployments with a monthly plan | 402 | let Some(url) = session.url else { |
| 403 | return Err(worker::Error::RustError( | |
| 404 | "the card processor returned no payment page".into(), | |
| 405 | )); | |
| 406 | }; | |
| 407 | self.db | |
| 408 | .prepare( | |
| 409 | "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at, feature) | |
| 410 | VALUES (?, ?, ?, ?, ?, ?)", | |
| 411 | ) | |
| 412 | .bind(&[ | |
| 413 | session.id.into(), | |
| 414 | workspace.into(), | |
| 415 | plan.monthly_cents.into(), | |
| 416 | a.actor.username.into(), | |
| 417 | rfc3339(now_ms()).into(), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 418 | feature.as_str().into(), |
| Paid features: a workspace turns on Deployments with a monthly plan | 419 | ])? |
| 420 | .run() | |
| 421 | .await?; | |
| 422 | Ok(Outcome::Ok(Checkout { url })) | |
| 423 | } | |
| 424 | ||
| 425 | pub(crate) async fn confirm_subscription( | |
| 426 | &self, | |
| 427 | a: ConfirmSubscriptionArgs, | |
| 428 | ) -> Result<Outcome<FeatureState>> { | |
| 429 | let workspace = a.workspace.to_lowercase(); | |
| 430 | if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) { | |
| 431 | return Ok(members_only()); | |
| 432 | } | |
| 433 | let checkout = self | |
| 434 | .db | |
| 435 | .prepare( | |
| 436 | "SELECT workspace, created_by, feature FROM checkouts | |
| 437 | WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NOT NULL", | |
| 438 | ) | |
| 439 | .bind(&[a.session.as_str().into(), workspace.as_str().into()])? | |
| 440 | .first::<PlanCheckoutRow>(None) | |
| 441 | .await?; | |
| 442 | let (Some(stripe), Some(checkout)) = (&self.stripe, checkout) else { | |
| 443 | // 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 look | 444 | return Ok(Outcome::Ok(self.state(&workspace, Feature::Plan).await?)); |
| Paid features: a workspace turns on Deployments with a monthly plan | 445 | }; |
| 446 | let Some(feature) = Feature::parse(&checkout.feature) else { | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 447 | return Ok(Outcome::fail(FailureCode::NotFound, "No such plan.")); |
| Paid features: a workspace turns on Deployments with a monthly plan | 448 | }; |
| 449 | let session = stripe.session(&a.session).await?; | |
| 450 | if let (Some(subscription_id), true) = (&session.subscription, session.payment_status == "paid") { | |
| 451 | let claimed = self | |
| 452 | .db | |
| 453 | .prepare("UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open' RETURNING id") | |
| 454 | .bind(&[a.session.as_str().into()])? | |
| 455 | .first::<Touched>(None) | |
| 456 | .await?; | |
| 457 | if claimed.is_some() { | |
| 458 | let subscription = stripe.subscription(subscription_id).await?; | |
| 459 | self.record(&checkout.workspace, feature, &subscription, &checkout.created_by) | |
| 460 | .await?; | |
| 461 | // Keep the card's customer, so later payments need no retyping. | |
| 462 | self.db | |
| 463 | .prepare( | |
| 464 | "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) | |
| 465 | VALUES (?1, 0, ?2, ?3) | |
| 466 | ON CONFLICT (workspace) DO UPDATE SET customer_id = COALESCE(customer_id, ?2)", | |
| 467 | ) | |
| 468 | .bind(&[ | |
| 469 | checkout.workspace.as_str().into(), | |
| 470 | optional(session.customer.as_deref()), | |
| 471 | rfc3339(now_ms()).into(), | |
| 472 | ])? | |
| 473 | .run() | |
| 474 | .await?; | |
| 475 | } | |
| 476 | } | |
| 477 | Ok(Outcome::Ok(self.state(&workspace, feature).await?)) | |
| 478 | } | |
| 479 | ||
| 480 | pub(crate) async fn cancel_subscription( | |
| 481 | &self, | |
| 482 | a: CancelSubscriptionArgs, | |
| 483 | ) -> Result<Outcome<FeatureState>> { | |
| 484 | let workspace = a.workspace.to_lowercase(); | |
| 485 | if a.actor.role_in(&workspace) != Some(Role::Owner) { | |
| 486 | return Ok(Outcome::fail( | |
| 487 | FailureCode::Forbidden, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 488 | "Only an owner can change the workspace's plan.", |
| Paid features: a workspace turns on Deployments with a monthly plan | 489 | )); |
| 490 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 491 | // The plan, or a Deployments subscription from before it. |
| 492 | let row = match self.current(&workspace, Feature::Plan).await? { | |
| 493 | Some(row) if status_from(&row.status) != SubscriptionStatus::Canceled => Some((Feature::Plan, row)), | |
| 494 | _ => self.current(&workspace, Feature::Deployments).await?.map(|row| (Feature::Deployments, row)), | |
| 495 | }; | |
| 496 | let (Some(stripe), Some((feature, row))) = (&self.stripe, row) else { | |
| 497 | 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 plan | 498 | }; |
| 499 | let subscription = stripe | |
| 500 | .cancel_at_period_end(&row.subscription_id, !a.resume) | |
| 501 | .await?; | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 502 | self.record(&workspace, feature, &subscription, &row.started_by) |
| Paid features: a workspace turns on Deployments with a monthly plan | 503 | .await?; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 504 | Ok(Outcome::Ok(self.state(&workspace, Feature::Plan).await?)) |
| Paid features: a workspace turns on Deployments with a monthly plan | 505 | } |
| 506 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 507 | /// Whether the workspace has the plan, which deployments come with. |
| Paid features: a workspace turns on Deployments with a monthly plan | 508 | pub(crate) async fn has_feature(&self, a: HasFeatureArgs) -> Result<Outcome<bool>> { |
| 509 | let workspace = a.workspace.to_lowercase(); | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 510 | if self.has_plan(&workspace).await? { |
| Paid features: a workspace turns on Deployments with a monthly plan | 511 | return Ok(Outcome::Ok(true)); |
| 512 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 513 | let what = match a.feature { |
| 514 | Feature::Deployments => "Deployments come with the g1t plan", | |
| 515 | Feature::Plan => "This needs the g1t plan", | |
| 516 | }; | |
| Paid features: a workspace turns on Deployments with a monthly plan | 517 | Ok(Outcome::fail( |
| 518 | FailureCode::PaymentRequired, | |
| 519 | format!( | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 520 | "{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 plan | 521 | ), |
| 522 | )) | |
| 523 | } | |
| 524 | ||
| 525 | pub(crate) async fn charge_feature(&self, a: ChargeFeatureArgs) -> Result<Outcome<bool>> { | |
| 526 | if self.stripe.is_none() || a.cost_micros <= 0 { | |
| 527 | return Ok(Outcome::Ok(false)); | |
| 528 | } | |
| 529 | let workspace = a.workspace.to_lowercase(); | |
| 530 | let seen = self | |
| 531 | .db | |
| 532 | .prepare("SELECT id FROM ledger WHERE reference = ?") | |
| 533 | .bind(&[a.reference.as_str().into()])? | |
| 534 | .first::<Touched>(None) | |
| 535 | .await?; | |
| 536 | if seen.is_some() { | |
| 537 | return Ok(Outcome::Ok(false)); | |
| 538 | } | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 539 | let timestamp = rfc3339(now_ms()); |
| 540 | let month = crate::credits::month_of(×tamp); | |
| 541 | let mut description = a.description.clone(); | |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 542 | // A build: every second is metered, at the price book's build |
| 543 | // second, which the keeper keeps at what Cloudflare bills, rather | |
| 544 | // than at what the caller worked out. The month's build time is | |
| 545 | // tallied for the Billing page. | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 546 | let cost_micros = match a.build_seconds.filter(|s| *s > 0 && a.feature == Feature::Deployments) { |
| 547 | Some(seconds) => { | |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 548 | self.tally("build_seconds", &workspace, &month, seconds.into()).await?; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 549 | 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 quotas | 550 | 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 put | 551 | } |
| 552 | None => a.cost_micros, | |
| 553 | }; | |
| 554 | let cost = cost_micros as f64 / MICROS_PER_DOLLAR as f64; | |
| Billing accounts, terms and enterprises; g1t is no longer free | 555 | // 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 look | 556 | // and only the account's terms change it. The plan's included usage |
| 557 | // 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 put | 558 | // deployments. |
| Billing accounts, terms and enterprises; g1t is no longer free | 559 | 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 put | 560 | let drawn = self.draw(&workspace, charge, &month, &crate::credits::Eligible::default()).await?; |
| 561 | description.push_str(&drawn.note()); | |
| 562 | self.post_usage(crate::storage::UsageLine { | |
| 563 | workspace: &workspace, | |
| 564 | charged: charge - drawn.total(), | |
| 565 | description: &description, | |
| 566 | repo: a.repo.as_deref(), | |
| 567 | task: a.feature.as_str(), | |
| 568 | cost: cost_micros, | |
| 569 | reference: &a.reference, | |
| 570 | created_at: ×tamp, | |
| 571 | drawn, | |
| 572 | }) | |
| 573 | .await?; | |
| Paid features: a workspace turns on Deployments with a monthly plan | 574 | Ok(Outcome::Ok(true)) |
| 575 | } | |
| 576 | } | |
| Deployments: a preview for every pull request, production on g1t.page | 577 | |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 578 | /// `50,000`: a count as the plan reads it. |
| 579 | pub(crate) fn thousands(n: u64) -> String { | |
| 580 | let digits = n.to_string(); | |
| 581 | let mut out = String::new(); | |
| 582 | for (i, c) in digits.chars().enumerate() { | |
| 583 | if i > 0 && (digits.len() - i).is_multiple_of(3) { | |
| 584 | out.push(','); | |
| 585 | } | |
| 586 | out.push(c); | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 587 | } |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 588 | out |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 589 | } |
| 590 | ||
| Deployments: a preview for every pull request, production on g1t.page | 591 | #[cfg(test)] |
| 592 | mod tests { | |
| 593 | use super::*; | |
| 594 | ||
| 595 | #[test] | |
| status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas | 596 | fn every_build_second_is_metered_at_cost_plus_the_margin() { |
| 597 | // A 5-minute build at 15 millionths a second costs g1t 4,500, and | |
| 598 | // is charged at cost plus 20%, from the first second: there are no | |
| 599 | // included build minutes, only the plan's included usage. | |
| 600 | let cost = 300 * costs::MICROS_PER_BUILD_SECOND; | |
| 601 | assert_eq!(cost, 4_500); | |
| 602 | assert_eq!(crate::credits::with_margin(cost, 20), 5_400); | |
| 603 | } | |
| 604 | ||
| 605 | #[test] | |
| 606 | fn counts_read_with_thousands_separators() { | |
| 607 | assert_eq!(thousands(0), "0"); | |
| 608 | assert_eq!(thousands(999), "999"); | |
| 609 | assert_eq!(thousands(50_000), "50,000"); | |
| 610 | 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 put | 611 | } |
| 612 | ||
| 613 | #[test] | |
| 614 | fn storage_reads_in_gigabytes() { | |
| 615 | assert_eq!(bytes(1_000_000_000), "1 GB"); | |
| 616 | assert_eq!(bytes(50_000_000_000), "50 GB"); | |
| 617 | assert_eq!(bytes(1_500_000_000), "1.5 GB"); | |
| 618 | assert_eq!(bytes(500_000_000), "500 MB"); | |
| 619 | } | |
| 620 | ||
| 621 | #[test] | |
| Deployments: a preview for every pull request, production on g1t.page | 622 | fn prices_under_a_cent_keep_their_digits() { |
| 623 | assert_eq!(dollars(1512), "$0.0015"); | |
| 624 | assert_eq!(dollars(24_000), "$0.024"); | |
| 625 | assert_eq!(dollars(360_000), "$0.36"); | |
| 626 | assert_eq!(dollars(5_000_000), "$5.00"); | |
| 627 | } | |
| 628 | } |