Merge pull request #127 from BinaryAlley/feature/implement-file-hashing-media-library-scan-job

Implements file hashing media library scan job
This commit is contained in:
BinaryAlley authored and GitHub committed 2025-03-01 14:50:48 +00:00
commit 46778b6408
63 files changed
+2009 -287

No files matched your search

@@ -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<FileInfo> 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 <windows.h>
void win_enumerate(const char* path, void (callback)(const char))
{
WIN32_FIND_DATA fd;
HANDLE h = FindFirstFileEx(path, FindExInfoStandard, &fd, ...);
// ... recursive implementation
}
#else
#include <dirent.h>
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 |
@@ -36,7 +36,7 @@ public class LibraryScanResultEntity : IStorageEntity
/// <summary>
/// Gets the hash calculated for the media library scan file.
/// </summary>
public required string ContentHash { get; init; }
public required ulong ContentHash { get; init; }
/// <summary>
/// Gets the size of the media library scan file.
@@ -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;
@@ -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;
/// <summary>
/// Interface for the repository for media library scan results.
/// </summary>
public interface ILibraryScanResultRepository : IRepository<LibraryScanResultEntity>,
IInsertRepositoryAction<LibraryScanResultEntity>
{
/// <summary>
/// Gets all media library scan results that belong to the last scan of a library identified by <paramref name="libraryId"/>, from the storage medium.
/// </summary>
/// <param name="libraryId">The unique identifier of the library for which to get the results of the last scans.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a path mapped dictionary of <see cref="LibraryScanResultEntity"/>, or an error.</returns>
Task<ErrorOr<Dictionary<string, LibraryScanResultEntity>>> GetPathMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using System.IO;
#endregion
namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
/// <summary>
/// Represents an item for the payload of the file hashing media library scan job.
/// </summary>
/// <param name="File">The file to whom <paramref name="FileHash"/> belongs.</param>
/// <param name="FileHash">The hash of <paramref name="File"/>.</param>
[DebuggerDisplay("File: {File}; FileHash: {FileHash}")]
public record ChangedFileSystemFile(FileInfo File, ulong FileHash);
@@ -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;
/// <summary>
/// Generic file system node.
@@ -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;
/// <summary>
/// Interface for the service for hashing files by sampling chunks from them.
/// </summary>
public interface IFileHashService
{
/// <summary>
/// Hashes <paramref name="files"/> by sampling chunks from them.
/// </summary>
/// <param name="files">The collection of files to hash.</param>
/// <param name="previousScanResults">Lookup dictionary of a previous media library scan, used to determine if a file changed or not.</param>
/// <param name="callback">Callback to invoke during processing of elements.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A collection of files that changed since last library scan, along with their hashes.</returns>
List<ChangedFileSystemFile> HashFiles(
List<FileInfo> files,
Dictionary<string, LibraryScanResultEntity> previousScanResults,
Func<Task> callback,
CancellationToken cancellationToken);
}
@@ -3,7 +3,7 @@ namespace Lumina.Application.Common.Infrastructure.Security;
/// <summary>
/// Interface for the service for hashing passwords.
/// </summary>
public interface IHashService
public interface IPasswordHashService
{
/// <summary>
/// Creates a hash from a string.
@@ -25,7 +25,7 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApp
public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCommand, ErrorOr<RegistrationResponse>>
{
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 : IRequestHandler<SetupApplicationCo
/// <param name="dataSeedService">Injected service for the initial persistence medium data seed.</param>
public SetupApplicationCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
IPasswordHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator,
@@ -20,7 +20,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Change
public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordCommand, ErrorOr<ChangePasswordResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
private readonly IPasswordHashService _hashService;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordCommandHandler"/> class.
@@ -29,7 +29,7 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
/// <param name="hashService">Injected service for password hashing functionality.</param>
public ChangePasswordCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService)
IPasswordHashService hashService)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
@@ -21,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Recove
public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordCommand, ErrorOr<RecoverPasswordResponse>>
{
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 : IRequestHandler<RecoverPasswordComm
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
public RecoverPasswordCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
IPasswordHashService hashService,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService)
{
@@ -22,7 +22,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Regist
public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, ErrorOr<RegistrationResponse>>
{
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 : IRequestHandler<RegisterUserCommand, E
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
public RegisterUserCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
IPasswordHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator,
@@ -22,7 +22,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUs
public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<LoginResponse>>
{
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 : IRequestHandler<LoginUserQuery, ErrorOr<Log
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
public LoginUserQueryHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
IPasswordHashService hashService,
IJwtTokenGenerator jwtTokenGenerator,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService,
@@ -204,19 +204,19 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
});
// 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);
}
@@ -83,19 +83,19 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
});
// 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);
}
@@ -42,19 +42,19 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration<LibraryScanEnti
.HasColumnOrder(1);
// audit
builder.Property(permission => 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);
}
@@ -0,0 +1,877 @@
// <auto-generated />
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
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
modelBuilder.Entity("BookGenres", b =>
{
b.Property<Guid>("BookId")
.HasColumnType("TEXT");
b.Property<string>("GenreId")
.HasColumnType("TEXT");
b.HasKey("BookId", "GenreId");
b.HasIndex("GenreId");
b.ToTable("BookGenres", (string)null);
});
modelBuilder.Entity("BookTags", b =>
{
b.Property<Guid>("BookId")
.HasColumnType("TEXT");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("PermissionName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<DateTime?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("RoleName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<DateTime?>("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<Guid>("RoleId")
.HasColumnType("TEXT");
b.Property<Guid>("PermissionId")
.HasColumnType("TEXT");
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("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<Guid>("UserId")
.HasColumnType("TEXT");
b.Property<Guid>("PermissionId")
.HasColumnType("TEXT");
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("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<Guid>("UserId")
.HasColumnType("TEXT");
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid>("RoleId")
.HasColumnType("TEXT");
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("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<string>("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<string>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<string>("CoverImage")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<bool>("DownloadMedatadaFromWeb")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(true)
.HasColumnOrder(6);
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(true)
.HasColumnOrder(4);
b.Property<bool>("IsLocked")
.HasColumnType("INTEGER")
.HasColumnOrder(5);
b.Property<string>("LibraryType")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<bool>("SaveMetadataInMediaDirectories")
.HasColumnType("INTEGER")
.HasColumnOrder(7);
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(11);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(10);
b.Property<Guid>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<Guid>("LibraryId")
.HasColumnType("TEXT");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<Guid>("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<Guid>("LibraryScanId")
.HasColumnType("TEXT");
b.Property<string>("Path")
.HasMaxLength(1024)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<ulong>("ContentHash")
.HasMaxLength(24)
.HasColumnType("INTEGER")
.HasColumnOrder(2);
b.Property<long>("FileSize")
.HasColumnType("INTEGER")
.HasColumnOrder(3);
b.Property<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<DateTime>("LastModified")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<Guid?>("LibraryScanEntityId")
.HasColumnType("TEXT");
b.Property<string>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<string>("ASIN")
.HasMaxLength(10)
.HasColumnType("TEXT")
.HasColumnOrder(21);
b.Property<string>("AppleBooksId")
.HasColumnType("TEXT")
.HasColumnOrder(29);
b.Property<string>("BarnesAndNobleId")
.HasMaxLength(10)
.HasColumnType("TEXT")
.HasColumnOrder(28);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(33);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(32);
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("Edition")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(19);
b.Property<string>("Format")
.HasColumnType("TEXT")
.HasColumnOrder(18);
b.Property<string>("GoodreadsId")
.HasColumnType("TEXT")
.HasColumnOrder(22);
b.Property<string>("GoogleBooksId")
.HasMaxLength(12)
.HasColumnType("TEXT")
.HasColumnOrder(27);
b.Property<string>("LCCN")
.HasColumnType("TEXT")
.HasColumnOrder(23);
b.Property<string>("LanguageCode")
.HasColumnType("TEXT")
.HasColumnOrder(10);
b.Property<string>("LanguageName")
.HasColumnType("TEXT")
.HasColumnOrder(11);
b.Property<string>("LanguageNativeName")
.HasColumnType("TEXT")
.HasColumnOrder(12);
b.Property<string>("LibraryThingId")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(26);
b.Property<string>("OCLCNumber")
.HasColumnType("TEXT")
.HasColumnOrder(24);
b.Property<string>("OpenLibraryId")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(25);
b.Property<string>("OriginalLanguageCode")
.HasColumnType("TEXT")
.HasColumnOrder(13);
b.Property<string>("OriginalLanguageName")
.HasColumnType("TEXT")
.HasColumnOrder(14);
b.Property<string>("OriginalLanguageNativeName")
.HasColumnType("TEXT")
.HasColumnOrder(15);
b.Property<DateOnly?>("OriginalReleaseDate")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<int?>("OriginalReleaseYear")
.HasColumnType("INTEGER")
.HasColumnOrder(5);
b.Property<string>("OriginalTitle")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<int?>("PageCount")
.HasColumnType("INTEGER")
.HasColumnOrder(17);
b.Property<string>("Publisher")
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(16);
b.Property<DateOnly?>("ReReleaseDate")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<int?>("ReReleaseYear")
.HasColumnType("INTEGER")
.HasColumnOrder(7);
b.Property<string>("ReleaseCountry")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<string>("ReleaseVersion")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(35);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(34);
b.Property<int?>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("TempPassword")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<DateTime?>("TempPasswordCreated")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<string>("TotpSecret")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("LibraryId")
.HasColumnType("TEXT");
b1.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("BookId")
.HasColumnType("TEXT");
b1.Property<decimal>("MaxValue")
.HasColumnType("decimal(3,2)");
b1.Property<string>("Source")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b1.Property<decimal>("Value")
.HasColumnType("decimal(3,2)");
b1.Property<int?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("BookId")
.HasColumnType("TEXT");
b1.Property<string>("Format")
.IsRequired()
.HasMaxLength(6)
.HasColumnType("TEXT");
b1.Property<string>("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
}
}
}
@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations;
/// <inheritdoc />
public partial class ChangesLibraryScanResultContentHashColumnToUlong : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<ulong>(
name: "ContentHash",
table: "LibraryScanResults",
type: "INTEGER",
maxLength: 24,
nullable: false,
oldClrType: typeof(string),
oldType: "TEXT",
oldMaxLength: 24);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "ContentHash",
table: "LibraryScanResults",
type: "TEXT",
maxLength: 24,
nullable: false,
oldClrType: typeof(ulong),
oldType: "INTEGER",
oldMaxLength: 24);
}
}
@@ -359,10 +359,9 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<string>("ContentHash")
.IsRequired()
b.Property<ulong>("ContentHash")
.HasMaxLength(24)
.HasColumnType("TEXT")
.HasColumnType("INTEGER")
.HasColumnOrder(2);
b.Property<long>("FileSize")
@@ -31,9 +31,9 @@ internal sealed class RolePermissionRepository : IRolePermissionRepository
/// <param name="rolePermission">The authorization role permission to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<ErrorOr<Created>> InsertAsync(RolePermissionEntity rolePermission, CancellationToken cancellationToken)
public Task<ErrorOr<Created>> InsertAsync(RolePermissionEntity rolePermission, CancellationToken cancellationToken)
{
_luminaDbContext.RolePermissions.Add(rolePermission);
return await Task.FromResult(Result.Created);
return Task.FromResult(ErrorOrFactory.From(Result.Created));
}
}
@@ -31,9 +31,9 @@ internal sealed class UserRoleRepository : IUserRoleRepository
/// <param name="userRole">The authorization user role to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<ErrorOr<Created>> InsertAsync(UserRoleEntity userRole, CancellationToken cancellationToken)
public Task<ErrorOr<Created>> InsertAsync(UserRoleEntity userRole, CancellationToken cancellationToken)
{
_luminaDbContext.UserRoles.Add(userRole);
return await Task.FromResult(Result.Created);
return Task.FromResult(ErrorOrFactory.From(Result.Created));
}
}
@@ -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;
/// <summary>
/// Repository for media library scan results.
/// </summary>
internal sealed class LibraryScanResultRepository : ILibraryScanResultRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanResultRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public LibraryScanResultRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new library scan result.
/// </summary>
/// <param name="libraryScan">The library scan result to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public Task<ErrorOr<Created>> InsertAsync(LibraryScanResultEntity libraryScan, CancellationToken cancellationToken)
{
_luminaDbContext.LibraryScanResults.Add(libraryScan);
return Task.FromResult(ErrorOrFactory.From(Result.Created));
}
/// <summary>
/// Gets all media library scan results that belong to the last scan of a library identified by <paramref name="libraryId"/>, from the storage medium.
/// </summary>
/// <param name="libraryId">The unique identifier of the library for which to get the results of the last scans.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a path mapped dictionary of <see cref="LibraryScanResultEntity"/>, or an error.</returns>
public async Task<ErrorOr<Dictionary<string, LibraryScanResultEntity>>> 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);
}
}
@@ -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;
/// <summary>
/// Interface for the media library scan job for filtering only files that have known book formats extensions.
/// </summary>
public interface IBooksFileExtensionsFilterJob : IMediaLibraryScanJob
{
}
@@ -33,15 +33,19 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
// declare the list of jobs that this scanner requires
IFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IFileSystemDiscoveryJob>(libraryId);
IRepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob<IRepositoryMetadataDiscoveryJob>(libraryId);
IBooksFileExtensionsFilterJob booksFileExtensionsFilterJob = _mediaScanJobFactory.CreateJob<IBooksFileExtensionsFilterJob>(libraryId);
IHashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob<IHashComparerJob>(libraryId);
IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob<IGoodReadsMetadataScrapJob>(libraryId);
IRepositoryMetadataSaveJob repositoryMetadataSaveJob = _mediaScanJobFactory.CreateJob<IRepositoryMetadataSaveJob>(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)
@@ -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<IHashService, HashService>();
services.AddSingleton<IFileHashService, FileHashService>();
services.AddSingleton<IPasswordHashService, PasswordHashService>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IJwtTokenGenerator, JwtTokenGenerator>();
services.AddSingleton<IQRCodeGenerator, QRCodeGenerator>();
@@ -68,10 +69,12 @@ public static class InfrastructureLayerServices
services.AddTransient<IFileSystemDiscoveryJob, FileSystemDiscoveryJob>();
services.AddTransient<IRepositoryMetadataDiscoveryJob, RepositoryMetadataDiscoveryJob>();
services.AddTransient<IBooksFileExtensionsFilterJob, BooksFileExtensionsFilterJob>();
services.AddTransient<IHashComparerJob, HashComparerJob>();
services.AddTransient<IGoodReadsMetadataScrapJob, GoodReadsMetadataScrapJob>();
services.AddTransient<IRepositoryMetadataSaveJob, RepositoryMetadataSaveJob>();
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
return services;
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
#endregion
namespace Lumina.Infrastructure.Common.Errors;
/// <summary>
/// Media Library Scan error types.
/// </summary>
public static partial class Errors
{
public static class LibraryScanning
{
public static Error FailedToCreateScanJobProgress => Error.Failure(description: nameof(FailedToCreateScanJobProgress));
}
}
@@ -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
/// </summary>
internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob
{
private readonly IDirectoryService _directoryService;
private readonly IFileService _fileService;
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemDiscoveryJob"/> class.
/// </summary>
/// <param name="directoryService">Injected service for handling directories.</param>
/// <param name="fileService">Injected service for handling files.</param>
/// <param name="serviceScopeFactory">
/// 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.
/// </param>
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<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> 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<Library> 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<MediaLibraryScanJobProgress> 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<Success> 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<FileSystemTreeNode> contentLocationTrees = [];
// get the files for each of the media library content locations
List<FileInfo> discoveredFiles = [];
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{
await Task.Delay(1000);
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> 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
}
/// <summary>
/// Builds a hierarchical tree structure representing the file system starting from the specified path.
/// Gets all files under the specified directory.
/// </summary>
/// <param name="path">The identifier of the root path from which to build the tree.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the tree.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
private ErrorOr<FileSystemTreeNode> BuildTree(FileSystemPathId path, bool includeHiddenElements = false, CancellationToken cancellationToken = default)
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <remarks>
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md for details.
/// </remarks>
/// <returns>The discovered collection of files.</returns>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static IEnumerable<FileInfo> GetFiles(string rootDirectoryPath, bool includeHiddenElements, CancellationToken cancellationToken)
{
// validate the path and get the root directory node
ErrorOr<Directory> rootDirectoryResult = Directory.Create(path, path.Path, Optional<DateTime>.None(), Optional<DateTime>.None());
if (rootDirectoryResult.IsError)
return rootDirectoryResult.Errors;
Queue<DirectoryInfo> 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<FileInfo>? 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<DirectoryInfo>? 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);
}
}
}
}
/// <summary>
/// Recursively builds a tree node for a given directory, including its subdirectories and files.
/// Publishes a job progress update.
/// </summary>
/// <param name="directory">The directory for which to build a tree node.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the node's children.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
private ErrorOr<FileSystemTreeNode> BuildNodeRecursive(Directory directory, bool includeHiddenElements, CancellationToken cancellationToken)
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
FileSystemTreeNode node = new()
ErrorOr<MediaLibraryScanJobProgress> 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<IEnumerable<Directory>> subdirectoriesResult = _directoryService.GetSubdirectories(directory, includeHiddenElements);
if (subdirectoriesResult.IsError)
return subdirectoriesResult.Errors;
foreach (Directory subdirectory in subdirectoriesResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> 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<IEnumerable<File>> 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;
}
}
@@ -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<string, LibraryScanResultEntity> libraryScanResultEntities = [];
private List<FileInfo> files = [];
/// <summary>
/// Initializes a new instance of the <see cref="HashComparerJob"/> 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<string, LibraryScanResultEntity> libraryScanResultsPayload)
libraryScanResultEntities = libraryScanResultsPayload;
else if (input is List<FileInfo> 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<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> 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<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
IFileService fileService = asyncServiceScope.ServiceProvider.GetService<IFileService>()!;
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// convert it to a domain object
ErrorOr<Library> 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<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 50, "ComparingFileHashes");
//ErrorOr<MediaLibraryScanJobProgress> 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<int> 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<LibraryEntity?> 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<Library> 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<Success> 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<FileInfo> 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<ChangedFileSystemFile> 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;
}
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> 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;
}
}
@@ -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<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanResultRepository libraryScanResultRepository = unitOfWork.GetRepository<ILibraryScanResultRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> 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<Library> 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<MediaLibraryScanJobProgress> 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<Success> 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<Dictionary<string, LibraryScanResultEntity>> 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<int> 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;
}
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> 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;
}
}
@@ -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<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> 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<Library> 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<MediaLibraryScanJobProgress> 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<Success> 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<int> 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;
}
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> 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;
}
}
@@ -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;
/// <summary>
/// Media library scan job for filtering only files that have known book formats extensions.
/// </summary>
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"
];
/// <summary>
/// Initializes a new instance of the <see cref="BooksFileExtensionsFilterJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">
/// 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.
/// </param>
public BooksFileExtensionsFilterJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(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<FileInfo> 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<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
ErrorOr<LibraryEntity?> 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<Library> 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<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, payload.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
return;
DateTime lastUpdateTime = DateTime.UtcNow;
int minUpdateIntervalMs = 100;
List<FileInfo> 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;
}
}
/// <summary>
/// Checks if <paramref name="filePath"/> has a known book file extension or not.
/// </summary>
/// <param name="filePath">The file path to be checked.</param>
/// <returns><see langword="true"/> if <paramref name="filePath"/> contains a known book file extension, <see langword="false"/> otherwise.</returns>
public bool HasKnownBookExtension(ReadOnlySpan<char> 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<char> extension = filePath[lastDotIndex..];
// check against each known extension
foreach (string knownExt in _knownBookFileExtensions)
if (extension.SequenceEqual(knownExt.AsSpan()))
return true;
return false;
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> 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;
}
}
@@ -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)
@@ -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;
/// <summary>
/// Service for hashing files by sampling chunks from them.
/// </summary>
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<byte[]> _threadLocalBuffer = new(() => new byte[DEFAULT_BUFFER_SIZE]); // thread-local buffer to minimize memory allocations during parallel processing
private static readonly ObjectPool<XxHash64> s_hasherPool = new DefaultObjectPool<XxHash64>(new DefaultPooledObjectPolicy<XxHash64>()); // object pool for reusing hashers, to reduce GC pressure
/// <summary>
/// Hashes <paramref name="files"/> by sampling chunks from them.
/// </summary>
/// <param name="files">The collection of files to hash.</param>
/// <param name="previousScanResults">Lookup dictionary of a previous media library scan, used to determine if a file changed or not.</param>
/// <param name="callback">Callback to invoke during processing of elements.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A collection of files that changed since last library scan, along with their hashes.</returns>
public List<ChangedFileSystemFile> HashFiles(
List<FileInfo> files,
Dictionary<string, LibraryScanResultEntity> previousScanResults,
Func<Task> callback,
CancellationToken cancellationToken)
{
List<ChangedFileSystemFile> 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;
}
/// <summary>
/// Computes content hash using memory-mapped sampling.
/// </summary>
/// <param name="bufferSize">Sample window size (automatically clamped to file size).</param>
/// <param name="buffer">Reusable read buffer (thread-local allocation optimized).</param>
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<byte> 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<byte> 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();
}
}
/// <summary>
/// Generates sample offsets for reading portions of a file.
/// </summary>
/// <param name="fileSize">The size of the file, in bytes.</param>
/// <param name="bufferSize">The buffer size used for reading.</param>
/// <returns>An enumerable of byte offsets to sample from the file.</returns>
private static IEnumerable<long> 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;
}
}
@@ -11,7 +11,7 @@ namespace Lumina.Infrastructure.Core.Security;
/// <summary>
/// Service for hashing passwords.
/// </summary>
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)
@@ -7,6 +7,7 @@
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
@@ -19,6 +20,7 @@
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Core" Version="1.2.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="9.0.0" />
@@ -27,6 +29,7 @@
<PackageReference Include="Otp.NET" Version="1.4.0" />
<PackageReference Include="QRCoder" Version="1.6.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.0" />
<PackageReference Include="System.IO.Hashing" Version="9.0.2" />
</ItemGroup>
<ItemGroup>
@@ -47,6 +47,6 @@ public class CheckInitializationEndpoint : BaseEndpoint<EmptyRequest, IResult>
public override async Task<IResult> 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);
}
}
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>Filmreihe</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>Buchdateien werden gefiltert...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Metadaten werden von GoodReads heruntergeladen...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>Film Series</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>Filtering book files...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Downloading metadata from GoodReads...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>Saga Cinematográfica</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>Filtrando archivos de libros...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Descargando metadatos de GoodReads...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>Saga Cinématographique</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>Filtrage des fichiers de livres...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Téléchargement des métadonnées depuis GoodReads...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>Saga Cinematografica</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>Filtraggio dei file di libri...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Scaricamento dei metadati da GoodReads...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>映画シリーズ</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>書籍ファイルをフィルタリング中...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>GoodReadsからメタデータをダウンロード中...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>Film Series</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>Filtering book files...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Downloading metadata from GoodReads...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>Serie de Filme</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>Se filtrează fișierele de tip carte...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Se descarcă metadate de pe GoodReads...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>Киносерия</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>Фильтрация файлов книг...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>Загрузка метаданных из GoodReads...</value>
</data>
@@ -186,6 +186,9 @@
<data name="FilmSeries" xml:space="preserve">
<value>电影系列</value>
</data>
<data name="FilteringBookFiles" xml:space="preserve">
<value>正在过滤书籍文件...</value>
</data>
<data name="GoodReadsMetadataDownload" xml:space="preserve">
<value>正在从GoodReads下载元数据...</value>
</data>
@@ -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"]',
+1
View File
@@ -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
@@ -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
/// </summary>
public AuthenticatedLuminaApiFactory()
{
_hashService = new HashService();
_hashService = new PasswordHashService();
}
/// <summary>
@@ -112,7 +112,7 @@ public class CheckInitializationEndpointTests : IClassFixture<AuthenticatedLumin
UserEntity user = new()
{
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Password = new PasswordHashService().HashString("TestPass123!"),
Libraries = [],
UserPermissions = [],
UserRole = null,
@@ -215,7 +215,7 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
UserEntity user = new()
{
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Password = new PasswordHashService().HashString("TestPass123!"),
Libraries = [],
UserPermissions = [],
UserRole = null, // TODO: test default role and permissions?
@@ -32,7 +32,7 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
{
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<AuthenticatedLuminaApiFactory>,
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
_hashService = new HashService();
_hashService = new PasswordHashService();
_totpTokenGenerator = new TotpTokenGenerator();
_testUsername = $"testuser_{Guid.NewGuid()}";
@@ -34,7 +34,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
{
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()
@@ -52,7 +52,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
_hashService = new HashService();
_hashService = new PasswordHashService();
_totpTokenGenerator = new TotpTokenGenerator();
_testUsername = $"testuser_{Guid.NewGuid()}";
@@ -194,7 +194,7 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
UserEntity user = new()
{
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Password = new PasswordHashService().HashString("TestPass123!"),
Libraries = [],
UserPermissions = [],
UserRole = null,
@@ -25,7 +25,7 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, 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<LuminaApiFactory>, 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()}";
}
@@ -26,7 +26,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
[ExcludeFromCodeCoverage]
public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, 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<LuminaApiFactory>, 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()}";
@@ -22,7 +22,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
[ExcludeFromCodeCoverage]
public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, 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<LuminaApiFactory>, 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()}";
}
@@ -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<IUnitOfWork>();
_mockHashService = Substitute.For<IHashService>();
_mockHashService = Substitute.For<IPasswordHashService>();
_mockCryptographyService = Substitute.For<ICryptographyService>();
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
@@ -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<IUnitOfWork>();
_mockHashService = Substitute.For<IHashService>();
_mockHashService = Substitute.For<IPasswordHashService>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
@@ -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<IUnitOfWork>();
_mockHashService = Substitute.For<IHashService>();
_mockHashService = Substitute.For<IPasswordHashService>();
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockCryptographyService = Substitute.For<ICryptographyService>();
_mockUserRepository = Substitute.For<IUserRepository>();
@@ -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<IUnitOfWork>();
_mockHashService = Substitute.For<IHashService>();
_mockHashService = Substitute.For<IPasswordHashService>();
_mockCryptographyService = Substitute.For<ICryptographyService>();
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
@@ -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<IUnitOfWork>();
_mockHashService = Substitute.For<IHashService>();
_mockHashService = Substitute.For<IPasswordHashService>();
_mockJwtTokenGenerator = Substitute.For<IJwtTokenGenerator>();
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockCryptographyService = Substitute.For<ICryptographyService>();
@@ -7,19 +7,19 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Infrastructure.UnitTests.Core.Security;
/// <summary>
/// Contains unit tests for the <see cref="HashService"/> class.
/// Contains unit tests for the <see cref="PasswordHashService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class HashServiceTests
{
private readonly HashService _sut;
private readonly PasswordHashService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="HashServiceTests"/> class.
/// </summary>
public HashServiceTests()
{
_sut = new HashService();
_sut = new PasswordHashService();
}
[Fact]