From b9476d55a5878029ede5d654eff26e5d6efa7615 Mon Sep 17 00:00:00 2001 From: Timo Ruohomaki Date: Mon, 9 Nov 2026 20:05:39 +0200 Subject: [PATCH] MOS-16: Run the server on PostgreSQL, add --migrate flags - main wires postgres.New(pool) in place of the in-memory store, which is now used only in tests. PostgreSQL is required: without DATABASE_URL, postgres.url or PG* variables the server exits. - --migrate applies pending migrations before starting; --migrate-only applies them and exits. Migrations use MIGRATE_DATABASE_URL (postgres.migrateurl) when set, with the same verify-full rule. - A plain start checks the schema version and refuses an outdated one; a newer schema only logs a warning. - postgres.MigrateWith and postgres.CheckSchema with tests against the test database (fresh, migrated, rolled back, newer, TLS rule, wrong password with SQLSTATE 28P01). - Docs: README quick start and requirements, developer reference flags, roadmap and migration plan. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 +++- doc/database-migration.md | 11 +- doc/developer-reference.md | 30 +++-- doc/roadmap.md | 3 +- src/database.go | 93 ++++++++++++---- src/internal/config/config.go | 6 +- src/internal/config/env.go | 3 + src/internal/config/load_test.go | 2 +- src/internal/config/postgres_test.go | 14 ++- src/internal/repository/memory/memory.go | 3 +- src/internal/store/postgres/migrate.go | 4 +- src/internal/store/postgres/startup.go | 72 ++++++++++++ src/internal/store/postgres/startup_test.go | 115 ++++++++++++++++++++ src/main.go | 17 ++- src/wiring.go | 9 -- 15 files changed, 341 insertions(+), 63 deletions(-) create mode 100644 src/internal/store/postgres/startup.go create mode 100644 src/internal/store/postgres/startup_test.go diff --git a/README.md b/README.md index 2050741..4cb4b4e 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,11 @@ The project will aim at compliance with Profile 7. > [!NOTE] > The MOS protocol specification requires TCP socket connections (default port 10540). At initial stages, message attributes differ from the protocol specification due to practical reasons. -Implementation status (2026-11-08): +Implementation status (2026-11-09): * [x] Core server skeleton and TCP socket server * [x] Sentry observability * [x] Internal event bus for client notifications -* [ ] PostgreSQL data repository (in progress; runs on in-memory storage until then, see [migration plan](doc/database-migration.md)) +* [x] PostgreSQL data repository (see [migration plan](doc/database-migration.md)) * [ ] Profile 0 - Basic Communication (partial) * [ ] Profile 1 - Basic Object Based Workflow * [ ] Profile 2 - Basic Running Order / Content List Workflow (partial) @@ -28,7 +28,7 @@ The [roadmap](doc/roadmap.md) shows how ready each profile is, the milestones th OpenMOS implements the MOS protocol using: - **TCP Socket Server**: Maintains persistent connections with MOS clients (NCS systems) -- **PostgreSQL**: Stores running orders, stories, items, and MOS objects (in progress; until it lands the server keeps data in memory only, see [database-migration.md](doc/database-migration.md)) +- **PostgreSQL**: Stores running orders, stories, items, and MOS objects; each MOS message is applied in one transaction (see [database-migration.md](doc/database-migration.md)) - **Sentry**: Provides error tracking and performance monitoring The server handles multiple concurrent client connections, processes MOS XML messages, and manages the lifecycle of running orders and their associated content. @@ -108,10 +108,22 @@ cd src go build -o openmos ``` +The server needs PostgreSQL. For local development: + +```bash +docker compose up -d # from the repository root +export APP_ENV=development DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos?sslmode=disable' +./openmos --migrate # apply pending schema migrations, then start +``` + +`--migrate-only` applies the migrations and exits, for deployment jobs. Without +either flag the server checks the schema and refuses to start if migrations +are pending. + ## Requirements -- Go 1.25 or later -- PostgreSQL 17, optional until the PostgreSQL store is wired in (MOS-16). For local development, `docker compose up -d` starts one (see `docker-compose.yml`) +- Go 1.26 or later +- PostgreSQL 17. For local development, `docker compose up -d` starts one (see `docker-compose.yml`) - Network access on port 10540 (default MOS port) ## License diff --git a/doc/database-migration.md b/doc/database-migration.md index 2394e82..c01341d 100644 --- a/doc/database-migration.md +++ b/doc/database-migration.md @@ -2,9 +2,9 @@ OpenMOS stores its data in PostgreSQL only. The original MongoDB store was removed outright (MOS-34) rather than kept alongside or behind a switch. -The PostgreSQL repositories exist (`internal/store/postgres`, MOS-14), but -until the server is switched over (MOS-16) it runs on the in-memory -reference store (`internal/repository/memory`), so data is not persisted. +The server runs on the PostgreSQL store (`internal/store/postgres`) since +MOS-16. The in-memory store (`internal/repository/memory`) remains as the +reference implementation for tests only. ## Why @@ -58,7 +58,9 @@ Tables: `running_orders`, `stories`, `items`, `mos_objects`. - Configuration: the old `mongo` block is gone; a new `postgres` block, with `DATABASE_URL` or the standard `PG*` environment variables. - Startup can apply migrations automatically (`--migrate`) or only migrate and - exit (`--migrate-only`) for deployment jobs. + exit (`--migrate-only`) for deployment jobs. Migrations use + `MIGRATE_DATABASE_URL` when set, so they can run as the schema owner over a + direct connection. A plain start refuses an outdated schema. ## Steps @@ -68,6 +70,7 @@ Tables: `running_orders`, `stories`, `items`, `mos_objects`. 3. Add the schema migration and the PostgreSQL repositories, passing that suite (MOS-12 to MOS-14). 4. Add transactions and switch the server to PostgreSQL (MOS-15, MOS-16). +5. Provision Aiven and run the first production migration (MOS-31).
diff --git a/doc/developer-reference.md b/doc/developer-reference.md index d2336d8..7e3009a 100644 --- a/doc/developer-reference.md +++ b/doc/developer-reference.md @@ -11,7 +11,7 @@ OpenMOS is an implementation of the Media Object Server (MOS) Protocol 4.0 using | Component | Technology | Version | |-----------|------------|---------| | Language | Go | 1.25+ | -| Database | PostgreSQL (in progress; in-memory until then) | 17 | +| Database | PostgreSQL | 17 | | Observability | Sentry | v0.50 | | Communication | TCP Sockets | Port 10540 | | Configuration | YAML | go.yaml.in/yaml/v3 | @@ -42,7 +42,7 @@ OpenMOS follows a **Clean Layered Architecture** with clear separation of concer │ ┌─────────────────────────▼───────────────────────────────────┐ │ Database Layer │ -│ (PostgreSQL; in-memory store until MOS-16) │ +│ (PostgreSQL) │ └─────────────────────────────────────────────────────────────┘ ``` @@ -84,7 +84,7 @@ OpenMOS/ │ │ │ ├── repository.go # Interface definitions │ │ │ ├── errors.go # Shared errors (ErrNotFound, ...) │ │ │ ├── order.go # ID checks and shared ordering rules -│ │ │ ├── memory/ # In-memory reference implementation +│ │ │ ├── memory/ # In-memory reference implementation (tests only) │ │ │ └── repotest/ # Contract suite for every implementation │ │ │ │ │ ├── store/postgres/ @@ -165,7 +165,7 @@ RunningOrder (1) ──► (N) Story ──► (N) Item ──► MOSObject 2. **Heartbeat Monitoring**: Client heartbeat is tracked; timeout triggers disconnection 3. **Message Reception**: XML messages are parsed and validated 4. **Service Processing**: Business logic handles operations (create/update/replace) -5. **Storage**: Changes are stored through the repository interfaces (in memory until the server switches to PostgreSQL in MOS-16) +5. **Storage**: Each change is stored in PostgreSQL in one transaction, through the repository interfaces 6. **Event Publishing**: Service publishes events to the event bus 7. **Client Notification**: Connected clients receive real-time updates via subscriptions @@ -174,7 +174,7 @@ RunningOrder (1) ──► (N) Story ──► (N) Item ──► MOSObject ### Core Infrastructure - [x] TCP Socket Server with multi-client support - [x] Repository pattern with a contract test suite and an in-memory store -- [ ] PostgreSQL persistence (M1, see database-migration.md) +- [x] PostgreSQL persistence (M1, see database-migration.md) - [x] YAML configuration with environment variable overrides - [x] Multi-level logging with Sentry integration - [x] Client heartbeat monitoring with timeout detection @@ -288,6 +288,7 @@ server: postgres: url: "" # Connection URL; a secret, so use DATABASE_URL instead + migrateurl: "" # Optional URL for --migrate; a secret, use MIGRATE_DATABASE_URL maxconns: 10 # Pool size (env POSTGRES_MAX_CONNS) minconns: 1 # Connections kept open (env POSTGRES_MIN_CONNS) connecttimeout: 5s # Connect and startup ping timeout (POSTGRES_CONNECT_TIMEOUT) @@ -314,15 +315,28 @@ sentry: - `DATABASE_URL` (the backend01 `.env` name) overrides `postgres.url`. With neither set, the standard `PG*` variables (`PGHOST`, `PGUSER`, ...) are used; - with nothing set, the server runs without a database. -- When a database is configured, the server connects and pings it at startup - and exits if that fails. Logs and errors name host, database and user, never + with nothing set, the server refuses to start: PostgreSQL is required. +- The server connects and pings the database at startup, checks that the + schema is migrated, and exits if either fails. Logs and errors name host, database and user, never the password. - Outside `app.environment: development`, connections must use `sslmode=verify-full` with `sslrootcert` pointing at the server CA (on the server, `/secrets/aiven-ca.pem`). Connect to Aiven directly, not through its PgBouncer pool. +### Startup flags + +| Flag | Effect | +| --- | --- | +| `--migrate` | Apply pending schema migrations, then start the server | +| `--migrate-only` | Apply pending schema migrations and exit (deployment jobs) | + +Migrations connect with `MIGRATE_DATABASE_URL` (`postgres.migrateurl`) if set, +otherwise with `DATABASE_URL`. On Aiven, set it to the `openmos_migrate` role +over a direct connection, and `DATABASE_URL` to `openmos_app`. The same +verify-full rule applies. Without either flag the server refuses to start on +an outdated schema; a schema newer than the build only logs a warning. + ## Development Guidelines ### Code Organization diff --git a/doc/roadmap.md b/doc/roadmap.md index 6434ef4..0578ccd 100644 --- a/doc/roadmap.md +++ b/doc/roadmap.md @@ -24,7 +24,8 @@ Status as of 2026-11-08 (commit `3a73754`). Milestones run in order; each one builds on the previous. 1. **M1 Foundations and PostgreSQL.** Build passes for the whole module, CI runs - build, vet and tests, and storage moves to PostgreSQL. + build, vet and tests, and storage moves to PostgreSQL. The server runs on + PostgreSQL since MOS-16; Aiven provisioning remains (MOS-31). See [database-migration.md](./database-migration.md). 2. **M2 Wire protocol and Profile 0.** Messages use the `` envelope (`mosID`, `ncsID`, `messageID`), UTF-16BE encoding, robust stream framing, diff --git a/src/database.go b/src/database.go index dd3fbcb..82f7c2f 100644 --- a/src/database.go +++ b/src/database.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "airshift/openmos/internal/config" "airshift/openmos/internal/store/postgres" @@ -10,35 +11,81 @@ import ( "github.com/jackc/pgx/v5/pgxpool" ) -// connectDatabase opens the PostgreSQL pool if a database is configured -// (DATABASE_URL, postgres.url or the PG* variables) and exits the process if -// it cannot connect. It returns nil when no database is configured. -// -// The repositories still use the in-memory store until MOS-16. The pool is -// opened now so that bad settings or credentials fail at startup. -func connectDatabase(ctx context.Context, cfg *config.Config, log *logger.SentryLogger) *pgxpool.Pool { - if !postgres.Configured(cfg.Postgres.URL) { - log.Info("No PostgreSQL configured (DATABASE_URL or PG* variables); skipping database connection") - return nil - } - - pool, err := postgres.NewPool(ctx, postgres.PoolOptions{ - URL: cfg.Postgres.URL, +// poolOptions returns the connection settings for url. Only local +// development may connect without sslmode=verify-full. +func poolOptions(cfg *config.Config, url string) postgres.PoolOptions { + return postgres.PoolOptions{ + URL: url, MaxConns: cfg.Postgres.MaxConns, MinConns: cfg.Postgres.MinConns, ConnectTimeout: cfg.Postgres.ConnectTimeout, HealthCheckPeriod: cfg.Postgres.HealthCheckPeriod, - // Only local development may connect without verify-full - AllowInsecureTLS: cfg.App.Environment == "development", - }) + AllowInsecureTLS: cfg.App.Environment == "development", + } +} + +// migrationURL is the connection for --migrate: MIGRATE_DATABASE_URL if +// set (the schema owner over a direct connection, openmos_migrate on +// Aiven), otherwise the application's own. +func migrationURL(cfg *config.Config) string { + if cfg.Postgres.MigrateURL != "" { + return cfg.Postgres.MigrateURL + } + return cfg.Postgres.URL +} + +// fatalDatabase reports a database error and exits. Errors from the +// postgres package name host, database and user, never the password. +func fatalDatabase(log *logger.SentryLogger, action string, err error, format string) { + log.CaptureException(err, map[string]string{ + "component": "database", + "action": action, + }, nil) + log.Fatalf(format, err) +} + +// migrateDatabase applies pending schema migrations, or exits the process +// if it cannot. +func migrateDatabase(ctx context.Context, cfg *config.Config, log *logger.SentryLogger) { + url := migrationURL(cfg) + if !postgres.Configured(url) { + log.Fatalf("Cannot migrate: no PostgreSQL configured (set MIGRATE_DATABASE_URL, DATABASE_URL or the PG* variables)") + } + applied, err := postgres.MigrateWith(ctx, poolOptions(cfg, url)) + if err != nil { + fatalDatabase(log, "migrate", err, "Failed to migrate the database schema: %v") + } + if len(applied) == 0 { + log.Info("Database schema is up to date; no migrations applied") + return + } + log.Infof("Applied schema migrations %v", applied) +} + +// openDatabase connects to PostgreSQL and checks that the schema is +// migrated, or exits the process. The server cannot run without it. +func openDatabase(ctx context.Context, cfg *config.Config, log *logger.SentryLogger) *pgxpool.Pool { + if !postgres.Configured(cfg.Postgres.URL) { + log.Fatalf("No PostgreSQL configured: set DATABASE_URL (or postgres.url, or the PG* variables)") + } + pool, err := postgres.NewPool(ctx, poolOptions(cfg, cfg.Postgres.URL)) if err != nil { - // The error names host, database and user, never the password - log.CaptureException(err, map[string]string{ - "component": "database", - "action": "connect", - }, nil) - log.Fatalf("Failed to connect to PostgreSQL: %v", err) + fatalDatabase(log, "connect", err, "Failed to connect to PostgreSQL: %v") } log.Infof("Connected to PostgreSQL %s", postgres.Describe(pool.Config())) + + current, latest, err := postgres.CheckSchema(ctx, pool) + switch { + case errors.Is(err, postgres.ErrSchemaOutdated): + pool.Close() + log.Fatalf("%v; run with --migrate, or --migrate-only before starting", err) + case err != nil: + pool.Close() + fatalDatabase(log, "check_schema", err, "Failed to check the database schema: %v") + case current > latest: + log.Warningf("Database schema version %d is newer than this build (%d); a newer release migrated it", current, latest) + default: + log.Infof("Database schema at version %d", current) + } return pool } diff --git a/src/internal/config/config.go b/src/internal/config/config.go index 2e8bb49..a56dc0a 100644 --- a/src/internal/config/config.go +++ b/src/internal/config/config.go @@ -25,9 +25,13 @@ type Config struct { // PostgreSQL configuration. URL is a secret (it holds the password): set // it with DATABASE_URL or in a local, gitignored config.yaml. Without a - // URL, the standard PG* environment variables are used. + // URL, the standard PG* environment variables are used. MigrateURL, also + // a secret (MIGRATE_DATABASE_URL), is used for --migrate when set, so + // migrations can run as the schema owner over a direct connection; + // otherwise URL is used. Postgres struct { URL string + MigrateURL string MaxConns int32 MinConns int32 ConnectTimeout time.Duration diff --git a/src/internal/config/env.go b/src/internal/config/env.go index 8e03fcb..ff5b4ec 100644 --- a/src/internal/config/env.go +++ b/src/internal/config/env.go @@ -37,6 +37,9 @@ func applyEnvOverrides(config *Config, yamlLoaded bool) { if envVal := getEnv("DATABASE_URL", ""); envVal != "" || !yamlLoaded { config.Postgres.URL = getEnv("DATABASE_URL", config.Postgres.URL) } + if envVal := getEnv("MIGRATE_DATABASE_URL", ""); envVal != "" || !yamlLoaded { + config.Postgres.MigrateURL = getEnv("MIGRATE_DATABASE_URL", config.Postgres.MigrateURL) + } if envVal := getEnv("POSTGRES_MAX_CONNS", ""); envVal != "" || !yamlLoaded { config.Postgres.MaxConns = getEnvAsInt32("POSTGRES_MAX_CONNS", getDefaultInt32(config.Postgres.MaxConns, 10)) } diff --git a/src/internal/config/load_test.go b/src/internal/config/load_test.go index b0d8a6f..af755de 100644 --- a/src/internal/config/load_test.go +++ b/src/internal/config/load_test.go @@ -11,7 +11,7 @@ var configEnvKeys = []string{ "CONFIG_FILE", "APP_NAME", "APP_VERSION", "APP_ENV", "SERVER_HOST", "SERVER_PORT", "SERVER_READ_TIMEOUT", "SERVER_WRITE_TIMEOUT", "SERVER_SHUTDOWN_TIMEOUT", - "DATABASE_URL", "POSTGRES_MAX_CONNS", "POSTGRES_MIN_CONNS", "POSTGRES_CONNECT_TIMEOUT", "POSTGRES_HEALTH_CHECK_PERIOD", + "DATABASE_URL", "MIGRATE_DATABASE_URL", "POSTGRES_MAX_CONNS", "POSTGRES_MIN_CONNS", "POSTGRES_CONNECT_TIMEOUT", "POSTGRES_HEALTH_CHECK_PERIOD", "PGHOST", "PGPORT", "PGDATABASE", "PGUSER", "PGPASSWORD", "PGSSLMODE", "PGSSLROOTCERT", "MOS_ID", "MOS_HEARTBEAT_INTERVAL", "MOS_CLIENT_TIMEOUT", "LOG_LEVEL", diff --git a/src/internal/config/postgres_test.go b/src/internal/config/postgres_test.go index 5721cd6..c81e7af 100644 --- a/src/internal/config/postgres_test.go +++ b/src/internal/config/postgres_test.go @@ -12,7 +12,7 @@ import ( func TestDatabaseURLOverridesYAML(t *testing.T) { dir := isolate(t) path := filepath.Join(dir, "config.yaml") - yamlDoc := "postgres:\n url: postgres://from-yaml/openmos\n maxconns: 4\n connecttimeout: 3s\n" + yamlDoc := "postgres:\n url: postgres://from-yaml/openmos\n migrateurl: postgres://migrate-yaml/openmos\n maxconns: 4\n connecttimeout: 3s\n" if err := os.WriteFile(path, []byte(yamlDoc), 0o600); err != nil { t.Fatal(err) } @@ -21,19 +21,23 @@ func TestDatabaseURLOverridesYAML(t *testing.T) { if err != nil { t.Fatalf("LoadConfig: %v", err) } - if cfg.Postgres.URL != "postgres://from-yaml/openmos" || cfg.Postgres.MaxConns != 4 || + if cfg.Postgres.URL != "postgres://from-yaml/openmos" || cfg.Postgres.MigrateURL != "postgres://migrate-yaml/openmos" || + cfg.Postgres.MaxConns != 4 || cfg.Postgres.ConnectTimeout != 3*time.Second { t.Errorf("YAML postgres block not loaded: %+v", cfg.Postgres) } t.Setenv("DATABASE_URL", "postgres://from-env/openmos") + t.Setenv("MIGRATE_DATABASE_URL", "postgres://migrate-env/openmos") t.Setenv("POSTGRES_MAX_CONNS", "7") cfg, err = LoadConfig() if err != nil { t.Fatalf("LoadConfig: %v", err) } - if cfg.Postgres.URL != "postgres://from-env/openmos" || cfg.Postgres.MaxConns != 7 { - t.Errorf("env did not override: URL %q, MaxConns %d", cfg.Postgres.URL, cfg.Postgres.MaxConns) + if cfg.Postgres.URL != "postgres://from-env/openmos" || cfg.Postgres.MigrateURL != "postgres://migrate-env/openmos" || + cfg.Postgres.MaxConns != 7 { + t.Errorf("env did not override: URL %q, MigrateURL %q, MaxConns %d", + cfg.Postgres.URL, cfg.Postgres.MigrateURL, cfg.Postgres.MaxConns) } } @@ -49,7 +53,7 @@ func TestGeneratedConfigHasNoDatabaseURL(t *testing.T) { if err != nil { t.Fatalf("LoadConfig: %v", err) } - if cfg.Postgres.URL != "" || cfg.Postgres.MaxConns != 10 { + if cfg.Postgres.URL != "" || cfg.Postgres.MigrateURL != "" || cfg.Postgres.MaxConns != 10 { t.Errorf("generated postgres block = %+v, want empty URL and defaults", cfg.Postgres) } } diff --git a/src/internal/repository/memory/memory.go b/src/internal/repository/memory/memory.go index 10c823c..10ce689 100644 --- a/src/internal/repository/memory/memory.go +++ b/src/internal/repository/memory/memory.go @@ -1,7 +1,8 @@ // Package memory is an in-memory implementation of repository.Repository. // // It is the reference implementation of the contract in package repotest and -// a fake for service tests. Nothing is persisted. +// a fake for service tests. Nothing is persisted, and the server does not +// use it: it runs on PostgreSQL (internal/store/postgres). package memory import ( diff --git a/src/internal/store/postgres/migrate.go b/src/internal/store/postgres/migrate.go index 1825ca8..5c40c3e 100644 --- a/src/internal/store/postgres/migrate.go +++ b/src/internal/store/postgres/migrate.go @@ -1,5 +1,5 @@ -// Package postgres is the PostgreSQL store: schema migrations now, and the -// connection pool and repositories as they are added (MOS-13, MOS-14). +// Package postgres is the PostgreSQL store OpenMOS runs on: the connection +// pool, schema migrations and the repositories. package postgres import ( diff --git a/src/internal/store/postgres/startup.go b/src/internal/store/postgres/startup.go new file mode 100644 index 0000000..630042d --- /dev/null +++ b/src/internal/store/postgres/startup.go @@ -0,0 +1,72 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "github.com/jackc/pgx/v5/pgxpool" + "github.com/jackc/pgx/v5/stdlib" +) + +// ErrSchemaOutdated means the database schema is older than this build +// needs: pending migrations must be applied first. +var ErrSchemaOutdated = errors.New("database schema is outdated") + +// MigrateWith connects with opts, applies all pending migrations and +// returns the versions applied. The connection gets the same checks as +// NewPool (verify-full outside development) and is closed afterwards. Use +// the schema owner over a direct connection (openmos_migrate on Aiven). +func MigrateWith(ctx context.Context, opts PoolOptions) ([]int64, error) { + cfg, err := ParsePoolConfig(opts) + if err != nil { + return nil, err + } + db := stdlib.OpenDB(*cfg.ConnConfig) + defer db.Close() + + pingCtx, cancel := context.WithTimeout(ctx, cfg.ConnConfig.ConnectTimeout) + defer cancel() + if err := db.PingContext(pingCtx); err != nil { + return nil, fmt.Errorf("connect to PostgreSQL %s for migrations: %w", Describe(cfg), err) + } + applied, err := Migrate(ctx, db) + if err != nil { + return nil, fmt.Errorf("migrate %s: %w", Describe(cfg), err) + } + return applied, nil +} + +// CheckSchema returns the schema version of the database behind pool and +// the latest version this build has migrations for. It returns +// ErrSchemaOutdated if migrations are pending, including on a database +// that was never migrated. A newer schema than the build knows, as after +// rolling back a deploy, is not an error. +func CheckSchema(ctx context.Context, pool *pgxpool.Pool) (current, latest int64, err error) { + db := stdlib.OpenDBFromPool(pool) + defer db.Close() + + var tableExists bool + err = db.QueryRowContext(ctx, "SELECT to_regclass($1) IS NOT NULL", Schema+".goose_db_version").Scan(&tableExists) + if err != nil { + return 0, 0, fmt.Errorf("check schema version: %w", err) + } + p, err := newProvider(db) + if err != nil { + return 0, 0, err + } + sources := p.ListSources() + if len(sources) > 0 { + latest = sources[len(sources)-1].Version + } + if tableExists { + if current, err = p.GetDBVersion(ctx); err != nil { + return 0, 0, fmt.Errorf("check schema version: %w", err) + } + } + if current < latest { + return current, latest, fmt.Errorf("schema at version %d, this build needs %d: %w", + current, latest, ErrSchemaOutdated) + } + return current, latest, nil +} diff --git a/src/internal/store/postgres/startup_test.go b/src/internal/store/postgres/startup_test.go new file mode 100644 index 0000000..8d4141e --- /dev/null +++ b/src/internal/store/postgres/startup_test.go @@ -0,0 +1,115 @@ +package postgres + +import ( + "errors" + "slices" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" +) + +// testPool returns a pool on the test database, closed at the end of the +// test. +func testPool(t *testing.T) *pgxpool.Pool { + t.Helper() + pool, err := pgxpool.New(t.Context(), testDatabaseURL(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + return pool +} + +func devOptions(t *testing.T) PoolOptions { + return PoolOptions{URL: testDatabaseURL(t), AllowInsecureTLS: true} +} + +func TestMigrateWith(t *testing.T) { + db := testDB(t) // empty database, no schema + ctx := t.Context() + + applied, err := MigrateWith(ctx, devOptions(t)) + if err != nil { + t.Fatalf("MigrateWith: %v", err) + } + if !slices.Contains(applied, 1) { + t.Errorf("first MigrateWith applied %v, want version 1 among them", applied) + } + if v, err := Version(ctx, db); err != nil || v != applied[len(applied)-1] { + t.Errorf("Version after MigrateWith = %d, %v; want %d", v, err, applied[len(applied)-1]) + } + + applied, err = MigrateWith(ctx, devOptions(t)) + if err != nil || len(applied) != 0 { + t.Errorf("second MigrateWith applied %v, %v; want nothing", applied, err) + } +} + +// The migration connection has the same TLS rule as the pool, and fails +// before connecting +func TestMigrateWithRequiresVerifyFull(t *testing.T) { + url := testDatabaseURL(t) + if !strings.Contains(url, "sslmode=disable") { + t.Skip("test database URL does not use sslmode=disable") + } + _, err := MigrateWith(t.Context(), PoolOptions{URL: url}) + if err == nil || !strings.Contains(err.Error(), "verify-full") { + t.Errorf("MigrateWith without verify-full: err = %v, want the verify-full rule", err) + } +} + +func TestMigrateWithBadPassword(t *testing.T) { + url := testDatabaseURL(t) + bad := strings.Replace(url, ":openmos@", ":wrong-secret@", 1) + if bad == url { + t.Skip("test database URL does not have the expected openmos password") + } + _, err := MigrateWith(t.Context(), PoolOptions{URL: bad, AllowInsecureTLS: true}) + var pe *pgconn.PgError + if !errors.As(err, &pe) || pe.Code != "28P01" { + t.Fatalf("MigrateWith with a wrong password: err = %v, want SQLSTATE 28P01", err) + } + if strings.Contains(err.Error(), "wrong-secret") { + t.Errorf("error reveals the password: %v", err) + } +} + +func TestCheckSchema(t *testing.T) { + db := testDB(t) + pool := testPool(t) + ctx := t.Context() + + // Never migrated: no schema at all + current, latest, err := CheckSchema(ctx, pool) + if !errors.Is(err, ErrSchemaOutdated) || current != 0 || latest < 1 { + t.Fatalf("CheckSchema on empty database = %d, %d, %v; want 0, >=1, %v", current, latest, err, ErrSchemaOutdated) + } + + if _, err := Migrate(ctx, db); err != nil { + t.Fatal(err) + } + current, latest, err = CheckSchema(ctx, pool) + if err != nil || current != latest { + t.Errorf("CheckSchema after Migrate = %d, %d, %v; want equal versions, nil", current, latest, err) + } + + // Rolled back: the version table exists but is behind + if err := MigrateDownTo(ctx, db, 0); err != nil { + t.Fatal(err) + } + if _, _, err := CheckSchema(ctx, pool); !errors.Is(err, ErrSchemaOutdated) { + t.Errorf("CheckSchema after rollback: err = %v, want %v", err, ErrSchemaOutdated) + } + + // A schema newer than the build is accepted + if _, err := Migrate(ctx, db); err != nil { + t.Fatal(err) + } + exec(t, db, "INSERT INTO openmos.goose_db_version (version_id, is_applied) VALUES (99999, true)") + current, latest, err = CheckSchema(ctx, pool) + if err != nil || current != 99999 || latest >= current { + t.Errorf("CheckSchema with newer schema = %d, %d, %v; want 99999, older, nil", current, latest, err) + } +} diff --git a/src/main.go b/src/main.go index 5db7093..071fddf 100644 --- a/src/main.go +++ b/src/main.go @@ -9,6 +9,7 @@ import ( "time" "airshift/openmos/internal/config" + "airshift/openmos/internal/store/postgres" "airshift/openmos/pkg/logger" "github.com/getsentry/sentry-go" @@ -18,6 +19,8 @@ func main() { // Define command-line flags generateConfig := flag.String("generate-config", "", "Generate a default configuration file at the specified path and exit") configPath := flag.String("config", "", "Path to the configuration file (default: search for config.yaml)") + migrate := flag.Bool("migrate", false, "Apply pending database schema migrations, then start the server") + migrateOnly := flag.Bool("migrate-only", false, "Apply pending database schema migrations and exit") // Parse flags flag.Parse() @@ -49,11 +52,19 @@ func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - if pool := connectDatabase(ctx, cfg, log); pool != nil { - defer pool.Close() + if *migrate || *migrateOnly { + migrateDatabase(ctx, cfg, log) + if *migrateOnly { + log.Info("Migrations done; exiting (--migrate-only)") + sentry.Flush(2 * time.Second) + return + } } - tcpServer := newTCPServer(cfg, newRepository(log), log) + pool := openDatabase(ctx, cfg, log) + defer pool.Close() + + tcpServer := newTCPServer(cfg, postgres.New(pool), log) // Handle signals for graceful shutdown sigCh := make(chan os.Signal, 1) diff --git a/src/wiring.go b/src/wiring.go index 8b93eb9..8c58f1b 100644 --- a/src/wiring.go +++ b/src/wiring.go @@ -7,7 +7,6 @@ import ( "airshift/openmos/internal/config" "airshift/openmos/internal/events" "airshift/openmos/internal/repository" - "airshift/openmos/internal/repository/memory" "airshift/openmos/internal/server" "airshift/openmos/internal/service" "airshift/openmos/pkg/logger" @@ -15,14 +14,6 @@ import ( "github.com/getsentry/sentry-go" ) -// newRepository returns the storage the server runs on. Until the PostgreSQL -// store lands (MOS-14, wired in MOS-16) this is the in-memory store, so all -// data is lost on restart. -func newRepository(log *logger.SentryLogger) repository.Repository { - log.Warning("Using in-memory storage: data is not persisted") - return memory.New() -} - // newTCPServer wires repositories, the event bus and the MOS service into a // TCP server, and exits the process if the server cannot be created. func newTCPServer(cfg *config.Config, repo repository.Repository, log *logger.SentryLogger) *server.TCPServer {