From cbc0a10ae094f7168d89ac640c1abef0b17c2330 Mon Sep 17 00:00:00 2001 From: Timo Ruohomaki Date: Mon, 9 Nov 2026 19:50:37 +0200 Subject: [PATCH] MOS-15: Run each MOS message in one transaction - repository.TxRunner: InTx(ctx, fn) commits fn's changes if it returns nil and discards them on error or panic; nested InTx is a savepoint. Embedded in Repository, so the contract suite covers it. - PostgreSQL: InTx via pgx.BeginFunc with a transaction-bound repository. - Memory store: InTx works on a deep snapshot swapped in on commit; a writer mutex serialises transactions with direct writes. - Service takes the Repository and handles roCreate/roReplace and story actions in one transaction each; events are published after commit. A failed NEW story action no longer leaves its auto-created RO. - Tests: transaction contract (commit, rollback on error and panic, restored order, isolation, direct writes, nesting), concurrent running order updates (one winner, others ErrVersionConflict), and half-failed roCreate leaving no rows on memory and PostgreSQL. - Docs: how to use InTx in services. Co-Authored-By: Claude Opus 5.5 --- doc/database-migration.md | 5 +- doc/developer-reference.md | 5 + src/internal/repository/memory/item.go | 18 +- src/internal/repository/memory/memory.go | 1 + src/internal/repository/memory/object.go | 9 +- .../repository/memory/runningorder.go | 9 +- src/internal/repository/memory/story.go | 18 +- src/internal/repository/memory/tx.go | 68 +++++++ src/internal/repository/repository.go | 16 ++ src/internal/repository/repotest/repotest.go | 1 + .../repository/repotest/runningorder.go | 43 +++++ src/internal/repository/repotest/tx.go | 170 ++++++++++++++++++ src/internal/service/mos.go | 165 ++++++++--------- src/internal/service/mos_test.go | 2 +- src/internal/service/story.go | 73 ++++---- src/internal/service/story_create.go | 73 +++----- src/internal/service/tx_test.go | 128 +++++++++++++ src/internal/store/postgres/repository.go | 9 + .../store/postgres/repository_test.go | 28 +++ src/wiring.go | 2 +- 20 files changed, 632 insertions(+), 211 deletions(-) create mode 100644 src/internal/repository/memory/tx.go create mode 100644 src/internal/repository/repotest/tx.go create mode 100644 src/internal/service/tx_test.go diff --git a/doc/database-migration.md b/doc/database-migration.md index fec40cd..2394e82 100644 --- a/doc/database-migration.md +++ b/doc/database-migration.md @@ -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 diff --git a/doc/developer-reference.md b/doc/developer-reference.md index f0526f1..d2336d8 100644 --- a/doc/developer-reference.md +++ b/doc/developer-reference.md @@ -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 diff --git a/src/internal/repository/memory/item.go b/src/internal/repository/memory/item.go index edbcade..a97cc48 100644 --- a/src/internal/repository/memory/item.go +++ b/src/internal/repository/memory/item.go @@ -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) @@ -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 { @@ -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) @@ -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) @@ -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) @@ -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 } diff --git a/src/internal/repository/memory/memory.go b/src/internal/repository/memory/memory.go index 78701f9..10c823c 100644 --- a/src/internal/repository/memory/memory.go +++ b/src/internal/repository/memory/memory.go @@ -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 diff --git a/src/internal/repository/memory/object.go b/src/internal/repository/memory/object.go index a53d3c3..5820773 100644 --- a/src/internal/repository/memory/object.go +++ b/src/internal/repository/memory/object.go @@ -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) @@ -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 { @@ -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) diff --git a/src/internal/repository/memory/runningorder.go b/src/internal/repository/memory/runningorder.go index f0b7a9c..9d94389 100644 --- a/src/internal/repository/memory/runningorder.go +++ b/src/internal/repository/memory/runningorder.go @@ -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) } @@ -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) @@ -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) } diff --git a/src/internal/repository/memory/story.go b/src/internal/repository/memory/story.go index 9688020..e6b4327 100644 --- a/src/internal/repository/memory/story.go +++ b/src/internal/repository/memory/story.go @@ -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) @@ -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 { @@ -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) @@ -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) @@ -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) @@ -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 } diff --git a/src/internal/repository/memory/tx.go b/src/internal/repository/memory/tx.go new file mode 100644 index 0000000..f7c30b8 --- /dev/null +++ b/src/internal/repository/memory/tx.go @@ -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 +} diff --git a/src/internal/repository/repository.go b/src/internal/repository/repository.go index db2af65..61db576 100644 --- a/src/internal/repository/repository.go +++ b/src/internal/repository/repository.go @@ -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 ( @@ -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 diff --git a/src/internal/repository/repotest/repotest.go b/src/internal/repository/repotest/repotest.go index a3db74e..49aebff 100644 --- a/src/internal/repository/repotest/repotest.go +++ b/src/internal/repository/repotest/repotest.go @@ -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. diff --git a/src/internal/repository/repotest/runningorder.go b/src/internal/repository/repotest/runningorder.go index e014316..eb4d40b 100644 --- a/src/internal/repository/repotest/runningorder.go +++ b/src/internal/repository/repotest/runningorder.go @@ -1,8 +1,10 @@ package repotest import ( + "sync" "testing" + "airshift/openmos/internal/model" "airshift/openmos/internal/repository" ) @@ -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()) diff --git a/src/internal/repository/repotest/tx.go b/src/internal/repository/repotest/tx.go new file mode 100644 index 0000000..083ced6 --- /dev/null +++ b/src/internal/repository/repotest/tx.go @@ -0,0 +1,170 @@ +package repotest + +import ( + "errors" + "testing" + "time" + + "airshift/openmos/internal/repository" +) + +var errAbort = errors.New("abort transaction") + +func testTx(t *testing.T, newRepo Factory) { + t.Run("Commit", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + err := r.InTx(ctx, func(tx repository.Repository) error { + createRunningOrder(t, tx, "ro") + createStory(t, tx, "ro", "s") + createItem(t, tx, "ro", "s", "i") + createObject(t, tx, testMOS, "o") + return nil + }) + must(t, "InTx", err) + exist(t, r, []string{"ro", "ro/s", "ro/s/i"}, "ro", "ro/s", "ro/s/i") + _, err = r.Objects().Get(ctx, testMOS, "o") + must(t, "Get object after commit", err) + }) + + t.Run("RollbackOnError", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + createRunningOrder(t, r, "kept") + createStory(t, r, "kept", "s") + err := r.InTx(ctx, func(tx repository.Repository) error { + createRunningOrder(t, tx, "ro") + createStory(t, tx, "ro", "s") + createItem(t, tx, "ro", "s", "i") + createObject(t, tx, testMOS, "o") + ro, err := tx.RunningOrders().Get(ctx, "kept") + must(t, "Get in tx", err) + ro.Slug = "changed" + must(t, "Update in tx", tx.RunningOrders().Update(ctx, ro)) + must(t, "Delete in tx", tx.Stories().Delete(ctx, "kept", "s")) + return errAbort + }) + wantErr(t, "InTx", err, errAbort) + assertRolledBack(t, r) + }) + + t.Run("RollbackRestoresOrder", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + createRunningOrder(t, r, "ro") + createStory(t, r, "ro", "s") + for _, id := range []string{"a", "b", "c"} { + createStory(t, r, "ro", id) + createItem(t, r, "ro", "s", id) + } + err := r.InTx(ctx, func(tx repository.Repository) error { + must(t, "Swap stories in tx", tx.Stories().Swap(ctx, "ro", "a", "c")) + must(t, "Move items in tx", tx.Items().Move(ctx, "ro", "s", []string{"c"}, "a")) + return errAbort + }) + wantErr(t, "InTx", err, errAbort) + stories, err := r.Stories().ListByRunningOrder(ctx, "ro") + must(t, "list stories", err) + equalIDs(t, "stories after rollback", storyKind.ids(stories), []string{"s", "a", "b", "c"}) + items, err := r.Items().ListByStory(ctx, "ro", "s") + must(t, "list items", err) + equalIDs(t, "items after rollback", itemKind.ids(items), []string{"a", "b", "c"}) + }) + + t.Run("RollbackOnPanic", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + createRunningOrder(t, r, "kept") + createStory(t, r, "kept", "s") + func() { + defer func() { + if recover() == nil { + t.Error("InTx swallowed the panic") + } + }() + _ = r.InTx(ctx, func(tx repository.Repository) error { + createRunningOrder(t, tx, "ro") + must(t, "Delete in tx", tx.Stories().Delete(ctx, "kept", "s")) + panic("boom") + }) + }() + assertRolledBack(t, r) + // The repository is still usable + createRunningOrder(t, r, "after") + }) + + t.Run("Isolation", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + err := r.InTx(ctx, func(tx repository.Repository) error { + createRunningOrder(t, tx, "ro") + _, err := tx.RunningOrders().Get(ctx, "ro") + must(t, "Get own write in tx", err) + _, err = r.RunningOrders().Get(ctx, "ro") + wantErr(t, "Get uncommitted write from outside", err, repository.ErrNotFound) + list, err := r.RunningOrders().List(ctx) + must(t, "List from outside", err) + equalIDs(t, "List from outside", runningOrderKind.ids(list), nil) + return nil + }) + must(t, "InTx", err) + }) + + // A write outside the transaction while it runs must survive its commit + t.Run("DirectWriteDuringTx", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + direct := make(chan error, 1) + err := r.InTx(ctx, func(tx repository.Repository) error { + createRunningOrder(t, tx, "tx") + go func() { + _, err := r.RunningOrders().Create(ctx, newRunningOrder("direct")) + direct <- err + }() + time.Sleep(20 * time.Millisecond) // let the direct write run or block + return nil + }) + must(t, "InTx", err) + must(t, "direct Create", <-direct) + exist(t, r, []string{"tx", "direct"}, "tx", "direct") + }) + + t.Run("NestedRollback", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + err := r.InTx(ctx, func(tx repository.Repository) error { + createRunningOrder(t, tx, "outer") + err := tx.InTx(ctx, func(inner repository.Repository) error { + createRunningOrder(t, inner, "inner") + createStory(t, inner, "outer", "s") + return errAbort + }) + wantErr(t, "inner InTx", err, errAbort) + createStory(t, tx, "outer", "after") + return nil + }) + must(t, "outer InTx", err) + exist(t, r, []string{"outer", "inner", "outer/s", "outer/after"}, "outer", "outer/after") + }) + + t.Run("NestedCommitRolledBackByOuter", func(t *testing.T) { + r, ctx := newRepo(t), t.Context() + err := r.InTx(ctx, func(tx repository.Repository) error { + must(t, "inner InTx", tx.InTx(ctx, func(inner repository.Repository) error { + createRunningOrder(t, inner, "inner") + return nil + })) + return errAbort + }) + wantErr(t, "outer InTx", err, errAbort) + exist(t, r, []string{"inner"}) + }) +} + +// assertRolledBack checks the state the rollback tests started from: only +// running order kept with its story s and unchanged slug, and no object. +func assertRolledBack(t *testing.T, r repository.Repository) { + t.Helper() + ctx := t.Context() + exist(t, r, []string{"ro", "ro/s", "ro/s/i", "kept", "kept/s"}, "kept", "kept/s") + ro, err := r.RunningOrders().Get(ctx, "kept") + must(t, "Get kept", err) + if ro.Slug != "slug kept" || ro.Version != 1 { + t.Errorf("kept after rollback: slug %q, version %d; want %q, 1", ro.Slug, ro.Version, "slug kept") + } + _, err = r.Objects().Get(ctx, testMOS, "o") + wantErr(t, "Get object after rollback", err, repository.ErrNotFound) +} diff --git a/src/internal/service/mos.go b/src/internal/service/mos.go index d797a14..e145859 100644 --- a/src/internal/service/mos.go +++ b/src/internal/service/mos.go @@ -12,62 +12,53 @@ import ( "airshift/openmos/internal/xml" ) -// MOSService provides business logic for MOS operations +// MOSService provides business logic for MOS operations. Each MOS message +// that changes data is handled in one transaction (repository.TxRunner), so +// it is applied completely or not at all, and events are published only +// after the commit. type MOSService struct { - runningOrderRepo repository.RunningOrderRepository - storyRepo repository.StoryRepository - itemRepo repository.ItemRepository - objectRepo repository.ObjectRepository - eventBus *events.EventBus + repo repository.Repository + eventBus *events.EventBus } -// NewMOSService creates a new MOS service -func NewMOSService( - runningOrderRepo repository.RunningOrderRepository, - storyRepo repository.StoryRepository, - itemRepo repository.ItemRepository, - objectRepo repository.ObjectRepository, - eventBus *events.EventBus, -) *MOSService { - return &MOSService{ - runningOrderRepo: runningOrderRepo, - storyRepo: storyRepo, - itemRepo: itemRepo, - objectRepo: objectRepo, - eventBus: eventBus, +// NewMOSService creates a new MOS service. eventBus may be nil. +func NewMOSService(repo repository.Repository, eventBus *events.EventBus) *MOSService { + return &MOSService{repo: repo, eventBus: eventBus} +} + +// publish sends an event if the service has an event bus. +func (s *MOSService) publish(typ events.EventType, payload string) { + if s.eventBus != nil { + s.eventBus.Publish(events.Event{Type: typ, Payload: payload, Source: "mos_service"}) } } // ListRunningOrders returns all running orders func (s *MOSService) ListRunningOrders(ctx context.Context) ([]*model.RunningOrder, error) { - return s.runningOrderRepo.List(ctx) + return s.repo.RunningOrders().List(ctx) } // GetRunningOrderWithStories retrieves a running order with all its stories func (s *MOSService) GetRunningOrderWithStories(ctx context.Context, id string) (*model.RunningOrder, []*model.Story, error) { - // Get the running order - ro, err := s.runningOrderRepo.Get(ctx, id) + ro, err := s.repo.RunningOrders().Get(ctx, id) if err != nil { return nil, nil, err } - - // Get all stories for this running order - stories, err := s.storyRepo.ListByRunningOrder(ctx, id) + stories, err := s.repo.Stories().ListByRunningOrder(ctx, id) if err != nil { return nil, nil, fmt.Errorf("failed to get stories: %w", err) } - return ro, stories, nil } // GetItemsForStory retrieves all items for a story func (s *MOSService) GetItemsForStory(ctx context.Context, roID, storyID string) ([]*model.Item, error) { - return s.itemRepo.ListByStory(ctx, roID, storyID) + return s.repo.Items().ListByStory(ctx, roID, storyID) } // 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. +// order the message lists them. If any part fails, nothing is changed. func (s *MOSService) ProcessRunningOrderInfo(ctx context.Context, roInfo xml.RunningOrderInfo) error { // Parse duration if provided; an unparsable value falls back to 0 var duration int @@ -77,74 +68,72 @@ func (s *MOSService) ProcessRunningOrderInfo(ctx context.Context, roInfo xml.Run } } - 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, - } - if _, err := s.runningOrderRepo.Create(ctx, ro); err != nil { - return fmt.Errorf("failed to create running order: %w", err) - } - 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 - if err := s.runningOrderRepo.Update(ctx, existingRO); err != nil { - return fmt.Errorf("failed to update running order: %w", err) - } - } - - stories := make([]*model.Story, len(roInfo.Stories)) - for i, storyInfo := range roInfo.Stories { - stories[i] = &model.Story{ - ID: storyInfo.ID, - RunningOrderID: roInfo.ID, - Slug: storyInfo.Slug, - Number: storyInfo.Number, - Status: model.StatusPending, + err := s.repo.InTx(ctx, func(tx repository.Repository) error { + existingRO, err := tx.RunningOrders().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, + } + if _, err := tx.RunningOrders().Create(ctx, ro); err != nil { + return fmt.Errorf("failed to create running order: %w", err) + } + 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 + if err := tx.RunningOrders().Update(ctx, existingRO); err != nil { + return fmt.Errorf("failed to update running order: %w", err) + } } - } - if err := s.storyRepo.ReplaceAll(ctx, roInfo.ID, stories); err != nil { - return fmt.Errorf("failed to replace stories: %w", err) - } - 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, + stories := make([]*model.Story, len(roInfo.Stories)) + for i, storyInfo := range roInfo.Stories { + stories[i] = &model.Story{ + ID: storyInfo.ID, RunningOrderID: roInfo.ID, - StoryID: storyInfo.ID, - ObjectID: itemInfo.ObjectID, - MosID: itemInfo.MosID, - Slug: itemInfo.Slug, + Slug: storyInfo.Slug, + Number: storyInfo.Number, Status: model.StatusPending, } - // 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) + if err := tx.Stories().ReplaceAll(ctx, roInfo.ID, stories); err != nil { + return fmt.Errorf("failed to replace stories: %w", err) } - } - // Publish event after successful update - if s.eventBus != nil { - s.eventBus.Publish(events.Event{ - Type: events.RunningOrderUpdated, - Payload: roInfo.ID, - Source: "mos_service", - }) + 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, + } + // 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 := tx.Items().ReplaceAll(ctx, roInfo.ID, storyInfo.ID, items); err != nil { + return fmt.Errorf("failed to replace items of story %s: %w", storyInfo.ID, err) + } + } + return nil + }) + if err != nil { + return err } + s.publish(events.RunningOrderUpdated, roInfo.ID) return nil } diff --git a/src/internal/service/mos_test.go b/src/internal/service/mos_test.go index 9cf265e..fb4381f 100644 --- a/src/internal/service/mos_test.go +++ b/src/internal/service/mos_test.go @@ -12,7 +12,7 @@ import ( func newTestService() (*MOSService, repository.Repository) { repo := memory.New() - return NewMOSService(repo.RunningOrders(), repo.Stories(), repo.Items(), repo.Objects(), nil), repo + return NewMOSService(repo, nil), repo } func getRO(t *testing.T, repo repository.Repository, id string) *model.RunningOrder { diff --git a/src/internal/service/story.go b/src/internal/service/story.go index 60682ad..2a91f01 100644 --- a/src/internal/service/story.go +++ b/src/internal/service/story.go @@ -6,72 +6,69 @@ import ( "strings" "airshift/openmos/internal/events" + "airshift/openmos/internal/repository" "airshift/openmos/internal/xml" "airshift/openmos/pkg/logger" ) -// ProcessStoryAction processes a story action request from an NCS +// ProcessStoryAction processes a story action request from an NCS. The +// action runs in one transaction. func (s *MOSService) ProcessStoryAction(ctx context.Context, action xml.NCSReqStoryAction) error { logger.Infof("Processing story action: %s", action.Operation) + var apply func(context.Context, repository.Repository, xml.ROStorySend) (string, error) switch strings.ToUpper(action.Operation) { case "NEW": - return s.createNewStory(ctx, action.ROStorySend) + apply = s.createNewStory case "UPDATE": - return s.updateStory(ctx, action.ROStorySend) + apply = s.updateStory case "REPLACE": - return s.replaceStory(ctx, action.ROStorySend) + apply = s.replaceStory default: return fmt.Errorf("unsupported story operation: %s", action.Operation) } + + var storyID string + err := s.repo.InTx(ctx, func(tx repository.Repository) error { + var err error + storyID, err = apply(ctx, tx, action.ROStorySend) + return err + }) + if err != nil { + return err + } + s.publish(events.StoryModified, storyID) + return nil } -// 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.ROID, storySend.StoryID) +// updateStory updates an existing story from the provided ROStorySend and +// returns its ID. +func (s *MOSService) updateStory(ctx context.Context, tx repository.Repository, storySend xml.ROStorySend) (string, error) { + story, err := tx.Stories().Get(ctx, storySend.ROID, storySend.StoryID) if err != nil { - return fmt.Errorf("story not found: %w", err) + return "", fmt.Errorf("story not found: %w", err) } - // Update story fields story.Slug = storySend.StorySlug story.Number = storySend.StoryNum - // Process story body - err = s.processStoryBody(ctx, story, &storySend.StoryBody) - if err != nil { - return fmt.Errorf("failed to process story body: %w", err) - } - - // Update the story - err = s.storyRepo.Update(ctx, story) - if err != nil { - return fmt.Errorf("failed to update story: %w", err) + if err := s.processStoryBody(ctx, story, &storySend.StoryBody); err != nil { + return "", fmt.Errorf("failed to process story body: %w", err) } - - // Publish event after successful update - if s.eventBus != nil { - s.eventBus.Publish(events.Event{ - Type: events.StoryModified, - Payload: story.ID, - Source: "mos_service", - }) + if err := tx.Stories().Update(ctx, story); err != nil { + return "", fmt.Errorf("failed to update story: %w", err) } logger.Infof("Updated story %s in running order %s", story.ID, story.RunningOrderID) - return nil + return story.ID, nil } -// replaceStory replaces an existing story from the provided ROStorySend -func (s *MOSService) replaceStory(ctx context.Context, storySend xml.ROStorySend) error { +// replaceStory replaces an existing story from the provided ROStorySend and +// returns its ID. +func (s *MOSService) replaceStory(ctx context.Context, tx repository.Repository, storySend xml.ROStorySend) (string, error) { // For now, implement as delete + create - // Delete existing story - err := s.storyRepo.Delete(ctx, storySend.ROID, storySend.StoryID) - if err != nil { - return fmt.Errorf("failed to delete existing story: %w", err) + if err := tx.Stories().Delete(ctx, storySend.ROID, storySend.StoryID); err != nil { + return "", fmt.Errorf("failed to delete existing story: %w", err) } - - // Create new story - return s.createNewStory(ctx, storySend) + return s.createNewStory(ctx, tx, storySend) } diff --git a/src/internal/service/story_create.go b/src/internal/service/story_create.go index 61bdbab..cbe3a45 100644 --- a/src/internal/service/story_create.go +++ b/src/internal/service/story_create.go @@ -2,38 +2,35 @@ package service import ( "context" + "errors" "fmt" "time" - "airshift/openmos/internal/events" "airshift/openmos/internal/model" + "airshift/openmos/internal/repository" "airshift/openmos/internal/xml" "airshift/openmos/pkg/logger" ) -// createNewStory creates a new story from the provided ROStorySend -func (s *MOSService) createNewStory(ctx context.Context, storySend xml.ROStorySend) error { - // Check if Running Order exists, create if not - var ro *model.RunningOrder - var err error - - if storySend.ROID != "" { - ro, err = s.runningOrderRepo.Get(ctx, storySend.ROID) - 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, - } - - ro, err = s.runningOrderRepo.Create(ctx, ro) - if err != nil { - return fmt.Errorf("failed to create running order: %w", err) - } +// createNewStory creates a new story from the provided ROStorySend, creating +// its running order if needed, and returns the story's ID. +func (s *MOSService) createNewStory(ctx context.Context, tx repository.Repository, storySend xml.ROStorySend) (string, error) { + if storySend.ROID == "" { + return "", fmt.Errorf("no running order ID specified") + } + _, err := tx.RunningOrders().Get(ctx, storySend.ROID) + switch { + case errors.Is(err, repository.ErrNotFound): + ro := &model.RunningOrder{ + ID: storySend.ROID, + Slug: "Auto-created RO", + Status: model.StatusPending, + } + if _, err := tx.RunningOrders().Create(ctx, ro); err != nil { + return "", fmt.Errorf("failed to create running order: %w", err) } - } else { - return fmt.Errorf("no running order ID specified") + case err != nil: + return "", fmt.Errorf("failed to get running order: %w", err) } // Create a story ID if not provided @@ -42,37 +39,23 @@ func (s *MOSService) createNewStory(ctx context.Context, storySend xml.ROStorySe storyID = fmt.Sprintf("S%d", time.Now().UnixNano()) } - // Create the new story story := &model.Story{ ID: storyID, - RunningOrderID: ro.ID, + RunningOrderID: storySend.ROID, Slug: storySend.StorySlug, Number: storySend.StoryNum, Status: model.StatusPending, } - // The repository appends the new story to the running order - // Process story body - err = s.processStoryBody(ctx, story, &storySend.StoryBody) - if err != nil { - return fmt.Errorf("failed to process story body: %w", err) - } - - // Create the story - _, err = s.storyRepo.Create(ctx, story) - if err != nil { - return fmt.Errorf("failed to create story: %w", err) + if err := s.processStoryBody(ctx, story, &storySend.StoryBody); err != nil { + return "", fmt.Errorf("failed to process story body: %w", err) } - // Publish event after successful creation - if s.eventBus != nil { - s.eventBus.Publish(events.Event{ - Type: events.StoryModified, - Payload: story.ID, - Source: "mos_service", - }) + // The repository appends the new story to the running order + if _, err := tx.Stories().Create(ctx, story); err != nil { + return "", fmt.Errorf("failed to create story: %w", err) } - logger.Infof("Created new story %s in running order %s", story.ID, ro.ID) - return nil + logger.Infof("Created new story %s in running order %s", story.ID, storySend.ROID) + return story.ID, nil } diff --git a/src/internal/service/tx_test.go b/src/internal/service/tx_test.go new file mode 100644 index 0000000..364e5e4 --- /dev/null +++ b/src/internal/service/tx_test.go @@ -0,0 +1,128 @@ +package service + +import ( + "errors" + "strings" + "testing" + + "airshift/openmos/internal/events" + "airshift/openmos/internal/repository" + "airshift/openmos/internal/repository/memory" + "airshift/openmos/internal/xml" +) + +// halfFailingROCreate is an roCreate whose second story has an item without +// an ID, so it fails after the running order, the stories and the first +// story's items were written. +var halfFailingROCreate = xml.RunningOrderInfo{ID: "RO1", Slug: "new", Stories: []xml.StoryInfo{ + {ID: "S1", Items: []xml.ItemInfo{{ID: "I1"}}}, + {ID: "S2", Items: []xml.ItemInfo{{ID: ""}}}, +}} + +func TestHalfFailedROCreateLeavesNoRows(t *testing.T) { + repo, ctx := memory.New(), t.Context() + eb := events.NewEventBus() + sub := eb.Subscribe(events.RunningOrderUpdated, 1) + svc := NewMOSService(repo, eb) + + err := svc.ProcessRunningOrderInfo(ctx, halfFailingROCreate) + if !errors.Is(err, repository.ErrInvalid) { + t.Fatalf("ProcessRunningOrderInfo err = %v, want %v", err, repository.ErrInvalid) + } + if _, err := repo.RunningOrders().Get(ctx, "RO1"); !errors.Is(err, repository.ErrNotFound) { + t.Errorf("Get RO1 after failed roCreate: err = %v, want %v", err, repository.ErrNotFound) + } + for _, s := range []string{"S1", "S2"} { + if _, err := repo.Stories().Get(ctx, "RO1", s); !errors.Is(err, repository.ErrNotFound) { + t.Errorf("Get story %s after failed roCreate: err = %v, want %v", s, err, repository.ErrNotFound) + } + } + if _, err := repo.Items().Get(ctx, "RO1", "S1", "I1"); !errors.Is(err, repository.ErrNotFound) { + t.Errorf("Get item I1 after failed roCreate: err = %v, want %v", err, repository.ErrNotFound) + } + select { + case ev := <-sub: + t.Errorf("failed roCreate published %+v", ev) + default: + } +} + +// A failed roReplace keeps the running order as it was +func TestHalfFailedROReplaceKeepsOldState(t *testing.T) { + svc, repo := newTestService() + ctx := t.Context() + old := xml.RunningOrderInfo{ID: "RO1", Slug: "old", Stories: []xml.StoryInfo{ + {ID: "S0", Items: []xml.ItemInfo{{ID: "I0"}}}, + }} + if err := svc.ProcessRunningOrderInfo(ctx, old); err != nil { + t.Fatal(err) + } + if err := svc.ProcessRunningOrderInfo(ctx, halfFailingROCreate); err == nil { + t.Fatal("ProcessRunningOrderInfo succeeded, want an error") + } + + if ro := getRO(t, repo, "RO1"); ro.Slug != "old" || ro.Version != 1 { + t.Errorf("RO1 after failed replace: slug %q, version %d; want %q, 1", ro.Slug, ro.Version, "old") + } + if _, err := repo.Items().Get(ctx, "RO1", "S0", "I0"); err != nil { + t.Errorf("Get item S0/I0 after failed replace: %v", err) + } + if _, err := repo.Stories().Get(ctx, "RO1", "S1"); !errors.Is(err, repository.ErrNotFound) { + t.Errorf("Get story S1 after failed replace: err = %v, want %v", err, repository.ErrNotFound) + } +} + +func TestSuccessfulROCreatePublishesAfterCommit(t *testing.T) { + repo := memory.New() + eb := events.NewEventBus() + sub := eb.Subscribe(events.RunningOrderUpdated, 1) + svc := NewMOSService(repo, eb) + + if err := svc.ProcessRunningOrderInfo(t.Context(), xml.RunningOrderInfo{ID: "RO1"}); err != nil { + t.Fatal(err) + } + select { + case ev := <-sub: + // A subscriber reacting to the event must see the committed data + if _, err := repo.RunningOrders().Get(t.Context(), ev.Payload.(string)); err != nil { + t.Errorf("Get %s on event: %v", ev.Payload, err) + } + default: + t.Error("no event published") + } +} + +// A NEW story action that fails must not leave its auto-created running order +func TestFailedStoryActionRollsBackAutoCreatedRO(t *testing.T) { + svc, repo := newTestService() + ctx := t.Context() + // A story ID over the MOS limit makes the story insert fail after the + // running order was auto-created + long := strings.Repeat("x", repository.MaxIDLength+1) + err := svc.ProcessStoryAction(ctx, xml.NCSReqStoryAction{ + Operation: "NEW", + ROStorySend: xml.ROStorySend{ROID: "RO9", StoryID: long}, + }) + if !errors.Is(err, repository.ErrInvalid) { + t.Fatalf("ProcessStoryAction err = %v, want %v", err, repository.ErrInvalid) + } + if _, err := repo.RunningOrders().Get(ctx, "RO9"); !errors.Is(err, repository.ErrNotFound) { + t.Errorf("auto-created RO9 survived the failed action: err = %v", err) + } +} + +func TestStoryActionNewCreatesROAndStory(t *testing.T) { + svc, repo := newTestService() + ctx := t.Context() + err := svc.ProcessStoryAction(ctx, xml.NCSReqStoryAction{ + Operation: "new", + ROStorySend: xml.ROStorySend{ROID: "RO9", StoryID: "S1", StorySlug: "first"}, + }) + if err != nil { + t.Fatal(err) + } + s, err := repo.Stories().Get(ctx, "RO9", "S1") + if err != nil || s.Slug != "first" { + t.Errorf("story RO9/S1 = %+v, %v; want slug %q", s, err, "first") + } +} diff --git a/src/internal/store/postgres/repository.go b/src/internal/store/postgres/repository.go index c09bda9..eeccc8c 100644 --- a/src/internal/store/postgres/repository.go +++ b/src/internal/store/postgres/repository.go @@ -37,6 +37,15 @@ func (r *Repository) Stories() repository.StoryRepository { return func (r *Repository) Items() repository.ItemRepository { return items{r.db} } func (r *Repository) Objects() repository.ObjectRepository { return objects{r.db} } +// InTx runs fn in a database transaction, committed if fn returns nil. +// On a repository already bound to a transaction it uses a savepoint. +// Isolation is READ COMMITTED: fn sees rows others commit meanwhile, while +// the version check on running orders and the parent locks guard against +// lost updates. +func (r *Repository) InTx(ctx context.Context, fn func(repository.Repository) error) error { + return pgx.BeginFunc(ctx, r.db, func(tx pgx.Tx) error { return fn(New(tx)) }) +} + // 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 { diff --git a/src/internal/store/postgres/repository_test.go b/src/internal/store/postgres/repository_test.go index bebdf13..b1f37cc 100644 --- a/src/internal/store/postgres/repository_test.go +++ b/src/internal/store/postgres/repository_test.go @@ -1,6 +1,7 @@ package postgres import ( + "errors" "fmt" "sync" "testing" @@ -10,6 +11,8 @@ import ( "airshift/openmos/internal/model" "airshift/openmos/internal/repository" "airshift/openmos/internal/repository/repotest" + "airshift/openmos/internal/service" + "airshift/openmos/internal/xml" ) // TestContract runs the repository contract suite against the test @@ -78,3 +81,28 @@ func TestConcurrentAppends(t *testing.T) { } } } + +// MOS-15: an roCreate that fails halfway, after the running order, its +// stories and some items were written, must leave no rows behind. +func TestHalfFailedROCreateLeavesNoRows(t *testing.T) { + db := migrated(t) + pool, err := pgxpool.New(t.Context(), testDatabaseURL(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + svc := service.NewMOSService(New(pool), nil) + + err = svc.ProcessRunningOrderInfo(t.Context(), xml.RunningOrderInfo{ID: "RO1", Stories: []xml.StoryInfo{ + {ID: "S1", Items: []xml.ItemInfo{{ID: "I1"}}}, + {ID: "S2", Items: []xml.ItemInfo{{ID: "I2", Duration: "1"}, {ID: "I2"}}}, // duplicate item + }}) + if !errors.Is(err, repository.ErrInvalid) { + t.Fatalf("ProcessRunningOrderInfo err = %v, want %v", err, repository.ErrInvalid) + } + for _, table := range []string{"running_orders", "stories", "items"} { + if n := count(t, db, "SELECT count(*) FROM openmos."+table); n != 0 { + t.Errorf("%d rows left in %s, want 0", n, table) + } + } +} diff --git a/src/wiring.go b/src/wiring.go index 2815bec..8b93eb9 100644 --- a/src/wiring.go +++ b/src/wiring.go @@ -30,7 +30,7 @@ func newTCPServer(cfg *config.Config, repo repository.Repository, log *logger.Se eventBus := events.NewEventBus() // Create service - mosService := service.NewMOSService(repo.RunningOrders(), repo.Stories(), repo.Items(), repo.Objects(), eventBus) + mosService := service.NewMOSService(repo, eventBus) // Create and start TCP server log.Info("Starting TCP server...")