add library health indicator in sidebar (#3005) (#3066)

This commit is contained in:
ACX
2026-02-27 01:32:27 -07:00
committed by GitHub
parent c67291cc7f
commit f9132fea12
16 changed files with 414 additions and 4 deletions
@@ -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);
}
}
@@ -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;
}
}
@@ -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()}},
]
});
+3
View File
@@ -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;
}
});
@@ -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<typeof vi.fn>;
let wsSubject: Subject<IMessage>;
beforeEach(() => {
httpGetSpy = vi.fn().mockReturnValue(of({}));
wsSubject = new Subject<IMessage>();
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);
});
});
@@ -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<Record<number, boolean>>({});
initialize(): void {
this.http.get<Record<number, boolean>>(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<boolean> {
return this.healthSubject.pipe(
map(health => health[libraryId] === false),
distinctUntilChanged()
);
}
}
@@ -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),
})),
},
];
@@ -53,6 +53,13 @@
tabindex="0"
pRipple
>
@if (item.unhealthy$ | async) {
<span
class="library-health-dot"
[pTooltip]="'common.libraryPathInaccessible' | transloco"
tooltipPosition="right"
></span>
}
<app-icon-display
[icon]="getIconSelection()"
iconClass="layout-menuitem-icon"
@@ -66,6 +66,7 @@
width: 100%;
}
.menu-item-text {
width: 100%;
overflow: hidden;
@@ -92,3 +93,24 @@
.submenu-container {
overflow: hidden;
}
.library-health-dot {
display: inline-block;
flex-shrink: 0;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ef4444;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
}
50% {
opacity: 0.85;
box-shadow: 0 0 0 5px rgba(239, 68, 68, 0);
}
}
@@ -12,8 +12,10 @@ import {UserService} from '../../../../features/settings/user-management/user.se
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
import {BookDialogHelperService} from '../../../../features/book/components/book-browser/book-dialog-helper.service';
import {IconDisplayComponent} from '../../../components/icon-display/icon-display.component';
import {Tooltip} from 'primeng/tooltip';
import {MenuItem} from 'primeng/api';
import {IconSelection} from '../../../service/icon-picker.service';
import {TranslocoPipe} from '@jsverse/transloco';
@Component({
selector: '[app-menuitem]',
@@ -26,7 +28,9 @@ import {IconSelection} from '../../../service/icon-picker.service';
AsyncPipe,
Button,
Menu,
IconDisplayComponent
IconDisplayComponent,
Tooltip,
TranslocoPipe
],
animations: [
trigger('children', [
+2 -1
View File
@@ -21,5 +21,6 @@
"select": "Select",
"dismiss": "Dismiss",
"discard": "Discard",
"review": "Review"
"review": "Review",
"libraryPathInaccessible": "Library path inaccessible"
}
+2 -1
View File
@@ -21,5 +21,6 @@
"select": "Seleccionar",
"dismiss": "Descartar",
"discard": "Descartar",
"review": "Revisar"
"review": "Revisar",
"libraryPathInaccessible": "Ruta de biblioteca inaccesible"
}