mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 06:11:10 +00:00
Fixes large library scans hitting the SQLite parameter limit
Bounds path lookups and enrichment resets to 20,000 parameters per query, restores failed scans from their staged metadata, and clears staged data only after the materialized items are saved.
This commit is contained in:
1 parent
800f4ab334
commit
6ef9592f00
22 files changed
+542
-94
No files matched your search
@@ -73,10 +73,15 @@ internal static class SharedReferenceResolver
|
||||
List<string> unresolvedNames = [.. resolvedByName.Keys.Where(name => !namesResolvedFromTrackedEntities.Contains(name))];
|
||||
if (unresolvedNames.Count > 0)
|
||||
{
|
||||
// Stored names are normalized when they are written, so the normalized incoming names are matched directly against the primary key.
|
||||
List<TEntity> storedEntities = await context.Set<TEntity>()
|
||||
.Where(entity => unresolvedNames.Contains(EF.Property<string>(entity, nameof(ISharedReferenceEntity.Name))))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
// A large request can reference more shared names than the storage medium accepts as the parameters of a single statement, so the lookup
|
||||
// is split into bounded chunks and the stored rows of every chunk are accumulated.
|
||||
const int LOOKUP_CHUNK_SIZE = 20_000;
|
||||
List<TEntity> storedEntities = [];
|
||||
foreach (string[] chunk in unresolvedNames.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
// Stored names are normalized when they are written, so the normalized incoming names are matched directly against the primary key.
|
||||
storedEntities.AddRange(await context.Set<TEntity>()
|
||||
.Where(entity => chunk.Contains(EF.Property<string>(entity, nameof(ISharedReferenceEntity.Name))))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false));
|
||||
|
||||
foreach (TEntity storedEntity in storedEntities)
|
||||
resolvedByName[NormalizeName(storedEntity.Name!)] = storedEntity;
|
||||
|
||||
@@ -320,10 +320,15 @@ internal sealed class BookRepository : IBookRepository
|
||||
|
||||
// The stored paths are compared ordinally, matching the case sensitive comparison used by the unique index of the storage medium.
|
||||
List<string> distinctPaths = [.. paths.Distinct(StringComparer.Ordinal)];
|
||||
List<string> existingPaths = await _luminaDbContext.Books
|
||||
.Where(repositoryBook => repositoryBook.LibraryId == libraryId && distinctPaths.Contains(repositoryBook.Path))
|
||||
.Select(repositoryBook => repositoryBook.Path)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
// A large library stages far more paths than the storage medium accepts as the parameters of a single statement, so the lookup is split into
|
||||
// bounded chunks and the matches of every chunk are accumulated, which keeps a scan of any size within the parameter limit.
|
||||
const int LOOKUP_CHUNK_SIZE = 20_000;
|
||||
List<string> existingPaths = [];
|
||||
foreach (string[] chunk in distinctPaths.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
existingPaths.AddRange(await _luminaDbContext.Books
|
||||
.Where(repositoryBook => repositoryBook.LibraryId == libraryId && chunk.Contains(repositoryBook.Path))
|
||||
.Select(repositoryBook => repositoryBook.Path)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false));
|
||||
return Result.From<IReadOnlyCollection<string>>(existingPaths);
|
||||
}
|
||||
|
||||
@@ -413,15 +418,25 @@ internal sealed class BookRepository : IBookRepository
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken)
|
||||
{
|
||||
await _luminaDbContext.Books
|
||||
.Where(book => book.LibraryId == libraryId && paths.Contains(book.Path))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(book => book.MetadataStatus, MetadataStatus.Pending), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
List<string> pathList = [.. paths.Distinct(StringComparer.Ordinal)];
|
||||
if (pathList.Count == 0)
|
||||
return Result.Updated;
|
||||
|
||||
await _luminaDbContext.Set<BookArtworkEntity>()
|
||||
.Where(artwork => _luminaDbContext.Books.Any(book => book.Id == artwork.BookId && book.LibraryId == libraryId && paths.Contains(book.Path)))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(artwork => artwork.Status, ArtworkStatus.Pending), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
// A scan can change more paths than the storage medium accepts as the parameters of a single statement, so the reset is split into bounded
|
||||
// chunks, keeping the operation within the parameter limit regardless of the library size.
|
||||
const int LOOKUP_CHUNK_SIZE = 20_000;
|
||||
foreach (string[] chunk in pathList.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
{
|
||||
await _luminaDbContext.Books
|
||||
.Where(book => book.LibraryId == libraryId && chunk.Contains(book.Path))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(book => book.MetadataStatus, MetadataStatus.Pending), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await _luminaDbContext.Set<BookArtworkEntity>()
|
||||
.Where(artwork => _luminaDbContext.Books.Any(book => book.Id == artwork.BookId && book.LibraryId == libraryId && chunk.Contains(book.Path)))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(artwork => artwork.Status, ArtworkStatus.Pending), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
||||
/// <param name="libraryId">The unique identifier of the library whose media library scan snapshot item paths are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of media library scan snapshot item paths, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyList<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
public async Task<Result<IReadOnlySet<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
const string GET_PATHS_SQL = """
|
||||
@@ -82,7 +82,8 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
||||
CommandDefinition command = new(GET_PATHS_SQL, new { libraryId }, cancellationToken: cancellationToken);
|
||||
|
||||
IEnumerable<string> paths = await connection.QueryAsync<string>(command).ConfigureAwait(false);
|
||||
return paths.ToList();
|
||||
// The snapshot is keyed by path, so the paths are unique, and a set answers the membership checks of the materializers without another copy.
|
||||
return Result.From<IReadOnlySet<string>>(paths.ToHashSet(StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -182,6 +183,36 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the media library scan snapshot entries that the scan identified by <paramref name="scanId"/> added or modified, restoring the snapshot to
|
||||
/// the state it had before the scan was applied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library whose scan snapshot is rolled back.</param>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose snapshot entries are removed.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Deleted>> RollbackSnapshotForScanAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
// The audit rows of the scan identify the paths that its snapshot swap added or updated, so removing those snapshot rows makes the next scan
|
||||
// treat the files as new again, instead of skipping the re-extraction of the metadata that never made it into materialized items.
|
||||
const string ROLLBACK_SQL = """
|
||||
DELETE FROM LibraryScanSnapshots
|
||||
WHERE LibraryId = @libraryId
|
||||
AND Path IN (
|
||||
SELECT Path
|
||||
FROM LibraryScanResults
|
||||
WHERE LibraryScanId = @scanId
|
||||
AND Status IN ('New', 'Modified')
|
||||
);
|
||||
""";
|
||||
|
||||
CommandDefinition command = new(ROLLBACK_SQL, new { libraryId, scanId }, cancellationToken: cancellationToken);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a dedicated connection to the database, so that the raw SQL operations performed here do not interfere with the Entity Framework change tracking.
|
||||
/// </summary>
|
||||
|
||||
+16
@@ -58,6 +58,22 @@ internal sealed class MusicLibraryScanItemMetadataRepository : IMusicLibraryScan
|
||||
return Result.From(items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the staged music metadata items of the media library identified by <paramref name="libraryId"/>, regardless of the scan that staged them.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose staged music metadata is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicLibraryScanItemMetadataEntity"/>, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
IReadOnlyList<MusicLibraryScanItemMetadataEntity> items = await _luminaDbContext.MusicLibraryScanItemMetadata
|
||||
.AsNoTracking()
|
||||
.Where(musicMetadata => musicMetadata.LibraryId == libraryId)
|
||||
.OrderBy(musicMetadata => musicMetadata.Path)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.From(items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes all the staged music metadata items of the media library scan identified by <paramref name="scanId"/>.
|
||||
/// </summary>
|
||||
|
||||
@@ -84,10 +84,15 @@ internal sealed class TrackRepository : ITrackRepository
|
||||
|
||||
// The stored paths are compared ordinally, matching the case sensitive comparison used by the unique index of the storage medium.
|
||||
List<string> distinctPaths = [.. paths.Distinct(StringComparer.Ordinal)];
|
||||
List<string> existingPaths = await _luminaDbContext.Tracks
|
||||
.Where(repositoryTrack => repositoryTrack.LibraryId == libraryId && distinctPaths.Contains(repositoryTrack.Path))
|
||||
.Select(repositoryTrack => repositoryTrack.Path)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
// A large library stages far more paths than the storage medium accepts as the parameters of a single statement, so the lookup is split into
|
||||
// bounded chunks and the matches of every chunk are accumulated, which keeps a scan of any size within the parameter limit.
|
||||
const int LOOKUP_CHUNK_SIZE = 20_000;
|
||||
List<string> existingPaths = [];
|
||||
foreach (string[] chunk in distinctPaths.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
existingPaths.AddRange(await _luminaDbContext.Tracks
|
||||
.Where(repositoryTrack => repositoryTrack.LibraryId == libraryId && chunk.Contains(repositoryTrack.Path))
|
||||
.Select(repositoryTrack => repositoryTrack.Path)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false));
|
||||
return Result.From<IReadOnlyCollection<string>>(existingPaths);
|
||||
}
|
||||
|
||||
@@ -463,38 +468,54 @@ internal sealed class TrackRepository : ITrackRepository
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken)
|
||||
{
|
||||
List<string> pathList = [.. paths];
|
||||
List<string> pathList = [.. paths.Distinct(StringComparer.Ordinal)];
|
||||
if (pathList.Count == 0)
|
||||
return Result.Updated;
|
||||
|
||||
// A scan can change more paths and reach more tracks than the storage medium accepts as the parameters of a single statement, so every lookup
|
||||
// and every update is split into bounded chunks, keeping the whole operation within the parameter limit regardless of the library size.
|
||||
const int LOOKUP_CHUNK_SIZE = 20_000;
|
||||
|
||||
// The tracks stored at the changed paths are reset, together with the albums and the artists they belong to, because the metadata of the whole release is re-evaluated.
|
||||
List<Guid> trackIds = await _luminaDbContext.Tracks
|
||||
.Where(track => track.LibraryId == libraryId && pathList.Contains(track.Path))
|
||||
.Select(track => track.Id)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<Guid> trackIds = [];
|
||||
foreach (string[] chunk in pathList.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
trackIds.AddRange(await _luminaDbContext.Tracks
|
||||
.Where(track => track.LibraryId == libraryId && chunk.Contains(track.Path))
|
||||
.Select(track => track.Id)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false));
|
||||
if (trackIds.Count == 0)
|
||||
return Result.Updated;
|
||||
|
||||
List<Guid> albumIds = await _luminaDbContext.Tracks
|
||||
.Where(track => trackIds.Contains(track.Id))
|
||||
.Select(track => track.AlbumId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<Guid> artistIds = await _luminaDbContext.Albums
|
||||
.Where(album => albumIds.Contains(album.Id))
|
||||
.Select(album => album.ArtistId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
HashSet<Guid> albumIdSet = [];
|
||||
foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
albumIdSet.UnionWith(await _luminaDbContext.Tracks
|
||||
.Where(track => chunk.Contains(track.Id))
|
||||
.Select(track => track.AlbumId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false));
|
||||
List<Guid> albumIds = [.. albumIdSet];
|
||||
|
||||
await _luminaDbContext.Tracks
|
||||
.Where(track => trackIds.Contains(track.Id))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
|
||||
await _luminaDbContext.Albums
|
||||
.Where(album => albumIds.Contains(album.Id))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(album => album.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
|
||||
await _luminaDbContext.Artists
|
||||
.Where(artist => artistIds.Contains(artist.Id))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
|
||||
HashSet<Guid> artistIdSet = [];
|
||||
foreach (Guid[] chunk in albumIds.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
artistIdSet.UnionWith(await _luminaDbContext.Albums
|
||||
.Where(album => chunk.Contains(album.Id))
|
||||
.Select(album => album.ArtistId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false));
|
||||
List<Guid> artistIds = [.. artistIdSet];
|
||||
|
||||
foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
await _luminaDbContext.Tracks
|
||||
.Where(track => chunk.Contains(track.Id))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
|
||||
foreach (Guid[] chunk in albumIds.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
await _luminaDbContext.Albums
|
||||
.Where(album => chunk.Contains(album.Id))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(album => album.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
|
||||
foreach (Guid[] chunk in artistIds.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
await _luminaDbContext.Artists
|
||||
.Where(artist => chunk.Contains(artist.Id))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user