refactor(threads): replace manual thread management with Spring lifecycle (#322)
* refactor(threads): replace manual thread management with Spring lifecycle - Convert LibraryWatchService, LibraryFileEventProcessor, BookdropMonitoringService, BookdropEventHandlerService to SmartLifecycle for proper startup/shutdown ordering - Replace Executors.newCachedThreadPool() in FilenamePatternExtractor with Spring-managed ExecutorService bean - Delete SecurityContextVirtualThread utility class - Add DelegatingSecurityContextRunnable task decorator to TaskExecutorConfig for automatic security context propagation - Replace SecurityContextVirtualThread.runWithSecurityContext() calls in TaskService, BookCoverService, SendEmailV2Service, LibraryService with injected Executor - Fix CbxReaderService pre-existing compile error (transferEntryTo) * refactor(threads): improve thread management with ThreadPoolTaskExecutor and improve shutdown handling * fix: fix broken test
This commit is contained in:
@@ -5,6 +5,7 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
|
|
||||||
import java.net.http.HttpClient;
|
import java.net.http.HttpClient;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@@ -19,4 +20,9 @@ public class HttpClientConfig {
|
|||||||
.executor(Executors.newVirtualThreadPerTaskExecutor())
|
.executor(Executors.newVirtualThreadPerTaskExecutor())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ExecutorService regexExecutor() {
|
||||||
|
return Executors.newVirtualThreadPerTaskExecutor();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,16 +3,27 @@ package org.booklore.config;
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.core.task.AsyncTaskExecutor;
|
import org.springframework.core.task.AsyncTaskExecutor;
|
||||||
import org.springframework.core.task.VirtualThreadTaskExecutor;
|
import org.springframework.core.task.SimpleAsyncTaskExecutor;
|
||||||
import org.springframework.scheduling.TaskScheduler;
|
import org.springframework.scheduling.TaskScheduler;
|
||||||
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;
|
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;
|
||||||
|
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
||||||
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class TaskExecutorConfig {
|
public class TaskExecutorConfig {
|
||||||
|
|
||||||
@Bean(name = "taskExecutor")
|
@Bean(name = "taskExecutor")
|
||||||
public AsyncTaskExecutor taskExecutor() {
|
public AsyncTaskExecutor taskExecutor() {
|
||||||
return new VirtualThreadTaskExecutor("async-");
|
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||||
|
executor.setThreadNamePrefix("async-");
|
||||||
|
executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
|
||||||
|
executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
|
||||||
|
executor.setQueueCapacity(500);
|
||||||
|
executor.setTaskDecorator(DelegatingSecurityContextRunnable::new);
|
||||||
|
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||||
|
executor.setAwaitTerminationSeconds(60);
|
||||||
|
executor.initialize();
|
||||||
|
return executor;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
+47
-9
@@ -9,10 +9,9 @@ import org.booklore.model.websocket.Topic;
|
|||||||
import org.booklore.repository.BookdropFileRepository;
|
import org.booklore.repository.BookdropFileRepository;
|
||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
import org.booklore.service.appsettings.AppSettingService;
|
import org.booklore.service.appsettings.AppSettingService;
|
||||||
import jakarta.annotation.PostConstruct;
|
|
||||||
import jakarta.annotation.PreDestroy;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.context.SmartLifecycle;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -27,8 +26,9 @@ import java.util.concurrent.LinkedBlockingQueue;
|
|||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
public class BookdropEventHandlerService implements SmartLifecycle {
|
||||||
public class BookdropEventHandlerService {
|
|
||||||
|
private static final int LIFECYCLE_PHASE = 10;
|
||||||
|
|
||||||
private final BookdropFileRepository bookdropFileRepository;
|
private final BookdropFileRepository bookdropFileRepository;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
@@ -41,21 +41,59 @@ public class BookdropEventHandlerService {
|
|||||||
private static final long STABILITY_MAX_WAIT_MS = 30_000;
|
private static final long STABILITY_MAX_WAIT_MS = 30_000;
|
||||||
|
|
||||||
private final BlockingQueue<BookDropFileEvent> fileQueue = new LinkedBlockingQueue<>();
|
private final BlockingQueue<BookDropFileEvent> fileQueue = new LinkedBlockingQueue<>();
|
||||||
private volatile boolean running = true;
|
private volatile boolean running;
|
||||||
private Thread workerThread;
|
private Thread workerThread;
|
||||||
|
|
||||||
@PostConstruct
|
public BookdropEventHandlerService(
|
||||||
public void init() {
|
BookdropFileRepository bookdropFileRepository,
|
||||||
|
NotificationService notificationService,
|
||||||
|
BookdropNotificationService bookdropNotificationService,
|
||||||
|
AppSettingService appSettingService,
|
||||||
|
BookdropMetadataService bookdropMetadataService) {
|
||||||
|
this.bookdropFileRepository = bookdropFileRepository;
|
||||||
|
this.notificationService = notificationService;
|
||||||
|
this.bookdropNotificationService = bookdropNotificationService;
|
||||||
|
this.appSettingService = appSettingService;
|
||||||
|
this.bookdropMetadataService = bookdropMetadataService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void start() {
|
||||||
|
running = true;
|
||||||
workerThread = new Thread(this::processQueue, "BookdropFileProcessor");
|
workerThread = new Thread(this::processQueue, "BookdropFileProcessor");
|
||||||
workerThread.start();
|
workerThread.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreDestroy
|
@Override
|
||||||
public void shutdown() {
|
public void stop() {
|
||||||
|
stop(() -> {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stop(Runnable callback) {
|
||||||
|
log.info("Stopping BookdropEventHandlerService...");
|
||||||
running = false;
|
running = false;
|
||||||
if (workerThread != null) {
|
if (workerThread != null) {
|
||||||
workerThread.interrupt();
|
workerThread.interrupt();
|
||||||
|
try {
|
||||||
|
workerThread.join(5000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.warn("Interrupted while waiting for BookdropEventHandlerService workerThread to stop");
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
log.info("Stopped BookdropEventHandlerService");
|
||||||
|
callback.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isRunning() {
|
||||||
|
return running;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getPhase() {
|
||||||
|
return LIFECYCLE_PHASE;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void enqueueFile(Path file, WatchEvent.Kind<?> kind) {
|
public void enqueueFile(Path file, WatchEvent.Kind<?> kind) {
|
||||||
|
|||||||
+30
-5
@@ -4,9 +4,8 @@ import org.booklore.config.AppProperties;
|
|||||||
import org.booklore.model.enums.BookFileExtension;
|
import org.booklore.model.enums.BookFileExtension;
|
||||||
import org.booklore.repository.BookdropFileRepository;
|
import org.booklore.repository.BookdropFileRepository;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import jakarta.annotation.PostConstruct;
|
|
||||||
import jakarta.annotation.PreDestroy;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.context.SmartLifecycle;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -20,7 +19,9 @@ import java.util.stream.Stream;
|
|||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
public class BookdropMonitoringService {
|
public class BookdropMonitoringService implements SmartLifecycle {
|
||||||
|
|
||||||
|
private static final int LIFECYCLE_PHASE = 20;
|
||||||
|
|
||||||
private final AppProperties appProperties;
|
private final AppProperties appProperties;
|
||||||
private final BookdropEventHandlerService eventHandler;
|
private final BookdropEventHandlerService eventHandler;
|
||||||
@@ -45,7 +46,7 @@ public class BookdropMonitoringService {
|
|||||||
this.bookdropFileRepository = bookdropFileRepository;
|
this.bookdropFileRepository = bookdropFileRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostConstruct
|
@Override
|
||||||
public void start() {
|
public void start() {
|
||||||
bookdrop = Path.of(appProperties.getBookdropFolder());
|
bookdrop = Path.of(appProperties.getBookdropFolder());
|
||||||
if (Files.notExists(bookdrop)) {
|
if (Files.notExists(bookdrop)) {
|
||||||
@@ -72,17 +73,30 @@ public class BookdropMonitoringService {
|
|||||||
this.watchThread.setDaemon(true);
|
this.watchThread.setDaemon(true);
|
||||||
this.watchThread.start();
|
this.watchThread.start();
|
||||||
scanExistingBookdropFiles();
|
scanExistingBookdropFiles();
|
||||||
|
this.disabled = false;
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.warn("Failed to start bookdrop folder monitor. Bookdrop monitoring is disabled.", e);
|
log.warn("Failed to start bookdrop folder monitor. Bookdrop monitoring is disabled.", e);
|
||||||
this.disabled = true;
|
this.disabled = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreDestroy
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
|
stop(() -> {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stop(Runnable callback) {
|
||||||
|
log.info("Stopping bookdrop folder monitor...");
|
||||||
running = false;
|
running = false;
|
||||||
if (watchThread != null) {
|
if (watchThread != null) {
|
||||||
watchThread.interrupt();
|
watchThread.interrupt();
|
||||||
|
try {
|
||||||
|
watchThread.join(5000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.warn("Interrupted while waiting for watchThread to stop");
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (watchService != null) {
|
if (watchService != null) {
|
||||||
try {
|
try {
|
||||||
@@ -92,6 +106,17 @@ public class BookdropMonitoringService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.info("Stopped bookdrop folder monitor");
|
log.info("Stopped bookdrop folder monitor");
|
||||||
|
callback.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isRunning() {
|
||||||
|
return running;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getPhase() {
|
||||||
|
return LIFECYCLE_PHASE;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void pauseMonitoring() {
|
public void pauseMonitoring() {
|
||||||
|
|||||||
+1
-18
@@ -11,7 +11,6 @@ import org.apache.commons.io.FilenameUtils;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import jakarta.annotation.PreDestroy;
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.Year;
|
import java.time.Year;
|
||||||
import java.time.YearMonth;
|
import java.time.YearMonth;
|
||||||
@@ -31,11 +30,7 @@ public class FilenamePatternExtractor {
|
|||||||
private static final Pattern PATTERN = Pattern.compile("[,;&]");
|
private static final Pattern PATTERN = Pattern.compile("[,;&]");
|
||||||
private final BookdropFileRepository bookdropFileRepository;
|
private final BookdropFileRepository bookdropFileRepository;
|
||||||
private final BookdropMetadataHelper metadataHelper;
|
private final BookdropMetadataHelper metadataHelper;
|
||||||
private final ExecutorService regexExecutor = Executors.newCachedThreadPool(runnable -> {
|
private final ExecutorService regexExecutor;
|
||||||
Thread thread = new Thread(runnable);
|
|
||||||
thread.setDaemon(true);
|
|
||||||
return thread;
|
|
||||||
});
|
|
||||||
|
|
||||||
private static final int PREVIEW_FILE_LIMIT = 5;
|
private static final int PREVIEW_FILE_LIMIT = 5;
|
||||||
private static final long REGEX_TIMEOUT_SECONDS = 5;
|
private static final long REGEX_TIMEOUT_SECONDS = 5;
|
||||||
@@ -216,18 +211,6 @@ public class FilenamePatternExtractor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreDestroy
|
|
||||||
public void shutdownRegexExecutor() {
|
|
||||||
regexExecutor.shutdown();
|
|
||||||
try {
|
|
||||||
if (!regexExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
|
|
||||||
regexExecutor.shutdownNow();
|
|
||||||
}
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
regexExecutor.shutdownNow();
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private BookdropPatternExtractResult.FileExtractionResult extractFromFile(
|
private BookdropPatternExtractResult.FileExtractionResult extractFromFile(
|
||||||
BookdropFileEntity file,
|
BookdropFileEntity file,
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import org.booklore.repository.EmailRecipientV2Repository;
|
|||||||
import org.booklore.repository.UserEmailProviderPreferenceRepository;
|
import org.booklore.repository.UserEmailProviderPreferenceRepository;
|
||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import org.booklore.util.SecurityContextVirtualThread;
|
|
||||||
import jakarta.mail.MessagingException;
|
import jakarta.mail.MessagingException;
|
||||||
import jakarta.mail.internet.MimeMessage;
|
import jakarta.mail.internet.MimeMessage;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
@@ -32,6 +31,7 @@ import org.springframework.stereotype.Service;
|
|||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -45,6 +45,7 @@ public class SendEmailV2Service {
|
|||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
private final AuditService auditService;
|
private final AuditService auditService;
|
||||||
|
private final Executor taskExecutor;
|
||||||
|
|
||||||
public void emailBookQuick(Long bookId) {
|
public void emailBookQuick(Long bookId) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
@@ -73,7 +74,7 @@ public class SendEmailV2Service {
|
|||||||
String logMessage = "Email dispatch initiated for book: " + bookTitle + " to " + recipientEmail;
|
String logMessage = "Email dispatch initiated for book: " + bookTitle + " to " + recipientEmail;
|
||||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(logMessage));
|
notificationService.sendMessage(Topic.LOG, LogNotification.info(logMessage));
|
||||||
log.info(logMessage);
|
log.info(logMessage);
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
taskExecutor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
sendEmail(emailProvider, recipientEmail, book, bookFile);
|
sendEmail(emailProvider, recipientEmail, book, bookFile);
|
||||||
auditService.log(AuditAction.BOOK_SENT, "Book", book.getId(), "Sent book: " + bookTitle + " to " + recipientEmail);
|
auditService.log(AuditAction.BOOK_SENT, "Book", book.getId(), "Sent book: " + bookTitle + " to " + recipientEmail);
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ import org.booklore.service.audit.AuditService;
|
|||||||
import org.booklore.service.monitoring.LibraryWatchService;
|
import org.booklore.service.monitoring.LibraryWatchService;
|
||||||
import org.booklore.task.options.RescanLibraryContext;
|
import org.booklore.task.options.RescanLibraryContext;
|
||||||
import org.booklore.util.FileService;
|
import org.booklore.util.FileService;
|
||||||
import org.booklore.util.SecurityContextVirtualThread;
|
|
||||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitialization;
|
import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitialization;
|
||||||
import org.springframework.context.event.EventListener;
|
import org.springframework.context.event.EventListener;
|
||||||
@@ -45,6 +44,7 @@ import java.nio.file.Path;
|
|||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -77,6 +77,7 @@ public class LibraryService {
|
|||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final AuditService auditService;
|
private final AuditService auditService;
|
||||||
|
private final Executor taskExecutor;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@EventListener(ApplicationReadyEvent.class)
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
@@ -209,7 +210,7 @@ public class LibraryService {
|
|||||||
LibraryEntity lib = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
LibraryEntity lib = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
auditService.log(AuditAction.LIBRARY_SCANNED, "Library", libraryId, "Scanned library: " + lib.getName());
|
auditService.log(AuditAction.LIBRARY_SCANNED, "Library", libraryId, "Scanned library: " + lib.getName());
|
||||||
|
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
taskExecutor.execute(() -> {
|
||||||
if (!scanningLibraries.add(libraryId)) {
|
if (!scanningLibraries.add(libraryId)) {
|
||||||
log.warn("Library {} is already being scanned, skipping duplicate rescan request", libraryId);
|
log.warn("Library {} is already being scanned, skipping duplicate rescan request", libraryId);
|
||||||
return;
|
return;
|
||||||
@@ -367,7 +368,7 @@ public class LibraryService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void startBackgroundScan(long libraryId) {
|
private void startBackgroundScan(long libraryId) {
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
taskExecutor.execute(() -> {
|
||||||
if (!scanningLibraries.add(libraryId)) {
|
if (!scanningLibraries.add(libraryId)) {
|
||||||
log.warn("Library {} is already being scanned, skipping duplicate process request", libraryId);
|
log.warn("Library {} is already being scanned, skipping duplicate process request", libraryId);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import org.booklore.service.metadata.writer.MetadataWriterFactory;
|
|||||||
import org.booklore.util.BookCoverUtils;
|
import org.booklore.util.BookCoverUtils;
|
||||||
import org.booklore.util.FileService;
|
import org.booklore.util.FileService;
|
||||||
import org.booklore.config.AppProperties;
|
import org.booklore.config.AppProperties;
|
||||||
import org.booklore.util.SecurityContextVirtualThread;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.transaction.support.TransactionTemplate;
|
import org.springframework.transaction.support.TransactionTemplate;
|
||||||
@@ -33,6 +32,7 @@ import java.time.Instant;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
import java.util.function.BiConsumer;
|
import java.util.function.BiConsumer;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@@ -53,6 +53,7 @@ public class BookCoverService {
|
|||||||
private final BookQueryService bookQueryService;
|
private final BookQueryService bookQueryService;
|
||||||
private final CoverImageGenerator coverImageGenerator;
|
private final CoverImageGenerator coverImageGenerator;
|
||||||
private final MetadataWriterFactory metadataWriterFactory;
|
private final MetadataWriterFactory metadataWriterFactory;
|
||||||
|
private final Executor taskExecutor;
|
||||||
private final TransactionTemplate transactionTemplate;
|
private final TransactionTemplate transactionTemplate;
|
||||||
|
|
||||||
private record BookCoverInfo(Long id, String title) {
|
private record BookCoverInfo(Long id, String title) {
|
||||||
@@ -216,7 +217,7 @@ public class BookCoverService {
|
|||||||
validateCoverFile(file);
|
validateCoverFile(file);
|
||||||
byte[] coverImageBytes = extractBytesFromMultipartFile(file);
|
byte[] coverImageBytes = extractBytesFromMultipartFile(file);
|
||||||
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes));
|
taskExecutor.execute(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes));
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
@@ -284,7 +285,7 @@ public class BookCoverService {
|
|||||||
*/
|
*/
|
||||||
public void regenerateCoversForBooks(Set<Long> bookIds) {
|
public void regenerateCoversForBooks(Set<Long> bookIds) {
|
||||||
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
|
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks));
|
taskExecutor.execute(() -> processBulkCoverRegeneration(unlockedBooks));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -292,14 +293,14 @@ public class BookCoverService {
|
|||||||
*/
|
*/
|
||||||
public void generateCustomCoversForBooks(Set<Long> bookIds) {
|
public void generateCustomCoversForBooks(Set<Long> bookIds) {
|
||||||
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCustomCoverGeneration(unlockedBooks));
|
taskExecutor.execute(() -> processBulkCustomCoverGeneration(unlockedBooks));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Regenerate covers for all books, optionally only for books with missing covers.
|
* Regenerate covers for all books, optionally only for books with missing covers.
|
||||||
*/
|
*/
|
||||||
public void regenerateCovers(boolean missingOnly) {
|
public void regenerateCovers(boolean missingOnly) {
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
taskExecutor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream()
|
List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream()
|
||||||
.filter(book -> !isCoverLocked(book))
|
.filter(book -> !isCoverLocked(book))
|
||||||
|
|||||||
+44
-22
@@ -1,11 +1,10 @@
|
|||||||
package org.booklore.service.monitoring;
|
package org.booklore.service.monitoring;
|
||||||
|
|
||||||
import jakarta.annotation.PostConstruct;
|
|
||||||
import jakarta.annotation.PreDestroy;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.booklore.model.dto.Library;
|
import org.booklore.model.dto.Library;
|
||||||
import org.booklore.model.enums.BookFileExtension;
|
import org.booklore.model.enums.BookFileExtension;
|
||||||
import org.booklore.service.watcher.LibraryFileEventProcessor;
|
import org.booklore.service.watcher.LibraryFileEventProcessor;
|
||||||
|
import org.springframework.context.SmartLifecycle;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -21,28 +20,62 @@ import java.util.stream.Stream;
|
|||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
public class LibraryWatchService {
|
public class LibraryWatchService implements SmartLifecycle {
|
||||||
|
|
||||||
|
private static final int LIFECYCLE_PHASE = 20;
|
||||||
|
|
||||||
private final LibraryFileEventProcessor eventProcessor;
|
private final LibraryFileEventProcessor eventProcessor;
|
||||||
private final WatchService watchService;
|
private WatchService watchService;
|
||||||
private final ExecutorService registrationExecutor;
|
private ExecutorService registrationExecutor;
|
||||||
|
|
||||||
private final ConcurrentHashMap<Path, WatchEntry> watches = new ConcurrentHashMap<>();
|
private final ConcurrentHashMap<Path, WatchEntry> watches = new ConcurrentHashMap<>();
|
||||||
private final Map<Long, Boolean> libraryWatchStatus = new ConcurrentHashMap<>();
|
private final Map<Long, Boolean> libraryWatchStatus = new ConcurrentHashMap<>();
|
||||||
private final Lock watchLock = new ReentrantLock();
|
private final Lock watchLock = new ReentrantLock();
|
||||||
|
private volatile boolean running;
|
||||||
|
|
||||||
private record WatchEntry(WatchKey key, long libraryId) {}
|
private record WatchEntry(WatchKey key, long libraryId) {}
|
||||||
|
|
||||||
public LibraryWatchService(LibraryFileEventProcessor eventProcessor) throws IOException {
|
public LibraryWatchService(LibraryFileEventProcessor eventProcessor) {
|
||||||
this.eventProcessor = eventProcessor;
|
this.eventProcessor = eventProcessor;
|
||||||
this.watchService = FileSystems.getDefault().newWatchService();
|
|
||||||
this.registrationExecutor = Executors.newSingleThreadExecutor(
|
|
||||||
Thread.ofVirtual().name("watch-registrar").factory());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostConstruct
|
@Override
|
||||||
public void start() {
|
public void start() {
|
||||||
Thread.ofVirtual().name("watch-poll").start(this::pollLoop);
|
try {
|
||||||
|
if (watchService == null) {
|
||||||
|
this.watchService = FileSystems.getDefault().newWatchService();
|
||||||
|
}
|
||||||
|
if (registrationExecutor == null || registrationExecutor.isShutdown()) {
|
||||||
|
this.registrationExecutor = Executors.newSingleThreadExecutor(
|
||||||
|
Thread.ofVirtual().name("watch-registrar").factory());
|
||||||
|
}
|
||||||
|
running = true;
|
||||||
|
Thread.ofVirtual().name("watch-poll").start(this::pollLoop);
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Failed to start LibraryWatchService", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stop() {
|
||||||
|
log.info("Shutting down LibraryWatchService...");
|
||||||
|
running = false;
|
||||||
|
registrationExecutor.shutdownNow();
|
||||||
|
try {
|
||||||
|
watchService.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Failed to close WatchService", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isRunning() {
|
||||||
|
return running;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getPhase() {
|
||||||
|
return LIFECYCLE_PHASE;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void pollLoop() {
|
private void pollLoop() {
|
||||||
@@ -285,15 +318,4 @@ public class LibraryWatchService {
|
|||||||
log.warn("Timeout waiting for events to drain for {} paths", paths.size());
|
log.warn("Timeout waiting for events to drain for {} paths", paths.size());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreDestroy
|
|
||||||
public void shutdown() {
|
|
||||||
log.info("Shutting down LibraryWatchService...");
|
|
||||||
registrationExecutor.shutdownNow();
|
|
||||||
try {
|
|
||||||
watchService.close();
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("Failed to close WatchService", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import org.booklore.model.enums.TaskType;
|
|||||||
import org.booklore.task.TaskCancellationManager;
|
import org.booklore.task.TaskCancellationManager;
|
||||||
import org.booklore.task.TaskStatus;
|
import org.booklore.task.TaskStatus;
|
||||||
import org.booklore.task.tasks.Task;
|
import org.booklore.task.tasks.Task;
|
||||||
import org.booklore.util.SecurityContextVirtualThread;
|
|
||||||
import org.springframework.context.annotation.Lazy;
|
import org.springframework.context.annotation.Lazy;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.scheduling.TaskScheduler;
|
import org.springframework.scheduling.TaskScheduler;
|
||||||
@@ -188,11 +187,8 @@ public class TaskService {
|
|||||||
.taskType(taskType)
|
.taskType(taskType)
|
||||||
.status(TaskStatus.ACCEPTED)
|
.status(TaskStatus.ACCEPTED)
|
||||||
.build();
|
.build();
|
||||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
|
||||||
taskExecutor.execute(() ->
|
taskExecutor.execute(() ->
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(securityContext, () ->
|
|
||||||
executeAsyncTask(taskId, request, taskType)
|
executeAsyncTask(taskId, request, taskType)
|
||||||
)
|
|
||||||
);
|
);
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|||||||
+44
-16
@@ -13,10 +13,9 @@ import org.booklore.repository.LibraryRepository;
|
|||||||
import org.booklore.service.file.FileFingerprint;
|
import org.booklore.service.file.FileFingerprint;
|
||||||
import org.booklore.service.library.LibraryProcessingService;
|
import org.booklore.service.library.LibraryProcessingService;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import jakarta.annotation.PostConstruct;
|
import lombok.RequiredArgsConstructor;
|
||||||
import jakarta.annotation.PreDestroy;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.context.SmartLifecycle;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -29,9 +28,10 @@ import java.util.concurrent.*;
|
|||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@AllArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class LibraryFileEventProcessor {
|
public class LibraryFileEventProcessor implements SmartLifecycle {
|
||||||
|
|
||||||
|
private static final int LIFECYCLE_PHASE = 10;
|
||||||
private static final long DEBOUNCE_MS = 500L;
|
private static final long DEBOUNCE_MS = 500L;
|
||||||
private static final long FOLDER_CREATE_DEBOUNCE_MS = 5000L;
|
private static final long FOLDER_CREATE_DEBOUNCE_MS = 5000L;
|
||||||
private static final long PENDING_DELETION_GRACE_MS = 8000L;
|
private static final long PENDING_DELETION_GRACE_MS = 8000L;
|
||||||
@@ -47,16 +47,28 @@ public class LibraryFileEventProcessor {
|
|||||||
private final LibraryProcessingService libraryProcessingService;
|
private final LibraryProcessingService libraryProcessingService;
|
||||||
private final PendingDeletionPool pendingDeletionPool;
|
private final PendingDeletionPool pendingDeletionPool;
|
||||||
|
|
||||||
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
private ScheduledExecutorService scheduler;
|
||||||
private final ConcurrentMap<Path, ScheduledFuture<?>> pendingDeletes = new ConcurrentHashMap<>();
|
private final ConcurrentMap<Path, ScheduledFuture<?>> pendingDeletes = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentMap<Path, ScheduledFuture<?>> pendingFolderCreates = new ConcurrentHashMap<>();
|
private final ConcurrentMap<Path, ScheduledFuture<?>> pendingFolderCreates = new ConcurrentHashMap<>();
|
||||||
private final Set<Path> filesFromPendingFolder = ConcurrentHashMap.newKeySet();
|
private final Set<Path> filesFromPendingFolder = ConcurrentHashMap.newKeySet();
|
||||||
|
private volatile boolean running;
|
||||||
|
private Thread workerThread;
|
||||||
|
|
||||||
@PostConstruct
|
@Override
|
||||||
public void init() {
|
public void start() {
|
||||||
Thread.ofVirtual().start(() -> {
|
if (running && workerThread != null && workerThread.isAlive()) {
|
||||||
|
log.info("LibraryFileEventProcessor is already running.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (scheduler == null || scheduler.isShutdown()) {
|
||||||
|
scheduler = Executors.newScheduledThreadPool(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
running = true;
|
||||||
|
workerThread = Thread.ofVirtual().name("lib-event-processor").start(() -> {
|
||||||
log.info("LibraryFileEventProcessor virtual thread started.");
|
log.info("LibraryFileEventProcessor virtual thread started.");
|
||||||
while (!Thread.currentThread().isInterrupted()) {
|
while (running && !Thread.currentThread().isInterrupted()) {
|
||||||
try {
|
try {
|
||||||
handleEvent(eventQueue.take());
|
handleEvent(eventQueue.take());
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
@@ -69,6 +81,28 @@ public class LibraryFileEventProcessor {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stop() {
|
||||||
|
log.info("Shutting down LibraryFileEventProcessor...");
|
||||||
|
running = false;
|
||||||
|
if (scheduler != null) {
|
||||||
|
scheduler.shutdownNow();
|
||||||
|
}
|
||||||
|
if (workerThread != null) {
|
||||||
|
workerThread.interrupt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isRunning() {
|
||||||
|
return running;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getPhase() {
|
||||||
|
return LIFECYCLE_PHASE;
|
||||||
|
}
|
||||||
|
|
||||||
public void processEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
|
public void processEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
|
||||||
Path path = fullPath.toAbsolutePath().normalize();
|
Path path = fullPath.toAbsolutePath().normalize();
|
||||||
|
|
||||||
@@ -542,12 +576,6 @@ public class LibraryFileEventProcessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreDestroy
|
|
||||||
public void shutdown() {
|
|
||||||
scheduler.shutdownNow();
|
|
||||||
log.info("Shutting down LibraryFileEventProcessor...");
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean hasPendingEventsForPaths(Set<Path> paths) {
|
public boolean hasPendingEventsForPaths(Set<Path> paths) {
|
||||||
boolean inQueue = eventQueue.stream()
|
boolean inQueue = eventQueue.stream()
|
||||||
.anyMatch(e -> paths.stream().anyMatch(p -> e.fullPath().startsWith(p)));
|
.anyMatch(e -> paths.stream().anyMatch(p -> e.fullPath().startsWith(p)));
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
package org.booklore.util;
|
|
||||||
|
|
||||||
import lombok.experimental.UtilityClass;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.context.SecurityContext;
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
|
||||||
|
|
||||||
@UtilityClass
|
|
||||||
public class SecurityContextVirtualThread {
|
|
||||||
|
|
||||||
public void runWithSecurityContext(Runnable task) {
|
|
||||||
Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
|
|
||||||
|
|
||||||
Thread.startVirtualThread(() -> {
|
|
||||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
|
||||||
context.setAuthentication(currentAuth);
|
|
||||||
SecurityContextHolder.setContext(context);
|
|
||||||
try {
|
|
||||||
task.run();
|
|
||||||
} finally {
|
|
||||||
SecurityContextHolder.clearContext();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public void runWithSecurityContext(SecurityContext parentContext, Runnable task) {
|
|
||||||
Thread.startVirtualThread(() -> {
|
|
||||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
|
||||||
context.setAuthentication(parentContext.getAuthentication());
|
|
||||||
SecurityContextHolder.setContext(context);
|
|
||||||
try {
|
|
||||||
task.run();
|
|
||||||
} finally {
|
|
||||||
SecurityContextHolder.clearContext();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+12
@@ -5,14 +5,18 @@ import org.booklore.model.dto.request.BookdropPatternExtractRequest;
|
|||||||
import org.booklore.model.dto.response.BookdropPatternExtractResult;
|
import org.booklore.model.dto.response.BookdropPatternExtractResult;
|
||||||
import org.booklore.model.entity.BookdropFileEntity;
|
import org.booklore.model.entity.BookdropFileEntity;
|
||||||
import org.booklore.repository.BookdropFileRepository;
|
import org.booklore.repository.BookdropFileRepository;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.Spy;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
@@ -26,9 +30,17 @@ class FilenamePatternExtractorTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private BookdropMetadataHelper metadataHelper;
|
private BookdropMetadataHelper metadataHelper;
|
||||||
|
|
||||||
|
@Spy
|
||||||
|
private ExecutorService regexExecutor = Executors.newVirtualThreadPerTaskExecutor();
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private FilenamePatternExtractor extractor;
|
private FilenamePatternExtractor extractor;
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
regexExecutor.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
private BookdropFileEntity createFileEntity(Long id, String fileName) {
|
private BookdropFileEntity createFileEntity(Long id, String fileName) {
|
||||||
BookdropFileEntity entity = new BookdropFileEntity();
|
BookdropFileEntity entity = new BookdropFileEntity();
|
||||||
entity.setId(id);
|
entity.setId(id);
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ import org.booklore.repository.EmailProviderV2Repository;
|
|||||||
import org.booklore.repository.EmailRecipientV2Repository;
|
import org.booklore.repository.EmailRecipientV2Repository;
|
||||||
import org.booklore.repository.UserEmailProviderPreferenceRepository;
|
import org.booklore.repository.UserEmailProviderPreferenceRepository;
|
||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
|
import org.booklore.service.audit.AuditService;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import org.booklore.util.SecurityContextVirtualThread;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InOrder;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.MockedStatic;
|
import org.mockito.MockedStatic;
|
||||||
@@ -23,6 +24,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
@@ -48,11 +50,18 @@ class SendEmailV2ServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private AuthenticationService authenticationService;
|
private AuthenticationService authenticationService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AuditService auditService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Executor taskExecutor;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private SendEmailV2Service sendEmailV2Service;
|
private SendEmailV2Service sendEmailV2Service;
|
||||||
|
|
||||||
private BookLoreUser user;
|
private BookLoreUser user;
|
||||||
private BookEntity book;
|
private BookEntity book;
|
||||||
|
private BookFileEntity bookFile;
|
||||||
private EmailProviderV2Entity emailProvider;
|
private EmailProviderV2Entity emailProvider;
|
||||||
private EmailRecipientV2Entity emailRecipient;
|
private EmailRecipientV2Entity emailRecipient;
|
||||||
private UserEmailProviderPreferenceEntity preference;
|
private UserEmailProviderPreferenceEntity preference;
|
||||||
@@ -68,7 +77,7 @@ class SendEmailV2ServiceTest {
|
|||||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||||
libraryPath.setPath("/library");
|
libraryPath.setPath("/library");
|
||||||
|
|
||||||
BookFileEntity bookFile = new BookFileEntity();
|
bookFile = new BookFileEntity();
|
||||||
bookFile.setFileName("test-book.epub");
|
bookFile.setFileName("test-book.epub");
|
||||||
bookFile.setFileSubPath("books");
|
bookFile.setFileSubPath("books");
|
||||||
bookFile.setBookFormat(true);
|
bookFile.setBookFormat(true);
|
||||||
@@ -114,22 +123,19 @@ class SendEmailV2ServiceTest {
|
|||||||
when(emailProviderRepository.findAccessibleProvider(100L, 1L)).thenReturn(Optional.of(emailProvider));
|
when(emailProviderRepository.findAccessibleProvider(100L, 1L)).thenReturn(Optional.of(emailProvider));
|
||||||
when(emailRecipientRepository.findDefaultEmailRecipientByUserId(1L)).thenReturn(Optional.of(emailRecipient));
|
when(emailRecipientRepository.findDefaultEmailRecipientByUserId(1L)).thenReturn(Optional.of(emailRecipient));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(invocation -> {
|
||||||
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
Runnable task = invocation.getArgument(0);
|
||||||
.thenAnswer(invocation -> {
|
task.run();
|
||||||
Runnable task = invocation.getArgument(0);
|
return null;
|
||||||
task.run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book)).thenReturn(Path.of("/library/books/test-book.epub"));
|
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile)).thenReturn(Path.of("/library/books/test-book.epub"));
|
||||||
|
|
||||||
sendEmailV2Service.emailBookQuick(10L);
|
sendEmailV2Service.emailBookQuick(10L);
|
||||||
|
|
||||||
securityMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
|
verify(taskExecutor).execute(any(Runnable.class));
|
||||||
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,22 +190,19 @@ class SendEmailV2ServiceTest {
|
|||||||
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
|
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
|
||||||
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
|
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(invocation -> {
|
||||||
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
Runnable task = invocation.getArgument(0);
|
||||||
.thenAnswer(invocation -> {
|
task.run();
|
||||||
Runnable task = invocation.getArgument(0);
|
return null;
|
||||||
task.run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book)).thenReturn(Path.of("/library/books/test-book.epub"));
|
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile)).thenReturn(Path.of("/library/books/test-book.epub"));
|
||||||
|
|
||||||
sendEmailV2Service.emailBook(request);
|
sendEmailV2Service.emailBook(request);
|
||||||
|
|
||||||
securityMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
|
verify(taskExecutor).execute(any(Runnable.class));
|
||||||
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,22 +220,19 @@ class SendEmailV2ServiceTest {
|
|||||||
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
|
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
|
||||||
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
|
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(invocation -> {
|
||||||
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
Runnable task = invocation.getArgument(0);
|
||||||
.thenAnswer(invocation -> {
|
task.run();
|
||||||
Runnable task = invocation.getArgument(0);
|
return null;
|
||||||
task.run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book)).thenReturn(Path.of("/library/books/test-book.epub"));
|
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile)).thenReturn(Path.of("/library/books/test-book.epub"));
|
||||||
|
|
||||||
sendEmailV2Service.emailBook(request);
|
sendEmailV2Service.emailBook(request);
|
||||||
|
|
||||||
securityMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
|
verify(taskExecutor).execute(any(Runnable.class));
|
||||||
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,28 +290,25 @@ class SendEmailV2ServiceTest {
|
|||||||
when(emailProviderRepository.findAccessibleProvider(100L, 1L)).thenReturn(Optional.of(emailProvider));
|
when(emailProviderRepository.findAccessibleProvider(100L, 1L)).thenReturn(Optional.of(emailProvider));
|
||||||
when(emailRecipientRepository.findDefaultEmailRecipientByUserId(1L)).thenReturn(Optional.of(emailRecipient));
|
when(emailRecipientRepository.findDefaultEmailRecipientByUserId(1L)).thenReturn(Optional.of(emailRecipient));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(invocation -> {
|
||||||
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
Runnable task = invocation.getArgument(0);
|
||||||
.thenAnswer(invocation -> {
|
task.run();
|
||||||
Runnable task = invocation.getArgument(0);
|
return null;
|
||||||
task.run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book))
|
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile))
|
||||||
.thenThrow(new IllegalStateException("Book file not found"));
|
.thenThrow(new IllegalStateException("Book file not found"));
|
||||||
|
|
||||||
sendEmailV2Service.emailBookQuick(10L);
|
sendEmailV2Service.emailBookQuick(10L);
|
||||||
|
|
||||||
// Error is caught and logged, not rethrown
|
// Error is caught and logged, not rethrown
|
||||||
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void emailBook_notificationSentBeforeVirtualThread() {
|
void emailBook_notificationSentBeforeAsyncExecution() {
|
||||||
SendBookByEmailRequest request = SendBookByEmailRequest.builder()
|
SendBookByEmailRequest request = SendBookByEmailRequest.builder()
|
||||||
.bookId(10L)
|
.bookId(10L)
|
||||||
.providerId(100L)
|
.providerId(100L)
|
||||||
@@ -323,16 +320,17 @@ class SendEmailV2ServiceTest {
|
|||||||
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
|
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
|
||||||
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
|
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
|
// Don't execute the runnable - just capture it
|
||||||
// Don't execute the runnable - just capture it
|
doNothing().when(taskExecutor).execute(any(Runnable.class));
|
||||||
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
|
||||||
.thenAnswer(invocation -> null);
|
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
||||||
|
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile)).thenReturn(Path.of("/library/books/test-book.epub"));
|
||||||
|
|
||||||
sendEmailV2Service.emailBook(request);
|
sendEmailV2Service.emailBook(request);
|
||||||
|
|
||||||
// Log notification is sent before the virtual thread starts
|
InOrder inOrder = inOrder(notificationService, taskExecutor);
|
||||||
verify(notificationService).sendMessage(any(), any());
|
inOrder.verify(notificationService).sendMessage(any(), any());
|
||||||
securityMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
|
inOrder.verify(taskExecutor).execute(any(Runnable.class));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import java.util.Collections;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
@@ -63,6 +64,8 @@ class LibraryServiceIconTest {
|
|||||||
private UserRepository userRepository;
|
private UserRepository userRepository;
|
||||||
@Mock
|
@Mock
|
||||||
private AuditService auditService;
|
private AuditService auditService;
|
||||||
|
@Mock
|
||||||
|
private Executor taskExecutor;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private LibraryService libraryService;
|
private LibraryService libraryService;
|
||||||
|
|||||||
+49
-69
@@ -17,7 +17,6 @@ import org.booklore.service.metadata.writer.MetadataWriter;
|
|||||||
import org.booklore.service.metadata.writer.MetadataWriterFactory;
|
import org.booklore.service.metadata.writer.MetadataWriterFactory;
|
||||||
import org.booklore.service.file.FileFingerprint;
|
import org.booklore.service.file.FileFingerprint;
|
||||||
import org.booklore.util.FileService;
|
import org.booklore.util.FileService;
|
||||||
import org.booklore.util.SecurityContextVirtualThread;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Nested;
|
import org.junit.jupiter.api.Nested;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -30,6 +29,7 @@ import org.springframework.transaction.support.TransactionTemplate;
|
|||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
@@ -49,6 +49,7 @@ class BookCoverServiceTest {
|
|||||||
@Mock private CoverImageGenerator coverImageGenerator;
|
@Mock private CoverImageGenerator coverImageGenerator;
|
||||||
@Mock private MetadataWriterFactory metadataWriterFactory;
|
@Mock private MetadataWriterFactory metadataWriterFactory;
|
||||||
@Mock private TransactionTemplate transactionTemplate;
|
@Mock private TransactionTemplate transactionTemplate;
|
||||||
|
@Mock private Executor taskExecutor;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private BookCoverService service;
|
private BookCoverService service;
|
||||||
@@ -654,7 +655,7 @@ class BookCoverServiceTest {
|
|||||||
class BulkRegenerateCoversForBooks {
|
class BulkRegenerateCoversForBooks {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void delegatesToVirtualThreadWithUnlockedBooks() {
|
void delegatesToAsyncExecutorWithUnlockedBooks() {
|
||||||
BookEntity unlocked = buildBook(1L, false);
|
BookEntity unlocked = buildBook(1L, false);
|
||||||
unlocked.setBookFiles(List.of(BookFileEntity.builder().bookType(BookFileType.EPUB).isBookFormat(true).build()));
|
unlocked.setBookFiles(List.of(BookFileEntity.builder().bookType(BookFileType.EPUB).isBookFormat(true).build()));
|
||||||
unlocked.setLibrary(LibraryEntity.builder().build());
|
unlocked.setLibrary(LibraryEntity.builder().build());
|
||||||
@@ -663,17 +664,14 @@ class BookCoverServiceTest {
|
|||||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
|
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
|
||||||
.thenReturn(List.of(unlocked, locked));
|
.thenReturn(List.of(unlocked, locked));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(inv -> {
|
||||||
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
inv.<Runnable>getArgument(0).run();
|
||||||
.thenAnswer(inv -> {
|
return null;
|
||||||
inv.<Runnable>getArgument(0).run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
service.regenerateCoversForBooks(Set.of(1L, 2L));
|
service.regenerateCoversForBooks(Set.of(1L, 2L));
|
||||||
|
|
||||||
secMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
|
verify(taskExecutor).execute(any(Runnable.class));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -681,24 +679,21 @@ class BookCoverServiceTest {
|
|||||||
class BulkGenerateCustomCoversForBooks {
|
class BulkGenerateCustomCoversForBooks {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void delegatesToVirtualThreadWithUnlockedBooks() {
|
void delegatesToAsyncExecutorWithUnlockedBooks() {
|
||||||
BookEntity unlocked = buildBook(1L, false);
|
BookEntity unlocked = buildBook(1L, false);
|
||||||
BookEntity locked = buildBook(2L, true);
|
BookEntity locked = buildBook(2L, true);
|
||||||
|
|
||||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
|
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
|
||||||
.thenReturn(List.of(unlocked, locked));
|
.thenReturn(List.of(unlocked, locked));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(inv -> {
|
||||||
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
inv.<Runnable>getArgument(0).run();
|
||||||
.thenAnswer(inv -> {
|
return null;
|
||||||
inv.<Runnable>getArgument(0).run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
service.generateCustomCoversForBooks(Set.of(1L, 2L));
|
service.generateCustomCoversForBooks(Set.of(1L, 2L));
|
||||||
|
|
||||||
secMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
|
verify(taskExecutor).execute(any(Runnable.class));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -719,17 +714,14 @@ class BookCoverServiceTest {
|
|||||||
when(file.getSize()).thenReturn(1024L);
|
when(file.getSize()).thenReturn(1024L);
|
||||||
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
|
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(inv -> {
|
||||||
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
inv.<Runnable>getArgument(0).run();
|
||||||
.thenAnswer(inv -> {
|
return null;
|
||||||
inv.<Runnable>getArgument(0).run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
service.updateCoverFromFileForBooks(Set.of(1L, 2L), file);
|
service.updateCoverFromFileForBooks(Set.of(1L, 2L), file);
|
||||||
|
|
||||||
secMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
|
verify(taskExecutor).execute(any(Runnable.class));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -756,18 +748,15 @@ class BookCoverServiceTest {
|
|||||||
when(processor.generateCover(book)).thenReturn(true);
|
when(processor.generateCover(book)).thenReturn(true);
|
||||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(inv -> {
|
||||||
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
inv.<Runnable>getArgument(0).run();
|
||||||
.thenAnswer(inv -> {
|
return null;
|
||||||
inv.<Runnable>getArgument(0).run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
service.regenerateCovers(false);
|
service.regenerateCovers(false);
|
||||||
|
|
||||||
verify(bookRepository).save(book);
|
verify(bookRepository).save(book);
|
||||||
assertThat(book.getMetadata().getCoverUpdatedOn()).isNotNull();
|
assertThat(book.getMetadata().getCoverUpdatedOn()).isNotNull();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -780,17 +769,14 @@ class BookCoverServiceTest {
|
|||||||
|
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(locked));
|
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(locked));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(inv -> {
|
||||||
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
inv.<Runnable>getArgument(0).run();
|
||||||
.thenAnswer(inv -> {
|
return null;
|
||||||
inv.<Runnable>getArgument(0).run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
service.regenerateCovers(false);
|
service.regenerateCovers(false);
|
||||||
|
|
||||||
verify(bookRepository, never()).save(any());
|
verify(bookRepository, never()).save(any());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -821,19 +807,16 @@ class BookCoverServiceTest {
|
|||||||
when(processor.generateCover(withoutCover)).thenReturn(true);
|
when(processor.generateCover(withoutCover)).thenReturn(true);
|
||||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(inv -> {
|
||||||
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
inv.<Runnable>getArgument(0).run();
|
||||||
.thenAnswer(inv -> {
|
return null;
|
||||||
inv.<Runnable>getArgument(0).run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
service.regenerateCovers(true);
|
service.regenerateCovers(true);
|
||||||
|
|
||||||
verify(transactionTemplate, times(1)).execute(any());
|
verify(transactionTemplate, times(1)).execute(any());
|
||||||
verify(bookRepository).save(withoutCover);
|
verify(bookRepository).save(withoutCover);
|
||||||
verify(bookRepository, never()).findById(1L);
|
verify(bookRepository, never()).findById(1L);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -843,17 +826,14 @@ class BookCoverServiceTest {
|
|||||||
|
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(book));
|
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(book));
|
||||||
|
|
||||||
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
|
doAnswer(inv -> {
|
||||||
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
inv.<Runnable>getArgument(0).run();
|
||||||
.thenAnswer(inv -> {
|
return null;
|
||||||
inv.<Runnable>getArgument(0).run();
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
service.regenerateCovers(false);
|
service.regenerateCovers(false);
|
||||||
|
|
||||||
verify(transactionTemplate, never()).execute(any());
|
verify(transactionTemplate, never()).execute(any());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-1
@@ -30,12 +30,13 @@ class LibraryWatchServiceTest {
|
|||||||
void setup() throws Exception {
|
void setup() throws Exception {
|
||||||
processor = mock(LibraryFileEventProcessor.class);
|
processor = mock(LibraryFileEventProcessor.class);
|
||||||
service = new LibraryWatchService(processor);
|
service = new LibraryWatchService(processor);
|
||||||
|
service.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterEach
|
@AfterEach
|
||||||
void teardown() {
|
void teardown() {
|
||||||
try {
|
try {
|
||||||
service.shutdown();
|
service.stop();
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-6
@@ -74,13 +74,13 @@ class LibraryFileEventProcessorTest {
|
|||||||
when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq(tempDir.toString())))
|
when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq(tempDir.toString())))
|
||||||
.thenReturn(libraryPath);
|
.thenReturn(libraryPath);
|
||||||
|
|
||||||
// Start the event processing thread (normally done by @PostConstruct)
|
// Start the event processing thread (normally done by SmartLifecycle)
|
||||||
processor.init();
|
processor.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterEach
|
@AfterEach
|
||||||
void tearDown() throws Exception {
|
void tearDown() throws Exception {
|
||||||
processor.shutdown();
|
processor.stop();
|
||||||
mocks.close();
|
mocks.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,9 +392,9 @@ class LibraryFileEventProcessorTest {
|
|||||||
class Shutdown {
|
class Shutdown {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shutdownCompletesCleanly() {
|
void stopCompletesCleanly() {
|
||||||
// Just verify shutdown doesn't throw
|
// Just verify stop doesn't throw
|
||||||
processor.shutdown();
|
processor.stop();
|
||||||
|
|
||||||
// Reinitialize so tearDown's shutdown doesn't fail
|
// Reinitialize so tearDown's shutdown doesn't fail
|
||||||
processor = new LibraryFileEventProcessor(
|
processor = new LibraryFileEventProcessor(
|
||||||
|
|||||||
@@ -1,156 +0,0 @@
|
|||||||
package org.booklore.util;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.context.SecurityContext;
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
|
||||||
import org.springframework.security.core.context.SecurityContextImpl;
|
|
||||||
|
|
||||||
import java.util.concurrent.CompletableFuture;
|
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
class SecurityContextVirtualThreadTest {
|
|
||||||
|
|
||||||
private Authentication originalAuth;
|
|
||||||
private SecurityContext originalContext;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
originalAuth = new UsernamePasswordAuthenticationToken("testUser", "password", null);
|
|
||||||
originalContext = new SecurityContextImpl(originalAuth);
|
|
||||||
SecurityContextHolder.setContext(originalContext);
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
void tearDown() {
|
|
||||||
SecurityContextHolder.clearContext();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testRunWithSecurityContext_executesRunnable() throws ExecutionException, InterruptedException {
|
|
||||||
AtomicReference<String> result = new AtomicReference<>();
|
|
||||||
|
|
||||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
|
||||||
try {
|
|
||||||
result.set("executed");
|
|
||||||
future.complete(null);
|
|
||||||
} catch (Exception e) {
|
|
||||||
future.completeExceptionally(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Wait for the virtual thread to complete
|
|
||||||
future.get();
|
|
||||||
assertEquals("executed", result.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testRunWithSecurityContext_preservesSecurityContext() throws ExecutionException, InterruptedException {
|
|
||||||
AtomicReference<Authentication> capturedAuth = new AtomicReference<>();
|
|
||||||
|
|
||||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
|
||||||
try {
|
|
||||||
capturedAuth.set(SecurityContextHolder.getContext().getAuthentication());
|
|
||||||
future.complete(null);
|
|
||||||
} catch (Exception e) {
|
|
||||||
future.completeExceptionally(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
future.get();
|
|
||||||
assertNotNull(capturedAuth.get());
|
|
||||||
assertEquals(originalAuth.getName(), capturedAuth.get().getName());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testRunWithSecurityContext_maintainsMainThreadContext() throws ExecutionException, InterruptedException {
|
|
||||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
|
||||||
try {
|
|
||||||
// Context should be set here
|
|
||||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
|
||||||
future.complete(null);
|
|
||||||
} catch (Exception e) {
|
|
||||||
future.completeExceptionally(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
future.get();
|
|
||||||
|
|
||||||
// After the virtual thread completes, the main thread's context should still be intact
|
|
||||||
Authentication mainThreadAuth = SecurityContextHolder.getContext().getAuthentication();
|
|
||||||
assertNotNull(mainThreadAuth);
|
|
||||||
assertEquals(originalAuth.getName(), mainThreadAuth.getName());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testRunWithSecurityContext_withProvidedContext() throws ExecutionException, InterruptedException {
|
|
||||||
Authentication differentAuth = new UsernamePasswordAuthenticationToken("differentUser", "password", null);
|
|
||||||
SecurityContext differentContext = new SecurityContextImpl(differentAuth);
|
|
||||||
|
|
||||||
AtomicReference<Authentication> capturedAuth = new AtomicReference<>();
|
|
||||||
|
|
||||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(differentContext, () -> {
|
|
||||||
try {
|
|
||||||
capturedAuth.set(SecurityContextHolder.getContext().getAuthentication());
|
|
||||||
future.complete(null);
|
|
||||||
} catch (Exception e) {
|
|
||||||
future.completeExceptionally(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
future.get();
|
|
||||||
assertNotNull(capturedAuth.get());
|
|
||||||
assertEquals("differentUser", capturedAuth.get().getName());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testRunWithSecurityContext_withProvidedContext_clearsAfterExecution() throws ExecutionException, InterruptedException {
|
|
||||||
Authentication differentAuth = new UsernamePasswordAuthenticationToken("differentUser", "password", null);
|
|
||||||
SecurityContext differentContext = new SecurityContextImpl(differentAuth);
|
|
||||||
|
|
||||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(differentContext, () -> {
|
|
||||||
try {
|
|
||||||
// Different context should be set here
|
|
||||||
assertEquals("differentUser", SecurityContextHolder.getContext().getAuthentication().getName());
|
|
||||||
future.complete(null);
|
|
||||||
} catch (Exception e) {
|
|
||||||
future.completeExceptionally(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
future.get();
|
|
||||||
|
|
||||||
// Main thread should still have original context
|
|
||||||
Authentication mainThreadAuth = SecurityContextHolder.getContext().getAuthentication();
|
|
||||||
assertEquals("testUser", mainThreadAuth.getName());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testRunWithSecurityContext_handlesException() throws ExecutionException, InterruptedException {
|
|
||||||
CompletableFuture<Exception> future = new CompletableFuture<>();
|
|
||||||
|
|
||||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
|
||||||
try {
|
|
||||||
throw new RuntimeException("Test exception");
|
|
||||||
} catch (Exception e) {
|
|
||||||
future.complete(e);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Exception capturedException = future.get();
|
|
||||||
assertNotNull(capturedException);
|
|
||||||
assertEquals("Test exception", capturedException.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user