fix(frontend): fixes library health pinging even when the user is not authenticated (#385)
* fix(frontend): library health pings even not authenticated * test * authInitialized guard * subscription
This commit is contained in:
@@ -44,12 +44,12 @@ describe("AppComponent", () => {
|
|||||||
};
|
};
|
||||||
let bookdropFileService: { handleIncomingFile: ReturnType<typeof vi.fn> };
|
let bookdropFileService: { handleIncomingFile: ReturnType<typeof vi.fn> };
|
||||||
let taskService: { handleTaskProgress: ReturnType<typeof vi.fn> };
|
let taskService: { handleTaskProgress: ReturnType<typeof vi.fn> };
|
||||||
let libraryHealthService: { initialize: ReturnType<typeof vi.fn> };
|
let libraryHealthService: { initWebsocket: ReturnType<typeof vi.fn>, fetchHealth: ReturnType<typeof vi.fn> };
|
||||||
let libraryLoadingService: {
|
let libraryLoadingService: {
|
||||||
showBookLoadingProgress: ReturnType<typeof vi.fn>;
|
showBookLoadingProgress: ReturnType<typeof vi.fn>;
|
||||||
hide: ReturnType<typeof vi.fn>;
|
hide: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
let authService: { forceLogout: ReturnType<typeof vi.fn> };
|
let authService: { forceLogout: ReturnType<typeof vi.fn>, isAuthenticated: ReturnType<typeof signal> };
|
||||||
let libraryService: {
|
let libraryService: {
|
||||||
largeLibraryLoading: ReturnType<typeof signal>;
|
largeLibraryLoading: ReturnType<typeof signal>;
|
||||||
setLargeLibraryLoading: ReturnType<typeof vi.fn>;
|
setLargeLibraryLoading: ReturnType<typeof vi.fn>;
|
||||||
@@ -62,7 +62,7 @@ describe("AppComponent", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function configureComponent(
|
function configureComponent(
|
||||||
authReady = true,
|
auth = { ready: true, authenticated: true },
|
||||||
largeLibraryLoading = { isLoading: false, expectedCount: 0 },
|
largeLibraryLoading = { isLoading: false, expectedCount: 0 },
|
||||||
): void {
|
): void {
|
||||||
topics = new Map();
|
topics = new Map();
|
||||||
@@ -82,12 +82,12 @@ describe("AppComponent", () => {
|
|||||||
metadataProgressService = { handleIncomingProgress: vi.fn() };
|
metadataProgressService = { handleIncomingProgress: vi.fn() };
|
||||||
bookdropFileService = { handleIncomingFile: vi.fn() };
|
bookdropFileService = { handleIncomingFile: vi.fn() };
|
||||||
taskService = { handleTaskProgress: vi.fn() };
|
taskService = { handleTaskProgress: vi.fn() };
|
||||||
libraryHealthService = { initialize: vi.fn() };
|
libraryHealthService = { initWebsocket: vi.fn(), fetchHealth: vi.fn() };
|
||||||
libraryLoadingService = {
|
libraryLoadingService = {
|
||||||
showBookLoadingProgress: vi.fn(),
|
showBookLoadingProgress: vi.fn(),
|
||||||
hide: vi.fn(),
|
hide: vi.fn(),
|
||||||
};
|
};
|
||||||
authService = { forceLogout: vi.fn() };
|
authService = { forceLogout: vi.fn(), isAuthenticated: signal(auth.authenticated) };
|
||||||
libraryService = {
|
libraryService = {
|
||||||
largeLibraryLoading: signal(largeLibraryLoading),
|
largeLibraryLoading: signal(largeLibraryLoading),
|
||||||
setLargeLibraryLoading: vi.fn(),
|
setLargeLibraryLoading: vi.fn(),
|
||||||
@@ -98,7 +98,7 @@ describe("AppComponent", () => {
|
|||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
provide: AuthInitializationService,
|
provide: AuthInitializationService,
|
||||||
useValue: { initialized: signal(authReady) },
|
useValue: { initialized: signal(auth.ready) },
|
||||||
},
|
},
|
||||||
{ provide: RxStompService, useValue: rxStompService },
|
{ provide: RxStompService, useValue: rxStompService },
|
||||||
{ provide: BookService, useValue: bookService },
|
{ provide: BookService, useValue: bookService },
|
||||||
@@ -135,18 +135,27 @@ describe("AppComponent", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("boots the websocket wiring when auth initialization is ready", () => {
|
it("boots the websocket wiring when auth initialization is ready", () => {
|
||||||
configureComponent(true);
|
configureComponent();
|
||||||
|
|
||||||
expect(component.loading).toBe(false);
|
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/book-add");
|
||||||
expect(rxStompService.watch).toHaveBeenCalledWith(
|
expect(rxStompService.watch).toHaveBeenCalledWith(
|
||||||
"/user/queue/session-revoked",
|
"/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", () => {
|
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
|
topics
|
||||||
.get("/user/queue/book-add")
|
.get("/user/queue/book-add")
|
||||||
@@ -169,7 +178,7 @@ describe("AppComponent", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("forwards websocket updates to the matching root services", () => {
|
it("forwards websocket updates to the matching root services", () => {
|
||||||
configureComponent(true);
|
configureComponent();
|
||||||
|
|
||||||
topics
|
topics
|
||||||
.get("/user/queue/book-update")
|
.get("/user/queue/book-update")
|
||||||
@@ -226,7 +235,7 @@ describe("AppComponent", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("forces logout when the session is revoked", () => {
|
it("forces logout when the session is revoked", () => {
|
||||||
configureComponent(true);
|
configureComponent();
|
||||||
|
|
||||||
topics.get("/user/queue/session-revoked")?.next({ body: "" });
|
topics.get("/user/queue/session-revoked")?.next({ body: "" });
|
||||||
|
|
||||||
@@ -234,7 +243,7 @@ describe("AppComponent", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("unsubscribes and hides the loading overlay when destroyed", () => {
|
it("unsubscribes and hides the loading overlay when destroyed", () => {
|
||||||
configureComponent(true);
|
configureComponent();
|
||||||
|
|
||||||
component.ngOnDestroy();
|
component.ngOnDestroy();
|
||||||
|
|
||||||
|
|||||||
@@ -52,11 +52,19 @@ export class AppComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
if (ready && !this.subscriptionsInitialized) {
|
if (ready && !this.subscriptionsInitialized) {
|
||||||
this.setupWebSocketSubscriptions();
|
this.setupWebSocketSubscriptions();
|
||||||
this.libraryHealthService.initialize();
|
this.libraryHealthService.initWebsocket();
|
||||||
this.subscriptionsInitialized = true;
|
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 {
|
ngOnInit(): void {
|
||||||
window.addEventListener('online', this.onOnline);
|
window.addEventListener('online', this.onOnline);
|
||||||
window.addEventListener('offline', this.onOffline);
|
window.addEventListener('offline', this.onOffline);
|
||||||
|
|||||||
@@ -31,16 +31,16 @@ describe('LibraryHealthService', () => {
|
|||||||
service = TestBed.inject(LibraryHealthService);
|
service = TestBed.inject(LibraryHealthService);
|
||||||
});
|
});
|
||||||
|
|
||||||
async function initializeService(): Promise<void> {
|
async function fetchHealth(): Promise<void> {
|
||||||
const fetchQuerySpy = vi.spyOn(queryClient, 'fetchQuery');
|
const fetchQuerySpy = vi.spyOn(queryClient, 'fetchQuery');
|
||||||
service.initialize();
|
service.fetchHealth();
|
||||||
await fetchQuerySpy.mock.results[0]?.value;
|
await fetchQuerySpy.mock.results[0]?.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
it('fetches initial health on initialize', async () => {
|
it('fetches health', async () => {
|
||||||
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
||||||
|
|
||||||
await initializeService();
|
await fetchHealth();
|
||||||
|
|
||||||
expect(httpGetSpy).toHaveBeenCalledOnce();
|
expect(httpGetSpy).toHaveBeenCalledOnce();
|
||||||
expect(service.health()).toEqual({1: true, 2: false});
|
expect(service.health()).toEqual({1: true, 2: false});
|
||||||
@@ -49,7 +49,7 @@ describe('LibraryHealthService', () => {
|
|||||||
it('reports unhealthy for a library with false health', async () => {
|
it('reports unhealthy for a library with false health', async () => {
|
||||||
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
||||||
|
|
||||||
await initializeService();
|
await fetchHealth();
|
||||||
|
|
||||||
expect(service.isUnhealthy(2)).toBe(true);
|
expect(service.isUnhealthy(2)).toBe(true);
|
||||||
});
|
});
|
||||||
@@ -57,7 +57,7 @@ describe('LibraryHealthService', () => {
|
|||||||
it('reports healthy for a library with true health', async () => {
|
it('reports healthy for a library with true health', async () => {
|
||||||
httpGetSpy.mockReturnValue(of({1: true}));
|
httpGetSpy.mockReturnValue(of({1: true}));
|
||||||
|
|
||||||
await initializeService();
|
await fetchHealth();
|
||||||
|
|
||||||
expect(service.isUnhealthy(1)).toBe(false);
|
expect(service.isUnhealthy(1)).toBe(false);
|
||||||
});
|
});
|
||||||
@@ -65,15 +65,13 @@ describe('LibraryHealthService', () => {
|
|||||||
it('reports false for an unknown library', async () => {
|
it('reports false for an unknown library', async () => {
|
||||||
httpGetSpy.mockReturnValue(of({}));
|
httpGetSpy.mockReturnValue(of({}));
|
||||||
|
|
||||||
await initializeService();
|
await fetchHealth();
|
||||||
|
|
||||||
expect(service.isUnhealthy(99)).toBe(false);
|
expect(service.isUnhealthy(99)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('updates state from websocket messages', async () => {
|
it('updates state from websocket messages', async () => {
|
||||||
httpGetSpy.mockReturnValue(of({1: true}));
|
service.initWebsocket();
|
||||||
|
|
||||||
await initializeService();
|
|
||||||
wsSubject.next({body: JSON.stringify({libraryHealth: {1: false}})} as IMessage);
|
wsSubject.next({body: JSON.stringify({libraryHealth: {1: false}})} as IMessage);
|
||||||
|
|
||||||
expect(service.isUnhealthy(1)).toBe(true);
|
expect(service.isUnhealthy(1)).toBe(true);
|
||||||
|
|||||||
@@ -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 {HttpClient} from '@angular/common/http';
|
||||||
import {lastValueFrom} from 'rxjs';
|
import {lastValueFrom} from 'rxjs';
|
||||||
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
||||||
@@ -13,6 +14,9 @@ export class LibraryHealthService {
|
|||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private rxStompService = inject(RxStompService);
|
private rxStompService = inject(RxStompService);
|
||||||
private queryClient = inject(QueryClient);
|
private queryClient = inject(QueryClient);
|
||||||
|
private destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
|
private socketInitialized = false;
|
||||||
|
|
||||||
private healthQuery = injectQuery(() => ({
|
private healthQuery = injectQuery(() => ({
|
||||||
...this.getHealthQueryOptions(),
|
...this.getHealthQueryOptions(),
|
||||||
@@ -28,13 +32,20 @@ export class LibraryHealthService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
initialize(): void {
|
fetchHealth(): void {
|
||||||
void this.queryClient.fetchQuery(this.getHealthQueryOptions());
|
void this.queryClient.fetchQuery(this.getHealthQueryOptions());
|
||||||
|
}
|
||||||
|
|
||||||
this.rxStompService.watch('/topic/library-health').subscribe(msg => {
|
initWebsocket(): void {
|
||||||
const payload = JSON.parse(msg.body);
|
if (this.socketInitialized) return;
|
||||||
this.queryClient.setQueryData(LIBRARY_HEALTH_QUERY_KEY, payload.libraryHealth);
|
|
||||||
});
|
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 {
|
isUnhealthy(libraryId: number): boolean {
|
||||||
|
|||||||
@@ -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 {HttpClient} from '@angular/common/http';
|
||||||
import {Observable, tap} from 'rxjs';
|
import {Observable, tap} from 'rxjs';
|
||||||
import {RxStompService} from '../websocket/rx-stomp.service';
|
import {RxStompService} from '../websocket/rx-stomp.service';
|
||||||
@@ -22,6 +22,7 @@ export class AuthService {
|
|||||||
private postLoginInitializer = inject(PostLoginInitializerService);
|
private postLoginInitializer = inject(PostLoginInitializerService);
|
||||||
|
|
||||||
readonly token = signal<string | null>(this.getInternalAccessToken());
|
readonly token = signal<string | null>(this.getInternalAccessToken());
|
||||||
|
readonly isAuthenticated = computed(() => !!this.token());
|
||||||
|
|
||||||
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
|
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(
|
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||||
|
|||||||
Reference in New Issue
Block a user