Skip to content

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

g1t.sh
339 linesCodeBlameRaw
1//! A workspace renamed: everything billing keeps under its slug moves to
2//! the new one.
3//!
4//! Identity publishes `workspace.renamed` with the old and new slugs. The
5//! handler asks identity what the workspace is called now, so that a late
6//! or repeated delivery still converges on the current slug, and moves the
7//! rows of each stale slug in one D1 batch (one transaction).
8//!
9//! Rows may already exist under the current slug: usage recorded in the
10//! seconds between the rename and this event. Those are merged, never
11//! dropped where money is concerned: balances are summed, sandbox seconds
12//! are summed, and owners' limits are kept field by field.
13
14use g1t_contracts::events::{Event, WorkspaceRenamed};
15use g1t_contracts::identity::UsernamesArgs;
16use serde::Deserialize;
17use serde_json::Value;
18use worker::wasm_bindgen::JsValue;
19use worker::{Fetcher, Result};
20
21use crate::Billing;
22use crate::accounts::own_account;
23
24/// The event this module handles.
25pub(crate) const RENAMED: &str = "workspace.renamed";
26
27/// The statements that move one stale slug's rows to the current slug, in
28/// order. Parameters: `?1` the current slug, `?2` the stale one, `?3` and
29/// `?4` their own billing accounts (`ws_<slug>`).
30///
31/// Every statement is a no-op once the stale slug has no rows, so running
32/// the batch again changes nothing.
33pub(crate) const STATEMENTS: &[&str] = &[
34 // Plain rows: many per workspace, keyed by their own id.
35 "UPDATE ledger SET workspace = ?1 WHERE workspace = ?2",
36 "UPDATE runs SET workspace = ?1 WHERE workspace = ?2",
37 "UPDATE credit_grants SET workspace = ?1 WHERE workspace = ?2",
38 "UPDATE checkouts SET workspace = ?1 WHERE workspace = ?2",
39 "UPDATE ai_reloads SET workspace = ?1 WHERE workspace = ?2",
40 "UPDATE gateway_requests SET workspace = ?1 WHERE workspace = ?2",
41 // Auto-reload's settings: the stale slug's, when the current has none.
42 "INSERT OR IGNORE INTO ai_reload (workspace, enabled, threshold_micros, target_micros, monthly_max_micros, updated_by, updated_at, failed_at, error)
43 SELECT ?1, enabled, threshold_micros, target_micros, monthly_max_micros, updated_by, updated_at, failed_at, error FROM ai_reload WHERE workspace = ?2",
44 "DELETE FROM ai_reload WHERE workspace = ?2",
45 "UPDATE workspace_invoices SET workspace = ?1 WHERE workspace = ?2",
46 "UPDATE sales_notes SET workspace = ?1 WHERE workspace = ?2",
47 // Repositories are named `<slug>/<name>`. Compared exactly rather than
48 // with LIKE, so nothing in a slug is read as a wildcard.
49 "UPDATE ledger SET repo = ?1 || substr(repo, length(?2) + 1) WHERE substr(repo, 1, length(?2) + 1) = ?2 || '/'",
50 "UPDATE runs SET repo = ?1 || substr(repo, length(?2) + 1) WHERE substr(repo, 1, length(?2) + 1) = ?2 || '/'",
51 // The balance is the sum of the ledger, and both ledgers are now the
52 // current slug's: the balances add. The older customer (with the card
53 // and the payment history) is kept when both have one.
54 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
55 SELECT ?1, balance_micros, customer_id, created_at FROM accounts WHERE workspace = ?2
56 ON CONFLICT (workspace) DO UPDATE SET
57 balance_micros = accounts.balance_micros + excluded.balance_micros,
58 customer_id = COALESCE(excluded.customer_id, accounts.customer_id),
59 created_at = MIN(accounts.created_at, excluded.created_at)",
60 "DELETE FROM accounts WHERE workspace = ?2",
61 // Replaced on each report with the month's whole figure: the newer
62 // report wins.
63 "INSERT INTO pending_usage (workspace, source, month, charge_micros, cost_micros, charged_at, updated_at, detail)
64 SELECT ?1, source, month, charge_micros, cost_micros, charged_at, updated_at, detail FROM pending_usage WHERE workspace = ?2
65 ON CONFLICT (workspace, source, month) DO UPDATE SET
66 charge_micros = CASE WHEN excluded.updated_at > pending_usage.updated_at
67 THEN excluded.charge_micros ELSE pending_usage.charge_micros END,
68 cost_micros = CASE WHEN excluded.updated_at > pending_usage.updated_at
69 THEN excluded.cost_micros ELSE pending_usage.cost_micros END,
70 detail = CASE WHEN excluded.updated_at > pending_usage.updated_at
71 THEN excluded.detail ELSE pending_usage.detail END,
72 charged_at = COALESCE(pending_usage.charged_at, excluded.charged_at),
73 updated_at = MAX(pending_usage.updated_at, excluded.updated_at)",
74 "DELETE FROM pending_usage WHERE workspace = ?2",
75 // What a test-mode detach kept as never charged: the larger stays, so
76 // a rename never charges what was written off.
77 "INSERT INTO pending_baselines (workspace, source, month, cost_micros, charge_micros, created_at)
78 SELECT ?1, source, month, cost_micros, charge_micros, created_at FROM pending_baselines WHERE workspace = ?2
79 ON CONFLICT (workspace, source, month) DO UPDATE SET
80 cost_micros = MAX(pending_baselines.cost_micros, excluded.cost_micros),
81 charge_micros = MAX(pending_baselines.charge_micros, excluded.charge_micros)",
82 "DELETE FROM pending_baselines WHERE workspace = ?2",
83 // Monthly allowances drawn by the workspace (its plan's included usage,
84 // its build time) add up; a repository's share of the open-source pool
85 // follows the repository's new name.
86 "INSERT INTO allowance_use (kind, scope, month, used)
87 SELECT kind, ?1, month, used FROM allowance_use WHERE scope = ?2
88 ON CONFLICT (kind, scope, month) DO UPDATE SET used = allowance_use.used + excluded.used",
89 "DELETE FROM allowance_use WHERE scope = ?2",
90 "UPDATE OR IGNORE allowance_use SET scope = ?1 || substr(scope, length(?2) + 1)
91 WHERE kind = 'oss_repo' AND substr(scope, 1, length(?2) + 1) = ?2 || '/'",
92 // One trial grant per workspace: the current slug's stays if it has one.
93 "UPDATE OR IGNORE trial_grants SET workspace = ?1 WHERE workspace = ?2",
94 "DELETE FROM trial_grants WHERE workspace = ?2",
95 "UPDATE OR IGNORE storage_days SET workspace = ?1 WHERE workspace = ?2",
96 "DELETE FROM storage_days WHERE workspace = ?2",
97 "UPDATE OR IGNORE package_storage_days SET workspace = ?1 WHERE workspace = ?2",
98 "DELETE FROM package_storage_days WHERE workspace = ?2",
99 // Month-end snapshots, by day: the current slug's stays if it has one.
100 "UPDATE OR IGNORE pending_days SET workspace = ?1 WHERE workspace = ?2",
101 "DELETE FROM pending_days WHERE workspace = ?2",
102 // Model tokens, by day, person, session and model: the counts add.
103 "INSERT INTO token_usage (day, workspace, person, session, model, tier, input, output, cache_read, cache_write, requests)
104 SELECT day, ?1, person, session, model, tier, input, output, cache_read, cache_write, requests FROM token_usage WHERE workspace = ?2
105 ON CONFLICT (day, workspace, person, session, model) DO UPDATE SET
106 input = token_usage.input + excluded.input,
107 output = token_usage.output + excluded.output,
108 cache_read = token_usage.cache_read + excluded.cache_read,
109 cache_write = token_usage.cache_write + excluded.cache_write,
110 requests = token_usage.requests + excluded.requests",
111 "DELETE FROM token_usage WHERE workspace = ?2",
112 // Price notices sent, one per version: told once is told.
113 "UPDATE OR IGNORE price_notices SET workspace = ?1 WHERE workspace = ?2",
114 "DELETE FROM price_notices WHERE workspace = ?2",
115 "UPDATE OR IGNORE closed_workspaces SET workspace = ?1 WHERE workspace = ?2",
116 "DELETE FROM closed_workspaces WHERE workspace = ?2",
117 // The margin figures and counts are redone each day from the ledger and
118 // the meters; moved so the days between keep adding up.
119 "UPDATE OR IGNORE workspace_costs SET workspace = ?1 WHERE workspace = ?2",
120 "DELETE FROM workspace_costs WHERE workspace = ?2",
121 "UPDATE OR IGNORE own_counts SET workspace = ?1 WHERE workspace = ?2",
122 "DELETE FROM own_counts WHERE workspace = ?2",
123 "UPDATE margin_alerts SET subject = ?1 WHERE kind = 'workspace' AND subject = ?2",
124 // What testing resets wiped that g1t paid for: kept, under the new slug
125 // (a row under both slugs at the same instant cannot happen).
126 "UPDATE OR IGNORE reset_costs SET workspace = ?1 WHERE workspace = ?2",
127 // Holds, spikes, requests and the plan's payments: many per workspace.
128 "UPDATE reservations SET workspace = ?1 WHERE workspace = ?2",
129 "UPDATE reservations SET repo = ?1 || substr(repo, length(?2) + 1) WHERE substr(repo, 1, length(?2) + 1) = ?2 || '/'",
130 "UPDATE spikes SET workspace = ?1 WHERE workspace = ?2",
131 "UPDATE limit_requests SET workspace = ?1 WHERE workspace = ?2",
132 "UPDATE plan_payments SET workspace = ?1 WHERE workspace = ?2",
133 "UPDATE disputes SET workspace = ?1 WHERE workspace = ?2",
134 "UPDATE tax_and_fees SET workspace = ?1 WHERE workspace = ?2",
135 // One card check per workspace; alerts sent, one per level a month.
136 "UPDATE OR IGNORE card_checks SET workspace = ?1 WHERE workspace = ?2",
137 "DELETE FROM card_checks WHERE workspace = ?2",
138 "UPDATE OR IGNORE alerts_sent SET workspace = ?1 WHERE workspace = ?2",
139 "DELETE FROM alerts_sent WHERE workspace = ?2",
140 // Limits, field by field: a ceiling or an owner's spend limit set under
141 // either slug is kept (the current slug's if both), a stop for a
142 // declined card stays, and the highest warning this month is kept.
143 "INSERT INTO limits (workspace, ceiling_micros, spend_limit_micros, spend_limit_full, autopay_failed_at,
144 autopay_error, warned_month, warned_level, declined_told_at, updated_at,
145 max_ceiling_micros, granted_ceiling_micros, raised_at, dispute_owed_micros)
146 SELECT ?1, ceiling_micros, spend_limit_micros, spend_limit_full, autopay_failed_at,
147 autopay_error, warned_month, warned_level, declined_told_at, updated_at,
148 max_ceiling_micros, granted_ceiling_micros, raised_at, dispute_owed_micros
149 FROM limits WHERE workspace = ?2
150 ON CONFLICT (workspace) DO UPDATE SET
151 dispute_owed_micros = limits.dispute_owed_micros + excluded.dispute_owed_micros,
152 ceiling_micros = COALESCE(limits.ceiling_micros, excluded.ceiling_micros),
153 max_ceiling_micros = MAX(COALESCE(limits.max_ceiling_micros, 0), COALESCE(excluded.max_ceiling_micros, 0)),
154 granted_ceiling_micros = MAX(COALESCE(limits.granted_ceiling_micros, 0), COALESCE(excluded.granted_ceiling_micros, 0)),
155 raised_at = COALESCE(limits.raised_at, excluded.raised_at),
156 spend_limit_micros = CASE WHEN limits.spend_limit_micros IS NOT NULL OR limits.spend_limit_full = 1
157 THEN limits.spend_limit_micros ELSE excluded.spend_limit_micros END,
158 spend_limit_full = CASE WHEN limits.spend_limit_micros IS NOT NULL OR limits.spend_limit_full = 1
159 THEN limits.spend_limit_full ELSE excluded.spend_limit_full END,
160 autopay_error = CASE WHEN limits.autopay_failed_at IS NOT NULL
161 THEN limits.autopay_error ELSE excluded.autopay_error END,
162 autopay_failed_at = COALESCE(limits.autopay_failed_at, excluded.autopay_failed_at),
163 warned_level = CASE WHEN excluded.warned_month > COALESCE(limits.warned_month, '') THEN excluded.warned_level
164 WHEN excluded.warned_month = limits.warned_month THEN MAX(limits.warned_level, excluded.warned_level)
165 ELSE limits.warned_level END,
166 warned_month = COALESCE(MAX(limits.warned_month, excluded.warned_month), limits.warned_month, excluded.warned_month),
167 declined_told_at = COALESCE(MAX(limits.declined_told_at, excluded.declined_told_at), limits.declined_told_at, excluded.declined_told_at),
168 updated_at = MAX(limits.updated_at, excluded.updated_at)",
169 "DELETE FROM limits WHERE workspace = ?2",
170 // Plans: one per feature. A live plan under the stale slug replaces a
171 // canceled one under the current slug; otherwise the current one stays.
172 "DELETE FROM subscriptions WHERE workspace = ?1 AND status = 'canceled'
173 AND feature IN (SELECT feature FROM subscriptions WHERE workspace = ?2 AND status <> 'canceled')",
174 "UPDATE OR IGNORE subscriptions SET workspace = ?1 WHERE workspace = ?2",
175 "DELETE FROM subscriptions WHERE workspace = ?2",
176 // Records of one per workspace (per month): the current slug's stays
177 // if it has one.
178 "UPDATE OR IGNORE month_closes SET workspace = ?1 WHERE workspace = ?2",
179 "DELETE FROM month_closes WHERE workspace = ?2",
180 "UPDATE OR IGNORE account_members SET workspace = ?1 WHERE workspace = ?2",
181 "DELETE FROM account_members WHERE workspace = ?2",
182 "UPDATE OR IGNORE sales_records SET workspace = ?1 WHERE workspace = ?2",
183 "DELETE FROM sales_records WHERE workspace = ?2",
184 // An enterprise invoice's line for the workspace: amounts add.
185 "INSERT INTO enterprise_invoice_lines (invoice_id, workspace, amount_micros)
186 SELECT invoice_id, ?1, amount_micros FROM enterprise_invoice_lines WHERE workspace = ?2
187 ON CONFLICT (invoice_id, workspace) DO UPDATE SET
188 amount_micros = enterprise_invoice_lines.amount_micros + excluded.amount_micros",
189 "DELETE FROM enterprise_invoice_lines WHERE workspace = ?2",
190 // The workspace's own billing account, `ws_<slug>`. Terms set by staff
191 // are kept: a standard row under the current slug gives way to the
192 // stale one; two with terms keep the current one.
193 "DELETE FROM billing_accounts WHERE id = ?3 AND terms_kind = 'standard'
194 AND EXISTS (SELECT 1 FROM billing_accounts WHERE id = ?4)",
195 "UPDATE OR IGNORE billing_accounts SET id = ?3, name = CASE WHEN name = ?2 THEN ?1 ELSE name END WHERE id = ?4",
196 "DELETE FROM billing_accounts WHERE id = ?4",
197 "UPDATE admin_actions SET account = ?3 WHERE account = ?4",
198 "UPDATE OR IGNORE budget_alerts SET account = ?3 WHERE account = ?4",
199 "DELETE FROM budget_alerts WHERE account = ?4",
200 "UPDATE account_members SET account_id = ?3 WHERE account_id = ?4",
201 "UPDATE enterprise_invoices SET account_id = ?3 WHERE account_id = ?4",
202];
203
204/// The highest `?N` a statement names: how many values it is bound with.
205pub(crate) fn parameters(sql: &str) -> usize {
206 let bytes = sql.as_bytes();
207 let mut highest = 0;
208 for (i, byte) in bytes.iter().enumerate() {
209 if *byte == b'?' {
210 let digits: String = bytes[i + 1..].iter().take_while(|b| b.is_ascii_digit()).map(|b| *b as char).collect();
211 highest = highest.max(digits.parse().unwrap_or(0));
212 }
213 }
214 highest
215}
216
217/// The values `STATEMENTS` are bound with, in parameter order.
218pub(crate) fn values(stale: &str, current: &str) -> [String; 4] {
219 [current.to_owned(), stale.to_owned(), own_account(current), own_account(stale)]
220}
221
222impl Billing {
223 /// Handles one event from the bus; every type but a rename is ignored.
224 pub(crate) async fn on_event(&self, identity: Option<&Fetcher>, event: &Event) -> Result<()> {
225 if event.kind != RENAMED {
226 return Ok(());
227 }
228 let renamed: WorkspaceRenamed = serde_json::from_value(event.data.clone())?;
229 let current = match identity {
230 Some(identity) => {
231 let names: std::collections::HashMap<String, String> = g1t_kit::call(
232 identity,
233 "usernames",
234 &UsernamesArgs { ids: vec![renamed.workspace_id.clone()] },
235 )
236 .await?;
237 names.get(&renamed.workspace_id).cloned().unwrap_or_else(|| renamed.to.clone())
238 }
239 None => renamed.to.clone(),
240 };
241 self.rename_workspace(&renamed, &current.to_lowercase()).await
242 }
243
244 /// Moves every row of the rename's stale slugs to `current`.
245 pub(crate) async fn rename_workspace(&self, renamed: &WorkspaceRenamed, current: &str) -> Result<()> {
246 for stale in renamed.stale_slugs(current) {
247 let stale = stale.to_lowercase();
248 if stale.is_empty() || stale == current {
249 continue;
250 }
251 let values = values(&stale, current);
252 let mut batch = Vec::with_capacity(STATEMENTS.len());
253 for sql in STATEMENTS {
254 let binds: Vec<JsValue> = values[..parameters(sql)].iter().map(|v| JsValue::from(v.as_str())).collect();
255 batch.push(self.db.prepare(*sql).bind(&binds)?);
256 }
257 self.db.batch(batch).await?;
258 self.rename_customer(&stale, current).await;
259 }
260 Ok(())
261 }
262
263 /// The Stripe customer carries the slug as its name and metadata; both
264 /// follow the rename. A name someone changed at Stripe is left alone.
265 /// Best effort: a failure here moves no money.
266 async fn rename_customer(&self, stale: &str, current: &str) {
267 let Some(stripe) = &self.stripe else { return };
268 let Ok(Some(customer)) = self.row(current).await.map(|row| row.and_then(|row| row.customer_id)) else {
269 return;
270 };
271 #[derive(Deserialize)]
272 struct Customer {
273 name: Option<String>,
274 metadata: Option<std::collections::HashMap<String, String>>,
275 }
276 let path = format!("/customers/{customer}");
277 let found: Customer = match stripe.get(&path).await {
278 Ok(found) => found,
279 Err(error) => {
280 worker::console_error!("renaming {stale} at Stripe: could not read {customer}: {error}");
281 return;
282 }
283 };
284 let mut fields = vec![];
285 if found.name.as_deref() == Some(stale) {
286 fields.push(("name", current.to_owned()));
287 }
288 let tagged = found.metadata.as_ref().and_then(|m| m.get("workspace")).map(String::as_str);
289 if tagged != Some(current) {
290 fields.push(("metadata[workspace]", current.to_owned()));
291 }
292 if fields.is_empty() {
293 return;
294 }
295 if let Err(error) = stripe.post::<Value>(&path, &fields).await {
296 worker::console_error!("renaming {stale} at Stripe: could not update {customer}: {error}");
297 }
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304
305 #[test]
306 fn every_statement_is_bound_with_what_it_names() {
307 for sql in STATEMENTS {
308 let n = parameters(sql);
309 assert!((1..=4).contains(&n), "{sql}");
310 // Numbered only: a bare `?` would take the wrong value.
311 assert!(!sql.contains("? ") && !sql.ends_with('?'), "{sql}");
312 }
313 assert_eq!(parameters("UPDATE t SET a = ?1 WHERE b = ?2"), 2);
314 assert_eq!(parameters("UPDATE t SET a = ?3 WHERE b = ?4"), 4);
315 }
316
317 #[test]
318 fn the_values_name_both_slugs_and_their_accounts() {
319 assert_eq!(values("acme", "acme-co"), ["acme-co".to_owned(), "acme".into(), "ws_acme-co".into(), "ws_acme".into()]);
320 }
321
322 #[test]
323 fn every_table_keyed_by_a_slug_is_moved() {
324 let all = STATEMENTS.join("\n");
325 for table in [
326 "ledger", "runs", "checkouts", "workspace_invoices", "sales_notes", "accounts",
327 "pending_usage", "pending_baselines", "limits", "subscriptions", "month_closes", "account_members", "sales_records",
328 "enterprise_invoice_lines", "billing_accounts", "admin_actions", "enterprise_invoices",
329 "allowance_use", "trial_grants", "credit_grants", "storage_days",
330 "reservations", "spikes", "limit_requests", "plan_payments", "card_checks", "alerts_sent",
331 "package_storage_days", "pending_days", "token_usage", "price_notices", "closed_workspaces",
332 "workspace_costs", "own_counts", "ai_reload", "ai_reloads", "tax_and_fees", "reset_costs",
333 ] {
334 assert!(all.contains(&format!("FROM {table} WHERE workspace = ?2"))
335 || all.contains(&format!("UPDATE {table} SET"))
336 || all.contains(&format!("UPDATE OR IGNORE {table} SET")), "{table}");
337 }
338 }
339}