diff --git a/doc/developer-reference.md b/doc/developer-reference.md index 46eaa0c..567713f 100644 --- a/doc/developer-reference.md +++ b/doc/developer-reference.md @@ -86,10 +86,13 @@ OpenMOS/ │ │ │ │ │ ├── repository/ │ │ │ ├── repository.go # Interface definitions +│ │ │ ├── errors.go # Shared errors (ErrNotFound, ...) │ │ │ ├── runningorder.go # RunningOrder MongoDB repo │ │ │ ├── story.go # Story MongoDB repo │ │ │ ├── item.go # Item MongoDB repo -│ │ │ └── object.go # MOSObject MongoDB repo +│ │ │ ├── object.go # MOSObject MongoDB repo +│ │ │ ├── memory/ # In-memory reference implementation +│ │ │ └── repotest/ # Contract suite for every implementation │ │ │ │ │ ├── server/ │ │ │ ├── server.go # TCPServer main logic @@ -319,6 +322,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`) - Use interfaces to enable mocking - Test XML parsing with example messages from `/res/` diff --git a/src/internal/repository/errors.go b/src/internal/repository/errors.go new file mode 100644 index 0000000..162265b --- /dev/null +++ b/src/internal/repository/errors.go @@ -0,0 +1,18 @@ +package repository + +import "errors" + +// Errors shared by all repository implementations. Implementations wrap them +// (fmt.Errorf("...: %w", ErrNotFound)), so callers test with errors.Is. +var ( + // ErrNotFound means the requested record, or the parent a new record + // refers to, does not exist. + ErrNotFound = errors.New("not found") + + // ErrAlreadyExists means Create was called with an ID 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") +) diff --git a/src/internal/repository/item.go b/src/internal/repository/item.go index 2765b21..aa6edc4 100644 --- a/src/internal/repository/item.go +++ b/src/internal/repository/item.go @@ -45,7 +45,7 @@ func (r *MongoItemRepository) Create(ctx context.Context, item *model.Item) (*mo return nil, fmt.Errorf("failed to check item ID uniqueness: %w", err) } if count > 0 { - return nil, fmt.Errorf("item with ID %s already exists", item.ID) + return nil, fmt.Errorf("item %s: %w", item.ID, ErrAlreadyExists) } _, err = r.collection.InsertOne(ctx, item) @@ -62,7 +62,7 @@ func (r *MongoItemRepository) Get(ctx context.Context, id string) (*model.Item, err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&item) if err != nil { if errors.Is(err, mongo.ErrNoDocuments) { - return nil, fmt.Errorf("item not found: %s", id) + return nil, fmt.Errorf("item %s: %w", id, ErrNotFound) } return nil, fmt.Errorf("failed to get item: %w", err) } @@ -75,10 +75,13 @@ func (r *MongoItemRepository) Update(ctx context.Context, item *model.Item) erro item.UpdatedAt = now filter := bson.M{"_id": item.ID} - _, err := r.collection.ReplaceOne(ctx, filter, item) + result, err := r.collection.ReplaceOne(ctx, filter, item) if err != nil { return fmt.Errorf("failed to update item: %w", err) } + if result.MatchedCount == 0 { + return fmt.Errorf("item %s: %w", item.ID, ErrNotFound) + } return nil } @@ -91,7 +94,7 @@ func (r *MongoItemRepository) Delete(ctx context.Context, id string) error { } if result.DeletedCount == 0 { - return fmt.Errorf("item not found: %s", id) + return fmt.Errorf("item %s: %w", id, ErrNotFound) } return nil diff --git a/src/internal/repository/memory/item.go b/src/internal/repository/memory/item.go new file mode 100644 index 0000000..e3c49ec --- /dev/null +++ b/src/internal/repository/memory/item.go @@ -0,0 +1,85 @@ +package memory + +import ( + "context" + "errors" + "fmt" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +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") + } + 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) + } + if err := s.checkParentLocked(item); err != nil { + return nil, err + } + t := now() + item.CreatedAt, item.UpdatedAt = t, t + s.r.items[item.ID] = cloneItem(item) + return cloneItem(item), nil +} + +func (s items) Get(_ context.Context, id string) (*model.Item, error) { + s.r.mu.RLock() + defer s.r.mu.RUnlock() + item, ok := s.r.items[id] + if !ok { + return nil, fmt.Errorf("item %s: %w", id, repository.ErrNotFound) + } + return cloneItem(item), nil +} + +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] + if !ok { + return fmt.Errorf("item %s: %w", item.ID, repository.ErrNotFound) + } + if err := s.checkParentLocked(item); err != nil { + return err + } + item.CreatedAt = current.CreatedAt + item.UpdatedAt = now() + s.r.items[item.ID] = cloneItem(item) + return nil +} + +func (s items) Delete(_ context.Context, id 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) + } + delete(s.r.items, id) + return nil +} + +func (s items) ListByStory(_ context.Context, storyID string) ([]*model.Item, error) { + s.r.mu.RLock() + defer s.r.mu.RUnlock() + return sorted(s.r.items, + func(item *model.Item) bool { return item.StoryID == storyID }, + cloneItem, + func(a, b *model.Item) int { return byOrder(a.Order, b.Order, a.ID, b.ID) }, + ), nil +} + +// 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) + } + return nil +} diff --git a/src/internal/repository/memory/memory.go b/src/internal/repository/memory/memory.go new file mode 100644 index 0000000..8a7ea68 --- /dev/null +++ b/src/internal/repository/memory/memory.go @@ -0,0 +1,121 @@ +// Package memory is an in-memory implementation of repository.Repository. +// +// It is the reference implementation of the contract in package repotest and +// a fake for service tests. Nothing is persisted. +package memory + +import ( + "cmp" + "maps" + "slices" + "sync" + "time" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +// 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 +} + +// 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), + } +} + +var _ repository.Repository = (*Repository)(nil) + +// RunningOrders returns the running order repository. +func (r *Repository) RunningOrders() repository.RunningOrderRepository { return runningOrders{r} } + +// Stories returns the story repository. +func (r *Repository) Stories() repository.StoryRepository { return stories{r} } + +// Items returns the item repository. +func (r *Repository) Items() repository.ItemRepository { return items{r} } + +// Objects returns the MOS object repository. +func (r *Repository) Objects() repository.ObjectRepository { return objects{r} } + +// now returns the current time without the monotonic reading, so stored +// timestamps compare like ones read back from a database. +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) + } + } +} + +// Stored values are copied on the way in and out, so callers never share +// memory with the store. + +func cloneRunningOrder(ro *model.RunningOrder) *model.RunningOrder { + c := *ro + c.Metadata = maps.Clone(ro.Metadata) + if ro.AirTime != nil { + t := *ro.AirTime + c.AirTime = &t + } + return &c +} + +func cloneStory(s *model.Story) *model.Story { + c := *s + c.Metadata = maps.Clone(s.Metadata) + return &c +} + +func cloneItem(i *model.Item) *model.Item { + c := *i + c.Metadata = maps.Clone(i.Metadata) + return &c +} + +func cloneObject(o *model.MOSObject) *model.MOSObject { + c := *o + c.Metadata = maps.Clone(o.Metadata) + return &c +} + +// newestFirst orders by CreatedAt descending, then by ID for equal times. +func newestFirst(aCreated, bCreated time.Time, aID, bID 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)) +} + +// 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 { + out := make([]*T, 0) + for _, v := range m { + if keep(v) { + out = append(out, clone(v)) + } + } + slices.SortFunc(out, cmpFn) + return out +} diff --git a/src/internal/repository/memory/memory_test.go b/src/internal/repository/memory/memory_test.go new file mode 100644 index 0000000..ca4c420 --- /dev/null +++ b/src/internal/repository/memory/memory_test.go @@ -0,0 +1,13 @@ +package memory_test + +import ( + "testing" + + "airshift/openmos/internal/repository" + "airshift/openmos/internal/repository/memory" + "airshift/openmos/internal/repository/repotest" +) + +func TestContract(t *testing.T) { + repotest.Run(t, func(*testing.T) repository.Repository { return memory.New() }) +} diff --git a/src/internal/repository/memory/object.go b/src/internal/repository/memory/object.go new file mode 100644 index 0000000..7652356 --- /dev/null +++ b/src/internal/repository/memory/object.go @@ -0,0 +1,70 @@ +package memory + +import ( + "context" + "errors" + "fmt" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +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") + } + 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) + } + t := now() + obj.CreatedAt, obj.UpdatedAt = t, t + s.r.objects[obj.ID] = cloneObject(obj) + return cloneObject(obj), nil +} + +func (s objects) Get(_ context.Context, id string) (*model.MOSObject, error) { + s.r.mu.RLock() + defer s.r.mu.RUnlock() + obj, ok := s.r.objects[id] + if !ok { + return nil, fmt.Errorf("object %s: %w", id, repository.ErrNotFound) + } + return cloneObject(obj), nil +} + +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] + if !ok { + return fmt.Errorf("object %s: %w", obj.ID, repository.ErrNotFound) + } + obj.CreatedAt = current.CreatedAt + obj.UpdatedAt = now() + s.r.objects[obj.ID] = cloneObject(obj) + return nil +} + +func (s objects) Delete(_ context.Context, id 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) + } + delete(s.r.objects, id) + return nil +} + +func (s objects) List(_ context.Context) ([]*model.MOSObject, error) { + s.r.mu.RLock() + defer s.r.mu.RUnlock() + 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) }, + ), nil +} diff --git a/src/internal/repository/memory/runningorder.go b/src/internal/repository/memory/runningorder.go new file mode 100644 index 0000000..24eba17 --- /dev/null +++ b/src/internal/repository/memory/runningorder.go @@ -0,0 +1,80 @@ +package memory + +import ( + "context" + "errors" + "fmt" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +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") + } + s.r.mu.Lock() + defer s.r.mu.Unlock() + if _, ok := s.r.runningOrders[ro.ID]; ok { + return nil, fmt.Errorf("running order %s: %w", ro.ID, repository.ErrAlreadyExists) + } + t := now() + ro.CreatedAt, ro.UpdatedAt, ro.Version = t, t, 1 + s.r.runningOrders[ro.ID] = cloneRunningOrder(ro) + return cloneRunningOrder(ro), nil +} + +func (s runningOrders) Get(_ context.Context, id string) (*model.RunningOrder, error) { + s.r.mu.RLock() + defer s.r.mu.RUnlock() + ro, ok := s.r.runningOrders[id] + if !ok { + return nil, fmt.Errorf("running order %s: %w", id, repository.ErrNotFound) + } + return cloneRunningOrder(ro), nil +} + +func (s runningOrders) Update(_ context.Context, ro *model.RunningOrder) error { + s.r.mu.Lock() + defer s.r.mu.Unlock() + current, ok := s.r.runningOrders[ro.ID] + if !ok { + return fmt.Errorf("running order %s: %w", ro.ID, repository.ErrNotFound) + } + if ro.Version != current.Version { + return fmt.Errorf("running order %s at version %d, update based on %d: %w", + ro.ID, current.Version, ro.Version, repository.ErrVersionConflict) + } + ro.Version++ + ro.CreatedAt = current.CreatedAt + ro.UpdatedAt = now() + s.r.runningOrders[ro.ID] = cloneRunningOrder(ro) + return nil +} + +func (s runningOrders) Delete(_ context.Context, id 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) + } + delete(s.r.runningOrders, id) + for storyID, story := range s.r.stories { + if story.RunningOrderID == id { + s.r.deleteStoryLocked(storyID) + } + } + return nil +} + +func (s runningOrders) List(_ context.Context) ([]*model.RunningOrder, error) { + s.r.mu.RLock() + defer s.r.mu.RUnlock() + return sorted(s.r.runningOrders, + func(*model.RunningOrder) bool { return true }, + cloneRunningOrder, + func(a, b *model.RunningOrder) int { return newestFirst(a.CreatedAt, b.CreatedAt, a.ID, b.ID) }, + ), nil +} diff --git a/src/internal/repository/memory/story.go b/src/internal/repository/memory/story.go new file mode 100644 index 0000000..7f84988 --- /dev/null +++ b/src/internal/repository/memory/story.go @@ -0,0 +1,86 @@ +package memory + +import ( + "context" + "errors" + "fmt" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +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") + } + 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) + } + if err := s.checkParentLocked(story); err != nil { + return nil, err + } + t := now() + story.CreatedAt, story.UpdatedAt = t, t + s.r.stories[story.ID] = cloneStory(story) + return cloneStory(story), nil +} + +func (s stories) Get(_ context.Context, id string) (*model.Story, error) { + s.r.mu.RLock() + defer s.r.mu.RUnlock() + story, ok := s.r.stories[id] + if !ok { + return nil, fmt.Errorf("story %s: %w", id, repository.ErrNotFound) + } + return cloneStory(story), nil +} + +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] + if !ok { + return fmt.Errorf("story %s: %w", story.ID, repository.ErrNotFound) + } + if err := s.checkParentLocked(story); err != nil { + return err + } + story.CreatedAt = current.CreatedAt + story.UpdatedAt = now() + s.r.stories[story.ID] = cloneStory(story) + return nil +} + +func (s stories) Delete(_ context.Context, id 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) + } + s.r.deleteStoryLocked(id) + return nil +} + +func (s stories) ListByRunningOrder(_ context.Context, roID string) ([]*model.Story, error) { + s.r.mu.RLock() + defer s.r.mu.RUnlock() + 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 +} + +// 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) + } + return nil +} diff --git a/src/internal/repository/object.go b/src/internal/repository/object.go index 1b1aa62..4b5f1ae 100644 --- a/src/internal/repository/object.go +++ b/src/internal/repository/object.go @@ -45,7 +45,7 @@ func (r *MongoObjectRepository) Create(ctx context.Context, obj *model.MOSObject return nil, fmt.Errorf("failed to check object ID uniqueness: %w", err) } if count > 0 { - return nil, fmt.Errorf("object with ID %s already exists", obj.ID) + return nil, fmt.Errorf("object %s: %w", obj.ID, ErrAlreadyExists) } _, err = r.collection.InsertOne(ctx, obj) @@ -62,7 +62,7 @@ func (r *MongoObjectRepository) Get(ctx context.Context, id string) (*model.MOSO err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&obj) if err != nil { if errors.Is(err, mongo.ErrNoDocuments) { - return nil, fmt.Errorf("object not found: %s", id) + return nil, fmt.Errorf("object %s: %w", id, ErrNotFound) } return nil, fmt.Errorf("failed to get object: %w", err) } @@ -75,10 +75,13 @@ func (r *MongoObjectRepository) Update(ctx context.Context, obj *model.MOSObject obj.UpdatedAt = now filter := bson.M{"_id": obj.ID} - _, err := r.collection.ReplaceOne(ctx, filter, obj) + result, err := r.collection.ReplaceOne(ctx, filter, obj) if err != nil { return fmt.Errorf("failed to update object: %w", err) } + if result.MatchedCount == 0 { + return fmt.Errorf("object %s: %w", obj.ID, ErrNotFound) + } return nil } @@ -91,7 +94,7 @@ func (r *MongoObjectRepository) Delete(ctx context.Context, id string) error { } if result.DeletedCount == 0 { - return fmt.Errorf("object not found: %s", id) + return fmt.Errorf("object %s: %w", id, ErrNotFound) } return nil diff --git a/src/internal/repository/repository.go b/src/internal/repository/repository.go index 7c165d4..18a3afc 100644 --- a/src/internal/repository/repository.go +++ b/src/internal/repository/repository.go @@ -1,3 +1,22 @@ +// Package repository defines the storage interfaces used by the MOS service. +// +// 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. +// - 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. +// - Returned values are copies: changing them does not change stored data. package repository import ( @@ -14,19 +33,19 @@ type RunningOrderRepository interface { // Get retrieves a running order by ID Get(ctx context.Context, id string) (*model.RunningOrder, error) - // Update updates a running order + // Update updates a running order, checking its version Update(ctx context.Context, ro *model.RunningOrder) error - // Delete deletes a running order + // Delete deletes a running order with its stories and items Delete(ctx context.Context, id string) error - // List returns all running orders + // List returns all running orders, newest first List(ctx context.Context) ([]*model.RunningOrder, error) } // StoryRepository defines operations for stories type StoryRepository interface { - // Create creates a new story + // Create creates a new story in an existing running order Create(ctx context.Context, story *model.Story) (*model.Story, error) // Get retrieves a story by ID @@ -35,16 +54,16 @@ type StoryRepository interface { // Update updates a story Update(ctx context.Context, story *model.Story) error - // Delete deletes a story + // Delete deletes a story with its items Delete(ctx context.Context, id string) error - // ListByRunningOrder returns all stories for a running order + // ListByRunningOrder returns the stories of a running order by Order ListByRunningOrder(ctx context.Context, roID string) ([]*model.Story, error) } // ItemRepository defines operations for items type ItemRepository interface { - // Create creates a new item + // Create creates a new item in an existing story Create(ctx context.Context, item *model.Item) (*model.Item, error) // Get retrieves an item by ID @@ -56,7 +75,7 @@ type ItemRepository interface { // Delete deletes an item Delete(ctx context.Context, id string) error - // ListByStory returns all items for a story + // ListByStory returns the items of a story by Order ListByStory(ctx context.Context, storyID string) ([]*model.Item, error) } @@ -74,7 +93,7 @@ type ObjectRepository interface { // Delete deletes a MOS object Delete(ctx context.Context, id string) error - // List returns all MOS objects + // 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 new file mode 100644 index 0000000..0ec4750 --- /dev/null +++ b/src/internal/repository/repotest/cascade.go @@ -0,0 +1,86 @@ +package repotest + +import ( + "testing" + + "airshift/openmos/internal/repository" +) + +func testCascade(t *testing.T, newRepo Factory) { + // setup creates two running orders with stories and items, and an object: + // + // ro-1: s1 (i1, i2), s2 (i3) + // ro-2: s3 (i4) + // 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") + return r + } + + 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"}) + }) + + t.Run("DeleteStory", func(t *testing.T) { + r := setup(t) + must(t, "Delete s1", r.Stories().Delete(t.Context(), "s1")) + + 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"}) + }) +} + +// 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) + } +} + +// kept fails the test unless all the given records still exist. +func kept(t *testing.T, r repository.Repository, ros, stories, items, objects []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 _, 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 new file mode 100644 index 0000000..35b969d --- /dev/null +++ b/src/internal/repository/repotest/children.go @@ -0,0 +1,78 @@ +package repotest + +import ( + "testing" + + "airshift/openmos/internal/repository" +) + +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)) + wantErr(t, "Create story without running order", err, repository.ErrNotFound) + }) + + t.Run("ListByRunningOrder", func(t *testing.T) { + r := newRepo(t) + 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) + + list := func(roID string) []string { + t.Helper() + stories, err := r.Stories().ListByRunningOrder(t.Context(), roID) + must(t, "ListByRunningOrder "+roID, err) + return storyKind.ids(stories) + } + 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"}) + }) +} + +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)) + wantErr(t, "Create item without story", err, repository.ErrNotFound) + }) + + t.Run("ListByStory", func(t *testing.T) { + r := newRepo(t) + 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) + } + 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"}) + }) +} diff --git a/src/internal/repository/repotest/crud.go b/src/internal/repository/repotest/crud.go new file mode 100644 index 0000000..92a6ff1 --- /dev/null +++ b/src/internal/repository/repotest/crud.go @@ -0,0 +1,132 @@ +package repotest + +import ( + "context" + "testing" + "time" + + "airshift/openmos/internal/repository" +) + +// 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) + } + + t.Run("CreateAndGet", func(t *testing.T) { + ctx, r := setup(t) + before := time.Now() + created, err := r.Create(ctx, k.fixture("a")) + after := time.Now() + must(t, "Create", err) + c := k.fields(created) + if !within(*c.CreatedAt, before, after) || !within(*c.UpdatedAt, before, after) { + t.Errorf("Create set CreatedAt %v, UpdatedAt %v; want both between %v and %v", + *c.CreatedAt, *c.UpdatedAt, before, after) + } + k.same(t, "Create result", created, k.fixture("a")) + + got, err := r.Get(ctx, "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) { + t.Errorf("Get timestamps %v / %v, want %v / %v", *g.CreatedAt, *g.UpdatedAt, *c.CreatedAt, *c.UpdatedAt) + } + }) + + 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") + } + }) + + t.Run("CreateDuplicate", func(t *testing.T) { + ctx, r := setup(t) + _, err := r.Create(ctx, k.fixture("a")) + must(t, "Create", err) + dup := k.fixture("a") + *k.fields(dup).Slug = "duplicate" + _, err = r.Create(ctx, dup) + wantErr(t, "Create duplicate", err, repository.ErrAlreadyExists) + + got, err := r.Get(ctx, "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") + 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")) + must(t, "Create", err) + c := k.fields(created) + + got, err := r.Get(ctx, "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)) + + updated, err := r.Get(ctx, "a") + must(t, "Get after Update", err) + k.same(t, "Get after Update", updated, got) + u := k.fields(updated) + if !closeTo(*u.CreatedAt, *c.CreatedAt) { + t.Errorf("Update changed CreatedAt from %v to %v", *c.CreatedAt, *u.CreatedAt) + } + if u.UpdatedAt.Before(c.UpdatedAt.Add(-time.Millisecond)) { + t.Errorf("Update moved UpdatedAt back from %v to %v", *c.UpdatedAt, *u.UpdatedAt) + } + }) + + 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) + }) + + t.Run("Delete", func(t *testing.T) { + ctx, r := setup(t) + for _, id := range []string{"a", "b"} { + _, err := r.Create(ctx, k.fixture(id)) + must(t, "Create "+id, err) + } + must(t, "Delete", r.Delete(ctx, "a")) + + _, err := r.Get(ctx, "a") + wantErr(t, "Get deleted", err, repository.ErrNotFound) + _, err = r.Get(ctx, "b") + must(t, "Get other record after Delete", err) + wantErr(t, "Delete again", r.Delete(ctx, "a"), repository.ErrNotFound) + }) + + t.Run("ReturnsCopies", func(t *testing.T) { + ctx, r := setup(t) + in := k.fixture("a") + _, err := r.Create(ctx, 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") + 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") + 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 new file mode 100644 index 0000000..7dce34b --- /dev/null +++ b/src/internal/repository/repotest/fixtures.go @@ -0,0 +1,78 @@ +package repotest + +import ( + "testing" + "time" + + "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" +) + +// IDs of the parents created for the story and item CRUD tests. +const ( + parentRO = "ro-parent" + parentStory = "story-parent" +) + +// The fixtures fill every field, so a store that drops one fails the +// round-trip comparison. + +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", + } +} + +func newStory(id, roID string, order int) *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", + Metadata: map[string]string{"k": "v"}, + } +} + +func newItem(id, storyID string, order int) *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"}, + } +} + +func newObject(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"}, + } +} + +func createRunningOrder(t *testing.T, r repository.Repository, id string) { + t.Helper() + _, err := r.RunningOrders().Create(t.Context(), newRunningOrder(id)) + must(t, "create running order "+id, err) +} + +func createStory(t *testing.T, r repository.Repository, id, roID string, order int) { + t.Helper() + _, err := r.Stories().Create(t.Context(), newStory(id, roID, order)) + must(t, "create story "+id, err) +} + +func createItem(t *testing.T, r repository.Repository, id, storyID string, order int) { + t.Helper() + _, err := r.Items().Create(t.Context(), newItem(id, storyID, order)) + must(t, "create item "+id, err) +} + +func createObject(t *testing.T, r repository.Repository, id string) { + t.Helper() + _, err := r.Objects().Create(t.Context(), newObject(id)) + must(t, "create object "+id, err) +} diff --git a/src/internal/repository/repotest/kinds.go b/src/internal/repository/repotest/kinds.go new file mode 100644 index 0000000..aa29266 --- /dev/null +++ b/src/internal/repository/repotest/kinds.go @@ -0,0 +1,116 @@ +package repotest + +import ( + "context" + "reflect" + "testing" + "time" + + "airshift/openmos/internal/model" + "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 + Metadata *map[string]string + CreatedAt, UpdatedAt *time.Time +} + +// kind describes one record type to the shared CRUD tests in crud.go. +type kind[T any] struct { + repo func(repository.Repository) crud[T] + parents func(t *testing.T, repo repository.Repository) // creates what fixture refers to + fixture func(id string) *T + fields func(v *T) common + + // normalize, if set, adjusts type-specific fields before comparison. + normalize func(v *T) +} + +// norm returns v without the fields a store sets itself, and with an empty +// map and nil map treated alike, so records can be compared with DeepEqual. +func (k kind[T]) norm(v T) T { + f := k.fields(&v) + *f.CreatedAt, *f.UpdatedAt = time.Time{}, time.Time{} + if len(*f.Metadata) == 0 { + *f.Metadata = nil + } + if k.normalize != nil { + k.normalize(&v) + } + return v +} + +// same fails the test unless got and want hold the same data. +func (k kind[T]) same(t *testing.T, op string, got, want *T) { + t.Helper() + if g, w := k.norm(*got), k.norm(*want); !reflect.DeepEqual(g, w) { + t.Errorf("%s:\n got %+v\n want %+v", op, g, w) + } +} + +// ids returns the IDs of list, in order. +func (k kind[T]) ids(list []*T) []string { + out := make([]string, len(list)) + for i, v := range list { + out[i] = *k.fields(v).ID + } + return out +} + +var runningOrderKind = kind[model.RunningOrder]{ + repo: func(r repository.Repository) crud[model.RunningOrder] { return r.RunningOrders() }, + parents: func(*testing.T, repository.Repository) {}, + fixture: newRunningOrder, + fields: func(v *model.RunningOrder) common { + return common{&v.ID, &v.Slug, &v.Metadata, &v.CreatedAt, &v.UpdatedAt} + }, + // A store may return AirTime in another time zone; compare the instant. + normalize: func(v *model.RunningOrder) { + if v.AirTime != nil { + air := v.AirTime.UTC() + v.AirTime = &air + } + }, +} + +var storyKind = kind[model.Story]{ + repo: func(r repository.Repository) crud[model.Story] { return r.Stories() }, + parents: func(t *testing.T, r repository.Repository) { + createRunningOrder(t, r, parentRO) + }, + fixture: func(id string) *model.Story { return newStory(id, parentRO, 1) }, + fields: func(v *model.Story) common { + return common{&v.ID, &v.Slug, &v.Metadata, &v.CreatedAt, &v.UpdatedAt} + }, +} + +var itemKind = kind[model.Item]{ + repo: func(r repository.Repository) crud[model.Item] { return r.Items() }, + parents: func(t *testing.T, r repository.Repository) { + createRunningOrder(t, r, parentRO) + createStory(t, r, parentStory, parentRO, 1) + }, + 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} + }, +} + +var objectKind = kind[model.MOSObject]{ + repo: func(r repository.Repository) crud[model.MOSObject] { return r.Objects() }, + parents: func(*testing.T, repository.Repository) {}, + fixture: newObject, + 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 new file mode 100644 index 0000000..0ac8719 --- /dev/null +++ b/src/internal/repository/repotest/object.go @@ -0,0 +1,20 @@ +package repotest + +import "testing" + +func testObjects(t *testing.T, newRepo Factory) { + t.Run("ListNewestFirst", func(t *testing.T) { + r := newRepo(t) + list, err := r.Objects().List(t.Context()) + must(t, "List empty", err) + equalIDs(t, "List empty", objectKind.ids(list), nil) + + for _, id := range []string{"a", "b", "c"} { + createObject(t, r, id) + tick() + } + list, err = r.Objects().List(t.Context()) + must(t, "List", err) + equalIDs(t, "List", objectKind.ids(list), []string{"c", "b", "a"}) + }) +} diff --git a/src/internal/repository/repotest/repotest.go b/src/internal/repository/repotest/repotest.go new file mode 100644 index 0000000..5542c0a --- /dev/null +++ b/src/internal/repository/repotest/repotest.go @@ -0,0 +1,89 @@ +// Package repotest is the contract test suite for repository.Repository. +// Every storage implementation runs it from its own tests: +// +// func TestContract(t *testing.T) { +// repotest.Run(t, func(t *testing.T) repository.Repository { +// return memory.New() +// }) +// } +// +// The behaviour it checks is summarised in the repository package comment. +package repotest + +import ( + "errors" + "slices" + "testing" + "time" + + "airshift/openmos/internal/repository" +) + +// Factory returns an empty repository. It is called once per subtest, and +// subtests run one at a time, so a database-backed factory may reset shared +// tables. It may register cleanup with t.Cleanup. +type Factory func(t *testing.T) repository.Repository + +// Run runs the whole contract suite against repositories from newRepo. +func Run(t *testing.T, newRepo Factory) { + t.Run("RunningOrders", func(t *testing.T) { + testCRUD(t, newRepo, runningOrderKind) + testRunningOrders(t, newRepo) + }) + t.Run("Stories", func(t *testing.T) { + testCRUD(t, newRepo, storyKind) + testStories(t, newRepo) + }) + t.Run("Items", func(t *testing.T) { + testCRUD(t, newRepo, itemKind) + testItems(t, newRepo) + }) + t.Run("Objects", func(t *testing.T) { + testCRUD(t, newRepo, objectKind) + testObjects(t, newRepo) + }) + t.Run("Cascade", func(t *testing.T) { testCascade(t, newRepo) }) +} + +// must stops the test if a setup step fails. +func must(t *testing.T, op string, err error) { + t.Helper() + if err != nil { + t.Fatalf("%s: %v", op, err) + } +} + +// wantErr fails the test unless err wraps target. +func wantErr(t *testing.T, op string, err, target error) { + t.Helper() + if !errors.Is(err, target) { + t.Errorf("%s: err = %v, want %v", op, err, target) + } +} + +// tick waits long enough that records created before and after it get +// distinct CreatedAt values, even in a store with millisecond precision. +func tick() { time.Sleep(2 * time.Millisecond) } + +// clockSkew allows for a store that sets timestamps with its own clock. +const clockSkew = 2 * time.Second + +// within reports whether ts lies between from and to, allowing clockSkew. +func within(ts, from, to time.Time) bool { + return !ts.Before(from.Add(-clockSkew)) && !ts.After(to.Add(clockSkew)) +} + +// closeTo reports whether a and b are equal at the precision a store may +// round timestamps to. +func closeTo(a, b time.Time) bool { + d := a.Sub(b) + return d > -time.Millisecond && d < time.Millisecond +} + +// equalIDs fails the test unless got lists exactly the IDs in want, in order. +func equalIDs(t *testing.T, op string, got, want []string) { + t.Helper() + if !slices.Equal(got, want) { + t.Errorf("%s: IDs = %v, want %v", op, got, want) + } +} diff --git a/src/internal/repository/repotest/runningorder.go b/src/internal/repository/repotest/runningorder.go new file mode 100644 index 0000000..e014316 --- /dev/null +++ b/src/internal/repository/repotest/runningorder.go @@ -0,0 +1,78 @@ +package repotest + +import ( + "testing" + + "airshift/openmos/internal/repository" +) + +func testRunningOrders(t *testing.T, newRepo Factory) { + t.Run("CreateSetsVersion", func(t *testing.T) { + r := newRepo(t).RunningOrders() + in := newRunningOrder("a") + in.Version = 7 + created, err := r.Create(t.Context(), in) + must(t, "Create", err) + got, err := r.Get(t.Context(), "a") + must(t, "Get", err) + if created.Version != 1 || got.Version != 1 { + t.Errorf("version after Create = %d (stored %d), want 1", created.Version, got.Version) + } + }) + + t.Run("UpdateIncrementsVersion", func(t *testing.T) { + r := newRepo(t).RunningOrders() + _, err := r.Create(t.Context(), newRunningOrder("a")) + must(t, "Create", err) + ro, err := r.Get(t.Context(), "a") + must(t, "Get", err) + for want := 2; want <= 3; want++ { + must(t, "Update", r.Update(t.Context(), ro)) + if ro.Version != want { + t.Errorf("Update set passed Version to %d, want %d", ro.Version, want) + } + } + got, err := r.Get(t.Context(), "a") + must(t, "Get", err) + if got.Version != 3 { + t.Errorf("stored Version = %d, want 3", got.Version) + } + }) + + t.Run("UpdateStaleVersion", func(t *testing.T) { + r := newRepo(t).RunningOrders() + _, err := r.Create(t.Context(), newRunningOrder("a")) + must(t, "Create", err) + first, err := r.Get(t.Context(), "a") + must(t, "Get", err) + second, err := r.Get(t.Context(), "a") + must(t, "Get", err) + + first.Slug = "first writer" + must(t, "first Update", r.Update(t.Context(), first)) + second.Slug = "second writer" + wantErr(t, "Update with stale version", r.Update(t.Context(), second), repository.ErrVersionConflict) + + got, err := r.Get(t.Context(), "a") + must(t, "Get", err) + if got.Slug != "first writer" || got.Version != 2 { + t.Errorf("after conflict: Slug %q, Version %d; want %q, 2", got.Slug, got.Version, "first writer") + } + }) + + t.Run("ListNewestFirst", func(t *testing.T) { + r := newRepo(t).RunningOrders() + list, err := r.List(t.Context()) + must(t, "List empty", err) + equalIDs(t, "List empty", runningOrderKind.ids(list), nil) + + for _, id := range []string{"a", "b", "c"} { + _, err := r.Create(t.Context(), newRunningOrder(id)) + must(t, "Create "+id, err) + tick() + } + list, err = r.List(t.Context()) + must(t, "List", err) + equalIDs(t, "List", runningOrderKind.ids(list), []string{"c", "b", "a"}) + }) +} diff --git a/src/internal/repository/runningorder.go b/src/internal/repository/runningorder.go index 65afdf5..b3a7eb9 100644 --- a/src/internal/repository/runningorder.go +++ b/src/internal/repository/runningorder.go @@ -46,7 +46,7 @@ func (r *MongoRunningOrderRepository) Create(ctx context.Context, ro *model.Runn return nil, fmt.Errorf("failed to check running order ID uniqueness: %w", err) } if count > 0 { - return nil, fmt.Errorf("running order with ID %s already exists", ro.ID) + return nil, fmt.Errorf("running order %s: %w", ro.ID, ErrAlreadyExists) } _, err = r.collection.InsertOne(ctx, ro) @@ -63,7 +63,7 @@ func (r *MongoRunningOrderRepository) Get(ctx context.Context, id string) (*mode err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&ro) if err != nil { if errors.Is(err, mongo.ErrNoDocuments) { - return nil, fmt.Errorf("running order not found: %s", id) + return nil, fmt.Errorf("running order %s: %w", id, ErrNotFound) } return nil, fmt.Errorf("failed to get running order: %w", err) } @@ -72,24 +72,24 @@ func (r *MongoRunningOrderRepository) Get(ctx context.Context, id string) (*mode // Update updates a running order func (r *MongoRunningOrderRepository) Update(ctx context.Context, ro *model.RunningOrder) error { - now := time.Now() - ro.UpdatedAt = now - ro.Version++ - - // Get current document to check version + // Get current document to check version. This read-then-replace is not + // atomic; MOS-15 replaces it with a version-checked write. var current model.RunningOrder err := r.collection.FindOne(ctx, bson.M{"_id": ro.ID}).Decode(¤t) if err != nil { if errors.Is(err, mongo.ErrNoDocuments) { - return fmt.Errorf("running order not found: %s", ro.ID) + return fmt.Errorf("running order %s: %w", ro.ID, ErrNotFound) } return fmt.Errorf("failed to get current running order: %w", err) } // Optimistic concurrency control - if ro.Version <= current.Version { - return fmt.Errorf("running order version conflict: expected > %d, got %d", current.Version, ro.Version) + if ro.Version != current.Version { + return fmt.Errorf("running order %s at version %d, update based on %d: %w", + ro.ID, current.Version, ro.Version, ErrVersionConflict) } + ro.Version++ + ro.UpdatedAt = time.Now() filter := bson.M{"_id": ro.ID} _, err = r.collection.ReplaceOne(ctx, filter, ro) @@ -108,7 +108,7 @@ func (r *MongoRunningOrderRepository) Delete(ctx context.Context, id string) err } if result.DeletedCount == 0 { - return fmt.Errorf("running order not found: %s", id) + return fmt.Errorf("running order %s: %w", id, ErrNotFound) } return nil diff --git a/src/internal/repository/story.go b/src/internal/repository/story.go index 115c7cd..b94510c 100644 --- a/src/internal/repository/story.go +++ b/src/internal/repository/story.go @@ -45,7 +45,7 @@ func (r *MongoStoryRepository) Create(ctx context.Context, story *model.Story) ( return nil, fmt.Errorf("failed to check story ID uniqueness: %w", err) } if count > 0 { - return nil, fmt.Errorf("story with ID %s already exists", story.ID) + return nil, fmt.Errorf("story %s: %w", story.ID, ErrAlreadyExists) } _, err = r.collection.InsertOne(ctx, story) @@ -62,7 +62,7 @@ func (r *MongoStoryRepository) Get(ctx context.Context, id string) (*model.Story err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&story) if err != nil { if errors.Is(err, mongo.ErrNoDocuments) { - return nil, fmt.Errorf("story not found: %s", id) + return nil, fmt.Errorf("story %s: %w", id, ErrNotFound) } return nil, fmt.Errorf("failed to get story: %w", err) } @@ -75,10 +75,13 @@ func (r *MongoStoryRepository) Update(ctx context.Context, story *model.Story) e story.UpdatedAt = now filter := bson.M{"_id": story.ID} - _, err := r.collection.ReplaceOne(ctx, filter, story) + result, err := r.collection.ReplaceOne(ctx, filter, story) if err != nil { return fmt.Errorf("failed to update story: %w", err) } + if result.MatchedCount == 0 { + return fmt.Errorf("story %s: %w", story.ID, ErrNotFound) + } return nil } @@ -91,7 +94,7 @@ func (r *MongoStoryRepository) Delete(ctx context.Context, id string) error { } if result.DeletedCount == 0 { - return fmt.Errorf("story not found: %s", id) + return fmt.Errorf("story %s: %w", id, ErrNotFound) } return nil