feat(380): extract shuffle-source construction to ShuffleSourceBuilder

Eliminate the one cross-engine reach-in in the scheduler: PlaylistEnumerator called
PlayoutBuilder.GetGroupedMediaItemsForShuffle / GetCollectionItemsForShuffleInOrder as
statics (one engine reaching into another engine's class). Move both helpers verbatim to
a new public static ShuffleSourceBuilder in ErsatzTV.Core/Scheduling (sibling to the
also-static MultiCollectionGrouper / MultiPartEpisodeGrouper; deps passed as parameters,
not DI). Classic (PlayoutBuilder) and Playlist (PlaylistEnumerator) now share this one
place to build shuffle sources.

One intentional signature change: GetGroupedMediaItemsForShuffle 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 callers without a ProgramSchedule
(#176, #70) a schedule-entity-free entry point.

Scope is deliberately (a)-only: engine separation preserved, no god-factory. Block stays
its own family; the Scripted/YAML construction duplication is a separate follow-up gated
on #381. See docs/decisions.md 2026-07-17.

Behavior-preserving: the characterization net added in the previous commit (classic-shuffle
golden byte-identical, PlaylistEnumerator reach-in sequence unchanged) plus new direct
ShuffleSourceBuilder unit tests (multi-collection vs fake-multi-collection lookup;
multi-part grouping on/off) all green. Full Core.Tests: 546 passed. PlayoutBuilder.cs
also de-BOM'd + whitespace-normalized per the fix-as-you-touch convention (#311).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-17 08:48:05 +02:00
co-authored by Claude Opus 4.8
parent 604ea96c9f
commit 764cd3c31b
5 changed files with 270 additions and 63 deletions
@@ -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<IMediaCollectionRepository>();
List<MediaItem> items = [FakeMovie(1), FakeMovie(2), FakeMovie(3)];
var key = new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 7 };
List<GroupedMediaItem> 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<IMediaCollectionRepository>();
repo.GetMultiCollectionCollections(42, Arg.Any<CancellationToken>())
.Returns(
new List<CollectionWithItems>
{
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<GroupedMediaItem> 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<CancellationToken>());
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<IMediaCollectionRepository>();
var expected = new List<CollectionWithItems>
{
new(
ShowId: 0,
ArtistId: 0,
Key: "fake",
MediaItems: [FakeMovie(20)],
ScheduleAsGroup: false,
PlaybackOrder: PlaybackOrder.ShuffleInOrder,
UseCustomOrder: false)
};
repo.GetFakeMultiCollectionCollections(5, null, Arg.Any<CancellationToken>()).Returns(expected);
var key = new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 5 };
List<CollectionWithItems> result = await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder(
repo,
key,
CancellationToken.None);
result.ShouldBe(expected);
await repo.Received(1).GetFakeMultiCollectionCollections(5, null, Arg.Any<CancellationToken>());
await repo.DidNotReceiveWithAnyArgs().GetMultiCollectionCollections(default, default);
}
[Test]
public async Task GetCollectionItemsForShuffleInOrder_MultiCollection_Uses_MultiCollection_Lookup()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
var expected = new List<CollectionWithItems>
{
new(
ShowId: 0,
ArtistId: 0,
Key: "mc",
MediaItems: [FakeMovie(30), FakeMovie(31)],
ScheduleAsGroup: true,
PlaybackOrder: PlaybackOrder.ShuffleInOrder,
UseCustomOrder: false)
};
repo.GetMultiCollectionCollections(9, Arg.Any<CancellationToken>()).Returns(expected);
var key = new CollectionKey { CollectionType = CollectionType.MultiCollection, MultiCollectionId = 9 };
List<CollectionWithItems> result = await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder(
repo,
key,
CancellationToken.None);
result.ShouldBe(expected);
await repo.Received(1).GetMultiCollectionCollections(9, Arg.Any<CancellationToken>());
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) }
]
};
}
@@ -171,10 +171,11 @@ public class PlaylistEnumerator : IMediaCollectionEnumerator
// TODO: fix multi episode shuffle?
case PlaybackOrder.MultiEpisodeShuffle:
case PlaybackOrder.Shuffle:
List<GroupedMediaItem> i = await PlayoutBuilder.GetGroupedMediaItemsForShuffle(
List<GroupedMediaItem> 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),
+16 -59
View File
@@ -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<List<GroupedMediaItem>> GetGroupedMediaItemsForShuffle(
IMediaCollectionRepository mediaCollectionRepository,
ProgramSchedule activeSchedule,
List<MediaItem> mediaItems,
CollectionKey collectionKey,
CancellationToken cancellationToken)
{
if (collectionKey.MultiCollectionId != null)
{
List<CollectionWithItems> 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<List<CollectionWithItems>> GetCollectionItemsForShuffleInOrder(
IMediaCollectionRepository mediaCollectionRepository,
CollectionKey collectionKey,
CancellationToken cancellationToken)
{
List<CollectionWithItems> 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)
@@ -0,0 +1,66 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
namespace ErsatzTV.Core.Scheduling;
/// <summary>
/// Builds the shuffle "source" for a collection key — the grouped media items fed to
/// <see cref="ShuffledMediaCollectionEnumerator" /> and the per-collection lists fed to
/// <see cref="ShuffleInOrderCollectionEnumerator" />.
/// <para>
/// Extracted from <c>PlayoutBuilder</c> (issue #380) so both the Classic builder and
/// <see cref="PlaylistEnumerator" /> share ONE stateless place to construct shuffle sources,
/// eliminating <see cref="PlaylistEnumerator" />'s cross-engine reach-in into
/// <c>PlayoutBuilder</c>'s statics. Kept as a static helper (dependencies passed as parameters)
/// to match the sibling <see cref="MultiCollectionGrouper" /> / <see cref="MultiPartEpisodeGrouper" />
/// (also <c>public static</c>) and because <see cref="PlaylistEnumerator.Create" /> is itself a
/// static factory.
/// </para>
/// </summary>
public static class ShuffleSourceBuilder
{
public static async Task<List<GroupedMediaItem>> GetGroupedMediaItemsForShuffle(
IMediaCollectionRepository mediaCollectionRepository,
bool keepMultiPartEpisodesTogether,
bool treatCollectionsAsShows,
List<MediaItem> mediaItems,
CollectionKey collectionKey,
CancellationToken cancellationToken)
{
if (collectionKey.MultiCollectionId != null)
{
List<CollectionWithItems> 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<List<CollectionWithItems>> GetCollectionItemsForShuffleInOrder(
IMediaCollectionRepository mediaCollectionRepository,
CollectionKey collectionKey,
CancellationToken cancellationToken)
{
List<CollectionWithItems> 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;
}
}
+42
View File
@@ -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).