From f9132fea12136e9dea90b12e6c06c4e5befad3d1 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Fri, 27 Feb 2026 01:32:27 -0700 Subject: [PATCH] add library health indicator in sidebar (#3005) (#3066) --- .../controller/LibraryController.java | 9 + .../model/websocket/LibraryHealthPayload.java | 5 + .../org/booklore/model/websocket/Topic.java | 3 +- .../repository/LibraryPathRepository.java | 5 + .../service/library/LibraryHealthService.java | 62 +++++++ .../library/LibraryHealthServiceTest.java | 161 ++++++++++++++++++ booklore-ui/src/app/app.component.spec.ts | 2 + booklore-ui/src/app/app.component.ts | 3 + .../service/library-health.service.spec.ts | 91 ++++++++++ .../book/service/library-health.service.ts | 33 ++++ .../layout-menu/app.menu.component.ts | 3 + .../layout-menu/app.menuitem.component.html | 7 + .../layout-menu/app.menuitem.component.scss | 22 +++ .../layout-menu/app.menuitem.component.ts | 6 +- booklore-ui/src/i18n/en/common.json | 3 +- booklore-ui/src/i18n/es/common.json | 3 +- 16 files changed, 414 insertions(+), 4 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/model/websocket/LibraryHealthPayload.java create mode 100644 booklore-api/src/main/java/org/booklore/service/library/LibraryHealthService.java create mode 100644 booklore-api/src/test/java/org/booklore/service/library/LibraryHealthServiceTest.java create mode 100644 booklore-ui/src/app/features/book/service/library-health.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/library-health.service.ts diff --git a/booklore-api/src/main/java/org/booklore/controller/LibraryController.java b/booklore-api/src/main/java/org/booklore/controller/LibraryController.java index 8013385c4..53640ddc0 100644 --- a/booklore-api/src/main/java/org/booklore/controller/LibraryController.java +++ b/booklore-api/src/main/java/org/booklore/controller/LibraryController.java @@ -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> 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"), diff --git a/booklore-api/src/main/java/org/booklore/model/websocket/LibraryHealthPayload.java b/booklore-api/src/main/java/org/booklore/model/websocket/LibraryHealthPayload.java new file mode 100644 index 000000000..b2aeb030e --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/websocket/LibraryHealthPayload.java @@ -0,0 +1,5 @@ +package org.booklore.model.websocket; + +import java.util.Map; + +public record LibraryHealthPayload(Map libraryHealth) {} diff --git a/booklore-api/src/main/java/org/booklore/model/websocket/Topic.java b/booklore-api/src/main/java/org/booklore/model/websocket/Topic.java index 0370187f1..7858d7615 100644 --- a/booklore-api/src/main/java/org/booklore/model/websocket/Topic.java +++ b/booklore-api/src/main/java/org/booklore/model/websocket/Topic.java @@ -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; diff --git a/booklore-api/src/main/java/org/booklore/repository/LibraryPathRepository.java b/booklore-api/src/main/java/org/booklore/repository/LibraryPathRepository.java index 51c170945..8fe5dd85c 100644 --- a/booklore-api/src/main/java/org/booklore/repository/LibraryPathRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/LibraryPathRepository.java @@ -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 { Optional findByLibraryIdAndPath(Long libraryId, String path); + + @Query("SELECT lp FROM LibraryPathEntity lp JOIN FETCH lp.library") + List findAllWithLibrary(); } diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryHealthService.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryHealthService.java new file mode 100644 index 000000000..02b1d19f0 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryHealthService.java @@ -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 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 getCurrentHealth() { + return Map.copyOf(previousHealth); + } + + private Map 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); + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/library/LibraryHealthServiceTest.java b/booklore-api/src/test/java/org/booklore/service/library/LibraryHealthServiceTest.java new file mode 100644 index 000000000..b2ef2f854 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/library/LibraryHealthServiceTest.java @@ -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 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 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 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 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 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; + } +} diff --git a/booklore-ui/src/app/app.component.spec.ts b/booklore-ui/src/app/app.component.spec.ts index 5b912edbd..bb4e26344 100644 --- a/booklore-ui/src/app/app.component.spec.ts +++ b/booklore-ui/src/app/app.component.spec.ts @@ -11,6 +11,7 @@ import {MetadataProgressService} from './shared/service/metadata-progress.servic import {BookdropFileService} from './features/bookdrop/service/bookdrop-file.service'; import {TaskService} from './features/settings/task-management/task.service'; import {LibraryService} from './features/book/service/library.service'; +import {LibraryHealthService} from './features/book/service/library-health.service'; import {LibraryLoadingService} from './features/library-creator/library-loading.service'; import {TranslocoTestingModule} from '@jsverse/transloco'; @@ -34,6 +35,7 @@ describe('AppComponent offline detection', () => { {provide: BookdropFileService, useValue: {}}, {provide: TaskService, useValue: {}}, {provide: LibraryService, useValue: {largeLibraryLoading$: of({isLoading: false, expectedCount: 0})}}, + {provide: LibraryHealthService, useValue: {initialize: vi.fn()}}, {provide: LibraryLoadingService, useValue: {hide: vi.fn()}}, ] }); diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index 2409a08da..32697e4b0 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -15,6 +15,7 @@ import {BookdropFileNotification, BookdropFileService} from './features/bookdrop import {Subscription} from 'rxjs'; import {TaskProgressPayload, TaskService} from './features/settings/task-management/task.service'; import {LibraryService} from './features/book/service/library.service'; +import {LibraryHealthService} from './features/book/service/library-health.service'; import {LibraryLoadingService} from './features/library-creator/library-loading.service'; import {scan, withLatestFrom} from 'rxjs/operators'; @@ -41,6 +42,7 @@ export class AppComponent implements OnInit, OnDestroy { private bookdropFileService = inject(BookdropFileService); private taskService = inject(TaskService); private libraryService = inject(LibraryService); + private libraryHealthService = inject(LibraryHealthService); private libraryLoadingService = inject(LibraryLoadingService); ngOnInit(): void { @@ -51,6 +53,7 @@ export class AppComponent implements OnInit, OnDestroy { this.loading = !ready; if (ready && !this.subscriptionsInitialized) { this.setupWebSocketSubscriptions(); + this.libraryHealthService.initialize(); this.subscriptionsInitialized = true; } }); diff --git a/booklore-ui/src/app/features/book/service/library-health.service.spec.ts b/booklore-ui/src/app/features/book/service/library-health.service.spec.ts new file mode 100644 index 000000000..7531a3b9d --- /dev/null +++ b/booklore-ui/src/app/features/book/service/library-health.service.spec.ts @@ -0,0 +1,91 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {LibraryHealthService} from './library-health.service'; +import {HttpClient} from '@angular/common/http'; +import {RxStompService} from '../../../shared/websocket/rx-stomp.service'; +import {of, Subject} from 'rxjs'; +import {IMessage} from '@stomp/rx-stomp'; + +describe('LibraryHealthService', () => { + let service: LibraryHealthService; + let httpGetSpy: ReturnType; + let wsSubject: Subject; + + beforeEach(() => { + httpGetSpy = vi.fn().mockReturnValue(of({})); + wsSubject = new Subject(); + + TestBed.configureTestingModule({ + providers: [ + LibraryHealthService, + {provide: HttpClient, useValue: {get: httpGetSpy}}, + {provide: RxStompService, useValue: {watch: vi.fn(() => wsSubject.asObservable())}}, + ] + }); + + service = TestBed.inject(LibraryHealthService); + }); + + it('should fetch initial health on initialize', () => { + httpGetSpy.mockReturnValue(of({1: true, 2: false})); + service.initialize(); + + expect(httpGetSpy).toHaveBeenCalled(); + }); + + it('should emit unhealthy for a library with false health', () => { + httpGetSpy.mockReturnValue(of({1: true, 2: false})); + service.initialize(); + + const results: boolean[] = []; + service.isUnhealthy$(2).subscribe(v => results.push(v)); + + expect(results).toContain(true); + }); + + it('should emit healthy for a library with true health', () => { + httpGetSpy.mockReturnValue(of({1: true})); + service.initialize(); + + const results: boolean[] = []; + service.isUnhealthy$(1).subscribe(v => results.push(v)); + + expect(results[results.length - 1]).toBe(false); + }); + + it('should emit false for unknown library', () => { + httpGetSpy.mockReturnValue(of({})); + service.initialize(); + + const results: boolean[] = []; + service.isUnhealthy$(99).subscribe(v => results.push(v)); + + expect(results[results.length - 1]).toBe(false); + }); + + it('should update state from websocket messages', () => { + httpGetSpy.mockReturnValue(of({1: true})); + service.initialize(); + + const results: boolean[] = []; + service.isUnhealthy$(1).subscribe(v => results.push(v)); + + wsSubject.next({body: JSON.stringify({libraryHealth: {1: false}})} as IMessage); + + expect(results[results.length - 1]).toBe(true); + }); + + it('should use distinctUntilChanged to avoid duplicate emissions', () => { + httpGetSpy.mockReturnValue(of({1: true})); + service.initialize(); + + const results: boolean[] = []; + service.isUnhealthy$(1).subscribe(v => results.push(v)); + + // Same state again via websocket + wsSubject.next({body: JSON.stringify({libraryHealth: {1: true}})} as IMessage); + wsSubject.next({body: JSON.stringify({libraryHealth: {1: true}})} as IMessage); + + expect(results.length).toBe(1); + }); +}); diff --git a/booklore-ui/src/app/features/book/service/library-health.service.ts b/booklore-ui/src/app/features/book/service/library-health.service.ts new file mode 100644 index 000000000..3f700a7b7 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/library-health.service.ts @@ -0,0 +1,33 @@ +import {inject, Injectable} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {BehaviorSubject, Observable} from 'rxjs'; +import {distinctUntilChanged, map} from 'rxjs/operators'; +import {RxStompService} from '../../../shared/websocket/rx-stomp.service'; +import {API_CONFIG} from '../../../core/config/api-config'; + +@Injectable({providedIn: 'root'}) +export class LibraryHealthService { + private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`; + private http = inject(HttpClient); + private rxStompService = inject(RxStompService); + + private healthSubject = new BehaviorSubject>({}); + + initialize(): void { + this.http.get>(this.url).subscribe(health => { + this.healthSubject.next(health); + }); + + this.rxStompService.watch('/topic/library-health').subscribe(msg => { + const payload = JSON.parse(msg.body); + this.healthSubject.next(payload.libraryHealth); + }); + } + + isUnhealthy$(libraryId: number): Observable { + return this.healthSubject.pipe( + map(health => health[libraryId] === false), + distinctUntilChanged() + ); + } +} diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.ts b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.ts index 79b8739b3..c3119c31b 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.ts +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.ts @@ -3,6 +3,7 @@ import {AppMenuitemComponent} from './app.menuitem.component'; import {AsyncPipe} from '@angular/common'; import {MenuModule} from 'primeng/menu'; import {LibraryService} from '../../../../features/book/service/library.service'; +import {LibraryHealthService} from '../../../../features/book/service/library-health.service'; import {combineLatest, Observable, of} from 'rxjs'; import {filter, map} from 'rxjs/operators'; import {ShelfService} from '../../../../features/book/service/shelf.service'; @@ -39,6 +40,7 @@ export class AppMenuComponent implements OnInit { dynamicDialogRef: DynamicDialogRef | undefined | null; private libraryService = inject(LibraryService); + private libraryHealthService = inject(LibraryHealthService); private shelfService = inject(ShelfService); private bookService = inject(BookService); private versionService = inject(VersionService); @@ -156,6 +158,7 @@ export class AppMenuComponent implements OnInit { iconType: (library.iconType || undefined) as 'PRIME_NG' | 'CUSTOM_SVG' | undefined, routerLink: [`/library/${library.id}/books`], bookCount$: this.libraryService.getBookCount(library.id ?? 0), + unhealthy$: this.libraryHealthService.isUnhealthy$(library.id ?? 0), })), }, ]; diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.html b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.html index 22185db5e..c2ce33948 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.html +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.html @@ -53,6 +53,13 @@ tabindex="0" pRipple > + @if (item.unhealthy$ | async) { + + }