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:
+12
@@ -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;
|
||||
|
||||
+49
-69
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -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) {}
|
||||
}
|
||||
|
||||
|
||||
+6
-6
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user