diff --git a/README.md b/README.md index 15134e4..478b68d 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Implementation status (2026-11-08): * [x] Core server skeleton and TCP socket server * [x] Sentry observability * [x] Internal event bus for client notifications -* [ ] PostgreSQL data repository (replacing MongoDB, see [migration plan](doc/database-migration.md)) +* [ ] PostgreSQL data repository (in progress; runs on in-memory storage until then, 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 (migration from MongoDB in progress, see [database-migration.md](doc/database-migration.md)) +- **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)) - **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. @@ -63,10 +63,6 @@ server: readtimeout: 5s writetimeout: 5s shutdowntimeout: 30s -mongo: # to be replaced by a postgres block - uri: "mongodb+srv://localhost" - database: openmosdb01 - timeout: 10s mos: id: mos01.station.com heartbeatinterval: 30s @@ -109,8 +105,8 @@ go build -o openmos ## Requirements -- Go 1.24.1 or later -- MongoDB 4.4 or later (current release; PostgreSQL 17 after the migration) +- Go 1.25 or later +- PostgreSQL 17 (once the PostgreSQL store lands; until then no database is needed) - Network access on port 10540 (default MOS port) ## License diff --git a/doc/database-migration.md b/doc/database-migration.md index 0885d69..6e2c605 100644 --- a/doc/database-migration.md +++ b/doc/database-migration.md @@ -1,7 +1,9 @@ # Database migration: MongoDB to PostgreSQL -OpenMOS is replacing MongoDB with PostgreSQL. MongoDB support will be removed, -not kept alongside, once the PostgreSQL store passes the same tests. +OpenMOS stores its data in PostgreSQL only. The original MongoDB store was +removed outright (MOS-34) rather than kept alongside or behind a switch. +Until the PostgreSQL store lands, the server runs on the in-memory reference +store (`internal/repository/memory`), so data is not persisted. ## Why @@ -10,8 +12,8 @@ not kept alongside, once the PostgreSQL store passes the same tests. - MOS messages such as `roCreate`, `roReplace` and `roStoryMove` change many rows at once and must succeed or fail as a whole, which calls for transactions. -- Only the storage layer (about 480 lines) uses MongoDB today, so switching - now is cheaper than after more profiles are built. +- Only the storage layer (about 480 lines) used MongoDB, so switching early + was cheaper than after more profiles were built. ## Tooling @@ -40,25 +42,25 @@ Tables: `running_orders`, `stories`, `items`, `mos_objects`. ## Code changes -- `internal/db`: drop the MongoDB client; a new `internal/store/postgres` +- `internal/db` and the MongoDB repositories are gone; a new `internal/store/postgres` package provides the pool, transactions and the four repositories. -- `internal/repository`: interfaces stay, with composite keys, ordering - operations and shared errors (`ErrNotFound`, `ErrVersionConflict`). +- `internal/repository`: interfaces stay, gaining composite keys and ordering + operations. Shared errors live in `errors.go` and grow with each change. - Services run each MOS message in one transaction, and running order updates use version-checked writes (optimistic locking). -- Configuration: the `mongo` block becomes a `postgres` block, with - `OPENMOS_DATABASE_URL` or the standard `PG*` environment variables. +- 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. ## Steps 1. Fix the build, add CI and an implementation-independent repository test - suite. -2. Add the schema migration and the PostgreSQL repositories, passing that - suite. -3. Switch the server to PostgreSQL and add transactions. -4. Remove the MongoDB code and driver, and update the documentation. + suite (MOS-11), with an in-memory reference store. +2. Remove the MongoDB code, driver and configuration (MOS-34). +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).
diff --git a/doc/developer-reference.md b/doc/developer-reference.md index 567713f..a647822 100644 --- a/doc/developer-reference.md +++ b/doc/developer-reference.md @@ -10,11 +10,11 @@ OpenMOS is an implementation of the Media Object Server (MOS) Protocol 4.0 using | Component | Technology | Version | |-----------|------------|---------| -| Language | Go | 1.24.1+ | -| Database | MongoDB | 4.4+ | -| Observability | Sentry | v0.31.1 | +| Language | Go | 1.25+ | +| Database | PostgreSQL (in progress; in-memory until then) | 17 | +| Observability | Sentry | v0.50 | | Communication | TCP Sockets | Port 10540 | -| Configuration | YAML | gopkg.in/yaml.v3 | +| Configuration | YAML | go.yaml.in/yaml/v3 | ## Architecture @@ -42,7 +42,7 @@ OpenMOS follows a **Clean Layered Architecture** with clear separation of concer │ ┌─────────────────────────▼───────────────────────────────────┐ │ Database Layer │ -│ (MongoDB) │ +│ (PostgreSQL; in-memory store until MOS-16) │ └─────────────────────────────────────────────────────────────┘ ``` @@ -56,7 +56,6 @@ OpenMOS follows a **Clean Layered Architecture** with clear separation of concer | **Repository** | `internal/repository/` | Data access abstraction, CRUD operations | | **Model** | `internal/model/` | Domain entities and value objects | | **XML** | `internal/xml/` | Message parsing and serialization | -| **Database** | `internal/db/` | MongoDB connection and collection management | | **Events** | `internal/events/` | Pub-sub event bus for real-time notifications | | **Utilities** | `pkg/` | Logging, monitoring, shared helpers | @@ -73,10 +72,6 @@ OpenMOS/ │ │ ├── config/ │ │ │ └── config.go # YAML/env configuration loader │ │ │ -│ │ ├── db/ -│ │ │ ├── db.go # Database interface -│ │ │ └── mongo.go # MongoDB implementation -│ │ │ │ │ ├── events/ │ │ │ └── bus.go # EventBus pub-sub implementation │ │ │ @@ -87,10 +82,6 @@ OpenMOS/ │ │ ├── repository/ │ │ │ ├── repository.go # Interface definitions │ │ │ ├── errors.go # Shared errors (ErrNotFound, ...) -│ │ │ ├── runningorder.go # RunningOrder MongoDB repo -│ │ │ ├── story.go # Story MongoDB repo -│ │ │ ├── item.go # Item MongoDB repo -│ │ │ ├── object.go # MOSObject MongoDB repo │ │ │ ├── memory/ # In-memory reference implementation │ │ │ └── repotest/ # Contract suite for every implementation │ │ │ @@ -165,7 +156,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. **Database Storage**: Changes are persisted to MongoDB +5. **Storage**: Changes are stored through the repository interfaces (in memory until the PostgreSQL store lands) 6. **Event Publishing**: Service publishes events to the event bus 7. **Client Notification**: Connected clients receive real-time updates via subscriptions @@ -173,7 +164,8 @@ RunningOrder (1) ──► (N) Story ──► (N) Item ──► MOSObject ### Core Infrastructure - [x] TCP Socket Server with multi-client support -- [x] MongoDB data persistence with repository pattern +- [x] Repository pattern with a contract test suite and an in-memory store +- [ ] 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 @@ -285,11 +277,6 @@ server: writetimeout: 5s # Write timeout duration shutdowntimeout: 30s # Graceful shutdown timeout -mongo: - uri: "mongodb://localhost" # MongoDB connection URI - database: openmosdb01 # Database name - timeout: 10s # Connection timeout - mos: id: mos01.station.com # MOS server identifier heartbeatinterval: 30s # Heartbeat interval diff --git a/doc/readme.md b/doc/readme.md index ca555e1..7b025c6 100644 --- a/doc/readme.md +++ b/doc/readme.md @@ -8,7 +8,7 @@ This section contains the documentation of the OpenMOS project. - [Roadmap](./roadmap.md) - Readiness by MOS profile, milestones and known issues -- [Database migration](./database-migration.md) - Plan for moving from MongoDB to PostgreSQL +- [Database migration](./database-migration.md) - Plan for moving storage to PostgreSQL - [Development tasks](./devtasks.md) diff --git a/doc/roadmap.md b/doc/roadmap.md index fb0db5c..6434ef4 100644 --- a/doc/roadmap.md +++ b/doc/roadmap.md @@ -24,7 +24,7 @@ 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 from MongoDB to PostgreSQL. + build, vet and tests, and storage moves to PostgreSQL. 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/go.mod b/src/go.mod index 70a551d..f4b70da 100644 --- a/src/go.mod +++ b/src/go.mod @@ -4,20 +4,10 @@ go 1.25.0 require ( github.com/getsentry/sentry-go v0.50.0 - go.mongodb.org/mongo-driver v1.17.3 go.yaml.in/yaml/v3 v3.0.6 ) require ( - github.com/golang/snappy v0.0.4 // indirect - github.com/klauspost/compress v1.16.7 // indirect - github.com/montanaflynn/stats v0.7.1 // indirect - github.com/xdg-go/pbkdf2 v1.0.0 // indirect - github.com/xdg-go/scram v1.1.2 // indirect - github.com/xdg-go/stringprep v1.0.4 // indirect - github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect - golang.org/x/crypto v0.36.0 // indirect - golang.org/x/sync v0.22.0 // indirect golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.41.0 // indirect ) diff --git a/src/go.sum b/src/go.sum index ccc266a..2d10a21 100644 --- a/src/go.sum +++ b/src/go.sum @@ -4,14 +4,8 @@ github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2ol 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/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= -github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 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/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= -github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= -github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= -github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= 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= @@ -20,51 +14,13 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI 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/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= -github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= -github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= -github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= -github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= -github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= -github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= -github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ= -go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= 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/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= -golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/src/internal/config/config.go b/src/internal/config/config.go index 18ed346..6a830b9 100644 --- a/src/internal/config/config.go +++ b/src/internal/config/config.go @@ -23,13 +23,6 @@ type Config struct { ShutdownTimeout time.Duration } - // MongoDB configuration - Mongo struct { - URI string - Database string - Timeout time.Duration - } - // MOS configuration MOS struct { // MOS ID of this server, used in MOS messages diff --git a/src/internal/config/defaults.go b/src/internal/config/defaults.go index 239e47a..1791608 100644 --- a/src/internal/config/defaults.go +++ b/src/internal/config/defaults.go @@ -19,11 +19,6 @@ func GenerateDefaultConfig(filePath string) error { config.Server.WriteTimeout = 5 * time.Second config.Server.ShutdownTimeout = 30 * time.Second - // MongoDB config - config.Mongo.URI = "mongodb://localhost:27017" - config.Mongo.Database = "openmos" - config.Mongo.Timeout = 10 * time.Second - // MOS config config.MOS.ID = "OpenMOS_Server" config.MOS.HeartbeatInterval = 30 * time.Second diff --git a/src/internal/config/env.go b/src/internal/config/env.go index 87d4e5c..0909ca4 100644 --- a/src/internal/config/env.go +++ b/src/internal/config/env.go @@ -33,17 +33,6 @@ func applyEnvOverrides(config *Config, yamlLoaded bool) { config.Server.ShutdownTimeout = getEnvAsDuration("SERVER_SHUTDOWN_TIMEOUT", getDefaultDuration(config.Server.ShutdownTimeout, 30*time.Second)) } - // MongoDB config - if envVal := getEnv("MONGODB_URI", ""); envVal != "" || !yamlLoaded { - config.Mongo.URI = getEnv("MONGODB_URI", getDefaultString(config.Mongo.URI, "mongodb://localhost:27017")) - } - if envVal := getEnv("MONGODB_DATABASE", ""); envVal != "" || !yamlLoaded { - config.Mongo.Database = getEnv("MONGODB_DATABASE", getDefaultString(config.Mongo.Database, "openmos")) - } - if envVal := getEnv("MONGODB_TIMEOUT", ""); envVal != "" || !yamlLoaded { - config.Mongo.Timeout = getEnvAsDuration("MONGODB_TIMEOUT", getDefaultDuration(config.Mongo.Timeout, 10*time.Second)) - } - // MOS config if envVal := getEnv("MOS_ID", ""); envVal != "" || !yamlLoaded { config.MOS.ID = getEnv("MOS_ID", getDefaultString(config.MOS.ID, "OpenMOS_Server")) diff --git a/src/internal/config/load_test.go b/src/internal/config/load_test.go index c9244bb..a43af4a 100644 --- a/src/internal/config/load_test.go +++ b/src/internal/config/load_test.go @@ -11,7 +11,6 @@ var configEnvKeys = []string{ "CONFIG_FILE", "APP_NAME", "APP_VERSION", "APP_ENV", "SERVER_HOST", "SERVER_PORT", "SERVER_READ_TIMEOUT", "SERVER_WRITE_TIMEOUT", "SERVER_SHUTDOWN_TIMEOUT", - "MONGODB_URI", "MONGODB_DATABASE", "MONGODB_TIMEOUT", "MOS_ID", "MOS_HEARTBEAT_INTERVAL", "MOS_CLIENT_TIMEOUT", "LOG_LEVEL", "SENTRY_DSN", "SENTRY_ENV", "SENTRY_DEBUG", "SENTRY_ATTACH_STACKTRACE", @@ -48,8 +47,6 @@ 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.Mongo.URI, want.Mongo.Database = "mongodb://localhost:27017", "openmos" - want.Mongo.Timeout = 10 * time.Second want.MOS.ID = "OpenMOS_Server" want.MOS.HeartbeatInterval, want.MOS.ClientTimeout = 30*time.Second, 2*time.Minute want.Logging.Level = "info" diff --git a/src/internal/db/db.go b/src/internal/db/db.go deleted file mode 100644 index ff126d1..0000000 --- a/src/internal/db/db.go +++ /dev/null @@ -1,28 +0,0 @@ -package db - -import ( - "context" - - "go.mongodb.org/mongo-driver/mongo" -) - -// Database defines the interface for database operations -type Database interface { - // Close closes the database connection - Close(ctx context.Context) error - - // Ping checks if the database connection is alive - Ping(ctx context.Context) error - - // Collection returns a collection for the given name - Collection(name string) *mongo.Collection - - // Database returns the underlying database instance - Database() *mongo.Database - - // Client returns the underlying client instance - Client() *mongo.Client - - // CreateIndexes creates the necessary indexes for the collections - CreateIndexes(ctx context.Context) error -} diff --git a/src/internal/db/mongo.go b/src/internal/db/mongo.go deleted file mode 100644 index 596a1a2..0000000 --- a/src/internal/db/mongo.go +++ /dev/null @@ -1,81 +0,0 @@ -package db - -import ( - "context" - "fmt" - - "airshift/openmos/internal/config" - - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" - "go.mongodb.org/mongo-driver/mongo/readpref" -) - -// MongoDB implements the database interface for MongoDB -type MongoDB struct { - client *mongo.Client - database *mongo.Database - config *config.Config -} - -// NewMongoDB creates a new MongoDB connection -func NewMongoDB(cfg *config.Config) (*MongoDB, error) { - ctx, cancel := context.WithTimeout(context.Background(), cfg.Mongo.Timeout) - defer cancel() - - // Create client options - clientOptions := options.Client().ApplyURI(cfg.Mongo.URI) - - // Connect to MongoDB - client, err := mongo.Connect(ctx, clientOptions) - if err != nil { - return nil, fmt.Errorf("failed to connect to MongoDB: %w", err) - } - - // Ping the database to verify connection - err = client.Ping(ctx, readpref.Primary()) - if err != nil { - return nil, fmt.Errorf("failed to ping MongoDB: %w", err) - } - - // Get database - database := client.Database(cfg.Mongo.Database) - - return &MongoDB{ - client: client, - database: database, - config: cfg, - }, nil -} - -// Close closes the MongoDB connection -func (m *MongoDB) Close(ctx context.Context) error { - return m.client.Disconnect(ctx) -} - -// Database returns the mongo.Database instance -func (m *MongoDB) Database() *mongo.Database { - return m.database -} - -// Client returns the mongo.Client instance -func (m *MongoDB) Client() *mongo.Client { - return m.client -} - -// Collection returns a mongo.Collection for the given name -func (m *MongoDB) Collection(name string) *mongo.Collection { - return m.database.Collection(name) -} - -// Ping checks if the database connection is alive -func (m *MongoDB) Ping(ctx context.Context) error { - return m.client.Ping(ctx, readpref.Primary()) -} - -// CreateIndexes creates the necessary indexes for the collections -func (m *MongoDB) CreateIndexes(ctx context.Context) error { - // This function would create all the necessary indexes for our collections - // We'll implement it as needed when we define our schema requirements - return nil -} diff --git a/src/internal/model/mos.go b/src/internal/model/mos.go index b66cbb4..1f6b919 100644 --- a/src/internal/model/mos.go +++ b/src/internal/model/mos.go @@ -6,67 +6,67 @@ import ( // MOSObject represents the lowest level media object in the MOS hierarchy type MOSObject struct { - ID string `bson:"_id" json:"id"` // Unique MOS Object ID - ObjectType string `bson:"objectType" json:"objectType"` // Type of object (e.g., VIDEO, AUDIO, GRAPHIC) - Slug string `bson:"slug" json:"slug"` // Human-readable name - Duration int `bson:"duration" json:"duration"` // Duration in seconds - TimeBase int `bson:"timeBase,omitempty" json:"timeBase,omitempty"` - Status StatusType `bson:"status" json:"status"` - ObjectID string `bson:"objectID,omitempty" json:"objectID,omitempty"` - MediaID string `bson:"mediaID,omitempty" json:"mediaID,omitempty"` - MosAbstract string `bson:"mosAbstract,omitempty" json:"mosAbstract,omitempty"` - Metadata map[string]string `bson:"metadata,omitempty" json:"metadata,omitempty"` - CreatedAt time.Time `bson:"createdAt" json:"createdAt"` - UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"` + ID string `json:"id"` // Unique MOS Object ID + ObjectType string `json:"objectType"` // Type of object (e.g., VIDEO, AUDIO, GRAPHIC) + Slug string `json:"slug"` // Human-readable name + Duration int `json:"duration"` // Duration in seconds + TimeBase int `json:"timeBase,omitempty"` + Status StatusType `json:"status"` + ObjectID string `json:"objectID,omitempty"` + MediaID string `json:"mediaID,omitempty"` + MosAbstract string `json:"mosAbstract,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } // Item represents a single item within a story type Item struct { - ID string `bson:"_id" json:"id"` // Unique Item ID - ObjectID string `bson:"objectID,omitempty" json:"objectID,omitempty"` // Reference to MOS Object - Slug string `bson:"slug" json:"slug"` - Duration int `bson:"duration" json:"duration"` // Duration in seconds - EditorialDuration int `bson:"editorialDuration,omitempty" json:"editorialDuration,omitempty"` - TimeBase int `bson:"timeBase,omitempty" json:"timeBase,omitempty"` - Status StatusType `bson:"status" json:"status"` - Order int `bson:"order" json:"order"` // Order within the story - StoryID string `bson:"storyID" json:"storyID"` // Parent story ID - Metadata map[string]string `bson:"metadata,omitempty" json:"metadata,omitempty"` - CreatedAt time.Time `bson:"createdAt" json:"createdAt"` - UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"` + ID string `json:"id"` // Unique Item ID + ObjectID string `json:"objectID,omitempty"` // Reference to MOS Object + Slug string `json:"slug"` + Duration int `json:"duration"` // Duration in seconds + EditorialDuration int `json:"editorialDuration,omitempty"` + TimeBase int `json:"timeBase,omitempty"` + Status StatusType `json:"status"` + Order int `json:"order"` // Order within the story + StoryID string `json:"storyID"` // Parent story ID + Metadata map[string]string `json:"metadata,omitempty"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } // Story represents a story in the running order (collection of items) type Story struct { - ID string `bson:"_id" json:"id"` // Unique Story ID - RunningOrderID string `bson:"runningOrderID" json:"runningOrderID"` // Parent running order - Slug string `bson:"slug" json:"slug"` - Number string `bson:"number,omitempty" json:"number,omitempty"` - Duration int `bson:"duration" json:"duration"` // Duration in seconds - Status StatusType `bson:"status" json:"status"` - Order int `bson:"order" json:"order"` // Order within the running order - PreviousID string `bson:"previousID,omitempty" json:"previousID,omitempty"` // Previous story ID for linked list - NextID string `bson:"nextID,omitempty" json:"nextID,omitempty"` // Next story ID for linked list - Presenter string `bson:"presenter,omitempty" json:"presenter,omitempty"` - Metadata map[string]string `bson:"metadata,omitempty" json:"metadata,omitempty"` - CreatedAt time.Time `bson:"createdAt" json:"createdAt"` - UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"` + ID string `json:"id"` // Unique Story ID + RunningOrderID string `json:"runningOrderID"` // Parent running order + Slug string `json:"slug"` + Number string `json:"number,omitempty"` + Duration int `json:"duration"` // Duration in seconds + Status StatusType `json:"status"` + Order int `json:"order"` // Order within the running order + PreviousID string `json:"previousID,omitempty"` // Previous story ID for linked list + NextID string `json:"nextID,omitempty"` // Next story ID for linked list + Presenter string `json:"presenter,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } // RunningOrder represents the top-level running order (collection of stories) type RunningOrder struct { - ID string `bson:"_id" json:"id"` // Unique Running Order ID - MosID string `bson:"mosID" json:"mosID"` // MOS ID for this running order - Slug string `bson:"slug" json:"slug"` - Status StatusType `bson:"status" json:"status"` - Duration int `bson:"duration" json:"duration"` // Total duration in seconds - FirstStoryID string `bson:"firstStoryID,omitempty" json:"firstStoryID,omitempty"` // First story ID for linked list - LastStoryID string `bson:"lastStoryID,omitempty" json:"lastStoryID,omitempty"` // Last story ID for linked list - AirTime *time.Time `bson:"airTime,omitempty" json:"airTime,omitempty"` - Channel string `bson:"channel,omitempty" json:"channel,omitempty"` - Metadata map[string]string `bson:"metadata,omitempty" json:"metadata,omitempty"` - Version int `bson:"version" json:"version"` - CreatedBy string `bson:"createdBy,omitempty" json:"createdBy,omitempty"` - CreatedAt time.Time `bson:"createdAt" json:"createdAt"` - UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"` + ID string `json:"id"` // Unique Running Order ID + MosID string `json:"mosID"` // MOS ID for this running order + Slug string `json:"slug"` + Status StatusType `json:"status"` + Duration int `json:"duration"` // Total duration in seconds + FirstStoryID string `json:"firstStoryID,omitempty"` // First story ID for linked list + LastStoryID string `json:"lastStoryID,omitempty"` // Last story ID for linked list + AirTime *time.Time `json:"airTime,omitempty"` + Channel string `json:"channel,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` + Version int `json:"version"` + CreatedBy string `json:"createdBy,omitempty"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } diff --git a/src/internal/repository/item.go b/src/internal/repository/item.go deleted file mode 100644 index aa6edc4..0000000 --- a/src/internal/repository/item.go +++ /dev/null @@ -1,119 +0,0 @@ -package repository - -import ( - "context" - "errors" - "fmt" - "time" - - "airshift/openmos/internal/db" - "airshift/openmos/internal/model" - - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" -) - -// MongoItemRepository implements ItemRepository for MongoDB -type MongoItemRepository struct { - db db.Database - collection *mongo.Collection -} - -// NewMongoItemRepository creates a new MongoDB item repository -func NewMongoItemRepository(database db.Database) *MongoItemRepository { - return &MongoItemRepository{ - db: database, - collection: database.Collection("items"), - } -} - -// Create creates a new item -func (r *MongoItemRepository) Create(ctx context.Context, item *model.Item) (*model.Item, error) { - now := time.Now() - item.CreatedAt = now - item.UpdatedAt = now - - // Ensure ID uniqueness - if item.ID == "" { - return nil, errors.New("item ID is required") - } - - // Check if ID already exists - count, err := r.collection.CountDocuments(ctx, bson.M{"_id": item.ID}) - if err != nil { - return nil, fmt.Errorf("failed to check item ID uniqueness: %w", err) - } - if count > 0 { - return nil, fmt.Errorf("item %s: %w", item.ID, ErrAlreadyExists) - } - - _, err = r.collection.InsertOne(ctx, item) - if err != nil { - return nil, fmt.Errorf("failed to create item: %w", err) - } - - return item, nil -} - -// Get retrieves an item by ID -func (r *MongoItemRepository) Get(ctx context.Context, id string) (*model.Item, error) { - var item model.Item - err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&item) - if err != nil { - if errors.Is(err, mongo.ErrNoDocuments) { - return nil, fmt.Errorf("item %s: %w", id, ErrNotFound) - } - return nil, fmt.Errorf("failed to get item: %w", err) - } - return &item, nil -} - -// Update updates an item -func (r *MongoItemRepository) Update(ctx context.Context, item *model.Item) error { - now := time.Now() - item.UpdatedAt = now - - filter := bson.M{"_id": item.ID} - result, err := r.collection.ReplaceOne(ctx, filter, item) - if err != nil { - return fmt.Errorf("failed to update item: %w", err) - } - if result.MatchedCount == 0 { - return fmt.Errorf("item %s: %w", item.ID, ErrNotFound) - } - - return nil -} - -// Delete deletes an item -func (r *MongoItemRepository) Delete(ctx context.Context, id string) error { - result, err := r.collection.DeleteOne(ctx, bson.M{"_id": id}) - if err != nil { - return fmt.Errorf("failed to delete item: %w", err) - } - - if result.DeletedCount == 0 { - return fmt.Errorf("item %s: %w", id, ErrNotFound) - } - - return nil -} - -// ListByStory returns all items for a story -func (r *MongoItemRepository) ListByStory(ctx context.Context, storyID string) ([]*model.Item, error) { - opts := options.Find().SetSort(bson.M{"order": 1}) - cursor, err := r.collection.Find(ctx, bson.M{"storyID": storyID}, opts) - if err != nil { - return nil, fmt.Errorf("failed to list items: %w", err) - } - defer cursor.Close(ctx) - - var items []*model.Item - err = cursor.All(ctx, &items) - if err != nil { - return nil, fmt.Errorf("failed to decode items: %w", err) - } - - return items, nil -} diff --git a/src/internal/repository/object.go b/src/internal/repository/object.go deleted file mode 100644 index 4b5f1ae..0000000 --- a/src/internal/repository/object.go +++ /dev/null @@ -1,119 +0,0 @@ -package repository - -import ( - "context" - "errors" - "fmt" - "time" - - "airshift/openmos/internal/db" - "airshift/openmos/internal/model" - - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" -) - -// MongoObjectRepository implements ObjectRepository for MongoDB -type MongoObjectRepository struct { - db db.Database - collection *mongo.Collection -} - -// NewMongoObjectRepository creates a new MongoDB object repository -func NewMongoObjectRepository(database db.Database) *MongoObjectRepository { - return &MongoObjectRepository{ - db: database, - collection: database.Collection("mosObjects"), - } -} - -// Create creates a new MOS object -func (r *MongoObjectRepository) Create(ctx context.Context, obj *model.MOSObject) (*model.MOSObject, error) { - now := time.Now() - obj.CreatedAt = now - obj.UpdatedAt = now - - // Ensure ID uniqueness - if obj.ID == "" { - return nil, errors.New("object ID is required") - } - - // Check if ID already exists - count, err := r.collection.CountDocuments(ctx, bson.M{"_id": obj.ID}) - if err != nil { - return nil, fmt.Errorf("failed to check object ID uniqueness: %w", err) - } - if count > 0 { - return nil, fmt.Errorf("object %s: %w", obj.ID, ErrAlreadyExists) - } - - _, err = r.collection.InsertOne(ctx, obj) - if err != nil { - return nil, fmt.Errorf("failed to create object: %w", err) - } - - return obj, nil -} - -// Get retrieves a MOS object by ID -func (r *MongoObjectRepository) Get(ctx context.Context, id string) (*model.MOSObject, error) { - var obj model.MOSObject - err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&obj) - if err != nil { - if errors.Is(err, mongo.ErrNoDocuments) { - return nil, fmt.Errorf("object %s: %w", id, ErrNotFound) - } - return nil, fmt.Errorf("failed to get object: %w", err) - } - return &obj, nil -} - -// Update updates a MOS object -func (r *MongoObjectRepository) Update(ctx context.Context, obj *model.MOSObject) error { - now := time.Now() - obj.UpdatedAt = now - - filter := bson.M{"_id": obj.ID} - result, err := r.collection.ReplaceOne(ctx, filter, obj) - if err != nil { - return fmt.Errorf("failed to update object: %w", err) - } - if result.MatchedCount == 0 { - return fmt.Errorf("object %s: %w", obj.ID, ErrNotFound) - } - - return nil -} - -// Delete deletes a MOS object -func (r *MongoObjectRepository) Delete(ctx context.Context, id string) error { - result, err := r.collection.DeleteOne(ctx, bson.M{"_id": id}) - if err != nil { - return fmt.Errorf("failed to delete object: %w", err) - } - - if result.DeletedCount == 0 { - return fmt.Errorf("object %s: %w", id, ErrNotFound) - } - - return nil -} - -// List returns all MOS objects -func (r *MongoObjectRepository) List(ctx context.Context) ([]*model.MOSObject, error) { - opts := options.Find().SetSort(bson.M{"createdAt": -1}) - cursor, err := r.collection.Find(ctx, bson.M{}, opts) - if err != nil { - return nil, fmt.Errorf("failed to list objects: %w", err) - } - defer cursor.Close(ctx) - - var objects []*model.MOSObject - err = cursor.All(ctx, &objects) - if err != nil { - return nil, fmt.Errorf("failed to decode objects: %w", err) - } - - return objects, nil -} diff --git a/src/internal/repository/runningorder.go b/src/internal/repository/runningorder.go deleted file mode 100644 index b3a7eb9..0000000 --- a/src/internal/repository/runningorder.go +++ /dev/null @@ -1,133 +0,0 @@ -package repository - -import ( - "context" - "errors" - "fmt" - "time" - - "airshift/openmos/internal/db" - "airshift/openmos/internal/model" - - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" -) - -// MongoRunningOrderRepository implements RunningOrderRepository for MongoDB -type MongoRunningOrderRepository struct { - db db.Database - collection *mongo.Collection -} - -// NewMongoRunningOrderRepository creates a new MongoDB running order repository -func NewMongoRunningOrderRepository(database db.Database) *MongoRunningOrderRepository { - return &MongoRunningOrderRepository{ - db: database, - collection: database.Collection("runningOrders"), - } -} - -// Create creates a new running order -func (r *MongoRunningOrderRepository) Create(ctx context.Context, ro *model.RunningOrder) (*model.RunningOrder, error) { - now := time.Now() - ro.CreatedAt = now - ro.UpdatedAt = now - ro.Version = 1 - - // Ensure ID uniqueness - if ro.ID == "" { - return nil, errors.New("running order ID is required") - } - - // Check if ID already exists - count, err := r.collection.CountDocuments(ctx, bson.M{"_id": ro.ID}) - if err != nil { - return nil, fmt.Errorf("failed to check running order ID uniqueness: %w", err) - } - if count > 0 { - return nil, fmt.Errorf("running order %s: %w", ro.ID, ErrAlreadyExists) - } - - _, err = r.collection.InsertOne(ctx, ro) - if err != nil { - return nil, fmt.Errorf("failed to create running order: %w", err) - } - - return ro, nil -} - -// Get retrieves a running order by ID -func (r *MongoRunningOrderRepository) Get(ctx context.Context, id string) (*model.RunningOrder, error) { - var ro model.RunningOrder - err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&ro) - if err != nil { - if errors.Is(err, mongo.ErrNoDocuments) { - return nil, fmt.Errorf("running order %s: %w", id, ErrNotFound) - } - return nil, fmt.Errorf("failed to get running order: %w", err) - } - return &ro, nil -} - -// Update updates a running order -func (r *MongoRunningOrderRepository) Update(ctx context.Context, ro *model.RunningOrder) error { - // Get current document to check version. This read-then-replace is not - // atomic; MOS-15 replaces it with a version-checked write. - var current model.RunningOrder - err := r.collection.FindOne(ctx, bson.M{"_id": ro.ID}).Decode(¤t) - if err != nil { - if errors.Is(err, mongo.ErrNoDocuments) { - return fmt.Errorf("running order %s: %w", ro.ID, ErrNotFound) - } - return fmt.Errorf("failed to get current running order: %w", err) - } - - // Optimistic concurrency control - if ro.Version != current.Version { - return fmt.Errorf("running order %s at version %d, update based on %d: %w", - ro.ID, current.Version, ro.Version, ErrVersionConflict) - } - ro.Version++ - ro.UpdatedAt = time.Now() - - filter := bson.M{"_id": ro.ID} - _, err = r.collection.ReplaceOne(ctx, filter, ro) - if err != nil { - return fmt.Errorf("failed to update running order: %w", err) - } - - return nil -} - -// Delete deletes a running order -func (r *MongoRunningOrderRepository) Delete(ctx context.Context, id string) error { - result, err := r.collection.DeleteOne(ctx, bson.M{"_id": id}) - if err != nil { - return fmt.Errorf("failed to delete running order: %w", err) - } - - if result.DeletedCount == 0 { - return fmt.Errorf("running order %s: %w", id, ErrNotFound) - } - - return nil -} - -// List returns all running orders -func (r *MongoRunningOrderRepository) List(ctx context.Context) ([]*model.RunningOrder, error) { - opts := options.Find().SetSort(bson.M{"createdAt": -1}) - cursor, err := r.collection.Find(ctx, bson.M{}, opts) - if err != nil { - return nil, fmt.Errorf("failed to list running orders: %w", err) - } - defer cursor.Close(ctx) - - var runningOrders []*model.RunningOrder - err = cursor.All(ctx, &runningOrders) - if err != nil { - return nil, fmt.Errorf("failed to decode running orders: %w", err) - } - - return runningOrders, nil -} diff --git a/src/internal/repository/story.go b/src/internal/repository/story.go deleted file mode 100644 index b94510c..0000000 --- a/src/internal/repository/story.go +++ /dev/null @@ -1,119 +0,0 @@ -package repository - -import ( - "context" - "errors" - "fmt" - "time" - - "airshift/openmos/internal/db" - "airshift/openmos/internal/model" - - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" -) - -// MongoStoryRepository implements StoryRepository for MongoDB -type MongoStoryRepository struct { - db db.Database - collection *mongo.Collection -} - -// NewMongoStoryRepository creates a new MongoDB story repository -func NewMongoStoryRepository(database db.Database) *MongoStoryRepository { - return &MongoStoryRepository{ - db: database, - collection: database.Collection("stories"), - } -} - -// Create creates a new story -func (r *MongoStoryRepository) Create(ctx context.Context, story *model.Story) (*model.Story, error) { - now := time.Now() - story.CreatedAt = now - story.UpdatedAt = now - - // Ensure ID uniqueness - if story.ID == "" { - return nil, errors.New("story ID is required") - } - - // Check if ID already exists - count, err := r.collection.CountDocuments(ctx, bson.M{"_id": story.ID}) - if err != nil { - return nil, fmt.Errorf("failed to check story ID uniqueness: %w", err) - } - if count > 0 { - return nil, fmt.Errorf("story %s: %w", story.ID, ErrAlreadyExists) - } - - _, err = r.collection.InsertOne(ctx, story) - if err != nil { - return nil, fmt.Errorf("failed to create story: %w", err) - } - - return story, nil -} - -// Get retrieves a story by ID -func (r *MongoStoryRepository) Get(ctx context.Context, id string) (*model.Story, error) { - var story model.Story - err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&story) - if err != nil { - if errors.Is(err, mongo.ErrNoDocuments) { - return nil, fmt.Errorf("story %s: %w", id, ErrNotFound) - } - return nil, fmt.Errorf("failed to get story: %w", err) - } - return &story, nil -} - -// Update updates a story -func (r *MongoStoryRepository) Update(ctx context.Context, story *model.Story) error { - now := time.Now() - story.UpdatedAt = now - - filter := bson.M{"_id": story.ID} - result, err := r.collection.ReplaceOne(ctx, filter, story) - if err != nil { - return fmt.Errorf("failed to update story: %w", err) - } - if result.MatchedCount == 0 { - return fmt.Errorf("story %s: %w", story.ID, ErrNotFound) - } - - return nil -} - -// Delete deletes a story -func (r *MongoStoryRepository) Delete(ctx context.Context, id string) error { - result, err := r.collection.DeleteOne(ctx, bson.M{"_id": id}) - if err != nil { - return fmt.Errorf("failed to delete story: %w", err) - } - - if result.DeletedCount == 0 { - return fmt.Errorf("story %s: %w", id, ErrNotFound) - } - - return nil -} - -// ListByRunningOrder returns all stories for a running order -func (r *MongoStoryRepository) ListByRunningOrder(ctx context.Context, roID string) ([]*model.Story, error) { - opts := options.Find().SetSort(bson.M{"order": 1}) - cursor, err := r.collection.Find(ctx, bson.M{"runningOrderID": roID}, opts) - if err != nil { - return nil, fmt.Errorf("failed to list stories: %w", err) - } - defer cursor.Close(ctx) - - var stories []*model.Story - err = cursor.All(ctx, &stories) - if err != nil { - return nil, fmt.Errorf("failed to decode stories: %w", err) - } - - return stories, nil -} diff --git a/src/main.go b/src/main.go index 4347f54..3375480 100644 --- a/src/main.go +++ b/src/main.go @@ -49,14 +49,7 @@ func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - database := connectDatabase(cfg, log) - defer func() { - if err := database.Close(context.Background()); err != nil { - log.Errorf("Error disconnecting from MongoDB: %v", err) - } - }() - - tcpServer := newTCPServer(cfg, database, log) + tcpServer := newTCPServer(cfg, newRepository(log), log) // Handle signals for graceful shutdown sigCh := make(chan os.Signal, 1) diff --git a/src/wiring.go b/src/wiring.go index f90b34e..2815bec 100644 --- a/src/wiring.go +++ b/src/wiring.go @@ -5,9 +5,9 @@ import ( "time" "airshift/openmos/internal/config" - "airshift/openmos/internal/db" "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,35 +15,22 @@ import ( "github.com/getsentry/sentry-go" ) -// connectDatabase connects to MongoDB and exits the process on failure. -func connectDatabase(cfg *config.Config, log *logger.SentryLogger) *db.MongoDB { - log.Info("Connecting to MongoDB...") - database, err := db.NewMongoDB(cfg) - if err != nil { - // Capture the error in Sentry and then log and exit - log.CaptureException(err, map[string]string{ - "component": "database", - "action": "connect", - }, nil) - log.Fatalf("Failed to connect to MongoDB: %v", err) - } - return database +// 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, database *db.MongoDB, log *logger.SentryLogger) *server.TCPServer { - // Create repositories - runningOrderRepo := repository.NewMongoRunningOrderRepository(database) - storyRepo := repository.NewMongoStoryRepository(database) - itemRepo := repository.NewMongoItemRepository(database) - objectRepo := repository.NewMongoObjectRepository(database) - +func newTCPServer(cfg *config.Config, repo repository.Repository, log *logger.SentryLogger) *server.TCPServer { // Create event bus for pub-sub messaging eventBus := events.NewEventBus() // Create service - mosService := service.NewMOSService(runningOrderRepo, storyRepo, itemRepo, objectRepo, eventBus) + mosService := service.NewMOSService(repo.RunningOrders(), repo.Stories(), repo.Items(), repo.Objects(), eventBus) // Create and start TCP server log.Info("Starting TCP server...")