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>
449 lines
13 KiB
Go
449 lines
13 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgerrcode"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
)
|
|
|
|
// ─── M-MIG-7: subscriptions / usage / outbox / receipts / licences (Postgres) ─
|
|
|
|
func isFKViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation
|
|
}
|
|
|
|
func isInvalidUUID(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.InvalidTextRepresentation
|
|
}
|
|
|
|
const subscriptionSelect = `
|
|
SELECT id::text, tenant_id::text, product, sku, plan, seats, status,
|
|
erp_sales_order, erp_subscription, period_start, period_end, created_at, updated_at
|
|
FROM subscriptions `
|
|
|
|
func scanSubscription(row pgx.Row) (*Subscription, error) {
|
|
var s Subscription
|
|
var ps, pe *time.Time
|
|
err := row.Scan(&s.ID, &s.TenantID, &s.Product, &s.SKU, &s.Plan, &s.Seats, &s.Status,
|
|
&s.ErpSalesOrder, &s.ErpSubscription, &ps, &pe, &s.CreatedAt, &s.UpdatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.PeriodStart, s.PeriodEnd = ps, pe
|
|
return &s, nil
|
|
}
|
|
|
|
func (p *Postgres) UpsertSubscription(ctx context.Context, sub Subscription) (*Subscription, error) {
|
|
if sub.SKU == "" || sub.Product == "" {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
row := p.pool.QueryRow(ctx, `
|
|
INSERT INTO subscriptions (tenant_id, product, sku, plan, seats, status, erp_sales_order, erp_subscription, period_start, period_end)
|
|
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
ON CONFLICT (tenant_id, sku, erp_sales_order) DO UPDATE SET
|
|
product = EXCLUDED.product, plan = EXCLUDED.plan, seats = EXCLUDED.seats, status = EXCLUDED.status,
|
|
erp_subscription = EXCLUDED.erp_subscription, period_start = EXCLUDED.period_start, period_end = EXCLUDED.period_end
|
|
RETURNING id::text, tenant_id::text, product, sku, plan, seats, status,
|
|
erp_sales_order, erp_subscription, period_start, period_end, created_at, updated_at`,
|
|
sub.TenantID, sub.Product, sub.SKU, sub.Plan, sub.Seats, firstNonEmpty(sub.Status, SubscriptionActive),
|
|
sub.ErpSalesOrder, sub.ErpSubscription, nullableTime(sub.PeriodStart), nullableTime(sub.PeriodEnd))
|
|
out, err := scanSubscription(row)
|
|
if err != nil {
|
|
if isFKViolation(err) || isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if isCheckViolation(err) {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
return nil, err
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p *Postgres) ListSubscriptions(ctx context.Context, tenantID string) ([]Subscription, error) {
|
|
if _, err := p.GetTenant(ctx, tenantID); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := p.pool.Query(ctx, subscriptionSelect+`WHERE tenant_id = $1::uuid ORDER BY created_at, id`, tenantID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []Subscription{}
|
|
for rows.Next() {
|
|
s, err := scanSubscription(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *s)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
const usageSelect = `
|
|
SELECT id, idempotency_key, tenant_id::text, product, metric, quantity, occurred_at, properties, received_at, erp_synced_at
|
|
FROM usage_events `
|
|
|
|
func scanUsage(row pgx.Row) (*UsageEvent, error) {
|
|
var u UsageEvent
|
|
var props []byte
|
|
var synced *time.Time
|
|
err := row.Scan(&u.ID, &u.IdempotencyKey, &u.TenantID, &u.Product, &u.Metric, &u.Quantity, &u.OccurredAt, &props, &u.ReceivedAt, &synced)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
u.ErpSyncedAt = synced
|
|
if err := json.Unmarshal(props, &u.Properties); err != nil || u.Properties == nil {
|
|
u.Properties = map[string]interface{}{}
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
func (p *Postgres) InsertUsageEvent(ctx context.Context, ev UsageEvent) (*UsageEvent, bool, error) {
|
|
if ev.IdempotencyKey == "" || ev.Metric == "" || ev.Product == "" {
|
|
return nil, false, ErrInvalidInput
|
|
}
|
|
props, err := json.Marshal(ev.Properties)
|
|
if err != nil || string(props) == "null" {
|
|
props = []byte("{}")
|
|
}
|
|
occurred := ev.OccurredAt
|
|
if occurred.IsZero() {
|
|
occurred = time.Now().UTC()
|
|
}
|
|
row := p.pool.QueryRow(ctx, `
|
|
INSERT INTO usage_events (idempotency_key, tenant_id, product, metric, quantity, occurred_at, properties)
|
|
VALUES ($1, $2::uuid, $3, $4, $5, $6, $7::jsonb)
|
|
ON CONFLICT (idempotency_key) DO NOTHING
|
|
RETURNING id, idempotency_key, tenant_id::text, product, metric, quantity, occurred_at, properties, received_at, erp_synced_at`,
|
|
ev.IdempotencyKey, ev.TenantID, ev.Product, ev.Metric, ev.Quantity, occurred, props)
|
|
u, err := scanUsage(row)
|
|
if err == nil {
|
|
return u, true, nil
|
|
}
|
|
if errors.Is(err, ErrNotFound) {
|
|
// duplicate key → return the stored row
|
|
u, err = scanUsage(p.pool.QueryRow(ctx, usageSelect+`WHERE idempotency_key = $1`, ev.IdempotencyKey))
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
return u, false, nil
|
|
}
|
|
if isFKViolation(err) || isInvalidUUID(err) {
|
|
return nil, false, ErrNotFound
|
|
}
|
|
return nil, false, err
|
|
}
|
|
|
|
func (p *Postgres) ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageEvent, error) {
|
|
limit := f.Limit
|
|
if limit <= 0 || limit > 1000 {
|
|
limit = 200
|
|
}
|
|
where, args := usageWhere(f)
|
|
args = append(args, limit)
|
|
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) {
|
|
return []UsageEvent{}, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []UsageEvent{}
|
|
for rows.Next() {
|
|
u, err := scanUsage(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *u)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (p *Postgres) MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error {
|
|
if len(ids) == 0 {
|
|
return nil
|
|
}
|
|
_, err := p.pool.Exec(ctx, `UPDATE usage_events SET erp_synced_at = $2 WHERE id = ANY($1)`, ids, at)
|
|
return err
|
|
}
|
|
|
|
func scanOutbox(row pgx.Row) (*OutboxItem, error) {
|
|
var o OutboxItem
|
|
var payload []byte
|
|
var done *time.Time
|
|
err := row.Scan(&o.ID, &o.Kind, &o.TenantID, &payload, &o.Attempts, &o.NextAttemptAt, &o.LastError, &done, &o.CreatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
o.DoneAt = done
|
|
if err := json.Unmarshal(payload, &o.Payload); err != nil || o.Payload == nil {
|
|
o.Payload = map[string]interface{}{}
|
|
}
|
|
return &o, nil
|
|
}
|
|
|
|
func (p *Postgres) EnqueueOutbox(ctx context.Context, item OutboxItem) (*OutboxItem, error) {
|
|
if item.Kind == "" {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
payload, err := json.Marshal(item.Payload)
|
|
if err != nil || string(payload) == "null" {
|
|
payload = []byte("{}")
|
|
}
|
|
next := item.NextAttemptAt
|
|
if next.IsZero() {
|
|
next = time.Now().UTC()
|
|
}
|
|
var tenant any
|
|
if item.TenantID != "" {
|
|
tenant = item.TenantID
|
|
}
|
|
o, err := scanOutbox(p.pool.QueryRow(ctx, `
|
|
INSERT INTO erp_outbox (kind, tenant_id, payload, next_attempt_at)
|
|
VALUES ($1, $2::uuid, $3::jsonb, $4)
|
|
RETURNING id, kind, COALESCE(tenant_id::text, ''), payload, attempts, next_attempt_at, last_error, done_at, created_at`,
|
|
item.Kind, tenant, payload, next))
|
|
if err != nil {
|
|
if isFKViolation(err) || isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return o, nil
|
|
}
|
|
|
|
func (p *Postgres) ClaimOutbox(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error) {
|
|
if limit <= 0 {
|
|
limit = 50
|
|
}
|
|
rows, err := p.pool.Query(ctx, `
|
|
UPDATE erp_outbox SET next_attempt_at = $1::timestamptz + $2::interval
|
|
WHERE id IN (
|
|
SELECT id FROM erp_outbox
|
|
WHERE done_at IS NULL AND next_attempt_at <= $1
|
|
ORDER BY next_attempt_at, id
|
|
LIMIT $3
|
|
FOR UPDATE SKIP LOCKED
|
|
)
|
|
RETURNING id, kind, COALESCE(tenant_id::text, ''), payload, attempts, next_attempt_at, last_error, done_at, created_at`,
|
|
now, lease, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []OutboxItem{}
|
|
for rows.Next() {
|
|
o, err := scanOutbox(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *o)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (p *Postgres) CompleteOutbox(ctx context.Context, id int64, at time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET done_at = $2, attempts = attempts + 1, last_error = '' WHERE id = $1`, id, at)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) DeadLetterOutbox(ctx context.Context, id int64, errMsg string, at time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET attempts = attempts + 1, last_error = $2, done_at = $3 WHERE id = $1`,
|
|
id, DeadLetterPrefix+errMsg, at)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET attempts = attempts + 1, last_error = $2, next_attempt_at = $3 WHERE id = $1`, id, errMsg, nextAttempt)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) PendingOutbox(ctx context.Context) (int, error) {
|
|
var n int
|
|
err := p.pool.QueryRow(ctx, `SELECT COUNT(*) FROM erp_outbox WHERE done_at IS NULL`).Scan(&n)
|
|
return n, err
|
|
}
|
|
|
|
func (p *Postgres) RecordWebhookReceipt(ctx context.Context, eventID string) (bool, error) {
|
|
if eventID == "" {
|
|
return false, ErrInvalidInput
|
|
}
|
|
tag, err := p.pool.Exec(ctx, `INSERT INTO erp_webhook_receipts (event_id) VALUES ($1) ON CONFLICT DO NOTHING`, eventID)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return tag.RowsAffected() == 1, nil
|
|
}
|
|
|
|
const licenceSelect = `
|
|
SELECT id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at, COALESCE(llm_key_id, ''), llm_key_secret_enc
|
|
FROM licences `
|
|
|
|
func scanLicence(row pgx.Row) (*Licence, error) {
|
|
var l Licence
|
|
var revoked, seen *time.Time
|
|
err := row.Scan(&l.ID, &l.Kid, &l.TenantID, &l.Product, &l.Subject, &l.Device, &l.ExpiresAt, &revoked, &seen, &l.CreatedAt, &l.LLMKeyID, &l.LLMKeySecret)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
l.RevokedAt, l.LastSeenAt = revoked, seen
|
|
return &l, nil
|
|
}
|
|
|
|
func (p *Postgres) CreateLicence(ctx context.Context, l Licence) (*Licence, error) {
|
|
if l.Product == "" || l.Subject == "" || l.Kid == "" || l.ExpiresAt.IsZero() {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
var id any
|
|
if l.ID != "" {
|
|
id = l.ID
|
|
}
|
|
out, err := scanLicence(p.pool.QueryRow(ctx, `
|
|
INSERT INTO licences (id, kid, tenant_id, product, subject, device, expires_at)
|
|
VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3::uuid, $4, $5, $6, $7)
|
|
RETURNING id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at, COALESCE(llm_key_id, ''), llm_key_secret_enc`,
|
|
id, l.Kid, l.TenantID, l.Product, l.Subject, l.Device, l.ExpiresAt))
|
|
if err != nil {
|
|
if isFKViolation(err) || isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if isUniqueViolation(err) {
|
|
return nil, ErrConflict
|
|
}
|
|
return nil, err
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p *Postgres) GetLicence(ctx context.Context, id string) (*Licence, error) {
|
|
l, err := scanLicence(p.pool.QueryRow(ctx, licenceSelect+`WHERE id = $1::uuid`, id))
|
|
if err != nil && isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return l, err
|
|
}
|
|
|
|
func (p *Postgres) FindReusableLicence(ctx context.Context, tenantID, product, subject, device string, since, now time.Time) (*Licence, error) {
|
|
return scanLicence(p.pool.QueryRow(ctx, licenceSelect+`
|
|
WHERE tenant_id = $1::uuid AND product = $2 AND subject = $3 AND device = $4
|
|
AND created_at >= $5 AND expires_at > $6 AND revoked_at IS NULL
|
|
ORDER BY created_at DESC LIMIT 1`, tenantID, product, subject, device, since, now))
|
|
}
|
|
|
|
func (p *Postgres) ListLicences(ctx context.Context, tenantID string) ([]Licence, error) {
|
|
if _, err := p.GetTenant(ctx, tenantID); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := p.pool.Query(ctx, licenceSelect+`WHERE tenant_id = $1::uuid ORDER BY created_at, id`, tenantID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []Licence{}
|
|
for rows.Next() {
|
|
l, err := scanLicence(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *l)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (p *Postgres) RevokeLicence(ctx context.Context, id string, at time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE licences SET revoked_at = COALESCE(revoked_at, $2) WHERE id = $1::uuid`, id, at)
|
|
if err != nil {
|
|
if isInvalidUUID(err) {
|
|
return ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) SetLicenceLLMSecret(ctx context.Context, id string, sealed []byte) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE licences SET llm_key_secret_enc = $2 WHERE id = $1::uuid`, id, sealed)
|
|
if err != nil {
|
|
if isInvalidUUID(err) {
|
|
return ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) SetLicenceLLMKey(ctx context.Context, id string, keyID string) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE licences SET llm_key_id = NULLIF($2, '') WHERE id = $1::uuid`, id, keyID)
|
|
if err != nil {
|
|
if isInvalidUUID(err) {
|
|
return ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Postgres) TouchLicence(ctx context.Context, id string, at time.Time) error {
|
|
tag, err := p.pool.Exec(ctx, `UPDATE licences SET last_seen_at = $2 WHERE id = $1::uuid`, id, at)
|
|
if err != nil {
|
|
if isInvalidUUID(err) {
|
|
return ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|