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:
brios
2026-04-22 17:27:05 -04:00
committed by Zach Yale
parent 9ddbe3579d
commit cf7999044f
19 changed files with 331 additions and 419 deletions
@@ -5,6 +5,7 @@ import org.springframework.context.annotation.Configuration;
import java.net.http.HttpClient;
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Configuration
@@ -19,4 +20,9 @@ public class HttpClientConfig {
.executor(Executors.newVirtualThreadPerTaskExecutor())
.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.Configuration;
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.concurrent.SimpleAsyncTaskScheduler;
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class TaskExecutorConfig {
@Bean(name = "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
@@ -9,10 +9,9 @@ import org.booklore.model.websocket.Topic;
import org.booklore.repository.BookdropFileRepository;
import org.booklore.service.NotificationService;
import org.booklore.service.appsettings.AppSettingService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Service;
import java.io.IOException;
@@ -27,8 +26,9 @@ import java.util.concurrent.LinkedBlockingQueue;
@Slf4j
@Service
@RequiredArgsConstructor
public class BookdropEventHandlerService {
public class BookdropEventHandlerService implements SmartLifecycle {
private static final int LIFECYCLE_PHASE = 10;
private final BookdropFileRepository bookdropFileRepository;
private final NotificationService notificationService;
@@ -41,21 +41,59 @@ public class BookdropEventHandlerService {
private static final long STABILITY_MAX_WAIT_MS = 30_000;
private final BlockingQueue<BookDropFileEvent> fileQueue = new LinkedBlockingQueue<>();
private volatile boolean running = true;
private volatile boolean running;
private Thread workerThread;
@PostConstruct
public void init() {
public BookdropEventHandlerService(
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.start();
}
@PreDestroy
public void shutdown() {
@Override
public void stop() {
stop(() -> {});
}
@Override
public void stop(Runnable callback) {
log.info("Stopping BookdropEventHandlerService...");
running = false;
if (workerThread != null) {
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) {
@@ -4,9 +4,8 @@ import org.booklore.config.AppProperties;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.repository.BookdropFileRepository;
import org.booklore.util.FileUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Service;
import java.io.IOException;
@@ -20,7 +19,9 @@ import java.util.stream.Stream;
@Slf4j
@Service
public class BookdropMonitoringService {
public class BookdropMonitoringService implements SmartLifecycle {
private static final int LIFECYCLE_PHASE = 20;
private final AppProperties appProperties;
private final BookdropEventHandlerService eventHandler;
@@ -45,7 +46,7 @@ public class BookdropMonitoringService {
this.bookdropFileRepository = bookdropFileRepository;
}
@PostConstruct
@Override
public void start() {
bookdrop = Path.of(appProperties.getBookdropFolder());
if (Files.notExists(bookdrop)) {
@@ -72,17 +73,30 @@ public class BookdropMonitoringService {
this.watchThread.setDaemon(true);
this.watchThread.start();
scanExistingBookdropFiles();
this.disabled = false;
} catch (IOException e) {
log.warn("Failed to start bookdrop folder monitor. Bookdrop monitoring is disabled.", e);
this.disabled = true;
}
}
@PreDestroy
@Override
public void stop() {
stop(() -> {});
}
@Override
public void stop(Runnable callback) {
log.info("Stopping bookdrop folder monitor...");
running = false;
if (watchThread != null) {
watchThread.interrupt();
try {
watchThread.join(5000);
} catch (InterruptedException e) {
log.warn("Interrupted while waiting for watchThread to stop");
Thread.currentThread().interrupt();
}
}
if (watchService != null) {
try {
@@ -92,6 +106,17 @@ public class BookdropMonitoringService {
}
}
log.info("Stopped bookdrop folder monitor");
callback.run();
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return LIFECYCLE_PHASE;
}
public void pauseMonitoring() {
@@ -11,7 +11,6 @@ import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.PreDestroy;
import java.time.LocalDate;
import java.time.Year;
import java.time.YearMonth;
@@ -31,11 +30,7 @@ public class FilenamePatternExtractor {
private static final Pattern PATTERN = Pattern.compile("[,;&]");
private final BookdropFileRepository bookdropFileRepository;
private final BookdropMetadataHelper metadataHelper;
private final ExecutorService regexExecutor = Executors.newCachedThreadPool(runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
});
private final ExecutorService regexExecutor;
private static final int PREVIEW_FILE_LIMIT = 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(
BookdropFileEntity file,
@@ -17,7 +17,6 @@ import org.booklore.repository.EmailRecipientV2Repository;
import org.booklore.repository.UserEmailProviderPreferenceRepository;
import org.booklore.service.NotificationService;
import org.booklore.util.FileUtils;
import org.booklore.util.SecurityContextVirtualThread;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.AllArgsConstructor;
@@ -32,6 +31,7 @@ import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;
@Slf4j
@Service
@@ -45,6 +45,7 @@ public class SendEmailV2Service {
private final NotificationService notificationService;
private final AuthenticationService authenticationService;
private final AuditService auditService;
private final Executor taskExecutor;
public void emailBookQuick(Long bookId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
@@ -73,7 +74,7 @@ public class SendEmailV2Service {
String logMessage = "Email dispatch initiated for book: " + bookTitle + " to " + recipientEmail;
notificationService.sendMessage(Topic.LOG, LogNotification.info(logMessage));
log.info(logMessage);
SecurityContextVirtualThread.runWithSecurityContext(() -> {
taskExecutor.execute(() -> {
try {
sendEmail(emailProvider, recipientEmail, book, bookFile);
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.task.options.RescanLibraryContext;
import org.booklore.util.FileService;
import org.booklore.util.SecurityContextVirtualThread;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitialization;
import org.springframework.context.event.EventListener;
@@ -45,6 +44,7 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
@Slf4j
@@ -77,6 +77,7 @@ public class LibraryService {
private final AuthenticationService authenticationService;
private final UserRepository userRepository;
private final AuditService auditService;
private final Executor taskExecutor;
@Transactional
@EventListener(ApplicationReadyEvent.class)
@@ -209,7 +210,7 @@ public class LibraryService {
LibraryEntity lib = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
auditService.log(AuditAction.LIBRARY_SCANNED, "Library", libraryId, "Scanned library: " + lib.getName());
SecurityContextVirtualThread.runWithSecurityContext(() -> {
taskExecutor.execute(() -> {
if (!scanningLibraries.add(libraryId)) {
log.warn("Library {} is already being scanned, skipping duplicate rescan request", libraryId);
return;
@@ -367,7 +368,7 @@ public class LibraryService {
}
private void startBackgroundScan(long libraryId) {
SecurityContextVirtualThread.runWithSecurityContext(() -> {
taskExecutor.execute(() -> {
if (!scanningLibraries.add(libraryId)) {
log.warn("Library {} is already being scanned, skipping duplicate process request", libraryId);
return;
@@ -23,7 +23,6 @@ import org.booklore.service.metadata.writer.MetadataWriterFactory;
import org.booklore.util.BookCoverUtils;
import org.booklore.util.FileService;
import org.booklore.config.AppProperties;
import org.booklore.util.SecurityContextVirtualThread;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
@@ -33,6 +32,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
@@ -53,6 +53,7 @@ public class BookCoverService {
private final BookQueryService bookQueryService;
private final CoverImageGenerator coverImageGenerator;
private final MetadataWriterFactory metadataWriterFactory;
private final Executor taskExecutor;
private final TransactionTemplate transactionTemplate;
private record BookCoverInfo(Long id, String title) {
@@ -216,7 +217,7 @@ public class BookCoverService {
validateCoverFile(file);
byte[] coverImageBytes = extractBytesFromMultipartFile(file);
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) {
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) {
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.
*/
public void regenerateCovers(boolean missingOnly) {
SecurityContextVirtualThread.runWithSecurityContext(() -> {
taskExecutor.execute(() -> {
try {
List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream()
.filter(book -> !isCoverLocked(book))
@@ -1,11 +1,10 @@
package org.booklore.service.monitoring;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.Library;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.service.watcher.LibraryFileEventProcessor;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Service;
import java.io.IOException;
@@ -21,28 +20,62 @@ import java.util.stream.Stream;
@Slf4j
@Service
public class LibraryWatchService {
public class LibraryWatchService implements SmartLifecycle {
private static final int LIFECYCLE_PHASE = 20;
private final LibraryFileEventProcessor eventProcessor;
private final WatchService watchService;
private final ExecutorService registrationExecutor;
private WatchService watchService;
private ExecutorService registrationExecutor;
private final ConcurrentHashMap<Path, WatchEntry> watches = new ConcurrentHashMap<>();
private final Map<Long, Boolean> libraryWatchStatus = new ConcurrentHashMap<>();
private final Lock watchLock = new ReentrantLock();
private volatile boolean running;
private record WatchEntry(WatchKey key, long libraryId) {}
public LibraryWatchService(LibraryFileEventProcessor eventProcessor) throws IOException {
public LibraryWatchService(LibraryFileEventProcessor eventProcessor) {
this.eventProcessor = eventProcessor;
this.watchService = FileSystems.getDefault().newWatchService();
this.registrationExecutor = Executors.newSingleThreadExecutor(
Thread.ofVirtual().name("watch-registrar").factory());
}
@PostConstruct
@Override
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() {
@@ -285,15 +318,4 @@ public class LibraryWatchService {
log.warn("Timeout waiting for events to drain for {} paths", paths.size());
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.TaskStatus;
import org.booklore.task.tasks.Task;
import org.booklore.util.SecurityContextVirtualThread;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.TaskScheduler;
@@ -188,11 +187,8 @@ public class TaskService {
.taskType(taskType)
.status(TaskStatus.ACCEPTED)
.build();
SecurityContext securityContext = SecurityContextHolder.getContext();
taskExecutor.execute(() ->
SecurityContextVirtualThread.runWithSecurityContext(securityContext, () ->
executeAsyncTask(taskId, request, taskType)
)
);
return response;
}
@@ -13,10 +13,9 @@ import org.booklore.repository.LibraryRepository;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.library.LibraryProcessingService;
import org.booklore.util.FileUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Service;
import java.io.IOException;
@@ -29,9 +28,10 @@ import java.util.concurrent.*;
@Slf4j
@Service
@AllArgsConstructor
public class LibraryFileEventProcessor {
@RequiredArgsConstructor
public class LibraryFileEventProcessor implements SmartLifecycle {
private static final int LIFECYCLE_PHASE = 10;
private static final long DEBOUNCE_MS = 500L;
private static final long FOLDER_CREATE_DEBOUNCE_MS = 5000L;
private static final long PENDING_DELETION_GRACE_MS = 8000L;
@@ -47,16 +47,28 @@ public class LibraryFileEventProcessor {
private final LibraryProcessingService libraryProcessingService;
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<?>> pendingFolderCreates = new ConcurrentHashMap<>();
private final Set<Path> filesFromPendingFolder = ConcurrentHashMap.newKeySet();
private volatile boolean running;
private Thread workerThread;
@PostConstruct
public void init() {
Thread.ofVirtual().start(() -> {
@Override
public void 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.");
while (!Thread.currentThread().isInterrupted()) {
while (running && !Thread.currentThread().isInterrupted()) {
try {
handleEvent(eventQueue.take());
} 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) {
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) {
boolean inQueue = eventQueue.stream()
.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();
}
});
}
}
@@ -5,14 +5,18 @@ import org.booklore.model.dto.request.BookdropPatternExtractRequest;
import org.booklore.model.dto.response.BookdropPatternExtractResult;
import org.booklore.model.entity.BookdropFileEntity;
import org.booklore.repository.BookdropFileRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@@ -26,9 +30,17 @@ class FilenamePatternExtractorTest {
@Mock
private BookdropMetadataHelper metadataHelper;
@Spy
private ExecutorService regexExecutor = Executors.newVirtualThreadPerTaskExecutor();
@InjectMocks
private FilenamePatternExtractor extractor;
@AfterEach
void tearDown() {
regexExecutor.shutdownNow();
}
private BookdropFileEntity createFileEntity(Long id, String fileName) {
BookdropFileEntity entity = new BookdropFileEntity();
entity.setId(id);
@@ -10,11 +10,12 @@ import org.booklore.repository.EmailProviderV2Repository;
import org.booklore.repository.EmailRecipientV2Repository;
import org.booklore.repository.UserEmailProviderPreferenceRepository;
import org.booklore.service.NotificationService;
import org.booklore.service.audit.AuditService;
import org.booklore.util.FileUtils;
import org.booklore.util.SecurityContextVirtualThread;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
@@ -23,6 +24,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executor;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
@@ -48,11 +50,18 @@ class SendEmailV2ServiceTest {
@Mock
private AuthenticationService authenticationService;
@Mock
private AuditService auditService;
@Mock
private Executor taskExecutor;
@InjectMocks
private SendEmailV2Service sendEmailV2Service;
private BookLoreUser user;
private BookEntity book;
private BookFileEntity bookFile;
private EmailProviderV2Entity emailProvider;
private EmailRecipientV2Entity emailRecipient;
private UserEmailProviderPreferenceEntity preference;
@@ -68,7 +77,7 @@ class SendEmailV2ServiceTest {
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath("/library");
BookFileEntity bookFile = new BookFileEntity();
bookFile = new BookFileEntity();
bookFile.setFileName("test-book.epub");
bookFile.setFileSubPath("books");
bookFile.setBookFormat(true);
@@ -114,22 +123,19 @@ class SendEmailV2ServiceTest {
when(emailProviderRepository.findAccessibleProvider(100L, 1L)).thenReturn(Optional.of(emailProvider));
when(emailRecipientRepository.findDefaultEmailRecipientByUserId(1L)).thenReturn(Optional.of(emailRecipient));
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(invocation -> {
Runnable task = invocation.getArgument(0);
task.run();
return null;
});
doAnswer(invocation -> {
Runnable task = invocation.getArgument(0);
task.run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book)).thenReturn(Path.of("/library/books/test-book.epub"));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
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(notificationService, atLeastOnce()).sendMessage(any(), any());
}
verify(taskExecutor).execute(any(Runnable.class));
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
}
}
@@ -184,22 +190,19 @@ class SendEmailV2ServiceTest {
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(invocation -> {
Runnable task = invocation.getArgument(0);
task.run();
return null;
});
doAnswer(invocation -> {
Runnable task = invocation.getArgument(0);
task.run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book)).thenReturn(Path.of("/library/books/test-book.epub"));
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);
securityMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
}
verify(taskExecutor).execute(any(Runnable.class));
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
}
}
@@ -217,22 +220,19 @@ class SendEmailV2ServiceTest {
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(invocation -> {
Runnable task = invocation.getArgument(0);
task.run();
return null;
});
doAnswer(invocation -> {
Runnable task = invocation.getArgument(0);
task.run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book)).thenReturn(Path.of("/library/books/test-book.epub"));
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);
securityMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
}
verify(taskExecutor).execute(any(Runnable.class));
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
}
}
@@ -290,28 +290,25 @@ class SendEmailV2ServiceTest {
when(emailProviderRepository.findAccessibleProvider(100L, 1L)).thenReturn(Optional.of(emailProvider));
when(emailRecipientRepository.findDefaultEmailRecipientByUserId(1L)).thenReturn(Optional.of(emailRecipient));
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(invocation -> {
Runnable task = invocation.getArgument(0);
task.run();
return null;
});
doAnswer(invocation -> {
Runnable task = invocation.getArgument(0);
task.run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book))
.thenThrow(new IllegalStateException("Book file not found"));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile))
.thenThrow(new IllegalStateException("Book file not found"));
sendEmailV2Service.emailBookQuick(10L);
sendEmailV2Service.emailBookQuick(10L);
// Error is caught and logged, not rethrown
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
}
// Error is caught and logged, not rethrown
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
}
}
@Test
void emailBook_notificationSentBeforeVirtualThread() {
void emailBook_notificationSentBeforeAsyncExecution() {
SendBookByEmailRequest request = SendBookByEmailRequest.builder()
.bookId(10L)
.providerId(100L)
@@ -323,16 +320,17 @@ class SendEmailV2ServiceTest {
when(bookRepository.findByIdWithBookFiles(10L)).thenReturn(Optional.of(book));
when(emailRecipientRepository.findByIdAndUserId(200L, 1L)).thenReturn(Optional.of(emailRecipient));
try (MockedStatic<SecurityContextVirtualThread> securityMock = mockStatic(SecurityContextVirtualThread.class)) {
// Don't execute the runnable - just capture it
securityMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(invocation -> null);
// Don't execute the runnable - just capture it
doNothing().when(taskExecutor).execute(any(Runnable.class));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile)).thenReturn(Path.of("/library/books/test-book.epub"));
sendEmailV2Service.emailBook(request);
// Log notification is sent before the virtual thread starts
verify(notificationService).sendMessage(any(), any());
securityMock.verify(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)));
InOrder inOrder = inOrder(notificationService, taskExecutor);
inOrder.verify(notificationService).sendMessage(any(), any());
inOrder.verify(taskExecutor).execute(any(Runnable.class));
}
}
}
@@ -31,6 +31,7 @@ import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executor;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
@@ -63,6 +64,8 @@ class LibraryServiceIconTest {
private UserRepository userRepository;
@Mock
private AuditService auditService;
@Mock
private Executor taskExecutor;
@InjectMocks
private LibraryService libraryService;
@@ -17,7 +17,6 @@ import org.booklore.service.metadata.writer.MetadataWriter;
import org.booklore.service.metadata.writer.MetadataWriterFactory;
import org.booklore.service.file.FileFingerprint;
import org.booklore.util.FileService;
import org.booklore.util.SecurityContextVirtualThread;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -30,6 +29,7 @@ import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.util.*;
import java.util.concurrent.Executor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -49,6 +49,7 @@ class BookCoverServiceTest {
@Mock private CoverImageGenerator coverImageGenerator;
@Mock private MetadataWriterFactory metadataWriterFactory;
@Mock private TransactionTemplate transactionTemplate;
@Mock private Executor taskExecutor;
@InjectMocks
private BookCoverService service;
@@ -654,7 +655,7 @@ class BookCoverServiceTest {
class BulkRegenerateCoversForBooks {
@Test
void delegatesToVirtualThreadWithUnlockedBooks() {
void delegatesToAsyncExecutorWithUnlockedBooks() {
BookEntity unlocked = buildBook(1L, false);
unlocked.setBookFiles(List.of(BookFileEntity.builder().bookType(BookFileType.EPUB).isBookFormat(true).build()));
unlocked.setLibrary(LibraryEntity.builder().build());
@@ -663,17 +664,14 @@ class BookCoverServiceTest {
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
.thenReturn(List.of(unlocked, locked));
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
});
doAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
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 {
@Test
void delegatesToVirtualThreadWithUnlockedBooks() {
void delegatesToAsyncExecutorWithUnlockedBooks() {
BookEntity unlocked = buildBook(1L, false);
BookEntity locked = buildBook(2L, true);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
.thenReturn(List.of(unlocked, locked));
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
});
doAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
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.getBytes()).thenReturn(new byte[]{1, 2, 3});
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
});
doAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
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(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
});
doAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
service.regenerateCovers(false);
service.regenerateCovers(false);
verify(bookRepository).save(book);
assertThat(book.getMetadata().getCoverUpdatedOn()).isNotNull();
}
verify(bookRepository).save(book);
assertThat(book.getMetadata().getCoverUpdatedOn()).isNotNull();
}
@Test
@@ -780,17 +769,14 @@ class BookCoverServiceTest {
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(locked));
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
});
doAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
service.regenerateCovers(false);
service.regenerateCovers(false);
verify(bookRepository, never()).save(any());
}
verify(bookRepository, never()).save(any());
}
@Test
@@ -821,19 +807,16 @@ class BookCoverServiceTest {
when(processor.generateCover(withoutCover)).thenReturn(true);
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
});
doAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
service.regenerateCovers(true);
service.regenerateCovers(true);
verify(transactionTemplate, times(1)).execute(any());
verify(bookRepository).save(withoutCover);
verify(bookRepository, never()).findById(1L);
}
verify(transactionTemplate, times(1)).execute(any());
verify(bookRepository).save(withoutCover);
verify(bookRepository, never()).findById(1L);
}
@Test
@@ -843,17 +826,14 @@ class BookCoverServiceTest {
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(book));
try (MockedStatic<SecurityContextVirtualThread> secMock = mockStatic(SecurityContextVirtualThread.class)) {
secMock.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
});
doAnswer(inv -> {
inv.<Runnable>getArgument(0).run();
return null;
}).when(taskExecutor).execute(any(Runnable.class));
service.regenerateCovers(false);
service.regenerateCovers(false);
verify(transactionTemplate, never()).execute(any());
}
verify(transactionTemplate, never()).execute(any());
}
}
@@ -30,12 +30,13 @@ class LibraryWatchServiceTest {
void setup() throws Exception {
processor = mock(LibraryFileEventProcessor.class);
service = new LibraryWatchService(processor);
service.start();
}
@AfterEach
void teardown() {
try {
service.shutdown();
service.stop();
} catch (Exception ignored) {}
}
@@ -74,13 +74,13 @@ class LibraryFileEventProcessorTest {
when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq(tempDir.toString())))
.thenReturn(libraryPath);
// Start the event processing thread (normally done by @PostConstruct)
processor.init();
// Start the event processing thread (normally done by SmartLifecycle)
processor.start();
}
@AfterEach
void tearDown() throws Exception {
processor.shutdown();
processor.stop();
mocks.close();
}
@@ -392,9 +392,9 @@ class LibraryFileEventProcessorTest {
class Shutdown {
@Test
void shutdownCompletesCleanly() {
// Just verify shutdown doesn't throw
processor.shutdown();
void stopCompletesCleanly() {
// Just verify stop doesn't throw
processor.stop();
// Reinitialize so tearDown's shutdown doesn't fail
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());
}
}