#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Favorites; using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; using Lumina.Application.Common.DataAccess.Repositories.Playlists; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.Repositories.BookLibrary; using Lumina.DataAccess.Core.Repositories.Favorites; using Lumina.DataAccess.Core.Repositories.Libraries; using Lumina.DataAccess.Core.Repositories.MediaConsumption; using Lumina.DataAccess.Core.Repositories.MediaContributors; using Lumina.DataAccess.Core.Repositories.MusicLibrary; using Lumina.DataAccess.Core.Repositories.Playlists; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.Repositories.Scheduling; using Lumina.DataAccess.Core.Repositories.Themes; using Lumina.DataAccess.Core.Repositories.Users; using Lumina.Domain.Common.Primitives; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using System; using System.Threading; using System.Threading.Tasks; #endregion namespace Lumina.DataAccess.Core.UoW; /// /// Interaction boundary with the Data Access Layer. /// public class UnitOfWork : IUnitOfWork, IDisposable { private readonly LuminaDbContext _luminaDbContext; private readonly IDateTimeProvider _dateTimeProvider; private IDbContextTransaction? _transaction; private IPermissionRepository? _permissionRepository; private IRolePermissionRepository? _rolePermissionRepository; private IRoleRepository? _roleRepository; private IUserRoleRepository? _userRoleRepository; private IBookRepository? _bookRepository; private IArtistRepository? _artistRepository; private IAlbumRepository? _albumRepository; private ITrackRepository? _trackRepository; private IMusicArtworkRepository? _musicArtworkRepository; private IMusicLibraryScanItemMetadataRepository? _musicLibraryScanItemMetadataRepository; private IMediaContributorRepository? _mediaContributorRepository; private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository; private ILibraryRepository? _libraryRepository; private ILibraryScanRepository? _libraryScanRepository; private ILibraryScanSnapshotRepository? _libraryScanSnapshotRepository; private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository; private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository; private IArtworkProviderConfigurationRepository? _artworkProviderConfigurationRepository; private ILibraryBookReaderConfigurationRepository? _libraryBookReaderConfigurationRepository; private IScheduledJobRepository? _scheduledJobRepository; private IScheduledJobExecutionRepository? _scheduledJobExecutionRepository; private ISchedulerDisplayPreferencesRepository? _schedulerDisplayPreferencesRepository; private IPluginRepository? _pluginRepository; private IThemeRepository? _themeRepository; private IUserRepository? _userRepository; private IUserSettingsRepository? _userSettingsRepository; private IPlaylistRepository? _playlistRepository; private IFavoriteRepository? _favoriteRepository; private IMediaConsumptionRecordRepository? _mediaConsumptionRecordRepository; private IMediaResumePointRepository? _mediaResumePointRepository; private IConsumptionStatisticsRepository? _consumptionStatisticsRepository; /// /// Gets the permission repository. /// public IPermissionRepository PermissionRepository { get { _permissionRepository ??= new PermissionRepository(_luminaDbContext); return _permissionRepository; } } /// /// Gets the role permission repository. /// public IRolePermissionRepository RolePermissionRepository { get { _rolePermissionRepository ??= new RolePermissionRepository(_luminaDbContext); return _rolePermissionRepository; } } /// /// Gets the role repository. /// public IRoleRepository RoleRepository { get { _roleRepository ??= new RoleRepository(_luminaDbContext); return _roleRepository; } } /// /// Gets the user role repository. /// public IUserRoleRepository UserRoleRepository { get { _userRoleRepository ??= new UserRoleRepository(_luminaDbContext); return _userRoleRepository; } } /// /// Gets the book repository. /// public IBookRepository BookRepository { get { _bookRepository ??= new BookRepository(_luminaDbContext, _dateTimeProvider); return _bookRepository; } } /// /// Gets the artist repository. /// public IArtistRepository ArtistRepository { get { _artistRepository ??= new ArtistRepository(_luminaDbContext, AlbumRepository, TrackRepository, _dateTimeProvider); return _artistRepository; } } /// /// Gets the album repository. /// public IAlbumRepository AlbumRepository { get { _albumRepository ??= new AlbumRepository(_luminaDbContext, TrackRepository, _dateTimeProvider); return _albumRepository; } } /// /// Gets the track repository. /// public ITrackRepository TrackRepository { get { _trackRepository ??= new TrackRepository(_luminaDbContext, _dateTimeProvider); return _trackRepository; } } /// /// Gets the repository for the artwork of the music library items. /// public IMusicArtworkRepository MusicArtworkRepository { get { _musicArtworkRepository ??= new MusicArtworkRepository(_luminaDbContext); return _musicArtworkRepository; } } /// /// Gets the repository for the music metadata staged during a media library scan. /// public IMusicLibraryScanItemMetadataRepository MusicLibraryScanItemMetadataRepository { get { _musicLibraryScanItemMetadataRepository ??= new MusicLibraryScanItemMetadataRepository(_luminaDbContext); return _musicLibraryScanItemMetadataRepository; } } public IMediaContributorRepository MediaContributorRepository { get { _mediaContributorRepository ??= new MediaContributorRepository(_luminaDbContext); return _mediaContributorRepository; } } /// /// Gets the directory scan fingerprint repository. /// public IDirectoryScanFingerprintRepository DirectoryScanFingerprintRepository { get { _directoryScanFingerprintRepository ??= new DirectoryScanFingerprintRepository(_luminaDbContext); return _directoryScanFingerprintRepository; } } /// /// Gets the library repository. /// public ILibraryRepository LibraryRepository { get { _libraryRepository ??= new LibraryRepository(_luminaDbContext); return _libraryRepository; } } /// /// Gets the library scan repository. /// public ILibraryScanRepository LibraryScanRepository { get { _libraryScanRepository ??= new LibraryScanRepository(_luminaDbContext); return _libraryScanRepository; } } /// /// Gets the library scan snapshot repository. /// public ILibraryScanSnapshotRepository LibraryScanSnapshotRepository { get { _libraryScanSnapshotRepository ??= new LibraryScanSnapshotRepository(_luminaDbContext); return _libraryScanSnapshotRepository; } } /// /// Gets the library scan staging results repository. /// public ILibraryScanStagingResultsRepository LibraryScanStagingResultsRepository { get { _libraryScanStagingResultsRepository ??= new LibraryScanStagingResultsRepository(_luminaDbContext); return _libraryScanStagingResultsRepository; } } /// /// Gets the library metadata provider configuration repository. /// public ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get { _libraryMetadataProviderConfigurationRepository ??= new LibraryMetadataProviderConfigurationRepository(_luminaDbContext); return _libraryMetadataProviderConfigurationRepository; } } /// /// Gets the library artwork provider configuration repository. /// public IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get { _artworkProviderConfigurationRepository ??= new ArtworkProviderConfigurationRepository(_luminaDbContext); return _artworkProviderConfigurationRepository; } } /// /// Gets the library book reader configuration repository. /// public ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get { _libraryBookReaderConfigurationRepository ??= new LibraryBookReaderConfigurationRepository(_luminaDbContext); return _libraryBookReaderConfigurationRepository; } } /// /// Gets the scheduled job repository. /// public IScheduledJobRepository ScheduledJobRepository { get { _scheduledJobRepository ??= new ScheduledJobRepository(_luminaDbContext); return _scheduledJobRepository; } } /// /// Gets the scheduled job execution repository. /// public IScheduledJobExecutionRepository ScheduledJobExecutionRepository { get { _scheduledJobExecutionRepository ??= new ScheduledJobExecutionRepository(_luminaDbContext); return _scheduledJobExecutionRepository; } } /// /// Gets the scheduler display preferences repository. /// public ISchedulerDisplayPreferencesRepository SchedulerDisplayPreferencesRepository { get { _schedulerDisplayPreferencesRepository ??= new SchedulerDisplayPreferencesRepository(_luminaDbContext); return _schedulerDisplayPreferencesRepository; } } /// /// Gets the plugin repository. /// public IPluginRepository PluginRepository { get { _pluginRepository ??= new PluginRepository(_luminaDbContext); return _pluginRepository; } } /// /// Gets the theme repository. /// public IThemeRepository ThemeRepository { get { _themeRepository ??= new ThemeRepository(_luminaDbContext); return _themeRepository; } } /// /// Gets the user repository. /// public IUserRepository UserRepository { get { _userRepository ??= new UserRepository(_luminaDbContext); return _userRepository; } } /// /// Gets the user settings repository. /// public IUserSettingsRepository UserSettingsRepository { get { _userSettingsRepository ??= new UserSettingsRepository(_luminaDbContext); return _userSettingsRepository; } } /// /// Gets the playlist repository. /// public IPlaylistRepository PlaylistRepository { get { _playlistRepository ??= new PlaylistRepository(_luminaDbContext); return _playlistRepository; } } /// /// Gets the favorite repository. /// public IFavoriteRepository FavoriteRepository { get { _favoriteRepository ??= new FavoriteRepository(_luminaDbContext); return _favoriteRepository; } } /// /// Gets the media consumption record repository. /// public IMediaConsumptionRecordRepository MediaConsumptionRecordRepository { get { _mediaConsumptionRecordRepository ??= new MediaConsumptionRecordRepository(_luminaDbContext); return _mediaConsumptionRecordRepository; } } /// /// Gets the media resume point repository. /// public IMediaResumePointRepository MediaResumePointRepository { get { _mediaResumePointRepository ??= new MediaResumePointRepository(_luminaDbContext); return _mediaResumePointRepository; } } /// /// Gets the repository for the consumption records used to build consumption statistics. /// public IConsumptionStatisticsRepository ConsumptionStatisticsRepository { get { _consumptionStatisticsRepository ??= new ConsumptionStatisticsRepository(_luminaDbContext); return _consumptionStatisticsRepository; } } /// /// Initializes a new instance of the class. /// /// Injected Entity Framework DbContext. /// Injected provider for the current UTC time, passed to the repositories that stamp their own timestamps. public UnitOfWork(LuminaDbContext luminaDbContext, IDateTimeProvider dateTimeProvider) { _luminaDbContext = luminaDbContext; _dateTimeProvider = dateTimeProvider; } /// /// Saves the changes made to the database. /// /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async Task> SaveChangesAsync(CancellationToken cancellationToken) { try { await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return Result.Success; } // A concurrency conflict means that another request changed the same row after this request read it. It is an expected persistence // conflict, so it is reported as a failure result instead of bubbling up as an unhandled exception. catch (DbUpdateConcurrencyException) { return Errors.Persistence.ConcurrencyConflict; } // A unique constraint violation is an expected persistence conflict, so it is reported as a failure result instead of bubbling up // as an unhandled exception and being turned into a generic internal server error. catch (DbUpdateException exception) when (IsUniqueConstraintViolation(exception)) { return Errors.Persistence.UniqueConstraintViolation; } // SQLite reports a busy or locked database when another writer holds the lock. It is a concurrent write conflict, not an unexpected // server failure, so it is reported the same way as an optimistic concurrency conflict. catch (DbUpdateException exception) when (IsSqliteConcurrencyConflict(exception)) { return Errors.Persistence.ConcurrencyConflict; } catch (SqliteException exception) when (IsSqliteBusyOrLocked(exception)) { return Errors.Persistence.ConcurrencyConflict; } } /// /// Determines whether the provided was caused by a unique constraint violation of the storage medium. /// /// The exception to inspect. /// if the exception was caused by a unique constraint violation, otherwise. private static bool IsUniqueConstraintViolation(DbUpdateException exception) { // SQLite reports a generic constraint failure code for several constraints, so the extended code is used to tell a unique violation apart. return exception.InnerException is SqliteException sqliteException && sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE } /// /// Determines whether the provided was caused by a SQLite write conflict. /// /// The exception to inspect. /// if the exception was caused by a busy or locked database, otherwise. private static bool IsSqliteConcurrencyConflict(DbUpdateException exception) { return exception.InnerException is SqliteException sqliteException && IsSqliteBusyOrLocked(sqliteException); } /// /// Determines whether the provided reports a busy or locked SQLite database. /// /// The exception to inspect. /// if the database is busy or locked, otherwise. private static bool IsSqliteBusyOrLocked(SqliteException exception) { return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED } /// /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. /// public void ClearTrackedEntities() { _luminaDbContext.ChangeTracker.Clear(); } /// /// Begins a new database transaction. /// /// Cancellation token that can be used to stop the execution. /// A task representing the asynchronous operation. public async Task BeginTransactionAsync(CancellationToken cancellationToken) { _transaction = await _luminaDbContext.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); } /// /// Commits the current transaction. /// /// Cancellation token that can be used to stop the execution. /// A task representing the asynchronous operation. public async Task CommitTransactionAsync(CancellationToken cancellationToken) { if (_transaction is not null) { await _transaction.CommitAsync(cancellationToken).ConfigureAwait(false); await _transaction.DisposeAsync().ConfigureAwait(false); _transaction = null; } } /// /// Rolls back the current transaction. /// /// Cancellation token that can be used to stop the execution. /// A task representing the asynchronous operation. public async Task RollbackTransactionAsync(CancellationToken cancellationToken) { if (_transaction is not null) { await _transaction.RollbackAsync(cancellationToken).ConfigureAwait(false); await _transaction.DisposeAsync().ConfigureAwait(false); _transaction = null; } } /// /// Disposes the unit of work and its resources. /// public void Dispose() { _transaction?.Dispose(); _luminaDbContext.Dispose(); } }