An open-source, faster Devin alternative
TypeScript
feat(capacity): add internal GET /api/capacity/billable-events for outbox inspection
Igor Zalutski0658eee7d941
diff --git a/internal/api/capacity.go b/internal/api/capacity.goindex 264612b3..d38bb2d8 100644--- a/internal/api/capacity.go+++ b/internal/api/capacity.go@@ -217,6 +217,92 @@ func (s *Server) listCapacityReservations(c echo.Context) error {return c.JSON(http.StatusOK, resp)}+// getCapacityBillableEvents → GET /api/capacity/billable-events+//+// **INTERNAL — INTENTIONALLY UNDOCUMENTED.**+// This endpoint surfaces the phase-2 outbox (`billable_events`) for the+// caller's org so the allocator can be verified end-to-end without DB+// access. It is deliberately not in the public spec+// (ws-pricing/design/001-reserved-capacity-squares.md), not advertised+// to customers, and may be removed once the unified pipeline is fully+// cut over and the dashboard exposes this data through a proper UI.+//+// Future agents: do **not** add this to the spec or to docs. If the+// debugging need has gone away (phase 3 cut over, dashboard view+// landed), feel free to delete it.+//+// Response shape mirrors the DB row 1:1 — no normalisation — so it's+// useful as a raw inspection tool, not a customer-facing contract.+func (s *Server) getCapacityBillableEvents(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"), capacityMaxListSpan)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }++ eventType := c.QueryParam("eventType")+ switch eventType {+ case "", db.BillableEventReservedUsage, db.BillableEventOverageUsage, db.BillableEventDiskOverageUsage:+ // ok+ default:+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "eventType must be one of reserved_usage, overage_usage, disk_overage_usage (or omitted for all)",+ })+ }++ limit := capacityListDefaultLimit+ if raw := c.QueryParam("limit"); raw != "" {+ var n int+ if _, perr := fmt.Sscanf(raw, "%d", &n); perr != 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+ }++ ctx, cancel := context.WithTimeout(c.Request().Context(), capacityHandlerTimeout)+ defer cancel()++ events, err := s.store.ListBillableEventsForOrg(ctx, orgID, from, to, eventType, limit)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ items := make([]map[string]any, 0, len(events))+ for _, e := range events {+ row := map[string]any{+ "id": e.ID.String(),+ "eventType": e.EventType,+ "memoryMb": e.MemoryMB,+ "gbSeconds": e.GBSeconds,+ "bucketStart": e.BucketStart.UTC().Format(time.RFC3339),+ "bucketEnd": e.BucketEnd.UTC().Format(time.RFC3339),+ "deliveryState": e.DeliveryState,+ "createdAt": e.CreatedAt.UTC().Format(time.RFC3339),+ }+ if e.StripeEventID != nil {+ row["stripeEventId"] = *e.StripeEventID+ }+ if e.DeliveredAt != nil {+ row["deliveredAt"] = e.DeliveredAt.UTC().Format(time.RFC3339)+ }+ items = append(items, row)+ }+ return c.JSON(http.StatusOK, map[string]any{+ "events": items,+ "count": len(items),+ })+}+// --- request parsing / validation ---type reservationRequestBody struct {diff --git a/internal/api/router.go b/internal/api/router.goindex 5fcd77d0..afc63fd7 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -203,6 +203,9 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.GET("/capacity/calendar", s.getCapacityCalendar)api.POST("/capacity/reservations", s.createCapacityReservation)api.GET("/capacity/reservations", s.listCapacityReservations)+ // Internal/undocumented — phase-2 outbox inspection. See note in+ // getCapacityBillableEvents handler.+ api.GET("/capacity/billable-events", s.getCapacityBillableEvents)// Usage + tags (design: .agents/design/sandbox-tags-and-usage.md)api.GET("/usage", s.getUsage)diff --git a/internal/db/billable_events.go b/internal/db/billable_events.goindex 85a2ce9b..9f3ce72e 100644--- a/internal/db/billable_events.go+++ b/internal/db/billable_events.go@@ -237,6 +237,56 @@ func (s *Store) GetScaleEventsForBucket(ctx context.Context, orgID uuid.UUID, bureturn out, nil}+// ListBillableEventsForOrg returns rows for one org in+// `[from, to)` ordered by `(bucket_start, event_type, memory_mb)`.+// `eventType` is optional — empty string returns all types.+// Used only by the org-scoped debugging endpoint+// `GET /api/capacity/billable-events`; not part of the public spec.+func (s *Store) ListBillableEventsForOrg(ctx context.Context, orgID uuid.UUID, from, to time.Time, eventType string, limit int) ([]BillableEvent, error) {+ if limit <= 0 {+ limit = 200+ }+ args := []any{orgID, from, to, limit}+ typeFilter := ""+ if eventType != "" {+ typeFilter = "AND event_type = $5"+ args = append(args, eventType)+ }+ rows, err := s.pool.Query(ctx, `+ SELECT id, org_id, event_type, memory_mb, gb_seconds,+ bucket_start, bucket_end, delivery_state,+ stripe_event_id, created_at, delivered_at+ FROM billable_events+ WHERE org_id = $1+ AND bucket_start >= $2+ AND bucket_start < $3+ `+typeFilter+`+ ORDER BY bucket_start, event_type, memory_mb+ LIMIT $4+ `, args...)+ if err != nil {+ return nil, fmt.Errorf("list billable events for org: %w", err)+ }+ defer rows.Close()++ out := make([]BillableEvent, 0, limit)+ for rows.Next() {+ var e BillableEvent+ if err := rows.Scan(+ &e.ID, &e.OrgID, &e.EventType, &e.MemoryMB, &e.GBSeconds,+ &e.BucketStart, &e.BucketEnd, &e.DeliveryState,+ &e.StripeEventID, &e.CreatedAt, &e.DeliveredAt,+ ); err != nil {+ return nil, fmt.Errorf("scan billable event: %w", err)+ }+ out = append(out, e)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("billable events rows: %w", err)+ }+ return out, nil+}+// ListBillableEventsForBucket returns every emitted row for a single// (org, bucket) pair across all event types. Used by the shadow-verify// script and the dashboard breakdown view to reconcile against