An open-source, faster Devin alternative
TypeScript
billing: meter disk usage above 20GB included allowance (#129)
Mohamed Habib4891b056b268
diff --git a/cmd/backfill-disk-overage/main.go b/cmd/backfill-disk-overage/main.gonew file mode 100644index 00000000..c336e576--- /dev/null+++ b/cmd/backfill-disk-overage/main.go@@ -0,0 +1,149 @@+// backfill-disk-overage attaches the disk-overage metered price to every+// existing pro-tier subscription that was created before disk overage billing+// shipped. Idempotent — safe to re-run.+//+// Usage:+//+// DATABASE_URL=postgres://... STRIPE_SECRET_KEY=sk_live_... \+// go run ./cmd/backfill-disk-overage [--dry-run]+//+// New subscriptions created via the normal checkout flow already include the+// disk overage price (see billing.StripeClient.CreateSubscription), so this+// script only needs to run once after deploying the disk-overage migration.+package main++import (+ "context"+ "flag"+ "fmt"+ "log"+ "os"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/stripe/stripe-go/v82"+ "github.com/stripe/stripe-go/v82/subscription"+ "github.com/stripe/stripe-go/v82/subscriptionitem"++ "github.com/opensandbox/opensandbox/internal/billing"+)++func main() {+ dryRun := flag.Bool("dry-run", false, "report what would change without calling Stripe write APIs")+ flag.Parse()++ 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")+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)+ defer cancel()++ stripe.Key = stripeKey+ client := billing.NewStripeClient(stripeKey, "", "", "")+ if err := client.EnsureProducts(); err != nil {+ log.Fatalf("ensure products: %v", err)+ }+ if client.DiskOveragePriceID == "" {+ log.Fatal("disk overage price not provisioned by EnsureProducts — aborting")+ }+ log.Printf("disk overage price id: %s", client.DiskOveragePriceID)++ conn, err := pgx.Connect(ctx, dbURL)+ if err != nil {+ log.Fatalf("connect db: %v", err)+ }+ defer conn.Close(ctx)++ rows, err := conn.Query(ctx,+ `SELECT id, name, stripe_subscription_id+ FROM orgs+ WHERE plan = 'pro'+ AND stripe_subscription_id IS NOT NULL`)+ if err != nil {+ log.Fatalf("query orgs: %v", err)+ }+ defer rows.Close()++ type target struct {+ orgID, name, subID string+ }+ var targets []target+ for rows.Next() {+ var t target+ if err := rows.Scan(&t.orgID, &t.name, &t.subID); err != nil {+ log.Fatalf("scan: %v", err)+ }+ targets = append(targets, t)+ }+ if err := rows.Err(); err != nil {+ log.Fatalf("rows: %v", err)+ }++ log.Printf("found %d pro org(s) with active subscriptions", len(targets))++ var attached, alreadyHad, failed int+ for _, t := range targets {+ sub, err := subscription.Get(t.subID, &stripe.SubscriptionParams{+ Expand: []*string{stripe.String("items.data.price")},+ })+ if err != nil {+ log.Printf("org %s (%s): fetch subscription %s: %v", t.orgID, t.name, t.subID, err)+ failed+++ continue+ }++ hasDisk := false+ for _, it := range sub.Items.Data {+ if it.Price != nil && it.Price.ID == client.DiskOveragePriceID {+ hasDisk = true+ break+ }+ }+ if hasDisk {+ alreadyHad+++ continue+ }++ if *dryRun {+ log.Printf("[dry-run] org %s (%s): would attach disk overage price to sub %s", t.orgID, t.name, t.subID)+ attached+++ continue+ }++ newItem, err := subscriptionitem.New(&stripe.SubscriptionItemParams{+ Subscription: stripe.String(t.subID),+ Price: stripe.String(client.DiskOveragePriceID),+ // ProrationBehavior=none — metered prices have no proration anyway+ // and we don't want any surprise immediate invoice.+ ProrationBehavior: stripe.String("none"),+ })+ if err != nil {+ log.Printf("org %s (%s): attach disk overage to sub %s: %v", t.orgID, t.name, t.subID, err)+ failed+++ continue+ }+ log.Printf("org %s (%s): attached disk overage item %s to sub %s", t.orgID, t.name, newItem.ID, t.subID)+ attached+++ }++ fmt.Println()+ fmt.Println("=== summary ===")+ fmt.Printf("orgs scanned: %d\n", len(targets))+ fmt.Printf("already had disk price: %d\n", alreadyHad)+ if *dryRun {+ fmt.Printf("would attach (dry-run): %d\n", attached)+ } else {+ fmt.Printf("attached: %d\n", attached)+ }+ fmt.Printf("failed: %d\n", failed)++ if failed > 0 {+ os.Exit(1)+ }+}diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex a8f888da..c7d1dcc0 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -248,7 +248,8 @@ func main() {if err != nil || orgID == "" {return}- _ = st.RecordScaleEvent(context.Background(), sandboxID, orgID, memoryMB, cpuPercent)+ // Disk doesn't change on memory scale; pass 0 to inherit disk_mb from the prior event.+ _ = st.RecordScaleEvent(context.Background(), sandboxID, orgID, memoryMB, cpuPercent, 0)})}}diff --git a/internal/api/dashboard_billing.go b/internal/api/dashboard_billing.goindex 34749c84..cabf20a4 100644--- a/internal/api/dashboard_billing.go+++ b/internal/api/dashboard_billing.go@@ -76,11 +76,13 @@ func (s *Server) billingGet(c echo.Context) error {type tierUsage struct {MemoryMB int `json:"memoryMB"`VCPUs int `json:"vcpus"`+ DiskMB int `json:"diskMB"`TotalSeconds float64 `json:"totalSeconds"`CostCents float64 `json:"costCents"`}var tiers []tierUsagevar totalCost float64+ var diskOverageGBSeconds float64for _, u := range usage {rate := billing.TierPricePerSecond[u.MemoryMB]cost := u.TotalSeconds * rate * 100@@ -88,9 +90,19 @@ func (s *Server) billingGet(c echo.Context) error {tiers = append(tiers, tierUsage{MemoryMB: u.MemoryMB,VCPUs: u.CPUPercent / 100,+ DiskMB: u.DiskMB,TotalSeconds: u.TotalSeconds,CostCents: cost,})+ diskOverageGBSeconds += billing.DiskOverageGBSeconds(u)+ }+ diskOverageCostCents := diskOverageGBSeconds * billing.DiskOveragePricePerGBPerSecond * 100+ totalCost += diskOverageCostCents+ diskOverage := map[string]interface{}{+ "freeAllowanceMB": billing.DiskFreeAllowanceMB,+ "pricePerGBPerSecond": billing.DiskOveragePricePerGBPerSecond,+ "gbSeconds": diskOverageGBSeconds,+ "costCents": diskOverageCostCents,}// Stripe balance for pro users@@ -109,6 +121,7 @@ func (s *Server) billingGet(c echo.Context) error {"hasPaymentMethod": org.StripeCustomerID != nil,"currentUsage": map[string]interface{}{"tiers": tiers,+ "diskOverage": diskOverage,"totalCostCents": totalCost,},})diff --git a/internal/billing/pricing.go b/internal/billing/pricing.goindex 816b98fb..e4106a11 100644--- a/internal/billing/pricing.go+++ b/internal/billing/pricing.go@@ -24,15 +24,34 @@ var TierMetadataKey = map[int]string{65536: "sandbox_64gb",}-// CalculateUsageCostCents returns total cost in cents from usage summaries.+// 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+ DiskOverageMetadataKey = "sandbox_disk_overage"+)++// DiskOverageGBSeconds returns the chargeable GB-seconds for one usage summary+// row (zero if the sandbox stayed within the free allowance).+func DiskOverageGBSeconds(s db.OrgUsageSummary) float64 {+ overageMB := s.DiskMB - DiskFreeAllowanceMB+ if overageMB <= 0 || s.TotalSeconds <= 0 {+ return 0+ }+ return float64(overageMB) / 1024.0 * s.TotalSeconds+}++// CalculateUsageCostCents returns total cost in cents from usage summaries —+// memory tier compute plus per-GB-second disk overage above 20GB.func CalculateUsageCostCents(summaries []db.OrgUsageSummary) float64 {var totalUSD float64for _, s := range summaries {- rate, ok := TierPricePerSecond[s.MemoryMB]- if !ok {- continue+ if rate, ok := TierPricePerSecond[s.MemoryMB]; ok {+ totalUSD += s.TotalSeconds * rate}- totalUSD += s.TotalSeconds * rate+ totalUSD += DiskOverageGBSeconds(s) * DiskOveragePricePerGBPerSecond}return totalUSD * 100.0}diff --git a/internal/billing/stripe.go b/internal/billing/stripe.goindex 45714329..fb623401 100644--- a/internal/billing/stripe.go+++ b/internal/billing/stripe.go@@ -29,6 +29,10 @@ type StripeClient struct {PriceIDs map[int]string// Maps memoryMB → meter event_name (e.g. "sandbox_compute_4gb")MeterEventNames map[int]string++ // Disk overage meter / price (single dimension: GB-seconds above 20GB).+ DiskOveragePriceID string+ DiskOverageMeterEventName string}// NewStripeClient creates a new Stripe client.@@ -157,6 +161,66 @@ func (s *StripeClient) EnsureProducts() error {log.Printf("billing: created price for %s (id=%s)", metaKey, p.ID)}+ // 4. Disk overage meter + price (single dimension, billed per GB-second above 20GB).+ diskEventName := "sandbox_compute_" + DiskOverageMetadataKey+ s.DiskOverageMeterEventName = diskEventName++ var diskMeterID string+ if m, ok := existingMeters[diskEventName]; ok {+ diskMeterID = m.ID+ log.Printf("billing: found existing disk overage meter %s (id=%s)", diskEventName, diskMeterID)+ } else {+ m, err := meter.New(&stripe.BillingMeterParams{+ DisplayName: stripe.String("Sandbox Disk Overage (GB-seconds)"),+ EventName: stripe.String(diskEventName),+ DefaultAggregation: &stripe.BillingMeterDefaultAggregationParams{+ Formula: stripe.String(string(stripe.BillingMeterDefaultAggregationFormulaSum)),+ },+ CustomerMapping: &stripe.BillingMeterCustomerMappingParams{+ EventPayloadKey: stripe.String("stripe_customer_id"),+ Type: stripe.String(string(stripe.BillingMeterCustomerMappingTypeByID)),+ },+ ValueSettings: &stripe.BillingMeterValueSettingsParams{+ EventPayloadKey: stripe.String("value"),+ },+ })+ if err != nil {+ return fmt.Errorf("create disk overage meter: %w", err)+ }+ diskMeterID = m.ID+ log.Printf("billing: created disk overage meter %s (id=%s)", diskEventName, diskMeterID)+ }++ if id, ok := existingPrices[DiskOverageMetadataKey]; ok {+ s.DiskOveragePriceID = id+ log.Printf("billing: found existing disk overage price (id=%s)", id)+ } else {+ ratePerGBPerSecondCents := DiskOveragePricePerGBPerSecond * 100+ truncated := math.Floor(ratePerGBPerSecondCents*1e12) / 1e12++ p, err := price.New(&stripe.PriceParams{+ Product: stripe.String(productID),+ Currency: stripe.String("usd"),+ UnitAmountDecimal: stripe.Float64(truncated),+ BillingScheme: stripe.String(string(stripe.PriceBillingSchemePerUnit)),+ Recurring: &stripe.PriceRecurringParams{+ Interval: stripe.String(string(stripe.PriceRecurringIntervalMonth)),+ UsageType: stripe.String(string(stripe.PriceRecurringUsageTypeMetered)),+ Meter: stripe.String(diskMeterID),+ },+ Metadata: map[string]string{+ "tier": DiskOverageMetadataKey,+ "opensandbox": "compute",+ "unit": "gb_second_above_20gb",+ },+ })+ if err != nil {+ return fmt.Errorf("create disk overage price: %w", err)+ }+ s.DiskOveragePriceID = p.ID+ log.Printf("billing: created disk overage price (id=%s)", p.ID)+ }+return nil}@@ -204,6 +268,11 @@ func (s *StripeClient) CreateSubscription(customerID string) (string, map[int]stPrice: stripe.String(priceID),})}+ if s.DiskOveragePriceID != "" {+ items = append(items, &stripe.SubscriptionItemsParams{+ Price: stripe.String(s.DiskOveragePriceID),+ })+ }sub, err := subscription.New(&stripe.SubscriptionParams{Customer: stripe.String(customerID),@@ -262,6 +331,26 @@ func (s *StripeClient) ReportUsage(customerID string, memoryMB int, seconds int6return nil}+// ReportDiskOverageUsage sends a meter event for disk overage GB-seconds+// (provisioned disk above 20GB, integrated over time).+func (s *StripeClient) ReportDiskOverageUsage(customerID string, gbSeconds int64, timestamp int64) error {+ if s.DiskOverageMeterEventName == "" {+ return fmt.Errorf("disk overage meter not provisioned")+ }+ _, err := meterevent.New(&stripe.BillingMeterEventParams{+ EventName: stripe.String(s.DiskOverageMeterEventName),+ Timestamp: stripe.Int64(timestamp),+ Payload: map[string]string{+ "stripe_customer_id": customerID,+ "value": fmt.Sprintf("%d", gbSeconds),+ },+ })+ if err != nil {+ return fmt.Errorf("report disk overage: %w", err)+ }+ return nil+}+// GetCustomerBalance returns the customer's balance in cents (negative = credit).func (s *StripeClient) GetCustomerBalance(customerID string) (int64, error) {c, err := customer.Get(customerID, nil)diff --git a/internal/billing/usage_reporter.go b/internal/billing/usage_reporter.goindex 21970cb8..4a67f166 100644--- a/internal/billing/usage_reporter.go+++ b/internal/billing/usage_reporter.go@@ -86,16 +86,26 @@ func (r *UsageReporter) reportOrg(ctx context.Context, orgID uuid.UUID) error {}reported := 0+ var totalDiskGBSeconds float64for _, u := range usage {seconds := int64(math.Ceil(u.TotalSeconds))- if seconds < 1 {- continue+ if seconds >= 1 {+ if err := r.stripe.ReportUsage(*org.StripeCustomerID, u.MemoryMB, seconds, now.Unix()); err != nil {+ log.Printf("usage-reporter: org %s tier %dMB: %v", orgID, u.MemoryMB, err)+ } else {+ reported+++ }}- if err := r.stripe.ReportUsage(*org.StripeCustomerID, u.MemoryMB, seconds, now.Unix()); err != nil {- log.Printf("usage-reporter: org %s tier %dMB: %v", orgID, u.MemoryMB, err)- continue+ totalDiskGBSeconds += DiskOverageGBSeconds(u)+ }++ // Report disk overage as a single aggregated meter event for the window.+ if diskGBSec := int64(math.Ceil(totalDiskGBSeconds)); diskGBSec >= 1 {+ if err := r.stripe.ReportDiskOverageUsage(*org.StripeCustomerID, diskGBSec, now.Unix()); err != nil {+ log.Printf("usage-reporter: org %s disk overage: %v", orgID, err)+ } else {+ reported++}- reported++}if err := r.store.UpdateLastUsageReportedAt(ctx, orgID, to); err != nil {diff --git a/internal/db/migrations/020_scale_events_disk_mb.down.sql b/internal/db/migrations/020_scale_events_disk_mb.down.sqlnew file mode 100644index 00000000..4f84f1b6--- /dev/null+++ b/internal/db/migrations/020_scale_events_disk_mb.down.sql@@ -0,0 +1,2 @@+DROP INDEX IF EXISTS idx_scale_events_org_disk;+ALTER TABLE sandbox_scale_events DROP COLUMN IF EXISTS disk_mb;diff --git a/internal/db/migrations/020_scale_events_disk_mb.up.sql b/internal/db/migrations/020_scale_events_disk_mb.up.sqlnew file mode 100644index 00000000..34a9e6e0--- /dev/null+++ b/internal/db/migrations/020_scale_events_disk_mb.up.sql@@ -0,0 +1,5 @@+-- Track per-sandbox disk size on scale events for metered disk-overage billing.+-- Disk doesn't change mid-life, but bracketing it alongside memory tiers lets the+-- existing GetOrgUsage aggregation produce GB-seconds per (memory_mb, disk_mb).+ALTER TABLE sandbox_scale_events ADD COLUMN disk_mb INTEGER NOT NULL DEFAULT 20480;+CREATE INDEX IF NOT EXISTS idx_scale_events_org_disk ON sandbox_scale_events(org_id, disk_mb);diff --git a/internal/db/usage.go b/internal/db/usage.goindex c30a3aa3..ec80b48d 100644--- a/internal/db/usage.go+++ b/internal/db/usage.go@@ -14,6 +14,7 @@ type ScaleEvent struct {OrgID string `json:"orgId"`MemoryMB int `json:"memoryMB"`CPUPct int `json:"cpuPercent"`+ DiskMB int `json:"diskMB"`StartedAt time.Time `json:"startedAt"`EndedAt *time.Time `json:"endedAt,omitempty"`}@@ -30,13 +31,29 @@ type UsageSample struct {}// RecordScaleEvent ends the current scale event (if any) and starts a new one.-func (s *Store) RecordScaleEvent(ctx context.Context, sandboxID, orgID string, memoryMB, cpuPct int) error {+// diskMB is the workspace disk size at this point — pass 0 to inherit from the+// most recent scale event (disk doesn't change at runtime).+func (s *Store) RecordScaleEvent(ctx context.Context, sandboxID, orgID string, memoryMB, cpuPct, diskMB int) error {tx, err := s.pool.Begin(ctx)if err != nil {return err}defer tx.Rollback(ctx)+ if diskMB <= 0 {+ // Inherit from the most recent open or closed event for this sandbox.+ var prev int+ err = tx.QueryRow(ctx,+ `SELECT disk_mb FROM sandbox_scale_events+ WHERE sandbox_id = $1+ ORDER BY started_at DESC LIMIT 1`, sandboxID).Scan(&prev)+ if err == nil && prev > 0 {+ diskMB = prev+ } else {+ diskMB = 20480 // fall back to default 20GB+ }+ }+// End the current open event_, err = tx.Exec(ctx,`UPDATE sandbox_scale_events SET ended_at = now()@@ -47,9 +64,9 @@ func (s *Store) RecordScaleEvent(ctx context.Context, sandboxID, orgID string, m// Start a new event_, err = tx.Exec(ctx,- `INSERT INTO sandbox_scale_events (sandbox_id, org_id, memory_mb, cpu_percent)- VALUES ($1, $2, $3, $4)`,- sandboxID, orgID, memoryMB, cpuPct)+ `INSERT INTO sandbox_scale_events (sandbox_id, org_id, memory_mb, cpu_percent, disk_mb)+ VALUES ($1, $2, $3, $4, $5)`,+ sandboxID, orgID, memoryMB, cpuPct, diskMB)if err != nil {return err}@@ -146,24 +163,25 @@ func (s *Store) InsertUsageSamples(ctx context.Context, samples []UsageSample) ereturn tx.Commit(ctx)}-// OrgUsageSummary returns total billed seconds per memory tier for an org in a time range.+// OrgUsageSummary returns total billed seconds per (memory tier, disk size) for an org in a time range.type OrgUsageSummary struct {MemoryMB int `json:"memoryMB"`CPUPercent int `json:"cpuPercent"`+ DiskMB int `json:"diskMB"`TotalSeconds float64 `json:"totalSeconds"`}// GetOrgUsage returns billing summary for an org.func (s *Store) GetOrgUsage(ctx context.Context, orgID string, from, to time.Time) ([]OrgUsageSummary, error) {rows, err := s.pool.Query(ctx, `- SELECT memory_mb, cpu_percent,+ SELECT memory_mb, cpu_percent, disk_mb,SUM(EXTRACT(EPOCH FROM (COALESCE(ended_at, LEAST(now(), $3)) - GREATEST(started_at, $2)))) as total_secondsFROM sandbox_scale_eventsWHERE org_id = $1AND started_at < $3AND (ended_at IS NULL OR ended_at > $2)- GROUP BY memory_mb, cpu_percent- ORDER BY memory_mb`,+ GROUP BY memory_mb, cpu_percent, disk_mb+ ORDER BY memory_mb, disk_mb`,orgID, from, to)if err != nil {return nil, err@@ -173,7 +191,7 @@ func (s *Store) GetOrgUsage(ctx context.Context, orgID string, from, to time.Timvar results []OrgUsageSummaryfor rows.Next() {var s OrgUsageSummary- if err := rows.Scan(&s.MemoryMB, &s.CPUPercent, &s.TotalSeconds); err != nil {+ if err := rows.Scan(&s.MemoryMB, &s.CPUPercent, &s.DiskMB, &s.TotalSeconds); err != nil {return nil, err}results = append(results, s)diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex b8b4963a..27750472 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -230,9 +230,13 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqif cpuPct < 100 {cpuPct = 100}+ diskMB := cfg.DiskMB+ if diskMB <= 0 {+ diskMB = 20480+ }orgID, _ := s.store.GetSandboxOrgID(ctx, sb.ID)if orgID != "" {- if err := s.store.RecordScaleEvent(ctx, sb.ID, orgID, memMB, cpuPct); err != nil {+ if err := s.store.RecordScaleEvent(ctx, sb.ID, orgID, memMB, cpuPct, diskMB); err != nil {log.Printf("grpc: failed to record initial scale event for %s: %v", sb.ID, err)}}@@ -588,13 +592,14 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest}}- // Resume billing scale event after wake+ // Resume billing scale event after wake. Disk size is preserved across wake —+ // pass 0 so RecordScaleEvent inherits disk_mb from the prior event.if s.store != nil {memMB := 1024 // TODO: get actual memory from sandbox statecpuPct := 100orgID, _ := s.store.GetSandboxOrgID(ctx, sb.ID)if orgID != "" {- if err := s.store.RecordScaleEvent(ctx, sb.ID, orgID, memMB, cpuPct); err != nil {+ if err := s.store.RecordScaleEvent(ctx, sb.ID, orgID, memMB, cpuPct, 0); err != nil {log.Printf("grpc: failed to record scale event on wake for %s: %v", sb.ID, err)}}@@ -909,13 +914,14 @@ func (s *GRPCServer) SetSandboxLimits(ctx context.Context, req *pb.SetSandboxLimreturn nil, fmt.Errorf("set resource limits: %w", err)}- // Record scale event for billing+ // Record scale event for billing. Disk size is not affected by SetSandboxLimits;+ // pass 0 so RecordScaleEvent inherits disk_mb from the prior event.if s.store != nil && req.MaxMemoryBytes > 0 {memMB := int(req.MaxMemoryBytes / (1024 * 1024))cpuPct := int(req.CpuMaxUsec / 1000) // 100000us → 100%orgID, _ := s.store.GetSandboxOrgID(ctx, req.SandboxId)if orgID != "" {- if err := s.store.RecordScaleEvent(ctx, req.SandboxId, orgID, memMB, cpuPct); err != nil {+ if err := s.store.RecordScaleEvent(ctx, req.SandboxId, orgID, memMB, cpuPct, 0); err != nil {log.Printf("grpc: failed to record scale event for %s: %v", req.SandboxId, err)}}