Skip to content

An open-source, faster Devin alternative

TypeScript

feat(billing): free-tier trial credits with auto-hibernate (#156)

Mohamed Habiba8b41ae546a2
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 6241171d..70eff2bf 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -369,9 +369,16 @@ func main() {
// Create API server
server := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)
- // Start usage reporter (reports sandbox usage to Stripe every 5 min)
+ // Start usage reporter — reports Pro org usage to Stripe and deducts
+ // free-tier trial credits (force-hibernates on empty) every 5 min.
+ // redisRegistry may be nil in combined mode; reporter tolerates that by
+ // logging instead of hibernating when free credits run out.
if opts.Store != nil && stripeClient != nil {
- reporter := billing.NewUsageReporter(opts.Store, stripeClient)
+ var workers billing.WorkerClientSource
+ if redisRegistry != nil {
+ workers = redisRegistry
+ }
+ reporter := billing.NewUsageReporter(opts.Store, stripeClient, workers)
reporter.Start()
defer reporter.Stop()
log.Println("opensandbox: usage reporter started (interval=5m)")
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 33f6f85e..1805c169 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -44,21 +44,26 @@ func (s *Server) createSandbox(c echo.Context) error {
var err error
org, err = s.store.GetOrg(ctx, orgID)
if err == nil {
- // Concurrent sandbox limit
- count, err := s.store.CountActiveSandboxes(ctx, orgID)
- if err == nil && count >= org.MaxConcurrentSandboxes {
- return c.JSON(http.StatusTooManyRequests, map[string]string{
- "error": "concurrent sandbox limit reached",
- })
- }
-
- // Free tier: 4GB / 1 vCPU only
+ // Free-tier: trial credits gate instead of a concurrent-sandbox cap.
+ // Pro (and any other non-free plan): concurrent limit still applies.
if org.Plan == "free" {
+ if org.FreeCreditsRemainingCents <= 0 {
+ return c.JSON(http.StatusPaymentRequired, map[string]string{
+ "error": "free trial credits exhausted — upgrade to pro to create new sandboxes",
+ })
+ }
if cfg.MemoryMB > 4096 || cfg.CpuCount > 1 {
return c.JSON(http.StatusPaymentRequired, map[string]string{
"error": "upgrade to pro for larger instances",
})
}
+ } else {
+ count, err := s.store.CountActiveSandboxes(ctx, orgID)
+ if err == nil && count >= org.MaxConcurrentSandboxes {
+ return c.JSON(http.StatusTooManyRequests, map[string]string{
+ "error": "concurrent sandbox limit reached",
+ })
+ }
}
// Default to 4GB/1vCPU if not specified (all plans)
@@ -1475,6 +1480,17 @@ func (s *Server) wakeSandbox(c echo.Context) error {
var req types.WakeRequest
_ = c.Bind(&req)
+ // Free-tier credits gate: refuse to wake if trial credits are exhausted.
+ if orgID, ok := auth.GetOrgID(c); ok && s.store != nil {
+ if org, err := s.store.GetOrg(ctx, orgID); err == nil {
+ if org.Plan == "free" && org.FreeCreditsRemainingCents <= 0 {
+ return c.JSON(http.StatusPaymentRequired, map[string]string{
+ "error": "free trial credits exhausted — upgrade to pro to resume sandboxes",
+ })
+ }
+ }
+ }
+
// Server mode: pick any worker, dispatch via gRPC
if s.workerRegistry != nil {
return s.wakeSandboxRemote(c, id, req)
diff --git a/internal/billing/enforcer.go b/internal/billing/enforcer.go
new file mode 100644
index 00000000..99a0cdb9
--- /dev/null
+++ b/internal/billing/enforcer.go
@@ -0,0 +1,110 @@
+package billing
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/db"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// WorkerClientSource is the minimal surface the enforcer needs to reach
+// worker gRPC servers. Both the NATS and Redis registries satisfy this
+// implicitly (ScalerRegistry in internal/controlplane), and we keep the
+// dependency at interface-level so billing stays independent of controlplane.
+type WorkerClientSource interface {
+ GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error)
+}
+
+// enforcerStore is the subset of *db.Store the enforcer depends on. Kept
+// narrow for testability.
+type enforcerStore interface {
+ ListSandboxSessions(ctx context.Context, orgID uuid.UUID, status string, limit, offset int) ([]db.SandboxSession, error)
+ UpdateSandboxSessionStatus(ctx context.Context, sandboxID, status string, errorMsg *string) error
+ EndScaleEvent(ctx context.Context, sandboxID string) error
+ CreateHibernation(ctx context.Context, sandboxID string, orgID uuid.UUID, hibernationKey string, sizeBytes int64, region, template string, sandboxConfig json.RawMessage) (*db.SandboxHibernation, string, error)
+}
+
+// EnforceCreditExhaustion force-hibernates every running sandbox belonging to
+// an org whose free-tier credit balance has dropped to <= 0. Returns the
+// number of sandboxes successfully hibernated. Errors on individual sandboxes
+// are logged and counted as failures; the function continues for the rest.
+//
+// Intended caller: the usage reporter, immediately after DeductFreeCredits
+// returns a non-positive balance.
+func EnforceCreditExhaustion(
+ ctx context.Context,
+ store enforcerStore,
+ workers WorkerClientSource,
+ orgID uuid.UUID,
+) (hibernated int, err error) {
+ // Page through all running sandboxes for this org. The default page size
+ // of 500 is well above any realistic free-tier sandbox count.
+ const pageSize = 500
+ sessions, err := store.ListSandboxSessions(ctx, orgID, "running", pageSize, 0)
+ if err != nil {
+ return 0, fmt.Errorf("list running sandboxes: %w", err)
+ }
+ if len(sessions) == 0 {
+ return 0, nil
+ }
+
+ for _, sess := range sessions {
+ if sess.WorkerID == "" {
+ log.Printf("enforcer: org %s sandbox %s has no worker_id, skipping", orgID, sess.SandboxID)
+ continue
+ }
+ client, err := workers.GetWorkerClient(sess.WorkerID)
+ if err != nil {
+ log.Printf("enforcer: org %s sandbox %s: no client for worker %s: %v",
+ orgID, sess.SandboxID, sess.WorkerID, err)
+ continue
+ }
+ // Per-sandbox timeout so one slow/stuck worker can't block the entire
+ // enforcer pass (and kill the reporter goroutine's tick loop).
+ callCtx, callCancel := context.WithTimeout(ctx, 30*time.Second)
+ resp, err := client.HibernateSandbox(callCtx, &pb.HibernateSandboxRequest{
+ SandboxId: sess.SandboxID,
+ })
+ callCancel()
+ if err != nil {
+ log.Printf("enforcer: org %s sandbox %s hibernate failed: %v",
+ orgID, sess.SandboxID, err)
+ continue
+ }
+ // Update PG directly — the control plane initiated this hibernation,
+ // so we can't rely on worker-side callbacks or async sync to propagate
+ // the status change back to PG.
+ if err := store.EndScaleEvent(ctx, sess.SandboxID); err != nil {
+ log.Printf("enforcer: org %s sandbox %s: EndScaleEvent failed: %v", orgID, sess.SandboxID, err)
+ }
+ if err := store.UpdateSandboxSessionStatus(ctx, sess.SandboxID, "hibernated", nil); err != nil {
+ log.Printf("enforcer: org %s sandbox %s: status update failed: %v", orgID, sess.SandboxID, err)
+ }
+ // Create the hibernation record so the wake endpoint can find the
+ // checkpoint key. The gRPC handler doesn't do this (only the
+ // auto-timeout path does), so we must do it here.
+ checkpointKey := ""
+ var sizeBytes int64
+ if resp != nil {
+ checkpointKey = resp.CheckpointKey
+ sizeBytes = resp.SizeBytes
+ }
+ if checkpointKey != "" {
+ if _, _, err := store.CreateHibernation(ctx, sess.SandboxID, orgID, checkpointKey, sizeBytes, sess.Region, sess.Template, sess.Config); err != nil {
+ log.Printf("enforcer: org %s sandbox %s: CreateHibernation failed: %v", orgID, sess.SandboxID, err)
+ }
+ } else {
+ log.Printf("enforcer: org %s sandbox %s: no checkpoint key in response, wake will not work", orgID, sess.SandboxID)
+ }
+ hibernated++
+ }
+
+ log.Printf("enforcer: org %s credits exhausted — hibernated %d/%d running sandbox(es)",
+ orgID, hibernated, len(sessions))
+ return hibernated, nil
+}
diff --git a/internal/billing/enforcer_test.go b/internal/billing/enforcer_test.go
new file mode 100644
index 00000000..9d728b10
--- /dev/null
+++ b/internal/billing/enforcer_test.go
@@ -0,0 +1,185 @@
+package billing
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/db"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+ "google.golang.org/grpc"
+)
+
+// --- Test doubles ---
+
+type fakeLister struct {
+ sessions []db.SandboxSession
+ err error
+ hibernatedStatuses []string
+ endedScaleEvents []string
+ hibernations []string
+}
+
+func (f *fakeLister) ListSandboxSessions(_ context.Context, _ uuid.UUID, _ string, _, _ int) ([]db.SandboxSession, error) {
+ return f.sessions, f.err
+}
+
+func (f *fakeLister) UpdateSandboxSessionStatus(_ context.Context, sandboxID, status string, _ *string) error {
+ f.hibernatedStatuses = append(f.hibernatedStatuses, sandboxID+"="+status)
+ return nil
+}
+
+func (f *fakeLister) EndScaleEvent(_ context.Context, sandboxID string) error {
+ f.endedScaleEvents = append(f.endedScaleEvents, sandboxID)
+ return nil
+}
+
+func (f *fakeLister) CreateHibernation(_ context.Context, sandboxID string, _ uuid.UUID, key string, _ int64, _, _ string, _ json.RawMessage) (*db.SandboxHibernation, string, error) {
+ f.hibernations = append(f.hibernations, sandboxID+"="+key)
+ return &db.SandboxHibernation{SandboxID: sandboxID, HibernationKey: key}, "", nil
+}
+
+type fakeWorkerClient struct {
+ pb.SandboxWorkerClient
+ hibernated []string
+ hibernateErr error
+}
+
+func (c *fakeWorkerClient) HibernateSandbox(_ context.Context, req *pb.HibernateSandboxRequest, _ ...grpc.CallOption) (*pb.HibernateSandboxResponse, error) {
+ if c.hibernateErr != nil {
+ return nil, c.hibernateErr
+ }
+ c.hibernated = append(c.hibernated, req.SandboxId)
+ return &pb.HibernateSandboxResponse{
+ SandboxId: req.SandboxId,
+ CheckpointKey: "ckpt-" + req.SandboxId,
+ SizeBytes: 1024,
+ }, nil
+}
+
+type fakeWorkerSource struct {
+ clients map[string]*fakeWorkerClient
+ missing map[string]bool
+}
+
+func (s *fakeWorkerSource) GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error) {
+ if s.missing[workerID] {
+ return nil, errors.New("no client for worker")
+ }
+ if c, ok := s.clients[workerID]; ok {
+ return c, nil
+ }
+ return nil, errors.New("unknown worker")
+}
+
+// --- Tests ---
+
+func TestEnforceCreditExhaustion_NoSessions(t *testing.T) {
+ lister := &fakeLister{}
+ workers := &fakeWorkerSource{clients: map[string]*fakeWorkerClient{}}
+ got, err := EnforceCreditExhaustion(context.Background(), lister, workers, uuid.New())
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != 0 {
+ t.Fatalf("expected 0 hibernated, got %d", got)
+ }
+}
+
+func TestEnforceCreditExhaustion_HibernatesAllRunning(t *testing.T) {
+ orgID := uuid.New()
+ lister := &fakeLister{
+ sessions: []db.SandboxSession{
+ {SandboxID: "sb-1", WorkerID: "w-a"},
+ {SandboxID: "sb-2", WorkerID: "w-a"},
+ {SandboxID: "sb-3", WorkerID: "w-b"},
+ },
+ }
+ wA := &fakeWorkerClient{}
+ wB := &fakeWorkerClient{}
+ workers := &fakeWorkerSource{
+ clients: map[string]*fakeWorkerClient{"w-a": wA, "w-b": wB},
+ }
+
+ got, err := EnforceCreditExhaustion(context.Background(), lister, workers, orgID)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != 3 {
+ t.Fatalf("expected 3 hibernated, got %d", got)
+ }
+ if len(wA.hibernated) != 2 || len(wB.hibernated) != 1 {
+ t.Fatalf("unexpected dispatch split: w-a=%v w-b=%v", wA.hibernated, wB.hibernated)
+ }
+}
+
+func TestEnforceCreditExhaustion_SkipsWorkersWithoutClient(t *testing.T) {
+ lister := &fakeLister{
+ sessions: []db.SandboxSession{
+ {SandboxID: "sb-1", WorkerID: "w-a"},
+ {SandboxID: "sb-2", WorkerID: "w-gone"},
+ {SandboxID: "sb-3", WorkerID: "w-a"},
+ },
+ }
+ wA := &fakeWorkerClient{}
+ workers := &fakeWorkerSource{
+ clients: map[string]*fakeWorkerClient{"w-a": wA},
+ missing: map[string]bool{"w-gone": true},
+ }
+
+ got, err := EnforceCreditExhaustion(context.Background(), lister, workers, uuid.New())
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != 2 {
+ t.Fatalf("expected 2 hibernated (one worker gone), got %d", got)
+ }
+}
+
+func TestEnforceCreditExhaustion_SkipsSessionsWithoutWorkerID(t *testing.T) {
+ lister := &fakeLister{
+ sessions: []db.SandboxSession{
+ {SandboxID: "sb-orphan", WorkerID: ""},
+ {SandboxID: "sb-ok", WorkerID: "w-a"},
+ },
+ }
+ wA := &fakeWorkerClient{}
+ workers := &fakeWorkerSource{
+ clients: map[string]*fakeWorkerClient{"w-a": wA},
+ }
+
+ got, err := EnforceCreditExhaustion(context.Background(), lister, workers, uuid.New())
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != 1 {
+ t.Fatalf("expected 1 hibernated (orphan skipped), got %d", got)
+ }
+ if len(wA.hibernated) != 1 || wA.hibernated[0] != "sb-ok" {
+ t.Fatalf("expected only sb-ok hibernated, got %v", wA.hibernated)
+ }
+}
+
+func TestEnforceCreditExhaustion_ContinuesOnGRPCError(t *testing.T) {
+ lister := &fakeLister{
+ sessions: []db.SandboxSession{
+ {SandboxID: "sb-err", WorkerID: "w-err"},
+ {SandboxID: "sb-ok", WorkerID: "w-ok"},
+ },
+ }
+ wErr := &fakeWorkerClient{hibernateErr: errors.New("gRPC unavailable")}
+ wOk := &fakeWorkerClient{}
+ workers := &fakeWorkerSource{
+ clients: map[string]*fakeWorkerClient{"w-err": wErr, "w-ok": wOk},
+ }
+
+ got, err := EnforceCreditExhaustion(context.Background(), lister, workers, uuid.New())
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != 1 {
+ t.Fatalf("expected 1 hibernated (one errored), got %d", got)
+ }
+}
diff --git a/internal/billing/usage_reporter.go b/internal/billing/usage_reporter.go
index 4a67f166..7c247cee 100644
--- a/internal/billing/usage_reporter.go
+++ b/internal/billing/usage_reporter.go
@@ -10,19 +10,27 @@ import (
"github.com/opensandbox/opensandbox/internal/db"
)
-// UsageReporter periodically reports sandbox usage to Stripe via Billing Meter Events.
+// UsageReporter periodically (a) reports sandbox usage for Pro orgs to Stripe
+// via Billing Meter Events, and (b) deducts the same usage from free-tier
+// trial credits on the same tick; when a free org's balance reaches zero it
+// force-hibernates their running sandboxes via the enforcer.
+//
+// workers may be nil in tests or in deployments without a worker registry
+// (free-tier enforcement will then skip the hibernation step and log).
type UsageReporter struct {
store *db.Store
stripe *StripeClient
+ workers WorkerClientSource
interval time.Duration
stop chan struct{}
stopped chan struct{}
}
-func NewUsageReporter(store *db.Store, stripe *StripeClient) *UsageReporter {
+func NewUsageReporter(store *db.Store, stripe *StripeClient, workers WorkerClientSource) *UsageReporter {
return &UsageReporter{
store: store,
stripe: stripe,
+ workers: workers,
interval: 5 * time.Minute,
stop: make(chan struct{}),
stopped: make(chan struct{}),
@@ -39,30 +47,55 @@ func (r *UsageReporter) loop() {
for {
select {
case <-ticker.C:
- r.reportAll()
+ r.safeReportAll()
case <-r.stop:
return
}
}
}
+// safeReportAll wraps reportAll with a recover so a panic in one tick
+// (e.g. nil-pointer in a gRPC call) doesn't kill the reporter goroutine
+// and silently stop all future billing/credit ticks.
+func (r *UsageReporter) safeReportAll() {
+ defer func() {
+ if v := recover(); v != nil {
+ log.Printf("usage-reporter: recovered from panic: %v", v)
+ }
+ }()
+ r.reportAll()
+}
+
func (r *UsageReporter) reportAll() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
+ // Pro pass: ship usage to Stripe meters.
orgIDs, err := r.store.ListBillableOrgIDs(ctx)
if err != nil {
log.Printf("usage-reporter: failed to list billable orgs: %v", err)
+ } else if len(orgIDs) > 0 {
+ log.Printf("usage-reporter: reporting for %d pro org(s)", len(orgIDs))
+ for _, orgID := range orgIDs {
+ if err := r.reportOrg(ctx, orgID); err != nil {
+ log.Printf("usage-reporter: org %s: %v", orgID, err)
+ }
+ }
+ }
+
+ // Free-tier pass: deduct the same usage from trial credits; hibernate on empty.
+ freeIDs, err := r.store.ListFreeOrgIDsWithOpenUsage(ctx)
+ if err != nil {
+ log.Printf("usage-reporter: failed to list free orgs: %v", err)
return
}
- if len(orgIDs) == 0 {
+ if len(freeIDs) == 0 {
return
}
-
- log.Printf("usage-reporter: reporting for %d org(s)", len(orgIDs))
- for _, orgID := range orgIDs {
- if err := r.reportOrg(ctx, orgID); err != nil {
- log.Printf("usage-reporter: org %s: %v", orgID, err)
+ log.Printf("usage-reporter: deducting credits for %d free org(s)", len(freeIDs))
+ for _, orgID := range freeIDs {
+ if err := r.deductFreeOrg(ctx, orgID); err != nil {
+ log.Printf("usage-reporter: free org %s: %v", orgID, err)
}
}
}
@@ -117,3 +150,63 @@ func (r *UsageReporter) reportOrg(ctx context.Context, orgID uuid.UUID) error {
}
return nil
}
+
+// deductFreeOrg computes compute+disk cost for a free-tier org since its last
+// report watermark, decrements its trial balance, advances the watermark, and
+// force-hibernates running sandboxes when the balance hits zero.
+func (r *UsageReporter) deductFreeOrg(ctx context.Context, orgID uuid.UUID) error {
+ org, err := r.store.GetOrg(ctx, orgID)
+ if err != nil {
+ return err
+ }
+ // Defensive: an org that flipped to pro between ListFreeOrgIDs and now
+ // will be picked up by the pro pass on the next tick.
+ if org.Plan != "free" {
+ return nil
+ }
+
+ now := time.Now()
+ from := org.LastUsageReportedAt
+ to := now
+
+ usage, err := r.store.GetOrgUsage(ctx, orgID.String(), from, to)
+ if err != nil {
+ return err
+ }
+
+ // Round up to the nearest whole cent so sub-cent usage still accumulates
+ // over ticks; max overcharge per tick is <1 cent, negligible for a trial.
+ costCents := int64(math.Ceil(CalculateUsageCostCents(usage)))
+
+ // Always advance the watermark — even for a zero-cent window, otherwise
+ // we'd re-scan the same interval next tick without making progress.
+ defer func() {
+ if err := r.store.UpdateLastUsageReportedAt(ctx, orgID, to); err != nil {
+ log.Printf("usage-reporter: free org %s: failed to update watermark: %v", orgID, err)
+ }
+ }()
+
+ if costCents <= 0 {
+ return nil
+ }
+
+ newBalance, err := r.store.DeductFreeCredits(ctx, orgID, costCents)
+ if err != nil {
+ return err
+ }
+
+ if newBalance > 0 {
+ log.Printf("usage-reporter: free org %s — deducted %d cents, balance=%d", orgID, costCents, newBalance)
+ return nil
+ }
+
+ log.Printf("usage-reporter: free org %s — credits exhausted (deducted %d, balance=%d), force-hibernating", orgID, costCents, newBalance)
+ if r.workers == nil {
+ log.Printf("usage-reporter: free org %s: no worker client source configured, skipping hibernation", orgID)
+ return nil
+ }
+ if _, err := EnforceCreditExhaustion(ctx, r.store, r.workers, orgID); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/internal/db/migrations/023_free_credits_remaining_cents.down.sql b/internal/db/migrations/023_free_credits_remaining_cents.down.sql
new file mode 100644
index 00000000..fef98412
--- /dev/null
+++ b/internal/db/migrations/023_free_credits_remaining_cents.down.sql
@@ -0,0 +1,4 @@
+-- NOTE: irreversible data loss — the backfill to 500 for existing free orgs
+-- cannot be restored by dropping the column. This down migration only reverts
+-- the schema change.
+ALTER TABLE orgs DROP COLUMN IF EXISTS free_credits_remaining_cents;
diff --git a/internal/db/migrations/023_free_credits_remaining_cents.up.sql b/internal/db/migrations/023_free_credits_remaining_cents.up.sql
new file mode 100644
index 00000000..7f05dd42
--- /dev/null
+++ b/internal/db/migrations/023_free_credits_remaining_cents.up.sql
@@ -0,0 +1,12 @@
+-- Free-tier trial credits. Decremented by the usage reporter while plan='free'.
+-- At <=0, the org's running sandboxes are force-hibernated and new create/wake
+-- is rejected until the org upgrades to pro. Ignored while plan='pro'.
+ALTER TABLE orgs ADD COLUMN free_credits_remaining_cents BIGINT NOT NULL DEFAULT 500;
+
+-- Grandfather existing free orgs to the new $5 trial starting balance.
+UPDATE orgs SET free_credits_remaining_cents = 500 WHERE plan = 'free';
+
+-- Reset the usage-reporting watermark for free orgs so the first deduction
+-- window only covers post-migration usage, not months of historical scale
+-- events that would cause a massive one-shot over-deduction.
+UPDATE orgs SET last_usage_reported_at = now() WHERE plan = 'free';
diff --git a/internal/db/store.go b/internal/db/store.go
index a233dbff..5551d1a2 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -111,6 +111,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{23, "migrations/021_migration_state.up.sql"},
{24, "migrations/022_orgs_price_locked.up.sql"},
{25, "migrations/023_checkpoints_public.up.sql"},
+ {26, "migrations/023_free_credits_remaining_cents.up.sql"},
}
for _, m := range migrations {
@@ -170,6 +171,11 @@ type Org struct {
OwnerUserID *uuid.UUID `json:"ownerUserId,omitempty"`
CreditBalanceCents int `json:"creditBalanceCents"`
+ // Free-tier trial credits. Decremented by the usage reporter while
+ // plan='free'. At <=0, running sandboxes are force-hibernated and new
+ // create/wake is rejected until upgrade to pro. Ignored for plan='pro'.
+ FreeCreditsRemainingCents int64 `json:"freeCreditsRemainingCents"`
+
// Stripe billing fields
StripeCustomerID *string `json:"stripeCustomerId,omitempty"`
StripeSubscriptionID *string `json:"stripeSubscriptionId,omitempty"`
@@ -182,7 +188,8 @@ const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_
custom_domain, cf_hostname_id, domain_verification_status, domain_ssl_status,
verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value,
workos_org_id, is_personal, owner_user_id, credit_balance_cents,
- stripe_customer_id, stripe_subscription_id, last_usage_reported_at, price_locked`
+ stripe_customer_id, stripe_subscription_id, last_usage_reported_at, price_locked,
+ free_credits_remaining_cents`
// scanOrg scans a row into an Org struct.
func scanOrg(row pgx.Row) (*Org, error) {
@@ -195,6 +202,7 @@ func scanOrg(row pgx.Row) (*Org, error) {
&org.WorkOSOrgID, &org.IsPersonal, &org.OwnerUserID, &org.CreditBalanceCents,
&org.StripeCustomerID, &org.StripeSubscriptionID, &org.LastUsageReportedAt,
&org.PriceLocked,
+ &org.FreeCreditsRemainingCents,
)
return org, err
}
diff --git a/internal/db/usage.go b/internal/db/usage.go
index ec80b48d..bfb6a716 100644
--- a/internal/db/usage.go
+++ b/internal/db/usage.go
@@ -258,6 +258,33 @@ func (s *Store) ListBillableOrgIDs(ctx context.Context) ([]uuid.UUID, error) {
return ids, rows.Err()
}
+// ListFreeOrgIDsWithOpenUsage returns org IDs with plan="free" that have
+// deductible usage: either a currently-running sandbox or a scale event that
+// ended after the last deduction watermark. Mirrors ListBillableOrgIDs but
+// for the free-tier credit deduction loop.
+func (s *Store) ListFreeOrgIDsWithOpenUsage(ctx context.Context) ([]uuid.UUID, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT DISTINCT se.org_id
+ FROM sandbox_scale_events se
+ JOIN orgs o ON o.id = se.org_id
+ WHERE o.plan = 'free'
+ AND (se.ended_at IS NULL OR se.ended_at > o.last_usage_reported_at)`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var ids []uuid.UUID
+ for rows.Next() {
+ var id uuid.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ ids = append(ids, id)
+ }
+ return ids, rows.Err()
+}
+
// SubscriptionItem maps a memory tier to a Stripe subscription item ID.
type SubscriptionItem struct {
OrgID uuid.UUID `json:"orgId"`
@@ -302,6 +329,21 @@ func (s *Store) AddCredits(ctx context.Context, orgID uuid.UUID, amountCents int
return err
}
+// DeductFreeCredits atomically subtracts cents from the free-tier trial
+// balance and returns the resulting balance. Caller triggers hibernation
+// enforcement when the returned value is <= 0.
+func (s *Store) DeductFreeCredits(ctx context.Context, orgID uuid.UUID, amountCents int64) (int64, error) {
+ var newBalance int64
+ err := s.pool.QueryRow(ctx,
+ `UPDATE orgs
+ SET free_credits_remaining_cents = free_credits_remaining_cents - $2,
+ updated_at = now()
+ WHERE id = $1
+ RETURNING free_credits_remaining_cents`,
+ orgID, amountCents).Scan(&newBalance)
+ return newBalance, err
+}
+
// GetSubscriptionItems returns the subscription item mapping for an org.
func (s *Store) GetSubscriptionItems(ctx context.Context, orgID uuid.UUID) (map[int]string, error) {
rows, err := s.pool.Query(ctx,
diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.go
index 01f4ecc1..2054af18 100644
--- a/internal/proxy/controlplane_proxy.go
+++ b/internal/proxy/controlplane_proxy.go
@@ -90,6 +90,18 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string, port int)
// If the sandbox is hibernated, wake it on-demand before proxying
if session.Status == "hibernated" {
+ // Free-tier credits gate: don't auto-wake via preview URL if the
+ // owning org's trial credits are exhausted. Surface a 402 so the
+ // user sees a clear "upgrade required" instead of a silent wake
+ // that burns non-existent credits.
+ if org, err := p.store.GetOrg(ctx, session.OrgID); err == nil {
+ if org.Plan == "free" && org.FreeCreditsRemainingCents <= 0 {
+ return c.JSON(http.StatusPaymentRequired, map[string]string{
+ "error": "free trial credits exhausted — upgrade to pro to resume sandboxes",
+ })
+ }
+ }
+
worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)
if err != nil {
log.Printf("cp-proxy: wake-on-request failed for sandbox %s: %v", sandboxID, err)