An open-source, faster Devin alternative
TypeScript
billing: raise 8GB tier to $35/mo and add price migration tool (#131)
Mohamed Habib5648c7bb8dcf
diff --git a/cmd/migrate-prices/main.go b/cmd/migrate-prices/main.gonew file mode 100644index 00000000..6e9c5fde--- /dev/null+++ b/cmd/migrate-prices/main.go@@ -0,0 +1,145 @@+// migrate-prices is a one-shot tool that migrates every org's subscription+// item for a given memory tier to the current (v-latest) Stripe Price ID+// returned by billing.EnsureProducts.+//+// Usage:+// DATABASE_URL=... STRIPE_SECRET_KEY=... \+// go run ./cmd/migrate-prices --tier=8192 --dry-run+// DATABASE_URL=... STRIPE_SECRET_KEY=... \+// go run ./cmd/migrate-prices --tier=8192 --live+//+// The command is idempotent: items already attached to the target price are+// skipped. Usage already accrued this cycle stays at the previous rate because+// we pass proration_behavior=none; metered events are matched to whichever+// price was attached at event time.+package main++import (+ "context"+ "flag"+ "fmt"+ "log"+ "os"++ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/stripe/stripe-go/v82"+ "github.com/stripe/stripe-go/v82/subscriptionitem"++ "github.com/opensandbox/opensandbox/internal/billing"+)++func main() {+ tier := flag.Int("tier", 8192, "memory_mb tier to migrate (must be a key in billing.TierPriceKey)")+ dryRun := flag.Bool("dry-run", true, "if true, prints what would change without calling Stripe")+ live := flag.Bool("live", false, "must be set to actually mutate Stripe; overrides --dry-run")+ flag.Parse()++ if *live {+ *dryRun = false+ }++ dbURL := os.Getenv("DATABASE_URL")+ if dbURL == "" {+ log.Fatal("DATABASE_URL is required")+ }+ stripeKey := os.Getenv("STRIPE_SECRET_KEY")+ if stripeKey == "" {+ log.Fatal("STRIPE_SECRET_KEY is required")+ }++ if _, ok := billing.TierPriceKey[*tier]; !ok {+ log.Fatalf("tier %d is not defined in billing.TierPriceKey", *tier)+ }++ ctx := context.Background()++ pool, err := pgxpool.New(ctx, dbURL)+ if err != nil {+ log.Fatalf("connect db: %v", err)+ }+ defer pool.Close()++ client := billing.NewStripeClient(stripeKey, "", "", "")+ if err := client.EnsureProducts(); err != nil {+ log.Fatalf("ensure products: %v", err)+ }++ targetPriceID, ok := client.PriceIDs[*tier]+ if !ok || targetPriceID == "" {+ log.Fatalf("no price id for tier %d after EnsureProducts", *tier)+ }+ log.Printf("target price for tier %d: %s (key=%s)", *tier, targetPriceID, billing.TierPriceKey[*tier])++ rows, err := pool.Query(ctx,+ `SELECT osi.org_id, osi.stripe_subscription_item_id, o.stripe_subscription_id+ FROM org_subscription_items osi+ JOIN orgs o ON o.id = osi.org_id+ WHERE osi.memory_mb = $1+ AND o.stripe_subscription_id IS NOT NULL`, *tier)+ if err != nil {+ log.Fatalf("query items: %v", err)+ }+ defer rows.Close()++ type target struct {+ orgID, itemID, subID string+ }+ var targets []target+ for rows.Next() {+ var t target+ if err := rows.Scan(&t.orgID, &t.itemID, &t.subID); err != nil {+ log.Fatalf("scan: %v", err)+ }+ targets = append(targets, t)+ }+ if err := rows.Err(); err != nil {+ log.Fatalf("rows err: %v", err)+ }+ log.Printf("found %d candidate subscription item(s)", len(targets))++ stripe.Key = stripeKey++ var migrated, skipped, failed int+ for _, t := range targets {+ item, err := subscriptionitem.Get(t.itemID, nil)+ if err != nil {+ log.Printf("[FAIL] org=%s item=%s fetch: %v", t.orgID, t.itemID, err)+ failed+++ continue+ }+ currentPrice := ""+ if item.Price != nil {+ currentPrice = item.Price.ID+ }+ if currentPrice == targetPriceID {+ skipped+++ continue+ }++ log.Printf("[PLAN] org=%s item=%s price %s → %s", t.orgID, t.itemID, currentPrice, targetPriceID)+ if *dryRun {+ continue+ }++ _, err = subscriptionitem.Update(t.itemID, &stripe.SubscriptionItemParams{+ Price: stripe.String(targetPriceID),+ ProrationBehavior: stripe.String("none"),+ })+ if err != nil {+ log.Printf("[FAIL] org=%s item=%s update: %v", t.orgID, t.itemID, err)+ failed+++ continue+ }+ migrated+++ }++ mode := "DRY-RUN"+ if !*dryRun {+ mode = "LIVE"+ }+ fmt.Printf("\n%s complete: migrated=%d skipped=%d failed=%d total=%d\n",+ mode, migrated, skipped, failed, len(targets))+ if failed > 0 {+ os.Exit(1)+ }+}diff --git a/internal/billing/pricing.go b/internal/billing/pricing.goindex e4106a11..e2a0570d 100644--- a/internal/billing/pricing.go+++ b/internal/billing/pricing.go@@ -8,14 +8,16 @@ import (var TierPricePerSecond = map[int]float64{1024: 0.000001080246914, // 1GB / 1 vCPU4096: 0.000005787037037, // 4GB / 1 vCPU- 8192: 0.000005015432099, // 8GB / 2 vCPU+ 8192: 0.00001350308642, // 8GB / 2 vCPU16384: 0.00002700617284, // 16GB / 4 vCPU32768: 0.0001929012346, // 32GB / 8 vCPU65536: 0.0005401234568, // 64GB / 16 vCPU}-// TierMetadataKey maps memory_mb → Stripe metadata key for price lookup.-var TierMetadataKey = map[int]string{+// TierMeterKey maps memory_mb → stable key used to derive the Stripe meter+// event_name ("sandbox_compute_" + value). NEVER change these values: meters+// hold historical usage and are shared across price versions.+var TierMeterKey = map[int]string{1024: "sandbox_1gb",4096: "sandbox_4gb",8192: "sandbox_8gb",@@ -24,12 +26,26 @@ var TierMetadataKey = map[int]string{65536: "sandbox_64gb",}+// TierPriceKey maps memory_mb → Stripe Price metadata["tier"] key.+// Bump the suffix (e.g. sandbox_8gb → sandbox_8gb_v2) whenever TierPricePerSecond+// changes for that tier: Stripe Prices are immutable, so a new key forces+// EnsureProducts to create a fresh Price at the new rate. Existing subscriptions+// must then be migrated to the new Price via cmd/migrate-prices.+var TierPriceKey = map[int]string{+ 1024: "sandbox_1gb",+ 4096: "sandbox_4gb",+ 8192: "sandbox_8gb_v2",+ 16384: "sandbox_16gb",+ 32768: "sandbox_32gb",+ 65536: "sandbox_64gb",+}+// Disk overage billing — every GB above DiskFreeAllowanceMB is metered for the// full lifetime of the sandbox (running OR hibernated, since the workspace// qcow2 still occupies host disk).const (- DiskFreeAllowanceMB = 20480 // 20GB included with every sandbox- DiskOveragePricePerGBPerSecond = 0.0000001 // ~$0.26 per GB-month+ DiskFreeAllowanceMB = 20480 // 20GB included with every sandbox+ DiskOveragePricePerGBPerSecond = 0.0000001 // ~$0.26 per GB-monthDiskOverageMetadataKey = "sandbox_disk_overage")diff --git a/internal/billing/stripe.go b/internal/billing/stripe.goindex fb623401..5ad7ef24 100644--- a/internal/billing/stripe.go+++ b/internal/billing/stripe.go@@ -61,8 +61,8 @@ func (s *StripeClient) EnsureProducts() error {existingMeters[m.EventName] = m}- for memMB, metaKey := range TierMetadataKey {- eventName := "sandbox_compute_" + metaKey+ for memMB, meterKey := range TierMeterKey {+ eventName := "sandbox_compute_" + meterKeys.MeterEventNames[memMB] = eventNameif m, ok := existingMeters[eventName]; ok {@@ -72,7 +72,7 @@ func (s *StripeClient) EnsureProducts() error {}m, err := meter.New(&stripe.BillingMeterParams{- DisplayName: stripe.String(fmt.Sprintf("Sandbox Compute %s", metaKey)),+ DisplayName: stripe.String(fmt.Sprintf("Sandbox Compute %s", meterKey)),EventName: stripe.String(eventName),DefaultAggregation: &stripe.BillingMeterDefaultAggregationParams{Formula: stripe.String(string(stripe.BillingMeterDefaultAggregationFormulaSum)),@@ -126,10 +126,10 @@ func (s *StripeClient) EnsureProducts() error {}}- for memMB, metaKey := range TierMetadataKey {- if id, ok := existingPrices[metaKey]; ok {+ for memMB, priceKey := range TierPriceKey {+ if id, ok := existingPrices[priceKey]; ok {s.PriceIDs[memMB] = id- log.Printf("billing: found existing price for %s (id=%s)", metaKey, id)+ log.Printf("billing: found existing price for %s (id=%s)", priceKey, id)continue}@@ -149,16 +149,16 @@ func (s *StripeClient) EnsureProducts() error {Meter: stripe.String(meterID),},Metadata: map[string]string{- "tier": metaKey,+ "tier": priceKey,"memory_mb": fmt.Sprintf("%d", memMB),"opensandbox": "compute",},})if err != nil {- return fmt.Errorf("create price for %s: %w", metaKey, err)+ return fmt.Errorf("create price for %s: %w", priceKey, err)}s.PriceIDs[memMB] = p.ID- log.Printf("billing: created price for %s (id=%s)", metaKey, p.ID)+ log.Printf("billing: created price for %s (id=%s)", priceKey, p.ID)}// 4. Disk overage meter + price (single dimension, billed per GB-second above 20GB).diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex 4db03c85..334ba40c 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -8,7 +8,7 @@ import {const PRICING_TIERS = [{ memory: '1 GB', vcpus: 1, bestEffort: true, perSec: 0.000001080246914 },{ memory: '4 GB', vcpus: 1, perSec: 0.000005787037037 },- { memory: '8 GB', vcpus: 2, perSec: 0.000005015432099 },+ { memory: '8 GB', vcpus: 2, perSec: 0.00001350308642 },{ memory: '16 GB', vcpus: 4, perSec: 0.00002700617284 },{ memory: '32 GB', vcpus: 8, perSec: 0.0001929012346 },{ memory: '64 GB', vcpus: 16, perSec: 0.0005401234568 },