feat(usage): add GET /v1/usage/summary aggregate route
The portal's 30-day views folded at most 1000 events from the usage list, so busy tenants saw figures that were too low. The summary aggregates every matching event in the store (GROUP BY in Postgres, the same fold in Memory): counts, quantity sums and the latest occurred_at per product and metric, and counts and sums per UTC day and metric. Same filters, tenant pinning for user tokens and route group (usage.read) as GET /v1/usage/events, so the portal's service client needs no new AUTHZ grant. Both stores share the filter (usageWhere / matches). Refs: t80 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8a72469e18
commit
9138ac586b
11 files changed
+532
-43
No files matched your search
@@ -95,6 +95,7 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
|
||||
{"GET", "/v1/subscriptions?tenant_id=00000000-0000-0000-0000-000000000001"},
|
||||
{"POST", "/v1/usage/events"},
|
||||
{"GET", "/v1/usage/events?tenant_id=00000000-0000-0000-0000-000000000001"},
|
||||
{"GET", "/v1/usage/summary?tenant_id=00000000-0000-0000-0000-000000000001&since=2026-11-01T00:00:00Z"},
|
||||
{"POST", "/v1/licences"},
|
||||
{"POST", "/v1/licences/heartbeat"},
|
||||
{"POST", "/v1/licences/ci"},
|
||||
|
||||
@@ -206,6 +206,7 @@ func NewRouter(s *Server) http.Handler {
|
||||
// usage (§9.2) + subscriptions + ERP ops + licences (M-MIG-7)
|
||||
mux.HandleFunc("POST /v1/usage/events", s.postUsageEvents)
|
||||
mux.HandleFunc("GET /v1/usage/events", s.listUsageEvents)
|
||||
mux.HandleFunc("GET /v1/usage/summary", s.summarizeUsage)
|
||||
mux.HandleFunc("GET /v1/subscriptions", s.listSubscriptions)
|
||||
mux.HandleFunc("GET /v1/internal/erp/status", s.erpStatus)
|
||||
mux.HandleFunc("POST /v1/internal/erp/reconcile", s.erpReconcileNow)
|
||||
|
||||
@@ -149,8 +149,10 @@ func (s *Server) postUsageEvents(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, code, map[string]any{"accepted": accepted, "duplicates": duplicates, "rejected": rejected})
|
||||
}
|
||||
|
||||
// listUsageEvents — GET /v1/usage/events?tenant_id=&product=&metric=&since=&until=&limit=
|
||||
func (s *Server) listUsageEvents(w http.ResponseWriter, r *http.Request) {
|
||||
// usageFilterFrom reads tenant_id, product, metric, since and until. User
|
||||
// tokens are pinned to their own tenant. It writes the 400 and returns false
|
||||
// on bad input.
|
||||
func usageFilterFrom(w http.ResponseWriter, r *http.Request) (store.UsageFilter, bool) {
|
||||
q := r.URL.Query()
|
||||
f := store.UsageFilter{TenantID: q.Get("tenant_id"), Product: q.Get("product"), Metric: q.Get("metric")}
|
||||
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() {
|
||||
@@ -158,18 +160,29 @@ func (s *Server) listUsageEvents(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if f.TenantID == "" {
|
||||
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required")
|
||||
return
|
||||
return f, false
|
||||
}
|
||||
for name, dst := range map[string]**time.Time{"since": &f.Since, "until": &f.Until} {
|
||||
if v := q.Get(name); v != "" {
|
||||
ts, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_"+name, "must be RFC3339")
|
||||
return
|
||||
return f, false
|
||||
}
|
||||
ts = ts.UTC()
|
||||
*dst = &ts
|
||||
}
|
||||
}
|
||||
return f, true
|
||||
}
|
||||
|
||||
// listUsageEvents — GET /v1/usage/events?tenant_id=&product=&metric=&since=&until=&limit=
|
||||
func (s *Server) listUsageEvents(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := usageFilterFrom(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
if v := q.Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n <= 0 || n > 1000 {
|
||||
@@ -188,6 +201,26 @@ func (s *Server) listUsageEvents(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
}
|
||||
|
||||
// summarizeUsage — GET /v1/usage/summary?tenant_id=&product=&metric=&since=&until=
|
||||
//
|
||||
// Counts and quantity sums per product × metric, and per UTC day × metric,
|
||||
// over every matching event: the portal's 30-day views read this instead of
|
||||
// folding a capped page of /v1/usage/events.
|
||||
func (s *Server) summarizeUsage(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := usageFilterFrom(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
sum, err := s.Store.SummarizeUsage(ctx, f)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, sum)
|
||||
}
|
||||
|
||||
// previewActive reports whether the tenant uses product under an unexpired
|
||||
// staff preview grant. Lookup errors count as no: the event is then treated
|
||||
// like any other and refused for a product not for sale.
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
func (f *teamFixture) summary(t *testing.T, path string) (int, store.UsageSummary) {
|
||||
t.Helper()
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, httptest.NewRequest("GET", path, nil))
|
||||
var out store.UsageSummary
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &out)
|
||||
return rr.Code, out
|
||||
}
|
||||
|
||||
// The summary is a usage.read route, like the list: the portal's service
|
||||
// client needs no new grant, and a usage.read client still cannot push.
|
||||
func TestUsageSummary_authzGroup(t *testing.T) {
|
||||
if g := routeGroup("GET", "/v1/usage/summary"); g != "usage.read" {
|
||||
t.Fatalf("group: %s", g)
|
||||
}
|
||||
f := newTeamFixture(t, portal, "portal-svc:usage.read")
|
||||
if code, _ := f.summary(t, "/v1/usage/summary?tenant_id="+f.tenant.ID); code != 200 {
|
||||
t.Fatalf("usage.read: %d", code)
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, httptest.NewRequest("POST", "/v1/usage/events", nil))
|
||||
if rr.Code != 403 {
|
||||
t.Fatalf("push with usage.read: %d", rr.Code)
|
||||
}
|
||||
if code, _ := newTeamFixture(t, portal, "portal-svc:audit").summary(t, "/v1/usage/summary?tenant_id="+f.tenant.ID); code != 403 {
|
||||
t.Fatalf("without usage.read: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// A user token sees its own tenant whatever tenant_id says.
|
||||
func TestUsageSummary_userTokenPinnedToOwnTenant(t *testing.T) {
|
||||
seed := newTeamFixture(t, nil)
|
||||
ctx := context.Background()
|
||||
other, err := seed.s.Store.CreateTenant(ctx, store.TenantCreate{Slug: "other-co", Name: "Other"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, tenant := range []string{seed.tenant.ID, seed.tenant.ID, other.ID} {
|
||||
if _, _, err := seed.s.Store.InsertUsageEvent(ctx, store.UsageEvent{IdempotencyKey: fmt.Sprintf("k-%d", i), TenantID: tenant,
|
||||
Product: "pruefwerk", Metric: "scan.completed", Quantity: 1, OccurredAt: time.Now()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
f := newTeamFixture(t, &authn.Principal{Subject: "u-admin", ClientID: "portal", TenantID: seed.tenant.ID})
|
||||
f.s.Store = seed.s.Store
|
||||
if code, got := f.summary(t, "/v1/usage/summary?tenant_id="+other.ID); code != 200 || got.Events != 2 || got.TenantID != seed.tenant.ID {
|
||||
t.Fatalf("user token: %d %+v", code, got)
|
||||
}
|
||||
}
|
||||
|
||||
type failingSummaryStore struct{ store.Store }
|
||||
|
||||
func (failingSummaryStore) SummarizeUsage(context.Context, store.UsageFilter) (*store.UsageSummary, error) {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
|
||||
func TestUsageSummary_storeError(t *testing.T) {
|
||||
f := newTeamFixture(t, nil)
|
||||
f.s.Store = failingSummaryStore{f.s.Store}
|
||||
if code, _ := f.summary(t, "/v1/usage/summary?tenant_id="+f.tenant.ID); code != 500 {
|
||||
t.Fatalf("store error: %d", code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// summaryDay0 anchors the seeded events; the summary window starts here.
|
||||
var summaryDay0 = time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
// seedBusyTenant stores 1200 events for tn inside the window, 5 before it,
|
||||
// and 10 for other — directly through the store, since POST caps at 500.
|
||||
//
|
||||
// pruefwerk/scan.completed 700 × qty 1 — 100 per day, days 0..6 at 12:00
|
||||
// pruefwerk/target.added 300 × qty 2 — 100 per day, days 0..2 at 06:00
|
||||
// firmwerk/scan.completed 200 × qty 1.5 — 100 at day 0 23:59:59, 100 at day 1 00:00:00
|
||||
func seedBusyTenant(t *testing.T, s store.Store, tn, other string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
add := func(key, tenant, product, metric string, qty float64, at time.Time) {
|
||||
if _, ok, err := s.InsertUsageEvent(ctx, store.UsageEvent{IdempotencyKey: key, TenantID: tenant, Product: product,
|
||||
Metric: metric, Quantity: qty, OccurredAt: at}); err != nil || !ok {
|
||||
t.Fatalf("seed %s: %v %v", key, ok, err)
|
||||
}
|
||||
}
|
||||
day := func(n int) time.Time { return summaryDay0.Add(time.Duration(n) * 24 * time.Hour) }
|
||||
for i := 0; i < 700; i++ {
|
||||
add(fmt.Sprintf("ps-%d", i), tn, "pruefwerk", "scan.completed", 1, day(i%7).Add(12*time.Hour))
|
||||
}
|
||||
for i := 0; i < 300; i++ {
|
||||
add(fmt.Sprintf("pt-%d", i), tn, "pruefwerk", "target.added", 2, day(i%3).Add(6*time.Hour))
|
||||
}
|
||||
for i := 0; i < 200; i++ {
|
||||
at := day(1) // exactly midnight
|
||||
if i < 100 {
|
||||
at = at.Add(-time.Second)
|
||||
}
|
||||
add(fmt.Sprintf("fs-%d", i), tn, "firmwerk", "scan.completed", 1.5, at)
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
add(fmt.Sprintf("old-%d", i), tn, "pruefwerk", "scan.completed", 1, summaryDay0.Add(-time.Hour))
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
add(fmt.Sprintf("other-%d", i), other, "pruefwerk", "scan.completed", 1, day(0).Add(12*time.Hour))
|
||||
}
|
||||
}
|
||||
|
||||
func getSummary(t *testing.T, h *testHarness, q url.Values) store.UsageSummary {
|
||||
t.Helper()
|
||||
resp, raw := h.do("GET", "/v1/usage/summary?"+q.Encode(), nil)
|
||||
if resp.StatusCode != 200 {
|
||||
t.Fatalf("summary %s: %d %s", q.Encode(), resp.StatusCode, raw)
|
||||
}
|
||||
return decode[store.UsageSummary](t, raw)
|
||||
}
|
||||
|
||||
func TestUsageSummary_aggregatesPastTheListCap(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
tn := newTenant(t, h, "busy-co")
|
||||
other := newTenant(t, h, "other-co")
|
||||
seedBusyTenant(t, h.store, tn.ID, other.ID)
|
||||
since := summaryDay0.Format(time.RFC3339)
|
||||
|
||||
// The list route stops at 1000 — which is why the summary exists.
|
||||
_, raw := h.do("GET", "/v1/usage/events?tenant_id="+tn.ID+"&since="+since+"&limit=1000", nil)
|
||||
if n := len(decode[struct {
|
||||
Items []store.UsageEvent `json:"items"`
|
||||
}](t, raw).Items); n != 1000 {
|
||||
t.Fatalf("list cap: %d", n)
|
||||
}
|
||||
|
||||
got := getSummary(t, h, url.Values{"tenant_id": {tn.ID}, "since": {since}})
|
||||
day := func(n int) time.Time { return summaryDay0.Add(time.Duration(n) * 24 * time.Hour) }
|
||||
if got.Events != 1200 || got.TenantID != tn.ID || got.Since == nil || !got.Since.Equal(summaryDay0) || got.Until != nil {
|
||||
t.Fatalf("head: events=%d tenant=%s since=%v until=%v", got.Events, got.TenantID, got.Since, got.Until)
|
||||
}
|
||||
wantTotals := []store.UsageTotal{
|
||||
{Product: "firmwerk", Metric: "scan.completed", Events: 200, Quantity: 300, LastAt: day(1)},
|
||||
{Product: "pruefwerk", Metric: "scan.completed", Events: 700, Quantity: 700, LastAt: day(6).Add(12 * time.Hour)},
|
||||
{Product: "pruefwerk", Metric: "target.added", Events: 300, Quantity: 600, LastAt: day(2).Add(6 * time.Hour)},
|
||||
}
|
||||
if !reflect.DeepEqual(got.Totals, wantTotals) {
|
||||
t.Fatalf("totals:\n got %+v\nwant %+v", got.Totals, wantTotals)
|
||||
}
|
||||
wantDaily := []store.UsageDayStat{
|
||||
{Day: "2026-11-01", Metric: "scan.completed", Events: 200, Quantity: 250},
|
||||
{Day: "2026-11-01", Metric: "target.added", Events: 100, Quantity: 200},
|
||||
{Day: "2026-11-02", Metric: "scan.completed", Events: 200, Quantity: 250},
|
||||
{Day: "2026-11-02", Metric: "target.added", Events: 100, Quantity: 200},
|
||||
{Day: "2026-11-03", Metric: "scan.completed", Events: 100, Quantity: 100},
|
||||
{Day: "2026-11-03", Metric: "target.added", Events: 100, Quantity: 200},
|
||||
{Day: "2026-11-04", Metric: "scan.completed", Events: 100, Quantity: 100},
|
||||
{Day: "2026-11-05", Metric: "scan.completed", Events: 100, Quantity: 100},
|
||||
{Day: "2026-11-06", Metric: "scan.completed", Events: 100, Quantity: 100},
|
||||
{Day: "2026-11-07", Metric: "scan.completed", Events: 100, Quantity: 100},
|
||||
}
|
||||
if !reflect.DeepEqual(got.Daily, wantDaily) {
|
||||
t.Fatalf("daily:\n got %+v\nwant %+v", got.Daily, wantDaily)
|
||||
}
|
||||
|
||||
// Without since the 5 older events count too; the other tenant never does.
|
||||
if all := getSummary(t, h, url.Values{"tenant_id": {tn.ID}}); all.Events != 1205 || all.Since != nil {
|
||||
t.Fatalf("no window: %d", all.Events)
|
||||
}
|
||||
if o := getSummary(t, h, url.Values{"tenant_id": {other.ID}}); o.Events != 10 {
|
||||
t.Fatalf("other tenant: %d", o.Events)
|
||||
}
|
||||
|
||||
// until is inclusive: day 1 00:00:00 is in, day 1 12:00 is not.
|
||||
upto := getSummary(t, h, url.Values{"tenant_id": {tn.ID}, "since": {since}, "until": {day(1).Format(time.RFC3339)}})
|
||||
wantUpto := []store.UsageDayStat{
|
||||
{Day: "2026-11-01", Metric: "scan.completed", Events: 200, Quantity: 250},
|
||||
{Day: "2026-11-01", Metric: "target.added", Events: 100, Quantity: 200},
|
||||
{Day: "2026-11-02", Metric: "scan.completed", Events: 100, Quantity: 150},
|
||||
}
|
||||
if upto.Events != 400 || !reflect.DeepEqual(upto.Daily, wantUpto) {
|
||||
t.Fatalf("until: %d %+v", upto.Events, upto.Daily)
|
||||
}
|
||||
|
||||
// product and metric narrow like the list route.
|
||||
fw := getSummary(t, h, url.Values{"tenant_id": {tn.ID}, "since": {since}, "product": {"firmwerk"}})
|
||||
if fw.Events != 200 || len(fw.Totals) != 1 || fw.Totals[0].Product != "firmwerk" {
|
||||
t.Fatalf("product filter: %+v", fw)
|
||||
}
|
||||
tg := getSummary(t, h, url.Values{"tenant_id": {tn.ID}, "since": {since}, "metric": {"target.added"}})
|
||||
if tg.Events != 300 || len(tg.Daily) != 3 {
|
||||
t.Fatalf("metric filter: %+v", tg)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsageSummary_emptyAndBadInput(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
tn := newTenant(t, h, "empty-co")
|
||||
// Empty lists, never null: the portal renders them directly.
|
||||
for _, id := range []string{tn.ID, "not-a-uuid", "00000000-0000-0000-0000-0000000000ff"} {
|
||||
resp, raw := h.do("GET", "/v1/usage/summary?tenant_id="+id, nil)
|
||||
if resp.StatusCode != 200 || !bytes.Contains(raw, []byte(`"events":0`)) ||
|
||||
!bytes.Contains(raw, []byte(`"totals":[]`)) || !bytes.Contains(raw, []byte(`"daily":[]`)) {
|
||||
t.Fatalf("empty %s: %d %s", id, resp.StatusCode, raw)
|
||||
}
|
||||
}
|
||||
for _, q := range []string{"", "?since=2026-11-01T00:00:00Z", "?tenant_id=" + tn.ID + "&since=bad", "?tenant_id=" + tn.ID + "&until=yesterday"} {
|
||||
if resp, raw := h.do("GET", "/v1/usage/summary"+q, nil); resp.StatusCode != 400 {
|
||||
t.Fatalf("summary %q: %d %s", q, resp.StatusCode, raw)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -106,23 +106,9 @@ func (m *Memory) ListUsageEvents(_ context.Context, f UsageFilter) ([]UsageEvent
|
||||
}
|
||||
out := []UsageEvent{}
|
||||
for i := len(m.usage) - 1; i >= 0 && len(out) < limit; i-- {
|
||||
u := m.usage[i]
|
||||
if f.TenantID != "" && u.TenantID != f.TenantID {
|
||||
continue
|
||||
if u := m.usage[i]; f.matches(u) {
|
||||
out = append(out, *u)
|
||||
}
|
||||
if f.Product != "" && u.Product != f.Product {
|
||||
continue
|
||||
}
|
||||
if f.Metric != "" && u.Metric != f.Metric {
|
||||
continue
|
||||
}
|
||||
if f.Since != nil && u.OccurredAt.Before(*f.Since) {
|
||||
continue
|
||||
}
|
||||
if f.Until != nil && u.OccurredAt.After(*f.Until) {
|
||||
continue
|
||||
}
|
||||
out = append(out, *u)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
@@ -155,29 +154,9 @@ func (p *Postgres) ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageE
|
||||
if limit <= 0 || limit > 1000 {
|
||||
limit = 200
|
||||
}
|
||||
where := []string{"TRUE"}
|
||||
args := []any{}
|
||||
add := func(clause string, v any) {
|
||||
args = append(args, v)
|
||||
where = append(where, fmt.Sprintf(clause, len(args)))
|
||||
}
|
||||
if f.TenantID != "" {
|
||||
add("tenant_id = $%d::uuid", f.TenantID)
|
||||
}
|
||||
if f.Product != "" {
|
||||
add("product = $%d", f.Product)
|
||||
}
|
||||
if f.Metric != "" {
|
||||
add("metric = $%d", f.Metric)
|
||||
}
|
||||
if f.Since != nil {
|
||||
add("occurred_at >= $%d", *f.Since)
|
||||
}
|
||||
if f.Until != nil {
|
||||
add("occurred_at <= $%d", *f.Until)
|
||||
}
|
||||
where, args := usageWhere(f)
|
||||
args = append(args, limit)
|
||||
rows, err := p.pool.Query(ctx, usageSelect+`WHERE `+strings.Join(where, " AND ")+
|
||||
rows, err := p.pool.Query(ctx, usageSelect+`WHERE `+where+
|
||||
fmt.Sprintf(` ORDER BY occurred_at DESC, id DESC LIMIT $%d`, len(args)), args...)
|
||||
if err != nil {
|
||||
if isInvalidUUID(err) {
|
||||
|
||||
@@ -130,6 +130,9 @@ type Store interface {
|
||||
// was already stored (the existing row is returned).
|
||||
InsertUsageEvent(ctx context.Context, ev UsageEvent) (*UsageEvent, bool, error)
|
||||
ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageEvent, error)
|
||||
// SummarizeUsage aggregates every matching event (f.Limit is ignored).
|
||||
// Totals are ordered by product, metric; Daily by day, metric.
|
||||
SummarizeUsage(ctx context.Context, f UsageFilter) (*UsageSummary, error)
|
||||
MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error
|
||||
|
||||
// ERP outbox. ClaimOutbox returns due rows (next_attempt_at <= now) and
|
||||
|
||||
@@ -229,6 +229,39 @@ type UsageFilter struct {
|
||||
Limit int
|
||||
}
|
||||
|
||||
// UsageSummary aggregates a tenant's usage events over a window, without the
|
||||
// row cap of ListUsageEvents. Totals are per product and metric; Daily is per
|
||||
// UTC day and metric, summed across products. Events counts rows; Quantity
|
||||
// sums their quantity.
|
||||
type UsageSummary struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
Since *time.Time `json:"since,omitempty"`
|
||||
Until *time.Time `json:"until,omitempty"`
|
||||
Events int64 `json:"events"`
|
||||
Totals []UsageTotal `json:"totals"`
|
||||
Daily []UsageDayStat `json:"daily"`
|
||||
}
|
||||
|
||||
// UsageTotal — one product × metric line of a UsageSummary.
|
||||
type UsageTotal struct {
|
||||
Product string `json:"product"`
|
||||
Metric string `json:"metric"`
|
||||
Events int64 `json:"events"`
|
||||
Quantity float64 `json:"quantity"`
|
||||
LastAt time.Time `json:"last_at"`
|
||||
}
|
||||
|
||||
// UsageDayStat — one UTC day × metric bucket of a UsageSummary.
|
||||
type UsageDayStat struct {
|
||||
Day string `json:"day"` // YYYY-MM-DD, UTC
|
||||
Metric string `json:"metric"`
|
||||
Events int64 `json:"events"`
|
||||
Quantity float64 `json:"quantity"`
|
||||
}
|
||||
|
||||
// UsageDayLayout formats UsageDayStat.Day.
|
||||
const UsageDayLayout = "2006-01-02"
|
||||
|
||||
// OutboxItem — a pending ERP write.
|
||||
type OutboxItem struct {
|
||||
ID int64 `json:"id"`
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ─── usage summary: aggregates for the portal's 30-day views ─────────────
|
||||
//
|
||||
// ListUsageEvents caps at 1000 rows, so a busy tenant's totals computed from
|
||||
// it come out too low. SummarizeUsage aggregates in the store instead:
|
||||
// GROUP BY in Postgres, the same fold in Memory. Day buckets are UTC.
|
||||
|
||||
func newUsageSummary(f UsageFilter) *UsageSummary {
|
||||
return &UsageSummary{TenantID: f.TenantID, Since: f.Since, Until: f.Until, Totals: []UsageTotal{}, Daily: []UsageDayStat{}}
|
||||
}
|
||||
|
||||
func (m *Memory) SummarizeUsage(_ context.Context, f UsageFilter) (*UsageSummary, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
out := newUsageSummary(f)
|
||||
type key struct{ a, b string }
|
||||
totals := map[key]*UsageTotal{}
|
||||
days := map[key]*UsageDayStat{}
|
||||
for _, u := range m.usage {
|
||||
if !f.matches(u) {
|
||||
continue
|
||||
}
|
||||
at := u.OccurredAt.UTC()
|
||||
out.Events++
|
||||
tk := key{u.Product, u.Metric}
|
||||
t, ok := totals[tk]
|
||||
if !ok {
|
||||
t = &UsageTotal{Product: u.Product, Metric: u.Metric, LastAt: at}
|
||||
totals[tk] = t
|
||||
}
|
||||
t.Events++
|
||||
t.Quantity += u.Quantity
|
||||
if at.After(t.LastAt) {
|
||||
t.LastAt = at
|
||||
}
|
||||
dk := key{at.Format(UsageDayLayout), u.Metric}
|
||||
d, ok := days[dk]
|
||||
if !ok {
|
||||
d = &UsageDayStat{Day: dk.a, Metric: u.Metric}
|
||||
days[dk] = d
|
||||
}
|
||||
d.Events++
|
||||
d.Quantity += u.Quantity
|
||||
}
|
||||
for _, t := range totals {
|
||||
out.Totals = append(out.Totals, *t)
|
||||
}
|
||||
for _, d := range days {
|
||||
out.Daily = append(out.Daily, *d)
|
||||
}
|
||||
sort.Slice(out.Totals, func(i, j int) bool {
|
||||
a, b := out.Totals[i], out.Totals[j]
|
||||
if a.Product != b.Product {
|
||||
return a.Product < b.Product
|
||||
}
|
||||
return a.Metric < b.Metric
|
||||
})
|
||||
sort.Slice(out.Daily, func(i, j int) bool {
|
||||
a, b := out.Daily[i], out.Daily[j]
|
||||
if a.Day != b.Day {
|
||||
return a.Day < b.Day
|
||||
}
|
||||
return a.Metric < b.Metric
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// matches applies the filter the way ListUsageEvents does (bounds inclusive).
|
||||
func (f UsageFilter) matches(u *UsageEvent) bool {
|
||||
switch {
|
||||
case f.TenantID != "" && u.TenantID != f.TenantID,
|
||||
f.Product != "" && u.Product != f.Product,
|
||||
f.Metric != "" && u.Metric != f.Metric,
|
||||
f.Since != nil && u.OccurredAt.Before(*f.Since),
|
||||
f.Until != nil && u.OccurredAt.After(*f.Until):
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// usageWhere builds the WHERE clause shared by the usage list and summary.
|
||||
func usageWhere(f UsageFilter) (string, []any) {
|
||||
where := []string{"TRUE"}
|
||||
args := []any{}
|
||||
add := func(clause string, v any) {
|
||||
args = append(args, v)
|
||||
where = append(where, fmt.Sprintf(clause, len(args)))
|
||||
}
|
||||
if f.TenantID != "" {
|
||||
add("tenant_id = $%d::uuid", f.TenantID)
|
||||
}
|
||||
if f.Product != "" {
|
||||
add("product = $%d", f.Product)
|
||||
}
|
||||
if f.Metric != "" {
|
||||
add("metric = $%d", f.Metric)
|
||||
}
|
||||
if f.Since != nil {
|
||||
add("occurred_at >= $%d", *f.Since)
|
||||
}
|
||||
if f.Until != nil {
|
||||
add("occurred_at <= $%d", *f.Until)
|
||||
}
|
||||
return strings.Join(where, " AND "), args
|
||||
}
|
||||
|
||||
// SummarizeUsage — COLLATE "C" keeps the order byte-wise, as Memory sorts.
|
||||
func (p *Postgres) SummarizeUsage(ctx context.Context, f UsageFilter) (*UsageSummary, error) {
|
||||
out := newUsageSummary(f)
|
||||
if _, err := uuid.Parse(f.TenantID); f.TenantID != "" && err != nil {
|
||||
return out, nil // no tenant has that id; checked here, pgx reports the cast late
|
||||
}
|
||||
where, args := usageWhere(f)
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT product COLLATE "C", metric COLLATE "C", COUNT(*), SUM(quantity), MAX(occurred_at)
|
||||
FROM usage_events
|
||||
WHERE `+where+`
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var t UsageTotal
|
||||
if err := rows.Scan(&t.Product, &t.Metric, &t.Events, &t.Quantity, &t.LastAt); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
t.LastAt = t.LastAt.UTC()
|
||||
out.Events += t.Events
|
||||
out.Totals = append(out.Totals, t)
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err = p.pool.Query(ctx, `
|
||||
SELECT to_char(occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') COLLATE "C", metric COLLATE "C", COUNT(*), SUM(quantity)
|
||||
FROM usage_events
|
||||
WHERE `+where+`
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var d UsageDayStat
|
||||
if err := rows.Scan(&d.Day, &d.Metric, &d.Events, &d.Quantity); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.Daily = append(out.Daily, d)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -2200,6 +2200,31 @@ paths:
|
||||
items: { $ref: "#/components/schemas/UsageEvent" }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
|
||||
/v1/usage/summary:
|
||||
get:
|
||||
summary: Aggregate usage events (counts and quantity sums).
|
||||
description: |
|
||||
Aggregates every matching event, with no row cap (the list route
|
||||
stops at 1000): totals per product × metric, and per UTC day ×
|
||||
metric summed across products. The portal's 30-day views read this.
|
||||
Same filters and scoping as GET /v1/usage/events (bounds
|
||||
inclusive; user tokens see only their own tenant); route group
|
||||
usage.read. Totals are ordered by product, metric; daily by day,
|
||||
metric. An unknown tenant yields an empty summary.
|
||||
parameters:
|
||||
- { in: query, name: tenant_id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: query, name: product, schema: { type: string } }
|
||||
- { in: query, name: metric, schema: { type: string } }
|
||||
- { in: query, name: since, schema: { type: string, format: date-time } }
|
||||
- { in: query, name: until, schema: { type: string, format: date-time } }
|
||||
responses:
|
||||
"200":
|
||||
description: The aggregate.
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/UsageSummary" }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
|
||||
/v1/licences:
|
||||
post:
|
||||
summary: Issue a CLI licence JWT (Werkpilot, Firmwerk).
|
||||
@@ -2449,6 +2474,35 @@ components:
|
||||
id: { type: integer }
|
||||
received_at: { type: string, format: date-time }
|
||||
erp_synced_at: { type: string, format: date-time }
|
||||
UsageSummary:
|
||||
type: object
|
||||
required: [tenant_id, events, totals, daily]
|
||||
properties:
|
||||
tenant_id: { type: string }
|
||||
since: { type: string, format: date-time }
|
||||
until: { type: string, format: date-time }
|
||||
events: { type: integer, description: "Matching events in the window." }
|
||||
totals:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required: [product, metric, events, quantity, last_at]
|
||||
properties:
|
||||
product: { type: string }
|
||||
metric: { type: string }
|
||||
events: { type: integer }
|
||||
quantity: { type: number, description: "Sum of the events' quantity." }
|
||||
last_at: { type: string, format: date-time, description: "Latest occurred_at (UTC)." }
|
||||
daily:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required: [day, metric, events, quantity]
|
||||
properties:
|
||||
day: { type: string, format: date, description: "UTC day, YYYY-MM-DD." }
|
||||
metric: { type: string }
|
||||
events: { type: integer }
|
||||
quantity: { type: number }
|
||||
Licence:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
Reference in new issue
Block a user