An open-source, faster Devin alternative
TypeScript
feat(capacity): phase-1 reserved-capacity API — calendar, reserve, list, admission
Igor Zalutskib557bdfba736
diff --git a/internal/api/capacity.go b/internal/api/capacity.gonew file mode 100644index 00000000..264612b3--- /dev/null+++ b/internal/api/capacity.go@@ -0,0 +1,430 @@+package api++import (+ "context"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "time"++ "github.com/google/uuid"+ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db"+)++// Reserved-capacity endpoints. Spec lives in+// ws-pricing/design/001-reserved-capacity-squares.md; implementation plan+// in ws-pricing/work/001-reserved-capacity-impl.md.++const (+ capacityHandlerTimeout = 10 * time.Second++ // Closed phase-1 product decisions (ws-pricing work/001).+ capacityMinLeadTime = 30 * time.Minute+ capacityMaxCalendarSpan = 35 * 24 * time.Hour+ capacityMaxListSpan = 35 * 24 * time.Hour+ capacityMaxIntervalsPerPost = 96 * 7 // one week of 15-minute slots — generous; tighter cap can land later+ capacityListDefaultLimit = 50+ capacityListMaxLimit = 200+)++const (+ capacityCreateEndpoint = "POST /api/capacity/reservations"+)++// getCapacityCalendar → GET /api/capacity/calendar+func (s *Server) getCapacityCalendar(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ from, to, err := parseAlignedRange(c.QueryParam("from"), c.QueryParam("to"), capacityMaxCalendarSpan)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }++ ctx, cancel := context.WithTimeout(c.Request().Context(), capacityHandlerTimeout)+ defer cancel()++ org, err := s.store.GetOrg(ctx, orgID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ buckets, err := s.store.GetCapacityCalendar(ctx, orgID, from, to)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ items := make([]map[string]any, 0, len(buckets))+ for _, b := range buckets {+ items = append(items, map[string]any{+ "startsAt": b.StartsAt.UTC().Format(time.RFC3339),+ "endsAt": b.EndsAt.UTC().Format(time.RFC3339),+ "reservedGb": b.ReservedGB,+ "reservationLimitGb": org.MaxMemoryGB,+ "reservableGb": max0(org.MaxMemoryGB - b.ReservedGB),+ })+ }++ return c.JSON(http.StatusOK, map[string]any{+ "from": from.UTC().Format(time.RFC3339),+ "to": to.UTC().Format(time.RFC3339),+ "resource": "memory_gb",+ "intervals": items,+ })+}++// createCapacityReservation → POST /api/capacity/reservations+func (s *Server) createCapacityReservation(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ body, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "read body: " + err.Error()})+ }+ bodyHash := sha256.Sum256(body)++ intervals, err := parseAndValidateReservationBody(body)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }++ ctx, cancel := context.WithTimeout(c.Request().Context(), capacityHandlerTimeout)+ defer cancel()++ idemKey := c.Request().Header.Get("Idempotency-Key")++ reservationID, createdAt, err := s.store.CreateReservation(ctx, db.CreateReservationRequest{+ OrgID: orgID,+ IdempotencyKey: idemKey,+ IdempotencyEndpt: capacityCreateEndpoint,+ RequestBodyHash: bodyHash[:],+ Intervals: intervals,+ })+ if err != nil {+ var replay *db.IdempotencyReplay+ if errors.As(err, &replay) {+ return c.JSONBlob(replay.StatusCode, replay.ResponseBody)+ }+ var conflict *db.IdempotencyConflictError+ if errors.As(err, &conflict) {+ body := map[string]any{+ "error": "idempotency_key_conflict",+ "message": "Idempotency-Key was previously used with a different request body",+ }+ return c.JSON(http.StatusConflict, body)+ }+ var shortfall *db.CapacityShortfallError+ if errors.As(err, &shortfall) {+ body := buildCapacityShortfallBody(shortfall)+ cacheCapacityResponse(ctx, s.store, orgID, idemKey, bodyHash[:], http.StatusConflict, body)+ return c.JSON(http.StatusConflict, body)+ }+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ body200 := map[string]any{+ "reservationId": reservationID.String(),+ "createdAt": createdAt.UTC().Format(time.RFC3339),+ "intervals": intervalsToJSON(intervals),+ }+ cacheCapacityResponse(ctx, s.store, orgID, idemKey, bodyHash[:], http.StatusOK, body200)+ return c.JSON(http.StatusOK, body200)+}++// listCapacityReservations → GET /api/capacity/reservations+func (s *Server) listCapacityReservations(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ from, to, err := parseRange(c.QueryParam("from"), c.QueryParam("to"), capacityMaxListSpan)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }++ limit := capacityListDefaultLimit+ if s := c.QueryParam("limit"); s != "" {+ var n int+ if _, err := fmt.Sscanf(s, "%d", &n); err != nil || n <= 0 {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "`limit` must be a positive integer"})+ }+ if n > capacityListMaxLimit {+ n = capacityListMaxLimit+ }+ limit = n+ }++ var cursor *db.ReservationCursor+ if raw := c.QueryParam("cursor"); raw != "" {+ decoded, err := decodeCursor(raw)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid cursor"})+ }+ cursor = decoded+ }++ ctx, cancel := context.WithTimeout(c.Request().Context(), capacityHandlerTimeout)+ defer cancel()++ reservations, next, err := s.store.ListReservations(ctx, db.ListReservationsRequest{+ OrgID: orgID,+ From: from,+ To: to,+ Limit: limit,+ Cursor: cursor,+ })+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ items := make([]map[string]any, 0, len(reservations))+ for _, r := range reservations {+ items = append(items, map[string]any{+ "reservationId": r.ReservationID.String(),+ "createdAt": r.CreatedAt.UTC().Format(time.RFC3339),+ "intervals": intervalsToJSON(r.Intervals),+ })+ }++ resp := map[string]any{+ "from": from.UTC().Format(time.RFC3339),+ "to": to.UTC().Format(time.RFC3339),+ "reservations": items,+ "nextCursor": nullableString(encodeCursor(next)),+ }+ return c.JSON(http.StatusOK, resp)+}++// --- request parsing / validation ---++type reservationRequestBody struct {+ Intervals []reservationIntervalBody `json:"intervals"`+}++type reservationIntervalBody struct {+ StartsAt string `json:"startsAt"`+ EndsAt string `json:"endsAt"`+ CapacityGB int `json:"capacityGb"`+}++func parseAndValidateReservationBody(body []byte) ([]db.CapacityInterval, error) {+ var req reservationRequestBody+ if len(body) == 0 {+ return nil, fmt.Errorf("request body is required")+ }+ if err := json.Unmarshal(body, &req); err != nil {+ return nil, fmt.Errorf("invalid JSON: %w", err)+ }+ if len(req.Intervals) == 0 {+ return nil, fmt.Errorf("`intervals` must be non-empty")+ }+ if len(req.Intervals) > capacityMaxIntervalsPerPost {+ return nil, fmt.Errorf("`intervals` cannot exceed %d entries per request", capacityMaxIntervalsPerPost)+ }++ now := time.Now().UTC()+ earliest := alignUp15(now.Add(capacityMinLeadTime))++ out := make([]db.CapacityInterval, 0, len(req.Intervals))+ seen := make(map[time.Time]struct{}, len(req.Intervals))+ for i, iv := range req.Intervals {+ startsAt, err := time.Parse(time.RFC3339, iv.StartsAt)+ if err != nil {+ return nil, fmt.Errorf("intervals[%d].startsAt must be RFC3339: %w", i, err)+ }+ endsAt, err := time.Parse(time.RFC3339, iv.EndsAt)+ if err != nil {+ return nil, fmt.Errorf("intervals[%d].endsAt must be RFC3339: %w", i, err)+ }+ startsAt = startsAt.UTC()+ endsAt = endsAt.UTC()++ if !isAligned15(startsAt) {+ return nil, fmt.Errorf("intervals[%d].startsAt must be aligned to 15 minutes UTC", i)+ }+ if !endsAt.Equal(startsAt.Add(15 * time.Minute)) {+ return nil, fmt.Errorf("intervals[%d].endsAt must equal startsAt + 15 minutes", i)+ }+ if iv.CapacityGB <= 0 || iv.CapacityGB%4 != 0 {+ return nil, fmt.Errorf("intervals[%d].capacityGb must be a positive multiple of 4", i)+ }+ if startsAt.Before(earliest) {+ return nil, fmt.Errorf("intervals[%d].startsAt is inside the %s lead-time window", i, capacityMinLeadTime)+ }+ if _, dup := seen[startsAt]; dup {+ return nil, fmt.Errorf("intervals[%d].startsAt duplicates an earlier entry — combine into a single capacityGb", i)+ }+ seen[startsAt] = struct{}{}++ out = append(out, db.CapacityInterval{+ StartsAt: startsAt,+ EndsAt: endsAt,+ CapacityGB: iv.CapacityGB,+ })+ }+ return out, nil+}++func parseAlignedRange(fromStr, toStr string, maxSpan time.Duration) (time.Time, time.Time, error) {+ from, to, err := parseRange(fromStr, toStr, maxSpan)+ if err != nil {+ return time.Time{}, time.Time{}, err+ }+ if !isAligned15(from) {+ return time.Time{}, time.Time{}, fmt.Errorf("`from` must be aligned to 15 minutes UTC")+ }+ if !isAligned15(to) {+ return time.Time{}, time.Time{}, fmt.Errorf("`to` must be aligned to 15 minutes UTC")+ }+ return from, to, nil+}++func parseRange(fromStr, toStr string, maxSpan time.Duration) (time.Time, time.Time, error) {+ if fromStr == "" {+ return time.Time{}, time.Time{}, fmt.Errorf("`from` is required")+ }+ if toStr == "" {+ return time.Time{}, time.Time{}, fmt.Errorf("`to` is required")+ }+ from, err := time.Parse(time.RFC3339, fromStr)+ if err != nil {+ return time.Time{}, time.Time{}, fmt.Errorf("`from` must be RFC3339: %w", err)+ }+ to, err := time.Parse(time.RFC3339, toStr)+ if err != nil {+ return time.Time{}, time.Time{}, fmt.Errorf("`to` must be RFC3339: %w", err)+ }+ from = from.UTC()+ to = to.UTC()+ if !to.After(from) {+ return time.Time{}, time.Time{}, fmt.Errorf("`to` must be after `from`")+ }+ if to.Sub(from) > maxSpan {+ return time.Time{}, time.Time{}, fmt.Errorf("query window must be <= %s", maxSpan)+ }+ return from, to, nil+}++func isAligned15(t time.Time) bool {+ return t.Equal(t.Truncate(15 * time.Minute))+}++func alignUp15(t time.Time) time.Time {+ floored := t.Truncate(15 * time.Minute)+ if floored.Equal(t) {+ return floored+ }+ return floored.Add(15 * time.Minute)+}++func max0(n int) int {+ if n < 0 {+ return 0+ }+ return n+}++// --- response helpers ---++func intervalsToJSON(in []db.CapacityInterval) []map[string]any {+ out := make([]map[string]any, 0, len(in))+ for _, iv := range in {+ out = append(out, map[string]any{+ "startsAt": iv.StartsAt.UTC().Format(time.RFC3339),+ "endsAt": iv.EndsAt.UTC().Format(time.RFC3339),+ "capacityGb": iv.CapacityGB,+ })+ }+ return out+}++func buildCapacityShortfallBody(s *db.CapacityShortfallError) map[string]any {+ intervals := make([]map[string]any, 0, len(s.Intervals))+ for _, iv := range s.Intervals {+ intervals = append(intervals, map[string]any{+ "startsAt": iv.StartsAt.UTC().Format(time.RFC3339),+ "requestedGb": iv.RequestedGB,+ "reservableGb": iv.ReservableGB,+ "reason": iv.Reason,+ })+ }+ return map[string]any{+ "error": "capacity_not_available",+ "intervals": intervals,+ }+}++func cacheCapacityResponse(ctx context.Context, store *db.Store, orgID uuid.UUID, key string, bodyHash []byte, status int, body map[string]any) {+ if key == "" {+ return+ }+ encoded, err := json.Marshal(body)+ if err != nil {+ return+ }+ // Save best-effort. A failed save means the next replay will hit the+ // write path again and (idempotency aside) take the same outcome on a+ // matching key. Logged but not surfaced to the caller.+ _ = store.SaveIdempotencyResult(ctx, orgID, capacityCreateEndpoint, key, bodyHash, status, encoded)+}++// --- cursor encoding ---++type capacityCursorPayload struct {+ CreatedAt time.Time `json:"createdAt"`+ ReservationID uuid.UUID `json:"reservationId"`+}++func encodeCursor(c *db.ReservationCursor) string {+ if c == nil {+ return ""+ }+ payload, err := json.Marshal(capacityCursorPayload{+ CreatedAt: c.CreatedAt,+ ReservationID: c.ReservationID,+ })+ if err != nil {+ return ""+ }+ return base64.RawURLEncoding.EncodeToString(payload)+}++func decodeCursor(raw string) (*db.ReservationCursor, error) {+ decoded, err := base64.RawURLEncoding.DecodeString(raw)+ if err != nil {+ return nil, err+ }+ var p capacityCursorPayload+ if err := json.Unmarshal(decoded, &p); err != nil {+ return nil, err+ }+ if p.ReservationID == uuid.Nil {+ return nil, fmt.Errorf("cursor missing reservationId")+ }+ return &db.ReservationCursor{+ CreatedAt: p.CreatedAt,+ ReservationID: p.ReservationID,+ }, nil+}diff --git a/internal/api/capacity_test.go b/internal/api/capacity_test.gonew file mode 100644index 00000000..a0d37e86--- /dev/null+++ b/internal/api/capacity_test.go@@ -0,0 +1,194 @@+package api++import (+ "encoding/json"+ "strings"+ "testing"+ "time"++ "github.com/google/uuid"++ "github.com/opensandbox/opensandbox/internal/db"+)++func validRequestBody(t *testing.T) []byte {+ t.Helper()+ start := alignUp15(time.Now().UTC().Add(2 * time.Hour))+ body := reservationRequestBody{+ Intervals: []reservationIntervalBody{{+ StartsAt: start.Format(time.RFC3339),+ EndsAt: start.Add(15 * time.Minute).Format(time.RFC3339),+ CapacityGB: 8,+ }},+ }+ out, err := json.Marshal(body)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ return out+}++func TestParseAndValidateReservationBody_happy(t *testing.T) {+ out, err := parseAndValidateReservationBody(validRequestBody(t))+ if err != nil {+ t.Fatalf("expected ok, got %v", err)+ }+ if len(out) != 1 {+ t.Fatalf("expected 1 interval, got %d", len(out))+ }+ if out[0].CapacityGB != 8 {+ t.Errorf("capacity_gb = %d, want 8", out[0].CapacityGB)+ }+}++func TestParseAndValidateReservationBody_rejections(t *testing.T) {+ cases := []struct {+ name string+ body string+ wantSub string+ }{+ {+ name: "empty body",+ body: ``,+ wantSub: "request body is required",+ },+ {+ name: "intervals empty",+ body: `{"intervals": []}`,+ wantSub: "must be non-empty",+ },+ {+ name: "non-aligned startsAt",+ body: func() string {+ start := alignUp15(time.Now().UTC().Add(2 * time.Hour)).Add(7 * time.Minute)+ return `{"intervals":[{"startsAt":"` + start.Format(time.RFC3339) + `","endsAt":"` + start.Add(15*time.Minute).Format(time.RFC3339) + `","capacityGb":8}]}`+ }(),+ wantSub: "aligned to 15 minutes",+ },+ {+ name: "endsAt mismatch",+ body: func() string {+ start := alignUp15(time.Now().UTC().Add(2 * time.Hour))+ return `{"intervals":[{"startsAt":"` + start.Format(time.RFC3339) + `","endsAt":"` + start.Add(30*time.Minute).Format(time.RFC3339) + `","capacityGb":8}]}`+ }(),+ wantSub: "endsAt must equal startsAt + 15 minutes",+ },+ {+ name: "capacity not multiple of 4",+ body: func() string {+ start := alignUp15(time.Now().UTC().Add(2 * time.Hour))+ return `{"intervals":[{"startsAt":"` + start.Format(time.RFC3339) + `","endsAt":"` + start.Add(15*time.Minute).Format(time.RFC3339) + `","capacityGb":3}]}`+ }(),+ wantSub: "multiple of 4",+ },+ {+ name: "capacity zero",+ body: func() string {+ start := alignUp15(time.Now().UTC().Add(2 * time.Hour))+ return `{"intervals":[{"startsAt":"` + start.Format(time.RFC3339) + `","endsAt":"` + start.Add(15*time.Minute).Format(time.RFC3339) + `","capacityGb":0}]}`+ }(),+ wantSub: "multiple of 4",+ },+ {+ name: "lead time violation",+ body: func() string {+ start := alignUp15(time.Now().UTC().Add(5 * time.Minute))+ return `{"intervals":[{"startsAt":"` + start.Format(time.RFC3339) + `","endsAt":"` + start.Add(15*time.Minute).Format(time.RFC3339) + `","capacityGb":8}]}`+ }(),+ wantSub: "lead-time window",+ },+ {+ name: "duplicate startsAt",+ body: func() string {+ start := alignUp15(time.Now().UTC().Add(2 * time.Hour))+ ends := start.Add(15 * time.Minute)+ one := `{"startsAt":"` + start.Format(time.RFC3339) + `","endsAt":"` + ends.Format(time.RFC3339) + `","capacityGb":4}`+ return `{"intervals":[` + one + `,` + one + `]}`+ }(),+ wantSub: "duplicates an earlier entry",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ _, err := parseAndValidateReservationBody([]byte(tc.body))+ if err == nil {+ t.Fatalf("expected error containing %q, got nil", tc.wantSub)+ }+ if !strings.Contains(err.Error(), tc.wantSub) {+ t.Errorf("error %q does not contain %q", err.Error(), tc.wantSub)+ }+ })+ }+}++func TestCursorRoundTrip(t *testing.T) {+ in := &db.ReservationCursor{+ CreatedAt: time.Date(2026, 4, 28, 18, 0, 5, 0, time.UTC),+ ReservationID: uuid.MustParse("9f67b8f7-7b91-4d2d-b1cb-19d0d0a14562"),+ }+ encoded := encodeCursor(in)+ if encoded == "" {+ t.Fatal("encoded cursor is empty")+ }+ if strings.ContainsAny(encoded, "+/=") {+ t.Errorf("cursor %q must be url-safe (no +, /, =)", encoded)+ }++ out, err := decodeCursor(encoded)+ if err != nil {+ t.Fatalf("decode: %v", err)+ }+ if !out.CreatedAt.Equal(in.CreatedAt) {+ t.Errorf("createdAt: got %v, want %v", out.CreatedAt, in.CreatedAt)+ }+ if out.ReservationID != in.ReservationID {+ t.Errorf("reservationId: got %v, want %v", out.ReservationID, in.ReservationID)+ }+}++func TestDecodeCursor_invalid(t *testing.T) {+ cases := []string{+ "!!!", // not base64+ "YWJj", // base64 but not JSON+ "e30", // {} — missing fields+ "eyJjcmVhdGVkQXQiOjF9", // partial JSON, missing reservationId+ }+ for _, raw := range cases {+ if _, err := decodeCursor(raw); err == nil {+ t.Errorf("expected error for cursor %q", raw)+ }+ }+}++func TestAlignUp15(t *testing.T) {+ cases := []struct {+ in string+ want string+ }{+ {"2026-04-28T18:00:00Z", "2026-04-28T18:00:00Z"}, // already aligned+ {"2026-04-28T18:00:01Z", "2026-04-28T18:15:00Z"}, // round up+ {"2026-04-28T18:14:59Z", "2026-04-28T18:15:00Z"},+ {"2026-04-28T18:15:00Z", "2026-04-28T18:15:00Z"},+ {"2026-04-28T18:59:59Z", "2026-04-28T19:00:00Z"},+ }+ for _, tc := range cases {+ in, _ := time.Parse(time.RFC3339, tc.in)+ want, _ := time.Parse(time.RFC3339, tc.want)+ got := alignUp15(in)+ if !got.Equal(want) {+ t.Errorf("alignUp15(%s) = %s, want %s", tc.in, got.Format(time.RFC3339), tc.want)+ }+ }+}++func TestIsAligned15(t *testing.T) {+ if !isAligned15(time.Date(2026, 4, 28, 18, 15, 0, 0, time.UTC)) {+ t.Error(":15 must be aligned")+ }+ if isAligned15(time.Date(2026, 4, 28, 18, 7, 0, 0, time.UTC)) {+ t.Error(":07 must not be aligned")+ }+ if isAligned15(time.Date(2026, 4, 28, 18, 0, 1, 0, time.UTC)) {+ t.Error("non-zero seconds must not be aligned")+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex c9872214..5fcd77d0 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -199,6 +199,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.GET("/sandboxes/:id", s.getSandbox)api.DELETE("/sandboxes/:id", s.killSandbox)+ // Reserved capacity (spec: ws-pricing/design/001-reserved-capacity-squares.md)+ api.GET("/capacity/calendar", s.getCapacityCalendar)+ api.POST("/capacity/reservations", s.createCapacityReservation)+ api.GET("/capacity/reservations", s.listCapacityReservations)+// Usage + tags (design: .agents/design/sandbox-tags-and-usage.md)api.GET("/usage", s.getUsage)api.GET("/tags", s.listTags)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 685fe624..4d59c3e7 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -52,6 +52,25 @@ func (s *Server) createSandbox(c echo.Context) error {})}+ // Memory cap (orgs.max_memory_gb). Same field is used as the+ // reservationLimitGb in the capacity calendar — the cap and the+ // reservation ceiling are the same number by design.+ if org.MaxMemoryGB > 0 {+ running, err := s.store.GetOrgRunningMemoryMB(ctx, orgID)+ if err == nil {+ requestedMB := cfg.MemoryMB+ if requestedMB == 0 {+ requestedMB = 4096 // matches the default applied below+ }+ maxMB := org.MaxMemoryGB * 1024+ if running+requestedMB > maxMB {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": fmt.Sprintf("memory cap exceeded: %d MB running + %d MB requested > %d MB org limit", running, requestedMB, maxMB),+ })+ }+ }+ }+// Free-tier: trial credits gate + machine-size restriction.if org.Plan == "free" {if org.FreeCreditsRemainingCents <= 0 {@@ -1571,7 +1590,9 @@ 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.+ // Free-tier credits gate + memory cap admission. Wake admits the sandbox+ // back into the running set, so it consumes against orgs.max_memory_gb+ // just like a fresh create.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 {@@ -1579,6 +1600,18 @@ func (s *Server) wakeSandbox(c echo.Context) error {"error": "free trial credits exhausted — upgrade to pro to resume sandboxes",})}+ if org.MaxMemoryGB > 0 {+ wakeMB, err := s.store.GetSandboxLatestMemoryMB(ctx, id)+ if err == nil {+ running, rerr := s.store.GetOrgRunningMemoryMB(ctx, orgID)+ maxMB := org.MaxMemoryGB * 1024+ if rerr == nil && running+wakeMB > maxMB {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": fmt.Sprintf("memory cap exceeded: %d MB running + %d MB wake > %d MB org limit", running, wakeMB, maxMB),+ })+ }+ }+ }}}diff --git a/internal/db/capacity.go b/internal/db/capacity.gonew file mode 100644index 00000000..9637967d--- /dev/null+++ b/internal/db/capacity.go@@ -0,0 +1,402 @@+package db++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "hash/fnv"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+)++// ResourceMemoryGB is the only capacity resource in v1. CPU, fractional GB,+// and region are spec'd as out-of-scope until product calls land.+const ResourceMemoryGB = "memory_gb"++// CapacityInterval is one 15-minute slice of a reservation.+type CapacityInterval struct {+ StartsAt time.Time `json:"startsAt"`+ EndsAt time.Time `json:"endsAt"`+ CapacityGB int `json:"capacityGb"`+}++// Reservation aggregates intervals that share a reservation_id.+type Reservation struct {+ ReservationID uuid.UUID `json:"reservationId"`+ CreatedAt time.Time `json:"createdAt"`+ Intervals []CapacityInterval `json:"intervals"`+}++// CalendarBucket is one 15-minute interval as returned by the calendar+// endpoint. ReservedGB is the per-org sum across all reservations for the+// bucket; the handler layers reservationLimitGb (org.MaxMemoryGB) on top.+type CalendarBucket struct {+ StartsAt time.Time `json:"startsAt"`+ EndsAt time.Time `json:"endsAt"`+ ReservedGB int `json:"reservedGb"`+}++// IntervalCapacityShortfall is one entry in the capacity_not_available 409+// response — naming each interval that didn't fit, with the requested vs.+// remaining headroom.+type IntervalCapacityShortfall struct {+ StartsAt time.Time `json:"startsAt"`+ RequestedGB int `json:"requestedGb"`+ ReservableGB int `json:"reservableGb"`+ Reason string `json:"reason"`+}++// CapacityShortfallError carries per-interval shortfalls so the handler can+// build the 409 capacity_not_available body.+type CapacityShortfallError struct {+ Intervals []IntervalCapacityShortfall+}++func (e *CapacityShortfallError) Error() string {+ return fmt.Sprintf("capacity not available for %d interval(s)", len(e.Intervals))+}++// IdempotencyConflictError is returned when the same Idempotency-Key was+// previously used with a different request body. The handler maps it to+// 409 idempotency_key_conflict per design/001.+type IdempotencyConflictError struct{}++func (e *IdempotencyConflictError) Error() string { return "idempotency key conflict" }++// IdempotencyReplay is returned when the cached row exists for this key+// with a matching body hash. Handler responds with the cached status code+// and body verbatim — a cached 409 stays a 409.+type IdempotencyReplay struct {+ StatusCode int+ ResponseBody json.RawMessage+}++func (e *IdempotencyReplay) Error() string { return "idempotency replay" }++// GetCapacityCalendar returns one bucket per 15-minute slice in [from, to).+// Both bounds must be UTC and aligned to :00/:15/:30/:45. The caller is+// responsible for span enforcement; the SQL just walks the series.+func (s *Store) GetCapacityCalendar(ctx context.Context, orgID uuid.UUID, from, to time.Time) ([]CalendarBucket, error) {+ rows, err := s.pool.Query(ctx, `+ WITH bucket(starts_at) AS (+ SELECT generate_series(+ $2::timestamptz,+ $3::timestamptz - INTERVAL '15 minutes',+ INTERVAL '15 minutes'+ )+ )+ SELECT+ bucket.starts_at,+ COALESCE(SUM(cri.capacity_gb), 0)::int AS reserved_gb+ FROM bucket+ LEFT JOIN capacity_reservation_intervals cri+ ON cri.org_id = $1+ AND cri.resource = $4+ AND cri.starts_at = bucket.starts_at+ GROUP BY bucket.starts_at+ ORDER BY bucket.starts_at+ `, orgID, from, to, ResourceMemoryGB)+ if err != nil {+ return nil, fmt.Errorf("calendar query: %w", err)+ }+ defer rows.Close()++ var out []CalendarBucket+ for rows.Next() {+ var b CalendarBucket+ if err := rows.Scan(&b.StartsAt, &b.ReservedGB); err != nil {+ return nil, fmt.Errorf("calendar scan: %w", err)+ }+ b.EndsAt = b.StartsAt.Add(15 * time.Minute)+ out = append(out, b)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("calendar rows: %w", err)+ }+ return out, nil+}++// CreateReservationRequest is the validated, normalised input to the write+// path. Validation (alignment, lead time, % 4 grain, non-empty, no+// duplicate (resource, startsAt)) lives in the handler — the Store assumes+// the input is well-formed.+type CreateReservationRequest struct {+ OrgID uuid.UUID+ IdempotencyKey string // empty when no header was sent+ IdempotencyEndpt string // e.g. "POST /api/capacity/reservations"+ RequestBodyHash []byte+ Intervals []CapacityInterval+}++// CreateReservation writes the ledger rows for one reservation, atomically.+// Per-interval contention is serialised by org-scoped advisory locks+// acquired in deterministic (resource, startsAt) order to avoid ABBA.+//+// Returns the new reservationId and createdAt on success. On contention or+// over-cap, returns *CapacityShortfallError (the handler emits 409+// capacity_not_available). On idempotency replay, returns *IdempotencyReplay+// with the cached body. On idempotency-body mismatch, returns+// *IdempotencyConflictError.+func (s *Store) CreateReservation(ctx context.Context, req CreateReservationRequest) (uuid.UUID, time.Time, error) {+ if req.IdempotencyKey != "" {+ var (+ cachedHash []byte+ cachedCode int+ cachedBody json.RawMessage+ )+ err := s.pool.QueryRow(ctx, `+ SELECT request_body_hash, status_code, response_body+ FROM capacity_idempotency_keys+ WHERE org_id = $1 AND endpoint = $2 AND key = $3 AND expires_at > now()+ `, req.OrgID, req.IdempotencyEndpt, req.IdempotencyKey).Scan(&cachedHash, &cachedCode, &cachedBody)+ if err == nil {+ if !bytesEq(cachedHash, req.RequestBodyHash) {+ return uuid.Nil, time.Time{}, &IdempotencyConflictError{}+ }+ return uuid.Nil, time.Time{}, &IdempotencyReplay{StatusCode: cachedCode, ResponseBody: cachedBody}+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return uuid.Nil, time.Time{}, fmt.Errorf("idempotency lookup: %w", err)+ }+ }++ maxMemoryGB, err := s.getOrgMaxMemoryGB(ctx, req.OrgID)+ if err != nil {+ return uuid.Nil, time.Time{}, err+ }++ tx, err := s.pool.Begin(ctx)+ if err != nil {+ return uuid.Nil, time.Time{}, fmt.Errorf("begin tx: %w", err)+ }+ defer tx.Rollback(ctx)++ // Deterministic lock order: (resource, startsAt). Caller guarantees no+ // duplicate (resource, startsAt) pairs, so order is total.+ for _, iv := range req.Intervals {+ key := advisoryLockKey(req.OrgID, ResourceMemoryGB, iv.StartsAt)+ if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, key); err != nil {+ return uuid.Nil, time.Time{}, fmt.Errorf("advisory lock: %w", err)+ }+ }++ // Re-read existing reserved sums under lock — anything that wasn't held+ // by us at lookup time can't change for the rest of this tx.+ shortfalls := make([]IntervalCapacityShortfall, 0)+ for _, iv := range req.Intervals {+ var existingGB int+ err := tx.QueryRow(ctx, `+ SELECT COALESCE(SUM(capacity_gb), 0)::int+ FROM capacity_reservation_intervals+ WHERE org_id = $1 AND resource = $2 AND starts_at = $3+ `, req.OrgID, ResourceMemoryGB, iv.StartsAt).Scan(&existingGB)+ if err != nil {+ return uuid.Nil, time.Time{}, fmt.Errorf("read existing reserved: %w", err)+ }+ reservable := maxMemoryGB - existingGB+ if reservable < 0 {+ reservable = 0+ }+ if iv.CapacityGB > reservable {+ shortfalls = append(shortfalls, IntervalCapacityShortfall{+ StartsAt: iv.StartsAt,+ RequestedGB: iv.CapacityGB,+ ReservableGB: reservable,+ Reason: "insufficient_capacity",+ })+ }+ }+ if len(shortfalls) > 0 {+ return uuid.Nil, time.Time{}, &CapacityShortfallError{Intervals: shortfalls}+ }++ reservationID := uuid.New()+ createdAt := time.Now().UTC()++ var idemRowID *uuid.UUID+ if req.IdempotencyKey != "" {+ // Reserve the idempotency row first so the FK pointer on the ledger+ // rows can reference it. Insert is deferred until we have a body to+ // cache, but we need its id now for the FK column.+ newID := uuid.New()+ idemRowID = &newID+ }++ for _, iv := range req.Intervals {+ _, err := tx.Exec(ctx, `+ INSERT INTO capacity_reservation_intervals+ (reservation_id, org_id, resource, starts_at, ends_at, capacity_gb, created_at, idempotency_key_id)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ `, reservationID, req.OrgID, ResourceMemoryGB, iv.StartsAt, iv.EndsAt, iv.CapacityGB, createdAt, idemRowID)+ if err != nil {+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) && pgErr.Code == "23505" {+ // Defence in depth — the advisory lock + read-then-write should+ // preclude PK collisions, but if one slips through, surface as+ // shortfall rather than 500.+ return uuid.Nil, time.Time{}, &CapacityShortfallError{+ Intervals: []IntervalCapacityShortfall{{+ StartsAt: iv.StartsAt,+ RequestedGB: iv.CapacityGB,+ Reason: "concurrent_write",+ }},+ }+ }+ return uuid.Nil, time.Time{}, fmt.Errorf("insert interval: %w", err)+ }+ }++ if err := tx.Commit(ctx); err != nil {+ return uuid.Nil, time.Time{}, fmt.Errorf("commit: %w", err)+ }+ return reservationID, createdAt, nil+}++// SaveIdempotencyResult writes the cached response for an Idempotency-Key+// after the handler has built the body. Called once per write request that+// carried an Idempotency-Key, regardless of outcome (200, 409, etc.).+func (s *Store) SaveIdempotencyResult(ctx context.Context, orgID uuid.UUID, endpoint, key string, bodyHash []byte, statusCode int, responseBody json.RawMessage) error {+ if key == "" {+ return nil+ }+ _, err := s.pool.Exec(ctx, `+ INSERT INTO capacity_idempotency_keys+ (org_id, endpoint, key, request_body_hash, status_code, response_body, expires_at)+ VALUES ($1, $2, $3, $4, $5, $6, now() + INTERVAL '24 hours')+ ON CONFLICT (org_id, endpoint, key) DO NOTHING+ `, orgID, endpoint, key, bodyHash, statusCode, responseBody)+ if err != nil {+ return fmt.Errorf("save idempotency: %w", err)+ }+ return nil+}++// ListReservationsRequest carries the filters for the audit-list endpoint.+type ListReservationsRequest struct {+ OrgID uuid.UUID+ From time.Time+ To time.Time+ Limit int+ Cursor *ReservationCursor // nil on the first page+}++// ReservationCursor is the opaque pagination cursor decoded by the handler.+// Encoding lives in the handler so the storage layer doesn't need to know+// about base64.+type ReservationCursor struct {+ CreatedAt time.Time+ ReservationID uuid.UUID+}++// ListReservations returns reservations in (createdAt DESC, reservationId+// DESC) order. The result is one row per reservation_id with its intervals+// aggregated. NextCursor is non-nil when more rows exist past the limit.+func (s *Store) ListReservations(ctx context.Context, req ListReservationsRequest) ([]Reservation, *ReservationCursor, error) {+ limit := req.Limit+ if limit <= 0 {+ limit = 50+ }++ args := []any{req.OrgID, req.From, req.To, ResourceMemoryGB, limit + 1}+ cursorClause := ""+ if req.Cursor != nil {+ cursorClause = `AND (created_at, reservation_id) < ($6, $7)`+ args = append(args, req.Cursor.CreatedAt, req.Cursor.ReservationID)+ }++ query := fmt.Sprintf(`+ SELECT+ reservation_id,+ MIN(created_at) AS created_at,+ jsonb_agg(+ jsonb_build_object(+ 'startsAt', starts_at,+ 'endsAt', ends_at,+ 'capacityGb', capacity_gb+ ) ORDER BY starts_at+ ) AS intervals+ FROM capacity_reservation_intervals+ WHERE org_id = $1+ AND resource = $4+ AND created_at >= $2+ AND created_at < $3+ %s+ GROUP BY reservation_id+ ORDER BY MIN(created_at) DESC, reservation_id DESC+ LIMIT $5+ `, cursorClause)++ rows, err := s.pool.Query(ctx, query, args...)+ if err != nil {+ return nil, nil, fmt.Errorf("list reservations: %w", err)+ }+ defer rows.Close()++ out := make([]Reservation, 0, limit)+ for rows.Next() {+ var r Reservation+ var intervalsJSON []byte+ if err := rows.Scan(&r.ReservationID, &r.CreatedAt, &intervalsJSON); err != nil {+ return nil, nil, fmt.Errorf("scan reservation: %w", err)+ }+ if err := json.Unmarshal(intervalsJSON, &r.Intervals); err != nil {+ return nil, nil, fmt.Errorf("decode intervals: %w", err)+ }+ out = append(out, r)+ }+ if err := rows.Err(); err != nil {+ return nil, nil, fmt.Errorf("list rows: %w", err)+ }++ var next *ReservationCursor+ if len(out) > limit {+ last := out[limit-1]+ next = &ReservationCursor{CreatedAt: last.CreatedAt, ReservationID: last.ReservationID}+ out = out[:limit]+ }+ return out, next, nil+}++func (s *Store) getOrgMaxMemoryGB(ctx context.Context, orgID uuid.UUID) (int, error) {+ var v int+ err := s.pool.QueryRow(ctx, `SELECT max_memory_gb FROM orgs WHERE id = $1`, orgID).Scan(&v)+ if err != nil {+ return 0, fmt.Errorf("read max_memory_gb: %w", err)+ }+ return v, nil+}++// advisoryLockKey hashes (org, resource, startsAt) into the int64 keyspace+// used by pg_advisory_xact_lock. fnv64 is collision-prone at scale, but a+// collision here just means two unrelated tuples wait on each other for one+// transaction — a perf nit, not a correctness bug.+func advisoryLockKey(orgID uuid.UUID, resource string, startsAt time.Time) int64 {+ h := fnv.New64a()+ h.Write(orgID[:])+ h.Write([]byte{0})+ h.Write([]byte(resource))+ h.Write([]byte{0})+ var ts [8]byte+ t := startsAt.UTC().Unix()+ for i := 0; i < 8; i++ {+ ts[i] = byte(t >> (i * 8))+ }+ h.Write(ts[:])+ return int64(h.Sum64())+}++func bytesEq(a, b []byte) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i] != b[i] {+ return false+ }+ }+ return true+}diff --git a/internal/db/capacity_pgfixture_test.go b/internal/db/capacity_pgfixture_test.gonew file mode 100644index 00000000..e8b4e925--- /dev/null+++ b/internal/db/capacity_pgfixture_test.go@@ -0,0 +1,310 @@+//go:build pgfixture++// Integration tests for the reserved-capacity Store methods. Run only+// under `go test -tags=pgfixture` against a real Postgres pointed at by+// TEST_DATABASE_URL — the advisory-lock and idempotency-key paths cannot+// be exercised in pure-Go because they depend on Postgres semantics+// (transaction-scoped locks, row-level conflict, JSONB aggregation).+//+// Run locally:+//+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \+// go test -tags=pgfixture ./internal/db/ -run Capacity -v+package db++import (+ "context"+ "crypto/sha256"+ "errors"+ "sync"+ "testing"+ "time"++ "github.com/google/uuid"+)++// seedOrgWithCap inserts a fresh org with a known max_memory_gb so the+// capacity tests can assert against a deterministic ceiling.+func seedOrgWithCap(t *testing.T, store *Store, maxMemoryGB int) uuid.UUID {+ t.Helper()+ ctx := context.Background()+ orgID := uuid.New()+ _, err := store.pool.Exec(ctx, `+ INSERT INTO orgs (id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_timeout_sec, max_disk_mb, max_memory_gb)+ VALUES ($1, $2, $3, 'pro', 100, 86400, 20480, $4)+ `, orgID, "cap-"+orgID.String()[:8], "cap-"+orgID.String()[:8], maxMemoryGB)+ if err != nil {+ t.Fatalf("seed org: %v", err)+ }+ return orgID+}++func aligned(base time.Time, m int) time.Time {+ return base.Truncate(15 * time.Minute).Add(time.Duration(m) * 15 * time.Minute)+}++func TestCapacityCalendar_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 16)++ // Anchor far in the future so nothing else collides.+ base := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC)+ from := base+ to := base.Add(2 * time.Hour) // 8 buckets++ // Two reservations, partially overlapping at bucket 2 (sum should be 12).+ r1 := uuid.New()+ r2 := uuid.New()+ ins := func(reservationID uuid.UUID, m int, gb int) {+ _, err := store.pool.Exec(ctx, `+ INSERT INTO capacity_reservation_intervals+ (reservation_id, org_id, resource, starts_at, ends_at, capacity_gb)+ VALUES ($1, $2, 'memory_gb', $3, $4, $5)+ `, reservationID, orgID, aligned(base, m), aligned(base, m+1), gb)+ if err != nil {+ t.Fatalf("seed interval: %v", err)+ }+ }+ ins(r1, 1, 4)+ ins(r1, 2, 8)+ ins(r2, 2, 4)+ ins(r2, 3, 12)++ buckets, err := store.GetCapacityCalendar(ctx, orgID, from, to)+ if err != nil {+ t.Fatalf("calendar: %v", err)+ }+ if len(buckets) != 8 {+ t.Fatalf("expected 8 buckets, got %d", len(buckets))+ }+ want := map[int]int{0: 0, 1: 4, 2: 12, 3: 12, 4: 0, 5: 0, 6: 0, 7: 0}+ for i, b := range buckets {+ if b.ReservedGB != want[i] {+ t.Errorf("bucket[%d] = %d, want %d (startsAt=%s)", i, b.ReservedGB, want[i], b.StartsAt)+ }+ if !b.EndsAt.Equal(b.StartsAt.Add(15 * time.Minute)) {+ t.Errorf("bucket[%d] endsAt mismatch", i)+ }+ }+}++func TestCreateReservation_capExceeded_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 8) // cap = 8 GB++ base := time.Date(2030, 2, 1, 0, 0, 0, 0, time.UTC)+ bodyHash := sha256.Sum256([]byte(`{"oversize":true}`))++ _, _, err := store.CreateReservation(ctx, CreateReservationRequest{+ OrgID: orgID,+ RequestBodyHash: bodyHash[:],+ Intervals: []CapacityInterval{{+ StartsAt: aligned(base, 0),+ EndsAt: aligned(base, 1),+ CapacityGB: 12, // 12 > cap of 8+ }},+ })+ var shortfall *CapacityShortfallError+ if !errors.As(err, &shortfall) {+ t.Fatalf("expected CapacityShortfallError, got %v", err)+ }+ if len(shortfall.Intervals) != 1 || shortfall.Intervals[0].ReservableGB != 8 {+ t.Errorf("unexpected shortfall: %+v", shortfall.Intervals)+ }+}++func TestCreateReservation_idempotencyReplay_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 16)++ base := time.Date(2030, 3, 1, 0, 0, 0, 0, time.UTC)+ body := []byte(`{"intervals":[{"startsAt":"2030-03-01T00:00:00Z","endsAt":"2030-03-01T00:15:00Z","capacityGb":4}]}`)+ bodyHash := sha256.Sum256(body)++ req := CreateReservationRequest{+ OrgID: orgID,+ IdempotencyKey: "test-key-1",+ IdempotencyEndpt: "POST /api/capacity/reservations",+ RequestBodyHash: bodyHash[:],+ Intervals: []CapacityInterval{{+ StartsAt: aligned(base, 0),+ EndsAt: aligned(base, 1),+ CapacityGB: 4,+ }},+ }++ // First call: writes the reservation. Cache the (synthetic) success body.+ rid, _, err := store.CreateReservation(ctx, req)+ if err != nil {+ t.Fatalf("first call: %v", err)+ }+ if rid == uuid.Nil {+ t.Fatal("expected non-nil reservationId")+ }+ if err := store.SaveIdempotencyResult(ctx, orgID, req.IdempotencyEndpt, req.IdempotencyKey, bodyHash[:], 200, []byte(`{"reservationId":"`+rid.String()+`"}`)); err != nil {+ t.Fatalf("save idempotency: %v", err)+ }++ // Second call: same body, same key — should replay.+ _, _, err = store.CreateReservation(ctx, req)+ var replay *IdempotencyReplay+ if !errors.As(err, &replay) {+ t.Fatalf("expected IdempotencyReplay, got %v", err)+ }+ if replay.StatusCode != 200 {+ t.Errorf("replay status: got %d, want 200", replay.StatusCode)+ }++ // Third call: same key, different body — should conflict.+ conflictReq := req+ otherHash := sha256.Sum256([]byte(`{"different":true}`))+ conflictReq.RequestBodyHash = otherHash[:]+ _, _, err = store.CreateReservation(ctx, conflictReq)+ var conflict *IdempotencyConflictError+ if !errors.As(err, &conflict) {+ t.Fatalf("expected IdempotencyConflictError, got %v", err)+ }+}++// TestCreateReservation_concurrentSerializes proves the advisory-lock+// path. Two goroutines try to reserve 10 GB on the same bucket of an+// 16-GB-cap org. The first succeeds; the second must see the post-lock+// state and return a shortfall — not a duplicate insert, not a 500.+func TestCreateReservation_concurrentSerializes_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 16)++ base := time.Date(2030, 4, 1, 0, 0, 0, 0, time.UTC)+ hash := sha256.Sum256([]byte(`{}`))++ makeReq := func() CreateReservationRequest {+ return CreateReservationRequest{+ OrgID: orgID,+ RequestBodyHash: hash[:],+ Intervals: []CapacityInterval{{+ StartsAt: aligned(base, 0),+ EndsAt: aligned(base, 1),+ CapacityGB: 12,+ }},+ }+ }++ type result struct {+ rid uuid.UUID+ err error+ }+ results := make(chan result, 2)+ var wg sync.WaitGroup+ wg.Add(2)+ for i := 0; i < 2; i++ {+ go func() {+ defer wg.Done()+ rid, _, err := store.CreateReservation(ctx, makeReq())+ results <- result{rid: rid, err: err}+ }()+ }+ wg.Wait()+ close(results)++ successes := 0+ shortfalls := 0+ for r := range results {+ if r.err == nil {+ successes+++ continue+ }+ var s *CapacityShortfallError+ if errors.As(r.err, &s) {+ shortfalls+++ continue+ }+ t.Errorf("unexpected error: %v", r.err)+ }+ if successes != 1 || shortfalls != 1 {+ t.Errorf("expected 1 success and 1 shortfall, got successes=%d shortfalls=%d", successes, shortfalls)+ }+}++func TestListReservations_cursor_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ base := time.Date(2030, 5, 1, 0, 0, 0, 0, time.UTC)+ hash := sha256.Sum256([]byte(`{}`))++ // Five distinct reservations on five distinct buckets.+ for i := 0; i < 5; i++ {+ _, _, err := store.CreateReservation(ctx, CreateReservationRequest{+ OrgID: orgID,+ RequestBodyHash: hash[:],+ Intervals: []CapacityInterval{{+ StartsAt: aligned(base, i),+ EndsAt: aligned(base, i+1),+ CapacityGB: 4,+ }},+ })+ if err != nil {+ t.Fatalf("create %d: %v", i, err)+ }+ // Avoid timestamp ties — pagination ordering uses (created_at,+ // reservation_id) as the cursor key, and tied created_at would make+ // the assertion non-deterministic without also pinning IDs.+ time.Sleep(2 * time.Millisecond)+ }++ from := time.Date(2029, 1, 1, 0, 0, 0, 0, time.UTC)+ to := time.Date(2031, 1, 1, 0, 0, 0, 0, time.UTC)++ first, next, err := store.ListReservations(ctx, ListReservationsRequest{+ OrgID: orgID, From: from, To: to, Limit: 2,+ })+ if err != nil {+ t.Fatalf("list page 1: %v", err)+ }+ if len(first) != 2 {+ t.Fatalf("page 1 size: got %d, want 2", len(first))+ }+ if next == nil {+ t.Fatal("expected non-nil cursor after page 1")+ }++ second, next2, err := store.ListReservations(ctx, ListReservationsRequest{+ OrgID: orgID, From: from, To: to, Limit: 2, Cursor: next,+ })+ if err != nil {+ t.Fatalf("list page 2: %v", err)+ }+ if len(second) != 2 {+ t.Fatalf("page 2 size: got %d, want 2", len(second))+ }+ if next2 == nil {+ t.Fatal("expected non-nil cursor after page 2")+ }++ third, next3, err := store.ListReservations(ctx, ListReservationsRequest{+ OrgID: orgID, From: from, To: to, Limit: 2, Cursor: next2,+ })+ if err != nil {+ t.Fatalf("list page 3: %v", err)+ }+ if len(third) != 1 {+ t.Fatalf("page 3 size: got %d, want 1", len(third))+ }+ if next3 != nil {+ t.Errorf("expected nil cursor on final page, got %+v", next3)+ }++ // No reservation_id should appear twice across the three pages.+ seen := map[uuid.UUID]struct{}{}+ for _, r := range append(append(first, second...), third...) {+ if _, dup := seen[r.ReservationID]; dup {+ t.Errorf("reservation %s appeared on multiple pages", r.ReservationID)+ }+ seen[r.ReservationID] = struct{}{}+ }+}diff --git a/internal/db/migrations/027_capacity_reservation_intervals.down.sql b/internal/db/migrations/027_capacity_reservation_intervals.down.sqlnew file mode 100644index 00000000..dbc14096--- /dev/null+++ b/internal/db/migrations/027_capacity_reservation_intervals.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS capacity_reservation_intervals;diff --git a/internal/db/migrations/027_capacity_reservation_intervals.up.sql b/internal/db/migrations/027_capacity_reservation_intervals.up.sqlnew file mode 100644index 00000000..5913bb2a--- /dev/null+++ b/internal/db/migrations/027_capacity_reservation_intervals.up.sql@@ -0,0 +1,33 @@+-- Append-only ledger of reserved-capacity commitments.+-- One row per (reservation_id, resource, starts_at). Multiple rows share a+-- reservation_id when the customer commits to several 15-minute buckets in+-- a single POST. The ledger is the source of truth for the calendar+-- aggregation, the audit-list endpoint, and (in phase 2) the per-second+-- overage allocator.+CREATE TABLE IF NOT EXISTS capacity_reservation_intervals (+ reservation_id UUID NOT NULL,+ org_id UUID NOT NULL,+ resource TEXT NOT NULL,+ starts_at TIMESTAMPTZ NOT NULL,+ ends_at TIMESTAMPTZ NOT NULL,+ capacity_gb INTEGER NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ idempotency_key_id UUID,+ PRIMARY KEY (reservation_id, resource, starts_at),+ -- 1 GB-hour grain: capacity in 4 GB × 15 min units. Reject anything else+ -- at the schema level so a buggy handler can't write fractional grain.+ CHECK (capacity_gb > 0 AND capacity_gb % 4 = 0),+ -- Bucket must be exactly 15 minutes; multi-interval spans are rejected+ -- at the API layer but the schema enforces it as a final guard.+ CHECK (ends_at = starts_at + INTERVAL '15 minutes'),+ -- v1 only knows 'memory_gb'. Future resources extend this.+ CHECK (resource IN ('memory_gb'))+);++-- Calendar aggregation reads (org_id, resource, starts_at) range scans and+-- sums capacity_gb. List pagination orders by (created_at DESC,+-- reservation_id DESC). Two indexes to serve both shapes.+CREATE INDEX IF NOT EXISTS idx_capacity_intervals_org_resource_starts+ ON capacity_reservation_intervals (org_id, resource, starts_at);+CREATE INDEX IF NOT EXISTS idx_capacity_intervals_org_created+ ON capacity_reservation_intervals (org_id, created_at DESC, reservation_id DESC);diff --git a/internal/db/migrations/028_capacity_idempotency_keys.down.sql b/internal/db/migrations/028_capacity_idempotency_keys.down.sqlnew file mode 100644index 00000000..0e0307e0--- /dev/null+++ b/internal/db/migrations/028_capacity_idempotency_keys.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS capacity_idempotency_keys;diff --git a/internal/db/migrations/028_capacity_idempotency_keys.up.sql b/internal/db/migrations/028_capacity_idempotency_keys.up.sqlnew file mode 100644index 00000000..37d0543e--- /dev/null+++ b/internal/db/migrations/028_capacity_idempotency_keys.up.sql@@ -0,0 +1,20 @@+-- Cached results of write requests keyed by Idempotency-Key header.+-- Replays return the original status_code + response_body verbatim, so a+-- cached 409 stays a 409. Same key with a different request body returns+-- idempotency_key_conflict (handler responsibility, not schema).+CREATE TABLE IF NOT EXISTS capacity_idempotency_keys (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID NOT NULL,+ endpoint TEXT NOT NULL,+ key TEXT NOT NULL,+ request_body_hash BYTEA NOT NULL,+ status_code INTEGER NOT NULL,+ response_body JSONB NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ expires_at TIMESTAMPTZ NOT NULL,+ UNIQUE (org_id, endpoint, key)+);++-- Cleanup sweeps query expires_at < now().+CREATE INDEX IF NOT EXISTS idx_capacity_idempotency_expires+ ON capacity_idempotency_keys (expires_at);diff --git a/internal/db/migrations/029_orgs_max_memory_gb.down.sql b/internal/db/migrations/029_orgs_max_memory_gb.down.sqlnew file mode 100644index 00000000..d2e24639--- /dev/null+++ b/internal/db/migrations/029_orgs_max_memory_gb.down.sql@@ -0,0 +1 @@+ALTER TABLE orgs DROP COLUMN IF EXISTS max_memory_gb;diff --git a/internal/db/migrations/029_orgs_max_memory_gb.up.sql b/internal/db/migrations/029_orgs_max_memory_gb.up.sqlnew file mode 100644index 00000000..c24e4caf--- /dev/null+++ b/internal/db/migrations/029_orgs_max_memory_gb.up.sql@@ -0,0 +1,8 @@+-- Per-org ceiling on concurrent in-memory sandbox capacity, in whole GB.+-- Used both as the reservationLimitGb in the capacity calendar and as the+-- runtime admission cap when creating or waking sandboxes. Same shape as+-- max_disk_mb (migration 019). Default 2 covers free tier; pro orgs are+-- backfilled to 16. Per-row admin overrides remain available afterwards.+ALTER TABLE orgs ADD COLUMN max_memory_gb INTEGER NOT NULL DEFAULT 2+ CHECK (max_memory_gb >= 0);+UPDATE orgs SET max_memory_gb = 16 WHERE plan = 'pro';diff --git a/internal/db/store.go b/internal/db/store.goindex ea1ae0d1..b4068fef 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -120,6 +120,9 @@ func (s *Store) Migrate(ctx context.Context) error {{27, "migrations/024_patch_error_tracking.up.sql"},{28, "migrations/025_sandbox_golden_version.up.sql"},{29, "migrations/026_sandbox_tags.up.sql"},+ {30, "migrations/027_capacity_reservation_intervals.up.sql"},+ {31, "migrations/028_capacity_idempotency_keys.up.sql"},+ {32, "migrations/029_orgs_max_memory_gb.up.sql"},}for _, m := range migrations {@@ -160,6 +163,7 @@ type Org struct {MaxConcurrentSandboxes int `json:"maxConcurrentSandboxes"`MaxSandboxTimeoutSec int `json:"maxSandboxTimeoutSec"`MaxDiskMB int `json:"maxDiskMB"`+ MaxMemoryGB int `json:"maxMemoryGB"`CreatedAt time.Time `json:"createdAt"`UpdatedAt time.Time `json:"updatedAt"`@@ -192,7 +196,7 @@ type Org struct {}// orgColumns is the list of columns returned by all Org queries.-const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_timeout_sec, max_disk_mb, created_at, updated_at,+const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_timeout_sec, max_disk_mb, max_memory_gb, created_at, updated_at,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,@@ -204,7 +208,7 @@ func scanOrg(row pgx.Row) (*Org, error) {org := &Org{}err := row.Scan(&org.ID, &org.Name, &org.Slug, &org.Plan, &org.MaxConcurrentSandboxes,- &org.MaxSandboxTimeoutSec, &org.MaxDiskMB, &org.CreatedAt, &org.UpdatedAt,+ &org.MaxSandboxTimeoutSec, &org.MaxDiskMB, &org.MaxMemoryGB, &org.CreatedAt, &org.UpdatedAt,&org.CustomDomain, &org.CFHostnameID, &org.DomainVerificationStatus, &org.DomainSSLStatus,&org.VerificationTxtName, &org.VerificationTxtValue, &org.SSLTxtName, &org.SSLTxtValue,&org.WorkOSOrgID, &org.IsPersonal, &org.OwnerUserID, &org.CreditBalanceCents,@@ -789,6 +793,37 @@ func (s *Store) CountActiveSandboxes(ctx context.Context, orgID uuid.UUID) (int,return count, err}+// GetOrgRunningMemoryMB sums memory_mb of currently-open scale events for+// the org's running sandboxes. Used to enforce orgs.max_memory_gb at create+// and wake admission. Hibernated sandboxes are excluded — their memory is+// only "spent" when they're running.+func (s *Store) GetOrgRunningMemoryMB(ctx context.Context, orgID uuid.UUID) (int, error) {+ var total int+ err := s.pool.QueryRow(ctx,+ `SELECT COALESCE(SUM(e.memory_mb), 0)::int+ FROM sandbox_scale_events e+ INNER JOIN sandbox_sessions s ON s.sandbox_id = e.sandbox_id+ WHERE e.org_id = $1+ AND e.ended_at IS NULL+ AND s.status = 'running'`, orgID,+ ).Scan(&total)+ return total, err+}++// GetSandboxLatestMemoryMB returns the memory_mb of the sandbox's most+// recent scale event (open or closed). Used at wake time to size the+// admission check before transitioning the sandbox back to running.+func (s *Store) GetSandboxLatestMemoryMB(ctx context.Context, sandboxID string) (int, error) {+ var mem int+ err := s.pool.QueryRow(ctx,+ `SELECT memory_mb FROM sandbox_scale_events+ WHERE sandbox_id = $1+ ORDER BY started_at DESC+ LIMIT 1`, sandboxID,+ ).Scan(&mem)+ return mem, err+}+// --- Command Log operations (for NATS sync consumer) ---type CommandLog struct {