diff --git a/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs b/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs new file mode 100644 index 000000000..01e843554 --- /dev/null +++ b/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs @@ -0,0 +1,141 @@ +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Interfaces.Repositories; +using ErsatzTV.Core.Scheduling; +using NSubstitute; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Core.Tests.Scheduling; + +// Direct unit coverage for the shuffle-source helper extracted from PlayoutBuilder (#380). The builder +// goldens exercise the common non-multi-collection path; these pin the branch selection (multi-collection +// vs fake-multi-collection lookup, multi-part grouping on/off) that the goldens don't reach, so the +// "one well-tested place per family" the issue asks for is genuinely tested here. +[TestFixture] +public class ShuffleSourceBuilderTests +{ + [Test] + public async Task GetGroupedMediaItemsForShuffle_Single_Collection_No_MultiPart_Groups_Each_Item() + { + IMediaCollectionRepository repo = Substitute.For(); + List items = [FakeMovie(1), FakeMovie(2), FakeMovie(3)]; + var key = new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 7 }; + + List result = await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle( + repo, + keepMultiPartEpisodesTogether: false, + treatCollectionsAsShows: false, + items, + key, + CancellationToken.None); + + // No multi-part grouping and no multi-collection => each item is its own group, no repo call. + result.Count.ShouldBe(3); + result.Select(g => g.First.Id).ShouldBe([1, 2, 3]); + result.ShouldAllBe(g => g.Additional.Count == 0); + await repo.DidNotReceiveWithAnyArgs().GetMultiCollectionCollections(default, default); + } + + [Test] + public async Task GetGroupedMediaItemsForShuffle_MultiCollection_Reads_From_Repo() + { + IMediaCollectionRepository repo = Substitute.For(); + repo.GetMultiCollectionCollections(42, Arg.Any()) + .Returns( + new List + { + new( + ShowId: 0, + ArtistId: 0, + Key: "mc", + MediaItems: [FakeMovie(10), FakeMovie(11)], + ScheduleAsGroup: false, + PlaybackOrder: PlaybackOrder.Shuffle, + UseCustomOrder: false) + }); + + var key = new CollectionKey { CollectionType = CollectionType.MultiCollection, MultiCollectionId = 42 }; + + List result = await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle( + repo, + keepMultiPartEpisodesTogether: false, + treatCollectionsAsShows: false, + // the passed items list is ignored on the multi-collection branch + [], + key, + CancellationToken.None); + + // The multi-collection branch reads from the repo and feeds MultiCollectionGrouper (whose grouping + // behavior is covered by its own tests); here we only pin the branch selection + passthrough. + await repo.Received(1).GetMultiCollectionCollections(42, Arg.Any()); + GroupedMediaItem.FlattenGroups(result, 2).Select(mi => mi.Id).OrderBy(id => id).ShouldBe([10, 11]); + } + + [Test] + public async Task GetCollectionItemsForShuffleInOrder_Single_Collection_Uses_Fake_MultiCollection_Lookup() + { + IMediaCollectionRepository repo = Substitute.For(); + var expected = new List + { + new( + ShowId: 0, + ArtistId: 0, + Key: "fake", + MediaItems: [FakeMovie(20)], + ScheduleAsGroup: false, + PlaybackOrder: PlaybackOrder.ShuffleInOrder, + UseCustomOrder: false) + }; + repo.GetFakeMultiCollectionCollections(5, null, Arg.Any()).Returns(expected); + + var key = new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 5 }; + + List result = await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder( + repo, + key, + CancellationToken.None); + + result.ShouldBe(expected); + await repo.Received(1).GetFakeMultiCollectionCollections(5, null, Arg.Any()); + await repo.DidNotReceiveWithAnyArgs().GetMultiCollectionCollections(default, default); + } + + [Test] + public async Task GetCollectionItemsForShuffleInOrder_MultiCollection_Uses_MultiCollection_Lookup() + { + IMediaCollectionRepository repo = Substitute.For(); + var expected = new List + { + new( + ShowId: 0, + ArtistId: 0, + Key: "mc", + MediaItems: [FakeMovie(30), FakeMovie(31)], + ScheduleAsGroup: true, + PlaybackOrder: PlaybackOrder.ShuffleInOrder, + UseCustomOrder: false) + }; + repo.GetMultiCollectionCollections(9, Arg.Any()).Returns(expected); + + var key = new CollectionKey { CollectionType = CollectionType.MultiCollection, MultiCollectionId = 9 }; + + List result = await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder( + repo, + key, + CancellationToken.None); + + result.ShouldBe(expected); + await repo.Received(1).GetMultiCollectionCollections(9, Arg.Any()); + await repo.DidNotReceiveWithAnyArgs().GetFakeMultiCollectionCollections(default, default, default); + } + + private static Movie FakeMovie(int id) => new() + { + Id = id, + MediaVersions = [], + MovieMetadata = + [ + new MovieMetadata { ReleaseDate = new DateTime(2020, 1, id) } + ] + }; +} diff --git a/ErsatzTV.Core/Scheduling/PlaylistEnumerator.cs b/ErsatzTV.Core/Scheduling/PlaylistEnumerator.cs index 44706de67..a93cead90 100644 --- a/ErsatzTV.Core/Scheduling/PlaylistEnumerator.cs +++ b/ErsatzTV.Core/Scheduling/PlaylistEnumerator.cs @@ -171,10 +171,11 @@ public class PlaylistEnumerator : IMediaCollectionEnumerator // TODO: fix multi episode shuffle? case PlaybackOrder.MultiEpisodeShuffle: case PlaybackOrder.Shuffle: - List i = await PlayoutBuilder.GetGroupedMediaItemsForShuffle( + List i = await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle( mediaCollectionRepository, - // TODO: fix this - new ProgramSchedule { KeepMultiPartEpisodesTogether = false }, + // playlist items don't (yet) carry these schedule flags; preserve prior behavior + keepMultiPartEpisodesTogether: false, + treatCollectionsAsShows: false, items, CollectionKey.ForPlaylistItem(playlistItem), cancellationToken); @@ -182,7 +183,7 @@ public class PlaylistEnumerator : IMediaCollectionEnumerator break; case PlaybackOrder.ShuffleInOrder: enumerator = new ShuffleInOrderCollectionEnumerator( - await PlayoutBuilder.GetCollectionItemsForShuffleInOrder( + await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder( mediaCollectionRepository, CollectionKey.ForPlaylistItem(playlistItem), cancellationToken), diff --git a/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs b/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs index 1d467f567..bc97939f3 100644 --- a/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs +++ b/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs @@ -1,4 +1,4 @@ -using System.IO.Abstractions; +using System.IO.Abstractions; using ErsatzTV.Core.Domain; using ErsatzTV.Core.Domain.Filler; using ErsatzTV.Core.Errors; @@ -594,7 +594,7 @@ public class PlayoutBuilder : IPlayoutBuilder var sortedScheduleItems = activeSchedule.Items.OrderBy(i => i.Index).ToList(); CollectionEnumeratorState scheduleItemsEnumeratorState = playout.Anchor?.ScheduleItemsEnumeratorState ?? new CollectionEnumeratorState - { Seed = random.Next(), Index = 0 }; + { Seed = random.Next(), Index = 0 }; IScheduleItemsEnumerator scheduleItemsEnumerator = activeSchedule.ShuffleScheduleItems ? new ShuffledScheduleItemsEnumerator(activeSchedule.Items, scheduleItemsEnumeratorState) : new OrderedScheduleItemsEnumerator(activeSchedule.Items, scheduleItemsEnumeratorState); @@ -735,17 +735,17 @@ public class PlayoutBuilder : IPlayoutBuilder switch (scheduleItem.FillWithGroupMode) { case FillWithGroupMode.FillWithOrderedGroups: - { - var enumerator = new OrderedScheduleItemsEnumerator(fakeScheduleItems, enumeratorState); - scheduleItemsFillGroupEnumerators[scheduleItem.Id] = enumerator; - break; - } + { + var enumerator = new OrderedScheduleItemsEnumerator(fakeScheduleItems, enumeratorState); + scheduleItemsFillGroupEnumerators[scheduleItem.Id] = enumerator; + break; + } case FillWithGroupMode.FillWithShuffledGroups: - { - var enumerator = new ShuffledScheduleItemsEnumerator(fakeScheduleItems, enumeratorState); - scheduleItemsFillGroupEnumerators[scheduleItem.Id] = enumerator; - break; - } + { + var enumerator = new ShuffledScheduleItemsEnumerator(fakeScheduleItems, enumeratorState); + scheduleItemsFillGroupEnumerators[scheduleItem.Id] = enumerator; + break; + } } } @@ -1376,7 +1376,7 @@ public class PlayoutBuilder : IPlayoutBuilder return new RandomizedMediaCollectionEnumerator(mediaItems, state); case PlaybackOrder.ShuffleInOrder: return new ShuffleInOrderCollectionEnumerator( - await GetCollectionItemsForShuffleInOrder( + await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder( _mediaCollectionRepository, collectionKey, cancellationToken), @@ -1420,9 +1420,10 @@ public class PlayoutBuilder : IPlayoutBuilder case PlaybackOrder.MultiEpisodeShuffle: case PlaybackOrder.Shuffle: return new ShuffledMediaCollectionEnumerator( - await GetGroupedMediaItemsForShuffle( + await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle( _mediaCollectionRepository, - activeSchedule, + activeSchedule.KeepMultiPartEpisodesTogether, + activeSchedule.TreatCollectionsAsShows, mediaItems, collectionKey, cancellationToken), @@ -1454,50 +1455,6 @@ public class PlayoutBuilder : IPlayoutBuilder } } - internal static async Task> GetGroupedMediaItemsForShuffle( - IMediaCollectionRepository mediaCollectionRepository, - ProgramSchedule activeSchedule, - List mediaItems, - CollectionKey collectionKey, - CancellationToken cancellationToken) - { - if (collectionKey.MultiCollectionId != null) - { - List collections = await mediaCollectionRepository - .GetMultiCollectionCollections(collectionKey.MultiCollectionId.Value, cancellationToken); - - return MultiCollectionGrouper.GroupMediaItems(collections); - } - - return activeSchedule.KeepMultiPartEpisodesTogether - ? MultiPartEpisodeGrouper.GroupMediaItems(mediaItems, activeSchedule.TreatCollectionsAsShows) - : mediaItems.Map(mi => new GroupedMediaItem(mi, null)).ToList(); - } - - internal static async Task> GetCollectionItemsForShuffleInOrder( - IMediaCollectionRepository mediaCollectionRepository, - CollectionKey collectionKey, - CancellationToken cancellationToken) - { - List result; - - if (collectionKey.MultiCollectionId != null) - { - result = await mediaCollectionRepository.GetMultiCollectionCollections( - collectionKey.MultiCollectionId.Value, - cancellationToken); - } - else - { - result = await mediaCollectionRepository.GetFakeMultiCollectionCollections( - collectionKey.CollectionId, - collectionKey.SmartCollectionId, - cancellationToken); - } - - return result; - } - internal static string DisplayTitle(MediaItem mediaItem) { switch (mediaItem) diff --git a/ErsatzTV.Core/Scheduling/ShuffleSourceBuilder.cs b/ErsatzTV.Core/Scheduling/ShuffleSourceBuilder.cs new file mode 100644 index 000000000..210d04537 --- /dev/null +++ b/ErsatzTV.Core/Scheduling/ShuffleSourceBuilder.cs @@ -0,0 +1,66 @@ +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Interfaces.Repositories; + +namespace ErsatzTV.Core.Scheduling; + +/// +/// Builds the shuffle "source" for a collection key — the grouped media items fed to +/// and the per-collection lists fed to +/// . +/// +/// Extracted from PlayoutBuilder (issue #380) so both the Classic builder and +/// share ONE stateless place to construct shuffle sources, +/// eliminating 's cross-engine reach-in into +/// PlayoutBuilder's statics. Kept as a static helper (dependencies passed as parameters) +/// to match the sibling / +/// (also public static) and because is itself a +/// static factory. +/// +/// +public static class ShuffleSourceBuilder +{ + public static async Task> GetGroupedMediaItemsForShuffle( + IMediaCollectionRepository mediaCollectionRepository, + bool keepMultiPartEpisodesTogether, + bool treatCollectionsAsShows, + List mediaItems, + CollectionKey collectionKey, + CancellationToken cancellationToken) + { + if (collectionKey.MultiCollectionId != null) + { + List collections = await mediaCollectionRepository + .GetMultiCollectionCollections(collectionKey.MultiCollectionId.Value, cancellationToken); + + return MultiCollectionGrouper.GroupMediaItems(collections); + } + + return keepMultiPartEpisodesTogether + ? MultiPartEpisodeGrouper.GroupMediaItems(mediaItems, treatCollectionsAsShows) + : mediaItems.Map(mi => new GroupedMediaItem(mi, null)).ToList(); + } + + public static async Task> GetCollectionItemsForShuffleInOrder( + IMediaCollectionRepository mediaCollectionRepository, + CollectionKey collectionKey, + CancellationToken cancellationToken) + { + List result; + + if (collectionKey.MultiCollectionId != null) + { + result = await mediaCollectionRepository.GetMultiCollectionCollections( + collectionKey.MultiCollectionId.Value, + cancellationToken); + } + else + { + result = await mediaCollectionRepository.GetFakeMultiCollectionCollections( + collectionKey.CollectionId, + collectionKey.SmartCollectionId, + cancellationToken); + } + + return result; + } +} diff --git a/docs/decisions.md b/docs/decisions.md index 894e632b6..8f91f2283 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -84,6 +84,7 @@ in-file entries. - [2026-07-16 — Auto-tuning enumerates via EF, persists via SmartCollection; additive coexistence (#69)](#2026-07-16--auto-tuning-enumerates-via-ef-persists-via-smartcollection-additive-coexistence-69) - [2026-07-16 — Per-playout reshuffle = scoped Reset build; seed surfaced (#71)](#2026-07-16--per-playout-reshuffle--scoped-reset-build-seed-surfaced-71) - [2026-07-17 — Clock-boundary schedule padding already exists (FillerMode.Pad); #77 verified, convenience toggle deferred](#2026-07-17--clock-boundary-schedule-padding-already-exists-fillermodepad-77-verified-convenience-toggle-deferred) +- [2026-07-17 — Shuffle-source construction extracted to `ShuffleSourceBuilder`; per-family seam, not a god-factory (#380)](#2026-07-17--shuffle-source-construction-extracted-to-shufflesourcebuilder-per-family-seam-not-a-god-factory-380) --- @@ -1093,3 +1094,44 @@ per-schedule "clock-align this whole channel" toggle; today you hand-build a Pad into a schedule item's roll slot. That toggle is mostly SPA work and is deferred to a follow-up **blocked on the #388 design-system sync epic** (all UI work is currently gated on #388), which also covers adding a 60-minute increment to the filler-preset editor's options (the backend already accepts any integer). + +## 2026-07-17 — Shuffle-source construction extracted to `ShuffleSourceBuilder`; per-family seam, not a god-factory (#380) + +`PlaybackOrder` is turned into an enumerator at five independent sites (one per schedule kind, dispatched +by `BuildPlayoutHandler` on `ScheduleKind`): Classic (`PlayoutBuilder`), Block (`BlockPlayoutBuilder`, +`PlayoutHistory` rotation), Scripted (`SchedulingEngine.EnumeratorForContent`), Sequential/YAML +(`EnumeratorCache`), and the Playlist leaf (`PlaylistEnumerator.Create`, consumed by the others). These +are **not** accidental duplication — they map the same enum to different enumerator *families* keyed on +different state models (Block's history cursor vs the stateless-index `CollectionEnumeratorState` +enumerators). The real smell was one **cross-engine reach-in**: `PlaylistEnumerator` called +`PlayoutBuilder.GetGroupedMediaItemsForShuffle` / `GetCollectionItemsForShuffleInOrder` as **statics** — +one engine reaching into another engine's class. + +- **Fix (a) shipped, not (b).** The two shuffle-source helpers moved verbatim to a new + `public static class ShuffleSourceBuilder` in `ErsatzTV.Core/Scheduling` (sibling to the also-static + `MultiCollectionGrouper` / `MultiPartEpisodeGrouper`; dependencies passed as parameters, **not** a DI + service — `PlaylistEnumerator.Create` is itself a static factory). Both Classic and Playlist now consume + it, so the reach-in is gone and shuffle-source construction lives in one directly-unit-tested place. +- **One intentional signature change.** `GetGroupedMediaItemsForShuffle` now takes + `bool keepMultiPartEpisodesTogether, bool treatCollectionsAsShows` instead of a `ProgramSchedule` + (verified those are the only two properties it read). This deletes `PlaylistEnumerator`'s fake + `new ProgramSchedule { KeepMultiPartEpisodesTogether = false }` (its TODO becomes an honest + `false, false`) and gives future callers with no `ProgramSchedule` (#176 PseudoTV, #70 distribution) a + schedule-entity-free entry point. Behavior is unchanged. +- **Rejected: a unified Classic+Playlist enumerator factory (b).** That would be the god-factory the issue + forbids — three concrete hazards: Classic's `Marathon` arm *produces* a `PlaylistEnumerator` (a factory + consumed by `PlaylistEnumerator.Create` that also builds one is a dependency cycle); Playlist hardcodes + `KeepMultiPartEpisodesTogether=false`/`randomStartPoint=false` where Classic reads schedule flags (a + merge silently changes behavior); and Classic's `CustomOrder`/`Rerun`/`MultiEpisodeShuffle`-template arms + gate on instance deps Playlist doesn't have. Engine separation is deliberately preserved. +- **Block / Scripted / YAML left alone.** Block is a distinct family; the Scripted≡YAML construction + duplication (`EnumeratorForContent` ≡ `EnumeratorCache.GetEnumerator`, both using the *different* + `BlockPlayoutShuffledMediaCollectionEnumerator` for shuffle) is a real but separate cleanup — deferred to + a follow-up gated on #381 (those paths have no golden coverage yet). +- **Net first, because #163's was too narrow.** `PlayoutBuildGoldenTests` only pinned + `PlaybackOrder.Chronological`; the moved shuffle paths (incl. the entire Playlist reach-in) were + uncovered, so "goldens green" would have been a false signal. The PR adds a `classic-shuffle` golden + (pinned `Playout.Seed` + `Continue` build, since `Reset` randomizes the seed) and a + `PlaylistEnumerator.Create` reach-in characterization (Shuffle + ShuffleInOrder items) **before** the + move, plus direct `ShuffleSourceBuilder` unit tests for the branches goldens don't reach + (multi-collection vs fake-multi-collection lookup; multi-part grouping on/off).