diff --git a/frontend/src/app/app.component.spec.ts b/frontend/src/app/app.component.spec.ts index 0038a648f..528740403 100644 --- a/frontend/src/app/app.component.spec.ts +++ b/frontend/src/app/app.component.spec.ts @@ -44,12 +44,12 @@ describe("AppComponent", () => { }; let bookdropFileService: { handleIncomingFile: ReturnType }; let taskService: { handleTaskProgress: ReturnType }; - let libraryHealthService: { initialize: ReturnType }; + let libraryHealthService: { initWebsocket: ReturnType, fetchHealth: ReturnType }; let libraryLoadingService: { showBookLoadingProgress: ReturnType; hide: ReturnType; }; - let authService: { forceLogout: ReturnType }; + let authService: { forceLogout: ReturnType, isAuthenticated: ReturnType }; let libraryService: { largeLibraryLoading: ReturnType; setLargeLibraryLoading: ReturnType; @@ -62,7 +62,7 @@ describe("AppComponent", () => { } function configureComponent( - authReady = true, + auth = { ready: true, authenticated: true }, largeLibraryLoading = { isLoading: false, expectedCount: 0 }, ): void { topics = new Map(); @@ -82,12 +82,12 @@ describe("AppComponent", () => { metadataProgressService = { handleIncomingProgress: vi.fn() }; bookdropFileService = { handleIncomingFile: vi.fn() }; taskService = { handleTaskProgress: vi.fn() }; - libraryHealthService = { initialize: vi.fn() }; + libraryHealthService = { initWebsocket: vi.fn(), fetchHealth: vi.fn() }; libraryLoadingService = { showBookLoadingProgress: vi.fn(), hide: vi.fn(), }; - authService = { forceLogout: vi.fn() }; + authService = { forceLogout: vi.fn(), isAuthenticated: signal(auth.authenticated) }; libraryService = { largeLibraryLoading: signal(largeLibraryLoading), setLargeLibraryLoading: vi.fn(), @@ -98,7 +98,7 @@ describe("AppComponent", () => { providers: [ { provide: AuthInitializationService, - useValue: { initialized: signal(authReady) }, + useValue: { initialized: signal(auth.ready) }, }, { provide: RxStompService, useValue: rxStompService }, { provide: BookService, useValue: bookService }, @@ -135,18 +135,27 @@ describe("AppComponent", () => { }); it("boots the websocket wiring when auth initialization is ready", () => { - configureComponent(true); + configureComponent(); expect(component.loading).toBe(false); - expect(libraryHealthService.initialize).toHaveBeenCalledOnce(); + expect(libraryHealthService.initWebsocket).toHaveBeenCalledOnce(); + expect(libraryHealthService.fetchHealth).toHaveBeenCalledOnce(); expect(rxStompService.watch).toHaveBeenCalledWith("/user/queue/book-add"); expect(rxStompService.watch).toHaveBeenCalledWith( "/user/queue/session-revoked", ); }); + it("boots the websocket wiring but don't fetch library health when not authenticated", () => { + configureComponent({ ready: true, authenticated: false }); + + expect(component.loading).toBe(false); + expect(libraryHealthService.initWebsocket).toHaveBeenCalledOnce(); + expect(libraryHealthService.fetchHealth).not.toHaveBeenCalled(); + }); + it("routes websocket book notifications through the large library loading branch", () => { - configureComponent(true, { isLoading: true, expectedCount: 2 }); + configureComponent({ ready: true, authenticated: true }, { isLoading: true, expectedCount: 2 }); topics .get("/user/queue/book-add") @@ -169,7 +178,7 @@ describe("AppComponent", () => { }); it("forwards websocket updates to the matching root services", () => { - configureComponent(true); + configureComponent(); topics .get("/user/queue/book-update") @@ -226,7 +235,7 @@ describe("AppComponent", () => { }); it("forces logout when the session is revoked", () => { - configureComponent(true); + configureComponent(); topics.get("/user/queue/session-revoked")?.next({ body: "" }); @@ -234,7 +243,7 @@ describe("AppComponent", () => { }); it("unsubscribes and hides the loading overlay when destroyed", () => { - configureComponent(true); + configureComponent(); component.ngOnDestroy(); diff --git a/frontend/src/app/app.component.ts b/frontend/src/app/app.component.ts index f5f65d9e5..01de92928 100644 --- a/frontend/src/app/app.component.ts +++ b/frontend/src/app/app.component.ts @@ -52,11 +52,19 @@ export class AppComponent implements OnInit, OnDestroy { if (ready && !this.subscriptionsInitialized) { this.setupWebSocketSubscriptions(); - this.libraryHealthService.initialize(); + this.libraryHealthService.initWebsocket(); this.subscriptionsInitialized = true; } }); + private readonly authenticatedEffect = effect(() => { + const authInitialized = this.authInit.initialized(); + const isAuthenticated = this.authService.isAuthenticated(); + if (authInitialized && isAuthenticated) { + this.libraryHealthService.fetchHealth(); + } + }) + ngOnInit(): void { window.addEventListener('online', this.onOnline); window.addEventListener('offline', this.onOffline); diff --git a/frontend/src/app/features/book/service/library-health.service.spec.ts b/frontend/src/app/features/book/service/library-health.service.spec.ts index 127413908..6d7baa86e 100644 --- a/frontend/src/app/features/book/service/library-health.service.spec.ts +++ b/frontend/src/app/features/book/service/library-health.service.spec.ts @@ -31,16 +31,16 @@ describe('LibraryHealthService', () => { service = TestBed.inject(LibraryHealthService); }); - async function initializeService(): Promise { + async function fetchHealth(): Promise { const fetchQuerySpy = vi.spyOn(queryClient, 'fetchQuery'); - service.initialize(); + service.fetchHealth(); await fetchQuerySpy.mock.results[0]?.value; } - it('fetches initial health on initialize', async () => { + it('fetches health', async () => { httpGetSpy.mockReturnValue(of({1: true, 2: false})); - await initializeService(); + await fetchHealth(); expect(httpGetSpy).toHaveBeenCalledOnce(); expect(service.health()).toEqual({1: true, 2: false}); @@ -49,7 +49,7 @@ describe('LibraryHealthService', () => { it('reports unhealthy for a library with false health', async () => { httpGetSpy.mockReturnValue(of({1: true, 2: false})); - await initializeService(); + await fetchHealth(); expect(service.isUnhealthy(2)).toBe(true); }); @@ -57,7 +57,7 @@ describe('LibraryHealthService', () => { it('reports healthy for a library with true health', async () => { httpGetSpy.mockReturnValue(of({1: true})); - await initializeService(); + await fetchHealth(); expect(service.isUnhealthy(1)).toBe(false); }); @@ -65,15 +65,13 @@ describe('LibraryHealthService', () => { it('reports false for an unknown library', async () => { httpGetSpy.mockReturnValue(of({})); - await initializeService(); + await fetchHealth(); expect(service.isUnhealthy(99)).toBe(false); }); it('updates state from websocket messages', async () => { - httpGetSpy.mockReturnValue(of({1: true})); - - await initializeService(); + service.initWebsocket(); wsSubject.next({body: JSON.stringify({libraryHealth: {1: false}})} as IMessage); expect(service.isUnhealthy(1)).toBe(true); diff --git a/frontend/src/app/features/book/service/library-health.service.ts b/frontend/src/app/features/book/service/library-health.service.ts index 0f5fa182e..6d9313f8a 100644 --- a/frontend/src/app/features/book/service/library-health.service.ts +++ b/frontend/src/app/features/book/service/library-health.service.ts @@ -1,4 +1,5 @@ -import {computed, inject, Injectable} from '@angular/core'; +import {computed, inject, Injectable, DestroyRef} from '@angular/core'; +import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {HttpClient} from '@angular/common/http'; import {lastValueFrom} from 'rxjs'; import {RxStompService} from '../../../shared/websocket/rx-stomp.service'; @@ -13,6 +14,9 @@ export class LibraryHealthService { private http = inject(HttpClient); private rxStompService = inject(RxStompService); private queryClient = inject(QueryClient); + private destroyRef = inject(DestroyRef); + + private socketInitialized = false; private healthQuery = injectQuery(() => ({ ...this.getHealthQueryOptions(), @@ -28,13 +32,20 @@ export class LibraryHealthService { }); } - initialize(): void { + fetchHealth(): void { void this.queryClient.fetchQuery(this.getHealthQueryOptions()); + } - this.rxStompService.watch('/topic/library-health').subscribe(msg => { - const payload = JSON.parse(msg.body); - this.queryClient.setQueryData(LIBRARY_HEALTH_QUERY_KEY, payload.libraryHealth); - }); + initWebsocket(): void { + if (this.socketInitialized) return; + + this.rxStompService.watch('/topic/library-health') + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(msg => { + const payload = JSON.parse(msg.body); + this.queryClient.setQueryData(LIBRARY_HEALTH_QUERY_KEY, payload.libraryHealth); + }); + this.socketInitialized = true; } isUnhealthy(libraryId: number): boolean { diff --git a/frontend/src/app/shared/service/auth.service.ts b/frontend/src/app/shared/service/auth.service.ts index 8ae642b79..b12c30db7 100644 --- a/frontend/src/app/shared/service/auth.service.ts +++ b/frontend/src/app/shared/service/auth.service.ts @@ -1,4 +1,4 @@ -import {inject, Injectable, Injector, signal} from '@angular/core'; +import {computed, inject, Injectable, Injector, signal} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable, tap} from 'rxjs'; import {RxStompService} from '../websocket/rx-stomp.service'; @@ -22,6 +22,7 @@ export class AuthService { private postLoginInitializer = inject(PostLoginInitializerService); readonly token = signal(this.getInternalAccessToken()); + readonly isAuthenticated = computed(() => !!this.token()); internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> { return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(