Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,24 @@ jobs:
go:
name: Build, vet, test, staticcheck
runs-on: ubuntu-latest
# Throwaway PostgreSQL for the store tests; they skip without
# OPENMOS_TEST_DATABASE_URL locally, but must run here.
services:
postgres:
image: postgres:17
env:
POSTGRES_USER: openmos
POSTGRES_PASSWORD: openmos
POSTGRES_DB: openmos_test
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U openmos -d openmos_test"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
OPENMOS_TEST_DATABASE_URL: postgres://openmos:openmos@localhost:5432/openmos_test?sslmode=disable
steps:
- uses: actions/checkout@v5

Expand Down
24 changes: 24 additions & 0 deletions doc/developer-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ OpenMOS follows a **Clean Layered Architecture** with clear separation of concer
| **Server** | `internal/server/` | TCP connections, client management, heartbeat monitoring |
| **Service** | `internal/service/` | Business logic, MOS operations, event publishing |
| **Repository** | `internal/repository/` | Data access abstraction, CRUD operations |
| **Store** | `internal/store/postgres/` | PostgreSQL schema migrations (pool and repositories to follow) |
| **Model** | `internal/model/` | Domain entities and value objects |
| **XML** | `internal/xml/` | Message parsing and serialization |
| **Events** | `internal/events/` | Pub-sub event bus for real-time notifications |
Expand Down Expand Up @@ -85,6 +86,10 @@ OpenMOS/
│ │ │ ├── memory/ # In-memory reference implementation
│ │ │ └── repotest/ # Contract suite for every implementation
│ │ │
│ │ ├── store/postgres/
│ │ │ ├── migrate.go # Goose migrations (embedded SQL)
│ │ │ └── migrations/ # Schema migrations (00001_init.sql, ...)
│ │ │
│ │ ├── server/
│ │ │ ├── server.go # TCPServer main logic
│ │ │ ├── client.go # ClientConnection management
Expand Down Expand Up @@ -313,6 +318,25 @@ sentry:
call `repotest.Run` from its tests (see `repository/memory`)
- Use interfaces to enable mocking
- Test XML parsing with example messages from `/res/`
- PostgreSQL tests (`internal/store/postgres`) need a throwaway database in
`OPENMOS_TEST_DATABASE_URL`; without it they skip locally (CI provides one).
They drop and recreate the `openmos` schema, so never point it at real data:

```bash
docker run -d --name openmos-pg -p 127.0.0.1:5432:5432 \
-e POSTGRES_USER=openmos -e POSTGRES_PASSWORD=openmos -e POSTGRES_DB=openmos_test postgres:17
export OPENMOS_TEST_DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos_test?sslmode=disable'
go test ./internal/store/...
```

### Schema migrations
- Migrations are SQL files in `internal/store/postgres/migrations`, embedded
in the binary and applied with goose (`postgres.Migrate`). Tables and the
goose version table live in the `openmos` schema.
- Never edit a migration that has been applied anywhere; add a new one.
- Migrations run as the schema owner (`openmos_migrate` on Aiven) over a
direct connection, not a PgBouncer pool. Do not add GRANTs: the runtime
role `openmos_app` gets privileges through `ALTER DEFAULT PRIVILEGES`.

### Contributing
1. Create a feature branch from main
Expand Down
15 changes: 12 additions & 3 deletions src/go.mod
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
module airshift/openmos

go 1.25.0
go 1.26.0

require (
github.com/getsentry/sentry-go v0.50.0
github.com/jackc/pgx/v5 v5.12.0
github.com/pressly/goose/v3 v3.29.0
go.yaml.in/yaml/v3 v3.0.6
)

require (
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
)
61 changes: 49 additions & 12 deletions src/go.sum
Original file line number Diff line number Diff line change
@@ -1,26 +1,63 @@
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.12.0 h1:hWwax8YiGT0YiN50U1oIDn5kgR7KC2tG3rmavwpPkxY=
github.com/jackc/pgx/v5 v5.12.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.29.0 h1:dtEnBCT7CqkHIUCdgrXsrmeisaN8gFkRU4Y5OEwif4o=
github.com/pressly/goose/v3 v3.29.0/go.mod h1:plA4aP4+u+Q3FMTgbFbhF8TuAWpAdfWpoFGkJsIFWh0=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.78.0 h1:Lpm+e9K6ruVYEGwWfuBO1xXtYEaXDouFOG1SuWjFDP4=
modernc.org/libc v1.78.0/go.mod h1:wvxR55nOF2/66NkJoNV7/coXBTCvT3HR22rcqW6lOuA=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw=
modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0=
119 changes: 119 additions & 0 deletions src/internal/store/postgres/migrate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// 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

import (
"context"
"database/sql"
"embed"
"fmt"
"io/fs"

"github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/lock"

// Registers the "pgx" database/sql driver that goose runs on.
_ "github.com/jackc/pgx/v5/stdlib"
)

// Schema is the PostgreSQL schema that holds all OpenMOS tables, including
// the goose version table.
const Schema = "openmos"

//go:embed migrations/*.sql
var migrationFiles embed.FS

// Open opens a database/sql handle on the pgx driver for running
// migrations. Use a direct connection, not a PgBouncer transaction pool:
// goose holds a session-level advisory lock while it migrates.
func Open(databaseURL string) (*sql.DB, error) {
db, err := sql.Open("pgx", databaseURL)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
return db, nil
}

// Migrate applies all pending migrations and returns the versions applied.
// It runs as the schema owner (openmos_migrate on Aiven). If the schema does
// not exist yet, as in a fresh local database, it is created first.
func Migrate(ctx context.Context, db *sql.DB) ([]int64, error) {
if err := ensureSchema(ctx, db); err != nil {
return nil, err
}
p, err := newProvider(db)
if err != nil {
return nil, err
}
results, err := p.Up(ctx)
if err != nil {
return nil, fmt.Errorf("migrate up: %w", err)
}
applied := make([]int64, len(results))
for i, r := range results {
applied[i] = r.Source.Version
}
return applied, nil
}

// MigrateDownTo rolls back migrations until version is the latest applied;
// version 0 rolls back everything. It is for tests and manual rollback.
func MigrateDownTo(ctx context.Context, db *sql.DB, version int64) error {
p, err := newProvider(db)
if err != nil {
return err
}
if _, err := p.DownTo(ctx, version); err != nil {
return fmt.Errorf("migrate down to %d: %w", version, err)
}
return nil
}

// Version returns the latest applied migration version, 0 if none.
func Version(ctx context.Context, db *sql.DB) (int64, error) {
p, err := newProvider(db)
if err != nil {
return 0, err
}
return p.GetDBVersion(ctx)
}

func newProvider(db *sql.DB) (*goose.Provider, error) {
fsys, err := fs.Sub(migrationFiles, "migrations")
if err != nil {
return nil, err
}
// The advisory lock keeps two deploys from migrating at the same time.
locker, err := lock.NewPostgresSessionLocker()
if err != nil {
return nil, err
}
p, err := goose.NewProvider(goose.DialectPostgres, db, fsys,
goose.WithTableName(Schema+".goose_db_version"),
goose.WithSessionLocker(locker),
goose.WithDisableGlobalRegistry(true),
)
if err != nil {
return nil, fmt.Errorf("create migration provider: %w", err)
}
return p, nil
}

// ensureSchema creates the schema if it is missing. On Aiven it already
// exists, owned by openmos_migrate, so no CREATE privilege on the database
// is needed there.
func ensureSchema(ctx context.Context, db *sql.DB) error {
var exists bool
err := db.QueryRowContext(ctx,
"SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = $1)", Schema).Scan(&exists)
if err != nil {
return fmt.Errorf("check schema %s: %w", Schema, err)
}
if exists {
return nil
}
if _, err := db.ExecContext(ctx, "CREATE SCHEMA "+Schema); err != nil {
return fmt.Errorf("create schema %s: %w", Schema, err)
}
return nil
}
79 changes: 79 additions & 0 deletions src/internal/store/postgres/migrate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package postgres

import (
"slices"
"testing"
)

// tables are the OpenMOS tables, sorted, without goose's version table.
var tables = []string{"items", "mos_objects", "running_orders", "stories"}

func TestMigrateUpDownUp(t *testing.T) {
db := testDB(t)
ctx := t.Context()

listTables := func() []string {
t.Helper()
rows, err := db.QueryContext(ctx, `SELECT tablename FROM pg_tables
WHERE schemaname = $1 AND tablename <> 'goose_db_version' ORDER BY tablename`, Schema)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
var names []string
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
t.Fatal(err)
}
names = append(names, n)
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
return names
}

// Up on an empty database creates the schema and every table
applied, err := Migrate(ctx, db)
if err != nil {
t.Fatalf("Migrate: %v", err)
}
if !slices.Equal(applied, []int64{1}) {
t.Errorf("applied = %v, want [1]", applied)
}
if got := listTables(); !slices.Equal(got, tables) {
t.Errorf("tables after up = %v, want %v", got, tables)
}

// Up again is a no-op
applied, err = Migrate(ctx, db)
if err != nil {
t.Fatalf("second Migrate: %v", err)
}
if len(applied) != 0 {
t.Errorf("second Migrate applied %v, want nothing", applied)
}

// Down removes every table
if err := MigrateDownTo(ctx, db, 0); err != nil {
t.Fatalf("MigrateDownTo(0): %v", err)
}
if got := listTables(); len(got) != 0 {
t.Errorf("tables after down = %v, want none", got)
}
if v, err := Version(ctx, db); err != nil || v != 0 {
t.Errorf("Version after down = %d, %v; want 0", v, err)
}

// And up works again after a full rollback
if _, err := Migrate(ctx, db); err != nil {
t.Fatalf("Migrate after down: %v", err)
}
if got := listTables(); !slices.Equal(got, tables) {
t.Errorf("tables after re-up = %v, want %v", got, tables)
}
if v, err := Version(ctx, db); err != nil || v != 1 {
t.Errorf("Version = %d, %v; want 1", v, err)
}
}
Loading
Loading