Skip to content

Commit

Permalink
Avoid multiple concurrent extractions of the same archive
Browse files Browse the repository at this point in the history
  • Loading branch information
SamuelBMartins committed Apr 27, 2024
1 parent 5a7fd25 commit 0d14af0
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions API/Services/CacheService.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
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 +53,8 @@ public class CacheService : ICacheService
private readonly IReadingItemService _readingItemService;
private readonly IBookmarkService _bookmarkService;

private static readonly ConcurrentDictionary<int, SemaphoreSlim> ExtractLocks = new();

public CacheService(ILogger<CacheService> logger, IUnitOfWork unitOfWork,
IDirectoryService directoryService, IReadingItemService readingItemService,
IBookmarkService bookmarkService)
Expand Down Expand Up @@ -166,11 +170,19 @@ 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);
SemaphoreSlim extractLock = ExtractLocks.GetOrAdd(chapterId, id => new SemaphoreSlim(1,1));

await extractLock.WaitAsync();
try {
if(_directoryService.Exists(extractPath)) return chapter;

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

return chapter;
return chapter;
}

/// <summary>
Expand Down

0 comments on commit 0d14af0

Please sign in to comment.