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
22 changes: 17 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down
11 changes: 7 additions & 4 deletions doc/database-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand All @@ -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).

<hr />

Expand Down
30 changes: 22 additions & 8 deletions doc/developer-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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) │
└─────────────────────────────────────────────────────────────┘
```

Expand Down Expand Up @@ -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/
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion doc/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<mos>` envelope
(`mosID`, `ncsID`, `messageID`), UTF-16BE encoding, robust stream framing,
Expand Down
93 changes: 70 additions & 23 deletions src/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"errors"

"airshift/openmos/internal/config"
"airshift/openmos/internal/store/postgres"
Expand All @@ -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
}
6 changes: 5 additions & 1 deletion src/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/internal/config/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
2 changes: 1 addition & 1 deletion src/internal/config/load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
14 changes: 9 additions & 5 deletions src/internal/config/postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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)
}
}

Expand All @@ -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)
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/internal/repository/memory/memory.go
Original file line number Diff line number Diff line change
@@ -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 (
Expand Down
4 changes: 2 additions & 2 deletions src/internal/store/postgres/migrate.go
Original file line number Diff line number Diff line change
@@ -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 (
Expand Down
Loading
Loading