From ffec6916f45c160ddb5082d6661d9b4bd6a4e24a Mon Sep 17 00:00:00 2001 From: Timo Ruohomaki Date: Mon, 9 Nov 2026 19:27:13 +0200 Subject: [PATCH] MOS-14: Add PostgreSQL repositories with composite keys and ordering - Repository interfaces use MOS composite keys (roID/storyID/itemID, mosID/objID) and add Move, Swap and ReplaceAll for stories and items. Order is managed by the repositories; shared ordering rules and ID checks live in repository/order.go. New ErrInvalid. - internal/store/postgres: hand-written pgx repositories over a DBTX (pool or transaction). Version-checked running order updates, parent row locks around position changes, single-statement renumbering, and mapping of SQLSTATEs to the repository errors. - Contract suite extended: ordering, minimal records, create after delete, composite key independence, cascades incl. ReplaceAll. Runs against the memory store and the test database; plus concurrent append and error mapping tests for PostgreSQL. - Model drops fields that belonged to MongoDB-era linking (Previous/ NextID, First/LastStoryID, story Duration) and bson tags. - Service: roCreate replaces stories and items in message order; composite keys in story actions; server output drops storyDur and adds item mosID. - Docs: migration plan and developer reference updated. Co-Authored-By: Claude Opus 5.5 --- doc/database-migration.md | 14 +- doc/developer-reference.md | 10 +- src/internal/model/mos.go | 87 +++---- src/internal/repository/errors.go | 7 +- src/internal/repository/memory/item.go | 153 +++++++++--- src/internal/repository/memory/memory.go | 54 +++-- src/internal/repository/memory/object.go | 41 ++-- .../repository/memory/runningorder.go | 25 +- src/internal/repository/memory/story.go | 150 +++++++++--- src/internal/repository/order.go | 104 ++++++++ src/internal/repository/order_test.go | 98 ++++++++ src/internal/repository/repository.go | 96 +++++--- src/internal/repository/repotest/cascade.go | 107 +++++---- src/internal/repository/repotest/children.go | 81 +++---- src/internal/repository/repotest/crud.go | 91 ++++--- src/internal/repository/repotest/fixtures.go | 54 ++--- src/internal/repository/repotest/kinds.go | 88 +++++-- src/internal/repository/repotest/object.go | 20 +- src/internal/repository/repotest/ordering.go | 224 ++++++++++++++++++ src/internal/repository/repotest/repotest.go | 5 + src/internal/server/client_ro_handler.go | 12 +- src/internal/server/client_ro_notify.go | 12 +- src/internal/service/mos.go | 106 ++++----- src/internal/service/mos_test.go | 132 +++++++---- src/internal/service/story.go | 6 +- src/internal/service/story_body.go | 17 +- src/internal/service/story_create.go | 21 +- src/internal/store/postgres/errors_test.go | 45 ++++ src/internal/store/postgres/item.go | 174 ++++++++++++++ src/internal/store/postgres/object.go | 102 ++++++++ src/internal/store/postgres/repository.go | 135 +++++++++++ .../store/postgres/repository_test.go | 80 +++++++ src/internal/store/postgres/runningorder.go | 111 +++++++++ src/internal/store/postgres/story.go | 163 +++++++++++++ 34 files changed, 2105 insertions(+), 520 deletions(-) create mode 100644 src/internal/repository/order.go create mode 100644 src/internal/repository/order_test.go create mode 100644 src/internal/repository/repotest/ordering.go create mode 100644 src/internal/store/postgres/errors_test.go create mode 100644 src/internal/store/postgres/item.go create mode 100644 src/internal/store/postgres/object.go create mode 100644 src/internal/store/postgres/repository.go create mode 100644 src/internal/store/postgres/repository_test.go create mode 100644 src/internal/store/postgres/runningorder.go create mode 100644 src/internal/store/postgres/story.go diff --git a/doc/database-migration.md b/doc/database-migration.md index 6e2c605..fec40cd 100644 --- a/doc/database-migration.md +++ b/doc/database-migration.md @@ -2,8 +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. -Until the PostgreSQL store lands, the server runs on the in-memory reference -store (`internal/repository/memory`), so data is not persisted. +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. ## Why @@ -21,7 +22,7 @@ store (`internal/repository/memory`), so data is not persisted. | --- | --- | --- | | Driver and pool | [pgx v5](https://github.com/jackc/pgx) (`pgxpool`) | Actively maintained, native PostgreSQL types | | Migrations | [goose v3](https://github.com/pressly/goose) | Plain SQL files embedded in the binary | -| Integration tests | [testcontainers-go](https://github.com/testcontainers/testcontainers-go) | Runs a real PostgreSQL in tests and CI | +| Integration tests | PostgreSQL service container in CI, Docker Compose locally | Tests read `OPENMOS_TEST_DATABASE_URL`; chosen over testcontainers-go to keep Docker out of the test binary | | Database | PostgreSQL 17 | Local development via Docker Compose | ## Schema principles @@ -45,7 +46,12 @@ Tables: `running_orders`, `stories`, `items`, `mos_objects`. - `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, gaining composite keys and ordering - operations. Shared errors live in `errors.go` and grow with each change. + operations (`Move`, `Swap`, `ReplaceAll`). The ordering rules are shared + helpers in `order.go`, so both stores behave alike. Shared errors live in + `errors.go` and grow with each change. +- The PostgreSQL repositories use hand-written pgx queries. Operations that + assign positions lock the parent row first, so concurrent appends and moves + on one running order or story run one at a time. - Services run each MOS message in one transaction, and running order updates use version-checked writes (optimistic locking). - Configuration: the old `mongo` block is gone; a new `postgres` block, with diff --git a/doc/developer-reference.md b/doc/developer-reference.md index 6cc4252..f0526f1 100644 --- a/doc/developer-reference.md +++ b/doc/developer-reference.md @@ -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 connection pool and schema migrations (repositories to follow) | +| **Store** | `internal/store/postgres/` | PostgreSQL connection pool, schema migrations and repositories | | **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 | @@ -83,12 +83,15 @@ OpenMOS/ │ │ ├── repository/ │ │ │ ├── repository.go # Interface definitions │ │ │ ├── errors.go # Shared errors (ErrNotFound, ...) +│ │ │ ├── order.go # ID checks and shared ordering rules │ │ │ ├── memory/ # In-memory reference implementation │ │ │ └── repotest/ # Contract suite for every implementation │ │ │ │ │ ├── store/postgres/ │ │ │ ├── migrate.go # Goose migrations (embedded SQL) │ │ │ ├── pool.go # pgx connection pool, TLS rules +│ │ │ ├── repository.go # PostgreSQL repositories (New), error mapping +│ │ │ ├── runningorder.go, story.go, item.go, object.go │ │ │ └── migrations/ # Schema migrations (00001_init.sql, ...) │ │ │ │ │ ├── server/ @@ -162,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 PostgreSQL store lands) +5. **Storage**: Changes are stored through the repository interfaces (in memory until the server switches to PostgreSQL in MOS-16) 6. **Event Publishing**: Service publishes events to the event bus 7. **Client Notification**: Connected clients receive real-time updates via subscriptions @@ -336,7 +339,8 @@ sentry: ### Testing - Write unit tests for service and repository layers - Every repository implementation must pass the contract suite: - call `repotest.Run` from its tests (see `repository/memory`) + call `repotest.Run` from its tests (see `repository/memory` and + `store/postgres/repository_test.go`) - Use interfaces to enable mocking - Test XML parsing with example messages from `/res/` - PostgreSQL tests (`internal/store/postgres`) need a throwaway database in diff --git a/src/internal/model/mos.go b/src/internal/model/mos.go index 1f6b919..10f2031 100644 --- a/src/internal/model/mos.go +++ b/src/internal/model/mos.go @@ -4,49 +4,52 @@ import ( "time" ) +// The model follows the MOS keys: an ID is unique only within its parent, so +// stories and items carry their parents' IDs, and objects their MOS device. +// Order is the position among siblings and is managed by the repositories. +// Durations of items and objects are counts of samples at TimeBase samples +// per second (MOS objTB, e.g. 50 for PAL or 59.94 for NTSC). + // MOSObject represents the lowest level media object in the MOS hierarchy type MOSObject struct { - 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"` + MosID string `json:"mosID"` // MOS device that owns the object + ID string `json:"id"` // objID, unique within MosID + ObjectType string `json:"objectType"` // STILL, AUDIO or VIDEO; empty if unknown + Slug string `json:"slug"` // Human-readable name + Duration int64 `json:"duration"` // objDur, in samples + TimeBase float64 `json:"timeBase,omitempty"` + Status StatusType `json:"status"` + Abstract string `json:"abstract,omitempty"` // mosAbstract + 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 `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"` + RunningOrderID string `json:"runningOrderID"` // Parent running order + StoryID string `json:"storyID"` // Parent story + ID string `json:"id"` // itemID, unique within its story + ObjectID string `json:"objectID,omitempty"` // Referenced MOS object (objID) + MosID string `json:"mosID,omitempty"` // MOS device of the referenced object + Slug string `json:"slug"` + Duration int64 `json:"duration"` // itemEdDur, in samples + TimeBase float64 `json:"timeBase,omitempty"` + Status StatusType `json:"status"` + Order int `json:"order"` // Position within the story + 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 `json:"id"` // Unique Story ID RunningOrderID string `json:"runningOrderID"` // Parent running order + ID string `json:"id"` // storyID, unique within its 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 + Order int `json:"order"` // Position within the running order Presenter string `json:"presenter,omitempty"` Metadata map[string]string `json:"metadata,omitempty"` CreatedAt time.Time `json:"createdAt"` @@ -55,18 +58,16 @@ type Story struct { // RunningOrder represents the top-level running order (collection of stories) type RunningOrder struct { - 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"` + ID string `json:"id"` // roID + MosID string `json:"mosID"` // MOS ID for this running order + Slug string `json:"slug"` + Status StatusType `json:"status"` + Duration int `json:"duration"` // roEdDur, in seconds + AirTime *time.Time `json:"airTime,omitempty"` // roEdStart + 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/errors.go b/src/internal/repository/errors.go index 162265b..029e071 100644 --- a/src/internal/repository/errors.go +++ b/src/internal/repository/errors.go @@ -9,10 +9,15 @@ var ( // refers to, does not exist. ErrNotFound = errors.New("not found") - // ErrAlreadyExists means Create was called with an ID that is in use. + // ErrAlreadyExists means Create was called with a key that is in use. ErrAlreadyExists = errors.New("already exists") // ErrVersionConflict means an update was based on a stale version of a // running order. ErrVersionConflict = errors.New("version conflict") + + // ErrInvalid means the request itself is malformed: an empty or too long + // ID, a value outside its MOS limits, or an ordering request that names + // the same record twice. + ErrInvalid = errors.New("invalid") ) diff --git a/src/internal/repository/memory/item.go b/src/internal/repository/memory/item.go index e3c49ec..edbcade 100644 --- a/src/internal/repository/memory/item.go +++ b/src/internal/repository/memory/item.go @@ -2,8 +2,8 @@ package memory import ( "context" - "errors" "fmt" + "slices" "airshift/openmos/internal/model" "airshift/openmos/internal/repository" @@ -12,29 +12,28 @@ import ( type items struct{ r *Repository } func (s items) Create(_ context.Context, item *model.Item) (*model.Item, error) { - if item.ID == "" { - return nil, errors.New("item ID is required") + if err := checkItemKey(item.RunningOrderID, item.StoryID, item.ID); err != nil { + return nil, err } s.r.mu.Lock() defer s.r.mu.Unlock() - if _, ok := s.r.items[item.ID]; ok { - return nil, fmt.Errorf("item %s: %w", item.ID, repository.ErrAlreadyExists) + k := itemKey{item.RunningOrderID, item.StoryID, item.ID} + if _, ok := s.r.items[k]; ok { + return nil, fmt.Errorf("item %s/%s/%s: %w", k.ro, k.story, k.item, repository.ErrAlreadyExists) } - if err := s.checkParentLocked(item); err != nil { + if err := s.checkParentLocked(k.ro, k.story); err != nil { return nil, err } - t := now() - item.CreatedAt, item.UpdatedAt = t, t - s.r.items[item.ID] = cloneItem(item) + s.insertLocked(item, s.nextOrderLocked(k.ro, k.story)) return cloneItem(item), nil } -func (s items) Get(_ context.Context, id string) (*model.Item, error) { +func (s items) Get(_ context.Context, roID, storyID, itemID string) (*model.Item, error) { s.r.mu.RLock() defer s.r.mu.RUnlock() - item, ok := s.r.items[id] + item, ok := s.r.items[itemKey{roID, storyID, itemID}] if !ok { - return nil, fmt.Errorf("item %s: %w", id, repository.ErrNotFound) + return nil, fmt.Errorf("item %s/%s/%s: %w", roID, storyID, itemID, repository.ErrNotFound) } return cloneItem(item), nil } @@ -42,44 +41,138 @@ func (s items) Get(_ context.Context, id string) (*model.Item, error) { func (s items) Update(_ context.Context, item *model.Item) error { s.r.mu.Lock() defer s.r.mu.Unlock() - current, ok := s.r.items[item.ID] + k := itemKey{item.RunningOrderID, item.StoryID, item.ID} + current, ok := s.r.items[k] if !ok { - return fmt.Errorf("item %s: %w", item.ID, repository.ErrNotFound) - } - if err := s.checkParentLocked(item); err != nil { - return err + return fmt.Errorf("item %s/%s/%s: %w", k.ro, k.story, k.item, repository.ErrNotFound) } + item.Order = current.Order item.CreatedAt = current.CreatedAt item.UpdatedAt = now() - s.r.items[item.ID] = cloneItem(item) + s.r.items[k] = cloneItem(item) return nil } -func (s items) Delete(_ context.Context, id string) error { +func (s items) Delete(_ context.Context, roID, storyID, itemID string) error { s.r.mu.Lock() defer s.r.mu.Unlock() - if _, ok := s.r.items[id]; !ok { - return fmt.Errorf("item %s: %w", id, repository.ErrNotFound) + k := itemKey{roID, storyID, itemID} + if _, ok := s.r.items[k]; !ok { + return fmt.Errorf("item %s/%s/%s: %w", roID, storyID, itemID, repository.ErrNotFound) } - delete(s.r.items, id) + delete(s.r.items, k) return nil } -func (s items) ListByStory(_ context.Context, storyID string) ([]*model.Item, error) { +func (s items) ListByStory(_ context.Context, roID, storyID string) ([]*model.Item, error) { s.r.mu.RLock() defer s.r.mu.RUnlock() + return s.listLocked(roID, storyID), nil +} + +func (s items) Move(_ context.Context, roID, storyID string, itemIDs []string, beforeID string) error { + s.r.mu.Lock() + defer s.r.mu.Unlock() + order, err := repository.MoveIDs(s.idsLocked(roID, storyID), itemIDs, beforeID) + if err != nil { + return fmt.Errorf("move items in %s/%s: %w", roID, storyID, err) + } + s.setOrderLocked(roID, storyID, order) + return nil +} + +func (s items) Swap(_ context.Context, roID, storyID, itemID1, itemID2 string) error { + s.r.mu.Lock() + defer s.r.mu.Unlock() + order, err := repository.SwapIDs(s.idsLocked(roID, storyID), itemID1, itemID2) + if err != nil { + return fmt.Errorf("swap items in %s/%s: %w", roID, storyID, err) + } + s.setOrderLocked(roID, storyID, order) + return nil +} + +func (s items) ReplaceAll(_ context.Context, roID, storyID string, list []*model.Item) error { + ids := make([]string, len(list)) + for i, item := range list { + if err := checkItemKey(roID, storyID, item.ID); err != nil { + return err + } + ids[i] = item.ID + } + if err := repository.CheckDistinct(ids); err != nil { + return fmt.Errorf("replace items in %s/%s: %w", roID, storyID, err) + } + s.r.mu.Lock() + defer s.r.mu.Unlock() + if err := s.checkParentLocked(roID, storyID); err != nil { + return err + } + for k := range s.r.items { + if k.ro == roID && k.story == storyID { + delete(s.r.items, k) + } + } + for i, item := range list { + item.RunningOrderID, item.StoryID = roID, storyID + s.insertLocked(item, i) + } + return nil +} + +// insertLocked stores a new item at the given Order. The caller holds s.r.mu. +func (s items) insertLocked(item *model.Item, order int) { + t := now() + item.Order, item.CreatedAt, item.UpdatedAt = order, t, t + s.r.items[itemKey{item.RunningOrderID, item.StoryID, item.ID}] = cloneItem(item) +} + +func (s items) listLocked(roID, storyID string) []*model.Item { return sorted(s.r.items, - func(item *model.Item) bool { return item.StoryID == storyID }, + func(item *model.Item) bool { return item.RunningOrderID == roID && item.StoryID == storyID }, cloneItem, func(a, b *model.Item) int { return byOrder(a.Order, b.Order, a.ID, b.ID) }, - ), nil + ) +} + +func (s items) idsLocked(roID, storyID string) []string { + list := s.listLocked(roID, storyID) + ids := make([]string, len(list)) + for i, item := range list { + ids[i] = item.ID + } + return ids +} + +func (s items) nextOrderLocked(roID, storyID string) int { + var orders []int + for k, item := range s.r.items { + if k.ro == roID && k.story == storyID { + orders = append(orders, item.Order) + } + } + return nextOrder(orders) } -// checkParentLocked returns ErrNotFound if the item's story does not exist. -// The caller holds s.r.mu. -func (s items) checkParentLocked(item *model.Item) error { - if _, ok := s.r.stories[item.StoryID]; !ok { - return fmt.Errorf("story %s of item %s: %w", item.StoryID, item.ID, repository.ErrNotFound) +// setOrderLocked renumbers the items of a story to follow ids. +func (s items) setOrderLocked(roID, storyID string, ids []string) { + for k, item := range s.r.items { + if k.ro == roID && k.story == storyID { + item.Order = slices.Index(ids, k.item) + } + } +} + +func (s items) checkParentLocked(roID, storyID string) error { + if _, ok := s.r.stories[storyKey{roID, storyID}]; !ok { + return fmt.Errorf("story %s/%s: %w", roID, storyID, repository.ErrNotFound) } return nil } + +func checkItemKey(roID, storyID, itemID string) error { + if err := checkStoryKey(roID, storyID); err != nil { + return err + } + return repository.CheckID("item", itemID) +} diff --git a/src/internal/repository/memory/memory.go b/src/internal/repository/memory/memory.go index 8a7ea68..78701f9 100644 --- a/src/internal/repository/memory/memory.go +++ b/src/internal/repository/memory/memory.go @@ -15,23 +15,29 @@ import ( "airshift/openmos/internal/repository" ) +type storyKey struct{ ro, story string } + +type itemKey struct{ ro, story, item string } + +type objectKey struct{ mos, obj string } + // Repository holds all records behind one lock, so deletes can cascade // across record types atomically. type Repository struct { mu sync.RWMutex runningOrders map[string]*model.RunningOrder - stories map[string]*model.Story - items map[string]*model.Item - objects map[string]*model.MOSObject + stories map[storyKey]*model.Story + items map[itemKey]*model.Item + objects map[objectKey]*model.MOSObject } // New returns an empty repository. func New() *Repository { return &Repository{ runningOrders: make(map[string]*model.RunningOrder), - stories: make(map[string]*model.Story), - items: make(map[string]*model.Item), - objects: make(map[string]*model.MOSObject), + stories: make(map[storyKey]*model.Story), + items: make(map[itemKey]*model.Item), + objects: make(map[objectKey]*model.MOSObject), } } @@ -54,11 +60,11 @@ func (r *Repository) Objects() repository.ObjectRepository { return objects{r} } func now() time.Time { return time.Now().Round(0) } // deleteStoryLocked deletes a story and its items. The caller holds r.mu. -func (r *Repository) deleteStoryLocked(id string) { - delete(r.stories, id) - for itemID, item := range r.items { - if item.StoryID == id { - delete(r.items, itemID) +func (r *Repository) deleteStoryLocked(k storyKey) { + delete(r.stories, k) + for ik := range r.items { + if ik.ro == k.ro && ik.story == k.story { + delete(r.items, ik) } } } @@ -94,22 +100,17 @@ func cloneObject(o *model.MOSObject) *model.MOSObject { return &c } -// newestFirst orders by CreatedAt descending, then by ID for equal times. -func newestFirst(aCreated, bCreated time.Time, aID, bID string) int { +// newestFirst orders by CreatedAt descending, then by key for equal times. +func newestFirst(aCreated, bCreated time.Time, aKey, bKey string) int { if c := bCreated.Compare(aCreated); c != 0 { return c } - return cmp.Compare(aID, bID) -} - -// byOrder orders by Order ascending, then by ID for equal positions. -func byOrder(aOrder, bOrder int, aID, bID string) int { - return cmp.Or(cmp.Compare(aOrder, bOrder), cmp.Compare(aID, bID)) + return cmp.Compare(aKey, bKey) } // sorted returns copies of the values in m that keep accepts, sorted by // cmpFn. The caller holds r.mu. -func sorted[T any](m map[string]*T, keep func(*T) bool, clone func(*T) *T, cmpFn func(a, b *T) int) []*T { +func sorted[K comparable, T any](m map[K]*T, keep func(*T) bool, clone func(*T) *T, cmpFn func(a, b *T) int) []*T { out := make([]*T, 0) for _, v := range m { if keep(v) { @@ -119,3 +120,16 @@ func sorted[T any](m map[string]*T, keep func(*T) bool, clone func(*T) *T, cmpFn slices.SortFunc(out, cmpFn) return out } + +// byOrder sorts children by Order, then by ID. +func byOrder(aOrder, bOrder int, aID, bID string) int { + return cmp.Or(cmp.Compare(aOrder, bOrder), cmp.Compare(aID, bID)) +} + +// nextOrder returns the Order for a child appended after siblings. +func nextOrder(siblings []int) int { + if len(siblings) == 0 { + return 0 + } + return slices.Max(siblings) + 1 +} diff --git a/src/internal/repository/memory/object.go b/src/internal/repository/memory/object.go index 7652356..a53d3c3 100644 --- a/src/internal/repository/memory/object.go +++ b/src/internal/repository/memory/object.go @@ -2,7 +2,6 @@ package memory import ( "context" - "errors" "fmt" "airshift/openmos/internal/model" @@ -12,26 +11,30 @@ import ( type objects struct{ r *Repository } func (s objects) Create(_ context.Context, obj *model.MOSObject) (*model.MOSObject, error) { - if obj.ID == "" { - return nil, errors.New("object ID is required") + if err := repository.CheckID("MOS", obj.MosID); err != nil { + return nil, err + } + if err := repository.CheckID("object", obj.ID); err != nil { + return nil, err } s.r.mu.Lock() defer s.r.mu.Unlock() - if _, ok := s.r.objects[obj.ID]; ok { - return nil, fmt.Errorf("object %s: %w", obj.ID, repository.ErrAlreadyExists) + k := objectKey{obj.MosID, obj.ID} + if _, ok := s.r.objects[k]; ok { + return nil, fmt.Errorf("object %s/%s: %w", k.mos, k.obj, repository.ErrAlreadyExists) } t := now() obj.CreatedAt, obj.UpdatedAt = t, t - s.r.objects[obj.ID] = cloneObject(obj) + s.r.objects[k] = cloneObject(obj) return cloneObject(obj), nil } -func (s objects) Get(_ context.Context, id string) (*model.MOSObject, error) { +func (s objects) Get(_ context.Context, mosID, objID string) (*model.MOSObject, error) { s.r.mu.RLock() defer s.r.mu.RUnlock() - obj, ok := s.r.objects[id] + obj, ok := s.r.objects[objectKey{mosID, objID}] if !ok { - return nil, fmt.Errorf("object %s: %w", id, repository.ErrNotFound) + return nil, fmt.Errorf("object %s/%s: %w", mosID, objID, repository.ErrNotFound) } return cloneObject(obj), nil } @@ -39,23 +42,25 @@ func (s objects) Get(_ context.Context, id string) (*model.MOSObject, error) { func (s objects) Update(_ context.Context, obj *model.MOSObject) error { s.r.mu.Lock() defer s.r.mu.Unlock() - current, ok := s.r.objects[obj.ID] + k := objectKey{obj.MosID, obj.ID} + current, ok := s.r.objects[k] if !ok { - return fmt.Errorf("object %s: %w", obj.ID, repository.ErrNotFound) + return fmt.Errorf("object %s/%s: %w", k.mos, k.obj, repository.ErrNotFound) } obj.CreatedAt = current.CreatedAt obj.UpdatedAt = now() - s.r.objects[obj.ID] = cloneObject(obj) + s.r.objects[k] = cloneObject(obj) return nil } -func (s objects) Delete(_ context.Context, id string) error { +func (s objects) Delete(_ context.Context, mosID, objID string) error { s.r.mu.Lock() defer s.r.mu.Unlock() - if _, ok := s.r.objects[id]; !ok { - return fmt.Errorf("object %s: %w", id, repository.ErrNotFound) + k := objectKey{mosID, objID} + if _, ok := s.r.objects[k]; !ok { + return fmt.Errorf("object %s/%s: %w", mosID, objID, repository.ErrNotFound) } - delete(s.r.objects, id) + delete(s.r.objects, k) return nil } @@ -65,6 +70,8 @@ func (s objects) List(_ context.Context) ([]*model.MOSObject, error) { return sorted(s.r.objects, func(*model.MOSObject) bool { return true }, cloneObject, - func(a, b *model.MOSObject) int { return newestFirst(a.CreatedAt, b.CreatedAt, a.ID, b.ID) }, + func(a, b *model.MOSObject) int { + return newestFirst(a.CreatedAt, b.CreatedAt, a.MosID+"/"+a.ID, b.MosID+"/"+b.ID) + }, ), nil } diff --git a/src/internal/repository/memory/runningorder.go b/src/internal/repository/memory/runningorder.go index 24eba17..f0b7a9c 100644 --- a/src/internal/repository/memory/runningorder.go +++ b/src/internal/repository/memory/runningorder.go @@ -2,7 +2,6 @@ package memory import ( "context" - "errors" "fmt" "airshift/openmos/internal/model" @@ -12,8 +11,8 @@ import ( type runningOrders struct{ r *Repository } func (s runningOrders) Create(_ context.Context, ro *model.RunningOrder) (*model.RunningOrder, error) { - if ro.ID == "" { - return nil, errors.New("running order ID is required") + if err := repository.CheckID("running order", ro.ID); err != nil { + return nil, err } s.r.mu.Lock() defer s.r.mu.Unlock() @@ -26,12 +25,12 @@ func (s runningOrders) Create(_ context.Context, ro *model.RunningOrder) (*model return cloneRunningOrder(ro), nil } -func (s runningOrders) Get(_ context.Context, id string) (*model.RunningOrder, error) { +func (s runningOrders) Get(_ context.Context, roID string) (*model.RunningOrder, error) { s.r.mu.RLock() defer s.r.mu.RUnlock() - ro, ok := s.r.runningOrders[id] + ro, ok := s.r.runningOrders[roID] if !ok { - return nil, fmt.Errorf("running order %s: %w", id, repository.ErrNotFound) + return nil, fmt.Errorf("running order %s: %w", roID, repository.ErrNotFound) } return cloneRunningOrder(ro), nil } @@ -54,16 +53,16 @@ func (s runningOrders) Update(_ context.Context, ro *model.RunningOrder) error { return nil } -func (s runningOrders) Delete(_ context.Context, id string) error { +func (s runningOrders) Delete(_ context.Context, roID string) error { s.r.mu.Lock() defer s.r.mu.Unlock() - if _, ok := s.r.runningOrders[id]; !ok { - return fmt.Errorf("running order %s: %w", id, repository.ErrNotFound) + if _, ok := s.r.runningOrders[roID]; !ok { + return fmt.Errorf("running order %s: %w", roID, repository.ErrNotFound) } - delete(s.r.runningOrders, id) - for storyID, story := range s.r.stories { - if story.RunningOrderID == id { - s.r.deleteStoryLocked(storyID) + delete(s.r.runningOrders, roID) + for k := range s.r.stories { + if k.ro == roID { + s.r.deleteStoryLocked(k) } } return nil diff --git a/src/internal/repository/memory/story.go b/src/internal/repository/memory/story.go index 7f84988..9688020 100644 --- a/src/internal/repository/memory/story.go +++ b/src/internal/repository/memory/story.go @@ -2,8 +2,8 @@ package memory import ( "context" - "errors" "fmt" + "slices" "airshift/openmos/internal/model" "airshift/openmos/internal/repository" @@ -12,29 +12,28 @@ import ( type stories struct{ r *Repository } func (s stories) Create(_ context.Context, story *model.Story) (*model.Story, error) { - if story.ID == "" { - return nil, errors.New("story ID is required") + if err := checkStoryKey(story.RunningOrderID, story.ID); err != nil { + return nil, err } s.r.mu.Lock() defer s.r.mu.Unlock() - if _, ok := s.r.stories[story.ID]; ok { - return nil, fmt.Errorf("story %s: %w", story.ID, repository.ErrAlreadyExists) + k := storyKey{story.RunningOrderID, story.ID} + if _, ok := s.r.stories[k]; ok { + return nil, fmt.Errorf("story %s/%s: %w", k.ro, k.story, repository.ErrAlreadyExists) } - if err := s.checkParentLocked(story); err != nil { + if err := s.checkParentLocked(k.ro); err != nil { return nil, err } - t := now() - story.CreatedAt, story.UpdatedAt = t, t - s.r.stories[story.ID] = cloneStory(story) + s.insertLocked(story, s.nextOrderLocked(k.ro)) return cloneStory(story), nil } -func (s stories) Get(_ context.Context, id string) (*model.Story, error) { +func (s stories) Get(_ context.Context, roID, storyID string) (*model.Story, error) { s.r.mu.RLock() defer s.r.mu.RUnlock() - story, ok := s.r.stories[id] + story, ok := s.r.stories[storyKey{roID, storyID}] if !ok { - return nil, fmt.Errorf("story %s: %w", id, repository.ErrNotFound) + return nil, fmt.Errorf("story %s/%s: %w", roID, storyID, repository.ErrNotFound) } return cloneStory(story), nil } @@ -42,45 +41,138 @@ func (s stories) Get(_ context.Context, id string) (*model.Story, error) { func (s stories) Update(_ context.Context, story *model.Story) error { s.r.mu.Lock() defer s.r.mu.Unlock() - current, ok := s.r.stories[story.ID] + k := storyKey{story.RunningOrderID, story.ID} + current, ok := s.r.stories[k] if !ok { - return fmt.Errorf("story %s: %w", story.ID, repository.ErrNotFound) - } - if err := s.checkParentLocked(story); err != nil { - return err + return fmt.Errorf("story %s/%s: %w", k.ro, k.story, repository.ErrNotFound) } + story.Order = current.Order story.CreatedAt = current.CreatedAt story.UpdatedAt = now() - s.r.stories[story.ID] = cloneStory(story) + s.r.stories[k] = cloneStory(story) return nil } -func (s stories) Delete(_ context.Context, id string) error { +func (s stories) Delete(_ context.Context, roID, storyID string) error { s.r.mu.Lock() defer s.r.mu.Unlock() - if _, ok := s.r.stories[id]; !ok { - return fmt.Errorf("story %s: %w", id, repository.ErrNotFound) + k := storyKey{roID, storyID} + if _, ok := s.r.stories[k]; !ok { + return fmt.Errorf("story %s/%s: %w", roID, storyID, repository.ErrNotFound) } - s.r.deleteStoryLocked(id) + s.r.deleteStoryLocked(k) return nil } func (s stories) ListByRunningOrder(_ context.Context, roID string) ([]*model.Story, error) { s.r.mu.RLock() defer s.r.mu.RUnlock() + return s.listLocked(roID), nil +} + +func (s stories) Move(_ context.Context, roID string, storyIDs []string, beforeID string) error { + s.r.mu.Lock() + defer s.r.mu.Unlock() + order, err := repository.MoveIDs(s.idsLocked(roID), storyIDs, beforeID) + if err != nil { + return fmt.Errorf("move stories in %s: %w", roID, err) + } + s.setOrderLocked(roID, order) + return nil +} + +func (s stories) Swap(_ context.Context, roID, storyID1, storyID2 string) error { + s.r.mu.Lock() + defer s.r.mu.Unlock() + order, err := repository.SwapIDs(s.idsLocked(roID), storyID1, storyID2) + if err != nil { + return fmt.Errorf("swap stories in %s: %w", roID, err) + } + s.setOrderLocked(roID, order) + return nil +} + +func (s stories) ReplaceAll(_ context.Context, roID string, list []*model.Story) error { + ids := make([]string, len(list)) + for i, story := range list { + if err := checkStoryKey(roID, story.ID); err != nil { + return err + } + ids[i] = story.ID + } + if err := repository.CheckDistinct(ids); err != nil { + return fmt.Errorf("replace stories in %s: %w", roID, err) + } + s.r.mu.Lock() + defer s.r.mu.Unlock() + if err := s.checkParentLocked(roID); err != nil { + return err + } + for k := range s.r.stories { + if k.ro == roID { + s.r.deleteStoryLocked(k) + } + } + for i, story := range list { + story.RunningOrderID = roID + s.insertLocked(story, i) + } + return nil +} + +// insertLocked stores a new story at the given Order. The caller holds s.r.mu. +func (s stories) insertLocked(story *model.Story, order int) { + t := now() + story.Order, story.CreatedAt, story.UpdatedAt = order, t, t + s.r.stories[storyKey{story.RunningOrderID, story.ID}] = cloneStory(story) +} + +func (s stories) listLocked(roID string) []*model.Story { return sorted(s.r.stories, func(story *model.Story) bool { return story.RunningOrderID == roID }, cloneStory, func(a, b *model.Story) int { return byOrder(a.Order, b.Order, a.ID, b.ID) }, - ), nil + ) +} + +func (s stories) idsLocked(roID string) []string { + list := s.listLocked(roID) + ids := make([]string, len(list)) + for i, story := range list { + ids[i] = story.ID + } + return ids +} + +func (s stories) nextOrderLocked(roID string) int { + var orders []int + for k, story := range s.r.stories { + if k.ro == roID { + orders = append(orders, story.Order) + } + } + return nextOrder(orders) } -// checkParentLocked returns ErrNotFound if the story's running order does -// not exist. The caller holds s.r.mu. -func (s stories) checkParentLocked(story *model.Story) error { - if _, ok := s.r.runningOrders[story.RunningOrderID]; !ok { - return fmt.Errorf("running order %s of story %s: %w", - story.RunningOrderID, story.ID, repository.ErrNotFound) +// setOrderLocked renumbers the stories of roID to follow ids. +func (s stories) setOrderLocked(roID string, ids []string) { + for k, story := range s.r.stories { + if k.ro == roID { + story.Order = slices.Index(ids, k.story) + } + } +} + +func (s stories) checkParentLocked(roID string) error { + if _, ok := s.r.runningOrders[roID]; !ok { + return fmt.Errorf("running order %s: %w", roID, repository.ErrNotFound) } return nil } + +func checkStoryKey(roID, storyID string) error { + if err := repository.CheckID("running order", roID); err != nil { + return err + } + return repository.CheckID("story", storyID) +} diff --git a/src/internal/repository/order.go b/src/internal/repository/order.go new file mode 100644 index 0000000..bc927fa --- /dev/null +++ b/src/internal/repository/order.go @@ -0,0 +1,104 @@ +package repository + +import "fmt" + +// MaxIDLength is the MOS limit for roID, storyID, itemID, objID and mosID. +const MaxIDLength = 128 + +// CheckID returns ErrInvalid unless id is a usable MOS ID. +func CheckID(kind, id string) error { + if id == "" { + return fmt.Errorf("%s ID is required: %w", kind, ErrInvalid) + } + if len([]rune(id)) > MaxIDLength { + return fmt.Errorf("%s ID longer than %d characters: %w", kind, MaxIDLength, ErrInvalid) + } + return nil +} + +// The ordering helpers below compute a new order of child IDs (stories in a +// running order, items in a story). Both implementations use them, so Move, +// Swap and ReplaceAll behave the same everywhere. + +// MoveIDs returns order with ids moved, in the given order, to just before +// the ID before. An empty before moves them to the end. The other IDs keep +// their relative order. +func MoveIDs(order, ids []string, before string) ([]string, error) { + if len(ids) == 0 { + return nil, fmt.Errorf("move needs at least one ID: %w", ErrInvalid) + } + if err := CheckDistinct(ids); err != nil { + return nil, err + } + present := make(map[string]bool, len(order)) + for _, id := range order { + present[id] = true + } + moving := make(map[string]bool, len(ids)) + for _, id := range ids { + if !present[id] { + return nil, fmt.Errorf("%s: %w", id, ErrNotFound) + } + moving[id] = true + } + if before != "" { + if moving[before] { + return nil, fmt.Errorf("cannot move %s before itself: %w", before, ErrInvalid) + } + if !present[before] { + return nil, fmt.Errorf("%s: %w", before, ErrNotFound) + } + } + + out := make([]string, 0, len(order)) + for _, id := range order { + if moving[id] { + continue + } + if id == before { + out = append(out, ids...) + } + out = append(out, id) + } + if before == "" { + out = append(out, ids...) + } + return out, nil +} + +// SwapIDs returns order with a and b exchanged. +func SwapIDs(order []string, a, b string) ([]string, error) { + if a == b { + return nil, fmt.Errorf("cannot swap %s with itself: %w", a, ErrInvalid) + } + ia, ib := -1, -1 + for i, id := range order { + switch id { + case a: + ia = i + case b: + ib = i + } + } + if ia < 0 { + return nil, fmt.Errorf("%s: %w", a, ErrNotFound) + } + if ib < 0 { + return nil, fmt.Errorf("%s: %w", b, ErrNotFound) + } + out := append([]string(nil), order...) + out[ia], out[ib] = out[ib], out[ia] + return out, nil +} + +// CheckDistinct returns ErrInvalid if an ID appears more than once. +func CheckDistinct(ids []string) error { + seen := make(map[string]bool, len(ids)) + for _, id := range ids { + if seen[id] { + return fmt.Errorf("%s listed twice: %w", id, ErrInvalid) + } + seen[id] = true + } + return nil +} diff --git a/src/internal/repository/order_test.go b/src/internal/repository/order_test.go new file mode 100644 index 0000000..800116a --- /dev/null +++ b/src/internal/repository/order_test.go @@ -0,0 +1,98 @@ +package repository + +import ( + "errors" + "slices" + "strings" + "testing" +) + +func TestCheckID(t *testing.T) { + for _, tc := range []struct { + id string + want error + }{ + {"a", nil}, + {strings.Repeat("x", MaxIDLength), nil}, + {strings.Repeat("ä", MaxIDLength), nil}, // counted in characters + {"", ErrInvalid}, + {strings.Repeat("x", MaxIDLength+1), ErrInvalid}, + } { + if err := CheckID("story", tc.id); !errors.Is(err, tc.want) || (tc.want == nil) != (err == nil) { + t.Errorf("CheckID(%d characters) = %v, want %v", len([]rune(tc.id)), err, tc.want) + } + } +} + +func TestMoveIDs(t *testing.T) { + order := []string{"a", "b", "c", "d", "e"} + for _, tc := range []struct { + ids []string + before string + want []string + err error + }{ + {ids: []string{"d"}, before: "a", want: []string{"d", "a", "b", "c", "e"}}, + {ids: []string{"a"}, before: "", want: []string{"b", "c", "d", "e", "a"}}, + {ids: []string{"e"}, before: "", want: []string{"a", "b", "c", "d", "e"}}, + {ids: []string{"a"}, before: "b", want: []string{"a", "b", "c", "d", "e"}}, + // Moved IDs keep the order given, not their original order + {ids: []string{"e", "a"}, before: "c", want: []string{"b", "e", "a", "c", "d"}}, + {ids: []string{"b", "d"}, before: "", want: []string{"a", "c", "e", "b", "d"}}, + {ids: nil, before: "a", err: ErrInvalid}, + {ids: []string{"a", "a"}, before: "c", err: ErrInvalid}, + {ids: []string{"a", "b"}, before: "a", err: ErrInvalid}, + {ids: []string{"x"}, before: "a", err: ErrNotFound}, + {ids: []string{"a"}, before: "x", err: ErrNotFound}, + } { + in := slices.Clone(order) + got, err := MoveIDs(in, tc.ids, tc.before) + if !slices.Equal(in, order) { + t.Errorf("MoveIDs(%v, %q) changed its input to %v", tc.ids, tc.before, in) + } + if tc.err != nil { + if !errors.Is(err, tc.err) { + t.Errorf("MoveIDs(%v, %q) err = %v, want %v", tc.ids, tc.before, err, tc.err) + } + continue + } + if err != nil || !slices.Equal(got, tc.want) { + t.Errorf("MoveIDs(%v, %q) = %v, %v; want %v", tc.ids, tc.before, got, err, tc.want) + } + } +} + +func TestSwapIDs(t *testing.T) { + order := []string{"a", "b", "c"} + got, err := SwapIDs(order, "c", "a") + if err != nil || !slices.Equal(got, []string{"c", "b", "a"}) { + t.Errorf("SwapIDs(c, a) = %v, %v; want [c b a]", got, err) + } + if !slices.Equal(order, []string{"a", "b", "c"}) { + t.Errorf("SwapIDs changed its input to %v", order) + } + for _, tc := range []struct { + a, b string + err error + }{ + {"a", "a", ErrInvalid}, + {"a", "x", ErrNotFound}, + {"x", "a", ErrNotFound}, + } { + if _, err := SwapIDs(order, tc.a, tc.b); !errors.Is(err, tc.err) { + t.Errorf("SwapIDs(%s, %s) err = %v, want %v", tc.a, tc.b, err, tc.err) + } + } +} + +func TestCheckDistinct(t *testing.T) { + if err := CheckDistinct([]string{"a", "b"}); err != nil { + t.Errorf("CheckDistinct(a, b) = %v, want nil", err) + } + if err := CheckDistinct(nil); err != nil { + t.Errorf("CheckDistinct(nil) = %v, want nil", err) + } + if err := CheckDistinct([]string{"a", "b", "a"}); !errors.Is(err, ErrInvalid) { + t.Errorf("CheckDistinct(a, b, a) = %v, want %v", err, ErrInvalid) + } +} diff --git a/src/internal/repository/repository.go b/src/internal/repository/repository.go index 18a3afc..db2af65 100644 --- a/src/internal/repository/repository.go +++ b/src/internal/repository/repository.go @@ -3,19 +3,31 @@ // The behaviour every implementation must provide is specified by the // contract suite in package repotest: // -// - Create requires an ID, sets CreatedAt and UpdatedAt, and returns -// ErrAlreadyExists for an ID in use. Stories and items require their -// parent to exist, otherwise ErrNotFound. -// - Get, Update and Delete return ErrNotFound for a missing ID. -// - Update sets UpdatedAt. Running orders are versioned: Create sets -// Version to 1, and Update succeeds only if the passed Version equals the -// stored one, then increments it (also on the passed value). A stale -// Version returns ErrVersionConflict and changes nothing. +// - Keys follow MOS: a running order by roID, a story by (roID, storyID), +// an item by (roID, storyID, itemID) and an object by (mosID, objID). A +// story or item ID is unique only within its parent. +// - Create requires non-empty IDs of at most 128 characters (otherwise +// ErrInvalid), sets CreatedAt and UpdatedAt, and returns ErrAlreadyExists +// for a key in use. Stories and items require their parent to exist, +// otherwise ErrNotFound. +// - Get, Update and Delete return ErrNotFound for a missing key. +// - Update sets UpdatedAt and keeps CreatedAt. Running orders are +// versioned: Create sets Version to 1, and Update succeeds only if the +// passed Version equals the stored one, then increments it (also on the +// passed value). A stale Version returns ErrVersionConflict and changes +// nothing. +// - Order is managed by the repository: Create appends a story or item +// after its siblings, Update ignores Order, and Move, Swap and +// ReplaceAll change it. Listing returns children by Order, ascending. +// Ordering requests that name a record twice return ErrInvalid; unknown +// records return ErrNotFound. See MoveIDs and SwapIDs. // - Deleting a running order deletes its stories and their items; deleting -// a story deletes its items. MOS objects are independent. -// - List returns running orders and objects newest first. Stories and items -// are listed by Order, ascending. Listing an unknown parent returns an -// empty result, not an error. +// a story deletes its items. ReplaceAll deletes all existing children +// with their items, then creates the given ones under the parent named +// in the call (their own parent IDs are overwritten), as roReplace +// replaces the whole running order. MOS objects are independent. +// - List returns running orders and objects newest first. Listing the +// children of an unknown parent returns an empty result, not an error. // - Returned values are copies: changing them does not change stored data. package repository @@ -30,53 +42,75 @@ type RunningOrderRepository interface { // Create creates a new running order Create(ctx context.Context, ro *model.RunningOrder) (*model.RunningOrder, error) - // Get retrieves a running order by ID - Get(ctx context.Context, id string) (*model.RunningOrder, error) + // Get retrieves a running order by roID + Get(ctx context.Context, roID string) (*model.RunningOrder, error) // Update updates a running order, checking its version Update(ctx context.Context, ro *model.RunningOrder) error // Delete deletes a running order with its stories and items - Delete(ctx context.Context, id string) error + Delete(ctx context.Context, roID string) error // List returns all running orders, newest first List(ctx context.Context) ([]*model.RunningOrder, error) } -// StoryRepository defines operations for stories +// StoryRepository defines operations for the stories of a running order type StoryRepository interface { - // Create creates a new story in an existing running order + // Create appends a new story to its running order Create(ctx context.Context, story *model.Story) (*model.Story, error) - // Get retrieves a story by ID - Get(ctx context.Context, id string) (*model.Story, error) + // Get retrieves a story by its running order and storyID + Get(ctx context.Context, roID, storyID string) (*model.Story, error) - // Update updates a story + // Update updates a story's fields; its Order is not changed Update(ctx context.Context, story *model.Story) error // Delete deletes a story with its items - Delete(ctx context.Context, id string) error + Delete(ctx context.Context, roID, storyID string) error // ListByRunningOrder returns the stories of a running order by Order ListByRunningOrder(ctx context.Context, roID string) ([]*model.Story, error) + + // Move moves the stories, in the given order, to just before beforeID; + // an empty beforeID moves them to the end (roStoryMove) + Move(ctx context.Context, roID string, storyIDs []string, beforeID string) error + + // Swap exchanges the positions of two stories (roStorySwap) + Swap(ctx context.Context, roID, storyID1, storyID2 string) error + + // ReplaceAll replaces all stories of a running order with the given + // ones, in that order (roCreate or roReplace on an existing order) + ReplaceAll(ctx context.Context, roID string, stories []*model.Story) error } -// ItemRepository defines operations for items +// ItemRepository defines operations for the items of a story type ItemRepository interface { - // Create creates a new item in an existing story + // Create appends a new item to its story Create(ctx context.Context, item *model.Item) (*model.Item, error) - // Get retrieves an item by ID - Get(ctx context.Context, id string) (*model.Item, error) + // Get retrieves an item by its running order, story and itemID + Get(ctx context.Context, roID, storyID, itemID string) (*model.Item, error) - // Update updates an item + // Update updates an item's fields; its Order is not changed Update(ctx context.Context, item *model.Item) error // Delete deletes an item - Delete(ctx context.Context, id string) error + Delete(ctx context.Context, roID, storyID, itemID string) error // ListByStory returns the items of a story by Order - ListByStory(ctx context.Context, storyID string) ([]*model.Item, error) + ListByStory(ctx context.Context, roID, storyID string) ([]*model.Item, error) + + // Move moves the items, in the given order, to just before beforeID; + // an empty beforeID moves them to the end (roItemMove) + Move(ctx context.Context, roID, storyID string, itemIDs []string, beforeID string) error + + // Swap exchanges the positions of two items (roItemSwap) + Swap(ctx context.Context, roID, storyID, itemID1, itemID2 string) error + + // ReplaceAll replaces all items of a story with the given ones, in that + // order + ReplaceAll(ctx context.Context, roID, storyID string, items []*model.Item) error } // ObjectRepository defines operations for MOS objects @@ -84,14 +118,14 @@ type ObjectRepository interface { // Create creates a new MOS object Create(ctx context.Context, obj *model.MOSObject) (*model.MOSObject, error) - // Get retrieves a MOS object by ID - Get(ctx context.Context, id string) (*model.MOSObject, error) + // Get retrieves a MOS object by its MOS device and objID + Get(ctx context.Context, mosID, objID string) (*model.MOSObject, error) // Update updates a MOS object Update(ctx context.Context, obj *model.MOSObject) error // Delete deletes a MOS object - Delete(ctx context.Context, id string) error + Delete(ctx context.Context, mosID, objID string) error // List returns all MOS objects, newest first List(ctx context.Context) ([]*model.MOSObject, error) diff --git a/src/internal/repository/repotest/cascade.go b/src/internal/repository/repotest/cascade.go index 0ec4750..ac9b97a 100644 --- a/src/internal/repository/repotest/cascade.go +++ b/src/internal/repository/repotest/cascade.go @@ -1,86 +1,91 @@ package repotest import ( + "errors" + "strings" "testing" + "airshift/openmos/internal/model" "airshift/openmos/internal/repository" ) func testCascade(t *testing.T, newRepo Factory) { - // setup creates two running orders with stories and items, and an object: + // setup creates two running orders with stories and items, and an + // object. Story s1 exists in both running orders. // // ro-1: s1 (i1, i2), s2 (i3) - // ro-2: s3 (i4) - // obj-1 + // ro-2: s1 (i1) + // test.mos/obj-1 setup := func(t *testing.T) repository.Repository { r := newRepo(t) createRunningOrder(t, r, "ro-1") createRunningOrder(t, r, "ro-2") - createStory(t, r, "s1", "ro-1", 1) - createStory(t, r, "s2", "ro-1", 2) - createStory(t, r, "s3", "ro-2", 1) - createItem(t, r, "i1", "s1", 1) - createItem(t, r, "i2", "s1", 2) - createItem(t, r, "i3", "s2", 1) - createItem(t, r, "i4", "s3", 1) - createObject(t, r, "obj-1") + createStory(t, r, "ro-1", "s1") + createStory(t, r, "ro-1", "s2") + createStory(t, r, "ro-2", "s1") + createItem(t, r, "ro-1", "s1", "i1") + createItem(t, r, "ro-1", "s1", "i2") + createItem(t, r, "ro-1", "s2", "i3") + createItem(t, r, "ro-2", "s1", "i1") + createObject(t, r, testMOS, "obj-1") return r } + all := []string{"ro-1", "ro-2", "ro-1/s1", "ro-1/s2", "ro-2/s1", + "ro-1/s1/i1", "ro-1/s1/i2", "ro-1/s2/i3", "ro-2/s1/i1"} t.Run("DeleteRunningOrder", func(t *testing.T) { r := setup(t) must(t, "Delete ro-1", r.RunningOrders().Delete(t.Context(), "ro-1")) - - gone(t, r, []string{"s1", "s2"}, []string{"i1", "i2", "i3"}) - kept(t, r, []string{"ro-2"}, []string{"s3"}, []string{"i4"}, []string{"obj-1"}) + exist(t, r, all, "ro-2", "ro-2/s1", "ro-2/s1/i1") }) t.Run("DeleteStory", func(t *testing.T) { r := setup(t) - must(t, "Delete s1", r.Stories().Delete(t.Context(), "s1")) + must(t, "Delete ro-1/s1", r.Stories().Delete(t.Context(), "ro-1", "s1")) + exist(t, r, all, "ro-1", "ro-2", "ro-1/s2", "ro-2/s1", "ro-1/s2/i3", "ro-2/s1/i1") + }) - gone(t, r, []string{"s1"}, []string{"i1", "i2"}) - kept(t, r, []string{"ro-1", "ro-2"}, []string{"s2", "s3"}, []string{"i3", "i4"}, []string{"obj-1"}) + t.Run("ReplaceAllStories", func(t *testing.T) { + r := setup(t) + // s1 comes back, but without its items + must(t, "ReplaceAll stories of ro-1", r.Stories().ReplaceAll(t.Context(), "ro-1", + []*model.Story{newStory("ro-1", "s1"), newStory("ro-1", "s9")})) + exist(t, r, append(all, "ro-1/s9"), "ro-1", "ro-2", "ro-1/s1", "ro-1/s9", "ro-2/s1", "ro-2/s1/i1") }) -} -// gone fails the test unless the stories and items no longer exist. -func gone(t *testing.T, r repository.Repository, stories, items []string) { - t.Helper() - for _, id := range stories { - _, err := r.Stories().Get(t.Context(), id) - wantErr(t, "Get story "+id, err, repository.ErrNotFound) - } - for _, id := range items { - _, err := r.Items().Get(t.Context(), id) - wantErr(t, "Get item "+id, err, repository.ErrNotFound) - } + t.Run("ObjectsAreIndependent", func(t *testing.T) { + r := setup(t) + must(t, "Delete ro-1", r.RunningOrders().Delete(t.Context(), "ro-1")) + must(t, "Delete ro-2", r.RunningOrders().Delete(t.Context(), "ro-2")) + _, err := r.Objects().Get(t.Context(), testMOS, "obj-1") + must(t, "Get object after deleting all running orders", err) + }) } -// kept fails the test unless all the given records still exist. -func kept(t *testing.T, r repository.Repository, ros, stories, items, objects []string) { +// exist fails the test unless, of the records named by paths ("ro", +// "ro/story" or "ro/story/item"), exactly those in want exist. +func exist(t *testing.T, r repository.Repository, paths []string, want ...string) { t.Helper() ctx := t.Context() - check := func(what, id string, err error) { - t.Helper() - if err != nil { - t.Errorf("Get %s %s: %v, want it kept", what, id, err) + for _, p := range paths { + var err error + switch k := strings.Split(p, "/"); len(k) { + case 1: + _, err = r.RunningOrders().Get(ctx, k[0]) + case 2: + _, err = r.Stories().Get(ctx, k[0], k[1]) + default: + _, err = r.Items().Get(ctx, k[0], k[1], k[2]) + } + kept := false + for _, w := range want { + kept = kept || w == p + } + switch { + case kept && err != nil: + t.Errorf("Get %s: %v, want it kept", p, err) + case !kept && !errors.Is(err, repository.ErrNotFound): + t.Errorf("Get %s: err = %v, want %v", p, err, repository.ErrNotFound) } - } - for _, id := range ros { - _, err := r.RunningOrders().Get(ctx, id) - check("running order", id, err) - } - for _, id := range stories { - _, err := r.Stories().Get(ctx, id) - check("story", id, err) - } - for _, id := range items { - _, err := r.Items().Get(ctx, id) - check("item", id, err) - } - for _, id := range objects { - _, err := r.Objects().Get(ctx, id) - check("object", id, err) } } diff --git a/src/internal/repository/repotest/children.go b/src/internal/repository/repotest/children.go index 35b969d..2670359 100644 --- a/src/internal/repository/repotest/children.go +++ b/src/internal/repository/repotest/children.go @@ -9,70 +9,61 @@ import ( func testStories(t *testing.T, newRepo Factory) { t.Run("CreateRequiresRunningOrder", func(t *testing.T) { r := newRepo(t) - _, err := r.Stories().Create(t.Context(), newStory("s1", "missing", 1)) + _, err := r.Stories().Create(t.Context(), newStory("missing", "s1")) wantErr(t, "Create story without running order", err, repository.ErrNotFound) }) - t.Run("ListByRunningOrder", func(t *testing.T) { - r := newRepo(t) + // A storyID is unique only within its running order + t.Run("KeyIncludesRunningOrder", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() createRunningOrder(t, r, "ro-1") createRunningOrder(t, r, "ro-2") - // Created out of order, so the list must follow Order, not insertion - createStory(t, r, "s3", "ro-1", 3) - createStory(t, r, "s1", "ro-1", 1) - createStory(t, r, "s2", "ro-1", 2) - createStory(t, r, "other", "ro-2", 1) + createStory(t, r, "ro-1", "s") + createStory(t, r, "ro-2", "s") - list := func(roID string) []string { - t.Helper() - stories, err := r.Stories().ListByRunningOrder(t.Context(), roID) - must(t, "ListByRunningOrder "+roID, err) - return storyKind.ids(stories) + s, err := r.Stories().Get(ctx, "ro-1", "s") + must(t, "Get ro-1/s", err) + s.Slug = "changed in ro-1" + must(t, "Update ro-1/s", r.Stories().Update(ctx, s)) + other, err := r.Stories().Get(ctx, "ro-2", "s") + must(t, "Get ro-2/s", err) + if other.Slug != "slug s" { + t.Errorf("updating ro-1/s changed ro-2/s: slug %q", other.Slug) } - equalIDs(t, "ro-1", list("ro-1"), []string{"s1", "s2", "s3"}) - equalIDs(t, "ro-2", list("ro-2"), []string{"other"}) - equalIDs(t, "unknown running order", list("missing"), nil) - // Moving a story first must reorder the list - s3, err := r.Stories().Get(t.Context(), "s3") - must(t, "Get s3", err) - s3.Order = 0 - must(t, "Update s3", r.Stories().Update(t.Context(), s3)) - equalIDs(t, "ro-1 after move", list("ro-1"), []string{"s3", "s1", "s2"}) + must(t, "Delete ro-1/s", r.Stories().Delete(ctx, "ro-1", "s")) + _, err = r.Stories().Get(ctx, "ro-2", "s") + must(t, "Get ro-2/s after deleting ro-1/s", err) + _, err = r.Stories().Get(ctx, "ro-3", "s") + wantErr(t, "Get s in an unknown running order", err, repository.ErrNotFound) }) } func testItems(t *testing.T, newRepo Factory) { t.Run("CreateRequiresStory", func(t *testing.T) { r := newRepo(t) - _, err := r.Items().Create(t.Context(), newItem("i1", "missing", 1)) + createRunningOrder(t, r, "ro-1") + _, err := r.Items().Create(t.Context(), newItem("ro-1", "missing", "i1")) wantErr(t, "Create item without story", err, repository.ErrNotFound) }) - t.Run("ListByStory", func(t *testing.T) { - r := newRepo(t) + // An itemID is unique only within its story, and a storyID only within + // its running order + t.Run("KeyIncludesStoryAndRunningOrder", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() createRunningOrder(t, r, "ro-1") - createStory(t, r, "s1", "ro-1", 1) - createStory(t, r, "s2", "ro-1", 2) - createItem(t, r, "i3", "s1", 3) - createItem(t, r, "i1", "s1", 1) - createItem(t, r, "i2", "s1", 2) - createItem(t, r, "other", "s2", 1) - - list := func(storyID string) []string { - t.Helper() - items, err := r.Items().ListByStory(t.Context(), storyID) - must(t, "ListByStory "+storyID, err) - return itemKind.ids(items) + createRunningOrder(t, r, "ro-2") + createStory(t, r, "ro-1", "s1") + createStory(t, r, "ro-1", "s2") + createStory(t, r, "ro-2", "s1") + for _, k := range [][2]string{{"ro-1", "s1"}, {"ro-1", "s2"}, {"ro-2", "s1"}} { + createItem(t, r, k[0], k[1], "i") } - equalIDs(t, "s1", list("s1"), []string{"i1", "i2", "i3"}) - equalIDs(t, "s2", list("s2"), []string{"other"}) - equalIDs(t, "unknown story", list("missing"), nil) - i3, err := r.Items().Get(t.Context(), "i3") - must(t, "Get i3", err) - i3.Order = 0 - must(t, "Update i3", r.Items().Update(t.Context(), i3)) - equalIDs(t, "s1 after move", list("s1"), []string{"i3", "i1", "i2"}) + must(t, "Delete ro-1/s1/i", r.Items().Delete(ctx, "ro-1", "s1", "i")) + for _, k := range [][2]string{{"ro-1", "s2"}, {"ro-2", "s1"}} { + _, err := r.Items().Get(ctx, k[0], k[1], "i") + must(t, "Get "+k[0]+"/"+k[1]+"/i after deleting ro-1/s1/i", err) + } }) } diff --git a/src/internal/repository/repotest/crud.go b/src/internal/repository/repotest/crud.go index 92a6ff1..5f912d2 100644 --- a/src/internal/repository/repotest/crud.go +++ b/src/internal/repository/repotest/crud.go @@ -1,7 +1,7 @@ package repotest import ( - "context" + "strings" "testing" "time" @@ -11,16 +11,17 @@ import ( // testCRUD runs the tests every record type must pass. func testCRUD[T any](t *testing.T, newRepo Factory, k kind[T]) { // setup returns a fresh repository with the fixture's parents in place. - setup := func(t *testing.T) (context.Context, crud[T]) { - repo := newRepo(t) - k.parents(t, repo) - return t.Context(), k.repo(repo) + setup := func(t *testing.T) repository.Repository { + r := newRepo(t) + k.parents(t, r) + return r } + key := k.fixture // a fixture carries the full key of the record t.Run("CreateAndGet", func(t *testing.T) { - ctx, r := setup(t) + r, ctx := setup(t), t.Context() before := time.Now() - created, err := r.Create(ctx, k.fixture("a")) + created, err := k.create(ctx, r, k.fixture("a")) after := time.Now() must(t, "Create", err) c := k.fields(created) @@ -30,7 +31,7 @@ func testCRUD[T any](t *testing.T, newRepo Factory, k kind[T]) { } k.same(t, "Create result", created, k.fixture("a")) - got, err := r.Get(ctx, "a") + got, err := k.get(ctx, r, key("a")) must(t, "Get", err) k.same(t, "Get after Create", got, k.fixture("a")) if g := k.fields(got); !closeTo(*g.CreatedAt, *c.CreatedAt) || !closeTo(*g.UpdatedAt, *c.UpdatedAt) { @@ -38,46 +39,65 @@ func testCRUD[T any](t *testing.T, newRepo Factory, k kind[T]) { } }) - t.Run("CreateRequiresID", func(t *testing.T) { - ctx, r := setup(t) - if _, err := r.Create(ctx, k.fixture("")); err == nil { - t.Error("Create with empty ID succeeded, want error") + // Unknown values (zero durations and time bases, empty types, no + // metadata) must round-trip as such + t.Run("CreateMinimal", func(t *testing.T) { + r, ctx := setup(t), t.Context() + created, err := k.create(ctx, r, k.minimal("a")) + must(t, "Create", err) + k.same(t, "Create result", created, k.minimal("a")) + got, err := k.get(ctx, r, key("a")) + must(t, "Get", err) + k.same(t, "Get after Create", got, k.minimal("a")) + }) + + t.Run("CreateChecksID", func(t *testing.T) { + r, ctx := setup(t), t.Context() + for _, id := range []string{"", strings.Repeat("x", repository.MaxIDLength+1)} { + _, err := k.create(ctx, r, k.fixture(id)) + wantErr(t, "Create with ID of length "+itoa(len(id)), err, repository.ErrInvalid) } + // The longest allowed ID works, counted in characters, not bytes + longest := strings.Repeat("ä", repository.MaxIDLength) + _, err := k.create(ctx, r, k.fixture(longest)) + must(t, "Create with a 128-character ID", err) + _, err = k.get(ctx, r, key(longest)) + must(t, "Get with a 128-character ID", err) }) t.Run("CreateDuplicate", func(t *testing.T) { - ctx, r := setup(t) - _, err := r.Create(ctx, k.fixture("a")) + r, ctx := setup(t), t.Context() + _, err := k.create(ctx, r, k.fixture("a")) must(t, "Create", err) dup := k.fixture("a") *k.fields(dup).Slug = "duplicate" - _, err = r.Create(ctx, dup) + _, err = k.create(ctx, r, dup) wantErr(t, "Create duplicate", err, repository.ErrAlreadyExists) - got, err := r.Get(ctx, "a") + got, err := k.get(ctx, r, key("a")) must(t, "Get", err) k.same(t, "Get after duplicate Create", got, k.fixture("a")) }) t.Run("GetMissing", func(t *testing.T) { - ctx, r := setup(t) - _, err := r.Get(ctx, "missing") + r, ctx := setup(t), t.Context() + _, err := k.get(ctx, r, key("missing")) wantErr(t, "Get missing", err, repository.ErrNotFound) }) t.Run("Update", func(t *testing.T) { - ctx, r := setup(t) - created, err := r.Create(ctx, k.fixture("a")) + r, ctx := setup(t), t.Context() + created, err := k.create(ctx, r, k.fixture("a")) must(t, "Create", err) c := k.fields(created) - got, err := r.Get(ctx, "a") + got, err := k.get(ctx, r, key("a")) must(t, "Get", err) *k.fields(got).Slug = "updated" *k.fields(got).Metadata = map[string]string{"k": "v2", "k2": "v"} - must(t, "Update", r.Update(ctx, got)) + must(t, "Update", k.update(ctx, r, got)) - updated, err := r.Get(ctx, "a") + updated, err := k.get(ctx, r, key("a")) must(t, "Get after Update", err) k.same(t, "Get after Update", updated, got) u := k.fields(updated) @@ -90,42 +110,41 @@ func testCRUD[T any](t *testing.T, newRepo Factory, k kind[T]) { }) t.Run("UpdateMissing", func(t *testing.T) { - ctx, r := setup(t) - err := r.Update(ctx, k.fixture("missing")) - wantErr(t, "Update missing", err, repository.ErrNotFound) + r, ctx := setup(t), t.Context() + wantErr(t, "Update missing", k.update(ctx, r, k.fixture("missing")), repository.ErrNotFound) }) t.Run("Delete", func(t *testing.T) { - ctx, r := setup(t) + r, ctx := setup(t), t.Context() for _, id := range []string{"a", "b"} { - _, err := r.Create(ctx, k.fixture(id)) + _, err := k.create(ctx, r, k.fixture(id)) must(t, "Create "+id, err) } - must(t, "Delete", r.Delete(ctx, "a")) + must(t, "Delete", k.del(ctx, r, key("a"))) - _, err := r.Get(ctx, "a") + _, err := k.get(ctx, r, key("a")) wantErr(t, "Get deleted", err, repository.ErrNotFound) - _, err = r.Get(ctx, "b") + _, err = k.get(ctx, r, key("b")) must(t, "Get other record after Delete", err) - wantErr(t, "Delete again", r.Delete(ctx, "a"), repository.ErrNotFound) + wantErr(t, "Delete again", k.del(ctx, r, key("a")), repository.ErrNotFound) }) t.Run("ReturnsCopies", func(t *testing.T) { - ctx, r := setup(t) + r, ctx := setup(t), t.Context() in := k.fixture("a") - _, err := r.Create(ctx, in) + _, err := k.create(ctx, r, in) must(t, "Create", err) // Changing the value passed to Create must not change the stored one *k.fields(in).Slug = "changed" (*k.fields(in).Metadata)["k"] = "changed" - got, err := r.Get(ctx, "a") + got, err := k.get(ctx, r, key("a")) must(t, "Get", err) k.same(t, "Get after changing Create input", got, k.fixture("a")) // Neither may changing a value returned by Get (*k.fields(got).Metadata)["k"] = "changed" - again, err := r.Get(ctx, "a") + again, err := k.get(ctx, r, key("a")) must(t, "Get again", err) k.same(t, "Get after changing Get result", again, k.fixture("a")) }) diff --git a/src/internal/repository/repotest/fixtures.go b/src/internal/repository/repotest/fixtures.go index 7dce34b..a610620 100644 --- a/src/internal/repository/repotest/fixtures.go +++ b/src/internal/repository/repotest/fixtures.go @@ -8,10 +8,13 @@ import ( "airshift/openmos/internal/repository" ) -// IDs of the parents created for the story and item CRUD tests. const ( + // Parents created for the story and item CRUD tests parentRO = "ro-parent" parentStory = "story-parent" + + // MOS device of the object fixtures + testMOS = "test.mos" ) // The fixtures fill every field, so a store that drops one fails the @@ -20,36 +23,33 @@ const ( func newRunningOrder(id string) *model.RunningOrder { air := time.Date(2026, 11, 8, 18, 30, 0, 0, time.UTC) return &model.RunningOrder{ - ID: id, MosID: "test.mos", Slug: "slug " + id, Status: model.StatusReady, - Duration: 1800, FirstStoryID: "s-first", LastStoryID: "s-last", - AirTime: &air, Channel: "A", Metadata: map[string]string{"k": "v"}, - Version: 1, CreatedBy: "repotest", + ID: id, MosID: testMOS, Slug: "slug " + id, Status: model.StatusReady, + Duration: 1800, AirTime: &air, Channel: "A", + Metadata: map[string]string{"k": "v"}, Version: 1, CreatedBy: "repotest", } } -func newStory(id, roID string, order int) *model.Story { +func newStory(roID, id string) *model.Story { return &model.Story{ - ID: id, RunningOrderID: roID, Slug: "slug " + id, Number: "A1", - Duration: 90, Status: model.StatusPending, Order: order, - PreviousID: "s-prev", NextID: "s-next", Presenter: "presenter", + RunningOrderID: roID, ID: id, Slug: "slug " + id, Number: "A1", + Status: model.StatusPending, Presenter: "presenter", Metadata: map[string]string{"k": "v"}, } } -func newItem(id, storyID string, order int) *model.Item { +func newItem(roID, storyID, id string) *model.Item { return &model.Item{ - ID: id, ObjectID: "obj-1", Slug: "slug " + id, Duration: 30, - EditorialDuration: 25, TimeBase: 25, Status: model.StatusReady, - Order: order, StoryID: storyID, Metadata: map[string]string{"k": "v"}, + RunningOrderID: roID, StoryID: storyID, ID: id, ObjectID: "obj-1", + MosID: testMOS, Slug: "slug " + id, Duration: 1500, TimeBase: 59.94, + Status: model.StatusReady, Metadata: map[string]string{"k": "v"}, } } -func newObject(id string) *model.MOSObject { +func newObject(mosID, id string) *model.MOSObject { return &model.MOSObject{ - ID: id, ObjectType: "VIDEO", Slug: "slug " + id, Duration: 30, - TimeBase: 25, Status: model.StatusReady, ObjectID: "ext-" + id, - MediaID: "media-" + id, MosAbstract: "abstract", - Metadata: map[string]string{"k": "v"}, + MosID: mosID, ID: id, ObjectType: "VIDEO", Slug: "slug " + id, + Duration: 4294967295, TimeBase: 50, Status: model.StatusReady, + Abstract: "abstract", Metadata: map[string]string{"k": "v"}, } } @@ -59,20 +59,20 @@ func createRunningOrder(t *testing.T, r repository.Repository, id string) { must(t, "create running order "+id, err) } -func createStory(t *testing.T, r repository.Repository, id, roID string, order int) { +func createStory(t *testing.T, r repository.Repository, roID, id string) { t.Helper() - _, err := r.Stories().Create(t.Context(), newStory(id, roID, order)) - must(t, "create story "+id, err) + _, err := r.Stories().Create(t.Context(), newStory(roID, id)) + must(t, "create story "+roID+"/"+id, err) } -func createItem(t *testing.T, r repository.Repository, id, storyID string, order int) { +func createItem(t *testing.T, r repository.Repository, roID, storyID, id string) { t.Helper() - _, err := r.Items().Create(t.Context(), newItem(id, storyID, order)) - must(t, "create item "+id, err) + _, err := r.Items().Create(t.Context(), newItem(roID, storyID, id)) + must(t, "create item "+roID+"/"+storyID+"/"+id, err) } -func createObject(t *testing.T, r repository.Repository, id string) { +func createObject(t *testing.T, r repository.Repository, mosID, id string) { t.Helper() - _, err := r.Objects().Create(t.Context(), newObject(id)) - must(t, "create object "+id, err) + _, err := r.Objects().Create(t.Context(), newObject(mosID, id)) + must(t, "create object "+mosID+"/"+id, err) } diff --git a/src/internal/repository/repotest/kinds.go b/src/internal/repository/repotest/kinds.go index aa29266..6c754da 100644 --- a/src/internal/repository/repotest/kinds.go +++ b/src/internal/repository/repotest/kinds.go @@ -10,14 +10,6 @@ import ( "airshift/openmos/internal/repository" ) -// crud is the part every record repository shares. -type crud[T any] interface { - Create(ctx context.Context, v *T) (*T, error) - Get(ctx context.Context, id string) (*T, error) - Update(ctx context.Context, v *T) error - Delete(ctx context.Context, id string) error -} - // common points at the fields every record type has. type common struct { ID, Slug *string @@ -25,11 +17,16 @@ type common struct { CreatedAt, UpdatedAt *time.Time } -// kind describes one record type to the shared CRUD tests in crud.go. +// kind describes one record type to the shared CRUD tests in crud.go. Get +// and delete take the key from the value passed, since keys are composite. type kind[T any] struct { - repo func(repository.Repository) crud[T] - parents func(t *testing.T, repo repository.Repository) // creates what fixture refers to + create func(ctx context.Context, r repository.Repository, v *T) (*T, error) + get func(ctx context.Context, r repository.Repository, key *T) (*T, error) + update func(ctx context.Context, r repository.Repository, v *T) error + del func(ctx context.Context, r repository.Repository, key *T) error + parents func(t *testing.T, r repository.Repository) // creates what fixture refers to fixture func(id string) *T + minimal func(id string) *T // only the key set; every other field empty fields func(v *T) common // normalize, if set, adjusts type-specific fields before comparison. @@ -68,9 +65,21 @@ func (k kind[T]) ids(list []*T) []string { } var runningOrderKind = kind[model.RunningOrder]{ - repo: func(r repository.Repository) crud[model.RunningOrder] { return r.RunningOrders() }, + create: func(ctx context.Context, r repository.Repository, v *model.RunningOrder) (*model.RunningOrder, error) { + return r.RunningOrders().Create(ctx, v) + }, + get: func(ctx context.Context, r repository.Repository, k *model.RunningOrder) (*model.RunningOrder, error) { + return r.RunningOrders().Get(ctx, k.ID) + }, + update: func(ctx context.Context, r repository.Repository, v *model.RunningOrder) error { + return r.RunningOrders().Update(ctx, v) + }, + del: func(ctx context.Context, r repository.Repository, k *model.RunningOrder) error { + return r.RunningOrders().Delete(ctx, k.ID) + }, parents: func(*testing.T, repository.Repository) {}, fixture: newRunningOrder, + minimal: func(id string) *model.RunningOrder { return &model.RunningOrder{ID: id, Version: 1} }, fields: func(v *model.RunningOrder) common { return common{&v.ID, &v.Slug, &v.Metadata, &v.CreatedAt, &v.UpdatedAt} }, @@ -84,32 +93,73 @@ var runningOrderKind = kind[model.RunningOrder]{ } var storyKind = kind[model.Story]{ - repo: func(r repository.Repository) crud[model.Story] { return r.Stories() }, + create: func(ctx context.Context, r repository.Repository, v *model.Story) (*model.Story, error) { + return r.Stories().Create(ctx, v) + }, + get: func(ctx context.Context, r repository.Repository, k *model.Story) (*model.Story, error) { + return r.Stories().Get(ctx, k.RunningOrderID, k.ID) + }, + update: func(ctx context.Context, r repository.Repository, v *model.Story) error { + return r.Stories().Update(ctx, v) + }, + del: func(ctx context.Context, r repository.Repository, k *model.Story) error { + return r.Stories().Delete(ctx, k.RunningOrderID, k.ID) + }, parents: func(t *testing.T, r repository.Repository) { createRunningOrder(t, r, parentRO) }, - fixture: func(id string) *model.Story { return newStory(id, parentRO, 1) }, + fixture: func(id string) *model.Story { return newStory(parentRO, id) }, + minimal: func(id string) *model.Story { return &model.Story{RunningOrderID: parentRO, ID: id} }, fields: func(v *model.Story) common { return common{&v.ID, &v.Slug, &v.Metadata, &v.CreatedAt, &v.UpdatedAt} }, + // Order depends on creation order and is tested in ordering.go + normalize: func(v *model.Story) { v.Order = 0 }, } var itemKind = kind[model.Item]{ - repo: func(r repository.Repository) crud[model.Item] { return r.Items() }, + create: func(ctx context.Context, r repository.Repository, v *model.Item) (*model.Item, error) { + return r.Items().Create(ctx, v) + }, + get: func(ctx context.Context, r repository.Repository, k *model.Item) (*model.Item, error) { + return r.Items().Get(ctx, k.RunningOrderID, k.StoryID, k.ID) + }, + update: func(ctx context.Context, r repository.Repository, v *model.Item) error { + return r.Items().Update(ctx, v) + }, + del: func(ctx context.Context, r repository.Repository, k *model.Item) error { + return r.Items().Delete(ctx, k.RunningOrderID, k.StoryID, k.ID) + }, parents: func(t *testing.T, r repository.Repository) { createRunningOrder(t, r, parentRO) - createStory(t, r, parentStory, parentRO, 1) + createStory(t, r, parentRO, parentStory) + }, + fixture: func(id string) *model.Item { return newItem(parentRO, parentStory, id) }, + minimal: func(id string) *model.Item { + return &model.Item{RunningOrderID: parentRO, StoryID: parentStory, ID: id} }, - fixture: func(id string) *model.Item { return newItem(id, parentStory, 1) }, fields: func(v *model.Item) common { return common{&v.ID, &v.Slug, &v.Metadata, &v.CreatedAt, &v.UpdatedAt} }, + normalize: func(v *model.Item) { v.Order = 0 }, } var objectKind = kind[model.MOSObject]{ - repo: func(r repository.Repository) crud[model.MOSObject] { return r.Objects() }, + create: func(ctx context.Context, r repository.Repository, v *model.MOSObject) (*model.MOSObject, error) { + return r.Objects().Create(ctx, v) + }, + get: func(ctx context.Context, r repository.Repository, k *model.MOSObject) (*model.MOSObject, error) { + return r.Objects().Get(ctx, k.MosID, k.ID) + }, + update: func(ctx context.Context, r repository.Repository, v *model.MOSObject) error { + return r.Objects().Update(ctx, v) + }, + del: func(ctx context.Context, r repository.Repository, k *model.MOSObject) error { + return r.Objects().Delete(ctx, k.MosID, k.ID) + }, parents: func(*testing.T, repository.Repository) {}, - fixture: newObject, + fixture: func(id string) *model.MOSObject { return newObject(testMOS, id) }, + minimal: func(id string) *model.MOSObject { return &model.MOSObject{MosID: testMOS, ID: id} }, fields: func(v *model.MOSObject) common { return common{&v.ID, &v.Slug, &v.Metadata, &v.CreatedAt, &v.UpdatedAt} }, diff --git a/src/internal/repository/repotest/object.go b/src/internal/repository/repotest/object.go index 0ac8719..270a466 100644 --- a/src/internal/repository/repotest/object.go +++ b/src/internal/repository/repotest/object.go @@ -1,6 +1,10 @@ package repotest -import "testing" +import ( + "testing" + + "airshift/openmos/internal/repository" +) func testObjects(t *testing.T, newRepo Factory) { t.Run("ListNewestFirst", func(t *testing.T) { @@ -10,11 +14,23 @@ func testObjects(t *testing.T, newRepo Factory) { equalIDs(t, "List empty", objectKind.ids(list), nil) for _, id := range []string{"a", "b", "c"} { - createObject(t, r, id) + createObject(t, r, testMOS, id) tick() } list, err = r.Objects().List(t.Context()) must(t, "List", err) equalIDs(t, "List", objectKind.ids(list), []string{"c", "b", "a"}) }) + + // An objID is unique only within its MOS device + t.Run("KeyIncludesMosID", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + createObject(t, r, "a.mos", "obj") + createObject(t, r, "b.mos", "obj") + must(t, "Delete a.mos/obj", r.Objects().Delete(ctx, "a.mos", "obj")) + _, err := r.Objects().Get(ctx, "b.mos", "obj") + must(t, "Get b.mos/obj after deleting a.mos/obj", err) + _, err = r.Objects().Get(ctx, "c.mos", "obj") + wantErr(t, "Get obj of an unknown MOS device", err, repository.ErrNotFound) + }) } diff --git a/src/internal/repository/repotest/ordering.go b/src/internal/repository/repotest/ordering.go new file mode 100644 index 0000000..073b745 --- /dev/null +++ b/src/internal/repository/repotest/ordering.go @@ -0,0 +1,224 @@ +package repotest + +import ( + "context" + "testing" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +// ordered describes the children of one parent (stories of a running order +// or items of a story) to the shared ordering tests. A parent is named by a +// single string; the item variant places both test stories in one running +// order. +type ordered struct { + parents func(t *testing.T, r repository.Repository, names ...string) + create func(t *testing.T, r repository.Repository, parent, id string) + list func(ctx context.Context, r repository.Repository, parent string) (ids []string, orders []int, err error) + del func(ctx context.Context, r repository.Repository, parent, id string) error + setOrder func(ctx context.Context, r repository.Repository, parent, id string, order int) error // Update with Order changed + move func(ctx context.Context, r repository.Repository, parent string, ids []string, before string) error + swap func(ctx context.Context, r repository.Repository, parent, a, b string) error + replaceAll func(ctx context.Context, r repository.Repository, parent string, ids []string) error +} + +func testOrdering(t *testing.T, newRepo Factory, o ordered) { + // setup creates parents p and q, with children a, b, c, d in p + setup := func(t *testing.T) repository.Repository { + r := newRepo(t) + o.parents(t, r, "p", "q") + for _, id := range []string{"a", "b", "c", "d"} { + o.create(t, r, "p", id) + } + return r + } + // check fails unless parent lists want, with strictly increasing Order + check := func(t *testing.T, r repository.Repository, op, parent string, want ...string) { + t.Helper() + ids, orders, err := o.list(t.Context(), r, parent) + must(t, op+": list", err) + equalIDs(t, op, ids, want) + for i := 1; i < len(orders); i++ { + if orders[i] <= orders[i-1] { + t.Errorf("%s: Order values %v not strictly increasing", op, orders) + break + } + } + } + + t.Run("CreateAppends", func(t *testing.T) { + r := newRepo(t) + o.parents(t, r, "p", "q") + for _, id := range []string{"c", "a", "b"} { + o.create(t, r, "p", id) + } + check(t, r, "after creates", "p", "c", "a", "b") + check(t, r, "other parent", "q") + check(t, r, "unknown parent", "missing") + }) + + // A delete leaves a gap; the next create still goes after the last + t.Run("CreateAfterDelete", func(t *testing.T) { + r := setup(t) + must(t, "delete b", o.del(t.Context(), r, "p", "b")) + o.create(t, r, "p", "aa") + check(t, r, "create after delete", "p", "a", "c", "d", "aa") + }) + + t.Run("UpdateKeepsOrder", func(t *testing.T) { + r := setup(t) + must(t, "Update with a new Order", o.setOrder(t.Context(), r, "p", "a", 99)) + check(t, r, "after Update", "p", "a", "b", "c", "d") + }) + + t.Run("Move", func(t *testing.T) { + r, ctx := setup(t), t.Context() + must(t, "move d before a", o.move(ctx, r, "p", []string{"d"}, "a")) + check(t, r, "move d before a", "p", "d", "a", "b", "c") + must(t, "move a, b to the end", o.move(ctx, r, "p", []string{"a", "b"}, "")) + check(t, r, "move a, b to the end", "p", "d", "c", "a", "b") + must(t, "move b, d before c", o.move(ctx, r, "p", []string{"b", "d"}, "c")) + check(t, r, "move b, d before c", "p", "b", "d", "c", "a") + }) + + t.Run("MoveRejects", func(t *testing.T) { + r, ctx := setup(t), t.Context() + for _, tc := range []struct { + name string + ids []string + before string + want error + }{ + {"unknown child", []string{"x"}, "a", repository.ErrNotFound}, + {"unknown target", []string{"a"}, "x", repository.ErrNotFound}, + {"child of another parent", []string{"a"}, "", repository.ErrNotFound}, + {"target in the moved set", []string{"a", "b"}, "b", repository.ErrInvalid}, + {"child listed twice", []string{"a", "a"}, "c", repository.ErrInvalid}, + {"nothing to move", nil, "a", repository.ErrInvalid}, + } { + parent := "p" + if tc.name == "child of another parent" { + parent = "q" + } + wantErr(t, "move "+tc.name, o.move(ctx, r, parent, tc.ids, tc.before), tc.want) + } + check(t, r, "after rejected moves", "p", "a", "b", "c", "d") + }) + + t.Run("Swap", func(t *testing.T) { + r, ctx := setup(t), t.Context() + must(t, "swap a and c", o.swap(ctx, r, "p", "a", "c")) + check(t, r, "swap a and c", "p", "c", "b", "a", "d") + wantErr(t, "swap with itself", o.swap(ctx, r, "p", "a", "a"), repository.ErrInvalid) + wantErr(t, "swap with unknown", o.swap(ctx, r, "p", "a", "x"), repository.ErrNotFound) + check(t, r, "after rejected swaps", "p", "c", "b", "a", "d") + }) + + t.Run("ReplaceAll", func(t *testing.T) { + r, ctx := setup(t), t.Context() + o.create(t, r, "q", "a") // same ID under the other parent + must(t, "replace with x, c, a", o.replaceAll(ctx, r, "p", []string{"x", "c", "a"})) + check(t, r, "after replace", "p", "x", "c", "a") + check(t, r, "other parent untouched", "q", "a") + + wantErr(t, "replace with duplicates", o.replaceAll(ctx, r, "p", []string{"y", "y"}), repository.ErrInvalid) + wantErr(t, "replace in unknown parent", o.replaceAll(ctx, r, "missing", []string{"y"}), repository.ErrNotFound) + check(t, r, "after rejected replaces", "p", "x", "c", "a") + + must(t, "replace with nothing", o.replaceAll(ctx, r, "p", nil)) + check(t, r, "after replace with nothing", "p") + // Appending after a replace continues after the new children + must(t, "replace with a, b", o.replaceAll(ctx, r, "p", []string{"a", "b"})) + o.create(t, r, "p", "c") + check(t, r, "create after replace", "p", "a", "b", "c") + }) +} + +var storyOrdering = ordered{ + parents: func(t *testing.T, r repository.Repository, names ...string) { + for _, n := range names { + createRunningOrder(t, r, n) + } + }, + create: func(t *testing.T, r repository.Repository, parent, id string) { createStory(t, r, parent, id) }, + list: func(ctx context.Context, r repository.Repository, parent string) ([]string, []int, error) { + list, err := r.Stories().ListByRunningOrder(ctx, parent) + orders := make([]int, len(list)) + for i, s := range list { + orders[i] = s.Order + } + return storyKind.ids(list), orders, err + }, + del: func(ctx context.Context, r repository.Repository, parent, id string) error { + return r.Stories().Delete(ctx, parent, id) + }, + setOrder: func(ctx context.Context, r repository.Repository, parent, id string, order int) error { + s, err := r.Stories().Get(ctx, parent, id) + if err != nil { + return err + } + s.Order = order + return r.Stories().Update(ctx, s) + }, + move: func(ctx context.Context, r repository.Repository, parent string, ids []string, before string) error { + return r.Stories().Move(ctx, parent, ids, before) + }, + swap: func(ctx context.Context, r repository.Repository, parent, a, b string) error { + return r.Stories().Swap(ctx, parent, a, b) + }, + replaceAll: func(ctx context.Context, r repository.Repository, parent string, ids []string) error { + list := make([]*model.Story, len(ids)) + for i, id := range ids { + // The parent named in the call wins over the stories' own + list[i] = newStory("elsewhere", id) + } + return r.Stories().ReplaceAll(ctx, parent, list) + }, +} + +// Items are tested in stories p and q of running order itemsRO. +const itemsRO = "ro-items" + +var itemOrdering = ordered{ + parents: func(t *testing.T, r repository.Repository, names ...string) { + createRunningOrder(t, r, itemsRO) + for _, n := range names { + createStory(t, r, itemsRO, n) + } + }, + create: func(t *testing.T, r repository.Repository, parent, id string) { createItem(t, r, itemsRO, parent, id) }, + list: func(ctx context.Context, r repository.Repository, parent string) ([]string, []int, error) { + list, err := r.Items().ListByStory(ctx, itemsRO, parent) + orders := make([]int, len(list)) + for i, it := range list { + orders[i] = it.Order + } + return itemKind.ids(list), orders, err + }, + del: func(ctx context.Context, r repository.Repository, parent, id string) error { + return r.Items().Delete(ctx, itemsRO, parent, id) + }, + setOrder: func(ctx context.Context, r repository.Repository, parent, id string, order int) error { + it, err := r.Items().Get(ctx, itemsRO, parent, id) + if err != nil { + return err + } + it.Order = order + return r.Items().Update(ctx, it) + }, + move: func(ctx context.Context, r repository.Repository, parent string, ids []string, before string) error { + return r.Items().Move(ctx, itemsRO, parent, ids, before) + }, + swap: func(ctx context.Context, r repository.Repository, parent, a, b string) error { + return r.Items().Swap(ctx, itemsRO, parent, a, b) + }, + replaceAll: func(ctx context.Context, r repository.Repository, parent string, ids []string) error { + list := make([]*model.Item, len(ids)) + for i, id := range ids { + // The parent named in the call wins over the items' own + list[i] = newItem("elsewhere", "elsewhere", id) + } + return r.Items().ReplaceAll(ctx, itemsRO, parent, list) + }, +} diff --git a/src/internal/repository/repotest/repotest.go b/src/internal/repository/repotest/repotest.go index 5542c0a..a3db74e 100644 --- a/src/internal/repository/repotest/repotest.go +++ b/src/internal/repository/repotest/repotest.go @@ -13,6 +13,7 @@ package repotest import ( "errors" "slices" + "strconv" "testing" "time" @@ -32,10 +33,12 @@ func Run(t *testing.T, newRepo Factory) { }) t.Run("Stories", func(t *testing.T) { testCRUD(t, newRepo, storyKind) + testOrdering(t, newRepo, storyOrdering) testStories(t, newRepo) }) t.Run("Items", func(t *testing.T) { testCRUD(t, newRepo, itemKind) + testOrdering(t, newRepo, itemOrdering) testItems(t, newRepo) }) t.Run("Objects", func(t *testing.T) { @@ -87,3 +90,5 @@ func equalIDs(t *testing.T, op string, got, want []string) { t.Errorf("%s: IDs = %v, want %v", op, got, want) } } + +func itoa(n int) string { return strconv.Itoa(n) } diff --git a/src/internal/server/client_ro_handler.go b/src/internal/server/client_ro_handler.go index 4ca8df5..c6c8214 100644 --- a/src/internal/server/client_ro_handler.go +++ b/src/internal/server/client_ro_handler.go @@ -54,7 +54,7 @@ func (c *ClientConnection) handleReqRunningOrder(ctx context.Context, req xml.Re storyInfos := make([]xml.StoryInfo, 0, len(stories)) for _, story := range stories { // Get items for this story - items, err := c.server.service.GetItemsForStory(ctx, story.ID) + items, err := c.server.service.GetItemsForStory(ctx, ro.ID, story.ID) if err != nil { logger.Warningf("Failed to get items for story %s: %v", story.ID, err) continue @@ -68,16 +68,16 @@ func (c *ClientConnection) handleReqRunningOrder(ctx context.Context, req xml.Re Slug: item.Slug, Duration: fmt.Sprintf("%d", item.Duration), ObjectID: item.ObjectID, + MosID: item.MosID, }) } // Add story info storyInfos = append(storyInfos, xml.StoryInfo{ - ID: story.ID, - Slug: story.Slug, - Number: story.Number, - Duration: fmt.Sprintf("%d", story.Duration), - Items: itemInfos, + ID: story.ID, + Slug: story.Slug, + Number: story.Number, + Items: itemInfos, }) } diff --git a/src/internal/server/client_ro_notify.go b/src/internal/server/client_ro_notify.go index 288e9ad..7f1447e 100644 --- a/src/internal/server/client_ro_notify.go +++ b/src/internal/server/client_ro_notify.go @@ -30,7 +30,7 @@ func (c *ClientConnection) handleRunningOrderUpdate(ctx context.Context, event e storyInfos := make([]xml.StoryInfo, 0, len(stories)) for _, story := range stories { // Get items for this story - items, err := c.server.service.GetItemsForStory(ctx, story.ID) + items, err := c.server.service.GetItemsForStory(ctx, ro.ID, story.ID) if err != nil { logger.Warningf("Failed to get items for story %s: %v", story.ID, err) continue @@ -44,15 +44,15 @@ func (c *ClientConnection) handleRunningOrderUpdate(ctx context.Context, event e Slug: item.Slug, Duration: fmt.Sprintf("%d", item.Duration), ObjectID: item.ObjectID, + MosID: item.MosID, }) } storyInfos = append(storyInfos, xml.StoryInfo{ - ID: story.ID, - Slug: story.Slug, - Number: story.Number, - Duration: fmt.Sprintf("%d", story.Duration), - Items: itemInfos, + ID: story.ID, + Slug: story.Slug, + Number: story.Number, + Items: itemInfos, }) } diff --git a/src/internal/service/mos.go b/src/internal/service/mos.go index 5a84095..d797a14 100644 --- a/src/internal/service/mos.go +++ b/src/internal/service/mos.go @@ -2,9 +2,9 @@ package service import ( "context" + "errors" "fmt" "strconv" - "time" "airshift/openmos/internal/events" "airshift/openmos/internal/model" @@ -61,15 +61,14 @@ func (s *MOSService) GetRunningOrderWithStories(ctx context.Context, id string) } // GetItemsForStory retrieves all items for a story -func (s *MOSService) GetItemsForStory(ctx context.Context, storyID string) ([]*model.Item, error) { - return s.itemRepo.ListByStory(ctx, storyID) +func (s *MOSService) GetItemsForStory(ctx context.Context, roID, storyID string) ([]*model.Item, error) { + return s.itemRepo.ListByStory(ctx, roID, storyID) } -// ProcessRunningOrderInfo processes a running order creation/update message +// ProcessRunningOrderInfo processes a running order creation/update message. +// The stories and items in the message replace those stored before, in the +// order the message lists them. func (s *MOSService) ProcessRunningOrderInfo(ctx context.Context, roInfo xml.RunningOrderInfo) error { - // Check if running order exists - existingRO, getErr := s.runningOrderRepo.Get(ctx, roInfo.ID) - // Parse duration if provided; an unparsable value falls back to 0 var duration int if roInfo.Duration != "" { @@ -78,85 +77,64 @@ func (s *MOSService) ProcessRunningOrderInfo(ctx context.Context, roInfo xml.Run } } - // Create or update running order - var err error - if getErr != nil { // Running order doesn't exist - // Create new running order + existingRO, err := s.runningOrderRepo.Get(ctx, roInfo.ID) + switch { + case errors.Is(err, repository.ErrNotFound): ro := &model.RunningOrder{ - ID: roInfo.ID, - Slug: roInfo.Slug, - Status: model.StatusPending, - Duration: duration, - Channel: roInfo.Channel, - Version: 1, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), + ID: roInfo.ID, + Slug: roInfo.Slug, + Status: model.StatusPending, + Duration: duration, + Channel: roInfo.Channel, } - - _, err = s.runningOrderRepo.Create(ctx, ro) - if err != nil { + if _, err := s.runningOrderRepo.Create(ctx, ro); err != nil { return fmt.Errorf("failed to create running order: %w", err) } - } else { - // Update existing running order + case err != nil: + return fmt.Errorf("failed to get running order: %w", err) + default: existingRO.Slug = roInfo.Slug existingRO.Channel = roInfo.Channel existingRO.Duration = duration - existingRO.UpdatedAt = time.Now() - - err = s.runningOrderRepo.Update(ctx, existingRO) - if err != nil { + if err := s.runningOrderRepo.Update(ctx, existingRO); err != nil { return fmt.Errorf("failed to update running order: %w", err) } } - // Process stories (simplified - full implementation would handle deletions, etc.) + stories := make([]*model.Story, len(roInfo.Stories)) for i, storyInfo := range roInfo.Stories { - // Create or update each story - story := &model.Story{ + stories[i] = &model.Story{ ID: storyInfo.ID, RunningOrderID: roInfo.ID, Slug: storyInfo.Slug, Number: storyInfo.Number, Status: model.StatusPending, - Order: i + 1, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - } - - // Parse duration if provided - if storyInfo.Duration != "" { - if storyDuration, err := strconv.Atoi(storyInfo.Duration); err == nil { - story.Duration = storyDuration - } } + } + if err := s.storyRepo.ReplaceAll(ctx, roInfo.ID, stories); err != nil { + return fmt.Errorf("failed to replace stories: %w", err) + } - // Create or update the story - existingStory, err := s.storyRepo.Get(ctx, storyInfo.ID) - if err != nil { - // Story doesn't exist, create it - _, err = s.storyRepo.Create(ctx, story) - if err != nil { - return fmt.Errorf("failed to create story: %w", err) - } - } else { - // Story exists, update it - existingStory.Slug = storyInfo.Slug - existingStory.Number = storyInfo.Number - existingStory.Order = i + 1 - existingStory.UpdatedAt = time.Now() - - if storyInfo.Duration != "" { - if storyDuration, err := strconv.Atoi(storyInfo.Duration); err == nil { - existingStory.Duration = storyDuration - } + for _, storyInfo := range roInfo.Stories { + items := make([]*model.Item, len(storyInfo.Items)) + for j, itemInfo := range storyInfo.Items { + items[j] = &model.Item{ + ID: itemInfo.ID, + RunningOrderID: roInfo.ID, + StoryID: storyInfo.ID, + ObjectID: itemInfo.ObjectID, + MosID: itemInfo.MosID, + Slug: itemInfo.Slug, + Status: model.StatusPending, } - - err = s.storyRepo.Update(ctx, existingStory) - if err != nil { - return fmt.Errorf("failed to update story: %w", err) + // An unparsable or out-of-range duration falls back to 0 + if d, err := strconv.ParseUint(itemInfo.Duration, 10, 32); err == nil { + items[j].Duration = int64(d) } } + if err := s.itemRepo.ReplaceAll(ctx, roInfo.ID, storyInfo.ID, items); err != nil { + return fmt.Errorf("failed to replace items of story %s: %w", storyInfo.ID, err) + } } // Publish event after successful update diff --git a/src/internal/service/mos_test.go b/src/internal/service/mos_test.go index 5a60dd4..9cf265e 100644 --- a/src/internal/service/mos_test.go +++ b/src/internal/service/mos_test.go @@ -1,44 +1,27 @@ package service import ( - "context" - "fmt" + "slices" "testing" "airshift/openmos/internal/model" "airshift/openmos/internal/repository" + "airshift/openmos/internal/repository/memory" "airshift/openmos/internal/xml" ) -// fakeRORepo is an in-memory RunningOrderRepository. Methods not -// overridden panic via the nil embedded interface. -type fakeRORepo struct { - repository.RunningOrderRepository - ros map[string]*model.RunningOrder +func newTestService() (*MOSService, repository.Repository) { + repo := memory.New() + return NewMOSService(repo.RunningOrders(), repo.Stories(), repo.Items(), repo.Objects(), nil), repo } -func (f *fakeRORepo) Get(_ context.Context, id string) (*model.RunningOrder, error) { - ro, ok := f.ros[id] - if !ok { - return nil, fmt.Errorf("running order not found: %s", id) +func getRO(t *testing.T, repo repository.Repository, id string) *model.RunningOrder { + t.Helper() + ro, err := repo.RunningOrders().Get(t.Context(), id) + if err != nil { + t.Fatalf("Get running order %s: %v", id, err) } - c := *ro - return &c, nil -} - -func (f *fakeRORepo) Create(_ context.Context, ro *model.RunningOrder) (*model.RunningOrder, error) { - f.ros[ro.ID] = ro - return ro, nil -} - -func (f *fakeRORepo) Update(_ context.Context, ro *model.RunningOrder) error { - f.ros[ro.ID] = ro - return nil -} - -func newTestService() (*MOSService, *fakeRORepo) { - roRepo := &fakeRORepo{ros: map[string]*model.RunningOrder{}} - return NewMOSService(roRepo, nil, nil, nil, nil), roRepo + return ro } // Regression test for MOS-7: a new running order with a numeric duration @@ -46,47 +29,112 @@ func newTestService() (*MOSService, *fakeRORepo) { func TestProcessRunningOrderInfoCreatesNewROWithNumericDuration(t *testing.T) { svc, repo := newTestService() - err := svc.ProcessRunningOrderInfo(context.Background(), xml.RunningOrderInfo{ + err := svc.ProcessRunningOrderInfo(t.Context(), xml.RunningOrderInfo{ ID: "RO1", Slug: "Evening News", Duration: "1800", }) if err != nil { t.Fatalf("ProcessRunningOrderInfo: %v", err) } - - ro, ok := repo.ros["RO1"] - if !ok { - t.Fatal("running order RO1 was not created") - } - if ro.Duration != 1800 || ro.Slug != "Evening News" || ro.Version != 1 { + if ro := getRO(t, repo, "RO1"); ro.Duration != 1800 || ro.Slug != "Evening News" || ro.Version != 1 { t.Errorf("created RO = %+v, want duration 1800, slug %q, version 1", ro, "Evening News") } } func TestProcessRunningOrderInfoUpdatesExistingRO(t *testing.T) { svc, repo := newTestService() - repo.ros["RO1"] = &model.RunningOrder{ID: "RO1", Slug: "Old", Duration: 10, Version: 1} + _, err := repo.RunningOrders().Create(t.Context(), &model.RunningOrder{ID: "RO1", Slug: "Old", Duration: 10}) + if err != nil { + t.Fatal(err) + } - err := svc.ProcessRunningOrderInfo(context.Background(), xml.RunningOrderInfo{ + err = svc.ProcessRunningOrderInfo(t.Context(), xml.RunningOrderInfo{ ID: "RO1", Slug: "New", Duration: "1800", }) if err != nil { t.Fatalf("ProcessRunningOrderInfo: %v", err) } - if ro := repo.ros["RO1"]; ro.Slug != "New" || ro.Duration != 1800 { - t.Errorf("updated RO = %+v, want slug %q, duration 1800", ro, "New") + if ro := getRO(t, repo, "RO1"); ro.Slug != "New" || ro.Duration != 1800 || ro.Version != 2 { + t.Errorf("updated RO = %+v, want slug %q, duration 1800, version 2", ro, "New") } } func TestProcessRunningOrderInfoInvalidDurationFallsBackToZero(t *testing.T) { svc, repo := newTestService() - err := svc.ProcessRunningOrderInfo(context.Background(), xml.RunningOrderInfo{ + err := svc.ProcessRunningOrderInfo(t.Context(), xml.RunningOrderInfo{ ID: "RO1", Duration: "not-a-number", }) if err != nil { t.Fatalf("ProcessRunningOrderInfo: %v", err) } - if ro := repo.ros["RO1"]; ro == nil || ro.Duration != 0 { - t.Errorf("RO = %+v, want created with duration 0", ro) + if ro := getRO(t, repo, "RO1"); ro.Duration != 0 { + t.Errorf("RO = %+v, want duration 0", ro) + } +} + +func TestProcessRunningOrderInfoReplacesStoriesAndItems(t *testing.T) { + svc, repo := newTestService() + ctx := t.Context() + + first := xml.RunningOrderInfo{ID: "RO1", Stories: []xml.StoryInfo{ + {ID: "S1", Items: []xml.ItemInfo{{ID: "I1"}, {ID: "I2"}}}, + {ID: "S2"}, + }} + if err := svc.ProcessRunningOrderInfo(ctx, first); err != nil { + t.Fatalf("first ProcessRunningOrderInfo: %v", err) + } + + // The second message reorders the stories, drops S1's items except one + // and adds an item to S2 + second := xml.RunningOrderInfo{ID: "RO1", Stories: []xml.StoryInfo{ + {ID: "S2", Items: []xml.ItemInfo{{ID: "I9", MosID: "a.mos", ObjectID: "O1", Duration: "250"}}}, + {ID: "S1", Items: []xml.ItemInfo{{ID: "I2"}}}, + }} + if err := svc.ProcessRunningOrderInfo(ctx, second); err != nil { + t.Fatalf("second ProcessRunningOrderInfo: %v", err) + } + + _, stories, err := svc.GetRunningOrderWithStories(ctx, "RO1") + if err != nil { + t.Fatal(err) + } + var ids []string + for _, s := range stories { + ids = append(ids, s.ID) + } + if want := []string{"S2", "S1"}; !slices.Equal(ids, want) { + t.Errorf("stories = %v, want %v", ids, want) + } + + for story, want := range map[string][]string{"S1": {"I2"}, "S2": {"I9"}} { + items, err := svc.GetItemsForStory(ctx, "RO1", story) + if err != nil { + t.Fatal(err) + } + var got []string + for _, it := range items { + got = append(got, it.ID) + } + if !slices.Equal(got, want) { + t.Errorf("items of %s = %v, want %v", story, got, want) + } + } + + it, err := repo.Items().Get(ctx, "RO1", "S2", "I9") + if err != nil { + t.Fatal(err) + } + if it.MosID != "a.mos" || it.ObjectID != "O1" || it.Duration != 250 { + t.Errorf("item I9 = %+v, want mosID a.mos, objID O1, duration 250", it) + } +} + +func TestProcessRunningOrderInfoRejectsDuplicateStories(t *testing.T) { + svc, _ := newTestService() + err := svc.ProcessRunningOrderInfo(t.Context(), xml.RunningOrderInfo{ + ID: "RO1", Stories: []xml.StoryInfo{{ID: "S1"}, {ID: "S1"}}, + }) + if err == nil { + t.Fatal("ProcessRunningOrderInfo with a duplicate story succeeded, want an error") } } diff --git a/src/internal/service/story.go b/src/internal/service/story.go index 69a9b24..60682ad 100644 --- a/src/internal/service/story.go +++ b/src/internal/service/story.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "strings" - "time" "airshift/openmos/internal/events" "airshift/openmos/internal/xml" @@ -30,7 +29,7 @@ func (s *MOSService) ProcessStoryAction(ctx context.Context, action xml.NCSReqSt // updateStory updates an existing story from the provided ROStorySend func (s *MOSService) updateStory(ctx context.Context, storySend xml.ROStorySend) error { // Check if the story exists - story, err := s.storyRepo.Get(ctx, storySend.StoryID) + story, err := s.storyRepo.Get(ctx, storySend.ROID, storySend.StoryID) if err != nil { return fmt.Errorf("story not found: %w", err) } @@ -38,7 +37,6 @@ func (s *MOSService) updateStory(ctx context.Context, storySend xml.ROStorySend) // Update story fields story.Slug = storySend.StorySlug story.Number = storySend.StoryNum - story.UpdatedAt = time.Now() // Process story body err = s.processStoryBody(ctx, story, &storySend.StoryBody) @@ -69,7 +67,7 @@ func (s *MOSService) updateStory(ctx context.Context, storySend xml.ROStorySend) func (s *MOSService) replaceStory(ctx context.Context, storySend xml.ROStorySend) error { // For now, implement as delete + create // Delete existing story - err := s.storyRepo.Delete(ctx, storySend.StoryID) + err := s.storyRepo.Delete(ctx, storySend.ROID, storySend.StoryID) if err != nil { return fmt.Errorf("failed to delete existing story: %w", err) } diff --git a/src/internal/service/story_body.go b/src/internal/service/story_body.go index d519279..2ab78b6 100644 --- a/src/internal/service/story_body.go +++ b/src/internal/service/story_body.go @@ -3,7 +3,6 @@ package service import ( "context" "fmt" - "time" "airshift/openmos/internal/model" "airshift/openmos/internal/xml" @@ -21,15 +20,13 @@ func (s *MOSService) processStoryBody(ctx context.Context, story *model.Story, s for j, storyItem := range paragraph.Items { // Create a new item item := &model.Item{ - ID: fmt.Sprintf("%s_I%d_%d", story.ID, i, j), - StoryID: story.ID, - Slug: storyItem.ItemSlug, - ObjectID: storyItem.ObjID, - Duration: storyItem.ItemEdDur, - Status: model.StatusPending, - Order: j + 1, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), + ID: fmt.Sprintf("%s_I%d_%d", story.ID, i, j), + RunningOrderID: story.RunningOrderID, + StoryID: story.ID, + Slug: storyItem.ItemSlug, + ObjectID: storyItem.ObjID, + Duration: int64(storyItem.ItemEdDur), + Status: model.StatusPending, } items = append(items, item) diff --git a/src/internal/service/story_create.go b/src/internal/service/story_create.go index 226ed54..61bdbab 100644 --- a/src/internal/service/story_create.go +++ b/src/internal/service/story_create.go @@ -22,12 +22,9 @@ func (s *MOSService) createNewStory(ctx context.Context, storySend xml.ROStorySe if err != nil { // Create a new running order if it doesn't exist ro = &model.RunningOrder{ - ID: storySend.ROID, - Slug: "Auto-created RO", - Status: model.StatusPending, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - Version: 1, + ID: storySend.ROID, + Slug: "Auto-created RO", + Status: model.StatusPending, } ro, err = s.runningOrderRepo.Create(ctx, ro) @@ -52,19 +49,9 @@ func (s *MOSService) createNewStory(ctx context.Context, storySend xml.ROStorySe Slug: storySend.StorySlug, Number: storySend.StoryNum, Status: model.StatusPending, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), } - // Try to determine the story's order in the running order - stories, err := s.storyRepo.ListByRunningOrder(ctx, ro.ID) - if err != nil { - return fmt.Errorf("failed to list stories: %w", err) - } - - // New story goes at the end - story.Order = len(stories) + 1 - + // The repository appends the new story to the running order // Process story body err = s.processStoryBody(ctx, story, &storySend.StoryBody) if err != nil { diff --git a/src/internal/store/postgres/errors_test.go b/src/internal/store/postgres/errors_test.go new file mode 100644 index 0000000..59654cd --- /dev/null +++ b/src/internal/store/postgres/errors_test.go @@ -0,0 +1,45 @@ +package postgres + +import ( + "errors" + "fmt" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "airshift/openmos/internal/repository" +) + +// dbError is also reached by paths the contract suite cannot provoke, such +// as a foreign key violation, which the parent locks normally prevent. +func TestDBError(t *testing.T) { + other := errors.New("connection reset") + for _, tc := range []struct { + err error + want error + }{ + {pgx.ErrNoRows, repository.ErrNotFound}, + {fmt.Errorf("scan: %w", pgx.ErrNoRows), repository.ErrNotFound}, + {&pgconn.PgError{Code: "23505"}, repository.ErrAlreadyExists}, + {&pgconn.PgError{Code: "23503"}, repository.ErrNotFound}, + {&pgconn.PgError{Code: "23514"}, repository.ErrInvalid}, + {&pgconn.PgError{Code: "22003"}, repository.ErrInvalid}, + {&pgconn.PgError{Code: "22021"}, repository.ErrInvalid}, + {&pgconn.PgError{Code: "22P05"}, repository.ErrInvalid}, + {&pgconn.PgError{Code: "40001"}, nil}, + {other, nil}, + } { + got := dbError(tc.err, "story ro/s") + // No rows is just "not found"; other causes stay in the chain + if !errors.Is(tc.err, pgx.ErrNoRows) && !errors.Is(got, tc.err) { + t.Errorf("dbError(%v) = %v, lost the original error", tc.err, got) + } + for _, sentinel := range []error{repository.ErrNotFound, repository.ErrAlreadyExists, + repository.ErrInvalid, repository.ErrVersionConflict} { + if errors.Is(got, sentinel) != (sentinel == tc.want) { + t.Errorf("dbError(%v) = %v; errors.Is(%v) = %v", tc.err, got, sentinel, !(sentinel == tc.want)) + } + } + } +} diff --git a/src/internal/store/postgres/item.go b/src/internal/store/postgres/item.go new file mode 100644 index 0000000..c0cffba --- /dev/null +++ b/src/internal/store/postgres/item.go @@ -0,0 +1,174 @@ +package postgres + +import ( + "context" + "fmt" + + "github.com/jackc/pgx/v5" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +type items struct{ db DBTX } + +var itemSiblings = siblings{ + table: "openmos.items", + idCol: "item_id", + where: "ro_id = $1 AND story_id = $2", + lock: "SELECT 1 FROM openmos.stories WHERE ro_id = $1 AND story_id = $2 FOR NO KEY UPDATE", +} + +// itemColumns are read by scanItem. A zero time base is stored as NULL, +// meaning unknown. +const itemColumns = `ro_id, story_id, item_id, position, obj_id, mos_id, slug, + COALESCE(ed_dur, 0), COALESCE(time_base, 0)::float8, status, metadata, created_at, updated_at` + +func scanItem(row pgx.Row) (*model.Item, error) { + var it model.Item + err := row.Scan(&it.RunningOrderID, &it.StoryID, &it.ID, &it.Order, &it.ObjectID, &it.MosID, + &it.Slug, &it.Duration, &it.TimeBase, &it.Status, &it.Metadata, &it.CreatedAt, &it.UpdatedAt) + if err != nil { + return nil, err + } + return &it, nil +} + +func itemName(roID, storyID, itemID string) string { + return "item " + roID + "/" + storyID + "/" + itemID +} + +func checkItemKey(roID, storyID, itemID string) error { + if err := checkStoryKey(roID, storyID); err != nil { + return err + } + return repository.CheckID("item", itemID) +} + +// insertItem adds it to its story at position, given as SQL. The caller +// holds the parent lock. +func insertItem(ctx context.Context, tx pgx.Tx, it *model.Item, position string) (*model.Item, error) { + out, err := scanItem(tx.QueryRow(ctx, ` + INSERT INTO openmos.items + (ro_id, story_id, item_id, position, obj_id, mos_id, slug, ed_dur, time_base, status, metadata) + VALUES ($1, $2, $3, `+position+`, $4, $5, $6, $7, NULLIF($8::float8, 0)::numeric, $9, $10) + RETURNING `+itemColumns, + it.RunningOrderID, it.StoryID, it.ID, it.ObjectID, it.MosID, it.Slug, it.Duration, + it.TimeBase, string(it.Status), metadata(it.Metadata))) + if err != nil { + return nil, dbError(err, itemName(it.RunningOrderID, it.StoryID, it.ID)) + } + it.Order, it.CreatedAt, it.UpdatedAt = out.Order, out.CreatedAt, out.UpdatedAt + return out, nil +} + +func (s items) Create(ctx context.Context, it *model.Item) (*model.Item, error) { + if err := checkItemKey(it.RunningOrderID, it.StoryID, it.ID); err != nil { + return nil, err + } + var out *model.Item + err := pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + roID, storyID := it.RunningOrderID, it.StoryID + if err := itemSiblings.lockParent(ctx, tx, storyName(roID, storyID), roID, storyID); err != nil { + return err + } + var err error + out, err = insertItem(ctx, tx, it, itemSiblings.nextPosition()) + return err + }) + return out, err +} + +func (s items) Get(ctx context.Context, roID, storyID, itemID string) (*model.Item, error) { + it, err := scanItem(s.db.QueryRow(ctx, + "SELECT "+itemColumns+" FROM openmos.items WHERE ro_id = $1 AND story_id = $2 AND item_id = $3", + roID, storyID, itemID)) + if err != nil { + return nil, dbError(err, itemName(roID, storyID, itemID)) + } + return it, nil +} + +func (s items) Update(ctx context.Context, it *model.Item) error { + err := s.db.QueryRow(ctx, ` + UPDATE openmos.items SET + obj_id = $4, mos_id = $5, slug = $6, ed_dur = $7, time_base = NULLIF($8::float8, 0)::numeric, + status = $9, metadata = $10, updated_at = now() + WHERE ro_id = $1 AND story_id = $2 AND item_id = $3 + RETURNING position, created_at, updated_at`, + it.RunningOrderID, it.StoryID, it.ID, it.ObjectID, it.MosID, it.Slug, it.Duration, + it.TimeBase, string(it.Status), metadata(it.Metadata), + ).Scan(&it.Order, &it.CreatedAt, &it.UpdatedAt) + if err != nil { + return dbError(err, itemName(it.RunningOrderID, it.StoryID, it.ID)) + } + return nil +} + +func (s items) Delete(ctx context.Context, roID, storyID, itemID string) error { + tag, err := s.db.Exec(ctx, + "DELETE FROM openmos.items WHERE ro_id = $1 AND story_id = $2 AND item_id = $3", roID, storyID, itemID) + if err != nil { + return dbError(err, itemName(roID, storyID, itemID)) + } + if tag.RowsAffected() == 0 { + return fmt.Errorf("%s: %w", itemName(roID, storyID, itemID), repository.ErrNotFound) + } + return nil +} + +func (s items) ListByStory(ctx context.Context, roID, storyID string) ([]*model.Item, error) { + what := "items of " + roID + "/" + storyID + rows, err := s.db.Query(ctx, + "SELECT "+itemColumns+" FROM openmos.items WHERE ro_id = $1 AND story_id = $2 ORDER BY position, item_id", + roID, storyID) + if err != nil { + return nil, dbError(err, what) + } + list, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (*model.Item, error) { + return scanItem(row) + }) + if err != nil { + return nil, dbError(err, what) + } + return list, nil +} + +func (s items) Move(ctx context.Context, roID, storyID string, itemIDs []string, beforeID string) error { + return itemSiblings.reorder(ctx, s.db, "move items in "+roID+"/"+storyID, []any{roID, storyID}, + func(order []string) ([]string, error) { return repository.MoveIDs(order, itemIDs, beforeID) }) +} + +func (s items) Swap(ctx context.Context, roID, storyID, itemID1, itemID2 string) error { + return itemSiblings.reorder(ctx, s.db, "swap items in "+roID+"/"+storyID, []any{roID, storyID}, + func(order []string) ([]string, error) { return repository.SwapIDs(order, itemID1, itemID2) }) +} + +func (s items) ReplaceAll(ctx context.Context, roID, storyID string, list []*model.Item) error { + what := "replace items in " + roID + "/" + storyID + ids := make([]string, len(list)) + for i, it := range list { + if err := checkItemKey(roID, storyID, it.ID); err != nil { + return err + } + ids[i] = it.ID + } + if err := repository.CheckDistinct(ids); err != nil { + return fmt.Errorf("%s: %w", what, err) + } + return pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + if err := itemSiblings.lockParent(ctx, tx, storyName(roID, storyID), roID, storyID); err != nil { + return err + } + if _, err := tx.Exec(ctx, "DELETE FROM openmos.items WHERE ro_id = $1 AND story_id = $2", roID, storyID); err != nil { + return dbError(err, what) + } + for i, it := range list { + it.RunningOrderID, it.StoryID = roID, storyID + if _, err := insertItem(ctx, tx, it, fmt.Sprint(i)); err != nil { + return err + } + } + return nil + }) +} diff --git a/src/internal/store/postgres/object.go b/src/internal/store/postgres/object.go new file mode 100644 index 0000000..af63c9e --- /dev/null +++ b/src/internal/store/postgres/object.go @@ -0,0 +1,102 @@ +package postgres + +import ( + "context" + "fmt" + + "github.com/jackc/pgx/v5" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +type objects struct{ db DBTX } + +// objectColumns are read by scanObject. An empty type and a zero time base +// are stored as NULL, meaning unknown. +const objectColumns = `mos_id, obj_id, COALESCE(obj_type, ''), slug, COALESCE(duration, 0), + COALESCE(time_base, 0)::float8, status, abstract, metadata, created_at, updated_at` + +func scanObject(row pgx.Row) (*model.MOSObject, error) { + var o model.MOSObject + err := row.Scan(&o.MosID, &o.ID, &o.ObjectType, &o.Slug, &o.Duration, &o.TimeBase, + &o.Status, &o.Abstract, &o.Metadata, &o.CreatedAt, &o.UpdatedAt) + if err != nil { + return nil, err + } + return &o, nil +} + +func objectName(mosID, objID string) string { return "object " + mosID + "/" + objID } + +func (s objects) Create(ctx context.Context, obj *model.MOSObject) (*model.MOSObject, error) { + if err := repository.CheckID("MOS", obj.MosID); err != nil { + return nil, err + } + if err := repository.CheckID("object", obj.ID); err != nil { + return nil, err + } + out, err := scanObject(s.db.QueryRow(ctx, ` + INSERT INTO openmos.mos_objects + (mos_id, obj_id, obj_type, slug, duration, time_base, status, abstract, metadata) + VALUES ($1, $2, NULLIF($3, ''), $4, $5, NULLIF($6::float8, 0)::numeric, $7, $8, $9) + RETURNING `+objectColumns, + obj.MosID, obj.ID, obj.ObjectType, obj.Slug, obj.Duration, obj.TimeBase, + string(obj.Status), obj.Abstract, metadata(obj.Metadata))) + if err != nil { + return nil, dbError(err, objectName(obj.MosID, obj.ID)) + } + obj.CreatedAt, obj.UpdatedAt = out.CreatedAt, out.UpdatedAt + return out, nil +} + +func (s objects) Get(ctx context.Context, mosID, objID string) (*model.MOSObject, error) { + obj, err := scanObject(s.db.QueryRow(ctx, + "SELECT "+objectColumns+" FROM openmos.mos_objects WHERE mos_id = $1 AND obj_id = $2", mosID, objID)) + if err != nil { + return nil, dbError(err, objectName(mosID, objID)) + } + return obj, nil +} + +func (s objects) Update(ctx context.Context, obj *model.MOSObject) error { + err := s.db.QueryRow(ctx, ` + UPDATE openmos.mos_objects SET + obj_type = NULLIF($3, ''), slug = $4, duration = $5, time_base = NULLIF($6::float8, 0)::numeric, + status = $7, abstract = $8, metadata = $9, updated_at = now() + WHERE mos_id = $1 AND obj_id = $2 + RETURNING created_at, updated_at`, + obj.MosID, obj.ID, obj.ObjectType, obj.Slug, obj.Duration, obj.TimeBase, + string(obj.Status), obj.Abstract, metadata(obj.Metadata), + ).Scan(&obj.CreatedAt, &obj.UpdatedAt) + if err != nil { + return dbError(err, objectName(obj.MosID, obj.ID)) + } + return nil +} + +func (s objects) Delete(ctx context.Context, mosID, objID string) error { + tag, err := s.db.Exec(ctx, "DELETE FROM openmos.mos_objects WHERE mos_id = $1 AND obj_id = $2", mosID, objID) + if err != nil { + return dbError(err, objectName(mosID, objID)) + } + if tag.RowsAffected() == 0 { + return fmt.Errorf("%s: %w", objectName(mosID, objID), repository.ErrNotFound) + } + return nil +} + +func (s objects) List(ctx context.Context) ([]*model.MOSObject, error) { + rows, err := s.db.Query(ctx, + "SELECT "+objectColumns+" FROM openmos.mos_objects ORDER BY created_at DESC, mos_id DESC, obj_id DESC") + if err != nil { + return nil, dbError(err, "objects") + } + list, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (*model.MOSObject, error) { + return scanObject(row) + }) + if err != nil { + return nil, dbError(err, "objects") + } + return list, nil +} diff --git a/src/internal/store/postgres/repository.go b/src/internal/store/postgres/repository.go new file mode 100644 index 0000000..c09bda9 --- /dev/null +++ b/src/internal/store/postgres/repository.go @@ -0,0 +1,135 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "airshift/openmos/internal/repository" +) + +// DBTX is what the repositories need from a database handle. Both +// *pgxpool.Pool and pgx.Tx satisfy it; on a pgx.Tx, Begin starts a +// savepoint, so the repositories also work inside a caller's transaction. +type DBTX interface { + Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) + Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) + QueryRow(ctx context.Context, sql string, args ...any) pgx.Row + Begin(ctx context.Context) (pgx.Tx, error) +} + +// Repository implements repository.Repository on the openmos schema. The +// queries are written by hand; the behaviour is the contract in package +// repository, checked by the repotest suite. +type Repository struct{ db DBTX } + +var _ repository.Repository = (*Repository)(nil) + +// New returns a repository using db, normally a *pgxpool.Pool from NewPool. +// The schema must be migrated. +func New(db DBTX) *Repository { return &Repository{db: db} } + +func (r *Repository) RunningOrders() repository.RunningOrderRepository { return runningOrders{r.db} } +func (r *Repository) Stories() repository.StoryRepository { return stories{r.db} } +func (r *Repository) Items() repository.ItemRepository { return items{r.db} } +func (r *Repository) Objects() repository.ObjectRepository { return objects{r.db} } + +// dbError maps a database error to the repository errors, keeping the +// original in the chain. what names the record, as in "story ro-1/s1". +func dbError(err error, what string) error { + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s: %w", what, repository.ErrNotFound) + } + var pe *pgconn.PgError + if errors.As(err, &pe) { + var sentinel error + switch pe.Code { + case "23505": // unique_violation + sentinel = repository.ErrAlreadyExists + case "23503": // foreign_key_violation: the parent is gone + sentinel = repository.ErrNotFound + case "23514", // check_violation: a value outside its MOS limits + "22003", // numeric_value_out_of_range + "22021", // character_not_in_repertoire, e.g. a NUL byte + "22P05": // untranslatable_character + sentinel = repository.ErrInvalid + } + if sentinel != nil { + return fmt.Errorf("%s: %w: %w", what, sentinel, err) + } + } + return fmt.Errorf("%s: %w", what, err) +} + +// metadata returns m, or an empty map for nil: the column is NOT NULL and +// a nil map would encode as JSON null. +func metadata(m map[string]string) map[string]string { + if m == nil { + return map[string]string{} + } + return m +} + +// siblings describes the children of one parent: the stories of a running +// order or the items of a story. Its SQL takes the parent key as the first +// len(key) parameters. +type siblings struct { + table string // e.g. openmos.stories + idCol string // e.g. story_id + where string // selects the children of the parent, e.g. ro_id = $1 + lock string // locks the parent row; no row means no parent +} + +// lockParent locks the parent row against concurrent changes to its +// children's positions, and reports ErrNotFound if it does not exist. All +// operations that assign positions take this lock first, so appends, +// moves and replaces of one parent run one at a time. +func (s siblings) lockParent(ctx context.Context, tx pgx.Tx, what string, key ...any) error { + var one int + if err := tx.QueryRow(ctx, s.lock, key...).Scan(&one); err != nil { + return dbError(err, what) + } + return nil +} + +// nextPosition is a subquery giving the position after the last child. +func (s siblings) nextPosition() string { + return "(SELECT COALESCE(MAX(position) + 1, 0) FROM " + s.table + " WHERE " + s.where + ")" +} + +// reorder locks the parent, passes the current child IDs in order to +// compute and stores the order it returns. compute returns an order of the +// same IDs (see repository.MoveIDs and SwapIDs). +func (s siblings) reorder(ctx context.Context, db DBTX, what string, key []any, compute func([]string) ([]string, error)) error { + return pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error { + if err := s.lockParent(ctx, tx, what, key...); err != nil { + return err + } + rows, err := tx.Query(ctx, + "SELECT "+s.idCol+" FROM "+s.table+" WHERE "+s.where+" ORDER BY position, "+s.idCol, key...) + if err != nil { + return dbError(err, what) + } + ids, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + return dbError(err, what) + } + order, err := compute(ids) + if err != nil { + return fmt.Errorf("%s: %w", what, err) + } + // One statement, so the deferrable position constraint is checked + // only after every child has its new position. + n := len(key) + 1 + _, err = tx.Exec(ctx, fmt.Sprintf( + "UPDATE %s SET position = u.ord - 1 FROM unnest($%d::text[]) WITH ORDINALITY AS u(id, ord) WHERE %s AND %s = u.id", + s.table, n, s.where, s.idCol), append(key, order)...) + if err != nil { + return dbError(err, what) + } + return nil + }) +} diff --git a/src/internal/store/postgres/repository_test.go b/src/internal/store/postgres/repository_test.go new file mode 100644 index 0000000..bebdf13 --- /dev/null +++ b/src/internal/store/postgres/repository_test.go @@ -0,0 +1,80 @@ +package postgres + +import ( + "fmt" + "sync" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" + "airshift/openmos/internal/repository/repotest" +) + +// TestContract runs the repository contract suite against the test +// database. The schema is migrated once and the tables are emptied before +// each subtest. +func TestContract(t *testing.T) { + migrated(t) + pool, err := pgxpool.New(t.Context(), testDatabaseURL(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + + repo := New(pool) + repotest.Run(t, func(t *testing.T) repository.Repository { + _, err := pool.Exec(t.Context(), "TRUNCATE openmos.running_orders, openmos.mos_objects CASCADE") + if err != nil { + t.Fatalf("empty tables: %v", err) + } + return repo + }) +} + +// Appends to one parent from several connections must not race for the +// next position: each is serialised by the lock on the parent row. +func TestConcurrentAppends(t *testing.T) { + db := migrated(t) + pool, err := pgxpool.New(t.Context(), testDatabaseURL(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + repo, ctx := New(pool), t.Context() + if _, err := repo.RunningOrders().Create(ctx, &model.RunningOrder{ID: "ro"}); err != nil { + t.Fatal(err) + } + if _, err := repo.Stories().Create(ctx, &model.Story{RunningOrderID: "ro", ID: "s"}); err != nil { + t.Fatal(err) + } + + const n = 20 + var wg sync.WaitGroup + errs := make(chan error, 2*n) + for i := range n { + wg.Go(func() { + id := fmt.Sprint("c", i) + _, err := repo.Stories().Create(ctx, &model.Story{RunningOrderID: "ro", ID: id}) + errs <- err + _, err = repo.Items().Create(ctx, &model.Item{RunningOrderID: "ro", StoryID: "s", ID: id}) + errs <- err + }) + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Errorf("concurrent Create: %v", err) + } + } + // The unique constraints already rule out duplicates; positions must + // also have no gaps + for _, table := range []string{"stories", "items"} { + want := map[string]int{"stories": n, "items": n - 1}[table] + if got := count(t, db, "SELECT max(position) FROM openmos."+table); got != want { + t.Errorf("last %s position %d, want %d", table, got, want) + } + } +} diff --git a/src/internal/store/postgres/runningorder.go b/src/internal/store/postgres/runningorder.go new file mode 100644 index 0000000..7f38abb --- /dev/null +++ b/src/internal/store/postgres/runningorder.go @@ -0,0 +1,111 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "github.com/jackc/pgx/v5" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +type runningOrders struct{ db DBTX } + +// roColumns are read by scanRunningOrder. ed_dur holds roEdDur; the model +// keeps it in whole seconds. +const roColumns = `ro_id, mos_id, slug, status, + COALESCE(EXTRACT(EPOCH FROM ed_dur), 0)::bigint, ed_start, + channel, metadata, version, created_by, created_at, updated_at` + +func scanRunningOrder(row pgx.Row) (*model.RunningOrder, error) { + var ro model.RunningOrder + err := row.Scan(&ro.ID, &ro.MosID, &ro.Slug, &ro.Status, &ro.Duration, &ro.AirTime, + &ro.Channel, &ro.Metadata, &ro.Version, &ro.CreatedBy, &ro.CreatedAt, &ro.UpdatedAt) + if err != nil { + return nil, err + } + return &ro, nil +} + +func (s runningOrders) Create(ctx context.Context, ro *model.RunningOrder) (*model.RunningOrder, error) { + if err := repository.CheckID("running order", ro.ID); err != nil { + return nil, err + } + out, err := scanRunningOrder(s.db.QueryRow(ctx, ` + INSERT INTO openmos.running_orders + (ro_id, mos_id, slug, status, ed_dur, ed_start, channel, metadata, version, created_by) + VALUES ($1, $2, $3, $4, $5::bigint * interval '1 second', $6, $7, $8, 1, $9) + RETURNING `+roColumns, + ro.ID, ro.MosID, ro.Slug, string(ro.Status), ro.Duration, ro.AirTime, ro.Channel, + metadata(ro.Metadata), ro.CreatedBy)) + if err != nil { + return nil, dbError(err, "running order "+ro.ID) + } + ro.Version, ro.CreatedAt, ro.UpdatedAt = out.Version, out.CreatedAt, out.UpdatedAt + return out, nil +} + +func (s runningOrders) Get(ctx context.Context, roID string) (*model.RunningOrder, error) { + ro, err := scanRunningOrder(s.db.QueryRow(ctx, + "SELECT "+roColumns+" FROM openmos.running_orders WHERE ro_id = $1", roID)) + if err != nil { + return nil, dbError(err, "running order "+roID) + } + return ro, nil +} + +func (s runningOrders) Update(ctx context.Context, ro *model.RunningOrder) error { + what := "running order " + ro.ID + err := s.db.QueryRow(ctx, ` + UPDATE openmos.running_orders SET + mos_id = $3, slug = $4, status = $5, ed_dur = $6::bigint * interval '1 second', + ed_start = $7, channel = $8, metadata = $9, created_by = $10, + version = version + 1, updated_at = now() + WHERE ro_id = $1 AND version = $2 + RETURNING version, created_at, updated_at`, + ro.ID, ro.Version, ro.MosID, ro.Slug, string(ro.Status), ro.Duration, ro.AirTime, + ro.Channel, metadata(ro.Metadata), ro.CreatedBy, + ).Scan(&ro.Version, &ro.CreatedAt, &ro.UpdatedAt) + switch { + case err == nil: + return nil + case !errors.Is(err, pgx.ErrNoRows): + return dbError(err, what) + } + // No row matched: either it is gone or its version moved on + var current int + if err := s.db.QueryRow(ctx, + "SELECT version FROM openmos.running_orders WHERE ro_id = $1", ro.ID).Scan(¤t); err != nil { + return dbError(err, what) + } + return fmt.Errorf("%s at version %d, update based on %d: %w", + what, current, ro.Version, repository.ErrVersionConflict) +} + +func (s runningOrders) Delete(ctx context.Context, roID string) error { + tag, err := s.db.Exec(ctx, "DELETE FROM openmos.running_orders WHERE ro_id = $1", roID) + if err != nil { + return dbError(err, "running order "+roID) + } + if tag.RowsAffected() == 0 { + return fmt.Errorf("running order %s: %w", roID, repository.ErrNotFound) + } + return nil +} + +func (s runningOrders) List(ctx context.Context) ([]*model.RunningOrder, error) { + rows, err := s.db.Query(ctx, + "SELECT "+roColumns+" FROM openmos.running_orders ORDER BY created_at DESC, ro_id DESC") + if err != nil { + return nil, dbError(err, "running orders") + } + list, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (*model.RunningOrder, error) { + return scanRunningOrder(row) + }) + if err != nil { + return nil, dbError(err, "running orders") + } + return list, nil +} diff --git a/src/internal/store/postgres/story.go b/src/internal/store/postgres/story.go new file mode 100644 index 0000000..ae5c8bb --- /dev/null +++ b/src/internal/store/postgres/story.go @@ -0,0 +1,163 @@ +package postgres + +import ( + "context" + "fmt" + + "github.com/jackc/pgx/v5" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +type stories struct{ db DBTX } + +var storySiblings = siblings{ + table: "openmos.stories", + idCol: "story_id", + where: "ro_id = $1", + lock: "SELECT 1 FROM openmos.running_orders WHERE ro_id = $1 FOR NO KEY UPDATE", +} + +const storyColumns = "ro_id, story_id, position, slug, number, presenter, status, metadata, created_at, updated_at" + +func scanStory(row pgx.Row) (*model.Story, error) { + var s model.Story + err := row.Scan(&s.RunningOrderID, &s.ID, &s.Order, &s.Slug, &s.Number, &s.Presenter, + &s.Status, &s.Metadata, &s.CreatedAt, &s.UpdatedAt) + if err != nil { + return nil, err + } + return &s, nil +} + +func storyName(roID, storyID string) string { return "story " + roID + "/" + storyID } + +func checkStoryKey(roID, storyID string) error { + if err := repository.CheckID("running order", roID); err != nil { + return err + } + return repository.CheckID("story", storyID) +} + +// insertStory adds story to its running order at position, given as SQL. +// The caller holds the parent lock. +func insertStory(ctx context.Context, tx pgx.Tx, story *model.Story, position string) (*model.Story, error) { + out, err := scanStory(tx.QueryRow(ctx, ` + INSERT INTO openmos.stories (ro_id, story_id, position, slug, number, presenter, status, metadata) + VALUES ($1, $2, `+position+`, $3, $4, $5, $6, $7) + RETURNING `+storyColumns, + story.RunningOrderID, story.ID, story.Slug, story.Number, story.Presenter, + string(story.Status), metadata(story.Metadata))) + if err != nil { + return nil, dbError(err, storyName(story.RunningOrderID, story.ID)) + } + story.Order, story.CreatedAt, story.UpdatedAt = out.Order, out.CreatedAt, out.UpdatedAt + return out, nil +} + +func (s stories) Create(ctx context.Context, story *model.Story) (*model.Story, error) { + if err := checkStoryKey(story.RunningOrderID, story.ID); err != nil { + return nil, err + } + var out *model.Story + err := pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + roID := story.RunningOrderID + if err := storySiblings.lockParent(ctx, tx, "running order "+roID, roID); err != nil { + return err + } + var err error + out, err = insertStory(ctx, tx, story, storySiblings.nextPosition()) + return err + }) + return out, err +} + +func (s stories) Get(ctx context.Context, roID, storyID string) (*model.Story, error) { + story, err := scanStory(s.db.QueryRow(ctx, + "SELECT "+storyColumns+" FROM openmos.stories WHERE ro_id = $1 AND story_id = $2", roID, storyID)) + if err != nil { + return nil, dbError(err, storyName(roID, storyID)) + } + return story, nil +} + +func (s stories) Update(ctx context.Context, story *model.Story) error { + err := s.db.QueryRow(ctx, ` + UPDATE openmos.stories SET + slug = $3, number = $4, presenter = $5, status = $6, metadata = $7, updated_at = now() + WHERE ro_id = $1 AND story_id = $2 + RETURNING position, created_at, updated_at`, + story.RunningOrderID, story.ID, story.Slug, story.Number, story.Presenter, + string(story.Status), metadata(story.Metadata), + ).Scan(&story.Order, &story.CreatedAt, &story.UpdatedAt) + if err != nil { + return dbError(err, storyName(story.RunningOrderID, story.ID)) + } + return nil +} + +func (s stories) Delete(ctx context.Context, roID, storyID string) error { + tag, err := s.db.Exec(ctx, "DELETE FROM openmos.stories WHERE ro_id = $1 AND story_id = $2", roID, storyID) + if err != nil { + return dbError(err, storyName(roID, storyID)) + } + if tag.RowsAffected() == 0 { + return fmt.Errorf("%s: %w", storyName(roID, storyID), repository.ErrNotFound) + } + return nil +} + +func (s stories) ListByRunningOrder(ctx context.Context, roID string) ([]*model.Story, error) { + rows, err := s.db.Query(ctx, + "SELECT "+storyColumns+" FROM openmos.stories WHERE ro_id = $1 ORDER BY position, story_id", roID) + if err != nil { + return nil, dbError(err, "stories of "+roID) + } + list, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (*model.Story, error) { + return scanStory(row) + }) + if err != nil { + return nil, dbError(err, "stories of "+roID) + } + return list, nil +} + +func (s stories) Move(ctx context.Context, roID string, storyIDs []string, beforeID string) error { + return storySiblings.reorder(ctx, s.db, "move stories in "+roID, []any{roID}, + func(order []string) ([]string, error) { return repository.MoveIDs(order, storyIDs, beforeID) }) +} + +func (s stories) Swap(ctx context.Context, roID, storyID1, storyID2 string) error { + return storySiblings.reorder(ctx, s.db, "swap stories in "+roID, []any{roID}, + func(order []string) ([]string, error) { return repository.SwapIDs(order, storyID1, storyID2) }) +} + +func (s stories) ReplaceAll(ctx context.Context, roID string, list []*model.Story) error { + ids := make([]string, len(list)) + for i, story := range list { + if err := checkStoryKey(roID, story.ID); err != nil { + return err + } + ids[i] = story.ID + } + if err := repository.CheckDistinct(ids); err != nil { + return fmt.Errorf("replace stories in %s: %w", roID, err) + } + return pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + if err := storySiblings.lockParent(ctx, tx, "running order "+roID, roID); err != nil { + return err + } + // Deleting the stories deletes their items too + if _, err := tx.Exec(ctx, "DELETE FROM openmos.stories WHERE ro_id = $1", roID); err != nil { + return dbError(err, "replace stories in "+roID) + } + for i, story := range list { + story.RunningOrderID = roID + if _, err := insertStory(ctx, tx, story, fmt.Sprint(i)); err != nil { + return err + } + } + return nil + }) +}