@@ -4,6 +4,7 @@ import org.booklore.config.security.annotation.CheckLibraryAccess;
|
||||
import org.booklore.model.dto.Book;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.dto.request.CreateLibraryRequest;
|
||||
import org.booklore.service.library.LibraryHealthService;
|
||||
import org.booklore.service.library.LibraryService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -26,6 +27,7 @@ import java.util.Map;
|
||||
public class LibraryController {
|
||||
|
||||
private final LibraryService libraryService;
|
||||
private final LibraryHealthService libraryHealthService;
|
||||
|
||||
@Operation(summary = "Get all libraries", description = "Retrieve a list of all libraries.")
|
||||
@ApiResponse(responseCode = "200", description = "Libraries returned successfully")
|
||||
@@ -34,6 +36,13 @@ public class LibraryController {
|
||||
return ResponseEntity.ok(libraryService.getLibraries());
|
||||
}
|
||||
|
||||
@Operation(summary = "Get library health", description = "Check accessibility of all library paths.")
|
||||
@ApiResponse(responseCode = "200", description = "Library health returned successfully")
|
||||
@GetMapping("/health")
|
||||
public ResponseEntity<Map<Long, Boolean>> getLibraryHealth() {
|
||||
return ResponseEntity.ok(libraryHealthService.getCurrentHealth());
|
||||
}
|
||||
|
||||
@Operation(summary = "Get a library by ID", description = "Retrieve details of a specific library by its ID.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Library details returned successfully"),
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.booklore.model.websocket;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record LibraryHealthPayload(Map<Long, Boolean> libraryHealth) {}
|
||||
@@ -15,7 +15,8 @@ public enum Topic {
|
||||
BOOK_METADATA_BATCH_PROGRESS("/queue/book-metadata-batch-progress"),
|
||||
BOOKDROP_FILE("/queue/bookdrop-file"),
|
||||
LOG("/queue/log"),
|
||||
TASK_PROGRESS("/queue/task-progress");
|
||||
TASK_PROGRESS("/queue/task-progress"),
|
||||
LIBRARY_HEALTH("/topic/library-health");
|
||||
|
||||
private final String path;
|
||||
|
||||
|
||||
@@ -2,11 +2,16 @@ package org.booklore.repository;
|
||||
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface LibraryPathRepository extends JpaRepository<LibraryPathEntity, Long> {
|
||||
Optional<LibraryPathEntity> findByLibraryIdAndPath(Long libraryId, String path);
|
||||
|
||||
@Query("SELECT lp FROM LibraryPathEntity lp JOIN FETCH lp.library")
|
||||
List<LibraryPathEntity> findAllWithLibrary();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.booklore.service.library;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.websocket.LibraryHealthPayload;
|
||||
import org.booklore.model.websocket.Topic;
|
||||
import org.booklore.repository.LibraryPathRepository;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class LibraryHealthService {
|
||||
|
||||
private final LibraryPathRepository libraryPathRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
private final ConcurrentHashMap<Long, Boolean> previousHealth = new ConcurrentHashMap<>();
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
var health = checkHealth();
|
||||
previousHealth.putAll(health);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 30, timeUnit = TimeUnit.SECONDS)
|
||||
public void checkAndBroadcast() {
|
||||
var health = checkHealth();
|
||||
if (!health.equals(previousHealth)) {
|
||||
previousHealth.clear();
|
||||
previousHealth.putAll(health);
|
||||
messagingTemplate.convertAndSend(Topic.LIBRARY_HEALTH.getPath(), new LibraryHealthPayload(health));
|
||||
}
|
||||
}
|
||||
|
||||
public Map<Long, Boolean> getCurrentHealth() {
|
||||
return Map.copyOf(previousHealth);
|
||||
}
|
||||
|
||||
private Map<Long, Boolean> checkHealth() {
|
||||
return libraryPathRepository.findAllWithLibrary().stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
lp -> lp.getLibrary().getId(),
|
||||
Collectors.reducing(true, this::isPathAccessible, Boolean::logicalAnd)
|
||||
));
|
||||
}
|
||||
|
||||
private boolean isPathAccessible(LibraryPathEntity libraryPath) {
|
||||
var path = Path.of(libraryPath.getPath());
|
||||
return Files.exists(path) && Files.isReadable(path);
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package org.booklore.service.library;
|
||||
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.websocket.LibraryHealthPayload;
|
||||
import org.booklore.model.websocket.Topic;
|
||||
import org.booklore.repository.LibraryPathRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class LibraryHealthServiceTest {
|
||||
|
||||
@Mock
|
||||
private LibraryPathRepository libraryPathRepository;
|
||||
|
||||
@Mock
|
||||
private SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
private LibraryHealthService libraryHealthService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of());
|
||||
libraryHealthService = new LibraryHealthService(libraryPathRepository, messagingTemplate);
|
||||
libraryHealthService.init();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReportHealthyWhenAllPathsAccessible() {
|
||||
Path validPath = tempDir.resolve("books");
|
||||
validPath.toFile().mkdirs();
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString())
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
Map<Long, Boolean> health = libraryHealthService.getCurrentHealth();
|
||||
assertThat(health).containsEntry(1L, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReportUnhealthyWhenPathDoesNotExist() {
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, "/nonexistent/path/that/does/not/exist")
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
Map<Long, Boolean> health = libraryHealthService.getCurrentHealth();
|
||||
assertThat(health).containsEntry(1L, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReportUnhealthyWhenAnyPathIsDown() {
|
||||
Path validPath = tempDir.resolve("books");
|
||||
validPath.toFile().mkdirs();
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString()),
|
||||
createLibraryPath(1L, "/nonexistent/path")
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
Map<Long, Boolean> health = libraryHealthService.getCurrentHealth();
|
||||
assertThat(health).containsEntry(1L, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTrackMultipleLibrariesIndependently() {
|
||||
Path validPath = tempDir.resolve("lib1");
|
||||
validPath.toFile().mkdirs();
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString()),
|
||||
createLibraryPath(2L, "/nonexistent/path")
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
Map<Long, Boolean> health = libraryHealthService.getCurrentHealth();
|
||||
assertThat(health).containsEntry(1L, true);
|
||||
assertThat(health).containsEntry(2L, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldBroadcastOnlyWhenStateChanges() {
|
||||
Path validPath = tempDir.resolve("books");
|
||||
validPath.toFile().mkdirs();
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString())
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
verify(messagingTemplate, times(1)).convertAndSend(eq(Topic.LIBRARY_HEALTH.getPath()), any(LibraryHealthPayload.class));
|
||||
|
||||
// Same state, should not broadcast again
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
verify(messagingTemplate, times(1)).convertAndSend(eq(Topic.LIBRARY_HEALTH.getPath()), any(LibraryHealthPayload.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldBroadcastWhenStateChangesFromHealthyToUnhealthy() throws Exception {
|
||||
Path validPath = tempDir.resolve("books");
|
||||
Files.createDirectories(validPath);
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString())
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
verify(messagingTemplate, times(1)).convertAndSend(eq(Topic.LIBRARY_HEALTH.getPath()), any(LibraryHealthPayload.class));
|
||||
|
||||
// Path disappears
|
||||
Files.delete(validPath);
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
ArgumentCaptor<LibraryHealthPayload> captor = ArgumentCaptor.forClass(LibraryHealthPayload.class);
|
||||
verify(messagingTemplate, times(2)).convertAndSend(eq(Topic.LIBRARY_HEALTH.getPath()), captor.capture());
|
||||
assertThat(captor.getValue().libraryHealth()).containsEntry(1L, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnEmptyMapWhenNoLibraries() {
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of());
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
assertThat(libraryHealthService.getCurrentHealth()).isEmpty();
|
||||
}
|
||||
|
||||
private LibraryPathEntity createLibraryPath(Long libraryId, String path) {
|
||||
var library = new LibraryEntity();
|
||||
library.setId(libraryId);
|
||||
|
||||
var libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setLibrary(library);
|
||||
libraryPath.setPath(path);
|
||||
return libraryPath;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user