Keep personal notes private by default and require review before publishing shared notes. Restore backups and replay forgotten notes in one transaction, and retain the installed release when an unattended rollback could bring back forgotten notes.
130 lines
4.5 KiB
Go
130 lines
4.5 KiB
Go
// Package pg opens Archie's Postgres connections and applies its one ordered
|
|
// migration series.
|
|
package pg
|
|
|
|
import (
|
|
"context"
|
|
"embed"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"log/slog"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
// Registers the "pgx" database/sql driver that sqlx and goose use.
|
|
_ "github.com/jackc/pgx/v5/stdlib"
|
|
"github.com/jmoiron/sqlx"
|
|
"github.com/pressly/goose/v3"
|
|
"github.com/pressly/goose/v3/lock"
|
|
)
|
|
|
|
//go:embed migrations
|
|
var migrationFiles embed.FS
|
|
|
|
// Open connects with the runtime URL and checks the connection.
|
|
func Open(ctx context.Context, url string) (*sqlx.DB, error) {
|
|
db, err := sqlx.Open("pgx", url)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open database: %w", err)
|
|
}
|
|
if err := db.PingContext(ctx); err != nil {
|
|
_ = db.Close()
|
|
return nil, fmt.Errorf("reach database: %w", err)
|
|
}
|
|
return db, nil
|
|
}
|
|
|
|
// Migrate applies every pending migration as the owner, under a session
|
|
// advisory lock, so two instances starting together never race, then grants
|
|
// the runtime role DML on each module schema. A failed migration returns an
|
|
// error and the boot stops.
|
|
func Migrate(ctx context.Context, log *slog.Logger, ownerURL, runtimeURL string, schemas []string) error {
|
|
db, err := Open(ctx, ownerURL)
|
|
if err != nil {
|
|
return fmt.Errorf("owner connection: %w", err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
|
|
files, err := fs.Sub(migrationFiles, "migrations")
|
|
if err != nil {
|
|
return fmt.Errorf("migration files: %w", err)
|
|
}
|
|
locker, err := lock.NewPostgresSessionLocker()
|
|
if err != nil {
|
|
return fmt.Errorf("migration lock: %w", err)
|
|
}
|
|
provider, err := goose.NewProvider(goose.DialectPostgres, db.DB, files, goose.WithSessionLocker(locker))
|
|
if err != nil {
|
|
return fmt.Errorf("migration provider: %w", err)
|
|
}
|
|
results, err := provider.Up(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("apply migrations: %w", err)
|
|
}
|
|
for _, r := range results {
|
|
log.InfoContext(ctx, "migration applied", "migration", r.Source.Version, "file", r.Source.Path, "took", r.Duration)
|
|
}
|
|
return grantRuntime(ctx, db, runtimeURL, schemas)
|
|
}
|
|
|
|
// grantRuntime gives the runtime role USAGE and DML on each schema, never DDL.
|
|
func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas []string) error {
|
|
cfg, err := pgx.ParseConfig(runtimeURL)
|
|
if err != nil {
|
|
return fmt.Errorf("parse runtime URL: %w", err)
|
|
}
|
|
role := pgx.Identifier{cfg.User}.Sanitize()
|
|
for _, schema := range schemas {
|
|
name := pgx.Identifier{schema}.Sanitize()
|
|
for _, stmt := range []string{
|
|
"GRANT USAGE ON SCHEMA " + name + " TO " + role,
|
|
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA " + name + " TO " + role,
|
|
// A table keyed by a serial draws from a sequence, which is its
|
|
// own grant: a module whose insert draws on one would fail DML it
|
|
// is otherwise allowed.
|
|
"GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA " + name + " TO " + role,
|
|
} {
|
|
if _, err := db.ExecContext(ctx, stmt); err != nil {
|
|
return fmt.Errorf("grant runtime role on %s: %w", schema, err)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ServeLockKey is the advisory-lock key the serving processes hold in its shared
|
|
// form and a restore takes exclusively: several processes may serve at once, and
|
|
// none may serve while a restore runs. The other archie binaries lock the same
|
|
// key through internal/infrastructure/postgres, so there is one name for it.
|
|
func ServeLockKey(name string) string { return "archie." + name + ".owner" }
|
|
|
|
// ServeLockName is the one name every serving process claims and every restore
|
|
// takes exclusively. A serving process and a restore that named different locks
|
|
// would exclude nothing.
|
|
const ServeLockName = "serve"
|
|
|
|
// ClaimServe holds the serve lock shared for as long as the process serves. It
|
|
// fails when a restore holds the lock exclusively, so a process never starts on a
|
|
// database another process is restoring.
|
|
func ClaimServe(ctx context.Context, db *sqlx.DB, name string) (release func(), err error) {
|
|
conn, err := db.Conn(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("claim the serve lock: %w", err)
|
|
}
|
|
var taken bool
|
|
if err := conn.QueryRowContext(ctx,
|
|
"SELECT pg_try_advisory_lock_shared(hashtextextended($1, 0))", ServeLockKey(name)).Scan(&taken); err != nil {
|
|
_ = conn.Close()
|
|
return nil, fmt.Errorf("claim the serve lock: %w", err)
|
|
}
|
|
if !taken {
|
|
_ = conn.Close()
|
|
return nil, errors.New("a restore holds this database")
|
|
}
|
|
return func() {
|
|
_, _ = conn.ExecContext(context.WithoutCancel(ctx),
|
|
"SELECT pg_advisory_unlock_shared(hashtextextended($1, 0))", ServeLockKey(name))
|
|
_ = conn.Close()
|
|
}, nil
|
|
}
|