Phase 13, part 1: a Postgres schema per team
On the multi-tenant edition each team's data is in its own schema; the tables every team shares (people, sessions, memberships, keys, locks, and a new teams table) stay in the main one. A team's connection pool searches its own schema first, so the app's SQL runs unchanged and can't reach another team's tables. Each request is served by a copy of the Server for the viewer's team, with that team's database, secrets and caches; agents work on their own team's. The local and server editions are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -35,12 +35,17 @@ type DB struct {
|
||||
SQL *sql.DB
|
||||
Dialect Dialect
|
||||
|
||||
// Team is the team whose schema this is (Teams.Open); 0 for the main
|
||||
// database.
|
||||
Team int64
|
||||
|
||||
// MigratedFrom is the schema version the database was at when opened,
|
||||
// if Open migrated it (0 if it was new or already current), for the
|
||||
// log.
|
||||
MigratedFrom int
|
||||
|
||||
closeHook func() error // tests on Postgres: drop the test's schema
|
||||
url string // Postgres: where it was opened, for teams' schemas
|
||||
}
|
||||
|
||||
func (d *DB) query(q string) string {
|
||||
|
||||
@@ -17,8 +17,18 @@ type Migration struct {
|
||||
Note string // what it does, for the record (Postgres' schema_migrations)
|
||||
SQLite string
|
||||
Postgres string // empty: PostgresSQL(SQLite)
|
||||
// Platform marks a migration that only touches the tables every team
|
||||
// shares (people, sessions, keys, locks): on the multi-tenant edition
|
||||
// it runs in the main schema, never in a team's (see Teams). A
|
||||
// migration is one or the other, never both.
|
||||
Platform bool
|
||||
}
|
||||
|
||||
// PlatformTables are the tables every team shares on the multi-tenant
|
||||
// edition, in the main schema; every other table is a team's, in its own
|
||||
// schema.
|
||||
var PlatformTables = []string{"instances", "locks", "users", "memberships", "sessions", "links", "throttle", "agent_keys", "teams"}
|
||||
|
||||
// both are the migrations after schema 29, on both databases: schema 30
|
||||
// is both[0]. (migrations, before them, are SQLite's own; Postgres starts
|
||||
// from postgres.sql, which is schema 29 as a whole.)
|
||||
@@ -37,7 +47,8 @@ CREATE TABLE secrets (
|
||||
},
|
||||
// 31
|
||||
{
|
||||
Note: "copies of the app, and the locks that let only one of them do a job",
|
||||
Note: "copies of the app, and the locks that let only one of them do a job",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE instances (
|
||||
id TEXT PRIMARY KEY, -- a copy of the app, while it runs
|
||||
@@ -56,7 +67,8 @@ CREATE TABLE locks (
|
||||
},
|
||||
// 32
|
||||
{
|
||||
Note: "users, their memberships of the team, and their sign-in sessions (server and multi-tenant editions)",
|
||||
Note: "users, their memberships of the team, and their sign-in sessions (server and multi-tenant editions)",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY,
|
||||
@@ -94,7 +106,8 @@ CREATE INDEX sessions_user ON sessions(user_id);
|
||||
},
|
||||
// 33
|
||||
{
|
||||
Note: "one-time links: setting up the first owner, password resets, invitations",
|
||||
Note: "one-time links: setting up the first owner, password resets, invitations",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE links (
|
||||
id TEXT PRIMARY KEY, -- the SHA-256 of the link's random token
|
||||
@@ -108,7 +121,8 @@ CREATE INDEX links_user ON links(user_id, purpose);
|
||||
},
|
||||
// 34
|
||||
{
|
||||
Note: "signing in: failed attempts and locks, two-factor sign-in, and limits on tries",
|
||||
Note: "signing in: failed attempts and locks, two-factor sign-in, and limits on tries",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
ALTER TABLE users ADD COLUMN failed_signins INTEGER NOT NULL DEFAULT 0; -- in a row, since the last sign-in
|
||||
ALTER TABLE users ADD COLUMN locked_at TEXT NOT NULL DEFAULT ''; -- locked after too many; '' when not
|
||||
@@ -169,7 +183,8 @@ ALTER TABLE outreach ADD COLUMN created_by INTEGER NOT NULL DEFAULT 0;
|
||||
},
|
||||
// 37
|
||||
{
|
||||
Note: "agents' keys, and a description for each agent",
|
||||
Note: "agents' keys, and a description for each agent",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE agent_keys (
|
||||
id INTEGER PRIMARY KEY,
|
||||
@@ -240,6 +255,22 @@ CREATE TABLE agent_calls (
|
||||
ms INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX agent_calls_agent ON agent_calls(agent_id, at);
|
||||
`,
|
||||
},
|
||||
// 40
|
||||
{
|
||||
Note: "teams, and which team each sign-in session works in (multi-tenant edition)",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE teams (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
domain TEXT NOT NULL DEFAULT '', -- the one website domain it works on, such as example.com
|
||||
status TEXT NOT NULL DEFAULT 'active', -- active, suspended or deleting
|
||||
created_at TEXT NOT NULL,
|
||||
delete_at TEXT NOT NULL DEFAULT '' -- deleting: when its data goes for good
|
||||
);
|
||||
ALTER TABLE sessions ADD COLUMN team_id INTEGER NOT NULL DEFAULT 1;
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
+34
-7
@@ -37,7 +37,7 @@ func OpenPostgres(url string) (*DB, error) {
|
||||
sqldb.Close()
|
||||
return nil, fmt.Errorf("opening Postgres: %w", err)
|
||||
}
|
||||
d := &DB{SQL: sqldb, Dialect: Postgres}
|
||||
d := &DB{SQL: sqldb, Dialect: Postgres, url: url}
|
||||
if err := d.migratePostgres(); err != nil {
|
||||
sqldb.Close()
|
||||
return nil, err
|
||||
@@ -53,7 +53,12 @@ var AppVersion = "dev"
|
||||
// transaction: a failure leaves the database as it was. One copy of the
|
||||
// app at a time does it (an advisory lock), so several can start
|
||||
// together. Each step is recorded in schema_migrations.
|
||||
func (d *DB) migratePostgres() error {
|
||||
func (d *DB) migratePostgres() error { return d.migrateSchema(false) }
|
||||
|
||||
// migrateSchema migrates the schema the connection's search_path names
|
||||
// first: the main one, or (team) a team's, which skips the platform's
|
||||
// migrations and never has the platform's tables.
|
||||
func (d *DB) migrateSchema(team bool) error {
|
||||
if err := checkMigrations(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -62,7 +67,7 @@ func (d *DB) migratePostgres() error {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.Exec(`SELECT pg_advisory_xact_lock(4708421)`); err != nil { // any fixed number: "the schema"
|
||||
if _, err := tx.Exec(`SELECT pg_advisory_xact_lock(4708421, hashtext(current_schema()))`); err != nil { // any fixed number: "the schema", then which
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
@@ -77,8 +82,10 @@ func (d *DB) migratePostgres() error {
|
||||
_, err := tx.Exec(`INSERT INTO schema_migrations (version, note, app) VALUES ($1, $2, $3)`, version, note, AppVersion)
|
||||
return err
|
||||
}
|
||||
// In this schema itself: a team's search_path falls back to the main
|
||||
// schema, which has its own.
|
||||
var exists bool
|
||||
if err := tx.QueryRow(`SELECT to_regclass('schema_version') IS NOT NULL`).Scan(&exists); err != nil {
|
||||
if err := tx.QueryRow(`SELECT to_regclass(quote_ident(current_schema()) || '.schema_version') IS NOT NULL`).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
version := pgBaseline
|
||||
@@ -109,8 +116,13 @@ func (d *DB) migratePostgres() error {
|
||||
}
|
||||
for i := version; i < Schema(); i++ {
|
||||
m, q := postgresStep(i)
|
||||
if _, err := tx.Exec(q); err != nil {
|
||||
return fmt.Errorf("migration %d (%s): %w", i+1, m.Note, err)
|
||||
if team && m.Platform {
|
||||
q = "" // the platform's tables aren't in a team's schema
|
||||
}
|
||||
if q != "" {
|
||||
if _, err := tx.Exec(q); err != nil {
|
||||
return fmt.Errorf("migration %d (%s): %w", i+1, m.Note, err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE schema_version SET version = $1`, i+1); err != nil {
|
||||
return err
|
||||
@@ -174,7 +186,22 @@ func openTestSchema(base string) (*DB, error) {
|
||||
d.SQL.SetMaxOpenConns(4)
|
||||
d.closeHook = func() error {
|
||||
defer admin.Close()
|
||||
_, err := admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
|
||||
// Its teams' schemas too (Teams names them after it).
|
||||
rows, err := admin.Query(`SELECT nspname FROM pg_namespace WHERE nspname LIKE $1`, schema+`\_team\_%`)
|
||||
if err == nil {
|
||||
var teams []string
|
||||
for rows.Next() {
|
||||
var n string
|
||||
if rows.Scan(&n) == nil {
|
||||
teams = append(teams, n)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
for _, n := range teams {
|
||||
admin.Exec(`DROP SCHEMA ` + n + ` CASCADE`)
|
||||
}
|
||||
}
|
||||
_, err = admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
|
||||
return err
|
||||
}
|
||||
return d, nil
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Teams keeps each team's data in a Postgres schema of its own (the
|
||||
// multi-tenant edition). The main schema has what every team shares (see
|
||||
// PlatformTables); a team's schema has the rest, made by the same
|
||||
// migrations. A team's DB is a connection pool whose search_path is its
|
||||
// schema, then the main one: the app's SQL runs unchanged, finds the
|
||||
// team's tables, and the shared ones behind them, and can't reach another
|
||||
// team's tables without naming them.
|
||||
type Teams struct {
|
||||
platform *DB
|
||||
base string // the main database's address
|
||||
main string // the main schema
|
||||
prefix string // teams' schemas are <prefix><id>
|
||||
|
||||
mu sync.Mutex
|
||||
open map[int64]*DB
|
||||
}
|
||||
|
||||
// Teams opens the teams of a Postgres database.
|
||||
func (d *DB) Teams() (*Teams, error) {
|
||||
if d.Dialect != Postgres || d.url == "" {
|
||||
return nil, errors.New("teams need Postgres")
|
||||
}
|
||||
var main string
|
||||
if err := d.SQL.QueryRow(`SELECT current_schema()`).Scan(&main); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prefix := "team_"
|
||||
if main != "public" {
|
||||
prefix = main + "_team_" // tests: each in its own schema, its teams named after it
|
||||
}
|
||||
return &Teams{platform: d, base: d.url, main: main, prefix: prefix, open: map[int64]*DB{}}, nil
|
||||
}
|
||||
|
||||
// Schema is a team's schema's name.
|
||||
func (t *Teams) Schema(id int64) string { return t.prefix + strconv.FormatInt(id, 10) }
|
||||
|
||||
// connect opens a pool with a search_path.
|
||||
func (t *Teams) connect(path string) (*sql.DB, error) {
|
||||
u, err := url.Parse(t.base)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("search_path", path)
|
||||
u.RawQuery = q.Encode()
|
||||
return sql.Open("pgx", u.String())
|
||||
}
|
||||
|
||||
// Create makes a team's schema, with its tables at the current schema
|
||||
// version. Making one that exists only migrates it.
|
||||
func (t *Teams) Create(id int64) error {
|
||||
if id <= 0 {
|
||||
return errors.New("no team")
|
||||
}
|
||||
schema := t.Schema(id)
|
||||
if _, err := t.platform.SQL.Exec(`CREATE SCHEMA IF NOT EXISTS ` + schema); err != nil {
|
||||
return err
|
||||
}
|
||||
// Only the team's schema on the path while its tables are made, so
|
||||
// nothing is mistaken for the main schema's.
|
||||
sqldb, err := t.connect(schema)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sqldb.Close()
|
||||
d := &DB{SQL: sqldb, Dialect: Postgres}
|
||||
return d.migrateSchema(true)
|
||||
}
|
||||
|
||||
// Open is a team's database: one pool per team, kept while the app runs.
|
||||
// It migrates the team's schema to this version the first time.
|
||||
func (t *Teams) Open(id int64) (*DB, error) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if d, ok := t.open[id]; ok {
|
||||
return d, nil
|
||||
}
|
||||
var exists bool
|
||||
if err := t.platform.SQL.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, t.Schema(id)+".schema_version").Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("team %d has no data yet", id)
|
||||
}
|
||||
sqldb, err := t.connect(t.Schema(id) + "," + t.main)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Small: many teams share the server's connections. An idle team holds
|
||||
// none for long.
|
||||
sqldb.SetMaxOpenConns(4)
|
||||
sqldb.SetMaxIdleConns(1)
|
||||
sqldb.SetConnMaxIdleTime(time.Minute)
|
||||
d := &DB{SQL: sqldb, Dialect: Postgres, Team: id}
|
||||
if err := d.migrateSchema(true); err != nil {
|
||||
sqldb.Close()
|
||||
return nil, fmt.Errorf("team %d: %w", id, err)
|
||||
}
|
||||
t.open[id] = d
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// Drop deletes a team's schema and everything in it.
|
||||
func (t *Teams) Drop(id int64) error {
|
||||
t.mu.Lock()
|
||||
if d, ok := t.open[id]; ok {
|
||||
d.SQL.Close()
|
||||
delete(t.open, id)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
_, err := t.platform.SQL.Exec(`DROP SCHEMA IF EXISTS ` + t.Schema(id) + ` CASCADE`)
|
||||
return err
|
||||
}
|
||||
|
||||
// Close closes every team's pool.
|
||||
func (t *Teams) Close() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
for id, d := range t.open {
|
||||
d.SQL.Close()
|
||||
delete(t.open, id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTeamsSchemas(t *testing.T) {
|
||||
if !OnPostgres() {
|
||||
t.Skip("teams are Postgres's")
|
||||
}
|
||||
d, err := Open(filepath.Join(t.TempDir(), "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
teams, err := d.Teams()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer teams.Close()
|
||||
if _, err := teams.Open(1); err == nil {
|
||||
t.Error("opened a team that wasn't created")
|
||||
}
|
||||
for _, id := range []int64{1, 2} {
|
||||
if err := teams.Create(id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
a, err := teams.Open(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := teams.Open(2)
|
||||
if a2, _ := teams.Open(1); a2 != a {
|
||||
t.Error("a second pool")
|
||||
}
|
||||
if v, err := a.SchemaVersion(); err != nil || v != Schema() {
|
||||
t.Errorf("team schema at %d: %v", v, err)
|
||||
}
|
||||
// Each team's own tables.
|
||||
if err := a.PutJSON("company", "Acme"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := b.PutJSON("company", "Bolt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got string
|
||||
a.GetJSON("company", &got)
|
||||
if got != "Acme" {
|
||||
t.Errorf("team 1 sees %q", got)
|
||||
}
|
||||
b.GetJSON("company", &got)
|
||||
if got != "Bolt" {
|
||||
t.Errorf("team 2 sees %q", got)
|
||||
}
|
||||
var n int
|
||||
d.QueryRow(`SELECT count(*) FROM settings WHERE key = 'company'`).Scan(&n)
|
||||
if n != 0 {
|
||||
t.Error("a team's setting in the main schema")
|
||||
}
|
||||
// The shared tables: only in the main schema, reached from a team's.
|
||||
for _, tbl := range PlatformTables {
|
||||
var inTeam bool
|
||||
d.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, teams.Schema(1)+"."+tbl).Scan(&inTeam)
|
||||
if inTeam {
|
||||
t.Errorf("%s is in the team's schema", tbl)
|
||||
}
|
||||
}
|
||||
if _, err := d.Exec(`INSERT INTO teams (name, created_at) VALUES ('Acme', 'now')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.QueryRow(`SELECT count(*) FROM teams`).Scan(&n); err != nil || n != 1 {
|
||||
t.Errorf("the shared teams table from a team: %d %v", n, err)
|
||||
}
|
||||
// Creating again only migrates; dropping removes it all.
|
||||
if err := teams.Create(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := teams.Drop(2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := teams.Open(2); err == nil {
|
||||
t.Error("a dropped team opens")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user