#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Application.Common.Infrastructure.Security;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Hashing;
using System.IO.MemoryMappedFiles;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Security;
///
/// Service for hashing files by sampling chunks from them.
///
internal class FileHashService : IFileHashService
{
private const int SAMPLE_COUNT = 6; // Number of sample points for hash computation.
private const ushort DEFAULT_BUFFER_SIZE = 65535; // Buffer size (64KB - 1) for reading file chunks.
private static readonly ThreadLocal s_threadLocalHasher = new(() => new XxHash64()); // Thread-local hasher to avoid contention and pool management overhead during parallel processing.
private static readonly ulong s_emptyFileHash = ComputeEmptyHash();
///
/// Hashes by sampling chunks from them.
///
/// The collection of files to hash.
/// Whether the files should be read in parallel. Parallel reads benefit solid state drives, while mechanical hard drives are faster with sequential reads.
/// Callback to invoke during processing of elements.
/// Cancellation token that can be used to stop the execution.
/// A collection of the hashed files, along with their hashes.
public async Task> HashFilesAsync(IReadOnlyCollection inputFiles, bool shouldParallelizeReads, Func callback, CancellationToken cancellationToken)
{
List outputFiles = [];
object listLock = new();
// Solid state drives benefit from reading multiple files at once, while mechanical hard drives are faster with sequential reads because of their seek time.
// One logical processor is deliberately left out of the scan, so that the rest of the process, the web server included, keeps a processor available to it.
ParallelOptions parallelOptions = new()
{
CancellationToken = cancellationToken,
MaxDegreeOfParallelism = shouldParallelizeReads ? Math.Max(1, Environment.ProcessorCount - 1) : 1
};
await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) =>
{
cancellationToken.ThrowIfCancellationRequested();
try
{
// Invoke the method that triggers progress reporting.
await callback().ConfigureAwait(false);
ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, file.Size);
// Get the file hash and check if it differs from the one stored on previous scan.
ulong currentHash = file.Size == 0
? s_emptyFileHash // Precomputed constant: XxHash64 hash of zero-length input.
: ComputeFileHash(file.Path, file.Size, bufferSize);
// The decision of whether a file changed is already made before hashing, so all files that reach this point get their hash stored.
lock (listLock)
outputFiles.Add(file with { CurrentHash = currentHash });
}
catch (Exception ex)
{
Debug.WriteLine($"Error processing {file.Path}: {ex.Message}");
}
});
return outputFiles;
}
///
/// Computes the content hash of the file stored at , by sampling chunks from it.
///
/// The path of the file to hash.
/// The content hash of the file.
public ulong ComputeFileHash(string filePath)
{
long fileSize = new FileInfo(filePath).Length;
if (fileSize == 0)
return s_emptyFileHash; // Precomputed constant: XxHash64 hash of zero-length input.
ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, fileSize);
return ComputeFileHash(filePath, fileSize, bufferSize);
}
///
/// Computes content hash using memory-mapped sampling.
///
/// The path of the file to hash.
/// The size of the file, in bytes.
/// Sample window size (automatically clamped to file size).
private static unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize)
{
// 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 the thread-local hasher and reset it before use; resetting at entry (rather than at exit) ensures
// the hasher is always in a clean state even if a previous call on this thread threw mid-computation.
XxHash64 hasher = s_threadLocalHasher.Value!;
hasher.Reset();
// Allocate hash result buffer on the stack, to avoid heap allocation.
Span hashSpan = stackalloc byte[sizeof(ulong)];
// Process only predefined sampled segments of the file, instead of the entire file.
foreach (long offset in GetByteBufferSampleOffsets(fileSize, bufferSize))
{
// Calculate how many bytes to read (handle edge case at end of file, or when the file size is smaller than the buffer).
ushort readSize = (ushort)Math.Min(bufferSize, fileSize - offset);
// Create a span directly over the memory-mapped region.
ReadOnlySpan dataSpan = new(memoryPointer + offset, readSize);
// Update the hash with this chunk of data.
hasher.Append(dataSpan);
}
// Get the final hash value.
if (!hasher.TryGetCurrentHash(hashSpan, out int bytesWritten) || bytesWritten != sizeof(ulong))
throw new InvalidOperationException("Hash computation failed");
// Convert the hash byte span to a long, and return it.
return BitConverter.ToUInt64(hashSpan);
}
finally
{
if (memoryPointer is not null) // Always release the pointer, to prevent memory leaks.
memoryMappedViewAccessor.SafeMemoryMappedViewHandle.ReleasePointer();
}
}
///
/// Generates sample offsets for reading portions of a file.
///
/// The size of the file, in bytes.
/// The buffer size used for reading.
/// An enumerable of byte offsets to sample from the file.
private static IEnumerable GetByteBufferSampleOffsets(long fileSize, ushort bufferSize)
{
// For small files, just read from the beginning.
if (fileSize <= bufferSize * SAMPLE_COUNT)
{
yield return 0;
yield break;
}
// For larger files, sample at strategic points:
yield return 0; // Beginning of the file.
yield return fileSize / 4; // Quarter of the file.
yield return fileSize / 2; // Half 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;
}
///
/// Computes the hash for an empty file, which is a special case, since it has no content to sample.
///
/// The hash value for an empty file.
private static ulong ComputeEmptyHash()
{
XxHash64 hasher = new();
Span hashSpan = stackalloc byte[sizeof(ulong)];
hasher.TryGetCurrentHash(hashSpan, out _);
return BitConverter.ToUInt64(hashSpan);
}
}