feat: Add comprehensive race condition prevention for file operations (#1085)

- Implement MonitoringProtectionService with thread-safe pause/resume logic
- Add monitoring protection to file operations preventing data loss from race conditions
- Add comprehensive test coverage including concurrent and integration tests

Race condition scenario: File operations (move/delete) detected as "missing files"
by monitoring system before filesystem operations complete, causing incorrect
book removal and data loss.

Solution: Thread-safe monitoring pause during file operations with delayed resume
to ensure filesystem operations complete before monitoring resumes.
This commit is contained in:
Paul
2025-09-05 23:11:20 -06:00
committed by GitHub
parent 7604fa7fa0
commit c8e78d3bc8
12 changed files with 1398 additions and 198 deletions
@@ -8,7 +8,7 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -41,6 +41,7 @@ public class AdditionalFileService {
private final BookAdditionalFileRepository additionalFileRepository;
private final AdditionalFileMapper additionalFileMapper;
private final MonitoringProtectionService monitoringProtectionService;
public List<AdditionalFile> getAdditionalFilesByBookId(Long bookId) {
List<BookAdditionalFileEntity> entities = additionalFileRepository.findByBookId(bookId);
@@ -60,16 +61,21 @@ public class AdditionalFileService {
}
BookAdditionalFileEntity file = fileOpt.get();
monitoringProtectionService.executeWithProtection(() -> {
try {
// Delete physical file
Files.deleteIfExists(file.getFullFilePath());
log.info("Deleted additional file: {}", file.getFullFilePath());
// Delete physical file
try {
Files.deleteIfExists(file.getFullFilePath());
} catch (IOException e) {
log.warn("Failed to delete physical file: {}", file.getFullFilePath(), e);
}
// Delete database record
additionalFileRepository.delete(file);
// Delete database record
additionalFileRepository.delete(file);
} catch (IOException e) {
log.warn("Failed to delete physical file: {}", file.getFullFilePath(), e);
// Still delete the database record even if file deletion fails
additionalFileRepository.delete(file);
}
}, "additional file deletion");
}
public ResponseEntity<Resource> downloadAdditionalFile(Long fileId) throws IOException {
@@ -92,4 +98,5 @@ public class AdditionalFileService {
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
.body(resource);
}
}
@@ -15,6 +15,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
@@ -58,6 +59,7 @@ public class BookService {
private final BookQueryService bookQueryService;
private final UserProgressService userProgressService;
private final BookDownloadService bookDownloadService;
private final MonitoringProtectionService monitoringProtectionService;
private void setBookProgress(Book book, UserBookProgressEntity progress) {
@@ -493,29 +495,34 @@ public class BookService {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
List<Long> failedFileDeletions = new ArrayList<>();
for (BookEntity book : books) {
Path fullFilePath = book.getFullFilePath();
try {
if (Files.exists(fullFilePath)) {
Files.delete(fullFilePath);
Set<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
.map(Paths::get)
.map(Path::normalize)
.collect(Collectors.toSet());
return monitoringProtectionService.executeWithProtection(() -> {
for (BookEntity book : books) {
Path fullFilePath = book.getFullFilePath();
try {
if (Files.exists(fullFilePath)) {
Files.delete(fullFilePath);
log.info("Deleted book file: {}", fullFilePath);
Set<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
.map(Paths::get)
.map(Path::normalize)
.collect(Collectors.toSet());
deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots);
deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots);
}
} catch (IOException e) {
log.warn("Failed to delete book file: {}", fullFilePath, e);
failedFileDeletions.add(book.getId());
}
} catch (IOException e) {
failedFileDeletions.add(book.getId());
}
}
bookRepository.deleteAll(books);
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
return failedFileDeletions.isEmpty()
? ResponseEntity.ok(response)
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
bookRepository.deleteAll(books);
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
return failedFileDeletions.isEmpty()
? ResponseEntity.ok(response)
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
}, "book deletion");
}
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
@@ -582,4 +589,5 @@ public class BookService {
}
}
}
}
@@ -26,7 +26,7 @@ import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.util.PathPatternResolver;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -62,7 +62,7 @@ public class BookDropService {
private final BookdropFileRepository bookdropFileRepository;
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final MonitoringService monitoringService;
private final MonitoringProtectionService monitoringProtectionService;
private final BookdropMonitoringService bookdropMonitoringService;
private final NotificationService notificationService;
private final MetadataRefreshService metadataRefreshService;
@@ -88,112 +88,103 @@ public class BookDropService {
}
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
boolean monitoringWasActive = !monitoringService.isPaused();
if (monitoringWasActive) monitoringService.pauseMonitoring();
bookdropMonitoringService.pauseMonitoring();
return monitoringProtectionService.executeWithProtection(() -> {
try {
bookdropMonitoringService.pauseMonitoring();
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
.processedAt(Instant.now())
.build();
Long defaultLibraryId = request.getDefaultLibraryId();
Long defaultPathId = request.getDefaultPathId();
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
.processedAt(Instant.now())
.build();
Long defaultLibraryId = request.getDefaultLibraryId();
Long defaultPathId = request.getDefaultPathId();
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.collect(Collectors.toMap(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId, Function.identity()));
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.collect(Collectors.toMap(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId, Function.identity()));
final int CHUNK_SIZE = 100;
AtomicInteger failedCount = new AtomicInteger();
AtomicInteger totalFilesProcessed = new AtomicInteger();
final int CHUNK_SIZE = 100;
AtomicInteger failedCount = new AtomicInteger();
AtomicInteger totalFilesProcessed = new AtomicInteger();
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}",
request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}",
request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
if (Boolean.TRUE.equals(request.getSelectAll())) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
if (Boolean.TRUE.equals(request.getSelectAll())) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
for (int i = 0; i < allIds.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, allIds.size());
List<Long> chunk = allIds.subList(i, end);
for (int i = 0; i < allIds.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, allIds.size());
List<Long> chunk = allIds.subList(i, end);
log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) allIds.size() / CHUNK_SIZE), chunk.size(), chunk);
log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) allIds.size() / CHUNK_SIZE), chunk.size(), chunk);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunk) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
for (Long id : chunk) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
} else {
List<Long> ids = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.map(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId)
.toList();
} else {
List<Long> ids = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.map(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId)
.toList();
log.info("Processing {} manually selected files in chunks of {}. File IDs: {}", ids.size(), CHUNK_SIZE, ids);
log.info("Processing {} manually selected files in chunks of {}. File IDs: {}", ids.size(), CHUNK_SIZE, ids);
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, ids.size());
List<Long> chunkIds = ids.subList(i, end);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunkIds);
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, ids.size());
List<Long> chunkIds = ids.subList(i, end);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunkIds);
log.info("Processing chunk {} of {} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunkFiles.size(), chunkIds);
log.info("Processing chunk {} of {} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunkFiles.size(), chunkIds);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream()
.collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream()
.collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunkIds) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.error("File ID {} not found in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
for (Long id : chunkIds) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.error("File ID {} not found in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
results.setTotalFiles(totalFilesProcessed.get());
results.setFailed(failedCount.get());
results.setSuccessfullyImported(totalFilesProcessed.get() - failedCount.get());
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
results.getSuccessfullyImported(),
results.getFailed(),
results.getTotalFiles());
return results;
} finally {
bookdropMonitoringService.resumeMonitoring();
}
}
results.setTotalFiles(totalFilesProcessed.get());
results.setFailed(failedCount.get());
results.setSuccessfullyImported(totalFilesProcessed.get() - failedCount.get());
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
results.getSuccessfullyImported(),
results.getFailed(),
results.getTotalFiles());
if (monitoringWasActive) {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5000);
monitoringService.resumeMonitoring();
bookdropMonitoringService.resumeMonitoring();
log.info("Monitoring resumed after 5s delay following finalizeImport");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring after finalizeImport");
}
});
}
return results;
}, "bookdrop finalize import");
}
private void processFile(
@@ -285,51 +276,53 @@ public class BookDropService {
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
}
try {
Files.createDirectories(target.getParent());
Files.move(source, target);
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
BookFileExtension.fromFileName(bookdropFile.getFileName())
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
.getType());
BookEntity bookEntity = bookRepository.findById(processedBook.getId())
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
notificationService.sendMessage(Topic.BOOK_ADD, processedBook);
metadataRefreshService.updateBookMetadata(bookEntity, metadata, metadata.getThumbnailUrl() != null, false);
bookdropFileRepository.deleteById(bookdropFile.getId());
bookdropNotificationService.sendBookdropFileSummaryNotification();
File cachedCover = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg").toFile();
if (cachedCover.exists()) {
boolean deleted = cachedCover.delete();
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
}
log.info("File import completed: id={}, name={}, library={}, path={}", bookdropFile.getId(), targetFile.getName(), library.getName(), path.getPath());
return BookdropFileResult.builder()
.fileName(targetFile.getName())
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
.success(true)
.build();
} catch (Exception e) {
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
return monitoringProtectionService.executeWithProtection(() -> {
try {
if (Files.exists(target)) {
Files.deleteIfExists(target);
log.info("Cleaned up partially created target file: {}", target);
Files.createDirectories(target.getParent());
Files.move(source, target);
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
BookFileExtension.fromFileName(bookdropFile.getFileName())
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
.getType());
BookEntity bookEntity = bookRepository.findById(processedBook.getId())
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
notificationService.sendMessage(Topic.BOOK_ADD, processedBook);
metadataRefreshService.updateBookMetadata(bookEntity, metadata, metadata.getThumbnailUrl() != null, false);
bookdropFileRepository.deleteById(bookdropFile.getId());
bookdropNotificationService.sendBookdropFileSummaryNotification();
File cachedCover = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg").toFile();
if (cachedCover.exists()) {
boolean deleted = cachedCover.delete();
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
}
} catch (Exception cleanupException) {
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
log.info("File import completed: id={}, name={}, library={}, path={}", bookdropFile.getId(), targetFile.getName(), library.getName(), path.getPath());
return BookdropFileResult.builder()
.fileName(targetFile.getName())
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
.success(true)
.build();
} catch (Exception e) {
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
try {
if (Files.exists(target)) {
Files.deleteIfExists(target);
log.info("Cleaned up partially created target file: {}", target);
}
} catch (Exception cleanupException) {
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
}
return failureResult(bookdropFile.getFileName(), "Failed to move file: " + e.getMessage());
}
return failureResult(bookdropFile.getFileName(), "Failed to move file: " + e.getMessage());
}
}, "bookdrop file move");
}
private BookdropFileResult failureResult(String fileName, String message) {
@@ -435,4 +428,5 @@ public class BookDropService {
return null;
}
}
}
@@ -15,7 +15,7 @@ import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.library.LibraryService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -37,7 +37,7 @@ public class FileMoveService {
private final BookMapper bookMapper;
private final NotificationService notificationService;
private final LibraryService libraryService;
private final MonitoringService monitoringService;
private final MonitoringProtectionService monitoringProtectionService;
private final AppSettingService appSettingService;
public void moveFiles(FileMoveRequest request) {
@@ -49,29 +49,22 @@ public class FileMoveService {
Set<Long> libraryIds = new HashSet<>();
List<Book> updatedBooks = new ArrayList<>();
boolean didPause = pauseMonitoringIfNeeded();
try {
monitoringProtectionService.executeWithProtection(() -> {
for (BookEntity book : books) {
processBookMove(book, defaultPattern, updatedBooks, libraryIds);
}
log.info("Completed file move for {} books.", books.size());
sendUpdateNotifications(updatedBooks);
}, "file move operations");
// Trigger library rescan immediately after file operations complete
if (!libraryIds.isEmpty()) {
rescanLibraries(libraryIds);
} finally {
resumeMonitoringWithDelay(didPause);
}
}
private boolean pauseMonitoringIfNeeded() {
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
return true;
}
return false;
}
private void processBookMove(BookEntity book, String defaultPattern, List<Book> updatedBooks, Set<Long> libraryIds) {
if (book.getMetadata() == null) return;
@@ -195,22 +188,7 @@ public class FileMoveService {
}
}
private void resumeMonitoringWithDelay(boolean didPause) {
if (didPause && !monitoringService.isPaused()) {
log.info("Monitoring already resumed by another thread.");
} else if (didPause) {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5_000);
monitoringService.resumeMonitoring();
log.info("Monitoring resumed after 5s delay");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring");
}
});
}
}
public String generatePathFromPattern(BookEntity book, String pattern) {
return PathPatternResolver.resolvePattern(book, pattern);
@@ -0,0 +1,124 @@
package com.adityachandel.booklore.service.monitoring;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.function.Supplier;
/**
* Thread-safe service for managing monitoring protection during file operations.
*
* This service prevents race conditions where file operations are detected as
* "missing files" by the monitoring system, which could lead to data loss.
*
* The service ensures:
* - Thread-safe pause/resume operations
* - Monitoring always resumes even on exceptions
* - Protection against concurrent operations interfering with each other
*/
@Slf4j
@Service
@AllArgsConstructor
public class MonitoringProtectionService {
private final MonitoringService monitoringService;
// Synchronization lock to prevent race conditions in pause/resume logic
private static final Object monitoringLock = new Object();
/**
* Executes an operation with monitoring protection.
*
* @param operation The operation to execute while monitoring is paused
* @param operationName Name for logging purposes
* @param <T> Return type of the operation
* @return Result of the operation
*/
public <T> T executeWithProtection(Supplier<T> operation, String operationName) {
boolean didPause = pauseMonitoringSafely();
try {
log.debug("Executing {} with monitoring protection (paused: {})", operationName, didPause);
return operation.get();
} finally {
resumeMonitoringSafely(didPause, operationName);
}
}
/**
* Executes a void operation with monitoring protection.
*
* @param operation The operation to execute while monitoring is paused
* @param operationName Name for logging purposes
*/
public void executeWithProtection(Runnable operation, String operationName) {
executeWithProtection(() -> {
operation.run();
return null;
}, operationName);
}
/**
* Thread-safe pause of monitoring service.
*
* @return true if monitoring was paused by this call, false if already paused
*/
private boolean pauseMonitoringSafely() {
synchronized (monitoringLock) {
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
log.debug("Monitoring paused for file operations");
return true;
}
log.debug("Monitoring already paused by another operation");
return false;
}
}
/**
* Thread-safe resume of monitoring service with a 5-second delay.
* The delay is critical to prevent race conditions where file operations
* are still settling when monitoring resumes.
*
* @param didPause true if this operation paused monitoring
* @param operationName name of the operation for logging
*/
private void resumeMonitoringSafely(boolean didPause, String operationName) {
if (!didPause) {
log.debug("Monitoring was not paused by {} - no resume needed", operationName);
return;
}
// Use virtual thread for delayed resume to avoid blocking
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5_000); // Critical 5-second delay for filesystem operations to settle
synchronized (monitoringLock) {
// Double-check that monitoring is still paused before resuming
if (monitoringService.isPaused()) {
monitoringService.resumeMonitoring();
log.debug("Monitoring resumed after {} completed with 5s delay", operationName);
} else {
log.warn("Monitoring was already resumed by another thread during {}", operationName);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring after {}", operationName);
}
});
}
/**
* Checks if monitoring is currently paused.
*
* @return true if monitoring is paused
*/
public boolean isMonitoringPaused() {
synchronized (monitoringLock) {
return monitoringService.isPaused();
}
}
}