1 Commits

Author SHA1 Message Date
ecenshu dd53bc547f When a file is locked during hash calculation, if retries fails then do not throw exception out but rather return null hash
ci / build_linux (push) Has been cancelled
ci / build_linux (pull_request) Has been cancelled
2025-12-13 10:38:43 +10:30
2 changed files with 58 additions and 87 deletions
+8 -27
View File
@@ -17,11 +17,12 @@ namespace TinfoilVibeServer.Services
/// <summary>
/// Reads a ROM archive (zip / 7z / rar) from a stream.
/// </summary>
public sealed class RomArchiveReader : IDisposable, IAsyncDisposable
public sealed class RomArchiveReader : IDisposable
{
private readonly ZipArchive? _zipArchive;
private readonly IArchive? _archive;
private readonly Stream? _archiveStream; // the stream actually handed to SharpCompress
private readonly ICollection<Stream>? _partStreams;
public RomArchiveReader(string path)
{
@@ -54,16 +55,8 @@ namespace TinfoilVibeServer.Services
stream.CopyTo(ms);
ms.Position = 0;
_archiveStream = ms;
if (stream is IAsyncDisposable asyncDisposable)
{
var disposeAsync = asyncDisposable.DisposeAsync();
disposeAsync.ConfigureAwait(false);
}
else
{
stream.Dispose(); // original nonseekable stream no longer needed
}
}
else
{
_archiveStream = stream;
@@ -80,29 +73,28 @@ namespace TinfoilVibeServer.Services
// Detect whether the file is a multipart RAR and wrap it if necessary
private static IArchive DetectAndWrap(string path)
{
var ext = Path.GetExtension(path).ToLowerInvariant();
string ext = Path.GetExtension(path).ToLowerInvariant();
if (ext is ".rar" or ".r00" or ".r01" or ".r02")
if (ext == ".rar" || ext == ".r00" || ext == ".r01" || ext == ".r02")
{
var dir = Path.GetDirectoryName(path)!;
var fileName = Path.GetFileName(path);
// ----- 1️⃣ Determine the base name (everything before the first ".rar" or ".partNN") -----
var baseName = MultiPartRarHelper.GetBaseNameForRarVolume(fileName);
string baseName = MultiPartRarHelper.GetBaseNameForRarVolume(fileName);
// Any file that ends with .rar or .rNN could be the start of a multipart set
// Let MultiPartRarStream decide which parts belong together.
var volumes = MultiPartRarHelper.DiscoverVolumes(dir, baseName);
if (volumes.Count is 0 or 1)
{
return ArchiveFactory.Open(path, new ReaderOptions { LeaveStreamOpen = false });
return ArchiveFactory.Open(path);
}
var streams = new List<Stream>(volumes.Count);
foreach (var volume in volumes)
{
// todo: check all streams for read validity? The rar may be available but the parts are not all downloaded yet
streams.Add(new FileStream(volume, FileMode.Open, FileAccess.Read, FileShare.Read, 10*1024*1024, FileOptions.Asynchronous));
streams.Add(new FileStream(volume, FileMode.Open, FileAccess.Read, FileShare.Read));
}
return ArchiveFactory.Open(streams, new ReaderOptions { LeaveStreamOpen = false });
@@ -110,7 +102,7 @@ namespace TinfoilVibeServer.Services
// Normal singlefile archive (zip, 7z, singlerar, etc.)
using var archiveStream = File.OpenRead(path);
return ArchiveFactory.Open(archiveStream, new ReaderOptions { LeaveStreamOpen = false });
return ArchiveFactory.Open(archiveStream);
}
private static Stream? GetPart(int arg)
@@ -172,20 +164,9 @@ namespace TinfoilVibeServer.Services
/// Disposes the underlying archive objects and the stream(s).
/// </summary>
public void Dispose()
{
DisposeAsync().GetAwaiter().GetResult();
}
public async ValueTask DisposeAsync()
{
_zipArchive?.Dispose();
_archive?.Dispose();
// Dispose of the underlying stream (may support async)
if (_archiveStream is IAsyncDisposable asyncStream)
await asyncStream.DisposeAsync().ConfigureAwait(false);
else
// ReSharper disable once MethodHasAsyncOverload
_archiveStream?.Dispose();
}
+34 -44
View File
@@ -24,7 +24,7 @@ public interface ISnapshotService
Task RebuildSnapshotAsync(CancellationToken cancellationToken = default);
SnapshotService.ROMSnapshot GetSnapshot();
Task AddToSnapshotAsync(FileEntry entry, CancellationToken cancellationToken = default);
Task AddToSnapshotAsync(FileEntry entry);
Task BuildSnapshotAsync(CancellationToken cancellationToken = default);
void GetArchiveName(string titleId);
char GetArchivePathSeparator();
@@ -308,18 +308,17 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
#region Snapshot logic
public async Task AddToSnapshotAsync(FileEntry entry, CancellationToken cancellationToken = default)
public Task AddToSnapshotAsync(FileEntry entry)
{
// Update lookup tables
if (entry.Hash == null)
{
_logger.LogWarning("Cannot add entry {Path} to snapshot: no hash", entry.Path);
return;
return Task.CompletedTask;
}
var lastModified = File.GetLastWriteTimeUtc(entry.Path.Contains(ArchivePathSeparator) ? entry.Path.Split(ArchivePathSeparator)[0] : entry.Path);
var cacheUpdated = _cache.ContainsKey(entry.Path);
_cache[entry.Path] = new SnapshotEntry(entry.Path, entry.Hash, entry.Size, lastModified, entry.Titles);
_hashCache[entry.Hash] = entry.Path;
_sizeLookup[entry.Hash] = entry.Size;
@@ -340,14 +339,12 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
_hashCache[ncaMetadataWithHash.Hash] = entry.Path;
_sizeLookup[ncaMetadataWithHash.Hash] = entry.Size;
//_logger.LogInformation("Added entry {titleId} to snapshot (hash={hash})", ncaMetadataWithHash.TitleId, ncaMetadataWithHash.Hash);
}
// Persist snapshot to disk
// If entry.Titles is null, treat it as an empty collection
var titleIds = string.Join(",", entry.Titles.Select(t => t.TitleId.ToString()));
_logger.LogInformation(cacheUpdated ? "Updated snapshot for {Path}, titleIds=[{TitleIds}]" : "Added {Path} to snapshot, titleIds=[{TitleIds}]", entry.Path, titleIds);
await PersistSnapshotAsync(cancellationToken);
PersistSnapshotAsync();
return Task.CompletedTask;
}
/* ==============================================================
@@ -408,7 +405,7 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
}
}
//var currentHash = ComputeSnapshotHash(entries);
var currentHash = ComputeSnapshotHash(entries);
if (entries.Count > 0 || fileInfo.Exists && index.Count == 0)
SnapshotRebuilt?.Invoke(this, EventArgs.Empty);
}
@@ -455,8 +452,7 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
{
//var titleInfo = _titleDatabaseService.GetAsync(ncaMetadataWithHash.TitleId).Result;
var fileEntryFromFileName = new FileEntry(file, fileInfo.Length, ncaMetadataWithHash.Hash, [ncaMetadataWithHash]);
var addToSnapshotAsync = AddToSnapshotAsync(fileEntryFromFileName, cancellationToken);
addToSnapshotAsync.Wait(cancellationToken);
AddToSnapshotAsync(fileEntryFromFileName);
cancellationToken.ThrowIfCancellationRequested();
yield return fileEntryFromFileName;
continue;
@@ -476,8 +472,7 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
if (title != null)
{
var romEntry = new FileEntry(file, nspStreamLength, hash, [title]);
var addToSnapshotAsync = AddToSnapshotAsync(romEntry, cancellationToken);
addToSnapshotAsync.Wait(cancellationToken);
AddToSnapshotAsync(romEntry);
titles.Add((title.TitleId, nspStreamLength, title));
cancellationToken.ThrowIfCancellationRequested();
yield return romEntry;
@@ -491,7 +486,7 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
if (_archiveLookup.ContainsKey(file)) continue;
if (processedFiles.Contains(file)) continue;
_logger.LogDebug("Extracting hash for {File}", file);
var stopwatch = Stopwatch.StartNew();
Stopwatch stopwatch = Stopwatch.StartNew();
hash = ComputeFirstStreamHashAsync(file, cancellationToken).Result;
stopwatch.Stop();
if (!string.IsNullOrEmpty(hash))
@@ -532,8 +527,7 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
foreach (var title in titles)
{
var archiveEntry = new FileEntry(file + ArchivePathSeparator + title.Item1, title.Item2, title.Item3.Hash, [title.Item3]);
var addToSnapshotAsync = AddToSnapshotAsync(archiveEntry, cancellationToken);
addToSnapshotAsync.Wait(cancellationToken);
AddToSnapshotAsync(archiveEntry);
cancellationToken.ThrowIfCancellationRequested();
yield return archiveEntry;
}
@@ -571,14 +565,10 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
catch (IOException ex) when (attempt < _options.MaxRetryCount - 1)
{
var delay = (int)((attempt+1) * _options.DebounceTimeoutMs * _options.RetryMultiplier);
_logger.LogWarning(ex, "Failed to load {Path}. Attempt {Attempt}, Retrying after {Delay}.",
file, attempt + 1, delay);
_logger.LogWarning(ex, "Attempt {Attempt} failed for {Path}. Retrying after {Delay}.",
attempt + 1, file, delay);
await Task.Delay(delay, cancellationToken);
}
catch (IOException) when (attempt >= _options.MaxRetryCount - 1)
{
_logger.LogWarning("Load {Path} failed after {retries} attempts", file, attempt + 1);
}
}
return null;
}
@@ -598,8 +588,6 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
private Task PersistSnapshotAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
if (_debouncerCache.TryGetValue(_jsonPath, out _))
{
_logger.LogDebug("Sliding debounce in progress, skipping snapshot persistence");
@@ -627,8 +615,8 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
if (reason is not (EvictionReason.Expired or EvictionReason.TokenExpired))
return;
var filePath = (string)key;
if (!_snapshotFileSemaphore.Wait(SnapshotFileLockTimeout)) return;
if (_snapshotFileSemaphore.Wait(SnapshotFileLockTimeout))
{
try
{
if (FileLockHelper.IsFileLocked(filePath))
@@ -649,6 +637,7 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
}
}
}
}
});
cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(DebounceMs));
return Task.CompletedTask;
@@ -857,59 +846,60 @@ public sealed class SnapshotService : IDisposable, ISnapshotService, IHostedServ
{
try
{
var ext = Path.GetExtension(filePath).ToLowerInvariant();
var multiPartBasePathWithExtension = $"{MultiPartRarHelper.GetBaseNameForRarVolume(filePath)}{ext}";
if (string.CompareOrdinal(multiPartBasePathWithExtension, filePath) != 0)
{
filePath = multiPartBasePathWithExtension;
}
if (FileLockHelper.IsFileLocked(filePath))
{
throw new IOException("File is locked");
}
// Only treat NSP/XCI/XCZ as “firststream” files
var ext = Path.GetExtension(filePath).ToLowerInvariant();
if (ext is not ".nsp" and not ".xci" and not ".xcz")
{
// Open the NSP/XCI with LibHac and read the first stream.
// The first stream is the first entry returned by GetContentInfos().
try
{
await using var reader = new RomArchiveReader(filePath);
using var reader = new RomArchiveReader(filePath);
var first = reader.GetEntries().FirstOrDefault();
if (first == null) return ComputeFullHash(filePath);
//using var seekableWrapper = new SeekableBufferedStream(first.Stream, first.Stream.Length, 10*1024*1024, true);
await using var rewindableWrapper = new RewindableStream(first.Stream, () => first.Stream, 10 * 1024 * 1024, first.Stream.Length);
await using var rewindableWrapper = new RewindableStream(first.Stream, () => { return reader.GetEntries().FirstOrDefault().Stream; }, 10 * 1024 * 1024, first.Stream.Length);
var hash = _nspExtractor.ExtractHashFromStream(rewindableWrapper);
return hash;
}
catch
{
// ignored
}
}
// On error, fall back to the full file hash
await using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var ncaMetadataWithHash = _nspExtractor.ExtractFromStream(fs);
return ncaMetadataWithHash?.Hash ?? string.Empty;
}
}
else
{
await using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var ncaMetadataWithHash = _nspExtractor.ExtractFromStream(fs);
return ncaMetadataWithHash?.Hash ?? string.Empty;
}
}
catch (IOException ex) when (attempt < _options.MaxRetryCount - 1)
{
var delay = (int)((attempt + 1) * _options.DebounceTimeoutMs * _options.RetryMultiplier);
_logger.LogWarning(ex, "Failed to load {Path}. Attempt {Attempt}, Retrying after {Delay}.",
filePath, attempt + 1, delay);
_logger.LogWarning(ex, "Attempt {Attempt} failed for {Path}. Retrying after {Delay}.",
attempt + 1, filePath, delay);
await Task.Delay(delay, cancellationToken);
}
catch (IOException) when (attempt >= _options.MaxRetryCount - 1)
catch (IOException)
{
_logger.LogWarning("Load {Path} failed after {retries} attempts", filePath, attempt + 1);
_logger.LogWarning("Attempt to load {Path} failed after {retries}", filePath, attempt + 1);
return null;
}
}
return string.Empty;
throw new IOException($"Failed to compute hash for {filePath} after {_options.MaxRetryCount} attempts");
}
private static string ComputeFullHash(string filePath)