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
5 changes: 3 additions & 2 deletions doc/database-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ Tables: `running_orders`, `stories`, `items`, `mos_objects`.
- 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).
- Services run each MOS message in one transaction (`InTx`, MOS-15), and
running order updates use version-checked writes (optimistic locking).
Events go out only after the commit.
- Configuration: the old `mongo` block is gone; a new `postgres` block, with
`DATABASE_URL` or the standard `PG*` environment variables.
- Startup can apply migrations automatically (`--migrate`) or only migrate and
Expand Down
5 changes: 5 additions & 0 deletions doc/developer-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,11 @@ sentry:
### Code Organization
- Keep business logic in the `service` layer
- Data access should go through `repository` interfaces
- Handle each MOS message that changes data in one `repo.InTx(ctx, func(tx
repository.Repository) error { ... })`, using only `tx` inside it, and
publish events after `InTx` returns nil. A stale running order update
returns `repository.ErrVersionConflict`; report it to the NCS rather than
retrying blindly
- Models should be pure data structures without behavior
- Use the event bus for cross-component communication

Expand Down
18 changes: 6 additions & 12 deletions src/internal/repository/memory/item.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ func (s items) Create(_ context.Context, item *model.Item) (*model.Item, error)
if err := checkItemKey(item.RunningOrderID, item.StoryID, item.ID); err != nil {
return nil, err
}
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
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)
Expand All @@ -39,8 +38,7 @@ func (s items) Get(_ context.Context, roID, storyID, itemID string) (*model.Item
}

func (s items) Update(_ context.Context, item *model.Item) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
k := itemKey{item.RunningOrderID, item.StoryID, item.ID}
current, ok := s.r.items[k]
if !ok {
Expand All @@ -54,8 +52,7 @@ func (s items) Update(_ context.Context, item *model.Item) error {
}

func (s items) Delete(_ context.Context, roID, storyID, itemID string) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
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)
Expand All @@ -71,8 +68,7 @@ func (s items) ListByStory(_ context.Context, roID, storyID string) ([]*model.It
}

func (s items) Move(_ context.Context, roID, storyID string, itemIDs []string, beforeID string) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
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)
Expand All @@ -82,8 +78,7 @@ func (s items) Move(_ context.Context, roID, storyID string, itemIDs []string, b
}

func (s items) Swap(_ context.Context, roID, storyID, itemID1, itemID2 string) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
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)
Expand All @@ -103,8 +98,7 @@ func (s items) ReplaceAll(_ context.Context, roID, storyID string, list []*model
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()
defer s.r.lockWrite()()
if err := s.checkParentLocked(roID, storyID); err != nil {
return err
}
Expand Down
1 change: 1 addition & 0 deletions src/internal/repository/memory/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type objectKey struct{ mos, obj string }
// Repository holds all records behind one lock, so deletes can cascade
// across record types atomically.
type Repository struct {
writer sync.Mutex // held by writes and for a whole InTx; taken before mu
mu sync.RWMutex
runningOrders map[string]*model.RunningOrder
stories map[storyKey]*model.Story
Expand Down
9 changes: 3 additions & 6 deletions src/internal/repository/memory/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ func (s objects) Create(_ context.Context, obj *model.MOSObject) (*model.MOSObje
if err := repository.CheckID("object", obj.ID); err != nil {
return nil, err
}
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
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)
Expand All @@ -40,8 +39,7 @@ func (s objects) Get(_ context.Context, mosID, objID string) (*model.MOSObject,
}

func (s objects) Update(_ context.Context, obj *model.MOSObject) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
k := objectKey{obj.MosID, obj.ID}
current, ok := s.r.objects[k]
if !ok {
Expand All @@ -54,8 +52,7 @@ func (s objects) Update(_ context.Context, obj *model.MOSObject) error {
}

func (s objects) Delete(_ context.Context, mosID, objID string) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
k := objectKey{mosID, objID}
if _, ok := s.r.objects[k]; !ok {
return fmt.Errorf("object %s/%s: %w", mosID, objID, repository.ErrNotFound)
Expand Down
9 changes: 3 additions & 6 deletions src/internal/repository/memory/runningorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ func (s runningOrders) Create(_ context.Context, ro *model.RunningOrder) (*model
if err := repository.CheckID("running order", ro.ID); err != nil {
return nil, err
}
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
if _, ok := s.r.runningOrders[ro.ID]; ok {
return nil, fmt.Errorf("running order %s: %w", ro.ID, repository.ErrAlreadyExists)
}
Expand All @@ -36,8 +35,7 @@ func (s runningOrders) Get(_ context.Context, roID string) (*model.RunningOrder,
}

func (s runningOrders) Update(_ context.Context, ro *model.RunningOrder) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
current, ok := s.r.runningOrders[ro.ID]
if !ok {
return fmt.Errorf("running order %s: %w", ro.ID, repository.ErrNotFound)
Expand All @@ -54,8 +52,7 @@ func (s runningOrders) Update(_ context.Context, ro *model.RunningOrder) error {
}

func (s runningOrders) Delete(_ context.Context, roID string) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
if _, ok := s.r.runningOrders[roID]; !ok {
return fmt.Errorf("running order %s: %w", roID, repository.ErrNotFound)
}
Expand Down
18 changes: 6 additions & 12 deletions src/internal/repository/memory/story.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ func (s stories) Create(_ context.Context, story *model.Story) (*model.Story, er
if err := checkStoryKey(story.RunningOrderID, story.ID); err != nil {
return nil, err
}
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
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)
Expand All @@ -39,8 +38,7 @@ func (s stories) Get(_ context.Context, roID, storyID string) (*model.Story, err
}

func (s stories) Update(_ context.Context, story *model.Story) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
k := storyKey{story.RunningOrderID, story.ID}
current, ok := s.r.stories[k]
if !ok {
Expand All @@ -54,8 +52,7 @@ func (s stories) Update(_ context.Context, story *model.Story) error {
}

func (s stories) Delete(_ context.Context, roID, storyID string) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
k := storyKey{roID, storyID}
if _, ok := s.r.stories[k]; !ok {
return fmt.Errorf("story %s/%s: %w", roID, storyID, repository.ErrNotFound)
Expand All @@ -71,8 +68,7 @@ func (s stories) ListByRunningOrder(_ context.Context, roID string) ([]*model.St
}

func (s stories) Move(_ context.Context, roID string, storyIDs []string, beforeID string) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
order, err := repository.MoveIDs(s.idsLocked(roID), storyIDs, beforeID)
if err != nil {
return fmt.Errorf("move stories in %s: %w", roID, err)
Expand All @@ -82,8 +78,7 @@ func (s stories) Move(_ context.Context, roID string, storyIDs []string, beforeI
}

func (s stories) Swap(_ context.Context, roID, storyID1, storyID2 string) error {
s.r.mu.Lock()
defer s.r.mu.Unlock()
defer s.r.lockWrite()()
order, err := repository.SwapIDs(s.idsLocked(roID), storyID1, storyID2)
if err != nil {
return fmt.Errorf("swap stories in %s: %w", roID, err)
Expand All @@ -103,8 +98,7 @@ func (s stories) ReplaceAll(_ context.Context, roID string, list []*model.Story)
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()
defer s.r.lockWrite()()
if err := s.checkParentLocked(roID); err != nil {
return err
}
Expand Down
68 changes: 68 additions & 0 deletions src/internal/repository/memory/tx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package memory

import (
"context"
"maps"

"airshift/openmos/internal/repository"
)

// lockWrite locks r for a write and returns the unlock function, for
// "defer r.lockWrite()()". Writes also take r.writer, which InTx holds for
// the whole transaction, so a direct write cannot be overwritten when the
// transaction's snapshot is swapped in.
func (r *Repository) lockWrite() func() {
r.writer.Lock()
r.mu.Lock()
return func() {
r.mu.Unlock()
r.writer.Unlock()
}
}

// InTx runs fn on a private copy of the data and swaps the copy in if fn
// returns nil. Readers see the committed data until then. Transactions and
// direct writes run one at a time; fn must write only through the
// Repository it is given, as a direct write to r from fn would wait for the
// transaction forever.
func (r *Repository) InTx(_ context.Context, fn func(repository.Repository) error) error {
r.writer.Lock()
defer r.writer.Unlock()

r.mu.RLock()
tx := r.snapshot()
r.mu.RUnlock()

if err := fn(tx); err != nil {
return err
}

// A panic in fn skips this, discarding the copy
tx.mu.Lock()
defer tx.mu.Unlock()
r.mu.Lock()
defer r.mu.Unlock()
r.runningOrders, r.stories, r.items, r.objects = tx.runningOrders, tx.stories, tx.items, tx.objects
// Detach tx, so a leaked reference cannot change r's data
tx.runningOrders, tx.stories, tx.items, tx.objects = nil, nil, nil, nil
return nil
}

// snapshot returns a repository holding copies of r's records. The caller
// holds r.mu for reading.
func (r *Repository) snapshot() *Repository {
return &Repository{
runningOrders: cloneMap(r.runningOrders, cloneRunningOrder),
stories: cloneMap(r.stories, cloneStory),
items: cloneMap(r.items, cloneItem),
objects: cloneMap(r.objects, cloneObject),
}
}

func cloneMap[K comparable, T any](m map[K]*T, clone func(*T) *T) map[K]*T {
out := make(map[K]*T, len(m))
for k, v := range maps.All(m) {
out[k] = clone(v)
}
return out
}
16 changes: 16 additions & 0 deletions src/internal/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@
// - 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.
// - InTx runs a function against a transactional view of the repository:
// its changes become visible to others only when the function returns
// nil, and an error or panic discards all of them. A nested InTx works
// like a savepoint. Once an operation inside fn has failed, fn should
// return an error; the transaction may not accept more work (PostgreSQL
// aborts it). Inside fn, use only the Repository passed to it.
package repository

import (
Expand Down Expand Up @@ -131,8 +137,18 @@ type ObjectRepository interface {
List(ctx context.Context) ([]*model.MOSObject, error)
}

// TxRunner runs work in one transaction.
type TxRunner interface {
// InTx calls fn with a Repository whose changes are committed if fn
// returns nil and rolled back if it returns an error or panics. The
// error from fn is returned unchanged (wrapped only by commit
// failures). The passed Repository must not be used after fn returns.
InTx(ctx context.Context, fn func(Repository) error) error
}

// Repository combines all repositories
type Repository interface {
TxRunner
RunningOrders() RunningOrderRepository
Stories() StoryRepository
Items() ItemRepository
Expand Down
1 change: 1 addition & 0 deletions src/internal/repository/repotest/repotest.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func Run(t *testing.T, newRepo Factory) {
testObjects(t, newRepo)
})
t.Run("Cascade", func(t *testing.T) { testCascade(t, newRepo) })
t.Run("Tx", func(t *testing.T) { testTx(t, newRepo) })
}

// must stops the test if a setup step fails.
Expand Down
43 changes: 43 additions & 0 deletions src/internal/repository/repotest/runningorder.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package repotest

import (
"sync"
"testing"

"airshift/openmos/internal/model"
"airshift/openmos/internal/repository"
)

Expand Down Expand Up @@ -60,6 +62,47 @@ func testRunningOrders(t *testing.T, newRepo Factory) {
}
})

// Writers that read the same version race; exactly one may win, the
// rest get ErrVersionConflict
t.Run("ConcurrentUpdates", func(t *testing.T) {
r, ctx := newRepo(t).RunningOrders(), t.Context()
_, err := r.Create(ctx, newRunningOrder("a"))
must(t, "Create", err)
const n = 10
copies := make([]*model.RunningOrder, n)
for i := range copies {
copies[i], err = r.Get(ctx, "a")
must(t, "Get", err)
copies[i].Slug = "writer " + itoa(i)
}
errs := make([]error, n)
var wg sync.WaitGroup
for i := range copies {
wg.Go(func() { errs[i] = r.Update(ctx, copies[i]) })
}
wg.Wait()

winner := -1
for i, err := range errs {
switch {
case err == nil && winner < 0:
winner = i
case err == nil:
t.Errorf("writers %d and %d both succeeded", winner, i)
default:
wantErr(t, "losing writer", err, repository.ErrVersionConflict)
}
}
if winner < 0 {
t.Fatal("no writer succeeded")
}
got, err := r.Get(ctx, "a")
must(t, "Get", err)
if got.Version != 2 || got.Slug != copies[winner].Slug {
t.Errorf("after race: version %d, slug %q; want 2, %q", got.Version, got.Slug, copies[winner].Slug)
}
})

t.Run("ListNewestFirst", func(t *testing.T) {
r := newRepo(t).RunningOrders()
list, err := r.List(t.Context())
Expand Down
Loading
Loading