release gate / check (push) Failing after 7m7s
Foundation for the priced plans (PLAN_PRICING_TIERS.md): every user now belongs to exactly one tenant, and single-tenant deployments (self-hosted, core) use an implicit 'tenant-default' row so no code path special-cases 'no tenant'. Plans are per-tenant DATA, never code forks — the open-source promise depends on the free version being the same binary. Schema (migration 012 + schema.sql, converge- and atomicity-verified): Tenant, TenantMember (1:1 per user in phase 1), TenantEntitlement (per-tenant overrides), QuotaUsage (maintained counters), User.tenantId. The backfill adopts every existing user into the implicit tenant (ADMIN -> owner, others -> member). The User.tenantId FK is re-added by name under a guard so converge pass 2 (CASCADE-drop + chain re-run) stays clean. internal/entitlements: the shipped plan catalog (free/standard/premium/ core/selfhosted: storage, brain links, seats, notification channels, connectors, AI mode), tier -> default-plan derivation, override merging that fails CLOSED (unknown plan resolves to free limits; malformed override rows are ignored so a bad row can never widen access), and WithinQuota boundary logic. internal/db/tenants.go: EnsureDefault reconciles the implicit tenant's plan with TIER but only ever touches auto plans (core/selfhosted) — sold plans are billing data, not deployment config. AdoptOrphans is the runtime self-heal twin of the migration backfill (restored dumps); main runs Bootstrap once at startup, best-effort. QuotaAdd moves counters under an advisory lock and refuses growth past the plan limit with ErrQuotaExceeded; counters floor at 0. Wiring: createUserTx attaches tenant + membership atomically for EVERY creation path (signup, OIDC provisioning, seed CLI); the identity projection carries tenantId, so /api/me and the bridge response expose it. models.User gains TenantID. No behavior changes for existing installs: default limits are declarative until gate points land (connectors, brain links, notifications, storage metering are later steps). API.md documents tenantId and the password- reset endpoints; AGENTS.md records the invariant that features gate on PLAN, never on TIER directly. Tests: entitlements unit tests (catalog, fail-closed resolution, override normalization, quota boundaries) and integration tests (attach-on-create across all three paths with owner/member roles, bootstrap + plan reconcile including 'sold plans never overwritten', limits resolution, quota consume/refuse/release/floor).
202 lines
7.6 KiB
Go
202 lines
7.6 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/andrew/superbrain/internal/config"
|
|
"github.com/andrew/superbrain/internal/entitlements"
|
|
)
|
|
|
|
// Tenancy phase 1 (DESIGN_TENANCY_ENTITLEMENTS.md): every user belongs to
|
|
// exactly one tenant. Single-tenant deployments (self-hosted, core) use the
|
|
// implicit default tenant created here and backfilled by migration 012, so
|
|
// no code path ever special-cases "no tenant". Sold-plan tenants and real
|
|
// multi-tenant onboarding arrive with the billing workstream.
|
|
|
|
// DefaultTenantID is the fixed id/slug of the implicit tenant. A stable id
|
|
// (not NewID) keeps creation idempotent across processes and matches the
|
|
// migration backfill.
|
|
const DefaultTenantID = "tenant-default"
|
|
|
|
type TenantRepo struct{ db *DB }
|
|
|
|
func NewTenantRepo(d *DB) *TenantRepo { return &TenantRepo{db: d} }
|
|
|
|
// ErrQuotaExceeded is returned by QuotaAdd when a counter would grow past
|
|
// its plan limit. Gate points translate it into 402/413-class responses.
|
|
var ErrQuotaExceeded = errors.New("quota exceeded")
|
|
|
|
// EnsureDefault creates the implicit tenant when missing and reconciles its
|
|
// plan with the deployment tier. Only auto-derived plans ('core',
|
|
// 'selfhosted') are ever adjusted — a sold plan ('standard'/'premium') or a
|
|
// billing-owned 'free' is data, not deployment config, and stays untouched.
|
|
func (r *TenantRepo) EnsureDefault(ctx context.Context) error {
|
|
plan := entitlements.DefaultPlanForTier(config.Tier())
|
|
if _, err := r.db.ExecContext(ctx,
|
|
`INSERT INTO "Tenant"(id,name,slug,plan) VALUES($1,'Default','default',$2) ON CONFLICT (id) DO NOTHING`,
|
|
DefaultTenantID, string(plan)); err != nil {
|
|
return err
|
|
}
|
|
_, err := r.db.ExecContext(ctx,
|
|
`UPDATE "Tenant" SET plan=$2,"updatedAt"=now() WHERE id=$1 AND plan<>$2 AND plan IN ('core','selfhosted')`,
|
|
DefaultTenantID, string(plan))
|
|
return err
|
|
}
|
|
|
|
// AdoptOrphans attaches any tenantless user to the default tenant and
|
|
// backfills missing memberships (ADMIN -> owner, others -> member). This is
|
|
// the runtime self-heal twin of the migration 012 backfill: idempotent,
|
|
// safe on every boot, and it repairs databases restored without the ledger.
|
|
func (r *TenantRepo) AdoptOrphans(ctx context.Context) error {
|
|
if _, err := r.db.ExecContext(ctx,
|
|
`UPDATE "User" SET "tenantId"=$1 WHERE "tenantId" IS NULL`, DefaultTenantID); err != nil {
|
|
return err
|
|
}
|
|
_, err := r.db.ExecContext(ctx, `
|
|
INSERT INTO "TenantMember"(id,"tenantId","userId",role)
|
|
SELECT 'tmem-'||u.id, $1, u.id, CASE WHEN u.role='ADMIN' THEN 'owner' ELSE 'member' END
|
|
FROM "User" u
|
|
ON CONFLICT ("userId") DO NOTHING`, DefaultTenantID)
|
|
return err
|
|
}
|
|
|
|
// Bootstrap runs the startup pair: ensure the implicit tenant exists with
|
|
// the right plan, then adopt anything left behind. main calls this once.
|
|
func (r *TenantRepo) Bootstrap(ctx context.Context) error {
|
|
if err := r.EnsureDefault(ctx); err != nil {
|
|
return err
|
|
}
|
|
return r.AdoptOrphans(ctx)
|
|
}
|
|
|
|
// ensureDefaultTx is EnsureDefault scoped to a caller-owned transaction
|
|
// (user creation attaches membership atomically with the user row).
|
|
func ensureDefaultTx(ctx context.Context, tx *sql.Tx) error {
|
|
plan := entitlements.DefaultPlanForTier(config.Tier())
|
|
_, err := tx.ExecContext(ctx,
|
|
`INSERT INTO "Tenant"(id,name,slug,plan) VALUES($1,'Default','default',$2) ON CONFLICT (id) DO NOTHING`,
|
|
DefaultTenantID, string(plan))
|
|
return err
|
|
}
|
|
|
|
// attachDefaultTenantTx gives a freshly created user row its phase-1 tenant
|
|
// and membership inside the creating transaction.
|
|
func attachDefaultTenantTx(ctx context.Context, tx *sql.Tx, userID, role string) error {
|
|
if err := ensureDefaultTx(ctx, tx); err != nil {
|
|
return err
|
|
}
|
|
if _, err := tx.ExecContext(ctx,
|
|
`UPDATE "User" SET "tenantId"=$1 WHERE id=$2 AND "tenantId" IS NULL`,
|
|
DefaultTenantID, userID); err != nil {
|
|
return err
|
|
}
|
|
memberRole := "member"
|
|
if role == "ADMIN" {
|
|
memberRole = "owner"
|
|
}
|
|
_, err := tx.ExecContext(ctx,
|
|
`INSERT INTO "TenantMember"(id,"tenantId","userId",role) VALUES('tmem-'||$1,$2,$1,$3) ON CONFLICT ("userId") DO NOTHING`,
|
|
userID, DefaultTenantID, memberRole)
|
|
return err
|
|
}
|
|
|
|
// Plan returns a tenant's plan. Unknown tenants fail closed to the free
|
|
// catalog entry (entitlements.For semantics) rather than erroring, so a
|
|
// dangling tenantId can never widen access.
|
|
func (r *TenantRepo) Plan(ctx context.Context, tenantID string) (entitlements.Plan, error) {
|
|
var plan string
|
|
err := r.db.QueryRowContext(ctx, `SELECT plan FROM "Tenant" WHERE id=$1`, tenantID).Scan(&plan)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return entitlements.PlanFree, nil
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return entitlements.Plan(plan), nil
|
|
}
|
|
|
|
// Limits resolves a tenant's effective entitlements: catalog plan merged
|
|
// with per-tenant override rows. Unparsable override values are ignored by
|
|
// ApplyOverrides (a bad row can never widen limits).
|
|
func (r *TenantRepo) Limits(ctx context.Context, tenantID string) (entitlements.Limits, error) {
|
|
plan, err := r.Plan(ctx, tenantID)
|
|
if err != nil {
|
|
return entitlements.Limits{}, err
|
|
}
|
|
rows, err := r.db.QueryContext(ctx,
|
|
`SELECT key, value FROM "TenantEntitlement" WHERE "tenantId"=$1`, tenantID)
|
|
if err != nil {
|
|
return entitlements.Limits{}, err
|
|
}
|
|
defer rows.Close()
|
|
overrides := map[string]string{}
|
|
for rows.Next() {
|
|
var k, v string
|
|
if err := rows.Scan(&k, &v); err != nil {
|
|
return entitlements.Limits{}, err
|
|
}
|
|
overrides[k] = v
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return entitlements.Limits{}, err
|
|
}
|
|
return entitlements.ApplyOverrides(entitlements.For(plan), overrides), nil
|
|
}
|
|
|
|
// SetEntitlement writes or updates one override row (operator tooling;
|
|
// there is no public API for this in phase 1).
|
|
func (r *TenantRepo) SetEntitlement(ctx context.Context, tenantID, key, value string) error {
|
|
if !entitlements.ValidOverrideKey(key) {
|
|
return fmt.Errorf("unknown entitlement key %q", key)
|
|
}
|
|
_, err := r.db.ExecContext(ctx, `
|
|
INSERT INTO "TenantEntitlement"(id,"tenantId",key,value) VALUES($1,$2,$3,$4)
|
|
ON CONFLICT ("tenantId",key) DO UPDATE SET value=EXCLUDED.value`,
|
|
NewID(), tenantID, key, value)
|
|
return err
|
|
}
|
|
|
|
// QuotaUsage reads a maintained counter (0 when untouched).
|
|
func (r *TenantRepo) QuotaUsage(ctx context.Context, tenantID, key string) (int64, error) {
|
|
var used int64
|
|
err := r.db.QueryRowContext(ctx,
|
|
`SELECT used FROM "QuotaUsage" WHERE "tenantId"=$1 AND key=$2`, tenantID, key).Scan(&used)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return 0, nil
|
|
}
|
|
return used, err
|
|
}
|
|
|
|
// QuotaAdd moves a counter by delta (negative releases) inside one
|
|
// advisory-locked transaction, refusing growth past limit with
|
|
// ErrQuotaExceeded. Counters never go below 0. Callers pass the plan limit
|
|
// resolved via Limits so the check and the write share one serialization
|
|
// point — the same discipline as the version-bump paths elsewhere.
|
|
func (r *TenantRepo) QuotaAdd(ctx context.Context, tenantID, key string, delta, limit int64) error {
|
|
return Transaction(ctx, r.db, func(tx *sql.Tx) error {
|
|
if _, err := tx.ExecContext(ctx,
|
|
`SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, "quota:"+tenantID+":"+key); err != nil {
|
|
return err
|
|
}
|
|
var used int64
|
|
err := tx.QueryRowContext(ctx,
|
|
`SELECT used FROM "QuotaUsage" WHERE "tenantId"=$1 AND key=$2`, tenantID, key).Scan(&used)
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return err
|
|
}
|
|
if delta > 0 && !entitlements.WithinQuota(used, delta, limit) {
|
|
return ErrQuotaExceeded
|
|
}
|
|
_, err = tx.ExecContext(ctx, `
|
|
INSERT INTO "QuotaUsage"("tenantId",key,used,"updatedAt")
|
|
VALUES($1,$2,GREATEST($3::bigint,0),now())
|
|
ON CONFLICT ("tenantId",key)
|
|
DO UPDATE SET used=GREATEST("QuotaUsage".used+$3::bigint,0),"updatedAt"=now()`,
|
|
tenantID, key, delta)
|
|
return err
|
|
})
|
|
}
|