diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md new file mode 100644 index 00000000..51e0a773 --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md @@ -0,0 +1,112 @@ +# Architecture Decision Record (ADR): 0003 - Pragmatic `System.IO` Usage for File System Discovery in Library Scan Job + +## Status +**Accepted** (2025-03-01) + +## Context +The media library scanning subsystem requires: +1. **Performance at scale**: enumeration of files needs to run fast, because file discovery is the first job in the chain of media library scan jobs. If this is slow, the entire scan will be slow, no matter how optimized subsequent jobs are. +2. **Domain model limitations**: + - `FileSystemManagementAggregate` abstractions added over 16x latency overhead (65s vs 4s on tests ran on SSD). + - Domain wrapper incurred unacceptable I/O amplification. +3. **Real-world constraints**: + - Users potentially having tens of millions of files and hundreds of terrabytes of data, in some cases. + - Limited value from domain semantics during raw discovery. + +## Decision +Use `System.IO` directly in `FileSystemDiscoveryJob` with: + +```csharp +[MethodImpl(MethodImplOptions.AggressiveOptimization)] +private static List GetFiles(...) +{ + // raw directory traversal using System.IO + // (Domain aggregate bypassed) +} +``` + + +## Consequences + +### Performance vs Purity Tradeoff +| Metric | Before (Domain) | After (System.IO) | Delta | +|----------------------|-----------------|-------------------|----------| +| 100k File Enumeration| 65s | 4s | -94% | + +### Risks and Mitigations +| Risk | Mitigation Strategy | +|-------------------------------|------------------------------------------------------------| +| Hidden Platform Dependencies | Regular integration tests on Linux/Windows | +| Loss of Domain Abstraction | Strictly limit usage to library scan discovery phase only | + +## Alternatives Considered + +### 1. Optimized Domain Aggregate + +Domain entities like `File` or `Directory` could be modified to bypass invariants checks in their initialization, leading to a noticeable latency drop. + +**Rejected**: Invariants checks are one of the most important domain aspects, and the performance gain was still insufficient for the target scale. + +### 2. Hybrid Approach + +```csharp +if (fileCount > 10_000) + UseSystemIO(); +else + UseDomainAggregate(); +``` + +**Rejected**: Introduced unpredictable performance characteristics and potential for difference in behavior, hard to reproduce bugs that happen only on one branch, etc. + +### 3. Platform-Specific Native Interop via P/Invoke + +```csharp +// Windows implementation +[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] +static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); + +// Linux implementation +[DllImport("libc", EntryPoint = "opendir")] +static extern IntPtr OpenDir(string name); +``` + + +**Rejected** due to: + +| Risk | Impact Analysis | +|-------------------------------|------------------------------------------------------------------------------| +| Platform Fragility | Required separate implementations for Windows/macOS/Linux (2x codebase size) | +| Path Encoding Bugs | UTF-16/UTF-8 conversion errors in long paths (>32k chars) | +| Memory Leaks | Manual handle management required finalizers and safe handles | +| Testing Complexity | Physical VM requirements for platform validation | + +### 5. Native C Library with Managed Interop + +```c +// file_discovery.c +#ifdef _WIN32 +#include +void win_enumerate(const char* path, void (callback)(const char)) +{ + WIN32_FIND_DATA fd; + HANDLE h = FindFirstFileEx(path, FindExInfoStandard, &fd, ...); + // ... recursive implementation +} +#else +#include +void lin_enumerate(const char* path, void (callback)(const char)) +{ + DIR* dir = opendir(path); + struct dirent* entry; + // ... recursive implementation +} +#endif +``` + +**Rejected** due to: + +| Risk | Maintenance Burden | +|-------------------------------|---------------------------------------------------------------| +| Cross-Compilation Complexity | Required CI pipeline support for Windows/macOS/Linux binaries | +| ABI Breakage | High risk of crashes during .NET runtime updates | +| Debugging Difficulty | Specialized tools (WinDbg/gdb) needed for crash analysis | diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntity.cs index 370c6377..118dd953 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntity.cs @@ -36,7 +36,7 @@ public class LibraryScanResultEntity : IStorageEntity /// /// Gets the hash calculated for the media library scan file. /// - public required string ContentHash { get; init; } + public required ulong ContentHash { get; init; } /// /// Gets the size of the media library scan file. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs index 42c45804..516c8289 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs @@ -4,7 +4,6 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using System; using System.Collections.Generic; using System.Threading; diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanResultRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanResultRepository.cs new file mode 100644 index 00000000..09a580be --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanResultRepository.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; + +/// +/// Interface for the repository for media library scan results. +/// +public interface ILibraryScanResultRepository : IRepository, + IInsertRepositoryAction +{ + /// + /// Gets all media library scan results that belong to the last scan of a library identified by , from the storage medium. + /// + /// The unique identifier of the library for which to get the results of the last scans. + /// Cancellation token that can be used to stop the execution. + /// An containing either a path mapped dictionary of , or an error. + Task>> GetPathMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/ChangedFileSystemFile.cs b/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/ChangedFileSystemFile.cs new file mode 100644 index 00000000..04fd1433 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/ChangedFileSystemFile.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.IO; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; + +/// +/// Represents an item for the payload of the file hashing media library scan job. +/// +/// The file to whom belongs. +/// The hash of . +[DebuggerDisplay("File: {File}; FileHash: {FileHash}")] +public record ChangedFileSystemFile(FileInfo File, ulong FileHash); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Payloads/FileSystemTreeNode.cs b/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/FileSystemTreeNode.cs similarity index 92% rename from src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Payloads/FileSystemTreeNode.cs rename to src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/FileSystemTreeNode.cs index b0e91c6c..8bbd941a 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Payloads/FileSystemTreeNode.cs +++ b/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/FileSystemTreeNode.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Payloads; +namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; /// /// Generic file system node. diff --git a/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs b/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs new file mode 100644 index 00000000..d5f5a63b --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Security; + +/// +/// Interface for the service for hashing files by sampling chunks from them. +/// +public interface IFileHashService +{ + /// + /// Hashes by sampling chunks from them. + /// + /// The collection of files to hash. + /// Lookup dictionary of a previous media library scan, used to determine if a file changed or not. + /// Callback to invoke during processing of elements. + /// Cancellation token that can be used to stop the execution. + /// A collection of files that changed since last library scan, along with their hashes. + List HashFiles( + List files, + Dictionary previousScanResults, + Func callback, + CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs b/src/Lumina.Application/Common/Infrastructure/Security/IPasswordHashService.cs similarity index 95% rename from src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs rename to src/Lumina.Application/Common/Infrastructure/Security/IPasswordHashService.cs index 77395c85..abd81a2f 100644 --- a/src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Security/IPasswordHashService.cs @@ -3,7 +3,7 @@ namespace Lumina.Application.Common.Infrastructure.Security; /// /// Interface for the service for hashing passwords. /// -public interface IHashService +public interface IPasswordHashService { /// /// Creates a hash from a string. diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index 6e09a631..c620d610 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -25,7 +25,7 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApp public class SetupApplicationCommandHandler : IRequestHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IHashService _hashService; + private readonly IPasswordHashService _hashService; private readonly ICryptographyService _cryptographyService; private readonly ITotpTokenGenerator _totpTokenGenerator; private readonly IQRCodeGenerator _qRCodeGenerator; @@ -44,7 +44,7 @@ public class SetupApplicationCommandHandler : IRequestHandlerInjected service for the initial persistence medium data seed. public SetupApplicationCommandHandler( IUnitOfWork unitOfWork, - IHashService hashService, + IPasswordHashService hashService, ICryptographyService cryptographyService, ITotpTokenGenerator totpTokenGenerator, IQRCodeGenerator qRCodeGenerator, diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs index 95b06c11..c2ba7e8b 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs @@ -20,7 +20,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Change public class ChangePasswordCommandHandler : IRequestHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IHashService _hashService; + private readonly IPasswordHashService _hashService; /// /// Initializes a new instance of the class. @@ -29,7 +29,7 @@ public class ChangePasswordCommandHandler : IRequestHandlerInjected service for password hashing functionality. public ChangePasswordCommandHandler( IUnitOfWork unitOfWork, - IHashService hashService) + IPasswordHashService hashService) { _unitOfWork = unitOfWork; _hashService = hashService; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs index 799440d5..49a9ad1e 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -21,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Recove public class RecoverPasswordCommandHandler : IRequestHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IHashService _hashService; + private readonly IPasswordHashService _hashService; private readonly ITotpTokenGenerator _totpTokenGenerator; private readonly ICryptographyService _cryptographyService; @@ -34,7 +34,7 @@ public class RecoverPasswordCommandHandler : IRequestHandlerInjected service for cryptographic functionality. public RecoverPasswordCommandHandler( IUnitOfWork unitOfWork, - IHashService hashService, + IPasswordHashService hashService, ITotpTokenGenerator totpTokenGenerator, ICryptographyService cryptographyService) { diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index d3286586..e3aef197 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -22,7 +22,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Regist public class RegisterUserCommandHandler : IRequestHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IHashService _hashService; + private readonly IPasswordHashService _hashService; private readonly ICryptographyService _cryptographyService; private readonly ITotpTokenGenerator _totpTokenGenerator; private readonly IQRCodeGenerator _qRCodeGenerator; @@ -39,7 +39,7 @@ public class RegisterUserCommandHandler : IRequestHandlerInjected service for time related concerns. public RegisterUserCommandHandler( IUnitOfWork unitOfWork, - IHashService hashService, + IPasswordHashService hashService, ICryptographyService cryptographyService, ITotpTokenGenerator totpTokenGenerator, IQRCodeGenerator qRCodeGenerator, diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index 9d9dd177..82714982 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -22,7 +22,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUs public class LoginUserQueryHandler : IRequestHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IHashService _hashService; + private readonly IPasswordHashService _hashService; private readonly IJwtTokenGenerator _jwtTokenGenerator; private readonly ITotpTokenGenerator _totpTokenGenerator; private readonly ICryptographyService _cryptographyService; @@ -39,7 +39,7 @@ public class LoginUserQueryHandler : IRequestHandlerInjected service for time related concerns. public LoginUserQueryHandler( IUnitOfWork unitOfWork, - IHashService hashService, + IPasswordHashService hashService, IJwtTokenGenerator jwtTokenGenerator, ITotpTokenGenerator totpTokenGenerator, ICryptographyService cryptographyService, diff --git a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs index ce210241..438cc6a1 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs @@ -204,19 +204,19 @@ public class BookConfiguration : IEntityTypeConfiguration }); // audit - builder.Property(permission => permission.CreatedOnUtc) + builder.Property(book => book.CreatedOnUtc) .IsRequired() .HasColumnOrder(32); - builder.Property(permission => permission.CreatedBy) + builder.Property(book => book.CreatedBy) .IsRequired() .HasColumnOrder(33); - builder.Property(permission => permission.UpdatedOnUtc) + builder.Property(book => book.UpdatedOnUtc) .HasDefaultValue(null) .HasColumnOrder(34); - builder.Property(permission => permission.UpdatedBy) + builder.Property(book => book.UpdatedBy) .HasDefaultValue(null) .HasColumnOrder(35); } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs index cef4effc..77d66a5b 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -83,19 +83,19 @@ public class LibraryConfiguration : IEntityTypeConfiguration }); // audit - builder.Property(permission => permission.CreatedOnUtc) + builder.Property(library => library.CreatedOnUtc) .IsRequired() .HasColumnOrder(8); - builder.Property(permission => permission.CreatedBy) + builder.Property(library => library.CreatedBy) .IsRequired() .HasColumnOrder(9); - builder.Property(permission => permission.UpdatedOnUtc) + builder.Property(library => library.UpdatedOnUtc) .HasDefaultValue(null) .HasColumnOrder(10); - builder.Property(permission => permission.UpdatedBy) + builder.Property(library => library.UpdatedBy) .HasDefaultValue(null) .HasColumnOrder(11); } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs index 2c078806..6c14ad63 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs @@ -42,19 +42,19 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration permission.CreatedOnUtc) + builder.Property(libraryScan => libraryScan.CreatedOnUtc) .IsRequired() .HasColumnOrder(2); - builder.Property(permission => permission.CreatedBy) + builder.Property(libraryScan => libraryScan.CreatedBy) .IsRequired() .HasColumnOrder(3); - builder.Property(permission => permission.UpdatedOnUtc) + builder.Property(libraryScan => libraryScan.UpdatedOnUtc) .HasDefaultValue(null) .HasColumnOrder(4); - builder.Property(permission => permission.UpdatedBy) + builder.Property(libraryScan => libraryScan.UpdatedBy) .HasDefaultValue(null) .HasColumnOrder(5); } diff --git a/src/Lumina.DataAccess/Common/Migrations/20250301143105_ChangesLibraryScanResultContentHashColumnToUlong.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20250301143105_ChangesLibraryScanResultContentHashColumnToUlong.Designer.cs new file mode 100644 index 00000000..251a261a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250301143105_ChangesLibraryScanResultContentHashColumnToUlong.Designer.cs @@ -0,0 +1,877 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20250301143105_ChangesLibraryScanResultContentHashColumnToUlong")] + partial class ChangesLibraryScanResultContentHashColumnToUlong + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("DownloadMedatadaFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("LibraryId"); + + b.HasIndex("UserId"); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastModified") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LibraryScanEntityId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanEntityId"); + + b.HasIndex("Path") + .IsUnique(); + + b.HasIndex("ContentHash", "FileSize", "Path") + .IsUnique(); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanEntityId"); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250301143105_ChangesLibraryScanResultContentHashColumnToUlong.cs b/src/Lumina.DataAccess/Common/Migrations/20250301143105_ChangesLibraryScanResultContentHashColumnToUlong.cs new file mode 100644 index 00000000..194abb55 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250301143105_ChangesLibraryScanResultContentHashColumnToUlong.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class ChangesLibraryScanResultContentHashColumnToUlong : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "ContentHash", + table: "LibraryScanResults", + type: "INTEGER", + maxLength: 24, + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 24); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "ContentHash", + table: "LibraryScanResults", + type: "TEXT", + maxLength: 24, + nullable: false, + oldClrType: typeof(ulong), + oldType: "INTEGER", + oldMaxLength: 24); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 4e6017ad..841e3605 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -359,10 +359,9 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(1); - b.Property("ContentHash") - .IsRequired() + b.Property("ContentHash") .HasMaxLength(24) - .HasColumnType("TEXT") + .HasColumnType("INTEGER") .HasColumnOrder(2); b.Property("FileSize") diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/RolePermissionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/RolePermissionRepository.cs index 569c6ada..ef14416c 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/RolePermissionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/RolePermissionRepository.cs @@ -31,9 +31,9 @@ internal sealed class RolePermissionRepository : IRolePermissionRepository /// The authorization role permission to add. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async Task> InsertAsync(RolePermissionEntity rolePermission, CancellationToken cancellationToken) + public Task> InsertAsync(RolePermissionEntity rolePermission, CancellationToken cancellationToken) { _luminaDbContext.RolePermissions.Add(rolePermission); - return await Task.FromResult(Result.Created); + return Task.FromResult(ErrorOrFactory.From(Result.Created)); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/UserRoleRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/UserRoleRepository.cs index 33fa5e64..ea895071 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/UserRoleRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/UserRoleRepository.cs @@ -31,9 +31,9 @@ internal sealed class UserRoleRepository : IUserRoleRepository /// The authorization user role to add. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async Task> InsertAsync(UserRoleEntity userRole, CancellationToken cancellationToken) + public Task> InsertAsync(UserRoleEntity userRole, CancellationToken cancellationToken) { _luminaDbContext.UserRoles.Add(userRole); - return await Task.FromResult(Result.Created); + return Task.FromResult(ErrorOrFactory.From(Result.Created)); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs new file mode 100644 index 00000000..1cd4d2cd --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Errors; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Libraries; + +/// +/// Repository for media library scan results. +/// +internal sealed class LibraryScanResultRepository : ILibraryScanResultRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public LibraryScanResultRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new library scan result. + /// + /// The library scan result to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public Task> InsertAsync(LibraryScanResultEntity libraryScan, CancellationToken cancellationToken) + { + _luminaDbContext.LibraryScanResults.Add(libraryScan); + return Task.FromResult(ErrorOrFactory.From(Result.Created)); + } + + /// + /// Gets all media library scan results that belong to the last scan of a library identified by , from the storage medium. + /// + /// The unique identifier of the library for which to get the results of the last scans. + /// Cancellation token that can be used to stop the execution. + /// An containing either a path mapped dictionary of , or an error. + public async Task>> GetPathMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryScanResults + .Where(libraryScanResult => + libraryScanResult.LibraryScan.LibraryId == libraryId && // navigation property + libraryScanResult.LibraryScanId == _luminaDbContext.LibraryScans // subquery for latest scan Id + .Where(libraryScan => libraryScan.LibraryId == libraryId) + .OrderByDescending(libraryScan => libraryScan.CreatedOnUtc) + .Select(libraryScan => libraryScan.Id) + .FirstOrDefault()) + .ToDictionaryAsync( // since these are used in large quantity comparisons, dictionary allows for O(1) lookups, instead of lists, with O(n * m) + libraryScanResult => libraryScanResult.Path, + libraryScanResult => libraryScanResult, + StringComparer.Ordinal, // UNIX systems allow for case sensitive file paths + cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs new file mode 100644 index 00000000..46daf71b --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for filtering only files that have known book formats extensions. +/// +public interface IBooksFileExtensionsFilterJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs index 249d6711..d9faa1d5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs @@ -33,15 +33,19 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner // declare the list of jobs that this scanner requires IFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); IRepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); + IBooksFileExtensionsFilterJob booksFileExtensionsFilterJob = _mediaScanJobFactory.CreateJob(libraryId); IHashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob(libraryId); IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob(libraryId); IRepositoryMetadataSaveJob repositoryMetadataSaveJob = _mediaScanJobFactory.CreateJob(libraryId); // establish the hierarchical relationships between jobs - fileSystemDiscoveryJob.AddChild(hashComparerJob); + fileSystemDiscoveryJob.AddChild(booksFileExtensionsFilterJob); repositoryMetadataDiscoveryJob.AddChild(hashComparerJob); + + booksFileExtensionsFilterJob.AddChild(hashComparerJob); + booksFileExtensionsFilterJob.AddParent(fileSystemDiscoveryJob); - hashComparerJob.AddParent(fileSystemDiscoveryJob); + hashComparerJob.AddParent(booksFileExtensionsFilterJob); hashComparerJob.AddParent(repositoryMetadataDiscoveryJob); if (downloadMedatadaFromWeb) diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 54c63f4d..3866c9b1 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -46,7 +46,8 @@ public static class InfrastructureLayerServices // scan the current assembly for validators and add them to the DI container services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton); - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -68,10 +69,12 @@ public static class InfrastructureLayerServices services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); return services; } diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.LibraryScanning.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.LibraryScanning.cs new file mode 100644 index 00000000..29538e04 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.LibraryScanning.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Infrastructure.Common.Errors; + +/// +/// Media Library Scan error types. +/// +public static partial class Errors +{ + public static class LibraryScanning + { + public static Error FailedToCreateScanJobProgress => Error.Failure(description: nameof(FailedToCreateScanJobProgress)); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs index 855c987c..c8fb72a7 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs @@ -4,21 +4,20 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.Management; -using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Payloads; +using Lumina.Infrastructure.Common.Errors; using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; #endregion @@ -30,23 +29,17 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob { - private readonly IDirectoryService _directoryService; - private readonly IFileService _fileService; private readonly IServiceScopeFactory _serviceScopeFactory; - + /// /// Initializes a new instance of the class. /// - /// Injected service for handling directories. - /// Injected service for handling files. /// /// Injected factory for creating scopes in which services are requested. /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. /// - public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService, IServiceScopeFactory serviceScopeFactory) + public FileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory) { - _directoryService = directoryService; - _fileService = fileService; _serviceScopeFactory = serviceScopeFactory; } @@ -65,19 +58,20 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - Console.WriteLine("started file discovering"); + Stopwatch sw = Stopwatch.StartNew(); + Console.WriteLine("Started file system discovery scan job..."); // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); - IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryRepository libraryRepository = unitOfWork.GetRepository()!; MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError || getLibraryResult.Value is null) { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return; } @@ -85,57 +79,58 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); if (domainLibraryResult.IsError) { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return; } // set the initial progress of the scan job - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles"); - if (scanJobProgressResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) return; - } - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); + DateTime lastHeartbeat = DateTime.UtcNow; + long processedFiles = 0L; + int processedContentLocations = 0; - // recursively get the file system tree for each of the media library content locations - List contentLocationTrees = []; + // get the files for each of the media library content locations + List discoveredFiles = []; foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) { - await Task.Delay(1000); cancellationToken.ThrowIfCancellationRequested(); - ErrorOr treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken); - if (treeResult.IsError) - { - // handle errors, maybe: - // Status = LibraryScanJobStatus.Failed; - } - else - contentLocationTrees.Add(treeResult.Value); - // increment the number of processed elements progress - scanJobProgressResult = MediaLibraryScanJobProgress.Create( - scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles"); - if (scanJobProgressResult.IsError) + foreach (FileInfo file in GetFiles(contentLocation.Path, true, cancellationToken)) { - await publisher!.Publish(new LibraryScanFailedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; + discoveredFiles.Add(file); + processedFiles++; + + // increment the number of processed elements progress in a high-frequency counter with low overhead check + if (processedFiles % 1000 == 0) + { + DateTime now = DateTime.UtcNow; + if (now - lastHeartbeat >= heartbeatInterval) + { + publishJobProgressResult = await PublishJobProgress( + publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + return; + lastHeartbeat = now; + } + } } - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + processedContentLocations++; } // this job finished, increment the number of processed jobs progress - await publisher!.Publish(new LibraryScanProgressChangedDomainEvent( + await publisher.Publish(new LibraryScanProgressChangedDomainEvent( Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Console.WriteLine("ended file discovering"); + sw.Stop(); + Console.WriteLine($"Ended file system discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {discoveredFiles.Count} files."); + Status = LibraryScanJobStatus.Completed; // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob children in Children) - await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false); + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, discoveredFiles, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); } } @@ -147,69 +142,97 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD } /// - /// Builds a hierarchical tree structure representing the file system starting from the specified path. + /// Gets all files under the specified directory. /// - /// The identifier of the root path from which to build the tree. - /// Specifies whether hidden files and directories should be included in the tree. - /// An containing either a , or an error. - private ErrorOr BuildTree(FileSystemPathId path, bool includeHiddenElements = false, CancellationToken cancellationToken = default) + /// The path of the root directory from which to start collecting files. + /// Specifies whether hidden files and directories should be included. + /// Cancellation token that can be used to stop the execution. + /// + /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md for details. + /// + /// The discovered collection of files. + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + private static IEnumerable GetFiles(string rootDirectoryPath, bool includeHiddenElements, CancellationToken cancellationToken) { - // validate the path and get the root directory node - ErrorOr rootDirectoryResult = Directory.Create(path, path.Path, Optional.None(), Optional.None()); - if (rootDirectoryResult.IsError) - return rootDirectoryResult.Errors; + Queue directoryStack = new(); + directoryStack.Enqueue(new DirectoryInfo(rootDirectoryPath)); - // build the tree starting from the root directory - return BuildNodeRecursive(rootDirectoryResult.Value, includeHiddenElements, cancellationToken); + EnumerationOptions enumerationOptions = new() + { + AttributesToSkip = includeHiddenElements ? FileAttributes.None : FileAttributes.Hidden, + IgnoreInaccessible = true, + RecurseSubdirectories = false + }; + // use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory + // and could result in stack overflow on deeply nested directories + while (directoryStack.Count > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + DirectoryInfo currentDirectory = directoryStack.Dequeue(); + + // process files first + IEnumerable? files = null; + try + { + files = currentDirectory.EnumerateFiles("*", enumerationOptions); + } + catch (IOException ex) + { + Console.WriteLine(ex.Message); + } + + if (files is not null) + { + foreach (FileInfo file in files) + { + cancellationToken.ThrowIfCancellationRequested(); + yield return file; + } + } + + // process subdirectories - each new subdirectory is added to the same stack queue, for later processing + IEnumerable? subdirs = null; + try + { + subdirs = currentDirectory.EnumerateDirectories("*", enumerationOptions); + } + catch (IOException ex) + { + Console.WriteLine(ex.Message); + } + + if (subdirs is not null) + { + foreach (DirectoryInfo subdir in subdirs) + { + cancellationToken.ThrowIfCancellationRequested(); + directoryStack.Enqueue(subdir); + } + } + } } /// - /// Recursively builds a tree node for a given directory, including its subdirectories and files. + /// Publishes a job progress update. /// - /// The directory for which to build a tree node. - /// Specifies whether hidden files and directories should be included in the node's children. - /// An containing either a , or an error. - private ErrorOr BuildNodeRecursive(Directory directory, bool includeHiddenElements, CancellationToken cancellationToken) + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { - FileSystemTreeNode node = new() + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles"); + if (scanJobProgressResult.IsError) { - Path = directory.Id.Path, - Name = directory.Name, - ItemType = FileSystemItemType.Directory, - Children = [] - }; - - // fetch and add subdirectories - ErrorOr> subdirectoriesResult = _directoryService.GetSubdirectories(directory, includeHiddenElements); - if (subdirectoriesResult.IsError) - return subdirectoriesResult.Errors; - - foreach (Directory subdirectory in subdirectoriesResult.Value) - { - cancellationToken.ThrowIfCancellationRequested(); - ErrorOr subNodeResult = BuildNodeRecursive(subdirectory, includeHiddenElements, cancellationToken); - if (subNodeResult.IsError) - return subNodeResult.Errors; - - node.Children.Add(subNodeResult.Value); + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return Errors.LibraryScanning.FailedToCreateScanJobProgress; } - // fetch and add files - ErrorOr> filesResult = _fileService.GetFiles(directory.Id, includeHiddenElements); - if (filesResult.IsError) - return filesResult.Errors; + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - foreach (File file in filesResult.Value) - { - cancellationToken.ThrowIfCancellationRequested(); - node.Children.Add(new FileSystemTreeNode - { - Path = file.Id.Path, - Name = file.Name, - ItemType = FileSystemItemType.File, - Children = [] // files have no children - }); - } - return node; + return Result.Success; } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs index 2af05d88..7fd4c5ee 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs @@ -3,17 +3,22 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; +using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Infrastructure.Common.Errors; using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; -using System.Linq; +using System.Diagnostics; +using System.IO; using System.Threading; using System.Threading.Tasks; #endregion @@ -26,6 +31,8 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob { private readonly IServiceScopeFactory _serviceScopeFactory; + private Dictionary libraryScanResultEntities = []; + private List files = []; /// /// Initializes a new instance of the class. @@ -46,70 +53,115 @@ internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob { // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); + + // store the incoming payloads as they arrive from parent jobs + if (input is Dictionary libraryScanResultsPayload) + libraryScanResultEntities = libraryScanResultsPayload; + else if (input is List filesPayload) + files = filesPayload; + // only execute this job's payload when it has no parents, or when all the parents finished their execution if (Parents.Count == 0 || parentsCompleted == Parents.Count) { - Status = LibraryScanJobStatus.Running; - Console.WriteLine("started file hashing"); - // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); - IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError || getLibraryResult.Value is null) + // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // processing that takes time, and would block the processing of scan jobs in the in-memory queue + await Task.Run(async () => { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } + Status = LibraryScanJobStatus.Running; + Stopwatch sw = Stopwatch.StartNew(); + Console.WriteLine("Started file hashing..."); + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + IFileService fileService = asyncServiceScope.ServiceProvider.GetService()!; + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // convert it to a domain object - ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - // set the initial progress of the scan job - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 50, "ComparingFileHashes"); - //ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes"); - if (scanJobProgressResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - List ints = Enumerable.Range(0, 50).ToList(); - foreach (int nr in ints) - { - await Task.Delay(100); - // increment the number of processed elements progress - scanJobProgressResult = MediaLibraryScanJobProgress.Create( - nr, 50, "ComparingFileHashes"); - //scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes"); - if (scanJobProgressResult.IsError) + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) { await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return; } - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - } - // this job finished, increment the number of processed jobs progress - await publisher!.Publish(new LibraryScanProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Status = LibraryScanJobStatus.Completed; - Console.WriteLine("ended file hashing"); - // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob children in Children) - await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // set the initial progress of the scan job; total progress is going twice through the list of files, once to determine what needs to be hashed, second to actually hash + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, files.Count * 2, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + return; + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + // pre-allocate with worst case scenario, to avoid memory copying and garbage collection + List filesToHash = new(files.Count); + + for (int i = 0; i < files.Count; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + + FileInfo file = files[i]; + // fastest path - file does not exist in past scan, so it's a new file + if (!libraryScanResultEntities.TryGetValue(file.FullName, out LibraryScanResultEntity? previousScanFile)) + filesToHash.Add(file); + else if (file.Length != previousScanFile.FileSize) // next best comparison, check if file size or the last modified date changed + filesToHash.Add(file); // definitely changed + else if (file.LastWriteTimeUtc != previousScanFile.LastModified) // potential change - requires hash verification + filesToHash.Add(file); + + // remove any found items, to speed up subsequent lookups (if needed, all the remaining entries in this dictionary at the end of the scan are deleted filed) + libraryScanResultEntities.Remove(file.FullName); + + // check if enough time has passed since last update + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // increment the number of processed elements progress + publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, files.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + return; + + // update the last update time + lastUpdateTime = now; + } + } + int processedFiles = 0; + List processed = fileHashService.HashFiles(filesToHash, libraryScanResultEntities, + async () => + { + // check if enough time has passed since last update + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // increment the number of processed elements progress + publishJobProgressResult = await PublishJobProgress( + publisher, compositeKey, Interlocked.Increment(ref processedFiles), files.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + return; + // update the last update time + lastUpdateTime = now; + } + }, cancellationToken); + + // this job finished, increment the number of processed jobs progress + await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + sw.Stop(); + Console.WriteLine($"Ended file hashing in {sw.ElapsedMilliseconds}ms, hashed {processed.Count} files."); + + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, files, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) @@ -118,4 +170,28 @@ internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob throw; } } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes"); + if (scanJobProgressResult.IsError) + { + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return Errors.LibraryScanning.FailedToCreateScanJobProgress; + } + + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs index 3a5a4b39..6ccb3243 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs @@ -9,10 +9,13 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Infrastructure.Common.Errors; using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -49,23 +52,26 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep if (Parents.Count == 0 || parentsCompleted == Parents.Count) { // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous - // file system processing that takes time, and would block the processing of scan jobs in the in-memory queue + // processing that takes time, and would block the processing of scan jobs in the in-memory queue await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - Console.WriteLine("started repo discovering"); + Stopwatch sw = Stopwatch.StartNew(); + Console.WriteLine("Started repo discovering..."); // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); - IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryRepository libraryRepository = unitOfWork.GetRepository(); + ILibraryScanResultRepository libraryScanResultRepository = unitOfWork.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError || getLibraryResult.Value is null) { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return; } @@ -73,45 +79,35 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); if (domainLibraryResult.IsError) { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return; } - // set the initial progress of the scan job - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData"); - if (scanJobProgressResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + // set the initial progress of the scan job, it's a 1 step job - retrieving stuff from repository + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) return; - } - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + // get the results of the last scan of the media library + ErrorOr> getScanResultsResult = + await libraryScanResultRepository.GetPathMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getScanResultsResult.IsError) + return; + + // increment the number of processed elements progress + publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + return; - List ints = [1, 2, 3]; - foreach (int nr in ints) - { - await Task.Delay(1000); - // increment the number of processed elements progress - scanJobProgressResult = MediaLibraryScanJobProgress.Create( - scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData"); - if (scanJobProgressResult.IsError) - { - await publisher!.Publish( - new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - return; - } - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - } // this job finished, increment the number of processed jobs progress - await publisher!.Publish(new LibraryScanProgressChangedDomainEvent( + await publisher.Publish(new LibraryScanProgressChangedDomainEvent( Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; - Console.WriteLine("ended repo discovering"); + sw.Stop(); + Console.WriteLine($"Ended repository discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {getScanResultsResult.Value.Count} items."); // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob children in Children) - await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, getScanResultsResult.Value, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); } } @@ -121,4 +117,28 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep throw; } } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "RetrievingPastScanData"); + if (scanJobProgressResult.IsError) + { + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return Errors.LibraryScanning.FailedToCreateScanJobProgress; + } + + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs index 398249ca..36a47324 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs @@ -9,10 +9,12 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Infrastructure.Common.Errors; using Mediator; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Threading; using System.Threading.Tasks; #endregion @@ -49,23 +51,24 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito if (Parents.Count == 0 || parentsCompleted == Parents.Count) { // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous - // file system processing that takes time, and would block the processing of scan jobs in the in-memory queue + // processing that takes time, and would block the processing of scan jobs in the in-memory queue await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - Console.WriteLine("started repo saving"); + Stopwatch sw = Stopwatch.StartNew(); + Console.WriteLine("Started repository saving..."); // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); - IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryRepository libraryRepository = unitOfWork.GetRepository(); MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError || getLibraryResult.Value is null) { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return; } @@ -73,40 +76,29 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); if (domainLibraryResult.IsError) { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); return; } // set the initial progress of the scan job - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData"); - if (scanJobProgressResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) return; - } - - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); List ints = [1, 2, 3]; foreach (int nr in ints) { await Task.Delay(500); // increment the number of processed elements progress - scanJobProgressResult = MediaLibraryScanJobProgress.Create( - scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData"); - if (scanJobProgressResult.IsError) - { - await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) return; - } - await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); } // this job finished, and it's the last in the chain, the scan is completed Status = LibraryScanJobStatus.Completed; - await publisher!.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - Console.WriteLine("ended repo saving"); + await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + sw.Stop(); + Console.WriteLine($"Ended repository saving scan job in {sw.ElapsedMilliseconds}ms, saved {ints.Count} items."); // this should always be the last job in the directed acyclic job graph, so no linked child to call further }, cancellationToken).ConfigureAwait(false); } @@ -117,4 +109,28 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito throw; } } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData"); + if (scanJobProgressResult.IsError) + { + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return Errors.LibraryScanning.FailedToCreateScanJobProgress; + } + + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs new file mode 100644 index 00000000..ffdd71c4 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs @@ -0,0 +1,195 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; +using Lumina.Infrastructure.Common.Errors; +using Mediator; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Media library scan job for filtering only files that have known book formats extensions. +/// +internal sealed class BooksFileExtensionsFilterJob : MediaLibraryScanJob, IBooksFileExtensionsFilterJob +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly string[] _knownBookFileExtensions = + [ + ".pdf", ".epub", ".mobi", ".azw", ".azw3", + ".cbz", ".cbr", ".djvu", ".fb2", ".lit", + ".prc", ".txt", ".doc", ".docx", ".rtf" + ]; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// + public BooksFileExtensionsFilterJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); + // only execute this job's payload when it has no parents, or when all the parents finished their execution + if (Parents.Count == 0 || parentsCompleted == Parents.Count) + { + if (input is List payload) + { + // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // processing that takes time, and would block the processing of scan jobs in the in-memory queue + await Task.Run(async () => + { + Status = LibraryScanJobStatus.Running; + Stopwatch sw = Stopwatch.StartNew(); + Console.WriteLine("Started book file filtering..."); + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryRepository libraryRepository = unitOfWork.GetRepository(); + IPathService pathService = asyncServiceScope.ServiceProvider.GetService()!; + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) + { + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + { + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // set the initial progress of the scan job + ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, payload.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + return; + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + + List bookFiles = new(payload.Count / 2); // pre-allocate with estimated capacity (boy, that's an optimistic view on books...) + for (int i = 0; i < payload.Count; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + + FileInfo file = payload[i]; + + if (HasKnownBookExtension(file.Name.AsSpan())) + bookFiles.Add(file); + // check if enough time has passed since last update + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // update job progress report + publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, payload.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + return; + // update the last update time + lastUpdateTime = now; + } + } + + // this job finished, increment the number of processed jobs progress + await publisher.Publish(new LibraryScanProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + sw.Stop(); + Console.WriteLine($"Ended book file filtering in {sw.ElapsedMilliseconds}ms, filtered {bookFiles.Count} files."); + Status = LibraryScanJobStatus.Completed; + + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, bookFiles, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + } + + /// + /// Checks if has a known book file extension or not. + /// + /// The file path to be checked. + /// if contains a known book file extension, otherwise. + public bool HasKnownBookExtension(ReadOnlySpan filePath) + { + // find the last dot in the path + int lastDotIndex = filePath.LastIndexOf('.'); + + // if no dot found or it's the last character, return false + if (lastDotIndex == -1) + return false; + + // get the extension part (including the dot) + ReadOnlySpan extension = filePath[lastDotIndex..]; + + // check against each known extension + foreach (string knownExt in _knownBookFileExtensions) + if (extension.SequenceEqual(knownExt.AsSpan())) + return true; + + return false; + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "FilteringBookFiles"); + if (scanJobProgressResult.IsError) + { + await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return Errors.LibraryScanning.FailedToCreateScanJobProgress; + } + + await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs index 98b96e6e..c9999f84 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs @@ -109,8 +109,8 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead Status = LibraryScanJobStatus.Completed; Console.WriteLine("ended goodreads metadata"); // call each linked child with the obtained payload - foreach (IMediaLibraryScanJob children in Children) - await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs new file mode 100644 index 00000000..2c2c049b --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs @@ -0,0 +1,157 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; +using Lumina.Application.Common.Infrastructure.Security; +using Microsoft.Extensions.ObjectPool; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.Hashing; +using System.IO.MemoryMappedFiles; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Security; + +/// +/// Service for hashing files by sampling chunks from them. +/// +internal class FileHashService : IFileHashService +{ + private const int SAMPLE_COUNT = 6; // number of sample points for hash computation + private const ushort DEFAULT_BUFFER_SIZE = 65535; // buffer size (64KB - 1) for reading file chunks + private readonly ThreadLocal _threadLocalBuffer = new(() => new byte[DEFAULT_BUFFER_SIZE]); // thread-local buffer to minimize memory allocations during parallel processing + private static readonly ObjectPool s_hasherPool = new DefaultObjectPool(new DefaultPooledObjectPolicy()); // object pool for reusing hashers, to reduce GC pressure + + /// + /// Hashes by sampling chunks from them. + /// + /// The collection of files to hash. + /// Lookup dictionary of a previous media library scan, used to determine if a file changed or not. + /// Callback to invoke during processing of elements. + /// Cancellation token that can be used to stop the execution. + /// A collection of files that changed since last library scan, along with their hashes. + public List HashFiles( + List files, + Dictionary previousScanResults, + Func callback, + CancellationToken cancellationToken) + { + List changedFiles = []; + object listLock = new(); + int totalFiles = files.Count; + + // make use of all available processors + ParallelOptions parallelOptions = new() + { + CancellationToken = cancellationToken, + MaxDegreeOfParallelism = Environment.ProcessorCount + }; + Parallel.ForEach(files, parallelOptions, async file => + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + // invoke the method that triggers progress reporting + await callback().ConfigureAwait(false); + // if file has no contents, it needs no hashing + if (file.Length == 0) + return; + // buffer management with thread-local reuse + byte[] buffer = _threadLocalBuffer.Value ?? new byte[DEFAULT_BUFFER_SIZE]; + ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, file.Length); + + // get the file hash and check if it differs from the one stored on previous scan + ulong currentHash = ComputeFileHash(file.FullName, file.Length, bufferSize, buffer); + bool isChanged = !previousScanResults.TryGetValue(file.FullName, out LibraryScanResultEntity? previous) || previous.ContentHash != currentHash; + + if (isChanged) // hash changed, file needs to be re-scanned + lock (listLock) + changedFiles.Add(new ChangedFileSystemFile(file, currentHash)); + } + catch (Exception ex) + { + Debug.WriteLine($"Error processing {file.FullName}: {ex.Message}"); + } + }); + + return changedFiles; + } + + /// + /// Computes content hash using memory-mapped sampling. + /// + /// Sample window size (automatically clamped to file size). + /// Reusable read buffer (thread-local allocation optimized). + private unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize, byte[] buffer) + { + // create a memory-mapped file for efficient access to large files + using MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read); + // create a view accessor to read from the memory-mapped file + using MemoryMappedViewAccessor memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor(0, fileSize, MemoryMappedFileAccess.Read); + + byte* memoryPointer = null; + + try + { + // get a direct pointer to the memory-mapped file, for faster access + memoryMappedViewAccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref memoryPointer); + // get a hasher from the pool to avoid allocations + XxHash64 hasher = s_hasherPool.Get(); + + // allocate hash result buffer on the stack, to avoid heap allocation + Span hashSpan = stackalloc byte[sizeof(ulong)]; + + // process only predefined sampled segments of the file, instead of the entire file + foreach (long offset in GetByteBufferSampleOffsets(fileSize, bufferSize)) + { + // calculate how many bytes to read (handle edge case at end of file, or when the file size is smaller than the buffer) + ushort readSize = (ushort)Math.Min(bufferSize, fileSize - offset); + // create a span directly over the memory-mapped region + ReadOnlySpan dataSpan = new(memoryPointer + offset, readSize); + // update the hash with this chunk of data + hasher.Append(dataSpan); + } + + // get the final hash value + if (!hasher.TryGetCurrentHash(hashSpan, out int bytesWritten) || bytesWritten != sizeof(ulong)) + throw new InvalidOperationException("Hash computation failed"); + // convert the hash byte span to a long, and return it + return BitConverter.ToUInt64(hashSpan); + } + finally + { + if (memoryPointer is not null) // always release the pointer, to prevent memory leaks + memoryMappedViewAccessor.SafeMemoryMappedViewHandle.ReleasePointer(); + } + } + + /// + /// Generates sample offsets for reading portions of a file. + /// + /// The size of the file, in bytes. + /// The buffer size used for reading. + /// An enumerable of byte offsets to sample from the file. + private static IEnumerable GetByteBufferSampleOffsets(long fileSize, ushort bufferSize) + { + // for small files, just read from the beginning + if (fileSize <= bufferSize * SAMPLE_COUNT) + { + yield return 0; + yield break; + } + // for larger files, sample at strategic points: + yield return 0; // beginning of the file + yield return fileSize / 4; // quarter of the file + yield return fileSize / 2; // file of the file + yield return 3 * fileSize / 4; // three quarters of the file + yield return Math.Max(0, fileSize - bufferSize); // end of the file (ensure we don't go past the end) + + // additional evenly spaced samples, if needed + long interval = fileSize / (SAMPLE_COUNT + 1); + for (int i = 1; i <= SAMPLE_COUNT - 4; i++) + yield return interval * i; + } +} diff --git a/src/Lumina.Infrastructure/Core/Security/HashService.cs b/src/Lumina.Infrastructure/Core/Security/PasswordHashService.cs similarity index 98% rename from src/Lumina.Infrastructure/Core/Security/HashService.cs rename to src/Lumina.Infrastructure/Core/Security/PasswordHashService.cs index e1079cf6..7cc5233d 100644 --- a/src/Lumina.Infrastructure/Core/Security/HashService.cs +++ b/src/Lumina.Infrastructure/Core/Security/PasswordHashService.cs @@ -11,7 +11,7 @@ namespace Lumina.Infrastructure.Core.Security; /// /// Service for hashing passwords. /// -public sealed class HashService : IHashService +public sealed class PasswordHashService : IPasswordHashService { // OWASP recommended parameters for Argon2id private const int MEMORY_SIZE = 19456; // 19 MiB (19 * 1024 = 19456) diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 2b5504ac..0819fb26 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -7,6 +7,7 @@ false true $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + True @@ -19,6 +20,7 @@ + @@ -27,6 +29,7 @@ + diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs index 0ac46c2d..d2ce826f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs @@ -47,6 +47,6 @@ public class CheckInitializationEndpoint : BaseEndpoint public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { InitializationResponse result = await _sender.Send(new CheckInitializationQuery(), cancellationToken).ConfigureAwait(false); - return await Task.FromResult(TypedResults.Ok(result)); + return TypedResults.Ok(result); } } diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx index 90f4a3cf..ce6e8e39 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx @@ -186,6 +186,9 @@ Filmreihe + + Buchdateien werden gefiltert... + Metadaten werden von GoodReads heruntergeladen... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx index 8627b6f0..3903ded1 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx @@ -186,6 +186,9 @@ Film Series + + Filtering book files... + Downloading metadata from GoodReads... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx index fa7f4aa7..634313d9 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx @@ -186,6 +186,9 @@ Saga Cinematográfica + + Filtrando archivos de libros... + Descargando metadatos de GoodReads... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx index 9d5893fa..9c14201c 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx @@ -186,6 +186,9 @@ Saga Cinématographique + + Filtrage des fichiers de livres... + Téléchargement des métadonnées depuis GoodReads... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx index bfafb1a1..9958003b 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx @@ -186,6 +186,9 @@ Saga Cinematografica + + Filtraggio dei file di libri... + Scaricamento dei metadati da GoodReads... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx index 5ebc9838..966d7ae2 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx @@ -186,6 +186,9 @@ 映画シリーズ + + 書籍ファイルをフィルタリング中... + GoodReadsからメタデータをダウンロード中... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx index 8627b6f0..3903ded1 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx @@ -186,6 +186,9 @@ Film Series + + Filtering book files... + Downloading metadata from GoodReads... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx index 5332c1de..e22f1e82 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx @@ -186,6 +186,9 @@ Serie de Filme + + Se filtrează fișierele de tip carte... + Se descarcă metadate de pe GoodReads... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx index 4b5596eb..8e6340a9 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx @@ -186,6 +186,9 @@ Киносерия + + Фильтрация файлов книг... + Загрузка метаданных из GoodReads... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx index 439ac7bd..4f22d893 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx @@ -186,6 +186,9 @@ 电影系列 + + 正在过滤书籍文件... + 正在从GoodReads下载元数据... diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml index b4f14f2e..4c3cc226 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml @@ -144,7 +144,8 @@ RetrievingPastScanData: '@_localizer["RetrievingPastScanData"]', ComparingFileHashes: '@_localizer["ComparingFileHashes"]', GoodReadsMetadataDownload: '@_localizer["GoodReadsMetadataDownload"]', - SavingScanData: '@_localizer["SavingScanData"]' + SavingScanData: '@_localizer["SavingScanData"]', + FilteringBookFiles: '@_localizer["FilteringBookFiles"]' }; const jsLocalizedLibraryTypes = { Book: '@_localizer["Book"]', diff --git a/src/Lumina.sln b/src/Lumina.sln index 742b2154..6022e22c 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -190,6 +190,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", ProjectSection(SolutionItems) = preProject ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0001.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0001.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0002.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0002.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0003.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0003.md EndProjectSection EndProject Global diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs index ddf69249..e85e1420 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; [ExcludeFromCodeCoverage] public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable { - private readonly HashService _hashService; + private readonly PasswordHashService _hashService; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -41,7 +41,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable /// public AuthenticatedLuminaApiFactory() { - _hashService = new HashService(); + _hashService = new PasswordHashService(); } /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs index 95a2cee1..4d65d525 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -112,7 +112,7 @@ public class CheckInitializationEndpointTests : IClassFixture, { private HttpClient _client; private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly HashService _hashService; + private readonly PasswordHashService _hashService; private readonly ICryptographyService _cryptographyService; private readonly TotpTokenGenerator _totpTokenGenerator; private readonly JsonSerializerOptions _jsonOptions = new() @@ -50,7 +50,7 @@ public class LoginEndpointTests : IClassFixture, { _client = apiFactory.CreateClient(); _apiFactory = apiFactory; - _hashService = new HashService(); + _hashService = new PasswordHashService(); _totpTokenGenerator = new TotpTokenGenerator(); _testUsername = $"testuser_{Guid.NewGuid()}"; diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index 917992be..3867d841 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -34,7 +34,7 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDis { private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; - private readonly HashService _hashService; + private readonly PasswordHashService _hashService; private readonly string _testUsername; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -42,7 +42,7 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis _client = apiFactory.CreateClient(); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12"); - _hashService = new HashService(); + _hashService = new PasswordHashService(); _testUsername = $"testuser_{Guid.NewGuid()}"; } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs index a7ae8f7a..3485b038 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs @@ -26,7 +26,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A [ExcludeFromCodeCoverage] public class LoginEndpointTests : IClassFixture, IDisposable { - private readonly HashService _hashService; + private readonly PasswordHashService _hashService; private readonly ICryptographyService _cryptographyService; private readonly TotpTokenGenerator _totpTokenGenerator; private readonly LuminaApiFactory _apiFactory; @@ -49,7 +49,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable // set a fake IP for this test instance _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.1"); - _hashService = new HashService(); + _hashService = new PasswordHashService(); _totpTokenGenerator = new TotpTokenGenerator(); _testUsername = $"testuser_{Guid.NewGuid()}"; diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs index 5bcf5073..40d63a07 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -22,7 +22,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A [ExcludeFromCodeCoverage] public class RegisterEndpointTests : IClassFixture, IDisposable { - private readonly HashService _hashService; + private readonly PasswordHashService _hashService; private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly JsonSerializerOptions _jsonOptions = new() @@ -38,7 +38,7 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl _client = apiFactory.CreateClient(); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.5"); - _hashService = new HashService(); + _hashService = new PasswordHashService(); _testUsername = $"testuser_{Guid.NewGuid()}"; } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index bc66e4bd..d1961244 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -29,7 +29,7 @@ namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Command public class SetupApplicationCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; - private readonly IHashService _mockHashService; + private readonly IPasswordHashService _mockHashService; private readonly ICryptographyService _mockCryptographyService; private readonly ITotpTokenGenerator _mockTotpTokenGenerator; private readonly IQRCodeGenerator _mockQRCodeGenerator; @@ -45,7 +45,7 @@ public class SetupApplicationCommandHandlerTests public SetupApplicationCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); - _mockHashService = Substitute.For(); + _mockHashService = Substitute.For(); _mockCryptographyService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); _mockQRCodeGenerator = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs index 70b3b224..1c39e3cc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -24,7 +24,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma public class ChangePasswordCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; - private readonly IHashService _mockHashService; + private readonly IPasswordHashService _mockHashService; private readonly IUserRepository _mockUserRepository; private readonly ChangePasswordCommandHandler _sut; @@ -34,7 +34,7 @@ public class ChangePasswordCommandHandlerTests public ChangePasswordCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); - _mockHashService = Substitute.For(); + _mockHashService = Substitute.For(); _mockUserRepository = Substitute.For(); _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs index 64b8ad66..19af929a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -25,7 +25,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma public class RecoverPasswordCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; - private readonly IHashService _mockHashService; + private readonly IPasswordHashService _mockHashService; private readonly ITotpTokenGenerator _mockTotpTokenGenerator; private readonly ICryptographyService _mockCryptographyService; private readonly IUserRepository _mockUserRepository; @@ -37,7 +37,7 @@ public class RecoverPasswordCommandHandlerTests public RecoverPasswordCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); - _mockHashService = Substitute.For(); + _mockHashService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); _mockCryptographyService = Substitute.For(); _mockUserRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs index 03057e31..2b616481 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -27,7 +27,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma public class RegisterUserCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; - private readonly IHashService _mockHashService; + private readonly IPasswordHashService _mockHashService; private readonly ICryptographyService _mockCryptographyService; private readonly ITotpTokenGenerator _mockTotpTokenGenerator; private readonly IQRCodeGenerator _mockQRCodeGenerator; @@ -41,7 +41,7 @@ public class RegisterUserCommandHandlerTests public RegisterUserCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); - _mockHashService = Substitute.For(); + _mockHashService = Substitute.For(); _mockCryptographyService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); _mockQRCodeGenerator = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs index d868ffaa..383861ee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -26,7 +26,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queri public class LoginUserQueryHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; - private readonly IHashService _mockHashService; + private readonly IPasswordHashService _mockHashService; private readonly IJwtTokenGenerator _mockJwtTokenGenerator; private readonly ITotpTokenGenerator _mockTotpTokenGenerator; private readonly ICryptographyService _mockCryptographyService; @@ -40,7 +40,7 @@ public class LoginUserQueryHandlerTests public LoginUserQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); - _mockHashService = Substitute.For(); + _mockHashService = Substitute.For(); _mockJwtTokenGenerator = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); _mockCryptographyService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs index b30a0dfb..de079de3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs @@ -7,19 +7,19 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Infrastructure.UnitTests.Core.Security; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class HashServiceTests { - private readonly HashService _sut; + private readonly PasswordHashService _sut; /// /// Initializes a new instance of the class. /// public HashServiceTests() { - _sut = new HashService(); + _sut = new PasswordHashService(); } [Fact]