Files
superbrain/db/migrations/012_tenancy.sql
T
Andrew S Erwin 1f38c4d56c
release gate / check (push) Failing after 7m7s
Add tenancy phase 1: implicit tenants, plan entitlements, quota counters
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).
2026-10-26 13:21:12 -05:00

80 lines
3.2 KiB
SQL

-- 012_tenancy.sql — tenancy phase 1 (DESIGN_TENANCY_ENTITLEMENTS.md):
-- Tenant / TenantMember / TenantEntitlement / QuotaUsage, User.tenantId,
-- and the implicit-default-tenant backfill for existing installs.
--
-- Additive and idempotent; schema.sql carries identical structures so this
-- is a structural no-op on a fresh database (db-converge proves both paths
-- land the same). The User.tenantId FK is re-created by NAME under a guard:
-- converge pass 2 drops migration-created tables with CASCADE (which removes
-- the constraint from the non-migration-created User table) and re-runs the
-- chain, so an unguarded inline ADD COLUMN would leave the FK missing.
--
-- Backfill policy: one implicit tenant (slug 'default', fixed id) adopts
-- every existing user; ADMIN users become membership 'owner', others
-- 'member'. Plan starts 'selfhosted'; the app reconciles the implicit
-- tenant's plan with TIER at startup (core -> 'core', multi -> 'free') and
-- never overwrites a sold plan ('standard'/'premium').
CREATE TABLE IF NOT EXISTS "Tenant" (
id text PRIMARY KEY,
name text NOT NULL,
slug text NOT NULL UNIQUE,
plan text NOT NULL DEFAULT 'selfhosted' CHECK (plan IN ('free','standard','premium','core','selfhosted')),
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','suspended','closed')),
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "tenantId" text;
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'User_tenantId_fkey' AND conrelid = '"User"'::regclass
) THEN
ALTER TABLE "User"
ADD CONSTRAINT "User_tenantId_fkey"
FOREIGN KEY ("tenantId") REFERENCES "Tenant"(id) ON DELETE SET NULL;
END IF;
END $$;
CREATE TABLE IF NOT EXISTS "TenantMember" (
id text PRIMARY KEY,
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
"userId" text NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE CASCADE,
role text NOT NULL DEFAULT 'member' CHECK (role IN ('owner','admin','member')),
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS "TenantMember_tenantId_idx" ON "TenantMember"("tenantId");
CREATE TABLE IF NOT EXISTS "TenantEntitlement" (
id text PRIMARY KEY,
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
key text NOT NULL,
value text NOT NULL,
"createdAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("tenantId", key)
);
CREATE TABLE IF NOT EXISTS "QuotaUsage" (
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
key text NOT NULL,
used bigint NOT NULL DEFAULT 0,
"updatedAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("tenantId", key)
);
-- Backfill (idempotent): implicit tenant adopts every tenantless user.
INSERT INTO "Tenant"(id, name, slug, plan)
VALUES ('tenant-default', 'Default', 'default', 'selfhosted')
ON CONFLICT DO NOTHING;
UPDATE "User" SET "tenantId" = 'tenant-default' WHERE "tenantId" IS NULL;
INSERT INTO "TenantMember"(id, "tenantId", "userId", role)
SELECT 'tmem-' || u.id, 'tenant-default', u.id,
CASE WHEN u.role = 'ADMIN' THEN 'owner' ELSE 'member' END
FROM "User" u
ON CONFLICT ("userId") DO NOTHING;