Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion doc/developer-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/`

Expand Down
18 changes: 18 additions & 0 deletions src/internal/repository/errors.go
Original file line number Diff line number Diff line change
@@ -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")
)
11 changes: 7 additions & 4 deletions src/internal/repository/item.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
}
Expand All @@ -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
}
Expand All @@ -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
Expand Down
85 changes: 85 additions & 0 deletions src/internal/repository/memory/item.go
Original file line number Diff line number Diff line change
@@ -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
}
121 changes: 121 additions & 0 deletions src/internal/repository/memory/memory.go
Original file line number Diff line number Diff line change
@@ -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
}
13 changes: 13 additions & 0 deletions src/internal/repository/memory/memory_test.go
Original file line number Diff line number Diff line change
@@ -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() })
}
70 changes: 70 additions & 0 deletions src/internal/repository/memory/object.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading