Skip to content

Commit

Permalink
Avoid multiple concurrent extractions of the same archive (#2840)
Browse files Browse the repository at this point in the history
  • Loading branch information
SamuelBMartins committed Apr 25, 2024
1 parent 8894b2e commit a4fca35
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions API/Services/CacheService.cs
Expand Up @@ -3,6 +3,7 @@
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using API.Data;
using API.DTOs.Reader;
Expand Down Expand Up @@ -51,6 +52,8 @@ public class CacheService : ICacheService
private readonly IReadingItemService _readingItemService;
private readonly IBookmarkService _bookmarkService;

private static readonly SemaphoreSlim ExtractSemaphore = new SemaphoreSlim(1, 1);

public CacheService(ILogger<CacheService> logger, IUnitOfWork unitOfWork,
IDirectoryService directoryService, IReadingItemService readingItemService,
IBookmarkService bookmarkService)
Expand Down Expand Up @@ -166,9 +169,18 @@ public string GetCachedFile(Chapter chapter)
var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId);
var extractPath = GetCachePath(chapterId);

if (_directoryService.Exists(extractPath)) return chapter;
var files = chapter?.Files.ToList();
ExtractChapterFiles(extractPath, files, extractPdfToImages);
await ExtractSemaphore.WaitAsync();
try
{
if (_directoryService.Exists(extractPath)) return chapter;

var files = chapter?.Files.ToList();
ExtractChapterFiles(extractPath, files, extractPdfToImages);
}
finally
{
ExtractSemaphore.Release();
}

return chapter;
}
Expand Down

0 comments on commit a4fca35

Please sign in to comment.