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
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ server:
readtimeout: 5s
writetimeout: 5s
shutdowntimeout: 30s
postgres: # url is a secret: prefer the DATABASE_URL env var
maxconns: 10
minconns: 1
connecttimeout: 5s
healthcheckperiod: 30s
mos:
id: mos01.station.com
heartbeatinterval: 30s
Expand Down Expand Up @@ -106,7 +111,7 @@ go build -o openmos
## Requirements

- Go 1.25 or later
- PostgreSQL 17 (once the PostgreSQL store lands; until then no database is needed)
- 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`)
- Network access on port 10540 (default MOS port)

## License
Expand Down
3 changes: 3 additions & 0 deletions dev/postgres-init/01-test-database.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- Runs once, when the volume is first created. The store tests drop and
-- recreate the openmos schema, so they get a database of their own.
CREATE DATABASE openmos_test;
26 changes: 23 additions & 3 deletions doc/developer-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +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) |
| **Store** | `internal/store/postgres/` | PostgreSQL connection pool and schema migrations (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 @@ -88,6 +88,7 @@ OpenMOS/
│ │ │
│ │ ├── store/postgres/
│ │ │ ├── migrate.go # Goose migrations (embedded SQL)
│ │ │ ├── pool.go # pgx connection pool, TLS rules
│ │ │ └── migrations/ # Schema migrations (00001_init.sql, ...)
│ │ │
│ │ ├── server/
Expand Down Expand Up @@ -282,6 +283,13 @@ server:
writetimeout: 5s # Write timeout duration
shutdowntimeout: 30s # Graceful shutdown timeout

postgres:
url: "" # Connection URL; a secret, so use DATABASE_URL instead
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)
healthcheckperiod: 30s # Idle connection health checks (POSTGRES_HEALTH_CHECK_PERIOD)

mos:
id: mos01.station.com # MOS server identifier
heartbeatinterval: 30s # Heartbeat interval
Expand All @@ -299,6 +307,19 @@ sentry:
tracessamplerate: 0.2 # Performance trace sampling rate
```

### Database connection

- `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
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.

## Development Guidelines

### Code Organization
Expand All @@ -323,8 +344,7 @@ sentry:
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
docker compose up -d # from the repository root; also creates openmos_test
export OPENMOS_TEST_DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos_test?sslmode=disable'
go test ./internal/store/...
```
Expand Down
28 changes: 28 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Local PostgreSQL for development and tests only. Production uses Aiven
# (verify-full TLS, separate roles); see doc/database-migration.md.
#
# docker compose up -d
# export DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos?sslmode=disable'
# export OPENMOS_TEST_DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos_test?sslmode=disable'
#
# sslmode=disable is accepted only with APP_ENV=development (the default).
services:
postgres:
image: postgres:17
environment:
POSTGRES_USER: openmos
POSTGRES_PASSWORD: openmos # local only, not a secret
POSTGRES_DB: openmos
ports:
- "127.0.0.1:5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
- ./dev/postgres-init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD", "pg_isready", "-U", "openmos", "-d", "openmos"]
interval: 5s
timeout: 5s
retries: 10

volumes:
pgdata:
44 changes: 44 additions & 0 deletions src/database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
"context"

"airshift/openmos/internal/config"
"airshift/openmos/internal/store/postgres"
"airshift/openmos/pkg/logger"

"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,
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",
})
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)
}
log.Infof("Connected to PostgreSQL %s", postgres.Describe(pool.Config()))
return pool
}
11 changes: 11 additions & 0 deletions src/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ type Config struct {
ShutdownTimeout time.Duration
}

// 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.
Postgres struct {
URL string
MaxConns int32
MinConns int32
ConnectTimeout time.Duration
HealthCheckPeriod time.Duration
}

// MOS configuration
MOS struct {
// MOS ID of this server, used in MOS messages
Expand Down
7 changes: 7 additions & 0 deletions src/internal/config/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ func GenerateDefaultConfig(filePath string) error {
config.Server.WriteTimeout = 5 * time.Second
config.Server.ShutdownTimeout = 30 * time.Second

// PostgreSQL config. The URL stays empty: it is a secret and belongs in
// DATABASE_URL, not in a generated file.
config.Postgres.MaxConns = 10
config.Postgres.MinConns = 1
config.Postgres.ConnectTimeout = 5 * time.Second
config.Postgres.HealthCheckPeriod = 30 * time.Second

// MOS config
config.MOS.ID = "OpenMOS_Server"
config.MOS.HeartbeatInterval = 30 * time.Second
Expand Down
17 changes: 17 additions & 0 deletions src/internal/config/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,23 @@ func applyEnvOverrides(config *Config, yamlLoaded bool) {
config.Server.ShutdownTimeout = getEnvAsDuration("SERVER_SHUTDOWN_TIMEOUT", getDefaultDuration(config.Server.ShutdownTimeout, 30*time.Second))
}

// PostgreSQL config. DATABASE_URL matches the backend01 .env convention.
if envVal := getEnv("DATABASE_URL", ""); envVal != "" || !yamlLoaded {
config.Postgres.URL = getEnv("DATABASE_URL", config.Postgres.URL)
}
if envVal := getEnv("POSTGRES_MAX_CONNS", ""); envVal != "" || !yamlLoaded {
config.Postgres.MaxConns = getEnvAsInt32("POSTGRES_MAX_CONNS", getDefaultInt32(config.Postgres.MaxConns, 10))
}
if envVal := getEnv("POSTGRES_MIN_CONNS", ""); envVal != "" || !yamlLoaded {
config.Postgres.MinConns = getEnvAsInt32("POSTGRES_MIN_CONNS", getDefaultInt32(config.Postgres.MinConns, 1))
}
if envVal := getEnv("POSTGRES_CONNECT_TIMEOUT", ""); envVal != "" || !yamlLoaded {
config.Postgres.ConnectTimeout = getEnvAsDuration("POSTGRES_CONNECT_TIMEOUT", getDefaultDuration(config.Postgres.ConnectTimeout, 5*time.Second))
}
if envVal := getEnv("POSTGRES_HEALTH_CHECK_PERIOD", ""); envVal != "" || !yamlLoaded {
config.Postgres.HealthCheckPeriod = getEnvAsDuration("POSTGRES_HEALTH_CHECK_PERIOD", getDefaultDuration(config.Postgres.HealthCheckPeriod, 30*time.Second))
}

// MOS config
if envVal := getEnv("MOS_ID", ""); envVal != "" || !yamlLoaded {
config.MOS.ID = getEnv("MOS_ID", getDefaultString(config.MOS.ID, "OpenMOS_Server"))
Expand Down
23 changes: 23 additions & 0 deletions src/internal/config/env_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ func getEnvAsInt(key string, defaultValue int) int {
return value
}

// getEnvAsInt32 parses with a 32-bit limit, so values that do not fit fall
// back to the default instead of being truncated by a conversion.
func getEnvAsInt32(key string, defaultValue int32) int32 {
valueStr := getEnv(key, "")
if valueStr == "" {
return defaultValue
}

value, err := strconv.ParseInt(valueStr, 10, 32)
if err != nil {
return defaultValue
}

return int32(value)
}

func getEnvAsDuration(key string, defaultValue time.Duration) time.Duration {
valueStr := getEnv(key, "")
if valueStr == "" {
Expand Down Expand Up @@ -85,6 +101,13 @@ func getDefaultInt(current, defaultValue int) int {
return current
}

func getDefaultInt32(current, defaultValue int32) int32 {
if current == 0 {
return defaultValue
}
return current
}

func getDefaultBool(current, defaultValue bool) bool {
// Zero value for bool is false, but can't determine if it's default without context
// We'll just use the provided default
Expand Down
4 changes: 4 additions & 0 deletions src/internal/config/load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ 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",
"PGHOST", "PGPORT", "PGDATABASE", "PGUSER", "PGPASSWORD", "PGSSLMODE", "PGSSLROOTCERT",
"MOS_ID", "MOS_HEARTBEAT_INTERVAL", "MOS_CLIENT_TIMEOUT",
"LOG_LEVEL",
"SENTRY_DSN", "SENTRY_ENV", "SENTRY_DEBUG", "SENTRY_ATTACH_STACKTRACE",
Expand Down Expand Up @@ -47,6 +49,8 @@ func TestLoadConfigDefaultsWithoutYAML(t *testing.T) {
want.Server.Host, want.Server.Port = "0.0.0.0", 10540
want.Server.ReadTimeout, want.Server.WriteTimeout = 5*time.Second, 5*time.Second
want.Server.ShutdownTimeout = 30 * time.Second
want.Postgres.MaxConns, want.Postgres.MinConns = 10, 1
want.Postgres.ConnectTimeout, want.Postgres.HealthCheckPeriod = 5*time.Second, 30*time.Second
want.MOS.ID = "OpenMOS_Server"
want.MOS.HeartbeatInterval, want.MOS.ClientTimeout = 30*time.Second, 2*time.Minute
want.Logging.Level = "info"
Expand Down
76 changes: 76 additions & 0 deletions src/internal/config/postgres_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package config

import (
"os"
"path/filepath"
"testing"
"time"
)

// DATABASE_URL (the backend01 .env name) overrides postgres.url in YAML,
// and the other postgres fields come from YAML.
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"
if err := os.WriteFile(path, []byte(yamlDoc), 0o600); err != nil {
t.Fatal(err)
}

cfg, err := LoadConfig()
if err != nil {
t.Fatalf("LoadConfig: %v", err)
}
if cfg.Postgres.URL != "postgres://from-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("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)
}
}

// The generated default config never contains a database URL.
func TestGeneratedConfigHasNoDatabaseURL(t *testing.T) {
dir := isolate(t)
path := filepath.Join(dir, "generated.yaml")
if err := GenerateDefaultConfig(path); err != nil {
t.Fatalf("GenerateDefaultConfig: %v", err)
}
t.Setenv("CONFIG_FILE", path)
cfg, err := LoadConfig()
if err != nil {
t.Fatalf("LoadConfig: %v", err)
}
if cfg.Postgres.URL != "" || cfg.Postgres.MaxConns != 10 {
t.Errorf("generated postgres block = %+v, want empty URL and defaults", cfg.Postgres)
}
}

// Pool sizes that do not fit in an int32 fall back to the default instead
// of wrapping around.
func TestPostgresConnsOutOfRangeFallBack(t *testing.T) {
for _, v := range []string{"2147483648", "99999999999", "-2147483649", "ten"} {
isolate(t)
t.Setenv("POSTGRES_MAX_CONNS", v)
cfg, err := LoadConfig()
if err != nil {
t.Fatalf("LoadConfig: %v", err)
}
if cfg.Postgres.MaxConns != 10 {
t.Errorf("POSTGRES_MAX_CONNS=%s: MaxConns = %d, want default 10", v, cfg.Postgres.MaxConns)
}
}
isolate(t)
t.Setenv("POSTGRES_MAX_CONNS", "2147483647")
if cfg, err := LoadConfig(); err != nil || cfg.Postgres.MaxConns != 2147483647 {
t.Errorf("largest int32 not accepted: %v, %v", cfg.Postgres.MaxConns, err)
}
}
Loading
Loading