Files
tenant-registry/internal/store/postgres.go
Sharang ParnerkarandClaude Opus 5.5 65ad1b52f6
ci / shared (pull_request) Failing after 12s
ci / test (pull_request) Failing after 15m24s
ci / image (pull_request) Skipped
feat(telemetry): traces to SigNoz for requests, outbound calls and SQL
internal/telemetry: OTLP/HTTP tracer provider from the OTEL_* env
(already set on stage and prod; unset = off), W3C propagation, one server
span per request named after the ServeMux pattern, client spans on the
default transport (Keycloak, ERP, LiteLLM, OIDC) and a pgx QueryTracer.
Client and DB spans only inside a request, so the background loops add
no traces. No raw paths, query strings, bodies, SQL parameters or client
addresses in spans; outbound spans carry the host only.

slog lines logged with a request context get trace_id/span_id; the
access log names the route instead of the raw path (slugs are names).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4
2026-10-28 22:24:34 +01:00

748 lines
23 KiB
Go

package store
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"git.breakpilot.com/platform/tenant-registry/internal/telemetry"
)
// Postgres — pgxpool-backed Store. The schema this expects is produced by
// the migrations/ package (M4.1 forward).
type Postgres struct {
pool *pgxpool.Pool
}
// NewPostgres opens a pool and pings. Caller must Close().
func NewPostgres(ctx context.Context, dsn string) (*Postgres, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, fmt.Errorf("parse dsn: %w", err)
}
cfg.MaxConns = 20
cfg.MinConns = 2
cfg.MaxConnLifetime = time.Hour
cfg.ConnConfig.Tracer = telemetry.QueryTracer{} // spans only inside a traced request
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping: %w", err)
}
return &Postgres{pool: pool}, nil
}
func (p *Postgres) Close() { p.pool.Close() }
func (p *Postgres) Ping(ctx context.Context) error { return p.pool.Ping(ctx) }
// isUniqueViolation detects Postgres unique_violation (23505) so callers
// can return ErrConflict cleanly.
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation
}
// isCheckViolation detects check_constraint_violation (23514) — used by the
// slug regex check + plan/status enum guards.
func isCheckViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.CheckViolation
}
// ─── tenants ──────────────────────────────────────────────────────────────
const tenantSelect = `
SELECT id::text, slug, name, status::text, kind::text, plan,
COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''),
trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''),
COALESCE(admin_email,''), status_changed_at, created_at, updated_at
FROM tenants `
func scanTenant(row pgx.Row) (*Tenant, error) {
var t Tenant
var trialEnds, cStart, cEnd *time.Time
err := row.Scan(
&t.ID, &t.Slug, &t.Name, &t.Status, &t.Kind, &t.Plan,
&t.ErpCustomerID, &t.StripeCustID,
&trialEnds, &cStart, &cEnd, &t.SalesOwner,
&t.AdminEmail, &t.StatusChangedAt, &t.CreatedAt, &t.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
t.TrialEndsAt = trialEnds
t.ContractStart = cStart
t.ContractEnd = cEnd
return &t, nil
}
func (p *Postgres) CreateTenant(ctx context.Context, in TenantCreate) (*Tenant, error) {
kind := firstNonEmpty(in.Kind, "customer")
plan := firstNonEmpty(in.Plan, "starter")
// Default status = 'trial'; set trial_ends_at = NOW() + 14 days so the
// portal's trial banner has a real countdown to render. Demo tenants
// (kind=demo) get status='demo' and no trial_ends_at — that's set by
// the M13.2 demo provisioning path.
row := p.pool.QueryRow(ctx,
`INSERT INTO tenants (slug, name, kind, plan, status, sales_owner, trial_ends_at, admin_email)
VALUES (
$1, $2, $3::tenant_kind, $4,
CASE WHEN $3::tenant_kind = 'demo' THEN 'demo'::tenant_status
ELSE 'trial'::tenant_status END,
NULLIF($5, ''),
CASE WHEN $3::tenant_kind = 'demo' THEN NULL
ELSE NOW() + INTERVAL '14 days' END,
NULLIF($6, '')
)
RETURNING id::text, slug, name, status::text, kind::text, plan,
COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''),
trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''),
COALESCE(admin_email,''), status_changed_at, created_at, updated_at`,
in.Slug, in.Name, kind, plan, in.SalesOwner, in.AdminEmail,
)
t, err := scanTenant(row)
if err != nil {
if isUniqueViolation(err) {
return nil, ErrConflict
}
if isCheckViolation(err) {
return nil, ErrInvalidInput
}
return nil, fmt.Errorf("create tenant: %w", err)
}
return t, nil
}
func (p *Postgres) GetTenant(ctx context.Context, id string) (*Tenant, error) {
return scanTenant(p.pool.QueryRow(ctx, tenantSelect+`WHERE id = $1::uuid`, id))
}
func (p *Postgres) GetTenantBySlug(ctx context.Context, slug string) (*Tenant, error) {
return scanTenant(p.pool.QueryRow(ctx, tenantSelect+`WHERE slug = $1`, slug))
}
func (p *Postgres) GetTenantByErpCustomerID(ctx context.Context, erpCustomerID string) (*Tenant, error) {
if erpCustomerID == "" {
return nil, ErrNotFound
}
return scanTenant(p.pool.QueryRow(ctx, tenantSelect+`WHERE erp_customer_id = $1`, erpCustomerID))
}
func (p *Postgres) UpdateTenant(ctx context.Context, id string, in TenantUpdate) (*Tenant, error) {
// Build a partial UPDATE via COALESCE on each nullable input. Reads each
// field once; trivially type-safe.
row := p.pool.QueryRow(ctx, `
UPDATE tenants SET
status = COALESCE($2::tenant_status, status),
plan = COALESCE($3, plan),
erp_customer_id = COALESCE($4, erp_customer_id),
stripe_cust_id = COALESCE($5, stripe_cust_id),
trial_ends_at = COALESCE($6, trial_ends_at),
contract_start = COALESCE($7, contract_start),
contract_end = COALESCE($8, contract_end),
sales_owner = COALESCE($9, sales_owner),
admin_email = COALESCE($10, admin_email)
WHERE id = $1::uuid
RETURNING id::text, slug, name, status::text, kind::text, plan,
COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''),
trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''),
COALESCE(admin_email,''), status_changed_at, created_at, updated_at`,
id,
nullableStr(in.Status), nullableStr(in.Plan),
nullableStr(in.ErpCustomerID), nullableStr(in.StripeCustID),
nullableTime(in.TrialEndsAt), nullableTime(in.ContractStart), nullableTime(in.ContractEnd),
nullableStr(in.SalesOwner), nullableStr(in.AdminEmail),
)
t, err := scanTenant(row)
if err != nil {
if isCheckViolation(err) {
return nil, ErrInvalidInput
}
return nil, err
}
return t, nil
}
// ─── entitlements ─────────────────────────────────────────────────────────
func (p *Postgres) UpsertTenantProduct(ctx context.Context, tp TenantProduct) (*TenantProduct, error) {
cfg, err := json.Marshal(tp.Config)
if err != nil {
return nil, fmt.Errorf("marshal config: %w", err)
}
if cfg == nil || string(cfg) == "null" {
cfg = []byte("{}")
}
row := p.pool.QueryRow(ctx, `
INSERT INTO tenant_products (tenant_id, product, enabled, config, expires_at)
VALUES ($1::uuid, $2, $3, $4::jsonb, $5)
ON CONFLICT (tenant_id, product) DO UPDATE SET
enabled = EXCLUDED.enabled,
config = EXCLUDED.config,
expires_at = EXCLUDED.expires_at,
-- a real booking ends a preview grant (its expiry must never cut
-- off a paid entitlement)
preview = FALSE,
preview_expires_at = NULL
RETURNING `+tenantProductCols,
tp.TenantID, tp.Product, tp.Enabled, cfg, tp.ExpiresAt,
)
out, err := scanTenantProduct(row)
if err != nil {
// FK violation on tenant_id → not found
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation {
return nil, ErrNotFound
}
return nil, err
}
return out, nil
}
const tenantProductCols = `tenant_id::text, product, enabled, config, expires_at, preview, preview_expires_at, created_at, updated_at`
func scanTenantProduct(row pgx.Row) (*TenantProduct, error) {
var tp TenantProduct
var rawCfg []byte
if err := row.Scan(&tp.TenantID, &tp.Product, &tp.Enabled, &rawCfg, &tp.ExpiresAt, &tp.Preview, &tp.PreviewExpiresAt, &tp.CreatedAt, &tp.UpdatedAt); err != nil {
return nil, err
}
if err := json.Unmarshal(rawCfg, &tp.Config); err != nil || tp.Config == nil {
tp.Config = map[string]interface{}{}
}
return &tp, nil
}
func (p *Postgres) SetPreviewGrant(ctx context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error) {
tp, err := scanTenantProduct(p.pool.QueryRow(ctx, `
INSERT INTO tenant_products (tenant_id, product, enabled, config, preview, preview_expires_at)
VALUES ($1::uuid, $2, TRUE, '{}'::jsonb, TRUE, $3)
ON CONFLICT (tenant_id, product) DO UPDATE SET
enabled = TRUE, preview = TRUE, preview_expires_at = EXCLUDED.preview_expires_at
WHERE tenant_products.preview OR NOT tenant_products.enabled
RETURNING `+tenantProductCols, tenantID, product, expiresAt))
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrConflict // really booked: the WHERE refused the update
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && (pgErr.Code == pgerrcode.ForeignKeyViolation || pgErr.Code == pgerrcode.InvalidTextRepresentation) {
return nil, ErrNotFound
}
return tp, err
}
func (p *Postgres) RevokePreviewGrant(ctx context.Context, tenantID, product string) error {
tag, err := p.pool.Exec(ctx, `DELETE FROM tenant_products WHERE tenant_id = $1::uuid AND product = $2 AND preview`, tenantID, product)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.InvalidTextRepresentation {
return ErrNotFound
}
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) ListTenantProducts(ctx context.Context, tenantID string) ([]TenantProduct, error) {
// First confirm tenant exists so we can return ErrNotFound consistent with Memory.
if _, err := p.GetTenant(ctx, tenantID); err != nil {
return nil, err
}
rows, err := p.pool.Query(ctx, `
SELECT `+tenantProductCols+`
FROM tenant_products WHERE tenant_id = $1::uuid ORDER BY product`, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []TenantProduct{}
for rows.Next() {
tp, err := scanTenantProduct(rows)
if err != nil {
return nil, err
}
out = append(out, *tp)
}
return out, rows.Err()
}
// ─── api keys ─────────────────────────────────────────────────────────────
func (p *Postgres) CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error) {
var product, createdBy, hash, holder any
if in.Product != "" {
product = in.Product
}
if in.CreatedBy != "" {
createdBy = in.CreatedBy
}
if in.Hash != "" {
hash = in.Hash
}
if in.Holder != "" {
holder = in.Holder
}
kind := in.Kind
if kind == "" {
kind = APIKeyKindUser
}
// Coerce nil to an empty slice — the schema's NOT NULL DEFAULT only
// fires when the column is omitted, not when an explicit NULL is sent.
scopes := in.Scopes
if scopes == nil {
scopes = []string{}
}
row := p.pool.QueryRow(ctx, `
INSERT INTO api_keys (tenant_id, product, name, scopes, hash, hash_sha256, prefix, kind, holder, expires_at, created_by)
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
RETURNING `+apiKeyCols,
in.TenantID, product, in.Name, scopes, hash, in.HashSHA256, in.Prefix, kind, holder, in.ExpiresAt, createdBy,
)
k, err := scanAPIKey(row)
if err != nil {
if isUniqueViolation(err) {
return nil, ErrConflict
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation {
return nil, ErrNotFound
}
return nil, err
}
return k, nil
}
// apiKeyCols is the column list scanAPIKey reads, in order.
const apiKeyCols = `id::text, tenant_id::text, COALESCE(product,''), name, scopes, prefix,
kind, COALESCE(holder,''), expires_at, COALESCE(created_by,''), last_used_at, revoked_at, created_at`
func scanAPIKey(row pgx.Row, extra ...any) (*APIKey, error) {
var k APIKey
dest := append([]any{&k.ID, &k.TenantID, &k.Product, &k.Name, &k.Scopes, &k.Prefix,
&k.Kind, &k.Holder, &k.ExpiresAt, &k.CreatedBy, &k.LastUsedAt, &k.RevokedAt, &k.CreatedAt}, extra...)
err := row.Scan(dest...)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return &k, nil
}
func (p *Postgres) FindAPIKeyBySHA256(ctx context.Context, sum []byte) (*APIKey, error) {
return scanAPIKey(p.pool.QueryRow(ctx, `
SELECT `+apiKeyCols+` FROM api_keys WHERE hash_sha256 = $1 AND revoked_at IS NULL`, sum))
}
func (p *Postgres) FindAPIKeysByPrefix(ctx context.Context, prefix string) ([]APIKeyCandidate, error) {
rows, err := p.pool.Query(ctx, `
SELECT `+apiKeyCols+`, hash FROM api_keys
WHERE prefix = $1 AND revoked_at IS NULL AND hash IS NOT NULL`, prefix)
if err != nil {
return nil, err
}
defer rows.Close()
var out []APIKeyCandidate
for rows.Next() {
var hash string
k, err := scanAPIKey(rows, &hash)
if err != nil {
return nil, err
}
out = append(out, APIKeyCandidate{APIKey: *k, Hash: hash})
}
return out, rows.Err()
}
func (p *Postgres) TouchAPIKeyUsed(ctx context.Context, id string) error {
tag, err := p.pool.Exec(ctx, `UPDATE api_keys SET last_used_at = NOW() WHERE id = $1::uuid`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) RevokeAPIKey(ctx context.Context, id, tenantID string) error {
tag, err := p.pool.Exec(ctx, `
UPDATE api_keys SET revoked_at = NOW()
WHERE id = $1::uuid AND revoked_at IS NULL AND ($2 = '' OR tenant_id::text = $2)`, id, tenantID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) ListAPIKeys(ctx context.Context, tenantID string) ([]APIKey, error) {
if _, err := p.GetTenant(ctx, tenantID); err != nil {
return nil, err
}
rows, err := p.pool.Query(ctx, `
SELECT `+apiKeyCols+` FROM api_keys WHERE tenant_id = $1::uuid ORDER BY created_at DESC`, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []APIKey{}
for rows.Next() {
k, err := scanAPIKey(rows)
if err != nil {
return nil, err
}
out = append(out, *k)
}
return out, rows.Err()
}
// ─── audit ────────────────────────────────────────────────────────────────
func (p *Postgres) AppendAudit(ctx context.Context, ev AuditEvent) (*AuditEvent, error) {
meta, _ := json.Marshal(ev.Metadata)
if meta == nil || string(meta) == "null" {
meta = []byte("{}")
}
row := p.pool.QueryRow(ctx, `
INSERT INTO audit_log
(tenant_id, project_id, actor_id, actor_name, actor_type, action,
target_id, target_type, target_name, product, metadata, source_ip, user_agent)
VALUES
(NULLIF($1,'')::uuid, NULLIF($2,'')::uuid, NULLIF($3,''), NULLIF($4,''), NULLIF($5,''), $6,
NULLIF($7,''), NULLIF($8,''), NULLIF($9,''), NULLIF($10,''), $11::jsonb,
NULLIF($12,'')::inet, NULLIF($13,''))
RETURNING id, COALESCE(tenant_id::text,''), COALESCE(project_id::text,''),
COALESCE(actor_id,''), COALESCE(actor_name,''), COALESCE(actor_type,''),
action, COALESCE(target_id,''), COALESCE(target_type,''), COALESCE(target_name,''),
COALESCE(product,''), metadata, COALESCE(host(source_ip),''), COALESCE(user_agent,''),
created_at`,
ev.TenantID, ev.ProjectID, ev.ActorID, ev.ActorName, ev.ActorType, ev.Action,
ev.TargetID, ev.TargetType, ev.TargetName, ev.Product, meta, ev.SourceIP, ev.UserAgent,
)
out, err := scanAudit(row)
if err != nil {
return nil, err
}
return out, nil
}
func scanAudit(row pgx.Row) (*AuditEvent, error) {
var ev AuditEvent
var rawMeta []byte
err := row.Scan(
&ev.ID, &ev.TenantID, &ev.ProjectID,
&ev.ActorID, &ev.ActorName, &ev.ActorType,
&ev.Action, &ev.TargetID, &ev.TargetType, &ev.TargetName,
&ev.Product, &rawMeta, &ev.SourceIP, &ev.UserAgent,
&ev.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
if len(rawMeta) > 0 {
if err := json.Unmarshal(rawMeta, &ev.Metadata); err != nil {
ev.Metadata = map[string]interface{}{}
}
}
return &ev, nil
}
func (p *Postgres) ListAudit(ctx context.Context, f AuditFilter) ([]AuditEvent, int64, error) {
limit := f.Limit
if limit <= 0 || limit > 500 {
limit = 100
}
// Build WHERE clauses dynamically — keep param indices stable.
where := []string{"id > $1"}
args := []any{f.Cursor}
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.ActorID != "" {
add("actor_id = $%d", f.ActorID)
}
if f.Action != "" {
add("action = $%d", f.Action)
}
if f.Since != nil {
add("created_at >= $%d", *f.Since)
}
if f.Until != nil {
add("created_at <= $%d", *f.Until)
}
args = append(args, limit)
sql := `
SELECT id, COALESCE(tenant_id::text,''), COALESCE(project_id::text,''),
COALESCE(actor_id,''), COALESCE(actor_name,''), COALESCE(actor_type,''),
action, COALESCE(target_id,''), COALESCE(target_type,''), COALESCE(target_name,''),
COALESCE(product,''), metadata, COALESCE(host(source_ip),''), COALESCE(user_agent,''),
created_at
FROM audit_log
WHERE ` + strings.Join(where, " AND ") + `
ORDER BY id ASC
LIMIT $` + fmt.Sprintf("%d", len(args))
rows, err := p.pool.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
out := []AuditEvent{}
for rows.Next() {
ev, err := scanAudit(rows)
if err != nil {
return nil, 0, err
}
out = append(out, *ev)
}
if err := rows.Err(); err != nil {
return nil, 0, err
}
var nextCursor int64
if len(out) == limit && len(out) > 0 {
nextCursor = out[len(out)-1].ID
}
return out, nextCursor, nil
}
func nullableStr(p *string) any {
if p == nil {
return nil
}
return *p
}
func nullableTime(p *time.Time) any {
if p == nil {
return nil
}
return *p
}
// ─── tenant listing ───────────────────────────────────────────────────────
func (p *Postgres) ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, string, error) {
limit := f.Limit
if limit <= 0 || limit > 500 {
limit = 100
}
cAt, cID, ok := decodeTenantCursor(f.Cursor)
if !ok {
return nil, "", ErrInvalidInput
}
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.Status != "" {
add("status = $%d::tenant_status", f.Status)
}
if f.Kind != "" {
add("kind = $%d::tenant_kind", f.Kind)
}
if q := strings.TrimSpace(f.Query); q != "" {
args = append(args, "%"+likeEscape(q)+"%")
n := len(args)
where = append(where, fmt.Sprintf("(slug ILIKE $%d OR name ILIKE $%d OR COALESCE(admin_email, '') ILIKE $%d)", n, n, n))
}
if f.Cursor != "" {
args = append(args, cAt, cID)
where = append(where, fmt.Sprintf("(created_at, id::text) > ($%d, $%d)", len(args)-1, len(args)))
}
args = append(args, limit+1)
rows, err := p.pool.Query(ctx, tenantSelect+`WHERE `+strings.Join(where, " AND ")+
` ORDER BY created_at, id LIMIT $`+fmt.Sprintf("%d", len(args)), args...)
if err != nil {
return nil, "", err
}
defer rows.Close()
out := []Tenant{}
for rows.Next() {
t, err := scanTenant(rows)
if err != nil {
return nil, "", err
}
out = append(out, *t)
}
if err := rows.Err(); err != nil {
return nil, "", err
}
next := ""
if len(out) > limit {
out = out[:limit]
next = encodeTenantCursor(out[len(out)-1])
}
return out, next, nil
}
// ─── products ─────────────────────────────────────────────────────────────
const productSelect = `
SELECT key, name, description, type, launch_urls, provision_urls, skus, addons,
plans_required, supports_trial, trial_days, enabled, sort_order, created_at, updated_at
FROM products `
func scanProduct(row pgx.Row) (*Product, error) {
var pr Product
var launch, prov, skus, addons []byte
err := row.Scan(&pr.Key, &pr.Name, &pr.Description, &pr.Type, &launch, &prov, &skus, &addons,
&pr.PlansRequired, &pr.SupportsTrial, &pr.TrialDays, &pr.Enabled, &pr.SortOrder, &pr.CreatedAt, &pr.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
_ = json.Unmarshal(launch, &pr.LaunchURLs)
_ = json.Unmarshal(prov, &pr.ProvisionURLs)
_ = json.Unmarshal(skus, &pr.SKUs)
_ = json.Unmarshal(addons, &pr.Addons)
if pr.LaunchURLs == nil {
pr.LaunchURLs = map[string]string{}
}
if pr.ProvisionURLs == nil {
pr.ProvisionURLs = map[string]string{}
}
if pr.SKUs == nil {
pr.SKUs = []string{}
}
if pr.Addons == nil {
pr.Addons = []ProductAddon{}
}
if pr.PlansRequired == nil {
pr.PlansRequired = []string{}
}
return &pr, nil
}
func (p *Postgres) ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error) {
q := productSelect
if !includeDisabled {
q += `WHERE enabled `
}
rows, err := p.pool.Query(ctx, q+`ORDER BY sort_order, key`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Product{}
for rows.Next() {
pr, err := scanProduct(rows)
if err != nil {
return nil, err
}
out = append(out, *pr)
}
return out, rows.Err()
}
func (p *Postgres) GetProduct(ctx context.Context, key string) (*Product, error) {
return scanProduct(p.pool.QueryRow(ctx, productSelect+`WHERE key = $1`, key))
}
// likeEscape escapes the LIKE wildcards in user input (the default escape is \).
func likeEscape(s string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}
func (p *Postgres) TenantActivity(ctx context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) {
out := map[string]TenantActivity{}
if len(tenantIDs) == 0 {
return out, nil
}
get := func(id string) TenantActivity {
a, ok := out[id]
if !ok {
a = TenantActivity{Usage: map[string]float64{}}
}
return a
}
rows, err := p.pool.Query(ctx, `
SELECT tenant_id::text, metric, SUM(quantity)
FROM usage_events
WHERE tenant_id::text = ANY($1) AND occurred_at >= $2
GROUP BY tenant_id, metric`, tenantIDs, since)
if err != nil {
return nil, err
}
for rows.Next() {
var id, metric string
var total float64
if err := rows.Scan(&id, &metric, &total); err != nil {
rows.Close()
return nil, err
}
a := get(id)
a.Usage[metric] = total
out[id] = a
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
rows, err = p.pool.Query(ctx, `
SELECT tenant_id::text, MAX(created_at)
FROM audit_log
WHERE tenant_id::text = ANY($1)
GROUP BY tenant_id`, tenantIDs)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id string
var at time.Time
if err := rows.Scan(&id, &at); err != nil {
return nil, err
}
a := get(id)
a.LastActivityAt = &at
out[id] = a
}
return out, rows.Err()
}
// DeleteTenant implements Store. The foreign keys do the rest: every table
// that belongs to a tenant cascades, audit_log keeps its rows (SET NULL).
func (p *Postgres) DeleteTenant(ctx context.Context, id string) error {
tag, err := p.pool.Exec(ctx, `DELETE FROM tenants WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}