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>
166 lines
4.3 KiB
Go
166 lines
4.3 KiB
Go
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()
|
|
}
|